fix(gitops): enforce deployments.yaml as sole registry authority and remove dynamic discovery
Closes an admission authority bypass in the webhook continuous deployment engine by strictly requiring targets to be registered in Core/config/deployments.yaml. Previously, `get_trusted_repository_mapping()` attempted to load `deployments.yaml` in Step 1, but unconditionally fell back to Step 2 (scanning all directories in `~/Sites` with an `app.yaml`). This allowed unapproved workloads or experimental directories to receive automated webhook deployment authority simply by existing on disk, and failed open when `deployments.yaml` was missing or malformed. - Remove dynamic `SITES_DIR` directory scanning from `get_trusted_repository_mapping()`. - Enforce `deployments.yaml` as the sole authority, failing closed with an empty mapping if the registry is missing, unreadable, or malformed. - Update admission test fixtures to explicitly declare registered repositories. - Add regression tests verifying rejection of unregistered `~/Sites` directories and fail-closed behavior on corrupted/missing registry configurations. - Update `todo.txt` task tracking. Part of Pre-P4 Security Gate (Milestone P4 readiness).
This commit is contained in:
1 parent
667f8d19b9
commit
0d9a2ce511
3 files changed
+123
-74
No files matched your search
@@ -156,90 +156,54 @@ def get_trusted_repository_mapping() -> dict[str, Path]:
|
|||||||
"""
|
"""
|
||||||
Build authoritative mapping of logical repository identities to local paths.
|
Build authoritative mapping of logical repository identities to local paths.
|
||||||
Webhook payloads can only select repositories defined in this mapping.
|
Webhook payloads can only select repositories defined in this mapping.
|
||||||
Prioritizes Core Authoritative Registry (deployments.yaml) over dynamic discovery.
|
Core Authoritative Registry (deployments.yaml) is the sole admission authority.
|
||||||
|
Fails closed if the registry is missing, unreadable, or malformed.
|
||||||
"""
|
"""
|
||||||
mapping: dict[str, Path] = {}
|
mapping: dict[str, Path] = {}
|
||||||
|
|
||||||
# 1. Authoritative Core Repository Registry (deployments.yaml)
|
|
||||||
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
|
registry_file = DEPLOYMENTS_FILE if DEPLOYMENTS_FILE.is_file() else (CONFIG_DIR / "deployments.yaml")
|
||||||
if registry_file.is_file():
|
if not registry_file.is_file():
|
||||||
try:
|
logger.error(f"Authoritative registry {registry_file} not found. Failing closed with zero admitted repositories.")
|
||||||
content = registry_file.read_text(encoding="utf-8")
|
return mapping
|
||||||
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
|
|
||||||
repo_entries = registry.get("repositories", registry) if isinstance(registry, dict) else {}
|
|
||||||
if isinstance(repo_entries, dict):
|
|
||||||
for reg_name, entry in repo_entries.items():
|
|
||||||
if not isinstance(entry, dict):
|
|
||||||
continue
|
|
||||||
raw_path = entry.get("path")
|
|
||||||
if not raw_path:
|
|
||||||
continue
|
|
||||||
p = Path(raw_path).expanduser().resolve()
|
|
||||||
# Enforce strict containment strictly inside SITES_DIR
|
|
||||||
if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()):
|
|
||||||
mapping[reg_name] = p
|
|
||||||
raw_aliases = entry.get("aliases", [])
|
|
||||||
if isinstance(raw_aliases, str):
|
|
||||||
raw_aliases = [raw_aliases]
|
|
||||||
if isinstance(raw_aliases, list):
|
|
||||||
for alias in raw_aliases:
|
|
||||||
if isinstance(alias, str) and alias.strip():
|
|
||||||
mapping[alias.strip()] = p
|
|
||||||
else:
|
|
||||||
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
|
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
|
||||||
logger.warning(f"Failed to parse authoritative registry {registry_file}: {e}")
|
|
||||||
|
|
||||||
# 2. Dynamic Discovery in SITES_DIR (for workloads not explicitly registered)
|
yaml_errors = (yaml.YAMLError,) if yaml is not None else ()
|
||||||
if SITES_DIR.is_dir():
|
try:
|
||||||
sites_canonical = SITES_DIR.resolve()
|
content = registry_file.read_text(encoding="utf-8")
|
||||||
for entry in SITES_DIR.iterdir():
|
registry = (yaml.safe_load(content) if yaml else parse_yaml_simple(content)) or {}
|
||||||
if not entry.is_dir():
|
repo_entries = registry.get("repositories", registry) if isinstance(registry, dict) else {}
|
||||||
continue
|
if isinstance(repo_entries, dict):
|
||||||
|
for reg_name, entry in repo_entries.items():
|
||||||
|
if not isinstance(entry, dict):
|
||||||
|
continue
|
||||||
|
raw_path = entry.get("path")
|
||||||
|
if not raw_path:
|
||||||
|
continue
|
||||||
|
p = Path(raw_path).expanduser().resolve()
|
||||||
|
# Enforce strict containment strictly inside SITES_DIR
|
||||||
|
if SITES_DIR.is_dir() and p.is_relative_to(SITES_DIR.resolve()):
|
||||||
|
mapping[reg_name] = p
|
||||||
|
raw_aliases = entry.get("aliases", [])
|
||||||
|
if isinstance(raw_aliases, str):
|
||||||
|
raw_aliases = [raw_aliases]
|
||||||
|
if isinstance(raw_aliases, list):
|
||||||
|
for alias in raw_aliases:
|
||||||
|
if isinstance(alias, str) and alias.strip():
|
||||||
|
mapping[alias.strip()] = p
|
||||||
|
else:
|
||||||
|
logger.warning(f"Rejecting out-of-bounds path in deployments.yaml for '{reg_name}': {p}")
|
||||||
|
else:
|
||||||
|
logger.error(f"Malformed repositories block in {registry_file}: expected dictionary mapping.")
|
||||||
|
return {}
|
||||||
|
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError, TypeError, *yaml_errors) as e:
|
||||||
|
logger.critical(f"Failed to parse authoritative registry {registry_file}: {e}. Failing closed.")
|
||||||
|
return {}
|
||||||
|
|
||||||
# Defense-in-depth: resolve symlinks and ensure target is strictly inside SITES_DIR
|
|
||||||
resolved_entry = entry.resolve()
|
|
||||||
if not resolved_entry.is_relative_to(sites_canonical):
|
|
||||||
logger.warning(f"Rejecting repository symlink escape: {entry} -> {resolved_entry}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
manifest_file = resolved_entry / "app.yaml"
|
|
||||||
if not manifest_file.is_file():
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Register entry directory name if not already mapped
|
|
||||||
dir_name = entry.name
|
|
||||||
if dir_name not in mapping:
|
|
||||||
mapping[dir_name] = resolved_entry
|
|
||||||
|
|
||||||
# Parse app.yaml for canonical name and aliases
|
|
||||||
manifest = {}
|
|
||||||
try:
|
|
||||||
manifest_text = manifest_file.read_text(encoding="utf-8")
|
|
||||||
manifest = (yaml.safe_load(manifest_text) if yaml else parse_yaml_simple(manifest_text)) or {}
|
|
||||||
except (OSError, UnicodeDecodeError, ValueError, KeyError, AttributeError) as e:
|
|
||||||
logger.warning(f"Failed to parse {manifest_file}: {e}")
|
|
||||||
|
|
||||||
canonical_name = manifest.get("name")
|
|
||||||
if canonical_name and isinstance(canonical_name, str):
|
|
||||||
canonical_name = canonical_name.strip()
|
|
||||||
if canonical_name not in mapping:
|
|
||||||
mapping[canonical_name] = resolved_entry
|
|
||||||
alias_with_prefix = f"homelab-{canonical_name}" if not canonical_name.startswith("homelab-") else canonical_name.replace("homelab-", "", 1)
|
|
||||||
if alias_with_prefix not in mapping:
|
|
||||||
mapping[alias_with_prefix] = resolved_entry
|
|
||||||
|
|
||||||
aliases = manifest.get("aliases", [])
|
|
||||||
if isinstance(aliases, str):
|
|
||||||
aliases = [aliases]
|
|
||||||
if isinstance(aliases, list):
|
|
||||||
for alias in aliases:
|
|
||||||
if isinstance(alias, str) and alias.strip() and alias.strip() not in mapping:
|
|
||||||
mapping[alias.strip()] = resolved_entry
|
|
||||||
|
|
||||||
return mapping
|
return mapping
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(repo_name: str) -> Path | None:
|
def resolve_repository(repo_name: str) -> Path | None:
|
||||||
"""
|
"""
|
||||||
Resolve a logical repository identity to a trusted local directory.
|
Resolve a logical repository identity to a trusted local directory.
|
||||||
|
|||||||
@@ -122,7 +122,14 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n homelab-docs:\n path: "{app_dir}"\n aliases:\n - docs\n - doc2site\n - notes\n',
|
||||||
|
encoding="utf-8"
|
||||||
|
)
|
||||||
|
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
canonical = app_dir.resolve()
|
canonical = app_dir.resolve()
|
||||||
assert gitops_dispatcher.resolve_repository("homelab-docs") == canonical
|
assert gitops_dispatcher.resolve_repository("homelab-docs") == canonical
|
||||||
@@ -131,6 +138,7 @@ def test_resolve_repository_resolves_valid_manifest(tmp_path: Path, monkeypatch)
|
|||||||
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
assert gitops_dispatcher.resolve_repository("notes") == canonical
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
def test_resolve_repository_rejects_vault(tmp_path: Path, monkeypatch):
|
||||||
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
"""Ensure data vault identities (Brain / second-brain) are not recognized by GitOps."""
|
||||||
sites_dir = tmp_path / "Sites"
|
sites_dir = tmp_path / "Sites"
|
||||||
@@ -179,6 +187,57 @@ repositories:
|
|||||||
assert "escaped-app" not in mapping
|
assert "escaped-app" not in mapping
|
||||||
|
|
||||||
|
|
||||||
|
def test_unregistered_sites_directory_rejected_when_registry_active(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure unregistered directories in ~/Sites cannot be resolved when deployments.yaml is active."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
registered_dir = sites_dir / "homelab-docs"
|
||||||
|
unregistered_dir = sites_dir / "rogue-workload"
|
||||||
|
registered_dir.mkdir(parents=True)
|
||||||
|
unregistered_dir.mkdir(parents=True)
|
||||||
|
(registered_dir / "app.yaml").write_text("name: docs\n", encoding="utf-8")
|
||||||
|
(unregistered_dir / "app.yaml").write_text("name: rogue\n", encoding="utf-8")
|
||||||
|
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{registered_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.resolve_repository("docs") == registered_dir.resolve()
|
||||||
|
# Unregistered workload must be rejected despite having app.yaml in Sites
|
||||||
|
assert gitops_dispatcher.resolve_repository("rogue") is None
|
||||||
|
assert gitops_dispatcher.resolve_repository("rogue-workload") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_or_corrupt_registry_fails_closed(tmp_path: Path, monkeypatch):
|
||||||
|
"""Ensure missing or corrupted deployments.yaml fails closed without falling back to directory scanning."""
|
||||||
|
sites_dir = tmp_path / "Sites"
|
||||||
|
app_dir = sites_dir / "valid-app"
|
||||||
|
app_dir.mkdir(parents=True)
|
||||||
|
(app_dir / "app.yaml").write_text("name: valid\n", encoding="utf-8")
|
||||||
|
|
||||||
|
missing_registry = tmp_path / "nonexistent-deployments.yaml"
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", missing_registry)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "CONFIG_DIR", tmp_path / "nonexistent-config")
|
||||||
|
|
||||||
|
# Missing registry must fail closed: empty mapping, no resolution
|
||||||
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
# Corrupt YAML registry must also fail closed
|
||||||
|
corrupt_registry = tmp_path / "corrupt-deployments.yaml"
|
||||||
|
corrupt_registry.write_text("schemaVersion: 1.0\nrepositories: [bad list syntax", encoding="utf-8")
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", corrupt_registry)
|
||||||
|
|
||||||
|
assert gitops_dispatcher.get_trusted_repository_mapping() == {}
|
||||||
|
assert gitops_dispatcher.resolve_repository("valid") is None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_webhook_verification_valid_signature():
|
def test_webhook_verification_valid_signature():
|
||||||
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
"""Ensure valid HMAC-SHA256 signature passes verification."""
|
||||||
import hashlib
|
import hashlib
|
||||||
@@ -323,7 +382,13 @@ def test_admission_rejects_branch_mismatch(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: production\n",
|
"name: docs\ndeployment:\n branch: production\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/staging",
|
"ref": "refs/heads/staging",
|
||||||
@@ -343,7 +408,13 @@ def test_admission_rejects_unsupported_strategy(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
"name: docs\ndeployment:\n branch: main\n strategy: kubernetes\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -363,7 +434,13 @@ def test_admission_rejects_unsupported_actions(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - evil_action\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -383,7 +460,13 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
"name: docs\ndeployment:\n branch: main\n actions:\n - git_pull\n - compose_up\n",
|
||||||
encoding="utf-8"
|
encoding="utf-8"
|
||||||
)
|
)
|
||||||
|
registry = tmp_path / "deployments.yaml"
|
||||||
|
registry.write_text(
|
||||||
|
f'schemaVersion: "1.0"\nrepositories:\n docs:\n path: "{app_dir}"\n',
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
monkeypatch.setattr(gitops_dispatcher, "SITES_DIR", sites_dir)
|
||||||
|
monkeypatch.setattr(gitops_dispatcher, "DEPLOYMENTS_FILE", registry)
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"ref": "refs/heads/main",
|
"ref": "refs/heads/main",
|
||||||
@@ -391,6 +474,7 @@ def test_admission_admits_valid_push(tmp_path: Path, monkeypatch):
|
|||||||
}
|
}
|
||||||
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
admitted, target_dir, config, branch, reason = gitops_dispatcher.admit_deployment(payload, event_type="push")
|
||||||
assert admitted is True
|
assert admitted is True
|
||||||
|
|
||||||
assert "Admitted" in reason
|
assert "Admitted" in reason
|
||||||
assert target_dir == app_dir.resolve()
|
assert target_dir == app_dir.resolve()
|
||||||
assert branch == "main"
|
assert branch == "main"
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ x 2026-10-13 (B) Specify daemon execution and privilege boundaries for Docker, s
|
|||||||
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
x 2026-10-13 (B) Define append-only audit telemetry schema, lifecycle, and failure handling semantics in docs/plans/p4-readiness-plan.md +audit @p4-gate
|
||||||
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
x 2026-10-13 (C) Establish P4 acceptance test matrix and definition of done before daemon implementation in docs/plans/p4-readiness-plan.md +test @p4-gate
|
||||||
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
|
x 2026-10-14 (A) Eliminate eval in scripts/appctl and enforce strict env key validation in scripts/core_manifest.py +security @appctl
|
||||||
(A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
|
x 2026-10-15 (A) Enforce deployments.yaml as sole registry and remove dynamic discovery fallback in scripts/gitops_dispatcher.py +registry @gitops
|
||||||
|
|
||||||
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
|
(A) Harden validate_compose_security in scripts/gitops_dispatcher.py blocking relative traversal, cross-tenant mounts, and privilege escalation +compose @gitops
|
||||||
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
|
(A) Unify manifest parsing on core_manifest.py and eliminate duplicate parsers in scripts/appctl_engine.py +manifest @engine
|
||||||
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
|
(A) Scaffold asyncio daemon server supporting dual transports (Unix socket /run/homelab/appctl.sock and HTTP) in scripts/appctl_daemon.py +daemon @p4
|
||||||
|
|||||||
Reference in new issue
Block a user