chore: publish IntegraCI build modules 732ec6c83925

This commit is contained in:
dhimaz0445 committed 2026-10-28 08:09:16 +00:00
1 parent 7a84930dea
commit 5f8a24d014
133 files changed
+18990 -2

No files matched your search

+61
View File
@@ -0,0 +1,61 @@
# sast-scan
> **UNVERIFIED SCAFFOLD** — run `dagger develop` + `dagger functions` + test
> against a matching Dagger engine (engineVersion `v0.15.0`) 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` / `*File` types are generated). Do not
> assume it works as-is.
IntegraCI SAST (Static Application Security Testing) Dagger module. Runs
[Semgrep](https://semgrep.dev/) over a source directory, emits a SARIF
report, counts findings, and optionally POSTs the result to the IntegraCI
API.
It mirrors the structure and idioms of the sibling `security-scan` module.
## Functions
### `scan`
Runs Semgrep static analysis and returns a `ScanResult`.
| Param | Required | Default | Description |
| ------------ | -------- | ----------- | ------------------------------------------------ |
| `source` | yes | — | Source directory to scan |
| `tool` | no | `semgrep` | SAST tool to run; `none` skips scanning |
| `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 |
When `tool=none`, the scan is skipped and a result with `skipped=true` is
returned. Results are POSTed to the API only when both `api-url` and
`token` are set.
## 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 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)
```
+13
View File
@@ -0,0 +1,13 @@
{
"name": "sast-scan",
"engineVersion": "v0.21.7",
"sdk": {
"source": "go"
},
"source": ".",
"include": [
"./main.go",
"./qualitygate.go",
"./gate.go"
]
}
+51
View File
@@ -0,0 +1,51 @@
package main
// The platform's answer to a posted scan: what the pipeline does with the
// quality gate the code-quality server evaluated (POST /api/v1/scans/sast,
// `gate`). The platform decides from the tenant's policy for the stage the
// pipeline's token belongs to; this module only acts on it:
//
// - pass — nothing to do;
// - warn — reported as `gate-decision`; the Jenkins stage turns red and the
// pipeline goes on;
// - block — Scan fails, so the stage and the pipeline stop (a UAT pull
// request is then closed by the job's failure handler).
//
// An answer without a `gate` (a platform older than the policy, or a reply this
// module cannot read) is `pass`: the module never invents a stricter rule than
// the platform asked for, and the deploy gate still judges the stored verdict.
import (
"encoding/json"
"fmt"
)
type platformGate struct {
Decision string `json:"decision"`
Reason string `json:"reason"`
}
func gateFromResponse(body []byte) platformGate {
var answer struct {
Gate *platformGate `json:"gate"`
}
if err := json.Unmarshal(body, &answer); err != nil || answer.Gate == nil {
return platformGate{Decision: "pass"}
}
switch answer.Gate.Decision {
case "pass", "warn", "block":
return *answer.Gate
}
return platformGate{Decision: "pass"}
}
func (g platformGate) err() error {
if g.Decision != "block" {
return nil
}
reason := g.Reason
if reason == "" {
reason = "the quality gate failed"
}
return fmt.Errorf("IntegraCI stopped the pipeline: %s", reason)
}
+32
View File
@@ -0,0 +1,32 @@
package main
import "testing"
func TestGateFromResponse(t *testing.T) {
cases := []struct {
name, body, want string
}{
{"block", `{"id":"x","gate":{"decision":"block","reason":"r"}}`, "block"},
{"warn", `{"gate":{"decision":"warn"}}`, "warn"},
{"pass", `{"gate":{"decision":"pass"}}`, "pass"},
{"an older platform answers without a gate", `{"id":"x"}`, "pass"},
{"an unknown decision is not invented into a rule", `{"gate":{"decision":"stop"}}`, "pass"},
{"unreadable", `not json`, "pass"},
}
for _, c := range cases {
if got := gateFromResponse([]byte(c.body)).Decision; got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestOnlyBlockStopsTheScan(t *testing.T) {
if err := (platformGate{Decision: "block", Reason: "gate failed (uat: block)"}).err(); err == nil {
t.Fatal("block must fail the scan")
}
for _, d := range []string{"pass", "warn", ""} {
if err := (platformGate{Decision: d}).err(); err != nil {
t.Errorf("%q must not fail the scan: %v", d, err)
}
}
}
+669
View File
@@ -0,0 +1,669 @@
// 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
}
+164
View File
@@ -0,0 +1,164 @@
package main
// The SonarQube quality gate, as the SERVER evaluated it for this analysis.
//
// Why this exists. The scanner used to run as `sonar-scanner … || true` with no
// gate wait, and nothing read the verdict afterwards. MEASURED 2026-09-15 on an
// on-prem tenant: four projects analysed on every build, their gate status sat on
// the server (`api/qualitygates/project_status`), and no pipeline, gate or screen
// ever looked at it. A build that failed the tenant's own quality gate deployed
// exactly like one that passed.
//
// Why the web API and not the scanner's log. The scanner's console wording is not
// a contract and changes between scanner versions; the web API is documented and
// is what SonarQube's own CI integrations read. The analysis is processed
// asynchronously by the server's Compute Engine, so the verdict is read in two
// steps: the CE task named in `report-task.txt` (which the scanner writes into its
// working directory) yields the analysis id once it finishes, and the analysis id
// yields the gate status of exactly THIS analysis — not whatever the project's
// latest one is by the time we ask.
//
// Nothing here imports the Dagger SDK, so it is unit-testable on its own.
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"time"
)
const (
qualityGatePassed = "passed"
qualityGateFailed = "failed"
qualityGateUnavailable = "unavailable"
)
// ceTaskIDPattern is the shape of a Compute Engine task id. The id comes out of a
// file inside a container that ran the customer's repository, so it is data until
// it matches.
var ceTaskIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
// ceTaskIDFromReport reads `ceTaskId` out of a scanner `report-task.txt`
// (`key=value` lines). "" when absent or malformed.
func ceTaskIDFromReport(report string) string {
for _, line := range strings.Split(report, "\n") {
key, value, ok := strings.Cut(strings.TrimSpace(line), "=")
if ok && key == "ceTaskId" {
value = strings.TrimSpace(value)
if ceTaskIDPattern.MatchString(value) {
return value
}
return ""
}
}
return ""
}
// gateFromProjectStatus maps `projectStatus.status` onto the platform's words.
// OK and WARN (older servers) pass; ERROR fails; NONE (no gate) and anything
// unknown is unavailable — never "passed".
func gateFromProjectStatus(status string) string {
switch strings.ToUpper(strings.TrimSpace(status)) {
case "OK", "WARN":
return qualityGatePassed
case "ERROR":
return qualityGateFailed
default:
return qualityGateUnavailable
}
}
type sonarGateClient struct {
// hostURL is the server the pipeline was rendered with (the SonarQube
// connector's address, which a spec override can also set) — never the one a
// repository's own sonar-project.properties may name.
hostURL string
// expectedProjectKey, when set, is the IntegraCI-injected project this
// analysis MUST belong to. Without the check the verdict could be read from
// any project the token can see.
expectedProjectKey string
token string
http *http.Client
poll time.Duration
timeout time.Duration
}
func (c sonarGateClient) getJSON(ctx context.Context, path string, query url.Values, out any) error {
endpoint := strings.TrimRight(c.hostURL, "/") + path + "?" + query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return err
}
// A SonarQube user token is the basic-auth USERNAME with an empty password.
req.SetBasicAuth(c.token, "")
resp, err := c.http.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("%s answered %d", path, resp.StatusCode)
}
return json.NewDecoder(resp.Body).Decode(out)
}
// qualityGate waits for the analysis in `report` to be processed and returns its
// gate verdict. Any failure to learn it is `unavailable`, which the deploy gate
// does NOT read as a pass or a fail — it is recorded so the gap is visible.
func (c sonarGateClient) qualityGate(ctx context.Context, report string) string {
taskID := ceTaskIDFromReport(report)
if taskID == "" || c.hostURL == "" || c.token == "" {
return qualityGateUnavailable
}
deadline := time.Now().Add(c.timeout)
var task struct {
Task struct {
Status string `json:"status"`
AnalysisID string `json:"analysisId"`
ComponentKey string `json:"componentKey"`
} `json:"task"`
}
for {
if err := c.getJSON(ctx, "/api/ce/task", url.Values{"id": {taskID}}, &task); err != nil {
return qualityGateUnavailable
}
switch task.Task.Status {
case "SUCCESS":
if c.expectedProjectKey != "" && task.Task.ComponentKey != c.expectedProjectKey {
return qualityGateUnavailable
}
var status struct {
ProjectStatus struct {
Status string `json:"status"`
} `json:"projectStatus"`
}
if task.Task.AnalysisID == "" {
return qualityGateUnavailable
}
err := c.getJSON(ctx, "/api/qualitygates/project_status",
url.Values{"analysisId": {task.Task.AnalysisID}}, &status)
if err != nil {
return qualityGateUnavailable
}
return gateFromProjectStatus(status.ProjectStatus.Status)
case "FAILED", "CANCELED":
return qualityGateUnavailable
}
if time.Now().After(deadline) {
return qualityGateUnavailable
}
select {
case <-ctx.Done():
return qualityGateUnavailable
case <-time.After(c.poll):
}
}
}
// noRedirects keeps the token on the one host it was meant for: a redirect is
// answered as-is instead of being followed with the credential attached.
func noRedirects(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+166
View File
@@ -0,0 +1,166 @@
package main
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestCeTaskIDFromReport(t *testing.T) {
report := "projectKey=shop-api\nserverUrl=http://sonar.test\nceTaskId=AZkq-12_x\nceTaskUrl=http://sonar.test/api/ce/task?id=AZkq-12_x\n"
if got := ceTaskIDFromReport(report); got != "AZkq-12_x" {
t.Fatalf("ceTaskId = %q", got)
}
for _, bad := range []string{"", "projectKey=x\n", "ceTaskId=../../api/users\n", "ceTaskId=a b\n"} {
if got := ceTaskIDFromReport(bad); got != "" {
t.Fatalf("%q must yield no task id, got %q", bad, got)
}
}
}
func TestGateFromProjectStatusNeverInventsAPass(t *testing.T) {
cases := map[string]string{
"OK": qualityGatePassed, "WARN": qualityGatePassed, "ERROR": qualityGateFailed,
"NONE": qualityGateUnavailable, "": qualityGateUnavailable, "SOMETHING": qualityGateUnavailable,
}
for in, want := range cases {
if got := gateFromProjectStatus(in); got != want {
t.Fatalf("%q -> %q, want %q", in, got, want)
}
}
}
// fakeSonar serves the two endpoints; the CE task finishes after `pending` polls.
func fakeSonar(t *testing.T, pending int32, gate string, token string) (*httptest.Server, *atomic.Int32) {
t.Helper()
var polls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || user != token || pass != "" {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch r.URL.Path {
case "/api/ce/task":
if r.URL.Query().Get("id") != "TASK1" {
w.WriteHeader(http.StatusNotFound)
return
}
n := polls.Add(1)
status := "IN_PROGRESS"
if n > pending {
status = "SUCCESS"
}
_, _ = w.Write([]byte(`{"task":{"status":"` + status + `","analysisId":"AN1","componentKey":"shop-api"}}`))
case "/api/qualitygates/project_status":
if r.URL.Query().Get("analysisId") != "AN1" {
w.WriteHeader(http.StatusNotFound)
return
}
_, _ = w.Write([]byte(`{"projectStatus":{"status":"` + gate + `"}}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
t.Cleanup(srv.Close)
return srv, &polls
}
func client(host, token string) sonarGateClient {
return sonarGateClient{hostURL: host, token: token, http: http.DefaultClient, poll: time.Millisecond, timeout: 2 * time.Second}
}
const report = "ceTaskId=TASK1\n"
func TestQualityGateWaitsForTheAnalysisAndReadsItsVerdict(t *testing.T) {
srv, polls := fakeSonar(t, 2, "ERROR", "tok")
if got := client(srv.URL, "tok").qualityGate(context.Background(), report); got != qualityGateFailed {
t.Fatalf("gate = %q, want failed", got)
}
if polls.Load() != 3 {
t.Fatalf("expected to poll until the task finished, polled %d times", polls.Load())
}
srv2, _ := fakeSonar(t, 0, "OK", "tok")
if got := client(srv2.URL, "tok").qualityGate(context.Background(), report); got != qualityGatePassed {
t.Fatalf("gate = %q, want passed", got)
}
}
func TestQualityGateIsUnavailableWhenItCannotBeLearned(t *testing.T) {
srv, _ := fakeSonar(t, 0, "OK", "tok")
if got := client(srv.URL, "wrong").qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("a rejected token must not read as a verdict, got %q", got)
}
if got := client(srv.URL, "tok").qualityGate(context.Background(), "no task here"); got != qualityGateUnavailable {
t.Fatalf("no ceTaskId must be unavailable, got %q", got)
}
never, _ := fakeSonar(t, 1<<30, "OK", "tok")
c := client(never.URL, "tok")
c.timeout = 20 * time.Millisecond
if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("a task that never finishes must time out as unavailable, got %q", got)
}
if got := client("", "tok").qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("no configured host must be unavailable, got %q", got)
}
if !strings.Contains(qualityGateUnavailable, "unavailable") {
t.Fatal("constant drifted")
}
}
func TestAFailedAnalysisIsNotWaitedOn(t *testing.T) {
var polls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
polls.Add(1)
_, _ = w.Write([]byte(`{"task":{"status":"FAILED"}}`))
}))
t.Cleanup(srv.Close)
c := client(srv.URL, "tok")
c.poll = 5 * time.Millisecond
if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("gate = %q, want unavailable", got)
}
if polls.Load() != 1 {
t.Fatalf("a failed analysis must stop the wait at once, polled %d times", polls.Load())
}
}
func TestAVerdictFromAnotherProjectIsNotThisBuilds(t *testing.T) {
srv, _ := fakeSonar(t, 0, "OK", "tok")
c := client(srv.URL, "tok")
c.expectedProjectKey = "shop-api"
if got := c.qualityGate(context.Background(), report); got != qualityGatePassed {
t.Fatalf("matching project: gate = %q, want passed", got)
}
c.expectedProjectKey = "payments"
if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("another project's verdict must not count, got %q", got)
}
}
func TestTheTokenDoesNotFollowARedirect(t *testing.T) {
var leaked atomic.Int32
elsewhere := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, _, ok := r.BasicAuth(); ok {
leaked.Add(1)
}
_, _ = w.Write([]byte(`{"task":{"status":"SUCCESS","analysisId":"AN1"}}`))
}))
t.Cleanup(elsewhere.Close)
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, elsewhere.URL+r.URL.RequestURI(), http.StatusFound)
}))
t.Cleanup(redirector.Close)
c := client(redirector.URL, "tok")
c.http = &http.Client{CheckRedirect: noRedirects}
if got := c.qualityGate(context.Background(), report); got != qualityGateUnavailable {
t.Fatalf("a redirect is not a verdict, got %q", got)
}
if leaked.Load() != 0 {
t.Fatal("the token followed a redirect")
}
}