Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Pin the last 53 mutable action tags, and give the cache lint the direction it lacked (#11518)
Daniel Han008496354721
diff --git a/.github/workflows/docker-credential-probe.yml b/.github/workflows/docker-credential-probe.ymlindex 69536ed17b2..486e74caaf7 100644--- a/.github/workflows/docker-credential-probe.yml+++ b/.github/workflows/docker-credential-probe.yml@@ -50,7 +50,7 @@ jobs:# Step 1: does the token authenticate at all?- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:registry: ${{ env.REGISTRY }}username: ${{ env.REGISTRY_USERNAME }}diff --git a/.github/workflows/docker-publish-rocm.yml b/.github/workflows/docker-publish-rocm.ymlindex 1c5caa375e6..d4c7e6bea75 100644--- a/.github/workflows/docker-publish-rocm.yml+++ b/.github/workflows/docker-publish-rocm.yml@@ -247,7 +247,7 @@ jobs:outputs:digest: ${{ steps.build.outputs.digest }}steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1# The ROCm base image plus the wheel cache do not fit the default runner disk.- name: Reclaim disk@@ -256,17 +256,17 @@ jobs:/opt/hostedtoolcache/CodeQL "$AGENT_TOOLSDIRECTORY" || truedf -h /- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve labelsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# The action copies the repo's Apache-2.0; the image ships AGPL-3.0 files too@@ -276,7 +276,7 @@ jobs:- name: Build and push (by digest)id: build- uses: docker/build-push-action@v6+ uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2with:context: ./dockerfile: ./docker/Dockerfile.rocm@@ -310,17 +310,17 @@ jobs:outputs:tags: ${{ steps.meta.outputs.tags }}steps:- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve tagsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# latest: a default-input build of the default branch (schedule or dispatch).@@ -361,7 +361,7 @@ jobs:outputs:digest: ${{ steps.build.outputs.digest }}steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1# The 21GB base is pulled onto the runner and Studio adds a second torch on# top, so this clears more than the base build does.@@ -376,17 +376,17 @@ jobs:sudo docker image prune -af >/dev/null 2>&1 || truedf -h /- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve labelsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# This one ships Studio itself, which is AGPL-3.0.@@ -395,7 +395,7 @@ jobs:- name: Build and push (by digest)id: build- uses: docker/build-push-action@v6+ uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2with:context: ./dockerfile: ./docker/Dockerfile.studio-rocm@@ -430,17 +430,17 @@ jobs:needs: [prepare, build-studio, tag]timeout-minutes: 15steps:- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve tagsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# format(), not a bare ${{ }}-studio: the raw gfx line is matched by name@@ -488,7 +488,7 @@ jobs:permissions:contents: readsteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Sync docker/DOCKERHUB-ROCM.md to the Docker Hub pageenv:diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.ymlindex 3845d748534..a2350cb9a4c 100644--- a/.github/workflows/docker-publish.yml+++ b/.github/workflows/docker-publish.yml@@ -226,7 +226,7 @@ jobs:packages: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Reclaim diskrun: |@@ -240,17 +240,17 @@ jobs:sudo docker image prune -af >/dev/null 2>&1 || truedf -h /- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve labelsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# The action copies the repo's Apache-2.0, but both images ship Studio (AGPL-3.0) too.@@ -259,7 +259,7 @@ jobs:- name: Build and push (per-arch by digest)id: build- uses: docker/build-push-action@v6+ uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2with:context: ./dockerfile: ./docker/Dockerfile@@ -290,7 +290,7 @@ jobs:touch "/tmp/digests/${digest#sha256:}"- name: Upload digest- uses: actions/upload-artifact@v7+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: digests-core-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}path: /tmp/digests/*@@ -307,23 +307,23 @@ jobs:outputs:digest: ${{ steps.manifest_digest.outputs.digest }}steps:- - uses: actions/download-artifact@v8+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:path: /tmp/digestspattern: digests-core-*merge-multiple: true- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve tagsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# latest=auto would tag :latest on a v* push, colliding with the Studio image@@ -418,7 +418,7 @@ jobs:contents: readpackages: writesteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Reclaim diskrun: |@@ -432,17 +432,17 @@ jobs:sudo docker image prune -af >/dev/null 2>&1 || truedf -h /- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve labelsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# The action copies the repo's Apache-2.0, but both images ship Studio (AGPL-3.0) too.@@ -451,7 +451,7 @@ jobs:- name: Build and push (per-arch by digest)id: build- uses: docker/build-push-action@v6+ uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2with:context: ./dockerfile: ./docker/Dockerfile.studio@@ -492,7 +492,7 @@ jobs:touch "/tmp/digests/${digest#sha256:}"- name: Upload digest- uses: actions/upload-artifact@v7+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: digests-studio-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}path: /tmp/digests/*@@ -509,23 +509,23 @@ jobs:outputs:digest: ${{ steps.studio_manifest_digest.outputs.digest }}steps:- - uses: actions/download-artifact@v8+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:path: /tmp/digestspattern: digests-studio-*merge-multiple: true- - uses: docker/setup-buildx-action@v3+ - uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0- name: Log in to Docker Hub- uses: docker/login-action@v4+ uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0with:username: ${{ env.REGISTRY_USERNAME }}password: ${{ secrets.DOCKER_API_KEY }}- name: Resolve tagsid: meta- uses: docker/metadata-action@v6+ uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0with:images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}# latest=false disables the implicit latest=auto, which would emit :latest on@@ -617,7 +617,7 @@ jobs:permissions:contents: readsteps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- name: Sync docker/DOCKERHUB.md to the Docker Hub page# Key by env, not interpolated into the script: an expanded ${{ secrets.* }}@@ -666,7 +666,7 @@ jobs:runs-on: [self-hosted, gpu]timeout-minutes: 30steps:- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1# Both images are pulled by the digest their merge job resolved and verified, so# there is no tag to re-derive here and no `enable=` expression to keep in stepdiff --git a/.github/workflows/woa-wheelhouse.yml b/.github/workflows/woa-wheelhouse.ymlindex 3477d63d7db..a3bdd4e000e 100644--- a/.github/workflows/woa-wheelhouse.yml+++ b/.github/workflows/woa-wheelhouse.yml@@ -71,13 +71,13 @@ jobs:with:egress-policy: audit- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:repository: apache/arrowref: ${{ inputs.arrow_tag }}path: arrow- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:repository: ${{ env.ARROW_WOA_REPO }}ref: ${{ env.ARROW_WOA_REF }}@@ -129,7 +129,7 @@ jobs:Set-Content $bat -Value $b -Encoding asciiif (-not (Test-Path "$vs\VC\Auxiliary\Build\vcvarsarm64.bat")) { throw "no vcvarsarm64.bat under $vs" }- - uses: actions/setup-python@v7+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0with:python-version: ${{ matrix.python }}architecture: arm64@@ -170,7 +170,7 @@ jobs:Select-String -Path $bat -Pattern '^set ARROW_' | ForEach-Object { $_.Line }- name: Cache vcpkg packages- uses: actions/cache@v6+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:path: C:\vcpkg\installedkey: vcpkg-arm64-static-md-trimmed-${{ inputs.arrow_tag }}-${{ hashFiles('arrow/ci/vcpkg/vcpkg.json') }}@@ -260,7 +260,7 @@ jobs:"@if ($LASTEXITCODE -ne 0) { exit 1 }- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: unsigned-pyarrow-cp${{ matrix.python }}path: arrow/python/repaired_wheels/*.whl@@ -276,21 +276,21 @@ jobs:with:egress-policy: audit- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:repository: asg017/sqlite-vecref: ${{ inputs.sqlite_vec_tag }}path: svfetch-depth: 0- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1with:path: toolssparse-checkout: |.github/scriptssparse-checkout-cone-mode: false- - uses: actions/setup-python@v7+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0with:python-version: '3.13'architecture: arm64@@ -386,7 +386,7 @@ jobs:"@if ($LASTEXITCODE -ne 0) { exit 1 }- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: unsigned-sqlite-vecpath: wheel/*.whl@@ -411,9 +411,9 @@ jobs:with:egress-policy: audit- - uses: actions/checkout@v7+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- - uses: actions/download-artifact@v8+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:pattern: unsigned-*merge-multiple: true@@ -564,7 +564,7 @@ jobs:Get-Content signed/index.txtGet-Content signed/SHA256SUMS- - uses: actions/upload-artifact@v7+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:name: woa-wheelhouse-signedpath: |@@ -587,7 +587,7 @@ jobs:with:egress-policy: audit- - uses: actions/download-artifact@v8+ - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1with:name: woa-wheelhouse-signedpath: wheelhousediff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.ymlindex cc31bdf5f23..05b5f8f6211 100644--- a/.github/workflows/workflow-trigger-lint.yml+++ b/.github/workflows/workflow-trigger-lint.yml@@ -135,6 +135,7 @@ jobs:tests/studio/test_backend_ci_parallel_isolation.py \tests/studio/test_cache_budget_discipline.py \tests/studio/test_cached_paths_hold_no_credentials.py \+ tests/studio/test_actions_are_pinned_to_commits.py \tests/studio/test_local_actions_are_in_path_filters.py \tests/studio/test_chat_ui_shards_cover_everything.py \tests/studio/test_ui_shard_engines.py \diff --git a/scripts/lint_workflow_triggers.py b/scripts/lint_workflow_triggers.pyindex 2b55099acb1..d8199e890b2 100644--- a/scripts/lint_workflow_triggers.py+++ b/scripts/lint_workflow_triggers.py@@ -34,6 +34,9 @@ except ImportError:sys.exit(2)REPO_ROOT = Path(__file__).resolve().parents[1]+# Kept in one place because every reader below opens files the same way.+ENC = "utf-8"+DEFAULT_WORKFLOWS_DIR = REPO_ROOT / ".github" / "workflows"BANNED_TRIGGERS: tuple[str, ...] = ("pull_request_target",)@@ -62,14 +65,962 @@ def _load_workflow(path: Path):sys.exit(2)+def _mappings(node):+ """Every mapping anywhere in a parsed document, at any depth."""+ if isinstance(node, dict):+ yield node+ for value in node.values():+ yield from _mappings(value)+ elif isinstance(node, list):+ for item in node:+ yield from _mappings(item)+++def _parse(path: Path):+ try:+ return yaml.safe_load(path.read_text(ENC))+ except Exception:+ return None++def _extract_cache_keys(path: Path) -> list[str]:- text = path.read_text(encoding = "utf-8")+ """Every `key:` declared anywhere in the document.++ Read from the parsed structure rather than by scanning text for `key:`. The lexical+ version had to be taught one spelling at a time and never finished: `"restore-keys":`+ is valid YAML, so is `uses :`, so is flow style `- {uses: ...}`, and each spelling it+ did not know was a declaration the lint could not see at all. On a security check that+ is a bypass, not a rough edge.+ """+ doc = _parse(path)keys: list[str] = []- for m in re.finditer(r"(?:^|\n)\s*key:\s*([^\n]+)", text):- keys.append(m.group(1).strip())+ for mapping in _mappings(doc):+ value = mapping.get("key")+ if isinstance(value, (str, int, float)):+ text = str(value).strip()+ if text:+ keys.append(text)return keys+def _extract_restore_key_prefixes(path: Path) -> list[str]:+ """Every prefix a `restore-keys:` field offers as a fallback.++ The exact-key comparison is blind to these: `restore-keys` restores the newest entry+ whose key merely STARTS WITH the prefix, so a publish workflow can adopt an entry a+ pull request wrote without the two keys ever being equal.++ Taken from the parsed value, which is the string `actions/cache` itself receives, so+ the YAML details that decide the answer are decided by the parser and not+ re-implemented here. Both of them used to be wrong. A blank line inside a literal+ block does not end it, and breaking there dropped every prefix after it. A FOLDED+ block (`>`) is a single space-joined scalar, so `safe-only-` then `shared-` arrives+ as `safe-only- shared-` and offers no `shared-` fallback at all, while reading each+ physical line invented one -- a false rejection of a correct configuration. PyYAML+ gets both right by construction, and the sequence form (`restore-keys: [a-, b-]`),+ which the line reader never handled, comes free.+ """+ doc = _parse(path)+ prefixes: list[str] = []+ for mapping in _mappings(doc):+ value = mapping.get("restore-keys")+ if isinstance(value, str):+ prefixes.extend(line.strip() for line in value.splitlines())+ elif isinstance(value, list):+ prefixes.extend(str(item).strip() for item in value)+ return [p for p in prefixes if p]+++def _local_uses(path: Path) -> list[str]:+ """Every `uses:` value in the document that points inside this repository."""+ doc = _parse(path)+ out: list[str] = []+ for mapping in _mappings(doc):+ value = mapping.get("uses")+ if isinstance(value, str) and value.strip().startswith("./"):+ out.append(value.strip())+ return out+++def _call_sites(path: Path, target: str) -> list[dict]:+ """The `with:` mappings of every call to a local action or workflow named `target`.++ `target` is the last path component of the `uses: ./...` reference, which is the+ action's directory or the reusable workflow's filename.+ """+ doc = _parse(path)+ sites: list = []+ jobs = doc.get("jobs") if isinstance(doc, dict) else None+ scoped = (+ [(str(jid), job) for jid, job in jobs.items()] if isinstance(jobs, dict) else [("", doc)]+ )+ for job_id, container in scoped:+ for mapping in _mappings(container):+ value = mapping.get("uses")+ if not isinstance(value, str):+ continue+ ref = value.strip()+ if not ref.startswith("./"):+ continue+ # Compared as the FULL local reference when one is given, because two actions+ # may share a directory name: `./.github/actions/a/cache` and+ # `./.github/actions/b/cache` both end in `cache`, so matching on the last+ # component pooled their call sites and invented one action's value for the+ # other. A bare name is still accepted, which is what the predicate self-tests+ # and the shell-head narrowing pass.+ full = ref[2:].rstrip("/") if ref.startswith("./") else ref.rstrip("/")+ # `./repo/.github/actions/cache` names the same action as+ # `./.github/actions/cache`; reachability already strips that runtime prefix and+ # this comparison did not, so literal inputs passed through the prefixed form+ # were never recovered and the key stayed undecidable.+ segments = full.split("/")+ if ".github" in segments[1:]:+ full = "/".join(segments[segments.index(".github") :])+ if "/" in target:+ if full != target and PurePosixPath(full).parent.as_posix() != target:+ continue+ else:+ stem = full.split("/")[-1]+ if stem != target and PurePosixPath(stem).stem != PurePosixPath(target).stem:+ continue+ with_ = mapping.get("with")+ # The CALLER's scope travels with the call site, because a value it delegates+ # names a step of the caller's job, not of the target. Resolving+ # `${{ steps.pip-cache.outputs.key }}` in the target's scope looked for a step+ # the target does not have, so this repository's own pip-cache-save read as+ # unresolvable and failed the live tree.+ sites.append(+ (+ with_ if isinstance(with_, dict) else {},+ (path.as_posix(), job_id),+ )+ )+ return sites+++_STEP_OUTPUT = re.compile(r"\$\{\{\s*steps\.([A-Za-z_][\w-]*)\.outputs\.([A-Za-z_][\w-]*)\s*\}\}")++# Which outputs an `actions/cache` step publishes from the `key:` it was given.+_CACHE_STEP_OUTPUTS = frozenset({"cache-primary-key", "cache-matched-key", "key"})+++def _recovered_outputs(text: str) -> set:+ """The output NAMES a shell body writes with a value this check can recover.++ Per output, not per step. A step may write several, and recording one boolean for+ the whole step let a recognisable `key=safe-key` certify a `danger=` written by a+ `printf` form that recovers nothing -- the cache consumed `outputs.danger`, the+ delegated key was dismissed, and a publish fallback passed.++ A value counts as recovered when it is literal, or when it begins with a literal+ head before its first expansion. `printf 'key=%s\n' "$X"` gives the value `%s`,+ which is neither, so that output stays unrecovered and the key that uses it stays+ undecided.+ """+ # Shell variables assigned a value with a literal head, so an output built from one+ # is still recoverable. `prefix="pip-v2-${name}-..."` followed by+ # `echo "key=${prefix}${hash}"` is how this repository's own producer works, and+ # reading the output line alone saw only `${prefix}` and recovered nothing.+ assigned: dict = {}+ for line in text.splitlines():+ stripped = line.split("#", 1)[0].strip()+ for name, value in re.findall(r"^([A-Za-z_]\w*)=[\"']?([^\"'\n]*)", stripped):+ head = value.split("$", 1)[0]+ if head and "%" not in head:+ assigned[name] = head++ def _head(value: str) -> str:+ """The literal text this value starts with, after one pass of substitution."""+ expanded = re.sub(+ r"\$\{?([A-Za-z_]\w*)\}?",+ lambda m: assigned.get(m.group(1), "$"),+ value,+ )+ return expanded.split("$", 1)[0]++ found: set = set()+ for line in text.splitlines():+ stripped = line.split("#", 1)[0]+ if "GITHUB_OUTPUT" not in stripped:+ continue+ for name, value in re.findall(r"\b([A-Za-z_][\w-]*)=([^\s'\"]*)", stripped):+ if not value or "%" in value:+ continue+ # Literal, or beginning with a literal head once known shell variables are+ # substituted. `printf 'key=%s\n'` gives the value `%s`, which is neither.+ if _head(value):+ found.add(name)+ return found+++_CACHE_KEY_OUTPUTS = ("cache-primary-key", "cache-matched-key", "key")+++def _cache_withs(node):+ """The `with:` mappings of steps that actually cache, or call a local action.++ Every mapping field named `key` used to count, so a composite passing+ `with: {key: release-key}` to an unrelated action registered that value as a cache+ namespace a pull request writes -- and a publish workflow genuinely caching+ `release-key` was rejected though the PR path never touches a cache. A local `./`+ call still counts, because the action it names may cache internally and the value+ is being forwarded to it.+ """+ for mapping in _mappings(node):+ uses = str(mapping.get("uses") or "").strip()+ if not uses:+ continue+ with_ = mapping.get("with")+ if not isinstance(with_, dict):+ continue+ action = uses.split("@")[0].casefold()+ if action.startswith("actions/cache") or uses.startswith("./"):+ yield with_+++def _scoped_cache_keys(path: Path) -> list:+ """[(job id, key)] so a key carries the scope its step ids are resolved in.++ Step ids are unique only within a job, so a key referring to+ `${{ steps.probe.outputs.key }}` means THIS job's `probe`. Without the scope the+ only safe reading was "every step of that id, anywhere, must be readable", and this+ repository has three unrelated `id: probe` steps -- two of which emit no cache key+ at all -- so the safe reading failed a correct tree. The scope makes the question+ answerable instead of merely conservative.+ """+ doc = _parse(path)+ out = []+ jobs = doc.get("jobs") if isinstance(doc, dict) else None+ if isinstance(jobs, dict):+ for job_id, job in jobs.items():+ for mapping in _cache_withs(job):+ key = mapping.get("key")+ if key is not None and not isinstance(key, (dict, list)):+ # Stringified, as `_extract_cache_keys` already does. Accepting only+ # `str` dropped an unquoted scalar such as `key: 123`, which YAML+ # parses as an int, so two workflows sharing that key were reported+ # as collision-free.+ out.append((str(job_id), str(key)))+ return out+ for mapping in _cache_withs(doc):+ key = mapping.get("key")+ if key is not None and not isinstance(key, (dict, list)):+ out.append(("", str(key)))+ return out+++def _producer_steps(path: Path) -> dict:+ """{(document, job, step id): was its key output actually recovered}.++ Keyed by the whole scope, because a step id is unique only within its job. Merging+ bare ids let a readable `id: probe` in one job -- or in a later-sorted file -- stand+ in for an unreadable `id: probe` in another, and the unread key was then dismissed+ on the strength of a step that has nothing to do with it. The dictionary is built+ globally, so a bare id was exactly the wrong identity.++ Per producer, because "some producer somewhere was readable" is not evidence about+ THIS one. A side-wide flag let a workflow with one ordinary+ `echo 'key=safe-key' >> "$GITHUB_OUTPUT"` vouch for a second step emitting+ `printf 'key=%s\n' "shared-$GITHUB_SHA"`, whose namespace was never recovered: the+ flag was true, the delegated key was dismissed, and a publish `restore-keys:+ shared-` passed. One readable step is not a warrant for an unreadable one.+ """+ out: dict = {}+ doc = _parse(path)+ jobs = doc.get("jobs") if isinstance(doc, dict) else None+ scopes = []+ if isinstance(jobs, dict):+ scopes = [(str(jid), job) for jid, job in jobs.items()]+ else:+ # An action definition has no jobs; its steps share one scope.+ scopes = [("", doc)]+ for job_id, scope in scopes:+ for mapping in _mappings(scope):+ step_id = mapping.get("id")+ if not isinstance(step_id, str):+ continue+ ident = (path.as_posix(), job_id, step_id)+ # A step that declares its own `key:` publishes it as an output+ # (`cache-primary-key`), so the namespace is right there in the YAML. This is+ # how `actions/cache/restore` steps hand a key onward, and reading only `run:`+ # bodies and local composites declared them unreadable.+ with_ = mapping.get("with")+ uses_value = str(mapping.get("uses") or "")+ if (+ isinstance(with_, dict)+ and with_.get("key") is not None+ and uses_value.strip().split("@")[0].casefold().startswith("actions/cache")+ ):+ # Only for an action whose published key output IS this input. Marking every+ # id-bearing step with a `with.key` readable was too generous: a local action+ # may take an unrelated `key` input while emitting its own `outputs.key` from+ # a command this check cannot read, and the delegated key was then dismissed+ # with nothing recovered.+ out[ident] = set(_CACHE_STEP_OUTPUTS)+ continue+ body = mapping.get("run")+ if isinstance(body, str):+ out[ident] = _recovered_outputs(body)+ continue+ # A step may produce its output by CALLING a local action rather than by running+ # a shell body -- which is how this repository's own pip-cache-restore works, and+ # reading `run:` steps alone declared that producer unreadable and failed the+ # live tree. The action's own shell is what has to be readable.+ uses = mapping.get("uses")+ if not isinstance(uses, str) or not uses.strip().startswith("./"):+ continue+ # The repository root, found by walking up to `.github` rather than counting+ # levels. A workflow sits at `.github/workflows/x.yml` and an action at+ # `.github/actions/<name>/action.yml`, one level deeper, so a fixed three-up+ # landed inside `.github` for every action.+ root = path.parent+ for parent in path.parents:+ if parent.name == ".github":+ root = parent.parent+ break+ candidates = []+ for target in _local_ref_candidates(uses, root):+ candidates += [target / "action.yml", target / "action.yaml", target]+ for candidate in candidates:+ if not candidate.is_file():+ continue+ text = candidate.read_text(ENC)+ # YAML-declared keys count as recovered too, and are in fact the usual case:+ # this repository's frontend-dist-restore hands out+ # `steps.restore.outputs.cache-primary-key`, whose value is the `key:` the+ # action declares. Requiring a SHELL-built key declared that producer+ # unreadable and failed the live tree on a correct configuration.+ out[ident] = _local_action_outputs(candidate, text)+ break+ return out+++def _local_action_outputs(action: Path, text: str) -> set:+ """The output names this local action hands out with a value this check can see.++ Its declared `outputs.<name>.value` is what a caller receives. When that value is a+ step output, the step behind it has to have recovered THAT output; when it is not+ delegated, the action's own shell is the evidence. Answering with one boolean for+ the action let a readable output certify an unreadable neighbour.+ """+ doc = _parse(action)+ outputs = doc.get("outputs") if isinstance(doc, dict) else None+ inner = _producer_steps(action)+ inner_by_id: dict = {}+ for ident, names in inner.items():+ inner_by_id.setdefault(ident[2], set()).update(names)+ if isinstance(outputs, dict):+ recovered: set = set()+ for name, spec in outputs.items():+ value = spec.get("value") if isinstance(spec, dict) else None+ match = _STEP_OUTPUT.search(str(value or ""))+ if match is None:+ # Not delegated to a step: the value is literal or an expression this+ # check reads no further into, so the shell is the evidence.+ if _recovered_outputs(text) or _extract_cache_keys(action):+ recovered.add(str(name))+ continue+ if match.group(2) in inner_by_id.get(match.group(1), set()):+ recovered.add(str(name))+ return recovered+ return (+ set(_CACHE_STEP_OUTPUTS)+ if (_extract_cache_keys(action) or _recovered_outputs(text))+ else set()+ )+++def _delegation_is_read(+ expression: str,+ producers: dict,+ scope = None,+) -> bool:+ """Was the step this expression names one whose key output we could read?++ An expression naming no step at all -- `${{ needs.build.outputs.key }}` -- is not+ something this check can follow, so it is not evidence either.+ """+ match = _STEP_OUTPUT.search(expression or "")+ if match is None:+ return False+ step_id, output = match.group(1), match.group(2)+ if scope is not None:+ return output in producers.get((scope[0], scope[1], step_id), set())+ # Without a scope, EVERY step of that id must have recovered that output. A single+ # namesake that did not is enough to make the answer no, which is the conservative+ # reading and the one that stops a readable namesake vouching for it.+ seen = [names for ident, names in producers.items() if ident[2] == step_id]+ return bool(seen) and all(output in names for names in seen)+++def _resolved_inputs(+ caller_paths: list,+ target: str,+ _depth: int = 0,+) -> dict:+ """{input: (literal values, every call site resolved)} over all callers of `target`.++ Callers are read from every PR-reachable document, workflows AND composites, not+ just the top-level workflow files. A cache action reached through a wrapper action+ gets its inputs from that wrapper, and collecting only from workflows meant such a+ call site was invisible: if the workflow ALSO called the action directly with a+ literal, every input looked resolved and the narrowing below dropped the namespace+ the wrapper passes.++ The second element of each pair is what keeps the narrowing honest. A call site+ passing `name: ${{ matrix.cache_name }}`, or omitting the input so the action default+ applies, has no literal value here. Substituting only the literals its siblings pass+ would DISCARD that caller's namespace, turning a fix for a false rejection into a+ false acceptance, which is the worse of the two.++ A value that is itself a `steps.*` or `needs.*` reference counts as neither literal+ nor unresolved: it is genuine delegation. Every live caller of pip-cache-save and+ uv-cache-save passes `key: ${{ steps.pip-cache.outputs.key }}`, whose real namespace+ was already collected from the restoring action's shell, so reporting it as+ undecidable was a false failure on this tree -- and a check that fails on a correct+ configuration is one that gets switched off.+ """+ values: dict = {}+ sites: list = []+ for pth in caller_paths:+ sites.extend(_call_sites(pth, target))+ if not sites:+ return {}+ # Every input named anywhere, collected BEFORE counting omissions. Doing both in one+ # pass made the answer depend on call-site order: a site that omitted an input had no+ # bucket yet, so the omission went unrecorded, and a later site supplying a literal+ # made the input look fully resolved. Verified before fixing -- a composite called+ # first with no `name` and then with `name: safe` reported ({'safe'}, True), so the+ # namespace narrowed to `safe` and the real default namespace was left undefended.+ names = {str(name) for site, _scope in sites for name in site}+ # {input name: {(wrapper's own input, wrapper scope)}} -- values a wrapper forwards+ # from its own inputs, resolvable against that wrapper's call sites.+ forwarded_inputs: dict = {}+ for name in names:+ literals: set = set()+ delegated: set = set()+ omitted = 0+ dynamic = 0+ for site, site_scope in sites:+ if name not in site:+ # Omitted, so the action's default applies. A declared default settles+ # THIS, and only this.+ omitted += 1+ continue+ literal = str(site[name]).strip().strip("'\"")+ if re.fullmatch(r"[A-Za-z0-9][\w.-]*", literal):+ literals.add(literal)+ elif _DELEGATED_KEY.fullmatch(literal):+ # Kept, not discarded. Which producer supplies the value decides+ # whether the delegation settles anything, and that is only knowable+ # from the expression the call site wrote.+ delegated.add((literal, site_scope))+ else:+ forwarded = _INPUT_KEY.fullmatch(literal)+ if forwarded is not None and site_scope is not None:+ # A WRAPPER forwarding its own input: `with: {name: ${{ inputs.name }}}`+ # inside another composite. The value is whatever that wrapper's own+ # callers pass, so it is resolvable one level up rather than unknown,+ # and counting it as dynamic left a nested composite undecidable and+ # rejected an unrelated publish key -- a false failure on a valid+ # arrangement.+ #+ # Recorded for the caller to resolve rather than followed here, which+ # would mean recursing while already inside the resolution it needs.+ forwarded_inputs.setdefault(name, set()).add((forwarded.group(1), site_scope))+ continue+ # An explicit value this check cannot expand, such as+ # `${{ matrix.cache_key }}`. No default can settle it, because the caller+ # overrode the default with something unknown.+ dynamic += 1+ for wrapper_input, wrapper_scope in forwarded_inputs.get(name, ()):+ # Resolved against the WRAPPER'S OWN callers, which is the whole point: the+ # forwarded value is whatever they pass it. Resolving the wrapper file+ # against itself looked for call sites inside the wrapper and found none.+ #+ # One level up, and one level only. A wrapper forwarding a wrapper is rare+ # enough that the extra depth is not worth the recursion, and `_depth` makes+ # the fallback the conservative one -- the value stays unresolved.+ outer = (+ {}+ if _depth+ else _resolved_inputs(+ caller_paths, _target_name(Path(wrapper_scope[0])), _depth + 1+ )+ ).get(wrapper_input)+ if outer and outer[1] and outer[0]:+ literals |= outer[0]+ else:+ dynamic += 1+ values[name] = (+ literals,+ dynamic == 0 and omitted == 0,+ omitted,+ dynamic,+ delegated,+ )+ return values+++def _literal_prefix(key: str) -> str:+ """The fixed-text head of a key: everything before the first expression.++ Keys are mostly `literal-${{ something }}`, so comparing whole strings compares the+ expressions too and almost never matches.+ """+ return re.split(r"\$\{\{", key, maxsplit = 1)[0].strip().strip("'\"")+++# `runner.os` is the only expression that routinely LEADS a cache key, and it takes+# exactly three values, so expanding it turns the common undecidable case into three+# decidable ones. Confirmed against GitHub's docs: the values are Linux, Windows and+# macOS, exact and case-sensitive.+_RUNNER_OS_VALUES = ("Linux", "Windows", "macOS")+_RUNNER_OS_EXPR = re.compile(r"\$\{\{\s*runner\.os\s*\}\}")++# A key that is nothing but one expression referring to a step output or an action input+# delegates its namespace rather than declaring one.+_DELEGATED_KEY = re.compile(r"\$\{\{\s*(steps|needs)\.[^}]*\}\}")++# `inputs.X` is NOT delegation: the value arrives from the caller, so it has to be+# resolved against the call sites rather than dismissed.+_INPUT_KEY = re.compile(r"\$\{\{\s*inputs\.([A-Za-z_][\w-]*)\s*\}\}")+++def _prefix_candidates(key: str) -> list[str]:+ """Every literal head this key could have at runtime.++ A key beginning with an expression has no literal head at all, and dropping it was a+ hole: a PR writing `${{ runner.os }}-shared-abc` and a publish job restoring+ `Linux-shared-` would never be compared, because the PR side reduced to the empty+ string and was filtered out. Expanding `runner.os` first gives `Linux-shared-abc`,+ which is comparable. Anything still expression-led afterwards is genuinely+ undecidable and is reported rather than dropped.+ """+ keys = (+ [_RUNNER_OS_EXPR.sub(v, key) for v in _RUNNER_OS_VALUES]+ if _RUNNER_OS_EXPR.search(key)+ else [key]+ )+ return [h for h in (_literal_prefix(k) for k in keys) if h]+++def _is_truncated(key: str) -> bool:+ """Did this key continue into an expression past its literal head?++ Only then can a publish prefix LONGER than the head still reach the runtime key.+ """+ keys = (+ [_RUNNER_OS_EXPR.sub(v, key) for v in _RUNNER_OS_VALUES]+ if _RUNNER_OS_EXPR.search(key)+ else [key]+ )+ return any("${{" in k for k in keys)+++def _prefix_compatible(+ pr_head: str,+ publish_prefix: str,+ truncated: bool = True,+) -> bool:+ """Can a key with this literal head be restored by this prefix?++ `restore-keys` matching is left-anchored and exact, with no globbing, so a publish+ prefix restores a PR-written entry when the PR's runtime key starts with it.++ A head is TRUNCATED when the key continued into an expression this check cannot+ expand, and that is the only case where the reverse direction holds. A PR key+ `pip-v2-${{ runner.os }}-abc` reduces to the head `pip-v2-`, and the publish prefix+ `pip-v2-Linux-` is longer than that head, yet the runtime key `pip-v2-Linux-abc` does+ start with it, so the pairing has to be treated as compatible.++ For a head that is the WHOLE key, the reverse direction is simply wrong. A PR key+ that is exactly `shared` is saved as `shared`, and `shared`.startswith(`shared-long`)+ is false, so a publish fallback `shared-long` cannot reach it. Allowing the reverse+ unconditionally rejected every longer fallback that merely shared an opening with a+ complete key, which is a false failure on a correct configuration.+ """+ if pr_head.startswith(publish_prefix):+ return True+ return truncated and publish_prefix.startswith(pr_head)+++def _shell_output_keys(text: str) -> list:+ """Fully literal `key=<value>` values written to `$GITHUB_OUTPUT`.++ The companion to `_shell_built_key_prefixes`, which recovers the literal HEAD of a+ key whose tail is assembled at runtime and therefore finds nothing in a key that is+ literal all the way through. Both are evidence that the producer was read; a step+ emitting `key=own-v1-abc` is completely resolved, and treating "no dynamic head" as+ "producer not understood" failed a correct configuration.++ These are exact keys, so they join the comparison rather than only vouching for it.+ """+ out = []+ for line in text.splitlines():+ # A commented-out line executes nothing, and reading one as a recovered output+ # let an otherwise unreadable producer certify itself: a `# echo 'key=safe-key'`+ # above a real `printf 'key=%s\n' "shared-$GITHUB_SHA"` marked the step readable,+ # its delegated key was dismissed, and a publish `restore-keys: shared-` passed.+ stripped = line.split("#", 1)[0]+ if "GITHUB_OUTPUT" not in stripped:+ continue+ for value in re.findall(r"\bkey=([A-Za-z0-9][A-Za-z0-9._-]*)", stripped):+ if "$" not in value and value not in out:+ out.append(value)+ return out+++def _shell_built_key_prefixes(+ text: str,+ inputs: set | None = None,+ all_literal: bool = True,+) -> list[str]:+ """Literal key heads assembled in a composite action's shell, not in its YAML.++ The pip and uv caches build their key in a `run:` step and expose it as an output, so+ the YAML `key:` is only `${{ steps.probe.outputs.key }}` and carries no namespace at+ all. Reading YAML alone therefore learned nothing about the very composites this+ check exists to cover: pip-cache-restore's real namespace is the `pip-v2-` in+ `prefix="pip-v2-${name}-..."`, several lines away from any `key:`.++ `inputs` are the values callers actually pass for the first shell variable in such a+ prefix, which keeps the recorded namespace as narrow as the real one. See+ `_local_action_inputs` for why a broader one is not the safe direction.++ Only `key`-ish and `prefix`-ish variables are read. Taking every shell assignment+ would invent namespaces that no cache uses, and each invented one is a potential+ false rejection of a publish prefix.+ """+ heads: list[str] = []+ # A shell value only becomes a cache key by leaving the step, and `$GITHUB_OUTPUT` is+ # how it leaves. Every assignment named `key` or `prefix` was being treated as a cache+ # namespace regardless, so an unrelated `key="shared-${RANDOM}"` in a workflow that+ # caches nothing made a publish `restore-keys: shared-` fail the hard gate.+ #+ # Requiring the output channel rather than a cache step in the same file is+ # deliberate: the composite that BUILDS the key and the workflow that CACHES with it+ # are routinely different documents, which is the whole arrangement this function+ # exists to read.+ #+ # Residual, stated rather than implied: a document that writes an unrelated `key=`+ # value AND uses $GITHUB_OUTPUT elsewhere still over-collects. That direction is a+ # false rejection rather than a bypass, and narrowing it further would mean tracing+ # shell dataflow, which is past what this check should attempt.+ if "GITHUB_OUTPUT" not in text:+ return []+ pattern = re.compile(+ r"""(?:^|[\s;(])(?:[A-Za-z_]*_)?(?:key|prefix|KEY|PREFIX)\s*=\s*["']?"""+ r"""([A-Za-z0-9][A-Za-z0-9._-]*?-)(?=\$|\{)""",+ re.M,+ )+ for m in pattern.finditer(text):+ heads.append(m.group(1))+ # `echo "key=pip-v2-${hash}" >> "$GITHUB_OUTPUT"` is the same thing written inline.+ for m in re.finditer(+ r"""echo\s+["']?(?:key|prefix)=([A-Za-z0-9][A-Za-z0-9._-]*?-)(?=\$|\{)""", text+ ):+ heads.append(m.group(1))+ # A prefix whose literal head does not come FIRST yields nothing above, because the+ # pattern requires the head to begin with an alphanumeric, and+ # `prefix="${name}-pip-..."` puts its literal part after the variable. Substituting+ # the values callers actually pass makes it readable. Without this the composite+ # contributed no head at all, while the `steps.*` key reading its output was+ # dismissed as delegation, so a publish `restore-keys: shared-pip-` had nothing to be+ # compared against.+ for value in sorted(inputs or ()):+ substituted = re.sub(r"\$\{\s*[\w-]+\s*\}|\$\{\{\s*inputs\.[\w-]+\s*\}\}", value, text)+ for found in pattern.findall(substituted) + re.findall(+ r"""echo\s+["']?(?:key|prefix)=([A-Za-z0-9][A-Za-z0-9._-]*?-)(?=\$|\{)""",+ substituted,+ ):+ if found not in heads:+ heads.append(found)+ if inputs and all_literal:+ # Narrowed heads, plus any head that already CARRIES a caller value because it+ # was recovered by substitution above and needs no further narrowing.+ return [f"{h}{v}-" for h in heads for v in sorted(inputs)] + [+ h for h in heads if any(h.startswith(v) for v in inputs)+ ]+ # An unresolved call site means the broad head still has to be carried, or narrowing+ # would silently drop the namespace that caller writes.+ return heads + [f"{h}{v}-" for h in heads for v in sorted(inputs or ())]+++def _target_name(path: Path) -> str:+ """What a `uses:` line writes to reach this definition.++ An action is named by its DIRECTORY (`./.github/actions/pip-cache`), a reusable+ workflow by its FILE (`./.github/workflows/reuse.yml`). Using the directory for both+ made every reusable workflow look like a target called `workflows`, so no call site+ ever matched and the values its callers pass were never recovered -- and a key built+ from one of those values then had no namespace at all.+ """+ directory = path.parent if path.name.startswith("action.") else path+ for parent in path.parents:+ if parent.name == ".github":+ try:+ return directory.relative_to(parent.parent).as_posix()+ except ValueError:+ break+ return directory.name+++def _namespaces_by_target(callers: list, targets: list) -> dict:+ """{target: {input name: (literal values, every call site resolved)}}.++ Per target, NOT merged across all of them. Two unrelated definitions may each declare+ an input called `cache_key`; pooling them by field name assigned one target's values+ to the other, so a publish key matching a value that only the NON-caching composite+ ever receives was rejected. The input name alone does not identify a namespace, and a+ guard that rejects a correct configuration is one someone eventually deletes.+ """+ out: dict = {}+ for target in targets:+ resolved = _resolved_inputs(callers, _target_name(target))+ # A declared default is a value the target really can be called with, so it+ # belongs in the namespace even when no call site mentions the input, and+ # recording it settles the OMISSION that made the input unresolved. It settles+ # nothing else: a caller that explicitly passes `${{ matrix.cache_key }}` has+ # overridden the default with a value this check cannot expand.+ for field, value in _declared_defaults(target).items():+ entry = resolved.get(field, (set(), True, 0, 0, set()))+ vals, _ok, _omitted, dynamic, delegated = entry+ resolved[field] = (vals | {value}, dynamic == 0, 0, dynamic, delegated)+ out[target] = {f: (p[0], p[1], p[4]) for f, p in resolved.items()}+ return out+++def _expand_key(+ key: str,+ namespaces: dict,+ producers: dict | None = None,+ scope = None,+) -> tuple:+ """(every literal key this can take, whether that list is complete).++ Substitutes each `${{ inputs.X }}` OCCURRENCE, rather than only a key that is+ nothing but one expression. `key: prefix-${{ inputs.name }}` called with+ `name: shared` runs as `prefix-shared`, and matching only whole-key expressions left+ that exact collision uncompared -- the commonest way a composite names a key, missed+ because it had a prefix in front of it.++ `runner.os` is expanded too, so the exact comparison sees the three keys a job really+ writes instead of one expression that equals nothing.+ """+ out = {key.strip()}+ complete = True+ # Inputs whose every call site DELEGATES: the value is assembled elsewhere and its+ # namespace is recorded by `_shell_built_key_prefixes`, so the expression left+ # standing for one of these is not an unanswered question.+ delegated_inputs: set = set()+ for _ in range(6):+ nxt: set = set()+ changed = False+ for k in out:+ match = _INPUT_KEY.search(k)+ if match is None:+ nxt.add(k)+ continue+ entry = namespaces.get(match.group(1), (set(), False, set()))+ values, resolved = entry[0], entry[1]+ delegated = entry[2] if len(entry) > 2 else set()+ if not values:+ nxt.add(k)+ # Resolved with NO literals means every call site delegates. Only+ # resolved-false is genuine doubt. Treating the two alike reported this+ # repository's own pip-cache-save, whose every caller passes+ # `${{ steps.pip-cache.outputs.key }}`, against every publish key in the+ # tree -- a false failure on a correct configuration.+ readable = bool(delegated) and all(+ _delegation_is_read(expr, producers or {}, expr_scope)+ for expr, expr_scope in delegated+ )+ if resolved and readable:+ delegated_inputs.add(match.group(1))+ else:+ # Delegation only settles the key when the producer's namespace was+ # actually recovered. `_shell_built_key_prefixes` reads two narrow+ # spellings; a workflow that emits its key with `printf 'key=%s\n'`+ # matches neither, so nothing was recorded and dismissing the key as+ # "delegated" turned an unread producer into a clean bill of health.+ complete = False+ continue+ changed = True+ if not resolved:+ # An unresolved call site keeps the raw expression alongside the+ # literals, or the caller this check cannot expand is silently dropped.+ complete = False+ nxt.add(k)+ for value in sorted(values):+ nxt.add(k[: match.start()] + value + k[match.end() :])+ out = nxt+ if not changed:+ break+ expanded: set = set()+ for k in out:+ if _RUNNER_OS_EXPR.search(k):+ expanded.update(_RUNNER_OS_EXPR.sub(v, k) for v in _RUNNER_OS_VALUES)+ else:+ expanded.add(k)+ # Residue that a delegated input accounts for does not make the key undecided; any+ # other surviving expression does. Checked after the delegated ones are removed, so a+ # key mixing the two is still reported.+ for k in expanded:+ residue = k+ for name in delegated_inputs:+ residue = re.sub(r"\$\{\{\s*inputs\." + re.escape(name) + r"\s*\}\}", "", residue)+ if "${{" in residue:+ complete = False+ break+ return sorted(expanded), complete+++def _input_namespaces(callers: list, targets: list) -> dict:+ """The merged view of `_namespaces_by_target`, for the shell-head narrowing only.++ Merging is wrong for deciding a key's value, which is what `_namespaces_by_target`+ exists for. It stays here because narrowing a shell-built HEAD only ever adds+ candidate heads, so a value borrowed from a neighbouring target widens the recorded+ namespace rather than moving it, and widening is the safe direction.+ """+ merged: dict = {}+ for target in targets:+ resolved = _resolved_inputs(callers, _target_name(target))+ # A declared default is a value the target really can be called with, so it+ # belongs in the namespace even when no call site mentions the input, and+ # recording it settles the OMISSION that made the input unresolved.+ #+ # It settles nothing else. A caller that explicitly passes+ # `${{ matrix.cache_key }}` has overridden the default with a value this check+ # cannot expand, so the namespace stays undecided however many defaults exist.+ # Treating a default as blanket resolution dropped that caller's namespace+ # entirely, which turned the fix for one false failure into a silent bypass.+ defaults = _declared_defaults(target)+ for field, value in defaults.items():+ entry = resolved.get(field, (set(), True, 0, 0, set()))+ vals, _ok, _omitted, dynamic = entry[0], entry[1], entry[2], entry[3]+ resolved[field] = (vals | {value}, dynamic == 0, 0, dynamic, entry[4])+ for field, pair in resolved.items():+ vals, ok = merged.get(field, (set(), True))+ merged[field] = (vals | pair[0], ok and pair[1])+ return merged+++def _expand_input_key(key: str, namespaces: dict) -> list[str]:+ """The literal keys a `key: ${{ inputs.X }}` can take, given its call sites.++ Needed on BOTH sides of the exact comparison, not just the prefix one. A pull request+ writing `shared-key` directly, against a dispatch workflow that calls a reusable+ workflow whose key is `${{ inputs.cache_key }}` with `cache_key: shared-key`, is an+ exact collision with no `restore-keys` anywhere, and comparing a literal against an+ unexpanded expression never matches. Resolution reached the prefix comparison through+ `pr_heads` and stopped there, so this plainest of all the shapes stayed open.+ """+ match = _INPUT_KEY.fullmatch(key.strip())+ if match is None:+ return [key]+ values, resolved = namespaces.get(match.group(1), (set(), False))+ if not values:+ return [key]+ # An unresolved call site keeps the raw expression alongside the literals. Returning+ # the literals alone dropped that caller: with one site passing `cache_key: safe-key`+ # and another `${{ matrix.cache_key }}`, the matrix value could be anything, and+ # discarding it meant neither comparison saw the namespace it writes.+ return sorted(values) if resolved else sorted(values) + [key]+++def _declared_defaults(path: Path) -> dict:+ """`inputs.<name>.default` from an action or reusable workflow definition.++ Actions applies a declared default when a caller omits the input, so a composite+ declaring `cache_key` with default `shared-key` writes the `shared-key` namespace on+ a bare invocation. Reading only the call sites left that key as an unexpanded+ expression, the exact comparison matched nothing, and with no `restore-keys` in play+ the undecidable-prefix path never reported it either: a silent pass.+ """+ doc = _parse(path)+ out: dict = {}+ if not isinstance(doc, dict):+ return out+ declared = doc.get("inputs")+ if not isinstance(declared, dict):+ on = doc.get(True) if True in doc else doc.get("on")+ call = on.get("workflow_call") if isinstance(on, dict) else None+ declared = call.get("inputs") if isinstance(call, dict) else None+ if isinstance(declared, dict):+ for name, spec in declared.items():+ if isinstance(spec, dict) and spec.get("default") is not None:+ out[str(name)] = str(spec["default"])+ return out+++def _local_ref_candidates(ref: str, root: Path) -> list:+ """Every source-tree path a `./...` reference could name.++ A job that checks this repository out into a subdirectory writes+ `./unsloth/.github/actions/x`, which is the same action reached through a layout+ that exists only at run time. Probing the reference as written found nothing in the+ source tree, so those actions were never added to the reachable set and never+ flattened: the keys they declare stayed outside both comparisons, and a login inside+ one was invisible. `notebooks-ci.yml` and `version-compat-ci.yml` both use this form.++ Tried as written first, then from the embedded `.github` component.+ """+ ref = ref.strip()+ if ref.startswith("./"):+ ref = ref[2:]+ ref = ref.rstrip("/")+ out = [root / ref]+ parts = ref.split("/")+ if ".github" in parts[1:]:+ out.append(root / "/".join(parts[parts.index(".github") :]))+ return out+++def _pr_reachable_action_dirs(workflows_dir: Path, pr_paths: list) -> set:+ """Composite actions a PR-triggered workflow actually uses.++ Scanning every action under .github/actions treated a publish-only composite's keys+ as a namespace pull requests write, so a publish workflow restoring its OWN action's+ prefix was rejected as PR-poisonable. That is a false failure on a safe+ configuration, and a security lint that cries wolf gets switched off.++ Local reusable WORKFLOWS are followed too, not just composite actions. A job-level+ `uses: ./.github/workflows/shared.yml` names the workflow file itself, so probing+ only for an `action.yml` beneath the reference found nothing and the keys that+ workflow declares stayed outside the comparison entirely -- reachable from a pull+ request in fact, invisible to the check.+ """+ root = workflows_dir.parent+ dirs: set = set()+ seen: set = set()+ queue = [pth for pth in pr_paths]+ while queue:+ pth = queue.pop()+ if pth in seen:+ continue+ seen.add(pth)+ for ref in _local_uses(pth):+ for cand in _local_ref_candidates(ref, root.parent):+ # A local reusable workflow reference names the .yml file itself rather+ # than a directory containing an action.yml, so it has to be followed on+ # its own.+ if cand.is_file() and cand.suffix in (".yml", ".yaml"):+ dirs.add(cand)+ queue.append(cand)+ break+ found = False+ for action in (cand / "action.yml", cand / "action.yaml"):+ if action.is_file():+ dirs.add(action)+ queue.append(action)+ found = True+ if found:+ break+ return dirs++def _on_field(yaml_doc):# PyYAML parses a bare `on:` key as True.on = yaml_doc.get(True) if isinstance(yaml_doc, dict) else None@@ -313,6 +1264,7 @@ def main() -> int:workflows = sorted(list(workflows_dir.glob("*.yml")) + list(workflows_dir.glob("*.yaml")))pr_triggered: list[tuple[Path, list[str]]] = []publish_triggered: list[tuple[Path, list[str]]] = []+ publish_restore_prefixes: list[tuple[Path, list[str]]] = []unfiltered_hosts: list[Path] = []for path in workflows:@@ -390,6 +1342,7 @@ def main() -> int:)if path.stem in PUBLISH_WORKFLOW_STEMS or is_dispatch_only:publish_triggered.append((path, _extract_cache_keys(path)))+ publish_restore_prefixes.append((path, _extract_restore_key_prefixes(path)))if require_host and not unfiltered_hosts:findings.append(@@ -398,17 +1351,361 @@ def main() -> int:"Restore the workflow-trigger-lint workflow.")- pr_keys = {key for _, keys in pr_triggered for key in keys}+ # A PR-triggered workflow usually delegates its key to a composite action, so the+ # literal key lives in .github/actions/*/action.yml and the workflow only carries+ # `${{ steps.x.outputs.key }}`. Those count as PR-reachable: the workflow that uses+ # them runs on pull requests. Without this the prefix rule below would compare+ # against opaque expressions and match nothing.+ pr_workflow_paths = [pth for pth, _ in pr_triggered]+ pr_reachable = sorted(_pr_reachable_action_dirs(workflows_dir, pr_workflow_paths))+ # Call sites come from every reachable document, workflows and composites alike, so a+ # cache action reached through a wrapper action is narrowed by what the WRAPPER passes+ # and not only by what a workflow passes directly.+ pr_callers = pr_workflow_paths + pr_reachable+ composite_keys: list[str] = []+ shell_built: set = set()+ # A workflow can build its key in one of its OWN `run:` steps and consume it as+ # `${{ steps.probe.outputs.key }}`, with no composite involved at all. Only actions+ # were read for shell-built heads, so that key hit the delegation branch with nothing+ # recovered and a publish `restore-keys: shared-` had nothing to compare against.+ shell_literals: set = set()+ for pth in pr_workflow_paths:+ text = pth.read_text(ENC)+ built = _shell_built_key_prefixes(text)+ composite_keys.extend(built)+ shell_built.update(built)+ # Literal keys the producer writes outright. Exact keys, so they belong in the+ # comparison, and evidence the step was understood.+ shell_literals.update(_shell_output_keys(text))+ for action_path in pr_reachable:+ composite_keys.extend(_extract_cache_keys(action_path))+ resolved = _resolved_inputs(pr_callers, _target_name(action_path))+ names, all_literal = resolved.get("name", (set(), False))[:2]+ built = _shell_built_key_prefixes(action_path.read_text(ENC), names, all_literal)+ composite_keys.extend(built)+ shell_literals.update(_shell_output_keys(action_path.read_text(ENC)))+ # A shell-built value is the literal HEAD of a key whose remainder is assembled+ # at runtime, so it is truncated by construction even though no `${{` survives+ # in the recorded string. Without this the reverse-direction rule below stopped+ # comparing them, and a publish prefix longer than the head -- which is the usual+ # shape, `pip-v2-shared-` against the head `pip-v2-` -- went unexamined.+ shell_built.update(built)++ # The publish side delegates to local actions exactly as the pull-request side does,+ # and reading only the top-level workflow file left that half unexamined. A publish+ # workflow whose composite holds the `actions/cache/restore` declares its keys and+ # its `restore-keys` in the action, so a PR writing `shared-*` against a publish-only+ # composite restoring `shared-` passed: the prefix was never collected, and a+ # comparison that collects nothing on one side reports success.+ for action_path in sorted(+ _pr_reachable_action_dirs(workflows_dir, [pth for pth, _ in publish_triggered])+ ):+ publish_triggered.append((action_path, _extract_cache_keys(action_path)))+ publish_restore_prefixes.append((action_path, _extract_restore_key_prefixes(action_path)))++ # Composite keys belong in the exact comparison as well, not only the prefix one. A+ # PR-reachable action declaring `key: shared-key`, against a publish workflow using+ # that same key and no restore-keys at all, is the original cache-poisoning shape,+ # and it was invisible while this set held workflow-declared keys only.+ # Inputs each side's targets are called with, so an input-backed key resolves to the+ # namespace its callers actually produce before either comparison runs.+ input_namespaces = _input_namespaces(pr_callers, pr_reachable)+ publish_callers = [pth for pth, _ in publish_triggered]+ publish_reachable = sorted(_pr_reachable_action_dirs(workflows_dir, publish_callers))+ publish_namespaces = _input_namespaces(publish_callers, publish_reachable)+ # The publish side builds keys in shell too, and its heads were never collected:+ # `_shell_built_key_prefixes` ran over PR-reachable documents only. A publish+ # workflow that emits `key=shared-key` and restores `${{ steps.probe.outputs.key }}`+ # therefore had that key dismissed as delegated with nothing recovered to compare,+ # while a pull request writing the literal `shared-key` passed.+ publish_shell: set = set()+ # (path, key) is not unique: two jobs may declare the same raw expression, and+ # `setdefault` kept only the first one's scope for both, so a second job whose+ # producer could not be read was judged against the first job's readable one.+ pub_scope_list: dict = {}+ for pth in publish_callers + publish_reachable:+ for jid, key in _scoped_cache_keys(pth):+ pub_scope_list.setdefault((pth.as_posix(), key), []).append((pth.as_posix(), jid))+ text = pth.read_text(ENC)+ publish_shell.update(_shell_built_key_prefixes(text))+ publish_shell.update(_shell_output_keys(text))+ publish_producers: dict = {}+ for pth in publish_callers + publish_reachable:+ publish_producers.update(_producer_steps(pth))+ # Each definition keeps its OWN inputs. See `_namespaces_by_target`.+ pr_by_target = _namespaces_by_target(pr_callers, pr_reachable)+ publish_by_target = _namespaces_by_target(publish_callers, publish_reachable)++ # (namespace, key) rather than a bare key, so every key is expanded against the+ # inputs of the definition that declares it and no other.+ # (namespace, key, scope) -- the scope is the document and job whose step ids a+ # delegated key refers to.+ pr_sites = [+ ({}, k, (pth.as_posix(), jid))+ for pth, _keys in pr_triggered+ for jid, k in _scoped_cache_keys(pth)+ ]+ # Shell-built heads only. Re-adding every composite's YAML keys here gave each one a+ # SECOND entry carrying an empty namespace: it expanded to nothing, counted as+ # unresolved, and a composite whose callers all pass literals then rejected an+ # unrelated publish key on the strength of its own duplicate. The target loop below+ # is where those keys belong, with the inputs that decide them.+ pr_sites += [({}, k, None) for k in sorted(shell_built | shell_literals)]+ for target, namespace in pr_by_target.items():+ pr_sites += [+ (namespace, k, (target.as_posix(), jid)) for jid, k in _scoped_cache_keys(target)+ ]++ pr_keys: set = set()+ # PR keys whose value this check could not settle, with the literal head they are+ # known to start with. Only these can collide with a publish key unseen.+ pr_undecided: list = []+ # Per producing STEP, not per side. One readable producer is not a warrant for an+ # unreadable one, and a side-wide flag let an ordinary `echo key=...` vouch for a+ # `printf` producer whose namespace was never recovered.+ pr_producers: dict = {}+ for pth in pr_workflow_paths + list(pr_reachable):+ pr_producers.update(_producer_steps(pth))+ for namespace, key, scope in pr_sites:+ literals, complete = _expand_key(key, namespace, pr_producers, scope)+ pr_keys.update(k for k in literals if "${{" not in k)+ # Delegation is not indecision. A key that is nothing but+ # `${{ steps.probe.outputs.key }}` names a value assembled in a shell step, and+ # `_shell_built_key_prefixes` recovers its head and records that namespace+ # separately; counting it here as well reported every publish key in the tree+ # against it, which failed the live tree on a correct configuration.+ if not complete and not (+ _DELEGATED_KEY.fullmatch(key.strip())+ and _delegation_is_read(key.strip(), pr_producers, scope)+ ):+ pr_undecided.append((key, _prefix_candidates(key)))+ pr_raw_unresolved = {raw.strip() for raw, _heads in pr_undecided}+for pub_path, pub_keys in publish_triggered:- for k in pub_keys:- if k in pr_keys:+ # This target's own inputs, not the merged view. Two publish-reachable actions+ # sharing an input name had every key expanded with both their values, so a cache+ # composite given `publish-key` was also expanded to an unrelated action's+ # `safe-key` and reported as colliding with a PR cache of that name.+ # A top-level workflow is not a target, and its `${{ inputs.X }}` is a+ # workflow_dispatch input chosen by whoever dispatches it. Falling back to the+ # merged CHILD namespace expanded that user-controlled value using an unrelated+ # action's literal and then called it settled, so dispatching with+ # `cache_key=shared-key` restored a pull request's cache with the lint green.+ # An empty namespace leaves it undecidable, which is what it is.+ pub_ns = publish_by_target.get(pub_path, {})+ for raw in pub_keys:+ # Every job that declares this key, not just the first. A key is only+ # settled when EVERY scope declaring it could be read; one unreadable+ # producer is enough to leave it undecided.+ scopes = pub_scope_list.get((pub_path.as_posix(), raw)) or [None]+ pub_scope = next(+ (+ sc+ for sc in scopes+ if sc is None+ or not _DELEGATED_KEY.fullmatch(raw.strip())+ or not _delegation_is_read(raw.strip(), publish_producers, sc)+ ),+ scopes[0],+ )+ literals, complete = _expand_key(raw, pub_ns, publish_producers, pub_scope)+ if _DELEGATED_KEY.fullmatch(raw.strip()):+ # Compared as the heads its own shell produced, rather than skipped.+ read = _delegation_is_read(raw.strip(), publish_producers, pub_scope)+ literals = sorted(publish_shell) if read else [raw.strip()]+ complete = read+ # Identical spellings first. Two keys written the same way around an+ # expression this check cannot expand -- `shared-${{ hashFiles('lock') }}`+ # on both sides -- resolve identically at run time, so a PR that leaves the+ # lockfile alone writes the very entry the publish run restores. Both sides+ # were being dropped for still containing `${{`, which made the most direct+ # collision of all invisible.+ if not complete and raw.strip() in pr_raw_unresolved:findings.append(- f"{pub_path.name}: cache key {k!r} is also declared in a "- "PR-triggered workflow. A fork PR could poison this cache "- "and the publish workflow would restore it on next run. "- "Add a unique suffix (e.g. '-publish-only') to partition "- "the namespaces."+ f"{pub_path.name}: cache key {raw.strip()!r} is spelled identically "+ "in a PR-triggered workflow. Neither value can be resolved here, "+ "but two identical keys resolve identically at run time, so a fork "+ "PR could write the entry this workflow restores. Add a unique "+ "suffix (e.g. '-publish-only').")+ continue+ for k in literals:+ if k in pr_keys:+ findings.append(+ f"{pub_path.name}: cache key {k!r} is also declared in a "+ "PR-triggered workflow. A fork PR could poison this cache "+ "and the publish workflow would restore it on next run. "+ "Add a unique suffix (e.g. '-publish-only') to partition "+ "the namespaces."+ )+ continue+ if "${{" in k:+ if _DELEGATED_KEY.fullmatch(k.strip()) and _delegation_is_read(+ k.strip(), publish_producers, pub_scope+ ):+ # Delegated AND read. See the PR side above.+ continue+ # An unresolved PUBLISH key, which needs the same treatment as an+ # unresolved PR key and was simply skipped. A publish composite+ # called with `cache_key: ${{ matrix.cache_key }}` may well produce a+ # literal a pull request also writes, and failing closed only on the+ # PR side left exactly half of this check's own rule unenforced.+ # No literal head at all means the key is expression-led and+ # could be ANY value, so it is not narrowable and every PR key is a+ # candidate. Requiring a head silently exempted exactly the least+ # decidable keys, which is the wrong way round.+ heads = [h for h in _prefix_candidates(k) if h]+ reported = False+ for literal in sorted(pr_keys):+ if not heads or any(literal.startswith(h) for h in heads):+ findings.append(+ f"{pub_path.name}: cache key {k!r} cannot be shown not "+ f"to collide with the PR-written key {literal!r}, "+ "because this check cannot resolve the publish key's "+ "value. Give it a unique suffix (e.g. "+ "'-publish-only'), or make it literal."+ )+ reported = True+ break+ if reported:+ continue+ # BOTH sides unresolved, and spelled differently. The identical-text+ # rule above does not reach `shared-${{ matrix.pr_part }}` against+ # `shared-${{ matrix.pub_part }}`, and comparing an unresolved+ # publish key only against RESOLVED pr keys skipped the pairing+ # entirely -- so two keys that can both become `shared-x` passed.+ # Compatible when either head could lead to the other, which for two+ # truncated keys is the prefix test in both directions.+ for raw_pr, pr_heads in pr_undecided:+ fixed = [h for h in pr_heads if h]+ if (+ not heads+ or not fixed+ or any(h.startswith(f) or f.startswith(h) for h in heads for f in fixed)+ ):+ findings.append(+ f"{pub_path.name}: cache key {k!r} and the PR-reachable "+ f"key {raw_pr!r} can both resolve to the same value, "+ "and neither can be resolved here. Give the publish key "+ "a unique suffix (e.g. '-publish-only'), or make one of "+ "them literal."+ )+ break+ continue+ # Fail closed. An unsettled PR key can equal this publish key at run+ # time, and reporting it only from the restore-prefix pass meant a+ # publish workflow with no `restore-keys` at all -- the plainest shape+ # there is -- never had the question asked. Narrowed to PR keys whose+ # fixed head this publish key actually begins with, because a PR key+ # headed `pip-v2-` cannot become `wheels-x` however its tail resolves.+ for raw_pr, heads in pr_undecided:+ # Same rule in the other direction: a PR key with no literal head is+ # unnarrowable rather than harmless.+ fixed = [h for h in heads if h]+ if not fixed or any(k.startswith(h) for h in fixed):+ findings.append(+ f"{pub_path.name}: cache key {k!r} cannot be shown not to "+ f"collide with the PR-reachable key {raw_pr!r}, whose value "+ "this check cannot resolve. Give the publish key a unique "+ "suffix (e.g. '-publish-only'), or make the PR key literal."+ )+ break++ # Same trust boundary, reached by prefix instead of by an equal key. `restore-keys`+ # restores the newest entry whose key merely STARTS WITH the prefix, so a publish+ # workflow can adopt an entry a pull request wrote without the two keys ever being+ # equal, which is the only thing the check above compares.+ pr_heads: set = set()+ # Heads whose key continued into an unexpandable expression. Only these may be+ # reached by a publish prefix LONGER than the head itself.+ truncated_heads: set = set()+ undecidable_pr_keys: list[str] = []+ for k in list(pr_keys) + composite_keys:+ cands = _prefix_candidates(k)+ if cands:+ pr_heads.update(cands)+ if _is_truncated(k) or k in shell_built:+ truncated_heads.update(cands)+ elif _INPUT_KEY.fullmatch(k.strip()):+ # `key: ${{ inputs.cache_key }}` in a reusable workflow or composite names no+ # namespace here, but unlike a `steps.*` reference it is not delegation+ # either: the value comes from the CALLER, and a pull request caller passing+ # `cache_key: shared-abc` writes the `shared-` namespace. Treating it as+ # delegation dropped it silently and a publish `shared-` fallback passed.+ field = _INPUT_KEY.fullmatch(k.strip()).group(1)+ vals, resolved = input_namespaces.get(field, (set(), False))+ heads = [h for v in sorted(vals) for h in _prefix_candidates(v)]+ pr_heads.update(heads)+ truncated_heads.update(+ h for v in sorted(vals) if _is_truncated(v) for h in _prefix_candidates(v)+ )+ if not resolved:+ # Some call site passes a value this check cannot expand, such as+ # `${{ matrix.cache_name }}`, or omits the input so the action default+ # applies. Say so rather than assuming it is harmless. Resolved with no+ # literals is the DELEGATION case and is fine: every live caller of+ # pip-cache-save passes `key: ${{ steps.pip-cache.outputs.key }}`, whose+ # real namespace was collected from the restoring action's shell.+ undecidable_pr_keys.append(k)+ elif _DELEGATED_KEY.fullmatch(k.strip()):+ # `key: ${{ steps.pip-cache.outputs.key }}` names no namespace of its own; it+ # hands the decision to a composite action, whose real prefix was collected+ # above from that action's own YAML and shell. Reporting it as undecidable+ # would flag every workflow that factors its cache out into an action.+ continue+ else:+ undecidable_pr_keys.append(k)++ for pub_path, prefixes in publish_restore_prefixes:+ for prefix in prefixes:+ # Expanded with the declaring target's own inputs first, exactly as its+ # exact keys are. Reducing `prefix-${{ inputs.name }}-` without them gave+ # the broad head `prefix-`, which collides with everything under it, so a+ # composite called with `name: publish` was reported against unrelated PR+ # keys whose runtime fallback it could never reach.+ prefix_ns = publish_by_target.get(pub_path, {})+ expanded_prefixes, _ok = _expand_key(prefix, prefix_ns)+ pub_heads = [+ head for candidate in expanded_prefixes for head in _prefix_candidates(candidate)+ ]+ if not pub_heads:+ findings.append(+ f"{pub_path.name}: restore-keys entry {prefix!r} begins with an "+ "expression, so what it can restore is not decidable here. Give it a "+ "literal prefix."+ )+ continue+ for pub_head in pub_heads:+ hit = next(+ (+ h+ for h in sorted(pr_heads)+ if _prefix_compatible(h, pub_head, h in truncated_heads)+ ),+ None,+ )+ if hit is not None:+ findings.append(+ f"{pub_path.name}: restore-keys prefix {pub_head!r} matches "+ f"{hit!r}, a cache key namespace a PR-triggered workflow writes. "+ "A prefix restore takes the newest matching entry, so this "+ "publish workflow could adopt a cache a pull request produced "+ "even though no key is equal. Partition the namespaces, or drop "+ "the restore-keys fallback on the publish side."+ )+ break+ else:+ # Only reachable when nothing matched: an undecidable PR key could still+ # expand into this prefix, so say so rather than passing silently.+ for k in undecidable_pr_keys:+ findings.append(+ f"{pub_path.name}: restore-keys prefix {prefix!r} cannot be "+ f"compared against PR cache key {k!r}, which begins with an "+ "expression this check cannot expand, so whether the prefix "+ "reaches that namespace is undecidable. Give the PR key a "+ "literal prefix."+ )+ breakif findings:print("Workflow trigger lint failed with the following issues:", file = sys.stderr)diff --git a/tests/python/test_docker_credential_probe.py b/tests/python/test_docker_credential_probe.pyindex 68d85b324d2..d5379dd3421 100644--- a/tests/python/test_docker_credential_probe.py+++ b/tests/python/test_docker_credential_probe.py@@ -130,3 +130,40 @@ def test_no_token_means_no_delete_and_a_failure(delete_step: dict, tmp_path: Patres, log = _run(delete_step, tmp_path, still_there = True, token = "")assert res.returncode != 0assert "DELETE" not in log+++def test_every_step_that_reads_the_key_is_given_the_key():+ """Moving a secret out of the body means putting it into `env:`. Both halves.++ Taking `${{ secrets.DOCKER_API_KEY }}` out of three `run:` bodies removed the key+ from argv, which was the point, and left two of those steps reading+ `os.environ["DOCKER_API_KEY"]` with nothing supplying it. Neither is exercised by a+ pull request: the Hub README sync and the handle-tag cleanup run after a publish, so+ the first sign would have been a released image whose page never updated and a set of+ per-run tags that never got pruned, both reported as "could not exchange the key for+ a token" -- a message that reads like an expired credential rather than a workflow+ that forgot to pass one.++ Derived by scanning, not listed, so a fourth site added later is covered too.+ """+ offenders = []+ for path in sorted(WORKFLOW.parent.glob("docker-*.yml")):+ doc = yaml.safe_load(path.read_text(encoding = "utf-8"))+ for job_name, job in (doc.get("jobs") or {}).items():+ job_env = set(job.get("env") or {})+ for step in job.get("steps") or []:+ body = step.get("run") or ""+ # A read, not a mention. The verdict step names the key in a sentence it+ # prints for a human, which needs no value.+ reads = (+ 'os.environ["DOCKER_API_KEY"]' in body+ or "$DOCKER_API_KEY" in body+ or "${DOCKER_API_KEY" in body+ )+ if reads and "DOCKER_API_KEY" not in (set(step.get("env") or {}) | job_env):+ offenders.append(f"{path.name}:{job_name}: {step.get('name')!r}")+ assert not offenders, (+ "these steps read DOCKER_API_KEY and no env: at step or job level provides it, "+ "so the token exchange gets an empty secret and the step fails at publish "+ "time:\n " + "\n ".join(offenders)+ )diff --git a/tests/python/test_docker_rocm.py b/tests/python/test_docker_rocm.pyindex a03e2b14ff1..e59959a835e 100644--- a/tests/python/test_docker_rocm.py+++ b/tests/python/test_docker_rocm.py@@ -416,7 +416,16 @@ class TestBuildShRocm:body = open(_WORKFLOW, encoding = "utf-8").read()assert "DEFAULT_ROCM_VERSION: '7.2.4'" in bodyassert "DEFAULT_TORCH_INDEX_URL: 'https://download.pytorch.org/whl/rocm7.2'" in body- assert "6.2" not in body.replace("ubuntu-22.04", "")+ # ROCm 6.2, which is what this file must no longer mention anywhere. The plain+ # substring also matched the version comment on a pinned action+ # (`docker/metadata-action@<sha> # v6.2.0`), which has nothing to do with ROCm+ # and would have forced the next person to either unpin the action or weaken the+ # check. Comments and the `runs-on` image name are dropped first; everything the+ # workflow actually executes still has to be free of it.+ meaningful = "\n".join(line.split("#", 1)[0] for line in body.splitlines()).replace(+ "ubuntu-22.04", ""+ )+ assert "6.2" not in meaningful# per RUN on main: a sha would still pair a scheduled run with a dispatch on# an unchanged main, and the group keeps only one pending runassert "github.ref == 'refs/heads/main' && github.run_id" in bodydiff --git a/tests/security/test_lint_workflow_triggers.py b/tests/security/test_lint_workflow_triggers.pyindex fda9d147e3e..3fd1f110d86 100644--- a/tests/security/test_lint_workflow_triggers.py+++ b/tests/security/test_lint_workflow_triggers.py@@ -942,3 +942,2606 @@ def test_lint_rejects_shared_cache_key_between_pr_and_publish(tmp_path):assert proc.returncode == 1assert "cache-key" in proc.stderr.lower() or "cache key" in proc.stderr.lower()assert "shared-cache-v1" in proc.stderr+++def test_lint_rejects_a_publish_restore_keys_prefix_over_a_pr_namespace(tmp_path):+ """A prefix restore reaches the same cache an equal key would, and was invisible.++ `restore-keys` restores the newest entry whose key merely STARTS WITH the prefix, so+ a publish workflow can adopt an entry a pull request wrote without the two keys ever+ being equal. The exact-key check next to this one compares whole strings, so it never+ saw this route.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: node_modules\n"+ " key: pip-v2-${{ runner.os }}-abc\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: node_modules\n"+ " key: pip-v2-exact-${{ runner.os }}\n"+ " restore-keys: |\n"+ " pip-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, f"prefix restore accepted:\n{proc.stdout}\n{proc.stderr}"+ assert "restore-keys" in proc.stderr+ assert "'pip-'" in proc.stderr+++def test_a_partitioned_publish_prefix_is_accepted(tmp_path):+ """The fix must actually pass, or the rule above is just a ban on restore-keys."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: node_modules\n"+ " key: pip-v2-${{ runner.os }}-abc\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: node_modules\n"+ " key: pip-publish-only-${{ runner.os }}\n"+ " restore-keys: |\n"+ " pip-publish-only-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, f"partitioned prefix rejected:\n{proc.stderr}"+++def test_lint_sees_cache_keys_declared_in_composite_actions(tmp_path):+ """The keys that matter mostly live in .github/actions, which the lint used to skip.++ A PR-triggered workflow here delegates its key to a composite action, so the workflow+ text carries only `${{ steps.x.outputs.key }}`. Before composite actions were read,+ the PR-side namespace was effectively empty and a publish prefix could not be+ compared against anything.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pip-cache-restore"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pip cache restore\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: pip-v2-${{ runner.os }}-abc\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ steps.pip-cache.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: pip-v2-publish-${{ runner.os }}\n"+ " restore-keys: |\n"+ " pip-v2-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the composite action's pip-v2- key was not seen, so the publish prefix matched "+ f"nothing:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "pip-v2-" in proc.stderr+++def test_a_restore_keys_entry_that_opens_with_an_unexpandable_expression_is_refused(tmp_path):+ """A prefix whose leading expression cannot be expanded decides nothing.++ `${{ runner.os }}-` is NOT this case: it takes exactly Linux, Windows and macOS, so it+ expands into three decidable prefixes. `${{ matrix.flavour }}-` is unbounded, so+ whether it reaches a pull-request namespace cannot be answered here.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: k-${{ matrix.flavour }}\n"+ " restore-keys: |\n"+ " ${{ matrix.flavour }}-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1+ assert "not decidable" in proc.stderr+++def _publish_with_restore_keys(key: str, prefixes: str) -> str:+ return (+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ f" key: {key}\n"+ " restore-keys: |\n" + prefixes+ )+++def _pr_workflow(key: str) -> str:+ return (+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ f" key: {key}\n"+ )+++def test_a_publish_prefix_longer_than_the_pr_literal_head_is_caught(tmp_path):+ """One-directional prefix comparison missed this, and it is the common shape.++ A PR key `pip-v2-${{ runner.os }}-abc` has the literal head `pip-v2-`. A publish+ prefix `pip-v2-Linux-` is LONGER than that head, so `head.startswith(prefix)` is+ False and the pairing was accepted, while the runtime key `pip-v2-Linux-abc` does+ start with the prefix and would be restored. restore-keys matching is left-anchored+ and exact, per GitHub's dependency-caching reference, so either string being a prefix+ of the other means they can meet.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("pip-v2-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pip-v2-pub-${{ runner.os }}", " pip-v2-Linux-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, f"longer publish prefix accepted:\n{proc.stdout}\n{proc.stderr}"+ assert "pip-v2-Linux-" in proc.stderr+++def test_an_expression_led_pr_key_is_expanded_not_dropped(tmp_path):+ """Dropping these was a gate bypass, not a gap in coverage.++ `${{ runner.os }}-shared-abc` has no literal head, so it used to be filtered out of+ the comparison entirely and a publish prefix `Linux-shared-` passed. runner.os takes+ exactly Linux, Windows and macOS, so expanding it makes the case decidable.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("${{ runner.os }}-shared-abc"))+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pub-${{ runner.os }}", " Linux-shared-\n")+ )+ proc = _run(wf)+ assert (+ proc.returncode == 1+ ), f"expression-led PR key silently dropped:\n{proc.stdout}\n{proc.stderr}"+ assert "Linux-shared-" in proc.stderr+++def test_a_composite_that_builds_its_key_in_shell_is_read(tmp_path):+ """The real composites name their namespace in shell, not in `key:`.++ pip-cache-restore sets `prefix="pip-v2-${name}-..."` in a run step and exposes it as+ an output, so its YAML `key:` is only `${{ steps.probe.outputs.key }}`. A check that+ read YAML alone learned nothing about the very actions it was added to cover, and the+ earlier regression test hid that by putting a literal key in the workflow instead.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pip-cache-restore"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pip cache restore\n"+ "outputs:\n"+ " key:\n"+ " value: ${{ steps.probe.outputs.key }}\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' prefix="pip-v2-${name}-${{ runner.os }}-py${pyver}-"\n'+ ' echo "key=${prefix}${hash}" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ steps.probe.outputs.key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pip-v2-pub", " pip-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the composite's shell-built pip-v2- namespace was not seen:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+ assert "pip-v2-" in proc.stderr+++def test_a_publish_only_composite_is_not_treated_as_a_pr_namespace(tmp_path):+ """Scanning every action made a publish-only cache reject its own prefix.++ That is a false failure on a safe configuration, and a security lint that fails on+ correct code is one someone eventually switches off. Only actions reachable from a+ pull-request-triggered workflow count.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "release-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: release cache\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: release-only-${{ runner.os }}\n"+ )+ (wf / "pr-build.yml").write_text(_pr_workflow("pip-v2-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/release-cache\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: release-only-pub\n"+ " restore-keys: |\n"+ " release-only-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"a publish-only composite was treated as a PR namespace:\n" f"{proc.stdout}\n{proc.stderr}"+ )+++def test_a_restore_keys_prefix_after_a_blank_line_is_still_read(tmp_path):+ """A blank line inside the block scalar used to truncate the list silently.++ A YAML block scalar runs until the indentation drops, blank lines included, and+ actions/cache reads the value as a newline-delimited list and skips empty entries. So+ `safe-`, a blank line, then `shared-` really does offer `shared-` at runtime, while+ the reader stopped at the blank line and never compared it. That is a bypass anyone+ can reach by formatting a long restore-keys block for readability, and the dropped+ entries are exactly the ones furthest from the eye.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys(+ "release-only-${{ runner.os }}",+ " release-only-\n\n shared-\n",+ )+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a prefix after a blank line in the block was dropped, so the collision was "+ f"never compared:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-" in proc.stderr+++def test_a_cache_key_in_a_local_reusable_workflow_is_seen(tmp_path):+ """`uses: ./.github/workflows/x.yml` names the file, not a directory with action.yml.++ Probing only for `action.yml` beneath the reference found nothing, so a reusable+ workflow called from a pull request declared keys that stayed outside the comparison+ entirely: reachable from a pull request in fact, invisible to the check. The+ composite-action case was already covered, which is what made this one easy to miss.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ wf.mkdir(parents = True)+ (wf / "shared-build.yml").write_text(+ "name: shared-build\n"+ "on:\n"+ " workflow_call:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: reuse-v1-${{ runner.os }}-abc\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " call:\n"+ " uses: ./.github/workflows/shared-build.yml\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("reuse-v1-pub-${{ runner.os }}", " reuse-v1-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the reusable workflow's reuse-v1- key was not seen, so the publish prefix "+ f"matched nothing:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "reuse-v1-" in proc.stderr+++def test_a_composite_key_equal_to_a_publish_key_is_caught(tmp_path):+ """An EQUAL key, not a prefix, and declared in a composite action rather than a workflow.++ Composite keys reached the prefix comparison but not the exact one, so a publish+ workflow sharing a literal key with a PR-reachable action and carrying no+ restore-keys at all passed. That is the original cache-poisoning shape, and it was+ the one route through this check with nothing watching it.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "shared-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: shared cache\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: wheels-shared-key\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/shared-cache\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: wheels-shared-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a composite action's literal key equal to the publish key was accepted:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+ assert "wheels-shared-key" in proc.stderr+++def test_a_shell_built_namespace_is_narrowed_by_the_inputs_callers_pass(tmp_path):+ """Recording a namespace more broadly than the real one is a false rejection.++ The pip cache builds `prefix="pip-${name}-..."`, so reading the shell alone records+ the bare head `pip-`, which then collides with any publish prefix beginning `pip-`+ including a properly partitioned `pip-release-` that no pull request can write.+ Substituting the `name:` values callers actually pass gives `pip-mlx-`, which does+ not.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pip-cache-restore"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pip cache restore\n"+ "inputs:\n"+ " name:\n"+ " required: true\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' name="${{ inputs.name }}"\n'+ ' prefix="pip-${name}-${{ runner.os }}-"\n'+ ' echo "key=${prefix}abc" >> "$GITHUB_OUTPUT"\n'+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " with:\n"+ " name: mlx\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pip-release-pub-${{ runner.os }}", " pip-release-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`pip-release-` cannot be written by a pull request whose only namespace is "+ f"`pip-mlx-`, so this must pass:\n{proc.stdout}\n{proc.stderr}"+ )++ # And the narrowed namespace still has teeth: a publish prefix over `pip-mlx-` fails.+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pip-mlx-pub-${{ runner.os }}", " pip-mlx-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a publish prefix over the PR's real `pip-mlx-` namespace must still be "+ f"rejected:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "pip-mlx-" in proc.stderr+++def test_a_publish_composite_that_restores_a_pr_namespace_is_caught(tmp_path):+ """The publish side delegates to local actions too, and that half went unread.++ Only the top-level publish workflow was parsed for `restore-keys`, so a publish+ workflow whose composite owns the `actions/cache/restore` contributed no prefixes at+ all. A pull request writing `shared-*` against a publish-only composite restoring+ `shared-` therefore passed, and a comparison that collects nothing on one side+ reports success rather than admitting it looked at nothing.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "publish-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: publish cache\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: shared-publish-${{ runner.os }}\n"+ " restore-keys: |\n"+ " shared-\n"+ )+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/publish-cache\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the publish composite's `shared-` fallback was never collected, so the "+ f"collision was not compared:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-" in proc.stderr+++def test_narrowing_keeps_the_broad_head_when_a_caller_is_dynamic(tmp_path):+ """Substituting only the literal call sites discards the dynamic one's namespace.++ With one caller passing `name: mlx` and another `name: ${{ matrix.cache_name }}`, the+ literal set is non-empty, so narrowing replaced the broad `pip-v2-` head with+ `pip-v2-mlx-` alone. The matrix caller can still expand to `shared`, write+ `pip-v2-shared-abc`, and a publish `restore-keys: pip-v2-shared-` would pass. The+ narrowing I added to remove a false REJECTION had therefore opened a false+ ACCEPTANCE, which is the worse of the two.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pip-cache-restore"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pip cache restore\n"+ "inputs:\n"+ " name:\n"+ " required: true\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' name="${{ inputs.name }}"\n'+ ' prefix="pip-v2-${name}-"\n'+ ' echo "key=${prefix}abc" >> "$GITHUB_OUTPUT"\n'+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " literal:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " with:\n"+ " name: mlx\n"+ " dynamic:\n"+ " runs-on: ubuntu-latest\n"+ " strategy:\n"+ " matrix:\n"+ " cache_name: [shared, other]\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " with:\n"+ " name: ${{ matrix.cache_name }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys(+ "pip-v2-shared-pub-${{ runner.os }}", " pip-v2-shared-\n"+ )+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a dynamic call site's namespace was discarded by the narrowing, so a publish "+ f"prefix over it passed:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "pip-v2-" in proc.stderr+++def test_a_folded_restore_keys_block_is_one_prefix_not_several(tmp_path):+ """Folding joins the lines with spaces, so the runtime fallback is a single string.++ `restore-keys: >` over `safe-only-` and `shared-` reaches actions/cache as+ `safe-only- shared-`, which cannot restore a `shared-` key: there is no fallback+ named `shared-` at all. Reading each physical line as its own prefix invented one,+ and rejecting a configuration over an invented fallback is how a security lint earns+ the reputation that gets it switched off.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: safe-only-${{ runner.os }}\n"+ " restore-keys: >\n"+ " safe-only-\n"+ " shared-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"a folded block is one space-joined prefix and cannot reach the `shared-` "+ f"namespace, so this must pass:\n{proc.stdout}\n{proc.stderr}"+ )++ # The literal form of the same block really does offer `shared-`, and must fail.+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys(+ "safe-only-${{ runner.os }}",+ " safe-only-\n shared-\n",+ )+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a literal block DOES offer `shared-` as a separate fallback and must be "+ f"rejected:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-" in proc.stderr+++def test_a_quoted_restore_keys_field_is_read(tmp_path):+ """`"restore-keys": |` is valid YAML and offers the same fallback.++ The lexical reader matched only the bare token, so this spelling produced no+ prefixes at all and the collision was accepted. One of several spellings that had to+ be added one at a time before the reader was replaced with the parser, which resolves+ all of them to the same mapping key.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ ' "key": pub-${{ runner.os }}\n'+ ' "restore-keys": |\n'+ " shared-\n"+ )+ proc = _run(wf)+ assert (+ proc.returncode == 1+ ), f"a quoted restore-keys field was not read:\n{proc.stdout}\n{proc.stderr}"+ assert "shared-" in proc.stderr+++def test_a_restore_keys_sequence_is_read(tmp_path):+ """`restore-keys: [a-, shared-]` is the sequence form, which the line reader never saw."""+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-${{ runner.os }}-abc"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: pub-${{ runner.os }}\n"+ " restore-keys: [safe-, shared-]\n"+ )+ proc = _run(wf)+ assert (+ proc.returncode == 1+ ), f"a sequence-form restore-keys was not read:\n{proc.stdout}\n{proc.stderr}"+ assert "shared-" in proc.stderr+++def test_a_flow_style_local_uses_is_followed(tmp_path):+ """`- {uses: ./.github/actions/x}` is the same step mapping in flow style.++ The traversal matched `uses:` lexically, so a flow-style or quoted-key call was never+ followed and the namespace that action declares stayed outside the comparison.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "shared-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: shared cache\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: flow-v1-${{ runner.os }}-abc\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - {uses: ./.github/actions/shared-cache}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("flow-v1-pub-${{ runner.os }}", " flow-v1-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a flow-style local `uses` was not followed, so the action's namespace was "+ f"invisible:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "flow-v1-" in proc.stderr+++def test_a_caller_supplied_key_is_resolved_not_dismissed(tmp_path):+ """`key: ${{ inputs.cache_key }}` is caller-supplied, which is not delegation.++ `steps.*` genuinely delegates: the real key is built in a composite's shell and is+ collected from there. `inputs.*` is different, because the value comes from the+ CALLER, so a pull request passing `cache_key: shared-abc` writes the `shared-`+ namespace. Treating the two alike dropped this key silently and a publish `shared-`+ fallback passed.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ wf.mkdir(parents = True)+ (wf / "shared-build.yml").write_text(+ "name: shared-build\n"+ "on:\n"+ " workflow_call:\n"+ " inputs:\n"+ " cache_key:\n"+ " required: true\n"+ " type: string\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ inputs.cache_key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " call:\n"+ " uses: ./.github/workflows/shared-build.yml\n"+ " with:\n"+ " cache_key: shared-abc\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub-${{ runner.os }}", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"a caller-supplied cache key was dismissed as delegation:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-" in proc.stderr+++def test_a_key_delegated_to_a_step_output_is_still_accepted(tmp_path):+ """The other half of the rule above, and the reason it is not simply stricter.++ Every live caller of this repository's pip-cache-save passes+ `key: ${{ steps.pip-cache.outputs.key }}`, whose real namespace was already collected+ from the restoring action's shell. Reporting that as undecidable failed the live tree,+ which is the false-failure shape that gets a security check switched off, so+ resolved-with-no-literals has to mean delegation rather than doubt.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "cache-save"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: cache save\n"+ "inputs:\n"+ " key:\n"+ " required: true\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ inputs.key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: probe\n"+ " run: echo 'key=own-v1-abc' >> \"$GITHUB_OUTPUT\"\n"+ " - uses: ./.github/actions/cache-save\n"+ " with:\n"+ " key: ${{ steps.probe.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("unrelated-pub-${{ runner.os }}", " unrelated-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"a key delegated to a step output, against an unrelated publish namespace, "+ f"must pass:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_inputs_are_collected_through_a_wrapper_action(tmp_path):+ """Call sites live in composites too, not only in workflow files.++ A cache action reached through a wrapper gets its inputs from that wrapper. Reading+ only the top-level workflows meant that call site was invisible, so if the workflow+ ALSO called the action directly with a literal, every input looked resolved and the+ narrowing dropped the namespace the wrapper passes.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ inner = root / "actions" / "pip-cache-restore"+ wrapper = root / "actions" / "setup-wrapper"+ wf.mkdir(parents = True)+ inner.mkdir(parents = True)+ wrapper.mkdir(parents = True)+ (inner / "action.yml").write_text(+ "name: pip cache restore\n"+ "inputs:\n"+ " name:\n"+ " required: true\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' name="${{ inputs.name }}"\n'+ ' prefix="pip-v3-${name}-"\n'+ ' echo "key=${prefix}abc" >> "$GITHUB_OUTPUT"\n'+ )+ (wrapper / "action.yml").write_text(+ "name: setup wrapper\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " with:\n"+ " name: wrapped\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " direct:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pip-cache-restore\n"+ " with:\n"+ " name: direct\n"+ " viawrapper:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/setup-wrapper\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys(+ "pip-v3-wrapped-pub-${{ runner.os }}", " pip-v3-wrapped-\n"+ )+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the wrapper's `name: wrapped` call site was not collected, so the narrowing "+ f"dropped that namespace:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "pip-v3-" in proc.stderr+++def test_an_omission_before_the_first_literal_is_counted(tmp_path):+ """Counting omissions in the same pass made the answer depend on call-site order.++ A site that omitted an input had no bucket yet, so the omission went unrecorded, and+ a later site supplying a literal made the input look fully resolved. Verified before+ fixing: a composite called first with no `name` and then with `name: safe` reported+ `({'safe'}, True)`, so the namespace narrowed to `safe` and the action's real default+ namespace was left undefended.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pipc"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pipc\n"+ "inputs:\n"+ " name:\n"+ " default: shared\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' name="${{ inputs.name }}"\n'+ ' prefix="pipx-${name}-"\n'+ ' echo "key=${prefix}abc" >> "$GITHUB_OUTPUT"\n'+ )+ # The omitting call site comes FIRST, which is the ordering that used to be lost.+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " defaulted:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pipc\n"+ " named:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pipc\n"+ " with:\n"+ " name: safe\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("pipx-pub-${{ runner.os }}", " pipx-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the first call site omits `name`, so the namespace is not fully resolved and "+ f"the broad `pipx-` head must still be defended:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "pipx-" in proc.stderr+++def test_a_prefix_that_opens_with_a_variable_is_recovered(tmp_path):+ """`prefix="${name}-pip-..."` put its literal part after the variable.++ The head pattern requires an alphanumeric start, so this composite contributed no+ head at all, while the `steps.*` key reading its output was dismissed as delegation.+ A publish `restore-keys: shared-pip-` then had nothing to be compared against, which+ is the failure mode where a check reports success having looked at nothing.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "varfirst"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: varfirst\n"+ "inputs:\n"+ " name:\n"+ " required: true\n"+ "outputs:\n"+ " key:\n"+ " value: ${{ steps.probe.outputs.key }}\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - id: probe\n"+ " shell: bash\n"+ " run: |\n"+ ' name="${{ inputs.name }}"\n'+ ' prefix="${name}-pip-${{ runner.os }}-"\n'+ ' echo "key=${prefix}abc" >> "$GITHUB_OUTPUT"\n'+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: vf\n"+ " uses: ./.github/actions/varfirst\n"+ " with:\n"+ " name: shared\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ steps.vf.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pip-pub-${{ runner.os }}", " shared-pip-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the namespace is `shared-pip-` once `name` is substituted, so the publish "+ f"fallback over it must be rejected:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-pip-" in proc.stderr+++def test_an_input_backed_key_is_resolved_before_the_exact_comparison(tmp_path):+ """The plainest shape of all: an equal key, with no `restore-keys` anywhere.++ Input resolution reached the prefix comparison through `pr_heads` and stopped there,+ so a pull request writing `shared-key` directly, against a dispatch workflow calling+ a reusable workflow whose key is `${{ inputs.cache_key }}` with+ `cache_key: shared-key`, compared a literal against an unexpanded expression and+ matched nothing.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ wf.mkdir(parents = True)+ (wf / "shared-build.yml").write_text(+ "name: shared-build\n"+ "on:\n"+ " workflow_call:\n"+ " inputs:\n"+ " cache_key:\n"+ " required: true\n"+ " type: string\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ inputs.cache_key }}\n"+ )+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-key"))+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " call:\n"+ " uses: ./.github/workflows/shared-build.yml\n"+ " with:\n"+ " cache_key: shared-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the publish side's key resolves to `shared-key`, which the PR writes directly, "+ f"so this exact collision must be caught:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-key" in proc.stderr+++def test_a_longer_fallback_over_a_complete_pr_key_is_accepted(tmp_path):+ """The reverse-prefix direction only holds for a head cut short by an expression.++ A PR key that is exactly `shared` is saved as `shared`, and+ `shared`.startswith(`shared-long`) is false, so a publish fallback `shared-long`+ cannot restore it. Allowing the reverse unconditionally rejected every longer+ fallback that merely shared an opening with a complete key, which is a false failure+ on a correct configuration.+ """+ wf = tmp_path / "wf"+ wf.mkdir()+ (wf / "pr-build.yml").write_text(_pr_workflow("shared"))+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-long-pub", " shared-long-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`shared-long-` cannot restore a key that is exactly `shared`, so this must "+ f"pass:\n{proc.stdout}\n{proc.stderr}"+ )++ # The truncated case still has teeth: the same fallback over an expression-completed+ # key CAN meet it at runtime.+ (wf / "pr-build.yml").write_text(_pr_workflow("shared-long-${{ runner.os }}-abc"))+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the runtime key here really does start with `shared-long-`:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+++def _lint_module():+ """The lint script loaded as a module, for testing its predicates directly.++ The rest of this file drives the script as a subprocess, which is the right way to+ test the tool but cannot reach a single function.+ """+ import importlib.util++ spec = importlib.util.spec_from_file_location("_lint_under_test", SCRIPT)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_the_truncation_predicate_reads_the_key():+ """The rule above is only as good as this predicate, so it is tested directly."""+ lint = _lint_module()+ _is_truncated = lint._is_truncated+ _prefix_compatible = lint._prefix_compatible+ # `runner.os` is expanded before the head is taken, so a key containing only that+ # expression ends up with a COMPLETE head and is not truncated. It is the expressions+ # this check cannot expand that cut a head short.+ cases = [+ ("shared", False),+ ("shared-long-abc", False),+ ("pip-v2-${{ runner.os }}-abc", False),+ ("${{ runner.os }}-shared-abc", False),+ ("pip-${{ hashFiles('x') }}", True),+ ("pip-${{ matrix.flavour }}-abc", True),+ ]+ for key, expected in cases:+ assert _is_truncated(key) is expected, f"_is_truncated({key!r})"++ # A head cut short by an expression may be reached by a LONGER publish prefix; a+ # complete key may not.+ assert _prefix_compatible("pip-v2-", "pip-v2-Linux-", True) is True+ assert _prefix_compatible("shared", "shared-long", False) is False+ # Either way, a prefix the head already starts with is always compatible.+ assert _prefix_compatible("shared-long-abc", "shared-", False) is True+++def test_a_declared_input_default_is_part_of_the_namespace(tmp_path):+ """Actions applies a declared default when the caller omits the input.++ A composite declaring `cache_key` with default `shared-key` writes that namespace on+ a bare invocation. Reading only the call sites left the key as an unexpanded+ expression, so the exact comparison matched nothing, and with no `restore-keys` in+ play the undecidable-prefix path never reported it either. A silent pass.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "defaulted-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: defaulted cache\n"+ "inputs:\n"+ " cache_key:\n"+ " default: shared-key\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ inputs.cache_key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/defaulted-cache\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: shared-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the bare invocation writes the default namespace `shared-key`, which the "+ f"publish workflow uses exactly:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "shared-key" in proc.stderr+++def test_a_declared_default_does_not_settle_an_explicit_dynamic_value(tmp_path):+ """A default applies to an OMISSION. It says nothing about an explicit override.++ Recording a declared default as blanket resolution -- the first fix for the omission+ case -- meant a second caller passing `key: ${{ matrix.cache_key }}` was marked+ resolved on the strength of a default it had overridden. Its namespace is unknown, so+ the publish prefix `shared-` cannot be shown not to reach it, and dropping it turned+ the fix for one false failure into a silent bypass.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "defaulted-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: defaulted cache\n"+ "inputs:\n"+ " cache_key:\n"+ " default: unrelated-default\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: ${{ inputs.cache_key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " strategy:\n"+ " matrix:\n"+ " cache_key: [a, b]\n"+ " steps:\n"+ " - uses: ./.github/actions/defaulted-cache\n"+ " with:\n"+ " cache_key: ${{ matrix.cache_key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: shared-key\n"+ " restore-keys: |\n"+ " shared-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the matrix caller overrode the default with a value the check cannot expand, "+ f"so the PR namespace is undecided and the publish prefix cannot be "+ f"cleared:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_shell_key_that_never_leaves_the_step_is_not_a_namespace(tmp_path):+ """A shell variable becomes a cache key by being written to `$GITHUB_OUTPUT`.++ Reading every assignment named `key` or `prefix` regardless meant an unrelated+ `key="shared-${RANDOM}"` -- a temp-file name, in a workflow with no cache at all --+ registered `shared-` as a pull-request cache namespace and failed the publish+ workflow's legitimate `restore-keys: shared-`. A false failure on a correct tree is+ how a guard gets exempted, so the recovered value has to be tied to something that+ can actually become a key.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n"+ " pull_request:\n"+ "jobs:\n"+ " build:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - run: |\n"+ ' key="shared-${RANDOM}"\n'+ ' echo hello > "/tmp/$key"\n'+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ "jobs:\n"+ " publish:\n"+ " runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: shared-key-v1\n"+ " restore-keys: |\n"+ " shared-\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"the pull request workflow caches nothing and the assignment never reaches "+ f"$GITHUB_OUTPUT, so `shared-` is not a namespace it can "+ f"write:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_an_input_embedded_in_a_key_is_expanded(tmp_path):+ """`key: prefix-${{ inputs.name }}` with `name: shared` runs as `prefix-shared`.++ Only a key that was NOTHING but one expression got expanded, so the commonest+ spelling -- an input with a literal prefix in front of it -- kept its raw text+ through the exact comparison and matched no publish key. With no `restore-keys` on+ the publish side the prefix pass never looked either, leaving the plainest exact+ collision unguarded.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "embedded"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: embedded\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n"+ " path: wheels\n"+ " key: prefix-${{ inputs.name }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/embedded\n"+ " with:\n name: shared\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-shared\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the composite writes `prefix-shared`, which the publish workflow restores by "+ f"that exact name:\n{proc.stdout}\n{proc.stderr}"+ )+ assert "prefix-shared" in proc.stderr+++def test_runner_os_is_expanded_before_the_exact_comparison(tmp_path):+ """`shared-${{ runner.os }}` and `shared-Linux` are the same key on a Linux runner.++ The exact comparison was a plain string test, so two keys that are equal at run time+ but differ textually never met. `_prefix_candidates` already knew the three values+ `runner.os` takes, but only the fallback-prefix pass used them, so a publish workflow+ with no `restore-keys` never benefited.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: shared-${{ runner.os }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: shared-Linux\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"both jobs write `shared-Linux` on a Linux runner:\n{proc.stdout}\n" f"{proc.stderr}"+ )+++def test_an_unresolvable_pr_key_is_reported_against_an_exact_publish_key(tmp_path):+ """Fail closed when the PR key's value cannot be settled and could equal a publish key.++ Unresolved keys were reported only from inside the restore-prefix pass, so a publish+ workflow that uses an exact key and no `restore-keys` at all had the question never+ asked: a matrix-supplied `shared-${{ matrix.tag }}` may well produce `shared-key`,+ and the lint exited 0.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " strategy:\n matrix:\n tag: [a, b]\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: shared-${{ matrix.tag }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: shared-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the matrix value is unknown and `shared-key` is one of the keys it could "+ f"produce:\n{proc.stdout}\n{proc.stderr}"+ )++ # ... and a publish key the PR key's fixed head cannot lead to stays accepted, or+ # every unresolved key in the tree would reject every publish key in it.+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: wheels-publish-only\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"a key headed `shared-` cannot become `wheels-publish-only` however its tail "+ f"resolves:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_two_targets_sharing_an_input_name_keep_their_own_namespaces(tmp_path):+ """An input name does not identify a namespace; the definition it belongs to does.++ Merging every reachable target's inputs by field name handed one composite's values+ to another, so a publish key equal to a value only the NON-caching composite ever+ receives was rejected. A guard that fails a correct configuration is one that gets+ deleted, so this direction matters as much as the bypasses.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ caching = root / "actions" / "caching"+ unrelated = root / "actions" / "unrelated"+ wf.mkdir(parents = True)+ caching.mkdir(parents = True)+ unrelated.mkdir(parents = True)+ (caching / "action.yml").write_text(+ "name: caching\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: ${{ inputs.cache_key }}\n"+ )+ # Same input NAME, no cache anywhere in it.+ (unrelated / "action.yml").write_text(+ "name: unrelated\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - run: echo ${{ inputs.cache_key }}\n"+ " shell: bash\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/caching\n"+ " with:\n cache_key: safe-key\n"+ " - uses: ./.github/actions/unrelated\n"+ " with:\n cache_key: publish-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: publish-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`publish-key` only ever reaches the composite that caches nothing, so no PR "+ f"cache writes it:\n{proc.stdout}\n{proc.stderr}"+ )++ # The caching composite receiving it IS a collision, so the narrowing kept its teeth.+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/caching\n"+ " with:\n cache_key: publish-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"now the caching composite is the one given `publish-key`:\n{proc.stdout}\n"+ f"{proc.stderr}"+ )+++def test_a_reusable_workflow_is_named_by_its_file_not_its_directory():+ """`uses: ./.github/workflows/reuse.yml` names a FILE. An action names a directory.++ Taking the parent directory for both made every reusable workflow a target called+ `workflows`, which no call site mentions, so the values its callers pass were never+ recovered and a key built from one of them had no namespace at all.+ """+ lint = _lint_module()+ # The FULL local reference, which is what a `uses:` line writes. A basename was+ # enough to tell a workflow from an action, and not enough to tell two actions+ # apart: `.github/actions/a/cache` and `.github/actions/b/cache` both end in+ # `cache`, so their call sites pooled and one action's value was invented for the+ # other.+ assert lint._target_name(Path(".github/workflows/reuse.yml")) == ".github/workflows/reuse.yml"+ assert (+ lint._target_name(Path(".github/actions/pip-cache/action.yml"))+ == ".github/actions/pip-cache"+ )+ assert (+ lint._target_name(Path(".github/actions/pip-cache/action.yaml"))+ == ".github/actions/pip-cache"+ )+ # An action is still named by its directory and a reusable workflow by its file,+ # which is the distinction this started from.+ assert lint._target_name(Path(".github/actions/a/cache/action.yml")) != (+ lint._target_name(Path(".github/actions/b/cache/action.yml"))+ )+++def test_an_unresolvable_publish_key_is_reported_too(tmp_path):+ """Failing closed on one side only leaves half this check's own rule unenforced.++ A publish composite called with `cache_key: ${{ matrix.cache_key }}` may well+ produce a literal a pull request also writes, and the publish branch skipped every+ key that still contained an expression. The PR side had already been made to fail+ closed, which made the asymmetry easy to miss: the rule looked enforced.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pub-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pub cache\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: ${{ inputs.cache_key }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: shared-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " strategy:\n matrix:\n cache_key: [x, y]\n"+ " steps:\n"+ " - uses: ./.github/actions/pub-cache\n"+ " with:\n cache_key: ${{ matrix.cache_key }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the matrix could produce `shared-key`, which the pull request writes:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+++def test_two_identically_spelled_unresolved_keys_collide(tmp_path):+ """`shared-${{ hashFiles('lock') }}` on both sides is one key at run time.++ Both sides were dropped for still containing an expression, so the most direct+ collision there is -- the same key, written the same way, in both workflows -- was+ invisible. A pull request that leaves the lockfile untouched writes exactly the entry+ the publish run restores.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ body = (+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: shared-${{ hashFiles('lock') }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n" + body+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n" + body+ )+ proc = _run(wf)+ assert (+ proc.returncode == 1+ ), f"identical keys resolve identically:\n{proc.stdout}\n{proc.stderr}"+ assert "identically" in proc.stderr+++def test_a_publish_key_is_expanded_with_its_own_targets_inputs(tmp_path):+ """The publish side kept using the merged namespace, so its scoping changed nothing.++ `publish_by_target` was computed and never read. Two publish-reachable actions+ sharing an input name therefore had every key expanded with both their values, and a+ cache composite given `publish-key` was also expanded to an unrelated action's+ `safe-key` and reported as colliding with a pull request cache of that name.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ caching = root / "actions" / "pub-caching"+ unrelated = root / "actions" / "pub-unrelated"+ wf.mkdir(parents = True)+ caching.mkdir(parents = True)+ unrelated.mkdir(parents = True)+ (caching / "action.yml").write_text(+ "name: pub caching\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: ${{ inputs.cache_key }}\n"+ )+ (unrelated / "action.yml").write_text(+ "name: pub unrelated\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - run: echo ${{ inputs.cache_key }}\n shell: bash\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: safe-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pub-caching\n"+ " with:\n cache_key: publish-key\n"+ " - uses: ./.github/actions/pub-unrelated\n"+ " with:\n cache_key: safe-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`safe-key` only ever reaches the action that caches nothing:\n{proc.stdout}\n"+ f"{proc.stderr}"+ )+++def test_a_composite_key_is_not_counted_a_second_time_without_its_inputs(tmp_path):+ """A duplicate entry with an empty namespace made a decided key look undecided.++ Composite YAML keys were added once with their target's inputs and once more with no+ namespace at all. The second copy expanded to nothing, counted as unresolved, and the+ fail-closed rule then rejected an unrelated publish key on the strength of the+ duplicate -- even though every caller passes a literal and the key can only be one+ thing.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "decided"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: decided\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: prefix-${{ inputs.name }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/decided\n"+ " with:\n name: safe\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-other\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"every caller passes `name: safe`, so the PR key can only be `prefix-safe` and "+ f"`prefix-other` is a different namespace:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_two_differently_spelled_unresolved_keys_are_paired(tmp_path):+ """Both sides unresolved, spelled differently, is the case the earlier fixes missed.++ The identical-text rule only reaches keys written the same way, and an unresolved+ publish key was compared against RESOLVED PR keys alone before continuing, so+ `shared-${{ matrix.pr_part }}` and `shared-${{ matrix.pub_part }}` were never+ paired even though both can become `shared-x`. Each earlier fix covered one+ unresolved side at a time.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " strategy:\n matrix:\n pr_part: [a, b]\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: shared-${{ matrix.pr_part }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " strategy:\n matrix:\n pub_part: [x, y]\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: shared-${{ matrix.pub_part }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"both keys are headed `shared-` and neither tail is known, so they can be the "+ f"same entry:\n{proc.stdout}\n{proc.stderr}"+ )++ # Incompatible heads stay accepted, or every unresolved key in a tree would reject+ # every other one.+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " strategy:\n matrix:\n pub_part: [x, y]\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: wheels-only-${{ matrix.pub_part }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`shared-` and `wheels-only-` cannot become each other:\n{proc.stdout}\n" f"{proc.stderr}"+ )+++def test_a_delegated_key_whose_producer_was_not_read_stays_undecided(tmp_path):+ """Delegation settles a key only when the producer's namespace was recovered.++ `_shell_built_key_prefixes` reads two narrow spellings. A workflow emitting its key+ with `printf 'key=%s\\n'` matches neither, so nothing was recorded -- and dismissing+ the key as "delegated" turned an unread producer into a clean bill of health, letting+ a publish `restore-keys: shared-` through.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ ' run: printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the producer's spelling was not recognised, so the key's namespace is "+ f"unknown and `shared-` cannot be cleared:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_literal_producer_output_is_read_as_a_key(tmp_path):+ """A producer emitting a fully literal key is resolved, not unrecognised.++ Requiring a dynamic HEAD as the evidence that a producer was understood failed the+ opposite case: `echo 'key=own-v1-abc'` has no tail to assemble, so the head+ extractor finds nothing while the key is completely known. The value is an exact+ cache key, so it joins the comparison rather than only vouching for the step.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: probe\n"+ " run: echo 'key=own-v1-abc' >> \"$GITHUB_OUTPUT\"\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.probe.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: unrelated-v1\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"the key is known to be `own-v1-abc`, which is not `unrelated-v1`:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )++ # And the literal really is compared, rather than merely vouching for the producer.+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: own-v1-abc\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the publish workflow restores exactly the key the probe writes:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+++def test_a_publish_side_delegated_key_is_resolved_from_its_own_shell(tmp_path):+ """Shell heads were collected from PR-reachable documents only.++ So a publish workflow that emits `key=shared-key` and restores+ `${{ steps.probe.outputs.key }}` had that key dismissed as delegated with nothing+ recovered to compare it against, and a pull request writing the literal `shared-key`+ passed an exact collision.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: shared-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: probe\n"+ " run: echo 'key=shared-key' >> \"$GITHUB_OUTPUT\"\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.probe.outputs.key }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the publish workflow's own shell says the key is `shared-key`, which the "+ f"pull request writes:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_two_actions_sharing_a_directory_name_keep_their_call_sites(tmp_path):+ """`a/cache` and `b/cache` are different actions, however they end.++ Matching call sites on the last path component pooled them, so a value passed to one+ was attributed to the other and a publish key no pull request writes was rejected.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ first = root / "actions" / "a" / "cache"+ second = root / "actions" / "b" / "cache"+ wf.mkdir(parents = True)+ first.mkdir(parents = True)+ second.mkdir(parents = True)+ (first / "action.yml").write_text(+ "name: a cache\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: prefix-${{ inputs.name }}\n"+ )+ (second / "action.yml").write_text(+ "name: b cache\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - run: echo ${{ inputs.name }}\n shell: bash\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/a/cache\n"+ " with:\n name: safe\n"+ " - uses: ./.github/actions/b/cache\n"+ " with:\n name: shared\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-shared\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"`shared` only ever reaches b/cache, which caches nothing, so no PR cache "+ f"writes `prefix-shared`:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_one_readable_producer_does_not_vouch_for_an_unreadable_one(tmp_path):+ """Resolution belongs to a producing STEP, not to a whole side of the comparison.++ A side-wide flag let an ordinary `echo 'key=safe-key'` in one step certify a second+ step emitting `printf 'key=%s\\n'`, whose namespace was never recovered: the flag was+ true, the unread delegated key was dismissed, and a publish `restore-keys: shared-`+ passed. The single-producer test could not see this, because there was nothing else+ in the workflow to do the vouching.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ # readable, and entirely unrelated to the key that is actually used+ " - id: safe\n"+ " run: echo 'key=safe-key' >> \"$GITHUB_OUTPUT\"\n"+ # unreadable spelling, and this is the one whose value reaches the cache+ " - id: make\n"+ ' run: printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the key in use comes from the step that could NOT be read, whatever the "+ f"other step spells correctly:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_producer_that_declares_its_key_inline_is_readable():+ """A step's own `key:` is its output, and a local action's is too.++ Requiring a shell-built key as the evidence declared this repository's real+ producers unreadable: `frontend-dist-restore` hands out+ `steps.restore.outputs.cache-primary-key`, whose value is the `key:` the action+ declares in YAML, and an `actions/cache/restore` step publishes the key written+ beside it. Both failed the live tree before being recognised.+ """+ lint = _lint_module()+ # Identities are (document, job, step id), because a step id is unique only within+ # its job. A bare id let a readable namesake in another job -- or another file --+ # answer for an unreadable one.+ here = ("wf.yml", "build")+ producers = {("wf.yml", "build", "probe"): {"key"}}+ assert lint._delegation_is_read("${{ steps.probe.outputs.key }}", producers, here) is True+ assert (+ lint._delegation_is_read(+ "${{ steps.probe.outputs.key }}", {("wf.yml", "build", "probe"): set()}, here+ )+ is False+ )+ # Per OUTPUT, not per step: a step may write several, and recovering one says+ # nothing about the others.+ assert lint._delegation_is_read("${{ steps.probe.outputs.danger }}", producers, here) is False+ # The SAME id in a different job is a different step and vouches for nothing.+ assert (+ lint._delegation_is_read(+ "${{ steps.probe.outputs.key }}", {("wf.yml", "other", "probe"): {"key"}}, here+ )+ is False+ )+ assert (+ lint._delegation_is_read(+ "${{ steps.probe.outputs.key }}", {("z.yml", "build", "probe"): {"key"}}, here+ )+ is False+ )+ # A step this check never saw is not evidence of anything.+ assert lint._delegation_is_read("${{ steps.other.outputs.key }}", producers, here) is False+ # Nor is a form that names no step at all.+ assert lint._delegation_is_read("${{ needs.build.outputs.key }}", producers, here) is False+++def test_a_readable_namesake_in_another_job_vouches_for_nothing(tmp_path):+ """Step ids are unique within a job, so a bare id is the wrong identity.++ Merging producers by bare id let a readable `id: probe` in a later job -- or a+ later-sorted file -- overwrite an unreadable `id: probe` elsewhere, and the unread+ key was then dismissed on the strength of a step that has nothing to do with it.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n"+ # unreadable producer, and the job that actually caches+ " first:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: probe\n"+ ' run: printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.probe.outputs.key }}\n"+ # readable namesake in a different job, caching nothing of interest+ " second:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: probe\n"+ " run: echo 'key=safe-key' >> \"$GITHUB_OUTPUT\"\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the caching job's own `probe` could not be read, whatever the other job's "+ f"step of the same name spells:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_an_inline_key_input_does_not_certify_an_unrelated_output(tmp_path):+ """`with: {key: ...}` is evidence only for an action that publishes THAT key.++ Marking every id-bearing step with a `with.key` readable was too generous: a local+ action may accept an unrelated `key` input while emitting its own `outputs.key`+ from a command this check cannot read, and the delegated key was then dismissed+ with no namespace recovered at all.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "sneaky"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: sneaky\n"+ "inputs:\n key:\n description: unrelated\n"+ "outputs:\n"+ " key:\n"+ " description: the real cache key\n"+ " value: ${{ steps.inner.outputs.key }}\n"+ "runs:\n using: composite\n steps:\n"+ " - id: inner\n"+ " shell: bash\n"+ ' run: printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: maker\n"+ " uses: ./.github/actions/sneaky\n"+ " with:\n key: safe-key\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.maker.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the action's published key comes from a command that could not be read; the "+ f"`key` input it happens to accept says nothing about it:\n{proc.stdout}\n"+ f"{proc.stderr}"+ )+++def test_a_top_level_publish_input_is_not_resolved_by_a_child_targets_value(tmp_path):+ """A dispatch workflow's own `${{ inputs.X }}` is chosen by whoever dispatches it.++ Top-level workflow paths are not targets, so the publish side fell back to the+ merged child namespace and expanded a user-controlled workflow input using an+ unrelated action's literal -- then marked it complete. Dispatching with+ `cache_key=shared-key` restores exactly the cache a pull request wrote.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "unrelated"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: unrelated\n"+ "inputs:\n cache_key:\n description: k\n"+ "runs:\n using: composite\n steps:\n"+ " - run: echo ${{ inputs.cache_key }}\n shell: bash\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: shared-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n"+ " workflow_dispatch:\n"+ " inputs:\n"+ " cache_key:\n"+ " description: chosen by whoever dispatches\n"+ " type: string\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/unrelated\n"+ " with:\n cache_key: safe-key\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ inputs.cache_key }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the dispatch input can be given `shared-key`, and the unrelated action's "+ f"`safe-key` says nothing about it:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_an_action_used_from_a_checkout_subdirectory_is_reachable(tmp_path):+ """`./unsloth/.github/actions/x` is the same action, through a runtime layout.++ A job that checks this repository out into a subdirectory writes the reference that+ way, and probing it as written found nothing in the source tree, so the action was+ never added to the reachable set: the keys it declares sat outside both comparisons.+ `notebooks-ci.yml` and `version-compat-ci.yml` both use this form.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "nested-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: nested cache\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: shared-inner\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ # checked out under `unsloth/`, so the reference carries that prefix+ " - uses: ./unsloth/.github/actions/nested-cache\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: shared-inner\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the prefixed reference names the same action, whose key the publish workflow "+ f"restores exactly:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_commented_out_output_does_not_certify_a_producer(tmp_path):+ """A commented line executes nothing, so it is not evidence about the step.++ Reading one as a recovered output let an otherwise unreadable producer certify+ itself: a `# echo 'key=safe-key'` above a real `printf` marked the step readable,+ its delegated key was dismissed, and a publish `restore-keys: shared-` passed.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ " run: |\n"+ " # echo 'key=safe-key' >> \"$GITHUB_OUTPUT\"\n"+ ' printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the only line that runs is the printf, which this check cannot read:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+++def test_an_unquoted_scalar_key_is_compared(tmp_path):+ """`key: 123` is an int to YAML and a cache key to Actions.++ The scoped pass accepted only `str`, so it dropped the key entirely and two+ workflows sharing it were reported as collision-free.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: 123\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: 123\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, f"both workflows use the same key:\n{proc.stdout}\n{proc.stderr}"+++def test_a_wrapper_forwarding_its_own_input_is_resolved(tmp_path):+ """A forwarded `${{ inputs.name }}` is whatever the WRAPPER's callers pass.++ Classifying it as dynamic left a nested composite undecidable, so an unrelated+ publish key was rejected though every top-level caller supplies a literal. A guard+ that fails a valid arrangement is one that gets switched off.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ inner = root / "actions" / "inner-cache"+ wrapper = root / "actions" / "wrapper"+ wf.mkdir(parents = True)+ inner.mkdir(parents = True)+ wrapper.mkdir(parents = True)+ (inner / "action.yml").write_text(+ "name: inner cache\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: prefix-${{ inputs.name }}\n"+ )+ (wrapper / "action.yml").write_text(+ "name: wrapper\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: ./.github/actions/inner-cache\n"+ " with:\n name: ${{ inputs.name }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/wrapper\n"+ " with:\n name: safe\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-other\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"every caller passes `name: safe`, so the only PR key is `prefix-safe`:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )++ # And the resolution keeps its teeth: the value really reaching the cache collides.+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-safe\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"`prefix-safe` is exactly what the wrapper produces:\n{proc.stdout}\n" f"{proc.stderr}"+ )+++def test_one_readable_output_does_not_certify_another_from_the_same_step(tmp_path):+ """Readability belongs to an OUTPUT, not to the step that writes several.++ A step emitting a recognisable `key=safe-key` alongside a `danger=` written by a+ `printf` form that recovers nothing was marked readable as a whole, and the cache+ consuming `outputs.danger` was dismissed on the strength of the output it does not+ use.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ " run: |\n"+ " echo 'key=safe-key' >> \"$GITHUB_OUTPUT\"\n"+ ' printf \'danger=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.danger }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the cache uses `danger`, which was written by the form this check cannot "+ f"read:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_an_unrelated_assignment_does_not_certify_the_output(tmp_path):+ """A recognisable assignment elsewhere in the body is not evidence about the output.++ `safe_key="safe-${RANDOM}"` followed by an unreadable `printf` writing the real key+ left only `safe-` recovered, and the delegated cache key was skipped even though+ nothing about it had been understood.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ " run: |\n"+ ' safe_key="safe-${RANDOM}"\n'+ ' printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/save@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ )+ (wf / "release-desktop.yml").write_text(+ _publish_with_restore_keys("shared-pub", " shared-\n")+ )+ proc = _run(wf)+ assert (+ proc.returncode == 1+ ), f"the only line writing an output is the printf:\n{proc.stdout}\n{proc.stderr}"+++def test_two_publish_jobs_sharing_a_raw_key_keep_their_own_scopes(tmp_path):+ """`(path, key)` is not unique, and the first job's scope was kept for both.++ So a second publish job whose producer could not be read was judged against the+ first job's readable one, and a PR cache matching the unread producer passed.+ """+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: shared-key\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n"+ " first:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ " run: echo 'key=unrelated-v1' >> \"$GITHUB_OUTPUT\"\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ " second:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - id: make\n"+ ' run: printf \'key=%s\\n\' "shared-$GITHUB_SHA" >> "$GITHUB_OUTPUT"\n'+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: ${{ steps.make.outputs.key }}\n"+ )+ proc = _run(wf)+ assert proc.returncode == 1, (+ f"the second job's producer could not be read, and the first job's readable "+ f"namesake says nothing about it:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_key_passed_to_a_non_cache_action_is_not_a_cache_namespace(tmp_path):+ """Not every field named `key` declares a cache.++ A composite passing `with: {key: release-key}` to an unrelated action registered+ that value as a namespace pull requests write, so a publish workflow genuinely+ caching `release-key` was rejected though the PR path never touches a cache.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "signer"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: signer\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: some/signing-action@v1\n"+ " with:\n key: release-key\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/signer\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: release-key\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"the pull request path caches nothing; `key` there is a signing key:\n"+ f"{proc.stdout}\n{proc.stderr}"+ )+++def test_a_call_site_reached_through_a_checkout_prefix_is_matched(tmp_path):+ """Reachability strips the runtime prefix; the call-site comparison did not.++ So literal inputs passed through `./repo/.github/actions/x` were never recovered and+ the key stayed undecidable, rejecting an unrelated publish key.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "prefixed-cache"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: prefixed cache\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: prefix-${{ inputs.name }}\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./repo/.github/actions/prefixed-cache\n"+ " with:\n name: safe\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n key: prefix-other\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"the prefixed call site passes `name: safe`, so the only PR key is "+ f"`prefix-safe`:\n{proc.stdout}\n{proc.stderr}"+ )+++def test_a_publish_restore_prefix_is_expanded_with_its_own_inputs(tmp_path):+ """A publish fallback carrying an input reduces to a head far broader than it is.++ `restore-keys: prefix-${{ inputs.name }}-` called with `name: publish` falls back to+ `prefix-publish-` at run time, and reducing it to `prefix-` collided with every PR+ key under that head.+ """+ root = tmp_path / ".github"+ wf = root / "workflows"+ action = root / "actions" / "pub-restore"+ wf.mkdir(parents = True)+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: pub restore\n"+ "inputs:\n name:\n description: n\n"+ "runs:\n using: composite\n steps:\n"+ " - uses: actions/cache/restore@v4\n"+ " with:\n path: wheels\n"+ " key: prefix-${{ inputs.name }}-exact\n"+ " restore-keys: |\n"+ " prefix-${{ inputs.name }}-\n"+ )+ (wf / "pr-build.yml").write_text(+ "name: pr-build\n"+ "on:\n pull_request:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache@v4\n"+ " with:\n path: wheels\n key: prefix-pr-exact\n"+ )+ (wf / "release-desktop.yml").write_text(+ "name: release-desktop\n"+ "on:\n workflow_dispatch:\n"+ "jobs:\n publish:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/pub-restore\n"+ " with:\n name: publish\n"+ )+ proc = _run(wf)+ assert proc.returncode == 0, (+ f"the runtime fallback is `prefix-publish-`, which cannot reach "+ f"`prefix-pr-exact`:\n{proc.stdout}\n{proc.stderr}"+ )diff --git a/tests/studio/test_actions_are_pinned_to_commits.py b/tests/studio/test_actions_are_pinned_to_commits.pynew file mode 100644index 00000000000..7098fc740d1--- /dev/null+++ b/tests/studio/test_actions_are_pinned_to_commits.py@@ -0,0 +1,374 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Every third-party action must be referenced by commit SHA, never by a tag.++A tag is a pointer the upstream owner can move whenever they like. `uses: foo/bar@v3` is+therefore not a dependency on reviewed code, it is an agreement to run whatever that+repository contains on the day CI happens to run, decided by someone outside this+project. The decision is theirs, the credentials are ours: the action runs inside our+job, with whatever secrets and token permissions that job holds. `tj-actions/changed-files`+(GHSA-mrrh-fwg8-l2gq, March 2025) is the case everybody cites, where retagging one action+exfiltrated secrets out of tens of thousands of repositories, and it needed nothing more+exotic than a moved tag.++This repository already got this right nearly everywhere, which is exactly why a guard is+worth having: 53 of ~400 `uses:` references had drifted onto mutable tags, all of them in+the `docker-*` and `woa-wheelhouse` family, while every other workflow pinned properly.+That is the shape a convention with no test develops. Nothing asserted it before this+module -- `scripts/lint_workflow_triggers.py` checks triggers and cache keys, and no test+under `tests/` mentioned SHA pinning at all.++The 53 were pinned at the SHAs their tags already resolved to, which changed no versions.+Worth recording how that was confirmed, because it is the reassuring part: the resolved+SHAs were byte-identical to what the same actions were already pinned to elsewhere in this+repo, e.g. `actions/checkout` at 3d3c42e5 and `actions/upload-artifact` at 043fb46d. So+the docker family had simply been written in a different style, not held at a different+version.++Scope, and why it is drawn here. First-party `uses: ./...` references are exempt: they+resolve inside this checkout at the commit under test, so there is no third party and no+mutable pointer. Everything else is in, including `actions/*` and `docker/*`. Those are+reputable publishers, but reputable is not the property that matters. The property that+matters is whether the bytes can change without a commit here, and for a tag they can. A+compromised upstream account moves the tag either way.++Docker image references in `container:` and `services:` are deliberately NOT covered.+They are a real instance of the same problem, and pinning them by digest is worth doing,+but a `:tag` image reference and a `uses:` action reference have different syntax and+different failure modes, and a guard that tried to cover both would assert neither+clearly. Recorded here so the gap is known rather than mistaken for coverage.+"""++import re+from pathlib import Path++import pytest+import yaml++REPO = Path(__file__).resolve().parents[2]+GITHUB = REPO / ".github"++_SHA = re.compile(r"^[0-9a-f]{40}$")++# A pinned-by-SHA reference whose upstream repository is gone or renamed cannot be+# reviewed, but it also cannot change, so it is not this module's problem.+DELIBERATELY_UNPINNED = {+ # Each entry needs the reason written here. Empty is the goal, and it growing needs+ # an argument rather than a deadline: there is no version of "we will pin it later"+ # that is safer than pinning it now, because the pin is a one-line change.+}+++# Actions deliberately held at two different commits, keyed on `owner/repo`, with the+# reason. The failure below used to tell people to "say so in a comment at each site",+# which nothing read, so the documented remedy could not make CI pass and the only way+# out was editing this file. This is the mechanism that advice implied.+DELIBERATELY_SPLIT: dict[str, str] = {+ # Empty, and a split is nearly always a half-finished upgrade rather than a decision.+ # An entry here needs the reason a single commit will not do, not a note that two+ # exist.+}+++def _owner_repo(ref_repo: str) -> str:+ """`actions/cache/save` and `actions/cache` are one repository, pinned once.++ A sub-action lives in its parent repository and a `uses:` SHA names a commit of that+ repository, so `actions/cache@<a>`, `actions/cache/restore@<b>` and+ `actions/cache/save@<c>` are three different commits of ONE action. Grouping by the+ full path put each under its own key, every group held a single SHA, and the+ one-commit rule passed while three versions of `actions/cache` ran side by side --+ exactly the half-finished upgrade it exists to catch.+ """+ parts = ref_repo.split("/")+ return "/".join(parts[:2]) if len(parts) > 2 else ref_repo+++def _sources():+ """Every workflow and action definition under .github, as (path, text)."""+ for path in sorted(GITHUB.rglob("*.y*ml")):+ yield path, path.read_text(encoding = "utf-8", errors = "ignore")+++# Split on the LAST `@` rather than enumerating what a ref may contain. Git ref names+# accept characters the first version left out -- `+` among them, and+# `git check-ref-format refs/tags/v1+build` agrees -- so `owner/action@v1+build` produced+# no match and was omitted from every pinning check while still being a mutable tag. A+# guard that silently skips what it cannot parse is worse than one that over-collects,+# because the `_SHA` test below decides the verdict anyway.+_REPO_PART = re.compile(r"""^[A-Za-z0-9][\w.-]*/[\w.-]+(?:/[\w.\-/]+)?$""")+++def _split_ref(value: str):+ r"""(repo, rev) for a `uses:` value, split at the FIRST `@`.++ The first, not the last. A repository name cannot contain `@`, so the first one is+ always the delimiter, and everything after it is the revision however many more it+ holds. The previous version said "last delimiter" in its comment and then spelled+ `[^@\s]+` for the revision, which forbids the very character it claimed to split on;+ `git check-ref-format refs/tags/v@1` succeeds, so `owner/action@v@1` is a valid+ mutable tag that produced no match at all and was dropped from every pinning check.+ Splitting last would not have fixed it either, since that reads the repository as+ `owner/action@v`. The failure mode is the one the comment was written about: a guard+ that silently skips what it cannot parse.+ """+ if "@" not in value:+ return None+ repo, _, rev = value.partition("@")+ if not rev or not rev.strip() or any(c.isspace() for c in rev):+ return None+ if not _REPO_PART.match(repo):+ return None+ return repo, rev+++def _uses_values(node):+ """Every `uses` value anywhere in a parsed document, at any depth.++ Walking the parsed structure rather than the source text, because enumerating+ spellings of the key does not converge. The lexical scan started on `uses:`, then+ needed `"uses":` and `uses :`, and flow style `- {uses: actions/checkout@v4}` is+ another valid step mapping again -- each one a reference the guard simply could not+ see, in a module whose entire job is to refuse mutable tags. PyYAML resolves all of+ them to the same mapping key, so asking it ends the sequence instead of extending it.+ """+ if isinstance(node, dict):+ for key, value in node.items():+ if str(key).strip() == "uses" and isinstance(value, str):+ yield value.strip()+ else:+ yield from _uses_values(value)+ elif isinstance(node, list):+ for item in node:+ yield from _uses_values(item)+++def _references():+ """(path, lineno, ref, repo, rev) for every third-party `uses:` in the tree."""+ for path, text in _sources():+ try:+ doc = yaml.safe_load(text)+ except yaml.YAMLError:+ continue+ for ref in _uses_values(doc):+ # `uses: ./.github/actions/x` resolves inside this checkout, and+ # `docker://` is an image rather than an action; neither is a mutable+ # third-party pointer.+ if ref.startswith(".") or ref.startswith("docker://"):+ continue+ parts = _split_ref(ref)+ if parts is None:+ continue+ # The parser discards positions, so recover the line from the source for the+ # failure message. Only ever cosmetic: a reference that cannot be located is+ # still reported, at line 0.+ index = text.find(ref)+ lineno = text.count("\n", 0, index) + 1 if index >= 0 else 0+ yield path, lineno, ref, parts[0], parts[1]+++def test_the_scan_finds_the_references_it_claims_to():+ """A regex that matched nothing would pass every check below on an empty set."""+ refs = list(_references())+ assert len(refs) >= 200, (+ f"only found {len(refs)} third-party `uses:` references; the scan is wrong. This "+ f"tree has hundreds across .github/workflows and .github/actions."+ )+ repos = {repo for _, _, _, repo, _ in refs}+ for expected in ("actions/checkout", "step-security/harden-runner"):+ assert expected in repos, f"{expected} is used here but the scan missed it"+++def test_the_sha_predicate_reads_the_revision():+ """The guard is only as good as this predicate, so the predicate is tested too."""+ forty = "3d3c42e5aac5ba805825da76410c181273ba90b1"+ cases = [+ (forty, True),+ (forty.upper(), False), # git object names are lowercase hex+ (forty[:39], False), # short SHAs are ambiguous and not pins+ (forty + "a", False),+ ("v7", False),+ ("v7.0.1", False),+ ("main", False),+ ("master", False),+ ("", False),+ ]+ for rev, expected in cases:+ assert bool(_SHA.match(rev)) is expected, f"_SHA.match({rev!r})"+++def test_the_scan_reads_every_spelling_of_a_step_mapping():+ """A guard that recognises one spelling of its own key is a guard with a keyhole.++ The scan began as a regex on `uses:`, which missed `"uses":` and `uses :`, and then+ missed flow style `- {uses: actions/checkout@v4}` after those were added. Each miss+ was a reference absent from the scan entirely, so a mutable tag written that way+ passed a test whose whole purpose is to refuse mutable tags, and the cost of the+ bypass was a pair of quotes or a pair of braces. Enumerating spellings does not+ converge; the parser resolves all of them to the same mapping key.+ """+ spellings = [+ "steps:\n - uses: actions/checkout@v4\n",+ 'steps:\n - "uses": actions/checkout@v4\n',+ "steps:\n - 'uses': actions/checkout@v4\n",+ "steps:\n - uses : actions/checkout@v4\n",+ "steps:\n - {uses: actions/checkout@v4}\n",+ "steps: [{uses: actions/checkout@v4}]\n",+ 'steps:\n - uses: "actions/checkout@v4"\n',+ # Nested inside a composite action, which is the other place `uses` appears.+ "runs:\n using: composite\n steps:\n - uses: actions/checkout@v4\n",+ ]+ for source in spellings:+ found = list(_uses_values(yaml.safe_load(source)))+ assert found == ["actions/checkout@v4"], f"{source!r} produced {found!r}"++ # A `uses` value that is not a reference, and a key that merely contains the word,+ # must not be picked up as third-party references.+ assert list(_uses_values(yaml.safe_load("steps:\n - uses: ./.github/actions/x\n"))) == [+ "./.github/actions/x"+ ]+ assert list(_uses_values(yaml.safe_load("steps:\n - name: uses a cache\n"))) == []+++def test_the_reference_predicate_reads_owner_repo_at_ref():+ """`_split_ref` decides what counts as a third-party reference at all."""+ cases = [+ ("actions/checkout@v4", True),+ ("actions/cache/restore@v4", True),+ ("owner/repo@0123456789abcdef0123456789abcdef01234567", True),+ ("./.github/actions/x", False),+ ("docker://alpine:3", False),+ ("actions/checkout", False), # no ref at all+ ("notapath@v4", False), # no owner+ ("", False),+ ]+ for ref, expected in cases:+ assert bool(_split_ref(ref)) is expected, f"_split_ref({ref!r})"+++def test_every_third_party_action_is_pinned_to_a_commit_sha():+ offenders = []+ for path, lineno, ref, _repo, rev in _references():+ if _SHA.match(rev):+ continue+ if ref in DELIBERATELY_UNPINNED:+ continue+ offenders.append(f"{path.relative_to(GITHUB).as_posix()}:{lineno}: {ref}")++ assert not offenders, (+ f"these `uses:` references name a mutable tag or branch instead of a commit:\n "+ + "\n ".join(sorted(offenders))+ + "\n\nA tag is a pointer the upstream owner can move, so each of these runs "+ "whatever that repository contains on the day CI runs, inside a job holding this "+ "repo's secrets and token permissions. That is the tj-actions/changed-files "+ "compromise (GHSA-mrrh-fwg8-l2gq), which needed nothing but a moved tag.\n\n"+ "Pin to the 40-character commit the tag currently points at and keep the version "+ "in a trailing comment, which is what the rest of this tree does:\n"+ " uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1\n\n"+ "`gh api repos/<owner>/<repo>/commits/<tag> --jq .sha` resolves it. If a reference "+ "genuinely cannot be pinned, add it to DELIBERATELY_UNPINNED with the reason."+ )+++def test_every_exemption_still_exists_and_still_needs_one():+ """A stale exemption is a hole nobody is asking for any more."""+ live = {ref for _, _, ref, _, _ in _references()}+ for ref in DELIBERATELY_UNPINNED:+ assert ref in live, (+ f"{ref} is exempted here but no longer referenced anywhere under .github, so "+ f"the exemption describes nothing. Remove it from DELIBERATELY_UNPINNED."+ )+++ "repo",+ sorted({_owner_repo(r) for _, _, _, r, _ in _references()}),+)+def test_an_action_is_pinned_to_one_sha_everywhere_it_is_used(repo):+ """Two SHAs for one action means two versions of it run, which is nearly always a slip.++ Not a security property on its own, but it is how a half-finished upgrade shows up,+ and a stale copy is the one that keeps an already-fixed bug alive.+ """+ revs = {rev for _, _, _, r, rev in _references() if _owner_repo(r) == repo and _SHA.match(rev)}+ if len(revs) <= 1:+ return+ if repo in DELIBERATELY_SPLIT:+ return+ sites = sorted(+ f"{p.relative_to(GITHUB).as_posix()}:{ln}: {rev[:12]}"+ for p, ln, _, r, rev in _references()+ if _owner_repo(r) == repo and _SHA.match(rev)+ )+ pytest.fail(+ f"{repo} is pinned to {len(revs)} different commits, so different jobs run "+ f"different versions of it:\n " + "\n ".join(sites) + "\n\n"+ f"Settle on one commit, usually the newest reviewed one. If the split really is "+ f"deliberate, add {repo!r} to DELIBERATELY_SPLIT in this file with the reason a "+ f"single commit will not do."+ )+++def test_every_split_exemption_still_exists_and_still_needs_one():+ """A stale exemption hides a split that has since been resolved."""+ live = {r for _, _, _, r, _ in _references()}+ for repo, reason in DELIBERATELY_SPLIT.items():+ assert reason.strip(), f"{repo} is exempted with no reason written; add one"+ assert repo in live, (+ f"{repo} is exempted from the one-commit rule but is no longer used anywhere "+ f"under .github, so the exemption describes nothing. Remove it."+ )+ revs = {rev for _, _, _, r, rev in _references() if r == repo and _SHA.match(rev)}+ assert len(revs) > 1, (+ f"{repo} is exempted from the one-commit rule but is now pinned to a single "+ f"commit, so the exemption is stale. Remove it from DELIBERATELY_SPLIT."+ )+++def test_the_reference_predicate_accepts_valid_git_ref_punctuation():+ """A ref the scan cannot parse is a ref the guard silently skips.++ Git ref names accept characters an enumerated character class leaves out: `+` among+ them, and `git check-ref-format refs/tags/v1+build` agrees. `owner/action@v1+build`+ produced no match and was omitted from every pinning check while still being a+ mutable tag.+ """+ # `v@1` included: `git check-ref-format refs/tags/v@1` succeeds, so it is a valid+ # mutable tag, and a revision pattern spelled `[^@\s]+` forbade the very character+ # the split is named for -- dropping it from every pinning check.+ for ref in (+ "owner/action@v1+build",+ "owner/action@release~1",+ "owner/[email protected]",+ "owner/action@v@1",+ ):+ parts = _split_ref(ref)+ assert parts is not None, f"{ref} is a valid mutable reference and must be seen"+ assert parts[0] == "owner/action", ref+ assert not _SHA.match(parts[1]), f"{ref} is not a pin"++ # Still not references, so over-collecting does not turn into over-reporting.+ for ref in ("./.github/actions/x", "docker://alpine:3", "actions/checkout", ""):+ assert _split_ref(ref) is None, ref+++def test_a_sub_action_is_pinned_with_its_repository():+ """`actions/cache/save` is a path inside `actions/cache`, not a separate repository.++ A `uses:` SHA names a commit of the repository the action lives in, so+ `actions/cache@<a>`, `actions/cache/restore@<b>` and `actions/cache/save@<c>` are+ three commits of ONE action. Grouping by the full path gave each its own group,+ every group held exactly one SHA, and the one-commit rule passed while three+ versions of `actions/cache` ran side by side -- the precise half-finished upgrade it+ exists to report.+ """+ assert _owner_repo("actions/cache/save") == "actions/cache"+ assert _owner_repo("actions/cache/restore") == "actions/cache"+ assert _owner_repo("actions/cache") == "actions/cache"+ assert _owner_repo("actions/checkout") == "actions/checkout"+ # A deep path still resolves to the repository that holds it.+ assert _owner_repo("owner/repo/a/b/c") == "owner/repo"+ # The grouping has to be what the rule is parametrized over, or it changes nothing.+ groups = {_owner_repo(r) for _, _, _, r, _ in _references()}+ assert "actions/cache/save" not in groupsdiff --git a/tests/studio/test_cached_paths_hold_no_credentials.py b/tests/studio/test_cached_paths_hold_no_credentials.pyindex 69050533d0b..16354f4da81 100644--- a/tests/studio/test_cached_paths_hold_no_credentials.py+++ b/tests/studio/test_cached_paths_hold_no_credentials.py@@ -80,9 +80,8 @@ ACTIONS = REPO / ".github" / "actions"CREDENTIAL_HOMES = {# huggingface_hub writes $HF_HOME/token and, since 0.25, $HF_HOME/stored_tokens."HF_HOME": "token, stored_tokens",- # Both are consulted before HF_HOME by older releases still pinned in some lanes.- "HUGGINGFACE_HUB_CACHE": "token",- "TRANSFORMERS_CACHE": "token",+ # And HF_TOKEN_PATH names the token file directly, overriding the location above.+ "HF_TOKEN_PATH": "the token file itself",# npm and cargo both keep registry credentials in their config roots."NPM_CONFIG_USERCONFIG": ".npmrc auth tokens","CARGO_HOME": "credentials.toml",@@ -91,9 +90,120 @@ CREDENTIAL_HOMES = {"GOOGLE_APPLICATION_CREDENTIALS": "service account json",}+# HUGGINGFACE_HUB_CACHE and TRANSFORMERS_CACHE are deliberately NOT here. Both select a+# MODEL cache, not a credential home: verified against huggingface_hub 1.32.0, where+# HUGGINGFACE_HUB_CACHE defaults to `$HF_HOME/hub` and the token is read from+# HF_TOKEN_PATH, default `$HF_HOME/token`, computed independently of it. So pointing+# HUGGINGFACE_HUB_CACHE at a directory and caching that directory persists blobs and no+# token. Listing them rejected the arrangement this module recommends everywhere else,+# which is the kind of false failure that gets a security guard switched off.++# Where those same tools keep credentials when nothing overrides them. Caching one of+# these is the identical hazard reached WITHOUT setting any variable, which is the version+# that reads as harmless: there is no HF_HOME in the file to notice.+# unsloth-zoo's gemma4-audio-probe.yml cached ~/.cache/huggingface until 2026-09-22 for+# exactly that reason, and the explicit-variable check below would have passed it.+# What each home actually holds, for deciding whether a restrictive glob could capture+# it. An empty tuple means the variable names the credential FILE itself rather than a+# directory, so the configured path is what a pattern has to match.+#+# Derived per variable rather than from one global list of filenames. The global list+# was a guess that omitted `credentials.toml`, which `CREDENTIAL_HOMES` three lines up+# already documents, so `cargo-home/*.toml` was accepted while it persisted exactly the+# file cargo writes. A canned list cannot cover a file-valued home at all, since those+# take whatever basename the job chooses.+CREDENTIAL_FILES = {+ "HF_HOME": ("token", "stored_tokens"),+ "HF_TOKEN_PATH": (),+ "NPM_CONFIG_USERCONFIG": (),+ "CARGO_HOME": ("credentials", "credentials.toml"),+ "DOCKER_CONFIG": ("config.json",),+ "AWS_SHARED_CREDENTIALS_FILE": (),+ "GOOGLE_APPLICATION_CREDENTIALS": (),+}+++# The files each DEFAULT home holds, so a workflow persisting one exactly is caught.+# The configured-home branch already tested `<home>/<file>`; defaults had no variable to+# take filenames from, so uploading `~/.cargo/credentials.toml` outright passed both+# guards -- the default directory is not inside the persisted file, which is the only+# question that was being asked.+DEFAULT_HOME_FILES = {+ "~/.cache/huggingface": ("token", "stored_tokens"),+ "~/.huggingface": ("token",),+ "~/.cargo": ("credentials", "credentials.toml"),+ "~/.docker": ("config.json",),+ "~/.npmrc": (),+ "~/.aws": ("credentials",),+ "~/.config/gh": ("hosts.yml",),+}++DEFAULT_CREDENTIAL_HOMES = {+ "~/.cache/huggingface": "HF_HOME default; token, stored_tokens",+ "~/.huggingface": "legacy HF_HOME default; token",+ "~/.cargo": "CARGO_HOME default; credentials.toml",+ "~/.docker": "DOCKER_CONFIG default; config.json auth entries",+ "~/.npmrc": "npm auth tokens",+ "~/.aws": "aws credentials",+ "~/.config/gh": "gh CLI oauth token",+}+# Anything that makes a tool persist a credential into one of the directories above.# Matched against the shell body of every step, so a login added anywhere in a job that# caches its own credential home fails the guard.+# Which variable overrides each default. A default is only where a tool looks when+# nothing points it elsewhere, so a job that sets the variable writes its credentials+# there instead and persisting the default location holds none. Flagging it anyway was a+# false failure on a correct configuration.+# Any ONE of these variables being set moves the credential out of the default+# location. Two variables reach the Hugging Face default: HF_HOME relocates the whole+# directory, and HF_TOKEN_PATH relocates the token and `stored_tokens` on their own, so+# a job setting only HF_TOKEN_PATH writes nothing of interest to `~/.cache/huggingface`+# and persisting it was reported anyway. A single owner per default could not express+# that.+DEFAULT_OWNERS = {+ "~/.cache/huggingface": ("HF_HOME", "HF_TOKEN_PATH"),+ "~/.huggingface": ("HF_HOME", "HF_TOKEN_PATH"),+ "~/.cargo": ("CARGO_HOME",),+ "~/.docker": ("DOCKER_CONFIG",),+ "~/.npmrc": ("NPM_CONFIG_USERCONFIG",),+ "~/.aws": ("AWS_SHARED_CREDENTIALS_FILE",),+ "~/.config/gh": (),+}++# Which credential homes each shell login actually writes into. Matching every pattern+# against every variable reported a job that caches `HF_HOME` and runs `docker login` as+# leaking the Hugging Face token, which it plainly does not: docker writes+# $DOCKER_CONFIG/config.json. The same false failure applied to npm, cargo, aws and gcloud.+#+# `None` means "any credential home", used for the Hugging Face patterns because those+# write to whichever of HF_HOME or HF_TOKEN_PATH is in force.+# Both, because `huggingface_hub` computes the token path from HF_TOKEN_PATH when it is+# set and from HF_HOME when it is not, independently of each other.+_HF_HOMES = ("HF_HOME", "HF_TOKEN_PATH")++LOGIN_PATTERN_HOMES = {+ # `hf auth login` writes whichever of these is in force, and nothing else. Leaving+ # them out of this map meant the "any home" fallback below matched them against every+ # variable in the job, so a job caching CARGO_HOME while running an unrelated Hugging+ # Face login failed, naming a Cargo directory the token never goes near. That is the+ # same false pairing the map was added to remove, left in place for the patterns the+ # map exists for.+ r"\bhf\s+auth\s+login\b": _HF_HOMES,+ r"\bhuggingface-cli\s+login\b": _HF_HOMES,+ r"\bhf\s+login\b": _HF_HOMES,+ r"huggingface_hub[.\s]*\.?\s*login\s*\(": _HF_HOMES,+ r"\bfrom\s+huggingface_hub\s+import\s+[^\n]*\blogin\b": _HF_HOMES,+ r"\bHfFolder\b[^\n]*\bsave_token\b": _HF_HOMES,+ r"\bsave_token\s*\(": _HF_HOMES,+ r"add_to_git_credential\s*=\s*True": _HF_HOMES,+ r"\bnpm\s+login\b": ("NPM_CONFIG_USERCONFIG",),+ r"\bcargo\s+login\b": ("CARGO_HOME",),+ r"\bdocker\s+login\b": ("DOCKER_CONFIG",),+ r"\bgcloud\s+auth\s+(?:application-default\s+)?login\b": ("GOOGLE_APPLICATION_CREDENTIALS",),+ r"\baws\s+configure\b": ("AWS_SHARED_CREDENTIALS_FILE",),+}+LOGIN_PATTERNS = (r"\bhf\s+auth\s+login\b",r"\bhuggingface-cli\s+login\b",@@ -111,6 +221,38 @@ LOGIN_PATTERNS = ()_CACHE_SAVE = ("actions/cache/save", "actions/cache@")+# Actions that write a credential into a tool's credential home. Same hazard as a `run:`+# login, with no shell body for a pattern to match.+#+# Each maps to the credential-home variables it ACTUALLY writes, and the pairing is the+# whole point. Keying only on the action fired on eight live workflows where+# `actions/setup-node` sat in a job whose cached directory was named by HF_HOME, a+# variable setup-node has nothing to do with. A guard that reports a Hugging Face leak+# because a job installs Node teaches people to switch it off.+#+# `condition` names a `with:` input that must be present before the action writes+# anything: setup-node only creates an .npmrc token when `registry-url` is set, and+# otherwise just installs a runtime.+LOGIN_ACTIONS = {+ "docker/login-action": {+ "vars": ("DOCKER_CONFIG",),+ "why": "registry auth into $DOCKER_CONFIG/config.json",+ },+ "aws-actions/configure-aws-credentials": {+ "vars": ("AWS_SHARED_CREDENTIALS_FILE",),+ "why": "aws credentials",+ },+ "google-github-actions/auth": {+ "vars": ("GOOGLE_APPLICATION_CREDENTIALS",),+ "why": "an application default credentials file",+ },+ "actions/setup-node": {+ "vars": ("NPM_CONFIG_USERCONFIG",),+ "why": "an .npmrc auth token",+ "condition": "registry-url",+ },+}+_PERSIST = _CACHE_SAVE + ("actions/upload-artifact",)@@ -163,6 +305,68 @@ def _env_of(job, doc):return env+def _step_envs(job):+ """Every step-level `env:` block in the job, one dict each.++ Setting the credential home on the step that runs the tool is the natural way to+ write it, and reading only workflow- and job-level `env:` missed that spelling+ entirely: a job whose cached directory was named by the very step writing into it+ passed this guard. Each is merged over the job's env, which is the precedence+ Actions applies.+ """+ out = []+ for step in _steps(job):+ source = step.get("env")+ if isinstance(source, dict):+ out.append({str(k): str(v) for k, v in source.items()})+ return out+++def _expand(+ value: str,+ env: dict,+ inputs: dict | None = None,+) -> str:+ """Substitute `${{ env.X }}`, and `${{ inputs.X }}`, before comparing paths.++ `_normalise` deletes expressions wholesale, so `path: ${{ env.HF_HOME }}` reduced to+ the empty string and `_inside` refuses an empty operand. A job that cached exactly+ its own credential home, spelled through the variable rather than repeated+ literally, was therefore silently exempt from the rule aimed at it.++ `inputs` matters for the same reason one level down. A composite whose cache step+ says `path: ${{ inputs.path }}` names its persisted directory through an input, so+ without the caller's `with:` block the path resolved to empty and the composite+ appeared to persist nothing at all.+ """+ # To a fixed point, because a variable's value may name another variable. With+ # `CACHE_ROOT: hf-cache` at workflow level, `HF_HOME: ${{ env.CACHE_ROOT }}` on the+ # job and `path: ${{ env.HF_HOME }}` on the cache step, one pass left+ # `${{ env.CACHE_ROOT }}` standing, `_normalise` erased it, and the job cached its+ # own credential home with no offender reported. Actions resolves the whole chain.+ #+ # The iteration is bounded rather than trusting the chain to terminate: two variables+ # that name each other would otherwise substitute forever. A value still holding an+ # expression after the last pass is left as it is and handled downstream, which is+ # the same outcome as an unknown variable.+ for _ in range(8):+ before = value+ value = re.sub(+ r"\$\{\{\s*env\.([A-Za-z_]\w*)\s*\}\}",+ lambda m: env.get(m.group(1), ""),+ value,+ )+ if inputs:+ value = re.sub(+ r"\$\{\{\s*inputs\.([A-Za-z_][\w-]*)\s*\}\}",+ lambda m: str(inputs.get(m.group(1), "")),+ value,+ )+ if value == before:+ break+ return value++def _persisted_paths(job):"""Every path this job writes to a cache or an artifact."""out = []@@ -183,35 +387,553 @@ def _persisted_paths(job):return out+def _reusable_jobs(+ job,+ env = None,+ inputs = None,+):+ """(steps, env, inputs) for a job that delegates to a local reusable workflow.++ `jobs.<id>.uses: ./.github/workflows/x.yml` has no `steps:` of its own, so the caller+ scanned as an empty job and the called workflow was scanned separately with no access+ to the caller's `with:` values. A reusable job that sets `HF_HOME: ${{ inputs.path }}`,+ logs in and caches `${{ inputs.path }}` was therefore accepted when the caller passed+ `path: hf-cache`: both expressions normalised away and neither document held enough to+ see the combination. The same split that hid composite logins, one level up.+ """+ ref = str(job.get("uses") or "").strip().strip("'\"")+ if not ref.startswith("./"):+ return []+ target = REPO / ref[2:]+ if not target.is_file():+ return []+ try:+ doc = yaml.safe_load(target.read_text(encoding = "utf-8"))+ except yaml.YAMLError:+ return []+ if not isinstance(doc, dict):+ return []+ passed = {}+ on = doc.get(True) if True in doc else doc.get("on")+ call = on.get("workflow_call") if isinstance(on, dict) else None+ declared = call.get("inputs") if isinstance(call, dict) else None+ if isinstance(declared, dict):+ for name, spec in declared.items():+ if isinstance(spec, dict) and spec.get("default") is not None:+ passed[str(name)] = str(spec["default"])+ with_ = job.get("with")+ if isinstance(with_, dict):+ # Resolved against the CALLER's env and inputs, exactly as a composite's+ # forwarded `with:` is. Copying verbatim meant reusable workflow A handing+ # `path: ${{ inputs.path }}` to B gave B a self-referential value: the path and+ # the credential home both normalised away and the login plus cache was accepted+ # even though the outer caller supplied a concrete directory.+ passed.update({str(k): _expand(str(v), env or {}, inputs or {}) for k, v in with_.items()})+ out = []+ for _jid, inner in _jobs(doc):+ out.append((inner, _env_of(inner, doc), passed))+ return out+++def _units(+ job,+ doc,+ env = None,+ inputs = None,+ depth = 0,+):+ """The independent runners this job's work lands on, as (job, env, inputs).++ A job is one runner, so a login in it and a cache save in it share a filesystem and+ the pairing is meaningful. A job that delegates with `uses: ./.github/workflows/x.yml`+ is NOT one runner: every job inside that workflow gets its own, exactly as if they+ had been written out separately.++ Flattening all of them into the calling job pooled their paths, so a login in one+ inner job was reported against a cache saved by a different inner job that merely+ used the same pathname. Two jobs writing `hf-cache` write two different directories+ on two different machines, and a finding that says otherwise is describing something+ that cannot happen.++ The split recurses, because a reusable workflow may delegate in turn, and `depth`+ stops a workflow that (transitively) calls itself from expanding forever.+ """+ env = _env_of(job, doc) if env is None else env+ inputs = {} if inputs is None else inputs+ if depth > 8:+ return [(job, env, inputs)]+ inner = _reusable_jobs(job, env, inputs)+ if not inner:+ return [(job, env, inputs)]+ out = []+ for inner_job, inner_env, passed in inner:+ # The called workflow's OWN env, not the caller's. GitHub does not propagate a+ # calling workflow's `env:` into a reusable workflow -- only `with:` and+ # `secrets:` cross that boundary -- so merging them reported a caller-level+ # `HF_HOME: hf-cache` against a called job that saves an unrelated `hf-cache`+ # and writes its token to the default home instead. The inputs still travel,+ # because those are what the caller really passes.+ out.extend(_units(inner_job, doc, inner_env, passed, depth + 1))+ return out+++def _ref_candidates(uses: str):+ """Every source-tree path a `./...` action reference could name.++ A job that checks this repository out into a subdirectory writes+ `./unsloth/.github/actions/x`, which is the same action through a layout that only+ exists on the runner. Probing the reference as written found nothing, so the+ composite was never flattened: a job could persist its credential home and delegate+ the login to such a composite with nothing seeing it. `notebooks-ci.yml` and+ `version-compat-ci.yml` both use this form.+ """+ ref = uses.strip()+ if ref.startswith("./"):+ ref = ref[2:]+ ref = ref.rstrip("/")+ bases = [REPO / ref]+ parts = ref.split("/")+ if ".github" in parts[1:]:+ bases.append(REPO / "/".join(parts[parts.index(".github") :]))+ for base in bases:+ for cand in (base, base / "action.yml", base / "action.yaml"):+ yield cand+++def _flat_steps(+ job,+ inherited = None,+ inputs = None,+ stack = None,+):+ """(step, inherited env, caller inputs) for this job and every local composite it uses.++ A composite's steps execute INSIDE the calling job, and the invoking step's `env:`+ applies while they run, so that environment has to travel with them. Appending the+ inner step dictionaries alone discarded it: a composite invoked with+ `env: {HF_HOME: hf-cache}` whose inner step logs in showed no credential home at all,+ and the login was accepted.++ The caller's `with:` block travels too, because a composite may name its own cached+ directory through an input (`path: ${{ inputs.path }}`), which resolves to nothing+ without it.++ `stack` is the recursion path, NOT a set of everything already visited. A shared+ visited set suppressed every invocation after the first, and each invocation runs+ with its own environment: a login composite called once with `HF_HOME` outside the+ cache and once with it inside was only ever inspected in its safe form. Verified+ before fixing -- that job produced no offender at all. Cycle detection still needs+ the path, so an action that (transitively) uses itself is not expanded forever.+ """+ inherited = {} if inherited is None else inherited+ inputs = {} if inputs is None else inputs+ stack = () if stack is None else stack+ out = []+ # A job may delegate wholesale to a local reusable workflow instead of listing steps.++ for step in _steps(job):+ own = step.get("env")+ env = {+ **inherited,+ **({str(k): str(v) for k, v in own.items()} if isinstance(own, dict) else {}),+ }+ out.append((step, inherited, inputs))+ uses = str(step.get("uses") or "").strip().strip("'\"")+ if not uses.startswith("./"):+ continue+ for cand in _ref_candidates(uses):+ if not cand.is_file():+ continue+ if cand in stack:+ break # a cycle, not a sibling invocation+ try:+ doc = yaml.safe_load(cand.read_text(encoding = "utf-8"))+ except yaml.YAMLError:+ break+ if not isinstance(doc, dict):+ break+ runs = doc.get("runs")+ if isinstance(runs, dict) and isinstance(runs.get("steps"), list):+ with_ = step.get("with")+ passed = {}+ # A declared default is what Actions applies when the caller omits the+ # input, so a composite invoked bare still names its real path.+ declared = doc.get("inputs")+ if isinstance(declared, dict):+ for field, spec in declared.items():+ if isinstance(spec, dict) and spec.get("default") is not None:+ passed[str(field)] = str(spec["default"])+ if isinstance(with_, dict):+ for field, value in with_.items():+ # Resolved against the CALLER's env and inputs, so a forwarded+ # `${{ inputs.path }}` arrives as the value it stands for rather+ # than as the same expression one level down.+ passed[str(field)] = _expand(str(value), env, inputs)+ out.extend(+ _flat_steps(+ {"steps": runs["steps"]},+ env,+ passed,+ stack + (cand,),+ )+ )+ break+ return out+++def _local_action_steps(job):+ """The composite-provided steps only, for tests that assert flattening happened."""+ own = {id(s) for s in _steps(job)}+ return [step for step, _env, _in in _flat_steps(job) if id(step) not in own]+++def _persisted_with_env(job, doc):+ """(path, env) for every path this job persists, with the env of the DECLARING step.++ Actions resolves a `path: ${{ env.CACHE_DIR }}` against the environment of the step+ that performs the save, so expanding it with some other step's environment answers a+ different question. Carrying the pair keeps the two apart, and it also brings in+ persistence that happens inside a local composite, which the caller-only scan could+ not see at all: a composite saving the job's credential home while the workflow logs+ in was a combination neither half observed.+ """+ out = []+ for unit, job_env, unit_inputs in _units(job, doc):+ out.extend(_persisted_in_unit(unit, job_env, unit_inputs))+ return out+++def _persisted_in_unit(job, job_env, unit_inputs):+ """The paths one runner persists. See `_units` for why that boundary matters."""+ out = []+ # The job's own env seeds the walk. Without it a root-level call passing+ # `path: ${{ env.CACHE_DIR }}` resolved against inherited and step-level values only,+ # `_expand` produced an empty string, and the composite appeared to persist nothing.+ for step, inherited, inputs in _flat_steps(job, job_env, unit_inputs):+ uses = str(step.get("uses") or "").casefold()+ if not any(marker.casefold() in uses for marker in _PERSIST):+ continue+ with_ = step.get("with")+ if not isinstance(with_, dict) or with_.get("path") is None:+ continue+ own = step.get("env")+ env = {+ **job_env,+ **inherited,+ **({str(k): str(v) for k, v in own.items()} if isinstance(own, dict) else {}),+ }+ for line in str(with_["path"]).splitlines():+ line = line.strip()+ if line and not line.startswith("!"):+ out.append((_expand(line, env, inputs), step))+ return out+++def _login_offenders(doc, job):+ """Steps that log in while THEIR OWN credential home sits inside a persisted path.++ Evaluated per step rather than per job, because the job-wide version rejected a safe+ arrangement: with one step setting a cached `HF_HOME` and a later step setting a+ different, uncached `HF_HOME` and logging in, combining every home in the job with+ every login in the job flagged the second step even though its token cannot reach the+ cache. The effective environment of the step that actually runs the login is what+ decides, which is also the only thing the runtime cares about.++ A login can be an ACTION as well as a shell command, and skipping every step without+ a `run:` body missed that class entirely: `docker/login-action` writes registry+ credentials into `$DOCKER_CONFIG/config.json` with no shell for a pattern to match.+ An action only counts against the variables it really writes, per LOGIN_ACTIONS.+ """+ offenders = []+ # Per runner, and a login is only ever paired with what its OWN runner persists.+ for unit, unit_env, unit_inputs in _units(job, doc):+ offenders.extend(_login_offenders_in_unit(unit, unit_env, unit_inputs))+ return offenders+++def _login_offenders_in_unit(job, job_env, unit_inputs):+ persisted = [path for path, _s in _persisted_in_unit(job, job_env, unit_inputs)]+ if not persisted:+ return []+ offenders = []+ for step, inherited, inputs in _flat_steps(job, job_env, unit_inputs):+ body = str(step.get("run") or "")+ uses = str(step.get("uses") or "").strip().strip("'\"")+ action = uses.split("@")[0]+ # GitHub treats owner/repo case-insensitively, so `Docker/login-action` runs the+ # same credential-writing action as `docker/login-action`. A case-sensitive+ # lookup let a capital letter skip the step entirely, since it has no `run:` body.+ spec = LOGIN_ACTIONS.get(action.casefold())+ if spec is not None:+ with_ = step.get("with")+ needed = spec.get("condition")+ if needed and not (isinstance(with_, dict) and with_.get(needed) is not None):+ spec = None+ if not body and spec is None:+ continue+ own = step.get("env")+ env = {+ **job_env,+ **inherited,+ **({str(k): str(v) for k, v in own.items()} if isinstance(own, dict) else {}),+ }+ homes = {v: _expand(str(env[v]), env, inputs) for v in CREDENTIAL_HOMES if v in env}+ # The two Hugging Face variables are alternatives with a precedence, not two+ # places a login writes. `huggingface_hub` takes HF_TOKEN_PATH when it is set and+ # falls back to `$HF_HOME/token` only when it is not, so a job with a cached+ # HF_HOME and HF_TOKEN_PATH pointing outside it writes the token outside it. The+ # report named HF_HOME anyway, which is a false failure that also misdescribes+ # where the credential lives.+ if "HF_TOKEN_PATH" in homes:+ homes.pop("HF_HOME", None)+ if not homes:+ continue+ for var, home in sorted(homes.items()):+ hit = next(+ (p for p in persisted if _inside(home, p, CREDENTIAL_FILES.get(var, ()))),+ None,+ )+ if hit is None:+ continue+ if spec is not None and var in spec["vars"]:+ offenders.append(+ f"{step.get('name') or uses}: {var}={home} is inside cached "+ f"{hit!r}, and this step uses {action} ({spec['why']})"+ )+ break+ matched = next(+ (+ p+ for p in LOGIN_PATTERNS+ if body+ and re.search(p, body, re.IGNORECASE)+ and var in LOGIN_PATTERN_HOMES.get(p, (var,))+ ),+ None,+ )+ if matched is not None:+ offenders.append(+ f"{step.get('name') or uses or 'run'}: {var}={home} is inside "+ f"cached {hit!r}, and this step matches /{matched}/"+ )+ break+ return offenders+++def _raw_persisted(job, doc = None):+ """Expanded persisted paths, including those declared inside local composites."""+ return [path for path, _step in _persisted_with_env(job, doc or {})]++def _normalise(path: str) -> str:"""Strip expressions and separators so a path and an env value can be compared."""path = re.sub(r"\$\{\{[^}]*\}\}", "", path)path = path.replace("\\", "/").strip().strip("'\"")+ path = re.sub(r"^\$(HOME|\{HOME\})/", "~/", path)while path.startswith("./"):path = path[2:]return path.strip("/")-def _inside(inner: str, outer: str) -> bool:- """Is `inner` the same directory as `outer`, or below it?"""- inner, outer = _normalise(inner), _normalise(outer)+def _glob_regex(pattern: str):+ """A glob compiled with `/` respected: `**` crosses separators, `*` does not."""+ out = []+ i = 0+ pattern = pattern.replace("\\", "/")+ while i < len(pattern):+ ch = pattern[i]+ if pattern.startswith("**/", i):+ # Zero directories included. `hf-cache/**/token` matches+ # `hf-cache/token`, and translating `**` to `.*` before escaping the+ # following slash demanded a separator that need not be there, so a+ # pattern that does persist the token read as though it did not.+ out.append("(?:[^/]+/)*")+ i += 3+ continue+ if pattern.startswith("**", i):+ out.append(".*")+ i += 2+ continue+ if ch == "[":+ # A bracket expression, compiled rather than escaped. `_inside` already+ # counted `[` as making the path a glob, so escaping it here meant+ # `hf-cache/[t]oken` was treated as a glob that matches the literal text+ # `[t]oken` -- it matched nothing, and an upload that does include the token+ # was permitted.+ close = pattern.find("]", i + 1)+ if close == -1:+ out.append(re.escape(ch))+ i += 1+ continue+ body = pattern[i + 1 : close]+ negate = body.startswith("!") or body.startswith("^")+ if negate:+ body = body[1:]+ out.append("[" + ("^" if negate else "") + body.replace("\\", "\\\\") + "]")+ i = close + 1+ continue+ if ch == "*":+ out.append("[^/]*")+ elif ch == "?":+ out.append("[^/]")+ else:+ out.append(re.escape(ch))+ i += 1+ return re.compile("^" + "".join(out) + "$")+++def _glob_captures(+ pattern: str,+ home: str,+ files = None,+) -> bool:+ """Could this persistence pattern include the credential this home holds?++ Asked of the REAL path, not of a list of likely filenames. `path: hf-cache/**` takes+ the token with everything else; `path: hf-cache/*.bin` takes the weight files and+ cannot contain it. Dropping the wildcard segment treated the two alike.++ `files` are the names the credential takes beneath a directory-valued home. A home+ with none is itself the credential file, which is the only workable rule for+ AWS_SHARED_CREDENTIALS_FILE and friends: those take whatever basename the job gives+ them, so no list of filenames can anticipate them and the configured value is the+ only thing that can be tested.+ """+ home = _normalise(home).rstrip("/")+ if files is None:+ # The caller did not say which variable this is, so the filename is unknown and+ # any pattern reaching into the home could match it. Falling back to the old+ # containment keeps an unannotated call site conservative: forgetting the+ # argument must not turn a finding off, which an empty tuple would have done.+ outer = _normalise(_deglob(pattern)).strip("/")+ return bool(outer) and (home == outer or home.startswith(outer + "/"))+ rx = _glob_regex(_normalise(pattern))+ # The home itself, for a variable that names the credential FILE, and each known+ # filename beneath it for one that names a directory.+ candidates = [home] + [home + "/" + f for f in files]+ return any(rx.match(c) for c in candidates)+++def _deglob(path: str) -> str:+ """The fixed directory a glob pattern lives under.++ `hf-cache/**` and `hf-cache/*.bin` both persist things inside `hf-cache`, so for a+ containment question the fixed leading part is what matters. Anything from the first+ wildcard segment onward is dropped.+ """+ parts = []+ for segment in path.replace("\\", "/").split("/"):+ if any(ch in segment for ch in "*?["):+ break+ parts.append(segment)+ return "/".join(parts) if parts else path+++def _inside(+ inner: str,+ outer: str,+ files = None,+) -> bool:+ """Is `inner` the same directory as `outer`, or below it?++ A glob suffix is trimmed off `outer` first. `path: hf-cache/**` uploads everything+ beneath `hf-cache`, including a token written there, but compared literally+ `_inside("hf-cache", "hf-cache/**")` is false and the whole upload looked unrelated to+ the credential home it contains.+ """+ # Identical expressions first, before anything is stripped. With+ # `HF_HOME: ${{ matrix.path }}` and `path: ${{ matrix.path }}`, the two are the same+ # directory at run time whatever the matrix chooses -- and `_normalise` erased both+ # to the empty string, which `_inside` refuses, so a login beside that cache was+ # accepted. Two spellings of one unknown are still one unknown.+ if "${{" in inner and inner.strip() == outer.strip():+ return True+ if any(ch in outer for ch in "*?["):+ # Decided by matching the credential's own path against the pattern, which is+ # both stricter and more honest than widening the pattern to its fixed prefix.+ return _glob_captures(outer, inner, files)+ inner, outer = _normalise(inner), _normalise(_deglob(outer))+ inner, outer = inner.strip("/"), outer.strip("/")if not inner or not outer:return False- return inner == outer or inner.startswith(outer + "/")+ if inner == outer or inner.startswith(outer + "/"):+ return True+ # The persisted path may name the credential FILE outright rather than a directory+ # holding it. `path: hf-cache/token` is not the home and does not contain it, so a+ # containment test answered no while the upload carried the token itself. The+ # filenames are the same ones a glob is tested against.+ return any(outer == inner.rstrip("/") + "/" + f for f in (files or ()))+++def _default_home_hits(persisted: str, overridden: set) -> list:+ """Which default credential homes this persisted path reaches.++ Factored out so the rule can be exercised directly. It was previously inline, and+ the test that meant to check it asserted on the module's own source text -- which+ counted the assertion itself and passed whatever the rule did.+ """+ hits = []+ for default, creds in DEFAULT_CREDENTIAL_HOMES.items():+ # A default is only where the tool looks when nothing overrides it. A job+ # setting `CARGO_HOME: /tmp/cargo` writes credentials there, so persisting+ # `~/.cargo` holds none, and flagging it was a false failure.+ if any(v in overridden for v in DEFAULT_OWNERS.get(default, ())):+ continue+ # With the filenames that home holds, so persisting the credential FILE outright+ # counts as well as persisting the directory.+ if _inside(default, persisted, DEFAULT_HOME_FILES.get(default, ())):+ hits.append((default, creds))+ return hitsdef _offending_jobs():- """(label, var, path, home_value) for every job caching its own credential home."""+ """(label, var, path, home_value) for every job caching its own credential home.++ Resolved through `_units`, exactly as the login scan is. Reading the caller's own+ job and step environments only meant a job that delegates to a reusable workflow+ contributed nothing: the caller declares no credential home, and the called workflow+ read on its own cannot resolve `HF_HOME: ${{ inputs.path }}` because the value lives+ at the call site. So the parametrized guard below was never instantiated for that+ shape, and `_login_offenders` -- which does detect it -- was never asked. A check+ that works when called directly and is never called is not a check.+ """for path, doc in _docs():for jid, job in _jobs(doc):- env = _env_of(job, doc)- homes = {v: env[v] for v in CREDENTIAL_HOMES if v in env}- if not homes:- continue- for persisted, _step in _persisted_paths(job):- for var, home in homes.items():- if _inside(home, persisted):- yield f"{path.name}:{jid}", var, persisted, home+ for unit, unit_env, unit_inputs in _units(job, doc):+ # Through `_flat_steps`, so an env declared INSIDE a composite counts.+ # `_step_envs` sees the calling job's own steps only, and a composite+ # whose inner login step declares its own `HF_HOME` therefore produced+ # no label at all -- so the parametrized guard was never handed the job,+ # though `_login_offenders` detects it. Same shape as the reusable+ # workflow gap, one level further in.+ scopes = [unit_env]+ for step, inherited, _si in _flat_steps(unit, unit_env, unit_inputs):+ own = step.get("env")+ scopes.append(+ {+ **inherited,+ **(+ {str(k): str(v) for k, v in own.items()}+ if isinstance(own, dict)+ else {}+ ),+ }+ )+ for scope in scopes:+ env = {**unit_env, **scope}+ homes = {v: env[v] for v in CREDENTIAL_HOMES if v in env}+ if "HF_TOKEN_PATH" in homes:+ homes.pop("HF_HOME", None)+ if not homes:+ continue+ for persisted, _s in _persisted_in_unit(unit, unit_env, unit_inputs):+ for var, home in homes.items():+ if _inside(+ _expand(home, env, unit_inputs),+ persisted,+ CREDENTIAL_FILES.get(var, ()),+ ):+ yield f"{path.name}:{jid}", var, persisted, homedef test_the_scan_finds_the_jobs_it_claims_to():@@ -261,14 +983,11 @@ def test_a_job_that_caches_its_credential_home_performs_no_login(label, var, perdoc = yaml.safe_load(path.read_text(encoding = "utf-8"))job = dict(_jobs(doc)).get(jid) or {}- offenders = []- for step in _steps(job):- body = str(step.get("run") or "")- if not body:- continue- for pattern in LOGIN_PATTERNS:- if re.search(pattern, body, re.IGNORECASE):- offenders.append(f"{step.get('name') or step.get('uses')}: matched /{pattern}/")+ # Per step, with that step's own environment, and including the steps of any local+ # composite this job uses. See _login_offenders for why the job-wide version was both+ # too broad (a later step with an uncached home) and too narrow (a login inside an+ # action).+ offenders = _login_offenders(doc, job)assert not offenders, (f"{label} sets {var}={home}, which is inside the persisted path {persisted!r}, and a "@@ -283,3 +1002,1399 @@ def test_a_job_that_caches_its_credential_home_performs_no_login(label, var, perf"does today ({var} is set for the download path and no step authenticates), or point "f"{var} somewhere outside the persisted path.")+++def test_expanding_an_env_reference_finds_the_path_the_expression_names():+ """`path: ${{ env.HF_HOME }}` has to resolve, or the rule cannot see its own case.++ `_normalise` deletes expressions, so an unexpanded reference reduces to the empty+ string and `_inside` refuses an empty operand. A job caching exactly its own+ credential home, spelled through the variable instead of repeated literally, was+ therefore exempt from the rule written for it.+ """+ env = {"HF_HOME": "${{ github.workspace }}/hf-cache"}+ assert _expand("${{ env.HF_HOME }}", env) == "${{ github.workspace }}/hf-cache"+ assert _inside(_expand("${{ env.HF_HOME }}", env), "hf-cache") is True+ # An undefined name expands to empty, which is what Actions itself does.+ assert _expand("${{ env.NOT_SET }}", env) == ""+ # Nothing else is touched, so `github.workspace` is still normalised away later.+ assert _expand("hf-cache", env) == "hf-cache"+++def test_a_subdirectory_of_a_credential_home_is_not_a_finding():+ """Caching `~/.cache/huggingface/hub` is the RECOMMENDED arrangement, not a hazard.++ huggingface_hub keeps the token at `~/.cache/huggingface/token`, a SIBLING of `hub`,+ so a cache of the `hub` subdirectory holds the model blobs and no credential. An+ earlier version of the check compared containment in both directions and rejected+ it, which is the kind of false failure that gets a security guard switched off.+ """+ assert _inside("~/.cache/huggingface/hub", "~/.cache/huggingface") is True+ assert _inside("~/.cache/huggingface", "~/.cache/huggingface/hub") is False+ home = "~/.cache/huggingface"+ flagged = [p for p in ("~/.cache/huggingface/hub", "~/.cache", home) if _inside(home, p)]+ assert flagged == ["~/.cache", home], (+ "only a persisted path CONTAINING the credential home is a finding; the hub "+ f"subdirectory must not be, and the set flagged was {flagged}"+ )+++def test_a_credential_home_set_on_a_step_is_seen():+ """Step-level `env:` is where a credential home is most naturally written.++ Reading only workflow- and job-level `env:` missed it, so a job whose cached+ directory was named by the very step writing into it passed this guard.+ """+ job = {+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"run": "python probe.py", "env": {"HF_HOME": "hf-cache"}},+ ]+ }+ scopes = _step_envs(job)+ assert {"HF_HOME": "hf-cache"} in scopes, f"step env not collected: {scopes}"+ assert _env_of(job, {}) == {}, "the job itself sets nothing, which is the point"+ assert any(+ _inside(scope["HF_HOME"], persisted)+ for scope in scopes+ if "HF_HOME" in scope+ for persisted, _step in _persisted_paths(job)+ ), "the step-scoped credential home is inside the cached path and must be a finding"+++def test_no_job_persists_a_default_credential_home():+ """The spelling that needs no variable set, and so reads as harmless.++ A job can reach the same hazard by caching the location a tool uses when nothing+ overrides it. There is then no `HF_HOME` in the workflow to notice, which is why the+ check above cannot see it. unsloth-zoo's gemma4-audio-probe.yml cached+ `~/.cache/huggingface` until 2026-09-22 and was invisible to the sibling guard for+ precisely this reason; it now points HF_HOME at a workspace directory and caches that,+ the way the model caches in this repository do.++ Nothing here does it today. The test exists so the next model cache is written the+ same way.++ Only the credential home being INSIDE the persisted path counts. Comparing both+ directions was wrong and rejected the recommended arrangement: caching+ `~/.cache/huggingface/hub` persists the model blobs while the token stays a SIBLING+ at `~/.cache/huggingface/token`, outside the cache entirely.+ """+ offenders = []+ for path, doc in _docs():+ for jid, job in _jobs(doc):+ # Per resolved unit, because the override and the persistence must come from+ # the SAME runner. `_persisted_with_env` traverses into a called reusable+ # workflow while `overridden` was read from the caller, and caller env does+ # not cross that boundary -- so a caller-level `CARGO_HOME=/tmp/cargo`+ # exempted a callee that caches the real `~/.cargo`, which the caller's+ # variable does nothing to move.+ for unit, unit_env, unit_inputs in _units(job, doc):+ env = unit_env+ overridden = {v for v in CREDENTIAL_HOMES if v in env}+ for persisted, _step in _persisted_in_unit(unit, unit_env, unit_inputs):+ for _default, creds in _default_home_hits(persisted, overridden):+ offenders.append(+ f"{path.name}:{jid}: caches {persisted!r}, a default "+ f"credential home ({creds})"+ )+ assert not offenders, (+ "these jobs cache or upload a tool's default credential home:\n "+ + "\n ".join(sorted(set(offenders)))+ + "\n\n"+ "Anything that logs in writes a token there, and the directory is then saved to a "+ "cache every pull request can restore. Point the tool at a directory the workflow "+ "owns and cache that instead, as the smoke workflows here do with "+ "`HF_HOME: ${{ github.workspace }}/hf-cache` and `path: hf-cache`."+ )+++def test_model_cache_variables_are_not_treated_as_credential_homes():+ """HUGGINGFACE_HUB_CACHE and TRANSFORMERS_CACHE select a MODEL cache, not a token.++ Listing them rejected the arrangement this module recommends everywhere else: point a+ variable at a directory you own and cache that. Checked against the installed+ huggingface_hub rather than asserted from memory, because the whole claim is about+ what that library does with these names.+ """+ for var in ("HUGGINGFACE_HUB_CACHE", "TRANSFORMERS_CACHE"):+ assert var not in CREDENTIAL_HOMES, (+ f"{var} names a model cache, not a credential home. The token is read from "+ f"HF_TOKEN_PATH (default $HF_HOME/token), computed independently of it, so "+ f"caching a directory {var} points at persists blobs and no token."+ )+ assert "HF_TOKEN_PATH" in CREDENTIAL_HOMES, (+ "HF_TOKEN_PATH names the token file directly and overrides HF_HOME, so it is the "+ "variable that actually has to be tracked"+ )++ hub = pytest.importorskip("huggingface_hub.constants")+ home = str(getattr(hub, "HF_HOME", ""))+ token = str(getattr(hub, "HF_TOKEN_PATH", ""))+ cache = str(getattr(hub, "HUGGINGFACE_HUB_CACHE", ""))+ assert token.startswith(home) and token.endswith(+ "token"+ ), f"expected the token under HF_HOME; got HF_HOME={home!r} HF_TOKEN_PATH={token!r}"+ assert not _inside(token, cache), (+ f"the token is supposed to sit OUTSIDE the hub cache, which is the reason "+ f"HUGGINGFACE_HUB_CACHE is not a credential home; got {token!r} inside {cache!r}"+ )+++def test_a_login_is_judged_against_that_step_s_own_environment():+ """The job-wide version was both too broad and, for the safe case, simply wrong.++ Combining every credential home in a job with every login in the same job flagged a+ step that sets its own uncached `HF_HOME` and logs in there, even though its token+ cannot reach the cache. The effective environment of the step running the login is+ what decides, which is also all the runtime cares about.+ """+ safe = {+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"name": "warm the cache", "run": "python download.py", "env": {"HF_HOME": "hf-cache"}},+ {+ "name": "log in elsewhere",+ "run": "hf auth login --token x",+ "env": {"HF_HOME": "/tmp/scratch-home"},+ },+ ]+ }+ assert _login_offenders({}, safe) == [], (+ "the login step points HF_HOME at an uncached directory, so its token cannot "+ "enter the cache and it must not be a finding"+ )++ # And the same shape with the login step's own home inside the cache must fire.+ unsafe = {+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"name": "log in", "run": "hf auth login --token x", "env": {"HF_HOME": "hf-cache"}},+ ]+ }+ offenders = _login_offenders({}, unsafe)+ assert offenders, "a login whose own HF_HOME is inside the cached path must be a finding"+ assert "hf-cache" in offenders[0] and "log in" in offenders[0], offenders++ # A job-level home with a login anywhere in the job is still caught, which is the+ # original rule and must not have been lost in making the above per-step.+ job_level = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"name": "log in", "run": "huggingface-cli login"},+ ],+ }+ assert _login_offenders({}, job_level), (+ "a job-level credential home inside the cached path, with a login in any step, "+ "is the case this module was written for and must still fire"+ )+++def test_a_login_inside_a_local_composite_action_is_seen(tmp_path, monkeypatch):+ """A composite's run steps execute in the calling job, so its logins are the job's.++ Scanning only the workflow's own `run` bodies let a job persist its credential home,+ delegate the login to `uses: ./.github/actions/whatever`, and pass: the workflow+ contains no login, and the action is scanned separately where neither the caller's+ environment nor its persisted paths are visible. Neither half sees the combination.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "hf-login"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: hf login\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - shell: bash\n"+ ' run: hf auth login --token "$HF_TOKEN"\n'+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"uses": "./.github/actions/hf-login"},+ ],+ }+ assert _local_action_steps(job), "the composite's steps were not flattened into the job"+ offenders = _login_offenders({}, job)+ assert offenders, (+ "the login happens inside the composite, and it writes into the cached HF_HOME "+ "just the same, so it must be a finding"+ )+ assert "hf auth login" in offenders[0] or "login" in offenders[0], offenders+++def test_a_composite_invoked_with_a_credential_home_carries_that_env(tmp_path, monkeypatch):+ """The invoking step's `env:` applies while the composite runs, so it must travel.++ Appending the inner step dictionaries alone discarded it: a composite invoked with+ `env: {HF_HOME: hf-cache}` whose inner step logs in showed no credential home at all,+ neither job-level nor inner-step, and the login was accepted even though the job saves+ `hf-cache`.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "hf-login"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: hf login\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - shell: bash\n"+ ' run: hf auth login --token "$HF_TOKEN"\n'+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"uses": "./.github/actions/hf-login", "env": {"HF_HOME": "hf-cache"}},+ ]+ }+ offenders = _login_offenders({}, job)+ assert offenders, (+ "the credential home is set on the step that invokes the composite, and the "+ "composite's login writes into it, so this must be a finding"+ )+++def test_persistence_inside_a_local_composite_is_seen(tmp_path, monkeypatch):+ """A composite can hold the `actions/cache/save`, and the caller-only scan saw none.++ `_raw_persisted` examined the workflow's own steps and returned empty, so the login+ scan never ran at all. Scanning the composite separately does not help either,+ because that document has neither the caller's environment nor its login step, so+ neither half observed the combination.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "save-cache"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: save cache\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n"+ " path: hf-cache\n"+ " key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"name": "log in", "run": "hf auth login --token x"},+ {"uses": "./.github/actions/save-cache"},+ ],+ }+ paths = [p for p, _s in _persisted_with_env(job, {})]+ assert "hf-cache" in paths, f"the composite's cache save was not collected: {paths}"+ assert _login_offenders({}, job), (+ "the composite saves the job's credential home and the workflow logs in, which "+ "is the combination this module exists to refuse"+ )+++def test_a_cached_path_is_expanded_with_its_own_step_s_environment():+ """Actions resolves `path:` against the environment of the step doing the save.++ Expanding it with some other step's environment answers a different question: with+ `env: {CACHE_DIR: creds}` on the cache step and a login step setting a credential+ home under `creds`, the path resolved to empty against the login step's environment+ and the combination was missed.+ """+ job = {+ "steps": [+ {+ "name": "save",+ "uses": "actions/cache/save@v4",+ "with": {"path": "${{ env.CACHE_DIR }}", "key": "k"},+ "env": {"CACHE_DIR": "creds"},+ },+ {"name": "log in", "run": "hf auth login --token x", "env": {"HF_HOME": "creds/hf"}},+ ]+ }+ paths = [p for p, _s in _persisted_with_env(job, {})]+ assert paths == [+ "creds"+ ], f"the path had to resolve against the saving step's own CACHE_DIR; got {paths}"+ assert _login_offenders(+ {}, job+ ), "HF_HOME is creds/hf, inside the cached creds, and that step logs in"+++def test_every_invocation_of_a_composite_is_flattened(tmp_path, monkeypatch):+ """A shared visited set suppressed every invocation after the first.++ Each invocation runs with its own environment, so a login composite called once with+ `HF_HOME` outside the cache and once with it inside was only ever inspected in its+ safe form. Verified before fixing: that job produced no offender at all. Cycle+ detection needs the recursion PATH, not a set of everything already seen.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "hf-login"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: hf login\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - shell: bash\n"+ " run: hf auth login --token x\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "steps": [+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ {"uses": "./.github/actions/hf-login", "env": {"HF_HOME": "/tmp/outside"}},+ {"uses": "./.github/actions/hf-login", "env": {"HF_HOME": "hf-cache"}},+ ]+ }+ offenders = _login_offenders({}, job)+ assert offenders, (+ "the SECOND invocation points HF_HOME inside the cached path, and suppressing it "+ "as already-visited is what hid the dangerous one behind the safe one"+ )+ # Two invocations of the one-step composite, so both inner steps are present.+ assert len(_local_action_steps(job)) == 2, _local_action_steps(job)+++def test_a_composite_cached_path_given_by_input_is_resolved(tmp_path, monkeypatch):+ """A composite may name its cached directory through an input.++ `path: ${{ inputs.path }}` resolved to the empty string without the caller's `with:`+ block, and `_inside` refuses an empty operand, so the composite appeared to persist+ nothing and the login beside it was accepted.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "save-in"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: save in\n"+ "inputs:\n"+ " path:\n"+ " required: true\n"+ "runs:\n"+ " using: composite\n"+ " steps:\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n"+ " path: ${{ inputs.path }}\n"+ " key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"name": "log in", "run": "hf auth login --token x"},+ {"uses": "./.github/actions/save-in", "with": {"path": "hf-cache"}},+ ],+ }+ paths = [p for p, _s in _persisted_with_env(job, {})]+ assert paths == ["hf-cache"], f"the input-backed path did not resolve; got {paths}"+ assert _login_offenders(+ {}, job+ ), "the composite persists the job's credential home and the workflow logs in"+++def test_no_job_that_persists_anything_performs_a_login():+ """The whole invariant, swept over every job, independent of label discovery.++ The parametrised test above is instantiated from the credential-home scan, and that+ scan reads each job's DIRECT steps. So a composite whose inner login step declares+ its own `HF_HOME` produced no label, the parametrisation never covered that job, and+ `_login_offenders` -- which would have caught it -- was simply never called. Scanning+ the action on its own does not help either, because that document has neither the+ caller's persisted paths nor its environment.++ This sweep depends on nothing but the job list, so a gap in discovery cannot hide a+ finding again. It is the backstop; the parametrised test stays for its per-job+ reporting.+ """+ offenders = []+ for path, doc in _docs():+ for jid, job in _jobs(doc):+ for item in _login_offenders(doc, job):+ offenders.append(f"{path.name}:{jid}: {item}")+ assert not offenders, (+ "these steps log in while their own credential home sits inside a path the job "+ "persists:\n " + "\n ".join(sorted(offenders)) + "\n\n"+ "A login writes a real token into that directory, and the directory is then "+ "saved to a cache or uploaded. GitHub lets every pull request restore caches "+ "written on the default branch, so the token becomes readable by anyone who can "+ "open one. Read the token from the environment instead of logging in, or point "+ "the credential home outside the persisted path."+ )+++def test_a_login_performed_by_an_action_is_seen():+ """A login can be an action, with no shell body for a pattern to match.++ `docker/login-action` writes registry credentials into `$DOCKER_CONFIG/config.json`,+ so a job pointing DOCKER_CONFIG at a cached directory leaks exactly as a+ `docker login` command would. Skipping every step without a `run:` missed the class.+ """+ job = {+ "env": {"DOCKER_CONFIG": "docker-cache"},+ "steps": [+ {"uses": "docker/login-action@v3", "with": {"username": "u", "password": "p"}},+ {"uses": "actions/cache/save@v4", "with": {"path": "docker-cache", "key": "k"}},+ ],+ }+ offenders = _login_offenders({}, job)+ assert offenders, "an action-performed login into a cached credential home must fire"+ assert "docker/login-action" in offenders[0], offenders++ safe = {+ "env": {"DOCKER_CONFIG": "/tmp/docker"},+ "steps": [+ {"uses": "docker/login-action@v3"},+ {"uses": "actions/cache/save@v4", "with": {"path": "docker-cache", "key": "k"}},+ ],+ }+ assert _login_offenders({}, safe) == [], "the credential home is outside the cache"+++def test_a_login_action_only_counts_against_what_it_writes():+ """The pairing is the point, and getting it wrong is how this rule cries wolf.++ Keying only on the action name fired on eight live workflows where+ `actions/setup-node` sat in a job whose cached directory was named by HF_HOME, a+ variable setup-node has nothing to do with. And setup-node writes an .npmrc token+ only when `registry-url` is set; otherwise it installs a runtime and touches no+ credential at all.+ """+ unrelated = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"uses": "actions/setup-node@v4", "with": {"node-version": "20"}},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ }+ assert _login_offenders({}, unrelated) == [], (+ "setup-node does not write HF_HOME, so caching an HF_HOME directory beside it "+ "is not a finding"+ )++ no_registry = {+ "env": {"NPM_CONFIG_USERCONFIG": "npm-cache/.npmrc"},+ "steps": [+ {"uses": "actions/setup-node@v4", "with": {"node-version": "20"}},+ {"uses": "actions/cache/save@v4", "with": {"path": "npm-cache", "key": "k"}},+ ],+ }+ assert (+ _login_offenders({}, no_registry) == []+ ), "without `registry-url` setup-node writes no token"++ with_registry = {+ "env": {"NPM_CONFIG_USERCONFIG": "npm-cache/.npmrc"},+ "steps": [+ {+ "uses": "actions/setup-node@v4",+ "with": {"registry-url": "https://registry.npmjs.org"},+ },+ {"uses": "actions/cache/save@v4", "with": {"path": "npm-cache", "key": "k"}},+ ],+ }+ assert _login_offenders(+ {}, with_registry+ ), "with `registry-url` it writes an .npmrc token into the cached config path"+++def test_an_input_forwarded_between_composites_is_resolved(tmp_path, monkeypatch):+ """One composite handing `${{ inputs.path }}` to another kept the outer expression.++ The inner step then expanded it back to itself and `_normalise` erased it, so a+ wrapper receiving `path: hf-cache` could save that directory while the job logged+ into `HF_HOME=hf-cache` and the guard reported nothing.+ """+ import sys++ module = sys.modules[__name__]+ inner = tmp_path / ".github" / "actions" / "save-in"+ outer = tmp_path / ".github" / "actions" / "wrap"+ inner.mkdir(parents = True)+ outer.mkdir(parents = True)+ (inner / "action.yml").write_text(+ "name: save in\ninputs:\n path:\n required: true\nruns:\n"+ " using: composite\n steps:\n - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ (outer / "action.yml").write_text(+ "name: wrap\ninputs:\n path:\n required: true\nruns:\n"+ " using: composite\n steps:\n - uses: ./.github/actions/save-in\n"+ " with:\n path: ${{ inputs.path }}\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"name": "log in", "run": "hf auth login --token x"},+ {"uses": "./.github/actions/wrap", "with": {"path": "hf-cache"}},+ ],+ }+ paths = [p for p, _s in _persisted_with_env(job, {})]+ assert paths == ["hf-cache"], f"the forwarded input did not resolve; got {paths}"+ assert _login_offenders({}, job), "the nested composite saves the credential home"+++def test_a_composite_input_default_is_applied(tmp_path, monkeypatch):+ """Actions applies a declared default when the caller omits the `with:` entirely.++ A composite declaring `path` with default `hf-cache` and caching+ `${{ inputs.path }}` was invoked bare, the empty input map left the expression+ unresolved, `_normalise` erased it, and the composite looked as though it persisted+ nothing at all.+ """+ import sys++ module = sys.modules[__name__]+ action = tmp_path / ".github" / "actions" / "save-default"+ action.mkdir(parents = True)+ (action / "action.yml").write_text(+ "name: save default\ninputs:\n path:\n default: hf-cache\nruns:\n"+ " using: composite\n steps:\n - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"name": "log in", "run": "hf auth login --token x"},+ {"uses": "./.github/actions/save-default"},+ ],+ }+ paths = [p for p, _s in _persisted_with_env(job, {})]+ assert paths == ["hf-cache"], f"the declared default was not applied; got {paths}"+ assert _login_offenders(+ {}, job+ ), "the composite persists the credential home via its default, and the job logs in"+++def test_a_glob_path_still_contains_its_directory():+ """`path: hf-cache/**` uploads whatever is beneath hf-cache, token included.++ A RESTRICTIVE glob does not. `hf-cache/*.bin` uploads the weight files and nothing+ else, and the token is not one of them, so reporting a login against it was a false+ failure. This assertion originally required the opposite, which recorded the+ over-broad behaviour as if it were the intent; dropping the wildcard segment is+ right for a recursive pattern and wrong for a narrow one.+ """+ assert _deglob("hf-cache/**") == "hf-cache"+ assert _deglob("hf-cache/*.bin") == "hf-cache"+ assert _deglob("hf-cache") == "hf-cache"+ assert _inside("hf-cache", "hf-cache/**") is True+ hf = CREDENTIAL_FILES["HF_HOME"]+ assert _inside("hf-cache", "hf-cache/*.bin", hf) is False+ assert _inside("other", "hf-cache/**", hf) is False+ # A bare `*` matches any NAME, `token` among them, so it still counts.+ assert _inside("hf-cache", "hf-cache/*", hf) is True+ # And a narrow pattern that matches the file THAT home really holds counts too:+ # docker writes `config.json`, cargo writes `credentials.toml`.+ assert _inside("docker-cache", "docker-cache/*.json", CREDENTIAL_FILES["DOCKER_CONFIG"]) is True+ assert _inside("cargo-home", "cargo-home/*.toml", CREDENTIAL_FILES["CARGO_HOME"]) is True+ # A caller that does not say which variable it means gets the conservative answer,+ # because an unknown filename could be anything.+ assert _inside("hf-cache", "hf-cache/*.bin") is True+++def test_a_login_action_is_matched_case_insensitively():+ """GitHub treats owner/repo case-insensitively; a capital letter is not an escape."""+ job = {+ "env": {"DOCKER_CONFIG": "docker-cache"},+ "steps": [+ {"uses": "Docker/Login-Action@v3"},+ {"uses": "actions/cache/save@v4", "with": {"path": "docker-cache", "key": "k"}},+ ],+ }+ assert _login_offenders({}, job), (+ "`Docker/Login-Action` runs the same credential-writing action, and the step has "+ "no `run:` body, so a case-sensitive lookup skipped it entirely"+ )+++def test_a_cached_path_resolves_against_job_level_env():+ """The job's own env has to seed the walk, or a root-level call resolves to nothing."""+ job = {+ "env": {"CACHE_DIR": "hf-cache", "HF_HOME": "hf-cache"},+ "steps": [+ {"name": "log in", "run": "hf auth login --token x"},+ {"uses": "actions/cache/save@v4", "with": {"path": "${{ env.CACHE_DIR }}", "key": "k"}},+ ],+ }+ assert [p for p, _s in _persisted_with_env(job, {})] == ["hf-cache"]+ assert _login_offenders({}, job)+++def test_an_overridden_default_home_is_not_a_finding():+ """A default is only where a tool looks when nothing points it elsewhere.++ A job setting `CARGO_HOME: /tmp/cargo` writes credentials there, so persisting+ `~/.cargo` holds none of them. Flagging it anyway was a false failure on a correct+ configuration, and every variable in CREDENTIAL_HOMES had the same problem.+ """+ for default, owners in DEFAULT_OWNERS.items():+ for owner in owners:+ assert (+ owner in CREDENTIAL_HOMES+ ), f"{owner} overrides {default} but is not tracked as a credential home"+ assert DEFAULT_OWNERS["~/.cargo"] == ("CARGO_HOME",)+ # Two variables reach the Hugging Face default. HF_TOKEN_PATH moves the token and+ # `stored_tokens` on its own, so a job setting only that one leaves nothing of+ # interest in `~/.cache/huggingface`, and a single owner could not say so.+ assert DEFAULT_OWNERS["~/.cache/huggingface"] == ("HF_HOME", "HF_TOKEN_PATH")+++def test_a_reusable_workflow_job_is_flattened(tmp_path, monkeypatch):+ """A job may delegate wholesale to a local reusable workflow instead of listing steps.++ The caller then scanned as an empty job and the called workflow was scanned+ separately with no access to the caller's `with:` values, so a reusable job that sets+ `HF_HOME: ${{ inputs.path }}`, logs in and caches `${{ inputs.path }}` was accepted.+ The same split that hid composite logins, one level up.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "shared.yml").write_text(+ "name: shared\n"+ "on:\n workflow_call:\n inputs:\n path:\n type: string\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: ${{ inputs.path }}\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ caller = {"uses": "./.github/workflows/shared.yml", "with": {"path": "hf-cache"}}+ assert [p for p, _s in _persisted_with_env(caller, {})] == ["hf-cache"]+ assert _login_offenders(+ {}, caller+ ), "the reusable job logs in and caches the same input-named directory"+++def test_a_reusable_workflow_resolves_the_inputs_it_was_handed(tmp_path, monkeypatch):+ """A reusable workflow forwarding `${{ inputs.path }}` means the CALLER's value.++ Copying a call site's `with:` verbatim made the forwarded expression+ self-referential one level down: workflow A hands B `path: ${{ inputs.path }}`, B+ resolves it against its own empty inputs, and both the credential home and the cached+ path normalise to the empty string. The containment test then compares nothing with+ nothing, the login plus cache is accepted, and the concrete directory the outer+ caller actually supplied never enters the comparison. This is the same forwarding bug+ already fixed for composites, one layer up, and it is a bypass rather than a false+ failure.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "inner.yml").write_text(+ "name: inner\n"+ "on:\n workflow_call:\n inputs:\n path:\n type: string\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: ${{ inputs.path }}\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ (wf / "outer.yml").write_text(+ "name: outer\n"+ "on:\n workflow_call:\n inputs:\n path:\n type: string\n"+ "jobs:\n forward:\n uses: ./.github/workflows/inner.yml\n"+ " with:\n path: ${{ inputs.path }}\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ caller = {"uses": "./.github/workflows/outer.yml", "with": {"path": "hf-cache"}}+ assert [p for p, _s in _persisted_with_env(caller, {})] == [+ "hf-cache"+ ], "the outer caller's concrete directory has to survive two hops of forwarding"+ assert _login_offenders(+ {}, caller+ ), "the innermost job logs in and caches the directory the outermost caller named"+++def test_a_shell_login_only_counts_against_what_that_command_writes():+ """`docker login` writes $DOCKER_CONFIG. It does not write the Hugging Face token.++ Every login pattern was tested against every credential home in the job, so a job+ that legitimately caches `HF_HOME` and separately runs `docker login` -- with+ `DOCKER_CONFIG` nowhere near the cache -- was reported as leaking a Hugging Face+ token into the cache. The same false pairing applied to npm, cargo, aws and gcloud,+ and the report named a credential the command never touches, which is worse than+ silence: it sends the reader looking for a leak that is not there.+ """+ safe = {+ "env": {"HF_HOME": "hf-cache", "DOCKER_CONFIG": "/tmp/docker"},+ "steps": [+ {"run": "echo y | docker login -u u --password-stdin"},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ }+ assert _login_offenders({}, safe) == [], (+ "docker writes $DOCKER_CONFIG/config.json, which is outside the cached "+ f"directory: {_login_offenders({}, safe)}"+ )++ unsafe = dict(+ safe,+ steps = [+ {"run": "hf auth login --token x"},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ )+ assert _login_offenders(+ {}, unsafe+ ), "the Hugging Face login does write the cached HF_HOME, and still has to be caught"++ docker_cached = {+ "env": {"DOCKER_CONFIG": "docker-cache"},+ "steps": [+ {"run": "echo y | docker login -u u --password-stdin"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "docker-cache", "key": "k"},+ },+ ],+ }+ assert _login_offenders(+ {}, docker_cached+ ), "narrowing the pairing must not stop docker being caught against its own home"+++def test_a_hugging_face_login_is_not_judged_against_an_unrelated_home():+ """`hf auth login` writes a Hugging Face home. It does not write CARGO_HOME.++ Mapping only the non-Hugging-Face patterns left the "any home" fallback covering the+ Hugging Face ones, so they matched against every credential variable in the job. A+ job caching `CARGO_HOME` while logging into Hugging Face was reported as leaking its+ token into the Cargo cache -- the same false pairing the map was introduced to+ remove, still in force for the patterns it was written for.+ """+ safe = {+ "env": {"CARGO_HOME": "cargo-cache", "HF_HOME": "/tmp/hf"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "cargo-cache", "key": "k"},+ },+ ],+ }+ assert _login_offenders({}, safe) == [], (+ f"the token goes to /tmp/hf, nowhere near the cached Cargo home: "+ f"{_login_offenders({}, safe)}"+ )++ unsafe = {+ "env": {"CARGO_HOME": "cargo-cache", "HF_HOME": "cargo-cache/hf"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "cargo-cache", "key": "k"},+ },+ ],+ }+ assert _login_offenders(+ {}, unsafe+ ), "with HF_HOME actually inside the cached path this is still a finding"+++def test_two_jobs_of_a_reusable_workflow_are_not_one_runner(tmp_path, monkeypatch):+ """Each job runs on its own machine, so `hf-cache` in two jobs is two directories.++ Flattening every job of a called workflow into the calling job pooled their+ persisted paths, so a login in one job was reported against a cache saved by a+ different job that merely used the same pathname. That finding describes something+ that cannot happen, and the cure for a guard like that is usually an exemption+ entry -- which then hides the real case too.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "split.yml").write_text(+ "name: split\n"+ "on:\n workflow_call:\n"+ "jobs:\n"+ # logs in, persists nothing+ " login:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: hf-cache\n"+ " steps:\n - run: hf auth login --token x\n"+ # persists the same NAME, on a different runner, and never logs in+ " save:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: hf-cache\n key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ caller = {"uses": "./.github/workflows/split.yml"}+ assert _login_offenders({}, caller) == [], (+ f"the login and the save are on different runners: " f"{_login_offenders({}, caller)}"+ )++ # Both in ONE job is a real finding, so the split did not cost the check its teeth.+ (wf / "split.yml").write_text(+ "name: split\n"+ "on:\n workflow_call:\n"+ "jobs:\n"+ " both:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: hf-cache\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: hf-cache\n key: k\n"+ )+ assert _login_offenders(+ {}, caller+ ), "one job logging in and caching its own credential home is still caught"+++def test_a_chain_of_environment_references_is_resolved():+ """A variable's value may name another variable, and Actions resolves the chain.++ One substitution pass left the inner expression standing, `_normalise` erased it,+ and a job that cached its own credential home through two hops produced no offender+ at all. Spelling the same thing in two steps instead of one was a complete bypass.+ """+ env = {"CACHE_ROOT": "hf-cache", "HF_HOME": "${{ env.CACHE_ROOT }}"}+ assert _expand("${{ env.HF_HOME }}", env) == "hf-cache"++ job = {+ "env": {"CACHE_ROOT": "hf-cache", "HF_HOME": "${{ env.CACHE_ROOT }}"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "${{ env.HF_HOME }}", "key": "k"},+ },+ ],+ }+ assert _login_offenders({}, job), (+ "the cached path and the credential home are the same directory, reached "+ "through two references"+ )+++def test_a_reference_cycle_does_not_hang_the_expansion():+ """Two variables naming each other must terminate, not spin.++ The fixed point is bounded for this reason. A value still holding an expression+ after the last pass is treated exactly like an unknown variable, which is the+ existing behaviour rather than a new one.+ """+ env = {"A": "${{ env.B }}", "B": "${{ env.A }}"}+ out = _expand("${{ env.A }}", env)+ assert "${{" in out, f"an unresolvable cycle stays an expression, got {out!r}"+++def test_a_restrictive_glob_does_not_capture_a_token():+ """`hf-cache/*.bin` uploads weight files. The token is not one of them.++ Widening every glob to its containing directory was right for `**` and wrong here,+ and the difference is whether the pattern can match a credential filename at all.+ An unfamiliar name still counts as capturable, so the narrowing only ever accepts a+ pattern that demonstrably excludes every credential file this check knows about.+ """+ hf = CREDENTIAL_FILES["HF_HOME"]+ assert _glob_captures("hf-cache/**", "hf-cache", hf) is True+ assert _glob_captures("hf-cache/*", "hf-cache", hf) is True+ assert _glob_captures("hf-cache/*.bin", "hf-cache", hf) is False+ # docker writes config.json, so a `*.json` pattern does capture a credential.+ assert (+ _glob_captures("docker-cache/*.json", "docker-cache", CREDENTIAL_FILES["DOCKER_CONFIG"])+ is True+ )+ # cargo writes credentials.toml, which a canned filename list had omitted.+ assert _glob_captures("cargo-home/*.toml", "cargo-home", CREDENTIAL_FILES["CARGO_HOME"]) is True+ # A file-valued home is matched as the path it names, whatever the basename. No+ # list of likely filenames can cover these, which is why the real value is tested.+ assert _glob_captures("creds/*.ini", "creds/my-profile.ini", ()) is True+ assert _glob_captures("creds/*.ini", "elsewhere/my-profile.ini", ()) is False+ # A pattern reaching only into a SUBDIRECTORY cannot hold a token at the root.+ assert _glob_captures("hf-cache/models/**", "hf-cache", hf) is False++ safe = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/upload-artifact@v4",+ "with": {"path": "hf-cache/*.bin", "name": "w"},+ },+ ],+ }+ assert (+ _login_offenders({}, safe) == []+ ), f"the upload cannot contain the token: {_login_offenders({}, safe)}"+++def test_hf_token_path_overrides_the_home_when_both_are_set():+ """They are alternatives with a precedence, not two places a login writes.++ `huggingface_hub` uses HF_TOKEN_PATH when it is set and `$HF_HOME/token` only when+ it is not, so a cached HF_HOME with HF_TOKEN_PATH pointing outside it holds no+ token. Matching every Hugging Face pattern against both variables reported that+ arrangement and named the wrong file while doing it.+ """+ safe = {+ "env": {"HF_HOME": "hf-cache", "HF_TOKEN_PATH": "/tmp/token"},+ "steps": [+ {"run": "hf auth login --token x"},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ }+ assert (+ _login_offenders({}, safe) == []+ ), f"the token is written to /tmp/token: {_login_offenders({}, safe)}"++ unsafe = {+ "env": {"HF_HOME": "/tmp/hf", "HF_TOKEN_PATH": "hf-cache/token"},+ "steps": [+ {"run": "hf auth login --token x"},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ }+ assert _login_offenders(+ {}, unsafe+ ), "HF_TOKEN_PATH inside the cache is the finding, and it is the variable that decides"+++def test_a_reusable_workflow_does_not_inherit_the_callers_env(tmp_path, monkeypatch):+ """`env:` does not cross the reusable-workflow boundary. `with:` does.++ Merging the caller's environment into every inner job meant a caller-level+ `HF_HOME: hf-cache` was attributed to a called workflow that saves an unrelated+ `hf-cache` and writes its token to the default home instead.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "inner.yml").write_text(+ "name: inner\n"+ "on:\n workflow_call:\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: hf-cache\n key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ caller = {"env": {"HF_HOME": "hf-cache"}, "uses": "./.github/workflows/inner.yml"}+ assert _login_offenders({}, caller) == [], (+ f"the caller's HF_HOME never reaches the called workflow: "+ f"{_login_offenders({}, caller)}"+ )++ # Passed as an INPUT, it does reach it, and that is still a finding.+ (wf / "inner.yml").write_text(+ "name: inner\n"+ "on:\n workflow_call:\n inputs:\n home:\n type: string\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: ${{ inputs.home }}\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: hf-cache\n key: k\n"+ )+ passed = {+ "uses": "./.github/workflows/inner.yml",+ "with": {"home": "hf-cache"},+ }+ assert _login_offenders({}, passed), "an input does cross the boundary"+++def test_the_discovery_scan_reaches_a_reusable_workflow_unit(tmp_path, monkeypatch):+ """The scan that DRIVES the parametrized guard has to resolve what the guard does.++ `_login_offenders` detects a called workflow that sets `HF_HOME` from an input,+ logs in and caches that input. The discovery generator read only the caller's own+ job and step environments, so it yielded nothing for that shape: the caller declares+ no credential home, and the called workflow read alone cannot resolve the input+ because its value lives at the call site. The parametrized case was therefore never+ created, and a check that is never called is not a check.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "inner.yml").write_text(+ "name: inner\n"+ "on:\n workflow_call:\n inputs:\n path:\n type: string\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " env:\n HF_HOME: ${{ inputs.path }}\n"+ " steps:\n - run: hf auth login --token x\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ (wf / "caller.yml").write_text(+ "name: caller\n"+ "on:\n push:\n"+ "jobs:\n go:\n uses: ./.github/workflows/inner.yml\n"+ " with:\n path: hf-cache\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)+ monkeypatch.setattr(module, "WORKFLOWS", wf)+ monkeypatch.setattr(module, "ACTIONS", tmp_path / ".github" / "actions")++ found = [f for f in _offending_jobs() if "caller.yml" in str(f[0])]+ assert found, (+ "the discovery scan has to reach the delegating job, or the guard below is "+ "never instantiated for it"+ )+++def test_a_restrictive_glob_is_matched_against_the_real_credential_path():+ """The filename comes from the home being tested, not from a canned list.++ A global list of likely filenames omitted `credentials.toml`, which+ `CREDENTIAL_HOMES` already documents for CARGO_HOME, so `cargo-home/*.toml` was+ accepted while persisting exactly the file cargo writes. And a file-valued home such+ as AWS_SHARED_CREDENTIALS_FILE takes whatever basename the job chooses, which no+ list can anticipate -- the configured value is the only thing that can be tested.+ """+ cargo = CREDENTIAL_FILES["CARGO_HOME"]+ assert _inside("cargo-home", "cargo-home/*.toml", cargo) is True++ leaking = {+ "env": {"CARGO_HOME": "cargo-home"},+ "steps": [+ {"run": "cargo login $TOKEN"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "cargo-home/*.toml", "key": "k"},+ },+ ],+ }+ assert _login_offenders(+ {}, leaking+ ), "cargo writes cargo-home/credentials.toml, which this pattern persists"++ named = {+ "env": {"AWS_SHARED_CREDENTIALS_FILE": "creds/my-profile.ini"},+ "steps": [+ {"run": "aws configure set aws_access_key_id x"},+ {+ "uses": "actions/upload-artifact@v4",+ "with": {"path": "creds/*.ini", "name": "c"},+ },+ ],+ }+ assert _login_offenders(+ {}, named+ ), "the configured path matches the pattern, whatever its basename"+++def test_hf_token_path_alone_moves_the_token_out_of_the_default_home():+ """Two variables reach the Hugging Face default, and either one relocates the token.++ A job setting only HF_TOKEN_PATH writes the token and `stored_tokens` beside it, so+ `~/.cache/huggingface` holds none and persisting it is safe. Tracking a single owner+ per default could not say that, and the default-home rule reported it anyway.+ """+ assert DEFAULT_OWNERS["~/.cache/huggingface"] == ("HF_HOME", "HF_TOKEN_PATH")+ assert DEFAULT_OWNERS["~/.huggingface"] == ("HF_HOME", "HF_TOKEN_PATH")+ # Every named owner is a variable this module actually tracks.+ for default, owners in DEFAULT_OWNERS.items():+ for owner in owners:+ assert owner in CREDENTIAL_HOMES, f"{owner} for {default}"+++def test_a_globstar_matches_zero_directories():+ """`hf-cache/**/token` includes `hf-cache/token`. GitHub's globstar may match none.++ Translating `**` to `.*` and then escaping the slash after it demanded a separator+ that need not be there, so a pattern which really does persist the token read as+ though it did not, and a job could log in and upload it with neither guard firing.+ """+ hf = CREDENTIAL_FILES["HF_HOME"]+ assert _inside("hf-cache", "hf-cache/**/token", hf) is True+ assert _inside("hf-cache", "hf-cache/**/*", hf) is True+ assert _inside("hf-cache", "hf-cache/**", hf) is True+ # Depth beyond zero still matches.+ assert _glob_captures("hf-cache/**/token", "hf-cache", hf) is True+ # And the narrowing is not lost: a restrictive tail still excludes the token.+ assert _inside("hf-cache", "hf-cache/**/*.bin", hf) is False++ cargo = CREDENTIAL_FILES["CARGO_HOME"]+ leaking = {+ "env": {"CARGO_HOME": "cargo-home"},+ "steps": [+ {"run": "cargo login $TOKEN"},+ {+ "uses": "actions/upload-artifact@v4",+ "with": {"path": "cargo-home/**/credentials.toml", "name": "c"},+ },+ ],+ }+ assert _inside("cargo-home", "cargo-home/**/credentials.toml", cargo) is True+ assert _login_offenders(+ {}, leaking+ ), "the upload includes cargo-home/credentials.toml at depth zero"+++def test_the_discovery_scan_sees_an_env_declared_inside_a_composite(tmp_path, monkeypatch):+ """A credential home set by a composite's own step has to activate the check.++ The discovery generator read the calling job's direct step environments, so a+ composite whose inner login step declares `HF_HOME` produced no label and the+ parametrized guard was never handed the job -- though `_login_offenders` detects it.+ The same shape as the reusable-workflow gap, one level further in.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ act = tmp_path / ".github" / "actions" / "inner-login"+ wf.mkdir(parents = True)+ act.mkdir(parents = True)+ (act / "action.yml").write_text(+ "name: inner login\n"+ "runs:\n using: composite\n steps:\n"+ " - run: hf auth login --token x\n"+ " shell: bash\n"+ " env:\n HF_HOME: hf-cache\n"+ )+ (wf / "caller.yml").write_text(+ "name: caller\n"+ "on:\n push:\n"+ "jobs:\n go:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: ./.github/actions/inner-login\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: hf-cache\n key: k\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)+ monkeypatch.setattr(module, "WORKFLOWS", wf)+ monkeypatch.setattr(module, "ACTIONS", tmp_path / ".github" / "actions")++ found = [f for f in _offending_jobs() if "caller.yml" in str(f[0])]+ assert found, (+ "the env is declared inside the composite, and the scan has to reach it or the "+ "guard is never instantiated for this job"+ )+++def test_a_character_class_is_compiled_not_escaped():+ """`hf-cache/[t]oken` includes `hf-cache/token`.++ `_inside` already counted `[` as making the path a glob, and the compiler then+ escaped it as a literal bracket, so the pattern matched nothing at all and an upload+ that does carry the token was permitted.+ """+ hf = CREDENTIAL_FILES["HF_HOME"]+ assert _inside("hf-cache", "hf-cache/[t]oken", hf) is True+ assert _inside("hf-cache", "hf-cache/[a-z]oken", hf) is True+ # A negated class that excludes the token really does exclude it.+ assert _inside("hf-cache", "hf-cache/[!t]oken", hf) is False++ leaking = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/upload-artifact@v4",+ "with": {"path": "hf-cache/[t]oken", "name": "a"},+ },+ ],+ }+ assert _login_offenders({}, leaking), "the upload pattern includes the token"+++def test_a_persisted_path_that_names_the_credential_file_is_caught():+ """A job may persist the credential itself rather than the directory holding it.++ `path: hf-cache/token` is not the home and does not contain it, so a containment+ test answered no while the upload carried the token outright. The filenames tested+ are the ones a glob is already checked against.+ """+ hf = CREDENTIAL_FILES["HF_HOME"]+ assert _inside("hf-cache", "hf-cache/token", hf) is True+ assert _inside("hf-cache", "hf-cache/stored_tokens", hf) is True+ assert _inside("hf-cache", "hf-cache/weights.bin", hf) is False++ leaking = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/upload-artifact@v4",+ "with": {"path": "hf-cache/token", "name": "a"},+ },+ ],+ }+ assert _login_offenders({}, leaking), "the token itself is the uploaded path"+++def test_a_default_home_override_must_come_from_the_same_runner(tmp_path, monkeypatch):+ """Caller `env:` does not reach a called workflow, so it overrides nothing there.++ A caller-level `CARGO_HOME=/tmp/cargo` was read as exempting a called job that+ caches the real `~/.cargo`, because the persistence traversal crossed the boundary+ while the override was still read from the caller. The variable moves nothing in the+ callee.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ wf.mkdir(parents = True)+ (wf / "inner.yml").write_text(+ "name: inner\n"+ "on:\n workflow_call:\n inputs:\n path:\n type: string\n"+ "jobs:\n build:\n runs-on: ubuntu-latest\n"+ " steps:\n"+ " - uses: actions/cache/save@v4\n"+ " with:\n path: ${{ inputs.path }}\n key: k\n"+ )+ (wf / "caller.yml").write_text(+ "name: caller\n"+ "on:\n push:\n"+ "jobs:\n go:\n"+ " env:\n CARGO_HOME: /tmp/cargo\n"+ " uses: ./.github/workflows/inner.yml\n"+ " with:\n path: ~/.cargo\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)+ monkeypatch.setattr(module, "WORKFLOWS", wf)+ monkeypatch.setattr(module, "ACTIONS", tmp_path / ".github" / "actions")++ units = _units(+ {+ "uses": "./.github/workflows/inner.yml",+ "with": {"path": "~/.cargo"},+ "env": {"CARGO_HOME": "/tmp/cargo"},+ },+ {},+ )+ assert units, "the delegation resolves to at least one unit"+ for _unit, unit_env, _inputs in units:+ assert "CARGO_HOME" not in unit_env, (+ "the caller's variable must not appear in the called job's environment, or "+ "it will be read as overriding a default it cannot move"+ )+++def test_a_composite_used_from_a_checkout_subdirectory_is_flattened(tmp_path, monkeypatch):+ """`./unsloth/.github/actions/x` names the same composite, one layout later.++ Probing the reference as written found nothing in the source tree, so the steps were+ never flattened and a job could persist its credential home while delegating the+ login to such a composite with nothing seeing it.+ """+ import sys++ module = sys.modules[__name__]+ wf = tmp_path / ".github" / "workflows"+ act = tmp_path / ".github" / "actions" / "hidden-login"+ wf.mkdir(parents = True)+ act.mkdir(parents = True)+ (act / "action.yml").write_text(+ "name: hidden login\n"+ "runs:\n using: composite\n steps:\n"+ " - run: hf auth login --token x\n shell: bash\n"+ )+ monkeypatch.setattr(module, "REPO", tmp_path)++ job = {+ "env": {"HF_HOME": "hf-cache"},+ "steps": [+ {"uses": "./unsloth/.github/actions/hidden-login"},+ {"uses": "actions/cache/save@v4", "with": {"path": "hf-cache", "key": "k"}},+ ],+ }+ assert _login_offenders(+ {}, job+ ), "the prefixed reference names the same composite, which logs in"+++def test_a_default_credential_file_persisted_exactly_is_caught():+ """`path: ~/.cargo/credentials.toml` is the credential, not a directory holding it.++ The configured-home branch was taught to match `<home>/<file>`; defaults had no+ variable to take filenames from, so persisting the exact default file asked only+ whether the default DIRECTORY was inside the persisted FILE, which is never true.+ """+ assert DEFAULT_HOME_FILES["~/.cargo"] == ("credentials", "credentials.toml")+ assert _inside("~/.cargo", "~/.cargo/credentials.toml", DEFAULT_HOME_FILES["~/.cargo"]) is True+ assert _inside("~/.docker", "~/.docker/config.json", DEFAULT_HOME_FILES["~/.docker"]) is True+ assert (+ _inside(+ "~/.cache/huggingface",+ "~/.cache/huggingface/token",+ DEFAULT_HOME_FILES["~/.cache/huggingface"],+ )+ is True+ )+ # Something else under the same home is still not a credential.+ assert _inside("~/.cargo", "~/.cargo/registry", DEFAULT_HOME_FILES["~/.cargo"]) is False+ # The filenames are load-bearing: without them the same question answers no, which+ # is exactly what the default-home rule was asking before they were supplied.+ assert _inside("~/.cargo", "~/.cargo/credentials.toml") is False+ # Every default this module reports has its filenames recorded.+ for default in DEFAULT_CREDENTIAL_HOMES:+ assert default in DEFAULT_HOME_FILES, default+ # And the rule really consults them. Asserted by calling it, not by reading this+ # file's own source -- the previous version counted its own assertion text and+ # passed however the rule behaved.+ assert _default_home_hits(+ "~/.cargo/credentials.toml", set()+ ), "persisting the exact default credential file has to be a finding"+ assert _default_home_hits("~/.docker/config.json", set())+ assert not _default_home_hits("~/.cargo/registry", set())+ # An override still exempts it, so the narrowing from earlier rounds is intact.+ assert not _default_home_hits("~/.cargo/credentials.toml", {"CARGO_HOME"})+++def test_two_identical_unresolved_expressions_are_the_same_directory():+ """`HF_HOME: ${{ matrix.path }}` and `path: ${{ matrix.path }}` are one directory.++ Whatever the matrix chooses, the cache and the credential home are the same place.+ Stripping expressions before comparing reduced both to the empty string, which+ `_inside` refuses, so a login beside that cache was accepted. Two spellings of one+ unknown are still one unknown.+ """+ assert _inside("${{ matrix.path }}", "${{ matrix.path }}") is True+ # Two DIFFERENT unknowns stay unknown rather than being assumed equal.+ assert _inside("${{ matrix.path }}", "${{ matrix.other }}") is False++ job = {+ "env": {"HF_HOME": "${{ matrix.path }}"},+ "steps": [+ {"run": "hf auth login --token x"},+ {+ "uses": "actions/cache/save@v4",+ "with": {"path": "${{ matrix.path }}", "key": "k"},+ },+ ],+ }+ assert _login_offenders({}, job), "the cached path is the credential home, by construction"