From 7954938fcee4d11c0b27751c7cf7abdcc64cd243 Mon Sep 17 00:00:00 2001 From: Md Nurnobi Date: Mon, 23 Nov 2026 16:11:55 +0000 Subject: [PATCH] fix(ci): classify finite Compose deploy metadata, allow only empty defaults and reject unsafe behavior --- tests/ci/production_contract/validate.py | 154 ++++++++++++++++++++--- 1 file changed, 136 insertions(+), 18 deletions(-) diff --git a/tests/ci/production_contract/validate.py b/tests/ci/production_contract/validate.py index 49db829..ff7a197 100644 --- a/tests/ci/production_contract/validate.py +++ b/tests/ci/production_contract/validate.py @@ -8,6 +8,7 @@ This checks a deliberately undeployable synthetic fixture, not production. from __future__ import annotations import copy +import hashlib import json import re import sys @@ -181,7 +182,14 @@ def verify_tracked_zero_replica_fixture() -> None: This tiny indentation check is intentionally stricter than general YAML. Docker Compose config separately parses/normalizes the complete fixture. """ - raw = (ROOT / COMPOSE_PATH).read_text(encoding="utf-8") + 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] @@ -200,8 +208,64 @@ def verify_tracked_zero_replica_fixture() -> None: 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: - """Known service IDs and fixed safe shape classes, never field values.""" + """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: @@ -222,6 +286,21 @@ def diagnose_normalized_deploy(c: object) -> None: 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 @@ -317,22 +396,19 @@ def validate_compose(c: object, p: dict) -> None: "postgres": "postgres"}[name] + ":never-deploy", "SYNTHETIC_IMAGE") deploy = service.get("deploy") - # Source verification (once before validation) independently requires - # the exact checked-in YAML's five zero replica declarations. If - # Compose JSON omits zero through normalization, only an absent/null - # deploy or an empty mapping is compatible with that proven source. - # Any explicit replicas value MUST be a real JSON integer zero. - if deploy is None: - check("deploy" not in service or service["deploy"] is None, - "DEPLOY_DISABLED") - else: - check(type(deploy) is dict and - set(deploy).issubset({"replicas"}), "DEPLOY_DISABLED") - if "replicas" in deploy: - check(type(deploy["replicas"]) is int and - deploy["replicas"] == 0, "DEPLOY_DISABLED") - # An omitted deploy section is never generally safe: validation - # is allowed only after verify_tracked_zero_replica_fixture() ran. + # 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") @@ -454,6 +530,47 @@ def negative_cases(p: dict, c: dict) -> None: + "_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) + def workflow_safety() -> None: body = WORKFLOW_PATH.read_text(encoding="utf-8") @@ -494,6 +611,7 @@ def main() -> int: diagnose_normalized_runtime_fields(compose) diagnose_normalized_deploy(compose) validate_all(policy, compose) + 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)