"""Credential broker. Mints one short-lived, audience-bound, scope-limited JWT per agent run. The token is the intersection of what the role allows and what the run asks for (like an AWS session policy, which can only reduce a role's permissions).""" import json, time, uuid, pathlib, jwt HERE = pathlib.Path(__file__).parent ROLES = json.loads((HERE / "roles.json").read_text()) PRIVATE = (HERE / "broker-private.pem").read_bytes() ISSUER = "http://broker.local" class Refused(Exception): pass def mint(agent: str, run_id: str, audience: str, scopes: list[str], ttl: int) -> str: role = ROLES.get(agent) if role is None: raise Refused(f"unknown agent {agent}") allowed = role["allowed"].get(audience) if allowed is None: raise Refused(f"{agent} has no access to audience {audience}") extra = sorted(set(scopes) - set(allowed)) if extra: raise Refused(f"{agent} may not hold {extra} on {audience}") if not 1 <= ttl <= role["max_ttl_seconds"]: raise Refused(f"ttl must be 1..{role['max_ttl_seconds']} seconds") now = int(time.time()) claims = {"iss": ISSUER, "sub": f"agent:{agent}", "aud": audience, "scope": " ".join(sorted(scopes)), "iat": now, "exp": now + ttl, "jti": str(uuid.uuid4()), "run": run_id} return jwt.encode(claims, PRIVATE, algorithm="RS256") def mint_static_admin() -> str: """What the setup looks like WITHOUT the control: one shared, year-long, every-scope credential. Only used by the tests to show them failing.""" now = int(time.time()) claims = {"iss": ISSUER, "sub": "svc:shared-admin", "aud": ["tickets-api", "billing-api"], "scope": "tickets:read tickets:comment tickets:delete refunds:read refunds:write", "iat": now, "exp": now + 365 * 86400, "jti": "static", "run": "none"} return jwt.encode(claims, PRIVATE, algorithm="RS256")