[go: up one dir, main page]

mockforge-cli 0.3.0

CLI interface for MockForge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! SMTP server management and mailbox operations

use crate::{FixturesCommands, MailboxCommands, SmtpCommands};
use mockforge_smtp::SmtpFixture;

/// Handle SMTP commands
pub async fn handle_smtp_command(
    smtp_command: SmtpCommands,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match smtp_command {
        SmtpCommands::Mailbox { mailbox_command } => {
            handle_mailbox_command(mailbox_command).await?;
        }
        SmtpCommands::Fixtures { fixtures_command } => {
            handle_fixtures_command(fixtures_command).await?;
        }
        SmtpCommands::Send {
            to,
            subject,
            body,
            host,
            port,
            from,
        } => {
            handle_send_command(to, subject, body, host, port, from).await?;
        }
    }
    Ok(())
}

/// Handle mailbox management commands
async fn handle_mailbox_command(
    mailbox_command: MailboxCommands,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match mailbox_command {
        MailboxCommands::List => {
            handle_mailbox_list().await?;
        }
        MailboxCommands::Show { email_id } => {
            handle_mailbox_show(&email_id).await?;
        }
        MailboxCommands::Clear => {
            handle_mailbox_clear().await?;
        }
        MailboxCommands::Export { format, output } => {
            handle_mailbox_export(&format, &output).await?;
        }
        MailboxCommands::Search {
            sender,
            recipient,
            subject,
            body,
            since,
            until,
            regex,
            case_sensitive,
        } => {
            handle_mailbox_search(
                sender,
                recipient,
                subject,
                body,
                since,
                until,
                regex,
                case_sensitive,
            )
            .await?;
        }
    }
    Ok(())
}

/// List emails in mailbox
async fn handle_mailbox_list() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("📧 Listing emails in mailbox...");

    // Try to connect to MockForge management API
    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client.get(format!("{}/smtp/mailbox", management_url)).send().await {
        Ok(response) => {
            if response.status().is_success() {
                let emails: Vec<serde_json::Value> = response.json().await?;
                if emails.is_empty() {
                    println!("📭 Mailbox is empty");
                } else {
                    println!("📬 Found {} emails:", emails.len());
                    println!("{:<5} {:<30} {:<50} {}", "ID", "From", "Subject", "Received");
                    println!("{}", "-".repeat(100));

                    for email in emails {
                        let id = email["id"].as_str().unwrap_or("N/A");
                        let from = email["from"].as_str().unwrap_or("N/A");
                        let subject = email["subject"].as_str().unwrap_or("N/A");
                        let received = email["received_at"].as_str().unwrap_or("N/A");

                        // Truncate subject if too long
                        let subject_display = if subject.len() > 47 {
                            format!("{}...", &subject[..44])
                        } else {
                            subject.to_string()
                        };

                        println!(
                            "{:<5} {:<30} {:<50} {}",
                            &id[..std::cmp::min(id.len(), 5)],
                            &from[..std::cmp::min(from.len(), 30)],
                            subject_display,
                            received
                        );
                    }
                }
            } else {
                println!("❌ Failed to access mailbox: HTTP {}", response.status());
                println!("💡 Make sure MockForge server is running with SMTP enabled");
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running at {}", management_url);
            println!("💡 Or set MOCKFORGE_MANAGEMENT_URL environment variable");
        }
    }

    Ok(())
}

/// Show email details
async fn handle_mailbox_show(
    email_id: &str,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("📧 Showing email {}...", email_id);

    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client.get(format!("{}/smtp/mailbox/{}", management_url, email_id)).send().await {
        Ok(response) => {
            if response.status().is_success() {
                let email: serde_json::Value = response.json().await?;
                println!("📧 Email Details:");
                println!("ID: {}", email["id"].as_str().unwrap_or("N/A"));
                println!("From: {}", email["from"].as_str().unwrap_or("N/A"));
                println!(
                    "To: {}",
                    email["to"]
                        .as_array()
                        .map(|to| to
                            .iter()
                            .map(|t| t.as_str().unwrap_or("N/A"))
                            .collect::<Vec<_>>()
                            .join(", "))
                        .unwrap_or_else(|| "N/A".to_string())
                );
                println!("Subject: {}", email["subject"].as_str().unwrap_or("N/A"));
                println!("Received: {}", email["received_at"].as_str().unwrap_or("N/A"));
                println!();
                println!("Headers:");
                if let Some(headers) = email["headers"].as_object() {
                    for (key, value) in headers {
                        println!("  {}: {}", key, value.as_str().unwrap_or("N/A"));
                    }
                }
                println!();
                println!("Body:");
                println!("{}", email["body"].as_str().unwrap_or("N/A"));
            } else if response.status() == reqwest::StatusCode::NOT_FOUND {
                println!("❌ Email with ID '{}' not found", email_id);
            } else {
                println!("❌ Failed to retrieve email: HTTP {}", response.status());
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running");
        }
    }

    Ok(())
}

/// Clear mailbox
async fn handle_mailbox_clear() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("🗑️  Clearing mailbox...");

    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client.delete(format!("{}/smtp/mailbox", management_url)).send().await {
        Ok(response) => {
            if response.status().is_success() {
                println!("✅ Mailbox cleared successfully");
            } else {
                println!("❌ Failed to clear mailbox: HTTP {}", response.status());
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running");
        }
    }

    Ok(())
}

/// Export mailbox
async fn handle_mailbox_export(
    format: &str,
    output: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("📤 Exporting mailbox to {} in {} format...", output.display(), format);

    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client
        .get(format!("{}/smtp/mailbox/export?format={}", management_url, format))
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                let content = response.text().await?;
                std::fs::write(output, content)?;
                println!("✅ Mailbox exported to {}", output.display());
            } else {
                println!("❌ Failed to export mailbox: HTTP {}", response.status());
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running");
        }
    }

    Ok(())
}

/// Search emails in mailbox
async fn handle_mailbox_search(
    sender: Option<String>,
    recipient: Option<String>,
    subject: Option<String>,
    body: Option<String>,
    since: Option<String>,
    until: Option<String>,
    regex: bool,
    case_sensitive: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("🔍 Searching emails in mailbox...");

    let mut query_params = Vec::new();
    if let Some(ref s) = sender {
        query_params.push(format!("sender={}", urlencoding::encode(s)));
    }
    if let Some(ref r) = recipient {
        query_params.push(format!("recipient={}", urlencoding::encode(r)));
    }
    if let Some(ref s) = subject {
        query_params.push(format!("subject={}", urlencoding::encode(s)));
    }
    if let Some(ref b) = body {
        query_params.push(format!("body={}", urlencoding::encode(b)));
    }
    if let Some(ref s) = since {
        query_params.push(format!("since={}", urlencoding::encode(s)));
    }
    if let Some(ref u) = until {
        query_params.push(format!("until={}", urlencoding::encode(u)));
    }
    if regex {
        query_params.push("regex=true".to_string());
    }
    if case_sensitive {
        query_params.push("case_sensitive=true".to_string());
    }

    let query_string = if query_params.is_empty() {
        String::new()
    } else {
        format!("?{}", query_params.join("&"))
    };

    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client
        .get(format!("{}/smtp/mailbox/search{}", management_url, query_string))
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                let emails: Vec<serde_json::Value> = response.json().await?;
                if emails.is_empty() {
                    println!("🔍 No emails found matching the criteria");
                } else {
                    println!("🔍 Found {} emails:", emails.len());
                    println!("{:<5} {:<30} {:<50} {}", "ID", "From", "Subject", "Received");
                    println!("{}", "-".repeat(100));

                    for email in emails {
                        let id = email["id"].as_str().unwrap_or("N/A");
                        let from = email["from"].as_str().unwrap_or("N/A");
                        let subject = email["subject"].as_str().unwrap_or("N/A");
                        let received = email["received_at"].as_str().unwrap_or("N/A");

                        let subject_display = if subject.len() > 47 {
                            format!("{}...", &subject[..44])
                        } else {
                            subject.to_string()
                        };

                        println!(
                            "{:<5} {:<30} {:<50} {}",
                            &id[..std::cmp::min(id.len(), 5)],
                            &from[..std::cmp::min(from.len(), 30)],
                            subject_display,
                            received
                        );
                    }
                }
            } else {
                println!("❌ Failed to search mailbox: HTTP {}", response.status());
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running");
        }
    }

    Ok(())
}

/// Handle fixture management commands
async fn handle_fixtures_command(
    fixtures_command: FixturesCommands,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match fixtures_command {
        FixturesCommands::List => {
            handle_fixtures_list().await?;
        }
        FixturesCommands::Reload => {
            handle_fixtures_reload().await?;
        }
        FixturesCommands::Validate { file } => {
            handle_fixtures_validate(&file).await?;
        }
    }
    Ok(())
}

/// Handle send test email command
async fn handle_send_command(
    to: String,
    subject: String,
    body: String,
    host: String,
    port: u16,
    from: String,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("📤 Sending test email...");
    println!("  From: {}", from);
    println!("  To: {}", to);
    println!("  Subject: {}", subject);
    println!("  Server: {}:{}", host, port);

    // Create SMTP client connection
    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
    use tokio::net::TcpStream;
    use tokio::time::{timeout, Duration};

    let stream = timeout(Duration::from_secs(5), TcpStream::connect(format!("{}:{}", host, port)))
        .await
        .map_err(|_| format!("Failed to connect to SMTP server at {}:{}", host, port))??;

    let (reader, mut writer) = stream.into_split();
    let mut reader = BufReader::new(reader);
    let mut response = String::new();

    // Read greeting
    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading SMTP greeting")??;

    if !response.starts_with("220") {
        return Err(format!("Unexpected SMTP greeting: {}", response.trim()).into());
    }
    response.clear();

    // EHLO
    writer.write_all(format!("EHLO {}\r\n", host).as_bytes()).await?;
    loop {
        let mut line = String::new();
        timeout(Duration::from_secs(5), reader.read_line(&mut line))
            .await
            .map_err(|_| "Timeout reading EHLO response")??;
        response.push_str(&line);
        if line.starts_with("250 ") {
            break;
        }
    }
    response.clear();

    // MAIL FROM
    writer.write_all(format!("MAIL FROM:<{}>\r\n", from).as_bytes()).await?;
    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading MAIL FROM response")??;

    if !response.starts_with("250") {
        return Err(format!("MAIL FROM rejected: {}", response.trim()).into());
    }
    response.clear();

    // RCPT TO
    writer.write_all(format!("RCPT TO:<{}>\r\n", to).as_bytes()).await?;
    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading RCPT TO response")??;

    if !response.starts_with("250") {
        return Err(format!("RCPT TO rejected: {}", response.trim()).into());
    }
    response.clear();

    // DATA
    writer.write_all(b"DATA\r\n").await?;
    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading DATA response")??;

    if !response.starts_with("354") {
        return Err(format!("DATA command rejected: {}", response.trim()).into());
    }
    response.clear();

    // Send email content
    writer.write_all(format!("From: {}\r\n", from).as_bytes()).await?;
    writer.write_all(format!("To: {}\r\n", to).as_bytes()).await?;
    writer.write_all(format!("Subject: {}\r\n", subject).as_bytes()).await?;
    writer.write_all(b"\r\n").await?;
    writer.write_all(format!("{}\r\n", body).as_bytes()).await?;
    writer.write_all(b".\r\n").await?;

    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading message acceptance response")??;

    if !response.starts_with("250") {
        return Err(format!("Message rejected: {}", response.trim()).into());
    }
    response.clear();

    // QUIT
    writer.write_all(b"QUIT\r\n").await?;
    timeout(Duration::from_secs(5), reader.read_line(&mut response))
        .await
        .map_err(|_| "Timeout reading QUIT response")??;

    if !response.starts_with("221") {
        return Err(format!("QUIT rejected: {}", response.trim()).into());
    }

    println!("✅ Email sent successfully!");
    Ok(())
}

/// Reload SMTP fixtures from disk
async fn handle_fixtures_reload() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("🔄 Reloading SMTP fixtures from disk...");

    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client.post(format!("{}/smtp/fixtures/reload", management_url)).send().await {
        Ok(response) => {
            if response.status().is_success() {
                let result: serde_json::Value = response.json().await?;
                let count = result["fixtures_loaded"].as_u64().unwrap_or(0);
                println!("✅ Successfully reloaded {} fixtures", count);
            } else {
                println!("❌ Failed to reload fixtures: HTTP {}", response.status());
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running");
        }
    }

    Ok(())
}

/// Validate SMTP fixture file
async fn handle_fixtures_validate(
    file: &std::path::Path,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("🔍 Validating SMTP fixture file {}...", file.display());

    // First, try to validate locally by parsing the file
    match std::fs::read_to_string(file) {
        Ok(content) => {
            // Try to parse as YAML first, then JSON
            let parse_result: Result<SmtpFixture, Box<dyn std::error::Error>> =
                if file.extension().and_then(|s| s.to_str()) == Some("json") {
                    serde_json::from_str::<SmtpFixture>(&content)
                        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
                } else {
                    serde_yaml::from_str::<SmtpFixture>(&content)
                        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
                };

            match parse_result {
                Ok(fixture) => {
                    println!("✅ Fixture file is valid");
                    println!("  Identifier: {}", fixture.identifier);
                    println!("  Name: {}", fixture.name);
                    println!("  Description: {}", fixture.description);
                    println!("  Status Code: {}", fixture.response.status_code);
                    println!("  Match All: {}", fixture.match_criteria.match_all);

                    if let Some(pattern) = &fixture.match_criteria.recipient_pattern {
                        println!("  Recipient Pattern: {}", pattern);
                    }
                    if let Some(pattern) = &fixture.match_criteria.sender_pattern {
                        println!("  Sender Pattern: {}", pattern);
                    }
                    if let Some(pattern) = &fixture.match_criteria.subject_pattern {
                        println!("  Subject Pattern: {}", pattern);
                    }
                }
                Err(e) => {
                    println!("❌ Fixture file is invalid: {}", e);
                    return Ok(());
                }
            }
        }
        Err(e) => {
            println!("❌ Failed to read fixture file: {}", e);
            return Ok(());
        }
    }

    // Also try to validate via management API if server is running
    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    let file_content = std::fs::read_to_string(file)?;
    match client
        .post(format!("{}/smtp/fixtures/validate", management_url))
        .body(file_content)
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                println!("✅ Server validation passed");
            } else {
                let error_msg =
                    response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
                println!("⚠️  Server validation failed: {}", error_msg);
            }
        }
        Err(_) => {
            // Server not available, but local validation passed
            println!("💡 Server validation skipped (server not running)");
        }
    }

    Ok(())
}

/// List loaded SMTP fixtures
async fn handle_fixtures_list() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    println!("📋 Listing loaded SMTP fixtures...");

    // Try to connect to MockForge management API
    let client = reqwest::Client::new();
    let management_url = std::env::var("MOCKFORGE_MANAGEMENT_URL")
        .unwrap_or_else(|_| "http://localhost:8080/__mockforge/api".to_string());

    match client.get(format!("{}/smtp/fixtures", management_url)).send().await {
        Ok(response) => {
            if response.status().is_success() {
                let fixtures: Vec<serde_json::Value> = response.json().await?;
                if fixtures.is_empty() {
                    println!("📋 No fixtures loaded");
                } else {
                    println!("📋 Found {} fixtures:", fixtures.len());
                    println!("{:<20} {:<50} {}", "Identifier", "Name", "Description");
                    println!("{}", "-".repeat(100));

                    for fixture in fixtures {
                        let identifier = fixture["identifier"].as_str().unwrap_or("N/A");
                        let name = fixture["name"].as_str().unwrap_or("N/A");
                        let description = fixture["description"].as_str().unwrap_or("");

                        // Truncate name if too long
                        let name_display = if name.len() > 47 {
                            format!("{}...", &name[..44])
                        } else {
                            name.to_string()
                        };

                        println!(
                            "{:<20} {:<50} {}",
                            &identifier[..std::cmp::min(identifier.len(), 20)],
                            name_display,
                            description
                        );
                    }
                }
            } else {
                println!("❌ Failed to access fixtures: HTTP {}", response.status());
                println!("💡 Make sure MockForge server is running with SMTP enabled");
            }
        }
        Err(e) => {
            println!("❌ Failed to connect to MockForge management API: {}", e);
            println!("💡 Make sure MockForge server is running at {}", management_url);
            println!("💡 Or set MOCKFORGE_MANAGEMENT_URL environment variable");
        }
    }

    Ok(())
}