Skip to main content

relay_event_schema/protocol/
security_report.rs

1//! Contains definitions for the security report interfaces.
2//!
3//! The security interface is CSP.
4
5use std::borrow::Cow;
6use std::collections::BTreeMap;
7use std::fmt::{self, Write};
8
9use relay_protocol::{Annotated, Empty, FromValue, IntoValue, Object, Value};
10use serde::de::{self, IgnoredAny};
11use serde::{Deserialize, Deserializer, Serialize};
12use url::Url;
13
14use crate::processor::ProcessValue;
15use crate::protocol::{
16    Event, HeaderName, HeaderValue, Headers, LogEntry, PairList, Request, TagEntry, Tags,
17};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub struct InvalidSecurityError;
21
22impl fmt::Display for InvalidSecurityError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "invalid security report")
25    }
26}
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CspDirective {
30    BaseUri,
31    ChildSrc,
32    ConnectSrc,
33    DefaultSrc,
34    FencedFrameSrc,
35    FontSrc,
36    FormAction,
37    FrameAncestors,
38    FrameSrc,
39    ImgSrc,
40    ManifestSrc,
41    MediaSrc,
42    ObjectSrc,
43    PluginTypes,
44    PrefetchSrc,
45    Referrer,
46    ScriptSrc,
47    ScriptSrcAttr,
48    ScriptSrcElem,
49    StyleSrc,
50    StyleSrcElem,
51    StyleSrcAttr,
52    UpgradeInsecureRequests,
53    WorkerSrc,
54    Sandbox,
55    NavigateTo,
56    ReportUri,
57    ReportTo,
58    BlockAllMixedContent,
59    RequireSriFor,
60    RequireTrustedTypesFor,
61    TrustedTypes,
62}
63
64relay_common::derive_fromstr_and_display!(CspDirective, InvalidSecurityError, {
65    CspDirective::BaseUri => "base-uri",
66    CspDirective::ChildSrc => "child-src",
67    CspDirective::ConnectSrc => "connect-src",
68    CspDirective::DefaultSrc => "default-src",
69    CspDirective::FencedFrameSrc => "fenced-frame-src",
70    CspDirective::FontSrc => "font-src",
71    CspDirective::FormAction => "form-action",
72    CspDirective::FrameAncestors => "frame-ancestors",
73    CspDirective::FrameSrc => "frame-src",
74    CspDirective::ImgSrc => "img-src",
75    CspDirective::ManifestSrc => "manifest-src",
76    CspDirective::MediaSrc => "media-src",
77    CspDirective::ObjectSrc => "object-src",
78    CspDirective::PluginTypes => "plugin-types",
79    CspDirective::PrefetchSrc => "prefetch-src",
80    CspDirective::Referrer => "referrer",
81    CspDirective::ScriptSrc => "script-src",
82    CspDirective::ScriptSrcAttr => "script-src-attr",
83    CspDirective::ScriptSrcElem => "script-src-elem",
84    CspDirective::StyleSrc => "style-src",
85    CspDirective::StyleSrcElem => "style-src-elem",
86    CspDirective::StyleSrcAttr => "style-src-attr",
87    CspDirective::UpgradeInsecureRequests => "upgrade-insecure-requests",
88    CspDirective::WorkerSrc => "worker-src",
89    CspDirective::Sandbox => "sandbox",
90    CspDirective::NavigateTo => "navigate-to",
91    CspDirective::ReportUri => "report-uri",
92    CspDirective::ReportTo => "report-to",
93    CspDirective::BlockAllMixedContent => "block-all-mixed-content",
94    CspDirective::RequireSriFor => "require-sri-for",
95    CspDirective::RequireTrustedTypesFor => "require-trusted-types-for",
96    CspDirective::TrustedTypes => "trusted-types",
97});
98
99relay_common::impl_str_serde!(CspDirective, "a csp directive");
100
101fn is_local(uri: &str) -> bool {
102    matches!(uri, "" | "self" | "'self'")
103}
104
105fn schema_uses_host(schema: &str) -> bool {
106    // List of schemas with host (netloc) from Python's urlunsplit:
107    // see <https://github.com/python/cpython/blob/1eac437e8da106a626efffe9fce1cb47dbf5be35/Lib/urllib/parse.py#L51>
108    //
109    // Only modification: "" is set to false, since there is a separate check in the urlunsplit
110    // implementation that omits the leading "//" in that case.
111    matches!(
112        schema,
113        "ftp"
114            | "http"
115            | "gopher"
116            | "nntp"
117            | "telnet"
118            | "imap"
119            | "wais"
120            | "file"
121            | "mms"
122            | "https"
123            | "shttp"
124            | "snews"
125            | "prospero"
126            | "rtsp"
127            | "rtspu"
128            | "rsync"
129            | "svn"
130            | "svn+ssh"
131            | "sftp"
132            | "nfs"
133            | "git"
134            | "git+ssh"
135            | "ws"
136            | "wss"
137    )
138}
139
140/// Mimicks Python's urlunsplit with all its quirks.
141fn unsplit_uri(schema: &str, host: &str) -> String {
142    if !host.is_empty() || schema_uses_host(schema) {
143        format!("{schema}://{host}")
144    } else if !schema.is_empty() {
145        format!("{schema}:{host}")
146    } else {
147        String::new()
148    }
149}
150
151fn normalize_uri(value: &str) -> Cow<'_, str> {
152    if is_local(value) {
153        return Cow::Borrowed("'self'");
154    }
155
156    // A lot of these values get reported as literally just the scheme. So a value like 'data'
157    // or 'blob', which are valid schemes, just not a uri. So we want to normalize it into a
158    // URI.
159
160    if !value.contains(':') {
161        return Cow::Owned(unsplit_uri(value, ""));
162    }
163
164    let url = match Url::parse(value) {
165        Ok(url) => url,
166        Err(_) => return Cow::Borrowed(value),
167    };
168
169    let normalized = match url.scheme() {
170        "http" | "https" => Cow::Borrowed(url.host_str().unwrap_or_default()),
171        scheme => Cow::Owned(unsplit_uri(scheme, url.host_str().unwrap_or_default())),
172    };
173
174    Cow::Owned(match url.port() {
175        Some(port) => format!("{normalized}:{port}"),
176        None => normalized.into_owned(),
177    })
178}
179
180/// Inner (useful) part of a CSP report.
181///
182/// See `Csp` for meaning of fields.
183#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
184struct CspRaw {
185    #[serde(
186        skip_serializing_if = "Option::is_none",
187        alias = "effective-directive",
188        alias = "effectiveDirective"
189    )]
190    effective_directive: Option<String>,
191    #[serde(
192        default = "CspRaw::default_blocked_uri",
193        alias = "blockedURL",
194        alias = "blocked-uri"
195    )]
196    blocked_uri: String,
197    #[serde(
198        skip_serializing_if = "Option::is_none",
199        alias = "documentURL",
200        alias = "document-uri"
201    )]
202    document_uri: Option<String>,
203    #[serde(
204        skip_serializing_if = "Option::is_none",
205        alias = "originalPolicy",
206        alias = "original-policy"
207    )]
208    original_policy: Option<String>,
209    #[serde(skip_serializing_if = "Option::is_none")]
210    referrer: Option<String>,
211    #[serde(
212        default,
213        skip_serializing_if = "Option::is_none",
214        alias = "statusCode",
215        alias = "status-code",
216        deserialize_with = "de_opt_num_or_str"
217    )]
218    status_code: Option<u64>,
219    #[serde(
220        default = "String::new",
221        alias = "violatedDirective",
222        alias = "violated-directive"
223    )]
224    violated_directive: String,
225    #[serde(
226        skip_serializing_if = "Option::is_none",
227        alias = "sourceFile",
228        alias = "source-file"
229    )]
230    source_file: Option<String>,
231    #[serde(
232        default,
233        skip_serializing_if = "Option::is_none",
234        alias = "lineNumber",
235        alias = "line-number",
236        deserialize_with = "de_opt_num_or_str"
237    )]
238    line_number: Option<u64>,
239    #[serde(
240        default,
241        skip_serializing_if = "Option::is_none",
242        alias = "columnNumber",
243        alias = "column-number",
244        deserialize_with = "de_opt_num_or_str"
245    )]
246    column_number: Option<u64>,
247    #[serde(
248        skip_serializing_if = "Option::is_none",
249        alias = "scriptSample",
250        alias = "script-sample",
251        alias = "sample"
252    )]
253    script_sample: Option<String>,
254    #[serde(skip_serializing_if = "Option::is_none")]
255    disposition: Option<String>,
256
257    #[serde(flatten)]
258    other: BTreeMap<String, serde_json::Value>,
259}
260
261fn de_opt_num_or_str<'de, D>(deserializer: D) -> Result<Option<u64>, D::Error>
262where
263    D: Deserializer<'de>,
264{
265    #[derive(Deserialize)]
266    #[serde(untagged)]
267    enum NumOrStr<'a> {
268        Num(u64),
269        Str(Cow<'a, str>),
270    }
271
272    Option::<NumOrStr>::deserialize(deserializer)?
273        .map(|status_code| match status_code {
274            NumOrStr::Num(num) => Ok(num),
275            NumOrStr::Str(s) => s.parse(),
276        })
277        .transpose()
278        .map_err(de::Error::custom)
279}
280
281impl CspRaw {
282    fn default_blocked_uri() -> String {
283        "self".to_owned()
284    }
285
286    fn effective_directive(&self) -> Result<CspDirective, InvalidSecurityError> {
287        // Firefox doesn't send effective-directive, so parse it from
288        // violated-directive but prefer effective-directive when present.
289        // refs: https://bugzil.la/1192684#c8
290
291        if let Some(directive) = &self.effective_directive {
292            // In C2P1 and CSP2, violated_directive and possibly effective_directive might contain
293            // more information than just the CSP-directive.
294            if let Ok(parsed_directive) = directive
295                .split_once(' ')
296                .map_or(directive.as_str(), |s| s.0)
297                .parse()
298            {
299                return Ok(parsed_directive);
300            }
301        }
302
303        if let Ok(parsed_directive) = self
304            .violated_directive
305            .split_once(' ')
306            .map_or(self.violated_directive.as_str(), |s| s.0)
307            .parse()
308        {
309            Ok(parsed_directive)
310        } else {
311            Err(InvalidSecurityError)
312        }
313    }
314
315    fn get_message(&self, effective_directive: CspDirective) -> String {
316        // CSP Level 3 names the blocked script resource with the exact blocked-uri
317        // markers `inline` and `eval`. Other local URIs stay ambiguous:
318        // `'unsafe-inline'` and `'unsafe-eval'` are permissions.
319        if effective_directive == CspDirective::ScriptSrc {
320            match self.blocked_uri.as_str() {
321                "inline" => return "Blocked unsafe inline 'script'".to_owned(),
322                "eval" => return "Blocked unsafe eval() 'script'".to_owned(),
323                _ => {}
324            }
325        }
326
327        if is_local(&self.blocked_uri) {
328            match effective_directive {
329                CspDirective::ChildSrc => "Blocked inline 'child'".to_owned(),
330                CspDirective::ConnectSrc => "Blocked inline 'connect'".to_owned(),
331                CspDirective::FontSrc => "Blocked inline 'font'".to_owned(),
332                CspDirective::ImgSrc => "Blocked inline 'image'".to_owned(),
333                CspDirective::ManifestSrc => "Blocked inline 'manifest'".to_owned(),
334                CspDirective::MediaSrc => "Blocked inline 'media'".to_owned(),
335                CspDirective::ObjectSrc => "Blocked inline 'object'".to_owned(),
336                CspDirective::ScriptSrcAttr => "Blocked unsafe 'script' element".to_owned(),
337                CspDirective::ScriptSrcElem => "Blocked inline script attribute".to_owned(),
338                CspDirective::StyleSrc => "Blocked inline 'style'".to_owned(),
339                CspDirective::StyleSrcElem => "Blocked 'style' or 'link' element".to_owned(),
340                CspDirective::StyleSrcAttr => "Blocked style attribute".to_owned(),
341                CspDirective::ScriptSrc => "Blocked unsafe (eval() or inline) 'script'".to_owned(),
342                directive => format!("Blocked inline '{directive}'"),
343            }
344        } else {
345            let uri = normalize_uri(&self.blocked_uri);
346
347            match effective_directive {
348                CspDirective::ChildSrc => format!("Blocked 'child' from '{uri}'"),
349                CspDirective::ConnectSrc => format!("Blocked 'connect' from '{uri}'"),
350                CspDirective::FontSrc => format!("Blocked 'font' from '{uri}'"),
351                CspDirective::FormAction => format!("Blocked 'form' action to '{uri}'"),
352                CspDirective::ImgSrc => format!("Blocked 'image' from '{uri}'"),
353                CspDirective::ManifestSrc => format!("Blocked 'manifest' from '{uri}'"),
354                CspDirective::MediaSrc => format!("Blocked 'media' from '{uri}'"),
355                CspDirective::ObjectSrc => format!("Blocked 'object' from '{uri}'"),
356                CspDirective::ScriptSrc => format!("Blocked 'script' from '{uri}'"),
357                CspDirective::ScriptSrcAttr => {
358                    format!("Blocked inline script attribute from '{uri}'")
359                }
360                CspDirective::ScriptSrcElem => format!("Blocked 'script' from '{uri}'"),
361                CspDirective::StyleSrc => format!("Blocked 'style' from '{uri}'"),
362                CspDirective::StyleSrcElem => format!("Blocked 'style' from '{uri}'"),
363                CspDirective::StyleSrcAttr => format!("Blocked style attribute from '{uri}'"),
364                directive => format!("Blocked '{directive}' from '{uri}'"),
365            }
366        }
367    }
368
369    fn into_protocol(self, effective_directive: CspDirective) -> Csp {
370        Csp {
371            effective_directive: Annotated::from(effective_directive.to_string()),
372            blocked_uri: Annotated::from(self.blocked_uri),
373            document_uri: Annotated::from(self.document_uri),
374            original_policy: Annotated::from(self.original_policy),
375            referrer: Annotated::from(self.referrer),
376            status_code: Annotated::from(self.status_code),
377            violated_directive: Annotated::from(self.violated_directive),
378            source_file: Annotated::from(self.source_file),
379            line_number: Annotated::from(self.line_number),
380            column_number: Annotated::from(self.column_number),
381            script_sample: Annotated::from(self.script_sample),
382            disposition: Annotated::from(self.disposition),
383            other: self
384                .other
385                .into_iter()
386                .map(|(k, v)| (k, Annotated::from(v)))
387                .collect(),
388        }
389    }
390
391    fn sanitized_blocked_uri(&self) -> String {
392        // HACK: This is 100% to work around Stripe urls that will casually put extremely sensitive
393        // information in querystrings. The real solution is to apply data scrubbing to all tags
394        // generically.
395        //
396        //    if netloc == 'api.stripe.com':
397        //      query = '' fragment = ''
398
399        let mut uri = self.blocked_uri.clone();
400
401        if uri.starts_with("https://api.stripe.com/")
402            && let Some(index) = uri.find(&['#', '?'][..])
403        {
404            uri.truncate(index);
405        }
406
407        uri
408    }
409
410    fn normalize_value<'a>(&self, value: &'a str, document_uri: &str) -> Cow<'a, str> {
411        // > If no scheme is specified, the same scheme as the one used to access the protected
412        // > document is assumed.
413        // Source: https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
414        if let "'none'" | "'self'" | "'unsafe-inline'" | "'unsafe-eval'" = value {
415            return Cow::Borrowed(value);
416        }
417
418        // Normalize a value down to 'self' if it matches the origin of document-uri FireFox
419        // transforms a 'self' value into the spelled out origin, so we want to reverse this and
420        // bring it back.
421        if value.starts_with("data:")
422            || value.starts_with("mediastream:")
423            || value.starts_with("blob:")
424            || value.starts_with("filesystem:")
425            || value.starts_with("http:")
426            || value.starts_with("https:")
427            || value.starts_with("file:")
428        {
429            if document_uri == normalize_uri(value) {
430                return Cow::Borrowed("'self'");
431            }
432
433            // Their rule had an explicit scheme, so let's respect that
434            return Cow::Borrowed(value);
435        }
436
437        // Value doesn't have a scheme, but let's see if their hostnames match at least, if so,
438        // they're the same.
439        if value == document_uri {
440            return Cow::Borrowed("'self'");
441        }
442
443        // Now we need to stitch on a scheme to the value, but let's not stitch on the boring
444        // values.
445        let original_uri = self.document_uri.as_deref().unwrap_or_default();
446        match original_uri.split_once(':').map(|x| x.0) {
447            None | Some("http" | "https") => Cow::Borrowed(value),
448            Some(scheme) => Cow::Owned(unsplit_uri(scheme, value)),
449        }
450    }
451
452    fn get_culprit(&self) -> String {
453        if self.violated_directive.is_empty() {
454            return String::new();
455        }
456
457        let mut bits = self.violated_directive.split_ascii_whitespace();
458        let mut culprit = bits.next().unwrap_or_default().to_owned();
459
460        let document_uri = self.document_uri.as_deref().unwrap_or("");
461        let normalized_uri = normalize_uri(document_uri);
462
463        // Conservative limit assuming all chars are 4 bytes. Since the culprit is trimmed to
464        // `Event::MAX_CULPRIT_CHARS` during normalization anyway, no point in materializing more.
465        let limit = Event::MAX_CULPRIT_CHARS * 4;
466
467        for bit in bits {
468            if culprit.len() >= limit {
469                break;
470            }
471            write!(culprit, " {}", self.normalize_value(bit, &normalized_uri)).ok();
472        }
473
474        culprit
475    }
476
477    fn get_tags(&self, effective_directive: CspDirective) -> Tags {
478        let mut tags = vec![
479            Annotated::new(TagEntry(
480                Annotated::new("effective-directive".to_owned()),
481                Annotated::new(effective_directive.to_string()),
482            )),
483            Annotated::new(TagEntry(
484                Annotated::new("blocked-uri".to_owned()),
485                Annotated::new(self.sanitized_blocked_uri()),
486            )),
487        ];
488
489        if let Ok(url) = Url::parse(&self.blocked_uri)
490            && let ("http" | "https", Some(host)) = (url.scheme(), url.host_str())
491        {
492            tags.push(Annotated::new(TagEntry(
493                Annotated::new("blocked-host".to_owned()),
494                Annotated::new(host.to_owned()),
495            )));
496        }
497
498        Tags(PairList::from(tags))
499    }
500
501    fn get_request(&self) -> Request {
502        let headers = match self.referrer {
503            Some(ref referrer) if !referrer.is_empty() => {
504                Annotated::new(Headers(PairList(vec![Annotated::new((
505                    Annotated::new(HeaderName::new("Referer")),
506                    Annotated::new(HeaderValue::new(referrer.clone())),
507                ))])))
508            }
509            Some(_) | None => Annotated::empty(),
510        };
511
512        Request {
513            url: Annotated::from(self.document_uri.clone()),
514            headers,
515            ..Request::default()
516        }
517    }
518}
519
520#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
521#[serde(untagged)]
522enum CspVariant {
523    Csp {
524        #[serde(rename = "csp-report")]
525        csp_report: CspRaw,
526    },
527    /// Defines CSP report sent through the [Reporting API](https://developer.mozilla.org/en-US/docs/Web/API/Reporting_API).
528    ///
529    /// This contains the [body](https://developer.mozilla.org/en-US/docs/Web/API/CSPViolationReportBody)
530    /// with actual report. We currently ignore the additional fields.
531    /// Reporting API has [slightly different format](https://csplite.com/csp66/#sample-violation-report) for the CSP report body,
532    /// but the biggest difference that browser sends the CSP reports in batches.
533    CspViolation { body: CspRaw },
534}
535
536/// The type of the CSP report which comes through the Reporting API.
537#[derive(Clone, Debug, PartialEq, Deserialize)]
538#[serde(rename_all = "kebab-case")]
539enum CspViolationType {
540    CspViolation,
541    #[serde(other)]
542    Other,
543}
544
545/// Models the content of a CSP report.
546///
547/// Note this models the older CSP reports (report-uri policy directive).
548/// The new CSP reports (using report-to policy directive) are different.
549///
550/// NOTE: This is the structure used inside the Event (serialization is based on Annotated
551/// infrastructure). We also use a version of this structure to deserialize from raw JSON
552/// via serde.
553///
554///
555/// See <https://www.w3.org/TR/CSP3/>
556#[derive(Clone, Debug, Default, PartialEq, Empty, FromValue, IntoValue, ProcessValue)]
557pub struct Csp {
558    /// The directive whose enforcement caused the violation.
559    #[metastructure(pii = "true")]
560    pub effective_directive: Annotated<String>,
561    /// The URI of the resource that was blocked from loading by the Content Security Policy.
562    #[metastructure(pii = "true")]
563    pub blocked_uri: Annotated<String>,
564    /// The URI of the document in which the violation occurred.
565    #[metastructure(pii = "true")]
566    pub document_uri: Annotated<String>,
567    /// The original policy as specified by the Content-Security-Policy HTTP header.
568    pub original_policy: Annotated<String>,
569    /// The referrer of the document in which the violation occurred.
570    #[metastructure(pii = "true")]
571    pub referrer: Annotated<String>,
572    /// The HTTP status code of the resource on which the global object was instantiated.
573    pub status_code: Annotated<u64>,
574    /// The name of the policy section that was violated.
575    pub violated_directive: Annotated<String>,
576    /// The URL of the resource where the violation occurred.
577    #[metastructure(pii = "maybe")]
578    pub source_file: Annotated<String>,
579    /// The line number in source-file on which the violation occurred.
580    pub line_number: Annotated<u64>,
581    /// The column number in source-file on which the violation occurred.
582    pub column_number: Annotated<u64>,
583    /// The first 40 characters of the inline script, event handler, or style that caused the
584    /// violation.
585    #[metastructure(pii = "maybe")]
586    pub script_sample: Annotated<String>,
587    /// Policy disposition (enforce or report).
588    pub disposition: Annotated<String>,
589    /// Additional arbitrary fields for forwards compatibility.
590    #[metastructure(pii = "true", additional_properties)]
591    pub other: Object<Value>,
592}
593
594impl Csp {
595    pub fn apply_to_event(data: &[u8], event: &mut Event) -> Result<(), serde_json::Error> {
596        let variant = serde_json::from_slice::<CspVariant>(data)?;
597        match variant {
598            CspVariant::Csp { csp_report } => Csp::extract_report(event, csp_report)?,
599            CspVariant::CspViolation { body } => Csp::extract_report(event, body)?,
600        }
601
602        Ok(())
603    }
604
605    fn extract_report(event: &mut Event, raw_csp: CspRaw) -> Result<(), serde_json::Error> {
606        let effective_directive = raw_csp
607            .effective_directive()
608            .map_err(serde::de::Error::custom)?;
609
610        event.logentry = Annotated::new(LogEntry::from(raw_csp.get_message(effective_directive)));
611        event.culprit = Annotated::new(raw_csp.get_culprit());
612        event.tags = Annotated::new(raw_csp.get_tags(effective_directive));
613        event.request = Annotated::new(raw_csp.get_request());
614        event.csp = Annotated::new(raw_csp.into_protocol(effective_directive));
615
616        Ok(())
617    }
618}
619
620#[derive(Clone, Debug, PartialEq, Eq)]
621pub enum SecurityReportType {
622    Csp,
623    Unsupported,
624}
625
626impl SecurityReportType {
627    /// Infers the type of a security report from its payload.
628    ///
629    /// This looks into the JSON payload and tries to infer the type from keys. If no report
630    /// matches, an error is returned.
631    pub fn from_json(data: &[u8]) -> Result<Option<Self>, serde_json::Error> {
632        #[derive(Deserialize)]
633        #[serde(rename_all = "kebab-case")]
634        struct SecurityReport {
635            #[serde(rename = "type")]
636            ty: Option<CspViolationType>,
637            csp_report: Option<IgnoredAny>,
638        }
639
640        let helper: SecurityReport = serde_json::from_slice(data)?;
641
642        Ok(if helper.csp_report.is_some() {
643            Some(SecurityReportType::Csp)
644        } else if let Some(CspViolationType::CspViolation) = helper.ty {
645            Some(SecurityReportType::Csp)
646        } else if let Some(CspViolationType::Other) = helper.ty {
647            Some(SecurityReportType::Unsupported)
648        } else {
649            None
650        })
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657    use relay_protocol::assert_annotated_snapshot;
658
659    #[test]
660    fn test_unsplit_uri() {
661        assert_eq!(unsplit_uri("", ""), "");
662        assert_eq!(unsplit_uri("data", ""), "data:");
663        assert_eq!(unsplit_uri("data", "foo"), "data://foo");
664        assert_eq!(unsplit_uri("http", ""), "http://");
665        assert_eq!(unsplit_uri("http", "foo"), "http://foo");
666    }
667
668    #[test]
669    fn test_normalize_uri() {
670        // Special handling for self URIs
671        assert_eq!(normalize_uri(""), "'self'");
672        assert_eq!(normalize_uri("self"), "'self'");
673
674        // Special handling for schema-only URIs
675        assert_eq!(normalize_uri("data"), "data:");
676        assert_eq!(normalize_uri("http"), "http://");
677
678        // URIs without port
679        assert_eq!(normalize_uri("http://notlocalhost/"), "notlocalhost");
680        assert_eq!(normalize_uri("https://notlocalhost/"), "notlocalhost");
681        assert_eq!(normalize_uri("data://notlocalhost/"), "data://notlocalhost");
682        assert_eq!(normalize_uri("http://notlocalhost/lol.css"), "notlocalhost");
683
684        // URIs with port
685        assert_eq!(
686            normalize_uri("http://notlocalhost:8000/"),
687            "notlocalhost:8000"
688        );
689        assert_eq!(
690            normalize_uri("http://notlocalhost:8000/lol.css"),
691            "notlocalhost:8000"
692        );
693
694        // Invalid URIs
695        assert_eq!(normalize_uri("xyz://notlocalhost/"), "xyz://notlocalhost");
696    }
697
698    #[test]
699    fn test_csp_basic() {
700        let json = r#"{
701            "csp-report": {
702                "document-uri": "http://example.com",
703                "violated-directive": "style-src cdn.example.com",
704                "blocked-uri": "http://example.com/lol.css",
705                "effective-directive": "style-src",
706                "status-code": "200"
707            }
708        }"#;
709
710        let mut event = Event::default();
711        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
712
713        assert_annotated_snapshot!(Annotated::new(event), @r###"
714        {
715          "culprit": "style-src cdn.example.com",
716          "logentry": {
717            "formatted": "Blocked 'style' from 'example.com'"
718          },
719          "request": {
720            "url": "http://example.com"
721          },
722          "tags": [
723            [
724              "effective-directive",
725              "style-src"
726            ],
727            [
728              "blocked-uri",
729              "http://example.com/lol.css"
730            ],
731            [
732              "blocked-host",
733              "example.com"
734            ]
735          ],
736          "csp": {
737            "effective_directive": "style-src",
738            "blocked_uri": "http://example.com/lol.css",
739            "document_uri": "http://example.com",
740            "status_code": 200,
741            "violated_directive": "style-src cdn.example.com"
742          }
743        }
744        "###);
745    }
746
747    #[test]
748    fn test_csp_coerce_blocked_uri_if_missing() {
749        let json = r#"{
750            "csp-report": {
751                "document-uri": "http://example.com",
752                "effective-directive": "script-src"
753            }
754        }"#;
755
756        let mut event = Event::default();
757        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
758
759        assert_annotated_snapshot!(Annotated::new(event), @r###"
760        {
761          "culprit": "",
762          "logentry": {
763            "formatted": "Blocked unsafe (eval() or inline) 'script'"
764          },
765          "request": {
766            "url": "http://example.com"
767          },
768          "tags": [
769            [
770              "effective-directive",
771              "script-src"
772            ],
773            [
774              "blocked-uri",
775              "self"
776            ]
777          ],
778          "csp": {
779            "effective_directive": "script-src",
780            "blocked_uri": "self",
781            "document_uri": "http://example.com",
782            "violated_directive": ""
783          }
784        }
785        "###);
786    }
787
788    #[test]
789    fn test_csp_msdn() {
790        let json = r#"{
791            "csp-report": {
792                "document-uri": "https://example.com/foo/bar",
793                "referrer": "https://www.google.com/",
794                "violated-directive": "default-src self",
795                "original-policy": "default-src self; report-uri /csp-hotline.php",
796                "blocked-uri": "http://evilhackerscripts.com"
797            }
798        }"#;
799
800        let mut event = Event::default();
801        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
802
803        assert_annotated_snapshot!(Annotated::new(event), @r###"
804        {
805          "culprit": "default-src self",
806          "logentry": {
807            "formatted": "Blocked 'default-src' from 'evilhackerscripts.com'"
808          },
809          "request": {
810            "url": "https://example.com/foo/bar",
811            "headers": [
812              [
813                "Referer",
814                "https://www.google.com/"
815              ]
816            ]
817          },
818          "tags": [
819            [
820              "effective-directive",
821              "default-src"
822            ],
823            [
824              "blocked-uri",
825              "http://evilhackerscripts.com"
826            ],
827            [
828              "blocked-host",
829              "evilhackerscripts.com"
830            ]
831          ],
832          "csp": {
833            "effective_directive": "default-src",
834            "blocked_uri": "http://evilhackerscripts.com",
835            "document_uri": "https://example.com/foo/bar",
836            "original_policy": "default-src self; report-uri /csp-hotline.php",
837            "referrer": "https://www.google.com/",
838            "violated_directive": "default-src self"
839          }
840        }
841        "###);
842    }
843
844    #[test]
845    fn test_csp_real() {
846        let json = r#"{
847            "csp-report": {
848                "document-uri": "https://sentry.io/sentry/csp/issues/88513416/",
849                "referrer": "https://sentry.io/sentry/sentry/releases/7329107476ff14cfa19cf013acd8ce47781bb93a/",
850                "violated-directive": "script-src",
851                "effective-directive": "script-src",
852                "original-policy": "default-src *; script-src 'make_csp_snapshot' 'unsafe-eval' 'unsafe-inline' e90d271df3e973c7.global.ssl.fastly.net cdn.ravenjs.com assets.zendesk.com ajax.googleapis.com ssl.google-analytics.com www.googleadservices.com analytics.twitter.com platform.twitter.com *.pingdom.net js.stripe.com api.stripe.com statuspage-production.s3.amazonaws.com s3.amazonaws.com *.google.com www.gstatic.com aui-cdn.atlassian.com *.atlassian.net *.jira.com *.zopim.com; font-src * data:; connect-src * wss://*.zopim.com; style-src 'make_csp_snapshot' 'unsafe-inline' e90d271df3e973c7.global.ssl.fastly.net s3.amazonaws.com aui-cdn.atlassian.com fonts.googleapis.com; img-src * data: blob:; report-uri https://sentry.io/api/54785/csp-report/?sentry_key=f724a8a027db45f5b21507e7142ff78e&sentry_release=39662eb9734f68e56b7f202260bb706be2f4cee7",
853                "disposition": "enforce",
854                "blocked-uri": "http://baddomain.com/test.js?_=1515535030116",
855                "line-number": 24,
856                "column-number": 66270,
857                "source-file": "https://e90d271df3e973c7.global.ssl.fastly.net/_static/f0c7c026a4b2a3d2b287ae2d012c9924/sentry/dist/vendor.js",
858                "status-code": 0,
859                "script-sample": ""
860            }
861        }"#;
862
863        let mut event = Event::default();
864        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
865
866        assert_annotated_snapshot!(Annotated::new(event), @r###"
867        {
868          "culprit": "script-src",
869          "logentry": {
870            "formatted": "Blocked 'script' from 'baddomain.com'"
871          },
872          "request": {
873            "url": "https://sentry.io/sentry/csp/issues/88513416/",
874            "headers": [
875              [
876                "Referer",
877                "https://sentry.io/sentry/sentry/releases/7329107476ff14cfa19cf013acd8ce47781bb93a/"
878              ]
879            ]
880          },
881          "tags": [
882            [
883              "effective-directive",
884              "script-src"
885            ],
886            [
887              "blocked-uri",
888              "http://baddomain.com/test.js?_=1515535030116"
889            ],
890            [
891              "blocked-host",
892              "baddomain.com"
893            ]
894          ],
895          "csp": {
896            "effective_directive": "script-src",
897            "blocked_uri": "http://baddomain.com/test.js?_=1515535030116",
898            "document_uri": "https://sentry.io/sentry/csp/issues/88513416/",
899            "original_policy": "default-src *; script-src 'make_csp_snapshot' 'unsafe-eval' 'unsafe-inline' e90d271df3e973c7.global.ssl.fastly.net cdn.ravenjs.com assets.zendesk.com ajax.googleapis.com ssl.google-analytics.com www.googleadservices.com analytics.twitter.com platform.twitter.com *.pingdom.net js.stripe.com api.stripe.com statuspage-production.s3.amazonaws.com s3.amazonaws.com *.google.com www.gstatic.com aui-cdn.atlassian.com *.atlassian.net *.jira.com *.zopim.com; font-src * data:; connect-src * wss://*.zopim.com; style-src 'make_csp_snapshot' 'unsafe-inline' e90d271df3e973c7.global.ssl.fastly.net s3.amazonaws.com aui-cdn.atlassian.com fonts.googleapis.com; img-src * data: blob:; report-uri https://sentry.io/api/54785/csp-report/?sentry_key=f724a8a027db45f5b21507e7142ff78e&sentry_release=39662eb9734f68e56b7f202260bb706be2f4cee7",
900            "referrer": "https://sentry.io/sentry/sentry/releases/7329107476ff14cfa19cf013acd8ce47781bb93a/",
901            "status_code": 0,
902            "violated_directive": "script-src",
903            "source_file": "https://e90d271df3e973c7.global.ssl.fastly.net/_static/f0c7c026a4b2a3d2b287ae2d012c9924/sentry/dist/vendor.js",
904            "line_number": 24,
905            "column_number": 66270,
906            "script_sample": "",
907            "disposition": "enforce"
908          }
909        }
910        "###);
911    }
912
913    #[test]
914    fn test_csp_sample_alias() {
915        let json = r#"{
916            "csp-report": {
917                "document-uri": "http://example.com/foo",
918                "violated-directive": "style-src http://cdn.example.com",
919                "effective-directive": "style-src",
920                "sample": "console.log(\"lo\")"
921            }
922    }"#;
923
924        let mut event = Event::default();
925        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
926        assert_annotated_snapshot!(event.csp, @r#"
927        {
928          "effective_directive": "style-src",
929          "blocked_uri": "self",
930          "document_uri": "http://example.com/foo",
931          "violated_directive": "style-src http://cdn.example.com",
932          "script_sample": "console.log(\"lo\")"
933        }
934        "#);
935    }
936
937    #[test]
938    fn test_csp_culprit_0() {
939        let json = r#"{
940            "csp-report": {
941                "document-uri": "http://example.com/foo",
942                "violated-directive": "style-src http://cdn.example.com",
943                "effective-directive": "style-src"
944            }
945        }"#;
946
947        let mut event = Event::default();
948        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
949        insta::assert_debug_snapshot!(event.culprit, @r###""style-src http://cdn.example.com""###);
950    }
951
952    #[test]
953    fn test_csp_culprit_1() {
954        let json = r#"{
955            "csp-report": {
956                "document-uri": "http://example.com/foo",
957                "violated-directive": "style-src cdn.example.com",
958                "effective-directive": "style-src"
959            }
960        }"#;
961
962        let mut event = Event::default();
963        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
964        insta::assert_debug_snapshot!(event.culprit, @r###""style-src cdn.example.com""###);
965    }
966
967    #[test]
968    fn test_csp_culprit_2() {
969        let json = r#"{
970            "csp-report": {
971                "document-uri": "https://example.com/foo",
972                "violated-directive": "style-src cdn.example.com",
973                "effective-directive": "style-src"
974            }
975        }"#;
976
977        let mut event = Event::default();
978        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
979        insta::assert_debug_snapshot!(event.culprit, @r###""style-src cdn.example.com""###);
980    }
981
982    #[test]
983    fn test_csp_culprit_3() {
984        let json = r#"{
985            "csp-report": {
986                "document-uri": "http://example.com/foo",
987                "violated-directive": "style-src https://cdn.example.com",
988                "effective-directive": "style-src"
989            }
990        }"#;
991
992        let mut event = Event::default();
993        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
994        insta::assert_debug_snapshot!(event.culprit, @r###""style-src https://cdn.example.com""###);
995    }
996
997    #[test]
998    fn test_csp_culprit_4() {
999        let json = r#"{
1000            "csp-report": {
1001                "document-uri": "http://example.com/foo",
1002                "violated-directive": "style-src http://example.com",
1003                "effective-directive": "style-src"
1004            }
1005        }"#;
1006
1007        let mut event = Event::default();
1008        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1009        insta::assert_debug_snapshot!(event.culprit, @r###""style-src 'self'""###);
1010    }
1011
1012    #[test]
1013    fn test_csp_culprit_5() {
1014        let json = r#"{
1015            "csp-report": {
1016                "document-uri": "http://example.com/foo",
1017                "violated-directive": "style-src http://example2.com example.com",
1018                "effective-directive": "style-src"
1019            }
1020        }"#;
1021
1022        let mut event = Event::default();
1023        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1024        insta::assert_debug_snapshot!(event.culprit, @r###""style-src http://example2.com 'self'""###);
1025    }
1026
1027    #[test]
1028    fn test_csp_culprit_uri_without_scheme() {
1029        // Not sure if this is a real-world example, but let's cover it anyway
1030        let json = r#"{
1031            "csp-report": {
1032                "document-uri": "example.com",
1033                "violated-directive": "style-src example2.com"
1034            }
1035        }"#;
1036
1037        let mut event = Event::default();
1038        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1039        insta::assert_debug_snapshot!(event.culprit, @r###""style-src example2.com""###);
1040    }
1041
1042    #[test]
1043    fn test_csp_culprit_limit() {
1044        // Since a long non-http scheme is stitched onto every source expression this can cause
1045        // culprit to grow drastically.
1046        let scheme = "z".repeat(1000);
1047        let json = format!(
1048            r#"{{
1049            "csp-report": {{
1050                "document-uri": "{scheme}://example.com/",
1051                "violated-directive": "script-src{}"
1052            }}
1053        }}"#,
1054            " a".repeat(10)
1055        );
1056
1057        let mut event = Event::default();
1058        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1059        // The scheme is so large that the first expansion already exceeds the limit.
1060        assert_eq!(
1061            event.culprit.as_str(),
1062            Some(format!("script-src {scheme}://a").as_str())
1063        );
1064    }
1065
1066    #[test]
1067    fn test_csp_tags_stripe() {
1068        // This is a regression test for potential PII in stripe URLs. PII stripping used to skip
1069        // report interfaces, which is why there is special handling.
1070
1071        let json = r#"{
1072            "csp-report": {
1073                "document-uri": "https://example.com",
1074                "blocked-uri": "https://api.stripe.com/v1/tokens?card[number]=xxx",
1075                "effective-directive": "script-src"
1076            }
1077        }"#;
1078
1079        let mut event = Event::default();
1080        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1081        insta::assert_debug_snapshot!(event.tags, @r###"
1082        Tags(
1083            PairList(
1084                [
1085                    TagEntry(
1086                        "effective-directive",
1087                        "script-src",
1088                    ),
1089                    TagEntry(
1090                        "blocked-uri",
1091                        "https://api.stripe.com/v1/tokens",
1092                    ),
1093                    TagEntry(
1094                        "blocked-host",
1095                        "api.stripe.com",
1096                    ),
1097                ],
1098            ),
1099        )
1100        "###);
1101    }
1102
1103    #[test]
1104    fn test_csp_get_message_0() {
1105        let json = r#"{
1106            "csp-report": {
1107                "document-uri": "http://example.com/foo",
1108                "effective-directive": "img-src",
1109                "blocked-uri": "http://google.com/foo"
1110            }
1111        }"#;
1112
1113        let mut event = Event::default();
1114        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1115        let message = &event.logentry.value().unwrap().formatted;
1116        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'image' from 'google.com'""###);
1117    }
1118
1119    #[test]
1120    fn test_csp_get_message_1() {
1121        let json = r#"{
1122            "csp-report": {
1123                "document-uri": "http://example.com/foo",
1124                "effective-directive": "style-src",
1125                "blocked-uri": ""
1126            }
1127        }"#;
1128
1129        let mut event = Event::default();
1130        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1131        let message = &event.logentry.value().unwrap().formatted;
1132        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked inline 'style'""###);
1133    }
1134
1135    #[test]
1136    fn test_csp_get_message_2() {
1137        // An empty blocked URI does not identify the blocked operation.
1138        // `'unsafe-inline'` in the violated directive is only a permission.
1139        let json = r#"{
1140            "csp-report": {
1141                "document-uri": "http://example.com/foo",
1142                "effective-directive": "script-src",
1143                "blocked-uri": "",
1144                "violated-directive": "script-src 'unsafe-inline'"
1145            }
1146        }"#;
1147
1148        let mut event = Event::default();
1149        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1150        let message = &event.logentry.value().unwrap().formatted;
1151        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked unsafe (eval() or inline) 'script'""###);
1152    }
1153
1154    #[test]
1155    fn test_csp_get_message_3() {
1156        // An empty blocked URI does not identify the blocked operation.
1157        // `'unsafe-eval'` in the violated directive is only a permission.
1158        let json = r#"{
1159            "csp-report": {
1160                "document-uri": "http://example.com/foo",
1161                "effective-directive": "script-src",
1162                "blocked-uri": "",
1163                "violated-directive": "script-src 'unsafe-eval'"
1164            }
1165        }"#;
1166
1167        let mut event = Event::default();
1168        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1169        let message = &event.logentry.value().unwrap().formatted;
1170        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked unsafe (eval() or inline) 'script'""###);
1171    }
1172
1173    #[test]
1174    fn test_csp_get_message_4() {
1175        let json = r#"{
1176            "csp-report": {
1177                "document-uri": "http://example.com/foo",
1178                "effective-directive": "script-src",
1179                "blocked-uri": "",
1180                "violated-directive": "script-src example.com"
1181            }
1182        }"#;
1183
1184        let mut event = Event::default();
1185        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1186        let message = &event.logentry.value().unwrap().formatted;
1187        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked unsafe (eval() or inline) 'script'""###);
1188    }
1189
1190    #[test]
1191    fn test_csp_get_message_5() {
1192        let json = r#"{
1193            "csp-report": {
1194                "document-uri": "http://example.com/foo",
1195                "effective-directive": "script-src",
1196                "blocked-uri": "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"
1197            }
1198        }"#;
1199
1200        let mut event = Event::default();
1201        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1202        let message = &event.logentry.value().unwrap().formatted;
1203        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'script' from 'data:'""###);
1204    }
1205
1206    #[test]
1207    fn test_csp_get_message_6() {
1208        let json = r#"{
1209            "csp-report": {
1210                "document-uri": "http://example.com/foo",
1211                "effective-directive": "script-src",
1212                "blocked-uri": "data"
1213            }
1214        }"#;
1215
1216        let mut event = Event::default();
1217        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1218        let message = &event.logentry.value().unwrap().formatted;
1219        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'script' from 'data:'""###);
1220    }
1221
1222    #[test]
1223    fn test_csp_get_message_7() {
1224        let json = r#"{
1225            "csp-report": {
1226                "document-uri": "http://example.com/foo",
1227                "effective-directive": "style-src-elem",
1228                "blocked-uri": "http://fonts.google.com/foo"
1229            }
1230        }"#;
1231
1232        let mut event = Event::default();
1233        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1234        let message = &event.logentry.value().unwrap().formatted;
1235        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'style' from 'fonts.google.com'""###);
1236    }
1237
1238    #[test]
1239    fn test_csp_get_message_8() {
1240        let json = r#"{
1241            "csp-report": {
1242                "document-uri": "http://example.com/foo",
1243                "effective-directive": "script-src-elem",
1244                "blocked-uri": "http://cdn.ajaxapis.com/foo"
1245            }
1246        }"#;
1247
1248        let mut event = Event::default();
1249        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1250        let message = &event.logentry.value().unwrap().formatted;
1251        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'script' from 'cdn.ajaxapis.com'""###);
1252    }
1253
1254    #[test]
1255    fn test_csp_get_message_9() {
1256        let json = r#"{
1257            "csp-report": {
1258                "document-uri": "http://notlocalhost:8000/",
1259                "effective-directive": "style-src",
1260                "blocked-uri": "http://notlocalhost:8000/lol.css"
1261            }
1262        }"#;
1263
1264        let mut event = Event::default();
1265        Csp::apply_to_event(json.as_bytes(), &mut event).unwrap();
1266        let message = &event.logentry.value().unwrap().formatted;
1267        insta::assert_debug_snapshot!(message.as_str().unwrap(), @r###""Blocked 'style' from 'notlocalhost:8000'""###);
1268    }
1269
1270    const INLINE_MSG: &str = "Blocked unsafe inline 'script'";
1271    const EVAL_MSG: &str = "Blocked unsafe eval() 'script'";
1272    const AMBIGUOUS_MSG: &str = "Blocked unsafe (eval() or inline) 'script'";
1273
1274    /// Violated-directive values that name neither permission, either permission, or both.
1275    const SCRIPT_SRC_POLICIES: [Option<&str>; 5] = [
1276        None,
1277        Some("script-src"),
1278        Some("script-src 'unsafe-inline'"),
1279        Some("script-src 'unsafe-eval'"),
1280        Some("script-src 'unsafe-inline' 'unsafe-eval'"),
1281    ];
1282
1283    #[derive(Clone, Copy, Debug)]
1284    enum CspPayloadFormat {
1285        /// Legacy `report-uri` payload with hyphenated keys.
1286        Legacy,
1287        /// Reporting API `csp-violation` payload with camelCase body fields.
1288        ReportingApi,
1289    }
1290
1291    fn apply_csp_payload(
1292        format: CspPayloadFormat,
1293        effective_directive: Option<&str>,
1294        violated_directive: Option<&str>,
1295        blocked_uri: Option<&str>,
1296    ) -> Result<Event, serde_json::Error> {
1297        let (effective_key, violated_key, blocked_key, document_key) = match format {
1298            CspPayloadFormat::Legacy => (
1299                "effective-directive",
1300                "violated-directive",
1301                "blocked-uri",
1302                "document-uri",
1303            ),
1304            CspPayloadFormat::ReportingApi => (
1305                "effectiveDirective",
1306                "violatedDirective",
1307                "blockedURL",
1308                "documentURL",
1309            ),
1310        };
1311
1312        let mut report = serde_json::Map::new();
1313        {
1314            let mut insert = |key: &str, value: &str| {
1315                report.insert(key.to_owned(), serde_json::Value::String(value.to_owned()));
1316            };
1317            insert(document_key, "http://example.com/foo");
1318            if let Some(directive) = effective_directive {
1319                insert(effective_key, directive);
1320            }
1321            if let Some(directive) = violated_directive {
1322                insert(violated_key, directive);
1323            }
1324            if let Some(uri) = blocked_uri {
1325                insert(blocked_key, uri);
1326            }
1327        }
1328
1329        let payload = match format {
1330            CspPayloadFormat::Legacy => serde_json::json!({ "csp-report": report }),
1331            CspPayloadFormat::ReportingApi => serde_json::json!({
1332                "type": "csp-violation",
1333                "age": 0,
1334                "url": "http://example.com/foo",
1335                "user_agent": "Mozilla/5.0",
1336                "body": report
1337            }),
1338        };
1339
1340        let mut event = Event::default();
1341        Csp::apply_to_event(&serde_json::to_vec(&payload)?, &mut event)?;
1342        Ok(event)
1343    }
1344
1345    #[track_caller]
1346    fn assert_csp_outcome(
1347        event: &Event,
1348        message: &str,
1349        blocked_uri: &str,
1350        directive: &str,
1351        context: &str,
1352    ) {
1353        let csp = event.csp.value();
1354        assert_eq!(
1355            event
1356                .logentry
1357                .value()
1358                .and_then(|entry| entry.formatted.as_str()),
1359            Some(message),
1360            "{context}"
1361        );
1362        assert_eq!(
1363            csp.and_then(|csp| csp.blocked_uri.as_str()),
1364            Some(blocked_uri),
1365            "{context}"
1366        );
1367        assert_eq!(
1368            csp.and_then(|csp| csp.effective_directive.as_str()),
1369            Some(directive),
1370            "{context}"
1371        );
1372    }
1373
1374    #[test]
1375    fn test_csp_script_src_blocked_uri_marker_selects_message() {
1376        let markers = [("inline", INLINE_MSG), ("eval", EVAL_MSG)];
1377
1378        for report_format in [CspPayloadFormat::Legacy, CspPayloadFormat::ReportingApi] {
1379            for (blocked_uri, message) in markers {
1380                for violated in SCRIPT_SRC_POLICIES {
1381                    let context = format!(
1382                        "format={report_format:?} blocked_uri={blocked_uri:?} violated={violated:?}"
1383                    );
1384                    let event = apply_csp_payload(
1385                        report_format,
1386                        Some("script-src"),
1387                        violated,
1388                        Some(blocked_uri),
1389                    )
1390                    .unwrap_or_else(|error| panic!("{context}: {error}"));
1391                    assert_csp_outcome(&event, message, blocked_uri, "script-src", &context);
1392                }
1393            }
1394        }
1395    }
1396
1397    #[test]
1398    fn test_csp_script_src_local_blocked_uri_stays_ambiguous() {
1399        // Explicit values, plus `None` for an omitted blocked URI. Omission defaults to "self".
1400        let blocked_uris = [Some(""), Some("self"), Some("'self'"), None];
1401
1402        for report_format in [CspPayloadFormat::Legacy, CspPayloadFormat::ReportingApi] {
1403            for blocked_uri in blocked_uris {
1404                for violated in SCRIPT_SRC_POLICIES {
1405                    let context = format!(
1406                        "format={report_format:?} blocked_uri={blocked_uri:?} violated={violated:?}"
1407                    );
1408                    let event =
1409                        apply_csp_payload(report_format, Some("script-src"), violated, blocked_uri)
1410                            .unwrap_or_else(|error| panic!("{context}: {error}"));
1411                    assert_csp_outcome(
1412                        &event,
1413                        AMBIGUOUS_MSG,
1414                        blocked_uri.unwrap_or("self"),
1415                        "script-src",
1416                        &context,
1417                    );
1418                }
1419            }
1420        }
1421    }
1422
1423    #[test]
1424    fn test_csp_apply_to_event_script_src_fallback_and_other_directives() {
1425        struct Case {
1426            effective: Option<&'static str>,
1427            violated: Option<&'static str>,
1428            blocked: Option<&'static str>,
1429            message: &'static str,
1430            raw_blocked_uri: &'static str,
1431            directive: &'static str,
1432        }
1433
1434        let cases = [
1435            // Effective directive omitted: violated-directive selects script-src, and the
1436            // blocked-uri marker still wins over the opposite permission keyword.
1437            Case {
1438                effective: None,
1439                violated: Some("script-src 'unsafe-eval'"),
1440                blocked: Some("inline"),
1441                message: INLINE_MSG,
1442                raw_blocked_uri: "inline",
1443                directive: "script-src",
1444            },
1445            Case {
1446                effective: None,
1447                violated: Some("script-src 'unsafe-inline'"),
1448                blocked: Some("eval"),
1449                message: EVAL_MSG,
1450                raw_blocked_uri: "eval",
1451                directive: "script-src",
1452            },
1453            Case {
1454                effective: None,
1455                violated: Some("script-src example.com"),
1456                blocked: Some(""),
1457                message: AMBIGUOUS_MSG,
1458                raw_blocked_uri: "",
1459                directive: "script-src",
1460            },
1461            Case {
1462                effective: None,
1463                violated: Some("script-src 'unsafe-inline' 'unsafe-eval'"),
1464                blocked: None,
1465                message: AMBIGUOUS_MSG,
1466                raw_blocked_uri: "self",
1467                directive: "script-src",
1468            },
1469            Case {
1470                effective: None,
1471                violated: Some("script-src 'unsafe-eval'"),
1472                blocked: Some("'self'"),
1473                message: AMBIGUOUS_MSG,
1474                raw_blocked_uri: "'self'",
1475                directive: "script-src",
1476            },
1477            // Unparseable effective-directive falls back to violated-directive.
1478            Case {
1479                effective: Some("not-a-directive"),
1480                violated: Some("script-src 'unsafe-inline'"),
1481                blocked: Some("eval"),
1482                message: EVAL_MSG,
1483                raw_blocked_uri: "eval",
1484                directive: "script-src",
1485            },
1486            // CSP2 may append the policy source list to effective-directive.
1487            Case {
1488                effective: Some("script-src 'unsafe-eval'"),
1489                violated: Some("script-src 'unsafe-eval'"),
1490                blocked: Some("inline"),
1491                message: INLINE_MSG,
1492                raw_blocked_uri: "inline",
1493                directive: "script-src",
1494            },
1495            // External and non-marker URIs keep normalized messages and the raw blocked URI.
1496            Case {
1497                effective: Some("script-src"),
1498                violated: Some("script-src 'unsafe-inline'"),
1499                blocked: Some("https://cdn.example.com/app.js"),
1500                message: "Blocked 'script' from 'cdn.example.com'",
1501                raw_blocked_uri: "https://cdn.example.com/app.js",
1502                directive: "script-src",
1503            },
1504            Case {
1505                effective: None,
1506                violated: Some("script-src 'unsafe-inline'"),
1507                blocked: Some("https://cdn.example.com/app.js"),
1508                message: "Blocked 'script' from 'cdn.example.com'",
1509                raw_blocked_uri: "https://cdn.example.com/app.js",
1510                directive: "script-src",
1511            },
1512            Case {
1513                effective: Some("script-src"),
1514                violated: Some("script-src"),
1515                blocked: Some("https://cdn.example.com:8443/app.js"),
1516                message: "Blocked 'script' from 'cdn.example.com:8443'",
1517                raw_blocked_uri: "https://cdn.example.com:8443/app.js",
1518                directive: "script-src",
1519            },
1520            Case {
1521                effective: Some("script-src"),
1522                violated: Some("script-src 'unsafe-eval'"),
1523                blocked: Some("data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D"),
1524                message: "Blocked 'script' from 'data:'",
1525                raw_blocked_uri: "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D",
1526                directive: "script-src",
1527            },
1528            Case {
1529                effective: Some("script-src"),
1530                violated: Some("script-src"),
1531                blocked: Some("data"),
1532                message: "Blocked 'script' from 'data:'",
1533                raw_blocked_uri: "data",
1534                directive: "script-src",
1535            },
1536            Case {
1537                effective: Some("script-src"),
1538                violated: Some("script-src 'unsafe-eval'"),
1539                blocked: Some("https://example.com/eval"),
1540                message: "Blocked 'script' from 'example.com'",
1541                raw_blocked_uri: "https://example.com/eval",
1542                directive: "script-src",
1543            },
1544            // Only the exact markers `inline` and `eval` select the specific messages.
1545            Case {
1546                effective: Some("script-src"),
1547                violated: Some("script-src 'unsafe-inline'"),
1548                blocked: Some("INLINE"),
1549                message: "Blocked 'script' from 'INLINE:'",
1550                raw_blocked_uri: "INLINE",
1551                directive: "script-src",
1552            },
1553            Case {
1554                effective: Some("script-src"),
1555                violated: Some("script-src 'unsafe-eval'"),
1556                blocked: Some("eval:"),
1557                message: "Blocked 'script' from 'eval:'",
1558                raw_blocked_uri: "eval:",
1559                directive: "script-src",
1560            },
1561            Case {
1562                effective: Some("script-src"),
1563                violated: Some("script-src 'unsafe-inline'"),
1564                blocked: Some("inline "),
1565                message: "Blocked 'script' from 'inline :'",
1566                raw_blocked_uri: "inline ",
1567                directive: "script-src",
1568            },
1569            // Other directives keep their own wording. `inline` and `eval` are ordinary URIs there.
1570            Case {
1571                effective: Some("style-src"),
1572                violated: Some("style-src 'unsafe-inline'"),
1573                blocked: Some(""),
1574                message: "Blocked inline 'style'",
1575                raw_blocked_uri: "",
1576                directive: "style-src",
1577            },
1578            Case {
1579                effective: Some("style-src"),
1580                violated: Some("style-src 'unsafe-inline'"),
1581                blocked: Some("inline"),
1582                message: "Blocked 'style' from 'inline:'",
1583                raw_blocked_uri: "inline",
1584                directive: "style-src",
1585            },
1586            Case {
1587                effective: Some("style-src-elem"),
1588                violated: Some("style-src-elem"),
1589                blocked: Some("http://fonts.google.com/foo"),
1590                message: "Blocked 'style' from 'fonts.google.com'",
1591                raw_blocked_uri: "http://fonts.google.com/foo",
1592                directive: "style-src-elem",
1593            },
1594            Case {
1595                effective: Some("style-src-elem"),
1596                violated: Some("style-src-elem 'unsafe-inline'"),
1597                blocked: Some("self"),
1598                message: "Blocked 'style' or 'link' element",
1599                raw_blocked_uri: "self",
1600                directive: "style-src-elem",
1601            },
1602            Case {
1603                effective: Some("style-src-attr"),
1604                violated: Some("style-src-attr"),
1605                blocked: Some(""),
1606                message: "Blocked style attribute",
1607                raw_blocked_uri: "",
1608                directive: "style-src-attr",
1609            },
1610            Case {
1611                effective: Some("script-src-elem"),
1612                violated: Some("script-src-elem 'unsafe-inline'"),
1613                blocked: Some("http://cdn.ajaxapis.com/foo"),
1614                message: "Blocked 'script' from 'cdn.ajaxapis.com'",
1615                raw_blocked_uri: "http://cdn.ajaxapis.com/foo",
1616                directive: "script-src-elem",
1617            },
1618            Case {
1619                effective: Some("script-src-elem"),
1620                violated: Some("script-src-elem 'unsafe-inline'"),
1621                blocked: Some("inline"),
1622                message: "Blocked 'script' from 'inline:'",
1623                raw_blocked_uri: "inline",
1624                directive: "script-src-elem",
1625            },
1626            Case {
1627                effective: Some("script-src-elem"),
1628                violated: Some("script-src-elem 'unsafe-inline'"),
1629                blocked: Some(""),
1630                message: "Blocked inline script attribute",
1631                raw_blocked_uri: "",
1632                directive: "script-src-elem",
1633            },
1634            Case {
1635                effective: Some("script-src-attr"),
1636                violated: Some("script-src-attr 'unsafe-eval'"),
1637                blocked: Some("eval"),
1638                message: "Blocked inline script attribute from 'eval:'",
1639                raw_blocked_uri: "eval",
1640                directive: "script-src-attr",
1641            },
1642            Case {
1643                effective: Some("script-src-attr"),
1644                violated: Some("script-src-attr"),
1645                blocked: Some("'self'"),
1646                message: "Blocked unsafe 'script' element",
1647                raw_blocked_uri: "'self'",
1648                directive: "script-src-attr",
1649            },
1650        ];
1651
1652        for report_format in [CspPayloadFormat::Legacy, CspPayloadFormat::ReportingApi] {
1653            for case in &cases {
1654                let context = format!(
1655                    "format={report_format:?} effective={:?} violated={:?} blocked={:?}",
1656                    case.effective, case.violated, case.blocked
1657                );
1658                let event =
1659                    apply_csp_payload(report_format, case.effective, case.violated, case.blocked)
1660                        .unwrap_or_else(|error| panic!("{context}: {error}"));
1661                assert_csp_outcome(
1662                    &event,
1663                    case.message,
1664                    case.raw_blocked_uri,
1665                    case.directive,
1666                    &context,
1667                );
1668            }
1669        }
1670    }
1671
1672    #[test]
1673    fn test_csp_apply_to_event_requires_a_known_directive() {
1674        // An inline or eval marker does not imply script-src when both directive fields are
1675        // missing or unparseable.
1676        let cases = [
1677            (None, None, Some("inline")),
1678            (None, None, Some("eval")),
1679            (None, Some(""), Some("inline")),
1680            (None, Some("'unsafe-inline'"), Some("inline")),
1681            (None, Some("'unsafe-eval'"), Some("eval")),
1682            (Some("not-a-directive"), None, Some("inline")),
1683            (Some("not-a-directive"), Some("also-not"), Some("eval")),
1684            (Some(""), Some(""), Some("inline")),
1685            (None, None, None),
1686        ];
1687
1688        for report_format in [CspPayloadFormat::Legacy, CspPayloadFormat::ReportingApi] {
1689            for (effective, violated, blocked) in cases {
1690                let error = apply_csp_payload(report_format, effective, violated, blocked)
1691                    .expect_err("missing directives must not produce a CSP event");
1692                assert!(
1693                    error.to_string().contains("invalid security report"),
1694                    "format={report_format:?} effective={effective:?} violated={violated:?} blocked={blocked:?}: {error}"
1695                );
1696            }
1697        }
1698    }
1699
1700    #[test]
1701    fn test_security_report_type_deserializer_recognizes_csp_reports() {
1702        let csp_report_text = r#"{
1703            "csp-report": {
1704                "document-uri": "https://example.com/foo/bar",
1705                "referrer": "https://www.google.com/",
1706                "violated-directive": "default-src self",
1707                "original-policy": "default-src self; report-uri /csp-hotline.php",
1708                "blocked-uri": "http://evilhackerscripts.com"
1709            }
1710        }"#;
1711
1712        let report_type = SecurityReportType::from_json(csp_report_text.as_bytes()).unwrap();
1713        assert_eq!(report_type, Some(SecurityReportType::Csp));
1714    }
1715
1716    #[test]
1717    fn test_security_report_type_deserializer_recognizes_csp_violations_reports() {
1718        let csp_report_text = r#"{
1719          "age":0,
1720          "body":{
1721            "blockedURL":"https://example.com/tst/media/7_del.png",
1722            "disposition":"enforce",
1723            "documentURL":"https://example.com/tst/test_frame.php?ID=229&hash=da964209653e467d337313e51876e27d",
1724            "effectiveDirective":"img-src",
1725            "lineNumber":9,
1726            "originalPolicy":"default-src 'none'; report-to endpoint-csp;",
1727            "referrer":"https://example.com/test229/",
1728            "sourceFile":"https://example.com/tst/test_frame.php?ID=229&hash=da964209653e467d337313e51876e27d",
1729            "statusCode":0
1730            },
1731          "type":"csp-violation",
1732          "url":"https://example.com/tst/test_frame.php?ID=229&hash=da964209653e467d337313e51876e27d",
1733          "user_agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
1734        }"#;
1735
1736        let report_type = SecurityReportType::from_json(csp_report_text.as_bytes()).unwrap();
1737        assert_eq!(report_type, Some(SecurityReportType::Csp));
1738    }
1739
1740    #[test]
1741    fn test_security_report_type_deserializer_rejects_expect_ct_reports() {
1742        // Expect-CT is no longer a supported report type: the classifier must not recognize it.
1743        let expect_ct_report_text = r#"{
1744            "expect-ct-report": {
1745                "date-time": "2014-04-06T13:00:50Z",
1746                "hostname": "www.example.com",
1747                "port": 443,
1748                "effective-expiration-date": "2014-05-01T12:40:50Z",
1749                "served-certificate-chain": [
1750                    "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"
1751                ],
1752                "validated-certificate-chain": [
1753                    "-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"
1754                ],
1755                "scts": [
1756                    {
1757                        "version": 1,
1758                        "status": "invalid",
1759                        "source": "embedded",
1760                        "serialized_sct": "ABCD=="
1761                    }
1762                ]
1763            }
1764        }"#;
1765
1766        let report_type = SecurityReportType::from_json(expect_ct_report_text.as_bytes()).unwrap();
1767        assert_eq!(report_type, None);
1768    }
1769
1770    #[test]
1771    fn test_security_report_type_deserializer_rejects_expect_staple_reports() {
1772        // Expect-Staple is no longer a supported report type: the classifier must not recognize it.
1773        let expect_staple_report_text = r#"{
1774             "expect-staple-report": {
1775                "date-time": "2014-04-06T13:00:50Z",
1776                "hostname": "www.example.com",
1777                "port": 443,
1778                "response-status": "ERROR_RESPONSE",
1779                "cert-status": "REVOKED",
1780                "effective-expiration-date": "2014-05-01T12:40:50Z",
1781                "served-certificate-chain": ["-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"],
1782                "validated-certificate-chain": ["-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"]
1783            }
1784        }"#;
1785        let report_type =
1786            SecurityReportType::from_json(expect_staple_report_text.as_bytes()).unwrap();
1787        assert_eq!(report_type, None);
1788    }
1789
1790    #[test]
1791    fn test_security_report_type_deserializer_rejects_hpkp_reports() {
1792        // HPKP is no longer a supported report type: the classifier must not recognize it.
1793        let hpkp_report_text = r#"{
1794            "date-time": "2014-04-06T13:00:50Z",
1795            "hostname": "www.example.com",
1796            "port": 443,
1797            "effective-expiration-date": "2014-05-01T12:40:50Z",
1798            "include-subdomains": false,
1799            "served-certificate-chain": [
1800              "-----BEGIN CERTIFICATE-----\n MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT\n... -----END CERTIFICATE-----"
1801            ],
1802            "validated-certificate-chain": [
1803              "-----BEGIN CERTIFICATE-----\n MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT\n... -----END CERTIFICATE-----"
1804            ],
1805            "known-pins": [
1806              "pin-sha256=\"d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=\"",
1807              "pin-sha256=\"E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=\""
1808            ]
1809          }"#;
1810
1811        let report_type = SecurityReportType::from_json(hpkp_report_text.as_bytes()).unwrap();
1812        assert_eq!(report_type, None);
1813    }
1814
1815    #[test]
1816    fn test_effective_directive_from_violated_directive_single() {
1817        // Example from Firefox:
1818        let csp_raw: CspRaw =
1819            serde_json::from_str(r#"{"violated-directive":"default-src"}"#).unwrap();
1820        assert!(matches!(
1821            csp_raw.effective_directive(),
1822            Ok(CspDirective::DefaultSrc)
1823        ));
1824    }
1825}