#!/usr/bin/env python3
"""Minimal shared-CDN simulation: personalized HTML leak vs private/no-store.

No network, no accounts. Models a shared cache keyed by method+URL only
(cookie NOT in the key), matching the common CDN footgun described in
RFC 9111 / Vercel docs. Also shows that Vary: Cookie alone is not a
blanket fix: it either fragments the cache (generic shared cache) or is
rejected as high-cardinality (Vercel vary_key_denied:cookie).
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple


def parse_directives(cache_control: str) -> set[str]:
    return {p.strip().lower().split("=", 1)[0] for p in cache_control.split(",") if p.strip()}


@dataclass
class Response:
    status: int
    body: str
    headers: Dict[str, str]


@dataclass
class SharedCDN:
    """Shared cache: key = (method, url). Cookie is NOT part of the key."""

    store: Dict[Tuple[str, str], Response] = field(default_factory=dict)
    name: str = "shared-cdn"

    def _cacheable(self, resp: Response) -> bool:
        cc = resp.headers.get("Cache-Control", "")
        dirs = parse_directives(cc)
        if "private" in dirs or "no-store" in dirs or "no-cache" in dirs:
            return False
        # Require an explicit shared freshness signal (s-maxage or public+max-age)
        if "s-maxage" in dirs:
            return True
        if "public" in dirs and "max-age" in dirs:
            return True
        return False

    def fetch(self, method: str, url: str, cookie: Optional[str], origin) -> Tuple[str, Response]:
        key = (method, url)
        if key in self.store:
            return "HIT", self.store[key]
        resp = origin(method, url, cookie)
        if self._cacheable(resp):
            self.store[key] = resp
            return "MISS+STORE", resp
        return "MISS+BYPASS", resp


@dataclass
class VercelLikeCDN(SharedCDN):
    """Like SharedCDN, but refuses to store when Vary includes Cookie."""

    name: str = "vercel-like-cdn"

    def _cacheable(self, resp: Response) -> bool:
        if not super()._cacheable(resp):
            return False
        vary = resp.headers.get("Vary", "")
        parts = {p.strip().lower() for p in vary.split(",") if p.strip()}
        if "cookie" in parts or "*" in parts:
            return False  # vary_key_denied:cookie / Vary:*
        return True


def make_origin(mode: str):
    """mode: bad_public | private_nostore | vary_cookie_public"""

    def origin(method: str, url: str, cookie: Optional[str]) -> Response:
        assert method == "GET" and url == "/account"
        user = "anonymous"
        if cookie and cookie.startswith("session="):
            user = cookie.split("=", 1)[1]
        body = f"<html>Hello {user}; balance=secret-{user}</html>"
        if mode == "bad_public":
            headers = {"Cache-Control": "public, s-maxage=60, max-age=0"}
        elif mode == "private_nostore":
            headers = {"Cache-Control": "private, no-store"}
        elif mode == "vary_cookie_public":
            headers = {
                "Cache-Control": "public, s-maxage=60, max-age=0",
                "Vary": "Cookie",
            }
        else:
            raise ValueError(mode)
        return Response(200, body, headers)

    return origin


def run_scenario(cdn, mode: str, label: str) -> None:
    origin = make_origin(mode)
    cdn.store.clear()
    print(f"\n== {label}")
    print(f"cdn={cdn.name}  origin_mode={mode}")

    alice = cdn.fetch("GET", "/account", "session=alice", origin)
    bob = cdn.fetch("GET", "/account", "session=bob", origin)
    print(f"alice: {alice[0]}  body={alice[1].body}")
    print(f"bob:   {bob[0]}  body={bob[1].body}")
    leaked = "alice" in bob[1].body and bob[0] == "HIT"
    print(f"LEAK_TO_BOB={leaked}")
    if mode == "vary_cookie_public" and isinstance(cdn, VercelLikeCDN):
        print("note: Vary:Cookie -> not stored (vary_key_denied:cookie analogue); no cross-user HIT")
    if mode == "vary_cookie_public" and type(cdn) is SharedCDN:
        # Generic shared cache that honors Vary would key by cookie; we still
        # demonstrate the wrong mental model of "Vary Cookie makes public safe"
        # by showing SharedCDN without Vary keying (the footgun) above, and
        # separately a Vary-aware path:
        print("note: this SharedCDN ignores Vary (footgun demo). Vary-aware path next.")


def run_vary_aware() -> None:
    """Minimal Vary-aware shared cache: key includes Cookie when Vary says so."""

    @dataclass
    class VaryAwareCDN:
        store: Dict[Tuple, Response] = field(default_factory=dict)

        def fetch(self, method, url, cookie, origin):
            resp_probe = None
            # Look up with tentative key; on miss call origin then decide key
            # First try URL-only if we somehow stored that; else miss.
            url_key = (method, url, None)
            # Always miss-first for clarity: call origin
            resp = origin(method, url, cookie)
            vary = {p.strip().lower() for p in resp.headers.get("Vary", "").split(",") if p.strip()}
            if "cookie" in vary:
                key = (method, url, cookie)
            else:
                key = (method, url, None)
            if key in self.store:
                return "HIT", self.store[key]
            dirs = parse_directives(resp.headers.get("Cache-Control", ""))
            cacheable = "s-maxage" in dirs and "private" not in dirs and "no-store" not in dirs
            if cacheable:
                self.store[key] = resp
                return "MISS+STORE", resp
            return "MISS+BYPASS", resp

    cdn = VaryAwareCDN()
    origin = make_origin("vary_cookie_public")
    print("\n== Vary-aware shared cache + Vary: Cookie + public s-maxage")
    a = cdn.fetch("GET", "/account", "session=alice", origin)
    b = cdn.fetch("GET", "/account", "session=bob", origin)
    a2 = cdn.fetch("GET", "/account", "session=alice", origin)
    print(f"alice1: {a[0]}  body={a[1].body}")
    print(f"bob:    {b[0]}  body={b[1].body}")
    print(f"alice2: {a2[0]}  body={a2[1].body}")
    print(f"LEAK_TO_BOB={'alice' in b[1].body and b[0] == 'HIT'}")
    print("note: no leak, but cache fragments per cookie (rarely reused); Vercel refuses to store")


def main() -> None:
    print("CDN personalized-response leak toy")
    print("shared cache key = (GET, /account); Cookie NOT in key unless Vary-aware")

    run_scenario(SharedCDN(), "bad_public", "1) BAD: public s-maxage on personalized HTML")
    run_scenario(SharedCDN(), "private_nostore", "2) SAFE: private, no-store")
    run_scenario(SharedCDN(), "vary_cookie_public", "3a) FOOTGUN demo: SharedCDN ignores Vary")
    run_scenario(VercelLikeCDN(), "vary_cookie_public", "3b) Vercel-like: Vary Cookie not stored")
    run_vary_aware()

    print("\n== checklist summary")
    print("authenticated/personalized HTML -> Cache-Control: private, no-store; no CDN-Cache-Control / Vercel-CDN-Cache-Control")
    print("do NOT use Vary: Cookie as the blanket 'make personalization safe' fix")
    print("SWR/stale-while-revalidate is about freshness, not identity isolation")


if __name__ == "__main__":
    main()
