View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html.csp;
16  
17  import static java.nio.charset.StandardCharsets.UTF_8;
18  import static org.htmlunit.BrowserVersionFeatures.CSP_META_SINGLE_POLICY;
19  import static org.htmlunit.BrowserVersionFeatures.CSP_CONNECT_REDIRECT_VIOLATION_DELAYED;
20  import static org.htmlunit.BrowserVersionFeatures.CSP_NONCE_HIDING_ENFORCED_ONLY;
21  import static org.htmlunit.BrowserVersionFeatures.CSP_NONCE_TRIMMED;
22  import static org.htmlunit.BrowserVersionFeatures.CSP_REPORT_FIREFOX_FORMAT;
23  import static org.htmlunit.BrowserVersionFeatures.CSP_UPGRADE_INSECURE_REQUESTS_MATCHES_HTTPS;
24  import static org.htmlunit.html.DomElement.ATTRIBUTE_NOT_DEFINED;
25  
26  import java.io.IOException;
27  import java.io.Serializable;
28  import java.net.MalformedURLException;
29  import java.net.URL;
30  import java.util.ArrayList;
31  import java.util.HashSet;
32  import java.util.List;
33  import java.util.Locale;
34  import java.util.Optional;
35  import java.util.Set;
36  import java.util.function.Predicate;
37  
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.htmlunit.HttpHeader;
41  import org.htmlunit.HttpMethod;
42  import org.htmlunit.SgmlPage;
43  import org.htmlunit.TopLevelWindow;
44  import org.htmlunit.WebClient;
45  import org.htmlunit.WebRequest;
46  import org.htmlunit.WebResponse;
47  import org.htmlunit.WebWindow;
48  import org.htmlunit.corejs.javascript.Context;
49  import org.htmlunit.corejs.javascript.EvaluatorException;
50  import org.htmlunit.corejs.javascript.ScriptStackElement;
51  import org.htmlunit.csp.FetchDirectiveKind;
52  import org.htmlunit.csp.Policy;
53  import org.htmlunit.csp.directive.ReportUriDirective;
54  import org.htmlunit.csp.directive.SandboxDirective;
55  import org.htmlunit.csp.directive.SourceExpressionDirective;
56  import org.htmlunit.csp.url.GUID;
57  import org.htmlunit.csp.url.URI;
58  import org.htmlunit.csp.url.URLWithScheme;
59  import org.htmlunit.html.DomAttr;
60  import org.htmlunit.html.DomElement;
61  import org.htmlunit.html.DomNode;
62  import org.htmlunit.html.FrameWindow;
63  import org.htmlunit.html.HtmlPage;
64  import org.htmlunit.javascript.AbstractJavaScriptEngine;
65  import org.htmlunit.javascript.JavaScriptEngine;
66  import org.htmlunit.javascript.host.event.EventTarget;
67  import org.htmlunit.javascript.host.event.SecurityPolicyViolationEvent;
68  import org.htmlunit.util.NameValuePair;
69  import org.htmlunit.util.StringUtils;
70  import org.htmlunit.util.UrlUtils;
71  
72  /**
73   * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
74   *
75   * The Content-Security-Policy of a page. Contains the enforced policies (from the
76   * Content-Security-Policy headers and meta elements) and the report only policies
77   * (from the Content-Security-Policy-Report-Only headers).
78   * <p>
79   * All the check methods return {@code false} if one of the enforced policies does not allow
80   * the action. For every policy (enforced or report only) that does not allow the action a
81   * securitypolicyviolation event is fired.
82   * </p>
83   *
84   * @author Ronald Brill
85   */
86  public final class ContentSecurityPolicy implements Serializable {
87  
88      private static final Log LOG = LogFactory.getLog(ContentSecurityPolicy.class);
89  
90      /** The name of the report only header. */
91      public static final String HEADER_REPORT_ONLY = "Content-Security-Policy-Report-Only";
92  
93      /** The maximum length of the sample reported for 'report-sample'. */
94      private static final int SAMPLE_LENGTH = 40;
95  
96      private static final String BLOCKED_INLINE = "inline";
97      private static final String BLOCKED_EVAL = "eval";
98      private static final String FORM_ACTION = "form-action";
99      private static final String BASE_URI = "base-uri";
100     private static final String REPORT_CONTENT_TYPE = "application/csp-report";
101 
102     /** The violation events to be fired after the current script has finished. */
103     private static final ThreadLocal<List<Runnable>> PENDING_VIOLATIONS = new ThreadLocal<>();
104 
105     private final List<String> enforced_ = new ArrayList<>();
106     private final List<String> reportOnly_ = new ArrayList<>();
107     private final List<String> meta_ = new ArrayList<>();
108     private boolean metaSinglePolicy_;
109     // for inherited policies the url of the creator document ('self')
110     private URL selfUrl_;
111 
112     private transient List<Policy> enforcedPolicies_;
113     private transient List<Policy> reportOnlyPolicies_;
114 
115     /**
116      * Ctor.
117      */
118     private ContentSecurityPolicy() {
119         super();
120     }
121 
122     /**
123      * Creates the policy for the given response.
124      *
125      * @param webResponse the response
126      * @return the policy or {@code null} if the response has no policy header
127      */
128     public static ContentSecurityPolicy fromResponse(final WebResponse webResponse) {
129         if (webResponse == null) {
130             return null;
131         }
132 
133         ContentSecurityPolicy result = null;
134         for (final NameValuePair header : webResponse.getResponseHeaders()) {
135             final String value = header.getValue();
136             if (StringUtils.isBlank(value)) {
137                 continue;
138             }
139 
140             if (HttpHeader.CONTENT_SECURIRY_POLICY.equalsIgnoreCase(header.getName())) {
141                 if (result == null) {
142                     result = new ContentSecurityPolicy();
143                 }
144                 result.enforced_.add(value);
145             }
146             else if (HEADER_REPORT_ONLY.equalsIgnoreCase(header.getName())) {
147                 if (result == null) {
148                     result = new ContentSecurityPolicy();
149                 }
150                 result.reportOnly_.add(value);
151             }
152         }
153         return result;
154     }
155 
156     /**
157      * Returns a copy of the policy of the creator for documents with a local scheme url
158      * (about:, data:, blob:). Like the browsers, these documents inherit the policy of the
159      * document creating them; for frames this is the parent document, for windows opened
160      * by window.open() the opener. The copy is independent from the policy of the creator
161      * (policies added later by meta elements are not shared) and 'self' refers to the
162      * origin of the creator.
163      *
164      * @param url the url of the new document
165      * @param window the window the new document is loaded into
166      * @return the inherited policy or {@code null}
167      */
168     public static ContentSecurityPolicy inherit(final URL url, final WebWindow window) {
169         if (url == null || window == null) {
170             return null;
171         }
172         final String protocol = url.getProtocol();
173         if (!"about".equals(protocol) && !"data".equals(protocol) && !"blob".equals(protocol)) {
174             return null;
175         }
176 
177         WebWindow creator = null;
178         if (window instanceof FrameWindow) {
179             creator = window.getParentWindow();
180         }
181         else if (window instanceof TopLevelWindow topLevelWindow) {
182             creator = topLevelWindow.getOpener();
183         }
184         if (creator == null || creator == window
185                 || !(creator.getEnclosedPage() instanceof HtmlPage creatorPage)) {
186             return null;
187         }
188 
189         final ContentSecurityPolicy creatorCsp = creatorPage.getContentSecurityPolicy();
190         if (creatorCsp == null) {
191             return null;
192         }
193 
194         final ContentSecurityPolicy result = new ContentSecurityPolicy();
195         result.enforced_.addAll(creatorCsp.enforced_);
196         result.reportOnly_.addAll(creatorCsp.reportOnly_);
197         result.meta_.addAll(creatorCsp.meta_);
198         result.metaSinglePolicy_ = creatorCsp.metaSinglePolicy_;
199         result.selfUrl_ = selfUrl(creatorPage);
200         return result;
201     }
202 
203     /**
204      * Adds a policy defined by a meta element to the given page.
205      * The policy is parsed with the meta restrictions (frame-ancestors, sandbox and
206      * report-uri are ignored). Depending on the browser, commas split the content into
207      * several policies (Chrome) or are part of the single policy (Firefox).
208      *
209      * @param page the page
210      * @param serializedPolicy the policy
211      */
212     public static void addMetaPolicy(final HtmlPage page, final String serializedPolicy) {
213         if (StringUtils.isBlank(serializedPolicy)) {
214             return;
215         }
216 
217         ContentSecurityPolicy csp = page.getContentSecurityPolicy();
218         if (csp == null) {
219             csp = new ContentSecurityPolicy();
220             page.setContentSecurityPolicy(csp);
221         }
222         csp.meta_.add(serializedPolicy);
223         csp.metaSinglePolicy_ = page.getWebClient().getBrowserVersion().hasFeature(CSP_META_SINGLE_POLICY);
224         csp.enforcedPolicies_ = null;
225     }
226 
227     /**
228      * Checks if the given inline script is allowed.
229      *
230      * @param page the page
231      * @param element the script element
232      * @param source the script source
233      * @return {@code true} if the script is allowed
234      */
235     public static boolean allowsInlineScript(final HtmlPage page, final DomElement element, final String source) {
236         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
237         if (csp == null) {
238             return true;
239         }
240 
241         final Optional<String> nonce = nonce(element);
242         final Optional<Boolean> parserInserted = Optional.of(isParserInserted(element));
243         final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, BLOCKED_INLINE, source,
244                 element, documentUrl(page), element.getStartLineNumber(), element.getStartColumnNumber());
245         return csp.check(page, violation,
246                 policy -> policy.allowsInlineScript(nonce, Optional.of(source), parserInserted));
247     }
248 
249     /**
250      * Checks if the given external script is allowed.
251      *
252      * @param page the page
253      * @param element the script element
254      * @param url the url of the script
255      * @return {@code true} if the script is allowed
256      */
257     public static boolean allowsExternalScript(final HtmlPage page, final DomElement element, final URL url) {
258         return allowsExternalScript(page, element, url, url);
259     }
260 
261     /**
262      * Checks if the given external script is allowed.
263      *
264      * @param page the page
265      * @param element the script element
266      * @param url the url of the script (or the target of a redirect)
267      * @param reportedUrl the url reported as blocked uri (for redirects the url of the script)
268      * @return {@code true} if the script is allowed
269      */
270     public static boolean allowsExternalScript(final HtmlPage page, final DomElement element, final URL url,
271             final URL reportedUrl) {
272         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
273         if (csp == null) {
274             return true;
275         }
276 
277         final Optional<String> nonce = nonce(element);
278         final String integrityAttrib = element.getAttributeDirect("integrity");
279         final Optional<String> integrity = ATTRIBUTE_NOT_DEFINED == integrityAttrib
280                 ? Optional.empty() : Optional.of(integrityAttrib);
281         final Optional<URLWithScheme> scriptUrl = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
282         final Optional<Boolean> parserInserted = Optional.of(isParserInserted(element));
283         final Optional<URI> origin = origin(page);
284         final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, blockedUri(reportedUrl), null,
285                 null, "", 0, 0);
286         final boolean redirected = isRedirect(url, reportedUrl);
287         return csp.check(page, violation,
288                 policy -> policy.allowsExternalScript(nonce, integrity, scriptUrl, parserInserted, origin,
289                         redirected));
290     }
291 
292     /**
293      * Checks if the given event handler attribute is allowed.
294      *
295      * @param page the page
296      * @param element the element
297      * @param source the source of the event handler
298      * @return {@code true} if the event handler is allowed
299      */
300     public static boolean allowsScriptAsAttribute(final HtmlPage page, final DomElement element,
301             final String source) {
302         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
303         if (csp == null) {
304             return true;
305         }
306 
307         final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcAttr, BLOCKED_INLINE, source,
308                 element, "", 0, 0);
309         final boolean allowed = csp.check(page, violation,
310                 policy -> policy.allowsScriptAsAttribute(Optional.of(source)));
311         firePendingViolationsIfNoScriptRunning(page);
312         return allowed;
313     }
314 
315     /**
316      * Checks if the given javascript: url is allowed.
317      *
318      * @param page the page
319      * @param element the element (link, form) or {@code null}
320      * @param source the source of the javascript url (including the 'javascript:' prefix)
321      * @return {@code true} if the javascript url is allowed
322      */
323     public static boolean allowsJavaScriptUrl(final HtmlPage page, final DomElement element,
324             final String source) {
325         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
326         if (csp == null) {
327             return true;
328         }
329 
330         final Optional<URI> origin = origin(page);
331         final Violation violation = new Violation(FetchDirectiveKind.ScriptSrcElem, BLOCKED_INLINE, source,
332                 element, "", 0, 0);
333         final boolean allowed = csp.check(page, violation,
334                 policy -> policy.allowsJavascriptUrlNavigation(Optional.of(source), origin));
335         firePendingViolationsIfNoScriptRunning(page);
336         return allowed;
337     }
338 
339     /**
340      * Checks if a connection (XMLHttpRequest, fetch(), ...) to the given url is allowed (connect-src).
341      *
342      * @param page the page
343      * @param url the url to connect to
344      * @param reportedUrl the url reported in case of a violation; for redirects this is the
345      *        url of the initial request
346      * @return {@code true} if the connection is allowed
347      */
348     public static boolean allowsConnection(final HtmlPage page, final URL url, final URL reportedUrl) {
349         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
350         if (csp == null) {
351             return true;
352         }
353 
354         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
355         final Optional<URI> origin = origin(page);
356         final Violation violation = new Violation(FetchDirectiveKind.ConnectSrc, blockedUri(reportedUrl), null,
357                 null, "", 0, 0);
358         // like browsers, ws: and wss: urls are not mapped to http: and https: before matching
359         final boolean redirected = isRedirect(url, reportedUrl);
360         final boolean allowed = csp.check(page, violation,
361                 policy -> policy.allowsConnection(target, origin, false, redirected));
362         // Chrome reports a violation of a redirect target (checked by the network stack) after the
363         // request has failed; the violation stays pending until the error is handled
364         // (see XMLHttpRequest) or the next script has finished
365         if (!redirected
366                 || !page.getWebClient().getBrowserVersion().hasFeature(CSP_CONNECT_REDIRECT_VIOLATION_DELAYED)) {
367             firePendingViolationsIfNoScriptRunning(page);
368         }
369         return allowed;
370     }
371 
372     /**
373      * Checks if the inline style element (style-src-elem) is allowed.
374      *
375      * @param page the page
376      * @param element the style element
377      * @param source the content of the style element
378      * @return {@code true} if the style is allowed
379      */
380     public static boolean allowsInlineStyle(final HtmlPage page, final DomElement element, final String source) {
381         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
382         if (csp == null) {
383             return true;
384         }
385 
386         final Optional<String> nonce = nonce(element);
387         final Violation violation = inlineViolation(page, FetchDirectiveKind.StyleSrcElem, source, element);
388         final boolean allowed = csp.check(page, violation,
389                 policy -> policy.allowsInlineStyle(nonce, Optional.of(source)));
390         firePendingViolationsIfNoScriptRunning(page);
391         return allowed;
392     }
393 
394     /**
395      * Checks if the style attribute (style-src-attr) is allowed.
396      * Like the browsers, style changes done by the CSSOM (e.g. element.style.color = 'red')
397      * are not checked.
398      *
399      * @param page the page
400      * @param element the element with the style attribute
401      * @param source the value of the style attribute
402      * @return {@code true} if the style attribute is allowed
403      */
404     public static boolean allowsStyleAttribute(final HtmlPage page, final DomElement element,
405             final String source) {
406         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
407         if (csp == null) {
408             return true;
409         }
410 
411         final Violation violation = inlineViolation(page, FetchDirectiveKind.StyleSrcAttr, source, element);
412         final boolean allowed = csp.check(page, violation,
413                 policy -> policy.allowsStyleAsAttribute(Optional.of(source)));
414         firePendingViolationsIfNoScriptRunning(page);
415         return allowed;
416     }
417 
418     /**
419      * Checks if loading the external stylesheet (link element or @import) is allowed (style-src-elem).
420      *
421      * @param page the page
422      * @param element the link element (the nonce is taken from this element) or {@code null} for @import
423      * @param url the url of the stylesheet
424      * @return {@code true} if the stylesheet is allowed
425      */
426     public static boolean allowsExternalStyle(final HtmlPage page, final DomElement element, final URL url) {
427         return allowsExternalStyle(page, element, url, url);
428     }
429 
430     /**
431      * Checks if loading the external stylesheet (link element or @import) is allowed (style-src-elem).
432      *
433      * @param page the page
434      * @param element the link element (the nonce is taken from this element) or {@code null} for @import
435      * @param url the url of the stylesheet (or the target of a redirect)
436      * @param reportedUrl the url reported as blocked uri (for redirects the url of the stylesheet)
437      * @return {@code true} if the stylesheet is allowed
438      */
439     public static boolean allowsExternalStyle(final HtmlPage page, final DomElement element, final URL url,
440             final URL reportedUrl) {
441         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
442         if (csp == null) {
443             return true;
444         }
445 
446         final Optional<String> nonce = element == null ? Optional.empty() : nonce(element);
447         final Optional<URLWithScheme> styleUrl = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
448         final Optional<URI> origin = origin(page);
449         final Violation violation = new Violation(FetchDirectiveKind.StyleSrcElem, blockedUri(reportedUrl), null,
450                 null, "", 0, 0);
451         final boolean redirected = isRedirect(url, reportedUrl);
452         final boolean allowed = csp.check(page, violation,
453                 policy -> policy.allowsExternalStyle(nonce, styleUrl, origin, redirected));
454         firePendingViolationsIfNoScriptRunning(page);
455         return allowed;
456     }
457 
458     /**
459      * Checks if loading the given url into a frame or iframe is allowed
460      * (frame-src, with fallback to child-src and default-src).
461      * Like the browsers, the violation is reported for the document and the blocked url
462      * is reported without path if it is cross origin (navigations may leak information).
463      *
464      * @param page the page containing the frame
465      * @param url the url to load into the frame (for redirects the target of the redirect)
466      * @return {@code true} if loading is allowed
467      */
468     public static boolean allowsFrame(final HtmlPage page, final URL url) {
469         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
470         if (csp == null) {
471             return true;
472         }
473 
474         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
475         final Optional<URI> origin = origin(page);
476         final Violation violation = new Violation(FetchDirectiveKind.FrameSrc, navigationBlockedUri(page, url),
477                 null, null, "", 0, 0);
478         final boolean allowed = csp.check(page, violation, policy -> policy.allowsFrame(target, origin));
479         firePendingViolationsIfNoScriptRunning(page);
480         return allowed;
481     }
482 
483     /**
484      * Checks if the url of an object or embed element is allowed (object-src, with fallback
485      * to default-src). HtmlUnit does not load the content of these elements; like the browsers,
486      * the url is checked anyway to report the violation.
487      *
488      * @param element the object or embed element
489      * @param src the value of the data (object) or src (embed) attribute
490      * @return {@code true} if the url is allowed (or the attribute is empty or invalid)
491      */
492     public static boolean allowsObject(final DomElement element, final String src) {
493         final HtmlPage page = element.getHtmlPageOrNull();
494         if (page == null || page.getContentSecurityPolicy() == null
495                 || ATTRIBUTE_NOT_DEFINED == src || StringUtils.isBlank(src)) {
496             return true;
497         }
498 
499         final URL url;
500         try {
501             url = page.getFullyQualifiedUrl(src);
502         }
503         catch (final MalformedURLException e) {
504             return true;
505         }
506 
507         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
508         final Optional<URI> origin = origin(page);
509         final Violation violation = new Violation(FetchDirectiveKind.ObjectSrc, objectBlockedUri(page, url), null,
510                 null, "", 0, 0);
511         final boolean allowed = page.getContentSecurityPolicy()
512                 .check(page, violation, policy -> policy.allowsObject(target, origin));
513         firePendingViolationsIfNoScriptRunning(page);
514         return allowed;
515     }
516 
517     /**
518      * Checks if the url of a media element (audio, video), a source element or a track element
519      * is allowed (media-src, with fallback to default-src). HtmlUnit does not load media; like the
520      * browsers, the url is checked anyway to report the violation.
521      *
522      * @param element the element
523      * @param src the value of the src attribute
524      * @return {@code true} if the url is allowed (or the attribute is empty or invalid)
525      */
526     public static boolean allowsMedia(final DomElement element, final String src) {
527         final HtmlPage page = element.getHtmlPageOrNull();
528         if (page == null || page.getContentSecurityPolicy() == null
529                 || ATTRIBUTE_NOT_DEFINED == src || StringUtils.isBlank(src)) {
530             return true;
531         }
532 
533         final URL url;
534         try {
535             url = upgradeInsecureRequest(page, page.getFullyQualifiedUrl(src));
536         }
537         catch (final MalformedURLException e) {
538             return true;
539         }
540 
541         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
542         final Optional<URI> origin = origin(page);
543         final Violation violation = new Violation(FetchDirectiveKind.MediaSrc, blockedUri(url), null,
544                 null, "", 0, 0);
545         final boolean allowed = page.getContentSecurityPolicy()
546                 .check(page, violation, policy -> policy.allowsMedia(target, origin));
547         firePendingViolationsIfNoScriptRunning(page);
548         return allowed;
549     }
550 
551     /**
552      * Checks if loading the given image url is allowed (img-src, with fallback to default-src).
553      *
554      * @param page the page containing the image
555      * @param url the url of the image
556      * @return {@code true} if the image is allowed
557      */
558     public static boolean allowsImage(final HtmlPage page, final URL url) {
559         return allowsImage(page, url, url);
560     }
561 
562     /**
563      * Checks if loading the given image url is allowed (img-src, with fallback to default-src).
564      *
565      * @param page the page containing the image
566      * @param url the url of the image (or the target of a redirect)
567      * @param reportedUrl the url reported as blocked uri (for redirects the url of the image)
568      * @return {@code true} if the image is allowed
569      */
570     public static boolean allowsImage(final HtmlPage page, final URL url, final URL reportedUrl) {
571         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
572         if (csp == null) {
573             return true;
574         }
575 
576         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
577         final Optional<URI> origin = origin(page);
578         final Violation violation = new Violation(FetchDirectiveKind.ImgSrc, blockedUri(reportedUrl), null,
579                 null, "", 0, 0);
580         final boolean redirected = isRedirect(url, reportedUrl);
581         final boolean allowed = csp.check(page, violation,
582                 policy -> policy.allowsImage(target, origin, redirected));
583         firePendingViolationsIfNoScriptRunning(page);
584         return allowed;
585     }
586 
587     /**
588      * Upgrade Insecure Requests (upgrade-insecure-requests directive): returns the url to be used for
589      * a request of the page; used for subresources, nested navigations (frames) and form submissions.
590      * <p>
591      * If the page (or one of its ancestors) has an enforced policy containing
592      * upgrade-insecure-requests, http urls are upgraded to https and ws urls to wss (port 80 is
593      * replaced by the default port). Like the browsers, loopback hosts (localhost, 127.0.0.0/8, ::1)
594      * are not upgraded.
595      * </p>
596      *
597      * @param page the page doing the request
598      * @param url the url of the request
599      * @return the upgraded url or the url itself
600      */
601     public static URL upgradeInsecureRequest(final HtmlPage page, final URL url) {
602         if (url == null || !isUpgradable(url) || !upgradesInsecureRequests(page)) {
603             return url;
604         }
605         return upgrade(url);
606     }
607 
608     /**
609      * Upgrade Insecure Requests for top level navigations: the url is upgraded only if the host and port
610      * are the same as the host and port of the page (or of one of its ancestors) having the
611      * upgrade-insecure-requests directive.
612      *
613      * @param page the page doing the navigation
614      * @param url the url of the navigation
615      * @return the upgraded url or the url itself
616      */
617     public static URL upgradeInsecureNavigation(final HtmlPage page, final URL url) {
618         if (url == null || !isUpgradable(url)) {
619             return url;
620         }
621 
622         HtmlPage current = page;
623         while (current != null) {
624             final ContentSecurityPolicy csp = current.getContentSecurityPolicy();
625             if (csp != null && csp.hasUpgradeInsecureRequests()) {
626                 final URL pageUrl = current.getUrl();
627                 if (pageUrl != null && pageUrl.getHost().equalsIgnoreCase(url.getHost())
628                         && effectivePort(pageUrl) == effectivePort(url)) {
629                     return upgrade(url);
630                 }
631             }
632             current = parentPage(current);
633         }
634         return url;
635     }
636 
637     /**
638      * Returns the url used for matching the source expressions. Firefox treats http (ws) urls
639      * like https (wss) urls if the page upgrades insecure requests; this is relevant for
640      * urls that are not upgraded (loopback hosts).
641      */
642     private static URL matchingUrl(final HtmlPage page, final URL url) {
643         if (page.getWebClient().getBrowserVersion().hasFeature(CSP_UPGRADE_INSECURE_REQUESTS_MATCHES_HTTPS)) {
644             final String protocol = url.getProtocol();
645             if (("http".equals(protocol) || "ws".equals(protocol)) && upgradesInsecureRequests(page)) {
646                 try {
647                     return UrlUtils.getUrlWithNewProtocol(url, "http".equals(protocol) ? "https" : "wss");
648                 }
649                 catch (final MalformedURLException e) {
650                     return url;
651                 }
652             }
653         }
654         return url;
655     }
656 
657     /**
658      * Upgrade Insecure Requests for the redirects of a request (subresources, nested navigations
659      * and form submissions): the redirect targets are upgraded like the request itself.
660      *
661      * @param page the page doing the request
662      * @param request the request
663      */
664     public static void upgradeInsecureRedirects(final HtmlPage page, final WebRequest request) {
665         if (upgradesInsecureRequests(page)) {
666             request.setRedirectUrlMapper(url -> upgradeInsecureRequest(page, url));
667         }
668     }
669 
670     /**
671      * Upgrade Insecure Requests for the redirects of a top level navigation.
672      *
673      * @param page the page doing the navigation
674      * @param request the request
675      */
676     public static void upgradeInsecureNavigationRedirects(final HtmlPage page, final WebRequest request) {
677         if (upgradesInsecureRequests(page)) {
678             request.setRedirectUrlMapper(url -> upgradeInsecureNavigation(page, url));
679         }
680     }
681 
682     private static boolean upgradesInsecureRequests(final HtmlPage page) {
683         HtmlPage current = page;
684         while (current != null) {
685             final ContentSecurityPolicy csp = current.getContentSecurityPolicy();
686             if (csp != null && csp.hasUpgradeInsecureRequests()) {
687                 return true;
688             }
689             current = parentPage(current);
690         }
691         return false;
692     }
693 
694     /**
695      * The directive is ignored for report only policies.
696      */
697     private boolean hasUpgradeInsecureRequests() {
698         for (final Policy policy : getEnforcedPolicies()) {
699             if (policy.upgradeInsecureRequests()) {
700                 return true;
701             }
702         }
703         return false;
704     }
705 
706     private static HtmlPage parentPage(final HtmlPage page) {
707         final WebWindow window = page.getEnclosingWindow();
708         if (window instanceof FrameWindow frameWindow) {
709             return frameWindow.getEnclosingPage();
710         }
711         return null;
712     }
713 
714     private static boolean isUpgradable(final URL url) {
715         final String protocol = url.getProtocol();
716         if (!"http".equals(protocol) && !"ws".equals(protocol)) {
717             return false;
718         }
719         return !UrlUtils.isLocalhostOrLoopback(url.getHost());
720     }
721 
722     private static int effectivePort(final URL url) {
723         final int port = url.getPort();
724         return port == -1 ? url.getDefaultPort() : port;
725     }
726 
727     private static URL upgrade(final URL url) {
728         final String protocol = "ws".equals(url.getProtocol()) ? "wss" : "https";
729         try {
730             URL upgraded = UrlUtils.getUrlWithNewProtocol(url, protocol);
731             if (url.getPort() == 80) {
732                 upgraded = UrlUtils.getUrlWithNewPort(upgraded, -1);
733             }
734             return upgraded;
735         }
736         catch (final MalformedURLException e) {
737             return url;
738         }
739     }
740 
741     /**
742      * Checks if creating a worker with the given script url is allowed
743      * (worker-src, with fallback to child-src, script-src and default-src).
744      *
745      * @param page the page creating the worker
746      * @param url the url of the worker script
747      * @return {@code true} if the worker is allowed
748      */
749     public static boolean allowsWorker(final HtmlPage page, final URL url) {
750         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
751         if (csp == null) {
752             return true;
753         }
754 
755         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
756         final Optional<URI> origin = origin(page);
757         final Violation violation = new Violation(FetchDirectiveKind.WorkerSrc, blockedUri(url), null,
758                 null, "", 0, 0);
759         final boolean allowed = csp.check(page, violation, policy -> policy.allowsWorker(target, origin));
760         firePendingViolationsIfNoScriptRunning(page);
761         return allowed;
762     }
763 
764     /**
765      * Checks if the given url is allowed as base url of the document (base-uri).
766      * There is no fallback to default-src for this directive.
767      *
768      * @param page the page containing the base element
769      * @param url the resolved url of the base element
770      * @return {@code true} if the base url is allowed
771      */
772     public static boolean allowsBaseUri(final HtmlPage page, final URL url) {
773         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
774         if (csp == null) {
775             return true;
776         }
777 
778         final URLWithScheme target = toUrlWithScheme(url);
779         final Optional<URI> origin = origin(page);
780         final Violation violation = new Violation(BASE_URI, withoutRef(url), null, null, "", 0, 0);
781         final boolean allowed = csp.check(page, violation,
782                 policy -> policy.baseUri()
783                             .map(directive -> Policy.doesUrlMatchSourceListInOrigin(target, directive, origin))
784                             .orElse(true));
785         firePendingViolationsIfNoScriptRunning(page);
786         return allowed;
787     }
788 
789     /**
790      * Checks if the submission of a form to the given url is allowed (form-action).
791      * There is no fallback to default-src for this directive.
792      *
793      * @param page the page containing the form
794      * @param url the url the form is submitted to (for javascript: urls the whole url)
795      * @param reportedUrl the url reported in case of a violation; for redirects this is the
796      *        url of the form submission
797      * @return {@code true} if the submission is allowed
798      */
799     public static boolean allowsFormAction(final HtmlPage page, final URL url, final URL reportedUrl) {
800         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
801         if (csp == null) {
802             return true;
803         }
804 
805         final Optional<URLWithScheme> target = Optional.of(toUrlWithScheme(matchingUrl(page, url)));
806         final Optional<URI> origin = origin(page);
807         final Violation violation = new Violation(FORM_ACTION, blockedUri(reportedUrl), null, null, "", 0, 0);
808         final boolean redirected = isRedirect(url, reportedUrl);
809         final boolean allowed = csp.check(page, violation,
810                 policy -> policy.allowsFormAction(target, origin, redirected));
811         firePendingViolationsIfNoScriptRunning(page);
812         return allowed;
813     }
814 
815     /**
816      * Checks if the evaluation of strings as code (eval(), new Function(), setTimeout(string)) is allowed.
817      *
818      * @param page the page
819      * @param source the source to evaluate
820      * @param lineNumber the line number of the code calling eval or {@code 0} if not known
821      * @return {@code true} if the evaluation is allowed
822      */
823     public static boolean allowsEval(final HtmlPage page, final String source, final int lineNumber) {
824         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
825         if (csp == null) {
826             return true;
827         }
828 
829         final Violation violation = new Violation(FetchDirectiveKind.ScriptSrc, BLOCKED_EVAL, source,
830                 null, documentUrl(page), lineNumber, 0);
831         final boolean allowed = csp.check(page, violation, Policy::allowsEval);
832         firePendingViolationsIfNoScriptRunning(page);
833         return allowed;
834     }
835 
836     /**
837      * Fires the securitypolicyviolation events of the violations detected by
838      * the current thread so far. Called after a script element was processed and
839      * when the outermost script execution has finished.
840      */
841     public static void firePendingViolations() {
842         final List<Runnable> pending = PENDING_VIOLATIONS.get();
843         if (pending == null) {
844             return;
845         }
846 
847         // firing an event may add new violations
848         while (!pending.isEmpty()) {
849             pending.remove(0).run();
850         }
851         PENDING_VIOLATIONS.remove();
852     }
853 
854     /**
855      * Fires the pending violations if no script is running; otherwise this is done
856      * at the end of the script execution.
857      */
858     private static void firePendingViolationsIfNoScriptRunning(final HtmlPage page) {
859         final AbstractJavaScriptEngine<?> engine = page.getWebClient().getJavaScriptEngine();
860         if (engine == null || !engine.isScriptRunning()) {
861             firePendingViolations();
862         }
863     }
864 
865     private boolean check(final HtmlPage page, final Violation violation, final Predicate<Policy> check) {
866         boolean allowed = true;
867         for (final Policy policy : getEnforcedPolicies()) {
868             if (!check.test(policy)) {
869                 allowed = false;
870                 report(page, policy, violation, SecurityPolicyViolationEvent.DISPOSITION_ENFORCE);
871             }
872         }
873         for (final Policy policy : getReportOnlyPolicies()) {
874             if (!check.test(policy)) {
875                 report(page, policy, violation, SecurityPolicyViolationEvent.DISPOSITION_REPORT);
876             }
877         }
878         return allowed;
879     }
880 
881     /**
882      * Logs the violation and fires the securitypolicyviolation event (async)
883      * at the target element (if connected) or the document.
884      */
885     private static void report(final HtmlPage page, final Policy policy, final Violation violation,
886             final String disposition) {
887         final FetchDirectiveKind directive = violation.directive_;
888         final String effectiveDirective = violation.effectiveDirective_;
889         final String blockedUri = violation.blockedUri_;
890         final String source = violation.source_;
891         final DomElement element = violation.target_;
892         if (LOG.isWarnEnabled()) {
893             LOG.warn((SecurityPolicyViolationEvent.DISPOSITION_REPORT.equals(disposition) ? "[Report Only] " : "")
894                     + "Content-Security-Policy violation: '" + effectiveDirective
895                     + "' blocked '" + blockedUri + "' in '" + page.getUrl() + "' (policy '" + policy + "').");
896         }
897 
898         String sample = "";
899         if (source != null && directive != null) {
900             final SourceExpressionDirective governing =
901                     policy.getGoverningDirectiveForEffectiveDirective(directive).orElse(null);
902             if (governing != null && governing.reportSample()) {
903                 sample = source.length() > SAMPLE_LENGTH ? source.substring(0, SAMPLE_LENGTH) : source;
904             }
905         }
906 
907         final DomNode target = element != null && element.isAttachedToPage() ? element : page;
908         final int lineNumber = Math.max(0, violation.lineNumber_);
909         final int columnNumber = Math.max(0, violation.columnNumber_);
910         final String documentUrl = documentUrl(page);
911         final String sourceFile = violation.sourceFile_;
912         final String originalPolicy = policy.toString();
913         final int statusCode = page.getWebResponse() == null ? 0 : page.getWebResponse().getStatusCode();
914         final String finalSample = sample;
915 
916         final ContentSecurityPolicyViolationListener listener =
917                 page.getWebClient().getContentSecurityPolicyViolationListener();
918         if (listener != null) {
919             listener.violation(page, new ContentSecurityPolicyViolation(documentUrl, blockedUri,
920                     effectiveDirective, originalPolicy, sourceFile, finalSample, lineNumber, columnNumber,
921                     statusCode, SecurityPolicyViolationEvent.DISPOSITION_REPORT.equals(disposition)));
922         }
923 
924         // like the browsers, report-uri is ignored if the policy is delivered by a meta element
925         // or if the policy contains a report-to directive
926         final ReportUriDirective reportUri = policy.deliveredViaMeta() || policy.reportTo().isPresent()
927                 ? null : policy.reportUri().orElse(null);
928         if (reportUri != null && !reportUri.getUris().isEmpty()) {
929             final String report;
930             if (page.getWebClient().getBrowserVersion().hasFeature(CSP_REPORT_FIREFOX_FORMAT)) {
931                 report = "{\"csp-report\":{"
932                         + jsonMember("blocked-uri", blockedUri) + ","
933                         + "\"column-number\":" + Math.max(1, columnNumber) + ","
934                         + jsonMember("disposition", disposition) + ","
935                         + jsonMember("document-uri", documentUrl) + ","
936                         + jsonMember("effective-directive", effectiveDirective) + ","
937                         + (lineNumber > 0 ? "\"line-number\":" + lineNumber + "," : "")
938                         + jsonMember("original-policy", absoluteReportUris(page, originalPolicy, reportUri)) + ","
939                         + jsonMember("referrer", "") + ","
940                         + (StringUtils.isEmptyOrNull(finalSample) ? "" : jsonMember("script-sample", finalSample) + ",")
941                         + (StringUtils.isEmptyOrNull(sourceFile) ? "" : jsonMember("source-file", sourceFile) + ",")
942                         + "\"status-code\":" + statusCode + ","
943                         + jsonMember("violated-directive", effectiveDirective)
944                         + "}}";
945             }
946             else {
947                 report = "{\"csp-report\":{"
948                         + jsonMember("document-uri", documentUrl) + ","
949                         + jsonMember("referrer", "") + ","
950                         + jsonMember("violated-directive", effectiveDirective) + ","
951                         + jsonMember("effective-directive", effectiveDirective) + ","
952                         + jsonMember("original-policy", originalPolicy) + ","
953                         + jsonMember("disposition", disposition) + ","
954                         + jsonMember("blocked-uri", blockedUri) + ","
955                         + (lineNumber > 0 ? "\"line-number\":" + lineNumber + "," : "")
956                         + (columnNumber > 0 ? "\"column-number\":" + columnNumber + "," : "")
957                         + (StringUtils.isEmptyOrNull(sourceFile) ? "" : jsonMember("source-file", sourceFile) + ",")
958                         + "\"status-code\":" + statusCode + ","
959                         + jsonMember("script-sample", finalSample)
960                         + "}}";
961             }
962             final List<String> uris = new ArrayList<>(reportUri.getUris());
963             addPending(() -> sendReports(page, uris, report));
964         }
965 
966         final WebWindow window = page.getEnclosingWindow();
967         if (window == null || !page.getWebClient().isJavaScriptEnabled()
968                 || window.getScriptableObject() == null) {
969             return;
970         }
971 
972         final Runnable fireEvent = () -> {
973             final SecurityPolicyViolationEvent event = new SecurityPolicyViolationEvent(target);
974             event.setDocumentURI(documentUrl);
975             event.setBlockedURI(blockedUri);
976             event.setEffectiveDirective(effectiveDirective);
977             event.setViolatedDirective(effectiveDirective);
978             event.setOriginalPolicy(originalPolicy);
979             event.setSourceFile(sourceFile);
980             event.setSample(finalSample);
981             event.setDisposition(disposition);
982             event.setStatusCode(statusCode);
983             event.setLineNumber(lineNumber);
984             event.setColumnNumber(columnNumber);
985 
986             final EventTarget jsTarget = target.getScriptableObject();
987             ((JavaScriptEngine) page.getWebClient().getJavaScriptEngine())
988                     .callSecured(cx -> jsTarget.fireEvent(event), page);
989         };
990 
991         // browsers queue a task to fire the event; to get a deterministic order
992         // we fire the event after the current script has finished
993         // (see firePendingViolations())
994         addPending(fireEvent);
995     }
996 
997     private static void addPending(final Runnable runnable) {
998         List<Runnable> pending = PENDING_VIOLATIONS.get();
999         if (pending == null) {
1000             pending = new ArrayList<>();
1001             PENDING_VIOLATIONS.set(pending);
1002         }
1003         pending.add(runnable);
1004     }
1005 
1006     /**
1007      * Sends the violation report (report-uri) as POST request with content type
1008      * application/csp-report to all the given uris (relative uris are resolved against the
1009      * url of the document). Errors are only logged.
1010      */
1011     private static void sendReports(final HtmlPage page, final List<String> uris, final String report) {
1012         final WebClient webClient = page.getWebClient();
1013         if (!webClient.getOptions().isContentSecurityPolicyReportsEnabled()) {
1014             return;
1015         }
1016         for (final String uri : uris) {
1017             try {
1018                 final URL url = page.getFullyQualifiedUrl(uri);
1019                 final WebRequest request = new WebRequest(url, HttpMethod.POST);
1020                 request.setAdditionalHeader(HttpHeader.CONTENT_TYPE, REPORT_CONTENT_TYPE);
1021                 request.setCharset(UTF_8);
1022                 request.setRequestBody(report);
1023                 request.setFetchDestination(WebRequest.FetchDestination.REPORT);
1024                 request.setFetchModeOverride(WebRequest.FetchMode.NO_CORS);
1025                 request.setRequestingUrl(page.getUrl());
1026                 request.setSiteForCookies(page.getSiteForCookiesUrl());
1027                 webClient.loadWebResponse(request);
1028             }
1029             catch (final IOException | RuntimeException e) {
1030                 if (LOG.isInfoEnabled()) {
1031                     LOG.info("Sending the Content-Security-Policy violation report to '" + uri + "' failed", e);
1032                 }
1033             }
1034         }
1035     }
1036 
1037     /**
1038      * Returns the policy with absolute report uris (like Firefox).
1039      */
1040     private static String absoluteReportUris(final HtmlPage page, final String policy,
1041             final ReportUriDirective reportUri) {
1042         final StringBuilder uris = new StringBuilder("report-uri");
1043         for (final String uri : reportUri.getUris()) {
1044             String absolute = uri;
1045             try {
1046                 absolute = page.getFullyQualifiedUrl(uri).toExternalForm();
1047             }
1048             catch (final MalformedURLException e) {
1049                 // keep the uri as it is
1050             }
1051             uris.append(' ').append(absolute);
1052         }
1053 
1054         final String[] parts = policy.split(";", -1);
1055         for (int i = 0; i < parts.length; i++) {
1056             final String trimmed = parts[i].trim();
1057             if (trimmed.toLowerCase(Locale.ROOT).startsWith("report-uri")) {
1058                 final String leading = parts[i].substring(0, parts[i].indexOf(trimmed));
1059                 parts[i] = leading + uris;
1060             }
1061         }
1062         return String.join(";", parts);
1063     }
1064 
1065     private static String jsonMember(final String name, final String value) {
1066         final StringBuilder json = new StringBuilder();
1067         json.append('"').append(name).append("\":\"");
1068         if (value != null) {
1069             for (int i = 0; i < value.length(); i++) {
1070                 final char c = value.charAt(i);
1071                 switch (c) {
1072                     case '"':
1073                         json.append("\\\"");
1074                         break;
1075                     case '\\':
1076                         json.append("\\\\");
1077                         break;
1078                     case '\n':
1079                         json.append("\\n");
1080                         break;
1081                     case '\r':
1082                         json.append("\\r");
1083                         break;
1084                     case '\t':
1085                         json.append("\\t");
1086                         break;
1087                     default:
1088                         if (c < 0x20) {
1089                             json.append(String.format("\\u%04x", (int) c));
1090                         }
1091                         else {
1092                             json.append(c);
1093                         }
1094                 }
1095             }
1096         }
1097         return json.append('"').toString();
1098     }
1099 
1100     /**
1101      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1102      *
1103      * Returns the sandbox tokens (e.g. 'allow-scripts') of the sandbox directives of the enforced
1104      * policies; like in the browsers report only policies and policies delivered by a meta element
1105      * are ignored. If more than one policy has a sandbox directive, only the tokens of all
1106      * directives are allowed.
1107      *
1108      * @return the tokens (lower case) or {@code null} if no enforced policy has a sandbox directive
1109      */
1110     public Set<String> getSandboxTokens() {
1111         Set<String> tokens = null;
1112         for (final Policy policy : getEnforcedPolicies()) {
1113             final SandboxDirective sandbox = policy.deliveredViaMeta() ? null : policy.sandbox().orElse(null);
1114             if (sandbox != null) {
1115                 final Set<String> policyTokens = new HashSet<>();
1116                 for (final String value : sandbox.getValues()) {
1117                     policyTokens.add(value.toLowerCase(Locale.ROOT));
1118                 }
1119                 if (tokens == null) {
1120                     tokens = policyTokens;
1121                 }
1122                 else {
1123                     tokens.retainAll(policyTokens);
1124                 }
1125             }
1126         }
1127         return tokens;
1128     }
1129 
1130     private List<Policy> getEnforcedPolicies() {
1131         if (enforcedPolicies_ == null) {
1132             final List<Policy> policies = parse(enforced_);
1133             final Policy.MetaCommaHandling commaHandling = metaSinglePolicy_
1134                     ? Policy.MetaCommaHandling.SINGLE_POLICY : Policy.MetaCommaHandling.SPLIT;
1135             for (final String serialized : meta_) {
1136                 policies.addAll(Policy.parseSerializedCSPList(serialized,
1137                         Policy.PolicyListErrorConsumer.ignored, commaHandling).getPolicies());
1138             }
1139             enforcedPolicies_ = policies;
1140         }
1141         return enforcedPolicies_;
1142     }
1143 
1144     private List<Policy> getReportOnlyPolicies() {
1145         if (reportOnlyPolicies_ == null) {
1146             reportOnlyPolicies_ = parse(reportOnly_);
1147         }
1148         return reportOnlyPolicies_;
1149     }
1150 
1151     private static List<Policy> parse(final List<String> serializedPolicies) {
1152         final List<Policy> policies = new ArrayList<>();
1153         for (final String serialized : serializedPolicies) {
1154             policies.addAll(Policy.parseSerializedCSPList(serialized,
1155                     Policy.PolicyListErrorConsumer.ignored).getPolicies());
1156         }
1157         return policies;
1158     }
1159 
1160     /**
1161      * Creates the violation for inline content (style element or style attribute). Like the browsers,
1162      * the location is the location of the running script, if the element was created or changed
1163      * by a script; otherwise the location of the element in the document.
1164      */
1165     private static Violation inlineViolation(final HtmlPage page, final FetchDirectiveKind directive,
1166             final String source, final DomElement element) {
1167         if (Context.getCurrentContext() != null) {
1168             final ScriptStackElement[] stack = new EvaluatorException("csp").getScriptStack();
1169             if (stack.length > 0) {
1170                 return new Violation(directive, BLOCKED_INLINE, source, element,
1171                         stack[0].fileName, Math.max(0, stack[0].lineNumber), 0);
1172             }
1173         }
1174         return new Violation(directive, BLOCKED_INLINE, source, element,
1175                 documentUrl(page), element.getStartLineNumber(), element.getStartColumnNumber());
1176     }
1177 
1178     /**
1179      * Returns the nonce of the element (the nonce slot, not the maybe hidden attribute);
1180      * empty if the element has no nonce or is not nonceable.
1181      */
1182     private static Optional<String> nonce(final DomElement element) {
1183         String nonce = element.getNonce();
1184         final SgmlPage page = element.getPage();
1185         if (page != null && page.getWebClient().getBrowserVersion().hasFeature(CSP_NONCE_TRIMMED)) {
1186             nonce = nonce.trim();
1187         }
1188         if (nonce.isEmpty() || !isNonceable(element)) {
1189             return Optional.empty();
1190         }
1191         return Optional.of(nonce);
1192     }
1193 
1194     /**
1195      * Spec 'is element nonceable': elements with an attribute name or value containing
1196      * '&lt;script' or '&lt;style' are not nonceable (protection against dangling markup).
1197      */
1198     private static boolean isNonceable(final DomElement element) {
1199         for (final DomAttr attr : element.getAttributesMap().values()) {
1200             if (containsScriptOrStyle(attr.getName()) || containsScriptOrStyle(attr.getValue())) {
1201                 return false;
1202             }
1203         }
1204         return true;
1205     }
1206 
1207     private static boolean containsScriptOrStyle(final String value) {
1208         final String lower = value.toLowerCase(Locale.ROOT);
1209         return lower.contains("<script") || lower.contains("<style");
1210     }
1211 
1212     /**
1213      * Nonce hiding: if the page has a policy delivered by a header, the nonce attribute of
1214      * an element added to the page is replaced by an empty string (the nonce IDL attribute
1215      * still returns the nonce). Firefox does this only for enforced policies.
1216      *
1217      * @param element the element added to the page
1218      */
1219     public static void hideNonceIfNeeded(final DomElement element) {
1220         final HtmlPage page = element.getHtmlPageOrNull();
1221         if (page == null) {
1222             return;
1223         }
1224         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
1225         if (csp == null) {
1226             return;
1227         }
1228         if (csp.enforced_.isEmpty()
1229                 && (csp.reportOnly_.isEmpty()
1230                         || page.getWebClient().getBrowserVersion().hasFeature(CSP_NONCE_HIDING_ENFORCED_ONLY))) {
1231             return;
1232         }
1233 
1234         final String nonce = element.getAttributeDirect(DomElement.NONCE_ATTRIBUTE);
1235         if (ATTRIBUTE_NOT_DEFINED == nonce || nonce.isEmpty()) {
1236             return;
1237         }
1238         element.hideNonce();
1239     }
1240 
1241     /**
1242      * Elements created by the parser have a line number; elements created by
1243      * JavaScript (e.g. document.createElement()) have no line number.
1244      */
1245     private static boolean isParserInserted(final DomElement element) {
1246         return element.getStartLineNumber() != -1;
1247     }
1248 
1249     private static String documentUrl(final HtmlPage page) {
1250         return withoutRef(page.getUrl());
1251     }
1252 
1253     private static String withoutRef(final URL url) {
1254         final String externalForm = url.toExternalForm();
1255         final int hashPos = externalForm.indexOf('#');
1256         if (hashPos == -1) {
1257             return externalForm;
1258         }
1259         return externalForm.substring(0, hashPos);
1260     }
1261 
1262     /**
1263      * Converts the given url into the url representation used by the csp library
1264      * (htmlunit-csp) to match the url against the source expressions of a policy.
1265      * <ul>
1266      *   <li>Urls with a host (e.g. http, https, ws, wss) are converted into a
1267      *       {@link URI} made of the scheme and the host (both lower case), the port
1268      *       (the default port of the scheme if the url has no explicit port) and the path; the query
1269      *       and the fragment are not part of the result. Host sources (e.g. {@code https://example.com/api/})
1270      *       and 'self' are matched against these parts.</li>
1271      *   <li>Urls without a host (e.g. data:, blob:, about:, file:///) are converted into a
1272      *       {@link GUID} made of the scheme (lower case) and the remaining part
1273      *       of the url; such urls are only matched by a scheme source (e.g. {@code data:}),
1274      *       never by 'self', a host source or {@code *}.</li>
1275      * </ul>
1276      * The result is the same as the one of {@link URI#parseURI(String)} or
1277      * {@link GUID#parseGUID(String)}, but without parsing the url again.
1278      *
1279      * @param url the url to convert
1280      * @return the converted url
1281      */
1282     static URLWithScheme toUrlWithScheme(final URL url) {
1283         final String scheme = url.getProtocol().toLowerCase(Locale.ROOT);
1284         final String host = url.getHost();
1285         if (host == null || host.isEmpty()) {
1286             final String externalForm = url.toExternalForm();
1287             return new GUID(scheme, externalForm.substring(externalForm.indexOf(':') + 1));
1288         }
1289 
1290         int port = url.getPort();
1291         if (port == -1) {
1292             port = URI.defaultPortForProtocol(scheme);
1293         }
1294         return new URI(scheme, host.toLowerCase(Locale.ROOT), port, url.getPath());
1295     }
1296 
1297     /**
1298      * Returns whether the url is the target of a redirect; the checks for redirects are called
1299      * with the redirect target as url and the url of the initial request as reported url.
1300      * Like the browsers, the path part of the source expressions is ignored for redirects.
1301      */
1302     private static boolean isRedirect(final URL url, final URL reportedUrl) {
1303         return !url.toExternalForm().equals(reportedUrl.toExternalForm());
1304     }
1305 
1306     /**
1307      * Returns the blockedURI reported for the given url; like in browsers only the scheme
1308      * is reported for urls without host (e.g. data:).
1309      */
1310     private static String blockedUri(final URL url) {
1311         final String host = url.getHost();
1312         if (host == null || host.isEmpty()) {
1313             return url.getProtocol();
1314         }
1315         return withoutRef(url);
1316     }
1317 
1318     /**
1319      * The blocked uri reported for navigations (e.g. frames); like Chrome
1320      * <ul>
1321      *   <li>urls without host (e.g. data:) are reported as empty string</li>
1322      *   <li>cross origin urls are reported as origin (without path)</li>
1323      *   <li>same origin urls are reported without the fragment</li>
1324      * </ul>
1325      */
1326     private static String navigationBlockedUri(final HtmlPage page, final URL url) {
1327         final String host = url.getHost();
1328         if (host == null || host.isEmpty()) {
1329             return "";
1330         }
1331         if (UrlUtils.isSameOrigin(selfUrl(page), url)) {
1332             return withoutRef(url);
1333         }
1334 
1335         final String protocol = url.getProtocol();
1336         final int port = url.getPort();
1337         if (port == -1 || port == url.getDefaultPort()) {
1338             return protocol + "://" + host;
1339         }
1340         return protocol + "://" + host + ":" + port;
1341     }
1342 
1343     /**
1344      * The blocked uri reported for objects (object-src); like the browsers.
1345      * <ul>
1346      *   <li>urls without host (e.g. data:) are reported as scheme</li>
1347      *   <li>cross origin urls are reported as origin (without path)</li>
1348      *   <li>same origin urls are reported without the fragment</li>
1349      * </ul>
1350      */
1351     private static String objectBlockedUri(final HtmlPage page, final URL url) {
1352         final String host = url.getHost();
1353         if (host == null || host.isEmpty()) {
1354             return url.getProtocol();
1355         }
1356         return navigationBlockedUri(page, url);
1357     }
1358 
1359     private static Optional<URI> origin(final HtmlPage page) {
1360         return URI.parseURI(selfUrl(page).toExternalForm());
1361     }
1362 
1363     /**
1364      * Returns the url used for 'self'; for inherited policies the url of the creator.
1365      */
1366     private static URL selfUrl(final HtmlPage page) {
1367         final ContentSecurityPolicy csp = page.getContentSecurityPolicy();
1368         if (csp != null && csp.selfUrl_ != null) {
1369             return csp.selfUrl_;
1370         }
1371         return page.getUrl();
1372     }
1373 
1374     /**
1375      * The details of a violation.
1376      */
1377     private static final class Violation {
1378         private final FetchDirectiveKind directive_;
1379         private final String effectiveDirective_;
1380         private final String blockedUri_;
1381         private final String source_;
1382         private final DomElement target_;
1383         private final String sourceFile_;
1384         private final int lineNumber_;
1385         private final int columnNumber_;
1386 
1387         Violation(final FetchDirectiveKind directive, final String blockedUri, final String source,
1388                 final DomElement target, final String sourceFile, final int lineNumber, final int columnNumber) {
1389             directive_ = directive;
1390             effectiveDirective_ = directive.getRepr();
1391             blockedUri_ = blockedUri;
1392             source_ = source;
1393             target_ = target;
1394             sourceFile_ = sourceFile;
1395             lineNumber_ = lineNumber;
1396             columnNumber_ = columnNumber;
1397         }
1398 
1399         /**
1400          * Ctor for violations of directives that are no fetch directives (e.g. form-action).
1401          */
1402         Violation(final String effectiveDirective, final String blockedUri, final String source,
1403                 final DomElement target, final String sourceFile, final int lineNumber, final int columnNumber) {
1404             directive_ = null;
1405             effectiveDirective_ = effectiveDirective;
1406             blockedUri_ = blockedUri;
1407             source_ = source;
1408             target_ = target;
1409             sourceFile_ = sourceFile;
1410             lineNumber_ = lineNumber;
1411             columnNumber_ = columnNumber;
1412         }
1413     }
1414 }