chore: publish IntegraCI build modules a11ec75d3e09
This commit is contained in:
1 parent
694710104a
commit
3c2b80914e
78 files changed
+4982
-405
No files matched your search
@@ -32,6 +32,45 @@ 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.
|
||||
|
||||
## Air-gapped rules (`--rules-dir`, ADR-0093 §8)
|
||||
|
||||
`semgrep --config=auto` fetches its rules from the Semgrep registry and sends
|
||||
the project URL, so it cannot run air-gapped. Pass `--rules-dir` with the
|
||||
extracted `sast-rules` content pack (`catalog/sast-rules`, ADR-0078) and the
|
||||
module runs `semgrep scan --config=/rules --metrics=off` with
|
||||
`SEMGREP_SEND_METRICS=off` and `SEMGREP_ENABLE_VERSION_CHECK=0`. `auto` is
|
||||
never used then. The argument builder is `semgrep_args.go`, tested without an
|
||||
engine in `semgrep_args_test.go`.
|
||||
|
||||
Without `--rules-dir` the legacy `--config=auto` run is unchanged and does
|
||||
NOT get `--metrics=off`: semgrep refuses that pair ("Cannot create auto config
|
||||
when metrics are off", exit 2).
|
||||
|
||||
Licences: the pack holds only in-house or permissively licensed rule files
|
||||
(the Semgrep-maintained registry rules are under the Semgrep Rules License
|
||||
v1.0, which forbids redistribution). The semgrep engine (LGPL-2.1) is never
|
||||
bundled by IntegraCI; the customer's mirror pulls `semgrep/semgrep` from
|
||||
upstream.
|
||||
|
||||
```sh
|
||||
dagger call sarif --source . --rules-dir ./sast-rules export --path=integraci-sarif/sast.sarif
|
||||
```
|
||||
|
||||
### Which ruleset ran (#2908)
|
||||
|
||||
`--rules-dir` accepts any directory, and SARIF does not say which rule files
|
||||
produced it. `scan` therefore digests the directory it mounts at `/rules`
|
||||
(`ruleset.go`: for each non-hidden file in byte order of its relative path,
|
||||
`<path>\0<sha256 hex>\n`, then `sha256:` + the sha256 of those lines) and
|
||||
posts it as `report_data.sast_ruleset_digest`. The platform computes the digest
|
||||
of the pack it ships (`catalog/sast-rules/rules`) itself and compares; where
|
||||
the gate point and the `sast` family both enforce, a SAST scan of record with
|
||||
no digest (no `--rules-dir`, CodeQL) or another one is `unknown`. The posted
|
||||
value is never taken as the pack's digest. Paths with a hidden segment
|
||||
(`.gitkeep`) are skipped on both sides. The API image and the pack the runners
|
||||
mount must be deployed together: a pack revision the API image does not carry
|
||||
reads `unknown`.
|
||||
|
||||
## Usage
|
||||
|
||||
> These commands are illustrative and have NOT been run here. Verify against
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "sast-scan",
|
||||
"engineVersion": "v0.21.7",
|
||||
"engineVersion": "v0.21.11",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
@@ -8,6 +8,8 @@
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./qualitygate.go",
|
||||
"./gate.go"
|
||||
"./gate.go",
|
||||
"./semgrep_args.go",
|
||||
"./ruleset.go"
|
||||
]
|
||||
}
|
||||
+181
-25
@@ -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
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package main
|
||||
|
||||
// The scan of record (ADR-0093 §4, WP-05): a SARIF that is not evidence of an
|
||||
// analysis is refused, and an in-repository suppression does not silence a
|
||||
// finding. Written on the build VM, not run there (owner decision 2026-10-11).
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const oneRule = `{"id":"python.lang.security.audit.eval","defaultConfiguration":{"level":"error"}}`
|
||||
|
||||
func sarif(rules, results, invocations string) string {
|
||||
return `{"version":"2.1.0","runs":[{"tool":{"driver":{"name":"semgrep","rules":[` + rules +
|
||||
`]}},"results":[` + results + `],"invocations":[` + invocations + `]}]}`
|
||||
}
|
||||
|
||||
func TestARecordRunThatLoadedNoRulesIsRefused(t *testing.T) {
|
||||
// What an air-gapped `--config=auto` leaves behind: well-formed, empty.
|
||||
err := checkRecordReport("semgrep", sarif("", "", `{"executionSuccessful":true}`))
|
||||
if err == nil || !strings.Contains(err.Error(), "no rules") {
|
||||
t.Fatalf("an empty rule set must not be a scan of record, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestARecordRunWithAToolErrorIsRefused(t *testing.T) {
|
||||
for name, inv := range map[string]string{
|
||||
"notification": `{"executionSuccessful":true,"toolExecutionNotifications":[{"level":"error","message":{"text":"Failed to download config from https://semgrep.dev/c/auto"}}]}`,
|
||||
"unsuccessful": `{"executionSuccessful":false}`,
|
||||
} {
|
||||
if err := checkRecordReport("semgrep", sarif(oneRule, "", inv)); err == nil {
|
||||
t.Errorf("%s: a failed run must not be a scan of record", name)
|
||||
}
|
||||
}
|
||||
if err := checkRecordReport("codeql", `{"runs":[]}`); err == nil {
|
||||
t.Error("no run at all must not be a scan of record")
|
||||
}
|
||||
if err := checkRecordReport("semgrep", "Authentication error"); err == nil {
|
||||
t.Error("unparseable output must not be a scan of record")
|
||||
}
|
||||
}
|
||||
|
||||
// Legal direction: a clean run that loaded rules is a scan of record, and a
|
||||
// warning-level notification does not refuse it.
|
||||
func TestACleanRecordRunIsAccepted(t *testing.T) {
|
||||
inv := `{"executionSuccessful":true,"toolExecutionNotifications":[{"level":"warning","message":{"text":"Syntax error at line 3 in a.py"}}]}`
|
||||
if err := checkRecordReport("semgrep", sarif(oneRule, "", inv)); err != nil {
|
||||
t.Fatalf("a clean run must be recorded: %v", err)
|
||||
}
|
||||
if err := checkRecordReport("sonarqube", "anything"); err != nil {
|
||||
t.Fatalf("sonarqube is not SARIF on stdout: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// CodeQL declares rules on tool.extensions (query packs), not on the driver.
|
||||
func TestACodeQLRunWithRulesOnItsExtensionsIsAccepted(t *testing.T) {
|
||||
report := `{"runs":[{"tool":{"driver":{"name":"CodeQL","rules":[]},"extensions":[{"name":"codeql/python-queries","rules":[` +
|
||||
oneRule + `]}]},"results":[],"invocations":[{"executionSuccessful":true}]}]}`
|
||||
if err := checkRecordReport("codeql", report); err != nil {
|
||||
t.Fatalf("a CodeQL run with pack rules must be recorded: %v", err)
|
||||
}
|
||||
empty := `{"runs":[{"tool":{"driver":{"name":"CodeQL"},"extensions":[{"name":"p","rules":[]}]},"results":[]}]}`
|
||||
if err := checkRecordReport("codeql", empty); err == nil {
|
||||
t.Fatal("a CodeQL run with no rules anywhere must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSemgrepExitCodes(t *testing.T) {
|
||||
for _, ok := range []int{0, 1} {
|
||||
if !semgrepRanToCompletion(ok) {
|
||||
t.Errorf("exit %d is a completed run", ok)
|
||||
}
|
||||
}
|
||||
for _, bad := range []int{2, 3, 4, 7, 13, 14, 127} {
|
||||
if semgrepRanToCompletion(bad) {
|
||||
t.Errorf("exit %d must not count as a completed run", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnInlineSuppressionCountsInTheScanOfRecordOnly(t *testing.T) {
|
||||
report := sarif(oneRule,
|
||||
`{"ruleId":"python.lang.security.audit.eval","ruleIndex":0,"level":"error","suppressions":[{"kind":"inSource"}]}`,
|
||||
`{"executionSuccessful":true}`)
|
||||
total, blocking, _, parsed := tallyFindings(report, true)
|
||||
if !parsed || total != 1 || blocking != 1 {
|
||||
t.Fatalf("scan of record: total=%d blocking=%d parsed=%v, want 1/1/true", total, blocking, parsed)
|
||||
}
|
||||
// Every other caller keeps honouring it, as before.
|
||||
total, blocking, _, _ = tallyFindings(report, false)
|
||||
if total != 0 || blocking != 0 {
|
||||
t.Fatalf("outside the scan of record: total=%d blocking=%d, want 0/0", total, blocking)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
// The ruleset a SAST run used, recorded with the scan (#2908, ADR-0093 §8).
|
||||
//
|
||||
// `--rules-dir` accepts any directory and a SARIF report does not say which
|
||||
// rule files produced it, so a near-empty rules directory would post a clean
|
||||
// scan of record. The module therefore digests the directory it mounted and
|
||||
// posts it as `report_data.sast_ruleset_digest`; the platform compares it with
|
||||
// the digest IT computes from the pack it ships (`catalog/sast-rules/rules`,
|
||||
// `apps/api/app/security/services/sast_ruleset.py`) and never with a value the
|
||||
// caller supplies. The two implementations must agree byte for byte: the test
|
||||
// vector in ruleset_test.go is the same one the Python test pins.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"dagger/sast-scan/internal/dagger"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// rulesetReportKey is the report_data key the digest is posted under
|
||||
// (`security_verdict.SAST_RULESET_KEY` on the platform).
|
||||
const rulesetReportKey = "sast_ruleset_digest"
|
||||
|
||||
// rulesetDigestPrefix names the algorithm, as an image digest does.
|
||||
const rulesetDigestPrefix = "sha256:"
|
||||
|
||||
// rulesetDigest is the digest of a rules tree given as relative POSIX path ->
|
||||
// file bytes. Deterministic: for each path in byte order, the line
|
||||
// `<path>\x00<hex sha256 of the bytes>\n`, and the sha256 of all the lines.
|
||||
// A file's name is part of the digest (renaming a rule file changes it) and
|
||||
// the NUL separator keeps a path from running into its hash. An empty tree has
|
||||
// a digest too (the sha256 of nothing); it is not the platform pack's.
|
||||
//
|
||||
// A path with any hidden segment (".gitkeep", ".github/x.yaml") is skipped, as
|
||||
// the platform does: semgrep does not load hidden config files, and the two
|
||||
// listings (dagger Glob here, Path.rglob in Python) need not agree on whether
|
||||
// they list dotfiles.
|
||||
func rulesetDigest(files map[string][]byte) string {
|
||||
paths := make([]string, 0, len(files))
|
||||
for p := range files {
|
||||
if isHiddenPath(p) {
|
||||
continue
|
||||
}
|
||||
paths = append(paths, p)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
h := sha256.New()
|
||||
for _, p := range paths {
|
||||
sum := sha256.Sum256(files[p])
|
||||
h.Write([]byte(p))
|
||||
h.Write([]byte{0})
|
||||
h.Write([]byte(hex.EncodeToString(sum[:])))
|
||||
h.Write([]byte{'\n'})
|
||||
}
|
||||
return rulesetDigestPrefix + hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
// isHiddenPath reports whether any segment of a relative path starts with ".".
|
||||
func isHiddenPath(p string) bool {
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if strings.HasPrefix(part, ".") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// rulesetDigestOf digests every regular file under dir, the directory semgrep
|
||||
// was given. A listing or read error is an error: a scan whose ruleset cannot
|
||||
// be named is not posted with a guessed one.
|
||||
func rulesetDigestOf(ctx context.Context, dir *dagger.Directory) (string, error) {
|
||||
entries, err := dir.Glob(ctx, "**/*")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("list the rules directory: %w", err)
|
||||
}
|
||||
files := make(map[string][]byte, len(entries))
|
||||
for _, e := range entries {
|
||||
// Directories are listed with a trailing slash; their files are listed
|
||||
// on their own.
|
||||
if strings.HasSuffix(e, "/") {
|
||||
continue
|
||||
}
|
||||
body, err := dir.File(e).Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read rule file %s: %w", e, err)
|
||||
}
|
||||
files[strings.TrimPrefix(e, "./")] = []byte(body)
|
||||
}
|
||||
return rulesetDigest(files), nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
// The ruleset digest (#2908). Written on the build VM, not run there (owner
|
||||
// decision 2026-10-11).
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The cross-language vector: apps/api/tests/test_sast_ruleset_pin.py pins the
|
||||
// SAME files to the SAME digest. If either side changes its encoding, one of
|
||||
// the two tests fails.
|
||||
const crossLanguageVector = "sha256:8fd4f707f97ff1e9f9d445830c1eaff610c1db0e96c3948039ebcbf7b04c1700"
|
||||
|
||||
func vectorFiles() map[string][]byte {
|
||||
return map[string][]byte{
|
||||
"python.yaml": []byte("rules: []\n"),
|
||||
"nested/go.yaml": []byte("x"),
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRulesetDigestMatchesThePlatformsEncoding(t *testing.T) {
|
||||
if got := rulesetDigest(vectorFiles()); got != crossLanguageVector {
|
||||
t.Fatalf("digest %s, want %s (the platform computes the pack's digest the same way)", got, crossLanguageVector)
|
||||
}
|
||||
}
|
||||
|
||||
// Hidden paths are not part of the digest on either side (#2908 review): the
|
||||
// Python twin pins the same vector with the same dotfiles added.
|
||||
func TestHiddenPathsAreNotPartOfTheDigest(t *testing.T) {
|
||||
files := vectorFiles()
|
||||
files[".gitkeep"] = []byte("")
|
||||
files[".hidden/x.yaml"] = []byte("y")
|
||||
files["nested/.keep"] = []byte("z")
|
||||
if got := rulesetDigest(files); got != crossLanguageVector {
|
||||
t.Fatalf("dotfiles changed the digest: %s, want %s", got, crossLanguageVector)
|
||||
}
|
||||
// Legal direction: a visible file with a dot inside its name still counts.
|
||||
files["a.b.yaml"] = []byte("rules: []\n")
|
||||
if rulesetDigest(files) == crossLanguageVector {
|
||||
t.Fatal("a visible rule file named a.b.yaml was skipped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRulesetDigestIsDeterministic(t *testing.T) {
|
||||
a := rulesetDigest(vectorFiles())
|
||||
for i := 0; i < 20; i++ {
|
||||
if b := rulesetDigest(vectorFiles()); b != a {
|
||||
t.Fatalf("map order changed the digest: %s vs %s", a, b)
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(a, "sha256:") || len(a) != len("sha256:")+64 {
|
||||
t.Fatalf("digest %q is not sha256:<64 hex>", a)
|
||||
}
|
||||
}
|
||||
|
||||
// Negative direction: every way of running fewer or other rules changes it.
|
||||
func TestAnyChangeToTheRulesetChangesTheDigest(t *testing.T) {
|
||||
base := rulesetDigest(vectorFiles())
|
||||
cases := map[string]map[string][]byte{
|
||||
"a file dropped": {"python.yaml": []byte("rules: []\n")},
|
||||
"a file edited": {"python.yaml": []byte("rules: [] \n"), "nested/go.yaml": []byte("x")},
|
||||
"a file renamed": {"python2.yaml": []byte("rules: []\n"), "nested/go.yaml": []byte("x")},
|
||||
"a file added": {"python.yaml": []byte("rules: []\n"), "nested/go.yaml": []byte("x"), "extra.yaml": nil},
|
||||
"an empty ruleset": {},
|
||||
// The separator: path and hash cannot run into each other.
|
||||
"bytes moved into the name": {"python.yamlr": []byte("ules: []\n"), "nested/go.yaml": []byte("x")},
|
||||
}
|
||||
for name, files := range cases {
|
||||
if rulesetDigest(files) == base {
|
||||
t.Errorf("%s: digest unchanged", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRulesetDigestIsPosted(t *testing.T) {
|
||||
// postResults is not callable without an engine; the payload key is the
|
||||
// contract the platform reads (security_verdict.SAST_RULESET_KEY).
|
||||
if rulesetReportKey != "sast_ruleset_digest" {
|
||||
t.Fatalf("report_data key %q changed; the platform reads sast_ruleset_digest", rulesetReportKey)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
// Semgrep's command line, kept apart from the Dagger calls so it can be tested
|
||||
// without an engine (ADR-0093 §8, WP-09).
|
||||
//
|
||||
// Two modes:
|
||||
//
|
||||
// - rules from the `sast-rules` content pack (the scan of record, air-gap
|
||||
// safe): `--config=/rules --metrics=off`, never `auto`. Nothing is fetched
|
||||
// from the Semgrep registry and nothing is reported to it.
|
||||
// - no pack given: the legacy `--config=auto`, which fetches the registry
|
||||
// rules (Semgrep Rules License v1.0: the tenant's own internal use, from the
|
||||
// tenant's own CI) and sends the project URL. It cannot run air-gapped.
|
||||
// `--metrics=off` is NOT added here: semgrep refuses that pair outright
|
||||
// ("Cannot create auto config when metrics are off", exit 2), so adding it
|
||||
// would turn every existing pipeline red rather than make it private.
|
||||
|
||||
// semgrepRulesMount is where the pack's rules/ tree is mounted in the container.
|
||||
const semgrepRulesMount = "/rules"
|
||||
|
||||
// semgrepRulesSubdir is the directory of the pack that holds the rule files.
|
||||
// The pack root also carries LICENSES.yaml, which semgrep would try to load as
|
||||
// a rule file, so only this subdirectory is mounted.
|
||||
const semgrepRulesSubdir = "rules"
|
||||
|
||||
// semgrepArgs is the exec line for one semgrep run writing SARIF to sarifPath.
|
||||
//
|
||||
// For the scan of record (disableNosem, ADR-0093 §4, WP-05) it also ignores
|
||||
// inline `nosemgrep` comments: a change could otherwise mark its own finding
|
||||
// as not a finding.
|
||||
func semgrepArgs(sarifPath string, rulesFromPack, disableNosem bool) []string {
|
||||
args := []string{"semgrep", "scan"}
|
||||
if rulesFromPack {
|
||||
args = append(args, "--config="+semgrepRulesMount, "--metrics=off")
|
||||
} else {
|
||||
args = append(args, "--config=auto")
|
||||
}
|
||||
args = append(args, "--error", "--sarif", "--output", sarifPath)
|
||||
if disableNosem {
|
||||
// `--no-git-ignore` too: a committed file listed in the repository's
|
||||
// own .gitignore is still the repository's code, and a .gitignore line
|
||||
// would otherwise drop it from the scan as a .semgrepignore line did.
|
||||
args = append(args, "--disable-nosem", "--no-git-ignore")
|
||||
}
|
||||
return append(args, ".")
|
||||
}
|
||||
|
||||
// semgrepEnv is the environment of a pack run: no metrics and no version
|
||||
// check (both are calls to semgrep.dev, which an air-gapped runner cannot make
|
||||
// and a private one should not). Empty for the legacy `auto` run, for the
|
||||
// reason in the file comment.
|
||||
func semgrepEnv(rulesFromPack bool) [][2]string {
|
||||
if !rulesFromPack {
|
||||
return nil
|
||||
}
|
||||
return [][2]string{
|
||||
{"SEMGREP_SEND_METRICS", "off"},
|
||||
{"SEMGREP_ENABLE_VERSION_CHECK", "0"},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func hasArg(args []string, want string) bool {
|
||||
for _, a := range args {
|
||||
if a == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestPackRunNeverFetchesRegistryRules(t *testing.T) {
|
||||
args := semgrepArgs("/tmp/out.sarif", true, false)
|
||||
for _, a := range args {
|
||||
if strings.Contains(a, "auto") {
|
||||
t.Fatalf("a pack run must never use the registry config, got %q in %v", a, args)
|
||||
}
|
||||
}
|
||||
if !hasArg(args, "--config=/rules") {
|
||||
t.Fatalf("a pack run reads the mounted rules, got %v", args)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackRunAlwaysTurnsMetricsOff(t *testing.T) {
|
||||
args := semgrepArgs("/tmp/out.sarif", true, false)
|
||||
if !hasArg(args, "--metrics=off") {
|
||||
t.Fatalf("--metrics=off missing from %v", args)
|
||||
}
|
||||
env := map[string]string{}
|
||||
for _, kv := range semgrepEnv(true) {
|
||||
env[kv[0]] = kv[1]
|
||||
}
|
||||
if env["SEMGREP_SEND_METRICS"] != "off" || env["SEMGREP_ENABLE_VERSION_CHECK"] != "0" {
|
||||
t.Fatalf("pack run env must disable metrics and the version check, got %v", env)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyRunKeepsAutoWithoutMetricsOff(t *testing.T) {
|
||||
// semgrep exits 2 on `--config=auto --metrics=off`; the legacy path must not
|
||||
// carry the pair (the tightening mutant: always add --metrics=off).
|
||||
args := semgrepArgs("/tmp/out.sarif", false, false)
|
||||
if !hasArg(args, "--config=auto") {
|
||||
t.Fatalf("legacy run lost --config=auto: %v", args)
|
||||
}
|
||||
if hasArg(args, "--metrics=off") {
|
||||
t.Fatalf("semgrep refuses --metrics=off with --config=auto: %v", args)
|
||||
}
|
||||
if len(semgrepEnv(false)) != 0 {
|
||||
t.Fatalf("legacy run must not set the metrics env either")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBothModesWriteSarifAndKeepFindingsAsExitCode(t *testing.T) {
|
||||
for _, pack := range []bool{true, false} {
|
||||
for _, record := range []bool{true, false} {
|
||||
args := semgrepArgs("/tmp/x.sarif", pack, record)
|
||||
if args[0] != "semgrep" || args[1] != "scan" || args[len(args)-1] != "." {
|
||||
t.Fatalf("unexpected shape %v", args)
|
||||
}
|
||||
for _, want := range []string{"--sarif", "--error", "/tmp/x.sarif"} {
|
||||
if !hasArg(args, want) {
|
||||
t.Fatalf("%s missing from %v", want, args)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The scan of record ignores in-repo suppressions in BOTH rule modes, and no
|
||||
// other run does (ADR-0093 §4, WP-05).
|
||||
func TestScanOfRecordDisablesNosemInBothModes(t *testing.T) {
|
||||
for _, pack := range []bool{true, false} {
|
||||
args := semgrepArgs("/tmp/x.sarif", pack, true)
|
||||
for _, want := range []string{"--disable-nosem", "--no-git-ignore"} {
|
||||
if !hasArg(args, want) {
|
||||
t.Fatalf("scan of record (pack=%v) lost %s: %v", pack, want, args)
|
||||
}
|
||||
}
|
||||
other := semgrepArgs("/tmp/x.sarif", pack, false)
|
||||
if hasArg(other, "--disable-nosem") || hasArg(other, "--no-git-ignore") {
|
||||
t.Fatalf("a non-record run (pack=%v) must keep nosemgrep: %v", pack, other)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user