Zero-Trust for Front-End Apps on AWS: Locking Down a Static Site with CloudFront, S3, and Browser Security Headers
Why the front end needs zero-trust too Zero-trust is usually discussed for networks and APIs: never trust, always verify, grant least privilege, assume breach. But the front end is where a lot of breaches actually start. Your JavaScript runs on a machine you don’t control, it pulls in dozens of third-party packages, and a single injected script can read tokens, rewrite forms, or exfiltrate data.
Architecture
Browser ──HTTPS only──► CloudFront (+ Response Headers Policy, optional WAF) │ └─ Origin Access Control (signed requests) │ ▼ S3 bucket (private, public access blocked)
Browser ──violation reports──► API Gateway ──► Lambda ──► CloudWatch LogsThe key idea is that CloudFront is the only door, and it stamps every response with security headers, so protection doesn’t depend on each developer remembering to add them in app code.
Step 1: Make the origin unreachable
A common mistake is making the S3 bucket public “so the website works.” Don’t. Block all public access and let only CloudFront read from it using Origin Access Control (OAC). OAC signs requests from CloudFront to S3, and the bucket policy allows only your specific distribution.
Also enforce encryption in transit (
enforceSSL ) and redirect viewers from HTTP to HTTPS.Step 2: Define the whole thing in CDK
Here’s a compact AWS CDK (TypeScript) stack. The
S3BucketOrigin.withOriginAccessControl helper requires a reasonably recent aws-cdk-lib version, so update if it’s missing.typescript
import * as cdk from 'aws-cdk-lib';import * as s3 from 'aws-cdk-lib/aws-s3';import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';import { Construct } from 'constructs';
export class ZeroTrustFrontendStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props);
const bucket = new s3.Bucket(this, 'SiteBucket', { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, enforceSSL: true, encryption: s3.BucketEncryption.S3_MANAGED, versioned: true, });
const headers = new cloudfront.ResponseHeadersPolicy(this, 'SecurityHeaders', { securityHeadersBehavior: { contentSecurityPolicy: { override: true, contentSecurityPolicy: [ "default-src 'none'", "script-src 'self'", "style-src 'self'", "img-src 'self' data:", "font-src 'self'", "connect-src 'self' https://api.example.com", "base-uri 'none'", "form-action 'self'", "frame-ancestors 'none'", "upgrade-insecure-requests", ].join('; '), }, strictTransportSecurity: { override: true, accessControlMaxAge: cdk.Duration.days(365), includeSubdomains: true, }, contentTypeOptions: { override: true }, frameOptions: { override: true, frameOption: cloudfront.HeadersFrameOption.DENY, }, referrerPolicy: { override: true, referrerPolicy: cloudfront.HeadersReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN, }, }, customHeadersBehavior: { customHeaders: [ { header: 'Cross-Origin-Opener-Policy', value: 'same-origin', override: true }, { header: 'Cross-Origin-Embedder-Policy', value: 'require-corp', override: true }, { header: 'Cross-Origin-Resource-Policy', value: 'same-origin', override: true }, { header: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=(), payment=()', override: true, }, ], }, });
new cloudfront.Distribution(this, 'Distribution', { defaultRootObject: 'index.html', minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021, defaultBehavior: { origin: origins.S3BucketOrigin.withOriginAccessControl(bucket), viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS, responseHeadersPolicy: headers, }, }); }}Replace
https://api.example.com with your real API origin. The rest of this article explains what each header buys you.Step 3: Understand what each control does
Content Security Policy (CSP): “only run what I approved”
The policy above starts from
default-src 'none' and opens only what the app needs. If an attacker injects a <script> tag or an inline handler, the browser refuses to run it. Notice what’s missing: no 'unsafe-inline' and no 'unsafe-eval' . Those two keywords largely cancel CSP’s protection against XSS.If your build tool emits inline scripts, you have two options: switch to external files, or use hashes or nonces. Nonces need a unique value per response, which static hosting can’t produce on its own. You’d add a CloudFront Function or Lambda@Edge, or prefer hashes computed at build time.
Subresource Integrity (SRI): “verify third-party files”
If you must load a script from a CDN, pin its hash so a tampered file is rejected:
html
<script src="https://cdn.example.com/lib.min.js" integrity="sha384-BASE64HASHHERE" crossorigin="anonymous"></script>Better still, bundle dependencies into your own build so
script-src 'self' is enough.Cross-origin isolation (COOP + COEP + CORP): “don’t share my process or memory”
- COOP: same-origin severs the link between your window and any cross-origin window that opened it (or that you opened), blocking a class of cross-window attacks.
- COEP: require-corp says your page will only load cross-origin resources that explicitly opt in (via CORP or CORS).
- CORP: same-origin on your own responses stops other sites from embedding your resources.
With COOP and COEP both set, the page becomes cross-origin isolated. That also unlocks powerful APIs such as
SharedArrayBuffer , which browsers gate behind isolation because of speculative-execution side channels.The catch is that
require-corp will block any third-party image, font, or script that doesn’t send the right headers. A variant, Cross-Origin-Embedder-Policy: credentialless , is more forgiving, but browser support differs, so check current compatibility before relying on it.HSTS: “never talk to me over HTTP”
Tells the browser to use HTTPS only for the next year. Add
preload and submit the domain to the preload list only after you’re sure every subdomain supports HTTPS, because it’s difficult to undo.Permissions-Policy and the rest
Permissions-Policy switches off camera, microphone, geolocation, and payment APIs your app never uses, so even injected code can’t ask for them. X-Content-Type-Options: nosniff stops MIME sniffing, frame-ancestors 'none' plus X-Frame-Options: DENY blocks clickjacking, and the referrer policy limits what leaks in outbound requests.Step 4: Roll out safely with report-only mode
Strict CSP and COEP can break a working site the moment you deploy. Don’t discover that in production. Start with the report-only variants:
-
Content-Security-Policy-Report-Only
-
Cross-Origin-Embedder-Policy-Report-Only
These log violations without blocking anything. Add a reporting directive pointing to an endpoint you control (for example an API Gateway route backed by a small Lambda that writes to CloudWatch Logs), watch the reports for a few days, fix what’s flagged, then switch to enforcement.
This reporting loop is also your “assume breach” control: a sudden burst of CSP violations on a page that was quiet yesterday is a signal worth alerting on.
Step 5: Protect the session, not just the page
Locking down the page matters less if the tokens it handles are easy to steal.
- Prefer HttpOnly, Secure, SameSite cookies for session tokens over
localStorage, so injected JavaScript can’t read them.
- Keep tokens short-lived and verify them on every API call. Don’t trust the front end to enforce access.
- On the API, validate tokens with a JWT authorizer (for example in API Gateway with Cognito) and restrict CORS to your exact CloudFront or custom domain, never
*.
- Apply least-privilege IAM to every backend function.
The front end is untrusted by definition. The real authorization decisions always belong on the server.
Step 6: Add depth with AWS WAF
Attach AWS WAF to the distribution for managed rule groups, rate limiting, and IP reputation filtering. It won’t replace the headers above, but it filters bad traffic before it reaches your origin, which fits the layered “assume breach” approach. Check pricing first, since WAF adds cost per web ACL, rule, and request volume.
Step 7: Verify, don’t assume
After deploying, check what the browser actually receives:
bash
curl -sI https://your-domain.example | grep -iE \ "content-security|strict-transport|cross-origin|permissions|x-frame|x-content|referrer"Then open DevTools and:
- Run
window.crossOriginIsolatedin the console. It should returntrue.
- Check the Console for CSP or COEP violation messages.
- Check the Network tab to confirm no resource was blocked unexpectedly.
You can also run the site through a header scanner such as Mozilla Observatory for a second opinion.
What went wrong (and what to watch for)
1. A blank page after enabling COEP.
require-corp silently blocked an externally hosted font and an analytics script. Fix: self-host assets or use sources that send CORP/CORS headers.2. Inline scripts blocked by CSP. The build output contained inline bootstrap code. Fix: configure the bundler to emit external files, or use build-time hashes.
3. Cached responses with old headers. Changing a response headers policy doesn’t help if you’re confused about what’s cached. Test with a fresh request and invalidate if needed.
4. Header conflicts with your origin. If the origin already sends a header, the
override flag decides who wins. Set it deliberately.5. Breaking OAuth or payment popups.
COOP: same-origin can sever the opener relationship that some login or payment flows depend on. Test those flows, and consider same-origin-allow-popups where genuinely required.Checklist
- S3 public access blocked, origin reachable only through CloudFront via OAC
- HTTPS enforced, TLS 1.2+ minimum
- Strict CSP with no
unsafe-inlineorunsafe-eval
- SRI on any third-party script, or dependencies bundled
- COOP, COEP, and CORP set,
crossOriginIsolatedverified
- HSTS enabled
- Permissions-Policy disabling unused features
- Report-only rollout first, violation reports collected
- Session tokens in HttpOnly cookies, API authorization enforced server-side
- WAF attached, billing alarm set
- Infrastructure defined in CDK so the posture is reproducible and reviewable
Conclusion
Zero-trust for the front end isn’t one product or one header. It’s a stance: the browser, the network, the third-party code, and even your own bundle are all treated as potentially hostile, and every layer verifies instead of assuming. On AWS, putting CloudFront in front of a private S3 bucket and defining the security headers as code gives you a strong baseline for a few dollars a month. Start in report-only mode, tighten gradually, and verify in the browser.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article