Skip to content

feat(hooks): add hook kinds, scanner integrations, SARIF summaries, and skip controls - #2482

Merged
Andriy Knysh (aknysh) merged 19 commits into
mainfrom
osterman/component-hooks-tfsec-sarif
May 25, 2026
Merged

Andriy Knysh (aknysh) merged 19 commits into
mainfrom
osterman/component-hooks-tfsec-sarif

Conversation

@osterman

@osterman Erik Osterman (Cloud Posse) (osterman) commented May 23, 2026 •

Copy link
Copy Markdown
Member

what

  • Adds a kind discriminator to the hook system with built-in kinds for store, command, infracost, checkov, trivy, and kics.
  • Adds the generic command hook engine, including toolchain-aware binary resolution, live stdout/stderr passthrough, templated args/env support, ATMOS_* runtime env vars, output-file/output-dir side channels, and configurable on_failure behavior.
  • Adds scanner and cost integrations:
    • infracost parses JSON breakdown output into a markdown cost summary.
    • checkov, trivy, and kics emit SARIF and share one parser/markdown renderer.
  • Adds normalized SARIF handling for severity counts, linked rule IDs via helpUri, short descriptions, file/line locations, and empty-result handling.
  • Adds hook dependency preflight: component dependencies.tools are installed before hooks run, toolchain paths take precedence over operator PATH, and missing hook binaries fail before Terraform starts.
  • Adds a curated embedded Atmos tool registry with a KICS override so dependencies.tools.kics can install from release tarballs.
  • Adds pkg/cacerts and wires Checkov to SSL_CERT_FILE / REQUESTS_CA_BUNDLE so PyInstaller-bundled Checkov can use the host CA bundle.
  • Adds the --skip-hooks global flag and ATMOS_SKIP_HOOKS, supporting skip-all and comma-separated named-hook skipping.
  • Preserves backward compatibility by accepting legacy command: store hook configs as kind: store.
  • Makes hooks work with resolved component workdirs so scanners inspect the same directory Terraform uses.
  • Adds runnable examples for infracost, checkov, trivy, kics, and custom kind: command hooks.
  • Updates hook docs, global flag docs, PRDs, roadmap data, and adds the custom hooks blog post.
  • Refreshes CLI help snapshots and updates CI workflow actions/shell handling needed by the branch.

why

  • Hooks were already the right lifecycle surface for component automation, but only store had first-class dispatch behavior.
  • Security scanners, cost estimators, and custom tools should run from stack config without wrapper scripts or GitHub Actions glue.
  • Named kinds provide zero-config defaults for common tools, while kind: command keeps the system open for arbitrary binaries.
  • Tool auto-install and preflight failures make examples and CI usage reproducible instead of relying on whatever happens to be on PATH.
  • SARIF and infracost summaries create a common typed output path for terminal rendering now and Atmos Pro upload later.

notes

  • This PR intentionally does not add a built-in tfsec kind or hooks-tfsec example. Trivy is the maintained Aqua-backed scanner path; legacy tfsec users can still wire it with kind: command.
  • Atmos Pro upload, cross-run SARIF aggregation, Terraform component dependency auto-install outside hooks, and planfile threading remain follow-up work.
  • The CodeRabbit-generated release notes below are preserved as-is.

Summary by CodeRabbit

  • New Features

    • Pluggable hook "kinds" (infracost, trivy, checkov, kics) plus a generic command kind; structured side‑channel outputs, markdown rendering, preflight tool resolution/auto‑install, CA‑bundle propagation, and per‑invocation hook skipping via --skip-hooks / ATMOS_SKIP_HOOKS.
  • Documentation

    • Detailed PRDs, reference docs, CLI help, blog post, and runnable examples for each hook kind.
  • Tests

    • Expanded unit and integration tests covering hooks, result handlers, SARIF parsing, toolchain registry, and examples.

Review Change Stack

@atmos-pro

atmos-pro Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Tip

Atmos Pro  

No affected stacks workflow was detected for this pull request.
If this is expected, no action is needed.
Learn More. Ask AI.

@osterman Erik Osterman (Cloud Posse) (osterman) added the minor New features that do not break anything label May 23, 2026
@github-actions github-actions Bot added the size/xl Extra large size PR label May 23, 2026
@github-actions

github-actions Bot commented May 23, 2026 •

Copy link
Copy Markdown

Dependency Review

The following issues were found:
  • ✅ 0 vulnerable package(s)
  • ✅ 0 package(s) with incompatible licenses
  • ✅ 0 package(s) with invalid SPDX license definitions
  • ⚠️ 3 package(s) with unknown licenses.
See the Details below.

License Issues

.github/workflows/test.yml

PackageVersionLicenseIssue Type
InoUno/yaml-ls-check2c229b85b877b2853b40bd0fbdcfccff5ff735c7NullUnknown License
cloudposse/.github/.github/workflows/shared-go-auto-release.yml8244c7c9142e92281e7841f655fa48e9ceb9b454NullUnknown License
hashicorp/setup-packer81d37653906f884aa356bd1208c578820280fdc6NullUnknown License
Allowed Licenses: MIT, MIT-0, Apache-2.0, BSD-2-Clause, BSD-2-Clause-Views, BSD-3-Clause, ISC, MPL-2.0, 0BSD, Unlicense, CC0-1.0, CC-BY-3.0, CC-BY-4.0, CC-BY-SA-3.0, Python-2.0, OFL-1.1, LicenseRef-scancode-generic-cla, LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-unicode, LicenseRef-scancode-google-patent-license-golang
Excluded from license check: pkg:golang/modernc.org/libc

Scanned Files

  • .github/workflows/test.yml

@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

Adds a pluggable hook "kind" system: kind registry and Hook schema, a generic command engine, SARIF parser/renderer and built-in kinds (infracost/checkov/kics/trivy/store), preflight tool install/verify and --skip-hooks, cacerts helper, embedded tool registry, many examples, docs, CI pinning, and comprehensive tests.

Changes

Hooks feature

Layer / File(s) Summary
Kind registry, types, and Hook schema
pkg/hooks/kind.go, pkg/hooks/hook.go, pkg/hooks/kind_test.go
Adds public types (Engine, ExecContext, Output, Artifact, Summary), a concurrency-safe kind registry (Register/Get/List/Clear), Hook schema changes (Kind, Args, Env, Format, OnFailure) and YAML compatibility support (UnmarshalYAML) with tests.
Command engine & execution pipeline
pkg/hooks/command_engine.go, pkg/hooks/command_engine_test.go
Implements the command Engine: env/arg expansion, toolchain-augmented PATH resolution, subprocess execution with stdout/stderr streaming, structured side-channel output capture, ResultHandler invocation, on_failure semantics, and many unit/integration tests.
SARIF parser, handler, and markdown renderer
pkg/hooks/sarif/sarif.go, pkg/hooks/sarif/handler.go, pkg/hooks/sarif/markdown.go, tests
Parses SARIF into normalized Findings, buckets/seeds severities, renders markdown summaries, and exposes NewResultHandler to build hook summaries from SARIF with tests.
Built-in kinds registrations and parsers
pkg/hooks/kinds/infracost/*, pkg/hooks/kinds/checkov/*, pkg/hooks/kics/*, pkg/hooks/kinds/trivy/*, pkg/hooks/store_cmd.go
Registers built-in kinds (infracost with JSON parser, checkov/kics/trivy with SARIF handlers, store adapted to Engine) and associated tests; uses cacerts.Env() for some Python-based tools.
Hooks orchestration, preflight & skip logic
pkg/hooks/hooks.go, pkg/hooks/skip_test.go, pkg/flags/*
Refactors RunAll to run a preflight that installs/verifies tool deps and builds ToolchainPATH, adds --skip-hooks/ATMOS_SKIP_HOOKS handling and per-invocation skip predicate, binary verification helpers, and tests.
Toolchain builtin registry & loader changes
pkg/toolchain/registry/atmos/builtin.go, pkg/toolchain/registry/loader.go, pkg/toolchain/registry/atmos/builtin.yaml
Embeds a curated built-in registry (KICS override), adds RegisterBuiltinAtmosRegistry and composite loading behavior so built-ins can win and be tested; includes test.
CACerts helper
pkg/cacerts/cacerts.go, pkg/cacerts/cacerts_test.go
Adds discovery of system CA bundle path and Env() helper to populate SSL env vars for subprocesses; includes caching and tests.
Examples, docs, website, CLI snapshots, CI
examples/hooks-*, docs/prd/custom-hooks.md, website/docs/..., website/blog/..., tests/snapshots/*, .github/workflows/test.yml
Adds multiple hook examples (trivy/checkov/kics/infracost/custom command), comprehensive docs/PRD/website content, help snapshot updates for --skip-hooks, and CI action pinning changes.
Minor test formatting and small refactors
assorted test files, cmd/terraform/output.go
Cosmetic reformatting in several tests and small var consolidation changes; no behavior change.
  • Estimated code review effort: 🎯 4 (Complex) | ⏱️ ~45 minutes

  • Possibly related PRs:

  • Suggested reviewers:

    • aknysh
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch osterman/component-hooks-tfsec-sarif

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 17

🧹 Nitpick comments (3)
docs/prd/custom-hooks.md (1)

328-328: 💤 Low value

Clarify Format field scope.

Line 328 comments "for kind=command" but the Hook struct at line 260 shows Format as a general field without that restriction. The Schema section (line 242) also shows Format applies to kind: command specifically. Consider aligning the wire format comment with the schema definition.

📝 Suggested clarification
-    Format        string            `json:"format,omitempty"` // for kind=command
+    Format        string            `json:"format,omitempty"` // only present when Hook.Format is set (generic kinds)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/prd/custom-hooks.md` at line 328, The comment on the Format field in the
Hook struct is inconsistent with the Schema section; update the documentation so
the Format field is clearly scoped to command hooks only: change the inline
comment on the Format field (Format string `json:"format,omitempty"`) to state
"applies only when Kind == \"command\"" and/or update the Schema section to
reflect that Format is only valid for kind: command, ensuring both the Hook
struct comment and Schema section use the same wording.
pkg/hooks/kinds/infracost/parser.go (1)

200-203: ⚡ Quick win

Escape markdown table cells before writing resource values.

Line 202 writes r.name and r.rtype directly into markdown cells. Values containing | or newlines can break table structure and produce misleading output.

Proposed fix
+func escapeMarkdownCell(s string) string {
+	s = strings.ReplaceAll(s, "|", `\|`)
+	s = strings.ReplaceAll(s, "\n", " ")
+	return strings.TrimSpace(s)
+}
+
 func renderMarkdown(b *breakdown, now, past, diff float64, currency string) string {
@@
 	sb.WriteString("\n| Resource | Type | Monthly |\n|---|---|---|\n")
 	for _, r := range rows[:limit] {
-		fmt.Fprintf(&sb, "| %s | %s | %s%.2f |\n", r.name, r.rtype, symbol, r.monthly)
+		fmt.Fprintf(&sb, "| %s | %s | %s%.2f |\n",
+			escapeMarkdownCell(r.name),
+			escapeMarkdownCell(r.rtype),
+			symbol,
+			r.monthly,
+		)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/hooks/kinds/infracost/parser.go` around lines 200 - 203, The markdown
table cells are written raw, so values like r.name and r.rtype can contain '|'
or newlines and break the table; add a small helper (e.g., escapeMarkdownCell)
that replaces pipe characters with '\|' and converts newlines to a safe
separator (space or '<br>'), then use that helper when formatting the rows
(replace r.name and r.rtype in the fmt.Fprintf call with the escaped versions)
so sb.WriteString/ fmt.Fprintf writes sanitized cell content.
pkg/hooks/hooks_test.go (1)

158-385: ⚡ Quick win

Add a regression test for skip-hooks + preflight binary verification.

Given the new preflight phase, it’s worth adding a RunAll test that proves a skipped hook with a missing command does not fail the invocation.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/hooks/hooks_test.go` around lines 158 - 385, Add a regression test in
hooks_test.go that constructs a Hooks containing a Hook configured for the
preflight event (use the same Hook struct as in existing tests) but with its
command/binary field left empty and flagged as skipped, then call Hooks.RunAll
with the preflight event constant and assert no error is returned and no
store/side-effect is invoked; reference the RunAll method on Hooks, the Hook
struct used in tests, and the preflight event constant (e.g. Preflight or
PreflightVerify) so the test ensures missing command for a skipped preflight
hook does not cause RunAll to fail.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/terraform/hooks_kinds.go`:
- Around line 8-11: The inline import comments for the blank imports `_
"github.com/cloudposse/atmos/pkg/hooks/kinds/checkov"`, `_
"github.com/cloudposse/atmos/pkg/hooks/kinds/infracost"`, `_
"github.com/cloudposse/atmos/pkg/hooks/kinds/kics"`, and `_
"github.com/cloudposse/atmos/pkg/hooks/kinds/trivy"` are missing trailing
periods and fail the godot linter; update each inline comment (`// kind:
checkov`, `// kind: infracost`, `// kind: kics`, `// kind: trivy`) to include a
trailing period (e.g., `// kind: checkov.`) so they comply with the comment
punctuation rule.

In `@docs/prd/custom-hooks.md`:
- Line 406: Update the inconsistent example paths in the documentation: replace
the incorrect reference to "examples/quick-start-advanced/" with the actual
examples directory pattern used in the implementation (e.g.,
"examples/hooks-checkov/", "examples/hooks-kics/", etc.) and ensure the
Verification section references the existing fixtures path
"tests/fixtures/scenarios/custom-hooks/"; update any mentions of "Six examples
under examples/hooks-*" to match the real examples names so all example paths
(examples/hooks-*) and verification fixtures
(tests/fixtures/scenarios/custom-hooks/) are consistent with the implementation.

In `@examples/hooks-checkov/README.md`:
- Around line 3-5: Update the README description to match the configured event:
change the hook event text from "before-terraform-plan" to
"after-terraform-plan" in the README.md so the README accurately reflects the
actual hook event used by the stack; ensure the phrase "a
`before-terraform-plan` hook" is replaced with "an `after-terraform-plan` hook".

In `@examples/hooks-custom-command/components/terraform/demo/main.tf`:
- Around line 1-3: Update the file header comment to remove the absolute claim
that "`tofu plan` completes without network access" and instead note that while
the random provider itself doesn't need cloud credentials, first-time provider
installation during `terraform init` or `tofu init` may require network access;
suggest running `init` beforehand or using a local plugin cache (e.g.,
plugin_cache_dir) to make subsequent `tofu plan` runs offline. Reference the
existing mention of the "random provider" and the command names `tofu plan` and
`init` when making this clarification.

In `@pkg/cacerts/cacerts_test.go`:
- Around line 43-53: The test stubs cachedPath but doesn't reset the
package-level findOnce, making Env() non-deterministic; save and restore the
original findOnce (e.g., savedOnce := findOnce), then set findOnce = sync.Once{}
(a fresh zeroed Once) before calling Env() so the test-controlled cachedPath is
honored, and use t.Cleanup to restore both cachedPath and findOnce after the
test (apply the same pattern to TestEnv_HasBundle and other Env tests).

In `@pkg/hooks/command_engine.go`:
- Around line 210-223: captureOutput currently dereferences ctx.Info when
building the Artifact metadata which can panic because validateCtx permits
ctx.Info == nil; update captureOutput (and the similar logic around lines
108-119) to guard that ctx.Info != nil before accessing ctx.Info.Stack or
ctx.Info.ComponentFromArg: only populate metadataKeyStack and
metadataKeyComponent (and any ctx.Info-derived metadata) when ctx.Info is
non-nil, otherwise omit those keys (still include Name/Body/Format), and ensure
the function handles a nil ctx.Info safely (e.g., build the Artifact.Metadata
map conditionally).
- Around line 334-354: resolveBinaryOnPath fails on Windows because
searchPathForBinary only checks exact filenames and exec.LookPath falls back to
the process PATH instead of the provided toolchainPATH; update
resolveBinaryOnPath so the binary lookup fully respects toolchainPATH by either
(a) enhancing searchPathForBinary to probe PATHEXT on Windows and not rely
solely on Unix execute bits (check for name + each PATHEXT and consider file
mode heuristics), or (b) replace the final fallback exec.LookPath call with a
LookPath-that-uses-searchPathOrProcessEnv(toolchainPATH) (i.e., perform
exec.LookPath semantics — including PATHEXT handling — against the PATH returned
by searchPathOrProcessEnv(toolchainPATH)) so resolution of names like "trivy"
finds "trivy.exe" in the toolchain PATH; adjust resolveBinaryOnPath to use that
new lookup function instead of the plain exec.LookPath.

In `@pkg/hooks/hooks.go`:
- Around line 114-124: The preflight verification currently checks every hook's
binary before the runtime skip filter is applied, causing --skip-hooks to still
fail on skipped hooks; update the flow so preflight only verifies hooks that
will run by applying the skip predicate (newSkipPredicate / skipPredicate)
before or inside h.preflight. Concretely, either change h.preflight to accept
the skipPredicate and have it skip verification for hooks where
skipPredicate.Matches(name) is true, or call newSkipPredicate and filter the
hook list using skipPredicate before invoking h.preflight; apply the same change
to the other preflight invocation region referenced (around the 280-307 logic)
so skipped hooks are excluded from preflight checks.
- Around line 320-347: The verifyCommandAvailable function incorrectly treats
any existing file as a valid command and manually scans toolchain PATH entries
without honoring platform executable rules (e.g., PATHEXT on Windows); update
the logic in verifyCommandAvailable to check executability (not just existence)
for file candidates from toolchainPATH and perform a PATH-style lookup that
applies PATHEXT when resolving names from the combined PATH variable instead of
naive os.Stat checks — reuse or call exec.LookPath (or implement equivalent
lookup that considers PATHEXT) for entries in combined, ensure candidates are
not directories and are executable (on Unix check file mode; on Windows apply
PATHEXT), and keep the final error return using errUtils.ErrCommandNotFound with
the command name.

In `@pkg/hooks/kinds/checkov/kind.go`:
- Around line 3-4: The package comment at the top of
pkg/hooks/kinds/checkov/kind.go still references `--output-file-path
$ATMOS_OUTPUT_FILE` but the code wires the flag to `$ATMOS_OUTPUT_DIR`; update
the docstring to reflect the actual flags and environment variable used (e.g.,
mention `-o sarif --output-dir $ATMOS_OUTPUT_DIR` or the exact flag form the
code constructs) so the comment matches the implementation in this file.

In `@pkg/hooks/kinds/infracost/parser.go`:
- Around line 60-63: Replace the ad-hoc wrapped errors returned after
os.ReadFile(ctx.OutputFile) and the subsequent parse failure with the repository
static errors from errors/errors.go: import the errors package and wrap the
original err using errors.Join with the appropriate static error (e.g.,
errors.ErrReadOutput for the read failure and errors.ErrParseOutput for the
parse/unmarshal failure), or combine a context fmt.Errorf("%s: %w", "infracost",
err) with errors.Join if you need contextual text; update the return statements
in the function that reads/parses the infracost output (the block that assigns
data, err from os.ReadFile and the parse/unmarshal block) to use those static
error variables so callers can reliably use errors.Is()/errors.Join().

In `@pkg/hooks/sarif/handler_test.go`:
- Line 67: Replace the hardcoded Unix path in the OutputPath closure with a
cross-platform tempdir-based missing file path: change the closure to return
filepath.Join(t.TempDir(), "missing.sarif") (ensure the test has access to the
testing.T variable `t` in scope and add an import for "path/filepath" if
missing). Update the OutputPath function reference in
pkg/hooks/sarif/handler_test.go accordingly so the test constructs the
non-existent path using t.TempDir() and filepath.Join instead of
"/nonexistent/path.sarif".

In `@pkg/hooks/sarif/handler.go`:
- Around line 32-35: The code calls opts.OutputPath(ctx) without checking that
the OutputPath function is non-nil, which can panic; add a nil check on
opts.OutputPath before invoking it (e.g., if opts == nil || opts.OutputPath ==
nil { return nil, nil }) and only call opts.OutputPath(ctx) after that check so
the handler returns safely when OutputPath is unset; update the logic around the
existing variable path and early return to use this guard.
- Around line 48-53: Replace the direct fmt.Errorf wrapping with the repo's
static error values from errors/errors.go so callers can detect failure types
via errors.Is(); specifically, in the read-SARIF and parse-SARIF error returns
(the lines that call fmt.Errorf("%s: read SARIF: %w", opts.Kind, err) and
fmt.Errorf("%s: parse SARIF: %w", opts.Kind, err)), wrap using the defined
static errors (for example errors.ErrRead or errors.ErrReadSARIF for the read
case and errors.ErrParse or errors.ErrParseSARIF for the parse case) instead of
the raw err (e.g. fmt.Errorf("%s: %w", opts.Kind, errors.ErrRead)). Import the
package that defines these static errors and keep the original error text if
desired as non-wrapped context (e.g. include err with %v) but ensure the static
error is the wrapped value so errors.Is() works.

In `@pkg/hooks/sarif/sarif.go`:
- Around line 210-212: In Parse (where json.Unmarshal error is returned) replace
the raw fmt.Errorf return with the repository’s static error wrapper from
errors/errors.go (e.g., errors.ErrInvalidSARIF) and wrap the original JSON error
using %w so errors.Is() can match; import the errors package and return the
wrapped static error (e.g., return nil, fmt.Errorf("%w: %v",
errors.ErrInvalidSARIF, err)) instead of the current fmt.Errorf("invalid SARIF
document: %w", err).

In `@pkg/toolchain/registry/atmos/builtin.go`:
- Around line 34-36: The YAML unmarshal error in
pkg/toolchain/registry/atmos/builtin.go (the yaml.Unmarshal(builtinYAML, &cfg)
error branch) must use the project's static error builder instead of fmt.Errorf;
replace the current return fmt.Errorf("failed to parse builtin atmos registry:
%w", err) with a wrapped static error using errUtils.Build(<appropriate static
error ID>).WithCause(err)... (follow the project's pattern) so the parse failure
is returned as the typed Atmos error; update the return to use the errUtils
builder chain that produces the final error instead of fmt.Errorf.

In `@website/src/data/roadmap.js`:
- Line 301: The roadmap milestone object with label "Custom hooks with built-in
kinds for cost and security scanners" is missing the required pr field; update
that object (the entry with label value exactly matching that string) to include
pr: <number> (e.g. pr: 1234) following the other fields so the milestone
includes the PR reference per guidelines.

---

Nitpick comments:
In `@docs/prd/custom-hooks.md`:
- Line 328: The comment on the Format field in the Hook struct is inconsistent
with the Schema section; update the documentation so the Format field is clearly
scoped to command hooks only: change the inline comment on the Format field
(Format string `json:"format,omitempty"`) to state "applies only when Kind ==
\"command\"" and/or update the Schema section to reflect that Format is only
valid for kind: command, ensuring both the Hook struct comment and Schema
section use the same wording.

In `@pkg/hooks/hooks_test.go`:
- Around line 158-385: Add a regression test in hooks_test.go that constructs a
Hooks containing a Hook configured for the preflight event (use the same Hook
struct as in existing tests) but with its command/binary field left empty and
flagged as skipped, then call Hooks.RunAll with the preflight event constant and
assert no error is returned and no store/side-effect is invoked; reference the
RunAll method on Hooks, the Hook struct used in tests, and the preflight event
constant (e.g. Preflight or PreflightVerify) so the test ensures missing command
for a skipped preflight hook does not cause RunAll to fail.

In `@pkg/hooks/kinds/infracost/parser.go`:
- Around line 200-203: The markdown table cells are written raw, so values like
r.name and r.rtype can contain '|' or newlines and break the table; add a small
helper (e.g., escapeMarkdownCell) that replaces pipe characters with '\|' and
converts newlines to a safe separator (space or '<br>'), then use that helper
when formatting the rows (replace r.name and r.rtype in the fmt.Fprintf call
with the escaped versions) so sb.WriteString/ fmt.Fprintf writes sanitized cell
content.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 048e6401-ad49-495c-b5e3-91a256ecd213

📥 Commits

Reviewing files that changed from the base of the PR and between eab5ad7 and 8bd1232.

📒 Files selected for processing (67)
  • cmd/terraform/hooks_kinds.go
  • docs/prd/custom-hooks.md
  • docs/prd/tool-dependencies-integration.md
  • examples/hooks-checkov/README.md
  • examples/hooks-checkov/atmos.yaml
  • examples/hooks-checkov/components/terraform/bucket/main.tf
  • examples/hooks-checkov/components/terraform/bucket/variables.tf
  • examples/hooks-checkov/components/terraform/bucket/versions.tf
  • examples/hooks-checkov/stacks/deploy/test.yaml
  • examples/hooks-custom-command/README.md
  • examples/hooks-custom-command/atmos.yaml
  • examples/hooks-custom-command/components/terraform/demo/main.tf
  • examples/hooks-custom-command/components/terraform/demo/variables.tf
  • examples/hooks-custom-command/components/terraform/demo/versions.tf
  • examples/hooks-custom-command/scripts/notify.py
  • examples/hooks-custom-command/stacks/deploy/test.yaml
  • examples/hooks-infracost/README.md
  • examples/hooks-infracost/atmos.yaml
  • examples/hooks-infracost/components/terraform/nat-gateway/main.tf
  • examples/hooks-infracost/components/terraform/nat-gateway/variables.tf
  • examples/hooks-infracost/components/terraform/nat-gateway/versions.tf
  • examples/hooks-infracost/stacks/deploy/test.yaml
  • examples/hooks-kics/README.md
  • examples/hooks-kics/atmos.yaml
  • examples/hooks-kics/components/terraform/bucket/main.tf
  • examples/hooks-kics/components/terraform/bucket/variables.tf
  • examples/hooks-kics/components/terraform/bucket/versions.tf
  • examples/hooks-kics/stacks/deploy/test.yaml
  • examples/hooks-trivy/README.md
  • examples/hooks-trivy/atmos.yaml
  • examples/hooks-trivy/components/terraform/bucket/main.tf
  • examples/hooks-trivy/components/terraform/bucket/variables.tf
  • examples/hooks-trivy/components/terraform/bucket/versions.tf
  • examples/hooks-trivy/stacks/deploy/test.yaml
  • pkg/cacerts/cacerts.go
  • pkg/cacerts/cacerts_test.go
  • pkg/flags/global/flags.go
  • pkg/flags/global_builder.go
  • pkg/hooks/command_engine.go
  • pkg/hooks/command_engine_test.go
  • pkg/hooks/hook.go
  • pkg/hooks/hooks.go
  • pkg/hooks/hooks_test.go
  • pkg/hooks/kind.go
  • pkg/hooks/kind_test.go
  • pkg/hooks/kinds/checkov/kind.go
  • pkg/hooks/kinds/infracost/kind.go
  • pkg/hooks/kinds/infracost/parser.go
  • pkg/hooks/kinds/infracost/parser_test.go
  • pkg/hooks/kinds/kics/kind.go
  • pkg/hooks/kinds/trivy/kind.go
  • pkg/hooks/main_test.go
  • pkg/hooks/sarif/handler.go
  • pkg/hooks/sarif/handler_test.go
  • pkg/hooks/sarif/markdown.go
  • pkg/hooks/sarif/sarif.go
  • pkg/hooks/sarif/sarif_test.go
  • pkg/hooks/skip_test.go
  • pkg/hooks/store_cmd.go
  • pkg/toolchain/registry/atmos/atmos.go
  • pkg/toolchain/registry/atmos/builtin.go
  • pkg/toolchain/registry/atmos/builtin.yaml
  • pkg/toolchain/registry/loader.go
  • website/blog/2026-05-22-custom-hooks.mdx
  • website/docs/cli/global-flags.mdx
  • website/docs/stacks/hooks.mdx
  • website/src/data/roadmap.js

Comment thread cmd/terraform/hooks_kinds.go Resolved
Comment thread docs/prd/custom-hooks.md Resolved
Comment thread examples/hooks-checkov/README.md Resolved
Comment thread pkg/cacerts/cacerts_test.go Resolved
Comment thread pkg/hooks/sarif/handler.go Resolved
Comment thread pkg/hooks/sarif/handler.go Resolved
Comment thread pkg/hooks/sarif/sarif.go Resolved
Comment thread pkg/toolchain/registry/atmos/builtin.go Resolved
Comment thread website/src/data/roadmap.js Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pkg/hooks/hooks_test.go`:
- Around line 389-390: The test sets viper key "skip-hooks" directly and resets
it to "" which can leak state; capture the previous value before calling
viper.Set("skip-hooks", "missing-tool") and in the t.Cleanup callback restore
that saved value (i.e., call viper.Set("skip-hooks", previous) rather than
viper.Set("skip-hooks", "")). Update the cleanup closure around the viper.Set
usage in this test so it restores the original value saved in a local variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9fa57897-5353-45f9-bc31-e5196bd5dc02

📥 Commits

Reviewing files that changed from the base of the PR and between 8bd1232 and 5f84acb.

📒 Files selected for processing (19)
  • cmd/terraform/hooks_kinds.go
  • docs/prd/custom-hooks.md
  • examples/hooks-checkov/README.md
  • examples/hooks-custom-command/components/terraform/demo/main.tf
  • pkg/cacerts/cacerts.go
  • pkg/cacerts/cacerts_test.go
  • pkg/hooks/command_engine.go
  • pkg/hooks/command_engine_test.go
  • pkg/hooks/hooks.go
  • pkg/hooks/hooks_test.go
  • pkg/hooks/kinds/checkov/kind.go
  • pkg/hooks/kinds/infracost/parser.go
  • pkg/hooks/kinds/infracost/parser_test.go
  • pkg/hooks/sarif/handler.go
  • pkg/hooks/sarif/handler_test.go
  • pkg/hooks/sarif/sarif.go
  • pkg/hooks/sarif/sarif_test.go
  • pkg/toolchain/registry/atmos/builtin.go
  • website/src/data/roadmap.js
✅ Files skipped from review due to trivial changes (3)
  • website/src/data/roadmap.js
  • examples/hooks-checkov/README.md
  • pkg/hooks/command_engine_test.go

Comment thread pkg/hooks/hooks_test.go Resolved
Pre-commit was failing on the merge ref for PR #2482 because three commits
recently merged to main (#2348, #2478, #2481) contain files that were not
gofumpt-formatted and a couple of native-ci test fixtures with trailing
whitespace from captured terraform output.

These files are not touched by this PR, but they appear in the PR's
GitHub-generated merge ref diff and so pre-commit checks them. Apply the
auto-fixes that pre-commit produces:

- cmd/terraform/output.go: group two consecutive var decls.
- internal/exec/terraform_output_getter_test.go: line-break in
  assert.PanicsWithValue calls (2x).
- pkg/terraform/output/executor_test.go: line-break in NewExecutor call.
- pkg/terraform/output/get_test.go: line-break in assert.PanicsWithValue
  calls (3x).
- tests/fixtures/scenarios/native-ci/github-output.txt: trim trailing
  whitespace.
- tests/fixtures/scenarios/native-ci/github-step-summary.txt: trim
  trailing whitespace.

The fixture files are runtime outputs set via GITHUB_OUTPUT and
GITHUB_STEP_SUMMARY env vars during the native-ci test scenarios and are
only checked via file_contains substring assertions, so trimming trailing
whitespace is safe.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The new --skip-hooks global flag added in pkg/flags/global_builder.go
appears in every command's --help output. Regenerated the 39 affected
golden snapshots so TestCLICommands passes on Linux, macOS, and Windows.

Also includes:
- pkg/hooks/hooks_test.go: save and restore prior viper "skip-hooks"
  value in TestRunAll_SkipHooksBypassesPreflightBinaryCheck to avoid
  cross-test viper leakage.
- website/src/data/roadmap.js: minor copy edit to custom-hooks milestone.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
coderabbitai[bot]
coderabbitai Bot previously approved these changes May 23, 2026
@mergify

mergify Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

Important

Cloud Posse Engineering Team Review Required

This pull request modifies files that require Cloud Posse's review. Please be patient, and a core maintainer will review your changes.

To expedite this process, reach out to us on Slack in the #pr-reviews channel.

@osterman Erik Osterman (Cloud Posse) (osterman) changed the title feat(hooks): kind system + scanner kinds + auto-install + --skip-hooks feat(hooks): add hook kinds, scanner integrations, SARIF summaries, and skip controls May 23, 2026
@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.41530% with 130 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.40%. Comparing base (38620de) to head (256b4c4).

Files with missing lines Patch % Lines
pkg/hooks/hooks.go 71.73% 32 Missing and 7 partials ⚠️
pkg/hooks/command_engine.go 87.30% 20 Missing and 13 partials ⚠️
pkg/hooks/kinds/infracost/parser.go 89.18% 9 Missing and 3 partials ⚠️
pkg/hooks/sarif/markdown.go 84.72% 6 Missing and 5 partials ⚠️
pkg/hooks/sarif/handler.go 86.48% 8 Missing and 2 partials ⚠️
pkg/toolchain/registry/atmos/builtin.go 44.44% 4 Missing and 1 partial ⚠️
pkg/hooks/store_cmd.go 66.66% 2 Missing and 2 partials ⚠️
pkg/hooks/sarif/sarif.go 98.21% 2 Missing and 1 partial ⚠️
pkg/hooks/hook.go 80.00% 1 Missing and 1 partial ⚠️
pkg/hooks/kinds/checkov/kind.go 90.90% 2 Missing ⚠️
... and 5 more
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2482      +/-   ##
==========================================
+ Coverage   78.30%   78.40%   +0.10%     
==========================================
  Files        1121     1133      +12     
  Lines      106770   107784    +1014     
==========================================
+ Hits        83609    84513     +904     
- Misses      18496    18567      +71     
- Partials     4665     4704      +39     
Flag Coverage Δ
unittests 78.40% <87.41%> (+0.10%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
cmd/terraform/output.go 54.92% <ø> (ø)
pkg/flags/global/flags.go 100.00% <ø> (ø)
pkg/flags/global_builder.go 100.00% <100.00%> (ø)
pkg/hooks/kind.go 100.00% <100.00%> (ø)
pkg/toolchain/registry/atmos/atmos.go 88.26% <100.00%> (+1.12%) ⬆️
pkg/cacerts/cacerts.go 95.23% <95.23%> (ø)
pkg/hooks/hook.go 88.88% <80.00%> (-11.12%) ⬇️
pkg/hooks/kinds/checkov/kind.go 90.90% <90.90%> (ø)
pkg/hooks/kinds/infracost/kind.go 87.50% <87.50%> (ø)
pkg/hooks/kinds/kics/kind.go 90.47% <90.47%> (ø)
... and 10 more

... and 9 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/test.yml:
- Around line 68-69: Add the missing "persist-credentials: false" configuration
to every checkout step that uses actions/checkout@v6 so credentials are not
persisted; locate each occurrences of the checkout step (uses:
actions/checkout@v6) and add a with: block containing persist-credentials: false
for each job where it appears (~68-69, ~119-120, ~259-260, ~324-325, ~365-366,
~451-452, ~563-564, ~615-616) to ensure the runner does not retain Git
credentials beyond the step.
- Line 54: Pin mutable GitHub Actions refs to immutable commit SHAs and disable
persisted credentials for checkout steps: replace uses: runs-on/action@v2 and
any uses: actions/checkout@v6 entries with the corresponding full commit SHA for
the exact release you want, and update all actions/checkout steps to include
with: persist-credentials: false so the GITHUB_TOKEN is not left available to
subsequent steps; ensure you update every occurrence (e.g., the runs-on/action
and actions/checkout uses) to SHAs and keep descriptive comments if needed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9439a3ab-082e-4412-8e85-fa213b8b05ad

📥 Commits

Reviewing files that changed from the base of the PR and between f75ab82 and 65fb8a7.

📒 Files selected for processing (2)
  • .github/workflows/test.yml
  • pkg/hooks/hooks_test.go

Comment thread .github/workflows/test.yml Resolved
Comment thread .github/workflows/test.yml Resolved
coderabbitai[bot]
coderabbitai Bot previously approved these changes May 24, 2026
…reamble

The per-kind sections list "(default)" values without indicating they're
customizable. Add a one-paragraph preamble under "Built-in Kinds" that
tells readers every default is overridable and points to the override
rules section before they read any individual kind.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ActionCard

Swap the four GitHub example URLs in the custom-hooks changelog post to
the website's /examples/<name> routes (already published by the
file-browser plugin), matching the change in website/docs/stacks/hooks.mdx.

Append an ActionCard at the bottom pointing readers from the changelog
narrative to /stacks/hooks for the full reference (kinds, override
semantics, lifecycle events, tool auto-install, --all / --skip-hooks).

The remaining github.com URL in the "Try it" section stays — git clone
needs the GitHub URL.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ctly

Add an "Override any default" h3 between the built-in-kinds and
bring-your-own-command sections, matching the chapter style of
"Workdir compatible". The new chapter shows that command, args, env,
and on_failure are all overridable on built-in kinds, with a worked
example (Trivy with HIGH,CRITICAL severity and on_failure: fail) and a
call-out that args/env are full replacement, not merge — linking to the
override docs at /stacks/hooks#overriding-kind-defaults.

Fix the closing ActionCard so the CTA buttons actually render. The
component reads ctaText/ctaLink and secondaryCtaText/secondaryCtaLink,
not href. The card now renders a primary "Read the docs" CTA to
/stacks/hooks and a secondary "Browse examples" CTA to
/examples/hooks-trivy.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@zack-is-cool

Copy link
Copy Markdown
Contributor

Erik Osterman (Cloud Posse) (@osterman) This is interesting, we'd be able to run the hooks ad-hoc if possible, say in CI if I just wanted to do trivy scans.

How do you see these being called differently?

@aknysh
Andriy Knysh (aknysh) merged commit df2c7bd into main May 25, 2026
61 of 63 checks passed
@aknysh
Andriy Knysh (aknysh) deleted the osterman/component-hooks-tfsec-sarif branch May 25, 2026 00:11
@atmos-pro

atmos-pro Bot commented May 25, 2026

Copy link
Copy Markdown
Contributor

Note

Atmos Pro  

Waiting for your GitHub Actions workflow to upload affected stacks.
Learn More.

@mergify mergify Bot removed the needs-cloudposse Needs Cloud Posse assistance label May 25, 2026
@github-actions

Copy link
Copy Markdown

Warning

Release Documentation Required

This PR is labeled minor or major and requires documentation updates:

  • Changelog entry - Add a blog post in website/blog/YYYY-MM-DD-feature-name.mdx
  • Roadmap update - Update website/src/data/roadmap.js with the new milestone

Alternatively: If this change doesn't require release documentation, remove the minor or major label.

@github-actions

Copy link
Copy Markdown

These changes were released in v1.220.0-rc.2.

Erik Osterman (Cloud Posse) (osterman) added a commit that referenced this pull request Jun 5, 2026
- duration.IsZeroTTL now trims whitespace before zero-value matching, so
  " 0s " is recognized as a zero TTL (consistent with Parse/ParseDuration).
  Add TestIsZeroTTL (with whitespace regression cases) and TestIsExpired.
- roadmap: the "Custom hooks with built-in kinds" milestone (#2482) was
  fully shipped (merged df2c7bd, changelog custom-hooks) but still marked
  in-progress; flip it to shipped. Extensibility progress recomputed to
  26 shipped / 30 total = 87 (was an inaccurate 83).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Andriy Knysh (aknysh) added a commit that referenced this pull request Jun 6, 2026
…2571)

* feat(imports): cache remote stack-import clones (dedup + opt-in TTL)

Clone each remote (git) stack-import source repo at most once per Atmos
invocation instead of once per import, and add an opt-in `ttl` to reuse
the clone across runs (so a warm CI cache can skip the re-clone).

- Wire the default git-subdir resolve path through ensureSourceDir so all
  subdir imports of the same repo share a single clone (within-run dedup,
  spanning both describe-affected passes via the global importer).
- Add per-session fetch tracking + TTL-based cross-run freshness to
  ensureSourceDir; persist UpdatedAt in the .atmos-source-ready marker.
  No ttl = refresh once per run, so mutable refs (?ref=main) stay fresh.
- Expose `ttl` per-import (StackImport.TTL) and as a global imports.ttl
  default; thread it through ResolveRemoteImportNested.
- Extract shared duration.IsExpired/IsZeroTTL; source provisioner now
  delegates to them.
- Update JSON schemas, add tests, docs, changelog post, and roadmap.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(imports): address CodeRabbit review on remote-import caching

- duration.IsZeroTTL now trims whitespace before zero-value matching, so
  " 0s " is recognized as a zero TTL (consistent with Parse/ParseDuration).
  Add TestIsZeroTTL (with whitespace regression cases) and TestIsExpired.
- roadmap: the "Custom hooks with built-in kinds" milestone (#2482) was
  fully shipped (merged df2c7bd, changelog custom-hooks) but still marked
  in-progress; flip it to shipped. Extensibility progress recomputed to
  26 shipped / 30 total = 87 (was an inaccurate 83).

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* docs(imports): call out that remote imports don't bring component code

Add a warning admonition to the Remote Imports docs: a remote stack
import resolves configuration only, not the referenced component's
Terraform/Helmfile root module. describe/list/validate work, but
plan/apply fails with "component not found" unless the component is
materialized via `source:` (JIT source provisioning) or `atmos vendor pull`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(imports): regenerate describe-config snapshots for new imports section

The new global `imports` config section renders as `"imports": {}` in
`atmos describe config` JSON output (encoding/json does not honor omitempty
for empty structs, unlike yaml.v3). Regenerate the two affected golden
snapshots so Acceptance Tests pass on all platforms.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* test(imports): cover ResolveRemoteImportNested and readSourceMetadata

Add tests for the clone-caching paths that were uncovered:
- ResolveRemoteImportNested public wrapper, exercised through the global
  importer with a mock downloader (consuming globalImporterOnce so the
  injected importer is not overwritten), including within-run source dedup.
- readSourceMetadata error/validation paths: missing marker, malformed
  JSON, legacy marker without a timestamp, and a valid marker.

Raises pkg/stack/imports coverage 93.3% -> 94.7% (readSourceMetadata to
100%, ResolveRemoteImportNested 0% -> 80%).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: aknysh <[email protected]>

This branch was successfully deployed

1 active deployment
preview — 256b4c4c Deployed May 24, 2026 by github-actions[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

minor New features that do not break anything size/xl Extra large size PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants