Phase 3: L7 Networking + WAF + API Security (Days 61–90)
Phase Goal: Move up to the application layer. Build HTTP middleware, a Web Application Firewall, and API security controls. These are the systems your platform security team owns.
Week 9: HTTP Internals (Days 61–67)
Why this week matters: HTTP is the protocol for every API your company exposes. Understanding how it works at the wire level explains every HTTP security vulnerability.
Day 61 — HTTP/1.1 from scratch
- Why: Parsing HTTP manually reveals why HTTP request smuggling, header injection, and request splitting attacks work. You can't evaluate these risks without knowing the protocol
- Topic: Request line, headers, body,
Content-LengthvsTransfer-Encoding: chunked, response format, persistent connections (Connection: keep-alive), pipelining - Exercise: Build an HTTP/1.1 server using only
net.Listen— nonet/http. Parse request line and headers manually usingbufio.Reader. ServeGET /→200 OK. HandleConnection: closevs keep-alive.
Day 62 — net/http server
- Why:
net/httpis what you'll use for every Go service. Understanding its config options (timeouts, limits) prevents slowloris and resource exhaustion - Topic:
http.Server,ServeMux,http.Handler,http.HandlerFunc,ReadHeaderTimeout,ReadTimeout,WriteTimeout,IdleTimeout,MaxHeaderBytes - Exercise: Build a hardened HTTP server: set all timeouts (read header: 5s, read body: 30s, write: 30s, idle: 120s), limit max header size, log connection state transitions using
ConnStatecallback.
Day 63 — HTTP middleware
- Why: Every cross-cutting concern (auth, logging, rate limiting, WAF) is implemented as middleware. Understanding the pattern helps you review middleware ordering decisions
- Topic: Middleware as
func(http.Handler) http.Handler, handler chain, middleware ordering (matters for auth before logging),http.ResponseWriterwrapping to capture status code - Exercise: Build a middleware chain builder:
Chain(h, mw1, mw2, mw3). Implement: (1) request ID injector, (2) latency logger (captures status code), (3) panic recoverer. Verify ordering.
Day 64 — HTTP reverse proxy
- Why: Nginx, Envoy, and your internal API gateway are all reverse proxies. Understanding how they work helps you configure them correctly and debug routing issues
- Topic:
httputil.ReverseProxy,Director(modify request before forwarding),ModifyResponse(modify response before returning), hop-by-hop headers,X-Forwarded-For,X-Real-IP - Exercise: Build a reverse proxy: forward to upstream, rewrite Host header, strip sensitive upstream headers (
X-Internal-*), injectX-Request-ID,X-Forwarded-For. Log: method, path, upstream latency, status.
Day 65 — HTTP/2
- Why: HTTP/2 is the default for gRPC and many modern APIs. H2 multiplexing changes how you think about connection limits and load balancing
- Topic: H2 vs H1 differences (multiplexing, header compression, binary framing),
net/httpH2 support (automatic with TLS), why H2 needs fewer connections, H2 cleartext (h2c) - Exercise: Build a server that supports both HTTP/1.1 and HTTP/2 (auto-negotiate via ALPN). Log which protocol each request uses. Send 100 requests via H1 and H2 — measure latency difference with
time.
Day 66 — WebSocket
- Why: WebSocket powers real-time features (dashboards, alerts, live config updates). Understanding the upgrade handshake explains why some WAF rules break WebSocket connections
- Topic: WebSocket upgrade (HTTP 101),
Sec-WebSocket-Key/Accepthandshake (SHA-1), frame format (opcode, mask, payload), ping/pong, close handshake - Exercise: Build a WebSocket server from scratch (no library): parse the Upgrade request, compute
Sec-WebSocket-Accept, read/write frames manually. Build a real-time event broadcaster: clients subscribe, server fans out messages.
Day 67 — HTTP security headers
- Why: Security headers (HSTS, CSP, CORS) are the browser-side security controls every service should set. You'll catch PRs that miss them
- Topic: HSTS, CSP (Content-Security-Policy), CORS (preflight,
Access-Control-Allow-*),X-Frame-Options,X-Content-Type-Options,Referrer-Policy,Permissions-Policy - Exercise: Build a security headers middleware: configurable CORS (allowlist-based, not
*), HSTS with preload, CSP with per-request nonce (viacrypto/rand), automatic OPTIONS preflight handling.
Week 9 Mini Project: HTTP Reverse Proxy with Full Observability
- Build a production-grade reverse proxy:
- HTTP/1.1 and HTTP/2 (TLS, auto-negotiate)
- Middleware chain: request ID → security headers → logging → proxy
- Backend health checks (HTTP GET
/healthevery 5s) - Request timeout enforcement (per-request context with deadline)
- Response modification: strip internal headers, inject tracing headers
- Metrics: RPS, error rate, p50/p95/p99 latency (ring buffer of 10k samples)
/metrics(expvar),/health,/debug/pprof- Graceful shutdown with connection drain
- Key packages:
net/http,net/http/httputil,crypto/tls,sync,expvar,time - Engineer Takeaway: Nginx at its core does exactly this. Every request through your company's API gateway goes through a chain like this.
Week 10: Web Application Firewall (Days 68–74)
Why this week matters: WAF is often the first security control evaluated for compliance. Understanding how rules work helps you configure a WAF, write precise exceptions, and reason about false positive tradeoffs.
Day 68 — WAF fundamentals & OWASP Top 10
- Why: OWASP Top 10 shows up in SOC2, PCI, and ISO 27001 audits. Knowing how WAF rules map to OWASP categories helps you have informed compliance conversations
- Topic: OWASP Top 10 categories, WAF modes (detection vs blocking), where WAF sits in the stack, false positive vs false negative tradeoffs, paranoia levels
- Exercise: Build a WAF skeleton:
type Rule interface { ID() string; Match(r *http.Request) (matched bool, score int, detail string) }. BuildWAFMiddleware(rules []Rule, threshold int) http.Handler. Log matches, block if score > threshold.
Day 69 — SQL injection detection
- Why: SQLi is the #1 data breach vector. WAF rules are your last line of defense when app code has a bug. Understanding detection helps you evaluate rule quality
- Topic: SQLi payloads (
' OR '1'='1,UNION SELECT,--comments, stacked queries), tokenization vs regex detection, false positive patterns (legitimate SQL in app names) - Exercise: Implement SQLi detection: (1) keyword list (
UNION,SELECT,DROP,INSERT,--), (2) quote-balance detection, (3) comment pattern detection. Test with 15 SQLi payloads + 15 legitimate inputs. Tune to 0 false positives on legitimate inputs.
Day 70 — XSS detection
- Why: XSS leads to session hijacking and account takeover. Understanding detection patterns helps you tune WAF rules vs CSP headers
- Topic: Reflected XSS (in response), stored XSS (in DB), DOM XSS (in JS),
<script>injection, event handlers (onerror=,onload=), JavaScript URIs (javascript:), SVG attacks - Exercise: Build XSS detection: scan URL params, headers, and JSON body. Normalize input first (URL-decode, HTML-unescape). Match:
<script,javascript:, event handler patterns (on[a-z]+=). Test with 10 payloads + 10 legitimate HTML fragments.
Day 71 — Path traversal & command injection
- Why: Path traversal lets attackers read
/etc/passwd. Command injection lets them run arbitrary code. These are critical severity vulnerabilities - Topic: Path traversal patterns (
../,%2e%2e%2f,%252e%252e%252fdouble-encoding), null bytes (%00), command injection (;,|,`,$(,&&) - Exercise: Build detection for path traversal (handle URL-encoding, double-encoding, unicode variants) and command injection. Add a normalization step: URL-decode → percent-decode → normalize. Test bypass attempts with encoded variants.
Day 72 — Request body inspection
- Why: Most WAFs only scan URL and headers by default. Body scanning is where complex attacks hide. Understanding the tradeoffs (latency vs coverage) is a product decision
- Topic: Reading body without breaking the handler (
io.TeeReader+ buffer),Content-Typedispatch (form, JSON, multipart), body size limits, streaming vs buffered inspection - Exercise: Build a body inspector: buffer up to 1MB of body (reject larger), dispatch by Content-Type for scanning, restore body for downstream handler using
io.NopCloser(bytes.NewReader(...)). Scan JSON values recursively.
Day 73 — WAF normalization pipeline
- Why: Attackers bypass WAF rules using encoding. Multi-layer normalization is what separates basic WAFs from production-grade ones
- Topic: Multi-layer decoding (URL → HTML → Unicode → lowercase), SQL comment stripping (
/**/), whitespace normalization, null byte removal, Unicode confusables - Exercise: Build a normalization pipeline:
input → URL-decode → HTML-unescape → remove SQL comments → collapse whitespace → lowercase. Apply before every rule match. Test 10 encoding bypass attempts.
Day 74 — WAF rule scoring & exceptions
- Why: Block-mode WAFs cause false positive incidents. Scoring-based WAFs (block only if multiple rules match) reduce false positives. Exception lists are how you handle legitimate traffic that looks like attacks
- Topic: Score accumulation (each rule adds weight), group scores (SQLi group, XSS group), block threshold per group, exception lists (by IP, path, header value)
- Exercise: Build a scoring WAF: SQLi group (block if SQLi score > 5), XSS group (block if XSS score > 4), path traversal (block on any match). Exception list: trusted IPs bypass all rules. Test with mixed payloads.
Week 10 Mini Project: Production WAF Middleware
- Build a full WAF middleware:
- Normalization pipeline (URL-decode → HTML-unescape → lowercase → comment strip)
- Rules: SQLi (scoring), XSS (scoring), path traversal (immediate block), command injection (immediate block)
- Body inspection (JSON + form, up to 1MB)
- Allow-list: trusted CIDRs bypass WAF
- Block response:
403with request ID (no internal details leaked to attacker) - Audit log: every match logged with rule ID, matched value, normalized value, score, action
- Config hot-reload (rule thresholds from JSON file, poll every 30s)
- Detection mode: log but don't block (for tuning)
- Key packages:
net/http,regexp,strings,html,net,sync,encoding/json - Engineer Takeaway: AWS WAF, Cloudflare WAF, and ModSecurity all implement this scoring model. When a WAF blocks a legitimate request, you'll know how to find the rule and write a narrow exception, and what risk it carries.
Week 11: API Security & Authentication (Days 75–81)
Why this week matters: API security is where most breaches happen today. OAuth2, API keys, rate limiting, and input validation are everyday concerns for anyone building APIs.
Day 75 — API authentication patterns
- Why: Auth is the most critical security control. Understanding the tradeoffs between API keys, HMAC signing, and JWTs helps you make the right architecture decisions
- Topic: API key (simple, no expiry), HMAC-signed requests (AWS SigV4 pattern — key + timestamp + body hash), signed tokens (JWT-like, expiry built in), mTLS (certificate as identity)
- Exercise: Implement all 3 auth patterns as middleware: (1) API key header, (2) HMAC-SHA256 request signing (include timestamp, method, path, body hash in signature), (3) ECDSA-signed token (from Phase 2). Each rejects unauthorized requests with
401.
Day 76 — Rate limiting at L7
- Why: API rate limiting protects backend systems from abuse. Token bucket is the algorithm used by AWS API Gateway, Stripe, and most API platforms
- Topic: Token bucket (tokens refill at rate R, burst up to capacity B), per-user vs per-IP vs per-API-key limiting, rate limit headers (
X-RateLimit-Limit,X-RateLimit-Remaining,Retry-After) - Exercise: Build rate limiting middleware: per-API-key token bucket (10 req/s, burst 50). Respond
429withRetry-Afterheader. Usesync.Mapfor per-key buckets +time.NewTickerfor background refill. Test with 100 concurrent clients.
Day 77 — Input validation
- Why: Unvalidated input is the root cause of injection attacks. Go struct tags for validation are in every serious API codebase
- Topic: Allowlist vs denylist validation, length limits, type coercion, required fields, pattern matching, nested struct validation, validation error aggregation
- Exercise: Build a struct validation framework using
reflectand struct tags:validate:"required,max=255,pattern=^[a-zA-Z]+$". Return all validation errors (not just first). Test with 20 valid + 20 invalid inputs.
Day 78 — JSON schema enforcement
- Why: API schema validation prevents malformed requests from reaching application code. OpenAPI/JSON Schema is the industry standard
- Topic: JSON Schema spec subset (
type,required,minLength,maxLength,minimum,maximum,pattern,enum,additionalProperties: false) - Exercise: Implement a JSON Schema validator (no library): validate incoming JSON request bodies against a schema defined in Go. Reject unknown fields (important for security — prevents parameter pollution). Return structured errors.
Day 79 — Sensitive data protection
- Why: PII in logs is a compliance violation (GDPR, CCPA). Response scrubbing and log masking are often compliance requirements. You'll review data handling designs
- Topic: PII detection patterns (email, phone, SSN, credit card), log field masking (
"password":"***"), response field redaction,encoding/jsonstreaming for large payloads - Exercise: Build a PII scrubber: (1) log middleware that masks known-sensitive field names (
password,token,ssn,card_number) in JSON bodies before logging, (2) response scrubber that redacts patterns (credit card regex, email regex) from JSON responses.
Day 80 — API abuse prevention
- Why: Credential stuffing, account enumeration, and scraping are attacks against APIs, not just web UIs. Understanding the patterns helps you design effective controls
- Topic: Credential stuffing (try leaked credentials), account enumeration (error message differences), brute force (repeated auth attempts), scraping (extract all data via API)
- Exercise: Build defenses: (1) failed auth rate limiting per username + per IP independently, (2) constant-time auth response (always ~200ms via
time.Sleep— prevent timing attacks), (3) honeypot API endpoint that flags any IP that calls it.
Day 81 — CORS & preflight
- Why: CORS misconfigurations are in the OWASP Top 10.
Access-Control-Allow-Origin: *on an authenticated API is a critical vulnerability - Topic: Same-origin policy (why CORS exists), preflight (OPTIONS),
Access-Control-Allow-Origin(allowlist, never*for auth'd APIs),Access-Control-Allow-Credentials,Vary: Origin - Exercise: Build a CORS middleware: strict origin allowlist (no wildcard for credentialed requests), preflight caching (
Access-Control-Max-Age),Vary: Originheader, reject disallowed origins with403. Test with 5 allowed + 5 disallowed origins.
Week 11 Mini Project: API Security Gateway
- Build a complete API security layer:
- Auth: ECDSA-signed token validation + HMAC request signing support
- Rate limiting: per-API-key token bucket, per-IP sliding window
- JSON schema validation per route (loaded from config file)
- Input validation (struct tags) for known request types
- Response PII scrubber (mask sensitive fields in logs and responses)
- Abuse prevention: failed auth rate limiting, honeypot endpoint
- CORS with origin allowlist
- Security headers (HSTS, CSP, X-Frame-Options)
- WAF (from Week 10) integrated in the chain
- Full audit log (request + masked body + response status + latency)
- Key packages:
net/http,crypto/ecdsa,crypto/hmac,encoding/json,sync,regexp - Engineer Takeaway: This is the security policy of your API platform codified in software. Every feature maps to a compliance control or a real attack vector.
Week 12: Phase 3 Review + Integration (Days 82–90)
Why this week matters: Integration week. Wire the L4 gateway (Phase 2) to the HTTP/API gateway (Phase 3) and validate the complete stack under load.
Day 82 — Middleware ordering & pipeline design
- Why: The order of security middleware matters. Auth before WAF? Rate limit before auth? Wrong order creates vulnerabilities or poor UX (user gets WAF-blocked before seeing auth error)
- Topic: Correct ordering: IP allowlist → connection limits → rate limit → TLS/bot check → auth → WAF → schema validation → handler. Short-circuit semantics. Context propagation.
- Exercise: Build a configurable middleware pipeline that loads order from a JSON config. Validate that required middleware are present. Log which middleware handled (rejected) each request.
Day 83 — Threat intelligence aggregation
- Why: IP reputation is a shared signal across WAF, DDoS, and bot detection. A unified threat score per IP improves accuracy and reduces false positives
- Topic: IP reputation store, score aggregation from multiple signals (WAF hits, rate limit violations, failed auth), score decay over time, block threshold vs challenge threshold
- Exercise: Build a
ThreatIntelstore: accepts signals from any module (ReportSignal(ip, type, weight)), aggregates scores with time decay (score halves every 10 minutes), exposesScore(ip) float64andAction(ip) string(allow/challenge/block).
Day 84 — Structured logging with slog
- Why:
log/slogis stdlib since Go 1.21. Structured logs are machine-parseable. Your observability platform (Datadog, Splunk) expects JSON. Use slog in every service you ship - Topic:
slog.Logger,slog.Handler, JSON handler (slog.NewJSONHandler), log levels,slog.With(add context fields), correlation ID propagation via context - Exercise: Replace all
log.Printfin your projects withslog. Add: request ID (from context), client IP, user identity (from auth middleware), module name. Output JSON. Add log level filtering (debug logs off in prod).
Day 85 — Configuration & hot reload
- Why: Changing WAF rules or rate limits without restarting a service is a production requirement. Understanding the patterns helps you design config management
- Topic: JSON config loading, env var override, config validation on load, hot reload via file watching (
os.Statpolling orSIGHUP), atomic config swap (sync.RWMutexoratomic.Value) - Exercise: Build a config system for the API gateway: JSON file with WAF thresholds, rate limits, CORS origins, auth config. Hot-reload on
SIGHUP. Validate new config before swapping (reject invalid config, keep old).
Day 86 — Integration testing the full chain
- Why: Unit tests don't catch middleware ordering bugs. Integration tests using
net/http/httptestornet.Pipecatch real issues - Topic:
httptest.NewServer,httptest.NewTLSServer,net.Pipefor TCP tests, test scenarios: auth bypass attempts, WAF evasion, rate limit exhaustion - Exercise: Write integration tests for the full middleware chain: (1) valid request passes all layers, (2) SQL injection blocked by WAF, (3) rate limit enforced, (4) invalid token rejected, (5) oversized body rejected, (6) CORS blocked for unknown origin.
Day 87 — Fuzz testing
- Why: Fuzz testing finds crashes and security bugs that hand-written tests miss. Go's built-in fuzzer is production-grade and requires no setup
- Topic:
testing/fuzz,f.Addseed corpus,f.Fuzz, what to fuzz (parsers, decoders, validators), interpreting results, fixing panics - Exercise: Write fuzz tests for: (1) WAF normalization pipeline (does it panic on arbitrary input?), (2) JSON schema validator (does malformed JSON panic?), (3) HTTP request parser (Day 61). Run with
go test -fuzz -fuzztime 30s.
Day 88 — Load testing the security stack
- Why: Security middleware adds latency. Knowing the overhead helps you justify the cost and set SLOs. "Our WAF adds 2ms p99" is a concrete business number
- Topic: Load generation with goroutines, measuring latency percentiles (ring buffer approach), connection reuse vs new connection per request, what to measure
- Exercise: Load test the full API gateway: 500 concurrent clients, 10,000 total requests, mix of valid + invalid (10% WAF triggers, 5% rate limit hits, 5% auth failures). Report: RPS, p50/p95/p99 latency, per-middleware overhead, error rate breakdown.
Day 89 — Goroutine leak audit
- Why: Goroutine leaks cause memory growth and eventually OOM. They're common in middleware that starts goroutines for timeouts or background tasks
- Topic:
runtime.NumGoroutine(), goroutine dumps (runtime.Stack), leak patterns (forgottendonechannel, missingcontextcancellation, goroutine with no exit path) - Exercise: Add goroutine count tracking to all middleware. Run the load test (Day 88). After load test ends, check goroutine count — it should return to baseline within 10s. Find and fix any leaks.
Day 90 — Phase 3 Review & architecture diagram
- Review the complete Phase 3 stack
- Draw an architecture diagram (ASCII) showing all components, data flow, and security controls
- Identify: what would you use a managed product for vs build? (WAF rules database, TLS certificate management, IP reputation feeds)
- Engineer Takeaway: You can now design, build, and operate a full API security gateway. You understand what a product sold as a "WAF" or "API gateway" does, line by line.
Week 12 Mini Project: Unified Security Proxy (L4 + L7)
- Wire the Phase 2 L4 gateway to the Phase 3 API security layer:
- L4: TLS termination, mTLS, SNI routing, L4 rate limiting, circuit breaker
- L7: HTTP/2, reverse proxy, WAF, API auth, rate limiting, schema validation
- Unified threat intel (
ThreatIntelstore, shared across L4 and L7) - Structured logging (slog, JSON, correlation IDs)
- Hot-reload config (SIGHUP)
- Full observability:
/debug/vars,/debug/pprof,/health,/metrics - Graceful shutdown (3-stage)
- Key packages: All stdlib
- Engineer Takeaway: This is the architecture of Cloudflare's edge, AWS WAF + ALB, and Fastly's compute platform — implemented in ~2000 lines of Go.