diff --git a/.github/workflows/docs-pages.yml b/.github/workflows/docs-pages.yml new file mode 100644 index 00000000..fa5ad4e4 --- /dev/null +++ b/.github/workflows/docs-pages.yml @@ -0,0 +1,74 @@ +name: Publish documentation to GitHub Pages (manual) + +# Explicit publication only. Merging this PR never deploys a website. +on: + workflow_dispatch: + +permissions: {} + +concurrency: + group: fastapi-cache-pages + cancel-in-progress: false + +jobs: + build: + name: Build and validate current published-docs site + if: github.ref == 'refs/heads/stable' + runs-on: ubuntu-24.04 + permissions: + contents: read + timeout-minutes: 15 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 + with: + python-version: "3.12" + - name: Install pinned documentation tool + run: python -m pip install "zensical==0.1.3" + - name: Build site from committed sources + run: zensical build --clean + - name: Validate every local link and HTML anchor + run: python scripts/check_docs_links.py --site-dir site --base-path /fastapi-cache + - name: Validate release and migration entry points + run: | + python - <<'PY' + from pathlib import Path + for page in ( + "index.html", + "getting-started/index.html", + "migration/index.html", + "reference/features/index.html", + "guides/privacy/index.html", + "reference/alternatives/index.html", + ): + file = Path("site") / page + if not file.is_file(): + raise SystemExit(f"Missing built docs page: {file}") + main = (Path("site") / "index.html").read_text(encoding="utf-8") + if "0.5.0" not in main or "fastapi-cache2" not in main: + raise SystemExit("Docs landing must identify the current published version") + PY + - name: Upload validated static output + uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 + with: + path: site/ + + deploy: + name: Deploy Pages (requires approved manual run) + if: github.ref == 'refs/heads/stable' + needs: build + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Prepare GitHub Pages in deploy-only permission boundary + uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d + - name: Deploy + id: deployment + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 diff --git a/.github/workflows/docs-site.yml b/.github/workflows/docs-site.yml index d14e1805..1b32b7dc 100644 --- a/.github/workflows/docs-site.yml +++ b/.github/workflows/docs-site.yml @@ -67,7 +67,7 @@ jobs: assert "fastapi-cache-stable==0.4.1" not in quickstart PY - name: Validate every built HTML link, target file and page fragment - run: python scripts/check_docs_links.py --site-dir site + run: python scripts/check_docs_links.py --site-dir site --base-path /fastapi-cache - name: Upload preview without publishing a website if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 diff --git a/ROADMAP.md b/ROADMAP.md index 8d5837fd..4b39ecf9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -40,6 +40,27 @@ Proven #53 privacy defects outrank the feature roadmap. Never inherit 0.5.0's release-specific security acceptance for a different SHA. +## Adoption and competitive documentation (0.6.0 proposal) + +- [#88](https://github.com/agustin18/fastapi-cache/issues/88): + **first coordinated public promotion**, not the first PyPI release; + published 0.5.0 stays the baseline until a separate reviewed 0.6.0. +- [#48](https://github.com/agustin18/fastapi-cache/issues/48): + navigable Zensical docs sources shipped in #87. A separate manual-only + GitHub Pages workflow, tested preview, API reference and comparison guide + are proposed; publication and live URL verification require approval. +- [Alternatives guide](site_docs/reference/alternatives.md): + compare FastAPI-CacheX, Cashews, aiocache and Redis SDK by application + fit, not unsupported performance multipliers. **No universal feature + parity goal** for 0.6.0. +- [Public API guide](site_docs/reference/api.md): + distinguish *published 0.5.0* from opt-in capabilities proposed in #54. +- **Feature freeze:** #54 only after clean base, heap fuzz, full-capacity + 10k/100k LRU/expired-reclaim benchmarks and signed exact-head CI; + #50 only if scoped, opt-in, data-minimizing, and reviewed without delaying + release. #53 residual stays a security review gate; #49, tags, + stampede/locks and other expansions remain separate design/research. + ## Version strategy - **0.5.x:** current published line. Keep the published Python diff --git a/changelog.d/86.doc.md b/changelog.d/86.doc.md new file mode 100644 index 00000000..f0c73576 --- /dev/null +++ b/changelog.d/86.doc.md @@ -0,0 +1 @@ +Add an evidence-bound public API reference and comparative alternatives guide, plus an explicit manual GitHub Pages deployment workflow and documented 0.5.0/0.6.0 docs versioning plan; no website is automatically published. diff --git a/docs/DOCS_SITE.md b/docs/DOCS_SITE.md index 34faac00..801037b7 100644 --- a/docs/DOCS_SITE.md +++ b/docs/DOCS_SITE.md @@ -36,4 +36,24 @@ Historical releases already remain navigable at [docs/releases](releases/README. - Mobile navigation, readable color schemes, accessible links/contrast and reduced-motion preferences are design requirements. - Compare release dates/hashes against [RELEASE_STATUS_0.5.0.md](releases/RELEASE_STATUS_0.5.0.md), not source version on stable. -The site uses [Zensical](https://zensical.org/) for search, responsive navigation and a modern theme. \ No newline at end of file +The site uses [Zensical](https://zensical.org/) for search, responsive navigation and a modern theme. + +## Planned public hosting (separate approval) + +A new **manual-only** workflow, `.github/workflows/docs-pages.yml`, uses the +same GitHub Pages deployment pattern as +[fastapi-stream-lease](https://github.com/agustin18/fastapi-stream-lease) +while retaining our Zensical theme. It has **no automatic push trigger**: +merging documentation changes does not activate or publish the website. + +Read the exact setup, live URL checks and immutable-version policy in +[HOSTING_AND_VERSIONING.md](HOSTING_AND_VERSIONING.md). +Compare the installed API, unshipped features and alternatives in +[site_docs/reference/](../site_docs/reference/). Do **not** claim a +publicly accessible URL until the manual deployment and smoke tests pass. + +CacheX publishes a Zensical-built site on Read the Docs. That does not require +us to change generator: GitHub Pages can publish our generated HTML without +a second documentation SaaS. Zensical's versioned `mike` integration +remains transitional; pin and test it independently before offering a +historical version selector. diff --git a/docs/HOSTING_AND_VERSIONING.md b/docs/HOSTING_AND_VERSIONING.md new file mode 100644 index 00000000..ee69f4f5 --- /dev/null +++ b/docs/HOSTING_AND_VERSIONING.md @@ -0,0 +1,42 @@ +# Hosting and versioning the documentation + +The published package remains [fastapi-cache-stable 0.5.0](https://pypi.org/project/fastapi-cache-stable/0.5.0/). **This document describes the proposed deployment**; a PR merge alone does not make a documentation URL public. + +## Why GitHub Pages? + +[fastapi-stream-lease](https://github.com/agustin18/fastapi-stream-lease) already uses [GitHub Pages](https://agustin18.github.io/fastapi-stream-lease/) with an automated documentation build, the same repository-owner account and a familiar Material-style interface. Our existing Zensical site already provides mobile navigation, search, light/dark modes, code-copy controls and checked internal links. **Do not replace Zensical just to change hosting.** + +[FastAPI-CacheX](https://fastapi-cachex.readthedocs.io/en/stable/) serves its Zensical-built documentation through Read the Docs. GitHub Pages can meet our current needs without configuring a third-party service or creating another account. + +**Proposed canonical URL (not confirmed live):** https://agustin18.github.io/fastapi-cache/ + +## Deployment steps (maintainer approval required) + +1. Review [#48](https://github.com/agustin18/fastapi-cache/issues/48) and the docs deployment PR. The workflow `.github/workflows/docs-pages.yml` has **only** a `workflow_dispatch` trigger; it does not deploy on a merge or other repository push. +2. In the GitHub repository settings, enable **Pages → Build and deployment → Source: GitHub Actions**. In **Settings → Environments → github-pages**, restrict deployment branches to **only `stable`** (selected branches), and optionally require reviewer approval. **The environment branch restriction is a security requirement**, not merely an optional approval: a maintainer with write access can dispatch a workflow from another branch, including a workflow that changes its own `if` guard. +3. Trigger the workflow explicitly on the reviewed `stable` branch. Both jobs refuse to run unless `github.ref == 'refs/heads/stable'`. The **read-only** build job installs pinned Zensical, generates static HTML, checks **all local links/anchors**, verifies the install/migration/reference entry points, and uploads the Pages artifact. Only the separate deploy job can request `pages: write` and `id-token: write`; it runs after the build and any required environment approval. +4. Inspect the GitHub Actions published deployment URL and open the actual website. Do **not** assume the expected URL is reachable: Pages' unique-domain setting can affect the final address. +5. Independently check the home page, `getting-started/`, `migration/`, `reference/api/`, `reference/alternatives/`, site search, mobile dark mode, and links to the real 0.5.0 PyPI artifact and GitHub release. Verify navigation from a phone-sized viewport; confirm the information in every page matches the released artifact. +6. **Only after successful publication**, add the verified website URL to the root README, PyPI metadata on a future release (do not republish an immutable old version), social posts, and launch tracker [#88](https://github.com/agustin18/fastapi-cache/issues/88). Keep issue #48 open until verification is recorded. + +## Historical versions + +The current root documentation documents **published 0.5.0 only**. Don't edit it to advertise future APIs before 0.6.0 actually ships. A site update on `stable` is not evidence that a new PyPI version was released. + +At 0.6.0, **do not overwrite the historical 0.5.0 docs silently**. Evaluate a reproducible snapshot built from Git tag `v0.5.0` and hosted at a separate `/v0.5.0/` path, and keep an unambiguous current-version alias. Validate all relative links inside both snapshots and the navigation between versions before adding a selector. + +Zensical currently supports a **transitional fork of `mike`** for versioned MkDocs documentation. This is not yet equivalent to native versioning, and the fork must be evaluated, pinned to a reviewed source revision and tested before adding it to a deployment pipeline. Alternative: explicit, immutable per-version static builds from tags and a small top-level versions page. Decide the final strategy independently under #48. + +## Repository and package boundaries + +- Static docs tooling and GitHub Pages tokens are **not runtime dependencies**. +- Workflow permissions default to none. The build job has `contents: read` only, checkout persists no credentials, and only the deploy job obtains `pages: write` and `id-token: write`. Protect the `github-pages` environment by limiting deployments to branch `stable`; the codebase and PyPI release jobs stay separate. +- Do not automatically deploy from feature PRs or unsafe forks. Existing PR workflows only upload short-lived preview artifacts. +- Documentation must never promise universal tenant isolation, Redis Cluster namespace clearing, automatic private-response migration or Python 3.14 support in 0.5.0. + +## Sources + +- [Zensical publication guide](https://zensical.org/docs/publish-your-site/) +- [Zensical versioning with mike](https://zensical.org/docs/compatibility/mkdocs/mike/) +- [fastapi-stream-lease Pages workflow](https://github.com/agustin18/fastapi-stream-lease/blob/main/.github/workflows/docs.yml) +- [FastAPI-CacheX hosted documentation](https://fastapi-cachex.readthedocs.io/en/stable/) diff --git a/mkdocs.yml b/mkdocs.yml index 8b489ce7..9fc3ffe1 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,5 +1,7 @@ site_name: fastapi-cache-stable site_description: Drop-in FastAPI response caching with safe migration from fastapi-cache2. +# Intended canonical URL after separately approved and verified Pages deployment. +site_url: https://agustin18.github.io/fastapi-cache/ repo_url: https://github.com/agustin18/fastapi-cache repo_name: agustin18/fastapi-cache edit_uri: edit/stable/site_docs/ @@ -20,6 +22,8 @@ nav: - Troubleshooting: guides/troubleshooting.md - Reference: - Capabilities: reference/features.md + - API reference: reference/api.md + - Compare alternatives: reference/alternatives.md - Compatibility: reference/compatibility.md - Version history: reference/releases.md - Roadmap: roadmap.md diff --git a/scripts/check_docs_links.py b/scripts/check_docs_links.py index 87876b26..b977684b 100644 --- a/scripts/check_docs_links.py +++ b/scripts/check_docs_links.py @@ -34,13 +34,22 @@ def _collect(self, attrs) -> None: self.links.append(value) -def _target(source: Path, href: str, site: Path): +def _target(source: Path, href: str, site: Path, base_path: str = ""): parts = urlsplit(href) if parts.scheme or parts.netloc or href.startswith("//"): return None path = unquote(parts.path) rel = source.relative_to(site).as_posix() if path.startswith("/"): + # Project Pages URLs start with //. Remove only the + # explicitly configured deployment prefix, not arbitrary paths. + base = base_path.rstrip("/") + if base and path == base: + path = "/" + elif base and path.startswith(base + "/"): + path = path[len(base):] + elif base: + return ("INVALID", parts.fragment) target_path = path.lstrip("/") elif path: target_path = posixpath.join(posixpath.dirname(rel), path) @@ -57,7 +66,7 @@ def _target(source: Path, href: str, site: Path): return (location, unquote(parts.fragment)) -def check_site(site: Path) -> tuple: +def check_site(site: Path, base_path: str = "") -> tuple: site = site.resolve() pages = sorted(site.rglob("*.html")) if not pages: @@ -74,7 +83,7 @@ def check_site(site: Path) -> tuple: for href in doc.links: if not href.strip(): continue - result = _target(source, href, site) + result = _target(source, href, site, base_path) if result is None: continue checked += 1 @@ -96,8 +105,9 @@ def check_site(site: Path) -> tuple: def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--site-dir", type=Path, default=Path("site")) + parser.add_argument("--base-path", default="", help="Deployment URI prefix, e.g. /fastapi-cache") args = parser.parse_args() - pages, links, errors = check_site(args.site_dir) + pages, links, errors = check_site(args.site_dir, base_path=args.base_path) print(f"Documentation: {pages} pages, {links} local links verified") if errors: for error in errors: diff --git a/site_docs/reference/alternatives.md b/site_docs/reference/alternatives.md new file mode 100644 index 00000000..ae500cd3 --- /dev/null +++ b/site_docs/reference/alternatives.md @@ -0,0 +1,62 @@ +# Compare caching alternatives + +Choosing a library is a question of **migration cost, HTTP semantics, operational needs and maintenance**, not which project has the longest feature list. + +!!! info "Scope and verification" + This snapshot uses upstream project documentation checked on **2026-11-21**. Our capability column refers to the **published 0.5.0** distribution, not draft PRs. Feature support and releases change; always verify a dependency before adopting it. No third-party performance rankings are implied. + +## At a glance + +| Library | Best fit | Meaningful difference | +|---|---|---| +| **fastapi-cache-stable 0.5.0** | Existing `fastapi-cache2==0.2.2` apps prioritizing low-friction migration | Preserves `fastapi_cache` imports and ordinary default-key contract; modern Redis client profiles, opt-in `vary_headers`, conservative privacy safeguards, published migration/rollback evidence | +| [FastAPI-CacheX](https://fastapi-cachex.readthedocs.io/en/stable/) | Teams wanting a broader HTTP caching and app-cache API | Separate `fastapi_cachex` import and API; documented tags, stale serving, event hooks, application caching, local/distributed coalescing and locks | +| [Cashews](https://github.com/Krukov/cashews) | General async function caching strategies | Tags, locking, early/soft expiration, Redis and in-memory strategies; different programming model | +| [aiocache](https://github.com/aio-libs/aiocache) | Async function/value caching with plugins | Custom serializers and instrumentation plugins; not a drop-in FastAPI HTTP response cache | +| [dogpile.cache](https://github.com/sqlalchemy/dogpile.cache) | Regeneration coordination and backend abstraction | Mature locking/invalidation concepts; not primarily a FastAPI decorator | +| [Redis FastAPI SDK](https://github.com/redis/fastapi-redis-sdk) | New Redis-specific FastAPI integrations | Redis-native integration and observability; different API and installation contract | +| [Yolley/fastapi-cache](https://github.com/Yolley/fastapi-cache) | Evaluating another maintained `fastapi_cache` project | **Import name collision** with our fork; review behavior/migration rather than co-installing either distribution | + +## What we prioritize for 0.6.0 + +
+ +- :material-shield-check-outline: **Migration correctness** + + --- + + Retain ordinary key goldens, separate historical private cache entries, preserve verified Redis migration and rollback, and test independent consumers. + +- :material-database-lock-outline: **Bounded in-process caching** + + --- + + [#54](https://github.com/agustin18/fastapi-cache/issues/54) is reviewing an opt-in, entry-count-limited LRU/TTL backend, with actual full-capacity 10k/100k workload benchmarks. **Not shipped in 0.5.0.** + +- :material-chart-timeline-variant: **Optional diagnostics** + + --- + + [#50](https://github.com/agustin18/fastapi-cache/issues/50) proposes typed HIT/MISS/BYPASS/STORE/error signals without exporting keys, credentials or payloads by default. Only include if independently audited. + +- :material-file-document-check-outline: **Documentation people can use** + + --- + + Separate fresh installation from `fastapi-cache2` migration; provide backend, troubleshooting and privacy guidance, a tested example and API reference. + +
+ +## Deliberately not promised + +A library that offers **tags, distributed coalescing, stale-while-revalidate, locks and a general application cache** may be a better choice for a new app than this compatibility-focused fork. We will not add all of those to claim feature parity in 0.6.0. Likewise, `vary_headers` does not automatically isolate hidden tenant/role state. + +Other important limits: Redis Cluster namespace-wide clear is unsupported; DynamoDB/Memcached are experimental; the 0.5.0 InMemory backend is unbounded; Python 3.8–3.10 have functional legacy coverage only. + +## How to decide + +**Already using `fastapi-cache2`?** Start with the [migration guide](../migration.md) and compare the documented behavior changes. **Starting fresh?** Try the [five-minute install](../getting-started.md) and choose a backend. If you need a broader abstraction and are willing to migrate APIs, look at the alternatives above. + +**Sources:** [FastAPI-CacheX feature overview](https://fastapi-cachex.readthedocs.io/en/stable/) · [CacheX technical comparison](https://fastapi-cachex.readthedocs.io/en/stable/COMPARISON/) · [Cashews](https://github.com/Krukov/cashews) · [aiocache](https://github.com/aio-libs/aiocache) · [Redis SDK](https://github.com/redis/fastapi-redis-sdk). + +**Our release evidence:** [0.5.0 provenance](releases.md) · [0.6.0 tracker #86](https://github.com/agustin18/fastapi-cache/issues/86). diff --git a/site_docs/reference/api.md b/site_docs/reference/api.md new file mode 100644 index 00000000..af624fec --- /dev/null +++ b/site_docs/reference/api.md @@ -0,0 +1,75 @@ +# Public API reference · published 0.5.0 + +This is a **curated reference** to stable, user-facing entry points; it does not advertise internal helpers, experimental backends or unreleased features. Consult the [source at tag v0.5.0](https://github.com/agustin18/fastapi-cache/tree/v0.5.0/fastapi_cache) for exact type signatures. + +## `FastAPICache` + +```python +from fastapi_cache import FastAPICache +``` + +| Entry point | Purpose | Notes | +|---|---|---| +| `FastAPICache.init(backend, prefix="", expire=None, coder=JsonCoder, key_builder=default_key_builder, cache_status_header="X-FastAPI-Cache", enable=True, cache_authenticated=False, *, force=False)` | Configure a cache backend once per application process | A second call raises unless deliberate `force=True`. Does not manage or close caller-owned Redis clients | +| `FastAPICache.reset()` | Reset process-global configuration | Does **not** remove stored backend/Redis entries | +| `await FastAPICache.clear(namespace=None, key=None)` | Selectively remove keys or a namespace | Namespace is scoped under the initialized prefix; **not** a global flush | +| `FastAPICache.get_backend()` | Retrieve initialized backend | Raises before initialization | + +## `@cache` decorator + +```python +from fastapi_cache.decorator import cache + +@app.get("/public/items") +@cache(expire=60, namespace="items") +async def items(): + return {"ok": True} +``` + +| Argument | Published 0.5.0 behavior | +|---|---| +| `expire: Optional[int]` | TTL in seconds; `None` uses the configured default, which may be no expiration | +| `namespace: str` | Application-scoped key namespace | +| `coder` | `JsonCoder` by default; `TypedJsonCoder` for opt-in typed Pydantic v2 decoding | +| `key_builder` | Custom function for validated identity and all response-defining dimensions | +| `cache_authenticated: Optional[bool]` | Only opt in with a **complete identity/permission-aware key** | +| `infer_response_model: bool` | Opt into FastAPI return-annotation response-model inference; disabled by default | +| `vary_headers: Optional[Sequence[str]]` | Explicit allowlist of request headers affecting **public** response variants; no automatic tenant/identity detection | +| `injected_dependency_namespace: str` | Names for injected request/response dependencies | + +HTTP `Vary` alone does not partition the library's internal cache. The decorator order is significant: FastAPI route decorators must go **above** `@cache`. + +## Backends + +=== "InMemory (0.5.0)" + + ```python + from fastapi_cache.backends.inmemory import InMemoryBackend + + FastAPICache.init(InMemoryBackend(), prefix="demo") + ``` + + Per-instance, process-local, **unbounded in published 0.5.0**. The proposed `max_entries` argument in [#54](https://github.com/agustin18/fastapi-cache/issues/54) is **not released**. + +=== "Redis standalone" + + ```python + from redis import asyncio as redis + from fastapi_cache.backends.redis import RedisBackend + + client = redis.from_url("redis://localhost:6379/0", decode_responses=False) + FastAPICache.init(RedisBackend(client), prefix="demo") + ``` + + Close your client in lifespan teardown. Redis Cluster namespace-wide `clear()` is unsupported. + +## Coders + +- `JsonCoder` is the default and decodes cached JSON into ordinary Python values. +- `TypedJsonCoder` is opt-in for Pydantic v2 and has its own validation contract. +- `PickleCoder` should **never** deserialize untrusted or attacker-modifiable bytes; avoid it in shared stores without integrity guarantees. + +**Related:** [Compatibility](compatibility.md) · [Security](../guides/privacy.md) · [Migration](../migration.md) · [Full source](https://github.com/agustin18/fastapi-cache/tree/v0.5.0/fastapi_cache). + +!!! note "Automatic reference generation" + We can evaluate Zensical's `mkdocstrings` integration against tagged source later. Do not generate or publish an API reference from unreleased `stable` changes while labeling it 0.5.0. diff --git a/tests/test_docs_link_checker.py b/tests/test_docs_link_checker.py index 0c0146b3..c3e9a440 100644 --- a/tests/test_docs_link_checker.py +++ b/tests/test_docs_link_checker.py @@ -56,3 +56,26 @@ def test_missing_site_fails(tmp_path: Path) -> None: pages, _, errors = check_site(tmp_path) assert pages == 0 assert "No HTML pages" in errors[0] + + +def test_links_under_github_pages_project_prefix(tmp_path: Path) -> None: + _page( + tmp_path, + "index.html", + 'Guide' + 'Styles', + ) + _page(tmp_path, "guide/index.html", '

Ready

') + (tmp_path / "assets").mkdir() + (tmp_path / "assets/site.css").write_text("body {}") + pages, links, errors = check_site(tmp_path, base_path="/fastapi-cache") + assert pages == 2 + assert links == 2 + assert errors == [] + + +def test_links_deny_absolute_path_outside_pages_base(tmp_path: Path) -> None: + _page(tmp_path, "index.html", 'Wrong') + _, _, errors = check_site(tmp_path, base_path="/fastapi-cache") + assert len(errors) == 1 + assert "escapes site" in errors[0] diff --git a/tests/test_docs_pages_permissions.py b/tests/test_docs_pages_permissions.py new file mode 100644 index 00000000..6b094e38 --- /dev/null +++ b/tests/test_docs_pages_permissions.py @@ -0,0 +1,37 @@ +"""Regression gates for the optional manual GitHub Pages deployment (#48).""" + +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +WORKFLOW = ROOT / ".github" / "workflows" / "docs-pages.yml" +HOSTING = ROOT / "docs" / "HOSTING_AND_VERSIONING.md" + + +def test_manual_pages_build_cannot_request_deploy_tokens() -> None: + data = WORKFLOW.read_text(encoding="utf-8") + top, jobs = data.split("jobs:\n", 1) + build, deploy = jobs.split("\n deploy:\n", 1) + assert " workflow_dispatch:" in top + assert "\n push:" not in top + assert "\n pull_request:" not in top + assert "permissions: {}" in top + assert "pages: write" not in build + assert "id-token: write" not in build + assert "contents: read" in build + assert "persist-credentials: false" in build + assert "if: github.ref == 'refs/heads/stable'" in build + assert " needs: build" in deploy + assert "if: github.ref == 'refs/heads/stable'" in deploy + assert "pages: write" in deploy + assert "id-token: write" in deploy + assert "github-pages" in deploy + assert "actions/configure-pages@" in deploy + assert "actions/deploy-pages@" in deploy + + +def test_environment_branch_protection_is_required_in_manual_runbook() -> None: + text = HOSTING.read_text(encoding="utf-8") + assert "Settings → Environments → github-pages" in text + assert "only `stable`" in text + assert "environment branch restriction is a security requirement" in text + assert "workflow that changes its own `if` guard" in text