chore: publish IntegraCI build modules a11ec75d3e09

This commit is contained in:
dhimaz0445 committed 2026-11-11 03:41:55 +00:00
1 parent 694710104a
commit 3c2b80914e
78 files changed
+4982 -405

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
{
"name": "prebuild-check",
"engineVersion": "v0.21.11",
"sdk": {
"source": "go"
},
"source": ".",
"include": [
"./main.go",
"./lockfile.go",
"./pinning.go",
"./report.go"
]
}
+324
View File
@@ -0,0 +1,324 @@
package main
// Lockfile present-and-in-sync check (ADR-0093 §10 item 2, WP-13 13b).
//
// Pure: it judges a map of repository-relative path -> file content, so it is
// tested without a Dagger engine. main.go reads the files from the mounted
// source and posts the result.
//
// Outcomes (the ADR-0093 §10 rule):
//
// not_applicable no package ecosystem in the repository (a static site): passes
// ran every declared ecosystem was checked; findings list what failed
//
// "No lockfile for a declared ecosystem" is a FINDING (lockfile_missing), never
// a pass and never could_not_run: the check ran and the lockfile is not there.
import (
"encoding/json"
"path"
"sort"
"strings"
)
// LockfileFinding is one lockfile problem. Kind is lockfile_missing,
// lockfile_out_of_sync or lockfile_changed_without_manifest.
type LockfileFinding struct {
Kind string `json:"kind"`
Ecosystem string `json:"ecosystem"`
Manifest string `json:"manifest"`
Lockfile string `json:"lockfile,omitempty"`
Detail string `json:"detail,omitempty"`
}
// LockfileReport is what the check posts (report_data of scan_type lockfile).
type LockfileReport struct {
Outcome string `json:"outcome"`
Ecosystems []string `json:"ecosystems"`
Findings []LockfileFinding `json:"lockfile_findings"`
}
// skippedDir reports whether a path lies in a vendored / generated tree whose
// manifests are not the repository's own.
func skippedDir(p string) bool {
for _, seg := range strings.Split(p, "/") {
switch seg {
case "node_modules", "vendor", ".git", "dist", "build", "target", ".venv", "venv", "__pycache__":
return true
}
}
return false
}
func exists(files map[string]string, p string) bool {
_, ok := files[p]
return ok
}
func firstExisting(files map[string]string, dir string, names ...string) string {
for _, n := range names {
p := path.Join(dir, n)
if exists(files, p) {
return p
}
}
return ""
}
// pythonLockfiles returns the lockfile a pyproject.toml's declared tool needs,
// or "" when it declares no locking tool (PEP 621 metadata alone).
func pythonTool(pyproject string) (tool, lock string) {
switch {
case strings.Contains(pyproject, "[tool.poetry"):
return "poetry", "poetry.lock"
case strings.Contains(pyproject, "[tool.uv"):
return "uv", "uv.lock"
case strings.Contains(pyproject, "[tool.pdm"):
return "pdm", "pdm.lock"
}
return "", ""
}
// npmManifestDeps returns the dependency names a package.json declares.
func npmManifestDeps(content string) (map[string]bool, bool) {
var pkg struct {
Dependencies map[string]any `json:"dependencies"`
DevDependencies map[string]any `json:"devDependencies"`
}
if err := json.Unmarshal([]byte(content), &pkg); err != nil {
return nil, false
}
out := map[string]bool{}
for k := range pkg.Dependencies {
out[k] = true
}
for k := range pkg.DevDependencies {
out[k] = true
}
return out, true
}
// npmLockRootDeps returns the root dependency names a package-lock.json v2/v3
// records (packages[""]), and false when the lock has no such section (v1).
func npmLockRootDeps(content string) (map[string]bool, bool) {
var lock struct {
Packages map[string]struct {
Dependencies map[string]any `json:"dependencies"`
DevDependencies map[string]any `json:"devDependencies"`
} `json:"packages"`
}
if err := json.Unmarshal([]byte(content), &lock); err != nil {
return nil, false
}
root, ok := lock.Packages[""]
if !ok {
return nil, false
}
out := map[string]bool{}
for k := range root.Dependencies {
out[k] = true
}
for k := range root.DevDependencies {
out[k] = true
}
return out, true
}
func setDiff(a, b map[string]bool) []string {
var out []string
for k := range a {
if !b[k] {
out = append(out, k)
}
}
sort.Strings(out)
return out
}
func goModRequires(content string) bool {
for _, line := range strings.Split(content, "\n") {
l := strings.TrimSpace(line)
if strings.HasPrefix(l, "require ") || l == "require (" || strings.HasPrefix(l, "require(") {
return true
}
}
return false
}
// CheckLockfiles judges every manifest under files. changed lists the
// repository-relative paths the change touched (the diff range); nil when the
// job does not know it, which skips only the changed-without-manifest rule.
func CheckLockfiles(files map[string]string, changed []string) LockfileReport {
ecos := map[string]bool{}
var findings []LockfileFinding
paths := make([]string, 0, len(files))
for p := range files {
if !skippedDir(p) {
paths = append(paths, p)
}
}
sort.Strings(paths)
// manifest -> lockfile actually used, for the changed-without-manifest rule.
pairs := map[string]string{}
missing := func(eco, manifest, lock string) {
findings = append(findings, LockfileFinding{
Kind: "lockfile_missing", Ecosystem: eco, Manifest: manifest, Lockfile: lock,
})
}
for _, p := range paths {
dir, base := path.Dir(p), path.Base(p)
switch base {
case "package.json":
ecos["npm"] = true
lock := firstExisting(files, dir, "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml", "bun.lockb", "bun.lock")
if lock == "" {
// A workspace member is locked by the root's lockfile.
if root := firstExisting(files, ".", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "bun.lock"); root != "" && dir != "." {
pairs[p] = root
continue
}
missing("npm", p, path.Join(dir, "package-lock.json"))
continue
}
pairs[p] = lock
if path.Base(lock) == "package-lock.json" {
want, okM := npmManifestDeps(files[p])
have, okL := npmLockRootDeps(files[lock])
if okM && okL {
if add, drop := setDiff(want, have), setDiff(have, want); len(add)+len(drop) > 0 {
findings = append(findings, LockfileFinding{
Kind: "lockfile_out_of_sync", Ecosystem: "npm", Manifest: p, Lockfile: lock,
Detail: "not in lockfile: " + strings.Join(add, ",") + "; only in lockfile: " + strings.Join(drop, ","),
})
}
}
}
case "pyproject.toml":
tool, lockName := pythonTool(files[p])
if tool == "" {
continue
}
ecos["pypi"] = true
if lock := firstExisting(files, dir, lockName); lock != "" {
pairs[p] = lock
} else {
missing("pypi", p, path.Join(dir, lockName))
}
case "requirements.in":
ecos["pypi"] = true
if lock := firstExisting(files, dir, "requirements.txt"); lock != "" {
pairs[p] = lock
} else {
missing("pypi", p, path.Join(dir, "requirements.txt"))
}
case "Pipfile":
ecos["pypi"] = true
if lock := firstExisting(files, dir, "Pipfile.lock"); lock != "" {
pairs[p] = lock
} else {
missing("pypi", p, path.Join(dir, "Pipfile.lock"))
}
case "requirements.txt":
// Its own lock when every line is pinned; pinning is the pinning check's job.
ecos["pypi"] = true
case "go.mod":
ecos["go"] = true
if !goModRequires(files[p]) {
continue
}
if lock := firstExisting(files, dir, "go.sum"); lock != "" {
pairs[p] = lock
} else {
missing("go", p, path.Join(dir, "go.sum"))
}
case "Cargo.toml":
ecos["cargo"] = true
// A workspace member is locked at the workspace root.
if lock := firstExisting(files, dir, "Cargo.lock"); lock != "" {
pairs[p] = lock
} else if !exists(files, "Cargo.lock") {
missing("cargo", p, path.Join(dir, "Cargo.lock"))
}
case "composer.json":
ecos["composer"] = true
if lock := firstExisting(files, dir, "composer.lock"); lock != "" {
pairs[p] = lock
} else {
missing("composer", p, path.Join(dir, "composer.lock"))
}
case "Gemfile":
ecos["ruby"] = true
if lock := firstExisting(files, dir, "Gemfile.lock"); lock != "" {
pairs[p] = lock
} else {
missing("ruby", p, path.Join(dir, "Gemfile.lock"))
}
case "build.gradle", "build.gradle.kts":
// Gradle locking is opt-in ("where used"): only a build that turned
// dependency locking on needs gradle.lockfile.
if !strings.Contains(files[p], "dependencyLocking") {
continue
}
ecos["gradle"] = true
if lock := firstExisting(files, dir, "gradle.lockfile"); lock != "" {
pairs[p] = lock
} else {
missing("gradle", p, path.Join(dir, "gradle.lockfile"))
}
}
}
if changed != nil {
touched := map[string]bool{}
for _, c := range changed {
touched[strings.TrimPrefix(strings.TrimSpace(c), "./")] = true
}
manifests := make([]string, 0, len(pairs))
for m := range pairs {
manifests = append(manifests, m)
}
sort.Strings(manifests)
for _, m := range manifests {
lock := pairs[m]
if touched[lock] && !touched[m] {
findings = append(findings, LockfileFinding{
Kind: "lockfile_changed_without_manifest", Ecosystem: ecoOf(path.Base(m)),
Manifest: m, Lockfile: lock,
})
}
}
}
report := LockfileReport{Outcome: "ran", Findings: findings}
for e := range ecos {
report.Ecosystems = append(report.Ecosystems, e)
}
sort.Strings(report.Ecosystems)
if len(report.Ecosystems) == 0 {
report.Outcome = "not_applicable"
}
if report.Findings == nil {
report.Findings = []LockfileFinding{}
}
return report
}
func ecoOf(manifest string) string {
switch manifest {
case "package.json":
return "npm"
case "pyproject.toml", "requirements.in", "Pipfile":
return "pypi"
case "go.mod":
return "go"
case "Cargo.toml":
return "cargo"
case "composer.json":
return "composer"
case "Gemfile":
return "ruby"
}
return "gradle"
}
+447
View File
@@ -0,0 +1,447 @@
// 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, " ")
}
+142
View File
@@ -0,0 +1,142 @@
package main
// Dependency pinning check (ADR-0093 §10 item 7, WP-13 13e). Pure.
//
// Findings (each only ever WARNS in the verdict):
//
// floating_range a package.json version range (^, ~, *, x, >, >=, latest)
// or a requirements.txt line without ==
// unpinned_from a Dockerfile FROM that is not pinned to an @sha256 digest
// unpinned_uses a GitHub Actions `uses:` not pinned to a 40-hex commit SHA
import (
"encoding/json"
"path"
"regexp"
"sort"
"strings"
)
// PinningFinding is one unpinned reference.
type PinningFinding struct {
Kind string `json:"kind"`
File string `json:"file"`
Line int `json:"line,omitempty"`
Ref string `json:"ref"`
}
var (
fromRe = regexp.MustCompile(`(?i)^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)(?:\s+AS\s+(\S+))?`)
usesRe = regexp.MustCompile(`^\s*-?\s*uses:\s*["']?([^"'\s#]+)`)
shaRe = regexp.MustCompile(`@[0-9a-f]{40}$`)
digestRe = regexp.MustCompile(`@sha256:[0-9a-f]{64}$`)
npmExactRe = regexp.MustCompile(`^v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$`)
reqPinnedRe = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*(?:\[[^\]]*\])?\s*===?\s*[^\s,;*]+\s*(?:;.*)?$`)
)
func isDockerfile(base string) bool {
return base == "Dockerfile" || strings.HasPrefix(base, "Dockerfile.") || strings.HasSuffix(base, ".Dockerfile") || base == "Containerfile"
}
func isWorkflow(p string) bool {
return strings.HasPrefix(p, ".github/workflows/") && (strings.HasSuffix(p, ".yml") || strings.HasSuffix(p, ".yaml"))
}
// npmRefPinned reports whether a package.json value names one exact version.
// Non-registry refs (git, file, link, workspace, npm: aliases with exact
// versions) are not ranges and are left to the lockfile.
func npmRefPinned(v string) bool {
v = strings.TrimSpace(v)
for _, p := range []string{"file:", "link:", "workspace:", "git+", "git:", "github:", "http:", "https:", "portal:", "patch:"} {
if strings.HasPrefix(v, p) {
return true
}
}
if strings.HasPrefix(v, "npm:") {
if i := strings.LastIndex(v, "@"); i > 0 {
v = v[i+1:]
}
}
return npmExactRe.MatchString(v)
}
// CheckPinning scans the given files (repository-relative path -> content).
func CheckPinning(files map[string]string) []PinningFinding {
paths := make([]string, 0, len(files))
for p := range files {
if !skippedDir(p) {
paths = append(paths, p)
}
}
sort.Strings(paths)
out := []PinningFinding{}
for _, p := range paths {
content, base := files[p], path.Base(p)
switch {
case isDockerfile(base):
stages := map[string]bool{}
for i, line := range strings.Split(content, "\n") {
m := fromRe.FindStringSubmatch(line)
if m == nil {
continue
}
ref := m[1]
// scratch, an EARLIER build stage, or a build-arg image (judged
// where the arg is set) are not registry pulls. Stages are
// recorded after the check, so `FROM x AS x` is still a pull.
local := strings.EqualFold(ref, "scratch") || stages[strings.ToLower(ref)] || strings.Contains(ref, "$")
if m[2] != "" {
stages[strings.ToLower(m[2])] = true
}
if !local && !digestRe.MatchString(ref) {
out = append(out, PinningFinding{Kind: "unpinned_from", File: p, Line: i + 1, Ref: ref})
}
}
case isWorkflow(p):
for i, line := range strings.Split(content, "\n") {
m := usesRe.FindStringSubmatch(line)
if m == nil {
continue
}
ref := m[1]
if strings.HasPrefix(ref, "./") || (strings.HasPrefix(ref, "docker://") && digestRe.MatchString(ref)) {
continue
}
if !shaRe.MatchString(ref) {
out = append(out, PinningFinding{Kind: "unpinned_uses", File: p, Line: i + 1, Ref: ref})
}
}
case base == "package.json":
var pkg struct {
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}
if json.Unmarshal([]byte(content), &pkg) != nil {
continue
}
for _, deps := range []map[string]string{pkg.Dependencies, pkg.DevDependencies} {
names := make([]string, 0, len(deps))
for n := range deps {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
if !npmRefPinned(deps[n]) {
out = append(out, PinningFinding{Kind: "floating_range", File: p, Ref: n + "@" + deps[n]})
}
}
}
case base == "requirements.txt":
for i, raw := range strings.Split(content, "\n") {
line := strings.TrimSpace(strings.SplitN(raw, "#", 2)[0])
if line == "" || strings.HasPrefix(line, "-") {
continue
}
if !reqPinnedRe.MatchString(line) {
out = append(out, PinningFinding{Kind: "floating_range", File: p, Line: i + 1, Ref: line})
}
}
}
}
return out
}
+120
View File
@@ -0,0 +1,120 @@
package main
import (
"strings"
"testing"
)
func kinds(r LockfileReport) []string {
var out []string
for _, f := range r.Findings {
out = append(out, f.Kind+":"+f.Manifest)
}
return out
}
// Mutant: treat "no lockfile" as a pass -> this test fails.
func TestPoetryWithoutLockIsMissing(t *testing.T) {
r := CheckLockfiles(map[string]string{"pyproject.toml": "[tool.poetry]\nname='x'\n"}, nil)
if r.Outcome != "ran" || len(r.Findings) != 1 || r.Findings[0].Kind != "lockfile_missing" {
t.Fatalf("got %+v", r)
}
}
// Mutant: report "no ecosystem" as could_not_run -> this test fails.
func TestStaticSiteIsNotApplicable(t *testing.T) {
r := CheckLockfiles(map[string]string{"index.html": "<html/>", "css/site.css": ""}, nil)
if r.Outcome != "not_applicable" || len(r.Findings) != 0 {
t.Fatalf("got %+v", r)
}
}
func TestLockedEcosystemsPass(t *testing.T) {
files := map[string]string{
"pyproject.toml": "[tool.uv]\n", "uv.lock": "",
"go.mod": "module x\nrequire github.com/a/b v1.0.0\n", "go.sum": "",
"Cargo.toml": "", "Cargo.lock": "",
"web/package.json": `{"dependencies":{"react":"18.3.1"}}`,
"web/package-lock.json": `{"packages":{"":{"dependencies":{"react":"18.3.1"}}}}`,
}
if r := CheckLockfiles(files, nil); len(r.Findings) != 0 {
t.Fatalf("unexpected findings %v", kinds(r))
}
}
func TestNpmLockOutOfSync(t *testing.T) {
files := map[string]string{
"package.json": `{"dependencies":{"react":"18.3.1","axios":"1.7.0"}}`,
"package-lock.json": `{"packages":{"":{"dependencies":{"react":"18.3.1"}}}}`,
}
r := CheckLockfiles(files, nil)
if len(r.Findings) != 1 || r.Findings[0].Kind != "lockfile_out_of_sync" || !strings.Contains(r.Findings[0].Detail, "axios") {
t.Fatalf("got %+v", r.Findings)
}
}
func TestLockChangedWithoutManifest(t *testing.T) {
files := map[string]string{"composer.json": "{}", "composer.lock": "{}"}
r := CheckLockfiles(files, []string{"composer.lock"})
if len(r.Findings) != 1 || r.Findings[0].Kind != "lockfile_changed_without_manifest" {
t.Fatalf("got %+v", r.Findings)
}
if r := CheckLockfiles(files, []string{"composer.lock", "composer.json"}); len(r.Findings) != 0 {
t.Fatalf("both changed is in sync: %+v", r.Findings)
}
}
func TestVendoredManifestsAreIgnored(t *testing.T) {
r := CheckLockfiles(map[string]string{"node_modules/x/package.json": "{}"}, nil)
if r.Outcome != "not_applicable" {
t.Fatalf("got %+v", r)
}
}
func TestGoModWithoutRequiresNeedsNoSum(t *testing.T) {
if r := CheckLockfiles(map[string]string{"go.mod": "module x\n\ngo 1.25\n"}, nil); len(r.Findings) != 0 {
t.Fatalf("got %+v", r.Findings)
}
}
func TestPinning(t *testing.T) {
files := map[string]string{
"Dockerfile": "FROM golang:1.25 AS build\nFROM build AS test\nFROM gcr.io/distroless/static@sha256:" +
strings.Repeat("a", 64) + "\nFROM scratch\nFROM ${BASE}\n",
".github/workflows/ci.yml": "steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-go@" +
strings.Repeat("b", 40) + "\n - uses: ./local-action\n",
"package.json": `{"dependencies":{"react":"^18.3.1","axios":"1.7.0","x":"workspace:*"}}`,
"requirements.txt": "requests==2.32.3\nflask>=3\n# comment\n-r other.txt\n",
}
got := map[string]bool{}
for _, f := range CheckPinning(files) {
got[f.Kind+" "+f.Ref] = true
}
want := []string{
"unpinned_from golang:1.25",
"unpinned_uses actions/checkout@v4",
"floating_range react@^18.3.1",
"floating_range flask>=3",
}
for _, w := range want {
if !got[w] {
t.Errorf("missing finding %q in %v", w, got)
}
}
if len(got) != len(want) {
t.Errorf("unexpected findings: %v", got)
}
}
func TestSpectralCounts(t *testing.T) {
c, err := spectralCounts(`[{"severity":0},{"severity":1},{"severity":3}]`)
if err != nil || c != [3]int{1, 1, 1} {
t.Fatalf("got %v %v", c, err)
}
if c, err := spectralCounts("[]"); err != nil || c != [3]int{} {
t.Fatalf("clean: %v %v", c, err)
}
if _, err := spectralCounts("Error: spectral crashed"); err == nil {
t.Fatal("an unreadable report must be could_not_run, not a clean lint")
}
}
+40
View File
@@ -0,0 +1,40 @@
package main
import (
"encoding/json"
"fmt"
"sort"
)
// spectralCounts reads spectral's JSON report: [errors, warnings, info+hint].
// An empty report is a clean lint ("[]"); anything not a JSON array means
// spectral did not produce its report, which is an error (could_not_run).
func spectralCounts(report string) ([3]int, error) {
var out [3]int
var results []struct {
Severity int `json:"severity"`
}
if err := json.Unmarshal([]byte(report), &results); err != nil {
return out, fmt.Errorf("spectral report unreadable: %w", err)
}
for _, r := range results {
switch r.Severity {
case 0:
out[0]++
case 1:
out[1]++
default:
out[2]++
}
}
return out, nil
}
func sortedKeys(m map[string]string) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}