rama-http-headers 0.3.0

typed http headers for rama
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
//! `Permissions-Policy` header — [W3C Permissions Policy](https://www.w3.org/TR/permissions-policy/).
//!
//! Comma-separated list of `feature=(allowlist)` entries. Built from
//! typed [`PermissionsPolicyDirective`]s; per-feature deny-all
//! shortcuts (`with_deny_camera`, `set_deny_microphone`, …) are
//! generated via [`rama_utils::macros::generate_set_and_with`].

mod directive;

pub use self::directive::{
    AllowlistSource, PermissionsPolicyDirective, PermissionsPolicyDirectiveName,
};

use std::fmt;

use rama_http_types::{HeaderName, HeaderValue};
use rama_utils::macros::generate_set_and_with;

use crate::{Error, HeaderDecode, HeaderEncode, TypedHeader};

/// `Permissions-Policy` response header.
///
/// Adding a directive that already exists in the policy *replaces* its
/// allow-list in place (preserving declared order). The user agent
/// would treat the second occurrence as the winner per RFC 8941
/// structured-fields anyway, so we collapse to the caller-most-recent
/// value.
///
/// # Examples
///
/// Deny the common ambient-capability features:
///
/// ```
/// use rama_http_headers::PermissionsPolicy;
///
/// let pp = PermissionsPolicy::empty()
///     .with_deny_camera()
///     .with_deny_microphone()
///     .with_deny_geolocation()
///     .with_deny_payment()
///     .with_deny_usb()
///     .with_deny_interest_cohort();
///
/// let rendered = pp.to_string();
/// assert!(rendered.contains("camera=()"));
/// assert!(rendered.contains("interest-cohort=()"));
/// ```
///
/// Drop down to the generic surface for an allow-list or for a
/// proposed/draft feature that isn't yet modelled:
///
/// ```
/// use rama_http_headers::{
///     PermissionsPolicy, PermissionsPolicyDirective, PermissionsPolicyDirectiveName,
///     AllowlistSource,
/// };
///
/// let pp = PermissionsPolicy::empty()
///     .with_directive(PermissionsPolicyDirective::allow(
///         PermissionsPolicyDirectiveName::Camera,
///         AllowlistSource::SelfOrigin,
///     ))
///     .with_directive(PermissionsPolicyDirective::deny(
///         // Unknown / vendor / draft feature names land in the
///         // auto-generated `Unknown` variant via `From<&str>`.
///         PermissionsPolicyDirectiveName::from("x-vendor-experimental"),
///     ));
/// assert_eq!(pp.to_string(), "camera=(self), x-vendor-experimental=()");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PermissionsPolicy {
    directives: Vec<PermissionsPolicyDirective>,
}

impl PermissionsPolicy {
    /// Empty policy. Build from this when adding directives one at a
    /// time.
    #[must_use]
    pub const fn empty() -> Self {
        Self {
            directives: Vec::new(),
        }
    }

    /// Iterate the policy's directives in encoding order.
    pub fn directives(&self) -> impl Iterator<Item = &PermissionsPolicyDirective> + '_ {
        self.directives.iter()
    }

    generate_set_and_with! {
        /// Generic escape hatch: append or replace a directive by
        /// name. If a directive with the same name exists, its
        /// allow-list is overwritten in place (order preserved);
        /// otherwise it's appended.
        ///
        /// The macro generates the `&mut self` sibling
        /// [`set_directive`](Self::set_directive).
        pub fn directive(mut self, directive: PermissionsPolicyDirective) -> Self {
            if let Some(slot) = self
                .directives
                .iter_mut()
                .find(|d| d.name == directive.name)
            {
                slot.allow_list = directive.allow_list;
            } else {
                self.directives.push(directive);
            }
            self
        }
    }

    // ---- per-directive deny-all shortcuts ----
    //
    // Each macro invocation generates both a `with_deny_*` (chaining,
    // takes ownership) and a `set_deny_*` (`&mut self`) form. Body
    // routes through `set_directive` so all paths share one canonical
    // write — taking advantage of the `&mut Self` return on the
    // generated setter.

    generate_set_and_with! {
        /// Set `camera=()` (deny-all).
        pub fn deny_camera(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Camera,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `microphone=()` (deny-all).
        pub fn deny_microphone(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Microphone,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `geolocation=()` (deny-all).
        pub fn deny_geolocation(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Geolocation,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `payment=()` (deny-all).
        pub fn deny_payment(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Payment,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `usb=()` (deny-all).
        pub fn deny_usb(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Usb,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `interest-cohort=()` (deny-all). Opts the site out of
        /// the deprecated FLoC experiment. Pair with
        /// [`deny_browsing_topics`](Self::with_deny_browsing_topics)
        /// to also block Topics API, FLoC's shipped successor.
        pub fn deny_interest_cohort(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::InterestCohort,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `browsing-topics=()` (deny-all). Opts the site out of
        /// the Topics API (Privacy Sandbox).
        pub fn deny_browsing_topics(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::BrowsingTopics,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `attribution-reporting=()` (deny-all). Opts the site
        /// out of the Attribution Reporting API (Privacy Sandbox).
        pub fn deny_attribution_reporting(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::AttributionReporting,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `accelerometer=()` (deny-all).
        pub fn deny_accelerometer(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Accelerometer,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `ambient-light-sensor=()` (deny-all).
        pub fn deny_ambient_light_sensor(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::AmbientLightSensor,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `autoplay=()` (deny-all).
        pub fn deny_autoplay(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Autoplay,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `battery=()` (deny-all).
        pub fn deny_battery(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Battery,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `bluetooth=()` (deny-all).
        pub fn deny_bluetooth(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Bluetooth,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `display-capture=()` (deny-all).
        pub fn deny_display_capture(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::DisplayCapture,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `encrypted-media=()` (deny-all).
        pub fn deny_encrypted_media(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::EncryptedMedia,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `fullscreen=()` (deny-all).
        pub fn deny_fullscreen(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Fullscreen,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `gyroscope=()` (deny-all).
        pub fn deny_gyroscope(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Gyroscope,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `idle-detection=()` (deny-all).
        pub fn deny_idle_detection(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::IdleDetection,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `magnetometer=()` (deny-all).
        pub fn deny_magnetometer(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Magnetometer,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `midi=()` (deny-all).
        pub fn deny_midi(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::Midi,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `picture-in-picture=()` (deny-all).
        pub fn deny_picture_in_picture(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::PictureInPicture,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `publickey-credentials-get=()` (deny-all).
        pub fn deny_publickey_credentials_get(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::PublickeyCredentialsGet,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `screen-wake-lock=()` (deny-all).
        pub fn deny_screen_wake_lock(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::ScreenWakeLock,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `sync-xhr=()` (deny-all).
        pub fn deny_sync_xhr(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::SyncXhr,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `web-share=()` (deny-all).
        pub fn deny_web_share(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::WebShare,
            ));
            self
        }
    }
    generate_set_and_with! {
        /// Set `xr-spatial-tracking=()` (deny-all).
        pub fn deny_xr_spatial_tracking(mut self) -> Self {
            self.set_directive(PermissionsPolicyDirective::deny(
                PermissionsPolicyDirectiveName::XrSpatialTracking,
            ));
            self
        }
    }
}

impl fmt::Display for PermissionsPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, d) in self.directives.iter().enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            fmt::Display::fmt(d, f)?;
        }
        Ok(())
    }
}

impl TypedHeader for PermissionsPolicy {
    fn name() -> &'static HeaderName {
        &::rama_http_types::header::PERMISSIONS_POLICY
    }
}

impl HeaderDecode for PermissionsPolicy {
    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
        // The spec allows the header to be set multiple times — the
        // user agent intersects all returned policies. For round-
        // tripping we concatenate them preserving order, then route
        // through `set_directive` so repeats collapse to the
        // last-seen allow-list.
        let mut out = Self::empty();
        let mut any = false;
        for value in values {
            any = true;
            let s = value.to_str().map_err(|_err| Error::invalid())?;
            for raw in split_top_level_commas(s) {
                let trimmed = raw.trim();
                if trimmed.is_empty() {
                    continue;
                }
                let Some(directive) = parse_directive(trimmed) else {
                    // Drop malformed directives, keep the rest. The
                    // alternative would be to fail the whole header
                    // on a single bad token, which would be more
                    // surprising than logging it and moving on.
                    continue;
                };
                out.set_directive(directive);
            }
        }
        if !any {
            return Err(Error::invalid());
        }
        Ok(out)
    }
}

impl HeaderEncode for PermissionsPolicy {
    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
        let rendered = self.to_string();
        match HeaderValue::try_from(rendered) {
            Ok(v) => values.extend(::std::iter::once(v)),
            Err(_) => {
                values.extend(::std::iter::once(HeaderValue::from_static("")));
            }
        }
    }
}

/// Split the header value on commas that are not inside `()`. The
/// allow-list is parenthesised, so a comma inside an allow-list isn't
/// the directive separator. (Tokens themselves don't contain commas,
/// and origin sf-strings don't either by spec.)
fn split_top_level_commas(s: &str) -> impl Iterator<Item = &str> {
    let bytes = s.as_bytes();
    let mut start = 0usize;
    let mut depth = 0i32;
    let mut out: Vec<&str> = Vec::new();
    for (i, b) in bytes.iter().enumerate() {
        match b {
            b'(' => depth += 1,
            b')' => depth = depth.saturating_sub(1),
            b',' if depth == 0 => {
                out.push(&s[start..i]);
                start = i + 1;
            }
            _ => {}
        }
    }
    if start <= s.len() {
        out.push(&s[start..]);
    }
    out.into_iter()
}

fn parse_directive(s: &str) -> Option<PermissionsPolicyDirective> {
    let eq = s.find('=')?;
    let name_raw = s[..eq].trim();
    let value_raw = s[eq + 1..].trim();
    if name_raw.is_empty() {
        return None;
    }
    let inner = value_raw
        .strip_prefix('(')
        .and_then(|t| t.strip_suffix(')'))?;
    // `From<&str>` on the @String enum is case-insensitive and falls
    // through to `Unknown(String)` for unrecognised tokens — exactly
    // the spec semantic (preserve declared name, even if not in the
    // typed registry).
    let name = PermissionsPolicyDirectiveName::from(name_raw);
    let allow_list = inner
        .split_whitespace()
        .filter_map(AllowlistSource::from_token)
        .collect();
    Some(PermissionsPolicyDirective { name, allow_list })
}

#[cfg(test)]
mod tests {
    use super::super::{test_decode, test_encode};
    use super::*;

    #[test]
    fn empty_renders_to_empty_string() {
        let pp = PermissionsPolicy::empty();
        assert_eq!(pp.to_string(), "");
    }

    #[test]
    fn keyword_shortcuts_render_deny_all_chain() {
        let pp = PermissionsPolicy::empty()
            .with_deny_camera()
            .with_deny_microphone()
            .with_deny_geolocation();
        assert_eq!(pp.to_string(), "camera=(), microphone=(), geolocation=()");
    }

    #[test]
    fn keyword_shortcuts_share_path_with_generic_with() {
        // The shortcut and the generic hatch should produce identical
        // typed state, which falls out of routing both through
        // `set_directive`.
        let via_shortcut = PermissionsPolicy::empty().with_deny_camera();
        let via_generic = PermissionsPolicy::empty().with_directive(
            PermissionsPolicyDirective::deny(PermissionsPolicyDirectiveName::Camera),
        );
        assert_eq!(via_shortcut, via_generic);
    }

    #[test]
    fn set_mutates_in_place() {
        let mut pp = PermissionsPolicy::empty();
        pp.set_deny_camera();
        pp.set_directive(PermissionsPolicyDirective::allow(
            PermissionsPolicyDirectiveName::Microphone,
            AllowlistSource::SelfOrigin,
        ));
        assert_eq!(pp.to_string(), "camera=(), microphone=(self)");
    }

    #[test]
    fn allow_list_self_and_origin_render() {
        let pp = PermissionsPolicy::empty().with_directive(PermissionsPolicyDirective::allow_from(
            PermissionsPolicyDirectiveName::Camera,
            [
                AllowlistSource::SelfOrigin,
                AllowlistSource::origin("https://example.com"),
            ],
        ));
        assert_eq!(pp.to_string(), r#"camera=(self "https://example.com")"#);
    }

    #[test]
    fn wildcard_and_src_render() {
        let pp_wild = PermissionsPolicy::empty().with_directive(PermissionsPolicyDirective::allow(
            PermissionsPolicyDirectiveName::Camera,
            AllowlistSource::Wildcard,
        ));
        assert_eq!(pp_wild.to_string(), "camera=(*)");

        let pp_src = PermissionsPolicy::empty().with_directive(PermissionsPolicyDirective::allow(
            PermissionsPolicyDirectiveName::Camera,
            AllowlistSource::Src,
        ));
        assert_eq!(pp_src.to_string(), "camera=(src)");
    }

    #[test]
    fn unknown_feature_via_other_round_trips() {
        // Use a vendor-prefixed name that's deliberately not in the
        // typed-variant set so the round-trip exercises the auto-
        // generated `Unknown` path. (The registry grows over time,
        // so any name we picked would risk becoming a real variant
        // in a future revision.)
        let pp = PermissionsPolicy::empty().with_directive(PermissionsPolicyDirective::deny(
            PermissionsPolicyDirectiveName::from("x-vendor-experimental"),
        ));
        assert_eq!(pp.to_string(), "x-vendor-experimental=()");
        let parsed = test_decode::<PermissionsPolicy>(&[pp.to_string().as_str()]).expect("decode");
        assert_eq!(parsed, pp);
    }

    #[test]
    fn decode_parses_canonical_deny_all_chain() {
        let parsed = test_decode::<PermissionsPolicy>(&[
            "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()",
        ])
        .expect("decode");
        let names: Vec<&str> = parsed.directives().map(|d| d.name.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "camera",
                "microphone",
                "geolocation",
                "payment",
                "usb",
                "interest-cohort",
            ]
        );
        for d in parsed.directives() {
            assert!(
                d.allow_list.is_empty(),
                "{} should be deny-all",
                d.name.as_str()
            );
        }
    }

    #[test]
    fn decode_preserves_declared_order() {
        let parsed = test_decode::<PermissionsPolicy>(&["usb=(), camera=()"]).expect("decode");
        let names: Vec<&str> = parsed.directives().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["usb", "camera"]);
    }

    #[test]
    fn decode_collapses_repeated_feature_last_wins() {
        let parsed =
            test_decode::<PermissionsPolicy>(&["camera=(), camera=(self)"]).expect("decode");
        let directives: Vec<_> = parsed.directives().collect();
        assert_eq!(directives.len(), 1);
        assert_eq!(directives[0].name, PermissionsPolicyDirectiveName::Camera);
        assert_eq!(
            directives[0].allow_list.as_slice(),
            &[AllowlistSource::SelfOrigin]
        );
    }

    #[test]
    fn decode_handles_multiple_header_values() {
        let parsed = test_decode::<PermissionsPolicy>(&["camera=()", "microphone=()"])
            .expect("decode multi-value");
        let names: Vec<&str> = parsed.directives().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["camera", "microphone"]);
    }

    #[test]
    fn decode_tolerates_whitespace() {
        let parsed =
            test_decode::<PermissionsPolicy>(&["  camera = ( self )  ,  microphone = ( )  "])
                .expect("decode whitespace-heavy");
        let directives: Vec<_> = parsed.directives().collect();
        assert_eq!(directives.len(), 2);
        assert_eq!(
            directives[0].allow_list.as_slice(),
            &[AllowlistSource::SelfOrigin]
        );
        assert!(directives[1].allow_list.is_empty());
    }

    #[test]
    fn decode_case_insensitive_on_known_features() {
        let parsed = test_decode::<PermissionsPolicy>(&["Camera=()"]).expect("decode");
        let directives: Vec<_> = parsed.directives().collect();
        assert_eq!(directives.len(), 1);
        assert_eq!(directives[0].name, PermissionsPolicyDirectiveName::Camera);
    }

    #[test]
    fn decode_mixed_sources() {
        let parsed = test_decode::<PermissionsPolicy>(&[r#"camera=(self "https://a.example" *)"#])
            .expect("decode");
        let directives: Vec<_> = parsed.directives().collect();
        assert_eq!(directives.len(), 1);
        assert_eq!(
            directives[0].allow_list.as_slice(),
            &[
                AllowlistSource::SelfOrigin,
                AllowlistSource::origin("https://a.example"),
                AllowlistSource::Wildcard,
            ]
        );
    }

    #[test]
    fn decode_empty_returns_error() {
        assert_eq!(test_decode::<PermissionsPolicy>(&[] as &[&str]), None);
    }

    #[test]
    fn newer_feature_names_round_trip_as_typed_variants() {
        // Regression for the post-ticket spec audit: these used to
        // fall through to `Other(...)`. They should now parse to
        // their canonical typed variants.
        for (token, expected) in [
            (
                "browsing-topics",
                PermissionsPolicyDirectiveName::BrowsingTopics,
            ),
            (
                "attribution-reporting",
                PermissionsPolicyDirectiveName::AttributionReporting,
            ),
            (
                "clipboard-read",
                PermissionsPolicyDirectiveName::ClipboardRead,
            ),
            (
                "clipboard-write",
                PermissionsPolicyDirectiveName::ClipboardWrite,
            ),
            (
                "compute-pressure",
                PermissionsPolicyDirectiveName::ComputePressure,
            ),
            ("gamepad", PermissionsPolicyDirectiveName::Gamepad),
            ("hid", PermissionsPolicyDirectiveName::Hid),
            ("serial", PermissionsPolicyDirectiveName::Serial),
            (
                "storage-access",
                PermissionsPolicyDirectiveName::StorageAccess,
            ),
            (
                "publickey-credentials-create",
                PermissionsPolicyDirectiveName::PublickeyCredentialsCreate,
            ),
            (
                "window-management",
                PermissionsPolicyDirectiveName::WindowManagement,
            ),
            ("local-fonts", PermissionsPolicyDirectiveName::LocalFonts),
            ("unload", PermissionsPolicyDirectiveName::Unload),
        ] {
            let raw = format!("{token}=()");
            let parsed = test_decode::<PermissionsPolicy>(&[raw.as_str()])
                .unwrap_or_else(|| panic!("decode {token}"));
            let directive = parsed.directives().next().expect("one directive");
            assert_eq!(directive.name, expected, "token `{token}` parsed wrong");
            assert_eq!(parsed.to_string(), raw, "round-trip changed `{token}`");
        }
    }

    #[test]
    fn topics_and_attribution_shortcuts_render_canonical_tokens() {
        let pp = PermissionsPolicy::empty()
            .with_deny_interest_cohort()
            .with_deny_browsing_topics()
            .with_deny_attribution_reporting();
        assert_eq!(
            pp.to_string(),
            "interest-cohort=(), browsing-topics=(), attribution-reporting=()",
        );
    }

    #[test]
    fn encode_round_trips_through_header_map() {
        let pp = PermissionsPolicy::empty()
            .with_deny_camera()
            .with_deny_microphone()
            .with_directive(PermissionsPolicyDirective::allow_from(
                PermissionsPolicyDirectiveName::Geolocation,
                [
                    AllowlistSource::SelfOrigin,
                    AllowlistSource::origin("https://example.com"),
                ],
            ));
        let map = test_encode(pp.clone());
        let raw = map
            .get(PermissionsPolicy::name())
            .expect("set")
            .to_str()
            .unwrap()
            .to_owned();
        assert_eq!(raw, pp.to_string());
        let parsed = test_decode::<PermissionsPolicy>(&[raw.as_str()]).expect("decode");
        assert_eq!(parsed, pp);
    }
}