Skip to content

Commit 31369f5

Browse files
zackeesclaude
andauthored
feat(ci-lint): per-job permission grants, sanctioned cache-action wrapper, plan-driven cache saves, GEN-004 (#22)
* feat(ci-lint): per-job permission grants, sanctioned cache-action wrapper, plan-driven cache saves, GEN-004 Round-4B-ci refinements to the fleet checker: - SEC-002: top-level `permissions:` is capped at contents:read + actions:read (both free on any job too, closing the gap that forced template-python-rust-cmd#19's actions:read exceptions). Any wider per-job grant must list that job id in the new `[allow].permissions` table; id-token:write still additionally requires environment:pypi on the `publish` job. Reusable (workflow_call) files are covered for free since the check already iterates each file's own jobs. - CACHE-001/002: `actions/cache` (and /save, /restore) may now appear only inside the one sanctioned wrapper directory `[allow].cache-actions.only-in` (default `.github/actions/cache`, still SHA-pinned per SEC-004). Inside that wrapper, a literal `key:` is CACHE-002 even without a volatile token -- it must be a step-output or `inputs.*` expression from `ci_lint cache key`. - Plan-driven saves: `[allow].setup-soldr.require`/new `[allow].setup-uv.require` values may be the special string "plan", meaning the actual input must be an expression derived from the precheck plan (`needs.precheck.outputs.*` or an `inputs.*` passthrough), not a literal. New static CACHE-003 half: astral-sh/setup-uv's save-cache input missing or a literal "true" fires it (both save unconditionally, matching the live CACHE-003 base-on-PR problem). `ci_lint plan --github-output` / `precheck --github-output` now also write `cache_save` ("true"/"false" = cache_mode == "write") so a writer step can bind straight to it. - GEN-004 (previously policy-only): when the repo has Python sources, the `fast` job must invoke `ruff check`, `ruff format --check`, and `pylint` -- directly or via a tracked `ci/*.py` script it calls one level deep; standalone Black/isort is GEN-004 too. Unresolvable indirection (missing or unparsable script) is needs_review, never a silent pass. Every rule has RED + GREEN fixtures; docs/ci-toml.md and examples/rust-pypi-app/ci.toml updated; `ci_lint selftest` passes with and without PyYAML (246 tests; 37 skipped without PyYAML/yq). Co-Authored-By: Claude <[email protected]> * docs(example): actions:write grant for precheck (PR-delta trim) and cache-maint (template job ids) --------- Co-authored-by: Claude <[email protected]>
1 parent 551d909 commit 31369f5

46 files changed

Lines changed: 2103 additions & 92 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ This repository defines fleet CI policy and the planned checker. Read the policy
1010
4. [README.md](README.md) is the public summary and links to the source issues.
1111
5. [proposal.md](proposal.md) is the consolidated CI normalization proposal, repository evidence inventory, fbuild mapping, and implementation acceptance plan. Its proposed release-cycle and event-selection rules supersede earlier design examples; enforcement is not implemented.
1212
6. `docs/case-studies/` holds evidence-first writeups of a specific repository incident or investigation: [clud-ci-cost.md](docs/case-studies/clud-ci-cost.md), [soldr-ci-cost.md](docs/case-studies/soldr-ci-cost.md), [zccache-ci-cost.md](docs/case-studies/zccache-ci-cost.md), [fbuild-ci-cost.md](docs/case-studies/fbuild-ci-cost.md). A case study is not policy: it becomes binding only once its candidate rules are reviewed and written into `policy-general.md` or `policy-rust.md`. Candidate rule IDs across all case studies so far: `RUST-005`–`RUST-007`, `GEN-005`–`GEN-008`; keep new candidates numbered past these to avoid collisions.
13-
7. [`ci_lint/`](ci_lint/) is the standard-library-only Python package implementing the checker: `ci_lint.schema` loads and strictly validates `ci.toml` schema 3, `ci_lint.precheck` runs the static rule groups (`python3 -m ci_lint precheck`, `--local` skips GitHub-API-dependent checks explicitly, `--live` covers them for real), and `ci_lint.plan` computes a run's flow/tag selection (`python3 -m ci_lint plan`). Round-2A added the runtime commands that need a real build/artifact/venv: `ci_lint.runtime.units` (`python3 -m ci_lint units`), `ci_lint.runtime.tests_size` (`python3 -m ci_lint tests size`), `ci_lint.runtime.wheel` (`python3 -m ci_lint wheel check|installed`), `ci_lint.runtime.gate` (`python3 -m ci_lint gate`, the `CI OK` aggregator), and `ci_lint.selftest` (`python3 -m ci_lint selftest`, agents must be able to run this directly per zackees/zccache#1760). Round-4A added the cache runtime, `ci_lint.cache.*` (`python3 -m ci_lint cache key|save-ok|audit|trim|janitor|heal|preprune|delta`): key building, the do-not-save table (`save-ok`, `CACHE-008`), a live read-only audit (`CACHE-001/003/005/006/008/009` + budget), live deletes (`trim`/`janitor`/`heal`/`preprune`), and PR delta packing (`delta manifest|pack|apply`, pure filesystem). `ci_lint.audit` (the fleet-inventory audit, unrelated to `ci_lint cache audit`) is still a stub pending a later round. [docs/ci-toml.md](docs/ci-toml.md) is the schema-3 field-by-field reference and rule catalog. [`examples/rust-pypi-app/ci.toml`](examples/rust-pypi-app/ci.toml) is the canonical example, copied verbatim from issue #6's draft.
13+
7. [`ci_lint/`](ci_lint/) is the standard-library-only Python package implementing the checker: `ci_lint.schema` loads and strictly validates `ci.toml` schema 3, `ci_lint.precheck` runs the static rule groups (`python3 -m ci_lint precheck`, `--local` skips GitHub-API-dependent checks explicitly, `--live` covers them for real), and `ci_lint.plan` computes a run's flow/tag selection (`python3 -m ci_lint plan`). Round-2A added the runtime commands that need a real build/artifact/venv: `ci_lint.runtime.units` (`python3 -m ci_lint units`), `ci_lint.runtime.tests_size` (`python3 -m ci_lint tests size`), `ci_lint.runtime.wheel` (`python3 -m ci_lint wheel check|installed`), `ci_lint.runtime.gate` (`python3 -m ci_lint gate`, the `CI OK` aggregator), and `ci_lint.selftest` (`python3 -m ci_lint selftest`, agents must be able to run this directly per zackees/zccache#1760). Round-4A added the cache runtime, `ci_lint.cache.*` (`python3 -m ci_lint cache key|save-ok|audit|trim|janitor|heal|preprune|delta`): key building, the do-not-save table (`save-ok`, `CACHE-008`), a live read-only audit (`CACHE-001/003/005/006/008/009` + budget), live deletes (`trim`/`janitor`/`heal`/`preprune`), and PR delta packing (`delta manifest|pack|apply`, pure filesystem). `ci_lint.audit` (the fleet-inventory audit, unrelated to `ci_lint cache audit`) is still a stub pending a later round. Round-4B added per-job permission grants (`[allow].permissions`, `SEC-002` refinement), the sanctioned `actions/cache*` wrapper (`[allow].cache-actions`, `CACHE-001`/`CACHE-002` refinement), plan-driven cache saves (`[allow].setup-soldr.require`/`[allow].setup-uv.require` = `"plan"`, and the planner's `cache_save` `--github-output` key), and the static `GEN-004` check (Ruff + Pylint in the `fast` job, no standalone Black/isort). [docs/ci-toml.md](docs/ci-toml.md) is the schema-3 field-by-field reference and rule catalog. [`examples/rust-pypi-app/ci.toml`](examples/rust-pypi-app/ci.toml) is the canonical example, copied verbatim from issue #6's draft.
1414

1515
## Working rules
1616

‎ci_lint/cli.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,12 @@ def _plan_github_output_lines(plan: Plan, reuse_result: ReuseResult | None) -> l
145145
platform_lanes_json = json.dumps([pl.to_json_dict() for pl in plan.platform_lanes], separators=(",", ":"))
146146
fast_suites_json = json.dumps(list(plan.fast_suites), separators=(",", ":"))
147147
lane_digests_json = json.dumps(dict(plan.lane_digests), separators=(",", ":"))
148+
# Round-4B: derived straight from cache_mode so a writer flow's steps
149+
# (setup-soldr's/astral-sh/setup-uv's 'save-cache' inputs) can pass this
150+
# straight through as their plan-driven expression -- see
151+
# ci_lint.rules.tools._is_plan_expr / ci_lint.rules.cache_static
152+
# .check_cache_003_setup_uv.
153+
cache_save = "true" if plan.cache_mode == "write" else "false"
148154

149155
lines = [
150156
f"plan={compact}",
@@ -158,6 +164,8 @@ def _plan_github_output_lines(plan: Plan, reuse_result: ReuseResult | None) -> l
158164
f"platform_lanes_json={platform_lanes_json}",
159165
f"fast_suites_json={fast_suites_json}",
160166
f"lane_digests_json={lane_digests_json}",
167+
# Round-4B.
168+
f"cache_save={cache_save}",
161169
]
162170

163171
if reuse_result is not None:

‎ci_lint/precheck.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,12 @@ def _local_skip_findings(*, live: bool = False) -> list[Finding]:
7979
1: "contract (CT-001..006, TAG-001, TAG-002)",
8080
2: "workflows (GEN-001/002/008, TAG-003, SEC-003/004, RUN-001, WF-001..003, CT-004)",
8181
3: "shell budget (GEN-005)",
82-
4: "tools (TOOL-001/002, CACHE-009)",
82+
4: "tools (TOOL-001/002, CACHE-009, GEN-004)",
8383
5: "secrets (SEC-001/002)",
8484
6: "layout (LAYOUT-001)",
8585
7: "tests & units (RUST-005/011/012)",
8686
8: "packaging (PKG-003/004/005)",
87-
9: "cache static (CACHE-001/002/004)",
87+
9: "cache static (CACHE-001/002/003/004)",
8888
10: "lint pin (CT-004, checked inside group 2)",
8989
}
9090

@@ -120,7 +120,7 @@ def run_precheck(repo_root: Path, *, title: str = "", local: bool = False, live:
120120
all_findings.extend(check_group2(ci, repo_root))
121121
all_findings.extend(check_group3(ci, repo_root))
122122
all_findings.extend(check_group4(ci, repo_root))
123-
all_findings.extend(check_group5(repo_root))
123+
all_findings.extend(check_group5(ci, repo_root))
124124
all_findings.extend(check_group6(ci, repo_root))
125125
all_findings.extend(check_group7(ci, repo_root))
126126
all_findings.extend(check_group8(ci, repo_root))

‎ci_lint/rules/cache_static.py‎

Lines changed: 138 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
1-
"""Group 9: static cache rules (CACHE-001, CACHE-002, CACHE-004).
2-
3-
No workflow may call `actions/cache` directly (setup-soldr owns cache
4-
identity); no cache key may embed a per-run volatile value; and the total
5-
declared cache footprint (steady state + one lockfile-change peak + the PR
6-
delta budget) must fit under `[cache].budget`, which itself may not exceed
7-
GitHub's 10GB default repository cap.
1+
"""Group 9: static cache rules (CACHE-001, CACHE-002, CACHE-003, CACHE-004).
2+
3+
`actions/cache` (and its `/save`/`/restore` sub-actions) may only appear
4+
inside the one sanctioned wrapper directory `[allow].cache-actions.only-in`
5+
(default `.github/actions/cache`, still SHA-pinned per SEC-004) -- anywhere
6+
else is CACHE-001. Inside that wrapper, a `key:` input must itself be an
7+
expression that reads a prior step's output or a passed-through input
8+
(keys come from `ci_lint cache key`), never a literal -- CACHE-002.
9+
CACHE-002 also still flags a volatile component (`github.sha`, ...) in any
10+
`key:`/`cache-key-suffix:` anywhere. CACHE-003's static half:
11+
`astral-sh/setup-uv`'s `save-cache` input, when `[allow].setup-uv.require`
12+
says it must be `"plan"`-derived, must not be missing or a literal `"true"`
13+
(round-4B; both are exactly the "saves on every PR push" failure mode
14+
documented under "astral-sh/setup-uv's own cache" in docs/ci-toml.md).
15+
Finally, the total declared cache footprint (steady state + one
16+
lockfile-change peak + the PR delta budget) must fit under `[cache].budget`,
17+
which itself may not exceed GitHub's 10GB default repository cap
18+
(CACHE-004).
819
"""
920

1021
from __future__ import annotations
@@ -17,14 +28,15 @@
1728
from ci_lint.schema import CiToml
1829
from ci_lint.workflow_scan import as_dict, load_composite_actions, load_workflows
1930
from ci_lint.yaml_io import LoadStatus, YamlValue
20-
from ci_lint.rules.tools import _iter_uses_with
31+
from ci_lint.rules.tools import _iter_uses_with, _is_plan_expr
2132

2233
SIZE_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$", re.IGNORECASE)
2334
SIZE_UNITS: dict[str, int] = {"B": 1, "KB": 1024, "MB": 1024**2, "GB": 1024**3}
2435
TEN_GB = 10 * 1024**3
2536

2637
VOLATILE_TOKENS: tuple[str, ...] = ("github.sha", "github.run_id", "github.run_number")
2738
KEY_FIELD_NAMES: frozenset[str] = frozenset({"key", "cache-key-suffix"})
39+
CACHE_ACTION_SLUGS_PREFIX = "actions/cache"
2840

2941

3042
def parse_size(text: str) -> int | None:
@@ -36,25 +48,41 @@ def parse_size(text: str) -> int | None:
3648
return int(value * SIZE_UNITS[unit])
3749

3850

39-
def check_cache_001(repo_root: Path) -> list[Finding]:
40-
findings: list[Finding] = []
51+
def _is_cache_action_slug(slug: str) -> bool:
52+
return slug == "actions/cache" or slug.startswith(f"{CACHE_ACTION_SLUGS_PREFIX}/")
53+
54+
55+
def _loaded_files(repo_root: Path) -> list[tuple[str, bool, dict[str, YamlValue]]]:
4156
files = [(w.path, False, as_dict(w.document)) for w in load_workflows(repo_root) if w.status == LoadStatus.OK]
4257
files += [
4358
(a.path, True, as_dict(a.document)) for a in load_composite_actions(repo_root) if a.status == LoadStatus.OK
4459
]
45-
for path, is_composite, doc in files:
60+
return files
61+
62+
63+
def check_cache_001(ci: CiToml, repo_root: Path) -> list[Finding]:
64+
findings: list[Finding] = []
65+
only_in = ci.allow.cache_actions.only_in.strip("/")
66+
for path, is_composite, doc in _loaded_files(repo_root):
67+
file_dir = Path(path).parent.as_posix()
4668
for uses, loc, _with in _iter_uses_with(doc, is_composite=is_composite):
4769
slug = uses.split("@", 1)[0]
48-
if slug == "actions/cache" or slug.startswith("actions/cache/"):
49-
findings.append(
50-
Finding(
51-
rule="CACHE-001",
52-
path=path,
53-
message=f"{loc}: raw '{slug}' is used directly",
54-
fix=f"remove {loc}; caching goes through zackees/setup-soldr's declared "
55-
"families (or the ci-lint 'uv' family), never a raw actions/cache call",
56-
)
70+
if not _is_cache_action_slug(slug):
71+
continue
72+
if file_dir == only_in:
73+
continue # the one sanctioned wrapper (still SHA-pinned per SEC-004)
74+
findings.append(
75+
Finding(
76+
rule="CACHE-001",
77+
path=path,
78+
message=f"{loc}: raw '{slug}' is used directly outside the sanctioned wrapper "
79+
f"'{only_in}' (found in '{file_dir}')",
80+
fix=f"move this call into the composite-action wrapper at {only_in}/action.yml "
81+
f"(SHA-pinned per SEC-004) and call that wrapper from {path} instead; caching "
82+
"otherwise goes through zackees/setup-soldr's declared families (or the ci-lint "
83+
"'uv' family), never a direct actions/cache call",
5784
)
85+
)
5886
return findings
5987

6088

@@ -76,16 +104,41 @@ def _check_key_value(value: YamlValue, path: str, loc: str) -> list[Finding]:
76104
return out
77105

78106

107+
def _check_wrapper_key_is_dynamic(value: YamlValue, path: str, loc: str) -> list[Finding]:
108+
"""Inside the sanctioned `actions/cache*` wrapper, `key:` must be an
109+
expression that reads a prior step's output or a passed-through input
110+
(round-4B: keys are built by `ci_lint cache key`, never hand-written) --
111+
a literal string, even one with no volatile token, is CACHE-002 here."""
112+
113+
if not isinstance(value, str):
114+
return []
115+
if _is_plan_expr(value) or re.search(r"steps\.[\w-]+\.outputs\.", value):
116+
return []
117+
return [
118+
Finding(
119+
rule="CACHE-002",
120+
path=path,
121+
message=f"{loc} is a literal cache key inside the sanctioned wrapper: {value!r}",
122+
fix=f"build {loc} from 'ci_lint cache key' (e.g. a prior step's "
123+
"'${{ steps.<id>.outputs.key }}') or pass it through as '${{ inputs.key }}' -- never "
124+
"hardcode a literal key inside the wrapper",
125+
)
126+
]
127+
128+
79129
def check_cache_002(ci: CiToml, repo_root: Path) -> list[Finding]:
80130
findings: list[Finding] = []
81-
files = [(w.path, False, as_dict(w.document)) for w in load_workflows(repo_root) if w.status == LoadStatus.OK]
82-
files += [
83-
(a.path, True, as_dict(a.document)) for a in load_composite_actions(repo_root) if a.status == LoadStatus.OK
84-
]
85-
for path, is_composite, doc in files:
131+
only_in = ci.allow.cache_actions.only_in.strip("/")
132+
for path, is_composite, doc in _loaded_files(repo_root):
133+
file_dir = Path(path).parent.as_posix()
86134
for uses, loc, with_ in _iter_uses_with(doc, is_composite=is_composite):
87135
for field_name in KEY_FIELD_NAMES:
88136
findings.extend(_check_key_value(with_.get(field_name), path, f"{loc}.with.{field_name}"))
137+
slug = uses.split("@", 1)[0]
138+
if _is_cache_action_slug(slug) and file_dir == only_in and "key" in with_:
139+
findings.extend(
140+
_check_wrapper_key_is_dynamic(with_.get("key"), path, f"{loc}.with.key")
141+
)
89142
for fam_id, fam in ci.cache.family.items():
90143
if fam.key is None:
91144
continue
@@ -96,6 +149,64 @@ def check_cache_002(ci: CiToml, repo_root: Path) -> list[Finding]:
96149
return findings
97150

98151

152+
def _setup_uv_save_cache_violation(actual: YamlValue) -> str | None:
153+
"""`None` if OK; else the reason `astral-sh/setup-uv`'s `save-cache`
154+
input fails the plan-driven requirement. Mirrors the two failure modes
155+
docs/ci-toml.md's "astral-sh/setup-uv's own cache" section documents as
156+
actually saving on every ordinary PR push: a missing input (falls back
157+
to the action's own `"auto"` default) and a literal `"true"` (forces a
158+
save regardless of ref). An explicit `"false"`, or any other value,
159+
is not this rule's concern."""
160+
161+
if actual is None:
162+
return "is missing (falls back to the action's 'auto' default, which still saves on every PR push)"
163+
if isinstance(actual, str) and actual.strip().lower() == "true":
164+
return f"= {actual!r} is a literal 'true' (saves unconditionally, on every ref including PRs)"
165+
return None
166+
167+
168+
def check_cache_003_setup_uv(ci: CiToml, repo_root: Path) -> list[Finding]:
169+
"""Round-4B: every `astral-sh/setup-uv` use (no single wrapper location
170+
-- unlike setup-soldr, this action is meant to be called directly), for
171+
each `[allow].setup-uv.require` entry whose expected value is the
172+
special string `"plan"`."""
173+
174+
findings: list[Finding] = []
175+
require = ci.allow.setup_uv.require
176+
if not require:
177+
return findings
178+
for path, is_composite, doc in _loaded_files(repo_root):
179+
for uses, loc, with_ in _iter_uses_with(doc, is_composite=is_composite):
180+
if uses.split("@", 1)[0] != "astral-sh/setup-uv":
181+
continue
182+
for key, expected in require.items():
183+
actual = with_.get(key)
184+
if expected == "plan":
185+
reason = _setup_uv_save_cache_violation(actual)
186+
if reason is not None:
187+
findings.append(
188+
Finding(
189+
rule="CACHE-003",
190+
path=path,
191+
message=f"{loc}: astral-sh/setup-uv input '{key}' {reason}",
192+
fix=f"set '{key}' to an expression derived from the precheck plan "
193+
f"(e.g. '${{{{ needs.precheck.outputs.cache_save }}}}' in the caller, "
194+
f"or '${{{{ inputs.{key} }}}}' inside a composite wrapper) at {loc}",
195+
)
196+
)
197+
elif actual is None or str(actual).lower() != expected.lower():
198+
findings.append(
199+
Finding(
200+
rule="CACHE-003",
201+
path=path,
202+
message=f"{loc}: astral-sh/setup-uv input '{key}' = {actual!r}, expected "
203+
f"'{expected}'",
204+
fix=f'set \'{key}: "{expected}"\' at {loc}',
205+
)
206+
)
207+
return findings
208+
209+
99210
def _cardinality(ci: CiToml, per: str | None) -> int:
100211
"""`per`'s cardinality multiplier. `ci_lint.schema` already rejects any
101212
value outside `CACHE_FAMILY_PER_VALUES` as `CT-002` (round-2A amendment
@@ -239,8 +350,9 @@ def check_cache_004(ci: CiToml) -> tuple[list[Finding], str]:
239350

240351
def check_group9(ci: CiToml, repo_root: Path) -> tuple[list[Finding], str]:
241352
findings: list[Finding] = []
242-
findings.extend(check_cache_001(repo_root))
353+
findings.extend(check_cache_001(ci, repo_root))
243354
findings.extend(check_cache_002(ci, repo_root))
355+
findings.extend(check_cache_003_setup_uv(ci, repo_root))
244356
cache_004_findings, arithmetic = check_cache_004(ci)
245357
findings.extend(cache_004_findings)
246358
return findings, arithmetic

0 commit comments

Comments
 (0)