fix(ci): narrow Auth.js subject and extend disposable P05 verification

This commit is contained in:
Vib Tools committed 2026-11-22 05:24:04 -08:00
1 parent 42adaba004
commit c27fe3d323
23 files changed
+415 -45

No files matched your search

+3 -1
View File
@@ -5,4 +5,6 @@
| [README.md](README.md) | CI-only test boundaries and safety constraints | P05-CI-01 |
| [MINIFEST.md](MINIFEST.md) | Exact tests/ci direct-file register | P05-CI-01 |
| [source_contract.py](source_contract.py) | Source and lockfile structural checks, no network/secrets | P05-CI-01 |
| [oidc_discovery.py](oidc_discovery.py) | Disposable ZITADEL ready/discovery/JWKS smoke only | P05-CI-01 |
| [oidc_discovery.py](oidc_discovery.py) | Disposable ZITADEL ready/discovery/JWKS plus malformed issuer/JWKS negative contracts | P05-CI-01/P05-CI-02 |
| [account_negative.py](account_negative.py) | CI-only Account Portal unauthenticated 401/protected redirect smoke | P05-CI-02 |
| [advisory_triage.py](advisory_triage.py) | Extract registry audit advisory IDs/package/range/fix from npm/pnpm JSON | P05-CI-02 |
+3 -1
View File
@@ -3,7 +3,9 @@
This folder contains **CI-only** source/lockfile checks and OIDC discovery smoke support. Run these through the approved `.gitea/workflows/p05-ci.yml` on a disposable Linux runner.
- `source_contract.py` checks the narrow P05 source/package constraints and paths. It is not a typecheck or application test.
- `oidc_discovery.py` checks ZITADEL readiness, OIDC discovery, and the public JWKS endpoint on the **disposable** Docker network. It does NOT log in a user, check a real callback, prove protected routes or administer accounts.
- `oidc_discovery.py` checks ZITADEL readiness, OIDC discovery, JWKS and fail-closed issuer/JWKS negative fixtures on the **disposable** Docker network. It does NOT log in a user or check an authenticated callback.
- `account_negative.py` checks that an anonymous Account Portal call returns 401 and that a protected page redirects to `/signin`. It does NOT create a test user or prove real login.
- `advisory_triage.py` summarizes available npm/pnpm registry advisory JSON with IDs, ranges and fixes, without changing dependency versions.
No real credentials or production domains are used. Never print bootstrap PATs, admin secrets, session cookies or `.env` contents. Cleanup of disposable volumes is mandatory; never apply `docker compose down -v` to a user's non-CI stack.
+58
View File
@@ -0,0 +1,58 @@
"""CI-only negative access checks against a disposable Next.js account server.
No login, credential acquisition, mock positive authentication or real accounts.
"""
from __future__ import annotations
import os
import time
from urllib.error import HTTPError, URLError
from urllib.request import build_opener, HTTPRedirectHandler, Request
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def main() -> None:
base = os.environ.get("ZITPLANE_CI_ACCOUNT", "http://127.0.0.1:3001")
if base != "http://127.0.0.1:3001":
raise RuntimeError("Account probe must use only CI localhost:3001")
opener = build_opener(NoRedirect())
# Keep bounded startup polling; every other error is an actual test failure.
deadline = time.monotonic() + 30
while True:
try:
opener.open(Request(base + "/api/account/me"), timeout=3)
raise AssertionError("Unauthenticated identity API returned 200")
except HTTPError as exc:
if exc.code in (401, 500, 503) and time.monotonic() < deadline and exc.code != 401:
time.sleep(1)
continue
if exc.code != 401:
raise AssertionError(f"Expected API HTTP 401, got {exc.code}") from exc
if "no-store" not in exc.headers.get("Cache-Control", "").lower():
raise AssertionError("Unauthorized identity response must be no-store")
break
except URLError:
if time.monotonic() >= deadline:
raise
time.sleep(1)
print("ZITPLANE_ACCOUNT_UNAUTHENTICATED_API_401_PASS")
try:
opener.open(Request(base + "/account"), timeout=8)
raise AssertionError("Unauthenticated account page returned 200")
except HTTPError as exc:
if exc.code not in (302, 303, 307, 308):
raise AssertionError(f"Expected protected redirect, got HTTP {exc.code}") from exc
location = exc.headers.get("Location", "")
if not (location.endswith("/signin") or location == "/signin"):
raise AssertionError("Protected route redirects anywhere other than /signin")
print("ZITPLANE_ACCOUNT_PROTECTED_REDIRECT_PASS")
print("ZITPLANE_INTERACTIVE_LOGIN_E2E_DEFERRED")
if __name__ == "__main__":
main()
+83
View File
@@ -0,0 +1,83 @@
"""Summarize CI registry advisory JSON without changing dependencies.
npm: audit --omit=dev --json; pnpm: audit --prod --json.
High/critical gating is performed separately by the workflow.
"""
from __future__ import annotations
import json
from pathlib import Path
import sys
def read_report(path: str) -> dict:
report = json.loads(Path(path).read_text(encoding="utf-8"))
if not isinstance(report, dict) or (
"advisories" not in report and "vulnerabilities" not in report
):
raise ValueError("Unexpected or incomplete audit JSON; triage cannot pass")
if "error" in report:
raise ValueError("Registry audit reported an error; not a valid pass")
return report
def triage_pnpm(report: dict) -> None:
advisories = report.get("advisories")
if not isinstance(advisories, dict):
raise ValueError("Expected pnpm audit advisories map")
counts: dict[str, int] = {}
for identifier, issue in sorted(advisories.items()):
if not isinstance(issue, dict):
raise ValueError(f"Invalid advisory record: {identifier}")
severity = str(issue.get("severity", "unknown")).lower()
counts[severity] = counts.get(severity, 0) + 1
aid = issue.get("github_advisory_id") or issue.get("url") or identifier
package = issue.get("module_name") or issue.get("name") or "unknown"
affected = issue.get("vulnerable_versions") or "unknown"
fixed = issue.get("patched_versions") or "not provided"
print(f"PNPM_ADVISORY id={aid} package={package} severity={severity} affected={affected} fixed={fixed}")
summary = report.get("metadata", {}).get("vulnerabilities", {})
print(f"PNPM_ADVISORY_RECORDS={len(advisories)} COUNT_BY_SEVERITY={counts}")
print(f"PNPM_REPORTED_SEVERITIES={summary}")
if sum(counts.values()) != len(advisories):
raise ValueError("Inconsistent advisory record count")
def triage_npm(report: dict) -> None:
issues = report.get("vulnerabilities")
if not isinstance(issues, dict):
raise ValueError("Expected npm audit vulnerabilities map")
for name, entry in sorted(issues.items()):
if not isinstance(entry, dict):
raise ValueError(f"Invalid npm record: {name}")
via = entry.get("via", [])
advisories = [
(item.get("url") or item.get("source") or "unknown")
for item in via if isinstance(item, dict)
]
print(
f"NPM_VULNERABILITY package={name} severity={entry.get('severity', 'unknown')} "
f"affected={entry.get('range', 'unknown')} fix={entry.get('fixAvailable', 'unknown')} "
f"advisories={advisories}"
)
print(f"NPM_VULNERABLE_PACKAGE_COUNT={len(issues)}")
print(f"NPM_REPORTED_SEVERITIES={report.get('metadata', {}).get('vulnerabilities', {})}")
def main() -> None:
if len(sys.argv) != 3 or sys.argv[1] not in ("npm", "pnpm"):
raise SystemExit("Usage: advisory_triage.py npm|pnpm audit-report.json")
report = read_report(sys.argv[2])
if sys.argv[1] == "npm":
triage_npm(report)
else:
triage_pnpm(report)
print("ZITPLANE_ADVISORY_TRIAGE_COMPLETE")
if __name__ == "__main__":
try:
main()
except (ValueError, OSError, json.JSONDecodeError) as exc:
print(f"ZITPLANE_ADVISORY_TRIAGE_FAILED: {exc}", file=sys.stderr)
raise SystemExit(1) from exc
+69 -13
View File
@@ -1,4 +1,7 @@
"""Read-only OIDC smoke: disposable Docker network only; not a login E2E."""
"""Disposable ZITADEL OIDC metadata/JWKS and fail-closed negative checks.
No interactive login, account provisioning, MFA or real user sessions.
"""
from __future__ import annotations
import json
@@ -10,30 +13,83 @@ PROXY = os.environ.get("ZITPLANE_CI_PROXY", "http://proxy")
EXPECTED_ISSUER = "http://localhost:8080"
HOST = "localhost:8080"
def fetch(path: str):
def verify_metadata(discovery: dict) -> str:
if discovery.get("issuer") != EXPECTED_ISSUER:
raise RuntimeError("OIDC issuer does not match disposable local origin")
for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
value = discovery.get(field)
if not isinstance(value, str):
raise RuntimeError(f"OIDC {field} missing")
parsed = urlparse(value)
if (
parsed.scheme != "http"
or parsed.netloc != "localhost:8080"
or not parsed.path.startswith("/")
or parsed.username or parsed.password
):
raise RuntimeError(f"OIDC {field} not on the allowed origin")
return urlparse(discovery["jwks_uri"]).path
def verify_jwks(jwks: dict) -> None:
keys = jwks.get("keys")
if not isinstance(keys, list) or not keys:
raise RuntimeError("JWKS must contain at least one public key")
for key in keys:
if not isinstance(key, dict) or not key.get("kty"):
raise RuntimeError("JWKS contains an invalid public key")
def verify_negative_contracts() -> None:
safe = {
"issuer": EXPECTED_ISSUER,
"authorization_endpoint": EXPECTED_ISSUER + "/oauth/v2/authorize",
"token_endpoint": EXPECTED_ISSUER + "/oauth/v2/token",
"jwks_uri": EXPECTED_ISSUER + "/oauth/v2/keys",
}
for field, dangerous in (
("issuer", "http://evil.invalid"),
("jwks_uri", "https://evil.invalid/keys"),
("authorization_endpoint", "//evil.invalid/authorize"),
("token_endpoint", "http://localhost:8080.evil.invalid/token"),
):
obj = {**safe, field: dangerous}
try:
verify_metadata(obj)
except RuntimeError:
continue
raise AssertionError(f"Unsafe OIDC {field} accepted")
for obj in ({"keys": []}, {"keys": "wrong"}, {"keys": [{}]}):
try:
verify_jwks(obj)
except RuntimeError:
continue
raise AssertionError("Unsafe JWKS payload accepted")
print("ZITPLANE_OIDC_NEGATIVE_CONTRACTS_PASS")
def fetch(path: str) -> bytes:
if PROXY != "http://proxy" or not path.startswith("/") or path.startswith("//"):
raise RuntimeError("Only disposable Docker proxy is allowed")
request = Request(PROXY + path, headers={"Host": HOST, "Accept": "application/json"})
with urlopen(request, timeout=20) as reply:
if reply.status != 200:
raise RuntimeError(f"HTTP {reply.status}: {path}")
return reply.read()
def main() -> None:
verify_negative_contracts()
fetch("/debug/ready")
print("ZITPLANE_BACKEND_READY_PASS")
discovery = json.loads(fetch("/.well-known/openid-configuration"))
if discovery.get("issuer") != EXPECTED_ISSUER:
raise RuntimeError("OIDC issuer does not match local dev origin")
for field in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
value = discovery.get(field)
if not isinstance(value, str) or not value.startswith(EXPECTED_ISSUER + "/"):
raise RuntimeError(f"Missing/unsafe OIDC {field}")
jwks_path = verify_metadata(discovery)
print("ZITPLANE_OIDC_DISCOVERY_PASS")
jwks_path = urlparse(discovery["jwks_uri"]).path
jwks = json.loads(fetch(jwks_path))
if not isinstance(jwks.get("keys"), list):
raise RuntimeError("Invalid JWKS shape")
verify_jwks(json.loads(fetch(jwks_path)))
print("ZITPLANE_OIDC_JWKS_PASS")
print("ZITPLANE_OIDC_INTERACTIVE_E2E_BLOCKED: no disposable OIDC app/user provisioning in P05")
print("ZITPLANE_OIDC_INTERACTIVE_E2E_DEFERRED: no disposable OIDC client/user")
if __name__ == "__main__":
main()
+11 -2
View File
@@ -53,9 +53,18 @@ def check_security_boundaries() -> None:
src = (ACCOUNT / "src/auth.ts").read_text(encoding="utf-8")
endpoint = (ACCOUNT / "src/app/api/account/me/route.ts").read_text(encoding="utf-8")
identity = (ACCOUNT / "src/lib/identity.ts").read_text(encoding="utf-8")
for flag in ('checks: ["pkce", "state", "nonce"]', 'zitadelTokenExpiresAt', 'token.zitadelSubject'):
for flag in (
'checks: ["pkce", "state", "nonce"]',
'typeof token.zitadelSubject === "string"',
'const subject: string',
'typeof token.zitadelTokenExpiresAt === "number"',
'token.zitadelTokenExpiresAt * 1000 > Date.now()',
'id: valid ? subject : ""',
):
if flag not in src:
fail(f"Missing reviewed OIDC source contract: {flag}")
fail(f"Missing reviewed fail-closed OIDC source contract: {flag}")
if "token.zitadelSubject!" in src or "as any" in src:
fail("Unsafe subject assertion or cast is not allowed")
if "session?.user?.id" not in endpoint or "session?.user?.id" not in identity:
fail("Protected source must gate on valid user id")
print("ZITPLANE_SOURCE_GUARD_CONTRACT_PASS")