feat(policy): netkingdom maturity-gated publication-scope policy

Token scope is now bound to package maturity, gated on netkingdom's own maturity:
- maturity-build -> gitea-wide, maturity-test -> org-wide, maturity-prod -> repo-scoped
  (scope narrows as stakes rise; broad tokens only for low-stakes build artifacts)
- the graduated table is DORMANT until netkingdom reaches production grade; until
  then every lane clamps to repo-scope, injected as NPM_AUTH_TOKEN (fail-safe)
- token env-var name signals blast radius: NPM_AUTH_TOKEN (repo default),
  NPM_AUTH_COULOMB_TOKEN (org), NPM_AUTH_GITEA_TOKEN (gitea), NPM_AUTH_WHYNOT_TOKEN
  (npm scope, defined but unused), NPM_AUTH_WHYNOTDESIGN (explicit repo)

netkingdom is at maturity-build today, so whynot-design resolves to repo-scope /
NPM_AUTH_TOKEN. Flip netkingdom_maturity to maturity-prod to activate graduation.

- policies/netkingdom-publication-scope.yaml: the policy data + gate
- publication_policy.py: load + resolve (clamp/active, env naming, override)
- exec delivery injects under the resolved env-var name (was fixed SE_NPM_TOKEN)
- catalog lane carries delivery_config.npm.maturity
- new CLI: `secrets-engine policy publication <lane>`
- docs/publication-scope-policy.md; tests for clamp, graduation, naming, override

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
tegwick 2026-06-28 13:14:46 +02:00
parent f87f4e5e4d
commit 5b48033bce
11 changed files with 394 additions and 9 deletions

View file

@ -211,6 +211,27 @@ def cmd_exec(cfg: Config, args) -> int:
return rc
def cmd_policy_publication(cfg: Config, args) -> int:
from secrets_engine.publication_policy import PublicationPolicy, resolve
entry = get_entry(cfg.catalog_dir, args.catalog_id)
npm = entry.npm
if not npm:
from secrets_engine.errors import PolicyGuardError
raise PolicyGuardError(f"lane '{entry.id}' has no npm delivery config")
policy = PublicationPolicy.load(cfg.policy_dir)
res = resolve(
policy,
org=entry.org, repo=entry.repo, npm_scope=npm.get("scope", ""),
package_maturity=npm.get("maturity", "maturity-build"),
token_env_override=npm.get("token_env", ""),
)
print(f"lane: {entry.id} ({entry.owner})")
print(f"netkingdom maturity: {policy.netkingdom_maturity} "
f"(production_grade={policy.production_grade})")
print(res.render())
return 0
def cmd_route(cfg: Config, args) -> int:
entry = get_entry(cfg.catalog_dir, args.catalog_id)
client = OpenBaoClient.resolve(cfg.bao_addr)
@ -306,6 +327,12 @@ def build_parser() -> argparse.ArgumentParser:
help="command after '--'")
ex.set_defaults(func=cmd_exec)
po = sub.add_parser("policy", help="inspect secrets-engine policies")
posub = po.add_subparsers(dest="subcmd", required=True)
popub = posub.add_parser("publication", help="resolve a lane's publication scope + token env")
popub.add_argument("catalog_id")
popub.set_defaults(func=cmd_policy_publication)
ro = sub.add_parser("route", help="ops-warden routing pointer for a lane")
ro.add_argument("catalog_id")
ro.add_argument("--json", action="store_true")

View file

@ -27,9 +27,29 @@ from typing import Iterator
from secrets_engine.catalog import CatalogEntry
from secrets_engine.errors import DeliveryError
from secrets_engine.openbao import OpenBaoClient
from secrets_engine.publication_policy import PublicationPolicy, resolve
from secrets_engine.redact import redact_text
def resolve_npm_token_env(entry: CatalogEntry, *, policy_dir=None) -> str:
"""Resolve the env-var name to inject for a lane via the publication policy."""
if policy_dir is None:
from secrets_engine.config import Config
policy_dir = Config.load().policy_dir
npm = entry.npm
policy = PublicationPolicy.load(policy_dir)
res = resolve(
policy,
org=entry.org,
repo=entry.repo,
npm_scope=npm.get("scope", ""),
package_maturity=npm.get("maturity", "maturity-build"),
token_env_override=npm.get("token_env", ""),
)
return res.token_env
def _fetch_value(client: OpenBaoClient, entry: CatalogEntry, field: str) -> str:
"""Read the field value via an approle-scoped token. Held in memory only."""
try:
@ -58,11 +78,13 @@ def _registry_authkey(registry: str) -> str:
@contextmanager
def _npm_userconfig(registry: str, scope: str) -> Iterator[Path]:
def _npm_userconfig(registry: str, scope: str, token_env: str) -> Iterator[Path]:
"""Write a mode-0600 temp .npmrc for the configured registry/scope.
The token itself is NOT written to the file npm expands ${SE_NPM_TOKEN}
from the child environment, so the value never touches disk.
The token itself is NOT written to the file npm expands ${<token_env>}
from the child environment, so the value never touches disk. `token_env` is
resolved from the netkingdom publication-scope policy, so its name reflects
the lane's effective publication scope.
"""
fd, name = tempfile.mkstemp(prefix="se-npmrc-", suffix=".ini")
path = Path(name)
@ -72,7 +94,7 @@ def _npm_userconfig(registry: str, scope: str) -> Iterator[Path]:
with os.fdopen(fd, "w") as fh:
# e.g. @whynot:registry=https://gitea.coulomb.social/api/packages/coulomb/npm/
fh.write(f"{scope}:registry={registry}\n")
fh.write(f"{authkey}:_authToken=${{SE_NPM_TOKEN}}\n")
fh.write(f"{authkey}:_authToken=${{{token_env}}}\n")
yield path
finally:
try:
@ -96,6 +118,7 @@ def exec_with_secret(
command: list[str],
*,
mode: str = "auto",
policy_dir=None,
) -> int:
"""Run `command` with the lane's secret injected for the child only.
@ -132,9 +155,10 @@ def exec_with_secret(
f"lane '{entry.id}' npm-config delivery needs "
"delivery_config.npm.registry and .scope"
)
with _npm_userconfig(registry, scope) as npmrc:
token_env = resolve_npm_token_env(entry, policy_dir=policy_dir)
with _npm_userconfig(registry, scope, token_env) as npmrc:
child_env["NPM_CONFIG_USERCONFIG"] = str(npmrc)
child_env["SE_NPM_TOKEN"] = value
child_env[token_env] = value
rc = _spawn(command, child_env, value)
return rc

View file

@ -0,0 +1,144 @@
"""netkingdom publication-scope policy: bind npm publication scope to maturity.
Resolves, for a publish lane, the *effective* publication scope and the token
env-var name to inject. The graduated maturity->scope table only activates once
netkingdom is production grade; until then every lane clamps to repo-scope
(fail-safe). This is the policy-binding the catalog data feeds into.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
from secrets_engine.errors import PolicyGuardError
VALID_MATURITY = ("maturity-build", "maturity-test", "maturity-prod")
VALID_SCOPES = ("gitea", "org", "scope", "repo")
# Narrow (small index) to broad (large index) — repo is narrowest, gitea broadest.
SCOPE_BREADTH = {"repo": 0, "scope": 1, "org": 2, "gitea": 3}
@dataclass(frozen=True)
class PublicationPolicy:
domain: str
netkingdom_maturity: str
maturity_scope: dict[str, str]
dormant_scope: str
token_env: dict[str, str]
raw: dict[str, Any]
@property
def production_grade(self) -> bool:
return self.netkingdom_maturity == "maturity-prod"
@classmethod
def load(cls, policy_dir: Path) -> "PublicationPolicy":
path = Path(policy_dir) / "netkingdom-publication-scope.yaml"
if not path.exists():
raise PolicyGuardError(f"publication-scope policy not found: {path}")
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
maturity = data.get("netkingdom_maturity")
if maturity not in VALID_MATURITY:
raise PolicyGuardError(
f"{path}: netkingdom_maturity '{maturity}' invalid; {VALID_MATURITY}"
)
return cls(
domain=data.get("domain", "netkingdom"),
netkingdom_maturity=maturity,
maturity_scope=data.get("maturity_scope", {}),
dormant_scope=data.get("dormant_scope", "repo"),
token_env=data.get("token_env", {}),
raw=data,
)
@dataclass(frozen=True)
class Resolution:
package_maturity: str
effective_scope: str
token_env: str
active: bool # is the graduated table in effect?
clamped: bool # was a broader maturity scope clamped to dormant_scope?
rationale: str
def render(self) -> str:
return (
f" netkingdom production-grade: {self.active}\n"
f" package maturity: {self.package_maturity}\n"
f" effective publication scope: {self.effective_scope}"
f"{' (clamped from graduated table — fail-safe)' if self.clamped else ''}\n"
f" inject token as env var: {self.token_env}\n"
f" rationale: {self.rationale}"
)
def _slug(value: str) -> str:
"""COULOMB / WHYNOT / WHYNOTDESIGN — upper, strip @ and non-alphanumerics."""
return re.sub(r"[^A-Za-z0-9]", "", value).upper()
def _render_env(template: str, *, org: str, npm_scope: str, repo: str) -> str:
return (
template.replace("{ORG}", _slug(org))
.replace("{SCOPE}", _slug(npm_scope))
.replace("{REPO}", _slug(repo))
)
def resolve(
policy: PublicationPolicy,
*,
org: str,
repo: str,
npm_scope: str,
package_maturity: str,
token_env_override: str = "",
) -> Resolution:
"""Resolve effective scope + token env for a lane under the policy."""
if package_maturity not in VALID_MATURITY:
raise PolicyGuardError(
f"package maturity '{package_maturity}' invalid; {VALID_MATURITY}"
)
if not policy.production_grade:
effective = policy.dormant_scope
graduated = policy.maturity_scope.get(package_maturity, effective)
clamped = SCOPE_BREADTH[graduated] > SCOPE_BREADTH[effective]
rationale = (
f"netkingdom is '{policy.netkingdom_maturity}', not production grade — "
f"graduated scoping is dormant; clamped to '{effective}'"
if clamped
else f"netkingdom dormant; lane already at safe scope '{effective}'"
)
active = False
else:
effective = policy.maturity_scope.get(package_maturity)
if effective not in VALID_SCOPES:
raise PolicyGuardError(
f"no scope mapped for maturity '{package_maturity}'"
)
clamped = False
active = True
rationale = (
f"netkingdom production grade — {package_maturity} maps to "
f"'{effective}' publication scope"
)
if token_env_override:
token_env = token_env_override
else:
template = policy.token_env.get(effective, "NPM_AUTH_TOKEN")
token_env = _render_env(template, org=org, npm_scope=npm_scope, repo=repo)
return Resolution(
package_maturity=package_maturity,
effective_scope=effective,
token_env=token_env,
active=active,
clamped=clamped,
rationale=rationale,
)