chore: publish IntegraCI build modules 732ec6c83925

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

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
// Package evidence builds the supply-chain evidence files a build leaves behind
// (ADR-0068 Layer 2, #2143 phase 1): an in-toto Statement carrying an SLSA v1
// provenance predicate for ONE image digest, and a SHA256SUMS manifest over the
// evidence set.
//
// It is a separate package, standard library only, for the reason db-migration
// keeps its logic in verdict/: the generated `dagger` package panics at init
// without a Dagger session, so nothing in package main can run under a plain
// `go test`. Everything here is pure and deterministic — the same inputs give
// the same bytes — which is what a later golden test comparing the Dagger and
// render-only paths (#2143 acceptance criterion 1) needs.
//
// What this package does NOT do: sign. A statement written here is evidence of
// what the build claims; it becomes an attestation only when cosign signs it
// (`cosign attest-provenance --predicate`), and the deploy-time gate that
// verifies the signature is a later phase.
package evidence
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"regexp"
"sort"
"strings"
"time"
)
const (
// StatementType is the in-toto Statement v1 `_type`.
StatementType = "https://in-toto.io/Statement/v1"
// SLSAProvenanceV1 is the SLSA v1.0 provenance predicate type.
SLSAProvenanceV1 = "https://slsa.dev/provenance/v1"
// DefaultBuildType names the recipe this module runs. A verifier keys its
// interpretation of externalParameters off this URI, so it is stable.
DefaultBuildType = "https://integraci.co/buildtypes/dagger-standard-build/v1"
)
// digestRef matches a reference pinned to a sha256 manifest digest, with or
// without a tag before it: host/repo@sha256:<64>, host/repo:tag@sha256:<64>.
var digestRef = regexp.MustCompile(`^([^@\s]+)@sha256:([0-9a-f]{64})$`)
// gitRevision is a full commit id: 40 hex (SHA-1 repositories) or 64 hex
// (SHA-256 repositories). An abbreviated id is refused — it does not pin a
// commit, and provenance that does not pin its source is not provenance.
var gitRevision = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`)
// Subject is the artifact a statement is about.
type Subject struct {
Name string `json:"name"`
Digest map[string]string `json:"digest"`
}
// ParseDigestRef splits a digest-pinned image reference into the subject name
// (repository, no tag) and the hex sha256.
//
// A TAG-ONLY reference is an error, not a lookup. A tag moves; a statement
// about a tag says nothing about the bytes that will be deployed, and resolving
// the tag here would record whatever it points at by the time this step runs —
// possibly another build's image.
func ParseDigestRef(ref string) (Subject, error) {
m := digestRef.FindStringSubmatch(strings.TrimSpace(ref))
if m == nil {
return Subject{}, fmt.Errorf(
"image reference %q is not pinned to a sha256 digest (want <repo>[:tag]@sha256:<64 hex>)", ref)
}
name := m[1]
// Strip a tag, but not a registry port: the tag is after the LAST slash.
if slash := strings.LastIndexByte(name, '/'); strings.LastIndexByte(name, ':') > slash {
name = name[:strings.LastIndexByte(name, ':')]
}
if name == "" {
return Subject{}, fmt.Errorf("image reference %q has no repository", ref)
}
return Subject{Name: name, Digest: map[string]string{"sha256": m[2]}}, nil
}
// ProvenanceInput is everything the provenance statement records. Every field
// is supplied by the caller (the CI step) — nothing is read from the
// environment here, so nothing in the output is a placeholder.
type ProvenanceInput struct {
ImageRef string // digest-pinned
BuilderID string // absolute URI identifying the build platform/pipeline
BuildType string // empty -> DefaultBuildType
SourceURI string // e.g. git+https://git.example/org/repo@refs/heads/main
SourceRevision string // full commit id
InvocationID string // CI run id; optional
StartedOn string // RFC 3339; optional, omitted when empty
FinishedOn string // RFC 3339; optional, omitted when empty
EngineVersion string // Dagger engine version the module is pinned to
Language string // build lane; optional
}
type resourceDescriptor struct {
URI string `json:"uri"`
Digest map[string]string `json:"digest"`
}
type buildDefinition struct {
BuildType string `json:"buildType"`
ExternalParameters map[string]string `json:"externalParameters"`
InternalParameters map[string]string `json:"internalParameters,omitempty"`
ResolvedDependencies []resourceDescriptor `json:"resolvedDependencies"`
}
type builder struct {
ID string `json:"id"`
Version map[string]string `json:"version,omitempty"`
}
type buildMetadata struct {
InvocationID string `json:"invocationId,omitempty"`
StartedOn string `json:"startedOn,omitempty"`
FinishedOn string `json:"finishedOn,omitempty"`
}
type runDetails struct {
Builder builder `json:"builder"`
Metadata *buildMetadata `json:"metadata,omitempty"`
}
type provenancePredicate struct {
BuildDefinition buildDefinition `json:"buildDefinition"`
RunDetails runDetails `json:"runDetails"`
}
type statement struct {
Type string `json:"_type"`
Subject []Subject `json:"subject"`
PredicateType string `json:"predicateType"`
Predicate provenancePredicate `json:"predicate"`
}
// ProvenanceStatement renders the in-toto Statement (SLSA v1 provenance) for
// one image digest, indented and newline-terminated. It refuses — rather than
// writes something a verifier would later have to distrust — when the subject
// is not digest-pinned, the builder is not an absolute URI, the source does
// not pin a full commit, or a timestamp is not RFC 3339.
func ProvenanceStatement(in ProvenanceInput) ([]byte, error) {
subject, err := ParseDigestRef(in.ImageRef)
if err != nil {
return nil, err
}
if err := absoluteURI("builder id", in.BuilderID); err != nil {
return nil, err
}
buildType := in.BuildType
if buildType == "" {
buildType = DefaultBuildType
}
if err := absoluteURI("build type", buildType); err != nil {
return nil, err
}
if strings.TrimSpace(in.SourceURI) == "" || strings.ContainsAny(in.SourceURI, " \t\r\n") {
return nil, fmt.Errorf("source uri %q must be a non-empty URI without whitespace", in.SourceURI)
}
rev := strings.ToLower(strings.TrimSpace(in.SourceRevision))
if !gitRevision.MatchString(rev) {
return nil, fmt.Errorf("source revision %q is not a full commit id (40 or 64 hex)", in.SourceRevision)
}
for name, ts := range map[string]string{"started-on": in.StartedOn, "finished-on": in.FinishedOn} {
if ts == "" {
continue
}
if _, err := time.Parse(time.RFC3339, ts); err != nil {
return nil, fmt.Errorf("%s %q is not RFC 3339: %w", name, ts, err)
}
}
if strings.ContainsAny(in.InvocationID, "\r\n") {
return nil, fmt.Errorf("invocation id must be a single line")
}
external := map[string]string{"source": in.SourceURI, "revision": rev}
var internal map[string]string
if in.Language != "" {
internal = map[string]string{"language": in.Language}
}
var version map[string]string
if in.EngineVersion != "" {
version = map[string]string{"dagger-engine": in.EngineVersion}
}
var meta *buildMetadata
if in.InvocationID != "" || in.StartedOn != "" || in.FinishedOn != "" {
meta = &buildMetadata{InvocationID: in.InvocationID, StartedOn: in.StartedOn, FinishedOn: in.FinishedOn}
}
st := statement{
Type: StatementType,
Subject: []Subject{subject},
PredicateType: SLSAProvenanceV1,
Predicate: provenancePredicate{
BuildDefinition: buildDefinition{
BuildType: buildType,
ExternalParameters: external,
InternalParameters: internal,
// `gitCommit` is the in-toto DigestSet key for a commit id. The
// old cosign predicate labelled it `sha1` after stripping a
// `sha256:` prefix — a digest under the wrong algorithm name.
ResolvedDependencies: []resourceDescriptor{{
URI: in.SourceURI,
Digest: map[string]string{"gitCommit": rev},
}},
},
RunDetails: runDetails{
Builder: builder{ID: in.BuilderID, Version: version},
Metadata: meta,
},
},
}
out, err := json.MarshalIndent(st, "", " ")
if err != nil {
return nil, err
}
return append(out, '\n'), nil
}
func absoluteURI(what, raw string) error {
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || (u.Host == "" && u.Opaque == "") || strings.ContainsAny(raw, " \t\r\n") {
return fmt.Errorf("%s %q must be an absolute URI", what, raw)
}
return nil
}
// fileName is what may appear in a SHA256SUMS line: a plain name, so a
// manifest can never point a verifier outside the evidence directory.
var fileName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
// SHA256Sums renders a `sha256sum -c`-compatible manifest over the given
// files, sorted by name so the output is deterministic.
func SHA256Sums(files map[string][]byte) ([]byte, error) {
names := make([]string, 0, len(files))
for name := range files {
if !fileName.MatchString(name) {
return nil, fmt.Errorf("evidence file name %q is not a plain file name", name)
}
names = append(names, name)
}
sort.Strings(names)
var b strings.Builder
for _, name := range names {
sum := sha256.Sum256(files[name])
fmt.Fprintf(&b, "%s %s\n", hex.EncodeToString(sum[:]), name)
}
return []byte(b.String()), nil
}
// SBOMFileName maps an SBOM format to the file name the evidence set uses.
func SBOMFileName(format string) (name string, syftOutput string, err error) {
switch format {
case "", "cyclonedx":
return "sbom.cdx.json", "cyclonedx-json", nil
case "spdx":
return "sbom.spdx.json", "spdx-json", nil
default:
return "", "", fmt.Errorf("unsupported sbom format %q (want cyclonedx|spdx)", format)
}
}
// DigestFromPushOutput finds the digest reference a push printed. crane push
// prints `<repo>@sha256:<64>` on success; Dagger's Publish returns
// `<repo>:<tag>@sha256:<64>`. Empty when no such reference is present.
func DigestFromPushOutput(out string) string {
for _, field := range strings.Fields(out) {
field = strings.Trim(field, `'"`)
if digestRef.MatchString(field) {
return field
}
}
return ""
}
// DigestOf returns `sha256:<hex>` for a digest-pinned reference, else "".
func DigestOf(ref string) string {
if m := digestRef.FindStringSubmatch(ref); m != nil {
return "sha256:" + m[2]
}
return ""
}
+211
View File
@@ -0,0 +1,211 @@
package evidence
import (
"encoding/json"
"strings"
"testing"
)
const (
hexDigest = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
commit = "89abcdef0123456789abcdef0123456789abcdef"
)
func validInput() ProvenanceInput {
return ProvenanceInput{
ImageRef: "registry.example:5000/team/orders:abc123@sha256:" + hexDigest,
BuilderID: "https://jenkins.example/job/orders/",
SourceURI: "git+https://git.example/team/orders@refs/heads/main",
SourceRevision: commit,
InvocationID: "42",
StartedOn: "2026-10-11T08:00:00Z",
FinishedOn: "2026-10-11T08:05:00Z",
EngineVersion: "v0.21.7",
Language: "go",
}
}
func TestParseDigestRefKeepsPortStripsTag(t *testing.T) {
cases := map[string]string{
"registry.example:5000/team/orders:abc@sha256:" + hexDigest: "registry.example:5000/team/orders",
"registry.example:5000/team/orders@sha256:" + hexDigest: "registry.example:5000/team/orders",
"ghcr.io/acme/app@sha256:" + hexDigest: "ghcr.io/acme/app",
}
for ref, want := range cases {
s, err := ParseDigestRef(ref)
if err != nil {
t.Fatalf("%q: %v", ref, err)
}
if s.Name != want || s.Digest["sha256"] != hexDigest {
t.Fatalf("%q -> %+v, want name %q", ref, s, want)
}
}
}
// A tag is never accepted as a subject: it moves, and a statement about a tag
// says nothing about the bytes that get deployed.
func TestParseDigestRefRefusesUnpinned(t *testing.T) {
for _, ref := range []string{
"",
"ghcr.io/acme/app:1.0.0",
"ghcr.io/acme/app@sha256:" + hexDigest[:63], // short
"ghcr.io/acme/app@sha256:" + strings.ToUpper(hexDigest), // not lowercase hex
"ghcr.io/acme/app@sha512:" + hexDigest,
"@sha256:" + hexDigest,
"ghcr.io/acme/app@sha256:" + hexDigest + "\nextra",
} {
if _, err := ParseDigestRef(ref); err == nil {
t.Fatalf("%q must be refused", ref)
}
}
}
func TestProvenanceStatementShape(t *testing.T) {
out, err := ProvenanceStatement(validInput())
if err != nil {
t.Fatal(err)
}
var st map[string]any
if err := json.Unmarshal(out, &st); err != nil {
t.Fatalf("not JSON: %v", err)
}
if st["_type"] != StatementType || st["predicateType"] != SLSAProvenanceV1 {
t.Fatalf("wrong types: %v / %v", st["_type"], st["predicateType"])
}
subj := st["subject"].([]any)[0].(map[string]any)
if subj["name"] != "registry.example:5000/team/orders" {
t.Fatalf("subject name %v", subj["name"])
}
if subj["digest"].(map[string]any)["sha256"] != hexDigest {
t.Fatalf("subject digest %v", subj["digest"])
}
bd := st["predicate"].(map[string]any)["buildDefinition"].(map[string]any)
if bd["buildType"] != DefaultBuildType {
t.Fatalf("buildType %v", bd["buildType"])
}
dep := bd["resolvedDependencies"].([]any)[0].(map[string]any)
if dep["digest"].(map[string]any)["gitCommit"] != commit {
t.Fatalf("source dependency digest %v", dep["digest"])
}
// The old cosign predicate shipped literal shell placeholders that nothing
// ever expanded. None may appear here.
if strings.Contains(string(out), "${") {
t.Fatalf("statement carries an unexpanded placeholder:\n%s", out)
}
if !strings.HasSuffix(string(out), "}\n") {
t.Fatal("statement must end with a newline")
}
}
func TestProvenanceStatementIsDeterministic(t *testing.T) {
a, err := ProvenanceStatement(validInput())
if err != nil {
t.Fatal(err)
}
b, _ := ProvenanceStatement(validInput())
if string(a) != string(b) {
t.Fatal("same input must give the same bytes")
}
}
func TestProvenanceStatementOmitsUnsetMetadata(t *testing.T) {
in := validInput()
in.InvocationID, in.StartedOn, in.FinishedOn = "", "", ""
out, err := ProvenanceStatement(in)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(out), "metadata") {
t.Fatalf("unset metadata must be omitted, not invented:\n%s", out)
}
}
func TestProvenanceStatementRefusesBadInput(t *testing.T) {
mutate := map[string]func(*ProvenanceInput){
"tag-only image": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app:1.0.0" },
"relative builder": func(in *ProvenanceInput) { in.BuilderID = "jenkins/job/orders" },
"empty builder": func(in *ProvenanceInput) { in.BuilderID = "" },
"builder whitespace": func(in *ProvenanceInput) { in.BuilderID = "https://ci.example/a b" },
"relative build type": func(in *ProvenanceInput) { in.BuildType = "standard-build" },
"empty source": func(in *ProvenanceInput) { in.SourceURI = "" },
"source newline": func(in *ProvenanceInput) { in.SourceURI = "git+https://x\n\"evil\"" },
"short revision": func(in *ProvenanceInput) { in.SourceRevision = commit[:12] },
"branch as revision": func(in *ProvenanceInput) { in.SourceRevision = "main" },
"bad started-on": func(in *ProvenanceInput) { in.StartedOn = "yesterday" },
"placeholder ts": func(in *ProvenanceInput) { in.FinishedOn = "${BUILD_FINISHED_ON}" },
"multiline run id": func(in *ProvenanceInput) { in.InvocationID = "1\n2" },
}
for name, m := range mutate {
in := validInput()
m(&in)
if _, err := ProvenanceStatement(in); err == nil {
t.Fatalf("%s: must be refused", name)
}
}
}
// Legitimate values a strict-looking validator must not reject.
func TestProvenanceStatementAcceptsLegitimateValues(t *testing.T) {
ok := map[string]func(*ProvenanceInput){
"sha256 repository commit": func(in *ProvenanceInput) { in.SourceRevision = hexDigest },
"uppercase commit": func(in *ProvenanceInput) { in.SourceRevision = strings.ToUpper(commit) },
"urn builder": func(in *ProvenanceInput) { in.BuilderID = "urn:integraci:builder:jenkins" },
"ssh source": func(in *ProvenanceInput) { in.SourceURI = "git+ssh://git@git.example:2222/team/orders.git" },
"offset timestamp": func(in *ProvenanceInput) { in.StartedOn = "2026-10-11T15:00:00+07:00" },
"no tag before digest": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app@sha256:" + hexDigest },
"no language": func(in *ProvenanceInput) { in.Language = "" },
}
for name, m := range ok {
in := validInput()
m(&in)
if _, err := ProvenanceStatement(in); err != nil {
t.Fatalf("%s: legitimate value refused: %v", name, err)
}
}
}
func TestSHA256SumsFormat(t *testing.T) {
out, err := SHA256Sums(map[string][]byte{"b.json": []byte("b"), "a.json": []byte("")})
if err != nil {
t.Fatal(err)
}
want := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 a.json\n" +
"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d b.json\n"
if string(out) != want {
t.Fatalf("got\n%s\nwant\n%s", out, want)
}
}
func TestSHA256SumsRefusesPathNames(t *testing.T) {
for _, name := range []string{"../x", "dir/x", "", ".hidden", "a b", "x\ny"} {
if _, err := SHA256Sums(map[string][]byte{name: nil}); err == nil {
t.Fatalf("%q must be refused", name)
}
}
}
func TestSBOMFileName(t *testing.T) {
if n, o, err := SBOMFileName(""); err != nil || n != "sbom.cdx.json" || o != "cyclonedx-json" {
t.Fatalf("default: %q %q %v", n, o, err)
}
if n, o, err := SBOMFileName("spdx"); err != nil || n != "sbom.spdx.json" || o != "spdx-json" {
t.Fatalf("spdx: %q %q %v", n, o, err)
}
if _, _, err := SBOMFileName("cyclonedx-json; rm -rf /"); err == nil {
t.Fatal("unknown format must be refused")
}
}
func TestDigestFromPushOutput(t *testing.T) {
ref := "registry.example:5000/team/orders@sha256:" + hexDigest
out := "logged in\n2026/10/11 pushed blob: sha256:aaaa\n" + ref + "\nPUSHED 'registry.example:5000/team/orders:abc'\ncrane exit=0\n"
if got := DigestFromPushOutput(out); got != ref {
t.Fatalf("got %q", got)
}
if got := DigestFromPushOutput("pushed blob: sha256:" + hexDigest + "\n"); got != "" {
t.Fatalf("a bare blob digest is not an image reference, got %q", got)
}
if DigestOf(ref) != "sha256:"+hexDigest || DigestOf("ghcr.io/a:1") != "" {
t.Fatal("DigestOf")
}
}