Coverage for packages/workshop/src/livery/workshop/_security.py: 75%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/extensions/docs/tests/test_task_links.py ran.

1"""Security verification for admin-secret isolation and privilege boundaries.
2
3Provides offline and live checks for ``fm security.check`` and the
4``fm doctor`` security section, plus the three-tier secret exposure
5summary. Reads contracts, ``CODEOWNERS``, and generated workflow files
6strictly with the standard library so it stays free of dev-only extras.
7"""
8
9from __future__ import annotations
10
11import re
12from dataclasses import dataclass
13from pathlib import Path
14from typing import Annotated
15
16import livery.footman as footman
17from livery.footman import Finding, doc, fail, group
18from livery.forge import Forge, Repository
19from livery.workshop._contract import load_contract
20from livery.workshop._extensions import workspace_root
21from livery.workshop._governance import (
22 ci_environments,
23 codeowners_file,
24 governance_config,
25 owners_of,
26 privileged_paths,
27)
28
29security = group(
30 "security",
31 help="Verify admin-secret isolation and privilege boundaries",
32)
33
34#: Secret names that must never live at repository scope on GitHub or
35#: remain unprotected on GitLab.
36PRIVILEGED_SECRETS: tuple[str, ...] = (
37 "FORGE_ADMIN_TOKEN",
38 "FORGE_TOKEN",
39 "PYPI_TOKEN",
40 "UV_PUBLISH_TOKEN",
41 "GITLAB_PUSH_TOKEN",
42)
43
44#: Default environment role for each standard CI credential name.
45SECRET_ROLES: dict[str, str] = {
46 "FORGE_ADMIN_TOKEN": "govern",
47 "FORGE_TOKEN": "bot",
48 "PYPI_TOKEN": "pypi",
49 "UV_PUBLISH_TOKEN": "pypi",
50}
51
52_RUNG_SECRET_RE = re.compile(r"RUNG_[A-Z0-9_]+\s*:\s*\$\{\{\s*secrets\.")
53_SECRET_REF_RE = re.compile(r"\$\{\{\s*secrets\.([A-Za-z0-9_]+)\s*\}\}")
54_PR_JOBS = ("legs", "check", "docs", "gate")
55
56
57@dataclass(frozen=True)
58class TierEntry:
59 """One row in the three-tier CI secret exposure summary.
60
61 Attributes:
62 tier: Exposure tier (1 = isolated privileged, 2 = trusted-branch
63 workspace, 3 = PR-reachable / repository-scoped).
64 secret: Credential name or mechanism.
65 scope: Where the credential is scoped (environment or branch rule).
66 jobs: CI jobs receiving the credential.
67 exposure: Plain statement of who can read or exfiltrate it.
68 """
69
70 tier: int
71 secret: str
72 scope: str
73 jobs: str
74 exposure: str
75
76
77def secret_tiers(root: Path) -> tuple[TierEntry, ...]:
78 """Classify the workspace's declared CI credentials into Tiers 1, 2, and 3."""
79 contract = load_contract(root / "workshop.toml")
80 kind = str((contract.get("forge") or {}).get("kind", ""))
81 envs = ci_environments(contract)
82 if kind == "gitlab":82 ↛ 83line 82 didn't jump to line 83 because the condition on line 82 was never true
83 govern_scope = "protected CI variable (main only)"
84 bot_scope = "protected CI variable (main only)"
85 pypi_scope = "protected CI variable (main only)"
86 elif kind == "gitea":86 ↛ 87line 86 didn't jump to line 87 because the condition on line 86 was never true
87 govern_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
88 bot_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
89 pypi_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
90 else:
91 govern_scope = f"environment {envs['govern']!r} (protected branches)"
92 bot_scope = f"environment {envs['bot']!r} (protected branches)"
93 pypi_scope = f"environment {envs['pypi']!r} (protected branches)"
94 return (
95 TierEntry(
96 tier=1,
97 secret="FORGE_ADMIN_TOKEN",
98 scope=govern_scope,
99 jobs="govern (isolated python3 -I)",
100 exposure=(
101 "protected from unmerged PRs and merged packages/*/ code"
102 if kind != "gitea"
103 else "exposed on same-repo branches; require forks or desk-only"
104 ),
105 ),
106 TierEntry(
107 tier=1,
108 secret="PYPI_TOKEN / OIDC",
109 scope=pypi_scope,
110 jobs="publish (isolated python3 -I)",
111 exposure=(
112 "protected from unmerged PRs and merged packages/*/ code"
113 if kind != "gitea"
114 else "exposed on same-repo branches; require forks"
115 ),
116 ),
117 TierEntry(
118 tier=2,
119 secret="FORGE_TOKEN (and any in-workspace extension credentials)",
120 scope=bot_scope,
121 jobs="nightly / workspace jobs on main",
122 exposure=(
123 "protected from unmerged PRs, NOT from merged packages/*/ code:"
124 " any contributor who can merge package code can read Tier 2"
125 " secrets"
126 ),
127 ),
128 TierEntry(
129 tier=3,
130 secret="PR-wired or repo-scoped secrets",
131 scope="pull_request jobs or GitHub repo secrets",
132 jobs="disallowed",
133 exposure=(
134 "exfiltrable without merging; any repo-scoped secret on GitHub"
135 " or PR-wired secret is a failure"
136 ),
137 ),
138 )
139
140
141def _normalize_owners(owners: tuple[str, ...]) -> tuple[str, ...]:
142 return tuple(sorted(o if o.startswith("@") else f"@{o}" for o in owners))
143
144
145def _pattern_matches(pattern: str, target: str) -> bool:
146 """Whether CODEOWNERS *pattern* matches root-relative *target*."""
147 if pattern == "*":147 ↛ 148line 147 didn't jump to line 148 because the condition on line 147 was never true
148 return True
149 norm_pat = pattern if pattern.startswith("/") else f"/{pattern}"
150 norm_tgt = target if target.startswith("/") else f"/{target}"
151 if norm_pat == norm_tgt:
152 return True
153 if norm_pat.endswith("/"):
154 return norm_tgt.startswith(norm_pat)
155 if "*" in norm_pat:155 ↛ 156line 155 didn't jump to line 156 because the condition on line 155 was never true
156 escaped = re.escape(norm_pat).replace(r"\*", "[^/]*")
157 return re.fullmatch(escaped, norm_tgt) is not None
158 return False
159
160
161def _parse_codeowners_rules(
162 text: str,
163) -> list[tuple[str, str, tuple[str, ...]]]:
164 """Return ``(section, pattern, owners)`` tuples from CODEOWNERS *text*."""
165 section = ""
166 rules: list[tuple[str, str, tuple[str, ...]]] = []
167 for raw in text.splitlines():
168 line = raw.strip()
169 if not line or line.startswith("#"):
170 continue
171 sec_match = re.match(r"^\^?\[([^\]]+)\](?:\[\d+\])?$", line)
172 if sec_match:
173 section = sec_match.group(1).strip()
174 continue
175 parts = line.split()
176 if len(parts) < 2:176 ↛ 177line 176 didn't jump to line 177 because the condition on line 176 was never true
177 continue
178 pattern = parts[0]
179 owners = tuple(part for part in parts[1:] if part.startswith("@"))
180 if owners:180 ↛ 167line 180 didn't jump to line 167 because the condition on line 180 was always true
181 rules.append((section, pattern, owners))
182 return rules
183
184
185def _check_codeowners(root: Path) -> list[Finding]:
186 """Verify every privileged path is owned by root owners without shadowing."""
187 contract = load_contract(root / "workshop.toml")
188 forge_table = contract.get("forge") or {}
189 kind = str(forge_table.get("kind", ""))
190 owner = str(forge_table.get("owner", ""))
191 root_users, root_teams, _approvals = owners_of(contract)
192 if not kind or not (root_users or root_teams):
193 return []
194 expected = codeowners_file(root)
195 if expected is None:195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true
196 return []
197 codeowners_path = root / expected.path
198 if not codeowners_path.is_file():198 ↛ 199line 198 didn't jump to line 199 because the condition on line 198 was never true
199 return [
200 Finding(
201 "security: codeowners",
202 f"{expected.path} is missing",
203 f"run `{footman.prog()} sync` to generate {expected.path}",
204 )
205 ]
206 qualified_root = _normalize_owners(
207 root_users + tuple(f"{owner}/{team}" for team in root_teams)
208 )
209 rules = _parse_codeowners_rules(codeowners_path.read_text("utf-8"))
210 priv = privileged_paths(root)
211 findings: list[Finding] = []
212 if kind == "gitlab":
213 gov_rules = [(pat, own) for sec, pat, own in rules if sec == "governance"]
214 for path in priv:
215 matched = [
216 (pat, own) for pat, own in gov_rules if _pattern_matches(pat, path)
217 ]
218 if not matched:
219 findings.append(
220 Finding(
221 "security: codeowners",
222 f"{path} is not guarded in [governance] of {expected.path}",
223 f"run `{footman.prog()} sync` to regenerate {expected.path}",
224 )
225 )
226 elif _normalize_owners(matched[-1][1]) != qualified_root:226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 findings.append(
228 Finding(
229 "security: codeowners",
230 f"{path} in [governance] is owned by"
231 f" {' '.join(matched[-1][1])}, not root owners",
232 f"run `{footman.prog()} sync` to regenerate {expected.path}",
233 )
234 )
235 else:
236 for path in priv:
237 matched = [
238 (pat, own) for _sec, pat, own in rules if _pattern_matches(pat, path)
239 ]
240 if not matched:240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true
241 findings.append(
242 Finding(
243 "security: codeowners",
244 f"{path} is not matched in {expected.path}",
245 f"run `{footman.prog()} sync` to regenerate {expected.path}",
246 )
247 )
248 else:
249 last_pat, last_owners = matched[-1]
250 if _normalize_owners(last_owners) != qualified_root:
251 findings.append(
252 Finding(
253 "security: codeowners",
254 f"{path} is shadowed by later rule {last_pat!r}"
255 f" ({' '.join(last_owners)}) in {expected.path}",
256 f"keep governance rules last in {expected.path}"
257 f" (`{footman.prog()} sync`)",
258 )
259 )
260 if not findings:
261 findings.append(
262 Finding(
263 f"security: codeowners: all {len(priv)} privileged paths guarded"
264 f" in {expected.path}"
265 )
266 )
267 return findings
268
269
270def _actions_job_block(text: str, job_name: str) -> str:
271 """Slice one top-level ``jobs.<job_name>`` block from Actions YAML text."""
272 marker = f"\n {job_name}:\n"
273 start = text.find(marker)
274 if start == -1:
275 return ""
276 rest = text[start + len(marker) :]
277 next_job = re.search(r"\n [A-Za-z0-9_-]+:\n", rest)
278 return rest[: next_job.start()] if next_job else rest
279
280
281def _gitlab_job_block(text: str, job_name: str) -> str:
282 """Slice one top-level job block from ``.gitlab-ci.yml`` text."""
283 marker = f"\n{job_name}:\n"
284 start = text.find(marker)
285 if start == -1:285 ↛ 286line 285 didn't jump to line 286 because the condition on line 285 was never true
286 if text.startswith(f"{job_name}:\n"):
287 rest = text[len(f"{job_name}:\n") :]
288 else:
289 return ""
290 else:
291 rest = text[start + len(marker) :]
292 next_job = re.search(r"\n[A-Za-z0-9_.-]+:\n", rest)
293 return rest[: next_job.start()] if next_job else rest
294
295
296def _check_workflows(root: Path) -> list[Finding]:
297 """Verify generated workflows isolate Tier 1 jobs and never wire secrets to PRs."""
298 contract = load_contract(root / "workshop.toml")
299 kind = str((contract.get("forge") or {}).get("kind", ""))
300 if not kind:300 ↛ 301line 300 didn't jump to line 301 because the condition on line 300 was never true
301 return []
302 envs = ci_environments(contract)
303 findings: list[Finding] = []
304 prog = footman.prog()
305
306 if kind == "gitlab":
307 gitlab_file = root / ".gitlab-ci.yml"
308 if not gitlab_file.is_file():308 ↛ 309line 308 didn't jump to line 309 because the condition on line 308 was never true
309 return []
310 text = gitlab_file.read_text("utf-8")
311 if _RUNG_SECRET_RE.search(text):311 ↛ 312line 311 didn't jump to line 312 because the condition on line 311 was never true
312 findings.append(
313 Finding(
314 "security: workflows",
315 ".gitlab-ci.yml maps .repo.env keys to secrets.*",
316 f"run `{prog} sync` so .repo.env maps to non-secret vars",
317 )
318 )
319 govern = _gitlab_job_block(text, "govern")
320 if govern and (320 ↛ 325line 320 didn't jump to line 325 because the condition on line 320 was never true
321 "livery.workshop._govern_entry" not in govern
322 or "python3 -I" not in govern
323 or "setup.sh" in govern
324 ):
325 findings.append(
326 Finding(
327 "security: workflows",
328 "govern job in .gitlab-ci.yml is not isolated under python3 -I",
329 f"run `{prog} sync` to regenerate .gitlab-ci.yml",
330 )
331 )
332 publish = _gitlab_job_block(text, "publish")
333 if publish:333 ↛ 355line 333 didn't jump to line 355 because the condition on line 333 was always true
334 if "git merge-base --is-ancestor" not in publish:334 ↛ 335line 334 didn't jump to line 335 because the condition on line 334 was never true
335 findings.append(
336 Finding(
337 "security: workflows",
338 "publish job in .gitlab-ci.yml lacks ref ancestry check",
339 f"run `{prog} sync` to regenerate .gitlab-ci.yml",
340 )
341 )
342 if (342 ↛ 347line 342 didn't jump to line 347 because the condition on line 342 was never true
343 "livery.workshop._publish_entry" not in publish
344 or "python3 -I" not in publish
345 or "setup.sh" in publish
346 ):
347 findings.append(
348 Finding(
349 "security: workflows",
350 "publish job in .gitlab-ci.yml is not isolated under"
351 " python3 -I",
352 f"run `{prog} sync` to regenerate .gitlab-ci.yml",
353 )
354 )
355 if not findings:355 ↛ 362line 355 didn't jump to line 362 because the condition on line 355 was always true
356 findings.append(
357 Finding(
358 "security: workflows: .gitlab-ci.yml isolates govern and"
359 " publish and verifies release ref ancestry"
360 )
361 )
362 return findings
363
364 wf_dir = root / f".{kind}" / "workflows"
365 if not wf_dir.is_dir():365 ↛ 366line 365 didn't jump to line 366 because the condition on line 365 was never true
366 return []
367
368 workflow_files = sorted(wf_dir.glob("*.yml"))
369 for wf in workflow_files:
370 text = wf.read_text("utf-8")
371 if _RUNG_SECRET_RE.search(text):
372 findings.append(
373 Finding(
374 "security: workflows",
375 f"{wf.relative_to(root)} wires .repo.env keys via secrets.*",
376 f"run `{prog} sync` so .repo.env uses vars.*",
377 )
378 )
379
380 ci_path = wf_dir / "ci.yml"
381 if ci_path.is_file():381 ↛ 425line 381 didn't jump to line 425 because the condition on line 381 was always true
382 ci_text = ci_path.read_text("utf-8")
383 for pr_job in _PR_JOBS:
384 block = _actions_job_block(ci_text, pr_job)
385 bad = sorted(
386 {s for s in _SECRET_REF_RE.findall(block) if s != "GITHUB_TOKEN"}
387 )
388 if bad:
389 findings.append(
390 Finding(
391 "security: workflows",
392 f"PR-reachable job {pr_job!r} in {ci_path.relative_to(root)}"
393 f" references secret(s): {', '.join(bad)}",
394 "remove secrets from PR-reachable jobs",
395 )
396 )
397 govern = _actions_job_block(ci_text, "govern")
398 if govern:398 ↛ 425line 398 didn't jump to line 425 because the condition on line 398 was always true
399 if (399 ↛ 403line 399 didn't jump to line 403 because the condition on line 399 was never true
400 kind == "github"
401 and f" environment: {envs['govern']}\n" not in govern
402 ):
403 findings.append(
404 Finding(
405 "security: workflows",
406 f"govern job in {ci_path.relative_to(root)} does not"
407 f" declare environment: {envs['govern']}",
408 f"run `{prog} sync` to regenerate workflows",
409 )
410 )
411 if (
412 "livery.workshop._govern_entry" not in govern
413 or "python3 -I" not in govern
414 or "setup.sh" in govern
415 ):
416 findings.append(
417 Finding(
418 "security: workflows",
419 f"govern job in {ci_path.relative_to(root)} is not"
420 " isolated under python3 -I",
421 f"run `{prog} sync` to regenerate workflows",
422 )
423 )
424
425 nightly_path = wf_dir / "nightly.yml"
426 if nightly_path.is_file() and kind == "github":426 ↛ 439line 426 didn't jump to line 439 because the condition on line 426 was always true
427 nightly_text = nightly_path.read_text("utf-8")
428 nightly_job = _actions_job_block(nightly_text, "nightly")
429 if nightly_job and f" environment: {envs['bot']}\n" not in nightly_job:429 ↛ 430line 429 didn't jump to line 430 because the condition on line 429 was never true
430 findings.append(
431 Finding(
432 "security: workflows",
433 f"nightly job in {nightly_path.relative_to(root)} does not"
434 f" declare environment: {envs['bot']}",
435 f"run `{prog} sync` to regenerate workflows",
436 )
437 )
438
439 release_path = wf_dir / "release.yml"
440 if release_path.is_file():440 ↛ 476line 440 didn't jump to line 476 because the condition on line 440 was always true
441 rel_text = release_path.read_text("utf-8")
442 publish = _actions_job_block(rel_text, "publish")
443 if publish:443 ↛ 476line 443 didn't jump to line 476 because the condition on line 443 was always true
444 if kind == "github" and f" environment: {envs['pypi']}\n" not in publish:444 ↛ 445line 444 didn't jump to line 445 because the condition on line 444 was never true
445 findings.append(
446 Finding(
447 "security: workflows",
448 f"publish job in {release_path.relative_to(root)} does"
449 f" not declare environment: {envs['pypi']}",
450 f"run `{prog} sync` to regenerate workflows",
451 )
452 )
453 if "git merge-base --is-ancestor" not in publish:
454 findings.append(
455 Finding(
456 "security: workflows",
457 f"publish job in {release_path.relative_to(root)} lacks"
458 " inputs.ref ancestry verification",
459 f"run `{prog} sync` to regenerate workflows",
460 )
461 )
462 if (462 ↛ 467line 462 didn't jump to line 467 because the condition on line 462 was never true
463 "livery.workshop._publish_entry" not in publish
464 or "python3 -I" not in publish
465 or "setup.sh" in publish
466 ):
467 findings.append(
468 Finding(
469 "security: workflows",
470 f"publish job in {release_path.relative_to(root)} is"
471 " not isolated under python3 -I",
472 f"run `{prog} sync` to regenerate workflows",
473 )
474 )
475
476 if not findings:
477 findings.append(
478 Finding(
479 "security: workflows: .repo.env uses vars.*, Tier 1 jobs run"
480 " isolated, and release verifies ref ancestry"
481 )
482 )
483 return findings
484
485
486def offline_security_findings(root: Path) -> list[Finding]:
487 """Run all offline admin-secret isolation checks against *root*."""
488 contract = load_contract(root / "workshop.toml")
489 root_users, root_teams, root_approvals = owners_of(contract)
490 findings: list[Finding] = []
491 prog = footman.prog()
492
493 if not (root_users or root_teams):
494 findings.append(
495 Finding(
496 "security: owners",
497 "no root [owners] declared; privileged paths are unguarded",
498 "add [owners] users/teams and approvals >= 1 to workshop.toml,"
499 f" then run `{prog} sync`",
500 )
501 )
502 elif root_approvals == 0:
503 findings.append(
504 Finding(
505 "security: owners: solo/unprotected mode (approvals = 0;"
506 " admin-secret isolation requires approvals >= 1)"
507 )
508 )
509 else:
510 findings.append(
511 Finding(
512 f"security: owners: root [owners] requires {root_approvals} approval(s)"
513 )
514 )
515
516 findings.extend(_check_codeowners(root))
517 findings.extend(_check_workflows(root))
518 return findings
519
520
521def live_security_findings(root: Path, forge: Forge, repo: Repository) -> list[Finding]:
522 """Run live forge checks for protection, environments, and secret scopes."""
523 from livery.workshop._workflow_tasks import required_context_string
524
525 contract = load_contract(root / "workshop.toml")
526 forge_table = contract.get("forge") or {}
527 kind = str(forge_table.get("kind", ""))
528 ci_table = contract.get("ci") or {}
529 context = str(ci_table.get("required-context") or "gate")
530 expected_ctx = required_context_string(kind, context)
531 gov = governance_config(root)
532 highest = gov.min_approvals or 0
533 envs = ci_environments(contract)
534 prog = footman.prog()
535 findings: list[Finding] = []
536
537 protection = repo.protection("main")
538 if protection is None:
539 findings.append(
540 Finding(
541 "security: protection",
542 "default branch 'main' has no branch protection",
543 f"run `{prog} workflow.configure`",
544 )
545 )
546 else:
547 if (547 ↛ 551line 547 didn't jump to line 551 because the condition on line 547 was never true
548 forge.supports("required_contexts")
549 and expected_ctx not in protection.required_contexts
550 ):
551 findings.append(
552 Finding(
553 "security: protection",
554 f"default branch protection does not require {expected_ctx!r}",
555 f"run `{prog} workflow.configure`",
556 )
557 )
558 if highest >= 1:558 ↛ 589line 558 didn't jump to line 589 because the condition on line 558 was always true
559 if forge.supports("min_approvals"):559 ↛ 577line 559 didn't jump to line 577 because the condition on line 559 was always true
560 if protection.required_approvals < highest:560 ↛ 561line 560 didn't jump to line 561 because the condition on line 560 was never true
561 findings.append(
562 Finding(
563 "security: protection",
564 f"required_approvals is {protection.required_approvals},"
565 f" expected >= {highest}",
566 f"run `{prog} workflow.configure`",
567 )
568 )
569 if protection.require_codeowner_review is not True:569 ↛ 570line 569 didn't jump to line 570 because the condition on line 569 was never true
570 findings.append(
571 Finding(
572 "security: protection",
573 "require_codeowner_review is not enabled on default branch",
574 f"run `{prog} workflow.configure`",
575 )
576 )
577 if (
578 forge.supports("dismiss_stale_reviews")
579 and not protection.dismiss_stale_reviews
580 ):
581 findings.append(
582 Finding(
583 "security: protection",
584 "dismiss_stale_reviews is disabled on default branch",
585 f"run `{prog} workflow.configure`",
586 )
587 )
588
589 if kind == "github":
590 existing_envs = {env.name: env for env in repo.environments()}
591 for env_name in dict.fromkeys(envs.values()):
592 info = existing_envs.get(env_name)
593 if info is None:
594 findings.append(
595 Finding(
596 "security: environments",
597 f"GitHub environment {env_name!r} is missing",
598 f"run `{prog} workflow.configure` to create and lock it",
599 )
600 )
601 elif not info.protected_branches_only:
602 findings.append(
603 Finding(
604 "security: environments",
605 f"GitHub environment {env_name!r} is not restricted to"
606 " protected branches",
607 f"run `{prog} workflow.configure` to lock {env_name!r}",
608 )
609 )
610 else:
611 env_secrets = [s.name for s in repo.secret_names(environment=env_name)]
612 listed = ", ".join(env_secrets) if env_secrets else "none"
613 findings.append(
614 Finding(
615 f"security: environment {env_name}: protected branches"
616 f" only (secrets: {listed})"
617 )
618 )
619 for secret in repo.secret_names():
620 findings.append(
621 Finding(
622 "security: secrets",
623 f"repository-scoped secret {secret.name} is readable by any"
624 " same-repo branch on GitHub",
625 f"move it with `{prog} workflow.secret.set {secret.name}`"
626 " and delete the repository-level secret",
627 )
628 )
629 elif kind == "gitlab":
630 variables = repo.secret_names()
631 for var in variables:
632 if var.name in PRIVILEGED_SECRETS and not var.protected:632 ↛ 631line 632 didn't jump to line 631 because the condition on line 632 was always true
633 findings.append(
634 Finding(
635 "security: secrets",
636 f"CI variable {var.name} is unprotected (protected=False)",
637 f"run `{prog} workflow.secret.set {var.name}` to mark it"
638 " protected",
639 )
640 )
641 if not forge.supports("min_approvals"):641 ↛ 659line 641 didn't jump to line 659 because the condition on line 641 was always true
642 findings.append(
643 Finding(
644 "security: gitlab-free: CODEOWNERS enforcement and"
645 " reset_approvals_on_push are licence-gated on GitLab"
646 " Free/CE; isolation relies on Maintainer-only merge to main"
647 )
648 )
649 elif kind == "gitea":649 ↛ 659line 649 didn't jump to line 659 because the condition on line 649 was always true
650 findings.append(
651 Finding(
652 "security: gitea: Gitea Actions lacks branch-scoped secrets;"
653 " require fork-only contributions or keep FORGE_ADMIN_TOKEN off"
654 f" CI and run `{prog} workflow.configure` from a maintainer's"
655 " desk"
656 )
657 )
658
659 if not any(f.found for f in findings):
660 findings.append(
661 Finding("security: live: forge protection and secret scopes verified")
662 )
663 return findings
664
665
666def security_findings(
667 root: Path,
668 *,
669 forge: Forge | None = None,
670 repo: Repository | None = None,
671 offline: bool = False,
672) -> list[Finding]:
673 """Combined offline and (when authenticated) live security findings."""
674 findings = offline_security_findings(root)
675 if offline:675 ↛ 677line 675 didn't jump to line 677 because the condition on line 675 was always true
676 return findings
677 contract = load_contract(root / "workshop.toml")
678 kind = str((contract.get("forge") or {}).get("kind", ""))
679 if not kind:
680 return findings
681 try:
682 if forge is None or repo is None:
683 from livery.workshop._forge_lane import this_forge, this_repository
684
685 forge = forge or this_forge(root)
686 repo = repo or this_repository(root)
687 findings.extend(live_security_findings(root, forge, repo))
688 except Exception as error:
689 findings.append(Finding(f"security: live checks skipped ({error})"))
690 return findings
691
692
693def format_tier_summary(root: Path) -> str:
694 """Render the human-readable three-tier CI secret exposure summary."""
695 lines = ["Secret exposure tiers:"]
696 for entry in secret_tiers(root):
697 lines.append(
698 f" Tier {entry.tier} | {entry.secret} | {entry.scope} | {entry.jobs}"
699 )
700 lines.append(f" {entry.exposure}")
701 return "\n".join(lines)
702
703
704@security.task(name="check")
705def security_check(
706 offline: Annotated[bool, doc("skip live forge API checks")] = False,
707) -> None:
708 """Verify admin-secret isolation, CODEOWNERS boundaries, and secret scopes.
709
710 Runs offline checks against ``workshop.toml``, ``CODEOWNERS``, and
711 generated workflows, then queries the forge for branch protection,
712 protected environments, and misplaced repository-level secrets
713 unless ``--offline`` is passed. Prints the three-tier secret
714 exposure summary and fails if any standing security issue is found.
715 """
716 root = workspace_root()
717 if root is None:
718 fail("no workspace: no workshop.toml above the working directory")
719 findings = security_findings(root, offline=offline)
720 failures: list[Finding] = []
721 for finding in findings:
722 if finding.found:
723 failures.append(finding)
724 print(f" FAIL {finding.what}: {finding.found}")
725 if finding.fix:
726 print(f" fix: {finding.fix}")
727 elif (
728 "solo/unprotected" in finding.what
729 or "gitlab-free" in finding.what
730 or "gitea:" in finding.what
731 or "skipped" in finding.what
732 ):
733 print(f" WARN {finding.what}")
734 else:
735 print(f" ok {finding.what}")
736 print()
737 print(format_tier_summary(root))
738 if failures:
739 fail(f"security.check found {len(failures)} standing issue(s)")