Files
integraci-dagger-modules/prebuild-check/main.go
T

448 lines
15 KiB
Go

// Package main implements the IntegraCI prebuild-check Dagger module.
//
// The pre-build checklist of ADR-0093 §10 that had no module (WP-13):
//
// lockfile item 2: a lockfile present and in sync per ecosystem (13b)
// pinning item 7: floating ranges, unpinned FROM, unpinned uses: (13e)
// manifests item 7: the dependency manifests, posted to the PLATFORM's
// typosquat check (POST /api/v1/supply-chain/dependency-scan);
// the platform decides, the job does not (13e)
// api-lint item 6: spectral over an OpenAPI document with the
// api-rulesets content pack (13d)
// tests item 5: a test report's counts and coverage (13f)
//
// No function fails the pipeline on what it FOUND: each posts a scan row and
// the platform's security verdict decides (ADR-0093 §10, "no item fails the
// pipeline on its own exit code"). A check that applies and could not execute
// posts outcome=could_not_run, which the verdict reads as unknown, never pass.
//
// Engines: spectral (stoplight/spectral, Apache-2.0) only. Nothing copyleft.
//
// Usage (from the analysis job; WP-05 renders the calls):
//
// dagger call lockfile --source . --api-url $API --token env:TOKEN --service-id $SVC --version $SHA
// dagger call pinning --source . --api-url $API --token env:TOKEN --service-id $SVC --version $SHA
// dagger call manifests --source . --api-url $API --token env:TOKEN --service-id $SVC --version $SHA
// dagger call api-lint --source . --rulesets ./rulesets --api-url $API --token env:TOKEN --service-id $SVC --version $SHA
package main
import (
"bytes"
"context"
"dagger/prebuild-check/internal/dagger"
"encoding/json"
"errors"
"fmt"
"net/http"
"path"
"strings"
"time"
)
// PrebuildCheck is the IntegraCI pre-build checklist module.
type PrebuildCheck struct{}
// CheckResult is what each function returns to the pipeline (for its log).
type CheckResult struct {
Check string `json:"check"`
Outcome string `json:"outcome"` // ran | not_applicable | could_not_run
Findings int `json:"findings"`
Posted bool `json:"posted"`
Error string `json:"error,omitempty"`
}
const spectralImage = "stoplight/spectral:6.14.2"
// maxFileBytes bounds what is read per manifest; a larger "manifest" is not one.
const maxFileBytes = 2 << 20
var manifestGlobs = []string{
"**/package.json", "**/package-lock.json", "**/npm-shrinkwrap.json", "**/yarn.lock",
"**/pnpm-lock.yaml", "**/bun.lock", "**/bun.lockb",
"**/pyproject.toml", "**/poetry.lock", "**/uv.lock", "**/pdm.lock",
"**/requirements.in", "**/requirements.txt", "**/Pipfile", "**/Pipfile.lock",
"**/go.mod", "**/go.sum", "**/Cargo.toml", "**/Cargo.lock",
"**/composer.json", "**/composer.lock", "**/Gemfile", "**/Gemfile.lock",
"**/build.gradle", "**/build.gradle.kts", "**/gradle.lockfile",
}
var pinningGlobs = []string{
"**/Dockerfile", "**/Dockerfile.*", "**/*.Dockerfile", "**/Containerfile",
".github/workflows/*.yml", ".github/workflows/*.yaml",
"**/package.json", "**/requirements.txt",
}
var specGlobs = []string{
"openapi.yaml", "openapi.yml", "openapi.json",
"**/openapi*.yaml", "**/openapi*.yml", "**/openapi*.json",
"**/swagger.yaml", "**/swagger.yml", "**/swagger.json",
}
// readFiles collects the files matching globs (deduplicated, vendored trees
// skipped). A read error is returned: the caller posts could_not_run.
func readFiles(ctx context.Context, source *dagger.Directory, globs []string, contents bool) (map[string]string, error) {
out := map[string]string{}
for _, g := range globs {
matches, err := source.Glob(ctx, g)
if err != nil {
return nil, fmt.Errorf("glob %s: %w", g, err)
}
for _, m := range matches {
m = strings.TrimPrefix(m, "./")
if _, seen := out[m]; seen || skippedDir(m) {
continue
}
if !contents || strings.HasSuffix(m, ".lockb") {
out[m] = ""
continue
}
f := source.File(m)
size, err := f.Size(ctx)
if err != nil {
return nil, fmt.Errorf("stat %s: %w", m, err)
}
if size > maxFileBytes {
out[m] = ""
continue
}
c, err := f.Contents(ctx)
if err != nil {
return nil, fmt.Errorf("read %s: %w", m, err)
}
out[m] = c
}
}
return out, nil
}
// errChangedUnknown is the could_not_run reason when the caller had no range.
var errChangedUnknown = errors.New("the change's file range could not be computed, so the lockfile-changed-without-manifest rule was not judged")
func splitChanged(changed string) []string {
if strings.TrimSpace(changed) == "" {
return nil
}
var out []string
for _, f := range strings.FieldsFunc(changed, func(r rune) bool { return r == '\n' || r == ',' }) {
if f = strings.TrimSpace(f); f != "" {
out = append(out, f)
}
}
return out
}
// Lockfile checks every declared ecosystem has a lockfile in sync with its
// manifest and posts scan_type=lockfile.
func (m *PrebuildCheck) Lockfile(
ctx context.Context,
source *dagger.Directory,
// Paths the change touched (newline or comma separated; the push/PR diff
// range). Empty skips only the "lockfile changed without its manifest" rule.
// +optional
changed string,
// The caller could not compute the change's file range (no usable base
// commit). The "lockfile changed without its manifest" rule then cannot be
// judged, so the row is could_not_run (the verdict reads unknown), never an
// empty list that silently skips the rule (WP-13 review, 2026-11-05).
// +optional
changedUnknown bool,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
) (*CheckResult, error) {
res := &CheckResult{Check: "lockfile"}
files, err := readFiles(ctx, source, manifestGlobs, true)
if err == nil && changedUnknown {
err = errChangedUnknown
}
var report LockfileReport
if err != nil {
res.Outcome, res.Error = "could_not_run", err.Error()
report = LockfileReport{Outcome: "could_not_run", Ecosystems: []string{}, Findings: []LockfileFinding{}}
} else {
report = CheckLockfiles(files, splitChanged(changed))
res.Outcome, res.Findings = report.Outcome, len(report.Findings)
}
data := map[string]any{
"outcome": report.Outcome,
"ecosystems": report.Ecosystems,
"lockfile_findings": report.Findings,
}
if res.Error != "" {
data["error"] = truncate(res.Error, 500)
}
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "lockfile", "integraci-lockfile", len(report.Findings), len(report.Findings), 0, 0, data,
))
}
// Pinning reports floating version ranges, FROM images not pinned to a digest
// and GitHub Actions not pinned to a commit SHA. Posts scan_type=pinning
// (warn-only in the verdict).
func (m *PrebuildCheck) Pinning(
ctx context.Context,
source *dagger.Directory,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
) (*CheckResult, error) {
res := &CheckResult{Check: "pinning", Outcome: "ran"}
findings := []PinningFinding{}
files, err := readFiles(ctx, source, pinningGlobs, true)
if err != nil {
res.Outcome, res.Error = "could_not_run", err.Error()
} else {
findings = CheckPinning(files)
if len(files) == 0 {
res.Outcome = "not_applicable"
}
}
res.Findings = len(findings)
if len(findings) > 500 {
findings = findings[:500]
}
data := map[string]any{"outcome": res.Outcome, "pinning_findings": findings}
if res.Error != "" {
data["error"] = truncate(res.Error, 500)
}
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "pinning", "integraci-pinning", res.Findings, 0, 0, res.Findings, data,
))
}
// Manifests posts each npm / PyPI manifest to the platform's typosquat check.
// The platform decides (and, air-gapped, asks only the tenant's mirror); this
// function never calls a package registry itself.
func (m *PrebuildCheck) Manifests(
ctx context.Context,
source *dagger.Directory,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
) (*CheckResult, error) {
res := &CheckResult{Check: "manifests", Outcome: "ran"}
files, err := readFiles(ctx, source, []string{"**/package.json", "**/requirements.txt"}, true)
if err != nil {
res.Outcome, res.Error = "could_not_run", err.Error()
// Nothing posted: with no platform package-check row of this commit the
// verdict's dependencies family is unknown, never pass.
return res, err
}
posted := 0
for _, p := range sortedKeys(files) {
eco := map[string]string{"package.json": "npm", "requirements.txt": "pypi"}[path.Base(p)]
if eco == "" || files[p] == "" {
continue
}
body := map[string]any{
"ecosystem": eco,
"manifest": files[p],
"service_id": serviceID,
"version": version,
"check_registry": true,
"on_typosquat": "block",
}
if err := m.post(ctx, res, apiURL, token, "/api/v1/supply-chain/dependency-scan", body); err != nil {
return res, err
}
posted++
}
if posted == 0 {
// No npm / PyPI manifest: the platform records not_applicable from the
// lockfile row's ecosystem list (prebuild_verdict), nothing is posted.
res.Outcome = "not_applicable"
}
return res, nil
}
// ApiLint runs spectral over each OpenAPI document with the api-rulesets
// pack's ruleset. No document: an explicit outcome=not_applicable row is
// posted (ADR-0093 §10 item 6), because in enforce the verdict reads a MISSING
// scan of record as unknown, never as "no spec". Posts scan_type=api_lint,
// report-only in the verdict.
func (m *PrebuildCheck) ApiLint(
ctx context.Context,
source *dagger.Directory,
// The api-rulesets content pack directory (catalog/api-rulesets): its
// golden-path/ruleset.yaml is used.
rulesets *dagger.Directory,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
) (*CheckResult, error) {
res := &CheckResult{Check: "api_lint"}
specs, err := readFiles(ctx, source, specGlobs, false)
if err != nil {
res.Outcome, res.Error = "could_not_run", err.Error()
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "api_lint", "spectral", 0, 0, 0, 0,
map[string]any{"outcome": "could_not_run", "error": truncate(err.Error(), 500)},
))
}
if len(specs) == 0 {
// Said out loud: a missing row is "the check did not report", which the
// verdict must not read as green.
res.Outcome = "not_applicable"
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "api_lint", "spectral", 0, 0, 0, 0,
map[string]any{"outcome": "not_applicable"},
))
}
args := []string{"spectral", "lint", "--ruleset", "/rulesets/golden-path/ruleset.yaml", "--format", "json", "--fail-severity", "error", "--quiet"}
args = append(args, sortedKeys(specs)...)
out, err := dag.Container().
From(spectralImage).
WithMountedDirectory("/src", source).
WithMountedDirectory("/rulesets", rulesets).
WithWorkdir("/src").
// spectral exits 1 on lint errors; `|| true` keeps "found something"
// apart from "could not run", which is an unreadable report below.
WithExec([]string{"sh", "-c", shellJoin(args) + " > /tmp/spectral.json || true"}).
File("/tmp/spectral.json").
Contents(ctx)
counts, perr := spectralCounts(out)
if err != nil || perr != nil {
msg := fmt.Sprint(err)
if perr != nil {
msg = perr.Error()
}
res.Outcome, res.Error = "could_not_run", msg
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "api_lint", "spectral", 0, 0, 0, 0,
map[string]any{"outcome": "could_not_run", "error": truncate(msg, 500)},
))
}
res.Outcome = "ran"
res.Findings = counts[0] + counts[1] + counts[2]
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "api_lint", "spectral", res.Findings, 0, counts[0], counts[1]+counts[2],
map[string]any{"outcome": "ran", "specs": sortedKeys(specs)},
))
}
// Tests posts a test report's result (item 5). Run in the branch / pull
// request job, after the tests: they execute the change's code, so never in
// the analysis job. Counts come from the job's own test step.
func (m *PrebuildCheck) Tests(
ctx context.Context,
total int,
failed int,
// +optional
errored int,
// Line coverage in percent; negative = not measured.
// +optional
// +default=-1
coverage float64,
// The test step could not run (no report): posted as could_not_run.
// +optional
couldNotRun bool,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
) (*CheckResult, error) {
res := &CheckResult{Check: "tests", Outcome: "ran", Findings: failed + errored}
data := map[string]any{"outcome": "ran", "tests_total": total, "tests_failed": failed, "tests_errored": errored}
if couldNotRun {
res.Outcome = "could_not_run"
data = map[string]any{"outcome": "could_not_run"}
} else if coverage >= 0 {
data["coverage_percent"] = coverage
}
return res, m.post(ctx, res, apiURL, token, "/api/v1/scans", scanPayload(
serviceID, version, "tests", "integraci-tests", failed+errored, 0, failed+errored, 0, data,
))
}
// ─── helpers ──────────────────────────────────────────────────────────────────
// scanPayload builds a POST /scans body. The severity COLUMNS stay zero on
// purpose: the deploy gate's legacy scan layer reads critical/high/medium of
// EVERY row of a version as CVE counts, so a lint error or a failed test there
// would deny a deploy as a CVE. The counts ride in report_data
// (prebuild_counts), which only the platform's pre-build judge reads.
func scanPayload(serviceID, version, scanType, scanner string, total, critical, high, medium int, data map[string]any) map[string]any {
data["prebuild_counts"] = map[string]int{"critical": critical, "high": high, "medium": medium}
return map[string]any{
"service_id": serviceID,
"version": version,
"scan_type": scanType,
"scanner": scanner,
"report_format": "json",
"findings_count": total,
"report_data": data,
}
}
// post sends body when the API is configured; a local run (no URL or token)
// posts nothing. A failed post is an error: an unposted check must not look
// like a posted pass.
func (m *PrebuildCheck) post(ctx context.Context, res *CheckResult, apiURL string, token *dagger.Secret, route string, body map[string]any) error {
if apiURL == "" || token == nil {
return nil
}
raw, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal %s payload: %w", res.Check, err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(apiURL, "/")+route, bytes.NewReader(raw))
if err != nil {
return fmt.Errorf("build request: %w", err)
}
tok, err := token.Plaintext(ctx)
if err != nil {
return fmt.Errorf("read token secret: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+tok)
resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req)
if err != nil {
return fmt.Errorf("post %s: %w", route, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("post %s returned %d", route, resp.StatusCode)
}
res.Posted = true
return nil
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n]
}
func shellJoin(args []string) string {
q := make([]string, len(args))
for i, a := range args {
q[i] = "'" + strings.ReplaceAll(a, "'", `'"'"'`) + "'"
}
return strings.Join(q, " ")
}