trust-tasks-rs 0.22.3

Reference Rust library for the Trust Tasks framework — transport-agnostic, JSON-based descriptions of verifiable work between parties.
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
//! Helpers for the `trust-task-discovery` exchange, versions 0.1 and 0.2.
//!
//! This module is the framework crate's companion to the registry specs
//! at `specs/trust-task-discovery/0.1` and `0.2`. The two differ only in
//! the response's `frameworkVersion`: 0.1 admits `MAJOR.MINOR`, 0.2 the
//! framework's full `MAJOR.MINOR.PATCH` (SPEC §5.1.1). A responder answers
//! each version in the version it was asked — [`DiscoveryRegistry::respond_to`]
//! for 0.1, [`DiscoveryRegistry::respond_to_v0_2`] for 0.2. It supplies:
//!
//! * [`match_slug`] / [`query_matches`] — the slug-glob matcher in
//!   primitive form, useful when integrating discovery into an existing
//!   server dispatcher.
//! * [`DiscoveryRegistry`] — a small builder that registers the
//!   [`Payload`] types a server supports and answers inbound discovery
//!   queries with the matching subset.
//!
//! ```rust,ignore
//! use trust_tasks_rs::{
//!     discovery::DiscoveryRegistry,
//!     specs::{acl::grant, acl::revoke, trust_task_discovery::v0_1 as discovery},
//! };
//!
//! let registry = DiscoveryRegistry::new()
//!     .with::<grant::v0_1::Payload>()
//!     .with::<revoke::v0_1::Payload>();
//!
//! // Query received off the wire. Generated payload types are
//! // `#[non_exhaustive]`, so construction goes through the builder.
//! let query: discovery::Payload = discovery::Payload::builder()
//!     .patterns(vec!["acl/*".parse::<discovery::PayloadPatternsItem>()?])
//!     .try_into()?;
//!
//! let response = registry.respond_to(&query);
//! // response.supported_types now lists the bare Type URIs of every
//! // registered Payload whose slug matches one of the query patterns.
//! ```

use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator;

use crate::payload::Payload;
use crate::specs::trust_task_discovery::v0_1 as wire;
use crate::specs::trust_task_discovery::v0_2 as wire_v0_2;
use crate::type_uri::TypeUri;

/// Framework release this registry advertises in its discovery responses by
/// default: the newest one whose envelope this crate's generated types
/// include. Callers MAY override or clear it. It is held three-part (SPEC
/// §5.1.1) and written in whichever form the answered version admits — the
/// full value in a 0.2 response, its `MAJOR.MINOR` in a 0.1 response.
const DEFAULT_FRAMEWORK_VERSION: &str = "0.6.0";

/// `MAJOR.MINOR` or `MAJOR.MINOR.PATCH`, split into its numeric parts. A
/// caller-supplied value in neither form yields `None`.
fn framework_version_parts(v: &str) -> Option<(u64, u64, u64)> {
    let mut parts = v.split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = match parts.next() {
        Some(p) => p.parse().ok()?,
        None => 0,
    };
    if parts.next().is_some() {
        return None;
    }
    Some((major, minor, patch))
}

/// Match a single glob `pattern` against a `slug`, per the
/// `trust-task-discovery/0.1` pattern grammar:
///
/// * `"*"` matches every slug.
/// * `"<prefix>/*"` matches every slug starting with `<prefix>/`.
/// * any other pattern is an exact slug match (wildcards in the
///   interior are treated literally and therefore never match).
///
/// Returns `true` on a match.
pub fn match_slug(pattern: &str, slug: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if let Some(prefix) = pattern.strip_suffix("/*") {
        // Reject pathological pattern like just "/" or "/*".
        if prefix.is_empty() {
            return false;
        }
        let mut full_prefix = String::with_capacity(prefix.len() + 1);
        full_prefix.push_str(prefix);
        full_prefix.push('/');
        return slug.starts_with(&full_prefix);
    }
    pattern == slug
}

/// `true` if any pattern in `patterns` matches `slug`. An empty
/// `patterns` slice is treated as `["*"]` — every slug matches —
/// per the [`trust-task-discovery/0.1`](../specs/trust-task-discovery)
/// MUST in its §Conformance.
pub fn query_matches<S: AsRef<str>>(patterns: &[S], slug: &str) -> bool {
    if patterns.is_empty() {
        return true;
    }
    patterns.iter().any(|p| match_slug(p.as_ref(), slug))
}

/// Builds responses to `trust-task-discovery/0.1` queries from a list
/// of registered Type URIs.
///
/// Use `with::<P: Payload>` to register a generated payload type — the
/// registry pulls the Type URI off the trait's `TYPE_URI` constant. For
/// hand-built types or for one-off URIs, use [`with_type_uri`].
///
/// The registry de-duplicates entries and sorts output lexicographically
/// for stable wire bytes.
///
/// [`with_type_uri`]: Self::with_type_uri
#[derive(Debug, Clone, Default)]
pub struct DiscoveryRegistry {
    type_uris: BTreeSet<String>,
    /// Per-URI `ext` namespaces this responder requires on inbound
    /// documents. Populated via [`Self::with_required_ext`] /
    /// [`Self::require_ext`]. URIs in this map MUST also appear in
    /// `type_uris`. When `respond_to` emits the response, URIs with an
    /// entry here use the expanded form so producers see the requirement
    /// before the wire trip.
    required_ext: BTreeMap<String, BTreeSet<String>>,
    /// Framework release advertised in the response payload's
    /// `frameworkVersion` field. `None` suppresses the field (caller opted
    /// out). Defaults to the crate's target. Accepted two- or three-part; a
    /// two-part `M.N` is the release `M.N.0` (SPEC §5.1.1).
    framework_version: Option<String>,
}

impl DiscoveryRegistry {
    /// New empty registry that advertises the crate's target framework
    /// release (`0.6.0`) in responses. Use [`Self::framework_version`] / [`Self::no_framework_version`]
    /// to change or suppress the advertised value.
    pub fn new() -> Self {
        Self {
            framework_version: Some(DEFAULT_FRAMEWORK_VERSION.to_string()),
            ..Self::default()
        }
    }

    /// Override the `frameworkVersion` advertised in the response payload.
    /// Most consumers should leave this at the default — the registry
    /// emits the framework version this crate targets. Pass the release
    /// three-part (`"0.6.0"`); a two-part value is read as its `.0`.
    pub fn framework_version(mut self, version: impl Into<String>) -> Self {
        self.framework_version = Some(version.into());
        self
    }

    /// Suppress the `frameworkVersion` field in the response payload.
    /// The field is OPTIONAL in both versions; callers who want to remain silent
    /// about their framework version (e.g. for privacy reasons per
    /// SPEC §10.6) can opt out with this.
    pub fn no_framework_version(mut self) -> Self {
        self.framework_version = None;
        self
    }

    /// Advertise that inbound documents of `uri` MUST carry the given
    /// reverse-DNS `ext` namespaces (SPEC §4.5.1, §7.2). The registry
    /// surfaces these in `respond_to()`'s expanded `supportedTypes` entry
    /// for `uri` so a producer sees the requirement before the wire trip.
    ///
    /// `uri` is also registered if not already present; calling this
    /// method is equivalent to calling [`Self::with_type_uri`] for the
    /// same URI plus recording the namespace requirements.
    ///
    /// Repeated calls for the same URI union their namespace sets.
    pub fn with_required_ext<I, S>(mut self, uri: TypeUri, namespaces: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let bare = uri.bare().to_string();
        self.type_uris.insert(bare.clone());
        let entry = self.required_ext.entry(bare).or_default();
        entry.extend(namespaces.into_iter().map(Into::into));
        self
    }

    /// Mutating equivalent of [`Self::with_required_ext`].
    pub fn require_ext<I, S>(&mut self, uri: TypeUri, namespaces: I)
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let bare = uri.bare().to_string();
        self.type_uris.insert(bare.clone());
        let entry = self.required_ext.entry(bare).or_default();
        entry.extend(namespaces.into_iter().map(Into::into));
    }

    /// Register a [`Payload`] type by reading its `TYPE_URI` constant.
    /// The bare URI (no `#request` / `#response` fragment) is stored;
    /// per SPEC §10.3 the response always lists bare URIs.
    pub fn with<P: Payload>(self) -> Self {
        let uri = P::type_uri();
        self.with_type_uri(uri)
    }

    /// Register a `TypeUri` directly. Useful for callers that hold a
    /// `TypeUri` without a corresponding `Payload`-implementing type
    /// (e.g. a server that delegates a slug to a downstream consumer
    /// without compiling against the typed payload itself).
    pub fn with_type_uri(mut self, uri: TypeUri) -> Self {
        self.type_uris.insert(uri.bare().to_string());
        self
    }

    /// Mutating equivalent of [`with_type_uri`](Self::with_type_uri).
    pub fn register(&mut self, uri: TypeUri) {
        self.type_uris.insert(uri.bare().to_string());
    }

    /// Mutating registration by `Payload`-implementing type.
    pub fn register_payload<P: Payload>(&mut self) {
        self.register(P::type_uri());
    }

    /// Insert a Type URI from its string form. Caller's responsibility to
    /// pass a well-formed bare Type URI — the registry stores it as-is
    /// without re-parsing. Useful for integrations that already hold
    /// canonical URI strings (e.g. server routing tables that key on
    /// `TypeUri::for_routing().to_string()`).
    pub fn register_str(&mut self, uri: impl Into<String>) {
        self.type_uris.insert(uri.into());
    }

    /// Builder-flavored [`register_str`](Self::register_str).
    pub fn with_str(mut self, uri: impl Into<String>) -> Self {
        self.register_str(uri);
        self
    }

    /// Bare Type URIs the registry currently holds, lexicographically
    /// sorted.
    pub fn supported_types(&self) -> Vec<&str> {
        self.type_uris.iter().map(String::as_str).collect()
    }

    /// Build a response to `query`, listing every registered Type URI
    /// whose slug matches at least one of the query's patterns. Absent
    /// or empty patterns produce the full list.
    ///
    /// URIs with no `requiredExt` policy are emitted in shorthand form
    /// ([`wire::ResponseSupportedTypesItem::Uri`]); URIs with a policy
    /// declared via [`Self::with_required_ext`] / [`Self::require_ext`]
    /// are emitted in expanded form
    /// ([`wire::ResponseSupportedTypesItem::Object`]) carrying the
    /// `requiredExt` array.
    ///
    /// This answers `trust-task-discovery/0.1`, whose `frameworkVersion` is
    /// `MAJOR.MINOR`: the configured release is written without its PATCH.
    /// Answer a 0.2 query with [`Self::respond_to_v0_2`].
    pub fn respond_to(&self, query: &wire::Payload) -> wire::Response {
        // Generated `Payload` wraps each pattern in a `PayloadPatternsItem`
        // newtype; deref to &str for matching.
        let patterns: Vec<&str> = query.patterns.iter().map(|p| p.as_str()).collect();
        let supported_types: Vec<wire::ResponseSupportedTypesItem> = self
            .matching(&patterns)
            .map(|uri| self.entry_for(uri))
            .collect();

        // A `framework_version` override that is not a version is omitted
        // rather than panicking on this caller-supplied value — building a
        // discovery response (which is advisory) must not abort on a
        // malformed setter argument.
        let framework_version = self
            .framework_version
            .as_deref()
            .and_then(framework_version_parts)
            .and_then(|(major, minor, _)| format!("{major}.{minor}").parse().ok());

        wire::Response {
            supported_types,
            framework_version,
        }
    }

    /// Build a response to a `trust-task-discovery/0.2` `query`: the same
    /// matching as [`Self::respond_to`], with `frameworkVersion` written as
    /// the full three-part release (SPEC §5.1.1) — a two-part configured
    /// value is written as its `.0`.
    pub fn respond_to_v0_2(&self, query: &wire_v0_2::Payload) -> wire_v0_2::Response {
        let patterns: Vec<&str> = query.patterns.iter().map(|p| p.as_str()).collect();
        let supported_types: Vec<wire_v0_2::ResponseSupportedTypesItem> = self
            .matching(&patterns)
            .map(|uri| match self.required_ext_for(uri) {
                Some(required_ext) => wire_v0_2::ResponseSupportedTypesItem::Object {
                    type_: uri.to_string(),
                    required_ext: Some(required_ext.filter_map(|ns| ns.parse().ok()).collect()),
                },
                None => wire_v0_2::ResponseSupportedTypesItem::Uri(uri.to_string()),
            })
            .collect();

        let framework_version = self
            .framework_version
            .as_deref()
            .and_then(framework_version_parts)
            .and_then(|(major, minor, patch)| format!("{major}.{minor}.{patch}").parse().ok());

        wire_v0_2::Response {
            supported_types,
            framework_version,
        }
    }

    /// Registered Type URIs whose slug matches at least one of `patterns`.
    fn matching<'a>(&'a self, patterns: &'a [&'a str]) -> impl Iterator<Item = &'a String> + 'a {
        self.type_uris
            .iter()
            .filter(move |uri| match parse_slug(uri) {
                Some(slug) => query_matches(patterns, slug),
                None => false,
            })
    }

    /// The `requiredExt` namespaces declared for `uri`, if any.
    fn required_ext_for(&self, uri: &str) -> Option<impl Iterator<Item = &String>> {
        self.required_ext
            .get(uri)
            .filter(|namespaces| !namespaces.is_empty())
            .map(|namespaces| namespaces.iter())
    }

    fn entry_for(&self, uri: &str) -> wire::ResponseSupportedTypesItem {
        match self.required_ext.get(uri) {
            Some(namespaces) if !namespaces.is_empty() => {
                // Namespaces that don't match the reverse-DNS pattern are
                // skipped rather than panicking on caller-supplied input.
                let required_ext: Vec<wire::ResponseSupportedTypesItemObjectRequiredExtItem> =
                    namespaces.iter().filter_map(|ns| ns.parse().ok()).collect();
                wire::ResponseSupportedTypesItem::Object {
                    type_: uri.to_string(),
                    required_ext: Some(required_ext),
                }
            }
            _ => wire::ResponseSupportedTypesItem::Uri(uri.to_string()),
        }
    }
}

impl<S: Into<String>> FromIterator<S> for DiscoveryRegistry {
    fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Self {
        let mut registry = Self::new();
        for uri in iter {
            registry.register_str(uri);
        }
        registry
    }
}

/// Extract the slug from a registered Type URI. Returns `None` for
/// inputs that don't parse as a Type URI (which can't happen for
/// URIs we registered through `with_type_uri` since they came from a
/// `TypeUri`).
fn parse_slug(uri: &str) -> Option<&str> {
    // The Type URI shape is `https://.../spec/<slug>/<MAJOR.MINOR>`.
    // We don't re-parse via `TypeUri::from_str` because we already know
    // the URIs are well-formed; cheap string slicing is fine.
    let after_spec = uri.split_once("/spec/")?.1;
    let last_slash = after_spec.rfind('/')?;
    Some(&after_spec[..last_slash])
}

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

    #[test]
    fn star_matches_anything() {
        assert!(match_slug("*", "acl/grant"));
        assert!(match_slug("*", "trust-task-discovery"));
        assert!(match_slug("*", "trust-task-discovery"));
    }

    #[test]
    fn prefix_wildcard_matches_descendants() {
        assert!(match_slug("acl/*", "acl/grant"));
        assert!(match_slug("acl/*", "acl/revoke"));
        assert!(match_slug("acl/*", "acl/grant/sub"));
    }

    #[test]
    fn prefix_wildcard_does_not_match_bare_prefix() {
        // SPEC §10.2 — `acl/*` requires the trailing slash; `acl` alone
        // does not satisfy the pattern.
        assert!(!match_slug("acl/*", "acl"));
        assert!(!match_slug("acl/*", "aclx"));
        assert!(!match_slug("acl/*", "trust-task-discovery"));
    }

    #[test]
    fn exact_pattern_matches_exact_slug_only() {
        assert!(match_slug("trust-task-discovery", "trust-task-discovery"));
        assert!(!match_slug(
            "trust-task-discovery",
            "trust-task-discovery/v2"
        ));
        assert!(!match_slug("trust-task-discovery", "trust-task"));
    }

    #[test]
    fn interior_wildcards_are_treated_literally() {
        // No slug can contain `*`, so a pattern with an interior `*`
        // never matches anything.
        assert!(!match_slug("acl/*/grant", "acl/grant"));
        assert!(!match_slug("a*b", "ab"));
    }

    #[test]
    fn empty_patterns_match_everything() {
        let patterns: &[&str] = &[];
        assert!(query_matches(patterns, "acl/grant"));
        assert!(query_matches(patterns, "anything"));
    }

    #[test]
    fn or_semantics_across_patterns() {
        let patterns = ["acl/*", "trust-task-discovery"];
        assert!(query_matches(&patterns, "acl/grant"));
        assert!(query_matches(&patterns, "trust-task-discovery"));
        assert!(!query_matches(&patterns, "consent/give"));
    }

    #[test]
    fn registry_dedupes_and_sorts() {
        let registry = DiscoveryRegistry::new()
            .with_type_uri(TypeUri::canonical("acl/revoke", 0, 1).unwrap())
            .with_type_uri(TypeUri::canonical("acl/grant", 0, 1).unwrap())
            .with_type_uri(TypeUri::canonical("acl/grant", 0, 1).unwrap());
        let types = registry.supported_types();
        assert_eq!(
            types,
            vec![
                "https://trusttasks.org/spec/acl/grant/0.1",
                "https://trusttasks.org/spec/acl/revoke/0.1",
            ]
        );
    }

    #[test]
    fn registry_responds_to_query_with_filtered_subset() {
        use crate::specs::acl::{change_role, grant, list, revoke, show};
        let registry = DiscoveryRegistry::new()
            .with::<grant::v0_1::Payload>()
            .with::<revoke::v0_1::Payload>()
            .with::<show::v0_1::Payload>()
            .with::<list::v0_1::Payload>()
            .with::<change_role::v0_1::Payload>();

        // ACL family — all 5 listed.
        let acl_only = wire::Payload {
            patterns: vec!["acl/*".parse().unwrap()],
        };
        let response = registry.respond_to(&acl_only);
        assert_eq!(response.supported_types.len(), 5);

        // Exact match — only one.
        let only_grant = wire::Payload {
            patterns: vec!["acl/grant".parse().unwrap()],
        };
        let response = registry.respond_to(&only_grant);
        assert_eq!(
            uris_in(&response),
            vec!["https://trusttasks.org/spec/acl/grant/0.1"]
        );

        // Empty patterns → everything.
        let everything = wire::Payload { patterns: vec![] };
        let response = registry.respond_to(&everything);
        assert_eq!(response.supported_types.len(), 5);

        // No match.
        let nothing = wire::Payload {
            patterns: vec!["does-not-exist/*".parse().unwrap()],
        };
        let response = registry.respond_to(&nothing);
        assert!(response.supported_types.is_empty());

        // frameworkVersion defaults to the framework release this crate
        // targets, written MAJOR.MINOR because 0.1 admits nothing finer.
        let response = registry.respond_to(&wire::Payload { patterns: vec![] });
        assert_eq!(
            response.framework_version.as_ref().map(|v| v.to_string()),
            Some("0.6".to_string())
        );
    }

    #[test]
    fn no_framework_version_suppresses_field() {
        let registry = DiscoveryRegistry::new().no_framework_version();
        let response = registry.respond_to(&wire::Payload { patterns: vec![] });
        assert!(response.framework_version.is_none());
    }

    #[test]
    fn override_framework_version_is_emitted_verbatim() {
        let registry = DiscoveryRegistry::new().framework_version("0.2");
        let response = registry.respond_to(&wire::Payload { patterns: vec![] });
        assert_eq!(
            response.framework_version.as_ref().map(|v| v.to_string()),
            Some("0.2".to_string())
        );
    }

    #[test]
    fn v0_2_writes_the_full_three_part_release() {
        let registry = DiscoveryRegistry::new().with::<crate::specs::acl::grant::v0_1::Payload>();
        let response = registry.respond_to_v0_2(&wire_v0_2::Payload { patterns: vec![] });
        assert_eq!(
            response.framework_version.as_ref().map(|v| v.to_string()),
            Some("0.6.0".to_string())
        );
        assert_eq!(response.supported_types.len(), 1);
    }

    #[test]
    fn a_patch_release_survives_in_0_2_and_is_dropped_only_in_0_1() {
        // 0.1 cannot express a PATCH; 0.2 exists so that it can.
        let registry = DiscoveryRegistry::new().framework_version("0.6.1");
        let v1 = registry.respond_to(&wire::Payload { patterns: vec![] });
        let v2 = registry.respond_to_v0_2(&wire_v0_2::Payload { patterns: vec![] });
        assert_eq!(
            v1.framework_version.map(|v| v.to_string()),
            Some("0.6".into())
        );
        assert_eq!(
            v2.framework_version.map(|v| v.to_string()),
            Some("0.6.1".into())
        );
    }

    #[test]
    fn a_two_part_override_is_written_as_its_dot_zero_in_0_2() {
        // SPEC §5.1.1: a two-part M.N is the release M.N.0.
        let registry = DiscoveryRegistry::new().framework_version("0.5");
        let v2 = registry.respond_to_v0_2(&wire_v0_2::Payload { patterns: vec![] });
        assert_eq!(
            v2.framework_version.map(|v| v.to_string()),
            Some("0.5.0".into())
        );
    }

    #[test]
    fn the_0_2_schema_refuses_a_two_part_framework_version() {
        assert!("0.6"
            .parse::<wire_v0_2::ResponseFrameworkVersion>()
            .is_err());
        assert!("0.6.0"
            .parse::<wire_v0_2::ResponseFrameworkVersion>()
            .is_ok());
    }

    #[test]
    fn v0_2_carries_required_ext_in_expanded_form() {
        let grant_uri = TypeUri::canonical("acl/grant", 0, 1).unwrap();
        let registry =
            DiscoveryRegistry::new().with_required_ext(grant_uri, ["vnd.affinidi.webvh"]);
        let response = registry.respond_to_v0_2(&wire_v0_2::Payload { patterns: vec![] });
        match &response.supported_types[0] {
            wire_v0_2::ResponseSupportedTypesItem::Object { required_ext, .. } => {
                assert_eq!(required_ext.as_ref().map(Vec::len), Some(1));
            }
            other => panic!("expected expanded Object form, got {other:?}"),
        }
    }

    #[test]
    fn malformed_framework_version_override_is_omitted_not_panicked() {
        // A caller-supplied override that doesn't match MAJOR.MINOR must not
        // panic when the response is built (M6); the field is simply omitted.
        let registry = DiscoveryRegistry::new().framework_version("not-a-version");
        let response = registry.respond_to(&wire::Payload { patterns: vec![] });
        assert!(response.framework_version.is_none());
        let response = registry.respond_to_v0_2(&wire_v0_2::Payload { patterns: vec![] });
        assert!(response.framework_version.is_none());
    }

    #[test]
    fn with_required_ext_advertises_namespace_policy_in_expanded_form() {
        let grant_uri = TypeUri::canonical("acl/grant", 0, 1).unwrap();
        let registry = DiscoveryRegistry::new()
            .with::<crate::specs::acl::revoke::v0_1::Payload>()
            .with_required_ext(grant_uri, ["vnd.affinidi.webvh"]);

        let response = registry.respond_to(&wire::Payload { patterns: vec![] });

        // acl/grant carries the requiredExt annotation in expanded form.
        let grant_entry = response
            .supported_types
            .iter()
            .find(|e| uri_of(e) == "https://trusttasks.org/spec/acl/grant/0.1")
            .expect("acl/grant entry present");
        match grant_entry {
            wire::ResponseSupportedTypesItem::Object { required_ext, .. } => {
                let namespaces: Vec<String> = required_ext
                    .as_ref()
                    .expect("requiredExt populated")
                    .iter()
                    .map(|n| n.to_string())
                    .collect();
                assert_eq!(namespaces, vec!["vnd.affinidi.webvh".to_string()]);
            }
            other => panic!("expected expanded Object form, got {other:?}"),
        }

        // acl/revoke had no policy declared → shorthand string form.
        let revoke_entry = response
            .supported_types
            .iter()
            .find(|e| uri_of(e) == "https://trusttasks.org/spec/acl/revoke/0.1")
            .expect("acl/revoke entry present");
        assert!(matches!(
            revoke_entry,
            wire::ResponseSupportedTypesItem::Uri(_)
        ));
    }

    fn uris_in(response: &wire::Response) -> Vec<&str> {
        response.supported_types.iter().map(uri_of).collect()
    }

    fn uri_of(entry: &wire::ResponseSupportedTypesItem) -> &str {
        match entry {
            wire::ResponseSupportedTypesItem::Uri(s) => s.as_str(),
            wire::ResponseSupportedTypesItem::Object { type_, .. } => type_.as_str(),
        }
    }
}