diff --git a/RELEASE_CYCLE.md b/RELEASE_CYCLE.md index 4826fbc05e..34eeedad79 100644 --- a/RELEASE_CYCLE.md +++ b/RELEASE_CYCLE.md @@ -196,6 +196,12 @@ Use the unified `--create-pr` flag (or `devops release pr`) to automate version uv run devops release prepare X.Y.Z --create-pr ``` +Before branching, modifying files, or creating the release commit, the cut runs a deterministic offline gate verifying that every Argo CD application in `k8s/argocd/apps/` and `k8s/argocd/bootstrap/` targeting this repository builds at the fetched remote release tip: +- Each path application is built with Kustomize from an exported archive of the release head (`git archive`), ensuring that uncommitted or gitignored files cannot hide broken kustomizations. +- Template domain placeholder values (`example.com`, `$DOMAIN`, etc.) are validated: placeholders are permitted only in host fields of homelab applications (`"devops"`, `"ingress"`), and are rejected anywhere else (ConfigMaps, non-host fields, Helm value files, or non-homelab applications). +- If any application fails to build or contains invalid placeholders, the cut stops immediately with an `ArgoCDGateError` before any files are changed, any branch is checked out, or any git/gh commands reach origin. + + ### Step 3: CI Quality Gate & PR Review Gate 1. The opened Pull Request triggers `.github/workflows/ci.yml` which validates: - Python 3.14 runtime environment diff --git a/docs/ERRORS.md b/docs/ERRORS.md index 383c1b1c4f..31cae71bbf 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -27,6 +27,7 @@ The Exit Code column is the exception's `exit_code` attribute. Only `devops clou | `AICredentialsError` | `LLM_INFERENCE_ERROR` | `10` | Devops_cli.ai.client.models | Raised when a provider rejects the request's credentials; retrying cannot help. | | `AgentRunError` | `AGENT_RUN_ERROR` | `20` | Ai | Raised when an error occurs during an agent run lifecycle. | | `ApprovalRequired` | `APPROVAL_REQUIRED` | `17` | Ai | Raised by a tool or validator when human approval is required to proceed. | +| `ArgoCDGateError` | `ARGOCD_GATE_ERROR` | `1` | K8s | Raised when an Argo CD application fails offline build, value, or placeholder validation (#1343). | | `ArgoError` | `ARGO_ERROR` | `1` | Argo | Base exception for Argo CD, Rollouts, and Workflows operations. | | `ArgoResourceNotFoundError` | `ARGO_RESOURCE_NOT_FOUND` | `1` | Argo | Raised when an Argo custom resource does not exist in the target cluster. | | `BranchAlreadyExistsError` | `BRANCH_ALREADY_EXISTS` | `1` | Git | Raised when attempting to create a branch that already exists. | diff --git a/docs/agent/tasks/task-1343-argocd-build-gate.md b/docs/agent/tasks/task-1343-argocd-build-gate.md new file mode 100644 index 0000000000..2a9426b835 --- /dev/null +++ b/docs/agent/tasks/task-1343-argocd-build-gate.md @@ -0,0 +1,35 @@ +# Task: Argo CD Application Build Gate at Release Cut (#1343) + +**Issue**: [#1343](https://github.com/dan-petty/devops-cli/issues/1343) +**Scope**: scope/release +**Feasibility**: Verified against local Argo CD applications in `k8s/argocd/apps` and `k8s/argocd/bootstrap`, `git archive` export behavior, `kubectl kustomize` execution against extracted archives, and `cut_release` orchestration in `tests/test_release.py`. + +## Description + +A release cut must guarantee that every GitOps application managed by Argo CD builds deterministically at the release head before cutting the release. This deliverable (Part 1 of #1343) implements the offline deterministic Argo CD build gate: +- Discovers all Argo CD `Application` resources across `k8s/argocd/apps` and `k8s/argocd/bootstrap` pointing to this repository (`CONST_K8S_ARGOCD_APPLICATION_DIRS`). +- Exports a clean snapshot of the release tip using `git archive` into an isolated temporary directory, ensuring uncommitted or gitignored files cannot mask broken kustomizations. +- Builds every path application using Kustomize (`build_manifest_path`) and verifies template domain placeholder safety: placeholders (`example.com`, `$DOMAIN`, etc.) are permitted only in host fields of homelab applications (`"devops"`, `"ingress"`), and are rejected in ConfigMaps, non-host fields, Helm value files, or non-homelab applications. +- Fails closed with typed `ArgoCDGateError` before any release branching, file modifications, commits, or pushes occur in `cut_release`. +- Updates `RELEASE_CYCLE.md` documenting the gate in Step 2 of the release procedure. + +## Acceptance Criteria + +- [x] Every Argo CD `Application` pointing to this repository is discovered and validated. +- [x] Path applications are built using Kustomize from an exported archive of the release tip. +- [x] Template domain placeholder values outside allowed homelab host fields trigger gate failure. +- [x] Missing kustomization files, broken resources, or missing Helm value files raise `ArgoCDGateError`. +- [x] A gate failure prevents `cut_release` from creating branches, writing files, or pushing to origin. +- [x] `RELEASE_CYCLE.md` documents the Argo CD build gate in Step 2. +- [x] Unit and integration tests verify pass and failure conditions across all application permutations. +- Live Argo CD diff and override report after the offline gate (closes #1343 in follow-up PR). + +## Deliverables + +- [x] Added `CONST_K8S_KUSTOMIZATION_NAMES` and `CONST_K8S_ARGOCD_APPLICATION_DIRS` in `src/devops_cli/config/constants.py`. +- [x] Added `ArgoCDGateError` in `src/devops_cli/exceptions/k8s.py`. +- [x] Added `holds_template_domain_value` and `build_manifest_path` in `src/devops_cli/k8s/template.py`. +- [x] Implemented `src/devops_cli/k8s/argocd_gate.py` with `check_argocd_gate`, `discover_argocd_applications`, and `discover_path_applications`. +- [x] Integrated `check_argocd_gate` into `cut_release` in `src/devops_cli/release/cut.py`. +- [x] Documented the Argo CD build gate in `RELEASE_CYCLE.md`. +- [x] Added comprehensive tests in `tests/test_k8s_argocd_gate.py` and `tests/test_release.py`, and updated `tests/test_k8s_argocd_apps.py`. diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 63a236b5a3..8a8f5a3287 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -1197,6 +1197,17 @@ """The ConfigMap `devops k8s deploy-stack` renders from config.yaml; no Argo CD Application owns it.""" CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS: Final[tuple[str, ...]] = ("devops", "ingress") """The Argo CD Applications whose hosts deploy-stack sets from the configured domain (#1290).""" +CONST_K8S_KUSTOMIZATION_NAMES: Final[tuple[str, ...]] = ( + "kustomization.yaml", + "kustomization.yml", + "Kustomization", +) +"""The standard file names Kustomize recognizes for a directory overlay.""" +CONST_K8S_ARGOCD_APPLICATION_DIRS: Final[tuple[Path, ...]] = ( + Path("k8s/argocd/apps"), + Path("k8s/argocd/bootstrap"), +) +"""Directories scanned for Argo CD Applications (#1343).""" CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS_BY_STACK: Final[dict[str, tuple[str, ...]]] = { "infra": ("ingress",), "devops": ("devops", "ingress"), diff --git a/src/devops_cli/exceptions/k8s.py b/src/devops_cli/exceptions/k8s.py index b0a5ff4907..5c6466468d 100644 --- a/src/devops_cli/exceptions/k8s.py +++ b/src/devops_cli/exceptions/k8s.py @@ -51,6 +51,32 @@ def __init__( ) +class ArgoCDGateError(KubernetesError): + """Raised when an Argo CD application fails offline build, value, or placeholder validation (#1343).""" + + def __init__( + self, + message: str, + *, + failures: dict[str, list[str]] | None = None, + context: str | None = None, + exit_code: int = CONST_EXIT_FAILURE, + error_code: str = "ARGOCD_GATE_ERROR", + details: dict[str, Any] | None = None, + ) -> None: + err_details = dict(details or {}) + if failures: + err_details["failures"] = failures + super().__init__( + message, + context=context, + exit_code=exit_code, + error_code=error_code, + details=err_details, + ) + self.failures: dict[str, list[str]] = failures or {} + + class ChaosExecutionError(KubernetesError, RuntimeError): """Raised when chaos engineering injection or validation fails.""" @@ -209,6 +235,7 @@ def __init__( __all__ = [ + "ArgoCDGateError", "ChaosExecutionError", "ClusterJobError", "ClusterSecretPushError", diff --git a/src/devops_cli/k8s/argocd_gate.py b/src/devops_cli/k8s/argocd_gate.py new file mode 100644 index 0000000000..17ae263e33 --- /dev/null +++ b/src/devops_cli/k8s/argocd_gate.py @@ -0,0 +1,313 @@ +"""Deterministic offline build gate and validation for Argo CD applications (#1343).""" + +from __future__ import annotations + +import io +import shutil +import tarfile +import tempfile +from pathlib import Path +from typing import Any + +import yaml + +from devops_cli.config.constants import ( + CONST_CANONICAL_OCI_SOURCE, + CONST_K8S_ARGOCD_APPLICATION_DIRS, + CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS, +) +from devops_cli.config.defaults import DEFAULT_SUBPROCESS_TIMEOUT_SECONDS +from devops_cli.core.process import run_subprocess +from devops_cli.exceptions.k8s import ArgoCDGateError, KubernetesError +from devops_cli.k8s.argocd_overrides import _host_fields +from devops_cli.k8s.template import build_manifest_path, holds_template_domain_value + + +def _normalize_git_url(url: str) -> str: + """Normalize git URLs for origin comparison.""" + norm = url.strip().rstrip("/") + if norm.endswith(".git"): + norm = norm[:-4] + if norm.startswith("git@github.com:"): + norm = f"https://github.com/{norm[len('git@github.com:') :]}" + elif norm.startswith("ssh://git@github.com/"): + norm = f"https://github.com/{norm[len('ssh://git@github.com/') :]}" + return norm + + +def _get_repo_origin(root: Path) -> str: + """Determine expected origin URL from git config, falling back to canonical source.""" + proc = run_subprocess( + ["git", "-C", str(root), "config", "--get", "remote.origin.url"], + capture_output=True, + text=True, + check=False, + ) + if proc.returncode == 0 and proc.stdout and proc.stdout.strip(): + return _normalize_git_url(proc.stdout.strip()) + return _normalize_git_url(CONST_CANONICAL_OCI_SOURCE) + + +def _load_applications_from_file(file_path: Path) -> list[tuple[str, dict[str, Any]]]: + """Load kind: Application documents from a single yaml file.""" + if file_path.name == "projects.yaml" or file_path.suffix.lower() not in (".yaml", ".yml"): + return [] + try: + content = file_path.read_text(encoding="utf-8") + docs = list(yaml.safe_load_all(content)) + except yaml.YAMLError, OSError, UnicodeDecodeError: + return [] + apps: list[tuple[str, dict[str, Any]]] = [] + for doc in docs: + if isinstance(doc, dict) and doc.get("kind") == "Application": + name = doc.get("metadata", {}).get("name") + if isinstance(name, str) and name: + apps.append((name, doc)) + return apps + + +def discover_argocd_applications(repo_root: Path) -> dict[str, dict[str, Any]]: + """Discover every kind: Application in k8s/argocd/apps and k8s/argocd/bootstrap.""" + apps: dict[str, dict[str, Any]] = {} + for rel_dir in CONST_K8S_ARGOCD_APPLICATION_DIRS: + target_dir = repo_root / rel_dir + if not target_dir.is_dir(): + continue + for file_path in sorted(target_dir.iterdir()): + for name, doc in _load_applications_from_file(file_path): + apps[name] = doc + return apps + + +def discover_path_applications(repo_root: Path, apps_dir: Path | None = None) -> dict[str, Path]: + """Discover applications with a git source path, optionally filtered by directory.""" + all_apps = discover_argocd_applications(repo_root) + result: dict[str, Path] = {} + for name, doc in all_apps.items(): + spec = doc.get("spec", {}) + source = spec.get("source", {}) + path_str = source.get("path") + if not path_str: + continue + target_path = repo_root / path_str + if apps_dir is not None: + source_file = apps_dir / f"{name}.yaml" + if not source_file.is_file(): + source_file_yml = apps_dir / f"{name}.yml" + if not source_file_yml.is_file(): + continue + result[name] = target_path + return result + + +def _json_pointer_escape(token: str) -> str: + """Escape tokens per RFC 6901 JSON pointer specification.""" + return token.replace("~", "~0").replace("/", "~1") + + +def find_template_domain_occurrences(obj: Any, pointer: str = "") -> list[tuple[str, str]]: + """Find all JSON pointers and values where template domain values appear.""" + occurrences: list[tuple[str, str]] = [] + if isinstance(obj, dict): + for k, v in obj.items(): + k_str = str(k) + k_esc = _json_pointer_escape(k_str) + child_pointer = f"{pointer}/{k_esc}" + if holds_template_domain_value(k_str): + occurrences.append((f"{child_pointer}#key", k_str)) + occurrences.extend(find_template_domain_occurrences(v, child_pointer)) + elif isinstance(obj, list): + for i, item in enumerate(obj): + child_pointer = f"{pointer}/{i}" + occurrences.extend(find_template_domain_occurrences(item, child_pointer)) + elif isinstance(obj, str): + if holds_template_domain_value(obj): + occurrences.append((pointer, obj)) + return occurrences + + +def _check_helm_source(app_name: str, helm_source: dict[str, Any], root: Path) -> list[str]: + """Check value files of a Helm chart source for existence, YAML syntax, and placeholders.""" + errors: list[str] = [] + helm_conf = helm_source.get("helm", {}) + value_files = helm_conf.get("valueFiles", []) + + for vf in value_files: + rel_path = vf.split("/", 1)[1] if vf.startswith("$") else vf + val_path = root / rel_path + if not val_path.is_file(): + errors.append(f"Helm value file '{rel_path}' does not exist") + continue + try: + val_text = val_path.read_text(encoding="utf-8") + val_docs = list(yaml.safe_load_all(val_text)) + except (yaml.YAMLError, OSError, UnicodeDecodeError) as e: + errors.append(f"Helm value file '{rel_path}' failed to parse: {e}") + continue + + for doc in val_docs: + if not isinstance(doc, dict): + continue + for ptr, val in find_template_domain_occurrences(doc): + errors.append( + f"Placeholder domain value '{val}' at Helm value file {rel_path} {ptr}" + ) + return errors + + +def _check_rendered_doc_placeholders(app_name: str, doc: dict[str, Any]) -> list[str]: + """Validate that placeholders appear only in authorized host fields of homelab applications.""" + errors: list[str] = [] + doc_kind = doc.get("kind", "Unknown") + doc_name = doc.get("metadata", {}).get("name", "unknown") + doc_id = f"{doc_kind}/{doc_name}" + + allowed_pointers = ( + {ptr for ptr, _ in _host_fields(doc)} + if app_name in CONST_K8S_ARGOCD_HOMELAB_APPLICATIONS + else set() + ) + + for ptr, val in find_template_domain_occurrences(doc): + if ptr not in allowed_pointers: + errors.append( + f"Placeholder domain value '{val}' at {doc_id} {ptr} " + f"is not permitted in application '{app_name}'" + ) + return errors + + +def _check_path_source(app_name: str, source: dict[str, Any], root: Path) -> list[str]: + """Validate and build an application path source with kustomize or yaml parsing.""" + errors: list[str] = [] + path_str = source.get("path", "") + target_path = (root / path_str).resolve() + root_resolved = root.resolve() + + if not target_path.is_relative_to(root_resolved): + return [f"Path '{path_str}' leaves repository tree"] + if (target_path / "Chart.yaml").exists(): + return [f"Path '{path_str}' holds Chart.yaml and cannot be built offline"] + if not target_path.exists(): + return [f"Path '{path_str}' does not exist"] + + try: + rendered = build_manifest_path(target_path) + except (KubernetesError, OSError) as e: + msg = e.message if isinstance(e, KubernetesError) else str(e) + return [f"Kustomize build failed for path '{path_str}': {msg}"] + + try: + docs = list(yaml.safe_load_all(rendered)) + except yaml.YAMLError as e: + return [f"Rendered output for path '{path_str}' failed to parse: {e}"] + + for doc in docs: + if isinstance(doc, dict): + errors.extend(_check_rendered_doc_placeholders(app_name, doc)) + + return errors + + +def _check_application( + name: str, doc: dict[str, Any], root: Path, expected_origin: str +) -> list[str]: + """Check a single Argo CD Application's sources and manifests.""" + errors: list[str] = [] + spec = doc.get("spec", {}) + sources: list[dict[str, Any]] = ( + spec.get("sources", []) if "sources" in spec else [spec.get("source", {})] + ) + + for s in sources: + if not isinstance(s, dict): + continue + repo_url = s.get("repoURL") + if "chart" not in s and repo_url: + norm_repo = _normalize_git_url(repo_url) + if norm_repo != expected_origin: + errors.append( + f"Git source repoURL '{repo_url}' is not repository origin '{expected_origin}'" + ) + if "chart" in s: + errors.extend(_check_helm_source(name, s, root)) + if "path" in s: + errors.extend(_check_path_source(name, s, root)) + + return errors + + +def _check_tree(tree_root: Path, *, origin_url: str | None = None) -> list[str]: + """Execute offline Argo CD gate over a repository filesystem tree.""" + apps = discover_argocd_applications(tree_root) + if not apps: + return [] + + if shutil.which("kubectl") is None: + raise ArgoCDGateError( + "kubectl is required to build Argo CD applications. " + "Run 'devops install-tools --tool kubectl'." + ) + + expected_origin = origin_url or _get_repo_origin(tree_root) + failures: dict[str, list[str]] = {} + + for name, doc in sorted(apps.items()): + app_errors = _check_application(name, doc, tree_root, expected_origin) + if app_errors: + failures[name] = app_errors + + if failures: + lines = [f"Argo CD gate failed for {len(failures)} application(s):"] + for app_name, reasons in sorted(failures.items()): + for r in reasons: + lines.append(f" - {app_name}: {r}") + raise ArgoCDGateError("\n".join(lines), failures=failures) + + return sorted(apps.keys()) + + +def check_argocd_gate( + root: Path, + *, + ref: str | None = None, + origin_url: str | None = None, +) -> list[str]: + """Check that every Argo CD application builds offline and adheres to placeholder invariants (#1343). + + If `ref` is provided, exports `git archive ` into a clean temporary directory first + so gitignored or uncommitted local files never reach the build. + """ + has_local_dirs = any((root / d).is_dir() for d in CONST_K8S_ARGOCD_APPLICATION_DIRS) + if not has_local_dirs and not (root / ".git").exists() and not (root / ".git").is_file(): + return [] + + if ref is None: + return _check_tree(root, origin_url=origin_url) + + expected_origin = origin_url or _get_repo_origin(root) + proc = run_subprocess( + ["git", "-C", str(root), "archive", ref], + capture_output=True, + text=False, + check=False, + timeout=DEFAULT_SUBPROCESS_TIMEOUT_SECONDS, + ) + if proc.returncode != 0: + err = ( + proc.stderr.decode("utf-8", errors="replace") + if isinstance(proc.stderr, bytes) + else str(proc.stderr or "") + ) + raise ArgoCDGateError(f"Failed to export git archive for '{ref}': {err.strip()}") + + with tempfile.TemporaryDirectory() as tmp_dir: + tmp_path = Path(tmp_dir) + raw_bytes = ( + proc.stdout + if isinstance(proc.stdout, bytes) + else str(proc.stdout or "").encode("utf-8") + ) + with tarfile.open(fileobj=io.BytesIO(raw_bytes)) as tar: + tar.extractall(path=tmp_path, filter="data") + return _check_tree(tmp_path, origin_url=expected_origin) diff --git a/src/devops_cli/k8s/template.py b/src/devops_cli/k8s/template.py index bd35ca4260..52ca530c34 100644 --- a/src/devops_cli/k8s/template.py +++ b/src/devops_cli/k8s/template.py @@ -8,6 +8,7 @@ from typing import Any from devops_cli.config.constants import ( + CONST_K8S_KUSTOMIZATION_NAMES, CONST_K8S_SUBDOMAIN_RE, CONST_K8S_TEMPLATE_DOMAIN_PLACEHOLDER, CONST_K8S_TEMPLATE_DOMAIN_VARS, @@ -18,8 +19,6 @@ from devops_cli.core.process import run_subprocess from devops_cli.exceptions.k8s import KubernetesContextError -_KUSTOMIZATION_NAMES: tuple[str, ...] = ("kustomization.yaml", "kustomization.yml", "Kustomization") - def normalize_domain(domain: str) -> str: """Normalize and validate a target domain string for template substitution.""" @@ -56,6 +55,18 @@ def resolve_template_domain(domain_override: str | None = None) -> str: ) +def holds_template_domain_value(text: str) -> bool: + """Whether `text` contains the placeholder domain or a template domain variable (#1343).""" + if not text: + return False + if re.search(re.escape(CONST_K8S_TEMPLATE_DOMAIN_PLACEHOLDER), text, re.IGNORECASE): + return True + return any( + f"${{{var_name}}}" in text or f"${var_name}" in text + for var_name in CONST_K8S_TEMPLATE_DOMAIN_VARS + ) + + def render_manifest_template( content: str, domain: str, @@ -84,12 +95,8 @@ def render_manifest_template( return rendered -def _render_kustomize_dir( - target_dir: Path, - domain: str, - extra_vars: dict[str, str] | None = None, -) -> str: - """Run kustomize build on a directory and substitute domain variables.""" +def _build_kustomize_dir(target_dir: Path) -> str: + """Run kustomize build on a directory without template substitution.""" cmd = ["kubectl", "kustomize", str(target_dir)] proc = run_subprocess( cmd, @@ -101,15 +108,11 @@ def _render_kustomize_dir( if proc.returncode != 0: err_msg = (proc.stderr or proc.stdout or "kubectl kustomize failed").strip() raise KubernetesContextError(f"Kustomize build failed for '{target_dir}': {err_msg}") - return render_manifest_template(proc.stdout or "", domain=domain, extra_vars=extra_vars) + return proc.stdout or "" -def _render_yaml_dir( - target_dir: Path, - domain: str, - extra_vars: dict[str, str] | None = None, -) -> str: - """Read all YAML files in a directory and render them as a combined stream.""" +def _build_yaml_dir(target_dir: Path) -> str: + """Read all YAML files in a directory and return them as a combined stream.""" yaml_files = sorted( f for f in target_dir.iterdir() @@ -119,28 +122,32 @@ def _render_yaml_dir( raise KubernetesContextError(f"No YAML manifests found in directory: {target_dir}") parts = [yf.read_text(encoding="utf-8") for yf in yaml_files] - combined = "\n---\n".join(parts) - return render_manifest_template(combined, domain=domain, extra_vars=extra_vars) + return "\n---\n".join(parts) -def render_manifest_path( - path: str | Path, - domain: str, - extra_vars: dict[str, str] | None = None, -) -> str: - """Render a manifest file or directory with domain and template variables substituted.""" +def build_manifest_path(path: str | Path) -> str: + """Build a manifest file or directory without domain and template substitution (#1343).""" target = Path(path).resolve() if not target.exists(): raise KubernetesContextError(f"Manifest path not found: {path}") if target.is_file(): - raw_text = target.read_text(encoding="utf-8") - return render_manifest_template(raw_text, domain=domain, extra_vars=extra_vars) + return target.read_text(encoding="utf-8") if target.is_dir(): - has_kustomize = any((target / kf).exists() for kf in _KUSTOMIZATION_NAMES) + has_kustomize = any((target / kf).exists() for kf in CONST_K8S_KUSTOMIZATION_NAMES) if has_kustomize: - return _render_kustomize_dir(target, domain=domain, extra_vars=extra_vars) - return _render_yaml_dir(target, domain=domain, extra_vars=extra_vars) + return _build_kustomize_dir(target) + return _build_yaml_dir(target) raise KubernetesContextError(f"Invalid manifest target path: {path}") + + +def render_manifest_path( + path: str | Path, + domain: str, + extra_vars: dict[str, str] | None = None, +) -> str: + """Render a manifest file or directory with domain and template variables substituted.""" + raw = build_manifest_path(path) + return render_manifest_template(raw, domain=domain, extra_vars=extra_vars) diff --git a/src/devops_cli/release/cut.py b/src/devops_cli/release/cut.py index c4d4462dd2..875280a27d 100644 --- a/src/devops_cli/release/cut.py +++ b/src/devops_cli/release/cut.py @@ -71,6 +71,7 @@ "print_warning": ("devops_cli.output", "print_warning"), "print_table": ("devops_cli.output", "print_table"), "format_code_span": ("devops_cli.output", "format_code_span"), + "check_argocd_gate": ("devops_cli.k8s.argocd_gate", "check_argocd_gate"), } @@ -1063,6 +1064,7 @@ def cut_release( release_branch = f"release/v{target_ver}" remote_ref = f"origin/{release_branch}" _fetch_remote_release_tip(root, release_branch) + _get("check_argocd_gate")(root, ref=remote_ref) _checkout_cut_branch(root, cut_branch, remote_ref) if is_prepare: diff --git a/tests/test_k8s_argocd_apps.py b/tests/test_k8s_argocd_apps.py index 9a034df949..e7ef2261ae 100644 --- a/tests/test_k8s_argocd_apps.py +++ b/tests/test_k8s_argocd_apps.py @@ -220,19 +220,19 @@ def test_projects_whitelists_and_orphaned_resources() -> None: # ── Ownership & No Duplicates ──────────────────────────────────────────────── +def test_this_repository_passes_the_argocd_gate() -> None: + """The repository passes the offline Argo CD gate, verifying all applications at the head (#1343).""" + from devops_cli.k8s.argocd_gate import check_argocd_gate + + built = check_argocd_gate(REPO_ROOT) + assert len(built) >= 23 + + def test_rendered_raw_objects_single_ownership() -> None: + from devops_cli.k8s.argocd_gate import discover_path_applications + apps = _all_applications() - raw_leaf_apps = { - "base": K8S_DIR, - "monitoring": K8S_DIR / "monitoring", - "llm": K8S_DIR / "llm", - "otel": K8S_DIR / "otel", - "logging": K8S_DIR / "logging", - "devops": K8S_DIR / "overlays" / "homelab" / "devops", - "ingress": K8S_DIR / "overlays" / "homelab" / "ingress", - "gpu-feature-discovery": K8S_DIR / "gpu-feature-discovery", - "agents": K8S_DIR / "agents", - } + raw_leaf_apps = discover_path_applications(REPO_ROOT, APPS_DIR) seen_objects: dict[tuple[str, str, str, str], str] = {} namespaces_declared: list[str] = [] @@ -282,17 +282,9 @@ def test_rendered_raw_objects_single_ownership() -> None: def test_namespace_and_pvc_data_safety() -> None: - raw_leaf_apps = [ - K8S_DIR, - K8S_DIR / "monitoring", - K8S_DIR / "llm", - K8S_DIR / "otel", - K8S_DIR / "logging", - K8S_DIR / "overlays" / "homelab" / "devops", - K8S_DIR / "overlays" / "homelab" / "ingress", - K8S_DIR / "gpu-feature-discovery", - K8S_DIR / "agents", - ] + from devops_cli.k8s.argocd_gate import discover_path_applications + + raw_leaf_apps = list(discover_path_applications(REPO_ROOT, APPS_DIR).values()) for dir_path in raw_leaf_apps: proc = subprocess.run( diff --git a/tests/test_k8s_argocd_gate.py b/tests/test_k8s_argocd_gate.py new file mode 100644 index 0000000000..4fc29cd720 --- /dev/null +++ b/tests/test_k8s_argocd_gate.py @@ -0,0 +1,317 @@ +"""Tests for the deterministic offline Argo CD application build gate (#1343).""" + +from __future__ import annotations + +import subprocess +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest +import yaml + +from devops_cli.exceptions.k8s import ArgoCDGateError +from devops_cli.k8s.argocd_gate import check_argocd_gate + + +def _git_run(cwd: Path, *args: str) -> str: + res = subprocess.run( + ["git", *args], + cwd=cwd, + check=True, + capture_output=True, + text=True, + ) + return res.stdout.strip() + + +def _write_app( + tree: Path, + name: str, + *, + path: str | None = None, + repo_url: str = "https://github.com/dan-petty/devops-cli", + value_files: list[str] | None = None, + chart: str | None = None, + is_bootstrap: bool = False, +) -> None: + target_dir = tree / ("k8s/argocd/bootstrap" if is_bootstrap else "k8s/argocd/apps") + target_dir.mkdir(parents=True, exist_ok=True) + app_file = target_dir / f"{name}.yaml" + + spec: dict[str, Any] = { + "project": "homelab", + "destination": {"server": "https://kubernetes.default.svc", "namespace": name}, + } + + if chart is not None: + spec["sources"] = [ + { + "repoURL": "https://example.com/charts", + "chart": chart, + "targetRevision": "1.0.0", + "helm": {"valueFiles": value_files or []}, + }, + { + "repoURL": repo_url, + "targetRevision": "main", + "ref": "values", + }, + ] + elif path is not None: + spec["source"] = { + "repoURL": repo_url, + "targetRevision": "main", + "path": path, + } + + doc = { + "apiVersion": "argoproj.io/v1alpha1", + "kind": "Application", + "metadata": {"name": name, "namespace": "argocd"}, + "spec": spec, + } + app_file.write_text(yaml.dump(doc), encoding="utf-8") + + +def test_a_kustomization_that_lists_a_missing_file_fails(tmp_path: Path) -> None: + _write_app(tmp_path, "broken", path="k8s/broken") + app_dir = tmp_path / "k8s" / "broken" + app_dir.mkdir(parents=True) + (app_dir / "kustomization.yaml").write_text( + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + "resources:\n" + " - nonexistent.yaml\n", + encoding="utf-8", + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("broken" in err, "nonexistent.yaml" in err) == (True, True) + + +def test_a_placeholder_in_a_configmap_of_devops_fails(tmp_path: Path) -> None: + _write_app(tmp_path, "devops", path="k8s/overlays/homelab/devops") + devops_dir = tmp_path / "k8s" / "overlays" / "homelab" / "devops" + devops_dir.mkdir(parents=True) + (devops_dir / "kustomization.yaml").write_text( + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + "resources:\n" + " - configmap.yaml\n", + encoding="utf-8", + ) + (devops_dir / "configmap.yaml").write_text( + "apiVersion: v1\n" + "kind: ConfigMap\n" + "metadata:\n" + " name: devops-config\n" + "data:\n" + " endpoint: http://example.com\n", + encoding="utf-8", + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("devops" in err, "ConfigMap/devops-config" in err, "/data/endpoint" in err) == ( + True, + True, + True, + ) + + +def test_a_placeholder_ingress_host_in_a_non_homelab_application_fails(tmp_path: Path) -> None: + _write_app(tmp_path, "monitoring", path="k8s/monitoring") + mon_dir = tmp_path / "k8s" / "monitoring" + mon_dir.mkdir(parents=True) + (mon_dir / "kustomization.yaml").write_text( + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + "resources:\n" + " - ingress.yaml\n", + encoding="utf-8", + ) + (mon_dir / "ingress.yaml").write_text( + "apiVersion: networking.k8s.io/v1\n" + "kind: Ingress\n" + "metadata:\n" + " name: grafana-ingress\n" + "spec:\n" + " rules:\n" + " - host: grafana.example.com\n", + encoding="utf-8", + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("monitoring" in err, "Ingress/grafana-ingress" in err, "/spec/rules/0/host" in err) == ( + True, + True, + True, + ) + + +def test_a_placeholder_in_a_helm_value_file_fails(tmp_path: Path) -> None: + _write_app( + tmp_path, + "loki", + chart="loki", + value_files=["$values/k8s/logging/loki-values.yaml"], + ) + val_dir = tmp_path / "k8s" / "logging" + val_dir.mkdir(parents=True) + (val_dir / "loki-values.yaml").write_text( + "external_url: https://example.com\n", encoding="utf-8" + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("loki" in err, "loki-values.yaml" in err, "/external_url" in err) == ( + True, + True, + True, + ) + + +def test_a_missing_value_file_fails(tmp_path: Path) -> None: + _write_app( + tmp_path, + "loki", + chart="loki", + value_files=["$values/k8s/logging/missing-values.yaml"], + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("loki" in err, "missing-values.yaml" in err) == (True, True) + + +def test_a_path_holding_chart_yaml_fails(tmp_path: Path) -> None: + _write_app(tmp_path, "custom", path="k8s/custom") + custom_dir = tmp_path / "k8s" / "custom" + custom_dir.mkdir(parents=True) + (custom_dir / "Chart.yaml").write_text( + "apiVersion: v2\nname: custom\nversion: 0.1.0\n", encoding="utf-8" + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("custom" in err, "Chart.yaml" in err) == (True, True) + + +def test_a_git_source_with_another_repourl_fails(tmp_path: Path) -> None: + _write_app( + tmp_path, + "foreign", + path="k8s/foreign", + repo_url="https://github.com/different-org/different-repo", + ) + foreign_dir = tmp_path / "k8s" / "foreign" + foreign_dir.mkdir(parents=True) + (foreign_dir / "manifest.yaml").write_text( + "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: foreign-cm\n", + encoding="utf-8", + ) + + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert ("foreign" in err, "different-org/different-repo" in err) == (True, True) + + +def test_a_clean_tree_passes_and_names_each_application_it_built(tmp_path: Path) -> None: + _write_app(tmp_path, "app-a", path="k8s/app-a") + a_dir = tmp_path / "k8s" / "app-a" + a_dir.mkdir(parents=True) + (a_dir / "kustomization.yaml").write_text( + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + "resources:\n" + " - cm.yaml\n", + encoding="utf-8", + ) + (a_dir / "cm.yaml").write_text( + "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: clean-cm\n", + encoding="utf-8", + ) + + _write_app( + tmp_path, + "app-b", + chart="my-chart", + value_files=["$values/k8s/my-values.yaml"], + ) + (tmp_path / "k8s" / "my-values.yaml").write_text("replicas: 2\n", encoding="utf-8") + + built = check_argocd_gate(tmp_path) + assert built == ["app-a", "app-b"] + + +def test_a_tree_with_no_k8s_argocd_passes(tmp_path: Path) -> None: + built = check_argocd_gate(tmp_path) + assert built == [] + + +def test_a_missing_kubectl_fails_naming_devops_install_tools(tmp_path: Path) -> None: + _write_app(tmp_path, "clean-app", path="k8s/clean-app") + app_dir = tmp_path / "k8s" / "clean-app" + app_dir.mkdir(parents=True) + (app_dir / "cm.yaml").write_text( + "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: clean-cm\n", + encoding="utf-8", + ) + + with patch("shutil.which", return_value=None): + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(tmp_path) + + err = str(exc_info.value) + assert "devops install-tools --tool kubectl" in err + + +def test_a_file_in_working_tree_but_not_in_commit_does_not_reach_the_build(tmp_path: Path) -> None: + repo = tmp_path / "repo" + repo.mkdir() + _git_run(repo, "init", "--quiet") + _git_run(repo, "config", "user.name", "Tester") + _git_run(repo, "config", "user.email", "test@example.com") + + _write_app(repo, "tested-app", path="k8s/tested-app") + app_dir = repo / "k8s" / "tested-app" + app_dir.mkdir(parents=True) + (app_dir / "kustomization.yaml").write_text( + "apiVersion: kustomize.config.k8s.io/v1beta1\n" + "kind: Kustomization\n" + "resources:\n" + " - uncommitted.yaml\n", + encoding="utf-8", + ) + _git_run(repo, "add", "-A") + _git_run(repo, "commit", "--quiet", "-m", "init commit") + + # Now create uncommitted.yaml in the working tree only: + (app_dir / "uncommitted.yaml").write_text( + "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: uncommitted-cm\n", + encoding="utf-8", + ) + + # Building from HEAD via git archive will not see uncommitted.yaml: + with pytest.raises(ArgoCDGateError) as exc_info: + check_argocd_gate(repo, ref="HEAD") + + err = str(exc_info.value) + assert ("tested-app" in err, "uncommitted.yaml" in err) == (True, True) diff --git a/tests/test_release.py b/tests/test_release.py index 2f9303e8a4..7208e50182 100644 --- a/tests/test_release.py +++ b/tests/test_release.py @@ -2158,6 +2158,65 @@ def mock_gh(cmd: list[str], *args: Any, **kwargs: Any) -> subprocess.CompletedPr ) == (True, "release/v0.2.26", tip, "", refs, []) +def test_an_argocd_gate_failure_stops_the_cut_before_it_writes_or_pushes( + git_release_repo: tuple[Path, Path], +) -> None: + """The cut verifies every Argo CD application at origin's release tip before writing or branching (#1343). + + The clone stays on its original branch with nothing checked out or changed, and neither git + nor gh reaches origin. + """ + origin, clone = git_release_repo + _git_out(clone, "checkout", "-q", "release/v0.2.26") + app_dir = clone / "k8s" / "argocd" / "apps" + app_dir.mkdir(parents=True, exist_ok=True) + (app_dir / "bad-app.yaml").write_text( + "apiVersion: argoproj.io/v1alpha1\n" + "kind: Application\n" + "metadata:\n" + " name: bad-app\n" + "spec:\n" + " source:\n" + " repoURL: https://github.com/dan-petty/devops-cli\n" + " path: k8s/apps/bad-app\n", + encoding="utf-8", + ) + bad_path = clone / "k8s" / "apps" / "bad-app" + bad_path.mkdir(parents=True, exist_ok=True) + (bad_path / "kustomization.yaml").write_text( + "resources:\n - nonexistent.yaml\n", encoding="utf-8" + ) + _git_out(clone, "add", "-A") + _git_out(clone, "commit", "-q", "-m", "feat: break bad-app") + _git_out(clone, "push", "-q", "origin", "release/v0.2.26") + _git_out(clone, "checkout", "-q", "feature/my-work") + clone_tip = _git_out(clone, "rev-parse", "HEAD") + refs = _git_out(origin, "for-each-ref") + gh_calls: list[list[str]] = [] + + def mock_gh(cmd: list[str], *args: Any, **kwargs: Any) -> subprocess.CompletedProcess[str]: + gh_calls.append(cmd) + return subprocess.CompletedProcess(args=cmd, returncode=0, stdout="", stderr="") + + from devops_cli.commands.release import cut_release + from devops_cli.exceptions.k8s import ArgoCDGateError + + with ( + patch("devops_cli.commands.release.run_gh", side_effect=mock_gh), + pytest.raises(ArgoCDGateError) as refused, + ): + cut_release(version="0.2.26", repo_root=clone, is_prepare=True, sync_docs=False) + + assert ( + "bad-app" in refused.value.message, + _git_out(clone, "branch", "--show-current"), + _git_out(clone, "rev-parse", "HEAD"), + _git_out(clone, "status", "--porcelain"), + _git_out(origin, "for-each-ref"), + gh_calls, + ) == (True, "feature/my-work", clone_tip, "", refs, []) + + @pytest.mark.parametrize( "remove", [