// 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 [: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 `@sha256:<64>` on success; Dagger's Publish returns // `:@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:` for a digest-pinned reference, else "". func DigestOf(ref string) string { if m := digestRef.FindStringSubmatch(ref); m != nil { return "sha256:" + m[2] } return "" }