Skip to main content

hyprstream_rpc/
did_url.rs

1//! DID URL parser + inert dereference plan (#906, at9p epic #880 **G1**).
2//!
3//! This module only parses attacker-reproducible selectors and produces a
4//! [`DereferencePlan`]. It deliberately does not resolve DID state, decode a
5//! carrier address, construct a dial target, or prove possession. Runtime
6//! dereferencing must keep these boundaries distinct:
7//!
8//! 1. verify the immutable genesis GATE;
9//! 2. obtain separately accepted current DID state (future #1027 work);
10//! 3. select the requested service from that accepted state;
11//! 4. decode the service into typed reach;
12//! 5. establish live possession before granting authority;
13//! 6. attach and walk using this plan's inert selectors.
14//!
15//! In particular, a `did:key` verification key is not an iroh `NodeId`, an
16//! endpoint, or evidence that its holder possesses any carrier.
17//!
18//! # Grammar (ratified 2026-07-10, fable spike — #906 comment)
19//!
20//! Recognized query params: **`service | relativeRef | pin`**.
21//! - `pin` = a CIDv1 string (base32 `bafy…`, validated via [`crate::cid`]), a
22//!   **client-verified** content commitment applied at 9P **READ**. It asserts
23//!   **no authority** — a DID URL is an inert, attacker-reproducible selector
24//!   (#905 §7/§8); `pin` only lets the reader reject wrong/inconsistent bytes.
25//! - `versionId` / `versionTime` → W3C-registered **DID-document-version**
26//!   resolution options. A conformant generic dereferencer MUST pass them to the
27//!   *resolve* step, which fails (`FEATURE_NOT_SUPPORTED` until capsule-epoch /
28//!   KERI resolution exists). We **fail closed at parse time** so a travelling
29//!   URL can never be silently mis-resolved, and they are **never** interpreted
30//!   as a content pin (that would poison the resolve → `#ns` → `alsoKnownAs`
31//!   interop prefix these URLs rely on when carried in `NameRecord.subject`).
32//! - `hl` is dropped from the grammar (document-level + doubly redundant for a
33//!   self-certifying DID); like any unrecognized param it is silently ignored.
34//! - `?service=ns` selects the `#ns` serviceEndpoint by fragment id →
35//!   `Tattach(aname="ns")`. Default service is [`DEFAULT_SERVICE`] (`"ns"`).
36//! - **path is canonical** over `relativeRef`: when both carry a walk, the URL
37//!   path wins and `relativeRef` is normalized away ([`DidUrl::walk_segments`]).
38//!
39//! # DID URL form
40//!
41//! Per W3C DID Core + RFC 3986 opaque-path (**no authority** — parses like
42//! `mailto:` everywhere, including WHATWG/browser): the DID is the scheme
43//! prefix, the path hangs off it natively.
44//!
45//! ```text
46//! did:<method>:<method-specific-id>[/<path>][?<query>][#<fragment>]
47//! ```
48//! The DID ends at the first `/`, `?`, or `#`. The fragment is a DID-document
49//! *internal* reference and is **stripped** — service selection is via
50//! `?service=`, never the URL fragment. No `9p://` or `moq://` scheme is
51//! accepted (#906 acceptance): only `did:`-prefixed URLs parse.
52
53use anyhow::{anyhow, bail, ensure, Context, Result};
54
55use crate::cid;
56
57/// Default service fragment id (`#ns`) — the `NinePExport` entry a DID URL
58/// attaches to when `?service=` is absent (#877 aname default).
59pub const DEFAULT_SERVICE: &str = "ns";
60
61// ─── percent-decoding (DID-URL query values) ─────────────────────────────────
62
63/// Percent-decode a DID-URL query value or path segment (RFC 3986 `%XX`).
64///
65/// Invalid escape sequences are left verbatim, while decoded bytes that are not
66/// valid UTF-8 fail closed. Distinct byte strings must never collapse onto the
67/// same lossy selector.
68pub(crate) fn percent_decode(s: &str) -> Result<String> {
69    let bytes = s.as_bytes();
70    let mut out = Vec::with_capacity(bytes.len());
71    let mut i = 0;
72    while i < bytes.len() {
73        if bytes[i] == b'%' && i + 2 < bytes.len() {
74            let hi = (bytes[i + 1] as char).to_digit(16);
75            let lo = (bytes[i + 2] as char).to_digit(16);
76            if let (Some(hi), Some(lo)) = (hi, lo) {
77                out.push((hi * 16 + lo) as u8);
78                i += 3;
79                continue;
80            }
81        }
82        out.push(bytes[i]);
83        i += 1;
84    }
85    String::from_utf8(out).context("percent-decoded DID URL component is not valid UTF-8")
86}
87
88/// Strip a single leading `#` from a service-id value (tolerant: `?service=ns`
89/// and `?service=%23ns` both select `#ns`).
90fn strip_leading_hash(s: &str) -> &str {
91    s.strip_prefix('#').unwrap_or(s)
92}
93
94// ─── canonical DID-URL type ───────────────────────────────────────────────────
95
96/// A parsed DID URL — the canonical, inert addressing type (#906 G1).
97///
98/// Carries **zero authority**: a `DidUrl` is a selector. Everything authoritative
99/// (identity, assurance, content) is created at the GATE (capsule content) and
100/// the admission boundary (subject assurance) during dereferencing — never in
101/// the URL itself (#905 §8). The same string reproduced by an attacker grants
102/// them nothing; separately accepted state, typed reach, and live possession
103/// are still required before any runtime operation can grant authority.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub struct DidUrl {
106    /// The base DID (`did:<method>:<id>`), no path/query/fragment.
107    did: String,
108    /// Percent-decoded URL path segments (9P walk **selectors**), carried
109    /// verbatim. The parser asserts nothing about assurance for these — they are
110    /// MAC-checked as selectors by the 9P walk layer, not trusted here.
111    path: Vec<String>,
112    /// `?service=<id>` — the serviceEndpoint fragment id (without `#`) → the
113    /// `aname` for `Tattach`. `None` means "use [`DEFAULT_SERVICE`]".
114    service: Option<String>,
115    /// `?relativeRef=<path>`. **Path is canonical**: when [`Self::path`] is
116    /// non-empty this is redundant and ignored ([`Self::walk_segments`]
117    /// normalizes the redundancy away rather than letting both carry the walk).
118    relative_ref: Option<Vec<String>>,
119    /// `?pin=<cid>` — a validated CIDv1 string (base32), client-verified at READ.
120    pin: Option<String>,
121}
122
123impl DidUrl {
124    /// Parse a DID URL string per the ratified #906 grammar.
125    ///
126    /// Rejects non-`did:` schemes (`9p://`, `moq://`, `https://`, …). See the
127    /// [module docs](self) for the full param-grammar contract; in particular
128    /// `versionId` / `versionTime` **fail closed** and `hl` / unknown params are
129    /// ignored.
130    pub fn parse(url: &str) -> Result<Self> {
131        // Must be a DID. Explicitly reject 9p://, moq://, https://, etc.
132        // (#906 acceptance: "no 9p:// / moq:// scheme accepted".)
133        let rest = url
134            .strip_prefix("did:")
135            .ok_or_else(|| anyhow!("not a DID URL (must start with 'did:'): {url}"))?;
136
137        // The DID (method + method-specific-id) ends at the first path/query/
138        // fragment delimiter (RFC 3986 opaque-path; DID Core §3.2).
139        let did_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
140        let method_and_id = &rest[..did_end];
141        // A DID needs at least "method:id" (two colon-separated parts after the
142        // "did:" scheme). An empty method-specific id is malformed.
143        let (method, msi) = method_and_id
144            .split_once(':')
145            .ok_or_else(|| anyhow!("malformed DID (missing method-specific id): {url}"))?;
146        ensure!(
147            !method.is_empty() && !msi.is_empty(),
148            "malformed DID (empty method or method-specific id): {url}"
149        );
150        let did = format!("did:{method_and_id}");
151
152        // Tail after the DID: path, ?query, #fragment (in RFC 3986 order).
153        let tail = &rest[did_end..];
154        // Strip the fragment first — it is a DID-document *internal* reference
155        // and never influences dereferencing (service selection is via ?service=).
156        let (before_frag, _fragment) = tail.split_once('#').unwrap_or((tail, ""));
157        let (path_str, query) = before_frag.split_once('?').unwrap_or((before_frag, ""));
158
159        // Path segments: percent-decoded selectors, carried verbatim. Empty
160        // segments (consecutive slashes, leading slash) are dropped — they
161        // contribute nothing to a 9P walk. The walk layer is the authority on
162        // traversal; the parser does not reject `.`/`..` here.
163        let path: Vec<String> = path_str
164            .split('/')
165            .filter(|s| !s.is_empty())
166            .map(percent_decode)
167            .collect::<Result<_>>()?;
168
169        let mut service = None;
170        let mut relative_ref = None;
171        let mut pin = None;
172        for pair in query.split('&').filter(|s| !s.is_empty()) {
173            let (raw_key, raw_val) = pair.split_once('=').unwrap_or((pair, ""));
174            let key = percent_decode(raw_key)?;
175            let val = percent_decode(raw_val)?;
176            match key.as_str() {
177                "service" => {
178                    let service_id = strip_leading_hash(&val);
179                    ensure!(
180                        !service_id.is_empty(),
181                        "?service= must contain a fragment id: {url}"
182                    );
183                    service = Some(service_id.to_owned());
184                }
185                "relativeRef" => {
186                    ensure!(
187                        !raw_val.is_empty(),
188                        "?relativeRef= must be non-empty: {url}"
189                    );
190                    // Split before decoding, exactly like the URL path. Decoding
191                    // the whole value first would turn `%2F` into a structural
192                    // separator here while leaving it inside one path segment.
193                    let segments: Vec<String> = raw_val
194                        .split('/')
195                        .filter(|segment| !segment.is_empty())
196                        .map(percent_decode)
197                        .collect::<Result<_>>()?;
198                    ensure!(
199                        !segments.is_empty(),
200                        "?relativeRef= must contain a path segment: {url}"
201                    );
202                    relative_ref = Some(segments);
203                }
204                "pin" => {
205                    ensure!(!val.is_empty(), "?pin= must be non-empty: {url}");
206                    // Validate the CID shape now so a malformed pin fails closed
207                    // at parse time. The pin asserts NO authority; this only
208                    // rejects structurally-invalid content commitments.
209                    cid::decode_cid(&val)
210                        .with_context(|| format!("?pin= is not a valid CIDv1 string: {val}"))?;
211                    pin = Some(val);
212                }
213                "versionId" | "versionTime" => {
214                    // W3C-registered DID-DOCUMENT-version selectors. A conformant
215                    // generic dereferencer MUST pass these to the RESOLVE step,
216                    // which fails (FEATURE_NOT_SUPPORTED) until capsule-epoch /
217                    // KERI resolution exists. NEVER a content pin — interpreting
218                    // them as one would poison the resolve → #ns → alsoKnownAs
219                    // interop prefix. Fail closed at parse time. (#906 decision.)
220                    bail!(
221                        "DID URL parameter `{key}` selects a DID-document version, which is not \
222                         supported; use `?pin=<cid>` for a client-verified content commitment: {url}"
223                    );
224                }
225                // `hl` is dropped from the grammar (document-level + redundant
226                // for a self-certifying DID). Any other unrecognized key is a
227                // method-defined / generic param and is silently ignored (DID
228                // Core: unknown params must not error a generic dereferencer).
229                _ => {}
230            }
231        }
232
233        Ok(Self {
234            did,
235            path,
236            service,
237            relative_ref,
238            pin,
239        })
240    }
241
242    /// The base DID (`did:<method>:<id>`), no path/query/fragment.
243    pub fn did(&self) -> &str {
244        &self.did
245    }
246
247    /// Percent-decoded URL path segments (9P walk selectors), verbatim.
248    pub fn path(&self) -> &[String] {
249        &self.path
250    }
251
252    /// `?service=<id>` if present (without `#`). `None` means "default".
253    pub fn service(&self) -> Option<&str> {
254        self.service.as_deref()
255    }
256
257    /// `?relativeRef=<path>` if present. Path is canonical; see
258    /// [`Self::walk_segments`] for the normalized walk.
259    pub fn relative_ref(&self) -> Option<&[String]> {
260        self.relative_ref.as_deref()
261    }
262
263    /// `?pin=<cid>` — a validated CIDv1 string applied (client-verified) at READ.
264    pub fn pin(&self) -> Option<&str> {
265        self.pin.as_deref()
266    }
267
268    /// The selected service fragment id (without `#`), defaulting to
269    /// [`DEFAULT_SERVICE`] (`"ns"`). This is the `aname` for `Tattach`.
270    pub fn aname(&self) -> &str {
271        self.service.as_deref().unwrap_or(DEFAULT_SERVICE)
272    }
273
274    /// The effective 9P walk segments. **Path is canonical**: when the URL path
275    /// is non-empty it wins and `relativeRef` is ignored (normalized away). When
276    /// only `relativeRef` is present, it supplies the walk. Empty when neither
277    /// carries a walk (attach the export root).
278    ///
279    /// This is the single source of truth for "what to `Twalk`" — callers must
280    /// not consult [`Self::path`] and [`Self::relative_ref`] independently.
281    pub fn walk_segments(&self) -> Vec<&str> {
282        if !self.path.is_empty() {
283            self.path.iter().map(String::as_str).collect()
284        } else if let Some(rel) = &self.relative_ref {
285            rel.iter().map(String::as_str).collect()
286        } else {
287            Vec::new()
288        }
289    }
290
291    /// Build the dereference plan (aname + walk + pin) from the parsed URL.
292    ///
293    /// Pure (no resolution). Before using these selectors, a runtime must verify
294    /// the genesis GATE, obtain accepted current state, select/decode typed
295    /// reach, and establish live possession. This module implements none of
296    /// those authority-bearing stages and does not invent #1027 admission.
297    pub fn plan(&self) -> DereferencePlan {
298        DereferencePlan {
299            did: self.did.clone(),
300            aname: self.aname().to_owned(),
301            walk: self
302                .walk_segments()
303                .into_iter()
304                .map(str::to_owned)
305                .collect(),
306            pin: self.pin.clone(),
307        }
308    }
309}
310
311// ─── dereference plan + seam ─────────────────────────────────────────────────
312
313/// Inert service/attach/walk inputs for a parsed [`DidUrl`] (#906 G1, #905 §4).
314///
315/// Produced purely from the URL by [`DidUrl::plan`]. It contains no accepted
316/// DID state, transport, identity key, authority subject, or possession proof.
317#[derive(Debug, Clone, PartialEq, Eq)]
318pub struct DereferencePlan {
319    /// The base DID selector; not proof of accepted state or authority.
320    pub did: String,
321    /// Requested service/aname selector; not a decoded or admitted endpoint.
322    pub aname: String,
323    /// Path segments for `Twalk` (selectors; MAC-checked by the 9P layer).
324    pub walk: Vec<String>,
325    /// Optional content pin — client-verified at READ, asserts **no** authority.
326    pub pin: Option<String>,
327}
328
329#[cfg(test)]
330#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
331mod tests {
332    use super::*;
333
334    // ─── parser: core shape ───────────────────────────────────────────────
335
336    #[test]
337    fn parses_did_with_path_and_service() {
338        let u = DidUrl::parse("did:at9p:bafyfake/a/b?service=ns").unwrap();
339        assert_eq!(u.did(), "did:at9p:bafyfake");
340        assert_eq!(u.path(), &["a".to_owned(), "b".to_owned()]);
341        assert_eq!(u.service(), Some("ns"));
342        assert_eq!(u.aname(), "ns");
343        assert_eq!(u.walk_segments(), vec!["a", "b"]);
344        assert!(u.pin().is_none());
345    }
346
347    #[test]
348    fn default_service_is_ns() {
349        let u = DidUrl::parse("did:at9p:bafyfake/x").unwrap();
350        assert_eq!(u.service(), None);
351        assert_eq!(u.aname(), DEFAULT_SERVICE);
352        assert_eq!(u.aname(), "ns");
353    }
354
355    #[test]
356    fn fragment_is_stripped() {
357        // A URL fragment is a DID-doc internal reference; it must not influence
358        // selection (service selection is via ?service=).
359        let u = DidUrl::parse("did:web:example.com#mesh").unwrap();
360        assert_eq!(u.did(), "did:web:example.com");
361        assert_eq!(u.service(), None);
362        assert_eq!(u.walk_segments(), Vec::<&str>::new());
363    }
364
365    #[test]
366    fn rejects_non_did_schemes() {
367        // #906 acceptance: no 9p:// / moq:// scheme accepted.
368        assert!(DidUrl::parse("9p://host:5640/path").is_err());
369        assert!(DidUrl::parse("moq://host/stream").is_err());
370        assert!(DidUrl::parse("https://example.com/x").is_err());
371        assert!(DidUrl::parse("at://did:plc:abc/coll/rkey").is_err());
372    }
373
374    #[test]
375    fn rejects_malformed_did() {
376        assert!(DidUrl::parse("did:").is_err()); // no method/id
377        assert!(DidUrl::parse("did:web").is_err()); // no method-specific id
378        assert!(DidUrl::parse("did::id").is_err()); // empty method
379    }
380
381    #[test]
382    fn path_segments_percent_decoded() {
383        // Decode only after splitting structural `/` delimiters. `%2F` remains
384        // within one inert selector rather than becoming a second segment.
385        let u = DidUrl::parse("did:web:example.com/a%2Fb/c%20d").unwrap();
386        assert_eq!(u.path(), &["a/b".to_owned(), "c d".to_owned()]);
387    }
388
389    // ─── parser: pin (content commitment, client-verified at READ) ─────────
390
391    #[test]
392    fn pin_round_trips_when_cid_valid() {
393        // A real CIDv1 string (base32). Produced by the rpc cid module so it
394        // decodes through the same codec registry the parser validates with.
395        let cid_str =
396            crate::cid::encode_git_oid("0000000000000000000000000000000000000000").unwrap();
397        let url = format!("did:at9p:bafyfake/models/qwen3?pin={cid_str}");
398        let u = DidUrl::parse(&url).unwrap();
399        assert_eq!(u.pin(), Some(cid_str.as_str()));
400        // The plan carries the pin verbatim — READ-time verification is the
401        // caller's job, but the commitment round-trips through parse → plan.
402        assert_eq!(u.plan().pin.as_deref(), Some(cid_str.as_str()));
403    }
404
405    #[test]
406    fn pin_rejects_non_cid() {
407        // A structurally-invalid pin fails closed at parse time.
408        assert!(DidUrl::parse("did:at9p:bafyfake/x?pin=not-a-cid").is_err());
409        // base58btc 'z' prefix is for Multikeys, not base32 CIDs.
410        assert!(DidUrl::parse("did:at9p:bafyfake/x?pin=z6Mkfoo").is_err());
411    }
412
413    #[test]
414    fn pin_is_inert_not_authority() {
415        // pin asserts no authority: an attacker can reproduce the URL verbatim
416        // and it grants nothing. The parser merely carries the CID; it does not
417        // mint identity or assurance. (Demonstrated by the plan being selector-
418        // only: aname/walk/pin, never a SecurityContext.)
419        let cid_str =
420            crate::cid::encode_git_oid("1111111111111111111111111111111111111111").unwrap();
421        let u = DidUrl::parse(&format!("did:at9p:bafyfake/x?pin={cid_str}&service=ns")).unwrap();
422        let plan = u.plan();
423        assert_eq!(plan.aname, "ns");
424        assert_eq!(plan.walk, vec!["x".to_owned()]);
425        assert_eq!(plan.pin.as_deref(), Some(cid_str.as_str()));
426    }
427
428    // ─── parser: versionId / versionTime FAIL CLOSED ───────────────────────
429
430    #[test]
431    fn version_id_fails_closed_not_treated_as_pin() {
432        // versionId is a W3C-registered DID-document-version selector. It MUST
433        // fail closed (FEATURE_NOT_SUPPORTED), NEVER be read as a content pin.
434        let err = DidUrl::parse("did:at9p:bafyfake/x?versionId=bafyfake").unwrap_err();
435        assert!(
436            err.to_string().contains("versionId"),
437            "must name the offending param: {err}"
438        );
439        assert!(
440            err.to_string().contains("not supported"),
441            "must be fail-closed FEATURE_NOT_SUPPORTED: {err}"
442        );
443    }
444
445    #[test]
446    fn version_time_fails_closed() {
447        let err =
448            DidUrl::parse("did:at9p:bafyfake/x?versionTime=2026-01-01T00:00:00Z").unwrap_err();
449        assert!(err.to_string().contains("versionTime"));
450    }
451
452    #[test]
453    fn version_params_are_never_pins() {
454        // Even a versionId value that looks like a CID must not populate pin.
455        let res = DidUrl::parse("did:at9p:bafyfake/x?versionId=bafyfakecid");
456        assert!(res.is_err());
457        // (No DidUrl produced → no pin field can carry it.)
458    }
459
460    // ─── parser: hl dropped, unknown params ignored ────────────────────────
461
462    #[test]
463    fn hl_is_dropped_from_grammar() {
464        // `hl` was removed from the grammar (document-level + redundant for a
465        // self-certifying DID). It is silently ignored, not an error, and never
466        // populates pin.
467        let u = DidUrl::parse("did:at9p:bafyfake/x?hl=bafyfake").unwrap();
468        assert!(u.pin().is_none(), "hl must not become a pin");
469        assert_eq!(u.walk_segments(), vec!["x"]);
470    }
471
472    #[test]
473    fn unknown_params_ignored() {
474        let u = DidUrl::parse("did:at9p:bafyfake/x?foo=bar&baz=qux&service=ns").unwrap();
475        assert_eq!(u.service(), Some("ns"));
476        assert!(u.pin().is_none());
477    }
478
479    // ─── parser: service → aname mapping ──────────────────────────────────
480
481    #[test]
482    fn service_strips_leading_hash_tolerantly() {
483        // ?service=%23ns (encoded #) and ?service=ns select the same #ns entry.
484        let a = DidUrl::parse("did:at9p:bafyfake/x?service=ns").unwrap();
485        let b = DidUrl::parse("did:at9p:bafyfake/x?service=%23ns").unwrap();
486        assert_eq!(a.aname(), "ns");
487        assert_eq!(b.aname(), "ns");
488    }
489
490    #[test]
491    fn empty_service_value_rejected() {
492        assert!(DidUrl::parse("did:at9p:bafyfake/x?service=").is_err());
493        assert!(DidUrl::parse("did:at9p:bafyfake/x?service=%23").is_err());
494    }
495
496    #[test]
497    fn invalid_utf8_percent_encoding_is_rejected_without_aliasing() {
498        assert!(DidUrl::parse("did:at9p:bafyfake/%FF").is_err());
499        assert!(DidUrl::parse("did:at9p:bafyfake?relativeRef=%FE").is_err());
500        assert!(DidUrl::parse("did:at9p:bafyfake?service=%FF").is_err());
501
502        let replacement = DidUrl::parse("did:at9p:bafyfake/%EF%BF%BD").unwrap();
503        assert_eq!(replacement.walk_segments(), vec!["�"]);
504    }
505
506    // ─── parser: relativeRef / path normalization (path canonical) ─────────
507
508    #[test]
509    fn path_is_canonical_over_relative_ref() {
510        // When both carry a walk, path wins and relativeRef is normalized away.
511        let u = DidUrl::parse("did:at9p:bafyfake/a/b?relativeRef=c/d").unwrap();
512        assert_eq!(u.walk_segments(), vec!["a", "b"], "path must win");
513    }
514
515    #[test]
516    fn relative_ref_supplies_walk_when_no_path() {
517        let u = DidUrl::parse("did:at9p:bafyfake?relativeRef=c/d").unwrap();
518        assert!(u.path().is_empty());
519        assert_eq!(u.walk_segments(), vec!["c", "d"]);
520    }
521
522    #[test]
523    fn relative_ref_with_no_segments_is_rejected() {
524        assert!(DidUrl::parse("did:at9p:bafyfake?relativeRef=///").is_err());
525    }
526
527    #[test]
528    fn encoded_slash_has_identical_path_and_relative_ref_semantics() {
529        let path = DidUrl::parse("did:at9p:bafyfake/a%2Fb/c").unwrap();
530        let relative = DidUrl::parse("did:at9p:bafyfake?relativeRef=a%2Fb/c").unwrap();
531
532        assert_eq!(path.walk_segments(), vec!["a/b", "c"]);
533        assert_eq!(relative.walk_segments(), path.walk_segments());
534        assert_eq!(
535            relative.relative_ref(),
536            Some(&["a/b".to_owned(), "c".to_owned()][..])
537        );
538    }
539
540    #[test]
541    fn encoded_slash_cannot_change_precedence() {
542        let u =
543            DidUrl::parse("did:at9p:bafyfake/canonical%2Fsegment?relativeRef=attacker/controlled")
544                .unwrap();
545        assert_eq!(u.walk_segments(), vec!["canonical/segment"]);
546    }
547
548    #[test]
549    fn no_walk_when_neither_present() {
550        let u = DidUrl::parse("did:at9p:bafyfake?service=ns").unwrap();
551        assert!(u.walk_segments().is_empty());
552    }
553
554    // ─── authority separation ──────────────────────────────────────────────
555
556    #[test]
557    fn did_key_plan_contains_no_reach_or_possession() {
558        let raw = [9u8; 32];
559        let did = crate::did_key::ed25519_to_did_key(&raw);
560        let url = DidUrl::parse(&format!("{did}/x/y?service=ns")).unwrap();
561        let plan = url.plan();
562
563        assert_eq!(plan.did, did);
564        assert_eq!(plan.aname, "ns");
565        assert_eq!(plan.walk, vec!["x".to_owned(), "y".to_owned()]);
566        assert!(plan.pin.is_none());
567        // DereferencePlan intentionally has no transport, NodeId, identity key,
568        // assurance, or possession field. The key bytes remain inside the DID
569        // selector until separately accepted current state and typed reach are
570        // supplied by later runtime stages.
571    }
572}