Before Launch, Check CSP Rules for New URL Destinations

Check CSP URL sources before website launch with a report-only test, and review directives, redirects, subdomains, and ports before updating policy.

Published
Reading time
8 min read
Before Launch, Check CSP Rules for New URL Destinations
On this page

When a site adds a new destination, Content Security Policy (CSP) can affect some uses of that URL but not others. A link may open normally while an image, form submission, or API request to the same host triggers a CSP violation. This workflow shows how to check CSP URL sources before website launch without blindly broadening the production policy.

Key Takeaways

  • Match the destination to the directive for its use: img-src for images, script-src for scripts, connect-src for fetch requests, and form-action for form submissions.
  • Ordinary links are not controlled by default-src. Do not assume that adding a host there permits or blocks a link navigation.
  • Use a controlled page and a report-only policy to observe candidate violations before changing an enforced policy.
  • Check the complete redirect chain, hostname, scheme, and port. Add only the destinations each resource type actually needs.

First, identify what the URL does

CSP source expressions describe permitted sources for particular operations. The relevant directive depends on how the browser uses the URL, not just on the destination hostname.

UseDirective to investigateImportant distinction
External JavaScriptscript-srcControls script loading and execution under the policy.
Imageimg-srcApplies to image requests, not a click on a link to the same host.
fetch() or other script-initiated connectionsconnect-srcCSP permission does not replace the destination's CORS requirements.
Form submissionform-actionRestricts where forms can submit; it does not fall back to default-src.
Embedded frameframe-srcControls frames loaded by this page. It is different from frame-ancestors, which controls who may embed this page.
Ordinary link navigationDo not rely on default-srcA normal <a href> is not an image, script, or connection request governed by those directives. Other restrictions, including sandboxing, may still affect navigation.

For resource directives such as img-src, script-src, and connect-src, default-src can supply a fallback when a more specific directive is absent. Once a specific directive is present, changing default-src does not add sources to it. base-uri, which restricts URLs in a document's <base> element, also does not fall back to default-src.

CSP navigation-directive support can vary by browser. In particular, do not treat navigate-to as a dependable cross-browser control for ordinary links without checking the documentation and behavior of every browser you support.

Advertisement

Set up a controlled report-only test

Use a staging origin you administer and test destinations under your control. The names below use the reserved .test suffix as placeholders: replace them with real lab hostnames, provision valid HTTPS, and serve the referenced paths. Do not use customer data or credentials in this experiment.

The test page should be served with only this CSP header for the initial experiment. If another enforced CSP is present, it may block requests independently of the report-only policy. Remove such conflicts only in the isolated lab—not from production.

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self'; img-src 'self'; connect-src 'self'; form-action 'self'; frame-src 'self'; base-uri 'self'

A report-only policy records violations rather than enforcing that policy. This example relies on browser developer tools for investigation; it does not configure a remote report collector. Other browser security controls, network failures, and any separate enforced policy can still block a request.

Place these files on the same staging origin. For example, save the page as index.html and the script as csp-check.js in the same served directory:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CSP destination check</title>
  <script src="./csp-check.js" defer></script>
</head>
<body>
  <p><a href="https://shop.example.test/landing">Open the test landing page</a></p>

  <img src="https://assets.example.test/test.png" alt="Test asset">

  <form action="https://shop.example.test/search" method="get">
    <label>Test query <input name="q" value="csp-test"></label>
    <button type="submit">Submit test form</button>
  </form>

  <button id="check-api" type="button">Request test API</button>
</body>
</html>
// csp-check.js
const button = document.getElementById('check-api');

button.addEventListener('click', async () => {
  try {
    const response = await fetch('https://api.example.test/health', {
      credentials: 'omit'
    });
    console.log('API response status:', response.status);
  } catch (error) {
    console.error('API request failed:', error);
  }
});

Configure the API endpoint to allow the staging origin through CORS if you want JavaScript to read its response. The form endpoint should accept a harmless GET request. The image and API examples should not depend on cookies or sensitive data.

Inspect the results

  1. Open the page in each browser your launch supports. In developer tools, enable the console and network panels; preserve logs across navigation if the browser offers that option.
  2. Reload the page. Look for a report-only violation associated with the external image and img-src.
  3. Click Request test API and inspect both the CSP message and the network request. A CORS or network error is separate from a report-only CSP violation.
  4. Submit the form and inspect the message associated with form-action. Return to the test page afterward.
  5. Click the ordinary link and inspect the navigation. The example policy's default-src 'self' is not a general restriction on that link.

The examples have not been executed here, and console wording and reporting behavior can differ across browser versions. If a result differs, check the actual response headers, requested URLs, browser settings, and any additional enforced policies before changing a source list.

Advertisement

Review destinations and redirects before allowing them

Use the network panel to follow each request and its redirects. Record the initial URL and the final URL, including scheme, hostname, port, and resource type. Test redirects you expect in production as well as the direct destination: a request that starts at an approved host can end at a different host. Redirect handling and path-based source matching have subtleties, so verify the actual chain in supported browsers rather than assuming that approval of the first URL covers everything.

For each candidate source, ask:

  • Scheme: Is HTTPS required throughout the chain? Avoid adding an insecure scheme merely to make a failing request work.
  • Hostname: Is the exact host necessary? https://assets.example.test is narrower than https://*.example.test. A wildcard subdomain pattern does not include the apex host example.test itself.
  • Port: Is the request on the expected port? Non-default ports may need an explicit source expression; account for scheme and browser matching behavior when testing.
  • Directive: Is the host needed for an image, a connection, a script, or a form? Allow it only in the applicable directive.
  • Control: Who operates the destination and any redirect targets? A broad wildcard can authorize hosts that your team does not control or that may be created later.

For example, after confirming the image and API hosts are necessary, a candidate policy might retain the existing default-src 'self' and use these more specific directives:

img-src 'self' https://assets.example.test; connect-src 'self' https://api.example.test

This is a fragment, not a complete production policy. It does not permit the sample form submission, load external scripts, or control the ordinary link. If the form is required, separately assess and test its destination under form-action. Avoid copying the sample domains into production.

Roll out without weakening production blindly

  1. Inventory the production policy headers and any policy delivered through HTML. Multiple enforced policies can restrict the same request independently.
  2. Build a candidate policy from the current production policy, adding only reviewed sources to the appropriate directives. Do not replace the production policy with the simplified lab example.
  3. Deploy the candidate as report-only alongside the existing enforced policy where your deployment supports it. Configure a reporting endpoint if you need reports beyond individual browser sessions; protect and retain reports appropriately because URLs can contain sensitive data.
  4. Exercise critical user journeys and redirect paths in supported browsers. Remember that the existing enforced policy can still block a request while the candidate is being evaluated.
  5. Review violations, distinguish CSP failures from CORS, DNS, TLS, server, or extension problems, and decide whether each destination is intended. Then deploy the reviewed policy through your normal change process and continue monitoring.

If the enforced policy already blocks a required request, use the isolated lab or another appropriately controlled staging environment to test it. Report-only mode does not override the enforced policy.

Common Mistakes

  • Adding every destination to default-src. A specific directive may override that fallback, and ordinary links are not generally governed by it.
  • Confusing frame-src with frame-ancestors. One governs frames the page loads; the other governs which pages may embed it.
  • Allowing a whole domain family to fix one host. A wildcard can grant substantially more access than the feature requires.
  • Treating a report-only message as proof of a blocked request. The report-only policy itself does not block it; inspect enforced policies and other errors separately.
  • Stopping at the initial URL. Redirects, alternate subdomains, and non-default ports can change what must be evaluated.
  • Treating CSP as an outbound firewall. CSP is a browser-side control and does not replace server-side authorization, network controls, or validation.

Best Practices

Keep an inventory of approved destinations by directive and owner. Test the actual production-like redirect flow, use narrowly scoped HTTPS sources where practical, and review report-only findings before enforcing changes. Recheck the policy when a vendor changes infrastructure or a destination is retired.

This article was prepared without access to current official CSP or browser documentation, and the example was not run. Before launch, consult the official CSP documentation and the documentation for your supported browser versions, then verify the behavior in those browsers.

Conclusion

Start with how the page uses each URL, not with a blanket domain allowlist. A controlled report-only test, followed by redirect and source review, helps identify the smallest policy change needed for launch.

What would your domain sell for?

A free TidyURLs account unlocks the Domain Estimator. It prices a name from 191,011 real domain sales.