chore: publish IntegraCI build modules a11ec75d3e09

This commit is contained in:
dhimaz0445 committed 2026-11-11 03:41:55 +00:00
1 parent 694710104a
commit 3c2b80914e
78 files changed
+4982 -405

No files matched your search

+301 -63
View File
@@ -44,18 +44,28 @@ type SecurityScan struct{}
// ScanResult contains the output of a security scan.
type ScanResult struct {
TrivyFindings int `json:"trivy_findings"`
GitleaksFindings int `json:"gitleaks_findings"`
LicenseFindings int `json:"license_findings"`
ForbiddenFound int `json:"forbidden_found"`
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
SecretCount int `json:"secret_count"`
IacCritical int `json:"iac_critical"`
IacHigh int `json:"iac_high"`
SarifPath string `json:"sarif_path,omitempty"`
Success bool `json:"success"`
TrivyFindings int `json:"trivy_findings"`
GitleaksFindings int `json:"gitleaks_findings"`
LicenseFindings int `json:"license_findings"`
ForbiddenFound int `json:"forbidden_found"`
Critical int `json:"critical"`
High int `json:"high"`
Medium int `json:"medium"`
SecretCount int `json:"secret_count"`
IacCritical int `json:"iac_critical"`
IacHigh int `json:"iac_high"`
// IacScanned is true only when the IaC misconfig scan RAN. The zeros in
// iac_critical/iac_high are posted either way, so the security verdict
// (ADR-0093) reads this flag to tell "nothing found" from "not scanned".
IacScanned bool `json:"iac_scanned"`
// Suppression files the scan of record removed from the scanned copy
// (ADR-0093 §4). Empty for every other scan.
IgnoredSuppressions []string `json:"ignored_suppressions,omitempty"`
SarifPath string `json:"sarif_path,omitempty"`
// Trivy's VulnerabilityDB.UpdatedAt for an image scan (vulndb.go); empty
// when Trivy reported none.
VulnDBUpdatedAt string `json:"vuln_db_updated_at,omitempty"`
Success bool `json:"success"`
}
// LicenseReport summarises Trivy's license scan output.
@@ -95,12 +105,25 @@ func (m *SecurityScan) Scan(
// +optional
// +default="none"
cis string,
// The analysis job of record (ADR-0093 §4, WP-05): suppression files the
// repository ships are removed from the scanned copy, gitleaks ignores
// `gitleaks:allow`, and what was ignored is posted as information. Off for
// every other caller, so branch and pull request jobs scan as before.
// +optional
scanOfRecord bool,
) (*ScanResult, error) {
result := &ScanResult{}
source = withoutCITooling(source)
if scanOfRecord {
var err error
source, result.IgnoredSuppressions, err = withoutSuppression(ctx, source)
if err != nil {
return nil, err
}
}
// Run Trivy filesystem scan
critical, high, medium, err := m.runTrivy(ctx, source)
critical, high, medium, err := m.runTrivy(ctx, source, scanOfRecord)
if err != nil {
return nil, fmt.Errorf("trivy scan failed: %w", err)
}
@@ -110,7 +133,7 @@ func (m *SecurityScan) Scan(
result.TrivyFindings = critical + high + medium
// Run Gitleaks secret detection
secretCount, err := m.runGitleaks(ctx, source)
secretCount, err := m.runGitleaks(ctx, source, scanOfRecord)
if err != nil {
return nil, fmt.Errorf("gitleaks failed: %w", err)
}
@@ -121,14 +144,18 @@ func (m *SecurityScan) Scan(
// insecure Dockerfiles / k8s manifests / Terraform (open ports, missing
// encryption, privileged containers, ...). Counts land in report_data as
// iac_critical/iac_high, which the deploy OPA gate reads. When disabled
// they stay 0 — identical to the pre-existing payload, so no flag day.
// they stay 0 — identical to the pre-existing payload, so no flag day —
// and iac_scanned stays false, so the security verdict (ADR-0093) reads
// those zeros as "not scanned", never as "nothing found".
if iacScan != "" && iacScan != "none" {
iacCritical, iacHigh, err := m.runTrivyConfig(ctx, source)
iacCritical, iacHigh, inline, err := m.runTrivyConfig(ctx, source, scanOfRecord)
if err != nil {
return nil, fmt.Errorf("trivy config (iac misconfig) scan failed: %w", err)
}
result.IgnoredSuppressions = append(result.IgnoredSuppressions, inline...)
result.IacCritical = iacCritical
result.IacHigh = iacHigh
result.IacScanned = true
}
// Optional CIS Benchmark / hardening scan (opt-in). Trivy's docker-cis
@@ -202,17 +229,92 @@ func (m *SecurityScan) ImageScan(
}
args = append(args, imageRef)
ctr := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db"))
if registryUsername != "" && registryPassword != nil {
ctr = ctr.
WithEnvVariable("TRIVY_USERNAME", registryUsername).
WithSecretVariable("TRIVY_PASSWORD", registryPassword)
}
report, err := ctr.WithExec(args).File(reportPath).Contents(ctx)
scanned := ctr.WithExec(args)
report, err := scanned.File(reportPath).Contents(ctx)
if err != nil {
return nil, fmt.Errorf("trivy image scan of %s failed: %w", imageRef, err)
}
// The age of the DB that scan used, read from the same cache with no
// network call (ADR-0093 §8). A failure here is not a scan failure: the
// platform treats a missing date as `cve = unknown`.
versionJSON, _ := scanned.WithExec([]string{"trivy", "version", "--format", "json"}).Stdout(ctx)
critical, high, medium := countTrivySeverities(report)
result := &ScanResult{
Critical: critical,
High: high,
Medium: medium,
TrivyFindings: critical + high + medium,
SecretCount: len(ruleIDPattern.FindAllStringIndex(report, -1)),
VulnDBUpdatedAt: vulnDBUpdatedAt(versionJSON),
}
if apiURL != "" && token != nil {
if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", imageRef, result); err != nil {
return nil, fmt.Errorf("posting image scan to API failed: %w", err)
}
}
result.Success = true
return result, nil
}
// ArchiveScan scans the image the build wrote as an OCI ARCHIVE, before
// anything is pushed (ADR-0093 §5 step 2, scan before push), and posts the
// counts as scanner "trivy-image" -- the same row ImageScan posts after a
// push, so the deploy gate and the security verdict read one scanner either
// way. The archive's manifest digest rides in report_data.image_ref as
// `archive:sha256:<hex>`, for the record only: the verdict does NOT match on
// it (a caller-chosen digest is never identity, WP-01 review); it reads the
// scan by --version, the tag the archive was built as.
//
// No registry, no credential: the layout is read from the directory the build
// exported. Same scanners and severities as ImageScan.
func (m *SecurityScan) ArchiveScan(
ctx context.Context,
// The OCI image layout `standard-build build --archive` exported
layout *dagger.Directory,
// The archive's manifest digest (standard-build `archive-digest`)
archiveDigest string,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// The tag the archive was built as
// +optional
version string,
) (*ScanResult, error) {
if !archiveDigestRE.MatchString(archiveDigest) {
return nil, fmt.Errorf("archive-scan: --archive-digest %q is not sha256", archiveDigest)
}
const reportPath = "/tmp/trivy-image.json"
ctr := dag.Container().
From("aquasec/trivy:0.76.1").
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/layout", layout).
// trivy reads an OCI archive (tar of the layout) with --input; the
// working directory is empty, so no trivy.yaml / .trivyignore from the
// checkout can change what it reports (ADR-0093 §4, condition 3).
WithWorkdir("/work").
WithExec([]string{"sh", "-c", "tar -cf /tmp/image.tar -C /layout ."})
report, err := ctr.WithExec([]string{
"trivy", "image",
"--input", "/tmp/image.tar",
"--scanners", "vuln,secret",
"--format", "json",
"--severity", "CRITICAL,HIGH,MEDIUM",
"--exit-code", "0",
"--output", reportPath,
}).File(reportPath).Contents(ctx)
if err != nil {
return nil, fmt.Errorf("trivy scan of the archive %s failed: %w", archiveDigest, err)
}
critical, high, medium := countTrivySeverities(report)
result := &ScanResult{
Critical: critical,
@@ -222,14 +324,17 @@ func (m *SecurityScan) ImageScan(
SecretCount: len(ruleIDPattern.FindAllStringIndex(report, -1)),
}
if apiURL != "" && token != nil {
if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", imageRef, result); err != nil {
return nil, fmt.Errorf("posting image scan to API failed: %w", err)
if err := m.postScan(ctx, apiURL, token, serviceID, version, "trivy-image", "archive:"+archiveDigest, result); err != nil {
return nil, fmt.Errorf("posting archive scan to API failed: %w", err)
}
}
result.Success = true
return result, nil
}
// archiveDigestRE is the manifest digest grammar (lower-case sha256).
var archiveDigestRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
// withoutCITooling removes what the PIPELINE put into the checkout before the
// scan: the dagger CLI (`./bin/dagger`, installed by every stage's install
// script) and the platform's module mirror (`./.integraci-modules`). They are
@@ -242,6 +347,107 @@ func withoutCITooling(source *dagger.Directory) *dagger.Directory {
return source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")
}
// suppressionFiles are the files a scanner reads from the tree it scans and
// obeys: each one can silence a finding in the very change that adds it. The
// scan of record (ADR-0093 §4, WP-05) removes them, wherever they are in the
// tree, and reports which. Suppression goes through the platform's waivers.
var suppressionFiles = []string{
".gitleaksignore",
".gitleaks.toml",
".trivyignore",
".trivyignore.yaml",
"trivy.yaml",
"trivy.yml",
".semgrepignore",
".checkov.yaml",
".checkov.yml",
// Trivy loads ./trivy-secret.yaml by default; it can disable built-in
// secret rules or allow-list a path.
"trivy-secret.yaml",
"trivy-secret.yml",
}
// withoutSuppression removes every suppressionFiles entry from source and
// returns the paths it removed. A tree that cannot be listed is an error: a
// scan of record that could not drop the suppressions is not one.
func withoutSuppression(ctx context.Context, source *dagger.Directory) (*dagger.Directory, []string, error) {
return dropSuppression(ctx, source,
func(ctx context.Context, pattern string) ([]string, error) { return source.Glob(ctx, pattern) },
func(d *dagger.Directory, paths []string) *dagger.Directory { return d.WithoutFiles(paths) },
)
}
// dropSuppression is withoutSuppression over any tree: glob lists it by
// pattern, without returns it minus paths. A test passes an in-memory tree,
// so the DIRECTORY that comes back is checked, not just the reported names.
func dropSuppression[T any](
ctx context.Context,
source T,
glob func(context.Context, string) ([]string, error),
without func(T, []string) T,
) (T, []string, error) {
var found []string
for _, name := range suppressionFiles {
for _, pattern := range []string{name, "**/" + name} {
matches, err := glob(ctx, pattern)
if err != nil {
var none T
return none, nil, fmt.Errorf("list %s for the scan of record: %w", name, err)
}
found = append(found, matches...)
}
}
seen := map[string]bool{}
var removed []string
for _, path := range found {
if !seen[path] {
seen[path] = true
removed = append(removed, path)
}
}
if len(removed) == 0 {
return source, nil, nil
}
return without(source, removed), removed, nil
}
// trustedConfigArgs are the Trivy flags the scan of record adds: no
// configuration, ignore file or secret configuration is read from the tree
// it scans (Trivy 0.76 docs, "Disabling configuration files"). The files are
// removed from the scanned copy too; these flags also cover a renamed path a
// later Trivy might look up by default.
func trustedConfigArgs(scanOfRecord bool) []string {
if !scanOfRecord {
return nil
}
return []string{"--config=", "--ignorefile=", "--secret-config="}
}
// inlineIgnoreScript neutralises Trivy/tfsec inline ignore comments
// (`#trivy:ignore:AVD-...`, `#tfsec:ignore:...`) in the IaC files of the
// scanned copy, and prints each file it changed. Trivy has no flag that turns
// inline ignores off, and a change could otherwise silence its own
// misconfiguration next to the resource it adds (ADR-0093 §4). Only the
// container's copy is rewritten. POSIX find/grep/sed: runs on the Trivy
// image's busybox.
const inlineIgnoreScript = `find . -type f \( -name '*.tf' -o -name '*.tf.json' -o -name '*.hcl' ` +
`-o -name '*.yaml' -o -name '*.yml' -o -name '*.json' -o -name '*.tpl' ` +
`-o -name 'Dockerfile*' -o -name '*.dockerfile' -o -name 'Containerfile*' \) ` +
`-exec grep -lE '(trivy|tfsec):ignore' {} \; ` +
`-exec sed -i -E 's/(trivy|tfsec):ignore/\1-ignore-disabled-by-scan-of-record/g' {} \;`
// inlineIgnoredFiles turns inlineIgnoreScript's output into report entries.
func inlineIgnoredFiles(out string) []string {
var files []string
for _, line := range strings.Split(out, "\n") {
line = strings.TrimPrefix(strings.TrimSpace(line), "./")
if line != "" {
files = append(files, "inline:"+line)
}
}
return files
}
// postResults sends the security-scan result back to the IntegraCI scans
// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: typed
// severity columns plus the report_data counters the deploy OPA gate reads
@@ -280,19 +486,25 @@ func (m *SecurityScan) postScan(
"high_count": result.High,
"medium_count": result.Medium,
"report_data": map[string]any{
"secret_count": result.SecretCount,
"dast_high": 0,
"dast_critical": 0,
"sast_errors": 0,
"iac_critical": result.IacCritical,
"iac_high": result.IacHigh,
"sbom_present": false,
"signed": false,
"ignored_suppressions": result.IgnoredSuppressions,
"secret_count": result.SecretCount,
"dast_high": 0,
"dast_critical": 0,
"sast_errors": 0,
"iac_critical": result.IacCritical,
"iac_high": result.IacHigh,
"iac_scanned": result.IacScanned,
"sbom_present": false,
"signed": false,
},
}
if imageRef != "" {
payload["report_data"].(map[string]any)["image_ref"] = imageRef
}
if result.VulnDBUpdatedAt != "" {
// security/services/vuln_db_freshness.py VULN_DB_UPDATED_AT_KEY.
payload["report_data"].(map[string]any)["vuln_db_updated_at"] = result.VulnDBUpdatedAt
}
body, err := json.Marshal(payload)
if err != nil {
@@ -346,7 +558,7 @@ func (m *SecurityScan) LicenseScan(
}
trivy := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", withoutCITooling(source)).
@@ -436,7 +648,7 @@ func (m *SecurityScan) Sarif(
) (*dagger.File, error) {
const reportPath = "/tmp/trivy-results.sarif"
report := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")).
WithWorkdir("/src").
@@ -459,22 +671,15 @@ func (m *SecurityScan) Sarif(
// vulnerability counts parsed from the JSON report. Trivy may exit non-zero
// when vulnerabilities are present, so counts are read from the report file
// rather than the exit code.
func (m *SecurityScan) runTrivy(ctx context.Context, source *dagger.Directory) (int, int, int, error) {
func (m *SecurityScan) runTrivy(ctx context.Context, source *dagger.Directory, scanOfRecord bool) (int, int, int, error) {
const reportPath = "/tmp/trivy-results.json"
trivy := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{
"trivy", "fs",
"--format", "json",
"--severity", "CRITICAL,HIGH,MEDIUM",
"--exit-code", "0",
"--output", reportPath,
".",
})
WithExec(trivyArgs("fs", reportPath, scanOfRecord))
report, err := trivy.File(reportPath).Contents(ctx)
if err != nil {
@@ -490,30 +695,52 @@ func (m *SecurityScan) runTrivy(ctx context.Context, source *dagger.Directory) (
// from the JSON report. Reuses countTrivySeverities — trivy config emits the
// same "Severity":"<LEVEL>" shape as the vuln scan. exit-code 0 so findings
// don't fail the container step; gating is the deploy OPA gate's job.
func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Directory) (int, int, error) {
//
// For the scan of record, inline ignore comments are neutralised first
// (inlineIgnoreScript) and the files that carried one are returned, so they
// are posted as `ignored_suppressions`.
func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Directory, scanOfRecord bool) (int, int, []string, error) {
const reportPath = "/tmp/trivy-config.json"
trivy := dag.Container().
From("aquasec/trivy:0.58.1").
base := dag.Container().
From("aquasec/trivy:0.76.1").
// Persist Trivy's DB across runs (avoids re-downloading it).
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{
"trivy", "config",
"--format", "json",
"--severity", "CRITICAL,HIGH,MEDIUM",
"--exit-code", "0",
"--output", reportPath,
".",
})
WithWorkdir("/src")
var inline []string
if scanOfRecord {
base = base.WithExec([]string{"sh", "-c", inlineIgnoreScript})
out, err := base.Stdout(ctx)
if err != nil {
// Not "nothing to neutralise": a scan of record that could not
// drop the inline ignores is not one.
return 0, 0, nil, fmt.Errorf("neutralise inline ignores for the scan of record: %w", err)
}
inline = inlineIgnoredFiles(out)
}
trivy := base.WithExec(trivyArgs("config", reportPath, scanOfRecord))
report, err := trivy.File(reportPath).Contents(ctx)
if err != nil {
return 0, 0, fmt.Errorf("read trivy config output: %w", err)
return 0, 0, nil, fmt.Errorf("read trivy config output: %w", err)
}
critical, high, _ := countTrivySeverities(report)
return critical, high, nil
return critical, high, inline, nil
}
// trivyArgs is the argv of `trivy fs` / `trivy config` with a JSON report at
// reportPath; the scan of record adds trustedConfigArgs.
func trivyArgs(sub, reportPath string, scanOfRecord bool) []string {
args := []string{
"trivy", sub,
"--format", "json",
"--severity", "CRITICAL,HIGH,MEDIUM",
"--exit-code", "0",
"--output", reportPath,
}
args = append(args, trustedConfigArgs(scanOfRecord)...)
return append(args, ".")
}
// runTrivyCisCompliance runs `trivy config --compliance docker-cis-1.6.0` over
@@ -521,7 +748,7 @@ func (m *SecurityScan) runTrivyConfig(ctx context.Context, source *dagger.Direct
// failures don't fail the container step; gating is the deploy gate's job.
func (m *SecurityScan) runTrivyCisCompliance(ctx context.Context, source *dagger.Directory) int {
out, _ := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source).
WithWorkdir("/src").
@@ -541,19 +768,13 @@ func (m *SecurityScan) runTrivyCisCompliance(ctx context.Context, source *dagger
// runGitleaks runs Gitleaks secret detection and returns the number of
// detected secrets, parsed from the SARIF report (one "ruleId" per finding).
func (m *SecurityScan) runGitleaks(ctx context.Context, source *dagger.Directory) (int, error) {
func (m *SecurityScan) runGitleaks(ctx context.Context, source *dagger.Directory, ignoreInlineAllow bool) (int, error) {
const reportPath = "/tmp/gitleaks-results.sarif"
gitleaks := dag.Container().
From("zricethezav/gitleaks:v8.21.2").
WithDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{
"gitleaks", "detect",
"--source", ".",
"--report-format", "sarif",
"--report-path", reportPath,
"--exit-code", "0",
})
WithExec(gitleaksArgs(reportPath, ignoreInlineAllow))
report, err := gitleaks.File(reportPath).Contents(ctx)
if err != nil {
@@ -563,6 +784,23 @@ func (m *SecurityScan) runGitleaks(ctx context.Context, source *dagger.Directory
return countSarifResults(report), nil
}
// gitleaksArgs is the gitleaks argv. For the scan of record it also ignores
// inline `gitleaks:allow` comments: a change could otherwise mark its own
// secret allowed (ADR-0093 §4).
func gitleaksArgs(reportPath string, ignoreInlineAllow bool) []string {
args := []string{
"gitleaks", "detect",
"--source", ".",
"--report-format", "sarif",
"--report-path", reportPath,
"--exit-code", "0",
}
if ignoreInlineAllow {
args = append(args, "--ignore-gitleaks-allow")
}
return args
}
// countTrivySeverities tallies CRITICAL/HIGH/MEDIUM occurrences from Trivy's
// JSON report: one "Severity" per finding (see severityPattern for why the
// match is whitespace-tolerant).