Poison-resistant CI cache
`cache_key(job, lockfile_hash, env, untrusted)` builds a cache key and decides
whether the cache may be restored. It returns `CachePlan(key, restore_keys)`;
the plan exposes a `can_restore` property.
`env` holds environment variables that affect the build.
Rules:
- `job` is a non-empty string matching `[a-z0-9][a-z0-9._-]*`;
- `lockfile_hash` is exactly 64 characters `0-9a-f`; empty or anything else —
`ValueError`;
- `env` is a dict of non-empty string keys and string values;
- `untrusted` is strictly a `bool`;
- secret variables are keys whose uppercase name contains `TOKEN`, `SECRET`,
`PASSWORD`, `CREDENTIAL`, `API_KEY`, `ACCESS_KEY`, `SSH_KEY` or `GPG_KEY`;
- secret values never enter the key: rotating a secret does not change the key;
- key: `v2-<job>-<scope>-<env_digest>-<lockfile_hash>`;
- `scope`: `untrusted` when `untrusted=True`; otherwise `secret` when `env`
contains a secret; otherwise `trusted`;
- `env_digest` is `sha256` of the canonical JSON list of sorted non-secret
`[key, value]` pairs, first 12 hex characters; the insertion order of `env`
does not matter;
- `restore_keys` is `(f"v2-<job>-trusted-<env_digest>-",)` only for `trusted`;
for `untrusted` and `secret` it is an empty tuple;
- `can_restore` is `True` when `restore_keys` is not empty;
- the same arguments always produce the same result.
The point: an untrusted PR must neither read nor poison the trusted branch
cache, and a job with secrets does not restore a cache built without them.
Write tests: stable key, lockfile change, public env change, env key order, a
secret in `env`, secret rotation, an `untrusted` PR, the restore-key prefix, an
empty and invalid hash, and invalid inputs.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
What can an untrusted PR do to a shared cache? Which inputs must change the key, and which must only forbid restore?