</>Học Dev
Bài học

Tuần 6 - Ngày 3: ACM và CloudFront Security

Tuần 6 – Ngày 3

Tuần 6 - Ngày 3: ACM và CloudFront Security

Mục tiêu học tập

  • Hiểu AWS Certificate Manager (ACM) cấp SSL/TLS certs miễn phí
  • Nắm CloudFront fundamentals + caching
  • Bảo vệ origin với OAC (Origin Access Control)
  • Implement signed URLs / signed cookies

1. AWS Certificate Manager (ACM)

Định nghĩa

ACM = managed SSL/TLS certificate service.

Đặc điểm

  • Free cho certs dùng với AWS services (CloudFront, ALB, NLB, API GW)
  • Auto-renewal trước khi expire
  • Support public certs (DV - Domain Validation) và private certs (qua AWS Private CA)
  • Regional: cert ở region nào dùng cho services ở region đó (trừ CloudFront)

CloudFront special case

  • CloudFront yêu cầu cert ở us-east-1 (N. Virginia)
  • Vì CloudFront là global, dùng us-east-1 làm "home"

Validation methods

  • DNS validation (recommended): add CNAME record vào DNS
  • Email validation: AWS gửi email đến admin@domain.com

Workflow public cert

1. Request certificate trong ACM
2. Choose validation: DNS or Email
3. Validate ownership (add CNAME if DNS)
4. Cert issued (few minutes)
5. Deploy to ALB / CloudFront / API GW
6. Auto-renew khi 60 days before expire

Limitations

  • Free public certs: không export private key (chỉ dùng trong AWS)
  • Cần export private key → dùng AWS Private CA ($)

2. CloudFront Fundamentals

Định nghĩa

CloudFront = global CDN (Content Delivery Network), cache content tại 600+ edge locations.

Đặc điểm

  • Low latency: serve content từ edge gần user
  • DDoS protection: AWS Shield Standard included free
  • Origin types:
    • S3 bucket
    • ALB / NLB
    • EC2 / Custom HTTP origin
    • API Gateway
    • Lambda Function URL
    • MediaStore / MediaPackage
  • HTTPS: SSL via ACM
  • HTTP/2, HTTP/3 (QUIC) support

Pricing

  • Pay per request + data transfer out (edge → user)
  • Free tier: 1 TB data transfer out + 10M requests/month (forever free)
  • Cheaper than direct S3/ALB data transfer

Cost optimization

  • CloudFront data transfer out ($0.085/GB) cheaper than EC2 direct ($0.09/GB)
  • Cache hit reduces origin load (origin tính bandwidth riêng)

3. CloudFront Distribution

Components

  • Distribution: top-level config (e.g., d1234.cloudfront.net)
  • Origins: backends (S3, ALB, ...)
  • Behaviors: routing rules per path pattern
  • Cache settings: TTL, headers, query strings to forward
  • Security: WAF, signed URLs

Architecture

User → CloudFront Edge → Regional Edge Cache → Origin
        (600+ locations)   (~13 locations)     (S3, ALB)
              ↓
           Cache lookup
              ↓
          Cache HIT → Serve from edge (fast)
          Cache MISS → Fetch from origin → Cache → Serve

4. Caching Behavior

Cache Key

Combination of fields that uniquely identify a cached object:

  • URL path (default)
  • Optional: Query strings, headers, cookies

TTL (Time to Live)

  • Default TTL: 24 hours
  • Min/Max TTL: configurable
  • Cache headers from origin: Cache-Control: max-age=N, Expires: date

Cache invalidation

  • Invalidate: remove from cache before TTL expires
  • Pattern: /images/* or specific path
  • First 1000 invalidations/month free, then $0.005/path

Best practice

  • High TTL for static assets (CSS, JS, images): months
  • Low TTL for dynamic content: seconds-minutes
  • Cache versioning: add hash to filename (app.v123.js) instead of invalidating

5. Origin Access Control (OAC)

Vấn đề

S3 bucket exposed publicly để CloudFront access → users có thể bypass CloudFront (truy cập S3 trực tiếp, không qua WAF, không cache).

Giải pháp: OAC

  • CloudFront có IAM identity, có thể signed request to S3
  • S3 bucket policy chỉ allow access từ CloudFront distribution (qua OAC)
  • Block direct S3 access

OAC vs OAI (legacy)

  • OAI (Origin Access Identity): older, supports only S3 buckets (SSE-S3)
  • OAC (Origin Access Control): newer, supports S3 + SSE-KMS + CRR + Object Lambda
  • Recommended: OAC for new distributions

Bucket policy example

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": { "Service": "cloudfront.amazonaws.com" },
    "Action": "s3:GetObject",
    "Resource": "arn:aws:s3:::my-bucket/*",
    "Condition": {
      "StringEquals": {
        "AWS:SourceArn": "arn:aws:cloudfront::111111111111:distribution/DIST_ID"
      }
    }
  }]
}

6. CloudFront Signed URLs and Cookies

Use case

Restrict access to paid content (videos, downloads) — only authorized users.

Signed URL

  • URL với signature
  • Access single file
  • Generated bằng private key
  • Cookie với signature
  • Access multiple files (entire site or directory)
  • Generated bằng private key

Workflow

1. User requests content from app
2. App authenticates user, authorizes
3. App generates signed URL/cookie (using CloudFront key pair)
4. User uses signed URL/cookie to access CloudFront
5. CloudFront validates signature, serves content (or denies)

Trusted Signers vs Trusted Key Groups

Trusted Signers (legacy)Trusted Key Groups (modern)
KeyAccount root userPublic keys group
RecommendedNoYes

7. Geo Restriction

2 modes

  • Whitelist: only allow listed countries
  • Blacklist: block listed countries

Use case

  • Compliance (copyright, licensing per country)
  • Block adversarial regions
  • Compliance (GDPR)

8. CloudFront with HTTPS

SSL/TLS termination

  • HTTPS at edge: cert via ACM (us-east-1)
  • HTTPS to origin: optional (recommended)

Cipher policies

  • TLS 1.2 minimum (recommended)
  • Modern policies: ECDHE, AES-GCM

9. CloudFront Functions vs Lambda@Edge

CloudFront Functions

  • Lightweight JavaScript (~1 KB)
  • Sub-millisecond execution
  • Run at edge (all 600+ locations)
  • Use case: simple header manipulation, URL rewrites, redirects
  • Free tier: 2M requests/month
  • No external network access

Lambda@Edge

  • Full Lambda (Node.js, Python)
  • Up to 5 seconds execution
  • Run at Regional Edge Cache (~13 locations)
  • Use case: complex logic, A/B testing, dynamic content
  • Standard Lambda pricing
  • Can call external services (DB, APIs)

Comparison

CloudFront FunctionsLambda@Edge
LanguageJavaScript onlyNode.js, Python
Memory2 MB128 MB - 10 GB
Max execution1 ms5-30 sec
Network accessNoYes
CostVery cheapStandard Lambda
Use caseHeader rewrite, simpleComplex logic

CloudFront events

  • Viewer Request (before cache lookup)
  • Origin Request (before forward to origin)
  • Origin Response (after origin response)
  • Viewer Response (before response to user)

10. CloudFront Patterns

Pattern 1: Static website (S3 + CloudFront)

S3 (private) ← OAC ← CloudFront ← User
              SSL via ACM
              WAF for security

Pattern 2: Dynamic + Static

Dynamic (api.example.com):
  CloudFront → ALB → ECS

Static (cdn.example.com):
  CloudFront → S3 (with OAC)

Pattern 3: Paid content

User → App (auth) → Generates signed URL
User → CloudFront (signed URL) → Origin

Pattern 4: A/B testing

User → CloudFront → Lambda@Edge (random pick A/B) → Origin A or B

11. CloudFront vs Global Accelerator

CloudFrontGlobal Accelerator
Use caseHTTP/HTTPS content cachingNon-HTTP (TCP/UDP), routing
CachingYesNo
Static IPsNo (DNS)Yes (2 anycast)
ProtocolsHTTP, HTTPSTCP, UDP
Use case examplesWeb content, video streamingGaming, IoT, financial

Câu hỏi ôn tập

  1. CloudFront cert ACM phải ở Region nào?

    Xem đáp án

    us-east-1 (N. Virginia) — CloudFront là global service nhưng chỉ đọc ACM certificates từ us-east-1. Nếu provision cert ở Region khác sẽ không thấy trong CloudFront. Đây là điểm hay bị sai trong thực tế: team provision cert ở ap-southeast-1 nhưng CloudFront không tìm thấy. Cert cho ALB/API GW có thể provision tại Region của resource đó.

  2. OAC khác OAI ở điểm gì? Khi nào dùng OAC?

    Xem đáp án

    OAI (Origin Access Identity): legacy, chỉ S3 standard, không hỗ trợ SSE-KMS encryption. OAC (Origin Access Control): thế hệ mới, hỗ trợ S3 + SSE-KMS encrypted objects, hỗ trợ cross-account, HTTP method signing. AWS khuyến nghị dùng OAC thay OAI cho tất cả deployments mới. Cả hai đều cho phép CloudFront access S3 bucket private mà không cần public access.

  3. Khác biệt CloudFront Signed URL vs Signed Cookie?

    Xem đáp án

    Signed URL: restrict access đến 1 file cụ thể — URL chứa signature, expiry, IP restrictions. Phù hợp khi share link download cho 1 file. Signed Cookie: restrict access đến nhiều files trong cùng phiên — browser gửi cookie theo mọi request. Phù hợp cho premium content, video streaming (nhiều segments), khi URL cần giữ sạch (không muốn append signature vào URL).

  4. CloudFront Functions vs Lambda@Edge: cái nào cho phép external network calls?

    Xem đáp án

    Chỉ Lambda@Edge — có thể gọi external APIs, DynamoDB, Secrets Manager. CloudFront Functions: không có network access, không có filesystem, execution time < 1ms, rẻ hơn nhiều (~1/6 giá). Phù hợp cho lightweight operations: URL rewrite, header manipulation, simple A/B routing. Lambda@Edge: CPU-intensive, complex logic, cần external data, max 5-30 giây execution.

  5. Khi nào dùng CloudFront vs Global Accelerator?

    Xem đáp án

    CloudFront: tối ưu cho HTTP/HTTPS workloads với cacheable content — website, APIs, static assets. CloudFront cache tại Edge Locations. Global Accelerator: tối ưu cho any TCP/UDP traffic (gaming, IoT, VoIP), không cache, cần static IP addresses (NLB-fronting), hoặc cần route non-HTTP traffic. Global Accelerator cũng hỗ trợ HTTP nhưng không cache — phù hợp cho dynamic content, health routing between regions.

Bài tập thực hành

  • Request ACM cert cho domain ở us-east-1 (DNS validation)
  • Setup CloudFront distribution với S3 origin + OAC
  • Test direct S3 access bị deny, qua CloudFront thành công
  • Tạo signed URL cho 1 object, expire 1 hour
  • Setup Geo Restriction blacklist 2 countries
  • Tạo CloudFront Function rewrite URL /api/v2/api

Tài liệu tham khảo chính thức


Tiếp theo: WAF và Shield