- All Implemented Interfaces:
CspQueries
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.
- Author:
- Ronald Brill, Rick Mitchell, Salvation Team
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceA callback interface for receiving errors and warnings encountered while parsing a single serialized CSP.static interfaceA callback interface for receiving errors and warnings encountered while parsing a serialized CSP list (comma-separated policies).static enumThe severity level of a parsing error or warning. -
Method Summary
Modifier and TypeMethodDescriptionbooleanallowsApplicationManifest(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading an application manifest from the given source.booleanallowsConnection(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows a connection (e.g.booleanDetermines whether this policy allows the use ofeval()and similar string-to-code mechanisms.booleanallowsExternalScript(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.booleanallowsExternalStyle(Optional<String> nonce, Optional<? extends URLWithScheme> styleUrl, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading an external stylesheet.booleanallowsFont(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading a font from the given source.booleanallowsFormAction(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.booleanallowsFrame(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading a frame (iframe/frame) from the given source.booleanallowsFrameAncestor(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows being framed by the given ancestor origin.booleanallowsImage(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading an image from the given source.booleanallowsInlineScript(Optional<String> nonce, Optional<String> source, Optional<Boolean> parserInserted) Determines whether this policy allows an inline<script>element.booleanallowsInlineStyle(Optional<String> nonce, Optional<String> source) Determines whether this policy allows an inline<style>element.booleanallowsJavascriptUrlNavigation(Optional<String> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows ajavascript:URL navigation.booleanallowsMedia(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading media (audio/video) from the given source.booleanallowsNavigation(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.booleanallowsObject(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading an object/embed/applet from the given source.booleanallowsPlugin(Optional<? extends MediaType> mediaType) Determines whether this policy allows a plugin of the given media type.booleanallowsPrefetch(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows a prefetch from the given source.booleanallowsScriptAsAttribute(Optional<String> source) Determines whether this policy allows a script provided as an inline event handler attribute (e.g.booleanallowsStyleAsAttribute(Optional<String> source) Determines whether this policy allows an inline style attribute (e.g.booleanIndicates if wildcard policy names are permitted in the trusted-types directive.booleanallowsWorker(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading a worker (dedicated, shared, or service) from the given source.baseUri()Returns the parsedbase-uridirective, if present.booleanReturns whether theblock-all-mixed-contentdirective is present.booleanReturns whether this policy was parsed as delivered via ametaelement.static booleandoesUrlMatchSourceListInOrigin(URLWithScheme url, HostSourceDirective list, Optional<? extends URLWithScheme> origin) Determines whether a URL matches a source list in the context of a given origin.Returns the parsedform-actiondirective, if present.Returns the parsedframe-ancestorsdirective, if present.Returns the parsed fetch directive of the specified kind, if present.Returns the governing directive for the given effective fetch directive kind, walking the fallback chain as defined in the specification.Returns the parsednavigate-todirective, if present.static PolicyparseSerializedCSP(String serialized, Policy.PolicyErrorConsumer policyErrorConsumer) Parses a single serialized CSP string into aPolicy.static PolicyparseSerializedCSP(String serialized, Policy.PolicyErrorConsumer policyErrorConsumer, boolean deliveredViaMeta) Parses a single serialized CSP string into aPolicy.static PolicyListparseSerializedCSPList(String serialized, Policy.PolicyListErrorConsumer policyListErrorConsumer) Parses a serialized CSP list (comma-separated policies) into aPolicyList.Returns the parsedplugin-typesdirective, if present.reportTo()Returns the parsedreport-todirective value, if present.Returns the parsedreport-uridirective, if present.Returns the parsedrequire-trusted-types-fordirective, if present.sandbox()Returns the parsedsandboxdirective, if present.toString()Serializes this policy back to its string representation.Returns the parsedtrusted-typesdirective, if present.booleanReturns whether theupgrade-insecure-requestsdirective is present.
-
Method Details
-
parseSerializedCSPList
public static PolicyList parseSerializedCSPList(String serialized, Policy.PolicyListErrorConsumer policyListErrorConsumer) Parses a serialized CSP list (comma-separated policies) into aPolicyList.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 parsepolicyListErrorConsumer- a consumer that receives any errors or warnings encountered during parsing- Returns:
- the parsed
PolicyList - Throws:
IllegalArgumentException- ifserializedcontains non-ASCII characters
-
parseSerializedCSP
public static Policy parseSerializedCSP(String serialized, Policy.PolicyErrorConsumer policyErrorConsumer) Parses a single serialized CSP string into aPolicy.Equivalent to
parseSerializedCSP(String, PolicyErrorConsumer, boolean)withdeliveredViaMetaset tofalse.- 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- ifserializedcontains non-ASCII characters or contains a comma
-
parseSerializedCSP
public static Policy parseSerializedCSP(String serialized, Policy.PolicyErrorConsumer policyErrorConsumer, boolean deliveredViaMeta) Parses a single serialized CSP string into aPolicy.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).When
deliveredViaMetaistrue, warnings are emitted forframe-ancestors,sandbox, andreport-uri, which are ignored when a policy is delivered via ametaelement.- Parameters:
serialized- the serialized CSP string to parse (must not contain commas)policyErrorConsumer- a consumer that receives any errors or warnings encountered during parsingdeliveredViaMeta-trueif the policy was delivered via ametaelement rather than an HTTP header- Returns:
- the parsed
Policy - Throws:
IllegalArgumentException- ifserializedcontains non-ASCII characters or contains a comma- Since:
- 5.4.0
- See Also:
-
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. -
baseUri
Returns the parsedbase-uridirective, if present.- Returns:
- an
Optionalcontaining theSourceExpressionDirectiveforbase-uri, or empty if the directive was not specified - See Also:
-
blockAllMixedContent
public boolean blockAllMixedContent()Returns whether theblock-all-mixed-contentdirective is present.- Returns:
trueif the policy contains theblock-all-mixed-contentdirective- See Also:
-
deliveredViaMeta
public boolean deliveredViaMeta()Returns whether this policy was parsed as delivered via ametaelement.When
true,frame-ancestors,sandbox, andreport-uristill appear in getters for analysis, butallows*methods ignoreframe-ancestorsandsandbox(matching browser enforce after the HTML meta algorithm strips those directives).- Returns:
trueifparseSerializedCSP(String, PolicyErrorConsumer, boolean)was called withdeliveredViaMetaset totrue- Since:
- 5.4.0
- See Also:
-
formAction
Returns the parsedform-actiondirective, if present.- Returns:
- an
Optionalcontaining theSourceExpressionDirectiveforform-action, or empty if the directive was not specified - See Also:
-
frameAncestors
Returns the parsedframe-ancestorsdirective, if present.- Returns:
- an
Optionalcontaining theFrameAncestorsDirective, or empty if the directive was not specified - See Also:
-
pluginTypes
Returns the parsedplugin-typesdirective, if present.Note: the
plugin-typesdirective has been deprecated.- Returns:
- an
Optionalcontaining thePluginTypesDirective, or empty if the directive was not specified
-
reportTo
Returns the parsedreport-todirective value, if present.- Returns:
- an
Optionalcontaining theRFC7230Tokenrepresenting the report-to group name, or empty if the directive was not specified - See Also:
-
reportUri
Returns the parsedreport-uridirective, if present.Note: the
report-uridirective has been deprecated in favor ofreport-to.- Returns:
- an
Optionalcontaining theReportUriDirective, or empty if the directive was not specified - See Also:
-
sandbox
Returns the parsedsandboxdirective, if present.- Returns:
- an
Optionalcontaining theSandboxDirective, or empty if the directive was not specified - See Also:
-
trustedTypes
Returns the parsedtrusted-typesdirective, if present.- Returns:
- an
Optionalcontaining theTrustedTypesDirective, 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
Returns the parsedrequire-trusted-types-fordirective, if present.- Returns:
- an
Optionalcontaining theRequireTrustedTypesForDirective, or empty if the directive was not specified - See Also:
-
upgradeInsecureRequests
public boolean upgradeInsecureRequests()Returns whether theupgrade-insecure-requestsdirective is present.- Returns:
trueif the policy contains theupgrade-insecure-requestsdirective- See Also:
-
getFetchDirective
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/-attrvariants.- Parameters:
kind- theFetchDirectiveKindto look up- Returns:
- an
Optionalcontaining theSourceExpressionDirectivefor 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 returnstrueonly if there is no value for theOptional.of()case of that parameter which would cause it to returnfalse.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.- Specified by:
allowsExternalScriptin interfaceCspQueries- Parameters:
nonce- the nonce attribute value of the script element, if anyintegrity- the integrity attribute value (SRI metadata), if anyscriptUrl- the URL of the external script, if knownparserInserted- whether the script element is parser-inserted;Optional.empty()if unknownorigin- the origin of the protected resource, if known- Returns:
trueif 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.- Specified by:
allowsInlineScriptin interfaceCspQueries- Parameters:
nonce- the nonce attribute value of the script element, if anysource- 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:
trueif this policy allows the inline script- See Also:
-
allowsScriptAsAttribute
Determines whether this policy allows a script provided as an inline event handler attribute (e.g.onclick).- Specified by:
allowsScriptAsAttributein interfaceCspQueries- Parameters:
source- the text content of the event handler attribute, if known (used for hash matching with'unsafe-hashes')- Returns:
trueif this policy allows the script attribute- See Also:
-
allowsEval
public boolean allowsEval()Determines whether this policy allows the use ofeval()and similar string-to-code mechanisms.The governing directive is
script-srcif present, otherwisedefault-src. Returnstrueif no governing directive is present or if the governing directive includes'unsafe-eval'.- Specified by:
allowsEvalin interfaceCspQueries- Returns:
trueif this policy allows eval- 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-actiondirective first; if absent, falls back to thenavigate-todirective viaallowsNavigation(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 includeallow-forms, form submission is blocked.- Specified by:
allowsFormActionin interfaceCspQueries- Parameters:
to- the form action target URL, if knownredirected- whether the form submission results in a redirect;Optional.empty()if unknownredirectedTo- the final URL after redirect, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the form action- See Also:
-
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-elemper the effective directive for a request algorithm. Integrity is not checked for stylesheets per w3c/webappsec-csp#430.- Specified by:
allowsExternalStylein interfaceCspQueries- Parameters:
nonce- the nonce attribute value of the link element, if anystyleUrl- the URL of the external stylesheet, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the external style- See Also:
-
allowsInlineStyle
Determines whether this policy allows an inline<style>element.- Specified by:
allowsInlineStylein interfaceCspQueries- Parameters:
nonce- the nonce attribute value of the style element, if anysource- the text content of the inline style, if known (used for hash matching)- Returns:
trueif this policy allows the inline style- See Also:
-
allowsStyleAsAttribute
Determines whether this policy allows an inline style attribute (e.g.style="...").- Specified by:
allowsStyleAsAttributein interfaceCspQueries- Parameters:
source- the text content of the style attribute, if known (used for hash matching with'unsafe-hashes')- Returns:
trueif this policy allows the style attribute- See Also:
-
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-srceffective directive with its fallback chain.- Specified by:
allowsFramein interfaceCspQueries- Parameters:
source- the URL of the framed resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the frame- See Also:
-
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-ancestorsdirective. If not present, or if this policy was delivered via meta (whereframe-ancestorsis ignored), all ancestors are allowed.- Specified by:
allowsFrameAncestorin interfaceCspQueries- Parameters:
source- the URL of the ancestor frame, if knownorigin- the origin of the protected resource, if known- Returns:
trueif 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:andwss:URLs (when usingnew WebSocket), the scheme is mapped tohttp:/https:respectively for matching, per the WebSocket establish algorithm.- Specified by:
allowsConnectionin interfaceCspQueries- Parameters:
source- the URL to connect to, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the connection- See Also:
-
allowsFont
public boolean allowsFont(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading a font from the given source.- Specified by:
allowsFontin interfaceCspQueries- Parameters:
source- the URL of the font resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the font- See Also:
-
allowsImage
public boolean allowsImage(Optional<? extends URLWithScheme> source, Optional<? extends URLWithScheme> origin) Determines whether this policy allows loading an image from the given source.- Specified by:
allowsImagein interfaceCspQueries- Parameters:
source- the URL of the image resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the image- See Also:
-
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.- Specified by:
allowsApplicationManifestin interfaceCspQueries- Parameters:
source- the URL of the manifest resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the manifest- See Also:
-
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.- Specified by:
allowsMediain interfaceCspQueries- Parameters:
source- the URL of the media resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the media- See Also:
-
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.- Specified by:
allowsObjectin interfaceCspQueries- Parameters:
source- the URL of the object resource, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the object- See Also:
-
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-srcdirective is not properly spec'd. See whatwg/fetch#1008.- Specified by:
allowsPrefetchin interfaceCspQueries- Parameters:
source- the URL to prefetch, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the prefetch- See Also:
-
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.- Specified by:
allowsWorkerin interfaceCspQueries- Parameters:
source- the URL of the worker script, if knownorigin- the origin of the protected resource, if known- Returns:
trueif this policy allows the worker- See Also:
-
allowsPlugin
Determines whether this policy allows a plugin of the given media type.Checks the (deprecated)
plugin-typesdirective. If not present, all plugin types are allowed.- Specified by:
allowsPluginin interfaceCspQueries- Parameters:
mediaType- the media type of the plugin, if known- Returns:
trueif this policy allows the plugin type- See Also:
-
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-elemis not present, this falls back toscript-src, then todefault-src.- Parameters:
kind- the effectiveFetchDirectiveKindto resolve- Returns:
- an
Optionalcontaining the governingSourceExpressionDirective, 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 checklist- the host-source directive (source list) to match againstorigin- the origin of the protected resource, if known- Returns:
trueif the URL matches the source list
-