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..16bd38cc3 100644
--- a/.github/workflows/build-image-test.yaml
+++ b/.github/workflows/build-image-test.yaml
@@ -11,6 +11,83 @@ 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
+ timeout-minutes: 45
+ strategy:
+ matrix:
+ checkov-version:
+ - 3.3.0
+ - 3.3.30
+ - 3.4.3
+ 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.4 .
+
+ - 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/.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/.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 fd647dae2..b650ac249 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.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
@@ -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.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` |
@@ -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`
@@ -616,6 +623,212 @@ 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.
+
+The optional [terraform_iac_guard_v](#terraform_iac_guard_v) hook packages that
+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.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,
+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.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.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
+```
+
+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
+repos:
+- repo: https://github.com/antonbabenko/pre-commit-terraform
+ rev: # Release/commit containing terraform_iac_guard_v
+ hooks:
+ - id: terraform_iac_guard_v
+ args:
+ - --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.4/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. 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
+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.4.3 \
+ --build-arg IAC_GUARD_V_VERSION=1.0.4 .
+```
+
+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 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
+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.
+
+**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
+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.3/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
`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)).
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..88dbc51eb
--- /dev/null
+++ b/src/pre_commit_terraform/terraform_iac_guard_v.py
@@ -0,0 +1,401 @@
+"""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
+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
+
+
+if TYPE_CHECKING:
+ from argparse import ArgumentParser
+ from collections.abc import Callable, Iterator
+ from types import FrameType
+
+
+# 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.
+SUPPORTED_PROTOCOLS: Final = MappingProxyType(
+ {'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
+# 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()))'
+)
+# 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:
+ 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',
+ type=str,
+ 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 = cast('_Arguments', parsed)
+ 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'
+ self.cancelled = False
+
+ 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',
+ )
+ product_version = (
+ (self.directory / 'runtime.stdout.log').read_text().strip()
+ )
+ protocol = SUPPORTED_PROTOCOLS.get(product_version)
+ _require(
+ '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.',
+ 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('schema_version') == protocol
+ and 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 _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,
+ ):
+ process = subprocess.Popen( # noqa: S603 — explicit trusted executable, literal argv
+ command,
+ cwd=self.root,
+ env=dict(os.environ, PYTHONDONTWRITEBYTECODE='1'),
+ stdout=stdout,
+ stderr=stderr,
+ text=True,
+ start_new_session=True,
+ )
+ 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:
+ """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.
+ """
+ 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.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.',
+ )
+ return INCONCLUSIVE
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
new file mode 100644
index 000000000..0ec5d832e
--- /dev/null
+++ b/tests/iac_guard_v_integration_test.py
@@ -0,0 +1,286 @@
+"""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
+from typing import TypeAlias
+
+
+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'
+HOOK_ID = 'terraform_iac_guard_v'
+CONFIG_FILE = '.pre-commit-config.yaml'
+RUN_COMMAND = 'run'
+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."""
+
+ 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."""
+ self.configure_precommit()
+ for files in (
+ [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_PATTERN))
+ completed = self.command(
+ [
+ self.precommit,
+ RUN_COMMAND,
+ HOOK_ID,
+ '--verbose',
+ '--files',
+ *files,
+ ],
+ cwd=self.root / AFTER,
+ )
+ self.assertEqual(completed.returncode, 0, completed.stdout)
+ fresh = set(reports.glob(RUN_PATTERN)) - before
+ self.assertEqual(len(fresh), 1)
+
+ 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', '.'])
+ failed = self.command(
+ [self.precommit, RUN_COMMAND, HOOK_ID, '--all-files'],
+ )
+ self.assertEqual(failed.returncode, 1, failed.stdout)
+
+ 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', '.'])
+ reports = self.root / '.git/iac-guard-v/runs'
+ existing = set(reports.glob(RUN_PATTERN))
+ omitted = self.command(
+ [
+ self.precommit,
+ RUN_COMMAND,
+ '--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')
+
+ 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/iac_guard_v_process_test.py b/tests/iac_guard_v_process_test.py
new file mode 100644
index 000000000..387560973
--- /dev/null
+++ b/tests/iac_guard_v_process_test.py
@@ -0,0 +1,310 @@
+"""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, Final, Protocol, cast
+
+import pytest
+
+from pre_commit_terraform import terraform_iac_guard_v as hook
+
+
+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',
+)
+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, 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,
+)
+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,
+ str(WAIT_LIMIT),
+ ]
+ 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,
+ PYTHON_CODE,
+ 'import time; time.sleep(30)',
+ 'unrelated',
+ ],
+ )
+ input_hashes = _snapshot_bytes(repository)
+
+ 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()
+ 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)
+ 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_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,
+ 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
new file mode 100644
index 000000000..ace02e93d
--- /dev/null
+++ b/tests/pytest/iac_guard_v_test.py
@@ -0,0 +1,604 @@
+"""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 os
+import shutil
+import signal
+import subprocess
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+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
+
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ from pre_commit_terraform.terraform_iac_guard_v import _Arguments
+
+
+BEFORE = 'before'
+AFTER = 'after'
+REPORT = 'report'
+USAGE_ERROR = 2
+EXECUTION_ERROR = 4
+REPEATED_RUNS = 2
+JSON_DUMPS: Final[Callable[[object], str]] = json.dumps
+
+
+class Transport(Protocol):
+ """Typed process-double installer with optional scenario arguments."""
+
+ def __call__(
+ self,
+ code: int,
+ report: str | None = None,
+ schema: int = 0,
+ version: str = '1.0.4',
+ ) -> None:
+ """Select product and report outcomes."""
+ ...
+
+
+@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,
+ 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')
+ 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: _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'
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments, 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: _Arguments,
+ 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: _Arguments,
+ 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))
+ @pytest.mark.parametrize('version', ('1.0.4',))
+ def test_exit(
+ self,
+ repair: _Arguments,
+ transport: Transport,
+ code: int,
+ version: str,
+ ) -> None:
+ """Keep errors distinct; a killed child cannot establish success."""
+ 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.2', '1.0.3', '1.0.4rc1', '1.0.5', '2.0.0', ''),
+ )
+ def test_unreviewed_version(
+ self,
+ repair: _Arguments,
+ 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: _Arguments,
+ 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.4',
+ )
+ assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE
+
+ @pytest.mark.parametrize(
+ REPORT,
+ (
+ '',
+ '{',
+ '[]',
+ '{}',
+ '{"exit_code":true}',
+ '{"exit_code":0,"verdict":"FAILED"}',
+ ),
+ )
+ def test_invalid_report(
+ self,
+ repair: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ repository: Path,
+ transport: Transport,
+ ) -> None:
+ """Repeated and concurrent requests never overwrite evidence."""
+ transport(0)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ 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
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ 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: _Arguments,
+ 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.4\n')
+ return 0
+
+ monkeypatch.setattr(hook.HookRun, '_process', process)
+ assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE
+
+ def test_no_input_mutation(
+ self,
+ repair: _Arguments,
+ 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: _Arguments) -> None:
+ """An executable without the released product fails before verify."""
+ assert hook.invoke_cli_app(repair) == hook.INCONCLUSIVE
+
+
+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
+
+
+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'),
+)
+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', _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
+ 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/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.
diff --git a/tox.ini b/tox.ini
index fc2237aa3..62df8be4e 100644
--- a/tox.ini
+++ b/tox.ini
@@ -303,3 +303,15 @@ package = skip
pass_env =
{[testenv]pass_env}
SKIP # set this variable
+
+
+[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 \
+ -o addopts= tests/iac_guard_v_process_test.py -v \
+ --junitxml={envtmpdir}{/}process.xml
+commands_post =