From 9ef56ececbb6670e29df5411aa4a3029a1bfd219 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Wed, 7 Oct 2026 07:04:20 -0500 Subject: [PATCH 01/10] docs: explain optional repair verification Assisted-by: Codex:GPT-6 --- README.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/README.md b/README.md index fd647dae2..9fd3821ea 100644 --- a/README.md +++ b/README.md @@ -616,6 +616,42 @@ For deprecated hook you need to specify each argument separately: ] ``` +#### Verify a declared repair (optional) + +Checkov's `--baseline` option reports new failures, which is useful when a +project has accepted existing findings. A zero exit with a baseline does not +prove that one of those existing findings was fixed. For that question, a +project can compare full JSON reports from before and after scans and require +the same check and resource to fail before and pass after. The comparison also +needs to handle skipped checks, parsing errors, and missing results. + +For teams that want the paired comparison packaged as a released tool, +[IaC-Guard-V 1.0's repo-local recipe](https://github.com/lokesh0186/iac-guard-v/blob/main/adoption/pre-commit-terraform-v1/README.md) +checks one declared repair using Checkov 3.3.0. It keeps a canonical report and +returns nonzero when the selected result is failed or inconclusive. It requires +separate Python environments for IaC-Guard-V and Checkov. The recipe shows how +to set the before and after paths, exact target, and executable paths. It +includes the script for this optional hook: + +```yaml +- repo: local + hooks: + - id: iac-guard-v-verify-repair + name: Verify declared Terraform repair + entry: scripts/verify-iac-repair.sh + language: script + pass_filenames: false + always_run: true + require_serial: true +``` + +Use this with a trusted, project-owned before/after pair and an exact target. +It checks that target under Checkov's rule; it does not validate every resource +or the rule itself. Trivy also supports [passing results](https://trivy.dev/docs/latest/references/configuration/cli/trivy_config/) +and [custom checks](https://www.trivy.dev/docs/latest/guide/scanner/misconfiguration/config/config/) +for projects that want to build their own workflow around its scans. This +local hook is not part of pre-commit-terraform's hook manifest. + ### infracost_breakdown `infracost_breakdown` executes `infracost breakdown` command and compare the estimated costs with those specified in the hook-config. `infracost breakdown` parses Terraform HCL code, and calls Infracost Cloud Pricing API (remote version or [self-hosted version](https://www.infracost.io/docs/cloud_pricing_api/self_hosted)). From c999c0bb3ec336b98ca700f2e69da0f3ff7c78ed Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sat, 7 Nov 2026 14:36:08 -0600 Subject: [PATCH 02/10] feat: add IaC-Guard-V repair hook Use the published verifier through the current Python dispatcher, with explicit trusted repair inputs and retained fail-closed evidence. Provision an optional product venv around the selected Checkov installation without changing the ordinary scanner environment. Assisted-by: Codex:GPT-6 --- .github/.container-structure-test-config.yaml | 17 + .github/workflows/build-image-test.yaml | 55 +++ .pre-commit-hooks.yaml | 9 + Dockerfile | 11 + README.md | 202 +++++++- src/pre_commit_terraform/_cli_subcommands.py | 5 +- .../terraform_iac_guard_v.py | 279 +++++++++++ tests/iac_guard_v_integration_test.py | 228 +++++++++ tests/pytest/iac_guard_v_test.py | 443 ++++++++++++++++++ tools/install/iac-guard-v.sh | 40 ++ 10 files changed, 1266 insertions(+), 23 deletions(-) create mode 100644 src/pre_commit_terraform/terraform_iac_guard_v.py create mode 100644 tests/iac_guard_v_integration_test.py create mode 100644 tests/pytest/iac_guard_v_test.py create mode 100755 tools/install/iac-guard-v.sh diff --git a/.github/.container-structure-test-config.yaml b/.github/.container-structure-test-config.yaml index 98aeac0c4..71f95b7b2 100644 --- a/.github/.container-structure-test-config.yaml +++ b/.github/.container-structure-test-config.yaml @@ -29,6 +29,23 @@ commandTests: expectedOutput: - ^([0-9]+\.){2}[0-9]+\n$ +# This configuration targets the INSTALL_ALL image, as do the other tool tests. +- name: iac-guard-v + command: /opt/iac-guard-v/bin/python + args: + - -IBm + - iac_guard_v.cli + - --version + expectedOutput: + - .*1\.[0-9]+\.[0-9]+.* + +- name: iac-guard-v controlled scanner + command: /opt/iac-guard-v/scanner/checkov + args: + - --version + expectedOutput: + - ^([0-9]+\.){2}[0-9]+\n$ + - name: infracost command: infracost args: diff --git a/.github/workflows/build-image-test.yaml b/.github/workflows/build-image-test.yaml index 77f4d42f3..6c012f68c 100644 --- a/.github/workflows/build-image-test.yaml +++ b/.github/workflows/build-image-test.yaml @@ -11,6 +11,61 @@ env: IMAGE_TAG: pr-test jobs: + iac-guard-v: + name: IaC-Guard-V / Checkov ${{ matrix.checkov-version }} + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + matrix: + checkov-version: + - 3.3.0 + - 3.3.30 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Detect verification changes + id: changes + uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6 + with: + files: | + .github/workflows/build-image-test.yaml + .pre-commit-hooks.yaml + Dockerfile + pyproject.toml + hatch.toml + src/pre_commit_terraform/** + tools/install/** + tests/iac_guard_v_integration_test.py + + - name: Build qualified released-product image + if: steps.changes.outputs.any_changed == 'true' + env: + CHECKOV_VERSION: ${{ matrix.checkov-version }} + run: >- + docker build --tag iac-guard-v-test + --build-arg CHECKOV_VERSION="$CHECKOV_VERSION" + --build-arg IAC_GUARD_V_VERSION=1.0.2 . + + - name: Exercise released verifier and real pre-commit hook + if: steps.changes.outputs.any_changed == 'true' + run: | + mkdir -p .iacgv-test-results + docker run --rm \ + -v "$PWD:/source:ro" -v "$PWD/.iacgv-test-results:/evidence" \ + -e IACGV_TEST_PRODUCT=/opt/iac-guard-v/bin/python \ + -e IACGV_TEST_SCANNER=/opt/iac-guard-v/scanner/checkov \ + -e IACGV_TEST_HOOK_REPO=/source \ + -e IACGV_TEST_PRE_COMMIT=/usr/bin/pre-commit \ + -e IACGV_TEST_DIRECTORY=/evidence \ + --entrypoint /bin/sh iac-guard-v-test -c \ + ' + git config --global --add safe.directory /source + exec python3 -IB /source/tests/iac_guard_v_integration_test.py -v + ' + build: permissions: # for MaxymVlasov/dive-action to write comments to PRs diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index bd4e592c7..a086c2af8 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -149,6 +149,15 @@ exclude: \.terraform/.*$ require_serial: true +- id: terraform_iac_guard_v + name: IaC-Guard-V declared repair verification + description: Verify an explicit trusted before/after Terraform repair. + entry: python -Im pre_commit_terraform iac-guard-v + language: python + pass_filenames: false + require_serial: true + always_run: true + - id: terraform_wrapper_module_for_each name: Terraform wrapper with for_each in module description: Generate Terraform wrappers with for_each in module. diff --git a/Dockerfile b/Dockerfile index 291293bc9..29f9b7de4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -154,6 +154,17 @@ RUN if [ "$(grep -o '^terraform-docs SKIPPED$' /usr/bin/tools_versions_info)" = COPY tools/entrypoint.sh /entrypoint.sh +# IaC-Guard-V must bind the FINAL relocated Checkov installation. Keep this +# opt-in product environment separate from the global scanner and pre-commit. +ARG IAC_GUARD_V_VERSION=${IAC_GUARD_V_VERSION:-false} +ARG INSTALL_ALL=${INSTALL_ALL:-false} +RUN --mount=type=bind,source=tools/install,target=/install \ + if [ "$INSTALL_ALL" != "false" ]; then export IAC_GUARD_V_VERSION=latest; fi && \ + /install/iac-guard-v.sh && \ + if [ "$IAC_GUARD_V_VERSION" != "false" ]; then \ + /opt/iac-guard-v/bin/python -IBm iac_guard_v.cli --version >> /usr/bin/tools_versions_info; \ + else echo "iac-guard-v SKIPPED" >> /usr/bin/tools_versions_info; fi + ENV PRE_COMMIT_COLOR=${PRE_COMMIT_COLOR:-always} # DL3064 - empty default; real value passed via `-e` at runtime, never hardcoded diff --git a/README.md b/README.md index 9fd3821ea..865df4b25 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ If you want to support the development of `pre-commit-terraform` and [many other * [Keeping pinned versions up-to-date using Renovate](#keeping-pinned-versions-up-to-date-using-renovate) * [Many hooks: Parallelism](#many-hooks-parallelism) * [checkov (deprecated) and terraform\_checkov](#checkov-deprecated-and-terraform_checkov) + * [terraform\_iac\_guard\_v](#terraform_iac_guard_v) * [infracost\_breakdown](#infracost_breakdown) * [terraform\_docs](#terraform_docs) * [terraform\_docs\_replace (deprecated)](#terraform_docs_replace-deprecated) @@ -238,6 +239,7 @@ Full list of dependencies and where they are used: Hope that it all will work.

* [`checkov`][checkov repo] required for `terraform_checkov` hook +* [`iac-guard-v==1.0.2`](https://pypi.org/project/iac-guard-v/1.0.2/) and a qualified Checkov installation required for `terraform_iac_guard_v`; see its [separate installation instructions](#terraform_iac_guard_v) * [`terraform-docs`][terraform-docs repo] 0.12.0+ required for `terraform_docs` hook * [`terragrunt`][terragrunt repo] required for `terragrunt_validate` and `terragrunt_valid_inputs` hooks * [`terrascan`][terrascan repo] required for `terrascan` hook @@ -336,6 +338,7 @@ There are several [pre-commit](https://pre-commit.com/) hooks to keep Terraform | `terraform_docs_replace` | Runs `terraform-docs` and pipes the output directly to README.md. **DEPRECATED**, see [#248](https://github.com/antonbabenko/pre-commit-terraform/issues/248). [Hook notes](#terraform_docs_replace-deprecated) | `python3`, `terraform-docs` | | `terraform_docs_without_`
`aggregate_type_defaults` | Inserts input and output documentation into `README.md` without aggregate type defaults. Hook notes same as for [terraform_docs](#terraform_docs) | `terraform-docs` | | `terraform_fmt` | Reformat all Terraform configuration files to a canonical format. [Hook notes](#terraform_fmt) | - | +| `terraform_iac_guard_v` | Verify a declared trusted before/after Terraform repair with [IaC-Guard-V](https://github.com/lokesh0186/iac-guard-v). [Hook notes](#terraform_iac_guard_v) | Python 3.10+, separately installed `iac-guard-v==1.0.2` (Python 3.10–3.13), qualified Checkov | | `terraform_providers_lock` | Updates provider signatures in [dependency lock files](https://www.terraform.io/docs/cli/commands/providers/lock.html). [Hook notes](#terraform_providers_lock) | - | | `terraform_tflint` | Validates all Terraform configuration files with [TFLint][tflint repo]. [Available TFLint rules](https://github.com/terraform-linters/tflint-ruleset-terraform/blob/main/docs/rules/README.md). [Hook notes](#terraform_tflint). | `tflint` | | `terraform_tfsec` | [TFSec][tfsec repo] static analysis of terraform templates to spot potential security issues. **DEPRECATED**, use `terraform_trivy`. [Hook notes](#terraform_tfsec-deprecated) | `tfsec` | @@ -355,6 +358,10 @@ Check the [source file](https://github.com/antonbabenko/pre-commit-terraform/blo ### Known limitations +`terraform_iac_guard_v` uses its own explicit arguments and repository-level +execution; the generic argument/environment and parallelism options below do +not apply. See its [usage notes](#terraform_iac_guard_v). + Terraform operates on a per-dir basis, while `pre-commit` framework only supports files and files that exist. This means if you only remove the TF-related file without any other changes in the same dir, checks will be skipped. Example and details [here](https://github.com/pre-commit/pre-commit/issues/3048). ### All hooks: Usage of environment variables in `--args` @@ -625,32 +632,185 @@ project can compare full JSON reports from before and after scans and require the same check and resource to fail before and pass after. The comparison also needs to handle skipped checks, parsing errors, and missing results. -For teams that want the paired comparison packaged as a released tool, -[IaC-Guard-V 1.0's repo-local recipe](https://github.com/lokesh0186/iac-guard-v/blob/main/adoption/pre-commit-terraform-v1/README.md) -checks one declared repair using Checkov 3.3.0. It keeps a canonical report and -returns nonzero when the selected result is failed or inconclusive. It requires -separate Python environments for IaC-Guard-V and Checkov. The recipe shows how -to set the before and after paths, exact target, and executable paths. It -includes the script for this optional hook: +The optional [terraform_iac_guard_v](#terraform_iac_guard_v) hook packages that +bounded verification through published IaC-Guard-V 1.0.2. Trivy's +[passing results](https://trivy.dev/docs/latest/references/configuration/cli/trivy_config/) +and [custom checks](https://trivy.dev/docs/latest/guide/scanner/misconfiguration/config/config/) +are other building blocks for project-owned comparisons. + +### terraform_iac_guard_v + +Verifies a particular declared Terraform repair using **iac-guard-v==1.0.2**. +The operator supplies trusted before/after directories and an exact +`CHECK_ID=RESOURCE_ADDRESS[@FILE]` target. The product requires legitimate +before-fail/after-pass evidence for that same target, including scanner authority, +coverage, suppression, provenance and dependency integrity. A zero scanner exit +alone cannot establish a repair. This hook does not scan arbitrary staged files. + +#### Install on a host + +Use Python 3.10–3.13 for the product (3.12 is recommended and tested). The +pre-commit adapter requires Python 3.10+ and has no product/scanner dependencies +in its own environment. Provision the product and one scanner outside both +snapshots and outside candidate control. For example, from an operator-owned +location, using a current pip with `--python` support: + +```bash +IACGV_ROOT="$HOME/.local/share/iac-guard-v-1.0.2" +python3.12 -m venv --copies --without-pip "$IACGV_ROOT/product" +python3.12 -m venv --copies --without-pip "$IACGV_ROOT/checkov" +PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/product/bin/python" install --no-compile 'iac-guard-v==1.0.2' +PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/checkov/bin/python" install --no-compile 'checkov==3.3.30' +"$IACGV_ROOT/product/bin/python" -IBm iac_guard_v.cli doctor --mode local-trusted --checkov-executable "$IACGV_ROOT/checkov/bin/checkov" --format json +``` + +Require **both** `validator_registry.status` and `checkov.status` to be `PASS`; +doctor's process exit alone is insufficient. Keep a strict scanner environment +bytecode-free; do not run unrelated Python tools in it. This provisions one +scanner explicitly; the hook never downloads or installs tools. An existing +installation can be used only if it passes the released integrity contract. +Cached pipx/venv installations are not automatically qualified. + +#### Configure one repair request + +For an EBS encryption example, put this in `verification/before/main.tf`: + +```hcl +resource "aws_ebs_volume" "target" { + availability_zone = "us-east-1a" + size = 1 + encrypted = false +} +``` + +Copy it to `verification/after/main.tf` and change `encrypted` to `true`. +Keep the original snapshot, hook configuration and declared target operator +controlled. Candidate content must not choose the original defect, property, +expected target, verifier, scanner or policy. + +Use a release/commit containing this hook for `rev` below. Substitute the two +absolute executable paths from installation; args do not expand shell variables, +`~`, `--args`, `--env-vars` or `__GIT_WORKING_DIR__` placeholders. ```yaml -- repo: local +repos: +- repo: https://github.com/antonbabenko/pre-commit-terraform + rev: # Release/commit containing terraform_iac_guard_v hooks: - - id: iac-guard-v-verify-repair - name: Verify declared Terraform repair - entry: scripts/verify-iac-repair.sh - language: script - pass_filenames: false - always_run: true - require_serial: true + - id: terraform_iac_guard_v + args: + - --iacgv-python=/absolute/operator/iac-guard-v-1.0.2/product/bin/python + - --local-trusted + - --before=verification/before + - --after=verification/after + - --framework=terraform + - --target=CKV_AWS_3=aws_ebs_volume.target + - --checkov-executable=/absolute/operator/iac-guard-v-1.0.2/checkov/bin/checkov +``` + +Run `pre-commit run terraform_iac_guard_v --all-files`. Paths to snapshots are +relative to Git root, including when invoked from a nested directory; absolute +paths and paths containing spaces are supported. Repeat `--target` to declare +multiple exact targets. The released product validates selector syntax. + +The hook runs once per invocation (`pass_filenames: false`, `require_serial: true`) +and uses `always_run: true`, including config-only changes or an empty file +selection. This trades recurring verification cost for avoiding silently skipped +requests. It evaluates the explicit pair, not necessarily the staged working tree. +Disabling `always_run` can skip verification on configuration-only changes. +Each child process has a ten-minute limit; timeouts block the commit and retain +available logs. Verification includes full integrity checks and can be costly. + +Each invocation retains stdout/stderr and a canonical `report.json` in a fresh +mode-0700 directory under `/iac-guard-v/runs/`. Linked Git +worktrees use their own metadata. Reports must remain outside both snapshots; +symlinked report directories and candidate-owned runtimes are rejected. Existing +reports are never overwritten or deleted; operators manage retention. The hook +prints the evidence path. A typical successful run reports: + +```text +IaC-Guard-V process exit: 0 +VERIFIED; canonical report: .../report.json +``` + +A changed snapshot that retains the defective target reports `FAILED` and exits +1. Missing/ambiguous/deleted targets, incomplete evidence, scanner integrity +failures or unsupported profiles cannot produce success. Published verification +outcomes are `VERIFIED/0`, `FAILED/1`, `INCONCLUSIVE/3`; other product errors retain +their nonzero codes. For example byte-identical role snapshots are rejected as +`INVALID_REQUEST/2`, rather than treated as a successful repair. The outer +pre-commit process normalizes unsuccessful hook exits to 1; verbose output and +retained product reports distinguish the underlying outcomes. + +#### Docker installation and Checkov selection + +Build from this checkout with explicit versions: + +```bash +docker build -t pre-commit-iacgv \ + --build-arg CHECKOV_VERSION=3.3.30 \ + --build-arg IAC_GUARD_V_VERSION=1.0.2 . ``` -Use this with a trusted, project-owned before/after pair and an exact target. -It checks that target under Checkov's rule; it does not validate every resource -or the rule itself. Trivy also supports [passing results](https://trivy.dev/docs/latest/references/configuration/cli/trivy_config/) -and [custom checks](https://www.trivy.dev/docs/latest/guide/scanner/misconfiguration/config/config/) -for projects that want to build their own workflow around its scans. This -local hook is not part of pre-commit-terraform's hook manifest. +In the configuration above use `/opt/iac-guard-v/bin/python` for `--iacgv-python` +and `/opt/iac-guard-v/scanner/checkov` for `--checkov-executable`. Run with the +normal [Docker usage](#docker-usage), mounting the consumer repository at `/lint`. +Keep its Git metadata writable to retain reports. The image does not contain +the pre-commit hook checkout; pre-commit installs the configured hook revision. + +`IAC_GUARD_V_VERSION=false` is the default and installs no product environment. +An explicit pin or `latest` enables it. `INSTALL_ALL=true` selects `latest`, +overriding individual version arguments just like the existing tools. The tested +product baseline is 1.0.2; the adapter requires that exact product version. +Enabling the product without Checkov is a build-time setup error. + +The final image creates a separate `--system-site-packages` product venv and +uses the released controlled shared-installation launcher. Only small product +parser dependencies are copied locally at compatible versions; no second Checkov +or scanner dependency tree is installed. The ordinary `/usr/bin/checkov`, global +packages and `terraform_checkov` hook remain authoritative for ordinary scanning. +The launcher is prepared after final-image relocation and binds package, RECORD, +interpreter, dependency and policy identities. Rebuild after changing the trusted +installation; never edit the generated manifest to silence drift failures. + +IaC-Guard-V 1.0.2 explicitly qualifies Checkov versions **3.3.0–3.3.30**, with +**property-specific** profiles. The integration respects `CHECKOV_VERSION`, +including `latest`; it never substitutes 3.3.0. Unknown versions and unqualified +check/version combinations fail closed at verification time. Such a profile +failure does not prevent building an image for unrelated hooks. CKV_K8S_40's +manifest semantics are excluded from 3.3.8 onward; this is not blanket support +for every check or a Kubernetes hook. See the released +[compatibility contract](https://github.com/lokesh0186/iac-guard-v/blob/v1.0.2/docs/CHECKOV_COMPATIBILITY.md) +for the qualified properties and exact limits. + +#### Troubleshooting and scope + +- Missing product or Python environment mismatch: set `--iacgv-python` to the + absolute provisioned product Python, not pre-commit's Python. Check its version + with `-IBm iac_guard_v.cli --version`; inspect retained `runtime.*.log` files. +- Missing Checkov: install it explicitly before running the hook and supply its + absolute path. In Docker, enable `CHECKOV_VERSION` alongside the product. +- Unsupported version/property: inspect the canonical report for + `CHECKOV_VERSION_UNSUPPORTED_FOR_REQUESTED_PROPERTY`; select an explicitly + qualified pair. Do not replace the scanner silently or infer compatibility + from a recognizable check ID. +- Provenance/integrity mismatch: inspect doctor JSON and verification logs. + Recreate the operator-owned installation from published packages, preserving + RECORD and other validations. Do not delete or rewrite scanner files to pass. +- Malformed arguments or invalid inputs: provide every required option, distinct + snapshots and the exact resource/check selector; inspect request diagnostics. +- Inconclusive results: inspect `report.json` and scanner diagnostics for missing, + suppressed, ambiguous or incomplete evidence. Uncertainty blocks the commit. +- Report/setup errors: Git metadata must be writable, outside both snapshots, + without symlinked report parents. Existing evidence is retained on failure. + +Verification is read-only with respect to IaC; only private report/log directories +are written. It does not run init/apply, remediate code, deploy infrastructure or +prove universal infrastructure safety, cloud behavior or scanner equivalence. +This is the product's **trusted local, reduced-isolation** workflow, not a sandbox +for hostile code. Protect configuration, installations, environment and the +before state independently of candidate content. Ordinary scanning remains a +separate `terraform_checkov` hook. ### infracost_breakdown diff --git a/src/pre_commit_terraform/_cli_subcommands.py b/src/pre_commit_terraform/_cli_subcommands.py index ba7a6982d..8afc7fed2 100644 --- a/src/pre_commit_terraform/_cli_subcommands.py +++ b/src/pre_commit_terraform/_cli_subcommands.py @@ -1,11 +1,12 @@ """A CLI sub-commands organization module.""" -from . import terraform_docs_replace +from . import terraform_docs_replace, terraform_iac_guard_v from ._types import CLISubcommandModuleProtocol -SUBCOMMAND_MODULES: tuple[CLISubcommandModuleProtocol] = ( +SUBCOMMAND_MODULES: tuple[CLISubcommandModuleProtocol, ...] = ( terraform_docs_replace, + terraform_iac_guard_v, ) diff --git a/src/pre_commit_terraform/terraform_iac_guard_v.py b/src/pre_commit_terraform/terraform_iac_guard_v.py new file mode 100644 index 000000000..6a0ad0489 --- /dev/null +++ b/src/pre_commit_terraform/terraform_iac_guard_v.py @@ -0,0 +1,279 @@ +"""Verify an explicit trusted repair through the released product CLI. + +The pre-commit environment contains only this adapter. Product and scanner +environments are provisioned separately by the operator, never by the hook. +""" + +from __future__ import annotations + +import json +import logging +import os +import shutil + +# Only explicit operator-provisioned executables and argv; never a shell. +import subprocess # noqa: S404 +import tempfile +from argparse import Namespace +from pathlib import Path +from typing import TYPE_CHECKING, Final, cast + + +if TYPE_CHECKING: + from argparse import ArgumentParser + + +# Eight small module members keep parser, process and Git concerns explicit. +# flake8: noqa: WPS202 +CLI_SUBCOMMAND_NAME: Final[str] = 'iac-guard-v' +VERSION: Final[str] = '1.0.2' +TIMEOUT: Final[int] = 600 +PRIVATE_DIRECTORY_MODE: Final[int] = 0o700 +LOGGER = logging.getLogger(__name__) +INCONCLUSIVE: Final[int] = 3 +# Use the released schema, not a second definition of verification semantics. +REPORT_VALIDATOR: Final[str] = ( + 'import json, sys; from importlib.resources import files; ' + 'from jsonschema import validate; ' + 'schema = files("iac_guard_v").joinpath("schemas/report-v1.schema.json"); ' + 'validate(json.load(open(sys.argv[1])), json.loads(schema.read_text()))' +) + + +def _require(message: str, *, condition: bool) -> None: + if not condition: + raise ValueError(message) + + +def populate_argument_parser(parser: ArgumentParser) -> None: + """Accept only explicit inputs to the released local repair workflow.""" + parser.allow_abbrev = False + parser.add_argument('--iacgv-python', type=Path, required=True) + parser.add_argument('--local-trusted', action='store_true', required=True) + parser.add_argument('--before', type=Path, required=True) + parser.add_argument('--after', type=Path, required=True) + parser.add_argument('--framework', choices=('terraform',), required=True) + parser.add_argument('--target', action='append', required=True) + parser.add_argument('--checkov-executable', type=Path, required=True) + + +def _executable(path: Path, snapshots: tuple[Path, Path]) -> str: + _require( + f'Expected an absolute, executable operator-provisioned path: {path}', + condition=path.is_absolute() + and path.is_file() + and os.access(path, os.X_OK), + ) + # Preserve the venv selection as well as checking its final interpreter. + # A candidate bin/python symlink to a trusted system binary is still a + # candidate-owned Python environment. Directory aliases must not hide it. + locations = (path.parent.resolve() / path.name, path.resolve()) + _require( + 'Product and scanner runtimes must be outside both snapshots.', + condition=not any( + location.is_relative_to(snapshot) + for location in locations + for snapshot in snapshots + ), + ) + # Resolving a venv Python symlink would lose the selected environment. + return str(path) + + +class _Arguments(Namespace): + iacgv_python: Path + local_trusted: bool + before: Path + after: Path + framework: str + target: list[str] + checkov_executable: Path + + +def verification_command( + parsed: Namespace, + root: Path, + report: Path, +) -> list[str]: + """Resolve snapshots from Git root and preserve literal product arguments. + + Returns: + list[str]: The published verify invocation, without shell expansion. + """ + args = _Arguments(**cast('dict[str, object]', parsed.__dict__)) + before, after = ( + (root / args.before).resolve(), + (root / args.after).resolve(), + ) + _require( + 'Provide distinct existing trusted before/after directories.', + condition=before.is_dir() and after.is_dir() and before != after, + ) + _require( + 'Reports must remain outside both snapshots.', + condition=not any( + report.is_relative_to(path) for path in (before, after) + ), + ) + selectors: list[str] = [] + for target in args.target: + selectors.extend(('--target', target)) + return [ + _executable(args.iacgv_python, (before, after)), + '-I', + '-B', + '-m', + 'iac_guard_v.cli', + 'verify', + '--before', + str(before), + '--after', + str(after), + '--framework', + args.framework, + '--local-trusted', + '--checkov-executable', + _executable(args.checkov_executable, (before, after)), + *selectors, + '--format', + 'json', + '--output', + str(report), + '--quiet', + ] + + +def _git_path(git: str, option: str) -> Path: + # Git is resolved through the operator PATH, as in other hooks. + output = subprocess.check_output( # noqa: S603 + [git, 'rev-parse', option], + text=True, + timeout=TIMEOUT, + ) + return Path(output.removesuffix('\n')).resolve(strict=True) + + +class HookRun: + """Retain an exclusive report and process logs for each invocation.""" + + def __init__(self, parsed: Namespace) -> None: + """Find actual Git metadata, including linked worktrees.""" + git = shutil.which('git') + _require('Git must be installed.', condition=git is not None) + self.root = _git_path(str(git), '--show-toplevel') + metadata = _git_path(str(git), '--absolute-git-dir') + # Check overlap before any writes, including metadata directories. + verification_command( + parsed, + self.root, + metadata / 'iac-guard-v/runs/report.json', + ) + reports = metadata + for name in ('iac-guard-v', 'runs'): + reports /= name + _require( + 'Report directories must not be symlinks.', + condition=not reports.is_symlink(), + ) + reports.mkdir(mode=PRIVATE_DIRECTORY_MODE, exist_ok=True) + self.directory = Path(tempfile.mkdtemp(prefix='run-', dir=reports)) + self.report = self.directory / 'report.json' + + def verify(self, parsed: Namespace) -> int: + """Invoke the product once, preserving its classifications and exits. + + Returns: + int: Published exit, or 3 when transport evidence is invalid. + """ + command = verification_command(parsed, self.root, self.report) + runtime = self._process( + [ + command[0], + '-I', + '-B', + '-c', + ( + 'from importlib.metadata import version; ' + 'print(version("iac-guard-v"))' + ), + ], + 'runtime', + ) + _require( + 'Runtime requires published iac-guard-v==1.0.2; see runtime logs.', + condition=runtime == 0 + and (self.directory / 'runtime.stdout.log').read_text().strip() + == VERSION, + ) + code = self._process(command, 'verification') + LOGGER.warning('IaC-Guard-V process exit: %s', code) + if code not in {0, 1, INCONCLUSIVE}: + return code if code > 0 else INCONCLUSIVE + _require( + 'Canonical report missing or symlinked; see verification logs.', + condition=self.report.is_file() and not self.report.is_symlink(), + ) + validation = self._process( + [command[0], '-I', '-B', '-c', REPORT_VALIDATOR, str(self.report)], + 'schema', + ) + _require( + 'Invalid or incomplete canonical report; see schema logs.', + condition=validation == 0, + ) + payload = cast( + 'dict[str, object]', + json.loads(self.report.read_text()), + ) + # The schema validates headers/types; compare transport consistency. + _require( + 'Canonical verdict/exit does not match the product process.', + condition=payload.get('result_kind') + in {'verification', 'operational_uncertainty'} + and payload['exit_code'] == code + and payload.get('verdict') + == {0: 'VERIFIED', 1: 'FAILED', 3: 'INCONCLUSIVE'}[code], + ) + LOGGER.warning( + '%s; canonical report: %s', + payload['verdict'], + self.report, + ) + return code + + def _process(self, command: list[str], label: str) -> int: + with ( + (self.directory / f'{label}.stdout.log').open('x') as stdout, + (self.directory / f'{label}.stderr.log').open('x') as stderr, + ): + completed = subprocess.run( # noqa: S603 — explicit trusted executable, literal argv + command, + cwd=self.root, + env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), + stdout=stdout, + stderr=stderr, + check=False, + timeout=TIMEOUT, + ) + return completed.returncode + + +def invoke_cli_app(args: Namespace) -> int: + """Return nonzero on setup, execution or evidence transport errors. + + Returns: + int: Product exit or inconclusive transport failure. pre-commit itself + normalizes nonzero hook statuses to 1. + """ + try: # noqa: WPS229 — allocation, diagnostics and verification share one boundary + invocation = HookRun(args) + LOGGER.warning('IaC-Guard-V evidence: %s', invocation.directory) + return invocation.verify(args) + except (OSError, ValueError, subprocess.SubprocessError) as error: + LOGGER.warning('IaC-Guard-V setup/transport error: %s', error) + return INCONCLUSIVE + except KeyboardInterrupt: + LOGGER.warning( + 'IaC-Guard-V execution interrupted; no verified result.', + ) + return INCONCLUSIVE diff --git a/tests/iac_guard_v_integration_test.py b/tests/iac_guard_v_integration_test.py new file mode 100644 index 000000000..db1ed93cf --- /dev/null +++ b/tests/iac_guard_v_integration_test.py @@ -0,0 +1,228 @@ +"""Opt-in acceptance tests with provisioned, released runtimes. + +Run this file directly, not as part of the deterministic unit suite. Required +operator environment variables: IACGV_TEST_PRODUCT, IACGV_TEST_SCANNER, +IACGV_TEST_HOOK_REPO (a committed checkout), IACGV_TEST_PRE_COMMIT and +IACGV_TEST_DIRECTORY (new evidence directory). No dependencies are installed +by this test. pre-commit provisions its ordinary adapter environment. +""" + +# Standalone unittest runner; deliberately outside the pytest unit namespace. +# ruff: noqa: INP001, PT009 + +from __future__ import annotations + +import json +import os +import subprocess +import unittest +from pathlib import Path + + +BAD = ( + 'resource "aws_ebs_volume" "target" {\n' + ' availability_zone = "us-east-1a"\n' + ' size = 1\n' + ' encrypted = false\n}\n' +) +TARGET = 'CKV_AWS_3=aws_ebs_volume.target' +TIMEOUT = 900 +GIT = 'git' +AFTER = 'after' + + +class ReleasedProductTests(unittest.TestCase): + """Real scanner verdicts and real pre-commit process exits.""" + + def setUp(self) -> None: + """Create a fresh consumer per test and preserve all evidence.""" + self.product = os.environ['IACGV_TEST_PRODUCT'] + self.scanner = os.environ['IACGV_TEST_SCANNER'] + self.precommit = os.environ['IACGV_TEST_PRE_COMMIT'] + self.source = Path(os.environ['IACGV_TEST_HOOK_REPO']) + self.directory = Path(os.environ['IACGV_TEST_DIRECTORY']) / self.id() + self.directory.mkdir(parents=True, exist_ok=False) + self.root = self.directory / 'consumer with spaces; $literal [test]' + self.root.mkdir() + # CWD content must not shadow the isolated adapter/product imports. + (self.root / 'json.py').write_text( + 'raise RuntimeError("cwd import")\n', + ) + self._environment = dict( + os.environ, + PYTHONDONTWRITEBYTECODE='1', + PRE_COMMIT_HOME=str(self.directory.parent / 'precommit-cache'), + ) + self._sequence = 0 + self.command([GIT, 'init', '-q']) + for name, source in ( + ('before', BAD), + (AFTER, BAD.replace('false', 'true')), + ('unchanged', f'{BAD}# changed snapshot; same defect\n'), + ('deleted', 'locals { harmless = true }\n'), + ('duplicate', BAD + BAD), + ('malformed', 'resource { !!!'), + ( + 'wrong-resource', + BAD + + BAD.replace('"target"', '"other"').replace('false', 'true'), + ), + ( + 'suppressed', + BAD.replace( + ' size', + ' # checkov:skip=CKV_AWS_3:negative control\n size', + ), + ), + ): + path = self.root / name + path.mkdir() + (path / 'main.tf').write_text(source) + (self.root / 'after/second.tf').write_text( + 'locals { multiple = true }\n', + ) + + def command( + self, + arguments: list[str], + cwd: Path | None = None, + ) -> subprocess.CompletedProcess[str]: + """Retain literal test argv output and process status. + + Returns: + CompletedProcess: Observed process result. + """ + self._sequence += 1 + completed = subprocess.run( # noqa: S603 — explicit test commands, no shell + arguments, + cwd=cwd or self.root, + env=self._environment, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + check=False, + timeout=TIMEOUT, + ) + (self.directory / f'{self._sequence}.log').write_text(completed.stdout) + return completed + + def test_repair_verdicts(self) -> None: # noqa: WPS210 — explicit evidence per case + """Require real fail/pass evidence and reject negative controls.""" + for after, target, expected in ( + (AFTER, TARGET, 0), + ('unchanged', TARGET, 1), + ('wrong-resource', TARGET, None), + ('deleted', TARGET, None), + ('duplicate', TARGET, None), + ('malformed', TARGET, None), + ('suppressed', TARGET, None), + (AFTER, 'CKV_AWS_3=aws_ebs_volume.absent', None), + (AFTER, 'CKV_AWS_19=aws_ebs_volume.target', None), + ): + with self.subTest(after=after, target=target): + report = self.directory / f'report-{self._sequence}.json' + completed = self.command( + [ + self.product, + '-IBm', + 'iac_guard_v.cli', + 'verify', + '--before', + str(self.root / 'before'), + '--after', + str(self.root / after), + '--framework', + 'terraform', + '--local-trusted', + '--checkov-executable', + self.scanner, + '--target', + target, + '--format', + 'json', + '--output', + str(report), + '--quiet', + ], + ) + payload = json.loads( + report.read_text() + if report.exists() + else completed.stdout, + ) + self.assertEqual(completed.returncode, payload['exit_code']) + if expected is None: + self.assertNotEqual(completed.returncode, 0) + self.assertNotEqual(payload.get('verdict'), 'VERIFIED') + else: + self.assertEqual(completed.returncode, expected) + self.assertEqual( + payload['verdict'], + {0: 'VERIFIED', 1: 'FAILED', 3: 'INCONCLUSIVE'}[ + expected + ], + ) + + def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports and process evidence + """Exercise manifest metadata and different pre-commit selections.""" + revision = self.command( + [GIT, '-C', str(self.source), 'rev-parse', 'HEAD'], + ).stdout.strip() + arguments = [ + f'--iacgv-python={self.product}', + '--local-trusted', + '--before=before', + '--after=after', + '--framework=terraform', + f'--target={TARGET}', + f'--checkov-executable={self.scanner}', + ] + config = { + 'repos': [ + { + 'repo': str(self.source), + 'rev': revision, + 'hooks': [ + { + 'id': 'terraform_iac_guard_v', + 'args': arguments, + }, + ], + }, + ], + } + (self.root / '.pre-commit-config.yaml').write_text(json.dumps(config)) + self.command([GIT, 'add', '.']) + for files in ( + ['.pre-commit-config.yaml'], + ['after/main.tf', 'after/second.tf'], + [], + ): + with self.subTest(files=files): + reports = self.root / '.git/iac-guard-v/runs' + before = set(reports.glob('run-*')) + completed = self.command( + [ + self.precommit, + 'run', + 'terraform_iac_guard_v', + '--verbose', + '--files', + *files, + ], + cwd=self.root / AFTER, + ) + self.assertEqual(completed.returncode, 0, completed.stdout) + fresh = set(reports.glob('run-*')) - before + self.assertEqual(len(fresh), 1) + arguments[arguments.index('--after=after')] = '--after=unchanged' + (self.root / '.pre-commit-config.yaml').write_text(json.dumps(config)) + self.command([GIT, 'add', '.']) + failed = self.command( + [self.precommit, 'run', 'terraform_iac_guard_v', '--all-files'], + ) + self.assertEqual(failed.returncode, 1, failed.stdout) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py new file mode 100644 index 000000000..4e3a4ea66 --- /dev/null +++ b/tests/pytest/iac_guard_v_test.py @@ -0,0 +1,443 @@ +"""Deterministic transport tests; real product tests run separately.""" + +# Repeated boundary assertions keep failure scenarios independently legible. +# flake8: noqa: WPS204 + +from __future__ import annotations + +import json +import shutil +import subprocess +from argparse import ArgumentParser, Namespace +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Protocol + +import pytest +from pre_commit_terraform import _cli +from pre_commit_terraform import terraform_iac_guard_v as hook + + +BEFORE = 'before' +AFTER = 'after' +REPORT = 'report' +USAGE_ERROR = 2 +EXECUTION_ERROR = 4 +REPEATED_RUNS = 2 + + +class Transport(Protocol): + """Typed process-double installer with optional scenario arguments.""" + + def __call__( + self, + code: int, + report: str | None = None, + schema: int = 0, + ) -> None: + """Select product and report outcomes.""" + ... + + +@pytest.fixture +def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Create a disposable repository, retaining spaces in its path. + + Returns: + Path: Repository root. + """ + root = tmp_path / 'repo with spaces ' + root.mkdir() + git = shutil.which('git') + assert git is not None + subprocess.run([git, 'init', '-q', str(root)], check=True) # noqa: S603 — resolved executable and fixed argv + monkeypatch.chdir(root) + return root + + +@pytest.fixture +def repair(repository: Path) -> Namespace: + """Parse a benign explicit repair request. + + Returns: + Namespace: Parsed operator-controlled arguments. + """ + executable = repository / 'python' + executable.write_text('#!/bin/sh\nexit 0\n') + executable.chmod(hook.PRIVATE_DIRECTORY_MODE) + for name in (BEFORE, AFTER): + (repository / name).mkdir() + parser = ArgumentParser() + hook.populate_argument_parser(parser) + return parser.parse_args( + [ + '--iacgv-python', + str(executable), + '--local-trusted', + '--before', + BEFORE, + '--after', + AFTER, + '--framework', + 'terraform', + '--target', + 'CKV_AWS_3=aws_ebs_volume.target', + '--checkov-executable', + str(executable), + ], + ) + + +@pytest.fixture +def transport( + monkeypatch: pytest.MonkeyPatch, +) -> Transport: + """Stub process transport without claiming product semantics. + + Returns: + Callable: Configure product exit, report bytes and schema process exit. + """ + + def install(code: int, report: str | None = None, schema: int = 0) -> None: # noqa: WPS430 — bind fixture state + def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: WPS430 — isolated subprocess double + (run.directory / f'{label}.stdout.log').write_text('1.0.2\n') + if label == 'schema': + return schema + if label == 'verification': + payload = { + 'schema_version': 'report-v1', + 'result_kind': 'verification', + 'exit_code': code, + 'verdict': { + 0: 'VERIFIED', + 1: 'FAILED', + 3: 'INCONCLUSIVE', + }.get(code), + } + run.report.write_text( + json.dumps(payload) if report is None else report, + ) + return code + return 0 + + monkeypatch.setattr(hook.HookRun, '_process', process) + + return install + + +class TestConfiguration: + """Exercise parsing and exact argument transport.""" + + def test_command(self, repair: Namespace, repository: Path) -> None: + """Preserve literal selectors and resolve paths against Git root.""" + repair.target.append('CKV_AWS_3=name with spaces;$(literal)@a=b.tf') + report = repository / '.git/report.json' + command = hook.verification_command(repair, repository, report) + assert command[:6] == [ + str(repair.iacgv_python), + '-I', + '-B', + '-m', + 'iac_guard_v.cli', + 'verify', + ] + assert str(repository / BEFORE) in command + assert 'CKV_AWS_3=name with spaces;$(literal)@a=b.tf' in command + assert '--all-baseline-findings' not in command + assert command[-2:] == [str(report), '--quiet'] + + @pytest.mark.parametrize('field', (BEFORE, AFTER)) + def test_missing_snapshot( + self, + repair: Namespace, + repository: Path, + field: str, + ) -> None: + """Reject nonexistent snapshot directories.""" + setattr(repair, field, Path('absent')) + with pytest.raises(ValueError, match='distinct existing'): + hook.verification_command( + repair, + repository, + repository / REPORT, + ) + + @pytest.mark.parametrize('field', ('iacgv_python', 'checkov_executable')) + @pytest.mark.parametrize( + 'alias', + ('direct', 'file-symlink', 'directory-symlink', 'venv-symlink'), + ) + def test_candidate_runtime( + self, + repair: Namespace, + repository: Path, + field: str, + alias: str, + ) -> None: + """Reject a candidate-owned verifier, scanner or Python environment.""" + executable = repository / AFTER / 'bin/python' + executable.parent.mkdir() + if alias == 'venv-symlink': + executable.symlink_to(repair.iacgv_python) + else: + executable.write_text('#!/bin/sh\nexit 0\n') + executable.chmod(hook.PRIVATE_DIRECTORY_MODE) + selected = executable + if alias == 'file-symlink': + selected = repository / 'alias' + selected.symlink_to(executable) + elif alias == 'directory-symlink': + parent = repository / 'alias' + parent.symlink_to(executable.parent, target_is_directory=True) + selected = parent / executable.name + setattr(repair, field, selected) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + assert not (repository / '.git/iac-guard-v').exists() + + def test_same_snapshot(self, repair: Namespace, repository: Path) -> None: + """Reject a symlink alias of the same snapshot.""" + alias = repository / 'alias' + alias.symlink_to(repository / BEFORE, target_is_directory=True) + repair.after = alias + with pytest.raises(ValueError, match='distinct existing'): + hook.verification_command( + repair, + repository, + repository / REPORT, + ) + + def test_output_in_snapshot( + self, + repair: Namespace, + repository: Path, + ) -> None: + """Do not place reports in protected input trees.""" + with pytest.raises(ValueError, match='outside both'): + hook.verification_command( + repair, + repository, + repository / 'before/report', + ) + + @pytest.mark.parametrize('path', ('relative', '/absent/runtime')) + def test_invalid_executable( + self, + repair: Namespace, + repository: Path, + path: str, + ) -> None: + """Require explicit absolute installed executables.""" + repair.iacgv_python = Path(path) + with pytest.raises(ValueError, match='absolute, executable'): + hook.verification_command( + repair, + repository, + repository / REPORT, + ) + + @pytest.mark.parametrize( + 'arguments', + ((), ('--unknown',), ('--bef', 'x'), ('--args=--soft-fail',)), + ) + def test_invalid_parser(self, arguments: tuple[str, ...]) -> None: + """Reject missing, abbreviated and unexpected arguments.""" + with pytest.raises(SystemExit) as error: + _cli.invoke_cli_app(['iac-guard-v', *arguments]) + assert error.value.code == USAGE_ERROR + + +class TestResults: + """Require fresh, consistent reports and preserve product errors.""" + + @pytest.mark.parametrize('code', (0, 1, 3, 2, 4, 17, -9)) + def test_exit( + self, + repair: Namespace, + transport: Transport, + code: int, + ) -> None: + """Keep errors distinct; a killed child cannot establish success.""" + transport(code) + expected = hook.INCONCLUSIVE if code < 0 else code + assert hook.invoke_cli_app(repair) == expected + + @pytest.mark.parametrize( + REPORT, + ( + '', + '{', + '[]', + '{}', + '{"exit_code":true}', + '{"exit_code":0,"verdict":"FAILED"}', + ), + ) + def test_invalid_report( + self, + repair: Namespace, + transport: Transport, + report: str, + ) -> None: + """The released schema must reject malformed or partial output.""" + transport(0, report, 1) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_inconsistent_exit( + self, + repair: Namespace, + transport: Transport, + ) -> None: + """Even a schema-valid report must match this process exit.""" + transport( + 0, + json.dumps( + { + 'schema_version': 'report-v1', + 'result_kind': 'verification', + 'exit_code': 1, + 'verdict': 'FAILED', + }, + ), + ) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_operational_uncertainty( + self, + repair: Namespace, + transport: Transport, + ) -> None: + """Keep the released operational uncertainty classification.""" + payload = { + 'schema_version': 'report-v1', + 'result_kind': 'operational_uncertainty', + 'verdict': 'INCONCLUSIVE', + 'exit_code': hook.INCONCLUSIVE, + } + transport(hook.INCONCLUSIVE, json.dumps(payload)) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_invalid_json_after_validation( + self, + repair: Namespace, + transport: Transport, + ) -> None: + """A changed/malformed report cannot fail open after validation.""" + transport(0, '{') + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_retention( + self, + repair: Namespace, + repository: Path, + transport: Transport, + ) -> None: + """Repeated and concurrent requests never overwrite evidence.""" + transport(0) + with ThreadPoolExecutor(max_workers=2) as executor: + assert list( + executor.map(hook.invoke_cli_app, (repair, repair)), + ) == [0, 0] + reports = list(repository.glob('.git/iac-guard-v/runs/*/report.json')) + original = {path: path.read_bytes() for path in reports} + assert len(reports) == REPEATED_RUNS + assert hook.invoke_cli_app(repair) == 0 + assert all( + path.read_bytes() == original_bytes + for path, original_bytes in original.items() + ) + + def test_nested( + self, + repair: Namespace, + repository: Path, + monkeypatch: pytest.MonkeyPatch, + transport: Transport, + ) -> None: + """Nested callers retain repository-relative snapshot meaning.""" + transport(0) + monkeypatch.chdir(repository / AFTER) + assert hook.invoke_cli_app(repair) == 0 + + +class TestErrors: + """Fail closed on setup, process and filesystem exceptions.""" + + @pytest.mark.parametrize( + 'error', + ( + OSError('blocked'), + subprocess.TimeoutExpired('verify', 1), + KeyboardInterrupt(), + ), + ) + def test_execution( + self, + repair: Namespace, + monkeypatch: pytest.MonkeyPatch, + error: BaseException, + ) -> None: + """Unsuccessful subprocess execution never returns verified success.""" + + def process(*_args: object) -> int: # noqa: WPS430 — exception injection + raise error + + monkeypatch.setattr(hook.HookRun, '_process', process) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_missing_git( + self, + repair: Namespace, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """Explain an absent Git runtime without traceback.""" + monkeypatch.setattr(shutil, 'which', lambda _: None) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_symlink_reports( + self, + repair: Namespace, + repository: Path, + ) -> None: + """Reject candidate-selected report directory redirection.""" + (repository / '.git/iac-guard-v').symlink_to( + repository / AFTER, + target_is_directory=True, + ) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + assert not (repository / 'after/runs').exists() + + def test_missing_report( + self, + repair: Namespace, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """A zero exit with no new report cannot establish a result.""" + + def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: WPS430 — missing report injection + (run.directory / f'{label}.stdout.log').write_text('1.0.2\n') + return 0 + + monkeypatch.setattr(hook.HookRun, '_process', process) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_no_input_mutation( + self, + repair: Namespace, + repository: Path, + ) -> None: + """Reject overlap before creating any report directories.""" + repair.before = repository + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + assert not (repository / '.git/iac-guard-v').exists() + + def test_wrong_version(self, repair: Namespace) -> None: + """An executable without the released product fails before verify.""" + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_real_process(self, repair: Namespace) -> None: + """Exercise log creation with literal argv and the real process API.""" + run = hook.HookRun(repair) + shell = shutil.which('sh') + assert shell is not None + assert run._process([shell, '-c', 'exit 4'], 'test') == EXECUTION_ERROR # noqa: SLF001 — exercise transport boundary + assert (run.directory / 'test.stderr.log').is_file() diff --git a/tools/install/iac-guard-v.sh b/tools/install/iac-guard-v.sh new file mode 100755 index 000000000..5476fbe70 --- /dev/null +++ b/tools/install/iac-guard-v.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" +readonly SCRIPT_DIR +# shellcheck source=_common.sh +. "$SCRIPT_DIR/_common.sh" + +# PyPI product: build-time only, never common::resolve_tool_path/runtime install. +# Run in the FINAL image: the controlled launcher binds the relocated Checkov +# executable and its actual interpreter/dependencies. Never modify that install. +if ! command -v checkov > /dev/null; then + echo 'IaC-Guard-V repair verification requires CHECKOV_VERSION; no scanner installed.' >&2 + exit 1 +fi + +readonly PRODUCT_ENV=/opt/iac-guard-v +export PYTHONDONTWRITEBYTECODE=1 +python3 -m venv --copies --without-pip --system-site-packages "$PRODUCT_ENV" +product_requirement="$TOOL" +if [[ $VERSION != latest ]]; then + product_requirement="${TOOL}==${VERSION}" +fi +python3 -m pip --python "$PRODUCT_ENV/bin/python" install \ + --no-cache-dir --no-compile "$product_requirement" + +# Product integrity requires bytecode-free parser copies. Use the versions of +# shared parser dependencies already selected by Checkov, rather than replacing +# global packages or copying a second scanner tree. python-hcl2 is product-local. +python3 -c 'from importlib.metadata import version; import sys; sys.stdout.write("\n".join(name+"=="+version(name) for name in ("PyYAML", "lark", "regex", "packaging"))+"\n")' > "$PRODUCT_ENV/parser-requirements.txt" +python3 -m pip --python "$PRODUCT_ENV/bin/python" install \ + --no-cache-dir --no-compile --ignore-installed --no-deps \ + -r "$PRODUCT_ENV/parser-requirements.txt" +python3 -m pip --python "$PRODUCT_ENV/bin/python" check +"$PRODUCT_ENV/bin/python" -IBm iac_guard_v.external_checkov \ + --checkov "$(command -v checkov)" --destination "$PRODUCT_ENV/scanner" +# Operator-owned installed files must also be readable by Docker USERID users. +chmod 755 "$PRODUCT_ENV/scanner" + +# Installation/provenance validation above is separate from request authority. +# Unknown CHECKOV_VERSION/latest stays installed for ordinary hooks; the product +# rejects unqualified versions/properties when verification is requested. From df25b0eef583ebabc7549dd4a6edc198a7f9d9ad Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sat, 7 Nov 2026 17:14:57 -0600 Subject: [PATCH 03/10] feat: accept qualified IaC-Guard-V 1.0.3 Bound reviewed product versions to report-v1 and retain 1.0.2 support. Prepare Checkov 3.4.3 candidate qualification and documentation; publication and published-artifact replay remain prerequisites for upstream submission. Assisted-by: Codex:GPT-6 --- .github/workflows/build-image-test.yaml | 3 +- README.md | 35 ++++++++------ .../terraform_iac_guard_v.py | 20 +++++--- tests/pytest/iac_guard_v_test.py | 48 +++++++++++++++++-- 4 files changed, 81 insertions(+), 25 deletions(-) diff --git a/.github/workflows/build-image-test.yaml b/.github/workflows/build-image-test.yaml index 6c012f68c..547159714 100644 --- a/.github/workflows/build-image-test.yaml +++ b/.github/workflows/build-image-test.yaml @@ -20,6 +20,7 @@ jobs: checkov-version: - 3.3.0 - 3.3.30 + - 3.4.3 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -47,7 +48,7 @@ jobs: run: >- docker build --tag iac-guard-v-test --build-arg CHECKOV_VERSION="$CHECKOV_VERSION" - --build-arg IAC_GUARD_V_VERSION=1.0.2 . + --build-arg IAC_GUARD_V_VERSION=1.0.3 . - name: Exercise released verifier and real pre-commit hook if: steps.changes.outputs.any_changed == 'true' diff --git a/README.md b/README.md index 865df4b25..cf26c658a 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ Full list of dependencies and where they are used: Hope that it all will work.

* [`checkov`][checkov repo] required for `terraform_checkov` hook -* [`iac-guard-v==1.0.2`](https://pypi.org/project/iac-guard-v/1.0.2/) and a qualified Checkov installation required for `terraform_iac_guard_v`; see its [separate installation instructions](#terraform_iac_guard_v) +* [`iac-guard-v==1.0.3`](https://pypi.org/project/iac-guard-v/1.0.3/) and a qualified Checkov installation required for `terraform_iac_guard_v`; see its [separate installation instructions](#terraform_iac_guard_v) * [`terraform-docs`][terraform-docs repo] 0.12.0+ required for `terraform_docs` hook * [`terragrunt`][terragrunt repo] required for `terragrunt_validate` and `terragrunt_valid_inputs` hooks * [`terrascan`][terrascan repo] required for `terrascan` hook @@ -338,7 +338,7 @@ There are several [pre-commit](https://pre-commit.com/) hooks to keep Terraform | `terraform_docs_replace` | Runs `terraform-docs` and pipes the output directly to README.md. **DEPRECATED**, see [#248](https://github.com/antonbabenko/pre-commit-terraform/issues/248). [Hook notes](#terraform_docs_replace-deprecated) | `python3`, `terraform-docs` | | `terraform_docs_without_`
`aggregate_type_defaults` | Inserts input and output documentation into `README.md` without aggregate type defaults. Hook notes same as for [terraform_docs](#terraform_docs) | `terraform-docs` | | `terraform_fmt` | Reformat all Terraform configuration files to a canonical format. [Hook notes](#terraform_fmt) | - | -| `terraform_iac_guard_v` | Verify a declared trusted before/after Terraform repair with [IaC-Guard-V](https://github.com/lokesh0186/iac-guard-v). [Hook notes](#terraform_iac_guard_v) | Python 3.10+, separately installed `iac-guard-v==1.0.2` (Python 3.10–3.13), qualified Checkov | +| `terraform_iac_guard_v` | Verify a declared trusted before/after Terraform repair with [IaC-Guard-V](https://github.com/lokesh0186/iac-guard-v). [Hook notes](#terraform_iac_guard_v) | Python 3.10+, separately installed `iac-guard-v==1.0.3` (Python 3.10–3.13), qualified Checkov | | `terraform_providers_lock` | Updates provider signatures in [dependency lock files](https://www.terraform.io/docs/cli/commands/providers/lock.html). [Hook notes](#terraform_providers_lock) | - | | `terraform_tflint` | Validates all Terraform configuration files with [TFLint][tflint repo]. [Available TFLint rules](https://github.com/terraform-linters/tflint-ruleset-terraform/blob/main/docs/rules/README.md). [Hook notes](#terraform_tflint). | `tflint` | | `terraform_tfsec` | [TFSec][tfsec repo] static analysis of terraform templates to spot potential security issues. **DEPRECATED**, use `terraform_trivy`. [Hook notes](#terraform_tfsec-deprecated) | `tfsec` | @@ -633,14 +633,14 @@ the same check and resource to fail before and pass after. The comparison also needs to handle skipped checks, parsing errors, and missing results. The optional [terraform_iac_guard_v](#terraform_iac_guard_v) hook packages that -bounded verification through published IaC-Guard-V 1.0.2. Trivy's +bounded verification through IaC-Guard-V. Trivy's [passing results](https://trivy.dev/docs/latest/references/configuration/cli/trivy_config/) and [custom checks](https://trivy.dev/docs/latest/guide/scanner/misconfiguration/config/config/) are other building blocks for project-owned comparisons. ### terraform_iac_guard_v -Verifies a particular declared Terraform repair using **iac-guard-v==1.0.2**. +Verifies a particular declared Terraform repair using **iac-guard-v==1.0.3**. The operator supplies trusted before/after directories and an exact `CHECK_ID=RESOURCE_ADDRESS[@FILE]` target. The product requires legitimate before-fail/after-pass evidence for that same target, including scanner authority, @@ -656,11 +656,11 @@ snapshots and outside candidate control. For example, from an operator-owned location, using a current pip with `--python` support: ```bash -IACGV_ROOT="$HOME/.local/share/iac-guard-v-1.0.2" +IACGV_ROOT="$HOME/.local/share/iac-guard-v-1.0.3" python3.12 -m venv --copies --without-pip "$IACGV_ROOT/product" python3.12 -m venv --copies --without-pip "$IACGV_ROOT/checkov" -PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/product/bin/python" install --no-compile 'iac-guard-v==1.0.2' -PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/checkov/bin/python" install --no-compile 'checkov==3.3.30' +PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/product/bin/python" install --no-compile 'iac-guard-v==1.0.3' +PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/checkov/bin/python" install --no-compile 'checkov==3.4.3' "$IACGV_ROOT/product/bin/python" -IBm iac_guard_v.cli doctor --mode local-trusted --checkov-executable "$IACGV_ROOT/checkov/bin/checkov" --format json ``` @@ -699,13 +699,13 @@ repos: hooks: - id: terraform_iac_guard_v args: - - --iacgv-python=/absolute/operator/iac-guard-v-1.0.2/product/bin/python + - --iacgv-python=/absolute/operator/iac-guard-v-1.0.3/product/bin/python - --local-trusted - --before=verification/before - --after=verification/after - --framework=terraform - --target=CKV_AWS_3=aws_ebs_volume.target - - --checkov-executable=/absolute/operator/iac-guard-v-1.0.2/checkov/bin/checkov + - --checkov-executable=/absolute/operator/iac-guard-v-1.0.3/checkov/bin/checkov ``` Run `pre-commit run terraform_iac_guard_v --all-files`. Paths to snapshots are @@ -748,8 +748,8 @@ Build from this checkout with explicit versions: ```bash docker build -t pre-commit-iacgv \ - --build-arg CHECKOV_VERSION=3.3.30 \ - --build-arg IAC_GUARD_V_VERSION=1.0.2 . + --build-arg CHECKOV_VERSION=3.4.3 \ + --build-arg IAC_GUARD_V_VERSION=1.0.3 . ``` In the configuration above use `/opt/iac-guard-v/bin/python` for `--iacgv-python` @@ -761,7 +761,8 @@ the pre-commit hook checkout; pre-commit installs the configured hook revision. `IAC_GUARD_V_VERSION=false` is the default and installs no product environment. An explicit pin or `latest` enables it. `INSTALL_ALL=true` selects `latest`, overriding individual version arguments just like the existing tools. The tested -product baseline is 1.0.2; the adapter requires that exact product version. +products are exactly 1.0.2 and 1.0.3, both using `report-v1`. Future product +versions and prereleases require explicit adapter review; they are rejected. Enabling the product without Checkov is a build-time setup error. The final image creates a separate `--system-site-packages` product venv and @@ -773,14 +774,18 @@ The launcher is prepared after final-image relocation and binds package, RECORD, interpreter, dependency and policy identities. Rebuild after changing the trusted installation; never edit the generated manifest to silence drift failures. -IaC-Guard-V 1.0.2 explicitly qualifies Checkov versions **3.3.0–3.3.30**, with -**property-specific** profiles. The integration respects `CHECKOV_VERSION`, +**Checkov 3.4.3 requires IaC-Guard-V 1.0.3 and supports only Terraform +CKV_AWS_3.** Other properties on 3.4.3 remain unqualified. Product 1.0.2 +continues to work with its property-specific **3.3.0–3.3.30** profiles, and +1.0.3 preserves those profiles. Using `latest` or `INSTALL_ALL=true` does not +guarantee authority for every check: a future scanner/product selection may +fail closed until reviewed. The integration respects `CHECKOV_VERSION`, including `latest`; it never substitutes 3.3.0. Unknown versions and unqualified check/version combinations fail closed at verification time. Such a profile failure does not prevent building an image for unrelated hooks. CKV_K8S_40's manifest semantics are excluded from 3.3.8 onward; this is not blanket support for every check or a Kubernetes hook. See the released -[compatibility contract](https://github.com/lokesh0186/iac-guard-v/blob/v1.0.2/docs/CHECKOV_COMPATIBILITY.md) +[compatibility contract](https://github.com/lokesh0186/iac-guard-v/blob/v1.0.3/docs/CHECKOV_COMPATIBILITY.md) for the qualified properties and exact limits. #### Troubleshooting and scope diff --git a/src/pre_commit_terraform/terraform_iac_guard_v.py b/src/pre_commit_terraform/terraform_iac_guard_v.py index 6a0ad0489..8fb2f0bbf 100644 --- a/src/pre_commit_terraform/terraform_iac_guard_v.py +++ b/src/pre_commit_terraform/terraform_iac_guard_v.py @@ -16,6 +16,7 @@ import tempfile from argparse import Namespace from pathlib import Path +from types import MappingProxyType from typing import TYPE_CHECKING, Final, cast @@ -26,7 +27,10 @@ # Eight small module members keep parser, process and Git concerns explicit. # flake8: noqa: WPS202 CLI_SUBCOMMAND_NAME: Final[str] = 'iac-guard-v' -VERSION: Final[str] = '1.0.2' +# Exact reviewed product/protocol pairs; future releases never self-promote. +SUPPORTED_PROTOCOLS: Final = MappingProxyType( + {'1.0.2': 'report-v1', '1.0.3': 'report-v1'}, +) TIMEOUT: Final[int] = 600 PRIVATE_DIRECTORY_MODE: Final[int] = 0o700 LOGGER = logging.getLogger(__name__) @@ -199,11 +203,14 @@ def verify(self, parsed: Namespace) -> int: ], 'runtime', ) + product_version = ( + (self.directory / 'runtime.stdout.log').read_text().strip() + ) + protocol = SUPPORTED_PROTOCOLS.get(product_version) _require( - 'Runtime requires published iac-guard-v==1.0.2; see runtime logs.', - condition=runtime == 0 - and (self.directory / 'runtime.stdout.log').read_text().strip() - == VERSION, + 'Runtime requires iac-guard-v 1.0.2 or 1.0.3 with report-v1; ' + 'see runtime logs.', + condition=runtime == 0 and protocol is not None, ) code = self._process(command, 'verification') LOGGER.warning('IaC-Guard-V process exit: %s', code) @@ -228,7 +235,8 @@ def verify(self, parsed: Namespace) -> int: # The schema validates headers/types; compare transport consistency. _require( 'Canonical verdict/exit does not match the product process.', - condition=payload.get('result_kind') + condition=payload.get('schema_version') == protocol + and payload.get('result_kind') in {'verification', 'operational_uncertainty'} and payload['exit_code'] == code and payload.get('verdict') diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py index 4e3a4ea66..2eaa2a790 100644 --- a/tests/pytest/iac_guard_v_test.py +++ b/tests/pytest/iac_guard_v_test.py @@ -34,6 +34,7 @@ def __call__( code: int, report: str | None = None, schema: int = 0, + version: str = '1.0.2', ) -> None: """Select product and report outcomes.""" ... @@ -98,9 +99,14 @@ def transport( Callable: Configure product exit, report bytes and schema process exit. """ - def install(code: int, report: str | None = None, schema: int = 0) -> None: # noqa: WPS430 — bind fixture state + def install( + code: int, + report: str | None = None, + schema: int = 0, + version: str = '1.0.2', + ) -> None: # noqa: WPS430 — bind fixture state def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: WPS430 — isolated subprocess double - (run.directory / f'{label}.stdout.log').write_text('1.0.2\n') + (run.directory / f'{label}.stdout.log').write_text(version + '\n') if label == 'schema': return schema if label == 'verification': @@ -250,17 +256,53 @@ class TestResults: """Require fresh, consistent reports and preserve product errors.""" @pytest.mark.parametrize('code', (0, 1, 3, 2, 4, 17, -9)) + @pytest.mark.parametrize('version', ('1.0.2', '1.0.3')) def test_exit( self, repair: Namespace, transport: Transport, code: int, + version: str, ) -> None: """Keep errors distinct; a killed child cannot establish success.""" - transport(code) + transport(code, version=version) expected = hook.INCONCLUSIVE if code < 0 else code assert hook.invoke_cli_app(repair) == expected + @pytest.mark.parametrize( + 'version', + ('1.0.1', '1.0.3rc1', '1.0.4', '2.0.0', ''), + ) + def test_unreviewed_version( + self, + repair: Namespace, + transport: Transport, + version: str, + ) -> None: + """No version range or prerelease can inherit protocol authority.""" + transport(0, version=version) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + def test_unreviewed_protocol( + self, + repair: Namespace, + transport: Transport, + ) -> None: + """Reject an unreviewed protocol even if schema validation succeeds.""" + transport( + 0, + json.dumps( + { + 'schema_version': 'report-v2', + 'result_kind': 'verification', + 'exit_code': 0, + 'verdict': 'VERIFIED', + }, + ), + version='1.0.3', + ) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + @pytest.mark.parametrize( REPORT, ( From aa5ae34029c103fb40afb8a6f0f705db2db41075 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 09:31:14 -0600 Subject: [PATCH 04/10] test: fix Windows repair fixture paths Keep embedded spaces on Windows, where trailing-space directory names are normalized by the filesystem. Preserve trailing-space coverage on POSIX without changing assertions or verifier behavior. Assisted-by: AI tooling --- tests/pytest/iac_guard_v_test.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py index 2eaa2a790..f4a87956e 100644 --- a/tests/pytest/iac_guard_v_test.py +++ b/tests/pytest/iac_guard_v_test.py @@ -8,6 +8,7 @@ import json import shutil import subprocess +import sys from argparse import ArgumentParser, Namespace from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -47,7 +48,11 @@ def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: Returns: Path: Repository root. """ - root = tmp_path / 'repo with spaces ' + # Windows strips trailing spaces from directory names; POSIX retains them. + name = ( + 'repo with spaces' if sys.platform == 'win32' else 'repo with spaces ' + ) + root = tmp_path / name root.mkdir() git = shutil.which('git') assert git is not None From 2399a5062e2da83074e1525b5bca31dc8d7e85d8 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 10:27:44 -0600 Subject: [PATCH 05/10] fix: Type repair hook transport and fixtures Narrow decoded JSON to object until released schema validation and use the parser namespace contract explicitly. Keep concurrent retention assertions while avoiding imprecise variadic map types. Assisted-by: AI tooling --- .../terraform_iac_guard_v.py | 16 +++- tests/pytest/iac_guard_v_test.py | 79 +++++++++++-------- 2 files changed, 57 insertions(+), 38 deletions(-) diff --git a/src/pre_commit_terraform/terraform_iac_guard_v.py b/src/pre_commit_terraform/terraform_iac_guard_v.py index 8fb2f0bbf..26f6008e3 100644 --- a/src/pre_commit_terraform/terraform_iac_guard_v.py +++ b/src/pre_commit_terraform/terraform_iac_guard_v.py @@ -22,9 +22,10 @@ if TYPE_CHECKING: from argparse import ArgumentParser + from collections.abc import Callable -# Eight small module members keep parser, process and Git concerns explicit. +# Keep parser, process and Git concerns explicit. # flake8: noqa: WPS202 CLI_SUBCOMMAND_NAME: Final[str] = 'iac-guard-v' # Exact reviewed product/protocol pairs; future releases never self-promote. @@ -42,6 +43,8 @@ 'schema = files("iac_guard_v").joinpath("schemas/report-v1.schema.json"); ' 'validate(json.load(open(sys.argv[1])), json.loads(schema.read_text()))' ) +# JSON values enter as objects; the released schema establishes report shape. +JSON_LOADS: Final[Callable[[str], object]] = json.loads def _require(message: str, *, condition: bool) -> None: @@ -56,7 +59,12 @@ def populate_argument_parser(parser: ArgumentParser) -> None: parser.add_argument('--local-trusted', action='store_true', required=True) parser.add_argument('--before', type=Path, required=True) parser.add_argument('--after', type=Path, required=True) - parser.add_argument('--framework', choices=('terraform',), required=True) + parser.add_argument( + '--framework', + type=str, + choices=('terraform',), + required=True, + ) parser.add_argument('--target', action='append', required=True) parser.add_argument('--checkov-executable', type=Path, required=True) @@ -104,7 +112,7 @@ def verification_command( Returns: list[str]: The published verify invocation, without shell expansion. """ - args = _Arguments(**cast('dict[str, object]', parsed.__dict__)) + args = cast('_Arguments', parsed) before, after = ( (root / args.before).resolve(), (root / args.after).resolve(), @@ -230,7 +238,7 @@ def verify(self, parsed: Namespace) -> int: ) payload = cast( 'dict[str, object]', - json.loads(self.report.read_text()), + JSON_LOADS(self.report.read_text()), ) # The schema validates headers/types; compare transport consistency. _require( diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py index f4a87956e..c3a55fe60 100644 --- a/tests/pytest/iac_guard_v_test.py +++ b/tests/pytest/iac_guard_v_test.py @@ -9,14 +9,19 @@ import shutil import subprocess import sys -from argparse import ArgumentParser, Namespace +from argparse import ArgumentParser from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from typing import Protocol +from typing import TYPE_CHECKING, Final, Protocol import pytest from pre_commit_terraform import _cli from pre_commit_terraform import terraform_iac_guard_v as hook +from pre_commit_terraform.terraform_iac_guard_v import _Arguments + + +if TYPE_CHECKING: + from collections.abc import Callable BEFORE = 'before' @@ -25,6 +30,7 @@ USAGE_ERROR = 2 EXECUTION_ERROR = 4 REPEATED_RUNS = 2 +JSON_DUMPS: Final[Callable[[object], str]] = json.dumps class Transport(Protocol): @@ -62,11 +68,11 @@ def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: @pytest.fixture -def repair(repository: Path) -> Namespace: +def repair(repository: Path) -> _Arguments: """Parse a benign explicit repair request. Returns: - Namespace: Parsed operator-controlled arguments. + _Arguments: Parsed operator-controlled arguments. """ executable = repository / 'python' executable.write_text('#!/bin/sh\nexit 0\n') @@ -75,7 +81,8 @@ def repair(repository: Path) -> Namespace: (repository / name).mkdir() parser = ArgumentParser() hook.populate_argument_parser(parser) - return parser.parse_args( + parsed = _Arguments() + parser.parse_args( [ '--iacgv-python', str(executable), @@ -91,7 +98,9 @@ def repair(repository: Path) -> Namespace: '--checkov-executable', str(executable), ], + namespace=parsed, ) + return parsed @pytest.fixture @@ -126,7 +135,7 @@ def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: }.get(code), } run.report.write_text( - json.dumps(payload) if report is None else report, + JSON_DUMPS(payload) if report is None else report, ) return code return 0 @@ -139,7 +148,7 @@ def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: class TestConfiguration: """Exercise parsing and exact argument transport.""" - def test_command(self, repair: Namespace, repository: Path) -> None: + def test_command(self, repair: _Arguments, repository: Path) -> None: """Preserve literal selectors and resolve paths against Git root.""" repair.target.append('CKV_AWS_3=name with spaces;$(literal)@a=b.tf') report = repository / '.git/report.json' @@ -160,7 +169,7 @@ def test_command(self, repair: Namespace, repository: Path) -> None: @pytest.mark.parametrize('field', (BEFORE, AFTER)) def test_missing_snapshot( self, - repair: Namespace, + repair: _Arguments, repository: Path, field: str, ) -> None: @@ -180,7 +189,7 @@ def test_missing_snapshot( ) def test_candidate_runtime( self, - repair: Namespace, + repair: _Arguments, repository: Path, field: str, alias: str, @@ -205,7 +214,7 @@ def test_candidate_runtime( assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE assert not (repository / '.git/iac-guard-v').exists() - def test_same_snapshot(self, repair: Namespace, repository: Path) -> None: + def test_same_snapshot(self, repair: _Arguments, repository: Path) -> None: """Reject a symlink alias of the same snapshot.""" alias = repository / 'alias' alias.symlink_to(repository / BEFORE, target_is_directory=True) @@ -219,7 +228,7 @@ def test_same_snapshot(self, repair: Namespace, repository: Path) -> None: def test_output_in_snapshot( self, - repair: Namespace, + repair: _Arguments, repository: Path, ) -> None: """Do not place reports in protected input trees.""" @@ -233,7 +242,7 @@ def test_output_in_snapshot( @pytest.mark.parametrize('path', ('relative', '/absent/runtime')) def test_invalid_executable( self, - repair: Namespace, + repair: _Arguments, repository: Path, path: str, ) -> None: @@ -264,7 +273,7 @@ class TestResults: @pytest.mark.parametrize('version', ('1.0.2', '1.0.3')) def test_exit( self, - repair: Namespace, + repair: _Arguments, transport: Transport, code: int, version: str, @@ -280,7 +289,7 @@ def test_exit( ) def test_unreviewed_version( self, - repair: Namespace, + repair: _Arguments, transport: Transport, version: str, ) -> None: @@ -290,13 +299,13 @@ def test_unreviewed_version( def test_unreviewed_protocol( self, - repair: Namespace, + repair: _Arguments, transport: Transport, ) -> None: """Reject an unreviewed protocol even if schema validation succeeds.""" transport( 0, - json.dumps( + JSON_DUMPS( { 'schema_version': 'report-v2', 'result_kind': 'verification', @@ -321,7 +330,7 @@ def test_unreviewed_protocol( ) def test_invalid_report( self, - repair: Namespace, + repair: _Arguments, transport: Transport, report: str, ) -> None: @@ -331,13 +340,13 @@ def test_invalid_report( def test_inconsistent_exit( self, - repair: Namespace, + repair: _Arguments, transport: Transport, ) -> None: """Even a schema-valid report must match this process exit.""" transport( 0, - json.dumps( + JSON_DUMPS( { 'schema_version': 'report-v1', 'result_kind': 'verification', @@ -350,7 +359,7 @@ def test_inconsistent_exit( def test_operational_uncertainty( self, - repair: Namespace, + repair: _Arguments, transport: Transport, ) -> None: """Keep the released operational uncertainty classification.""" @@ -360,12 +369,12 @@ def test_operational_uncertainty( 'verdict': 'INCONCLUSIVE', 'exit_code': hook.INCONCLUSIVE, } - transport(hook.INCONCLUSIVE, json.dumps(payload)) + transport(hook.INCONCLUSIVE, JSON_DUMPS(payload)) assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE def test_invalid_json_after_validation( self, - repair: Namespace, + repair: _Arguments, transport: Transport, ) -> None: """A changed/malformed report cannot fail open after validation.""" @@ -374,16 +383,18 @@ def test_invalid_json_after_validation( def test_retention( self, - repair: Namespace, + repair: _Arguments, repository: Path, transport: Transport, ) -> None: """Repeated and concurrent requests never overwrite evidence.""" transport(0) with ThreadPoolExecutor(max_workers=2) as executor: - assert list( - executor.map(hook.invoke_cli_app, (repair, repair)), - ) == [0, 0] + futures = [ + executor.submit(hook.invoke_cli_app, repair) + for _ in range(REPEATED_RUNS) + ] + assert [future.result() for future in futures] == [0, 0] reports = list(repository.glob('.git/iac-guard-v/runs/*/report.json')) original = {path: path.read_bytes() for path in reports} assert len(reports) == REPEATED_RUNS @@ -395,7 +406,7 @@ def test_retention( def test_nested( self, - repair: Namespace, + repair: _Arguments, repository: Path, monkeypatch: pytest.MonkeyPatch, transport: Transport, @@ -419,7 +430,7 @@ class TestErrors: ) def test_execution( self, - repair: Namespace, + repair: _Arguments, monkeypatch: pytest.MonkeyPatch, error: BaseException, ) -> None: @@ -433,7 +444,7 @@ def process(*_args: object) -> int: # noqa: WPS430 — exception injection def test_missing_git( self, - repair: Namespace, + repair: _Arguments, monkeypatch: pytest.MonkeyPatch, ) -> None: """Explain an absent Git runtime without traceback.""" @@ -442,7 +453,7 @@ def test_missing_git( def test_symlink_reports( self, - repair: Namespace, + repair: _Arguments, repository: Path, ) -> None: """Reject candidate-selected report directory redirection.""" @@ -455,7 +466,7 @@ def test_symlink_reports( def test_missing_report( self, - repair: Namespace, + repair: _Arguments, monkeypatch: pytest.MonkeyPatch, ) -> None: """A zero exit with no new report cannot establish a result.""" @@ -469,7 +480,7 @@ def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: def test_no_input_mutation( self, - repair: Namespace, + repair: _Arguments, repository: Path, ) -> None: """Reject overlap before creating any report directories.""" @@ -477,11 +488,11 @@ def test_no_input_mutation( assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE assert not (repository / '.git/iac-guard-v').exists() - def test_wrong_version(self, repair: Namespace) -> None: + def test_wrong_version(self, repair: _Arguments) -> None: """An executable without the released product fails before verify.""" assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE - def test_real_process(self, repair: Namespace) -> None: + def test_real_process(self, repair: _Arguments) -> None: """Exercise log creation with literal argv and the real process API.""" run = hook.HookRun(repair) shell = shutil.which('sh') From 6ed01385844cefcaa2f8ba61c3096f6a2ce8f670 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 11:05:44 -0600 Subject: [PATCH 06/10] fix: Coordinate verifier cancellation cleanup Require the cancellation-capable 1.0.4/report-v1 runtime, give it bounded cooperative shutdown time, and quarantine rejected reports. Exercise typed transport paths across Python versions and actual process ownership separately on Linux and macOS. Keep shared fixtures and process scenarios in strict typing reports. Assisted-by: AI tooling --- .github/workflows/build-image-test.yaml | 23 +- .mypy.ini | 4 +- README.md | 44 ++-- .../terraform_iac_guard_v.py | 122 ++++++++- tests/conftest.py | 81 ++++++ tests/iac_guard_v_integration_test.py | 60 ++++- tests/iac_guard_v_process_test.py | 245 ++++++++++++++++++ tests/pytest/iac_guard_v_test.py | 237 +++++++++++------ tox.ini | 9 + 9 files changed, 717 insertions(+), 108 deletions(-) create mode 100644 tests/conftest.py create mode 100644 tests/iac_guard_v_process_test.py diff --git a/.github/workflows/build-image-test.yaml b/.github/workflows/build-image-test.yaml index 547159714..16bd38cc3 100644 --- a/.github/workflows/build-image-test.yaml +++ b/.github/workflows/build-image-test.yaml @@ -11,6 +11,27 @@ env: IMAGE_TAG: pr-test jobs: + iac-guard-v-process: + name: IaC-Guard-V cancellation / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 5 + strategy: + matrix: + os: [ubuntu-latest, macos-15] + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0 + with: + python-version: '3.12' + - name: Install test orchestrator + run: >- + python -Im pip install tox + --constraint=dependencies/lock-files/dist-build-constraints.txt + - name: Exercise actual child and grandchild cleanup + run: tox -qq -e iacgv-process + iac-guard-v: name: IaC-Guard-V / Checkov ${{ matrix.checkov-version }} runs-on: ubuntu-latest @@ -48,7 +69,7 @@ jobs: run: >- docker build --tag iac-guard-v-test --build-arg CHECKOV_VERSION="$CHECKOV_VERSION" - --build-arg IAC_GUARD_V_VERSION=1.0.3 . + --build-arg IAC_GUARD_V_VERSION=1.0.4 . - name: Exercise released verifier and real pre-commit hook if: steps.changes.outputs.any_changed == 'true' diff --git a/.mypy.ini b/.mypy.ini index b5c7808b9..90082a077 100644 --- a/.mypy.ini +++ b/.mypy.ini @@ -6,7 +6,9 @@ error_summary = true # Ref: https://github.com/python/mypy/issues/11171#issuecomment-2567150548 files = src/, - tests/pytest/ + tests/pytest/, + tests/conftest.py, + tests/iac_guard_v_process_test.py check_untyped_defs = true diff --git a/README.md b/README.md index cf26c658a..b650ac249 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ Full list of dependencies and where they are used: Hope that it all will work.

* [`checkov`][checkov repo] required for `terraform_checkov` hook -* [`iac-guard-v==1.0.3`](https://pypi.org/project/iac-guard-v/1.0.3/) and a qualified Checkov installation required for `terraform_iac_guard_v`; see its [separate installation instructions](#terraform_iac_guard_v) +* [`iac-guard-v==1.0.4`](https://pypi.org/project/iac-guard-v/1.0.4/) and a qualified Checkov installation required for `terraform_iac_guard_v`; see its [separate installation instructions](#terraform_iac_guard_v) * [`terraform-docs`][terraform-docs repo] 0.12.0+ required for `terraform_docs` hook * [`terragrunt`][terragrunt repo] required for `terragrunt_validate` and `terragrunt_valid_inputs` hooks * [`terrascan`][terrascan repo] required for `terrascan` hook @@ -338,7 +338,7 @@ There are several [pre-commit](https://pre-commit.com/) hooks to keep Terraform | `terraform_docs_replace` | Runs `terraform-docs` and pipes the output directly to README.md. **DEPRECATED**, see [#248](https://github.com/antonbabenko/pre-commit-terraform/issues/248). [Hook notes](#terraform_docs_replace-deprecated) | `python3`, `terraform-docs` | | `terraform_docs_without_`
`aggregate_type_defaults` | Inserts input and output documentation into `README.md` without aggregate type defaults. Hook notes same as for [terraform_docs](#terraform_docs) | `terraform-docs` | | `terraform_fmt` | Reformat all Terraform configuration files to a canonical format. [Hook notes](#terraform_fmt) | - | -| `terraform_iac_guard_v` | Verify a declared trusted before/after Terraform repair with [IaC-Guard-V](https://github.com/lokesh0186/iac-guard-v). [Hook notes](#terraform_iac_guard_v) | Python 3.10+, separately installed `iac-guard-v==1.0.3` (Python 3.10–3.13), qualified Checkov | +| `terraform_iac_guard_v` | Verify a declared trusted before/after Terraform repair with [IaC-Guard-V](https://github.com/lokesh0186/iac-guard-v). [Hook notes](#terraform_iac_guard_v) | Python 3.10+, separately installed `iac-guard-v==1.0.4` (Python 3.10–3.13), qualified Checkov | | `terraform_providers_lock` | Updates provider signatures in [dependency lock files](https://www.terraform.io/docs/cli/commands/providers/lock.html). [Hook notes](#terraform_providers_lock) | - | | `terraform_tflint` | Validates all Terraform configuration files with [TFLint][tflint repo]. [Available TFLint rules](https://github.com/terraform-linters/tflint-ruleset-terraform/blob/main/docs/rules/README.md). [Hook notes](#terraform_tflint). | `tflint` | | `terraform_tfsec` | [TFSec][tfsec repo] static analysis of terraform templates to spot potential security issues. **DEPRECATED**, use `terraform_trivy`. [Hook notes](#terraform_tfsec-deprecated) | `tfsec` | @@ -640,7 +640,7 @@ are other building blocks for project-owned comparisons. ### terraform_iac_guard_v -Verifies a particular declared Terraform repair using **iac-guard-v==1.0.3**. +Verifies a particular declared Terraform repair using **iac-guard-v==1.0.4**. The operator supplies trusted before/after directories and an exact `CHECK_ID=RESOURCE_ADDRESS[@FILE]` target. The product requires legitimate before-fail/after-pass evidence for that same target, including scanner authority, @@ -656,10 +656,10 @@ snapshots and outside candidate control. For example, from an operator-owned location, using a current pip with `--python` support: ```bash -IACGV_ROOT="$HOME/.local/share/iac-guard-v-1.0.3" +IACGV_ROOT="$HOME/.local/share/iac-guard-v-1.0.4" python3.12 -m venv --copies --without-pip "$IACGV_ROOT/product" python3.12 -m venv --copies --without-pip "$IACGV_ROOT/checkov" -PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/product/bin/python" install --no-compile 'iac-guard-v==1.0.3' +PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/product/bin/python" install --no-compile 'iac-guard-v==1.0.4' PYTHONDONTWRITEBYTECODE=1 python3.12 -m pip --python "$IACGV_ROOT/checkov/bin/python" install --no-compile 'checkov==3.4.3' "$IACGV_ROOT/product/bin/python" -IBm iac_guard_v.cli doctor --mode local-trusted --checkov-executable "$IACGV_ROOT/checkov/bin/checkov" --format json ``` @@ -699,13 +699,13 @@ repos: hooks: - id: terraform_iac_guard_v args: - - --iacgv-python=/absolute/operator/iac-guard-v-1.0.3/product/bin/python + - --iacgv-python=/absolute/operator/iac-guard-v-1.0.4/product/bin/python - --local-trusted - --before=verification/before - --after=verification/after - --framework=terraform - --target=CKV_AWS_3=aws_ebs_volume.target - - --checkov-executable=/absolute/operator/iac-guard-v-1.0.3/checkov/bin/checkov + - --checkov-executable=/absolute/operator/iac-guard-v-1.0.4/checkov/bin/checkov ``` Run `pre-commit run terraform_iac_guard_v --all-files`. Paths to snapshots are @@ -718,8 +718,19 @@ and uses `always_run: true`, including config-only changes or an empty file selection. This trades recurring verification cost for avoiding silently skipped requests. It evaluates the explicit pair, not necessarily the staged working tree. Disabling `always_run` can skip verification on configuration-only changes. -Each child process has a ten-minute limit; timeouts block the commit and retain -available logs. Verification includes full integrity checks and can be costly. +Each child process has a ten-minute limit. SIGINT, SIGTERM and timeouts trigger +cooperative verifier cleanup, with up to 15 seconds before forced termination. +When storage permits, interrupted reports are retained as +`unaccepted-report.json`; they are never accepted as canonical success. A forcibly killed or unresponsive verifier cannot confirm its +separate scanner cleanup; inspect diagnostics. Native execution supports Linux +and macOS; use Linux Docker on Windows. SIGKILL and host failure are outside the +cooperative guarantee. Verification includes full integrity checks and can be +costly (approximately seven to eight minutes in the tested strict host setup). + +For on-demand verification, add `stages: [manual]` beside this hook's `args` and +run `pre-commit run terraform_iac_guard_v --hook-stage manual --all-files`. +The commit stage then omits this hook deliberately; each manual invocation still +runs once and enforces the same fail-closed verification. Each invocation retains stdout/stderr and a canonical `report.json` in a fresh mode-0700 directory under `/iac-guard-v/runs/`. Linked Git @@ -749,7 +760,7 @@ Build from this checkout with explicit versions: ```bash docker build -t pre-commit-iacgv \ --build-arg CHECKOV_VERSION=3.4.3 \ - --build-arg IAC_GUARD_V_VERSION=1.0.3 . + --build-arg IAC_GUARD_V_VERSION=1.0.4 . ``` In the configuration above use `/opt/iac-guard-v/bin/python` for `--iacgv-python` @@ -761,8 +772,9 @@ the pre-commit hook checkout; pre-commit installs the configured hook revision. `IAC_GUARD_V_VERSION=false` is the default and installs no product environment. An explicit pin or `latest` enables it. `INSTALL_ALL=true` selects `latest`, overriding individual version arguments just like the existing tools. The tested -products are exactly 1.0.2 and 1.0.3, both using `report-v1`. Future product -versions and prereleases require explicit adapter review; they are rejected. +product is exactly 1.0.4 using `report-v1`. Earlier products are rejected before +verification because they lack cooperative scanner cancellation. Future versions +and prereleases require explicit adapter review; they are rejected. Enabling the product without Checkov is a build-time setup error. The final image creates a separate `--system-site-packages` product venv and @@ -774,10 +786,10 @@ The launcher is prepared after final-image relocation and binds package, RECORD, interpreter, dependency and policy identities. Rebuild after changing the trusted installation; never edit the generated manifest to silence drift failures. -**Checkov 3.4.3 requires IaC-Guard-V 1.0.3 and supports only Terraform -CKV_AWS_3.** Other properties on 3.4.3 remain unqualified. Product 1.0.2 -continues to work with its property-specific **3.3.0–3.3.30** profiles, and -1.0.3 preserves those profiles. Using `latest` or `INSTALL_ALL=true` does not +**Checkov 3.4.3 supports only Terraform CKV_AWS_3.** Other properties on 3.4.3 +remain unqualified. IaC-Guard-V 1.0.4 preserves the property-specific +**3.3.0–3.3.30** profiles introduced in 1.0.2 and the exact 3.4.3 qualification +introduced in 1.0.3. Using `latest` or `INSTALL_ALL=true` does not guarantee authority for every check: a future scanner/product selection may fail closed until reviewed. The integration respects `CHECKOV_VERSION`, including `latest`; it never substitutes 3.3.0. Unknown versions and unqualified diff --git a/src/pre_commit_terraform/terraform_iac_guard_v.py b/src/pre_commit_terraform/terraform_iac_guard_v.py index 26f6008e3..88dbc51eb 100644 --- a/src/pre_commit_terraform/terraform_iac_guard_v.py +++ b/src/pre_commit_terraform/terraform_iac_guard_v.py @@ -10,11 +10,15 @@ import logging import os import shutil +import signal # Only explicit operator-provisioned executables and argv; never a shell. import subprocess # noqa: S404 import tempfile +import threading +import time from argparse import Namespace +from contextlib import contextmanager from pathlib import Path from types import MappingProxyType from typing import TYPE_CHECKING, Final, cast @@ -22,7 +26,8 @@ if TYPE_CHECKING: from argparse import ArgumentParser - from collections.abc import Callable + from collections.abc import Callable, Iterator + from types import FrameType # Keep parser, process and Git concerns explicit. @@ -30,9 +35,11 @@ CLI_SUBCOMMAND_NAME: Final[str] = 'iac-guard-v' # Exact reviewed product/protocol pairs; future releases never self-promote. SUPPORTED_PROTOCOLS: Final = MappingProxyType( - {'1.0.2': 'report-v1', '1.0.3': 'report-v1'}, + {'1.0.4': 'report-v1'}, ) TIMEOUT: Final[int] = 600 +CLEANUP_TIMEOUT: Final[int] = 15 +POLL_INTERVAL: Final[float] = 0.1 PRIVATE_DIRECTORY_MODE: Final[int] = 0o700 LOGGER = logging.getLogger(__name__) INCONCLUSIVE: Final[int] = 3 @@ -190,6 +197,7 @@ def __init__(self, parsed: Namespace) -> None: reports.mkdir(mode=PRIVATE_DIRECTORY_MODE, exist_ok=True) self.directory = Path(tempfile.mkdtemp(prefix='run-', dir=reports)) self.report = self.directory / 'report.json' + self.cancelled = False def verify(self, parsed: Namespace) -> int: """Invoke the product once, preserving its classifications and exits. @@ -216,13 +224,15 @@ def verify(self, parsed: Namespace) -> int: ) protocol = SUPPORTED_PROTOCOLS.get(product_version) _require( - 'Runtime requires iac-guard-v 1.0.2 or 1.0.3 with report-v1; ' + 'Runtime requires iac-guard-v 1.0.4 with report-v1 ' + 'and cooperative cancellation; ' 'see runtime logs.', condition=runtime == 0 and protocol is not None, ) code = self._process(command, 'verification') LOGGER.warning('IaC-Guard-V process exit: %s', code) if code not in {0, 1, INCONCLUSIVE}: + self.invalidate_report() return code if code > 0 else INCONCLUSIVE _require( 'Canonical report missing or symlinked; see verification logs.', @@ -257,21 +267,112 @@ def verify(self, parsed: Namespace) -> int: ) return code + def _interrupt(self, _signum: int, _frame: FrameType | None) -> None: + # Latch rather than raise inside Popen: ownership must be established + # before cleanup can run. Repeated signals never interrupt cleanup. + self.cancelled = True + + @contextmanager + def signals(self) -> Iterator[None]: + """Handle CLI signals temporarily; keep threaded callers unchanged.""" + if threading.current_thread() is not threading.main_thread(): + yield + return + previous = { + sig: signal.getsignal(sig) + for sig in (signal.SIGINT, signal.SIGTERM) + } + try: + for sig in previous: + signal.signal(sig, self._interrupt) + yield + finally: + for sig, handler in previous.items(): + signal.signal(sig, handler) + + def invalidate_report(self) -> None: + """Retain rejected evidence outside the canonical report path.""" + if self.report.exists() or self.report.is_symlink(): + try: + self.report.rename(self.directory / 'unaccepted-report.json') + except OSError as error: + LOGGER.warning( + 'Could not quarantine rejected report: %s', + error, + ) + + @staticmethod + def _stop(process: subprocess.Popen[str]) -> None: + # The qualified product cleans its separately owned scanner session. + # Keep the verifier alive long enough to complete that bounded cleanup. + process.terminate() + try: + process.wait(timeout=CLEANUP_TIMEOUT) + except subprocess.TimeoutExpired: + LOGGER.warning( + 'Verifier did not acknowledge cancellation; ' + 'scanner cleanup unconfirmed.', + ) + # The unreaped session leader reserves this process group identity. + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=CLEANUP_TIMEOUT) + def _process(self, command: list[str], label: str) -> int: + _require( + 'Native verification requires POSIX cleanup; ' + 'use Linux Docker on Windows.', + condition=os.name == 'posix', + ) with ( (self.directory / f'{label}.stdout.log').open('x') as stdout, (self.directory / f'{label}.stderr.log').open('x') as stderr, ): - completed = subprocess.run( # noqa: S603 — explicit trusted executable, literal argv + process = subprocess.Popen( # noqa: S603 — explicit trusted executable, literal argv command, cwd=self.root, env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'), stdout=stdout, stderr=stderr, - check=False, - timeout=TIMEOUT, + text=True, + start_new_session=True, ) - return completed.returncode + try: + return self._wait(process, command) + except BaseException: + try: + self._stop(process) + finally: + self.invalidate_report() + raise + + def _check_cancellation(self) -> None: + if self.cancelled: + raise KeyboardInterrupt + + def _wait(self, process: subprocess.Popen[str], command: list[str]) -> int: + deadline = time.monotonic() + TIMEOUT + while True: + self._check_cancellation() + remaining = deadline - time.monotonic() + if remaining <= 0: + raise subprocess.TimeoutExpired(command, TIMEOUT) + try: + code = process.wait(timeout=min(POLL_INTERVAL, remaining)) + except subprocess.TimeoutExpired: + continue + self._check_cancellation() + return code + + def execute(self, args: Namespace) -> int: + """Reject cancellation even after the verifier has written its report. + + Returns: + int: Product classification when no cancellation was observed. + """ + with self.signals(): + code = self.verify(args) + self._check_cancellation() + return code def invoke_cli_app(args: Namespace) -> int: @@ -281,14 +382,19 @@ def invoke_cli_app(args: Namespace) -> int: int: Product exit or inconclusive transport failure. pre-commit itself normalizes nonzero hook statuses to 1. """ + invocation: HookRun | None = None try: # noqa: WPS229 — allocation, diagnostics and verification share one boundary invocation = HookRun(args) LOGGER.warning('IaC-Guard-V evidence: %s', invocation.directory) - return invocation.verify(args) + return invocation.execute(args) except (OSError, ValueError, subprocess.SubprocessError) as error: LOGGER.warning('IaC-Guard-V setup/transport error: %s', error) + if invocation is not None: + invocation.invalidate_report() return INCONCLUSIVE except KeyboardInterrupt: + if invocation is not None: + invocation.invalidate_report() LOGGER.warning( 'IaC-Guard-V execution interrupted; no verified result.', ) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000..7a431da0b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,81 @@ +"""Shared consumer fixtures for deterministic and opt-in process tests.""" + +# Standalone test namespace, matching the existing acceptance runner. +# ruff: noqa: INP001 + +from __future__ import annotations + +import shutil +import subprocess +import sys +from argparse import ArgumentParser +from typing import TYPE_CHECKING + +import pytest + +from pre_commit_terraform import terraform_iac_guard_v as hook +from pre_commit_terraform.terraform_iac_guard_v import _Arguments + + +if TYPE_CHECKING: + from pathlib import Path + + +BEFORE = 'before' +AFTER = 'after' + + +@pytest.fixture +def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Create a disposable repository, retaining spaces in its path. + + Returns: + Path: Repository root. + """ + # Windows strips trailing spaces from directory names; POSIX retains them. + name = ( + 'repo with spaces' if sys.platform == 'win32' else 'repo with spaces ' + ) + root = tmp_path / name + root.mkdir() + git = shutil.which('git') + assert git is not None + subprocess.run([git, 'init', '-q', str(root)], check=True) # noqa: S603 — resolved executable and fixed argv + monkeypatch.chdir(root) + return root + + +@pytest.fixture +def repair(repository: Path) -> _Arguments: + """Parse a benign explicit repair request. + + Returns: + _Arguments: Parsed operator-controlled arguments. + """ + executable = repository / 'python' + executable.write_text('#!/bin/sh\nexit 0\n') + executable.chmod(hook.PRIVATE_DIRECTORY_MODE) + for name in (BEFORE, AFTER): + (repository / name).mkdir() + parser = ArgumentParser() + hook.populate_argument_parser(parser) + parsed = _Arguments() + parser.parse_args( + [ + '--iacgv-python', + str(executable), + '--local-trusted', + '--before', + BEFORE, + '--after', + AFTER, + '--framework', + 'terraform', + '--target', + 'CKV_AWS_3=aws_ebs_volume.target', + '--checkov-executable', + str(executable), + ], + namespace=parsed, + ) + return parsed diff --git a/tests/iac_guard_v_integration_test.py b/tests/iac_guard_v_integration_test.py index db1ed93cf..f7229e10c 100644 --- a/tests/iac_guard_v_integration_test.py +++ b/tests/iac_guard_v_integration_test.py @@ -29,6 +29,10 @@ TIMEOUT = 900 GIT = 'git' AFTER = 'after' +HOOK_ID = 'terraform_iac_guard_v' +CONFIG_FILE = '.pre-commit-config.yaml' +RUN_COMMAND = 'run' +RUN_PATTERN = 'run-*' class ReleasedProductTests(unittest.TestCase): @@ -184,28 +188,28 @@ def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports an 'rev': revision, 'hooks': [ { - 'id': 'terraform_iac_guard_v', + 'id': HOOK_ID, 'args': arguments, }, ], }, ], } - (self.root / '.pre-commit-config.yaml').write_text(json.dumps(config)) + (self.root / CONFIG_FILE).write_text(json.dumps(config)) self.command([GIT, 'add', '.']) for files in ( - ['.pre-commit-config.yaml'], + [CONFIG_FILE], ['after/main.tf', 'after/second.tf'], [], ): with self.subTest(files=files): reports = self.root / '.git/iac-guard-v/runs' - before = set(reports.glob('run-*')) + before = set(reports.glob(RUN_PATTERN)) completed = self.command( [ self.precommit, - 'run', - 'terraform_iac_guard_v', + RUN_COMMAND, + HOOK_ID, '--verbose', '--files', *files, @@ -213,16 +217,54 @@ def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports an cwd=self.root / AFTER, ) self.assertEqual(completed.returncode, 0, completed.stdout) - fresh = set(reports.glob('run-*')) - before + fresh = set(reports.glob(RUN_PATTERN)) - before self.assertEqual(len(fresh), 1) + hook_definition = config['repos'][0]['hooks'][0] + self.check_manual_stage(config, hook_definition) arguments[arguments.index('--after=after')] = '--after=unchanged' - (self.root / '.pre-commit-config.yaml').write_text(json.dumps(config)) + (self.root / CONFIG_FILE).write_text(json.dumps(config)) self.command([GIT, 'add', '.']) failed = self.command( - [self.precommit, 'run', 'terraform_iac_guard_v', '--all-files'], + [self.precommit, RUN_COMMAND, HOOK_ID, '--all-files'], ) self.assertEqual(failed.returncode, 1, failed.stdout) + def check_manual_stage( + self, + config: dict[str, object], + hook_definition: dict[str, object], + ) -> None: + """Test deliberate commit-stage omission and manual verification.""" + hook_definition['stages'] = ['manual'] + (self.root / CONFIG_FILE).write_text(json.dumps(config)) + self.command([GIT, 'add', '.']) + reports = self.root / '.git/iac-guard-v/runs' + existing = set(reports.glob(RUN_PATTERN)) + omitted = self.command( + [ + self.precommit, + RUN_COMMAND, + HOOK_ID, + '--all-files', + ], + ) + self.assertEqual(omitted.returncode, 0, omitted.stdout) + self.assertEqual(set(reports.glob(RUN_PATTERN)), existing) + manual = self.command( + [ + self.precommit, + RUN_COMMAND, + HOOK_ID, + '--hook-stage', + 'manual', + '--all-files', + ], + ) + self.assertEqual(manual.returncode, 0, manual.stdout) + fresh = set(reports.glob(RUN_PATTERN)) - existing + self.assertEqual(len(fresh), 1) + hook_definition.pop('stages') + if __name__ == '__main__': unittest.main() diff --git a/tests/iac_guard_v_process_test.py b/tests/iac_guard_v_process_test.py new file mode 100644 index 000000000..400eac7dc --- /dev/null +++ b/tests/iac_guard_v_process_test.py @@ -0,0 +1,245 @@ +"""Opt-in POSIX process tests; run explicitly on Linux and macOS. + +Keep OS process exercises separate from the deterministic Python unit matrix. +The unit suite exercises transport error paths with typed process doubles; +these tests require actual children, signals, and process identity checks. +""" + +# Standalone test namespace, matching the existing acceptance runner. +# ruff: noqa: INP001 +# OS scenarios and small ownership helpers stay flat rather than nested. +# flake8: noqa: WPS202 + +from __future__ import annotations + +import os +import signal +import subprocess +import sys +import threading +import time +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import pytest + +from pre_commit_terraform import terraform_iac_guard_v as hook + + +if TYPE_CHECKING: + from pre_commit_terraform.terraform_iac_guard_v import _Arguments + +POSIX_ONLY = pytest.mark.skipif( + sys.platform == 'win32', + reason='Native process cleanup requires POSIX', +) +PYTHON_CODE = '-c' +POLL_INTERVAL = 0.01 +WAIT_LIMIT = 5 +SUPERVISOR = """ +import json, os, signal, subprocess, sys, time +from pathlib import Path +pids, report, token = sys.argv[1:] +child = subprocess.Popen( + [sys.executable, '-c', 'import time; time.sleep(30)', token], + start_new_session=True, +) +def cancel(*args): + child.terminate() + child.wait(timeout=3) + raise SystemExit(3) +signal.signal(signal.SIGTERM, cancel) +Path(report).write_text('{"verdict":"VERIFIED","exit_code":0}') +ready = Path(pids).with_suffix(".tmp") +ready.write_text(json.dumps([os.getpid(), child.pid])) +ready.replace(pids) +while True: time.sleep(.05) +""" + + +def _alive(pid: int, token: str) -> bool: + """Check this fixture's argv identity, excluding zombie/reused PIDs. + + Returns: + bool: The original owned process remains running. + """ + if sys.platform == 'linux': + proc = Path('/proc') / str(pid) + try: + command, state = _linux_identity(proc) + except FileNotFoundError: + return False + return token.encode() in command and not state.startswith('Z') + status = subprocess.run( # noqa: S603 — fixed system ps and numeric owned PID + ['/bin/ps', '-o', 'stat=,args=', '-p', str(pid)], + capture_output=True, + text=True, + check=False, + ) + parts = status.stdout.strip().split(maxsplit=1) + return ( + len(parts) == len(('stat', 'args')) + and not parts[0].startswith('Z') + and token in parts[1] + ) + + +def _ready(path: Path) -> list[int]: + deadline = time.monotonic() + WAIT_LIMIT + while not path.exists() and time.monotonic() < deadline: + time.sleep(POLL_INTERVAL) + return cast('list[int]', hook.JSON_LOADS(path.read_text(encoding='utf-8'))) + + +@pytest.mark.parametrize('mode', ('int', 'term', 'repeated', 'timeout')) +@POSIX_ONLY +def test_cooperative_cleanup( # noqa: WPS210,WPS218 — keep process identities and independent assertions explicit + repair: _Arguments, + repository: Path, + monkeypatch: pytest.MonkeyPatch, + mode: str, +) -> None: + """Stop a separately sessioned descendant; quarantine stale output.""" + run = hook.HookRun(repair) + scanner = repository / 'cooperative fixture.py' + scanner.write_text(SUPERVISOR) + pids = repository / 'pids.json' + token = repository.parent.name + command = [ + sys.executable, + str(scanner), + str(pids), + str(run.report), + token, + ] + if mode == 'timeout': + monkeypatch.setattr(hook, 'TIMEOUT', 1) + unrelated = subprocess.Popen( # noqa: S603 — trusted interpreter, literal isolation fixture + [ + sys.executable, + PYTHON_CODE, + 'import time; time.sleep(30)', + 'unrelated', + ], + ) + input_hashes = _snapshot_bytes(repository) + controller = threading.Thread(target=_interrupt_fixture, args=(mode, pids)) + try: # noqa: WPS229 — keep interruption assertions next to guaranteed cleanup + with run.signals(): + controller.start() + with pytest.raises((KeyboardInterrupt, subprocess.TimeoutExpired)): + run._process(command, 'cancellation') # noqa: SLF001 — transport ownership boundary + controller.join(timeout=WAIT_LIMIT) + identities = _ready(pids) + assert not controller.is_alive() + assert all(not _alive(pid, token) for pid in identities) + assert unrelated.poll() is None + assert not run.report.exists() + assert (run.directory / 'unaccepted-report.json').is_file() + assert (run.directory / 'cancellation.stderr.log').is_file() + assert all( + path.read_bytes() == original + for path, original in input_hashes.items() + ) + finally: + _finish_fixture(unrelated, controller, pids, token) + + +@POSIX_ONLY +def test_escalation_stays_in_owned_session( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Bound unresponsive verifier cleanup to its owned session.""" + run = hook.HookRun(repair) + monkeypatch.setattr(hook, 'CLEANUP_TIMEOUT', 0.1) + process = subprocess.Popen( + [ + sys.executable, + '-c', + ( + 'import signal,time; ' + 'signal.signal(signal.SIGTERM, signal.SIG_IGN); ' + 'print("ready",flush=True); time.sleep(30)' + ), + ], + start_new_session=True, + stdout=subprocess.PIPE, + text=True, + ) + assert process.stdout is not None + try: # noqa: WPS229 — readiness, termination and exit evidence share ownership + assert process.stdout.readline() == 'ready\n' + run._stop(process) # noqa: SLF001 — bounded cleanup boundary + assert process.returncode == -signal.SIGKILL + finally: + process.stdout.close() + _reap(process) + + +def _cleanup_owned(identities: list[int], token: str) -> None: + for pid in identities: + if _alive(pid, token): + os.kill(pid, signal.SIGKILL) + + +@POSIX_ONLY +def test_fixture_cleanup_isolated() -> None: + """The fallback reaper checks the owned argv identity.""" + token = f'fixture-owned-cleanup-{os.getpid()}' + owned = subprocess.Popen( # noqa: S603 — owned current-interpreter fixture + [sys.executable, PYTHON_CODE, 'import time; time.sleep(30)', token], + ) + unrelated = subprocess.Popen( # noqa: S603 — trusted interpreter, literal isolation fixture + [sys.executable, PYTHON_CODE, 'import time; time.sleep(30)', 'other'], + ) + try: # noqa: WPS229 — cleanup proof and unrelated-process control share ownership + _cleanup_owned([owned.pid, unrelated.pid], token) + owned.wait(timeout=WAIT_LIMIT) + assert owned.returncode == -signal.SIGKILL + assert unrelated.poll() is None + finally: + for process in (owned, unrelated): + _reap(process) + + +def _linux_identity(proc: Path) -> tuple[bytes, str]: + command = (proc / 'cmdline').read_bytes() + state = (proc / 'stat').read_text(encoding='utf-8').split(') ')[1] + return command, state + + +def _snapshot_bytes(repository: Path) -> dict[Path, bytes]: + snapshots = tuple( + repository / name / 'main.tf' for name in ('before', 'after') + ) + for snapshot in snapshots: + snapshot.write_bytes(b'protected snapshot\n') + return {original: original.read_bytes() for original in snapshots} + + +def _interrupt_fixture(mode: str, pids: Path) -> None: + _ready(pids) + if mode != 'timeout': + signum = signal.SIGINT if mode == 'int' else signal.SIGTERM + os.kill(os.getpid(), signum) + if mode == 'repeated': + os.kill(os.getpid(), signal.SIGINT) + os.kill(os.getpid(), signal.SIGTERM) + + +def _finish_fixture( + unrelated: subprocess.Popen[bytes], + controller: threading.Thread, + pids: Path, + token: str, +) -> None: + unrelated.terminate() + unrelated.wait(timeout=WAIT_LIMIT) + controller.join(timeout=WAIT_LIMIT) + _cleanup_owned(_ready(pids), token) + + +def _reap(process: subprocess.Popen[str] | subprocess.Popen[bytes]) -> None: + process.kill() + process.wait(timeout=WAIT_LIMIT) diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py index c3a55fe60..5bafbd540 100644 --- a/tests/pytest/iac_guard_v_test.py +++ b/tests/pytest/iac_guard_v_test.py @@ -6,23 +6,25 @@ from __future__ import annotations import json +import os import shutil +import signal import subprocess -import sys -from argparse import ArgumentParser from concurrent.futures import ThreadPoolExecutor from pathlib import Path -from typing import TYPE_CHECKING, Final, Protocol +from types import SimpleNamespace +from typing import TYPE_CHECKING, Final, Protocol, cast import pytest from pre_commit_terraform import _cli from pre_commit_terraform import terraform_iac_guard_v as hook -from pre_commit_terraform.terraform_iac_guard_v import _Arguments if TYPE_CHECKING: from collections.abc import Callable + from pre_commit_terraform.terraform_iac_guard_v import _Arguments + BEFORE = 'before' AFTER = 'after' @@ -41,68 +43,12 @@ def __call__( code: int, report: str | None = None, schema: int = 0, - version: str = '1.0.2', + version: str = '1.0.4', ) -> None: """Select product and report outcomes.""" ... -@pytest.fixture -def repository(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - """Create a disposable repository, retaining spaces in its path. - - Returns: - Path: Repository root. - """ - # Windows strips trailing spaces from directory names; POSIX retains them. - name = ( - 'repo with spaces' if sys.platform == 'win32' else 'repo with spaces ' - ) - root = tmp_path / name - root.mkdir() - git = shutil.which('git') - assert git is not None - subprocess.run([git, 'init', '-q', str(root)], check=True) # noqa: S603 — resolved executable and fixed argv - monkeypatch.chdir(root) - return root - - -@pytest.fixture -def repair(repository: Path) -> _Arguments: - """Parse a benign explicit repair request. - - Returns: - _Arguments: Parsed operator-controlled arguments. - """ - executable = repository / 'python' - executable.write_text('#!/bin/sh\nexit 0\n') - executable.chmod(hook.PRIVATE_DIRECTORY_MODE) - for name in (BEFORE, AFTER): - (repository / name).mkdir() - parser = ArgumentParser() - hook.populate_argument_parser(parser) - parsed = _Arguments() - parser.parse_args( - [ - '--iacgv-python', - str(executable), - '--local-trusted', - '--before', - BEFORE, - '--after', - AFTER, - '--framework', - 'terraform', - '--target', - 'CKV_AWS_3=aws_ebs_volume.target', - '--checkov-executable', - str(executable), - ], - namespace=parsed, - ) - return parsed - - @pytest.fixture def transport( monkeypatch: pytest.MonkeyPatch, @@ -117,7 +63,7 @@ def install( code: int, report: str | None = None, schema: int = 0, - version: str = '1.0.2', + version: str = '1.0.4', ) -> None: # noqa: WPS430 — bind fixture state def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: WPS430 — isolated subprocess double (run.directory / f'{label}.stdout.log').write_text(version + '\n') @@ -270,7 +216,7 @@ class TestResults: """Require fresh, consistent reports and preserve product errors.""" @pytest.mark.parametrize('code', (0, 1, 3, 2, 4, 17, -9)) - @pytest.mark.parametrize('version', ('1.0.2', '1.0.3')) + @pytest.mark.parametrize('version', ('1.0.4',)) def test_exit( self, repair: _Arguments, @@ -285,7 +231,7 @@ def test_exit( @pytest.mark.parametrize( 'version', - ('1.0.1', '1.0.3rc1', '1.0.4', '2.0.0', ''), + ('1.0.1', '1.0.2', '1.0.3', '1.0.4rc1', '1.0.5', '2.0.0', ''), ) def test_unreviewed_version( self, @@ -313,7 +259,7 @@ def test_unreviewed_protocol( 'verdict': 'VERIFIED', }, ), - version='1.0.3', + version='1.0.4', ) assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE @@ -472,7 +418,7 @@ def test_missing_report( """A zero exit with no new report cannot establish a result.""" def process(run: hook.HookRun, _command: list[str], label: str) -> int: # noqa: WPS430 — missing report injection - (run.directory / f'{label}.stdout.log').write_text('1.0.2\n') + (run.directory / f'{label}.stdout.log').write_text('1.0.4\n') return 0 monkeypatch.setattr(hook.HookRun, '_process', process) @@ -492,10 +438,155 @@ def test_wrong_version(self, repair: _Arguments) -> None: """An executable without the released product fails before verify.""" assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE - def test_real_process(self, repair: _Arguments) -> None: - """Exercise log creation with literal argv and the real process API.""" - run = hook.HookRun(repair) - shell = shutil.which('sh') - assert shell is not None - assert run._process([shell, '-c', 'exit 4'], 'test') == EXECUTION_ERROR # noqa: SLF001 — exercise transport boundary - assert (run.directory / 'test.stderr.log').is_file() + +def test_post_wait_cancellation( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A signal arriving as wait returns cannot become success.""" + run = hook.HookRun(repair) + + def completed(_self: _ProcessDouble, **_kwargs: object) -> int: # noqa: WPS430 — signal/exit race injection + run.cancelled = True + return 0 + + process = cast('subprocess.Popen[str]', _ProcessDouble([0])) + monkeypatch.setattr(_ProcessDouble, 'wait', completed) + with pytest.raises(KeyboardInterrupt): + run._wait(process, ['fixture']) # noqa: SLF001 — race boundary + + +def test_native_windows_rejected( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Unsupported native cleanup fails before runtime or scanner startup.""" + run = hook.HookRun(repair) + monkeypatch.setattr(hook, 'os', SimpleNamespace(name='nt')) + with pytest.raises(ValueError, match='POSIX'): + run._process(['unreachable'], 'windows') # noqa: SLF001 — platform boundary + + +def test_quarantine_error_is_diagnostic( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A retention failure cannot replace cancellation with a false success.""" + run = hook.HookRun(repair) + run.report.write_text('{}') + + def denied(_path: Path, _target: Path) -> Path: # noqa: WPS430 — filesystem error injection + message = 'retention blocked' + raise OSError(message) + + monkeypatch.setattr(Path, 'rename', denied) + run.invalidate_report() + assert 'retention blocked' in caplog.text + + +def test_cancellation_before_allocation( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Fail closed on interruption during Git discovery.""" + + def interrupted(_self: hook.HookRun, _args: _Arguments) -> None: # noqa: WPS430 — allocation interruption + raise KeyboardInterrupt + + monkeypatch.setattr(hook.HookRun, '__init__', interrupted) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + + +def test_cancelled_after_report( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, + repository: Path, +) -> None: + """Reject cancellation after product completion/report creation.""" + + def completed(run: hook.HookRun, _args: _Arguments) -> int: # noqa: WPS430 — finalization race + run.report.write_text('{"verdict":"VERIFIED","exit_code":0}') + run.cancelled = True + return 0 + + monkeypatch.setattr(hook.HookRun, 'verify', completed) + assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE + assert not list(repository.glob('.git/iac-guard-v/runs/*/report.json')) + assert ( + len( + list( + repository.glob( + '.git/iac-guard-v/runs/*/unaccepted-report.json', + ), + ), + ) + == 1 + ) + + +class _ProcessDouble: + """Only the Popen ownership contract consumed by this transport.""" + + def __init__(self, responses: list[int | BaseException]) -> None: + self.responses = responses + self.pid = 12345 + self.returncode: int | None = None + self.terminated = False + + def terminate(self) -> None: + self.terminated = True + + def wait(self, *, timeout: float) -> int: + outcome = self.responses.pop(0) + if isinstance(outcome, BaseException): + raise outcome + self.returncode = outcome + return outcome + + +@pytest.mark.parametrize( + 'mode', + ('completed', 'cancelled', 'deadline', 'escalation'), +) +def test_process_contract( + repair: _Arguments, + monkeypatch: pytest.MonkeyPatch, + mode: str, +) -> None: + """Test transport exits and bounded cleanup on every unit-test platform.""" + run = hook.HookRun(repair) + timeout = subprocess.TimeoutExpired('fixture', 1) + responses: list[int | BaseException] = [EXECUTION_ERROR] + if mode == 'completed': + responses = [timeout, EXECUTION_ERROR] + elif mode == 'escalation': + responses = [timeout, -9] + process = _ProcessDouble(responses) + signals: list[tuple[int, int]] = [] + monkeypatch.setattr(hook, 'signal', SimpleNamespace(SIGKILL=9)) + monkeypatch.setattr( + hook, + 'os', + SimpleNamespace( + name='posix', + environ=os.environ, + killpg=lambda pid, sig: signals.append((pid, sig)), + ), + ) + monkeypatch.setattr(subprocess, 'Popen', lambda *_args, **_kwargs: process) + expected: type[BaseException] + if mode == 'completed': + assert run._process(['literal'], 'completed') == EXECUTION_ERROR # noqa: SLF001 — transport contract + assert (run.directory / 'completed.stderr.log').is_file() + else: + if mode == 'deadline': + monkeypatch.setattr(hook, 'TIMEOUT', 0) + expected = subprocess.TimeoutExpired + else: + run._interrupt(signal.SIGTERM, None) # noqa: SLF001 — signal latch contract + expected = KeyboardInterrupt + with pytest.raises(expected): + run._process(['literal'], mode) # noqa: SLF001 — cleanup ownership contract + assert process.terminated + assert signals == ([(process.pid, 9)] if mode == 'escalation' else []) diff --git a/tox.ini b/tox.ini index fc2237aa3..26699b8b9 100644 --- a/tox.ini +++ b/tox.ini @@ -303,3 +303,12 @@ package = skip pass_env = {[testenv]pass_env} SKIP # set this variable + + +[testenv:iacgv-process] +description = Exercise actual POSIX process cancellation and isolation +commands = + {envpython} -I -Werror -m pytest \ + -o addopts= tests/iac_guard_v_process_test.py -v \ + --junitxml={envtmpdir}{/}process.xml +commands_post = From c4ca4c66c047d35c726b03863208b189927298c5 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 11:16:55 -0600 Subject: [PATCH 07/10] test: Type scanner controller constructor Narrow only the keyword-only Thread constructor used by the process fixture, keeping its runtime behavior and strict typing coverage precise. Assisted-by: AI tooling --- tests/iac_guard_v_process_test.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/tests/iac_guard_v_process_test.py b/tests/iac_guard_v_process_test.py index 400eac7dc..2b49df958 100644 --- a/tests/iac_guard_v_process_test.py +++ b/tests/iac_guard_v_process_test.py @@ -19,7 +19,7 @@ import threading import time from pathlib import Path -from typing import TYPE_CHECKING, cast +from typing import TYPE_CHECKING, Final, Protocol, cast import pytest @@ -27,8 +27,21 @@ if TYPE_CHECKING: + from collections.abc import Callable + from pre_commit_terraform.terraform_iac_guard_v import _Arguments + +class ControllerFactory(Protocol): + """Only the keyword-only Thread constructor subset used by this fixture.""" + + def __call__(self, *, target: Callable[[], None]) -> threading.Thread: + """Construct a controller with no untyped argument forwarding.""" + ... + + +CONTROLLER: Final[ControllerFactory] = threading.Thread + POSIX_ONLY = pytest.mark.skipif( sys.platform == 'win32', reason='Native process cleanup requires POSIX', @@ -123,7 +136,11 @@ def test_cooperative_cleanup( # noqa: WPS210,WPS218 — keep process identities ], ) input_hashes = _snapshot_bytes(repository) - controller = threading.Thread(target=_interrupt_fixture, args=(mode, pids)) + + def interrupt() -> None: # noqa: WPS430 — precisely typed controller closure + _interrupt_fixture(mode, pids) + + controller = CONTROLLER(target=interrupt) try: # noqa: WPS229 — keep interruption assertions next to guaranteed cleanup with run.signals(): controller.start() From 9477c6466cdeda62b7ef102508b1ed472347fb8e Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 11:41:41 -0600 Subject: [PATCH 08/10] test: Isolate manual-stage acceptance cases Correct default-stage omission without selecting a manual-only hook. Keep independent positive, failed and manual pre-commit cases reusable for focused replay. Precisely type the process-platform double and verify session ownership arguments. Isolate process-suite coverage data from the unit matrix. Assisted-by: AI tooling --- tests/iac_guard_v_integration_test.py | 88 ++++++++++++++++----------- tests/pytest/iac_guard_v_test.py | 32 +++++++--- tox.ini | 3 + 3 files changed, 77 insertions(+), 46 deletions(-) diff --git a/tests/iac_guard_v_integration_test.py b/tests/iac_guard_v_integration_test.py index f7229e10c..0ec5d832e 100644 --- a/tests/iac_guard_v_integration_test.py +++ b/tests/iac_guard_v_integration_test.py @@ -17,6 +17,7 @@ import subprocess import unittest from pathlib import Path +from typing import TypeAlias BAD = ( @@ -35,6 +36,13 @@ RUN_PATTERN = 'run-*' +PrecommitConfiguration: TypeAlias = tuple[ + dict[str, object], + list[str], + dict[str, object], +] + + class ReleasedProductTests(unittest.TestCase): """Real scanner verdicts and real pre-commit process exits.""" @@ -169,34 +177,7 @@ def test_repair_verdicts(self) -> None: # noqa: WPS210 — explicit evidence pe def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports and process evidence """Exercise manifest metadata and different pre-commit selections.""" - revision = self.command( - [GIT, '-C', str(self.source), 'rev-parse', 'HEAD'], - ).stdout.strip() - arguments = [ - f'--iacgv-python={self.product}', - '--local-trusted', - '--before=before', - '--after=after', - '--framework=terraform', - f'--target={TARGET}', - f'--checkov-executable={self.scanner}', - ] - config = { - 'repos': [ - { - 'repo': str(self.source), - 'rev': revision, - 'hooks': [ - { - 'id': HOOK_ID, - 'args': arguments, - }, - ], - }, - ], - } - (self.root / CONFIG_FILE).write_text(json.dumps(config)) - self.command([GIT, 'add', '.']) + self.configure_precommit() for files in ( [CONFIG_FILE], ['after/main.tf', 'after/second.tf'], @@ -219,8 +200,10 @@ def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports an self.assertEqual(completed.returncode, 0, completed.stdout) fresh = set(reports.glob(RUN_PATTERN)) - before self.assertEqual(len(fresh), 1) - hook_definition = config['repos'][0]['hooks'][0] - self.check_manual_stage(config, hook_definition) + + def test_precommit_failure(self) -> None: + """A real FAILED/1 verifier must fail the outer pre-commit process.""" + config, arguments, _hook = self.configure_precommit() arguments[arguments.index('--after=after')] = '--after=unchanged' (self.root / CONFIG_FILE).write_text(json.dumps(config)) self.command([GIT, 'add', '.']) @@ -229,12 +212,9 @@ def test_precommit(self) -> None: # noqa: WPS210 — retain request, reports an ) self.assertEqual(failed.returncode, 1, failed.stdout) - def check_manual_stage( - self, - config: dict[str, object], - hook_definition: dict[str, object], - ) -> None: + def test_manual_stage(self) -> None: # noqa: WPS210 — explicit stage, request and report evidence """Test deliberate commit-stage omission and manual verification.""" + config, _arguments, hook_definition = self.configure_precommit() hook_definition['stages'] = ['manual'] (self.root / CONFIG_FILE).write_text(json.dumps(config)) self.command([GIT, 'add', '.']) @@ -244,7 +224,6 @@ def check_manual_stage( [ self.precommit, RUN_COMMAND, - HOOK_ID, '--all-files', ], ) @@ -265,6 +244,43 @@ def check_manual_stage( self.assertEqual(len(fresh), 1) hook_definition.pop('stages') + def configure_precommit( + self, + ) -> PrecommitConfiguration: + """Write the tested hook configuration and return its trusted fields. + + Returns: + tuple: Configuration, product arguments and hook definition. + """ + revision = self.command( + [GIT, '-C', str(self.source), 'rev-parse', 'HEAD'], + ).stdout.strip() + arguments = [ + f'--iacgv-python={self.product}', + '--local-trusted', + '--before=before', + '--after=after', + '--framework=terraform', + f'--target={TARGET}', + f'--checkov-executable={self.scanner}', + ] + hook_definition: dict[str, object] = { + 'id': HOOK_ID, + 'args': arguments, + } + config: dict[str, object] = { + 'repos': [ + { + 'repo': str(self.source), + 'rev': revision, + 'hooks': [hook_definition], + }, + ], + } + (self.root / CONFIG_FILE).write_text(json.dumps(config)) + self.command([GIT, 'add', '.']) + return config, arguments, hook_definition + if __name__ == '__main__': unittest.main() diff --git a/tests/pytest/iac_guard_v_test.py b/tests/pytest/iac_guard_v_test.py index 5bafbd540..ace02e93d 100644 --- a/tests/pytest/iac_guard_v_test.py +++ b/tests/pytest/iac_guard_v_test.py @@ -545,6 +545,19 @@ def wait(self, *, timeout: float) -> int: return outcome +class _ProcessPlatform: + """Precisely typed POSIX operations, without sending real OS signals.""" + + name = 'posix' + + def __init__(self, signals: list[tuple[int, int]]) -> None: + self.environ = dict(os.environ) + self.signals = signals + + def killpg(self, pid: int, signum: int) -> None: + self.signals.append((pid, signum)) + + @pytest.mark.parametrize( 'mode', ('completed', 'cancelled', 'deadline', 'escalation'), @@ -565,16 +578,15 @@ def test_process_contract( process = _ProcessDouble(responses) signals: list[tuple[int, int]] = [] monkeypatch.setattr(hook, 'signal', SimpleNamespace(SIGKILL=9)) - monkeypatch.setattr( - hook, - 'os', - SimpleNamespace( - name='posix', - environ=os.environ, - killpg=lambda pid, sig: signals.append((pid, sig)), - ), - ) - monkeypatch.setattr(subprocess, 'Popen', lambda *_args, **_kwargs: process) + monkeypatch.setattr(hook, 'os', _ProcessPlatform(signals)) + + def spawn(command: list[str], **options: object) -> _ProcessDouble: # noqa: WPS430 — trusted argv/session transport contract + assert command == ['literal'] + assert options['start_new_session'] is True + assert options['cwd'] == run.root + return process + + monkeypatch.setattr(subprocess, 'Popen', spawn) expected: type[BaseException] if mode == 'completed': assert run._process(['literal'], 'completed') == EXECUTION_ERROR # noqa: SLF001 — transport contract diff --git a/tox.ini b/tox.ini index 26699b8b9..62df8be4e 100644 --- a/tox.ini +++ b/tox.ini @@ -306,6 +306,9 @@ pass_env = [testenv:iacgv-process] +set_env = + COVERAGE_PROCESS_START = {toxinidir}{/}.coveragerc + COVERAGE_FILE = {envtmpdir}{/}.coverage description = Exercise actual POSIX process cancellation and isolation commands = {envpython} -I -Werror -m pytest \ From 1816b1befaf6d2caef599934f30b4fa0b1114e16 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 16:21:00 -0600 Subject: [PATCH 09/10] test: synchronize cancellation fixture startup Acknowledge the supervisor and its live descendant before entering the existing timeout loop. Gate fixture startup so this ordering is exercised deterministically, and require the expected signal or timeout exception. Assisted-by: AI tooling --- tests/iac_guard_v_process_test.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/tests/iac_guard_v_process_test.py b/tests/iac_guard_v_process_test.py index 2b49df958..d5419a39f 100644 --- a/tests/iac_guard_v_process_test.py +++ b/tests/iac_guard_v_process_test.py @@ -53,6 +53,7 @@ def __call__(self, *, target: Callable[[], None]) -> threading.Thread: import json, os, signal, subprocess, sys, time from pathlib import Path pids, report, token = sys.argv[1:] +while not Path(pids).with_suffix(".start").exists(): time.sleep(.01) child = subprocess.Popen( [sys.executable, '-c', 'import time; time.sleep(30)', token], start_new_session=True, @@ -127,6 +128,20 @@ def test_cooperative_cleanup( # noqa: WPS210,WPS218 — keep process identities ] if mode == 'timeout': monkeypatch.setattr(hook, 'TIMEOUT', 1) + wait = run._wait # noqa: SLF001 — preserve the real timeout loop + + def wait_when_ready( # noqa: WPS430 — synchronize before the real deadline starts + process: subprocess.Popen[str], + arguments: list[str], + ) -> int: + pids.with_suffix('.start').touch() + supervisor, descendant = _ready(pids) + assert supervisor == process.pid + assert _alive(supervisor, token) + assert _alive(descendant, token) + return wait(process, arguments) + + monkeypatch.setattr(run, '_wait', wait_when_ready) unrelated = subprocess.Popen( # noqa: S603 — trusted interpreter, literal isolation fixture [ sys.executable, @@ -144,7 +159,12 @@ def interrupt() -> None: # noqa: WPS430 — precisely typed controller closure try: # noqa: WPS229 — keep interruption assertions next to guaranteed cleanup with run.signals(): controller.start() - with pytest.raises((KeyboardInterrupt, subprocess.TimeoutExpired)): + expected = ( + subprocess.TimeoutExpired + if mode == 'timeout' + else KeyboardInterrupt + ) + with pytest.raises(expected): run._process(command, 'cancellation') # noqa: SLF001 — transport ownership boundary controller.join(timeout=WAIT_LIMIT) identities = _ready(pids) From 83ce3a31349fe5ca60db8cb69682f2983492b5a8 Mon Sep 17 00:00:00 2001 From: lokesh0186 Date: Sun, 8 Nov 2026 16:35:38 -0600 Subject: [PATCH 10/10] test: bound cancellation fixture startup Exit before creating a scanner or report if the startup acknowledgement never arrives. Exercise this branch with a real, reaped subprocess. Assisted-by: AI tooling --- tests/iac_guard_v_process_test.py | 32 +++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/tests/iac_guard_v_process_test.py b/tests/iac_guard_v_process_test.py index d5419a39f..387560973 100644 --- a/tests/iac_guard_v_process_test.py +++ b/tests/iac_guard_v_process_test.py @@ -52,8 +52,12 @@ def __call__(self, *, target: Callable[[], None]) -> threading.Thread: SUPERVISOR = """ import json, os, signal, subprocess, sys, time from pathlib import Path -pids, report, token = sys.argv[1:] -while not Path(pids).with_suffix(".start").exists(): time.sleep(.01) +pids, report, token, startup_timeout = sys.argv[1:] +deadline = time.monotonic() + float(startup_timeout) +while not Path(pids).with_suffix(".start").exists(): + if time.monotonic() >= deadline: + raise SystemExit(3) + time.sleep(.01) child = subprocess.Popen( [sys.executable, '-c', 'import time; time.sleep(30)', token], start_new_session=True, @@ -125,6 +129,7 @@ def test_cooperative_cleanup( # noqa: WPS210,WPS218 — keep process identities str(pids), str(run.report), token, + str(WAIT_LIMIT), ] if mode == 'timeout': monkeypatch.setattr(hook, 'TIMEOUT', 1) @@ -182,6 +187,29 @@ def interrupt() -> None: # noqa: WPS430 — precisely typed controller closure _finish_fixture(unrelated, controller, pids, token) +@POSIX_ONLY +def test_supervisor_startup_deadline(tmp_path: Path) -> None: + """An unacknowledged fixture exits before creating a scanner or report.""" + pids = tmp_path / 'pids.json' + report = tmp_path / 'report.json' + completed = subprocess.run( # noqa: S603 — current interpreter and literal fixture argv + [ + sys.executable, + PYTHON_CODE, + SUPERVISOR, + str(pids), + str(report), + tmp_path.name, + str(POLL_INTERVAL), + ], + check=False, + timeout=WAIT_LIMIT, + ) + assert completed.returncode == hook.INCONCLUSIVE + assert not pids.exists() + assert not report.exists() + + @POSIX_ONLY def test_escalation_stays_in_owned_session( repair: _Arguments,