Skip to main content

rocket/shield/
policy.rs

1//! Module containing the [`Policy`] trait and types that implement it.
2
3use std::fmt;
4use std::borrow::Cow;
5
6use indexmap::IndexMap;
7use rocket_http::{ext::IntoCollection, private::SmallVec};
8use time::Duration;
9
10use crate::http::{Header, uri::Absolute, uncased::Uncased};
11
12/// Trait implemented by security and privacy policy headers.
13///
14/// Types that implement this trait can be [`enable()`]d and [`disable()`]d on
15/// instances of [`Shield`].
16///
17/// [`Shield`]: crate::shield::Shield
18/// [`enable()`]: crate::shield::Shield::enable()
19/// [`disable()`]: crate::shield::Shield::disable()
20pub trait Policy: Default + Send + Sync + 'static {
21    /// The actual name of the HTTP header.
22    ///
23    /// This name must uniquely identify the header as it is used to determine
24    /// whether two implementations of `Policy` are for the same header. Use the
25    /// real HTTP header's name.
26    ///
27    /// # Example
28    ///
29    /// ```rust
30    /// # extern crate rocket;
31    /// # use rocket::http::Header;
32    /// use rocket::shield::Policy;
33    ///
34    /// #[derive(Default)]
35    /// struct MyPolicy;
36    ///
37    /// impl Policy for MyPolicy {
38    ///     const NAME: &'static str = "X-My-Policy";
39    /// #   fn header(&self) -> Header<'static> { unimplemented!() }
40    /// }
41    /// ```
42    const NAME: &'static str;
43
44    /// Returns the [`Header`](../../rocket/http/struct.Header.html) to attach
45    /// to all outgoing responses.
46    ///
47    /// # Example
48    ///
49    /// ```rust
50    /// # extern crate rocket;
51    /// use rocket::http::Header;
52    /// use rocket::shield::Policy;
53    ///
54    /// #[derive(Default)]
55    /// struct MyPolicy;
56    ///
57    /// impl Policy for MyPolicy {
58    /// #   const NAME: &'static str = "X-My-Policy";
59    ///     fn header(&self) -> Header<'static> {
60    ///         Header::new(Self::NAME, "value-to-enable")
61    ///     }
62    /// }
63    /// ```
64    fn header(&self) -> Header<'static>;
65}
66
67/// Hack to make `Policy` Object-Safe.
68pub(crate) trait SubPolicy: Send + Sync {
69    fn header(&self) -> Header<'static>;
70}
71
72impl<P: Policy> SubPolicy for P {
73    fn header(&self) -> Header<'static> {
74        Policy::header(self)
75    }
76}
77
78macro_rules! impl_policy {
79    ($T:ty, $name:expr) => (
80        impl Policy for $T {
81            const NAME: &'static str = $name;
82
83            fn header(&self) -> Header<'static> {
84                self.into()
85            }
86        }
87    )
88}
89
90// Keep this in-sync with the top-level module docs.
91impl_policy!(XssFilter, "X-XSS-Protection");
92impl_policy!(NoSniff, "X-Content-Type-Options");
93impl_policy!(Frame, "X-Frame-Options");
94impl_policy!(Hsts, "Strict-Transport-Security");
95impl_policy!(ExpectCt, "Expect-CT");
96impl_policy!(Referrer, "Referrer-Policy");
97impl_policy!(Prefetch, "X-DNS-Prefetch-Control");
98impl_policy!(Permission, "Permissions-Policy");
99
100/// The [Referrer-Policy] header: controls the value set by the browser for the
101/// [Referer] header.
102///
103/// Tells the browser if it should send all or part of URL of the current page
104/// to the next site the user navigates to via the [Referer] header. This can be
105/// important for security as the URL itself might expose sensitive data, such
106/// as a hidden file path or personal identifier.
107///
108/// [Referrer-Policy]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
109/// [Referer]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer
110pub enum Referrer {
111    /// Omits the `Referer` header (returned by [`Referrer::default()`]).
112    NoReferrer,
113
114    /// Omits the `Referer` header on connection downgrade i.e. following HTTP
115    /// link from HTTPS site (_Browser default_).
116    NoReferrerWhenDowngrade,
117
118    /// Only send the origin of part of the URL, e.g. the origin of
119    /// `https://foo.com/bob.html` is `https://foo.com`.
120    Origin,
121
122    /// Send full URL for same-origin requests, only send origin part when
123    /// replying to [cross-origin] requests.
124    ///
125    /// [cross-origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
126    OriginWhenCrossOrigin,
127
128    /// Send full URL for same-origin requests only.
129    SameOrigin,
130
131    /// Only send origin part of URL, only send if protocol security level
132    /// remains the same e.g. HTTPS to HTTPS.
133    StrictOrigin,
134
135    /// Send full URL for same-origin requests. For cross-origin requests, only
136    /// send origin part of URL if protocol security level remains the same e.g.
137    /// HTTPS to HTTPS.
138    StrictOriginWhenCrossOrigin,
139
140    /// Send full URL for same-origin or cross-origin requests. _This will leak
141    /// the full URL of TLS protected resources to insecure origins. Use with
142    /// caution._
143    UnsafeUrl,
144 }
145
146/// Defaults to [`Referrer::NoReferrer`]. Tells the browser to omit the
147/// `Referer` header.
148impl Default for Referrer {
149    fn default() -> Referrer {
150        Referrer::NoReferrer
151    }
152}
153
154impl From<&Referrer> for Header<'static> {
155    fn from(referrer: &Referrer) -> Self {
156        let policy_string = match referrer {
157            Referrer::NoReferrer => "no-referrer",
158            Referrer::NoReferrerWhenDowngrade => "no-referrer-when-downgrade",
159            Referrer::Origin => "origin",
160            Referrer::OriginWhenCrossOrigin => "origin-when-cross-origin",
161            Referrer::SameOrigin => "same-origin",
162            Referrer::StrictOrigin => "strict-origin",
163            Referrer::StrictOriginWhenCrossOrigin => "strict-origin-when-cross-origin",
164            Referrer::UnsafeUrl => "unsafe-url",
165        };
166
167        Header::new(Referrer::NAME, policy_string)
168    }
169}
170
171/// The [Expect-CT] header: enables reporting and/or enforcement of [Certificate
172/// Transparency].
173///
174/// [Certificate Transparency] can detect and prevent the use of incorrectly
175/// issued malicious, or revoked TLS certificates. It solves a variety of
176/// problems with public TLS/SSL certificate management and is valuable measure
177/// for all public TLS applications.
178///
179/// If you're just [getting started] with certificate transparency, ensure that
180/// your [site is in compliance][getting started] before you enable enforcement
181/// with [`ExpectCt::Enforce`] or [`ExpectCt::ReportAndEnforce`]. Failure to do
182/// so will result in the browser refusing to communicate with your application.
183/// _You have been warned_.
184///
185/// [Expect-CT]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expect-CT
186/// [Certificate Transparency]: http://www.certificate-transparency.org/what-is-ct
187/// [getting started]: http://www.certificate-transparency.org/getting-started
188pub enum ExpectCt {
189    /// Enforce certificate compliance for the next [`Duration`]. Ensure that
190    /// your certificates are in compliance before turning on enforcement.
191    /// (_Shield_ default).
192    Enforce(Duration),
193
194    /// Report to `Absolute`, but do not enforce, compliance violations for the
195    /// next [`Duration`]. Doesn't provide any protection but is a good way make
196    /// sure things are working correctly before turning on enforcement in
197    /// production.
198    Report(Duration, Absolute<'static>),
199
200    /// Enforce compliance and report violations to `Absolute` for the next
201    /// [`Duration`].
202    ReportAndEnforce(Duration, Absolute<'static>),
203}
204
205/// Defaults to [`ExpectCt::Enforce`] with a 30 day duration, enforce CT
206/// compliance, see [draft] standard for more.
207///
208/// [draft]: https://tools.ietf.org/html/draft-ietf-httpbis-expect-ct-03#page-15
209impl Default for ExpectCt {
210    fn default() -> ExpectCt {
211        ExpectCt::Enforce(Duration::days(30))
212    }
213}
214
215impl From<&ExpectCt> for Header<'static> {
216    fn from(expect: &ExpectCt) -> Self {
217        let policy_string =  match expect {
218            ExpectCt::Enforce(age) => format!("max-age={}, enforce", age.whole_seconds()),
219            ExpectCt::Report(age, uri) => {
220                format!(r#"max-age={}, report-uri="{}""#, age.whole_seconds(), uri)
221            }
222            ExpectCt::ReportAndEnforce(age, uri) => {
223                format!("max-age={}, enforce, report-uri=\"{}\"", age.whole_seconds(), uri)
224            }
225        };
226
227        Header::new(ExpectCt::NAME, policy_string)
228    }
229}
230
231/// The [X-Content-Type-Options] header: turns off [mime sniffing] which can
232/// prevent certain [attacks].
233///
234/// [mime sniffing]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#MIME_sniffing
235/// [X-Content-Type-Options]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
236/// [attacks]: https://blog.mozilla.org/security/2016/08/26/mitigating-mime-confusion-attacks-in-firefox/
237pub enum NoSniff {
238    /// Turns off mime sniffing.
239    Enable,
240}
241
242/// Defaults to [`NoSniff::Enable`], turns off mime sniffing.
243impl Default for NoSniff {
244    fn default() -> NoSniff {
245        NoSniff::Enable
246    }
247}
248
249impl From<&NoSniff> for Header<'static> {
250    fn from(_: &NoSniff) -> Self {
251        Header::new(NoSniff::NAME, "nosniff")
252    }
253}
254
255/// The HTTP [Strict-Transport-Security] (HSTS) header: enforces strict HTTPS
256/// usage.
257///
258/// HSTS tells the browser that the site should only be accessed using HTTPS
259/// instead of HTTP. HSTS prevents a variety of downgrading attacks and should
260/// always be used when [TLS] is enabled. `Shield` will turn HSTS on and issue a
261/// warning if you enable TLS without enabling HSTS when the application is run
262/// in non-debug profiles.
263///
264/// While HSTS is important for HTTPS security, incorrectly configured HSTS can
265/// lead to problems as you are disallowing access to non-HTTPS enabled parts of
266/// your site. [Yelp engineering] has good discussion of potential challenges
267/// that can arise and how to roll this out in a large scale setting. So, if
268/// you use TLS, use HSTS, but roll it out with care.
269///
270/// [TLS]: https://rocket.rs/guide/configuration/#configuring-tls
271/// [Strict-Transport-Security]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
272/// [Yelp engineering]: https://engineeringblog.yelp.com/2017/09/the-road-to-hsts.html
273#[derive(PartialEq, Copy, Clone)]
274pub enum Hsts {
275    /// Browser should only permit this site to be accesses by HTTPS for the
276    /// next [`Duration`].
277    Enable(Duration),
278
279    /// Like [`Hsts::Enable`], but also apply to all of the site's subdomains.
280    IncludeSubDomains(Duration),
281
282    /// Send a "preload" HSTS header, which requests inclusion in the HSTS
283    /// preload list. This variant implies [`Hsts::IncludeSubDomains`], which
284    /// implies [`Hsts::Enable`].
285    ///
286    /// The provided `Duration` must be _at least_ 365 days. If the duration
287    /// provided is less than 365 days, the header will be written out with a
288    /// `max-age` of 365 days.
289    ///
290    /// # Details
291    ///
292    /// Google maintains an [HSTS preload service] that can be used to prevent
293    /// the browser from ever connecting to your site over an insecure
294    /// connection. Read more at [MDN]. Don't enable this before you have
295    /// registered your site and you ensure that it meets the requirements
296    /// specified by the preload service.
297    ///
298    /// [HSTS preload service]: https://hstspreload.org/
299    /// [MDN]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security#Preloading_Strict_Transport_Security
300    Preload(Duration),
301}
302
303/// Defaults to `Hsts::Enable(Duration::days(365))`.
304impl Default for Hsts {
305    fn default() -> Hsts {
306        Hsts::Enable(Duration::days(365))
307    }
308}
309
310impl From<&Hsts> for Header<'static> {
311    fn from(hsts: &Hsts) -> Self {
312        if hsts == &Hsts::default() {
313            static DEFAULT: Header<'static> = Header {
314                name: Uncased::from_borrowed(Hsts::NAME),
315                value: Cow::Borrowed("max-age=31536000")
316            };
317
318            return DEFAULT.clone();
319        }
320
321        let policy_string = match hsts {
322            Hsts::Enable(age) => format!("max-age={}", age.whole_seconds()),
323            Hsts::IncludeSubDomains(age) => {
324                format!("max-age={}; includeSubDomains", age.whole_seconds())
325            }
326            Hsts::Preload(age) => {
327                // Google says it needs to be >= 365 days for preload list.
328                static YEAR: Duration = Duration::seconds(31536000);
329
330                format!("max-age={}; includeSubDomains; preload", age.max(&YEAR).whole_seconds())
331            }
332        };
333
334        Header::new(Hsts::NAME, policy_string)
335    }
336}
337
338/// The [X-Frame-Options] header: helps prevent [clickjacking] attacks.
339///
340/// Controls whether the browser should allow the page to render in a `<frame>`,
341/// [`<iframe>`][iframe] or `<object>`. This can be used to prevent
342/// [clickjacking] attacks.
343///
344/// [X-Frame-Options]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
345/// [clickjacking]: https://en.wikipedia.org/wiki/Clickjacking
346/// [owasp-clickjacking]: https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet
347/// [iframe]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe
348pub enum Frame {
349    /// Page cannot be displayed in a frame.
350    Deny,
351
352    /// Page can only be displayed in a frame if the page trying to render it is
353    /// in the same origin. Interpretation of same-origin is [browser
354    /// dependent][X-Frame-Options].
355    ///
356    /// [X-Frame-Options]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
357    SameOrigin,
358}
359
360/// Defaults to [`Frame::SameOrigin`].
361impl Default for Frame {
362    fn default() -> Frame {
363        Frame::SameOrigin
364    }
365}
366
367impl From<&Frame> for Header<'static> {
368    fn from(frame: &Frame) -> Self {
369        let policy_string: &'static str = match frame {
370            Frame::Deny => "DENY",
371            Frame::SameOrigin => "SAMEORIGIN",
372        };
373
374        Header::new(Frame::NAME, policy_string)
375    }
376}
377
378/// The [X-XSS-Protection] header: filters some forms of reflected [XSS]
379/// attacks. Modern browsers do not support or enforce this header.
380///
381/// [X-XSS-Protection]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
382/// [XSS]: https://developer.mozilla.org/en-US/docs/Glossary/Cross-site_scripting
383pub enum XssFilter {
384    /// Disables XSS filtering.
385    Disable,
386
387    /// Enables XSS filtering. If XSS is detected, the browser will sanitize
388    /// before rendering the page (_Shield default_).
389    Enable,
390
391    /// Enables XSS filtering. If XSS is detected, the browser will not
392    /// render the page.
393    EnableBlock,
394}
395
396/// Defaults to [`XssFilter::Enable`].
397impl Default for XssFilter {
398    fn default() -> XssFilter {
399        XssFilter::Enable
400    }
401}
402
403impl From<&XssFilter> for Header<'static> {
404    fn from(filter: &XssFilter) -> Self {
405        let policy_string: &'static str = match filter {
406            XssFilter::Disable => "0",
407            XssFilter::Enable => "1",
408            XssFilter::EnableBlock => "1; mode=block",
409        };
410
411        Header::new(XssFilter::NAME, policy_string)
412    }
413}
414
415/// The [X-DNS-Prefetch-Control] header: controls browser DNS prefetching.
416///
417/// Tells the browser if it should perform domain name resolution on both links
418/// that the user may choose to follow as well as URLs for items referenced by
419/// the document including images, CSS, JavaScript, and so forth. Disabling
420/// prefetching is useful if you don't control the link on the pages, or know
421/// that you don't want to leak information to these domains.
422///
423/// [X-DNS-Prefetch-Control]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control
424pub enum Prefetch {
425    /// Enables DNS prefetching. This is the browser default.
426    On,
427    /// Disables DNS prefetching. This is the shield policy default.
428    Off,
429}
430
431impl Default for Prefetch {
432    fn default() -> Prefetch {
433        Prefetch::Off
434    }
435}
436
437impl From<&Prefetch> for Header<'static> {
438    fn from(prefetch: &Prefetch) -> Self {
439        let policy_string = match prefetch {
440            Prefetch::On => "on",
441            Prefetch::Off => "off",
442        };
443
444        Header::new(Prefetch::NAME, policy_string)
445    }
446}
447
448/// The [Permissions-Policy] header: allow or block the use of browser features.
449///
450/// Tells the browser to allow or block the use of a browser feature in the
451/// top-level page as well as allow or block _requesting access to_ (via the
452/// `allow` `iframe` attribute) features in embedded iframes.
453///
454/// By default, the top-level page may access ~all features and any embedded
455/// iframes may request access to ~any feature. This header allows the server to
456/// control exactly _which_ (if any) origins may access or request access to
457/// browser features.
458///
459/// Features are enabled via the [`Permission::allowed()`] constructor and
460/// chainable [`allow()`](Self::allow()) build method. Features can be blocked
461/// via the [`Permission::blocked()`] and chainable [`block()`](Self::block())
462/// builder method.
463///
464/// ```rust
465    /// # #[macro_use] extern crate rocket;
466/// use rocket::shield::{Shield, Permission, Feature, Allow};
467///
468/// // In addition to defaults, block access to geolocation and USB features.
469/// // Enable camera and microphone features only for the serving origin. Enable
470/// // payment request access for the current origin and `https://rocket.rs`.
471/// let permission = Permission::default()
472///     .block(Feature::Geolocation)
473///     .block(Feature::Usb)
474///     .allow(Feature::Camera, Allow::This)
475///     .allow(Feature::Microphone, Allow::This)
476///     .allow(Feature::Payment, [Allow::This, Allow::Origin(uri!("https://rocket.rs"))]);
477///
478/// rocket::build().attach(Shield::default().enable(permission));
479/// ```
480///
481/// # Default
482///
483/// The default returned via [`Permission::default()`] blocks access to the
484/// `interest-cohort` feature, otherwise known as FLoC, which disables using the
485/// current site in ad targeting tracking computations.
486///
487/// [Permissions-Policy]: https://github.com/w3c/webappsec-permissions-policy/blob/a45df7b237e2a85e1909d7f226ca4eb4ce5095ba/permissions-policy-explainer.md
488#[derive(PartialEq, Clone)]
489pub struct Permission(IndexMap<Feature, Option<SmallVec<[Allow; 1]>>>);
490
491impl Default for Permission {
492    /// The default `Permission` policy blocks access to the `interest-cohort`
493    /// feature, otherwise known as FLoC, which disables using the current site
494    /// in ad targeting tracking computations.
495    fn default() -> Self {
496        Permission::blocked(Feature::InterestCohort)
497    }
498}
499
500impl Permission {
501    /// Constructs a new `Permission` policy with only `feature` allowed for the
502    /// set of origins in `allow` which may be a single [`Allow`], a slice
503    /// (`[Allow]` or `&[Allow]`), or a vector (`Vec<Allow>`).
504    ///
505    /// If `allow` is empty, the use of the feature is blocked unless another
506    /// call to `allow()` allows it. If `allow` contains [`Allow::Any`], the
507    /// feature is allowable for all origins. Otherwise, the feature is
508    /// allowable only for the origin specified in `allow`.
509    ///
510    /// # Panics
511    ///
512    /// Panics if an `Absolute` URI in an `Allow::Origin` does not contain a
513    /// host part.
514    ///
515    /// # Example
516    ///
517    /// ```rust
518    /// # #[macro_use] extern crate rocket;
519    /// use rocket::shield::{Permission, Feature, Allow};
520    ///
521    /// let rocket = Allow::Origin(uri!("https://rocket.rs"));
522    ///
523    /// let perm = Permission::allowed(Feature::Usb, Allow::This);
524    /// let perm = Permission::allowed(Feature::Usb, Allow::Any);
525    /// let perm = Permission::allowed(Feature::Usb, [Allow::This, rocket]);
526    /// ```
527    pub fn allowed<L>(feature: Feature, allow: L) -> Self
528        where L: IntoCollection<Allow>
529    {
530        Permission(IndexMap::new()).allow(feature, allow)
531    }
532
533    /// Constructs a new `Permission` policy with only `feature` blocked.
534    ///
535    /// # Example
536    ///
537    /// ```rust
538    /// use rocket::shield::{Permission, Feature};
539    ///
540    /// let perm = Permission::blocked(Feature::Usb);
541    /// let perm = Permission::blocked(Feature::Payment);
542    /// ```
543    pub fn blocked(feature: Feature) -> Self {
544        Permission(IndexMap::new()).block(feature)
545    }
546
547    /// Adds `feature` as allowable for the set of origins in `allow` which may
548    /// be a single [`Allow`], a slice (`[Allow]` or `&[Allow]`), or a vector
549    /// (`Vec<Allow>`).
550    ///
551    /// This policy supersedes any previous policy set for `feature`.
552    ///
553    /// If `allow` is empty, the use of the feature is blocked unless another
554    /// call to `allow()` allows it. If `allow` contains [`Allow::Any`], the
555    /// feature is allowable for all origins. Otherwise, the feature is
556    /// allowable only for the origin specified in `allow`.
557    ///
558    /// # Panics
559    ///
560    /// Panics if an `Absolute` URI in an `Allow::Origin` does not contain a
561    /// host part.
562    ///
563    /// # Example
564    ///
565    /// ```rust
566    /// # #[macro_use] extern crate rocket;
567    /// use rocket::shield::{Permission, Feature, Allow};
568    ///
569    /// let rocket = Allow::Origin(uri!("https://rocket.rs"));
570    /// let perm = Permission::allowed(Feature::Usb, Allow::This)
571    ///     .allow(Feature::Payment, [rocket, Allow::This]);
572    /// ```
573    pub fn allow<L>(mut self, feature: Feature, allow: L) -> Self
574        where L: IntoCollection<Allow>
575    {
576        let mut allow = allow.into_collection();
577
578        if allow.contains(&Allow::Any) {
579            allow = Allow::Any.into_collection();
580        }
581
582        for allow in &allow {
583            if let Allow::Origin(absolute) = allow {
584                let auth = absolute.authority();
585                if auth.is_none() || matches!(auth, Some(a) if a.host().is_empty()) {
586                    panic!("...")
587                }
588            }
589        }
590
591        self.0.insert(feature, Some(allow));
592        self
593    }
594
595    /// Blocks `feature`. This policy supersedes any previous policy set for
596    /// `feature`.
597    ///
598    /// # Example
599    ///
600    /// ```rust
601    /// use rocket::shield::{Permission, Feature};
602    ///
603    /// let perm = Permission::default()
604    ///     .block(Feature::Usb)
605    ///     .block(Feature::Payment);
606    /// ```
607    pub fn block(mut self, feature: Feature) -> Self {
608        self.0.insert(feature, None);
609        self
610    }
611
612    /// Returns the allow list (so far) for `feature` if feature is allowed.
613    ///
614    /// # Example
615    ///
616    /// ```rust
617    /// use rocket::shield::{Permission, Feature, Allow};
618    ///
619    /// let perm = Permission::default();
620    /// assert!(perm.get(Feature::Usb).is_none());
621    ///
622    /// let perm = perm.allow(Feature::Usb, Allow::Any);
623    /// assert_eq!(perm.get(Feature::Usb).unwrap(), &[Allow::Any]);
624    /// ```
625    pub fn get(&self, feature: Feature) -> Option<&[Allow]> {
626        self.0.get(&feature)?.as_deref()
627    }
628
629    /// Returns an iterator over the pairs of features and their allow lists,
630    /// `None` if the feature is blocked.
631    ///
632    /// Features are returned in the order in which they were first added.
633    ///
634    /// # Example
635    ///
636    /// ```rust
637    /// # #[macro_use] extern crate rocket;
638    /// use rocket::shield::{Permission, Feature, Allow};
639    ///
640    /// let foo = uri!("https://foo.com:1234");
641    /// let perm = Permission::blocked(Feature::Camera)
642    ///     .allow(Feature::Gyroscope, [Allow::This, Allow::Origin(foo.clone())])
643    ///     .block(Feature::Payment)
644    ///     .allow(Feature::Camera, Allow::Any);
645    ///
646    /// let perms: Vec<_> = perm.iter().collect();
647    /// assert_eq!(perms.len(), 3);
648    /// assert_eq!(perms, vec![
649    ///     (Feature::Camera, Some(&[Allow::Any][..])),
650    ///     (Feature::Gyroscope, Some(&[Allow::This, Allow::Origin(foo)][..])),
651    ///     (Feature::Payment, None),
652    /// ]);
653    /// ```
654    pub fn iter(&self) -> impl Iterator<Item = (Feature, Option<&[Allow]>)> {
655        self.0.iter().map(|(feature, list)| (*feature, list.as_deref()))
656    }
657}
658
659impl From<&Permission> for Header<'static> {
660    fn from(perm: &Permission) -> Self {
661        if perm == &Permission::default() {
662            static DEFAULT: Header<'static> = Header {
663                name: Uncased::from_borrowed(Permission::NAME),
664                value: Cow::Borrowed("interest-cohort=()")
665            };
666
667            return DEFAULT.clone();
668        }
669
670        let value = perm.0.iter()
671            .map(|(feature, allow)| {
672                let list = allow.as_ref()
673                    .into_iter()
674                    .flatten()
675                    .map(|origin| origin.rendered())
676                    .collect::<Vec<_>>()
677                    .join(" ");
678
679                format!("{}=({})", feature, list)
680            })
681            .collect::<Vec<_>>()
682            .join(", ");
683
684        Header::new(Permission::NAME, value)
685    }
686}
687
688/// Specifies the origin(s) allowed to access a browser [`Feature`] via
689/// [`Permission`].
690#[derive(Debug, PartialEq, Clone)]
691pub enum Allow {
692    /// Allow this specific origin. The feature is allowed only for this
693    /// specific origin.
694    ///
695    /// The `user_info`, `path`, and `query` parts of the URI, if any, are
696    /// ignored.
697    Origin(Absolute<'static>),
698    /// Any origin at all.
699    ///
700    /// The feature will be allowed in all browsing contexts regardless of their
701    /// origin.
702    Any,
703    /// The current origin.
704    ///
705    /// The feature will be allowed in the immediately returned document and in
706    /// all nested browsing contexts (iframes) in the same origin.
707    This,
708}
709
710impl Allow {
711    fn rendered(&self) -> Cow<'static, str> {
712        match self {
713            Allow::Origin(uri) => {
714                let mut string = String::with_capacity(32);
715                string.push('"');
716                string.push_str(uri.scheme());
717
718                // This should never fail when rendering a header for `Shield`
719                // due to `panic` in `.allow()`.
720                if let Some(auth) = uri.authority() {
721                    use std::fmt::Write;
722
723                    let _ = write!(string, "://{}", auth.host());
724                    if let Some(port) = auth.port() {
725                        let _ = write!(string, ":{}", port);
726                    }
727                }
728
729                string.push('"');
730                string.into()
731            }
732            Allow::Any => "*".into(),
733            Allow::This => "self".into(),
734        }
735    }
736}
737
738/// A browser feature that can be enabled or blocked via [`Permission`].
739#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
740#[non_exhaustive]
741pub enum Feature {
742    // Standardized.
743
744    /// The "accelerometer" feature.
745    Accelerometer,
746    /// The "ambient-light-sensor" feature.
747    AmbientLightSensor,
748    /// The "autoplay" feature.
749    Autoplay,
750    /// The "battery" feature.
751    Battery,
752    /// The "camera" feature.
753    Camera,
754    /// The "cross-origin-isolated" feature.
755    CrossOriginIsolated,
756    /// The "display-capture" feature.
757    Displaycapture,
758    /// The "document-domain" feature.
759    DocumentDomain,
760    /// The "encrypted-media" feature.
761    EncryptedMedia,
762    /// The "execution-while-not-rendered" feature.
763    ExecutionWhileNotRendered,
764    /// The "execution-while-out-of-viewport" feature.
765    ExecutionWhileOutOfviewport,
766    /// The "fullscreen" feature.
767    Fullscreen,
768    /// The "geolocation" feature.
769    Geolocation,
770    /// The "gyroscope" feature.
771    Gyroscope,
772    /// The "magnetometer" feature.
773    Magnetometer,
774    /// The "microphone" feature.
775    Microphone,
776    /// The "midi" feature.
777    Midi,
778    /// The "navigation-override" feature.
779    NavigationOverride,
780    /// The "payment" feature.
781    Payment,
782    /// The "picture-in-picture" feature.
783    PictureInPicture,
784    /// The "publickey-credentials-get" feature.
785    PublickeyCredentialsGet,
786    /// The "screen-wake-lock" feature.
787    ScreenWakeLock,
788    /// The "sync-xhr" feature.
789    SyncXhr,
790    /// The "usb" feature.
791    Usb,
792    /// The "web-share" feature.
793    WebShare,
794    /// The "xr-spatial-tracking" feature.
795    XrSpatialTracking,
796
797    // Proposed.
798
799    /// The "clipboard-read" feature.
800    ClipboardRead,
801    /// The "clipboard-write" feature.
802    ClipboardWrite,
803    /// The "gamepad" feature.
804    Gamepad,
805    /// The "speaker-selection" feature.
806    SpeakerSelection,
807    /// The "interest-cohort" feature.
808    InterestCohort,
809
810    // Experimental.
811
812    /// The "conversion-measurement" feature.
813    ConversionMeasurement,
814    /// The "focus-without-user-activation" feature.
815    FocusWithoutUserActivation,
816    /// The "hid" feature.
817    Hid,
818    /// The "idle-detection" feature.
819    IdleDetection,
820    /// The "serial" feature.
821    Serial,
822    /// The "sync-script" feature.
823    SyncScript,
824    /// The "trust-token-redemption" feature.
825    TrustTokenRedemption,
826    /// The "vertical-scroll" feature.
827    VerticalScroll,
828}
829
830impl Feature {
831    /// Returns the feature string as it appears in the header.
832    ///
833    /// # Example
834    ///
835    /// ```rust
836    /// use rocket::shield::Feature;
837    ///
838    /// assert_eq!(Feature::Camera.as_str(), "camera");
839    /// assert_eq!(Feature::SyncScript.as_str(), "sync-script");
840    /// ```
841    pub const fn as_str(self) -> &'static str {
842        use Feature::*;
843
844        match self {
845            Accelerometer => "accelerometer",
846            AmbientLightSensor => "ambient-light-sensor",
847            Autoplay => "autoplay",
848            Battery => "battery",
849            Camera => "camera",
850            CrossOriginIsolated => "cross-origin-isolated",
851            Displaycapture => "display-capture",
852            DocumentDomain => "document-domain",
853            EncryptedMedia => "encrypted-media",
854            ExecutionWhileNotRendered => "execution-while-not-rendered",
855            ExecutionWhileOutOfviewport => "execution-while-out-of-viewport",
856            Fullscreen => "fullscreen",
857            Geolocation => "geolocation",
858            Gyroscope => "gyroscope",
859            Magnetometer => "magnetometer",
860            Microphone => "microphone",
861            Midi => "midi",
862            NavigationOverride => "navigation-override",
863            Payment => "payment",
864            PictureInPicture => "picture-in-picture",
865            PublickeyCredentialsGet => "publickey-credentials-get",
866            ScreenWakeLock => "screen-wake-lock",
867            SyncXhr => "sync-xhr",
868            Usb => "usb",
869            WebShare => "web-share",
870            XrSpatialTracking => "xr-spatial-tracking",
871
872            ClipboardRead => "clipboard-read",
873            ClipboardWrite => "clipboard-write",
874            Gamepad => "gamepad",
875            SpeakerSelection => "speaker-selection",
876            InterestCohort => "interest-cohort",
877
878            ConversionMeasurement => "conversion-measurement",
879            FocusWithoutUserActivation => "focus-without-user-activation",
880            Hid => "hid",
881            IdleDetection => "idle-detection",
882            Serial => "serial",
883            SyncScript => "sync-script",
884            TrustTokenRedemption => "trust-token-redemption",
885            VerticalScroll => "vertical-scroll",
886        }
887    }
888}
889
890impl fmt::Display for Feature {
891    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
892        self.as_str().fmt(f)
893    }
894}