Class Policy

java.lang.Object
org.htmlunit.csp.Policy

public final class Policy extends Object
Represents a single parsed Content Security Policy.

A Policy is created by parsing a serialized CSP string via parseSerializedCSP(String, PolicyErrorConsumer) or by parsing a comma-separated list of policies via parseSerializedCSPList(String, PolicyListErrorConsumer).

The class preserves the original case, order, duplicate directives, unrecognized directives, and unrecognized values to support round-tripping. Whitespace and empty directives/policies are not preserved.

High-level query methods such as allowsExternalScript(java.util.Optional<java.lang.String>, java.util.Optional<java.lang.String>, java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>, java.util.Optional<java.lang.Boolean>, java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>) and allowsInlineScript(java.util.Optional<java.lang.String>, java.util.Optional<java.lang.String>, java.util.Optional<java.lang.Boolean>) implement the matching algorithms defined in the CSP specification.

See Also:
  • Method Details

    • parseSerializedCSPList

      public static PolicyList parseSerializedCSPList(String serialized, Policy.PolicyListErrorConsumer policyListErrorConsumer)
      Parses a serialized CSP list (comma-separated policies) into a PolicyList.

      Implements the parse a serialized CSP list algorithm. The input must be an ASCII string. Empty policies (those that contain no directives) are omitted from the resulting list.

      Parameters:
      serialized - the comma-separated serialized CSP list to parse
      policyListErrorConsumer - a consumer that receives any errors or warnings encountered during parsing
      Returns:
      the parsed PolicyList
      Throws:
      IllegalArgumentException - if serialized contains non-ASCII characters
    • parseSerializedCSP

      public static Policy parseSerializedCSP(String serialized, Policy.PolicyErrorConsumer policyErrorConsumer)
      Parses a single serialized CSP string into a Policy.

      Implements the parse a serialized CSP algorithm. The input must be an ASCII string and must not contain commas; for comma-separated CSP lists use parseSerializedCSPList(String, PolicyListErrorConsumer).

      Parameters:
      serialized - the serialized CSP string to parse (must not contain commas)
      policyErrorConsumer - a consumer that receives any errors or warnings encountered during parsing
      Returns:
      the parsed Policy
      Throws:
      IllegalArgumentException - if serialized contains non-ASCII characters or contains a comma
    • toString

      public String toString()
      Serializes this policy back to its string representation.

      Directives are separated by "; ". The original case, order, and values (including duplicates and unrecognized entries) are preserved.

      Overrides:
      toString in class Object
      Returns:
      the serialized CSP string
    • baseUri

      Returns the parsed base-uri directive, if present.
      Returns:
      an Optional containing the SourceExpressionDirective for base-uri, or empty if the directive was not specified
      See Also:
    • blockAllMixedContent

      public boolean blockAllMixedContent()
      Returns whether the block-all-mixed-content directive is present.
      Returns:
      true if the policy contains the block-all-mixed-content directive
      See Also:
    • formAction

      public Optional<SourceExpressionDirective> formAction()
      Returns the parsed form-action directive, if present.
      Returns:
      an Optional containing the SourceExpressionDirective for form-action, or empty if the directive was not specified
      See Also:
    • frameAncestors

      public Optional<FrameAncestorsDirective> frameAncestors()
      Returns the parsed frame-ancestors directive, if present.
      Returns:
      an Optional containing the FrameAncestorsDirective, or empty if the directive was not specified
      See Also:
    • pluginTypes

      public Optional<PluginTypesDirective> pluginTypes()
      Returns the parsed plugin-types directive, if present.

      Note: the plugin-types directive has been deprecated.

      Returns:
      an Optional containing the PluginTypesDirective, or empty if the directive was not specified
    • reportTo

      public Optional<RFC7230Token> reportTo()
      Returns the parsed report-to directive value, if present.
      Returns:
      an Optional containing the RFC7230Token representing the report-to group name, or empty if the directive was not specified
      See Also:
    • reportUri

      public Optional<ReportUriDirective> reportUri()
      Returns the parsed report-uri directive, if present.

      Note: the report-uri directive has been deprecated in favor of report-to.

      Returns:
      an Optional containing the ReportUriDirective, or empty if the directive was not specified
      See Also:
    • sandbox

      public Optional<SandboxDirective> sandbox()
      Returns the parsed sandbox directive, if present.
      Returns:
      an Optional containing the SandboxDirective, or empty if the directive was not specified
      See Also:
    • trustedTypes

      public Optional<TrustedTypesDirective> trustedTypes()
      Returns the parsed trusted-types directive, if present.
      Returns:
      an Optional containing the TrustedTypesDirective, or empty if the directive was not specified
      See Also:
    • allowsWildcardPolicyNames

      public boolean allowsWildcardPolicyNames()
      Indicates if wildcard policy names are permitted in the trusted-types directive. When true, any policy name is allowed, which may reduce security.
      Returns:
      true if wildcard policy names (*) are permitted, false if not present or not permitted
    • requireTrustedTypesFor

      public Optional<RequireTrustedTypesForDirective> requireTrustedTypesFor()
      Returns the parsed require-trusted-types-for directive, if present.
      Returns:
      an Optional containing the RequireTrustedTypesForDirective, or empty if the directive was not specified
      See Also:
    • upgradeInsecureRequests

      public boolean upgradeInsecureRequests()
      Returns whether the upgrade-insecure-requests directive is present.
      Returns:
      true if the policy contains the upgrade-insecure-requests directive
      See Also:
    • getFetchDirective

      public Optional<SourceExpressionDirective> getFetchDirective(FetchDirectiveKind kind)
      Returns the parsed fetch directive of the specified kind, if present.

      Fetch directives include default-src, script-src, style-src, img-src, font-src, connect-src, media-src, object-src, frame-src, child-src, worker-src, manifest-src, and their -elem / -attr variants.

      Parameters:
      kind - the FetchDirectiveKind to look up
      Returns:
      an Optional containing the SourceExpressionDirective for the requested fetch directive, or empty if not present
    • allowsExternalScript

      public boolean allowsExternalScript(Optional<String> nonce, Optional<String> integrity, Optional<? extends URLWithScheme> scriptUrl, Optional<Boolean> parserInserted, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading an external script.

      For each argument, if the value provided is Optional.empty(), this method returns true only if there is no value for the Optional.of() case of that parameter which would cause it to return false.

      Take care with integrity: a script can be allowed by CSP but blocked by Subresource Integrity if its integrity is wrong. Also note that "the URL" is somewhat fuzzy because of redirects.

      Parameters:
      nonce - the nonce attribute value of the script element, if any
      integrity - the integrity attribute value (SRI metadata), if any
      scriptUrl - the URL of the external script, if known
      parserInserted - whether the script element is parser-inserted; Optional.empty() if unknown
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the external script
      See Also:
    • allowsInlineScript

      public boolean allowsInlineScript(Optional<String> nonce, Optional<String> source, Optional<Boolean> parserInserted)
      Determines whether this policy allows an inline <script> element.
      Parameters:
      nonce - the nonce attribute value of the script element, if any
      source - the text content of the inline script, if known (used for hash matching)
      parserInserted - whether the script element is parser-inserted; Optional.empty() if unknown
      Returns:
      true if this policy allows the inline script
      See Also:
    • allowsScriptAsAttribute

      public boolean allowsScriptAsAttribute(Optional<String> source)
      Determines whether this policy allows a script provided as an inline event handler attribute (e.g. onclick).
      Parameters:
      source - the text content of the event handler attribute, if known (used for hash matching with 'unsafe-hashes')
      Returns:
      true if this policy allows the script attribute
      See Also:
    • allowsEval

      public boolean allowsEval()
      Determines whether this policy allows the use of eval() and similar string-to-code mechanisms.

      The governing directive is script-src if present, otherwise default-src. Returns true if no governing directive is present or if the governing directive includes 'unsafe-eval'.

      Returns:
      true if this policy allows eval
      See Also:
    • allowsNavigation

      public boolean allowsNavigation(Optional<? extends URLWithScheme> to, Optional<Boolean> redirected, Optional<? extends URLWithScheme> redirectedTo, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows a navigation to the given URL.

      This checks the navigate-to directive. If the directive is not present, navigation is allowed. This does not handle javascript: URL navigation; use allowsJavascriptUrlNavigation(java.util.Optional<java.lang.String>, java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>) for that.

      It is nonsensical to provide redirectedTo if redirected is Optional.of(false).

      Parameters:
      to - the initial navigation target URL, if known
      redirected - whether the navigation is a redirect; Optional.empty() if unknown
      redirectedTo - the final URL after redirect, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the navigation
      See Also:
    • allowsFormAction

      public boolean allowsFormAction(Optional<? extends URLWithScheme> to, Optional<Boolean> redirected, Optional<? extends URLWithScheme> redirectedTo, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows a form submission to the given URL.

      This checks the form-action directive first; if absent, falls back to the navigate-to directive via allowsNavigation(java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>, java.util.Optional<java.lang.Boolean>, java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>, java.util.Optional<? extends org.htmlunit.csp.url.URLWithScheme>). If the sandbox directive is present and does not include allow-forms, form submission is blocked.

      Parameters:
      to - the form action target URL, if known
      redirected - whether the form submission results in a redirect; Optional.empty() if unknown
      redirectedTo - the final URL after redirect, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the form action
      See Also:
    • allowsJavascriptUrlNavigation

      public boolean allowsJavascriptUrlNavigation(Optional<String> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows a javascript: URL navigation.

      The hashes (for 'unsafe-hashes') are expected to include the javascript: prefix per the specification.

      Parameters:
      source - the JavaScript source code after the javascript: prefix, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the javascript: URL navigation
    • allowsExternalStyle

      public boolean allowsExternalStyle(Optional<String> nonce, Optional<? extends URLWithScheme> styleUrl, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading an external stylesheet.

      The effective directive is style-src-elem per the effective directive for a request algorithm. Integrity is not checked for stylesheets per w3c/webappsec-csp#430.

      Parameters:
      nonce - the nonce attribute value of the link element, if any
      styleUrl - the URL of the external stylesheet, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the external style
    • allowsInlineStyle

      public boolean allowsInlineStyle(Optional<String> nonce, Optional<String> source)
      Determines whether this policy allows an inline <style> element.
      Parameters:
      nonce - the nonce attribute value of the style element, if any
      source - the text content of the inline style, if known (used for hash matching)
      Returns:
      true if this policy allows the inline style
    • allowsStyleAsAttribute

      public boolean allowsStyleAsAttribute(Optional<String> source)
      Determines whether this policy allows an inline style attribute (e.g. style="...").
      Parameters:
      source - the text content of the style attribute, if known (used for hash matching with 'unsafe-hashes')
      Returns:
      true if this policy allows the style attribute
    • allowsFrame

      public boolean allowsFrame(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading a frame (iframe/frame) from the given source.

      Uses the frame-src effective directive with its fallback chain.

      Parameters:
      source - the URL of the framed resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the frame
    • allowsFrameAncestor

      public boolean allowsFrameAncestor(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows being framed by the given ancestor origin.

      Checks the frame-ancestors directive. If not present, all ancestors are allowed.

      Parameters:
      source - the URL of the ancestor frame, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the frame ancestor
      See Also:
    • allowsConnection

      public boolean allowsConnection(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows a connection (e.g. fetch(), XMLHttpRequest, WebSocket) to the given source.

      For ws: and wss: URLs (when using new WebSocket), the scheme is mapped to http: / https: respectively for matching, per the WebSocket establish algorithm.

      Parameters:
      source - the URL to connect to, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the connection
    • allowsFont

      public boolean allowsFont(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading a font from the given source.
      Parameters:
      source - the URL of the font resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the font
    • allowsImage

      public boolean allowsImage(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading an image from the given source.
      Parameters:
      source - the URL of the image resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the image
    • allowsApplicationManifest

      public boolean allowsApplicationManifest(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading an application manifest from the given source.
      Parameters:
      source - the URL of the manifest resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the manifest
    • allowsMedia

      public boolean allowsMedia(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading media (audio/video) from the given source.
      Parameters:
      source - the URL of the media resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the media
    • allowsObject

      public boolean allowsObject(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading an object/embed/applet from the given source.
      Parameters:
      source - the URL of the object resource, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the object
    • allowsPrefetch

      public boolean allowsPrefetch(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows a prefetch from the given source.

      Note: the prefetch-src directive is not properly spec'd. See whatwg/fetch#1008.

      Parameters:
      source - the URL to prefetch, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the prefetch
    • allowsWorker

      public boolean allowsWorker(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin)
      Determines whether this policy allows loading a worker (dedicated, shared, or service) from the given source.
      Parameters:
      source - the URL of the worker script, if known
      origin - the origin of the protected resource, if known
      Returns:
      true if this policy allows the worker
    • allowsPlugin

      public boolean allowsPlugin(Optional<? extends MediaType> mediaType)
      Determines whether this policy allows a plugin of the given media type.

      Checks the (deprecated) plugin-types directive. If not present, all plugin types are allowed.

      Parameters:
      mediaType - the media type of the plugin, if known
      Returns:
      true if this policy allows the plugin type
    • getGoverningDirectiveForEffectiveDirective

      public Optional<SourceExpressionDirective> getGoverningDirectiveForEffectiveDirective(FetchDirectiveKind kind)
      Returns the governing directive for the given effective fetch directive kind, walking the fallback chain as defined in the specification.

      For example, if script-src-elem is not present, this falls back to script-src, then to default-src.

      Parameters:
      kind - the effective FetchDirectiveKind to resolve
      Returns:
      an Optional containing the governing SourceExpressionDirective, or empty if no directive in the fallback chain is present
      See Also:
    • doesUrlMatchSourceListInOrigin

      public static boolean doesUrlMatchSourceListInOrigin(URLWithScheme url, HostSourceDirective list, Optional<? extends URLWithScheme> origin)
      Determines whether a URL matches a source list in the context of a given origin.

      Implements the match a URL to a source list algorithm. This checks wildcards (*), scheme sources, host sources, and the 'self' keyword against the provided URL.

      Parameters:
      url - the URL to check
      list - the host-source directive (source list) to match against
      origin - the origin of the protected resource, if known
      Returns:
      true if the URL matches the source list