Files
integraci-dagger-modules/sast-scan/main.go
T

670 lines
24 KiB
Go

// Package main implements the IntegraCI sast-scan Dagger module.
//
// Runs static application security testing (SAST) over a source directory
// using one of several vendors, counts findings, 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):
//
// semgrep semgrep/semgrep semgrep scan --config=auto --error
// 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=
// checkmarx checkmarx/ast-cli cx scan create
// 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 sonarqube --sonar-token env:SONAR_TOKEN --sonar-host-url https://sonar.example.com
// 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
package main
import (
"bytes"
"context"
"dagger/sast-scan/internal/dagger"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// SastScan is the IntegraCI static application security testing module.
type SastScan struct{}
// ScanResult contains the output of a SAST scan.
type ScanResult struct {
Tool string `json:"tool"`
Findings int `json:"findings"`
// Findings whose SARIF `level` is `error` -- the only ones the deploy gate
// treats as blocking. `Findings` counts every result, whatever its level.
Errors int `json:"errors"`
Warnings int `json:"warnings"`
SarifPath string `json:"sarif_path,omitempty"`
Report string `json:"report,omitempty"`
Skipped bool `json:"skipped"`
Success bool `json:"success"`
// The quality gate the code-quality SERVER evaluated for this analysis:
// passed | failed | unavailable. Empty for tools that have no server gate.
QualityGate string `json:"quality_gate,omitempty"`
// What the IntegraCI platform decided the pipeline does with that verdict
// (see gate.go): pass | warn | block, empty when nothing was posted. The
// Jenkins SAST stage reads it (`... scan ... gate-decision`) to turn the
// stage red on `warn`; on `block` Scan returns an error instead.
GateDecision string `json:"gate_decision,omitempty"`
GateReason string `json:"gate_reason,omitempty"`
}
// Scan runs a SAST pass over the source directory with the selected tool,
// counts findings, and optionally POSTs the result to the IntegraCI API.
// Mirrors security-scan.Scan's reporting contract.
func (m *SastScan) Scan(
ctx context.Context,
// Source directory to scan
source *dagger.Directory,
// SAST tool: semgrep | sonarqube | codeql | snyk-code | checkmarx | none
// +optional
// +default="semgrep"
tool string,
// Failure/severity threshold: LOW | MEDIUM | HIGH | CRITICAL
// +optional
// +default="HIGH"
severity string,
// Programming language for CodeQL database creation (e.g. python, go, javascript)
// +optional
// +default="python"
language string,
// Vendor token for snyk-code (SNYK_TOKEN) / checkmarx (CX API key)
// +optional
vendorToken *dagger.Secret,
// SonarQube authentication token (SONAR_TOKEN)
// +optional
sonarToken *dagger.Secret,
// SonarQube server URL (SONAR_HOST_URL)
// +optional
sonarHostURL string,
// SonarQube project key. IntegraCI always injects this; repositories
// do not need a sonar-project.properties file.
// +optional
sonarProjectKey string,
// Checkmarx AST base URI (deployment-specific)
// +optional
cxBaseURI string,
// Checkmarx tenant name
// +optional
cxTenant 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,
// Full commit SHA the scan analysed (`git rev-parse HEAD`). IntegraCI
// records it only when `version` starts with its first twelve characters,
// and the UAT door judges SonarQube by it (ADR-0072).
// +optional
revision string,
) (*ScanResult, error) {
result := &ScanResult{Tool: tool}
// The pipeline installs the dagger CLI at ./bin/dagger and mirrors the
// platform's modules into ./.integraci-modules INSIDE the checkout. They are
// 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")
var (
report string
err error
)
switch strings.ToLower(tool) {
case "none":
result.Skipped = true
result.Success = true
return result, nil
case "semgrep":
report, result.SarifPath, err = m.runSemgrep(ctx, source)
case "sonarqube":
report, result.QualityGate, err = m.runSonarQube(ctx, source, sonarToken, sonarHostURL, sonarProjectKey)
case "codeql":
report, result.SarifPath, err = m.runCodeQL(ctx, source, language)
case "snyk-code":
report, err = m.runSnykCode(ctx, source, vendorToken, severity)
case "checkmarx":
report, err = m.runCheckmarx(ctx, source, vendorToken, cxBaseURI, cxTenant)
default:
return nil, fmt.Errorf(
"unsupported sast tool %q (expected one of: semgrep, sonarqube, codeql, snyk-code, checkmarx, none)",
tool,
)
}
if err != nil {
return nil, fmt.Errorf("%s sast scan failed: %w", tool, err)
}
result.Report = report
var parsed bool
result.Findings, result.Errors, result.Warnings, parsed = tallyFindings(report)
// 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,
// so it is an error here. sonarqube reports through its own server and is
// not SARIF on stdout by design; it keeps the old best-effort count.
if !parsed && result.Findings == 0 && tool != "sonarqube" {
return nil, fmt.Errorf(
"%s produced no parseable SARIF report (%d bytes of output); refusing to record a clean scan",
tool, len(report),
)
}
// 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 {
gate, err := m.postResults(ctx, apiURL, token, serviceID, version, revision, result)
if err != nil {
return nil, fmt.Errorf("posting results to API failed: %w", err)
}
result.GateDecision, result.GateReason = gate.Decision, gate.Reason
if err := gate.err(); err != nil {
return nil, err
}
}
result.Success = true
return result, nil
}
// Sarif runs a SARIF-native SAST tool and returns its report as a file, for a
// pipeline to export and archive (#2143 phase 2):
//
// dagger call sarif --source=. --tool=semgrep export --path=integraci-sarif/sast.sarif
//
// Only semgrep and codeql write SARIF; the others are refused rather than
// faked. Nothing is posted: Scan remains the step that reports to IntegraCI,
// and this one adds the report file. A report that is not SARIF is an error,
// for the same reason Scan refuses one.
func (m *SastScan) Sarif(
ctx context.Context,
// Source directory to scan
source *dagger.Directory,
// SAST tool: semgrep | codeql
// +optional
// +default="semgrep"
tool string,
// Programming language for CodeQL database creation
// +optional
// +default="python"
language string,
) (*dagger.File, error) {
// Same exclusion as Scan: the CLI and the mirrored modules are the
// platform's code, not the tenant's.
source = source.WithoutFile("bin/dagger").WithoutDirectory(".integraci-modules")
var (
report string
err error
)
switch strings.ToLower(tool) {
case "semgrep":
report, _, err = m.runSemgrep(ctx, source)
case "codeql":
report, _, err = m.runCodeQL(ctx, source, language)
default:
return nil, fmt.Errorf("sast tool %q writes no SARIF; sarif supports semgrep and codeql", tool)
}
if err != nil {
return nil, fmt.Errorf("%s sarif failed: %w", tool, err)
}
if _, _, _, parsed := tallyFindings(report); !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
}
// runSemgrep executes Semgrep in SARIF mode and returns the raw SARIF
// document. Semgrep exits non-zero when findings are present (--error), so the
// 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) {
const sarifPath = "/tmp/semgrep-results.sarif"
semgrep := dag.Container().
From("semgrep/semgrep:1.99.0").
// 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")).
WithMountedDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{
"semgrep", "scan",
"--config=auto",
"--error",
"--sarif",
"--output", sarifPath,
".",
}, 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
// error from Stdout() — which is what this used to do — does not help,
// because the failure is a property of the container, not of that one
// call.
//
// MEASURED on a customer's first pipeline run: semgrep reported
// "Ran 291 rules on 2010 files: 279 findings", then the step died with
// `File.contents ERROR / exit code: 1` and the build failed carrying no
// report at all. Every stage after it was skipped. So SAST only ever
// succeeded on code with NOTHING to report — the one case where its
// output does not matter.
Expect: dagger.ReturnTypeAny,
})
sarif, err := semgrep.File(sarifPath).Contents(ctx)
if err != nil {
return "", "", fmt.Errorf("read semgrep SARIF output: %w", err)
}
return sarif, sarifPath, 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.
//
// The working directory MUST NOT be inside the source mount. The scanner
// image runs as the non-root user `scanner-cli` (its image config sets
// User=scanner-cli), which cannot write into /usr/src, while sonar-scanner
// creates `.scannerwork` under the project base dir by default. That fails
// at project initialisation, AFTER authentication has already succeeded:
//
// Fail to create working dir: /usr/src/.scannerwork
//
// so every repository with a valid token hit it, not only uploaded ones.
// `-Dsonar.working.directory=/tmp/.scannerwork` moves it somewhere that user
// can write (the image sets HOME=/tmp). A command-line -D also overrides a
// repository's own sonar-project.properties, so no app needs one for this.
func (m *SastScan) runSonarQube(
ctx context.Context,
source *dagger.Directory,
sonarToken *dagger.Secret,
sonarHostURL string,
sonarProjectKey string,
) (string, string, error) {
c := dag.Container().
From("sonarsource/sonar-scanner-cli:11.1").
WithMountedDirectory("/usr/src", source).
WithWorkdir("/usr/src")
if sonarHostURL != "" {
c = c.WithEnvVariable("SONAR_HOST_URL", sonarHostURL)
}
if sonarToken != nil {
c = c.WithSecretVariable("SONAR_TOKEN", sonarToken)
}
const workDirFlag = `-Dsonar.working.directory=/tmp/.scannerwork`
// Where the scanner names its Compute Engine task, pinned on the command line
// so a repo file cannot move the file the quality-gate verdict is read from.
const metadataFlag = `-Dsonar.scanner.metadataFilePath=` + sonarReportTask
// `sonar.projectKey` is MANDATORY and the scanner has no default for it.
// IntegraCI always injects the service identity via -D (which overrides any
// optional repo file). No source tree needs sonar-project.properties.
// Passed through the environment rather than interpolated into the command,
// so a service name can never become part of the shell.
scan := "sonar-scanner " + workDirFlag + " " + metadataFlag
if sonarHostURL != "" {
// Pinned on the command line, which wins over the repository's own
// sonar-project.properties: the analysed code must not be able to send
// the bound SONAR_TOKEN to a server of its choosing. Passed through the
// environment, like the project key, so the URL never becomes shell.
scan += ` -Dsonar.host.url="$SONAR_HOST_URL"`
}
if sonarProjectKey != "" {
c = c.WithEnvVariable("INTEGRACI_SONAR_PROJECT_KEY", sonarProjectKey)
scan += ` -Dsonar.projectKey="$INTEGRACI_SONAR_PROJECT_KEY"` +
` -Dsonar.projectName="$INTEGRACI_SONAR_PROJECT_KEY"`
}
// `|| true`: a scanner failure must still leave a container we can read, and
// the verdict below does not depend on its exit code.
ran := c.WithExec([]string{"sh", "-c", scan + " || true"})
out, err := ran.Stdout(ctx)
if err != nil {
return "", "", err
}
// The server's verdict for THIS analysis (see qualitygate.go). The scanner
// names its Compute Engine task in report-task.txt, inside the working
// directory set above; no file means the analysis never reached the server,
// which is "unavailable" — never a pass.
report, rerr := ran.File(sonarReportTask).Contents(ctx)
if rerr != nil || sonarToken == nil || sonarHostURL == "" {
return out, qualityGateUnavailable, nil
}
token, terr := sonarToken.Plaintext(ctx)
if terr != nil {
return out, qualityGateUnavailable, nil
}
gate := sonarGateClient{
hostURL: sonarHostURL,
expectedProjectKey: sonarProjectKey,
token: token,
http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: noRedirects},
poll: 3 * time.Second,
timeout: 5 * time.Minute,
}.qualityGate(ctx, report)
return out, gate, nil
}
// sonarReportTask is where the scanner writes the task it submitted (see metadataFlag).
const sonarReportTask = "/tmp/.scannerwork/report-task.txt"
// runCodeQL creates a CodeQL database for the given language and analyses
// it, emitting a SARIF report. Uses the official CodeQL CLI bundle image.
func (m *SastScan) runCodeQL(
ctx context.Context,
source *dagger.Directory,
language string,
) (string, string, error) {
const sarifPath = "/tmp/codeql-results.sarif"
script := fmt.Sprintf(
"codeql database create /tmp/cqldb --language=%s --source-root=/src --overwrite && "+
"codeql database analyze /tmp/cqldb --format=sarifv2.1.0 --output=%s --no-rerun || true",
language, sarifPath,
)
c := dag.Container().
From("ghcr.io/github/codeql-action/codeql-bundle:codeql-bundle-v2.20.3").
WithMountedDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{"sh", "-c", script})
if _, err := c.Stdout(ctx); err != nil {
_ = err
}
sarif, err := c.File(sarifPath).Contents(ctx)
if err != nil {
return "", "", fmt.Errorf("read codeql SARIF output: %w", err)
}
return sarif, sarifPath, nil
}
// runSnykCode runs "snyk code test" with a severity threshold. The Snyk
// CLI authenticates via SNYK_TOKEN injected from a secret.
func (m *SastScan) runSnykCode(
ctx context.Context,
source *dagger.Directory,
vendorToken *dagger.Secret,
severity string,
) (string, error) {
c := dag.Container().
From("snyk/snyk:linux").
WithMountedDirectory("/src", source).
WithWorkdir("/src")
if vendorToken != nil {
c = c.WithSecretVariable("SNYK_TOKEN", vendorToken)
}
threshold := strings.ToLower(severity)
cmd := fmt.Sprintf("snyk code test --severity-threshold=%s --sarif || true", threshold)
return c.WithExec([]string{"sh", "-c", cmd}).Stdout(ctx)
}
// runCheckmarx runs "cx scan create" against the Checkmarx AST platform
// using the official ast-cli image. Auth is via the CX API key secret;
// the base URI and tenant are deployment-specific params.
func (m *SastScan) runCheckmarx(
ctx context.Context,
source *dagger.Directory,
vendorToken *dagger.Secret,
cxBaseURI string,
cxTenant string,
) (string, error) {
c := dag.Container().
From("checkmarx/ast-cli:2.3.0").
WithMountedDirectory("/src", source).
WithWorkdir("/src")
if vendorToken != nil {
c = c.WithSecretVariable("CX_APIKEY", vendorToken)
}
if cxBaseURI != "" {
c = c.WithEnvVariable("CX_BASE_URI", cxBaseURI)
}
if cxTenant != "" {
c = c.WithEnvVariable("CX_TENANT", cxTenant)
}
cmd := "cx scan create --project-name integraci --scan-types sast " +
"--branch main --source /src --report-format sarif || true"
return c.WithExec([]string{"sh", "-c", cmd}).Stdout(ctx)
}
// tallyFindings reads a SARIF report and returns (all results, blocking
// results, warning-level results, parsed).
//
// WHY THE LEVEL MATTERS. The previous tally counted every `"ruleId":` in the
// report and posted that one number as BOTH `report_data.sast_errors` and
// `high_count`. The deploy gate has one rule for each, so a single Semgrep
// finding of level `warning` -- MEASURED 2026-09-13 on a customer tenant:
// `problem-based-packs.insecure-transport.js-node.using-http-server`, a plain
// `http.createServer` behind an Ingress that terminates TLS -- was refused
// twice, as "1 Semgrep ERROR-level finding" and as "1 high severity
// vulnerability", and the first deploy of a freshly onboarded service never
// happened. Semgrep's `--error` flag changes the EXIT CODE on any finding; it
// does not make a warning an error, and the gate's message promises
// "ERROR-level".
//
// What counts as BLOCKING, fail-closed at every fork:
//
// - `level: error` on the result, or -- when the result carries no level --
// on the rule's `defaultConfiguration` (SARIF §3.27.10 falls back there
// before it falls back to `warning`).
// - a `security-severity` property of 7.0 or more on the result or its
// rule, whatever the level: CodeQL grades most security queries
// `warning` and puts the CVSS-style rating there, so reading the level
// alone would wave a hard-coded credential through.
// - any level this function does not know (`high`, `critical`, a typo): an
// unknown severity is not a reason to pass.
//
// Informational and non-findings (`note`, `none`, a `kind` other than `fail`,
// a result with a non-empty `suppressions` list -- the inline pragma the gate
// message tells people to use) are not blocking. Everything else is a warning.
//
// `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) {
type rule struct {
ID string `json:"id"`
DefaultConfiguration struct {
Level string `json:"level"`
} `json:"defaultConfiguration"`
Properties map[string]any `json:"properties"`
}
var doc struct {
Runs []struct {
Tool struct {
Driver struct {
Rules []rule `json:"rules"`
} `json:"driver"`
} `json:"tool"`
Results []struct {
RuleID string `json:"ruleId"`
RuleIndex *int `json:"ruleIndex"`
Level string `json:"level"`
Kind string `json:"kind"`
Suppressions []any `json:"suppressions"`
Properties map[string]any `json:"properties"`
} `json:"results"`
} `json:"runs"`
}
if err := json.NewDecoder(strings.NewReader(report)).Decode(&doc); err != nil || len(doc.Runs) == 0 {
n := countRuleIDs(report)
return n, n, 0, false
}
for _, run := range doc.Runs {
byID := map[string]rule{}
for _, r := range run.Tool.Driver.Rules {
byID[r.ID] = r
}
for _, res := range run.Results {
if res.Kind != "" && res.Kind != "fail" {
continue // pass / notApplicable / informational: not a finding
}
if len(res.Suppressions) > 0 {
continue // suppressed inline, as the gate message invites
}
total++
var rl rule
if res.RuleIndex != nil && *res.RuleIndex >= 0 && *res.RuleIndex < len(run.Tool.Driver.Rules) {
rl = run.Tool.Driver.Rules[*res.RuleIndex]
} else {
rl = byID[res.RuleID]
}
if securitySeverity(res.Properties) >= 7.0 || securitySeverity(rl.Properties) >= 7.0 {
blocking++
continue
}
level := strings.ToLower(res.Level)
if level == "" {
level = strings.ToLower(rl.DefaultConfiguration.Level)
}
switch level {
case "error":
blocking++
case "", "warning":
warnings++
case "note", "none":
// informational
default:
blocking++ // unknown severity is not a pass
}
}
}
return total, blocking, warnings, true
}
// securitySeverity reads the CodeQL/GitHub `security-severity` property (a
// CVSS-style 0-10 score, serialised as a string or a number); 0 when absent.
func securitySeverity(props map[string]any) float64 {
v, ok := props["security-severity"]
if !ok {
return 0
}
switch t := v.(type) {
case float64:
return t
case string:
var f float64
if _, err := fmt.Sscanf(strings.TrimSpace(t), "%g", &f); err == nil {
return f
}
}
return 0
}
// countRuleIDs is the level-blind fallback tally: every `"ruleId":` in the text.
// Zero-dep, matching the security-scan classifyLicenses approach; best-effort.
func countRuleIDs(report string) int {
count := 0
idx := 0
for {
k := strings.Index(report[idx:], `"ruleId":`)
if k < 0 {
break
}
count++
idx += k + len(`"ruleId":`)
}
return count
}
// postResults sends the SAST scan result to the IntegraCI scans/sast
// endpoint. Shape matches api/app/schemas/scan.py ScanResultCreate: SAST
// findings populate report_data.sast_errors (the field the deploy OPA gate
// reads, see deploy.py _build_scan_results) plus the typed severity columns.
func (m *SastScan) postResults(
ctx context.Context,
apiURL string,
token *dagger.Secret,
serviceID string,
version string,
revision string,
result *ScanResult,
) (platformGate, error) {
payload := map[string]any{
"service_id": serviceID,
"version": version,
"scan_type": "sast",
"scanner": result.Tool,
"report_format": "sarif",
"findings_count": result.Findings,
// SAST has no CVE severity ladder: `high_count` used to mirror the total
// and made the gate's CVE rule fire a second time for the same Semgrep
// finding. Error-level results are reported ONCE, as `sast_errors`;
// warnings go to `medium_count` for visibility and block nothing.
"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,
},
}
if revision != "" {
payload["revision"] = revision
}
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
}
body, err := json.Marshal(payload)
if err != nil {
return platformGate{}, fmt.Errorf("marshal scan payload: %w", err)
}
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/scans/sast"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return platformGate{}, fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
tokenStr, err := token.Plaintext(ctx)
if err != nil {
return platformGate{}, 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 platformGate{}, fmt.Errorf("API post to %s failed: %w", endpoint, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return platformGate{}, fmt.Errorf("API post to %s returned %d", endpoint, resp.StatusCode)
}
answer, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
return gateFromResponse(answer), nil
}