Skip to main content

weida_core/
addr.rs

1//! Endpoint addressing: `weida://[fingerprint@]host:port/path`.
2//!
3//! The path is an **opaque identifier** (master doc §4). Nothing in the core
4//! interprets its structure: no hierarchy, no wildcards, no topic semantics.
5//!
6//! The optional fingerprint in the userinfo position names the peer expected to
7//! answer: `weida://sha256:9f86…@10.0.0.8:7443/samples` is a complete
8//! description of *where* to dial and *whom* to accept, in one string that a
9//! discovery record, a config line or a pasted terminal line can carry.
10
11use std::fmt;
12
13use crate::error::Error;
14use crate::identity::Fingerprint;
15
16/// URL scheme of the native transport.
17pub const SCHEME: &str = "weida";
18
19/// Maximum endpoint path length in bytes (also the wire cap for DATA key 0).
20pub const MAX_PATH_BYTES: usize = 512;
21
22/// Validates an endpoint path.
23///
24/// A path MUST start with `/`, be 1..=[`MAX_PATH_BYTES`] bytes long and contain
25/// no byte below `0x20`. Every other byte sequence is accepted: the path is an
26/// opaque identifier, so `*`, `..` and `%20` carry no meaning here.
27pub fn validate_endpoint_path(path: &str) -> Result<(), Error> {
28    if path.is_empty() || path.len() > MAX_PATH_BYTES {
29        return Err(Error::InvalidEndpointPath);
30    }
31    if !path.starts_with('/') {
32        return Err(Error::InvalidEndpointPath);
33    }
34    if path.bytes().any(|b| b < 0x20) {
35        return Err(Error::InvalidEndpointPath);
36    }
37    Ok(())
38}
39
40/// The port a `weida://` URL means when it writes none.
41///
42/// A portless URL does not mean "guess": it means the authority names a **set**
43/// of nodes rather than one, which is what a Kubernetes headless service
44/// answers with, and every node of such a set listens on the same port
45/// ([decisions/0020](../../../docs/decisions/0020-cluster-and-discovery.md)
46/// §4.2).
47pub const DEFAULT_PORT: u16 = 7443;
48
49/// A parsed `weida://[fingerprint@]host[:port]/path` address.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct EndpointAddr {
52    /// Host as written: a DNS name or an IP literal without brackets.
53    pub host: String,
54    /// Port as written, or `None` when the URL names none.
55    ///
56    /// `None` is not a missing value: it is the statement that the authority
57    /// names a **set** of equivalent nodes, resolved through DNS and dialled
58    /// on [`DEFAULT_PORT`] ([decisions/0020](../../../docs/decisions/0020-cluster-and-discovery.md)
59    /// §4.2). A written port means exactly one endpoint and no discovery.
60    pub port: Option<u16>,
61    /// Opaque endpoint identifier, starting with `/`.
62    pub path: String,
63    /// The peer's public-key fingerprint, when the address names one.
64    ///
65    /// When present it is the only identity the dialling side accepts for this
66    /// address, whatever else it trusts.
67    pub peer: Option<Fingerprint>,
68}
69
70impl EndpointAddr {
71    /// Parses a `weida://[fingerprint@]host[:port]/path` URL.
72    ///
73    /// The port is **optional**, and its absence is meaningful rather than
74    /// lenient: it selects discovery, where the host names a set of nodes and
75    /// [`DEFAULT_PORT`] is the port (0020 §4.2). IPv6 literals are bracketed,
76    /// the fingerprint is in [`Fingerprint`]'s text form, and the path is
77    /// validated by [`validate_endpoint_path`].
78    pub fn parse(input: &str) -> Result<EndpointAddr, Error> {
79        let invalid = |m: &str| Error::InvalidAddress(format!("{m}: {input:?}"));
80
81        let rest = input
82            .strip_prefix(SCHEME)
83            .and_then(|r| r.strip_prefix("://"))
84            .ok_or_else(|| invalid("expected scheme weida://"))?;
85
86        let (authority, path) = match rest.find('/') {
87            Some(i) => rest.split_at(i),
88            None => return Err(invalid("missing endpoint path")),
89        };
90
91        let (peer, authority) = match authority.rsplit_once('@') {
92            Some((fp, rest)) => {
93                let peer = fp
94                    .parse::<Fingerprint>()
95                    .map_err(|_| invalid("expected sha256:<64 hex digits> before '@'"))?;
96                (Some(peer), rest)
97            }
98            None => (None, authority),
99        };
100
101        let (host, port_str) = if let Some(after) = authority.strip_prefix('[') {
102            let close = after
103                .find(']')
104                .ok_or_else(|| invalid("unterminated IPv6 literal"))?;
105            let host = &after[..close];
106            let rest = &after[close + 1..];
107            match rest.strip_prefix(':') {
108                Some(port) => (host, Some(port)),
109                None if rest.is_empty() => (host, None),
110                None => return Err(invalid("expected ':port' after an IPv6 literal")),
111            }
112        } else {
113            match authority.rsplit_once(':') {
114                Some((h, p)) => (h, Some(p)),
115                // No colon at all: a bare name, which is the discovery form.
116                None => (authority, None),
117            }
118        };
119
120        if host.is_empty() {
121            return Err(invalid("empty host"));
122        }
123        if host.bytes().any(|b| b < 0x20 || b == b'/' || b == b'@') {
124            return Err(invalid("invalid byte in host"));
125        }
126        let port = match port_str {
127            Some(text) => {
128                let port: u16 = text.parse().map_err(|_| invalid("port is not a u16"))?;
129                if port == 0 {
130                    return Err(invalid("port 0 is not connectable"));
131                }
132                Some(port)
133            }
134            None => None,
135        };
136
137        validate_endpoint_path(path).map_err(|_| invalid("invalid endpoint path"))?;
138
139        Ok(EndpointAddr {
140            host: host.to_owned(),
141            port,
142            path: path.to_owned(),
143            peer,
144        })
145    }
146
147    /// True if the host is an IPv6 literal and must be bracketed when printed.
148    fn host_needs_brackets(&self) -> bool {
149        self.host.contains(':')
150    }
151}
152
153impl EndpointAddr {
154    /// Prints `[peer@]host[:port]`, bracketing an IPv6 literal.
155    fn fmt_authority(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        if let Some(peer) = &self.peer {
157            write!(f, "{peer}@")?;
158        }
159        match (self.host_needs_brackets(), self.port) {
160            (true, Some(port)) => write!(f, "[{}]:{}", self.host, port),
161            (true, None) => write!(f, "[{}]", self.host),
162            (false, Some(port)) => write!(f, "{}:{}", self.host, port),
163            // Round-trips: a printed address without a port parses back to one
164            // without a port, and means the same set.
165            (false, None) => f.write_str(&self.host),
166        }
167    }
168}
169
170impl fmt::Display for EndpointAddr {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.write_str(SCHEME)?;
173        f.write_str("://")?;
174        self.fmt_authority(f)?;
175        f.write_str(&self.path)
176    }
177}
178
179/// URL scheme of an address reached through a relay.
180pub const SCHEME_RELAY: &str = "weida+relay";
181
182/// The endpoint path a relay serves on, and the one a relayed address dials
183/// on its relay (`docs/PROTOCOL.md` §9.6).
184pub const RELAY_PATH: &str = "/.weida/relay";
185
186/// A parsed `weida+relay://<peer>@[relay-key@]host[:port]/path` address: the
187/// endpoint `path` of the peer whose key is `target`, which serves through
188/// the relay at `relay`.
189///
190/// QUIC and TLS run end to end between the dialler and the target; the relay
191/// only forwards datagrams, so the target's key is part of the address.
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct RelayAddr {
194    /// The key of the peer the address reaches.
195    pub target: Fingerprint,
196    /// The relay's address; its `path` is always [`RELAY_PATH`] and its
197    /// `peer` is the relay's key when the address names one.
198    pub relay: EndpointAddr,
199    /// The endpoint path on the target.
200    pub path: String,
201}
202
203impl RelayAddr {
204    /// Parses a `weida+relay://<peer>@[relay-key@]host[:port]/path` URL.
205    ///
206    /// The relay's authority follows the rules of [`EndpointAddr::parse`];
207    /// the path is validated by [`validate_endpoint_path`].
208    pub fn parse(input: &str) -> Result<RelayAddr, Error> {
209        let invalid = |m: &str| Error::InvalidAddress(format!("{m}: {input:?}"));
210
211        let rest = input
212            .strip_prefix(SCHEME_RELAY)
213            .and_then(|r| r.strip_prefix("://"))
214            .ok_or_else(|| invalid("expected scheme weida+relay://"))?;
215
216        let (authority, path) = match rest.find('/') {
217            Some(i) => rest.split_at(i),
218            None => return Err(invalid("missing endpoint path")),
219        };
220
221        let target = authority
222            .split_once('@')
223            .and_then(|(target, relay)| Some((target.parse::<Fingerprint>().ok()?, relay)));
224        let Some((target, relay_authority)) = target else {
225            return Err(invalid(
226                "a relayed address names the peer it reaches: \
227                 weida+relay://sha256:<peer>@[sha256:<relay>@]host[:port]/path",
228            ));
229        };
230
231        let relay = EndpointAddr::parse(&format!("{SCHEME}://{relay_authority}{RELAY_PATH}"))
232            .map_err(|e| match e {
233                Error::InvalidAddress(m) => invalid(&format!("relay: {m}")),
234                other => other,
235            })?;
236
237        validate_endpoint_path(path).map_err(|_| invalid("invalid endpoint path"))?;
238
239        Ok(RelayAddr {
240            target,
241            relay,
242            path: path.to_owned(),
243        })
244    }
245}
246
247impl fmt::Display for RelayAddr {
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        write!(f, "{SCHEME_RELAY}://{}@", self.target)?;
250        self.relay.fmt_authority(f)?;
251        f.write_str(&self.path)
252    }
253}
254
255/// URL scheme of the in-process transport.
256pub const SCHEME_INPROC: &str = "weida+inproc";
257
258/// Longest in-process bus name, in bytes: libzmq's budget for the same thing
259/// ([decisions/0010](../../../docs/decisions/0010-local-transport.md) §4.8).
260pub const MAX_BUS_BYTES: usize = 256;
261
262/// A parsed `weida+inproc://<bus>/<path>` address.
263#[derive(Clone, Debug, PartialEq, Eq)]
264pub struct InprocAddr {
265    /// Bus name, unique within the process.
266    pub bus: String,
267    /// Opaque endpoint identifier, starting with `/`.
268    pub path: String,
269}
270
271impl fmt::Display for InprocAddr {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        write!(f, "{SCHEME_INPROC}://{}{}", self.bus, self.path)
274    }
275}
276
277/// An address of any transport.
278///
279/// The transport is part of the address and nothing falls back from one to
280/// another on its own: that would change who may connect and what proves
281/// them without saying so [0010 §4.6].
282#[derive(Clone, Debug, PartialEq, Eq)]
283pub enum Address {
284    /// `weida://[fingerprint@]host:port/path` — the network transport.
285    Quic(EndpointAddr),
286    /// `weida+inproc://bus/path` — in process, no socket and no identity.
287    Inproc(InprocAddr),
288    /// `weida+unix://<percent-encoded>/path` — `AF_UNIX`, the kernel proves
289    /// the peer.
290    Unix(UnixAddr),
291    /// `weida+pipe://<name>/path` — a Windows named pipe, the kernel proves
292    /// the peer.
293    Pipe(PipeAddr),
294    /// `weida+relay://<peer>@[relay-key@]host[:port]/path` — the network
295    /// transport, end to end, through a relay.
296    Relay(RelayAddr),
297}
298
299impl Address {
300    /// Parses an address of any transport, by scheme.
301    pub fn parse(input: &str) -> Result<Address, Error> {
302        if input.starts_with(SCHEME_RELAY) {
303            return RelayAddr::parse(input).map(Address::Relay);
304        }
305        if let Some(rest) = input
306            .strip_prefix(SCHEME_INPROC)
307            .and_then(|r| r.strip_prefix("://"))
308        {
309            return parse_inproc(input, rest).map(Address::Inproc);
310        }
311        if input.starts_with(SCHEME_UNIX) {
312            return UnixAddr::parse(input).map(Address::Unix);
313        }
314        if input.starts_with(SCHEME_PIPE) {
315            return PipeAddr::parse(input).map(Address::Pipe);
316        }
317        EndpointAddr::parse(input).map(Address::Quic)
318    }
319
320    /// The endpoint path, whatever the transport.
321    pub fn path(&self) -> &str {
322        match self {
323            Address::Quic(a) => &a.path,
324            Address::Inproc(a) => &a.path,
325            Address::Unix(a) => &a.path,
326            Address::Pipe(a) => &a.path,
327            Address::Relay(a) => &a.path,
328        }
329    }
330}
331
332fn parse_inproc(input: &str, rest: &str) -> Result<InprocAddr, Error> {
333    let invalid = |m: &str| Error::InvalidAddress(format!("{m}: {input:?}"));
334
335    let (bus, path) = match rest.find('/') {
336        Some(i) => rest.split_at(i),
337        None => return Err(invalid("missing endpoint path")),
338    };
339    // There is no key to pin on a local transport, and an address that looks
340    // like it authenticates but does not is worse than one that plainly does
341    // not [0010 §4.8].
342    if bus.contains('@') {
343        return Err(invalid("a local address carries no fingerprint"));
344    }
345    if bus.is_empty() || bus.len() > MAX_BUS_BYTES {
346        return Err(invalid("bus name must be 1..=256 bytes"));
347    }
348    if bus.bytes().any(|b| b < 0x20) {
349        return Err(invalid("invalid byte in bus name"));
350    }
351    validate_endpoint_path(path).map_err(|_| invalid("invalid endpoint path"))?;
352
353    Ok(InprocAddr {
354        bus: bus.to_owned(),
355        path: path.to_owned(),
356    })
357}
358
359/// URL scheme of the `AF_UNIX` transport.
360pub const SCHEME_UNIX: &str = "weida+unix";
361
362/// Longest socket path this platform accepts, in bytes, after decoding.
363///
364/// `sun_path` is `char[108]` on Linux and `char[104]` on macOS, and Rust's
365/// standard library, which every bind and connect here goes through, keeps
366/// room for the terminating NUL on both: 107 usable on Linux, 103 on macOS.
367/// On macOS an App Group container path plus a team-ID-prefixed group name
368/// consumes most of it, so the budget is checked against the *expanded* path
369/// ([decisions/0010](../../../docs/decisions/0010-local-transport.md) §4.5,
370/// `docs/research/ipc.md` §1.1, §2.1, §6.1).
371pub const MAX_SOCKET_PATH_BYTES: usize = if cfg!(target_os = "macos") { 103 } else { 107 };
372
373/// A parsed `weida+unix://<percent-encoded-socket-path>/<path>` address.
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub struct UnixAddr {
376    /// Filesystem path of the socket, **decoded**.
377    pub socket: String,
378    /// Opaque endpoint identifier, starting with `/`.
379    pub path: String,
380}
381
382impl UnixAddr {
383    /// Parses `weida+unix://<percent-encoded-socket-path>/<path>`.
384    ///
385    /// The socket path is percent-encoded because it contains the same
386    /// separator the endpoint path uses, and it is validated against this
387    /// platform's `sun_path` budget **after** decoding [0010 §4.8]. The
388    /// `sha256:…@` userinfo form is refused: there is no key to pin on a
389    /// local transport, and an address that looks like it authenticates but
390    /// does not is worse than one that plainly does not.
391    pub fn parse(input: &str) -> Result<UnixAddr, Error> {
392        let invalid = |m: &str| Error::InvalidAddress(format!("{m}: {input:?}"));
393        let rest = input
394            .strip_prefix(SCHEME_UNIX)
395            .and_then(|r| r.strip_prefix("://"))
396            .ok_or_else(|| invalid("expected scheme weida+unix://"))?;
397
398        let (authority, path) = match rest.find('/') {
399            Some(i) => rest.split_at(i),
400            None => return Err(invalid("missing endpoint path")),
401        };
402        if authority.contains('@') {
403            return Err(invalid("a local address carries no fingerprint"));
404        }
405        let socket = percent_decode(authority).ok_or_else(|| invalid("invalid percent escape"))?;
406        if socket.is_empty() {
407            return Err(invalid("empty socket path"));
408        }
409        if socket.len() > MAX_SOCKET_PATH_BYTES {
410            return Err(invalid(&format!(
411                "socket path exceeds this platform's {MAX_SOCKET_PATH_BYTES}-byte sun_path budget after decoding"
412            )));
413        }
414        // A NUL would truncate `sun_path` where the kernel reads it, and the
415        // abstract namespace — a leading NUL — is deliberately not this
416        // transport's [0010 §4.5].
417        if socket.bytes().any(|b| b == 0) {
418            return Err(invalid("a socket path contains no NUL"));
419        }
420        validate_endpoint_path(path).map_err(|_| invalid("invalid endpoint path"))?;
421
422        Ok(UnixAddr {
423            socket,
424            path: path.to_owned(),
425        })
426    }
427}
428
429impl fmt::Display for UnixAddr {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        write!(f, "{SCHEME_UNIX}://")?;
432        for byte in self.socket.bytes() {
433            match byte {
434                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
435                    f.write_str(std::str::from_utf8(&[byte]).expect("ascii"))?;
436                }
437                other => write!(f, "%{other:02X}")?,
438            }
439        }
440        f.write_str(&self.path)
441    }
442}
443
444/// URL scheme of the Windows named-pipe transport.
445pub const SCHEME_PIPE: &str = "weida+pipe";
446
447/// Longest pipe name accepted, in bytes.
448///
449/// The "entire pipe name string can be up to 256 characters long" — the
450/// name after `\\.\pipe\`, which is the part an address carries
451/// (`docs/research/ipc.md` §3.1).
452pub const MAX_PIPE_NAME_BYTES: usize = 256;
453
454/// The local pipe namespace every [`PipeAddr`] is mapped into.
455///
456/// Always `\\.\pipe\` and never a UNC path with a computer name: an address
457/// names a pipe on this machine only, which is the address-level half of
458/// `PIPE_REJECT_REMOTE_CLIENTS` [0010 §4.8].
459pub const PIPE_NAMESPACE: &str = r"\\.\pipe\";
460
461/// A parsed `weida+pipe://<pipe-name>/<path>` address.
462#[derive(Clone, Debug, PartialEq, Eq)]
463pub struct PipeAddr {
464    /// The pipe's name **without** the `\\.\pipe\` prefix.
465    pub name: String,
466    /// Opaque endpoint identifier, starting with `/`.
467    pub path: String,
468}
469
470impl PipeAddr {
471    /// Parses `weida+pipe://<pipe-name>/<path>`.
472    ///
473    /// The name is everything up to the first `/`, so it cannot contain the
474    /// endpoint separator; a backslash is refused too, because in the pipe
475    /// namespace it is the path separator and would let an address name
476    /// something outside `\\.\pipe\`. The `sha256:…@` userinfo form is
477    /// refused for the same reason as on every local transport: there is no
478    /// key to pin [0010 §4.8].
479    pub fn parse(input: &str) -> Result<PipeAddr, Error> {
480        let invalid = |m: &str| Error::InvalidAddress(format!("{m}: {input:?}"));
481        let rest = input
482            .strip_prefix(SCHEME_PIPE)
483            .and_then(|r| r.strip_prefix("://"))
484            .ok_or_else(|| invalid("expected scheme weida+pipe://"))?;
485
486        let (name, path) = match rest.find('/') {
487            Some(i) => rest.split_at(i),
488            None => return Err(invalid("missing endpoint path")),
489        };
490        if name.contains('@') {
491            return Err(invalid("a local address carries no fingerprint"));
492        }
493        if name.is_empty() || name.len() > MAX_PIPE_NAME_BYTES {
494            return Err(invalid(&format!(
495                "pipe name must be 1..={MAX_PIPE_NAME_BYTES} bytes"
496            )));
497        }
498        if name.bytes().any(|b| b < 0x20 || b == b'\\') {
499            return Err(invalid("invalid byte in pipe name"));
500        }
501        validate_endpoint_path(path).map_err(|_| invalid("invalid endpoint path"))?;
502
503        Ok(PipeAddr {
504            name: name.to_owned(),
505            path: path.to_owned(),
506        })
507    }
508
509    /// The OS path of the pipe: `\\.\pipe\<name>`.
510    pub fn os_path(&self) -> String {
511        format!("{PIPE_NAMESPACE}{}", self.name)
512    }
513}
514
515impl fmt::Display for PipeAddr {
516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517        write!(f, "{SCHEME_PIPE}://{}{}", self.name, self.path)
518    }
519}
520
521/// Decodes percent escapes, returning `None` on a malformed one.
522///
523/// Deliberately small: what has to round-trip here is a filesystem path, and
524/// the encoding exists only so that the socket path's separators cannot be
525/// mistaken for the endpoint path's [0010 §4.8].
526fn percent_decode(input: &str) -> Option<String> {
527    let bytes = input.as_bytes();
528    let mut out = Vec::with_capacity(bytes.len());
529    let mut i = 0;
530    while i < bytes.len() {
531        match bytes[i] {
532            b'%' => {
533                let hex = bytes.get(i + 1..i + 3)?;
534                let hex = std::str::from_utf8(hex).ok()?;
535                out.push(u8::from_str_radix(hex, 16).ok()?);
536                i += 3;
537            }
538            byte => {
539                out.push(byte);
540                i += 1;
541            }
542        }
543    }
544    String::from_utf8(out).ok()
545}
546
547#[cfg(test)]
548mod tests {
549    use super::*;
550
551    const FP: &str = "sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
552
553    #[test]
554    fn parses_ipv4_authority() {
555        let a = EndpointAddr::parse("weida://127.0.0.1:7443/transform").unwrap();
556        assert_eq!(a.host, "127.0.0.1");
557        assert_eq!(a.port, Some(7443));
558        assert_eq!(a.path, "/transform");
559        assert_eq!(a.peer, None);
560        assert_eq!(a.to_string(), "weida://127.0.0.1:7443/transform");
561    }
562
563    #[test]
564    fn parses_a_peer_fingerprint_before_the_authority() {
565        let s = format!("weida://{FP}@[::1]:7443/x");
566        let a = EndpointAddr::parse(&s).unwrap();
567        assert_eq!(a.host, "::1");
568        assert_eq!(a.peer, Some(FP.parse().unwrap()));
569        assert_eq!(a.to_string(), s);
570    }
571
572    #[test]
573    fn parses_bracketed_ipv6_authority() {
574        let a = EndpointAddr::parse("weida://[::1]:7443/x").unwrap();
575        assert_eq!(a.host, "::1");
576        assert_eq!(a.port, Some(7443));
577        assert_eq!(a.path, "/x");
578        assert_eq!(a.to_string(), "weida://[::1]:7443/x");
579    }
580
581    /// Claim: a URL without a port is legal and means a **set** — the
582    /// discovery form of
583    /// [0020](../../../docs/decisions/0020-cluster-and-discovery.md) §4.2 —
584    /// and it round-trips through `Display` unchanged, because a printed
585    /// address that gained a port would mean something else.
586    #[test]
587    fn a_portless_url_is_the_discovery_form() {
588        let a = EndpointAddr::parse("weida://jobs.prod.svc.cluster.local/queue").expect("parse");
589        assert_eq!(a.host, "jobs.prod.svc.cluster.local");
590        assert_eq!(a.port, None);
591        assert_eq!(a.path, "/queue");
592        assert_eq!(a.peer, None);
593        assert_eq!(
594            a.to_string(),
595            "weida://jobs.prod.svc.cluster.local/queue",
596            "a portless address prints without a port"
597        );
598        assert_eq!(EndpointAddr::parse(&a.to_string()).expect("reparse"), a);
599    }
600
601    /// A bracketed IPv6 literal without a port is the same form, and a
602    /// bracket followed by anything but `:port` is still an error rather than
603    /// a host.
604    #[test]
605    fn a_portless_ipv6_literal_round_trips_and_a_malformed_one_does_not() {
606        let a = EndpointAddr::parse("weida://[::1]/x").expect("parse");
607        assert_eq!(a.host, "::1");
608        assert_eq!(a.port, None);
609        assert_eq!(a.to_string(), "weida://[::1]/x");
610        assert_eq!(EndpointAddr::parse(&a.to_string()).expect("reparse"), a);
611
612        assert!(EndpointAddr::parse("weida://[::1]x/y").is_err());
613    }
614
615    const FP2: &str = "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae";
616
617    #[test]
618    fn a_relayed_address_round_trips_through_display() {
619        let s = format!("weida+relay://{FP}@{FP2}@relay.example:7443/jobs");
620        let a = RelayAddr::parse(&s).expect("parse");
621        assert_eq!(a.target, FP.parse().unwrap());
622        assert_eq!(a.relay.peer, Some(FP2.parse().unwrap()));
623        assert_eq!(a.relay.host, "relay.example");
624        assert_eq!(a.relay.port, Some(7443));
625        assert_eq!(a.relay.path, RELAY_PATH);
626        assert_eq!(a.path, "/jobs");
627        assert_eq!(a.to_string(), s);
628        assert_eq!(RelayAddr::parse(&a.to_string()).expect("reparse"), a);
629    }
630
631    #[test]
632    fn a_relayed_address_may_omit_the_relay_key_and_use_ipv6() {
633        let a = RelayAddr::parse(&format!("weida+relay://{FP}@relay.example:7443/jobs"))
634            .expect("parse");
635        assert_eq!(a.relay.peer, None);
636        assert_eq!(a.relay.host, "relay.example");
637
638        let s = format!("weida+relay://{FP}@[::1]:7443/jobs");
639        let a = RelayAddr::parse(&s).expect("parse");
640        assert_eq!(a.relay.host, "::1");
641        assert_eq!(a.relay.port, Some(7443));
642        assert_eq!(a.to_string(), s);
643    }
644
645    #[test]
646    fn a_relayed_address_without_its_target_is_invalid() {
647        assert!(matches!(
648            RelayAddr::parse("weida+relay://relay.example:7443/jobs"),
649            Err(Error::InvalidAddress(_))
650        ));
651        assert!(matches!(
652            Address::parse("weida+relay://relay.example:7443/jobs"),
653            Err(Error::InvalidAddress(_))
654        ));
655    }
656
657    #[test]
658    fn a_relayed_url_parses_as_a_relay_address() {
659        let s = format!("weida+relay://{FP}@127.0.0.1:7443/jobs");
660        assert!(matches!(Address::parse(&s), Ok(Address::Relay(_))));
661        assert_eq!(Address::parse(&s).unwrap().path(), "/jobs");
662    }
663
664    /// The pinned form works without a port too: the fingerprint identifies
665    /// the peer, the name identifies the set (0020 §4.4).
666    #[test]
667    fn a_portless_url_may_still_pin_a_fingerprint() {
668        let a = EndpointAddr::parse(&format!("weida://{FP}@jobs.example/queue")).expect("parse");
669        assert_eq!(a.port, None);
670        assert_eq!(a.peer, Some(FP.parse().expect("fingerprint")));
671    }
672
673    #[test]
674    fn parses_dns_name_and_deep_path() {
675        let a = EndpointAddr::parse("weida://broker.example.com:443/a/b/c").unwrap();
676        assert_eq!(a.host, "broker.example.com");
677        assert_eq!(a.path, "/a/b/c");
678    }
679
680    #[test]
681    fn path_stays_opaque() {
682        let a = EndpointAddr::parse("weida://h:1/important*/../%20").unwrap();
683        assert_eq!(a.path, "/important*/../%20");
684    }
685
686    #[test]
687    fn rejects_bad_addresses() {
688        let cases = [
689            "mq://127.0.0.1:7443/x",
690            // `weida://127.0.0.1/x` is not here: it is the discovery form of
691            // 0020 §4.2. An authority without a port names a set, dialled on
692            // `DEFAULT_PORT`. For a literal there is nothing to resolve, so it
693            // is one node on the default port.
694            "weida://127.0.0.1:7443",
695            "weida://:7443/x",
696            "weida://127.0.0.1:0/x",
697            "weida://127.0.0.1:99999/x",
698            "weida://127.0.0.1:abc/x",
699            "weida://[::1:7443/x",
700            "weida://[::1]7443/x",
701            "127.0.0.1:7443/x",
702            "weida://127.0.0.1:7443/a\u{0}b",
703            "weida://127.0.0.1:7443/a\u{1f}b",
704            "weida://user@host:1/x",
705            "weida://sha256:abc@host:1/x",
706            "weida://@host:1/x",
707            "weida://sha256:9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08@@host:1/x",
708        ];
709        for c in cases {
710            assert!(
711                EndpointAddr::parse(c).is_err(),
712                "expected rejection of {c:?}"
713            );
714        }
715    }
716
717    #[test]
718    fn path_length_bounds() {
719        let ok = format!("weida://h:1/{}", "a".repeat(MAX_PATH_BYTES - 1));
720        assert!(EndpointAddr::parse(&ok).is_ok());
721        let too_long = format!("weida://h:1/{}", "a".repeat(MAX_PATH_BYTES));
722        assert!(EndpointAddr::parse(&too_long).is_err());
723    }
724
725    #[test]
726    fn path_validation_rules() {
727        assert!(validate_endpoint_path("/").is_ok());
728        assert!(validate_endpoint_path("").is_err());
729        assert!(validate_endpoint_path("no-leading-slash").is_err());
730        assert!(validate_endpoint_path("/\t").is_err());
731        assert!(validate_endpoint_path(&"/".repeat(MAX_PATH_BYTES)).is_ok());
732        assert!(validate_endpoint_path(&"/".repeat(MAX_PATH_BYTES + 1)).is_err());
733    }
734
735    #[test]
736    fn display_parse_roundtrip() {
737        let pinned = format!("weida://{FP}@host:1/a");
738        for s in [
739            "weida://127.0.0.1:7443/transform",
740            "weida://[::1]:7443/x",
741            "weida://host:1/a",
742            pinned.as_str(),
743        ] {
744            let a = EndpointAddr::parse(s).unwrap();
745            assert_eq!(EndpointAddr::parse(&a.to_string()).unwrap(), a);
746        }
747    }
748
749    #[test]
750    fn a_unix_socket_path_round_trips_through_percent_encoding() {
751        let a = UnixAddr::parse("weida+unix://%2Frun%2Fweida.sock/jobs").expect("parse");
752        assert_eq!(a.socket, "/run/weida.sock");
753        assert_eq!(a.path, "/jobs");
754        // The encoding exists so that the socket path's separators cannot be
755        // read as the endpoint path's, so it must survive a round trip.
756        assert_eq!(UnixAddr::parse(&a.to_string()).expect("reparse"), a);
757    }
758
759    #[test]
760    fn a_unix_address_is_validated_after_decoding() {
761        // One byte past this platform's `sun_path` budget, written encoded:
762        // the check has to happen on the decoded form or it would pass.
763        let long: String = std::iter::repeat_n("%61", MAX_SOCKET_PATH_BYTES + 1).collect();
764        let err = UnixAddr::parse(&format!("weida+unix://{long}/jobs")).unwrap_err();
765        assert!(matches!(err, Error::InvalidAddress(_)), "{err:?}");
766
767        let ok: String = std::iter::repeat_n("%61", MAX_SOCKET_PATH_BYTES).collect();
768        assert!(UnixAddr::parse(&format!("weida+unix://{ok}/jobs")).is_ok());
769    }
770
771    #[test]
772    fn a_unix_address_refuses_what_would_look_authenticated() {
773        for case in [
774            // No key can be pinned on a local transport [0010 §4.8].
775            "weida+unix://sha256:0000000000000000000000000000000000000000000000000000000000000000@%2Ftmp%2Fs/jobs",
776            // A NUL would truncate `sun_path`, and the abstract namespace is
777            // deliberately not this transport.
778            "weida+unix://%00abstract/jobs",
779            // Malformed escape, empty socket path, missing endpoint path.
780            "weida+unix://%2/jobs",
781            "weida+unix:///jobs",
782            "weida+unix://%2Ftmp%2Fs",
783        ] {
784            assert!(
785                UnixAddr::parse(case).is_err(),
786                "expected rejection of {case:?}"
787            );
788        }
789    }
790
791    #[test]
792    fn a_pipe_address_names_a_local_pipe_only() {
793        let a = PipeAddr::parse("weida+pipe://weida-jobs.v1/jobs").expect("parse");
794        assert_eq!(a.name, "weida-jobs.v1");
795        assert_eq!(a.path, "/jobs");
796        // Always the local namespace, never a UNC path with a computer name.
797        assert_eq!(a.os_path(), r"\\.\pipe\weida-jobs.v1");
798        assert_eq!(PipeAddr::parse(&a.to_string()).expect("reparse"), a);
799        assert!(matches!(
800            Address::parse("weida+pipe://x/y").expect("by scheme"),
801            Address::Pipe(_)
802        ));
803    }
804
805    #[test]
806    fn a_pipe_address_refuses_what_would_escape_or_authenticate() {
807        for case in [
808            // No key can be pinned on a local transport [0010 §4.8].
809            "weida+pipe://sha256:0000000000000000000000000000000000000000000000000000000000000000@x/jobs",
810            // A backslash is the pipe namespace's separator: it would name
811            // something outside `\\.\pipe\`.
812            r"weida+pipe://..\..\c$\boot.ini/jobs",
813            // Empty name, control byte, over the 256-byte cap, missing
814            // endpoint path.
815            "weida+pipe:///jobs",
816            "weida+pipe://a\u{1}b/jobs",
817            "weida+pipe://x",
818        ] {
819            assert!(
820                PipeAddr::parse(case).is_err(),
821                "expected rejection of {case:?}"
822            );
823        }
824        let long = "a".repeat(MAX_PIPE_NAME_BYTES + 1);
825        assert!(PipeAddr::parse(&format!("weida+pipe://{long}/jobs")).is_err());
826        let ok = "a".repeat(MAX_PIPE_NAME_BYTES);
827        assert!(PipeAddr::parse(&format!("weida+pipe://{ok}/jobs")).is_ok());
828    }
829}