chore: publish IntegraCI build modules 732ec6c83925
This commit is contained in:
1 parent
7a84930dea
commit
5f8a24d014
133 files changed
+18990
-2
No files matched your search
@@ -0,0 +1,71 @@
|
||||
# iac-scan
|
||||
|
||||
> **UNVERIFIED SCAFFOLD** — run `dagger develop` + `dagger functions` + test
|
||||
> against a matching Dagger engine (engineVersion `v0.21.7`) before use. The
|
||||
> Go in `main.go` has NOT been compiled or validated by Dagger codegen in
|
||||
> this environment (`dagger develop` is unavailable, and the `dag` global
|
||||
> plus the `*Directory` / `*Container` / `*Secret` / `*File` types are
|
||||
> generated). Do not assume it works as-is.
|
||||
|
||||
IntegraCI IaC (Infrastructure-as-Code) security scanning Dagger module. Runs
|
||||
[Trivy](https://trivy.dev/) (`trivy config`) — or optionally
|
||||
[Checkov](https://www.checkov.io/) — over a source directory containing
|
||||
Terraform / Helm / Dockerfile / Kubernetes manifests, counts
|
||||
misconfigurations by severity, and optionally POSTs the result to the
|
||||
IntegraCI API.
|
||||
|
||||
It mirrors the structure and idioms of the sibling `sast-scan` module.
|
||||
|
||||
## Functions
|
||||
|
||||
### `scan`
|
||||
|
||||
Runs an IaC misconfiguration scan and returns a `ScanResult`.
|
||||
|
||||
| Param | Required | Default | Description |
|
||||
| ------------ | -------- | --------- | ------------------------------------------------- |
|
||||
| `source` | yes | — | Source directory to scan (Terraform/Helm/K8s/…) |
|
||||
| `tool` | no | `trivy` | IaC tool: `trivy` \| `checkov` \| `none` |
|
||||
| `api-url` | no | — | IntegraCI API URL for posting results |
|
||||
| `token` | no | — | JWT token for API authentication |
|
||||
| `service-id` | no | — | Service ID to link scan results |
|
||||
| `version` | no | — | Commit SHA / image tag the scan applies to |
|
||||
|
||||
When `tool=none`, the scan is skipped and a result with `skipped=true` is
|
||||
returned. Results are POSTed to the generic scan-ingest endpoint
|
||||
(`POST /api/v1/scans`, `scan_type="iac"`) only when both `api-url` and
|
||||
`token` are set. The per-severity counts populate the typed columns; the
|
||||
`iac_critical` / `iac_high` counters are mirrored into `report_data`, which is
|
||||
where the deploy OPA gate reads them (`golden_standard.rego`
|
||||
`scan_results.iac_critical` / `iac_high`).
|
||||
|
||||
## Usage
|
||||
|
||||
> These commands are illustrative and have NOT been run here. Verify against
|
||||
> a live Dagger engine first.
|
||||
|
||||
```sh
|
||||
# Scan and post results to the IntegraCI API
|
||||
dagger call scan \
|
||||
--source . \
|
||||
--api-url http://localhost:8000 \
|
||||
--token "$TOKEN" \
|
||||
--service-id "$SVC_ID"
|
||||
|
||||
# Scan with Checkov instead of Trivy
|
||||
dagger call scan --source . --tool checkov
|
||||
|
||||
# Scan only (no API post)
|
||||
dagger call scan --source .
|
||||
|
||||
# Skip scanning
|
||||
dagger call scan --source . --tool none
|
||||
```
|
||||
|
||||
## Verifying the scaffold
|
||||
|
||||
```sh
|
||||
dagger develop # generate the SDK + codegen
|
||||
dagger functions # confirm the 'scan' function is exposed
|
||||
gofmt -l main.go # confirm formatting (should print nothing)
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"name": "iac-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
// Package main implements the IntegraCI iac-scan Dagger module.
|
||||
//
|
||||
// Runs Infrastructure-as-Code (IaC) security scanning over a source directory
|
||||
// (Terraform / Helm / Dockerfile / Kubernetes manifests), counts
|
||||
// misconfigurations by severity, and optionally POSTs the result to the
|
||||
// IntegraCI API. Engine-agnostic: callable from any CI engine via
|
||||
// `dagger call`.
|
||||
//
|
||||
// Supported tools (each runs the vendor's canonical CLI inside its official
|
||||
// container image):
|
||||
//
|
||||
// trivy aquasec/trivy trivy config --format json .
|
||||
// checkov bridgecrew/checkov checkov -d . -o json
|
||||
// none no-op skip
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// dagger call scan --source . --api-url http://localhost:8000 --token env:TOKEN --service-id $SVC_ID
|
||||
// dagger call scan --source . --tool checkov
|
||||
// dagger call scan --source . --tool none
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/iac-scan/internal/dagger"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// IacScan is the IntegraCI Infrastructure-as-Code scanning module.
|
||||
type IacScan struct{}
|
||||
|
||||
// ScanResult contains the output of an IaC scan.
|
||||
type ScanResult struct {
|
||||
Tool string `json:"tool"`
|
||||
Findings int `json:"findings"`
|
||||
Critical int `json:"critical"`
|
||||
High int `json:"high"`
|
||||
Medium int `json:"medium"`
|
||||
Low int `json:"low"`
|
||||
Report string `json:"report,omitempty"`
|
||||
Skipped bool `json:"skipped"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
// Scan runs an IaC misconfiguration pass over the source directory with the
|
||||
// selected tool, counts findings by severity, and optionally POSTs the result
|
||||
// to the IntegraCI API. Mirrors sast-scan.Scan's reporting contract.
|
||||
func (m *IacScan) Scan(
|
||||
ctx context.Context,
|
||||
// Source directory to scan (Terraform / Helm / Dockerfile / K8s manifests)
|
||||
source *dagger.Directory,
|
||||
// IaC tool: trivy | checkov | none
|
||||
// +optional
|
||||
// +default="trivy"
|
||||
tool string,
|
||||
// IntegraCI API URL for posting results
|
||||
// +optional
|
||||
apiURL string,
|
||||
// JWT token for API authentication
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
// Service ID to link scan results
|
||||
// +optional
|
||||
serviceID string,
|
||||
// Version (commit SHA / image tag) the scan applies to
|
||||
// +optional
|
||||
version string,
|
||||
) (*ScanResult, error) {
|
||||
result := &ScanResult{Tool: tool}
|
||||
|
||||
var (
|
||||
report string
|
||||
err error
|
||||
)
|
||||
|
||||
switch strings.ToLower(tool) {
|
||||
case "none":
|
||||
result.Skipped = true
|
||||
result.Success = true
|
||||
return result, nil
|
||||
case "trivy":
|
||||
report, err = m.runTrivyConfig(ctx, source)
|
||||
case "checkov":
|
||||
report, err = m.runCheckov(ctx, source)
|
||||
default:
|
||||
return nil, fmt.Errorf(
|
||||
"unsupported iac tool %q (expected one of: trivy, checkov, none)",
|
||||
tool,
|
||||
)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s iac scan failed: %w", tool, err)
|
||||
}
|
||||
|
||||
result.Report = report
|
||||
result.Critical = countSeverity(report, "CRITICAL")
|
||||
result.High = countSeverity(report, "HIGH")
|
||||
result.Medium = countSeverity(report, "MEDIUM")
|
||||
result.Low = countSeverity(report, "LOW")
|
||||
result.Findings = result.Critical + result.High + result.Medium + result.Low
|
||||
|
||||
// POST results to the IntegraCI API when configured. Skipped silently
|
||||
// when apiURL or token is empty so local runs still work.
|
||||
if apiURL != "" && token != nil {
|
||||
if err := m.postResults(ctx, apiURL, token, serviceID, version, result); err != nil {
|
||||
return nil, fmt.Errorf("posting results to API failed: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// runTrivyConfig runs "trivy config" over the source directory in JSON mode.
|
||||
// Trivy exits non-zero when misconfigurations are present; we force
|
||||
// --exit-code 0 and read the JSON report rather than relying on the exit code.
|
||||
func (m *IacScan) runTrivyConfig(ctx context.Context, source *dagger.Directory) (string, error) {
|
||||
const reportPath = "/tmp/iac-report.json"
|
||||
report, err := dag.Container().
|
||||
From("aquasec/trivy:0.58.1").
|
||||
// Persist Trivy's misconfig/policy DB across runs (avoids re-downloading it).
|
||||
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{
|
||||
"trivy", "config",
|
||||
"--format", "json",
|
||||
"--output", reportPath,
|
||||
"--exit-code", "0",
|
||||
".",
|
||||
}).
|
||||
File(reportPath).
|
||||
Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read trivy config JSON output: %w", err)
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
// runCheckov runs Checkov over the source directory in JSON mode. Checkov
|
||||
// exits non-zero when failed checks are present, so we tolerate the exit code
|
||||
// and read the JSON emitted on stdout.
|
||||
func (m *IacScan) runCheckov(ctx context.Context, source *dagger.Directory) (string, error) {
|
||||
c := dag.Container().
|
||||
From("bridgecrew/checkov:3.2.334").
|
||||
WithMountedDirectory("/src", source).
|
||||
WithWorkdir("/src").
|
||||
WithExec([]string{"sh", "-c", "checkov -d . -o json --compact || true"})
|
||||
return c.Stdout(ctx)
|
||||
}
|
||||
|
||||
// countSeverity tallies findings of a given severity level from an IaC scan
|
||||
// report. Both Trivy (`"Severity": "HIGH"`) and Checkov (`"severity": "HIGH"`)
|
||||
// emit uppercase severity strings under a severity key; we count occurrences
|
||||
// of that key/value pair, tolerant of the optional space after the colon.
|
||||
// Zero-dep, matching the license-scan / sast-scan substring approach.
|
||||
func countSeverity(report, level string) int {
|
||||
total := 0
|
||||
for _, key := range []string{`"Severity"`, `"severity"`} {
|
||||
for _, sep := range []string{":", ": "} {
|
||||
total += strings.Count(report, key+sep+`"`+level+`"`)
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
// postResults sends the IaC scan result to the IntegraCI generic scan-ingest
|
||||
// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: the
|
||||
// per-severity misconfig counts populate the typed columns, and the
|
||||
// iac_critical / iac_high counters are mirrored into report_data (the fields
|
||||
// the deploy OPA gate reads — see deploy_policy_gate.py _build_scan_results).
|
||||
func (m *IacScan) postResults(
|
||||
ctx context.Context,
|
||||
apiURL string,
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
version string,
|
||||
result *ScanResult,
|
||||
) error {
|
||||
payload := map[string]any{
|
||||
"service_id": serviceID,
|
||||
"version": version,
|
||||
"scan_type": "iac",
|
||||
"scanner": result.Tool,
|
||||
"report_format": "json",
|
||||
"findings_count": result.Findings,
|
||||
"critical_count": result.Critical,
|
||||
"high_count": result.High,
|
||||
"medium_count": result.Medium,
|
||||
"low_count": result.Low,
|
||||
"report_data": map[string]any{
|
||||
"iac_critical": result.Critical,
|
||||
"iac_high": result.High,
|
||||
},
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal scan payload: %w", err)
|
||||
}
|
||||
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("API post to %s failed: %w", endpoint, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user