diff --git a/.github/workflows/migration-demo.yml b/.github/workflows/migration-demo.yml new file mode 100644 index 00000000..63234094 --- /dev/null +++ b/.github/workflows/migration-demo.yml @@ -0,0 +1,44 @@ +name: Published migration before-and-after demo + +on: + pull_request: + branches: [stable] + paths: + - "examples/migration/**" + - "examples/README.md" + - "site_docs/migration.md" + - "tests/test_migration_demo_contract.py" + - ".github/workflows/migration-demo.yml" + push: + branches: [stable] + paths: + - "examples/migration/**" + - "examples/README.md" + - "site_docs/migration.md" + - "tests/test_migration_demo_contract.py" + - ".github/workflows/migration-demo.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + before-after: + name: Published old/new demo on Py ${{ matrix.python }} + runs-on: ubuntu-24.04 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12"] + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: ${{ matrix.python }} + - name: Verify demo Python syntax (without importing the checkout) + run: python -m compileall -q examples/migration + - name: Run reproducible published-vs-published demo + run: python examples/migration/run_demo.py diff --git a/README.md b/README.md index b75324e7..c2bd1c6a 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,8 @@ See [compatibility & risk matrix](https://github.com/agustin18/fastapi-cache/blo | **Checking security** | [Tenant and request safety](site_docs/guides/privacy.md) · [Security policy](SECURITY.md) | Default auth bypass, custom headers, cache-key isolation | | **Looking ahead** | [Next release plan](site_docs/roadmap.md) · [#86 tracker](https://github.com/agustin18/fastapi-cache/issues/86) | 0.6.0 candidates, not publication promises | +**Try it:** [one-command before/after migration demo](examples/migration/README.md) (two isolated published environments, no Redis or credentials). + **Published:** [fastapi-cache-stable 0.5.0](https://pypi.org/project/fastapi-cache-stable/0.5.0/). The new searchable site is in [site_docs/](site_docs/index.md) and has a **CI build preview**; it is not claimed to be hosted publicly until a separate deployment is approved. diff --git a/changelog.d/88.doc.md b/changelog.d/88.doc.md new file mode 100644 index 00000000..4ae87b39 --- /dev/null +++ b/changelog.d/88.doc.md @@ -0,0 +1 @@ +Add a cross-platform, isolated before/after migration demo for published fastapi-cache2 0.2.2 and fastapi-cache-stable 0.5.0, illustrating unchanged imports, ordinary cache hits, and intentional private-request safety differences. diff --git a/examples/README.md b/examples/README.md index c88f0f6d..effb2a3b 100644 --- a/examples/README.md +++ b/examples/README.md @@ -12,6 +12,11 @@ python -m pip install "fastapi-cache-stable" uvicorn python -m pip install "fastapi-cache-stable[redis]" uvicorn ``` +To see **the same FastAPI app before and after migrating from `fastapi-cache2`**, +run the [one-command migration demo](migration/README.md). It installs the two +distributions in separate temporary virtual environments and compares safe +default behavior, without touching any Redis instance. + Run from the repository root, for example: ```sh diff --git a/examples/migration/README.md b/examples/migration/README.md new file mode 100644 index 00000000..ce9ce99e --- /dev/null +++ b/examples/migration/README.md @@ -0,0 +1,87 @@ +# Before and after: migrating one FastAPI app + +**Published baseline:** `fastapi-cache2==0.2.2` → `fastapi-cache-stable==0.5.0`. +The same [app.py](app.py), with the same `fastapi_cache` imports and +`@cache` decorators, runs twice in **different disposable environments**. + +Run from a checkout on **CPython 3.11 or 3.12**. The script is **designed for Windows, macOS and Linux**, but automated end-to-end execution has been verified **only on Linux** (Python 3.11 and 3.12); other platforms still need independent smoke tests: + +```console +python examples/migration/run_demo.py +``` + +You need Internet access to install the two pinned published distributions +and their pinned FastAPI/Pydantic/httpx comparison environment. The runner +creates two temporary virtual environments, calls `pip check` in each, +executes the app with `python -I` so it cannot accidentally import the +checkout, compares JSON results, and deletes the environments. No server, +Docker, Redis, credentials, or existing database is used. + +Expected end of the output: + +```text +PASS: unchanged FastAPI imports, ordinary MISS -> HIT, ETag 304 +PASS: legacy private-data reuse reproduced with fictional identities +PASS: published 0.5.0 bypasses protected requests by default +NOTE: this is not evidence of safe rollback for authenticated data +Temporary environments deleted; host environment unchanged. +``` + +## What it demonstrates + +| The same endpoint | Legacy 0.2.2 | Published fork 0.5.0 | +|---|---|---| +| Anonymous `/public` | MISS → HIT | MISS → HIT | +| Conditional request with ETag | 304 | 304 | +| `/viewer` with two *fictional* `Authorization` markers | Second request incorrectly receives the first demo viewer | Both requests run independently; no cache status | +| Python import | `from fastapi_cache ...` | **Exactly the same import** | + +The viewer example deliberately characterizes a known upstream weakness +**using fake identities only**. Never paste a real token or run this legacy +example against private/production data. This is an InMemory onboarding +demonstration, **not** verification that every consumer or hidden +tenant/role/middleware context is isolated automatically. + +## Production migration and rollback are separate gates + +For persisted Redis data, custom key builders, private cache namespaces and +rollbacks, use the [migration checklist](../../MIGRATION.md) and the existing +[Redis 7.4 migration/rollback integration workflow](../../.github/workflows/migration-candidate-phase-b.yml). +That evidence exercises a legacy writer, the new reader, selective namespace +cleanup, an independent consumer and a **package** rollback. It does **not** +endorse restoring legacy authenticated response caching. + +Do not co-install the two distributions: both own the same `fastapi_cache` +module. This demo does not change PyPI artifacts or introduce new runtime +dependencies. Before a future 0.6.0 launch, re-run the comparison against the +**exact published 0.6.0 artifact** in an independently reviewed release gate; +this 0.5.0 demonstration cannot certify an unreleased version. + +## Required 0.6.0 refresh checklist (not yet completed) + +This runnable tutorial is **deliberately pinned to already-published 0.5.0**. +Do not rename it to a 0.6.0 verification based on source code or a successful +0.5.0 CI run. When the exact release candidate is built and independently +reviewed, the release owner must: + +1. Run the **separate candidate wheel/sdist and Redis migration/rollback + workflow** at the final source SHA; this published-vs-published demo + cannot substitute for those release gates. +2. After **0.6.0 is actually published**, update the replacement pin in + `run_demo.py`, the distribution-version assertion in `app.py`, + the expected version and explanatory output in `compare.py`, the + negative-test fixtures in `tests/test_migration_demo_contract.py`, + this README, and links/version claims in the onboarding docs. +3. Re-run `pip check`, isolated `python -I` execution and the comparison + against **downloaded, installed 0.6.0 distribution artifacts**. + Preserve the previous 0.5.0 result as historical evidence, and record + exact artifact hashes and source SHA in release evidence. +4. Validate the refreshed tutorial on Linux CI for both supported demo + interpreters; run additional Windows/macOS smoke lanes before claiming + those platforms have been verified. +5. Keep **two genuine external consumers** as an independent requirement + under [#88](https://github.com/agustin18/fastapi-cache/issues/88); + this in-repository tutorial counts as **zero** such consumers. + +Release pin updates must not silently replace previously published audit +evidence. Nothing in this checklist authorizes PyPI publication. diff --git a/examples/migration/app.py b/examples/migration/app.py new file mode 100644 index 00000000..4396bc6f --- /dev/null +++ b/examples/migration/app.py @@ -0,0 +1,104 @@ +# ruff: noqa: S101 - demo assertions are intentional fail-closed checks +"""Same unchanged FastAPI application under two separately installed providers. + +This is a deliberately artificial, local-only, InMemory example. It exposes +legacy private cache reuse with *fictional* identities; never use real tokens. +""" + +from __future__ import annotations + +import importlib.metadata as metadata +import json +import sys +from pathlib import Path + +import fastapi_cache +from fastapi import FastAPI, Request, Response +from fastapi.testclient import TestClient +from fastapi_cache import FastAPICache +from fastapi_cache.backends.inmemory import InMemoryBackend +from fastapi_cache.decorator import cache + +app = FastAPI() +calls = {"public": 0, "viewer": 0} + + +@app.get("/public") +@cache(namespace="public", expire=120) +async def public(response: Response) -> dict[str, int]: + calls["public"] += 1 + return {"calls": calls["public"]} + + +@app.get("/viewer") +@cache(namespace="viewer", expire=120) +async def viewer(request: Request) -> dict[str, str]: + # These are fictitious markers, NOT credentials or an authentication demo. + calls["viewer"] += 1 + demo_marker = request.headers.get("Authorization") + return {"viewer": "alice" if demo_marker == "Bearer demo-alice" else "bob"} + + +def _status(response: Response) -> str | None: + return response.headers.get("X-FastAPI-Cache") + + +def main() -> None: + if len(sys.argv) != 2 or sys.argv[1] not in ("legacy", "replacement"): + raise SystemExit("Usage: app.py legacy|replacement") + mode = sys.argv[1] + distribution = ( + "fastapi-cache2" if mode == "legacy" else "fastapi-cache-stable" + ) + other = ( + "fastapi-cache-stable" if mode == "legacy" else "fastapi-cache2" + ) + version = "0.2.2" if mode == "legacy" else "0.5.0" + assert metadata.version(distribution) == version + + try: + metadata.version(other) + except metadata.PackageNotFoundError: + pass + else: + raise AssertionError("The two providers must never be co-installed") + + module = Path(fastapi_cache.__file__).resolve() + assert "site-packages" in module.parts, module + + FastAPICache.init(InMemoryBackend(), prefix="migration-demo") + with TestClient(app) as client: + first = client.get("/public") + second = client.get("/public") + conditional = client.get( + "/public", + headers={"If-None-Match": second.headers["ETag"]}, + ) + alice = client.get( + "/viewer", headers={"Authorization": "Bearer demo-alice"} + ) + bob = client.get( + "/viewer", headers={"Authorization": "Bearer demo-bob"} + ) + + assert first.status_code == second.status_code == 200 + assert first.json() == second.json() == {"calls": 1} + assert conditional.status_code == 304 + assert conditional.content == b"" + + report = { + "distribution": distribution, + "version": version, + "public_statuses": [_status(first), _status(second)], + "conditional_status": conditional.status_code, + "viewer_statuses": [_status(alice), _status(bob)], + "viewer_results": [ + alice.json()["viewer"], + bob.json()["viewer"], + ], + } + print(json.dumps(report, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/examples/migration/compare.py b/examples/migration/compare.py new file mode 100644 index 00000000..33c775fd --- /dev/null +++ b/examples/migration/compare.py @@ -0,0 +1,49 @@ +# ruff: noqa: S101 - comparison deliberately asserts migration safety +"""Fail-closed before/after comparison of two isolated demo executions.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any + + +def verify(legacy: dict[str, Any], replacement: dict[str, Any]) -> None: + assert (legacy["distribution"], legacy["version"]) == ( + "fastapi-cache2", + "0.2.2", + ) + assert (replacement["distribution"], replacement["version"]) == ( + "fastapi-cache-stable", + "0.5.0", + ) + + for report in (legacy, replacement): + assert report["public_statuses"] == ["MISS", "HIT"] + assert report["conditional_status"] == 304 + + # Published upstream deliberately exhibits the bug in this isolated, + # fictional demonstration. This is not behavior to preserve in production. + assert legacy["viewer_statuses"] == ["MISS", "HIT"] + assert legacy["viewer_results"] == ["alice", "alice"] + + # The published fork bypasses auth-derived results by default. + assert replacement["viewer_statuses"] == [None, None] + assert replacement["viewer_results"] == ["alice", "bob"] + + +def main() -> None: + if len(sys.argv) != 3: + raise SystemExit("Usage: compare.py legacy.json replacement.json") + legacy = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) + replacement = json.loads(Path(sys.argv[2]).read_text(encoding="utf-8")) + verify(legacy, replacement) + print("PASS: unchanged FastAPI imports, ordinary MISS -> HIT, ETag 304") + print("PASS: legacy private-data reuse reproduced with fictional identities") + print("PASS: published 0.5.0 bypasses protected requests by default") + print("NOTE: this is not evidence of safe rollback for authenticated data") + + +if __name__ == "__main__": + main() diff --git a/examples/migration/run_demo.py b/examples/migration/run_demo.py new file mode 100644 index 00000000..49e8be79 --- /dev/null +++ b/examples/migration/run_demo.py @@ -0,0 +1,90 @@ +"""Cross-platform single-command before/after migration demo. + +Creates two disposable virtual environments; never installs both packages +into one interpreter or touches Redis, credentials or production data. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +import tempfile +import venv +from pathlib import Path + +FRAMEWORK = ("fastapi==0.111.1", "pydantic==2.8.2", "httpx==0.27.0") +PROVIDERS = { + "legacy": "fastapi-cache2==0.2.2", + "replacement": "fastapi-cache-stable==0.5.0", +} +DIRECTORY = Path(__file__).resolve().parent + + +def _python_in_venv(folder: Path) -> Path: + if sys.platform == "win32": + return folder / "Scripts" / "python.exe" + return folder / "bin" / "python" + + +def _run(executable: Path, args: list[str], cwd: Path) -> str: + completed = subprocess.run( # noqa: S603 - trusted local venv interpreter and fixed args + [str(executable), *args], + cwd=str(cwd), + check=True, + text=True, + stdout=subprocess.PIPE, + ) + return completed.stdout + + +def _probe(root: Path, mode: str) -> dict[str, object]: + environment = root / mode + venv.EnvBuilder(with_pip=True).create(str(environment)) + python = _python_in_venv(environment) + print(f"Installing isolated {PROVIDERS[mode]} ...", flush=True) + _run( + python, + [ + "-m", "pip", "install", "--disable-pip-version-check", + PROVIDERS[mode], *FRAMEWORK, + ], + root, + ) + _run(python, ["-m", "pip", "check"], root) + output = _run(python, ["-I", str(DIRECTORY / "app.py"), mode], root) + report: dict[str, object] = json.loads(output) + (root / f"{mode}.json").write_text( + json.dumps(report, indent=2) + "\n", encoding="utf-8" + ) + return report + + +def main() -> None: + if sys.version_info[:2] not in {(3, 11), (3, 12)}: + raise SystemExit( + "This pinned demonstration was verified on CPython 3.11/3.12. " + "Use one of those versions; this is not a library support limit." + ) + with tempfile.TemporaryDirectory(prefix="fastapi-cache-demo-") as temp: + root = Path(temp) + for mode in ("legacy", "replacement"): + _probe(root, mode) + print( + _run( + Path(sys.executable), + [ + "-I", + str(DIRECTORY / "compare.py"), + str(root / "legacy.json"), + str(root / "replacement.json"), + ], + root, + ), + end="", + ) + print("Temporary environments deleted; host environment unchanged.") + + +if __name__ == "__main__": + main() diff --git a/site_docs/migration.md b/site_docs/migration.md index ecdb9a81..322280bc 100644 --- a/site_docs/migration.md +++ b/site_docs/migration.md @@ -64,6 +64,16 @@ from fastapi_cache.decorator import cache !!! danger "Hidden identity is not automatically safe" Headers like `X-API-Key`, tenant identity in `request.state`, middleware or `ContextVar` may not affect the default key. HTTP `Vary` alone does not partition the internal cache. See [privacy](guides/privacy.md) and [#53 residual](https://github.com/agustin18/fastapi-cache/issues/53). +## See the same app before and after + +The [runnable before/after demo](https://github.com/agustin18/fastapi-cache/blob/stable/examples/migration/README.md) +starts the **same FastAPI source** in two disposable virtual environments: +published `fastapi-cache2==0.2.2` and published `fastapi-cache-stable==0.5.0`. +It proves an ordinary MISS/HIT and ETag/304 stay functional, and illustrates +the intentional safer default for fictitious authenticated requests. +It uses InMemory, **not** persisted Redis, and is not proof that arbitrary +private/tenant state or rollback is safe. + ## Smoke-test before traffic 1. GET anonymously: **MISS → HIT**; include ETag/304. diff --git a/tests/test_migration_demo_contract.py b/tests/test_migration_demo_contract.py new file mode 100644 index 00000000..96f76c40 --- /dev/null +++ b/tests/test_migration_demo_contract.py @@ -0,0 +1,74 @@ +"""The public onboarding comparison fails closed on unsafe regressions.""" + +from __future__ import annotations + +from copy import deepcopy +from pathlib import Path +from typing import Any + +import pytest + +from examples.migration.compare import verify + + +def _reports() -> tuple[dict[str, Any], dict[str, Any]]: + return ( + { + "distribution": "fastapi-cache2", + "version": "0.2.2", + "public_statuses": ["MISS", "HIT"], + "conditional_status": 304, + "viewer_statuses": ["MISS", "HIT"], + "viewer_results": ["alice", "alice"], + }, + { + "distribution": "fastapi-cache-stable", + "version": "0.5.0", + "public_statuses": ["MISS", "HIT"], + "conditional_status": 304, + "viewer_statuses": [None, None], + "viewer_results": ["alice", "bob"], + }, + ) + + +def test_public_migration_demo_expected_contract() -> None: + legacy, replacement = _reports() + verify(legacy, replacement) + + +@pytest.mark.parametrize( + ("field", "bad_value"), + [ + ("version", "0.6.0"), + ("public_statuses", ["MISS", "MISS"]), + ("conditional_status", 200), + ("viewer_statuses", ["MISS", "HIT"]), + ("viewer_results", ["alice", "alice"]), + ], +) +def test_comparator_rejects_false_security_or_release_claims( + field: str, bad_value: object +) -> None: + legacy, replacement = _reports() + replacement = deepcopy(replacement) + replacement[field] = bad_value + with pytest.raises(AssertionError): + verify(legacy, replacement) + + +def test_demo_keeps_providers_separate_and_no_external_cache() -> None: + root = Path(__file__).resolve().parents[1] + runner = (root / "examples/migration/run_demo.py").read_text( + encoding="utf-8" + ) + app = (root / "examples/migration/app.py").read_text( + encoding="utf-8" + ) + assert "venv.EnvBuilder(with_pip=True)" in runner + assert '"-I"' in runner + assert "TemporaryDirectory" in runner + assert '"fastapi-cache2==0.2.2"' in runner + assert '"fastapi-cache-stable==0.5.0"' in runner + assert "redis.Redis" not in app + assert "Bearer demo-alice" in app