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

+4 -2
View File
@@ -1,11 +1,13 @@
{
"name": "license-scan",
"engineVersion": "v0.21.7",
"engineVersion": "v0.21.11",
"sdk": {
"source": "go"
},
"source": ".",
"include": [
"./main.go"
"./main.go",
"./report.go",
"./scanofrecord.go"
]
}
+2 -2
View File
@@ -50,7 +50,7 @@ func (m *LicenseScan) ScanFs(
}
report, err := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source).
@@ -100,7 +100,7 @@ func (m *LicenseScan) ScanImage(
}
report, err := dag.Container().
From("aquasec/trivy:0.58.1").
From("aquasec/trivy:0.76.1").
// Persist Trivy's vulnerability DB across runs (avoids re-downloading it).
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithExec([]string{
+177
View File
@@ -0,0 +1,177 @@
package main
// Report: the licence LIST, not a decision (ADR-0093 §10 item 3, WP-13 13f).
//
// A tenant's licence posture is its legal decision (OD-15): the tenant's
// allow / deny lists in secure_delivery_policies decide, in the platform's
// security verdict. This function posts what Trivy found, one entry per
// package, and never fails on a licence. The --blocklist of ScanFs/ScanImage is
// IntegraCI's own rule 3 for what IntegraCI bundles and stays as it is for
// that use; it is not the tenant's policy.
//
// dagger call report --source . --api-url $API --token env:TOKEN --service-id $SVC --version $SHA
import (
"bytes"
"context"
"dagger/license-scan/internal/dagger"
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"time"
)
// PackageLicence is one package's licence as Trivy reports it.
type PackageLicence struct {
Package string `json:"package"`
License string `json:"license"`
}
// ReportResult is what Report returns.
type ReportResult struct {
Outcome string `json:"outcome"` // ran | could_not_run
Licences []PackageLicence `json:"licenses"`
Posted bool `json:"posted"`
Error string `json:"error,omitempty"`
// Suppression files the scan of record removed from the scanned copy.
IgnoredSuppressions []string `json:"ignored_suppressions,omitempty"`
}
// licenceArgs is the `trivy fs --scanners license` argv; the scan of record
// adds trustedConfigArgs before the target.
func licenceArgs(scanOfRecord bool) []string {
return withTrustedConfig([]string{
"trivy", "fs", "--scanners", "license", "--format", "json",
"--output", "/tmp/license-report.json", "--exit-code", "0", ".",
}, scanOfRecord)
}
// parseLicences reads `trivy fs --scanners license --format json` output.
func parseLicences(report string) ([]PackageLicence, error) {
var doc struct {
Results []struct {
Licenses []struct {
PkgName string `json:"PkgName"`
Name string `json:"Name"`
} `json:"Licenses"`
} `json:"Results"`
}
if err := json.Unmarshal([]byte(report), &doc); err != nil {
return nil, fmt.Errorf("trivy licence report unreadable: %w", err)
}
seen := map[string]bool{}
out := []PackageLicence{}
for _, r := range doc.Results {
for _, l := range r.Licenses {
if l.PkgName == "" {
continue // file-level licence of the repository's own code
}
key := l.PkgName + "\x00" + l.Name
if seen[key] {
continue
}
seen[key] = true
out = append(out, PackageLicence{Package: l.PkgName, License: l.Name})
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].Package != out[j].Package {
return out[i].Package < out[j].Package
}
return out[i].License < out[j].License
})
return out, nil
}
// Report posts the dependency licence list as scan_type=license.
func (m *LicenseScan) Report(
ctx context.Context,
source *dagger.Directory,
// +optional
apiURL string,
// +optional
token *dagger.Secret,
// +optional
serviceID string,
// +optional
version string,
// The analysis job of record (ADR-0093 §4, WP-05): the repository's
// suppression files are removed from the scanned copy, Trivy reads no
// configuration from the tree, and what was ignored is posted as
// information. Off for every other caller.
// +optional
scanOfRecord bool,
) (*ReportResult, error) {
res := &ReportResult{Outcome: "ran", Licences: []PackageLicence{}}
var err error
if scanOfRecord {
source, res.IgnoredSuppressions, err = dropSuppression(ctx, source,
func(ctx context.Context, pattern string) ([]string, error) { return source.Glob(ctx, pattern) },
func(d *dagger.Directory, paths []string) *dagger.Directory { return d.WithoutFiles(paths) },
)
}
var report string
if err == nil {
report, err = dag.Container().
From("aquasec/trivy:0.76.1").
WithMountedCache("/root/.cache/trivy", dag.CacheVolume("trivy-db")).
WithDirectory("/src", source).
WithWorkdir("/src").
WithExec(licenceArgs(scanOfRecord)).
File("/tmp/license-report.json").
Contents(ctx)
}
if err == nil {
res.Licences, err = parseLicences(report)
}
if err != nil {
res.Outcome, res.Error, res.Licences = "could_not_run", err.Error(), []PackageLicence{}
}
if apiURL == "" || token == nil {
return res, nil
}
licences := res.Licences
if len(licences) > 5000 {
licences = licences[:5000]
}
data := map[string]any{"outcome": res.Outcome, "licenses": licences}
if res.Outcome == "could_not_run" {
data = map[string]any{"outcome": res.Outcome, "error": res.Error}
}
if len(res.IgnoredSuppressions) > 0 {
data["ignored_suppressions"] = res.IgnoredSuppressions
}
body, err := json.Marshal(map[string]any{
"service_id": serviceID,
"version": version,
"scan_type": "license",
"scanner": "trivy",
"report_format": "json",
"report_data": data,
})
if err != nil {
return res, fmt.Errorf("marshal licence payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(apiURL, "/")+"/api/v1/scans", bytes.NewReader(body))
if err != nil {
return res, fmt.Errorf("build request: %w", err)
}
tok, err := token.Plaintext(ctx)
if err != nil {
return res, 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 res, fmt.Errorf("post licence report: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return res, fmt.Errorf("post licence report returned %d", resp.StatusCode)
}
res.Posted = true
return res, nil
}
+25
View File
@@ -0,0 +1,25 @@
package main
import "testing"
func TestParseLicencesListsPackagesWithoutDeciding(t *testing.T) {
report := `{"Results":[{"Licenses":[
{"PkgName":"left-pad","Name":"MIT"},
{"PkgName":"left-pad","Name":"MIT"},
{"PkgName":"gpl-thing","Name":"GPL-3.0"},
{"PkgName":"","Name":"Apache-2.0"}]}]}`
got, err := parseLicences(report)
if err != nil {
t.Fatal(err)
}
want := []PackageLicence{{"gpl-thing", "GPL-3.0"}, {"left-pad", "MIT"}}
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestAnUnreadableLicenceReportIsAnError(t *testing.T) {
if _, err := parseLicences("FATAL"); err == nil {
t.Fatal("an unreadable report must be could_not_run, not an empty list")
}
}
+92
View File
@@ -0,0 +1,92 @@
package main
// The scan of record (ADR-0093 §4 condition 3, WP-05): the repository being
// judged must not be able to steer the scanner that judges it. By default
// Trivy reads trivy.yaml, .trivyignore[.yaml] and trivy-secret.yaml from the
// tree it scans, so a change could ignore its own licence or misconfiguration
// finding (WP-13 review, 2026-11-05, CONFIRMED). With --scan-of-record those
// files are removed from the scanned copy (reported as ignored_suppressions)
// and Trivy is told to read no configuration from the tree at all. Mirrors
// security-scan's withoutSuppression / trustedConfigArgs.
//
// Pure where it can be: dropSuppression takes the tree's glob and "without"
// as functions, so a test passes an in-memory tree and checks the tree that
// comes back.
import (
"context"
"fmt"
)
// suppressionFiles are the files Trivy (and Checkov) read from the scanned
// tree and obey. Kept equal to security-scan's list by
// apps/api/tests/test_analysis_of_record.py.
var suppressionFiles = []string{
".gitleaksignore",
".gitleaks.toml",
".trivyignore",
".trivyignore.yaml",
"trivy.yaml",
"trivy.yml",
".semgrepignore",
".checkov.yaml",
".checkov.yml",
"trivy-secret.yaml",
"trivy-secret.yml",
}
// dropSuppression returns source minus every suppressionFiles entry, at any
// depth, and the paths it removed. A tree that cannot be listed is an error:
// a scan of record that could not drop the suppressions is not one.
func dropSuppression[T any](
ctx context.Context,
source T,
glob func(context.Context, string) ([]string, error),
without func(T, []string) T,
) (T, []string, error) {
var found []string
for _, name := range suppressionFiles {
for _, pattern := range []string{name, "**/" + name} {
matches, err := glob(ctx, pattern)
if err != nil {
var none T
return none, nil, fmt.Errorf("list %s for the scan of record: %w", name, err)
}
found = append(found, matches...)
}
}
seen := map[string]bool{}
var removed []string
for _, p := range found {
if !seen[p] {
seen[p] = true
removed = append(removed, p)
}
}
if len(removed) == 0 {
return source, nil, nil
}
return without(source, removed), removed, nil
}
// trustedConfigArgs are the Trivy flags the scan of record adds: no
// configuration, ignore file or secret configuration is read from the tree
// it scans (Trivy 0.76, "Disabling configuration files").
func trustedConfigArgs(scanOfRecord bool) []string {
if !scanOfRecord {
return nil
}
return []string{"--config=", "--ignorefile=", "--secret-config="}
}
// withTrustedConfig inserts trustedConfigArgs before the final target
// argument of a Trivy argv (the target must stay last).
func withTrustedConfig(args []string, scanOfRecord bool) []string {
extra := trustedConfigArgs(scanOfRecord)
if len(extra) == 0 || len(args) == 0 {
return args
}
out := append([]string{}, args[:len(args)-1]...)
out = append(out, extra...)
return append(out, args[len(args)-1])
}
+127
View File
@@ -0,0 +1,127 @@
package main
// Written on the build VM, not run there (owner decision 2026-10-11). Runs
// with `go test ./...` after `dagger develop` has generated internal/dagger.
import (
"context"
"errors"
"path"
"reflect"
"sort"
"strings"
"testing"
)
type memTree struct {
files map[string]bool
globErr error
}
func newTree(paths ...string) memTree {
files := map[string]bool{}
for _, p := range paths {
files[p] = true
}
return memTree{files: files}
}
func (t memTree) Glob(_ context.Context, pattern string) ([]string, error) {
if t.globErr != nil {
return nil, t.globErr
}
var out []string
for p := range t.files {
if name, ok := strings.CutPrefix(pattern, "**/"); ok {
if strings.Contains(p, "/") && path.Base(p) == name {
out = append(out, p)
}
} else if p == pattern {
out = append(out, p)
}
}
sort.Strings(out)
return out, nil
}
func (t memTree) WithoutFiles(paths []string) memTree {
files := map[string]bool{}
for p := range t.files {
files[p] = true
}
for _, p := range paths {
delete(files, p)
}
return memTree{files: files}
}
func (t memTree) list() []string {
var out []string
for p := range t.files {
out = append(out, p)
}
sort.Strings(out)
return out
}
// A change that ships trivy.yaml / .trivyignore to hide its own GPL dependency
// is scanned WITHOUT them. Mutant: return `source, removed, nil` -> the tree
// still holds them and this fails.
func TestTheLicenceScanOfRecordTreeHasNoSuppressionFile(t *testing.T) {
tree := newTree("package.json", "trivy.yaml", ".trivyignore", "svc/.trivyignore.yaml", "trivy-secret.yaml")
got, removed, err := dropSuppression(context.Background(), tree, tree.Glob, memTree.WithoutFiles)
if err != nil {
t.Fatal(err)
}
if want := []string{"package.json"}; !reflect.DeepEqual(got.list(), want) {
t.Fatalf("scanned tree = %q, want %q", got.list(), want)
}
if len(removed) != 4 {
t.Fatalf("removed %q, want the four suppression files", removed)
}
}
// Legal direction: a tree without suppression is scanned whole.
func TestALicenceTreeWithoutSuppressionIsScannedWhole(t *testing.T) {
tree := newTree("package.json", "src/trivy.go")
got, removed, err := dropSuppression(context.Background(), tree, tree.Glob, memTree.WithoutFiles)
if err != nil || len(removed) != 0 || !reflect.DeepEqual(got.list(), tree.list()) {
t.Fatalf("got %q removed %q err %v", got.list(), removed, err)
}
}
func TestALicenceTreeThatCannotBeListedIsNotAScanOfRecord(t *testing.T) {
tree := memTree{globErr: errors.New("boom")}
if _, _, err := dropSuppression(context.Background(), tree, tree.Glob, memTree.WithoutFiles); err == nil {
t.Fatal("an unlistable tree must be an error, never a whole-tree scan")
}
}
// Mirrors security-scan's TestTrivyReadsNoConfigFromTheTreeInTheScanOfRecord.
// Mutant: drop trustedConfigArgs from licenceArgs -> fails; legal direction:
// add them outside the scan of record -> the second loop fails.
func TestLicenceTrivyReadsNoConfigFromTheTreeInTheScanOfRecord(t *testing.T) {
args := licenceArgs(true)
for _, flag := range []string{"--config=", "--ignorefile=", "--secret-config="} {
if !contains(args, flag) {
t.Errorf("licence scan of record lacks %s: %q", flag, args)
}
}
if args[len(args)-1] != "." {
t.Errorf("the target must stay last: %q", args)
}
for _, a := range licenceArgs(false) {
if strings.HasPrefix(a, "--config=") || strings.HasPrefix(a, "--ignorefile=") {
t.Errorf("outside the scan of record the argv must not change: %q", a)
}
}
}
func contains(xs []string, s string) bool {
for _, x := range xs {
if x == s {
return true
}
}
return false
}