Files
ZitPlane/tests/ci/production_contract/validate.py
T

316 lines
15 KiB
Python

#!/usr/bin/env python3
"""P05-OIDC-08: stdlib-only, static, fail-closed production CONTRACT checker.
NO requests/network, no Docker client, no subprocess, no resource lifecycle.
Inputs: JSON-rendered docker compose config on stdin + checked-in JSON policy.
This checks a deliberately undeployable synthetic fixture, not production.
"""
from __future__ import annotations
import copy
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
COMPOSE_PATH = "deployment/production-contract/compose.ci.yaml"
POLICY_PATH = ROOT / "deployment/production-contract/routing-policy.json"
WORKFLOW_PATH = ROOT / ".gitea/workflows/p05-production-contract-dry-run.yml"
ISSUER = "https://auth.vib.tools"
ORIGIN = "https://account.vib.tools"
CALLBACK = ORIGIN + "/api/auth/callback/zitadel"
SECRETS = (
"zitadel_masterkey",
"postgres_password",
"login_client_pat",
"login_cookie_secret",
"account_client_secret",
"account_auth_secret",
)
FORWARD = {
"Forwarded": "strip-and-replace",
"X-Forwarded-Host": "strip-and-replace",
"X-Forwarded-Proto": "strip-and-replace",
"X-Forwarded-For": "strip-and-replace",
}
ROUTES = [
{"host": "auth.vib.tools", "path_prefix": "/ui/v2/login", "target": "zitadel-login", "port": 3000, "protocol": "http1"},
{"host": "auth.vib.tools", "path_prefix": "/ui/console", "target": "zitadel-api", "port": 8080, "protocol": "h2c"},
{"host": "auth.vib.tools", "path_prefix": "/", "target": "zitadel-api", "port": 8080, "protocol": "h2c"},
{"host": "account.vib.tools", "path_prefix": "/", "target": "account", "port": 3000, "protocol": "http1"},
]
ENVS = {
"ingress-policy": {
"CONTRACT_PUBLIC_ISSUER": ISSUER,
"CONTRACT_ACCOUNT_ORIGIN": ORIGIN,
"CONTRACT_TLS_MODE": "external-https-only",
"CONTRACT_FORWARD_POLICY": "strip-and-replace",
},
"zitadel-api": {
"CONTRACT_ISSUER": ISSUER,
"CONTRACT_BACKEND_UPSTREAM": "h2c",
"CONTRACT_MASTERKEY_FILE": "/run/secrets/zitadel_masterkey",
"CONTRACT_POSTGRES_PASSWORD_FILE": "/run/secrets/postgres_password",
},
"zitadel-login": {
"CONTRACT_LOGIN_BASE_PATH": "/ui/v2/login",
"CONTRACT_ZITADEL_API": "zitadel-api:8080",
"CONTRACT_LOGIN_CLIENT_PAT_FILE": "/run/secrets/login_client_pat",
"CONTRACT_LOGIN_COOKIE_SECRET_FILE": "/run/secrets/login_cookie_secret",
},
"account": {
"CONTRACT_ISSUER": ISSUER,
"CONTRACT_ORIGIN": ORIGIN,
"CONTRACT_CALLBACK": CALLBACK,
"CONTRACT_OIDC_CLIENT_SECRET_FILE": "/run/secrets/account_client_secret",
"CONTRACT_AUTH_SECRET_FILE": "/run/secrets/account_auth_secret",
},
"postgres": {
"CONTRACT_POSTGRES_PASSWORD_FILE": "/run/secrets/postgres_password",
},
}
SERVICE_SECRETS = {
"ingress-policy": (),
"zitadel-api": ("zitadel_masterkey", "postgres_password"),
"zitadel-login": ("login_client_pat", "login_cookie_secret"),
"account": ("account_client_secret", "account_auth_secret"),
"postgres": ("postgres_password",),
}
class ContractError(Exception):
def __init__(self, code: str):
super().__init__(code)
self.code = code
def check(condition: bool, code: str) -> None:
if not condition:
raise ContractError(code)
def exact_keys(value: object, names: set[str], code: str) -> None:
check(type(value) is dict and set(value) == names, code)
def validate_policy(p: object) -> None:
exact_keys(p, {
"schema", "status", "issuer", "account_origin", "callback",
"allowed_redirect_uris", "allowed_post_logout_uris", "oidc",
"routes", "edge", "required_secret_references",
}, "POLICY_SCHEMA")
check(p["schema"] == "zitplane.synthetic-production-contract.v1" and
p["status"] == "CI_ONLY_NOT_DEPLOYABLE", "POLICY_NOT_SYNTHETIC")
check(p["issuer"] == ISSUER, "ISSUER")
check(p["account_origin"] == ORIGIN, "ACCOUNT_ORIGIN")
check(p["callback"] == CALLBACK, "CALLBACK")
check(type(p["allowed_redirect_uris"]) is list and
p["allowed_redirect_uris"] == [CALLBACK], "REDIRECT")
check(type(p["allowed_post_logout_uris"]) is list and
p["allowed_post_logout_uris"] == [ORIGIN + "/signin"], "LOGOUT_REDIRECT")
check(p["oidc"] == {
"response_type": "code", "pkce": "S256", "state_required": True,
"nonce_required": True, "client_type": "confidential",
}, "OIDC_POLICY")
check(type(p["routes"]) is list and p["routes"] == ROUTES, "ROUTE_POLICY")
edge = p["edge"]
exact_keys(edge, {
"tls_required", "tls_termination", "expected_public_listener",
"allowed_hosts", "unknown_host", "trusted_forwarding_source",
"forwarded_headers", "no_public_backend_ports", "no_privileged_docker_access",
}, "EDGE_SCHEMA")
check(edge["tls_required"] is True and
edge["tls_termination"] == "external-only" and
edge["expected_public_listener"] == "443/tcp (design only; not published by CI)",
"TLS_POLICY")
check(edge["allowed_hosts"] == ["auth.vib.tools", "account.vib.tools"] and
edge["unknown_host"] == "reject", "HOST_POLICY")
check(edge["trusted_forwarding_source"] == "ingress-policy-only" and
edge["forwarded_headers"] == FORWARD, "HEADER_POLICY")
check(edge["no_public_backend_ports"] is True and
edge["no_privileged_docker_access"] is True, "EDGE_EXPOSURE")
check(p["required_secret_references"] == list(SECRETS), "POLICY_SECRETS")
def service_secret_refs(service: dict) -> list[str]:
entries = service.get("secrets", [])
check(type(entries) is list, "SERVICE_SECRET_REFS")
values = []
for entry in entries:
if isinstance(entry, str):
values.append(entry)
elif isinstance(entry, dict):
check(set(entry).issubset({"source", "target", "uid", "gid", "mode"}) and
entry.get("target") == entry.get("source"), "SERVICE_SECRET_REFS")
values.append(entry.get("source"))
else:
raise ContractError("SERVICE_SECRET_REFS")
return values
def validate_compose(c: object, p: dict) -> None:
exact_keys(c, {"name", "services", "networks", "secrets"}, "COMPOSE_ROOT")
check(c["name"] == "zitplane-oidc-08-ci-do-not-deploy", "COMPOSE_NOT_SYNTHETIC")
check(type(c["services"]) is dict and set(c["services"]) == set(ENVS),
"SERVICE_SET")
check(type(c["networks"]) is dict and set(c["networks"]) == {"isolated"} and
type(c["networks"]["isolated"]) is dict and
c["networks"]["isolated"].get("internal") is True and
c["networks"]["isolated"].get("external") is not True,
"NETWORK_PRIVATE")
check(type(c["secrets"]) is dict and set(c["secrets"]) == set(SECRETS),
"SECRET_REGISTRY")
for secret in SECRETS:
item = c["secrets"][secret]
check(type(item) is dict and item.get("external") is True and
item.get("name") == "ci-only-placeholder-" + secret.replace("_", "-") and
not any(k in item for k in ("file", "environment", "driver")),
"SECRET_REGISTRY")
for name, env_expected in ENVS.items():
service = c["services"][name]
check(type(service) is dict, "SERVICE_TYPE")
check("ports" not in service and "expose" not in service and
"network_mode" not in service, "PUBLIC_PORTS")
check("volumes" not in service and "devices" not in service and
"tmpfs" not in service, "DOCKER_SOCKET")
check(service.get("privileged") is not True and
"cap_add" not in service and
"pid" not in service and
"ipc" not in service and
"userns_mode" not in service, "PRIVILEGED")
check("build" not in service and "command" not in service and
"entrypoint" not in service and
"configs" not in service, "RUNTIME_BEHAVIOR")
check(set(service).issubset({"image", "deploy", "networks", "environment", "secrets"}),
"SERVICE_FIELDS")
check(service.get("image") ==
"synthetic.invalid/zitplane/" +
{"ingress-policy": "ingress", "zitadel-api": "zitadel-api",
"zitadel-login": "login", "account": "account",
"postgres": "postgres"}[name] + ":never-deploy",
"SYNTHETIC_IMAGE")
deploy = service.get("deploy")
check(type(deploy) is dict and set(deploy) == {"replicas"} and
type(deploy["replicas"]) is int and deploy["replicas"] == 0,
"DEPLOY_DISABLED")
snet = service.get("networks")
check((type(snet) is dict and set(snet) == {"isolated"}) or
snet == ["isolated"], "SERVICE_NETWORK")
env = service.get("environment")
check(type(env) is dict, "ENV_POLICY")
for key in env:
check(not re.search(r"(PASSWORD|SECRET|TOKEN|PAT|MASTERKEY)$", key),
"INLINE_SECRET")
check(env == env_expected, "ENV_POLICY")
check(service_secret_refs(service) == list(SERVICE_SECRETS[name]),
"SERVICE_SECRET_REFS")
check(p["required_secret_references"] == list(SECRETS), "POLICY_SECRETS")
def validate_all(p: object, c: object) -> None:
validate_policy(p)
validate_compose(c, p)
def negative_cases(p: dict, c: dict) -> None:
# Each case targets one distinct security invariant. It must reject with
# the target error code, not merely fail because of an unrelated mutation.
cases = [
("HTTP_ISSUER", "ISSUER", lambda p,c: p.__setitem__("issuer", "http://auth.vib.tools")),
("WRONG_ISSUER", "ISSUER", lambda p,c: p.__setitem__("issuer", "https://other.invalid")),
("HTTP_ACCOUNT", "ACCOUNT_ORIGIN", lambda p,c: p.__setitem__("account_origin", "http://account.vib.tools")),
("WRONG_CALLBACK", "CALLBACK", lambda p,c: p.__setitem__("callback", ORIGIN + "/wrong")),
("WILDCARD_REDIRECT", "REDIRECT", lambda p,c: p.__setitem__("allowed_redirect_uris", ["https://*.vib.tools/callback"])),
("HTTP_REDIRECT", "REDIRECT", lambda p,c: p.__setitem__("allowed_redirect_uris", ["http://account.vib.tools/api/auth/callback/zitadel"])),
("WILDCARD_LOGOUT", "LOGOUT_REDIRECT", lambda p,c: p.__setitem__("allowed_post_logout_uris", ["https://account.vib.tools/*"])),
("LOGIN_BASE_PATH", "ROUTE_POLICY", lambda p,c: p["routes"][0].__setitem__("path_prefix", "/login")),
("CONSOLE_PATH", "ROUTE_POLICY", lambda p,c: p["routes"][1].__setitem__("path_prefix", "/console")),
("API_NOT_H2C", "ROUTE_POLICY", lambda p,c: p["routes"][2].__setitem__("protocol", "http1")),
("WILDCARD_HOST", "HOST_POLICY", lambda p,c: p["edge"].__setitem__("allowed_hosts", ["*"])),
("UNTRUSTED_FORWARDED", "HEADER_POLICY", lambda p,c: p["edge"]["forwarded_headers"].__setitem__("X-Forwarded-Proto", "trust-client")),
("TRUST_ANY_PROXY", "HEADER_POLICY", lambda p,c: p["edge"].__setitem__("trusted_forwarding_source", "any")),
("NO_TLS", "TLS_POLICY", lambda p,c: p["edge"].__setitem__("tls_required", False)),
("NO_PKCE", "OIDC_POLICY", lambda p,c: p["oidc"].__setitem__("pkce", "plain")),
("PUBLIC_API_PORT", "PUBLIC_PORTS", lambda p,c: c["services"]["zitadel-api"].__setitem__("ports", [{"target":8080,"published":"8080"}])),
("PUBLIC_DB_PORT", "PUBLIC_PORTS", lambda p,c: c["services"]["postgres"].__setitem__("ports", [{"target":5432,"published":"5432"}])),
("MISSING_SECRET", "SERVICE_SECRET_REFS", lambda p,c: c["services"]["account"].__setitem__("secrets", [])),
("MISSING_SECRET_REFERENCE", "SECRET_REGISTRY", lambda p,c: c["secrets"].pop("zitadel_masterkey")),
("PLAINTEXT_SECRET", "INLINE_SECRET", lambda p,c: c["services"]["account"]["environment"].__setitem__("AUTH_SECRET", "dummy-not-a-real-secret")),
("DOCKER_SOCKET", "DOCKER_SOCKET", lambda p,c: c["services"]["ingress-policy"].__setitem__("volumes", ["/var/run/docker.sock:/var/run/docker.sock:ro"])),
("PRIVILEGED", "PRIVILEGED", lambda p,c: c["services"]["zitadel-api"].__setitem__("privileged", True)),
("ACTIVATE_REPLICAS", "DEPLOY_DISABLED", lambda p,c: c["services"]["zitadel-login"]["deploy"].__setitem__("replicas", 1)),
("EXTERNAL_NETWORK", "NETWORK_PRIVATE", lambda p,c: c["networks"]["isolated"].__setitem__("internal", False)),
("DEPLOYABLE_IMAGE", "SYNTHETIC_IMAGE", lambda p,c: c["services"]["zitadel-api"].__setitem__("image", "ghcr.io/zitadel/zitadel:v4.20.4")),
]
for label, expected_error, mutate in cases:
bad_policy, bad_compose = copy.deepcopy(p), copy.deepcopy(c)
mutate(bad_policy, bad_compose)
try:
validate_all(bad_policy, bad_compose)
except ContractError as error:
check(error.code == expected_error, "NEGATIVE_WRONG_CLASS_" + label)
else:
raise ContractError("NEGATIVE_NOT_REJECTED_" + label)
print("ZITPLANE_P08_NEGATIVE_" + label + "_REJECTED_PASS", flush=True)
print("ZITPLANE_P08_ALL_25_NEGATIVE_CASES_PASS", flush=True)
def workflow_safety() -> None:
body = WORKFLOW_PATH.read_text(encoding="utf-8")
check(re.search(r"(?m)^on:\s*$", body) is not None and
re.search(r"(?m)^\s+workflow_dispatch:\s*$", body) is not None and
not re.search(r"(?m)^\s+(push|pull_request|schedule|workflow_run):\s*$", body),
"WORKFLOW_MANUAL_ONLY")
prefix = "docker compose -f " + COMPOSE_PATH + " config "
allowed = {
prefix + "--quiet",
prefix + "--format json | python3 tests/ci/production_contract/validate.py --compose-json-stdin",
}
commands = [line.strip() for line in body.splitlines()
if line.strip().startswith("docker ")]
check(len(commands) == 2 and set(commands) == allowed,
"WORKFLOW_DOCKER_COMMANDS")
check("if: always()" in body and
"python3 tests/ci/production_contract/validate.py --workflow-safety" in body,
"WORKFLOW_NO_RESOURCE_PROOF")
check(not re.search(r"(?im)^\s*(?:curl|wget|dig|nslookup|docker\s+(?:run|build|pull|push|create|rm|ps))\b", body),
"WORKFLOW_NETWORK_OR_DOCKER_LIFECYCLE")
print("ZITPLANE_P08_MANUAL_ONLY_NO_RESOURCE_ACTIONS_CONFIGURED_PASS", flush=True)
def main() -> int:
if len(sys.argv) != 2 or sys.argv[1] not in (
"--compose-json-stdin", "--workflow-safety"
):
print("ZITPLANE_P08_USAGE_BLOCKED", file=sys.stderr)
return 2
try:
workflow_safety()
if sys.argv[1] == "--workflow-safety":
return 0
policy = json.loads(POLICY_PATH.read_text(encoding="utf-8"))
compose = json.load(sys.stdin)
validate_all(policy, compose)
print("ZITPLANE_P08_CANONICAL_HTTPS_ISSUER_AND_CALLBACK_PASS", flush=True)
print("ZITPLANE_P08_LOGIN_CONSOLE_API_H2C_PRIVATE_ROUTING_PASS", flush=True)
print("ZITPLANE_P08_HOST_FORWARDED_HEADER_TLS_POLICY_PASS", flush=True)
print("ZITPLANE_P08_NO_PUBLIC_PORT_INLINE_SECRET_SOCKET_OR_RUNTIME_PASS", flush=True)
negative_cases(policy, compose)
print("ZITPLANE_P08_STATIC_DRY_RUN_ACCEPTANCE_PASS", flush=True)
return 0
except (ContractError, json.JSONDecodeError, OSError, ValueError, TypeError) as exc:
# Fixed diagnostic classes only. Never include input values, env or URLs.
code = exc.code if isinstance(exc, ContractError) else "INVALID_INPUT"
print("ZITPLANE_P08_FAIL_CLOSED_" + code, file=sys.stderr, flush=True)
return 1
if __name__ == "__main__":
sys.exit(main())