shep-core 0.6.1

Types, Flockfile parsing, and the wire protocol shared by the shep process manager's daemon, client, and CLI
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
//! `ProbeTarget`: parsing a probe's `target` once, at config time.
//!
//! `ProbeConfig::target` is free-form text whose grammar depends on
//! `ProbeConfig::kind`: an `http://` URL, a `host:port` pair, or a shell
//! command line. Parsing at Flockfile-normalize time means a malformed
//! target fails `shep start` naming the Flockfile field, rather than
//! surfacing at the daemon's first poll after the sheep comes online.
//!
//! No URL crate: the grammar needs no userinfo, query, fragment, IDN, or
//! percent-decoding, so a hand-rolled split covers it without pulling in
//! `url` and the `idna`/Unicode tables it drags along.

use core::fmt;

use crate::config::app::{ProbeConfig, ProbeKind};

/// A probe's `target` after validation: the form the prober consumes.
///
/// Parsing here rather than in the daemon means a malformed target fails the
/// Flockfile, not the first poll ten seconds after the sheep is online.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeTarget {
    /// `http://host[:port]/path`: port defaults to 80, path to `/`.
    Http {
        /// The host or IP literal. A bracketed IPv6 literal (`[::1]`) has
        /// its brackets stripped.
        ///
        /// Carried for the prober: connect with
        /// `(host.as_str(), port)`, not by formatting `"{host}:{port}"`
        /// into a `SocketAddr` parse: a stripped IPv6 literal has no
        /// brackets to make that string parseable. For the RFC 7230
        /// `Host:` header, re-bracket an IPv6 host (`format!("[{host}]")`)
        /// before writing it.
        host: String,
        /// The port; defaults to 80 when the authority carries none.
        port: u16,
        /// The path; defaults to `/` when the URL carries none.
        ///
        /// Free of whitespace and control characters whenever it came from
        /// [`ProbeTarget::parse`]: see [`ProbeTargetError::InvalidPath`].
        /// The prober writes this verbatim into a request line, so that is a
        /// security property, not a tidiness one; a caller that builds this
        /// variant by hand rather than parsing takes it on itself.
        path: String,
    },
    /// `host:port`.
    Tcp {
        /// The host or IP literal. A bracketed IPv6 literal (`[::1]`) has
        /// its brackets stripped.
        ///
        /// Carried for the prober: connect with
        /// `(host.as_str(), port)`, not by formatting `"{host}:{port}"`
        /// into a `SocketAddr` parse: a stripped IPv6 literal has no
        /// brackets to make that string parseable.
        host: String,
        /// The port.
        port: u16,
    },
    /// A command line, run through the platform shell.
    Exec {
        /// The command line exactly as written in the Flockfile.
        command: String,
    },
}

impl ProbeTarget {
    /// Parses `config.target` according to `config.kind`.
    ///
    /// # Errors
    ///
    /// - [`ProbeTargetError::Empty`]: the target is empty or all whitespace.
    /// - [`ProbeTargetError::HttpsUnsupported`]: an `https://` URL.
    /// - [`ProbeTargetError::NotHttpUrl`]: no `http://` scheme.
    /// - [`ProbeTargetError::MissingHost`]: the authority has no host.
    /// - [`ProbeTargetError::InvalidHost`]: the host contains `@`, whitespace, or an embedded `:`.
    /// - [`ProbeTargetError::InvalidPath`]: the path contains whitespace or a control character.
    /// - [`ProbeTargetError::MissingPort`]: a TCP target with no `:port`.
    /// - [`ProbeTargetError::BadPort`]: the port is not a `u16`.
    pub fn parse(config: &ProbeConfig) -> Result<Self, ProbeTargetError> {
        if config.target.trim().is_empty() {
            return Err(ProbeTargetError::Empty);
        }
        match config.kind {
            ProbeKind::Http => parse_http(&config.target),
            ProbeKind::Tcp => parse_tcp(&config.target),
            ProbeKind::Exec => Ok(Self::Exec {
                command: config.target.clone(),
            }),
        }
    }
}

/// Why a probe target was rejected.
///
/// `#[non_exhaustive]`: growth is expected as probe kinds change.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeTargetError {
    /// The target is empty or all whitespace.
    Empty,
    /// An `https://` URL. TLS probe targets are not supported.
    HttpsUnsupported {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// An HTTP probe target with no `http://` scheme.
    NotHttpUrl {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// The authority is empty: `http:///path`.
    MissingHost {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// The host contains a character the grammar has no field for: `@`
    /// (userinfo), whitespace, or an embedded `:` (outside a bracketed IPv6
    /// literal, a sign the authority carried more than one `host:port`
    /// pair).
    InvalidHost {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// The path contains whitespace or a control character. Both break the
    /// request line the prober builds around it: a `\r\n` appends
    /// Flockfile-chosen headers, or an entire second request, to what goes
    /// on the socket, and a space ends the path field early.
    InvalidPath {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// A TCP target with no `:port`.
    MissingPort {
        /// The target as written in the Flockfile.
        target: String,
    },
    /// The port is not a `u16`.
    BadPort {
        /// The target as written in the Flockfile.
        target: String,
    },
}

impl fmt::Display for ProbeTargetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => f.write_str("probe target is empty"),
            Self::HttpsUnsupported { target } => write!(
                f,
                "probe target `{target}` uses https://, which shep's probe client does not \
                 support (no TLS)"
            ),
            Self::NotHttpUrl { target } => {
                write!(f, "probe target `{target}` is not an http:// URL")
            }
            Self::MissingHost { target } => write!(f, "probe target `{target}` has no host"),
            Self::InvalidHost { target } => write!(
                f,
                "probe target `{target}` has a host containing `@`, whitespace, or an embedded \
                 `:`"
            ),
            Self::InvalidPath { target } => write!(
                f,
                "probe target `{target}` has a path containing whitespace or a control character"
            ),
            Self::MissingPort { target } => write!(f, "probe target `{target}` has no port"),
            Self::BadPort { target } => {
                write!(
                    f,
                    "probe target `{target}` has a port that is not a valid u16"
                )
            }
        }
    }
}

impl core::error::Error for ProbeTargetError {}

/// Parses an `http://` target into host, port and path.
fn parse_http(target: &str) -> Result<ProbeTarget, ProbeTargetError> {
    // The empty check in `ProbeTarget::parse` trims before deciding whether
    // there's anything here at all; the scheme match trims too, so
    // `"  http://host/  "` is accepted the same as `"http://host/"` instead
    // of falling through to `NotHttpUrl`.
    let trimmed = target.trim();
    let Some(rest) = strip_prefix_ignore_ascii_case(trimmed, "http://") else {
        if strip_prefix_ignore_ascii_case(trimmed, "https://").is_some() {
            return Err(ProbeTargetError::HttpsUnsupported {
                target: target.to_string(),
            });
        }
        return Err(ProbeTargetError::NotHttpUrl {
            target: target.to_string(),
        });
    };

    let (authority, path) = match rest.find('/') {
        Some(idx) => (&rest[..idx], &rest[idx..]),
        None => (rest, "/"),
    };
    if authority.is_empty() {
        return Err(ProbeTargetError::MissingHost {
            target: target.to_string(),
        });
    }

    let (host, port_str) = split_authority(authority, target)?;
    if host.is_empty() {
        return Err(ProbeTargetError::MissingHost {
            target: target.to_string(),
        });
    }
    validate_host(host, authority, target)?;
    validate_path(path, target)?;
    let port = parse_port(port_str.unwrap_or("80"), target)?;

    Ok(ProbeTarget::Http {
        host: host.to_string(),
        port,
        path: path.to_string(),
    })
}

/// Splits an authority into `(host, port)`. The port is `None` when the
/// authority carries none, leaving "default it" (HTTP, to 80) versus
/// "require it" (TCP, [`ProbeTargetError::MissingPort`]) to the caller.
/// Shared by [`parse_http`] and [`parse_tcp`] so both schemes agree on what
/// a bracketed IPv6 host looks like.
///
/// Bracketed IPv6 (`[::1]:8080`) is matched before the general "split on the
/// last colon" rule runs: splitting on the last colon alone puts `1]` in
/// the host, and on the first puts an empty host and `:1]:8080` in the
/// port.
fn split_authority<'a>(
    authority: &'a str,
    target: &str,
) -> Result<(&'a str, Option<&'a str>), ProbeTargetError> {
    if let Some(inner) = authority.strip_prefix('[') {
        // A missing closing bracket leaves no host to extract; report it the
        // same way an empty authority is reported.
        let close = inner
            .find(']')
            .ok_or_else(|| ProbeTargetError::MissingHost {
                target: target.to_string(),
            })?;
        let host = &inner[..close];
        let after = &inner[close + 1..];
        let port_str = match after.strip_prefix(':') {
            Some(p) => Some(p),
            None if after.is_empty() => None,
            // Trailing characters after `]` that are neither `:port` nor
            // nothing (e.g. `[::1]x`) have no valid port to report.
            None => {
                return Err(ProbeTargetError::BadPort {
                    target: target.to_string(),
                });
            }
        };
        return Ok((host, port_str));
    }
    match authority.rsplit_once(':') {
        Some((host, port_str)) => Ok((host, Some(port_str))),
        None => Ok((authority, None)),
    }
}

/// Rejects the host grammars [`ProbeTargetError::InvalidHost`] documents.
/// All three parse as a syntactically fine host and never resolve at poll
/// time.
fn validate_host(host: &str, authority: &str, target: &str) -> Result<(), ProbeTargetError> {
    let bracketed = authority.starts_with('[');
    let invalid = host.contains('@')
        || host.chars().any(char::is_whitespace)
        || (!bracketed && host.contains(':'));
    if invalid {
        return Err(ProbeTargetError::InvalidHost {
            target: target.to_string(),
        });
    }
    Ok(())
}

/// Rejects a path containing whitespace or a control character.
///
/// The prober writes this path verbatim into `GET {path} HTTP/1.1\r\n…`, so
/// a `\r\n` inside it is header injection, and a space ends the request
/// line's path early, handing the server whatever follows as the HTTP
/// version. RFC 3986 has no spelling for either character inside a path: a
/// space is written `%20`, and a control character is percent-encoded too.
fn validate_path(path: &str, target: &str) -> Result<(), ProbeTargetError> {
    if path.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err(ProbeTargetError::InvalidPath {
            target: target.to_string(),
        });
    }
    Ok(())
}

/// Case-insensitively strips `prefix` from the start of `s`, so `HTTPS://`
/// is recognized the same as `https://` (schemes are case-insensitive per
/// RFC 3986 §3.1). `s.get(..prefix.len())` rather than a byte-index slice:
/// a multi-byte character straddling that boundary would otherwise panic.
fn strip_prefix_ignore_ascii_case<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
    let head = s.get(..prefix.len())?;
    head.eq_ignore_ascii_case(prefix)
        .then_some(&s[prefix.len()..])
}

/// Parses a TCP `host:port` target: the whole target is the authority,
/// since a TCP target carries no scheme or path.
fn parse_tcp(target: &str) -> Result<ProbeTarget, ProbeTargetError> {
    let (host, port_str) = split_authority(target, target)?;
    if host.is_empty() {
        return Err(ProbeTargetError::MissingHost {
            target: target.to_string(),
        });
    }
    validate_host(host, target, target)?;
    let Some(port_str) = port_str else {
        return Err(ProbeTargetError::MissingPort {
            target: target.to_string(),
        });
    };
    if port_str.is_empty() {
        return Err(ProbeTargetError::MissingPort {
            target: target.to_string(),
        });
    }
    let port = parse_port(port_str, target)?;
    Ok(ProbeTarget::Tcp {
        host: host.to_string(),
        port,
    })
}

/// Parses a port string into a `u16`, reporting the original target (not
/// just the port substring) so the error names the line the user has to edit.
fn parse_port(port_str: &str, target: &str) -> Result<u16, ProbeTargetError> {
    port_str
        .parse::<u16>()
        .map_err(|_| ProbeTargetError::BadPort {
            target: target.to_string(),
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::values::UpDuration;

    fn probe_config(kind: ProbeKind, target: &str) -> ProbeConfig {
        ProbeConfig {
            kind,
            target: target.to_string(),
            interval: UpDuration::from_millis(10_000),
            timeout: UpDuration::from_millis(5_000),
            failure_threshold: 3,
        }
    }

    #[test]
    fn empty_target_rejected_for_every_kind() {
        // fails if the empty check lives inside one kind's parser instead of
        // running before the kind dispatch, so Exec's "only emptiness is
        // rejected" carve-out skips the check entirely rather than skipping
        // every other check
        for kind in [ProbeKind::Http, ProbeKind::Tcp, ProbeKind::Exec] {
            assert_eq!(
                ProbeTarget::parse(&probe_config(kind, "")).unwrap_err(),
                ProbeTargetError::Empty
            );
            assert_eq!(
                ProbeTarget::parse(&probe_config(kind, "   ")).unwrap_err(),
                ProbeTargetError::Empty
            );
        }
    }

    #[test]
    fn http_full_url_with_port_and_path_accepted() {
        // fails if authority/path splitting is off by one around the first `/`
        let target = ProbeTarget::parse(&probe_config(
            ProbeKind::Http,
            "http://127.0.0.1:8080/healthz",
        ))
        .unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "127.0.0.1".to_string(),
                port: 8080,
                path: "/healthz".to_string(),
            }
        );
    }

    #[test]
    fn http_missing_port_defaults_to_80_and_path_defaults_to_root() {
        // fails if the no-colon authority branch forgets to default the port
        let target =
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://localhost/")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "localhost".to_string(),
                port: 80,
                path: "/".to_string(),
            }
        );
    }

    #[test]
    fn http_missing_path_defaults_to_root() {
        // fails if the no-slash case (rest.find('/') == None) is not handled,
        // e.g. by treating the whole remainder as the authority and leaving
        // the path empty instead of "/"
        let target =
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://localhost:3000")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "localhost".to_string(),
                port: 3000,
                path: "/".to_string(),
            }
        );
    }

    #[test]
    fn http_bracketed_ipv6_with_port_and_path_accepted() {
        // fails if the host/port split uses a plain rsplit_once(':') without
        // checking for the bracket first, which would split "[::1]:8080"
        // into host "1]" (wrong) or worse
        let target =
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://[::1]:8080/x")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "::1".to_string(),
                port: 8080,
                path: "/x".to_string(),
            }
        );
    }

    #[test]
    fn http_bracketed_ipv6_without_port_defaults_to_80() {
        // fails if the bracket branch requires a following `:port` instead of
        // treating "nothing after the bracket" as "default port"
        let target = ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://[::1]/x")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "::1".to_string(),
                port: 80,
                path: "/x".to_string(),
            }
        );
    }

    #[test]
    fn https_scheme_rejected_as_unsupported() {
        // fails if https:// is treated as a generic "not http" failure
        // instead of its own named variant
        let err = ProbeTarget::parse(&probe_config(ProbeKind::Http, "https://x/")).unwrap_err();
        assert_eq!(
            err,
            ProbeTargetError::HttpsUnsupported {
                target: "https://x/".to_string()
            }
        );
        // fails if the error message regresses to something generic:
        // variant identity alone doesn't guard the text.
        assert!(err.to_string().contains("no TLS"), "{err}");
    }

    #[test]
    fn https_scheme_matched_case_insensitively() {
        // fails if scheme matching is case-sensitive: `HTTPS://` would then
        // fall through to the generic NotHttpUrl, losing the TLS-specific
        // explanation
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "HTTPS://x/")).unwrap_err(),
            ProbeTargetError::HttpsUnsupported {
                target: "HTTPS://x/".to_string()
            }
        );
    }

    #[test]
    fn http_scheme_matched_case_insensitively() {
        // fails if scheme matching is case-sensitive: `HTTP://` would then
        // be rejected as NotHttpUrl instead of parsed
        let target = ProbeTarget::parse(&probe_config(ProbeKind::Http, "HTTP://host/x")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "host".to_string(),
                port: 80,
                path: "/x".to_string(),
            }
        );
    }

    #[test]
    fn surrounding_whitespace_trimmed_before_scheme_match() {
        // fails if only the empty-check trims (config.target.trim().is_empty())
        // while the scheme matcher runs on the untrimmed target: that
        // combination accepts "" but rejects "  http://host/  " as
        // NotHttpUrl, even though both are just whitespace-padded
        let target =
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "  http://host/  ")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "host".to_string(),
                port: 80,
                path: "/".to_string(),
            }
        );
    }

    #[test]
    fn scheme_missing_rejected_as_not_http_url() {
        // fails if a target with no recognized scheme at all is mishandled
        // (e.g. parsed as if "http://" were implied)
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "x/")).unwrap_err(),
            ProbeTargetError::NotHttpUrl {
                target: "x/".to_string()
            }
        );
    }

    #[test]
    fn non_http_scheme_rejected_as_not_http_url() {
        // fails if scheme detection only checks for the ABSENCE of "http://"
        // rather than also rejecting a different, unrelated scheme
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "ftp://x/")).unwrap_err(),
            ProbeTargetError::NotHttpUrl {
                target: "ftp://x/".to_string()
            }
        );
    }

    #[test]
    fn empty_authority_rejected_as_missing_host() {
        // fails if an empty authority ("http:///path") is handed to the
        // colon-splitting logic instead of being caught first, which would
        // report a confusing BadPort or silently produce an empty host
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http:///path")).unwrap_err(),
            ProbeTargetError::MissingHost {
                target: "http:///path".to_string()
            }
        );
    }

    #[test]
    fn http_empty_host_before_port_rejected_as_missing_host() {
        // fails if the empty-host guard that runs after the authority split
        // is dropped: ":8080" is a non-empty authority, so the pre-split
        // guard passes it through, and `http://:8080/` would parse to an
        // empty host that never resolves at poll time.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://:8080/")).unwrap_err(),
            ProbeTargetError::MissingHost {
                target: "http://:8080/".to_string()
            }
        );
    }

    #[test]
    fn http_unclosed_bracket_rejected_as_missing_host() {
        // fails if the bracket branch reports a missing `]` as anything but
        // MissingHost: there is no host to extract from "[::1", so a BadPort
        // would point the user at a port the target never carried.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://[::1/")).unwrap_err(),
            ProbeTargetError::MissingHost {
                target: "http://[::1/".to_string()
            }
        );
    }

    #[test]
    fn http_trailing_characters_after_bracket_rejected_as_bad_port() {
        // fails if characters after `]` that are neither `:port` nor nothing
        // are read as "no port": `http://[::1]x` would then quietly become
        // `::1` on port 80, dropping the `x` the user wrote instead of saying
        // the port is unreadable.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://[::1]x")).unwrap_err(),
            ProbeTargetError::BadPort {
                target: "http://[::1]x".to_string()
            }
        );
    }

    #[test]
    fn http_userinfo_in_host_rejected_as_invalid_host() {
        // fails if the host/port split's "last colon" rule is trusted at
        // face value: "user:pass@host:8080" would otherwise parse to host
        // "user:pass@host", a userinfo prefix the grammar has no field for
        // and that will never resolve at poll time
        assert_eq!(
            ProbeTarget::parse(&probe_config(
                ProbeKind::Http,
                "http://user:pass@host:8080/"
            ))
            .unwrap_err(),
            ProbeTargetError::InvalidHost {
                target: "http://user:pass@host:8080/".to_string()
            }
        );
    }

    #[test]
    fn http_whitespace_in_host_rejected_as_invalid_host() {
        // fails if a host containing a literal space is accepted outright
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://my host/")).unwrap_err(),
            ProbeTargetError::InvalidHost {
                target: "http://my host/".to_string()
            }
        );
    }

    #[test]
    fn http_second_colon_in_host_rejected_as_invalid_host() {
        // fails if "host:8080:9090" is trusted after a single rsplit_once:
        // that puts "9090" in the port and leaves "host:8080" as the host,
        // silently dropping the middle port instead of rejecting the target
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://host:8080:9090/"))
                .unwrap_err(),
            ProbeTargetError::InvalidHost {
                target: "http://host:8080:9090/".to_string()
            }
        );
    }

    #[test]
    fn http_crlf_in_path_rejected_as_invalid_path() {
        // fails if the path is carried through unvalidated: this target puts
        // `X-Injected: yes` on the wire as a real header while the probe
        // still reports success. The trailing `yes` matters, since a
        // payload ending in `\r\n` itself would be trimmed and prove nothing.
        let target = "http://host:8080/health\r\nX-Injected: yes";
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, target)).unwrap_err(),
            ProbeTargetError::InvalidPath {
                target: target.to_string()
            }
        );
    }

    #[test]
    fn http_space_in_path_rejected_as_invalid_path() {
        // fails if the check looks for `\r` and `\n` alone: a space is the
        // same defect one field earlier, ending the request line's path and
        // handing the server `b` where the HTTP version belongs.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://host/a b")).unwrap_err(),
            ProbeTargetError::InvalidPath {
                target: "http://host/a b".to_string()
            }
        );
    }

    #[test]
    fn http_control_character_in_path_rejected_as_invalid_path() {
        // fails if the check tests `is_whitespace` alone: a NUL is neither
        // whitespace nor printable, and no RFC 3986 path may carry one
        // unencoded.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://host/a\u{0}b")).unwrap_err(),
            ProbeTargetError::InvalidPath {
                target: "http://host/a\u{0}b".to_string()
            }
        );
    }

    #[test]
    fn http_query_and_percent_encoded_path_still_accepted() {
        // fails if the path check is widened into full URI validation: `?`,
        // `&`, `=` and `%20` are all ordinary text in the tail of a target,
        // and `%20` is precisely how the space rejected above is meant to be
        // written.
        let target = ProbeTarget::parse(&probe_config(
            ProbeKind::Http,
            "http://host/health?a=1&b=%20x",
        ))
        .unwrap();
        assert_eq!(
            target,
            ProbeTarget::Http {
                host: "host".to_string(),
                port: 80,
                path: "/health?a=1&b=%20x".to_string(),
            }
        );
    }

    #[test]
    fn tcp_userinfo_in_host_rejected_as_invalid_host() {
        // fails if validate_host is wired only into parse_http and not
        // parse_tcp, which shares the same split_authority call
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "user:pass@host:5432")).unwrap_err(),
            ProbeTargetError::InvalidHost {
                target: "user:pass@host:5432".to_string()
            }
        );
    }

    #[test]
    fn non_numeric_port_rejected_as_bad_port() {
        // fails if the port substring is stored as-is without ever being
        // parsed into a u16
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://host:notaport/"))
                .unwrap_err(),
            ProbeTargetError::BadPort {
                target: "http://host:notaport/".to_string()
            }
        );
    }

    #[test]
    fn port_out_of_u16_range_rejected_as_bad_port() {
        // fails if the port is parsed as a wider integer type (e.g. u32) and
        // then truncated/cast into u16 instead of rejected
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Http, "http://host:99999/")).unwrap_err(),
            ProbeTargetError::BadPort {
                target: "http://host:99999/".to_string()
            }
        );
    }

    #[test]
    fn tcp_host_and_port_accepted() {
        let target = ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "db.internal:5432")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Tcp {
                host: "db.internal".to_string(),
                port: 5432,
            }
        );
    }

    #[test]
    fn tcp_no_colon_rejected_as_missing_port() {
        // fails if a TCP target with no colon at all is mistaken for a bare
        // hostname with a default port: TCP has no default port
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "host")).unwrap_err(),
            ProbeTargetError::MissingPort {
                target: "host".to_string()
            }
        );
    }

    #[test]
    fn tcp_trailing_colon_rejected_as_missing_port() {
        // fails if an empty port substring after the colon is parsed as "0"
        // or otherwise accepted instead of rejected
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "host:")).unwrap_err(),
            ProbeTargetError::MissingPort {
                target: "host:".to_string()
            }
        );
    }

    #[test]
    fn tcp_missing_host_rejected() {
        // fails if an empty host substring before the colon is accepted as a
        // literal empty hostname instead of rejected
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, ":8080")).unwrap_err(),
            ProbeTargetError::MissingHost {
                target: ":8080".to_string()
            }
        );
    }

    #[test]
    fn tcp_bracketed_ipv6_with_port_accepted() {
        // fails if parse_tcp hands its target straight to rsplit_once(':')
        // instead of routing through split_authority: that puts "1]" in the
        // host, and separately `("[::1]", 8080)` fails DNS lookup where
        // `("::1", 8080)` succeeds.
        let target = ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "[::1]:5432")).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Tcp {
                host: "::1".to_string(),
                port: 5432,
            }
        );
    }

    #[test]
    fn tcp_bracketed_ipv6_without_port_rejected_as_missing_port() {
        // fails if the bracket branch's "no port" case is defaulted to 80
        // for TCP the way it is for HTTP: TCP has no default port
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "[::1]")).unwrap_err(),
            ProbeTargetError::MissingPort {
                target: "[::1]".to_string()
            }
        );
    }

    #[test]
    fn tcp_unbracketed_ipv6_rejected_as_invalid_host() {
        // An unbracketed IPv6-shaped host is ambiguous: naive splitting on
        // the last colon would put "::1" in the host and "5432" in the
        // port, a spelling only the bracketed form should mean.
        assert_eq!(
            ProbeTarget::parse(&probe_config(ProbeKind::Tcp, "::1:5432")).unwrap_err(),
            ProbeTargetError::InvalidHost {
                target: "::1:5432".to_string()
            }
        );
    }

    #[test]
    fn exec_arbitrary_command_line_accepted_unmodified() {
        // fails if Exec narrows the accepted grammar beyond emptiness, e.g.
        // rejecting shell metacharacters or splitting on whitespace
        let command = "sh -c 'curl -f http://localhost/ || exit 1'";
        let target = ProbeTarget::parse(&probe_config(ProbeKind::Exec, command)).unwrap();
        assert_eq!(
            target,
            ProbeTarget::Exec {
                command: command.to_string()
            }
        );
    }
}