802 lines
36 KiB
Python
802 lines
36 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 hashlib
|
|
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 diagnose_normalized_runtime_fields(c: object) -> None:
|
|
"""Report only allowlisted field names, known synthetic service and safe shape.
|
|
|
|
Do not print field values, environment, raw JSON or arbitrary keys. This
|
|
deliberately runs once on the real Compose-normalized document, never on
|
|
the synthetic negative mutations.
|
|
"""
|
|
if type(c) is not dict or type(c.get("services")) is not dict:
|
|
return
|
|
for name in ENVS:
|
|
service = c["services"].get(name)
|
|
if type(service) is not dict:
|
|
continue
|
|
for field in ("build", "command", "entrypoint", "configs"):
|
|
if field not in service:
|
|
continue
|
|
value = service[field]
|
|
if value is None:
|
|
shape = "NULL"
|
|
elif type(value) is list:
|
|
shape = "EMPTY_LIST" if not value else "NONEMPTY_LIST"
|
|
elif type(value) is dict:
|
|
shape = "EMPTY_DICT" if not value else "NONEMPTY_DICT"
|
|
elif type(value) is str:
|
|
shape = "EMPTY_STRING" if not value else "STRING"
|
|
elif type(value) is bool:
|
|
shape = "BOOL"
|
|
elif type(value) in (int, float):
|
|
shape = "NUMBER"
|
|
else:
|
|
shape = "OTHER"
|
|
print(
|
|
"ZITPLANE_P08_NORMALIZED_RUNTIME_FIELD_"
|
|
+ name.replace("-", "_").upper() + "_" + field.upper()
|
|
+ "_" + shape, flush=True
|
|
)
|
|
|
|
|
|
def verify_tracked_zero_replica_fixture() -> None:
|
|
"""Prove every one of the five unchanged synthetic source blocks says zero.
|
|
|
|
Compose may normalize a numeric zero away. Never infer that an absent
|
|
normalized key is safe unless the exact checked-in source proves it.
|
|
This tiny indentation check is intentionally stricter than general YAML.
|
|
Docker Compose config separately parses/normalizes the complete fixture.
|
|
"""
|
|
raw_bytes = (ROOT / COMPOSE_PATH).read_bytes()
|
|
# Git's verified blob SHA for the unchanged, synthetic, zero-replica
|
|
# fixture. A different source is not eligible for normalized defaults.
|
|
blob = b"blob " + str(len(raw_bytes)).encode("ascii") + b"\0" + raw_bytes
|
|
check(hashlib.sha1(blob).hexdigest() ==
|
|
"930c0b0fbfb518555436acd6f0b4bb3bdd421937",
|
|
"SOURCE_FIXTURE_IMMUTABLE")
|
|
raw = raw_bytes.decode("utf-8")
|
|
check(raw.count("\nservices:\n") == 1 and
|
|
raw.count("\nnetworks:\n") == 1, "SOURCE_ZERO_REPLICA_STRUCTURE")
|
|
section = raw.split("\nservices:\n", 1)[1].split("\nnetworks:\n", 1)[0]
|
|
blocks = re.split(r"(?m)^ ([a-z][a-z0-9-]*):\s*\n", section)
|
|
check(len(blocks) == 1 + 2 * len(ENVS) and
|
|
not blocks[0].strip(), "SOURCE_ZERO_REPLICA_SERVICES")
|
|
names = blocks[1::2]
|
|
check(len(names) == len(ENVS) and set(names) == set(ENVS),
|
|
"SOURCE_ZERO_REPLICA_SERVICES")
|
|
for block in blocks[2::2]:
|
|
check(len(re.findall(r"(?m)^ deploy:\s*$", block)) == 1 and
|
|
len(re.findall(r"(?m)^ replicas:\s*0\s*$", block)) == 1 and
|
|
len(re.findall(r"(?m)^\s+replicas\s*:", block)) == 1 and
|
|
re.search(r"(?m)^ deploy:\s*\n replicas:\s*0\s*$", block)
|
|
is not None, "SOURCE_ZERO_REPLICA_DECLARATION")
|
|
print("ZITPLANE_P08_SOURCE_ALL_FIVE_REPLICAS_ZERO_PASS", flush=True)
|
|
|
|
|
|
# Only these official Compose deployment metadata names can ever be
|
|
# recognized. Names from input are NEVER interpolated into any log line.
|
|
KNOWN_DEPLOY_META = (
|
|
"resources", "restart_policy", "placement", "update_config",
|
|
"rollback_config", "labels", "mode", "endpoint_mode",
|
|
)
|
|
|
|
|
|
def inert_deploy_metadata(key: str, value: object) -> bool:
|
|
"""Accept only structurally empty/null normalized defaults.
|
|
|
|
An object with deployment behavior is never an inert default. The one
|
|
nested exception is Compose's empty resources limits/reservations wrapper;
|
|
keys and nested values are both strictly allowlisted and must be empty.
|
|
Source identity and five normalized int-zero replicas are checked
|
|
independently before any acceptance.
|
|
"""
|
|
if key not in KNOWN_DEPLOY_META:
|
|
return False
|
|
if key in ("mode", "endpoint_mode"):
|
|
return value is None
|
|
if value is None:
|
|
return True
|
|
if type(value) is dict:
|
|
if not value:
|
|
return True
|
|
return (
|
|
key == "resources"
|
|
and set(value).issubset({"limits", "reservations"})
|
|
and all(
|
|
nested is None or (type(nested) is dict and not nested)
|
|
for nested in value.values()
|
|
)
|
|
)
|
|
if key == "labels" and type(value) is list and not value:
|
|
return True
|
|
return False
|
|
|
|
|
|
def safe_deploy_shape(value: object) -> str:
|
|
"""Fixed type/emptiness category only; no input values or arbitrary keys."""
|
|
if value is None:
|
|
return "NULL"
|
|
if type(value) is dict:
|
|
return "EMPTY_OBJECT" if not value else "NONEMPTY_OBJECT"
|
|
if type(value) is list:
|
|
return "EMPTY_LIST" if not value else "NONEMPTY_LIST"
|
|
if type(value) is str:
|
|
return "STRING"
|
|
if type(value) is bool:
|
|
return "BOOL"
|
|
if type(value) in (int, float):
|
|
return "NUMBER"
|
|
return "OTHER"
|
|
|
|
|
|
def diagnose_normalized_deploy(c: object) -> None:
|
|
"""Finite known field labels and safe type categories; never field values."""
|
|
if type(c) is not dict or type(c.get("services")) is not dict:
|
|
return
|
|
for name in ENVS:
|
|
svc = c["services"].get(name)
|
|
if type(svc) is not dict:
|
|
continue
|
|
prefix = "ZITPLANE_P08_NORMALIZED_DEPLOY_" + name.replace("-", "_").upper()
|
|
if "deploy" not in svc:
|
|
print(prefix + "_MISSING", flush=True)
|
|
continue
|
|
deploy = svc["deploy"]
|
|
if deploy is None:
|
|
print(prefix + "_NULL", flush=True)
|
|
continue
|
|
if type(deploy) is not dict:
|
|
print(prefix + "_UNEXPECTED_TYPE", flush=True)
|
|
continue
|
|
print(prefix + ("_EMPTY_OBJECT" if not deploy else "_OBJECT"), flush=True)
|
|
if set(deploy) - {"replicas"}:
|
|
print(prefix + "_UNEXPECTED_FIELDS_PRESENT", flush=True)
|
|
for field in KNOWN_DEPLOY_META:
|
|
if field not in deploy:
|
|
continue
|
|
value = deploy[field]
|
|
shape = safe_deploy_shape(value)
|
|
if field == "resources" and type(value) is dict and value and (
|
|
inert_deploy_metadata(field, value)
|
|
):
|
|
shape = "ONLY_EMPTY_LIMITS_RESERVATIONS"
|
|
print(
|
|
prefix + "_KNOWN_" + field.upper() + "_" + shape,
|
|
flush=True,
|
|
)
|
|
if any(k not in {"replicas", *KNOWN_DEPLOY_META} for k in deploy):
|
|
print(prefix + "_UNKNOWN_KEY_PRESENT", flush=True)
|
|
if "replicas" not in deploy:
|
|
print(prefix + "_REPLICAS_MISSING", flush=True)
|
|
continue
|
|
replicas = deploy["replicas"]
|
|
if type(replicas) is int:
|
|
state = "INT_ZERO" if replicas == 0 else "INT_NONZERO"
|
|
elif replicas is None:
|
|
state = "NULL"
|
|
elif type(replicas) is bool:
|
|
state = "BOOL"
|
|
elif type(replicas) is str:
|
|
state = "STRING_ZERO" if replicas == "0" else "STRING_OTHER"
|
|
else:
|
|
state = "OTHER_TYPE"
|
|
print(prefix + "_REPLICAS_" + state, flush=True)
|
|
|
|
|
|
def secret_target_class(source: object, target: object) -> str:
|
|
"""Classify only known safe forms; never return or log raw input values."""
|
|
if type(source) is not str or type(target) is not str:
|
|
return "INVALID_TYPE"
|
|
if target == source:
|
|
return "SOURCE_NAME"
|
|
if target == "/run/secrets/" + source:
|
|
return "CANONICAL_MOUNT"
|
|
return "UNEXPECTED"
|
|
|
|
|
|
def safe_root_owner(value: object) -> bool:
|
|
return (type(value) is str and value == "0") or (
|
|
type(value) is int and value == 0
|
|
)
|
|
|
|
|
|
def safe_readonly_mode(value: object) -> bool:
|
|
# Compose default 0444 is decimal 292 in config --format json.
|
|
return (type(value) is int and value == 0o444) or (
|
|
type(value) is str and value == "0444"
|
|
)
|
|
|
|
|
|
def diagnose_normalized_service_grants(c: object) -> None:
|
|
"""Known service/index and fixed security classifications only.
|
|
|
|
Neither source/target strings, grant values, arbitrary keys nor
|
|
secret contents ever enter the diagnostic output.
|
|
"""
|
|
if type(c) is not dict or type(c.get("services")) is not dict:
|
|
return
|
|
for name, expected in SERVICE_SECRETS.items():
|
|
svc = c["services"].get(name)
|
|
if type(svc) is not dict:
|
|
continue
|
|
prefix = "ZITPLANE_P08_SECRET_GRANT_" + name.replace("-", "_").upper()
|
|
grants = svc.get("secrets", [])
|
|
if type(grants) is not list:
|
|
print(prefix + "_LIST_UNEXPECTED_TYPE", flush=True)
|
|
continue
|
|
print(prefix + "_LIST_" + ("EMPTY" if not grants else "NONEMPTY"),
|
|
flush=True)
|
|
seen = set()
|
|
for index, entry in enumerate(grants):
|
|
tag = prefix + "_ITEM_" + str(index) + "_"
|
|
if type(entry) is str:
|
|
source = entry
|
|
print(tag + "STRING", flush=True)
|
|
print(tag + "TARGET_SOURCE_NAME", flush=True)
|
|
elif type(entry) is dict:
|
|
source = entry.get("source")
|
|
print(tag + "OBJECT", flush=True)
|
|
target_class = secret_target_class(source, entry.get("target"))
|
|
print(tag + "TARGET_" + target_class, flush=True)
|
|
if set(entry) - {"source", "target", "uid", "gid", "mode"}:
|
|
print(tag + "UNKNOWN_METADATA_PRESENT", flush=True)
|
|
for key in ("uid", "gid"):
|
|
if key in entry:
|
|
print(tag + key.upper() + "_" +
|
|
("ROOT_DEFAULT" if safe_root_owner(entry[key])
|
|
else "UNSAFE"), flush=True)
|
|
if "mode" in entry:
|
|
print(tag + "MODE_" +
|
|
("READONLY_DEFAULT" if safe_readonly_mode(entry["mode"])
|
|
else "UNSAFE"), flush=True)
|
|
else:
|
|
print(tag + "UNEXPECTED_TYPE", flush=True)
|
|
continue
|
|
if type(source) is not str:
|
|
print(tag + "SOURCE_INVALID_TYPE", flush=True)
|
|
continue
|
|
source_class = ("EXPECTED" if source in expected else
|
|
"KNOWN_OTHER" if source in SECRETS else "UNKNOWN")
|
|
print(tag + "SOURCE_" + source_class, flush=True)
|
|
if source in seen:
|
|
print(tag + "DUPLICATE_SOURCE", flush=True)
|
|
seen.add(source)
|
|
if len(grants) != len(expected) or seen != set(expected):
|
|
print(prefix + "_REQUIRED_SET_OR_COUNT_MISMATCH", flush=True)
|
|
|
|
|
|
def service_secret_refs(service: dict) -> list[str]:
|
|
"""Only exact authorized symbolic mounts, canonical target, default perms."""
|
|
entries = service.get("secrets", [])
|
|
check(type(entries) is list, "SERVICE_SECRET_REFS")
|
|
values = []
|
|
for entry in entries:
|
|
if type(entry) is str:
|
|
source = entry
|
|
elif type(entry) is dict:
|
|
check(set(entry).issubset({"source", "target", "uid", "gid", "mode"})
|
|
and "source" in entry and "target" in entry,
|
|
"SERVICE_SECRET_REFS")
|
|
source = entry["source"]
|
|
check(secret_target_class(source, entry["target"]) in
|
|
{"SOURCE_NAME", "CANONICAL_MOUNT"}, "SERVICE_SECRET_REFS")
|
|
for field in ("uid", "gid"):
|
|
check(field not in entry or safe_root_owner(entry[field]),
|
|
"SERVICE_SECRET_REFS")
|
|
check("mode" not in entry or safe_readonly_mode(entry["mode"]),
|
|
"SERVICE_SECRET_REFS")
|
|
else:
|
|
raise ContractError("SERVICE_SECRET_REFS")
|
|
check(type(source) is str and source in SECRETS, "SERVICE_SECRET_REFS")
|
|
values.append(source)
|
|
check(len(values) == len(set(values)), "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")
|
|
# A Compose config JSON normalization can attach inert optional
|
|
# defaults. Accept only a null command/entrypoint (image defaults
|
|
# unchanged) or null/empty configs (no mounted config). Any build key,
|
|
# non-null command/entrypoint, nonempty configs or unknown key remains
|
|
# fail-closed, even for a zero-replica synthetic service.
|
|
inert = set()
|
|
for field in ("build", "command", "entrypoint", "configs"):
|
|
if field not in service:
|
|
continue
|
|
value = service[field]
|
|
if field in ("command", "entrypoint") and value is None:
|
|
inert.add(field)
|
|
elif field == "configs" and (
|
|
value is None or (type(value) is list and not value)
|
|
):
|
|
inert.add(field)
|
|
else:
|
|
raise ContractError("RUNTIME_BEHAVIOR")
|
|
check(
|
|
set(service).issubset(
|
|
{"image", "deploy", "networks", "environment", "secrets"} | inert
|
|
), "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")
|
|
# Run #103 proved the unchanged source's five zero declarations
|
|
# normalize to explicit JSON integer zero in all five services.
|
|
# Require exactly that: no omission/bool/string/other representation.
|
|
check(type(deploy) is dict and "replicas" in deploy and
|
|
type(deploy["replicas"]) is int and
|
|
deploy["replicas"] == 0, "DEPLOY_DISABLED")
|
|
# A03 conditional compatibility: only strictly inert known Compose
|
|
# metadata is allowed. Nonempty deployment-capable config and
|
|
# unknown fields must always fail closed.
|
|
for key, value in deploy.items():
|
|
if key == "replicas":
|
|
continue
|
|
check(inert_deploy_metadata(key, value), "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")
|
|
# Secret mount order is not a security property of normalized
|
|
# Compose JSON. Exact per-service identity and count ARE mandatory.
|
|
actual = service_secret_refs(service)
|
|
required = SERVICE_SECRETS[name]
|
|
check(len(actual) == len(required) and set(actual) == set(required),
|
|
"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"].__setitem__("deploy", {"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)
|
|
|
|
# Independently prove inert normalization compatibility: no command
|
|
# override is executed and no config is mounted by these null/empty
|
|
# defaults. Real nonempty runtime fields below must still be rejected.
|
|
inert_compose = copy.deepcopy(c)
|
|
inert_service = inert_compose["services"]["ingress-policy"]
|
|
inert_service["command"] = None
|
|
inert_service["entrypoint"] = None
|
|
inert_service["configs"] = []
|
|
validate_all(p, inert_compose)
|
|
print("ZITPLANE_P08_INERT_NORMALIZED_DEFAULTS_ACCEPTED_PASS", flush=True)
|
|
|
|
runtime_cases = [
|
|
("NONEMPTY_COMMAND", "RUNTIME_BEHAVIOR",
|
|
lambda c: c["services"]["ingress-policy"].__setitem__(
|
|
"command", ["sh", "-c", "true"])),
|
|
("NONEMPTY_ENTRYPOINT", "RUNTIME_BEHAVIOR",
|
|
lambda c: c["services"]["ingress-policy"].__setitem__(
|
|
"entrypoint", ["/bin/sh"])),
|
|
("BUILD_CONTEXT", "RUNTIME_BEHAVIOR",
|
|
lambda c: c["services"]["ingress-policy"].__setitem__(
|
|
"build", {"context": "."})),
|
|
("NONEMPTY_CONFIGS", "RUNTIME_BEHAVIOR",
|
|
lambda c: c["services"]["ingress-policy"].__setitem__(
|
|
"configs", [{"source": "unapproved-config"}])),
|
|
]
|
|
for label, expected_error, mutate in runtime_cases:
|
|
bad_compose = copy.deepcopy(c)
|
|
mutate(bad_compose)
|
|
try:
|
|
validate_all(p, bad_compose)
|
|
except ContractError as error:
|
|
check(error.code == expected_error,
|
|
"RUNTIME_NEGATIVE_WRONG_CLASS_" + label)
|
|
else:
|
|
raise ContractError("RUNTIME_NEGATIVE_NOT_REJECTED_" + label)
|
|
print("ZITPLANE_P08_RUNTIME_NEGATIVE_" + label
|
|
+ "_REJECTED_PASS", flush=True)
|
|
print("ZITPLANE_P08_ALL_4_RUNTIME_NEGATIVE_CASES_PASS", flush=True)
|
|
|
|
# Different hostile replica encodings must not be reinterpreted as zero.
|
|
replica_cases = [
|
|
("STRING_NONZERO", {"replicas": "1"}),
|
|
("BOOL_FALSE", {"replicas": False}),
|
|
("EXTRA_DEPLOY_KEY", {"replicas": 0, "mode": "global"}),
|
|
]
|
|
for label, deploy_value in replica_cases:
|
|
bad_compose = copy.deepcopy(c)
|
|
bad_compose["services"]["postgres"]["deploy"] = deploy_value
|
|
try:
|
|
validate_all(p, bad_compose)
|
|
except ContractError as error:
|
|
check(error.code == "DEPLOY_DISABLED",
|
|
"REPLICA_NEGATIVE_WRONG_CLASS_" + label)
|
|
else:
|
|
raise ContractError("REPLICA_NEGATIVE_NOT_REJECTED_" + label)
|
|
print("ZITPLANE_P08_REPLICA_NEGATIVE_" + label
|
|
+ "_REJECTED_PASS", flush=True)
|
|
print("ZITPLANE_P08_ALL_3_REPLICA_NEGATIVE_CASES_PASS", flush=True)
|
|
|
|
# Inert normalization must be accepted only when the tracked five-service
|
|
# fixture and explicit zero-replica normalized document are already valid.
|
|
empty_defaults = copy.deepcopy(c)
|
|
test_deploy = empty_defaults["services"]["postgres"]["deploy"]
|
|
test_deploy.update({
|
|
"resources": {"limits": {}, "reservations": {}},
|
|
"restart_policy": None,
|
|
"placement": {},
|
|
"update_config": None,
|
|
"rollback_config": {},
|
|
"labels": [],
|
|
"mode": None,
|
|
"endpoint_mode": None,
|
|
})
|
|
validate_all(p, empty_defaults)
|
|
print("ZITPLANE_P08_INERT_DEPLOY_METADATA_ACCEPTED_PASS", flush=True)
|
|
|
|
deploy_cases = [
|
|
("NONEMPTY_RESOURCES", "resources", {"limits": {"cpus": "1"}}),
|
|
("NONEMPTY_RESTART", "restart_policy", {"condition": "any"}),
|
|
("NONEMPTY_PLACEMENT", "placement", {"constraints": ["node.role==manager"]}),
|
|
("NONEMPTY_UPDATE", "update_config", {"parallelism": 1}),
|
|
("NONEMPTY_ROLLBACK", "rollback_config", {"order": "start-first"}),
|
|
("NONEMPTY_MODE", "mode", "replicated"),
|
|
("NONEMPTY_ENDPOINT", "endpoint_mode", "vip"),
|
|
("UNKNOWN_EXTRA_KEY", "unknown_security_key", None),
|
|
]
|
|
for label, field, value in deploy_cases:
|
|
bad_compose = copy.deepcopy(c)
|
|
bad_compose["services"]["postgres"]["deploy"][field] = value
|
|
try:
|
|
validate_all(p, bad_compose)
|
|
except ContractError as error:
|
|
check(error.code == "DEPLOY_DISABLED",
|
|
"DEPLOY_NEGATIVE_WRONG_CLASS_" + label)
|
|
else:
|
|
raise ContractError("DEPLOY_NEGATIVE_NOT_REJECTED_" + label)
|
|
print("ZITPLANE_P08_DEPLOY_NEGATIVE_" + label
|
|
+ "_REJECTED_PASS", flush=True)
|
|
print("ZITPLANE_P08_ALL_8_DEPLOY_NEGATIVE_CASES_PASS", flush=True)
|
|
|
|
# Grant security: test against the REAL normalized grant entry shape.
|
|
# Deliberate mutations never contact Docker, read secrets or log strings.
|
|
def source_mapping(item: object) -> dict:
|
|
return ({"source": item, "target": item} if type(item) is str
|
|
else copy.deepcopy(item))
|
|
|
|
def secret_case(compose: dict, label: str) -> None:
|
|
grants = compose["services"]["account"]["secrets"]
|
|
if label == "MISSING":
|
|
grants.pop()
|
|
elif label == "DUPLICATE":
|
|
grants.append(copy.deepcopy(grants[0]))
|
|
elif label == "EXTRA_AUTHORIZED_ELSEWHERE":
|
|
grants.append({"source": "zitadel_masterkey",
|
|
"target": "/run/secrets/zitadel_masterkey"})
|
|
elif label == "UNKNOWN_SOURCE":
|
|
grants.append({"source": "unapproved_symbolic_secret",
|
|
"target": "/run/secrets/unapproved_symbolic_secret"})
|
|
elif label == "WRONG_TARGET":
|
|
grant = source_mapping(grants[0])
|
|
grant["target"] = "/tmp/not-approved"
|
|
grants[0] = grant
|
|
elif label == "UNEXPECTED_METADATA":
|
|
grant = source_mapping(grants[0])
|
|
grant["privileged_grant"] = True
|
|
grants[0] = grant
|
|
elif label == "UNSAFE_UID":
|
|
grant = source_mapping(grants[0])
|
|
grant["uid"] = "1000"
|
|
grants[0] = grant
|
|
elif label == "WORLD_WRITABLE":
|
|
grant = source_mapping(grants[0])
|
|
grant["mode"] = 0o666
|
|
grants[0] = grant
|
|
|
|
labels = (
|
|
"MISSING", "DUPLICATE", "EXTRA_AUTHORIZED_ELSEWHERE",
|
|
"UNKNOWN_SOURCE", "WRONG_TARGET", "UNEXPECTED_METADATA",
|
|
"UNSAFE_UID", "WORLD_WRITABLE",
|
|
)
|
|
for label in labels:
|
|
bad_compose = copy.deepcopy(c)
|
|
secret_case(bad_compose, label)
|
|
try:
|
|
validate_all(p, bad_compose)
|
|
except ContractError as error:
|
|
check(error.code == "SERVICE_SECRET_REFS",
|
|
"SECRET_NEGATIVE_WRONG_CLASS_" + label)
|
|
else:
|
|
raise ContractError("SECRET_NEGATIVE_NOT_REJECTED_" + label)
|
|
print("ZITPLANE_P08_SECRET_NEGATIVE_" + label +
|
|
"_REJECTED_PASS", flush=True)
|
|
print("ZITPLANE_P08_ALL_8_SECRET_NEGATIVE_CASES_PASS", flush=True)
|
|
|
|
# A canonical mount path is a harmless representation change, not a
|
|
# new grant. Prove exact source/target mapping with each known service.
|
|
canonical = copy.deepcopy(c)
|
|
for service_name, expected in SERVICE_SECRETS.items():
|
|
grants = canonical["services"][service_name].get("secrets", [])
|
|
for i, grant in enumerate(grants):
|
|
normalized = source_mapping(grant)
|
|
source = normalized.get("source")
|
|
check(type(source) is str and source in expected,
|
|
"INERT_GRANT_SOURCE")
|
|
normalized["target"] = "/run/secrets/" + source
|
|
grants[i] = normalized
|
|
validate_all(p, canonical)
|
|
print("ZITPLANE_P08_CANONICAL_SECRET_MOUNTS_ACCEPTED_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)
|
|
verify_tracked_zero_replica_fixture()
|
|
diagnose_normalized_runtime_fields(compose)
|
|
diagnose_normalized_deploy(compose)
|
|
diagnose_normalized_service_grants(compose)
|
|
validate_all(policy, compose)
|
|
print("ZITPLANE_P08_NORMALIZED_SECRET_GRANT_POLICY_PASS", flush=True)
|
|
print("ZITPLANE_P08_NORMALIZED_DEPLOY_METADATA_POLICY_PASS", flush=True)
|
|
print("ZITPLANE_P08_NORMALIZED_ZERO_REPLICA_POLICY_PASS", flush=True)
|
|
print("ZITPLANE_P08_NORMALIZED_RUNTIME_DEFAULTS_POLICY_PASS", flush=True)
|
|
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())
|