Skip to content

livery.workshop._security

livery.workshop._security

Security verification for admin-secret isolation and privilege boundaries.

Provides offline and live checks for fm security.check and the fm doctor security section, plus the three-tier secret exposure summary. Reads contracts, CODEOWNERS, and generated workflow files strictly with the standard library so it stays free of dev-only extras.

Classes:

Name Description
TierEntry

One row in the three-tier CI secret exposure summary.

Functions:

Name Description
secret_tiers

Classify the workspace's declared CI credentials into Tiers 1, 2, and 3.

offline_security_findings

Run all offline admin-secret isolation checks against root.

live_security_findings

Run live forge checks for protection, environments, and secret scopes.

security_findings

Combined offline and (when authenticated) live security findings.

format_tier_summary

Render the human-readable three-tier CI secret exposure summary.

security_check

Verify admin-secret isolation, CODEOWNERS boundaries, and secret scopes.

Attributes:

Name Type Description
security
PRIVILEGED_SECRETS tuple[str, ...]
SECRET_ROLES dict[str, str]

security module-attribute

security = group('security', help='Verify admin-secret isolation and privilege boundaries')

PRIVILEGED_SECRETS module-attribute

PRIVILEGED_SECRETS: tuple[str, ...] = ('FORGE_ADMIN_TOKEN', 'FORGE_TOKEN', 'PYPI_TOKEN', 'UV_PUBLISH_TOKEN', 'GITLAB_PUSH_TOKEN')

SECRET_ROLES module-attribute

SECRET_ROLES: dict[str, str] = {'FORGE_ADMIN_TOKEN': 'govern', 'FORGE_TOKEN': 'bot', 'PYPI_TOKEN': 'pypi', 'UV_PUBLISH_TOKEN': 'pypi'}

TierEntry dataclass

TierEntry(tier: int, secret: str, scope: str, jobs: str, exposure: str)

One row in the three-tier CI secret exposure summary.

Attributes:

Name Type Description
tier int

Exposure tier (1 = isolated privileged, 2 = trusted-branch workspace, 3 = PR-reachable / repository-scoped).

secret str

Credential name or mechanism.

scope str

Where the credential is scoped (environment or branch rule).

jobs str

CI jobs receiving the credential.

exposure str

Plain statement of who can read or exfiltrate it.

tier instance-attribute

tier: int

secret instance-attribute

secret: str

scope instance-attribute

scope: str

jobs instance-attribute

jobs: str

exposure instance-attribute

exposure: str

secret_tiers

secret_tiers(root: Path) -> tuple[TierEntry, ...]

Classify the workspace's declared CI credentials into Tiers 1, 2, and 3.

Source code in packages/workshop/src/livery/workshop/_security.py
def secret_tiers(root: Path) -> tuple[TierEntry, ...]:
    """Classify the workspace's declared CI credentials into Tiers 1, 2, and 3."""
    contract = load_contract(root / "workshop.toml")
    kind = str((contract.get("forge") or {}).get("kind", ""))
    envs = ci_environments(contract)
    if kind == "gitlab":
        govern_scope = "protected CI variable (main only)"
        bot_scope = "protected CI variable (main only)"
        pypi_scope = "protected CI variable (main only)"
    elif kind == "gitea":
        govern_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
        bot_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
        pypi_scope = "unscoped (Gitea Actions lacks branch-scoped secrets)"
    else:
        govern_scope = f"environment {envs['govern']!r} (protected branches)"
        bot_scope = f"environment {envs['bot']!r} (protected branches)"
        pypi_scope = f"environment {envs['pypi']!r} (protected branches)"
    return (
        TierEntry(
            tier=1,
            secret="FORGE_ADMIN_TOKEN",
            scope=govern_scope,
            jobs="govern (isolated python3 -I)",
            exposure=(
                "protected from unmerged PRs and merged packages/*/ code"
                if kind != "gitea"
                else "exposed on same-repo branches; require forks or desk-only"
            ),
        ),
        TierEntry(
            tier=1,
            secret="PYPI_TOKEN / OIDC",
            scope=pypi_scope,
            jobs="publish (isolated python3 -I)",
            exposure=(
                "protected from unmerged PRs and merged packages/*/ code"
                if kind != "gitea"
                else "exposed on same-repo branches; require forks"
            ),
        ),
        TierEntry(
            tier=2,
            secret="FORGE_TOKEN (and any in-workspace extension credentials)",
            scope=bot_scope,
            jobs="nightly / workspace jobs on main",
            exposure=(
                "protected from unmerged PRs, NOT from merged packages/*/ code:"
                " any contributor who can merge package code can read Tier 2"
                " secrets"
            ),
        ),
        TierEntry(
            tier=3,
            secret="PR-wired or repo-scoped secrets",
            scope="pull_request jobs or GitHub repo secrets",
            jobs="disallowed",
            exposure=(
                "exfiltrable without merging; any repo-scoped secret on GitHub"
                " or PR-wired secret is a failure"
            ),
        ),
    )

offline_security_findings

offline_security_findings(root: Path) -> list[Finding]

Run all offline admin-secret isolation checks against root.

Source code in packages/workshop/src/livery/workshop/_security.py
def offline_security_findings(root: Path) -> list[Finding]:
    """Run all offline admin-secret isolation checks against *root*."""
    contract = load_contract(root / "workshop.toml")
    root_users, root_teams, root_approvals = owners_of(contract)
    findings: list[Finding] = []
    prog = footman.prog()

    if not (root_users or root_teams):
        findings.append(
            Finding(
                "security: owners",
                "no root [owners] declared; privileged paths are unguarded",
                "add [owners] users/teams and approvals >= 1 to workshop.toml,"
                f" then run `{prog} sync`",
            )
        )
    elif root_approvals == 0:
        findings.append(
            Finding(
                "security: owners: solo/unprotected mode (approvals = 0;"
                " admin-secret isolation requires approvals >= 1)"
            )
        )
    else:
        findings.append(
            Finding(
                f"security: owners: root [owners] requires {root_approvals} approval(s)"
            )
        )

    findings.extend(_check_codeowners(root))
    findings.extend(_check_workflows(root))
    return findings

live_security_findings

live_security_findings(root: Path, forge: Forge, repo: Repository) -> list[Finding]

Run live forge checks for protection, environments, and secret scopes.

Source code in packages/workshop/src/livery/workshop/_security.py
def live_security_findings(root: Path, forge: Forge, repo: Repository) -> list[Finding]:
    """Run live forge checks for protection, environments, and secret scopes."""
    from livery.workshop._workflow_tasks import required_context_string

    contract = load_contract(root / "workshop.toml")
    forge_table = contract.get("forge") or {}
    kind = str(forge_table.get("kind", ""))
    ci_table = contract.get("ci") or {}
    context = str(ci_table.get("required-context") or "gate")
    expected_ctx = required_context_string(kind, context)
    gov = governance_config(root)
    highest = gov.min_approvals or 0
    envs = ci_environments(contract)
    prog = footman.prog()
    findings: list[Finding] = []

    protection = repo.protection("main")
    if protection is None:
        findings.append(
            Finding(
                "security: protection",
                "default branch 'main' has no branch protection",
                f"run `{prog} workflow.configure`",
            )
        )
    else:
        if (
            forge.supports("required_contexts")
            and expected_ctx not in protection.required_contexts
        ):
            findings.append(
                Finding(
                    "security: protection",
                    f"default branch protection does not require {expected_ctx!r}",
                    f"run `{prog} workflow.configure`",
                )
            )
        if highest >= 1:
            if forge.supports("min_approvals"):
                if protection.required_approvals < highest:
                    findings.append(
                        Finding(
                            "security: protection",
                            f"required_approvals is {protection.required_approvals},"
                            f" expected >= {highest}",
                            f"run `{prog} workflow.configure`",
                        )
                    )
                if protection.require_codeowner_review is not True:
                    findings.append(
                        Finding(
                            "security: protection",
                            "require_codeowner_review is not enabled on default branch",
                            f"run `{prog} workflow.configure`",
                        )
                    )
            if (
                forge.supports("dismiss_stale_reviews")
                and not protection.dismiss_stale_reviews
            ):
                findings.append(
                    Finding(
                        "security: protection",
                        "dismiss_stale_reviews is disabled on default branch",
                        f"run `{prog} workflow.configure`",
                    )
                )

    if kind == "github":
        existing_envs = {env.name: env for env in repo.environments()}
        for env_name in dict.fromkeys(envs.values()):
            info = existing_envs.get(env_name)
            if info is None:
                findings.append(
                    Finding(
                        "security: environments",
                        f"GitHub environment {env_name!r} is missing",
                        f"run `{prog} workflow.configure` to create and lock it",
                    )
                )
            elif not info.protected_branches_only:
                findings.append(
                    Finding(
                        "security: environments",
                        f"GitHub environment {env_name!r} is not restricted to"
                        " protected branches",
                        f"run `{prog} workflow.configure` to lock {env_name!r}",
                    )
                )
            else:
                env_secrets = [s.name for s in repo.secret_names(environment=env_name)]
                listed = ", ".join(env_secrets) if env_secrets else "none"
                findings.append(
                    Finding(
                        f"security: environment {env_name}: protected branches"
                        f" only (secrets: {listed})"
                    )
                )
        for secret in repo.secret_names():
            findings.append(
                Finding(
                    "security: secrets",
                    f"repository-scoped secret {secret.name} is readable by any"
                    " same-repo branch on GitHub",
                    f"move it with `{prog} workflow.secret.set {secret.name}`"
                    " and delete the repository-level secret",
                )
            )
    elif kind == "gitlab":
        variables = repo.secret_names()
        for var in variables:
            if var.name in PRIVILEGED_SECRETS and not var.protected:
                findings.append(
                    Finding(
                        "security: secrets",
                        f"CI variable {var.name} is unprotected (protected=False)",
                        f"run `{prog} workflow.secret.set {var.name}` to mark it"
                        " protected",
                    )
                )
        if not forge.supports("min_approvals"):
            findings.append(
                Finding(
                    "security: gitlab-free: CODEOWNERS enforcement and"
                    " reset_approvals_on_push are licence-gated on GitLab"
                    " Free/CE; isolation relies on Maintainer-only merge to main"
                )
            )
    elif kind == "gitea":
        findings.append(
            Finding(
                "security: gitea: Gitea Actions lacks branch-scoped secrets;"
                " require fork-only contributions or keep FORGE_ADMIN_TOKEN off"
                f" CI and run `{prog} workflow.configure` from a maintainer's"
                " desk"
            )
        )

    if not any(f.found for f in findings):
        findings.append(
            Finding("security: live: forge protection and secret scopes verified")
        )
    return findings

security_findings

security_findings(root: Path, *, forge: Forge | None = None, repo: Repository | None = None, offline: bool = False) -> list[Finding]

Combined offline and (when authenticated) live security findings.

Source code in packages/workshop/src/livery/workshop/_security.py
def security_findings(
    root: Path,
    *,
    forge: Forge | None = None,
    repo: Repository | None = None,
    offline: bool = False,
) -> list[Finding]:
    """Combined offline and (when authenticated) live security findings."""
    findings = offline_security_findings(root)
    if offline:
        return findings
    contract = load_contract(root / "workshop.toml")
    kind = str((contract.get("forge") or {}).get("kind", ""))
    if not kind:
        return findings
    try:
        if forge is None or repo is None:
            from livery.workshop._forge_lane import this_forge, this_repository

            forge = forge or this_forge(root)
            repo = repo or this_repository(root)
        findings.extend(live_security_findings(root, forge, repo))
    except Exception as error:
        findings.append(Finding(f"security: live checks skipped ({error})"))
    return findings

format_tier_summary

format_tier_summary(root: Path) -> str

Render the human-readable three-tier CI secret exposure summary.

Source code in packages/workshop/src/livery/workshop/_security.py
def format_tier_summary(root: Path) -> str:
    """Render the human-readable three-tier CI secret exposure summary."""
    lines = ["Secret exposure tiers:"]
    for entry in secret_tiers(root):
        lines.append(
            f"  Tier {entry.tier} | {entry.secret} | {entry.scope} | {entry.jobs}"
        )
        lines.append(f"         {entry.exposure}")
    return "\n".join(lines)

security_check

security_check(offline: Annotated[bool, doc('skip live forge API checks')] = False) -> None

Verify admin-secret isolation, CODEOWNERS boundaries, and secret scopes.

Runs offline checks against workshop.toml, CODEOWNERS, and generated workflows, then queries the forge for branch protection, protected environments, and misplaced repository-level secrets unless --offline is passed. Prints the three-tier secret exposure summary and fails if any standing security issue is found.

Source code in packages/workshop/src/livery/workshop/_security.py
@security.task(name="check")
def security_check(
    offline: Annotated[bool, doc("skip live forge API checks")] = False,
) -> None:
    """Verify admin-secret isolation, CODEOWNERS boundaries, and secret scopes.

    Runs offline checks against ``workshop.toml``, ``CODEOWNERS``, and
    generated workflows, then queries the forge for branch protection,
    protected environments, and misplaced repository-level secrets
    unless ``--offline`` is passed. Prints the three-tier secret
    exposure summary and fails if any standing security issue is found.
    """
    root = workspace_root()
    if root is None:
        fail("no workspace: no workshop.toml above the working directory")
    findings = security_findings(root, offline=offline)
    failures: list[Finding] = []
    for finding in findings:
        if finding.found:
            failures.append(finding)
            print(f"  FAIL  {finding.what}: {finding.found}")
            if finding.fix:
                print(f"        fix: {finding.fix}")
        elif (
            "solo/unprotected" in finding.what
            or "gitlab-free" in finding.what
            or "gitea:" in finding.what
            or "skipped" in finding.what
        ):
            print(f"  WARN  {finding.what}")
        else:
            print(f"  ok    {finding.what}")
    print()
    print(format_tier_summary(root))
    if failures:
        fail(f"security.check found {len(failures)} standing issue(s)")