asphyxia 0.10.0

A fast and efficient network scanner written in Rust
Documentation
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! End-to-end tests for the `asphyxia` binary.
//!
//! These exercise argument parsing and the validation/guidance paths that do
//! not touch the network, so they stay fast and deterministic. Numeric IPs are
//! used where a host is required, since they resolve without DNS.

use assert_cmd::Command;
use predicates::prelude::*;

fn asphyxia() -> Command {
    let mut cmd = Command::cargo_bin("asphyxia").expect("binary `asphyxia` should be built");
    // Isolate every run from a real `~/.asphyxia.toml` on the developer's
    // machine by pointing the config loader at a path that does not exist, so
    // tests always start from the built-in defaults. Tests that exercise config
    // behavior set their own `ASPHYXIA_CONFIG`, which overrides this.
    cmd.env("ASPHYXIA_CONFIG", "/nonexistent/asphyxia-test-config.toml");
    cmd
}

#[test]
fn help_describes_the_tool() {
    asphyxia()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("network scanner"));
}

#[test]
fn version_flag_prints_version() {
    asphyxia()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn port_scan_requires_a_target() {
    // A target source is mandatory: either `-t/--host` or `--stdin`. With
    // neither, clap rejects the command and names the missing options.
    asphyxia()
        .args(["ps", "-s", "80"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("--host"))
        .stderr(predicate::str::contains("--stdin"));
}

#[test]
fn port_scan_host_and_stdin_are_mutually_exclusive() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "--stdin", "-s", "80"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn port_scan_all_ports_conflicts_with_specific() {
    // `--all-ports` shares the `ports` group with `-r`/`-s`, so combining them
    // is rejected at parse time.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "--all-ports", "-s", "80"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn port_scan_without_range_or_specific_prints_guidance() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Please specify either -r, -s"));
}

#[test]
fn port_scan_top_ports_conflicts_with_specific() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "--top-ports", "100", "-s", "80"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn port_scan_top_ports_rejects_overflow() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "--top-ports", "5000"])
        .assert()
        .success()
        .stderr(predicate::str::contains("at most 1000"));
}

#[test]
fn port_scan_named_set_rejects_unknown() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "--ports", "bogus"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Unknown port set"));
}

#[test]
fn port_scan_stdin_reads_plain_targets() {
    // A bare host per line is fed in; port 1 on loopback is closed, so the
    // machine output is an empty array — proving the target was read and scanned.
    asphyxia()
        .args(["ps", "--stdin", "-s", "1", "-o", "json"])
        .write_stdin("127.0.0.1\n")
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn port_scan_stdin_reads_jsonl_from_address_scan() {
    // The `ip` field of an `asphyxia as -o jsonl` record is used as the target.
    asphyxia()
        .args(["ps", "--stdin", "-s", "1", "-o", "json"])
        .write_stdin("{\"ip\":\"127.0.0.1\",\"proto\":\"tcp\",\"status\":\"up\"}\n")
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn port_scan_stdin_with_no_targets_prints_guidance() {
    asphyxia()
        .args(["ps", "--stdin", "-s", "1"])
        .write_stdin("")
        .assert()
        .success()
        .stderr(predicate::str::contains("No targets read from stdin"));
}

#[test]
fn port_scan_rejects_invalid_ports() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "22,abc,443"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid port number: abc"));
}

#[test]
fn port_scan_reports_unresolvable_host() {
    asphyxia()
        .args(["ps", "-t", "this-host-does-not-exist.invalid", "-s", "80"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Could not resolve host"));
}

#[test]
fn address_scan_without_args_prints_guidance() {
    asphyxia()
        .arg("as")
        .assert()
        .success()
        .stderr(predicate::str::contains(
            "Please specify either -s, -t, or -r",
        ));
}

#[test]
fn address_scan_rejects_invalid_ip() {
    asphyxia()
        .args(["as", "-t", "not-an-ip"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid IP address: not-an-ip"));
}

#[test]
fn address_scan_rejects_invalid_subnet() {
    asphyxia()
        .args(["as", "-s", "192.168.1.0/33"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid subnet format"));
}

#[test]
fn concurrency_flag_is_accepted() {
    // The flag should parse on both subcommands; a bad subnet keeps the scan
    // off the network so the test stays fast and deterministic.
    asphyxia()
        .args(["as", "-s", "192.168.1.0/33", "--concurrency", "64"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid subnet format"));
}

#[test]
fn retries_flag_is_accepted() {
    // A closed port on loopback returns quickly (refused → no retry), so this
    // stays fast even with retries requested.
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "--retries",
            "2",
            "-o",
            "json",
        ])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn retries_flag_rejects_non_numeric() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--retries", "lots"])
        .assert()
        .failure();
}

#[test]
fn timing_profile_out_of_range_is_rejected() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-T", "9"])
        .assert()
        .failure();
}

#[test]
fn timing_profile_is_accepted() {
    // -T4 is a valid preset; a closed port keeps the run fast.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-T", "4", "-o", "json"])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn rate_flag_is_accepted() {
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "--rate",
            "1000",
            "-o",
            "json",
        ])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn rate_limit_paces_multiple_probes() {
    use std::time::Instant;
    // Scan several closed ports on loopback at 20 probes/sec. Refused ports
    // return instantly, so without pacing this finishes in milliseconds; the
    // rate limit forces it to take at least a few slots (~200ms for 5 probes).
    let start = Instant::now();
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1,2,3,4,5",
            "--rate",
            "20",
            "-o",
            "json",
        ])
        .assert()
        .success();
    let elapsed = start.elapsed();
    // 5 probes at 20/sec span 4 intervals of 50ms = 200ms minimum for the
    // probes themselves; allow generous slack for process startup jitter.
    assert!(
        elapsed >= std::time::Duration::from_millis(150),
        "rate limit should pace the scan, took {:?}",
        elapsed
    );
}

#[test]
fn concurrency_flag_rejects_non_numeric() {
    asphyxia()
        .args(["as", "-s", "192.168.1.0/24", "--concurrency", "lots"])
        .assert()
        .failure();
}

#[test]
fn port_scan_json_with_no_open_ports_emits_empty_array() {
    // Port 1 on loopback is closed, so the machine output is an empty JSON
    // array and none of the human-facing banners leak onto stdout.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "json"])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn port_scan_jsonl_with_no_open_ports_emits_nothing() {
    // JSON Lines prints one object per result; with no open ports stdout is
    // empty (zero lines), keeping the stream clean for a consumer.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "jsonl"])
        .assert()
        .success()
        .stdout(predicate::eq(""));
}

#[test]
fn port_scan_csv_emits_header_even_with_no_open_ports() {
    // CSV always carries its header row so downstream parsers have a schema.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "csv"])
        .assert()
        .success()
        .stdout(predicate::eq("ip,port,proto,scan,status,latency_ms\n"));
}

#[test]
fn port_scan_grep_with_no_open_ports_emits_nothing() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "grep"])
        .assert()
        .success()
        .stdout(predicate::eq(""));
}

#[test]
fn target_file_conflicts_with_host() {
    // --target-file joins the same required target group as -t/--stdin.
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "--target-file",
            "targets.txt",
            "-s",
            "80",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn target_file_reads_targets_from_disk() {
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-targets-{}.txt", std::process::id()));
    // One bare IP plus a /31 that expands to two addresses; port 1 is closed on
    // all of them, so the run just proves the file was read and scanned.
    std::fs::write(&path, "127.0.0.1\n127.0.0.2/31\n").unwrap();

    asphyxia()
        .args(["ps", "-i", path.to_str().unwrap(), "-s", "1", "-o", "json"])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));

    let _ = std::fs::remove_file(&path);
}

#[test]
fn target_file_missing_reports_a_clear_error() {
    asphyxia()
        .args([
            "ps",
            "--target-file",
            "/no/such/asphyxia-targets.txt",
            "-s",
            "1",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("Could not read target file"));
}

#[test]
fn config_supplies_defaults_that_flags_override() {
    // A config setting the output to JSON applies when -o is absent; passing -o
    // csv on the command line must win over it.
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-config-{}.toml", std::process::id()));
    std::fs::write(&path, "output = \"json\"\ntimeout = 250\n").unwrap();

    // No -o: the config's JSON format is used (empty array on a closed port).
    asphyxia()
        .env("ASPHYXIA_CONFIG", &path)
        .args(["ps", "-t", "127.0.0.1", "-s", "1"])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));

    // Explicit -o csv overrides the config.
    asphyxia()
        .env("ASPHYXIA_CONFIG", &path)
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "csv"])
        .assert()
        .success()
        .stdout(predicate::eq("ip,port,proto,scan,status,latency_ms\n"));

    let _ = std::fs::remove_file(&path);
}

#[test]
fn service_detection_reports_service_and_banner() {
    use std::io::Write;
    use std::net::TcpListener;
    use std::thread;

    // A local server that greets like SSH on connect; --sV should identify it
    // and surface the banner in the JSONL record.
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
    let port = listener.local_addr().unwrap().port();
    // The scan makes one probe connection to confirm the port is open, then
    // --sV makes a second to grab the banner; greet both.
    let handle = thread::spawn(move || {
        for _ in 0..2 {
            match listener.accept() {
                Ok((mut sock, _)) => {
                    let _ = sock.write_all(b"SSH-2.0-OpenSSH_9.6\r\n");
                }
                Err(_) => break,
            }
        }
    });

    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            &port.to_string(),
            "--sV",
            "-o",
            "jsonl",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"service\":\"ssh\""))
        .stdout(predicate::str::contains("SSH-2.0-OpenSSH_9.6"));

    let _ = handle.join();
}

#[test]
fn syn_conflicts_with_udp() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--syn", "--udp"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn syn_scan_runs_or_falls_back_cleanly() {
    // Port 1 on loopback is closed. Whether the process can open a raw socket
    // (SYN → RST → closed) or not (falls back to connect → refused → closed),
    // the reported result is the same empty JSON array. This exercises the
    // capability check and fallback without needing privileges in CI.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--syn", "-o", "json"])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn ack_scan_reports_firewall_state_and_never_open_or_closed() {
    // Port 1 on loopback. With privileges the ACK probe draws an RST and the
    // port is reported unfiltered; without them the scan says so and falls back
    // to a connect probe, which finds nothing on a closed port. Either way no
    // result may claim "open" — an ACK probe cannot know that.
    let assertion = asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "--scan",
            "ack",
            "--timeout",
            "300",
            "-o",
            "jsonl",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&assertion.get_output().stdout).into_owned();

    for line in stdout.lines() {
        assert!(
            line.contains("\"scan\":\"ack\""),
            "an ACK result must record the probe that produced it: {line}"
        );
        assert!(
            line.contains("\"status\":\"unfiltered\"") || line.contains("\"status\":\"filtered\""),
            "an ACK result must be unfiltered or filtered: {line}"
        );
    }
    assert!(
        !stdout.contains("\"status\":\"open\"") && !stdout.contains("\"status\":\"closed\""),
        "an ACK scan must not report open/closed: {stdout}"
    );
}

#[test]
fn ack_scan_falls_back_visibly_for_an_ipv6_target() {
    // The raw path is IPv4-only (and needs privileges). Whichever check trips
    // first, the operator is told the scan changed question before the results
    // arrive, rather than reading connect results as ACK results.
    asphyxia()
        .args([
            "ps",
            "-t",
            "::1",
            "-s",
            "1",
            "--scan",
            "ack",
            "--timeout",
            "300",
            "-o",
            "json",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("falling back to connect scan"));
}

#[test]
fn ack_scan_rejects_a_udp_pairing() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--scan", "ack", "--udp"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("cannot be used with"));
}

#[test]
fn udp_scan_reports_proto_udp_in_json() {
    // A UDP probe to a closed loopback port typically draws an ICMP
    // port-unreachable (closed → not reported) or stays silent
    // (open|filtered). Either way the run succeeds and, when anything is
    // reported, it is tagged proto "udp" — never "tcp".
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "9",
            "--udp",
            "--timeout",
            "300",
            "-o",
            "jsonl",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"proto\":\"tcp\"").not());
}

#[test]
fn resume_writes_a_checkpoint_file() {
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-resume-out-{}.json", std::process::id()));

    // A closed-port scan finishes immediately; it must still leave a valid,
    // fully-completed checkpoint behind.
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "--resume",
            path.to_str().unwrap(),
            "-o",
            "json",
        ])
        .assert()
        .success();

    let state = std::fs::read_to_string(&path).expect("checkpoint file should exist");
    assert!(state.contains("\"job_count\":1"));
    assert!(state.contains("\"done\":[true]"));
    let _ = std::fs::remove_file(&path);
}

#[test]
fn resume_skips_completed_work_and_reuses_recorded_findings() {
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-resume-in-{}.json", std::process::id()));

    // Hand-craft a fully-completed state for `ps -t 127.0.0.1 -s 1` that claims
    // port 1 is open. Port 1 is actually closed, so seeing it in the output
    // proves the recorded finding was reused and the job was not re-scanned.
    let state = r#"{"proto":"tcp","targets":["127.0.0.1"],"ports":[1],"job_count":1,"done":[true],"findings":[{"host":0,"port":1,"latency_ms":7,"status":"open"}]}"#;
    std::fs::write(&path, state).unwrap();

    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "--resume",
            path.to_str().unwrap(),
            "-o",
            "jsonl",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"port\":1"))
        .stdout(predicate::str::contains("\"status\":\"open\""));

    let _ = std::fs::remove_file(&path);
}

#[test]
fn nmap_args_requires_the_nmap_flag() {
    // --nmap-args without --nmap is a parse error (clap `requires`).
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "80", "--nmap-args", "-A"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("nmap"));
}

#[test]
fn nmap_flag_with_no_open_ports_does_not_invoke_nmap() {
    // Port 1 on loopback is closed, so there is no handoff and the run succeeds
    // regardless of whether nmap is installed on the CI machine.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--nmap"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No open ports found"));
}

#[test]
fn exclude_ports_removing_the_only_port_prints_guidance() {
    // The only requested port is also excluded, so nothing is left to scan.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "--exclude-ports", "1"])
        .assert()
        .success()
        .stderr(predicate::str::contains("No ports left to scan"));
}

#[test]
fn exclude_ports_rejects_invalid_list() {
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1,2",
            "--exclude-ports",
            "nope",
        ])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid port number: nope"));
}

#[test]
fn address_scan_exclude_rejects_invalid_spec() {
    asphyxia()
        .args(["as", "-s", "10.0.0.0/30", "--exclude", "not-an-ip"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Invalid exclude address"));
}

#[test]
fn address_scan_exclude_filters_hosts_from_a_pn_scan() {
    // -Pn marks every address up without probing; --exclude removes one of them,
    // so the excluded address must not appear in the output.
    asphyxia()
        .args([
            "as",
            "-r",
            "10.20.30.1",
            "10.20.30.4",
            "--Pn",
            "--exclude",
            "10.20.30.2",
            "-o",
            "grep",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("10.20.30.1"))
        .stdout(predicate::str::contains("10.20.30.4"))
        .stdout(predicate::str::contains("10.20.30.2").not());
}

#[test]
fn address_scan_exclude_file_is_read() {
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-exclude-{}.txt", std::process::id()));
    std::fs::write(&path, "# comment\n10.20.31.3\n\n").unwrap();

    asphyxia()
        .args([
            "as",
            "-r",
            "10.20.31.1",
            "10.20.31.4",
            "--Pn",
            "--exclude-file",
            path.to_str().unwrap(),
            "-o",
            "grep",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("10.20.31.3").not())
        .stdout(predicate::str::contains("10.20.31.1"));

    let _ = std::fs::remove_file(&path);
}

#[test]
fn output_file_writes_machine_output_and_keeps_stdout_clean() {
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-cli-out-{}.csv", std::process::id()));
    let path_str = path.to_str().unwrap();

    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "1",
            "-o",
            "csv",
            "--output-file",
            path_str,
        ])
        .assert()
        .success()
        // Machine output went to the file, not stdout.
        .stdout(predicate::eq(""));

    let contents = std::fs::read_to_string(&path).expect("output file should exist");
    assert!(contents.starts_with("ip,port,proto,scan,status,latency_ms\n"));
    let _ = std::fs::remove_file(&path);
}

#[test]
fn address_scan_json_with_no_hosts_emits_empty_array() {
    // A short timeout keeps this fast: discovery now probes several ports, each
    // of which would otherwise block for the full default timeout.
    asphyxia()
        .args([
            "as",
            "-t",
            "192.168.255.255",
            "--timeout",
            "200",
            "-o",
            "json",
        ])
        .assert()
        .success()
        .stdout(predicate::eq("[]\n"));
}

#[test]
fn address_scan_pn_marks_target_up_without_probing() {
    // -Pn skips discovery, so even an address that would never answer is
    // reported up. No probe is sent, so this is instant regardless of timeout.
    asphyxia()
        .args(["as", "-t", "192.168.255.255", "--Pn", "-o", "jsonl"])
        .assert()
        .success()
        .stdout(predicate::str::contains("\"ip\":\"192.168.255.255\""))
        .stdout(predicate::str::contains("\"status\":\"up\""));
}

#[test]
fn address_scan_pn_marks_whole_range_up() {
    asphyxia()
        .args(["as", "-r", "10.10.10.1", "10.10.10.4", "--Pn", "-o", "json"])
        .assert()
        .success()
        // All four addresses in the range are reported up without any probe.
        .stdout(predicate::str::contains("10.10.10.1"))
        .stdout(predicate::str::contains("10.10.10.4"));
}

#[test]
fn output_flag_rejects_unknown_format() {
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1", "-o", "bogus"])
        .assert()
        .failure();
}

#[test]
fn text_output_remains_the_default() {
    // Without `-o`, the human-facing banner is still printed: this pins the
    // backwards-compatible default behavior.
    asphyxia()
        .args(["ps", "-t", "127.0.0.1", "-s", "1"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Game Over"));
}

#[test]
fn interface_flag_is_documented_in_help() {
    // Both subcommands accept `-e/--interface`; it must show up in their help.
    asphyxia()
        .args(["ps", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--interface"));
    asphyxia()
        .args(["as", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--interface"));
}

#[test]
fn unknown_interface_fails_before_scanning() {
    // A bogus interface name is rejected up front (non-zero exit) rather than
    // silently scanning over the default route. The message mentions the
    // interface — on supported platforms "no such network interface", on
    // unsupported ones "not supported on this platform"; both contain the word.
    asphyxia()
        .args([
            "ps",
            "-t",
            "127.0.0.1",
            "-s",
            "80",
            "-e",
            "definitely-not-an-iface-9999",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("interface"));
}

#[test]
fn config_interface_is_validated_too() {
    // An interface supplied via the config file is validated the same way as
    // the flag: a bogus name aborts the scan.
    let dir = std::env::temp_dir();
    let path = dir.join(format!("asphyxia-iface-config-{}.toml", std::process::id()));
    std::fs::write(&path, "interface = \"definitely-not-an-iface-9999\"\n").unwrap();

    asphyxia()
        .env("ASPHYXIA_CONFIG", &path)
        .args(["ps", "-t", "127.0.0.1", "-s", "80"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("interface"));

    let _ = std::fs::remove_file(&path);
}