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

+181 -25
View File
@@ -8,7 +8,8 @@
// Supported tools (each runs the vendor's canonical CLI inside its official
// container image):
//
// semgrep semgrep/semgrep semgrep scan --config=auto --error
// semgrep semgrep/semgrep semgrep scan --config=/rules --metrics=off --error (with --rules-dir)
// semgrep scan --config=auto --error (legacy, no --rules-dir)
// sonarqube sonarsource/sonar-scanner-cli sonar-scanner (SONAR_TOKEN + SONAR_HOST_URL)
// codeql codeql CLI bundle database create + database analyze
// snyk-code snyk/snyk snyk code test --severity-threshold=
@@ -22,6 +23,7 @@
// dagger call scan --source . --tool snyk-code --vendor-token env:SNYK_TOKEN --severity high
// dagger call scan --source . --tool codeql --language python
// dagger call scan --source . --tool none
// dagger call scan --source . --rules-dir ./sast-rules # air-gap: rules from the sast-rules pack
package main
import (
@@ -60,6 +62,13 @@ type ScanResult struct {
// stage red on `warn`; on `block` Scan returns an error instead.
GateDecision string `json:"gate_decision,omitempty"`
GateReason string `json:"gate_reason,omitempty"`
// `.semgrepignore` files the scan of record removed (ADR-0093 §4).
IgnoredSuppressions []string `json:"ignored_suppressions,omitempty"`
// sha256 of the rules directory semgrep ran (ruleset.go, #2908). Empty
// when no --rules-dir was given (registry `auto`, CodeQL's query packs):
// the platform then cannot tell which rules ran, and an enforcing verdict
// reads the scan as `unknown`.
RulesetDigest string `json:"ruleset_digest,omitempty"`
}
// Scan runs a SAST pass over the source directory with the selected tool,
@@ -117,6 +126,18 @@ func (m *SastScan) Scan(
// and the UAT door judges SonarQube by it (ADR-0072).
// +optional
revision string,
// The analysis job of record (ADR-0093 §4, WP-05): the repository's
// `.semgrepignore` is removed from the scanned copy and semgrep ignores
// inline `nosemgrep` comments, so a change cannot silence its own finding.
// Off for every other caller.
// +optional
scanOfRecord bool,
// The extracted `sast-rules` content pack (ADR-0078, ADR-0093 §8): its
// rules/ tree is what semgrep runs, with --metrics=off and never
// --config=auto. Omitted: the legacy --config=auto, which fetches the
// Semgrep registry and cannot run air-gapped.
// +optional
rulesDir *dagger.Directory,
) (*ScanResult, error) {
result := &ScanResult{Tool: tool}
// The pipeline installs the dagger CLI at ./bin/dagger and mirrors the
@@ -124,6 +145,21 @@ func (m *SastScan) Scan(
// the platform's code, not the tenant's; a SAST pass over them charges every
// tenant with findings in Go it never wrote. Only these two paths go.
source = source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")
if scanOfRecord {
removed, err := source.Glob(ctx, "**/.semgrepignore")
if err != nil {
return nil, fmt.Errorf("list .semgrepignore for the scan of record: %w", err)
}
top, err := source.Glob(ctx, ".semgrepignore")
if err != nil {
return nil, fmt.Errorf("list .semgrepignore for the scan of record: %w", err)
}
removed = append(top, removed...)
if len(removed) > 0 {
source = source.WithoutFiles(removed)
}
result.IgnoredSuppressions = removed
}
var (
report string
@@ -136,7 +172,15 @@ func (m *SastScan) Scan(
result.Success = true
return result, nil
case "semgrep":
report, result.SarifPath, err = m.runSemgrep(ctx, source)
if rulesDir != nil {
// Digest EXACTLY the directory runSemgrep mounts at /rules, before
// the run: a scan whose ruleset cannot be named is not posted.
result.RulesetDigest, err = rulesetDigestOf(ctx, rulesDir.Directory(semgrepRulesSubdir))
if err != nil {
return nil, fmt.Errorf("semgrep sast scan failed: %w", err)
}
}
report, result.SarifPath, err = m.runSemgrep(ctx, source, rulesDir, scanOfRecord)
case "sonarqube":
report, result.QualityGate, err = m.runSonarQube(ctx, source, sonarToken, sonarHostURL, sonarProjectKey)
case "codeql":
@@ -157,8 +201,19 @@ func (m *SastScan) Scan(
}
result.Report = report
if scanOfRecord {
// A scan of record that loaded no rules, or whose tool reported an
// execution error, did not analyse anything: posting it would make an
// empty run the trust=analysis evidence a commit is judged on.
if err := checkRecordReport(tool, report); err != nil {
return nil, err
}
}
var parsed bool
result.Findings, result.Errors, result.Warnings, parsed = tallyFindings(report)
// The scan of record counts a result the tool marked suppressed (CodeQL
// `// codeql[...]` alert-suppression comments, SARIF `suppressions`): an
// in-repo comment cannot silence its own finding (ADR-0093 §4).
result.Findings, result.Errors, result.Warnings, parsed = tallyFindings(report, scanOfRecord)
// A SARIF tool whose output parsed as nothing at all did not scan: snyk's
// `|| true` prints `Authentication error` to stdout, a truncated file has no
// results. Posting that as a clean scan is a green gate over an empty run,
@@ -209,6 +264,9 @@ func (m *SastScan) Sarif(
// +optional
// +default="python"
language string,
// The extracted `sast-rules` content pack; see Scan.
// +optional
rulesDir *dagger.Directory,
) (*dagger.File, error) {
// Same exclusion as Scan: the CLI and the mirrored modules are the
// platform's code, not the tenant's.
@@ -219,7 +277,7 @@ func (m *SastScan) Sarif(
)
switch strings.ToLower(tool) {
case "semgrep":
report, _, err = m.runSemgrep(ctx, source)
report, _, err = m.runSemgrep(ctx, source, rulesDir, false)
case "codeql":
report, _, err = m.runCodeQL(ctx, source, language)
default:
@@ -228,7 +286,7 @@ func (m *SastScan) Sarif(
if err != nil {
return nil, fmt.Errorf("%s sarif failed: %w", tool, err)
}
if _, _, _, parsed := tallyFindings(report); !parsed {
if _, _, _, parsed := tallyFindings(report, false); !parsed {
return nil, fmt.Errorf("%s produced no parseable SARIF report (%d bytes)", tool, len(report))
}
return dag.Directory().WithNewFile("sast.sarif", report).File("sast.sarif"), nil
@@ -239,23 +297,33 @@ func (m *SastScan) Sarif(
// exec DECLARES that a non-zero exit is an expected outcome; without that the
// report can never be read back and a scan that finds something is
// indistinguishable from a scan that could not run.
func (m *SastScan) runSemgrep(ctx context.Context, source *dagger.Directory) (string, string, error) {
//
// With rulesDir (the `sast-rules` pack) the rules come from the pack and nothing
// reaches semgrep.dev (semgrep_args.go); without it, the legacy registry run.
// The engine image itself is pulled from upstream or the customer's mirror,
// never bundled by IntegraCI (semgrep is LGPL-2.1; AGENTS.md rule 3).
//
// For the scan of record (disableNosem) the exit code is checked too: semgrep
// exits 0 (nothing found) or 1 (`--error`, findings); any other code is a run
// that failed, and its SARIF is not evidence of an analysis.
func (m *SastScan) runSemgrep(ctx context.Context, source *dagger.Directory, rulesDir *dagger.Directory, disableNosem bool) (string, string, error) {
const sarifPath = "/tmp/semgrep-results.sarif"
semgrep := dag.Container().
From("semgrep/semgrep:1.99.0").
fromPack := rulesDir != nil
semgrep := dag.Container().From("semgrep/semgrep:1.99.0")
if fromPack {
semgrep = semgrep.WithMountedDirectory(semgrepRulesMount, rulesDir.Directory(semgrepRulesSubdir))
for _, kv := range semgrepEnv(true) {
semgrep = semgrep.WithEnvVariable(kv[0], kv[1])
}
} else {
// Persist the semgrep registry rule cache across runs (--config=auto
// otherwise re-fetches the rulesets on every scan).
WithMountedCache("/root/.cache/semgrep", dag.CacheVolume("semgrep-rules")).
semgrep = semgrep.WithMountedCache("/root/.cache/semgrep", dag.CacheVolume("semgrep-rules"))
}
semgrep = semgrep.
WithMountedDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{
"semgrep", "scan",
"--config=auto",
"--error",
"--sarif",
"--output", sarifPath,
".",
}, dagger.ContainerWithExecOpts{
WithExec(semgrepArgs(sarifPath, fromPack, disableNosem), dagger.ContainerWithExecOpts{
// `--error` makes semgrep exit 1 the moment it finds anything, and a
// container whose exec failed cannot be read from: every later
// `.File(...).Contents()` re-raises that same failure. Swallowing the
@@ -272,6 +340,15 @@ func (m *SastScan) runSemgrep(ctx context.Context, source *dagger.Directory) (st
Expect: dagger.ReturnTypeAny,
})
if disableNosem {
code, err := semgrep.ExitCode(ctx)
if err != nil {
return "", "", fmt.Errorf("read semgrep exit code: %w", err)
}
if !semgrepRanToCompletion(code) {
return "", "", fmt.Errorf("semgrep exited %d: the scan of record did not run to completion", code)
}
}
sarif, err := semgrep.File(sarifPath).Contents(ctx)
if err != nil {
return "", "", fmt.Errorf("read semgrep SARIF output: %w", err)
@@ -279,6 +356,76 @@ func (m *SastScan) runSemgrep(ctx context.Context, source *dagger.Directory) (st
return sarif, sarifPath, nil
}
// semgrepRanToCompletion: 0 = no finding, 1 = findings (`--error`). Every
// other exit code (2 fatal, 3-8 parse/config/rule errors, 13 missing config,
// 14 rule download failure, ...) is a run that did not analyse the tree.
func semgrepRanToCompletion(code int) bool {
return code == 0 || code == 1
}
// checkRecordReport refuses a SARIF report as the scan of record when it is
// not evidence that the tool analysed anything (ADR-0093 §4, WP-05): no run,
// a run whose driver declares zero rules (a registry fetch that failed behind
// an air gap still writes a well-formed empty SARIF), or a run whose
// invocation reports an `error`-level tool execution notification or
// `executionSuccessful: false`. Only for SARIF tools; sonarqube reports
// through its server.
func checkRecordReport(tool, report string) error {
if tool == "sonarqube" {
return nil
}
var doc struct {
Runs []struct {
Tool struct {
Driver struct {
Rules []json.RawMessage `json:"rules"`
} `json:"driver"`
// CodeQL declares its queries' rules on the query-pack
// extensions, not on the driver.
Extensions []struct {
Rules []json.RawMessage `json:"rules"`
} `json:"extensions"`
} `json:"tool"`
Invocations []struct {
ExecutionSuccessful *bool `json:"executionSuccessful"`
Notifications []struct {
Level string `json:"level"`
Message struct {
Text string `json:"text"`
} `json:"message"`
} `json:"toolExecutionNotifications"`
} `json:"invocations"`
} `json:"runs"`
}
if err := json.Unmarshal([]byte(report), &doc); err != nil || len(doc.Runs) == 0 {
return fmt.Errorf("%s: no SARIF run; refusing to record an analysis that did not happen", tool)
}
for _, run := range doc.Runs {
rules := len(run.Tool.Driver.Rules)
for _, ext := range run.Tool.Extensions {
rules += len(ext.Rules)
}
if rules == 0 {
return fmt.Errorf("%s: the run loaded no rules; refusing to record it as the scan of record", tool)
}
for _, inv := range run.Invocations {
if inv.ExecutionSuccessful != nil && !*inv.ExecutionSuccessful {
return fmt.Errorf("%s: the run reports executionSuccessful=false", tool)
}
for _, n := range inv.Notifications {
if strings.EqualFold(n.Level, "error") {
msg := n.Message.Text
if len(msg) > 200 {
msg = msg[:200]
}
return fmt.Errorf("%s: tool execution error: %s", tool, msg)
}
}
}
}
return nil
}
// runSonarQube runs the SonarQube scanner CLI against the source. The
// scanner authenticates with SONAR_TOKEN and targets the server at
// SONAR_HOST_URL, both injected from secrets/params.
@@ -488,7 +635,10 @@ func (m *SastScan) runCheckmarx(
//
// `parsed` is false when the text is not SARIF; the caller decides what that
// means for the tool that produced it.
func tallyFindings(report string) (total, blocking, warnings int, parsed bool) {
//
// countSuppressed (the scan of record) counts a result the tool marked
// suppressed as a finding: the suppression came from the judged repository.
func tallyFindings(report string, countSuppressed bool) (total, blocking, warnings int, parsed bool) {
type rule struct {
ID string `json:"id"`
DefaultConfiguration struct {
@@ -526,7 +676,7 @@ func tallyFindings(report string) (total, blocking, warnings int, parsed bool) {
if res.Kind != "" && res.Kind != "fail" {
continue // pass / notApplicable / informational: not a finding
}
if len(res.Suppressions) > 0 {
if len(res.Suppressions) > 0 && !countSuppressed {
continue // suppressed inline, as the gate message invites
}
total++
@@ -621,17 +771,23 @@ func (m *SastScan) postResults(
"high_count": 0,
"medium_count": result.Warnings,
"report_data": map[string]any{
"sast_errors": result.Errors,
"secret_count": 0,
"dast_high": 0,
"dast_critical": 0,
"sbom_present": false,
"signed": false,
"ignored_suppressions": result.IgnoredSuppressions,
"sast_errors": result.Errors,
"secret_count": 0,
"dast_high": 0,
"dast_critical": 0,
"sbom_present": false,
"signed": false,
},
}
if revision != "" {
payload["revision"] = revision
}
if result.RulesetDigest != "" {
// Compared by the platform with the digest of the pack IT ships
// (security_verdict, #2908); never trusted as the pack's own digest.
payload["report_data"].(map[string]any)[rulesetReportKey] = result.RulesetDigest
}
if result.QualityGate != "" {
// Read by the deploy gate (`quality_gate_failed`) and the integration graph.
payload["report_data"].(map[string]any)["quality_gate"] = result.QualityGate