Coverage for gco / manifest_security_policy.py: 100.00%
32 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-09-14 22:07 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-09-14 22:07 +0000
1"""Shared fail-closed parsing for manifest admission security policy."""
3from __future__ import annotations
5import os
6from collections.abc import Mapping
7from typing import Final
9MANIFEST_SECURITY_POLICY_DEFAULTS: Final[Mapping[str, bool]] = {
10 "block_privileged": True,
11 "block_privilege_escalation": True,
12 "block_host_network": True,
13 "block_host_pid": True,
14 "block_host_ipc": True,
15 "block_host_path": True,
16 "block_added_capabilities": True,
17 "block_run_as_root": False,
18}
20_TRUE_BOOLEAN_VALUES: Final = frozenset({"true", "1", "yes", "on"})
21_FALSE_BOOLEAN_VALUES: Final = frozenset({"false", "0", "no", "off"})
24def parse_boolean_environment(name: str, default: bool) -> bool:
25 """Parse one boolean environment variable without treating typos as false.
27 Unset or blank values retain the documented default. Non-empty values must
28 use an explicit true or false spelling; malformed deployment substitutions
29 raise during service startup instead of disabling an admission control.
30 """
31 raw = os.environ.get(name)
32 if raw is None or not raw.strip():
33 return default
35 normalized = raw.strip().lower()
36 if normalized in _TRUE_BOOLEAN_VALUES:
37 return True
38 if normalized in _FALSE_BOOLEAN_VALUES:
39 return False
40 raise ValueError(
41 f"{name} must be an explicit boolean value "
42 f"(true/false, 1/0, yes/no, or on/off); got {raw!r}"
43 )
46def validate_manifest_security_policy(policy: object) -> dict[str, bool]:
47 """Return a complete policy after rejecting malformed or unknown fields."""
48 if not isinstance(policy, Mapping):
49 raise ValueError("manifest_security_policy must be an object")
51 unsupported = sorted(
52 repr(key) for key in policy if key not in MANIFEST_SECURITY_POLICY_DEFAULTS
53 )
54 if unsupported:
55 raise ValueError(
56 "manifest_security_policy contains unsupported fields: " + ", ".join(unsupported)
57 )
59 validated = dict(MANIFEST_SECURITY_POLICY_DEFAULTS)
60 for key in MANIFEST_SECURITY_POLICY_DEFAULTS:
61 if key not in policy:
62 continue
63 value = policy[key]
64 if type(value) is not bool:
65 raise ValueError(f"manifest_security_policy.{key} must be a boolean")
66 validated[key] = value
67 return validated