Skip to main content

script/dom/security/
cspviolationreporttask.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use bytes::Bytes;
6use content_security_policy as csp;
7use headers::{ContentType, HeaderMap, HeaderMapExt};
8use js::context::JSContext;
9use net_traits::request::{
10    CredentialsMode, Destination, RequestBody, RequestId, create_request_body_with_content,
11};
12use net_traits::{FetchMetadata, NetworkError, ResourceFetchTiming};
13use script_bindings::str::DOMString;
14use servo_url::ServoUrl;
15use stylo_atoms::Atom;
16
17use crate::conversions::Convert;
18use crate::dom::bindings::inheritance::Castable;
19use crate::dom::bindings::refcounted::Trusted;
20use crate::dom::bindings::root::DomRoot;
21use crate::dom::csp::Violation;
22use crate::dom::csppolicyviolationreport::{
23    CSPReportUriViolationReport, SecurityPolicyViolationReport,
24};
25use crate::dom::event::{Event, EventBubbles, EventCancelable, EventComposed};
26use crate::dom::eventtarget::EventTarget;
27use crate::dom::performance::performanceresourcetiming::InitiatorType;
28use crate::dom::reporting::reportingobserver::ReportingObserver;
29use crate::dom::securitypolicyviolationevent::SecurityPolicyViolationEvent;
30use crate::dom::types::GlobalScope;
31use crate::fetch::fetch::{RequestWithGlobalScope, create_a_potential_cors_request};
32use crate::fetch::network_listener::{
33    FetchResponseListener, ResourceTimingListener, submit_timing,
34};
35use crate::tasks::task::TaskOnce;
36
37pub(crate) struct CSPViolationReportTask {
38    global: Trusted<GlobalScope>,
39    event_target: Trusted<EventTarget>,
40    violation_report: SecurityPolicyViolationReport,
41    violation_policy: csp::Policy,
42}
43
44impl CSPViolationReportTask {
45    pub fn new(
46        global: Trusted<GlobalScope>,
47        event_target: Trusted<EventTarget>,
48        violation_report: SecurityPolicyViolationReport,
49        violation_policy: csp::Policy,
50    ) -> CSPViolationReportTask {
51        CSPViolationReportTask {
52            global,
53            event_target,
54            violation_report,
55            violation_policy,
56        }
57    }
58
59    fn fire_violation_event(&self, cx: &mut JSContext) {
60        let event = SecurityPolicyViolationEvent::new(
61            cx,
62            &self.global.root(),
63            Atom::from("securitypolicyviolation"),
64            EventBubbles::Bubbles,
65            EventCancelable::NotCancelable,
66            EventComposed::Composed,
67            &self.violation_report.clone().convert(),
68        );
69
70        event.upcast::<Event>().fire(cx, &self.event_target.root());
71    }
72
73    /// <https://www.w3.org/TR/CSP/#deprecated-serialize-violation>
74    fn serialize_violation(&self) -> Option<RequestBody> {
75        let report_body = CSPReportUriViolationReport {
76            // Steps 1-3.
77            csp_report: self.violation_report.clone().into(),
78        };
79        // Step 4. Return the result of serialize an infra value to JSON bytes given «[ "csp-report" → body ]».
80        Some(create_request_body_with_content(
81            serde_json::to_string(&report_body).unwrap_or_default(),
82        ))
83    }
84
85    /// Step 3.4 of <https://www.w3.org/TR/CSP/#report-violation>
86    fn post_csp_violation_to_report_uri(&self, report_uri_directive: &csp::Directive) {
87        let global = self.global.root();
88        // Step 3.4.1. If violation’s policy’s directive set contains a directive named
89        // "report-to", skip the remaining substeps.
90        if self
91            .violation_policy
92            .contains_a_directive_whose_name_is("report-to")
93        {
94            return;
95        }
96        // Step 3.4.2. For each token of directive’s value:
97        for token in &report_uri_directive.value {
98            // Step 3.4.2.1. Let endpoint be the result of executing the URL parser with token as the input,
99            // and violation’s url as the base URL.
100            //
101            // TODO: Figure out if this should be the URL of the containing document or not in case
102            // the url points to a blob
103            let Ok(endpoint) = ServoUrl::parse_with_base(Some(&global.get_url()), token) else {
104                // Step 3.4.2.2. If endpoint is not a valid URL, skip the remaining substeps.
105                continue;
106            };
107            // Step 3.4.2.3. Let request be a new request, initialized as follows:
108            let mut headers = HeaderMap::with_capacity(1);
109            headers.typed_insert(ContentType::from(
110                "application/csp-report".parse::<mime::Mime>().unwrap(),
111            ));
112            let request_body = self.serialize_violation();
113            let request = create_a_potential_cors_request(
114                None,
115                endpoint.clone(),
116                Destination::Report,
117                None,
118                None,
119                global.get_referrer(),
120            )
121            .with_global_scope(&global)
122            .method(http::Method::POST)
123            .body(request_body)
124            .credentials_mode(CredentialsMode::CredentialsSameOrigin)
125            .headers(headers);
126            // Step 3.4.2.4. Fetch request. The result will be ignored.
127            global.fetch(
128                request,
129                CSPReportUriFetchListener {
130                    endpoint,
131                    global: Trusted::new(&global),
132                },
133                global.task_manager().networking_task_source().into(),
134            );
135        }
136    }
137}
138
139/// Corresponds to the operation in 5.5 Report Violation
140/// <https://w3c.github.io/webappsec-csp/#report-violation>
141/// > Queue a task to run the following steps:
142impl TaskOnce for CSPViolationReportTask {
143    fn run_once(self, cx: &mut JSContext) {
144        // > If target implements EventTarget, fire an event named securitypolicyviolation
145        // > that uses the SecurityPolicyViolationEvent interface
146        // > at target with its attributes initialized as follows:
147        self.fire_violation_event(cx);
148        // Step 3.4. If violation’s policy’s directive set contains a directive named "report-uri" directive:
149        if let Some(report_uri_directive) = self
150            .violation_policy
151            .directive_set
152            .iter()
153            .find(|directive| directive.name == "report-uri")
154        {
155            self.post_csp_violation_to_report_uri(report_uri_directive);
156        }
157        // Step 3.5. If violation’s policy’s directive set contains a directive named "report-to" directive:
158        if let Some(report_to_directive) = self
159            .violation_policy
160            .directive_set
161            .iter()
162            .find(|directive| directive.name == "report-to")
163        {
164            // Step 3.5.1. Let body be a new CSPViolationReportBody, initialized as follows:
165            let body = self.violation_report.clone().convert();
166            // Step 3.5.2. Let settings object be violation’s global object’s relevant settings object.
167            // Step 3.5.3. Generate and queue a report with the following arguments:
168            ReportingObserver::generate_and_queue_a_report(
169                &self.global.root(),
170                DOMString::from_static("csp-violation"),
171                Some(body),
172                report_to_directive.value.join(" ").into(),
173            )
174        }
175    }
176}
177
178struct CSPReportUriFetchListener {
179    /// Endpoint URL of this request.
180    endpoint: ServoUrl,
181    /// The global object fetching the report uri violation
182    global: Trusted<GlobalScope>,
183}
184
185impl FetchResponseListener for CSPReportUriFetchListener {
186    fn process_request_body(&mut self, _: RequestId) {}
187
188    fn process_response(
189        &mut self,
190        _: &mut JSContext,
191        _: RequestId,
192        fetch_metadata: Result<FetchMetadata, NetworkError>,
193    ) {
194        _ = fetch_metadata;
195    }
196
197    fn process_response_chunk(&mut self, _: &mut JSContext, _: RequestId, chunk: Bytes) {
198        _ = chunk;
199    }
200
201    fn process_response_eof(
202        self,
203        cx: &mut JSContext,
204        _: RequestId,
205        response: Result<(), NetworkError>,
206        timing: ResourceFetchTiming,
207    ) {
208        submit_timing(cx, &self, &response, &timing)
209    }
210
211    fn process_csp_violations(
212        &mut self,
213        _cx: &mut JSContext,
214        _request_id: RequestId,
215        _violations: Vec<Violation>,
216    ) {
217    }
218}
219
220impl ResourceTimingListener for CSPReportUriFetchListener {
221    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
222        (InitiatorType::Other, self.endpoint.clone())
223    }
224
225    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
226        self.global.root()
227    }
228}