:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): lint secrets a reusable workflow reads against its callers (#97802)
Georges-Antoine Assifa1ce993bf1c
diff --git a/.agents/skills/authoring-ci-workflows/SKILL.md b/.agents/skills/authoring-ci-workflows/SKILL.mdindex e4714f2b1b1e..be83705ed72f 100644--- a/.agents/skills/authoring-ci-workflows/SKILL.md+++ b/.agents/skills/authoring-ci-workflows/SKILL.md@@ -28,7 +28,7 @@ The linters own the mechanical rules (below); this skill is the **judgment calls## What the linters already enforceRun `bin/hogli lint:workflows` and `actionlint` before pushing — they gate CI, and they (not this list) are the source of truth for what's enforced.-Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).+Today that's: `timeout-minutes` on every job, the canonical PR concurrency block, a repo-wide budget for unscoped PR event dispatches, `dorny/paths-filter` negation safety, justification for full-depth checkouts, cache-write gating, semgrep service coverage, MCP path-filter coverage of the trees the MCP build compiles, required-check gate hygiene, secrets a reusable workflow reads being declared and passed by its callers, and generic GHA correctness (bad `secrets.*` / `needs:` refs, deprecated `::set-output`, unknown runner labels).Third-party action digests are bumped by Renovate.## The dispatch budget (500 runs / 10s / repo)@@ -303,6 +303,14 @@ A dedicated GitHub App installation is its own bucket — rate-limit headroom pl- Cross-repo tokens set explicit `owner:` + `repositories:` (least privilege).- Creating the app + secret is out of scope here — use `/managing-github-actions-secrets`.+### Secrets in reusable workflows++A `workflow_call` workflow receives no secrets on its own.+A `secrets.X` it reads interpolates to an empty string unless it declares `X` under `on.workflow_call.secrets` and every caller passes it, or a caller uses `secrets: inherit`.+Nothing fails when that happens: an App-token step under `continue-on-error` falls back to `github.token` and the check stays green, which is how `ci-turbo` silently lost its dedicated rate-limit bucket.+`WF010` fails an undeclared read, and fails a caller that omits a secret declared `required: true`.+Declare `required: false` only when the callee genuinely works without the value, the way a smoke-test build withholds a publish key on purpose; that is the callee's promise, and the linter takes it at its word.+## Forks and untrusted PRs (public repo)Fork `pull_request` runs (and Dependabot) get a read-only `GITHUB_TOKEN` and no secrets.diff --git a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.pyindex 016995cc2b1b..c9b33ab04722 100644--- a/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py+++ b/tools/hogli-commands/hogli_commands/tests/test_workflow_lint.py@@ -31,6 +31,7 @@ from hogli_commands.workflow_lint.checks.mcp_filter_coverage import McpFilterCovfrom hogli_commands.workflow_lint.checks.pr_concurrency import PrConcurrencyCheckfrom hogli_commands.workflow_lint.checks.pr_event_fanout import PrEventFanoutCheckfrom hogli_commands.workflow_lint.checks.required_gates import RequiredGateCheck+from hogli_commands.workflow_lint.checks.reusable_secret_passthrough import ReusableSecretPassthroughCheckfrom hogli_commands.workflow_lint.checks.semgrep_services_coverage import SemgrepServicesCoverageCheckfrom hogli_commands.workflow_lint.cli import cmd_lint_workflowsfrom hogli_commands.workflow_lint.model import PR_TRIGGERS, Workflow, WorkflowParseError, read_workflows@@ -1885,3 +1886,121 @@ class TestLiveTreeSmoke:workflows = list(read_workflows(workflows_dir))for check in CHECKS:assert isinstance(check.run(workflows), CheckResult)+++class TestReusableSecretPassthroughCheck:+ @staticmethod+ def _callee(required: bool, reads: bool = True) -> str:+ env = "T: ${{ secrets.NEEDED }}" if reads else "T: static"+ return f"""+ name: R+ on:+ workflow_call:+ secrets:+ NEEDED:+ required: {str(required).lower()}+ jobs:+ build:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - run: echo+ env:+ {env}+ """++ @pytest.mark.parametrize(+ "on_block",+ ["on:\n workflow_call:", "on: workflow_call", "on: [workflow_call, push]"],+ ids=["empty-mapping", "scalar", "list"],+ )+ def test_flags_a_read_the_callee_never_declares(self, tmp_path: Path, on_block: str) -> None:+ _write(+ tmp_path,+ "_callee.yml",+ "name: R\n"+ + on_block+ + "\njobs:\n build:\n runs-on: ubuntu-latest\n timeout-minutes: 5\n"+ + " steps:\n - run: echo\n env:\n T: ${{ secrets.NEVER_ARRIVES }}\n",+ )+ issues = ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues+ assert len(issues) == 1, [i.render() for i in issues]+ assert "does not declare it" in issues[0].message++ def test_reads_come_only_from_expressions(self, tmp_path: Path) -> None:+ _write(+ tmp_path,+ "_callee.yml",+ """+ name: R+ # Needs secrets.COMMENTED_ONLY to be configured in the repo.+ on:+ workflow_call:+ jobs:+ build:+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - run: echo secrets.SHELL_LITERAL_ONLY+ env:+ T: ${{ secrets['BRACKETED'] }}+ """,+ )+ issues = ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues+ assert [i.message.split(" ")[1] for i in issues] == ["secrets.BRACKETED"], [i.render() for i in issues]++ @pytest.mark.parametrize("reads", [True, False], ids=["read", "declared-only"])+ def test_flags_a_caller_omitting_a_required_secret(self, tmp_path: Path, reads: bool) -> None:+ _write(tmp_path, "_callee.yml", self._callee(required=True, reads=reads))+ _write(+ tmp_path,+ "caller.yml",+ """+ name: C+ on: [push]+ jobs:+ call:+ uses: ./.github/workflows/_callee.yml+ """,+ )+ issues = ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues+ assert len(issues) == 1, [i.render() for i in issues]+ assert issues[0].job == "call"+ assert "does not pass it" in issues[0].message++ def test_allows_a_caller_omitting_an_optional_secret(self, tmp_path: Path) -> None:+ # `required: false` is the callee sanctioning absence, which callers rely on+ # to withhold a publish credential from a dry-run build.+ _write(tmp_path, "_callee.yml", self._callee(required=False))+ _write(+ tmp_path,+ "caller.yml",+ """+ name: C+ on: [push]+ jobs:+ call:+ uses: ./.github/workflows/_callee.yml+ """,+ )+ assert ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues == []++ @pytest.mark.parametrize(+ "secrets_block",+ [+ " secrets: inherit",+ " secrets:\n NEEDED: ${{ secrets.SOME_OTHER_NAME }}",+ ],+ ids=["inherit", "renamed-passthrough"],+ )+ def test_satisfied_by_inherit_or_a_renamed_passthrough(self, tmp_path: Path, secrets_block: str) -> None:+ _write(tmp_path, "_callee.yml", self._callee(required=True))+ _write(+ tmp_path,+ "caller.yml",+ "name: C\non: [push]\njobs:\n call:\n uses: ./.github/workflows/_callee.yml\n"+ + secrets_block+ + "\n",+ )+ issues = ReusableSecretPassthroughCheck().run(_read_all(tmp_path)).issues+ assert issues == [], [i.render() for i in issues]diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.pyindex 49e3f9614324..640b2e7e8acc 100644--- a/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/__init__.py@@ -20,6 +20,7 @@ from .mcp_filter_coverage import McpFilterCoverageCheckfrom .pr_concurrency import PrConcurrencyCheckfrom .pr_event_fanout import PrEventFanoutCheckfrom .required_gates import RequiredGateCheck+from .reusable_secret_passthrough import ReusableSecretPassthroughCheckfrom .semgrep_services_coverage import SemgrepServicesCoverageCheckCHECKS: list[WorkflowCheck] = [@@ -32,6 +33,7 @@ CHECKS: list[WorkflowCheck] = [RequiredGateCheck(),PrEventFanoutCheck(),McpFilterCoverageCheck(),+ ReusableSecretPassthroughCheck(),]diff --git a/tools/hogli-commands/hogli_commands/workflow_lint/checks/reusable_secret_passthrough.py b/tools/hogli-commands/hogli_commands/workflow_lint/checks/reusable_secret_passthrough.pynew file mode 100644index 000000000000..b7ec12a42ed5--- /dev/null+++ b/tools/hogli-commands/hogli_commands/workflow_lint/checks/reusable_secret_passthrough.py@@ -0,0 +1,172 @@+"""A reusable workflow's secret reads must be declared and passed by every caller.++Secrets do not flow into a ``workflow_call`` workflow on their own. A name the+callee reads must be declared under ``on.workflow_call.secrets`` and then+passed by each caller, or inherited wholesale with ``secrets: inherit``.+Miss either half and the reference interpolates to an empty string.++Nothing fails loudly when that happens. ``ci-turbo.yml`` once read an App+private key while declaring no secrets at all, so its token step failed under+``continue-on-error`` and the install fell back to ``github.token``, which lost+the dedicated rate-limit bucket the App exists to provide, with a green check+either way.++Two rules, because the halves fail independently:++- an undeclared read can never receive a value, whoever calls it;+- a secret declared ``required: true`` must be passed by every caller, whether+ or not the callee reads it directly, because GitHub refuses to start the call+ without it.++The second rule follows the declaration rather than second-guessing it.+``required: false`` is the callee saying it tolerates absence, and callers rely+on that: a smoke-test build deliberately withholds the symbol upload key so it+does not publish symbols. Mark a secret ``required: true`` when every caller+must supply it.++Reads are collected from ``${{ }}`` expressions in the parsed YAML only. A+``secrets.X`` in a YAML comment or in shell text outside an expression is not a+read, and a bracket reference such as ``secrets['X']`` is.++A caller that passes a differently named secret through to the callee's input+satisfies the second rule. The mapping is what matters, not the name matching.+"""++from __future__ import annotations++import re+from collections.abc import Iterator++from ..check import CheckResult, Issue, WorkflowCheck+from ..model import Workflow++LOCAL_CALL_PREFIX = "./.github/workflows/"+INHERIT = "inherit"++# GITHUB_TOKEN is minted per run and reaches every job, so it is never declared.+IMPLICIT_SECRETS = frozenset({"GITHUB_TOKEN"})++_EXPRESSION = re.compile(r"\$\{\{(.*?)\}\}", re.DOTALL)+_SECRET_REF = re.compile(r"""\bsecrets(?:\.([A-Za-z0-9_]+)|\[\s*['"]([A-Za-z0-9_]+)['"]\s*\])""")+++def _call_block(wf: Workflow) -> dict | None:+ """The ``workflow_call`` trigger body, ``{}`` when it declares nothing, ``None`` when absent."""+ on = wf.on+ if isinstance(on, str):+ return {} if on == "workflow_call" else None+ if isinstance(on, list):+ return {} if "workflow_call" in on else None+ if not isinstance(on, dict):+ return None+ call = on.get("workflow_call")+ if call is None and "workflow_call" in on:+ # `workflow_call:` with an empty body parses to None but is still callable.+ return {}+ return call if isinstance(call, dict) else None+++def _declared(call: dict) -> set[str]:+ secrets = call.get("secrets")+ return set(secrets.keys()) if isinstance(secrets, dict) else set()+++def _required(call: dict) -> set[str]:+ secrets = call.get("secrets")+ if not isinstance(secrets, dict):+ return set()+ return {name for name, body in secrets.items() if isinstance(body, dict) and body.get("required") is True}+++def _strings(node: object) -> Iterator[str]:+ if isinstance(node, str):+ yield node+ elif isinstance(node, dict):+ for key, value in node.items():+ yield from _strings(key)+ yield from _strings(value)+ elif isinstance(node, list):+ for item in node:+ yield from _strings(item)+++def _reads(wf: Workflow) -> set[str]:+ reads: set[str] = set()+ for text in _strings(wf.raw):+ for expression in _EXPRESSION.findall(text):+ for dotted, bracketed in _SECRET_REF.findall(expression):+ reads.add(dotted or bracketed)+ return reads - IMPLICIT_SECRETS+++def _callee_name(uses: str) -> str | None:+ if not uses.startswith(LOCAL_CALL_PREFIX):+ return None+ return uses[len(LOCAL_CALL_PREFIX) :].partition("@")[0]+++class ReusableSecretPassthroughCheck(WorkflowCheck):+ id = "WF010-reusable-secret-passthrough"+ label = "reusable secret pass-through"+ description = "reusable workflows declare the secrets they read, and callers pass the required ones"++ @property+ def fix_hint(self) -> str | None:+ return (+ "Declare the secret under `on.workflow_call.secrets` in the called workflow, "+ "then pass it from every caller's `secrets:` block (or use `secrets: inherit`)."+ )++ def run(self, workflows: list[Workflow]) -> CheckResult:+ result = CheckResult()++ callable_workflows: dict[str, tuple[Workflow, set[str], set[str]]] = {}+ for wf in workflows:+ call = _call_block(wf)+ if call is None:+ continue+ declared = _declared(call)+ reads = _reads(wf)+ callable_workflows[wf.path.name] = (wf, _required(call), reads - declared)++ for name, (wf, _needed, undeclared_reads) in sorted(callable_workflows.items()):+ for secret in sorted(undeclared_reads):+ result.issues.append(+ Issue(+ workflow=name,+ message=(+ f"reads secrets.{secret} but does not declare it under "+ "on.workflow_call.secrets, so it is always empty"+ ),+ file=str(wf.path),+ )+ )++ for caller in workflows:+ for job in caller.jobs:+ if job.uses is None:+ continue+ callee_name = _callee_name(job.uses)+ if callee_name is None or callee_name not in callable_workflows:+ continue++ _callee_wf, needed, _undeclared = callable_workflows[callee_name]+ if not needed:+ continue++ passed_block = job.raw.get("secrets")+ if passed_block == INHERIT:+ continue+ passed = set(passed_block.keys()) if isinstance(passed_block, dict) else set()++ for secret in sorted(needed - passed):+ result.issues.append(+ Issue(+ workflow=caller.path.name,+ job=job.name,+ message=f"calls {callee_name}, which requires secrets.{secret}, but does not pass it",+ file=str(caller.path),+ )+ )++ return result