Skip to content
← Back to Media & Content Delivery

Case Study · Media & Content Delivery

Secure Media Delivery at the Edge on AWS

Token-Based Auth · CloudFront Functions · Auto Session Revocation · Well-Architected Design

Based on: AWS Guidance: Secure Media Delivery at the Edge

CloudFrontCF FunctionsSecrets ManagerStep FunctionsAWS WAFS3+1 more

Executive Summary

This case study documents an edge-first architecture for protecting premium video content from unauthorised access. The solution implements token-based authentication at CloudFront edge locations using CloudFront Functions, validates tokens against signing keys managed by AWS Secrets Manager, and automatically revokes compromised playback sessions through a pipeline of CloudWatch Logs, AWS Step Functions, and AWS WAF, all without routing requests back to origin for security checks.

The architecture is derived from the AWS Guidance for Secure Media Delivery at the Edge and is structured as three independently deployable modules: the base request path with edge token validation, an automatic session-revocation pipeline, and a key management and rotation layer. Every component is serverless and aligned with the AWS Well-Architected Framework.

Business Value

Monetised video content is protected at the delivery layer, not just at the application layer. Unauthorised sharing of stream tokens is detected and blocked in near real-time, preventing revenue leakage on premium content.

Key Architectural Decision

Token validation runs inside CloudFront Functions at the edge, not in a Lambda@Edge or origin server. This eliminates the 5–50 ms round-trip to a compute layer, keeping authentication latency under 1 ms per request at the edge.

Security Posture

Three independent enforcement layers: edge token validation (CloudFront Functions), geo and rate controls (WAF), and automated session revocation (Step Functions + WAF). A token compromise is contained within minutes without human intervention.

Business Problem

Premium video content delivered over the internet is vulnerable to token theft, credential sharing, and stream piracy. A viewer who pays for a stream can share the playback URL with thousands of others, bypassing subscription gates and causing direct revenue loss. Existing countermeasures often require origin-side validation on every request, introducing latency at scale, or rely on time-limited signed URLs that provide only coarse-grained access control.

Token Theft & Credential Sharing

A viewer's playback token can be captured via traffic inspection, shared on forums, or embedded in piracy apps. Without active session monitoring, a stolen token continues to serve content until it naturally expires, often 3–24 hours after issuance.

Origin-Side Auth Latency

Routing every segment request through an authentication Lambda or API adds 10–50 ms per request. At 500,000 concurrent viewers each making one segment request every 2 seconds, this is 250,000 authentication calls per second, a significant cost and latency burden.

Key Rotation Complexity

Manually rotating signing keys introduces operational risk: if a key is rotated while tokens signed with the old key are still in use, legitimate viewers are immediately denied. The rotation process must be orchestrated carefully with overlap windows and atomic key swaps.

Reactive Security Posture

Most platforms respond to piracy reports manually, reviewing logs, identifying abusive sessions, and updating block lists. During the time between detection and remediation, the stolen stream continues to serve content at the operator's bandwidth cost.

Design Constraints

  • Authentication must not add measurable latency to segment delivery: target under 1 ms per request at the edge
  • Key rotation must be non-disruptive to active legitimate viewer sessions; old key must remain valid for a configurable grace period
  • Session revocation must be automatic: no manual intervention required to block a detected compromised session
  • The solution must scale to millions of concurrent requests without pre-provisioning dedicated compute capacity
  • All secret material (signing keys) must be managed by an AWS-native secret store with audit trails and automatic rotation support

Architecture Overview

The architecture is composed of three deployable modules that address the request path, threat response, and key lifecycle independently. All three modules operate on serverless AWS primitives: no EC2, no containers, no persistent compute to manage.

Architecture Diagram · Official AWS Icons

REQUEST & DELIVERY PATHTOKEN VALIDATIONAUTO SESSION-REVOCATIONViewerStream requestAWS WAFAccess controlCloudFront+ CF FunctionsAuthorisedS3 OriginMedia contentSecrets MgrSigning keyvalidate tokenCloudWatchAccess logsSuspicious patternStep FunctionsRevocation flowBlock sessionAWS WAFIP block ruleaccess logsauto-rotatedvia Step Fns
Request / auth flowTelemetry / automationIcons: AWS Architecture Icons (official)

Three-Module Structure

A

Base: Edge Token Auth

CloudFront distribution with a CloudFront Function attached to the viewer-request event. The function intercepts every request, extracts the token from the query string or cookie, validates the HMAC signature using the current key fetched from Secrets Manager at function initialisation, and either allows or denies the request, all at the edge, before any origin connection is opened.

B

Auto Session Revocation

CloudFront Real-Time Logs stream access records to CloudWatch Logs. A metric filter detects anomalous patterns (e.g. same token used from 50+ distinct IPs within 60 seconds). When the threshold is breached, CloudWatch triggers a Step Functions state machine that updates a WAF IP set rule to block traffic from the offending addresses, revoking the compromised session across all CloudFront edge locations within seconds.

C

Key Rotation

AWS Secrets Manager stores the current HMAC signing key. A Step Functions state machine, triggered on a configurable schedule (default: 24 hours), generates a new key, writes it to Secrets Manager as the next version, waits for the configured grace period (default: 30 minutes), then promotes the new key to current and retires the old one. CloudFront Functions automatically pick up the new key at their next cold start; no deployment required.

CloudFront Functions: Edge Token Validation

CloudFront Functions is a lightweight JavaScript execution environment that runs at every CloudFront edge location globally. Unlike Lambda@Edge (which runs at Regional Edge Caches), CloudFront Functions runs at the 400+ PoP locations, providing sub-millisecond execution with no cold-start latency.

Execution Model

CloudFront Functions run on the viewer-request event, executing before CloudFront checks its cache. Each function execution is limited to 1 ms of compute time and 2 MB of memory, sufficient for HMAC-SHA256 token validation but not for complex business logic. The signing key is loaded from Secrets Manager at function initialisation (not per-request), keeping per-request overhead minimal.

Token Structure

Each viewer token contains: a content ID, a viewer session ID, a not-before and expiry timestamp, an optional IP binding claim, and an HMAC-SHA256 signature over all claims. The function validates the signature, checks expiry, and optionally enforces the IP binding, rejecting tokens presented from a different IP than they were issued to.

Cost vs Lambda@Edge

CloudFront Functions cost $0.10 per million invocations, approximately 6× cheaper than Lambda@Edge ($0.60 per million). At 250,000 segment requests per second for a 3-hour live event, CloudFront Functions cost approximately $0.27 in function invocation charges. Lambda@Edge at the same volume would cost approximately $1.62, plus execution duration charges.

Limitations

CloudFront Functions cannot make network calls during execution; the signing key must be baked into the function code or loaded at initialisation from an environment variable. Key rotation therefore requires a function update or a CloudFront distribution update to inject the new key value. The Step Functions key rotation workflow handles this automatically via the CloudFront API.

Token Validation Logic

  • Extract token from the request query string (?token=...) or viewer-side cookie (preferred for HLS segment requests which cannot carry query strings through some players)
  • Base64-decode the token and parse the JSON claims object: {contentId, sessionId, iat, exp, ip (optional), sig}
  • Reject immediately if exp is in the past (token expired) or iat is in the future (clock skew > 30 seconds)
  • Reconstruct the signing input: the canonicalised JSON of all claims excluding the sig field
  • Compute HMAC-SHA256 over the signing input using the current key from Secrets Manager
  • Compare the computed signature to the sig claim using a constant-time comparison (prevents timing attacks)
  • If the token carries an ip claim and IP binding is enforced, compare to the CloudFront viewer IP header
  • Return a 403 Forbidden response with a JSON error body if any check fails; allow the request through if all checks pass

Automatic Session Revocation

The session revocation pipeline detects token abuse in near real-time and autonomously blocks offending sessions, without any human intervention. The pipeline is event-driven: CloudWatch Logs triggers the workflow when a metric threshold is breached, and Step Functions orchestrates the WAF rule update across all CloudFront edge locations.

Detection: CloudWatch Metric Filters

CloudFront Real-Time Logs deliver access records to a CloudWatch Log Group within 1 second of each request. A metric filter counts distinct viewer IPs per session ID in a 60-second sliding window. A CloudWatch Alarm triggers when a single session ID is observed from more than a configurable threshold of unique IPs (default: 10 IPs per 60 seconds, consistent with a shared/pirated token but not with legitimate NAT variance).

Orchestration: Step Functions

The CloudWatch Alarm invokes a Step Functions Express Workflow via EventBridge. The workflow: (1) queries the CloudWatch Log Insights API to extract the full list of offending IPs for the session, (2) calls the WAF UpdateIPSet API to add those IPs to a block list, (3) invalidates the session token in a DynamoDB revocation registry, (4) emits an SNS notification to the operations team. Total orchestration time: under 30 seconds from detection to block.

Enforcement: AWS WAF

The WAF block rule is attached to the CloudFront distribution and evaluated before CloudFront Function execution. Blocking at WAF is faster and cheaper than blocking in the function; a WAF IP match rule costs approximately $0.60 per million requests evaluated, while CloudFront Functions would still consume the 1 ms execution budget on blocked IPs.

Revocation Registry: DynamoDB

A DynamoDB table stores revoked session IDs with a TTL equal to the token expiry time. CloudFront Functions check this table during token validation; a session ID in the revocation list causes an immediate 403 regardless of token signature validity. This handles the case where an attacker obtains a valid token from a non-blocked IP range.

Threshold Tuning

The IP-per-session threshold requires careful calibration. Corporate users behind NAT gateways present many users under a single IP: the opposite of the piracy pattern. Mobile users on carrier-grade NAT may share IPs across legitimately distinct sessions. The default threshold of 10 unique IPs per session per 60 seconds is conservative; operators should review their user base distribution and adjust. A machine-learning-based anomaly detector (Amazon GuardDuty or a custom SageMaker model on the access log stream) can replace the static threshold for more nuanced detection.

Key Management & Rotation

HMAC signing key management is the operational foundation of the token authentication system. A compromised signing key allows an attacker to forge valid tokens for any content, any viewer, and any expiry, bypassing all token validation. Key rotation limits the blast radius of a key compromise and satisfies compliance requirements for periodic credential rotation.

Secrets Manager Storage

The signing key is stored in AWS Secrets Manager as a versioned secret. Secrets Manager supports multiple version labels: the AWSCURRENT label identifies the key in active use for token issuance and validation; the AWSPREVIOUS label identifies the key accepted during the grace period after rotation. CloudFront Functions load both versions at initialisation; tokens signed with either the current or previous key are accepted, preventing a revocation cliff for in-flight viewer sessions at rotation time.

Rotation Workflow (Step Functions)

The rotation state machine executes four steps: (1) Create a new random 256-bit key and write it to Secrets Manager as version AWSPENDING. (2) Update the CloudFront Function code to include the new key as the AWSPENDING validation key (alongside AWSCURRENT). (3) Wait for the grace period (configurable, default 30 minutes). (4) Promote AWSPENDING to AWSCURRENT and retire AWSPREVIOUS. During the grace period, tokens signed with both the old and new key are valid.

Audit Trail

Every Secrets Manager GetSecretValue and PutSecretValue call is logged to AWS CloudTrail. The Step Functions execution history provides a full audit trail of every rotation event: when it started, each state transition, and whether it succeeded or failed. Failed rotations trigger an SNS alert and leave the current key unchanged.

Key Access Control

The signing key is accessed by two principals: the token issuance service (application backend, via IAM role with SecretsManager:GetSecretValue on the specific secret ARN) and the Step Functions rotation workflow (via a separate IAM role with SecretsManager:RotateSecret). CloudFront Functions access the key value embedded in function code (not directly from Secrets Manager at request time) to avoid per-request API calls.

Security Architecture

Security is enforced across three independent layers. Each layer is capable of stopping unauthorised access independently, providing defence in depth: if one layer is misconfigured or bypassed, the others continue to enforce access control.

Layer 1: Network Edge (AWS WAF)

  • Geo-restriction rules block viewers from territories where content rights are not held
  • Rate limiting rule: 1,000 requests per 5-minute window per IP; prevents brute-force token enumeration
  • IP set block rules updated by the session revocation workflow block confirmed piracy sources within 30 seconds of detection
  • AWS Managed Rule Group (AWSManagedRulesCommonRuleSet) blocks known malicious user agents and request patterns

Layer 2: Token Authentication (CloudFront Functions)

  • HMAC-SHA256 signature validation prevents token forgery; an attacker cannot construct a valid token without the signing key
  • Expiry enforcement (exp claim) limits the window of exposure if a token is stolen; tokens issued for live events carry a 4-hour TTL
  • IP binding (ip claim, optional) ties a token to the viewer IP at issuance time, preventing use from different IP ranges
  • Session ID in the revocation registry is checked on every request; a revoked session is blocked even with a cryptographically valid token
  • Constant-time HMAC comparison prevents timing attacks that could reveal information about the signing key

Layer 3: Automated Threat Response

  • CloudWatch anomaly detection identifies token sharing within 60 seconds of the abuse pattern emerging
  • Step Functions revocation workflow executes in under 30 seconds from alarm to WAF block rule update
  • DynamoDB revocation registry provides session-level revocation independent of IP-based WAF blocking
  • All revocation events are logged to CloudTrail and emitted as SNS notifications for the security team
  • Failed revocation workflows trigger a PagerDuty-compatible SNS alert for immediate human escalation

Cost Model

The architecture is entirely serverless: costs scale directly with usage. The following estimate covers a single live streaming event with 200,000 concurrent viewers over a 3-hour window.

CloudFront Functions

200,000 viewers × 30 segment requests/min × 180 min = 1.08 billion invocations. At $0.10 per million: ~$108 for token validation across all requests. No cold-start costs; no duration billing.

AWS WAF

WAF web ACL: $5.00/month. Rules: ~$1.00/month per rule. At 108 million requests (3 hours at 10k req/sec average), WAF evaluation costs approximately $0.60 per million = ~$65 per event. IP set rule updates from the revocation workflow: negligible.

Secrets Manager

$0.40 per secret per month. One signing secret with two active versions: $0.40/month. API calls during key rotation: ~10 calls per rotation at $0.05 per 10,000 calls, effectively free. No per-request Secrets Manager calls from CloudFront Functions.

Step Functions (Revocation + Rotation)

Express Workflows: $0.00001 per state transition. A revocation workflow with 5 states and 1 rotation per day: under $0.01/month in Step Functions charges. CloudWatch Alarms: $0.10 per alarm per month.

CloudWatch Logs + Insights

CloudFront Real-Time Logs ingest: ~500 bytes per record × 108 million records = ~54 GB per event. At $0.50/GB ingestion: ~$27 per event. Log Insights queries for revocation detection: $0.005 per GB scanned, minimal for targeted queries. Logs retained for 30 days.

Total Estimated Event Cost

CloudFront Functions: ~$108 · WAF: ~$65 · CloudWatch Logs: ~$27 · Other (Secrets, Step Functions, DynamoDB): ~$5. Total: ~$205 per event for 200,000 concurrent viewers with full token validation, session monitoring, and revocation capability.

AWS Well-Architected Framework

Operational Excellence

Fully automated operations: Key rotation, session revocation, and threat response are all orchestrated by Step Functions; no operator action required for day-to-day security operations. The Step Functions execution history provides a complete runbook audit trail.

Observable: CloudWatch dashboards surface CloudFront error rates, WAF block rates, revocation workflow execution counts, and Secrets Manager rotation status in a single view. Anomalies are alerted via SNS before they become incidents.

Security

Defence in depth: Three independent enforcement layers (WAF, CloudFront Functions, DynamoDB revocation registry) ensure no single misconfiguration exposes content.

Least privilege: The CloudFront Function code embeds the signing key directly; no IAM permissions required at request time. The token issuance service and rotation workflow each have tightly scoped IAM roles with access only to the specific Secrets Manager secret ARN they need.

Secrets management: Signing keys are never logged, never transmitted in cleartext, and never exposed in CloudFront access logs. Secrets Manager provides a KMS-encrypted store with automatic rotation and a full audit trail.

Reliability

Edge resilience: CloudFront Functions execute at every edge PoP independently. A failure in one edge location does not affect others; there is no single authentication service that can become a single point of failure.

Grace period rotation: The key rotation workflow accepts tokens signed with both current and previous keys during the grace period, ensuring zero legitimate viewer disruptions during key changes.

Revocation idempotency: The Step Functions revocation workflow is idempotent; repeated executions for the same session ID are safe and produce the same final WAF state.

Performance Efficiency

Sub-millisecond auth: CloudFront Functions validates each request in under 1 ms at the edge; authentication adds no measurable latency to the viewer experience. Lambda@Edge or origin-side auth would add 5–50 ms per request.

No origin auth traffic: All authentication decisions are made at the edge. Origin servers never receive unauthenticated requests, reducing origin load and cost.

Cost Optimisation

CloudFront Functions over Lambda@Edge: 6× cheaper per invocation for token validation: a workload that does not require Lambda@Edge's network call or 5-second timeout capabilities.

WAF blocking before function execution: Confirmed malicious IPs are blocked at WAF before reaching CloudFront Functions, eliminating function invocation costs for repeat offenders.

Serverless revocation: Step Functions Express Workflows cost fractions of a cent per execution; no always-on compute for the revocation pipeline.

Sustainability (6th Pillar)

No idle compute: The entire security stack is event-driven and serverless. CloudFront Functions only execute on incoming requests; Step Functions only run during rotation and revocation events. Zero idle energy consumption between events.

Edge enforcement: Blocking unauthorised requests at the edge prevents the wasted bandwidth and compute of serving content that will ultimately be blocked or disputed, reducing total energy per delivered authorised stream.

Engineering Decisions & Tradeoffs

Decision 1: CloudFront Functions vs Lambda@Edge for Token Validation

Chosen: CloudFront Functions, executing at 400+ PoP edge locations, sub-millisecond latency, $0.10/million invocations.

Traded away: Lambda@Edge can make network calls during execution (to DynamoDB, Secrets Manager) and has a 5-second timeout. CloudFront Functions cannot make outbound calls; the signing key must be embedded in function code.

Why acceptable: For HMAC validation, the only external dependency is the signing key, which changes infrequently (once per day via rotation). Embedding the key in function code is secure, since CloudFront Functions code is not accessible to viewers, and eliminates per-request network latency.

Decision 2: WAF IP Blocking vs Session Token Invalidation

Chosen: Both: WAF IP block rules for known offending IPs, DynamoDB revocation registry for session-level invalidation.

Why both: IP blocking is coarse-grained; a piracy operation using residential proxies rotates IPs rapidly. Session ID revocation in DynamoDB catches re-attempts from new IPs using the same token. WAF handles the bulk of repeat traffic cheaply; DynamoDB handles the edge cases.

Decision 3: Step Functions vs Lambda for Revocation Orchestration

Chosen: Step Functions Express Workflows for the revocation pipeline.

Traded away: A single Lambda function could execute the same 4 steps in a single invocation, simpler to deploy and cheaper per execution.

Why acceptable: Step Functions provides a visual execution history, built-in retry with exponential backoff on WAF API calls, and clean state separation between detection (CloudWatch), analysis (Log Insights), and action (WAF update). The audit trail is essential for security incident reporting. The cost difference is negligible at the execution frequency of a revocation workflow.

Decision 4: Static IP Binding vs No IP Binding

Chosen: IP binding as an optional per-token claim, disabled by default for live streaming, enabled for VOD.

Traded away: Mandatory IP binding would stop token sharing entirely but breaks legitimate viewer scenarios: mobile users change between WiFi and cellular mid-stream, corporate NAT assigns different egress IPs on reconnect, and IPv6 prefix delegation can change the /64 observed by the CDN.

Why acceptable: The automatic session revocation pipeline (Module B) compensates for the lack of IP binding by detecting and blocking shared tokens based on concurrent IP count, achieving similar protection without breaking legitimate viewer sessions.