Class ContentSecurityPolicy

java.lang.Object
com.oorian.security.ContentSecurityPolicy

public class ContentSecurityPolicy extends Object
A fluent builder for constructing Content Security Policy (CSP) header values.

Content Security Policy is a security standard that helps prevent cross-site scripting (XSS), clickjacking, and other code injection attacks by specifying which content sources are allowed to be loaded by the browser. This class provides a type-safe, discoverable API for building CSP directives without manually constructing raw header strings.

Usage:


 ContentSecurityPolicy csp = new ContentSecurityPolicy();
 csp.addDefaultSrc(ContentSecurityPolicy.SELF);
 csp.addScriptSrc(ContentSecurityPolicy.SELF, "https://cdn.example.com");
 csp.addStyleSrc(ContentSecurityPolicy.SELF, ContentSecurityPolicy.UNSAFE_INLINE);
 csp.addImgSrc(ContentSecurityPolicy.SELF, "data:", "https:");
 csp.upgradeInsecureRequests();

 // Use with Head element
 head.setContentSecurityPolicy(csp);

 // Or get the raw header value
 String headerValue = csp.toString();
 // "default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; upgrade-insecure-requests"
 
Since:
2.0
Version:
1.0
Author:
Marvin P. Warble Jr.
  • Field Details

  • Constructor Details

    • ContentSecurityPolicy

      public ContentSecurityPolicy()
      Creates a new empty Content Security Policy builder.
  • Method Details

    • addDefaultSrc

      public ContentSecurityPolicy addDefaultSrc(String... sources)
      Adds sources to the default-src directive.

      The default-src directive serves as a fallback for other fetch directives. If a specific directive is not defined, the browser falls back to the value of default-src.

      Parameters:
      sources - one or more source expressions (e.g., SELF, domain URLs)
      Returns:
      this instance for method chaining
    • addScriptSrc

      public ContentSecurityPolicy addScriptSrc(String... sources)
      Adds sources to the script-src directive.

      Controls which scripts the browser is allowed to execute. This is one of the most important directives for preventing XSS attacks.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addStyleSrc

      public ContentSecurityPolicy addStyleSrc(String... sources)
      Adds sources to the style-src directive.

      Controls which stylesheets the browser is allowed to apply to the document.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addImgSrc

      public ContentSecurityPolicy addImgSrc(String... sources)
      Adds sources to the img-src directive.

      Controls which image sources the browser is allowed to load.

      Parameters:
      sources - one or more source expressions (e.g., SELF, "data:", "https:")
      Returns:
      this instance for method chaining
    • addFontSrc

      public ContentSecurityPolicy addFontSrc(String... sources)
      Adds sources to the font-src directive.

      Controls which font sources the browser is allowed to load.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addConnectSrc

      public ContentSecurityPolicy addConnectSrc(String... sources)
      Adds sources to the connect-src directive.

      Controls which URLs the browser is allowed to connect to via script interfaces such as XMLHttpRequest, WebSocket, fetch, and EventSource.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addMediaSrc

      public ContentSecurityPolicy addMediaSrc(String... sources)
      Adds sources to the media-src directive.

      Controls which media sources the browser is allowed to load for audio and video elements.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addObjectSrc

      public ContentSecurityPolicy addObjectSrc(String... sources)
      Adds sources to the object-src directive.

      Controls which plugin sources the browser is allowed to load for object, embed, and applet elements. Setting this to NONE is recommended for security.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addFrameSrc

      public ContentSecurityPolicy addFrameSrc(String... sources)
      Adds sources to the frame-src directive.

      Controls which URLs the browser is allowed to load in frames and iframes.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addChildSrc

      public ContentSecurityPolicy addChildSrc(String... sources)
      Adds sources to the child-src directive.

      Controls which URLs the browser is allowed to load for nested browsing contexts (frames) and worker execution contexts.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addWorkerSrc

      public ContentSecurityPolicy addWorkerSrc(String... sources)
      Adds sources to the worker-src directive.

      Controls which URLs the browser is allowed to load as Worker, SharedWorker, or ServiceWorker scripts.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addManifestSrc

      public ContentSecurityPolicy addManifestSrc(String... sources)
      Adds sources to the manifest-src directive.

      Controls which URLs the browser is allowed to load as application manifests.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addBaseUri

      public ContentSecurityPolicy addBaseUri(String... sources)
      Adds sources to the base-uri directive.

      Restricts the URLs that can be used in the document's <base> element. Setting this to SELF or NONE is recommended to prevent base tag injection attacks.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addFormAction

      public ContentSecurityPolicy addFormAction(String... sources)
      Adds sources to the form-action directive.

      Restricts which URLs can be used as the target of form submissions from the document.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addFrameAncestors

      public ContentSecurityPolicy addFrameAncestors(String... sources)
      Adds sources to the frame-ancestors directive.

      Specifies valid parents that may embed the page using <frame>, <iframe>, <object>, or <embed>. Setting this to NONE is equivalent to the X-Frame-Options: DENY header.

      Parameters:
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • addSandbox

      public ContentSecurityPolicy addSandbox(String... flags)
      Adds flags to the sandbox directive.

      Enables a sandbox for the document, similar to the <iframe sandbox> attribute. Sandbox flags control which features are allowed, such as "allow-scripts", "allow-forms", "allow-popups", etc. Calling this method with no arguments applies the strictest sandbox restrictions.

      Parameters:
      flags - zero or more sandbox flags (e.g., "allow-scripts", "allow-forms")
      Returns:
      this instance for method chaining
    • setReportUri

      public ContentSecurityPolicy setReportUri(String uri)
      Sets the report-uri directive.

      Specifies a URL to which the browser will send reports when the content security policy is violated. Note that report-uri is deprecated in favor of report-to, but is still widely supported by browsers.

      Parameters:
      uri - the URI to receive CSP violation reports
      Returns:
      this instance for method chaining
    • setReportTo

      public ContentSecurityPolicy setReportTo(String groupName)
      Sets the report-to directive.

      Specifies a reporting group name (defined via the Report-To HTTP header) to which the browser will send CSP violation reports.

      Parameters:
      groupName - the reporting group name
      Returns:
      this instance for method chaining
    • upgradeInsecureRequests

      public ContentSecurityPolicy upgradeInsecureRequests()
      Enables the upgrade-insecure-requests directive.

      Instructs the browser to treat all of the site's insecure URLs (HTTP) as though they have been replaced with secure URLs (HTTPS). This is intended for websites with large numbers of insecure legacy URLs that need to be rewritten.

      Returns:
      this instance for method chaining
    • addDirective

      public ContentSecurityPolicy addDirective(String directive, String... sources)
      Adds sources to a custom or future directive.

      This method provides an escape hatch for directives that are not covered by the typed methods, such as new or experimental directives. Calling this method multiple times for the same directive accumulates sources rather than replacing them.

      Parameters:
      directive - the directive name (e.g., "prefetch-src")
      sources - one or more source expressions
      Returns:
      this instance for method chaining
    • nonce

      public static String nonce(String value)
      Returns a nonce source expression for use in CSP directives.

      A nonce is a randomly generated value that allows specific inline scripts or styles to execute. The same nonce must be present in both the CSP header and the script/style element's nonce attribute.

      Parameters:
      value - the nonce value (should be a cryptographically random base64-encoded string)
      Returns:
      the formatted nonce expression (e.g., 'nonce-abc123')
    • sha256

      public static String sha256(String hash)
      Returns a SHA-256 hash source expression for use in CSP directives.

      Allows a specific inline script or style to execute by matching its SHA-256 hash. The hash should be the base64-encoded SHA-256 digest of the script or style content.

      Parameters:
      hash - the base64-encoded SHA-256 hash
      Returns:
      the formatted hash expression (e.g., 'sha256-abc123...')
    • sha384

      public static String sha384(String hash)
      Returns a SHA-384 hash source expression for use in CSP directives.

      Allows a specific inline script or style to execute by matching its SHA-384 hash. The hash should be the base64-encoded SHA-384 digest of the script or style content.

      Parameters:
      hash - the base64-encoded SHA-384 hash
      Returns:
      the formatted hash expression (e.g., 'sha384-abc123...')
    • sha512

      public static String sha512(String hash)
      Returns a SHA-512 hash source expression for use in CSP directives.

      Allows a specific inline script or style to execute by matching its SHA-512 hash. The hash should be the base64-encoded SHA-512 digest of the script or style content.

      Parameters:
      hash - the base64-encoded SHA-512 hash
      Returns:
      the formatted hash expression (e.g., 'sha512-abc123...')
    • toString

      public String toString()
      Returns the Content Security Policy as a formatted header value string.

      Produces a semicolon-separated string of all configured directives, suitable for use as the value of a Content-Security-Policy HTTP header or the content attribute of a <meta http-equiv="content-security-policy"> element.

      Overrides:
      toString in class Object
      Returns:
      the CSP header value string