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

+173
View File
@@ -0,0 +1,173 @@
// Package attestation holds the cosign module's pure predicate logic, standard
// library only, so it runs under a plain `go test` (the generated `dagger`
// package panics at init without a session — see db-migration/verdict/).
//
// Two jobs:
//
// - PredicateFromStatement takes the in-toto Statement standard-build's
// `evidence` wrote and returns the predicate cosign should attach — but
// only after checking the statement is about THIS image's digest. Attaching
// another build's provenance to an image is the one mistake an attestation
// must never make, and nothing downstream could tell.
// - ProvenancePredicate builds the inline SLSA v1 predicate for callers that
// do not pass a statement. It replaces a template that shipped literal
// `${BUILD_STARTED_ON}` / `${ACTOR_ID}` placeholders nothing ever
// expanded, labelled a commit id as `sha1` after stripping `sha256:`, and
// claimed `dagger v0.15.0` while every module pins v0.21.7.
package attestation
import (
"encoding/json"
"fmt"
"net/url"
"regexp"
"strings"
"time"
)
// SLSAProvenanceV1 is the predicate type cosign's `slsaprovenance1` maps to.
const SLSAProvenanceV1 = "https://slsa.dev/provenance/v1"
var digestRef = regexp.MustCompile(`^[^@\s]+@sha256:([0-9a-f]{64})$`)
var commitID = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`)
// ImageDigest returns the hex sha256 of a digest-pinned reference.
func ImageDigest(image string) (string, error) {
m := digestRef.FindStringSubmatch(strings.TrimSpace(image))
if m == nil {
return "", fmt.Errorf("image %q is not pinned to a sha256 digest", image)
}
return m[1], nil
}
type statement struct {
Type string `json:"_type"`
PredicateType string `json:"predicateType"`
Subject []subject `json:"subject"`
Predicate json.RawMessage `json:"predicate"`
}
type subject struct {
Name string `json:"name"`
Digest map[string]string `json:"digest"`
}
// PredicateFromStatement validates an in-toto Statement against the image it
// is about to be attached to and returns its predicate bytes.
//
// Refused: a malformed statement, a statement type other than in-toto v0.1/v1,
// a predicate type other than SLSA v1 provenance, a tag-only image, and — the
// point of the function — a statement with no subject whose sha256 equals the
// image's digest.
func PredicateFromStatement(raw []byte, image string) ([]byte, error) {
want, err := ImageDigest(image)
if err != nil {
return nil, err
}
var st statement
if err := json.Unmarshal(raw, &st); err != nil {
return nil, fmt.Errorf("statement is not valid JSON: %w", err)
}
switch st.Type {
case "https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1":
default:
return nil, fmt.Errorf("statement _type %q is not an in-toto Statement", st.Type)
}
if st.PredicateType != SLSAProvenanceV1 {
return nil, fmt.Errorf("predicateType %q is not %s", st.PredicateType, SLSAProvenanceV1)
}
matched := false
for _, s := range st.Subject {
if strings.EqualFold(s.Digest["sha256"], want) {
matched = true
break
}
}
if !matched {
return nil, fmt.Errorf("statement has no subject with sha256 %s: it describes a different artifact", want)
}
p := strings.TrimSpace(string(st.Predicate))
if p == "" || p == "null" || !strings.HasPrefix(p, "{") {
return nil, fmt.Errorf("statement predicate is missing or not an object")
}
return []byte(p + "\n"), nil
}
// ProvenanceInput is what the inline predicate records. Supplied by the caller;
// nothing is read from the environment.
type ProvenanceInput struct {
BuilderID string
BuildType string
SourceURI string
SourceDigest string // full commit id; a `sha1:`/`sha256:` prefix is tolerated
InvocationID string
StartedOn string // RFC 3339; empty -> Now
FinishedOn string // RFC 3339; empty -> Now
EngineVersion string
Now time.Time
}
// ProvenancePredicate renders the SLSA v1 provenance predicate (the predicate
// only — cosign wraps it in a Statement whose subject is the image digest).
func ProvenancePredicate(in ProvenanceInput) ([]byte, error) {
for what, raw := range map[string]string{"builder id": in.BuilderID, "build type": in.BuildType} {
u, err := url.Parse(raw)
if err != nil || u.Scheme == "" || (u.Host == "" && u.Opaque == "") || strings.ContainsAny(raw, " \t\r\n") {
return nil, fmt.Errorf("%s %q must be an absolute URI", what, raw)
}
}
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.SourceDigest))
for _, prefix := range []string{"sha1:", "sha256:"} {
rev = strings.TrimPrefix(rev, prefix)
}
if !commitID.MatchString(rev) {
return nil, fmt.Errorf("source digest %q is not a full commit id (40 or 64 hex)", in.SourceDigest)
}
now := in.Now.UTC().Format(time.RFC3339)
started, finished := in.StartedOn, in.FinishedOn
if started == "" {
started = now
}
if finished == "" {
finished = now
}
for what, ts := range map[string]string{"started-on": started, "finished-on": finished} {
if _, err := time.Parse(time.RFC3339, ts); err != nil {
return nil, fmt.Errorf("%s %q is not RFC 3339", what, ts)
}
}
if strings.ContainsAny(in.InvocationID, "\r\n") {
return nil, fmt.Errorf("invocation id must be a single line")
}
predicate := map[string]any{
"buildDefinition": map[string]any{
"buildType": in.BuildType,
"externalParameters": map[string]string{"source": in.SourceURI, "revision": rev},
"resolvedDependencies": []map[string]any{{
"uri": in.SourceURI,
"digest": map[string]string{"gitCommit": rev},
}},
},
"runDetails": map[string]any{
"builder": map[string]any{
"id": in.BuilderID,
"version": map[string]string{"dagger-engine": in.EngineVersion},
},
"metadata": map[string]string{
"invocationId": in.InvocationID,
"startedOn": started,
"finishedOn": finished,
},
},
}
out, err := json.MarshalIndent(predicate, "", " ")
if err != nil {
return nil, err
}
return append(out, '\n'), nil
}
+158
View File
@@ -0,0 +1,158 @@
package attestation
import (
"encoding/json"
"strings"
"testing"
"time"
)
const (
digestA = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
digestB = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
commit = "89abcdef0123456789abcdef0123456789abcdef"
)
func stmt(subjectDigest, predicateType, typ string) []byte {
b, _ := json.Marshal(map[string]any{
"_type": typ,
"predicateType": predicateType,
"subject": []map[string]any{{
"name": "registry.example/team/orders",
"digest": map[string]string{"sha256": subjectDigest},
}},
"predicate": map[string]any{"buildDefinition": map[string]any{"buildType": "https://x.example/t"}},
})
return b
}
const imageA = "registry.example/team/orders:abc@sha256:" + digestA
func TestPredicateFromStatementReturnsPredicate(t *testing.T) {
p, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), imageA)
if err != nil {
t.Fatal(err)
}
var got map[string]any
if err := json.Unmarshal(p, &got); err != nil {
t.Fatalf("predicate is not JSON: %v", err)
}
if _, ok := got["buildDefinition"]; !ok {
t.Fatalf("predicate lost its body: %s", p)
}
if _, ok := got["_type"]; ok {
t.Fatal("must return the predicate, not the whole statement")
}
}
// The reason the function exists: provenance about another digest must never
// be attached to this image.
func TestPredicateFromStatementRefusesOtherDigest(t *testing.T) {
if _, err := PredicateFromStatement(stmt(digestB, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), imageA); err == nil {
t.Fatal("a statement about digest B must not attach to image A")
}
}
func TestPredicateFromStatementRefusals(t *testing.T) {
cases := map[string]struct {
raw []byte
image string
}{
"tag-only image": {stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"), "registry.example/team/orders:abc"},
"not json": {[]byte("{"), imageA},
"wrong statement": {stmt(digestA, SLSAProvenanceV1, "https://example.test/Statement"), imageA},
"wrong predicate": {stmt(digestA, "https://cyclonedx.org/bom", "https://in-toto.io/Statement/v1"), imageA},
"no subject": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[],"predicate":{}}`), imageA},
"null predicate": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[{"name":"x","digest":{"sha256":"` + digestA + `"}}],"predicate":null}`), imageA},
"sha512 only subject": {[]byte(`{"_type":"https://in-toto.io/Statement/v1","predicateType":"` + SLSAProvenanceV1 + `","subject":[{"name":"x","digest":{"sha512":"` + digestA + `"}}],"predicate":{}}`), imageA},
}
for name, c := range cases {
if _, err := PredicateFromStatement(c.raw, c.image); err == nil {
t.Fatalf("%s: must be refused", name)
}
}
}
func TestPredicateFromStatementAcceptsLegitimate(t *testing.T) {
// in-toto v0.1 statements are still what many tools write.
if _, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v0.1"), imageA); err != nil {
t.Fatalf("v0.1 statement refused: %v", err)
}
// An image reference with a registry port and no tag.
if _, err := PredicateFromStatement(stmt(digestA, SLSAProvenanceV1, "https://in-toto.io/Statement/v1"),
"registry.example:5000/team/orders@sha256:"+digestA); err != nil {
t.Fatalf("port + digest refused: %v", err)
}
}
func validInput() ProvenanceInput {
return ProvenanceInput{
BuilderID: "https://github.com/acme/app/.github/workflows/release.yml@refs/tags/v1.2.3",
BuildType: "https://actions.github.io/buildtypes/workflow/v1",
SourceURI: "git+https://github.com/acme/app@refs/tags/v1.2.3",
SourceDigest: "sha256:" + commit, // what the old docstring told callers to pass
InvocationID: "123",
EngineVersion: "v0.21.7",
Now: time.Date(2026, 10, 11, 8, 0, 0, 0, time.UTC),
}
}
func TestProvenancePredicateHasNoPlaceholders(t *testing.T) {
p, err := ProvenancePredicate(validInput())
if err != nil {
t.Fatal(err)
}
s := string(p)
if strings.Contains(s, "${") {
t.Fatalf("unexpanded placeholder in predicate:\n%s", s)
}
if strings.Contains(s, `"sha1"`) {
t.Fatalf("commit id must be labelled gitCommit, not sha1:\n%s", s)
}
if !strings.Contains(s, `"gitCommit": "`+commit+`"`) {
t.Fatalf("source commit missing:\n%s", s)
}
if !strings.Contains(s, `"startedOn": "2026-10-11T08:00:00Z"`) {
t.Fatalf("defaulted timestamp missing:\n%s", s)
}
if strings.Contains(s, "v0.15.0") || !strings.Contains(s, "v0.21.7") {
t.Fatalf("engine version wrong:\n%s", s)
}
}
func TestProvenancePredicateRefusals(t *testing.T) {
mutate := map[string]func(*ProvenanceInput){
"relative builder": func(in *ProvenanceInput) { in.BuilderID = "release.yml" },
"relative type": func(in *ProvenanceInput) { in.BuildType = "workflow" },
"empty source": func(in *ProvenanceInput) { in.SourceURI = "" },
"short commit": func(in *ProvenanceInput) { in.SourceDigest = commit[:7] },
"placeholder time": func(in *ProvenanceInput) { in.StartedOn = "${BUILD_STARTED_ON}" },
"newline run id": func(in *ProvenanceInput) { in.InvocationID = "1\n2" },
}
for name, m := range mutate {
in := validInput()
m(&in)
if _, err := ProvenancePredicate(in); err == nil {
t.Fatalf("%s: must be refused", name)
}
}
}
func TestProvenancePredicateAcceptsLegitimate(t *testing.T) {
ok := map[string]func(*ProvenanceInput){
"bare commit": func(in *ProvenanceInput) { in.SourceDigest = commit },
"sha1-prefixed": func(in *ProvenanceInput) { in.SourceDigest = "sha1:" + commit },
"sha256 repository": func(in *ProvenanceInput) { in.SourceDigest = digestA },
"explicit times": func(in *ProvenanceInput) {
in.StartedOn, in.FinishedOn = "2026-10-11T08:00:00+07:00", "2026-10-11T09:00:00Z"
},
"no run id": func(in *ProvenanceInput) { in.InvocationID = "" },
}
for name, m := range ok {
in := validInput()
m(&in)
if _, err := ProvenancePredicate(in); err != nil {
t.Fatalf("%s: legitimate value refused: %v", name, err)
}
}
}
+160
View File
@@ -0,0 +1,160 @@
package attestation
// Pure helpers for the phase-2 functions (#2143): registry auth for cosign,
// the attestation gate's OPA input and verdict, and blob names for sign-blob.
// Standard library only, like the rest of this package.
import (
"encoding/base64"
"encoding/json"
"fmt"
"regexp"
"strings"
)
// GatePolicyQuery is the OPA query the gate evaluates. The package lives in
// policy/attestation_gate.rego, a byte-identical copy of
// infra/policies/bundles/attestation-gate/attestation_gate.rego.
const GatePolicyQuery = "data.integraci.supply_chain.attestation_gate.result"
// registryHostRE is what a registry host legitimately is: a DNS name or IP,
// with an optional port. Nothing else reaches the docker config key.
var registryHostRE = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9.-]{0,252})(:[0-9]{1,5})?$`)
// RegistryHost returns the registry host of an image reference, following the
// docker rule: the first path segment is a host only when it contains a `.` or
// a `:`, or is `localhost`. Otherwise the image lives on Docker Hub.
func RegistryHost(image string) string {
ref := strings.TrimSpace(image)
if i := strings.IndexByte(ref, '/'); i > 0 {
first := ref[:i]
if strings.ContainsAny(first, ".:") || first == "localhost" {
return first
}
}
return "docker.io"
}
// RegistryAuthConfig renders a docker `config.json` that logs cosign into one
// registry. Written as a FILE (mounted as a secret) rather than passed to
// `cosign login` on a shell line: the username and password then never touch
// an argv or a shell, so neither can inject anything and neither shows in a
// process listing.
func RegistryAuthConfig(host, username, password string) ([]byte, error) {
if !registryHostRE.MatchString(host) {
return nil, fmt.Errorf("registry host %q is not a host[:port]", host)
}
if username == "" || strings.ContainsAny(username, ":\r\n") {
return nil, fmt.Errorf("registry username must be non-empty and contain no ':' or newline")
}
if password == "" {
return nil, fmt.Errorf("registry password is empty")
}
key := host
if host == "docker.io" {
key = "https://index.docker.io/v1/"
}
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return json.Marshal(map[string]any{
"auths": map[string]any{key: map[string]string{"auth": auth}},
})
}
// gateEnvelope is the subset of a DSSE envelope the policy reads.
type gateEnvelope struct {
PayloadType string `json:"payloadType"`
Payload string `json:"payload"`
Signatures []json.RawMessage `json:"signatures,omitempty"`
}
// GateInput builds the attestation gate's OPA input from `cosign
// verify-attestation` stdout.
//
// cosign prints one DSSE envelope per line, and only envelopes whose signature
// verified against the key it was given. Lines that are not a JSON envelope
// with a string payloadType and payload are dropped; dropping one can only
// remove evidence, never add it, so the gate fails closed on anything odd.
//
// A tag-only image and an empty trusted-builder list are refused here as well
// as in the policy (guard at the call site and at the sink).
func GateInput(image, cosignOutput string, trustedBuilders []string, requireSBOM bool) ([]byte, error) {
hex, err := ImageDigest(image)
if err != nil {
return nil, err
}
builders := make([]string, 0, len(trustedBuilders))
for _, b := range trustedBuilders {
if b = strings.TrimSpace(b); b != "" {
builders = append(builders, b)
}
}
if len(builders) == 0 {
return nil, fmt.Errorf("at least one --trusted-builder is required: a gate that trusts no builder cannot pass, and one that trusts any builder proves nothing")
}
envelopes := []gateEnvelope{}
for _, line := range strings.Split(cosignOutput, "\n") {
line = strings.TrimSpace(line)
if !strings.HasPrefix(line, "{") {
continue
}
var env gateEnvelope
if err := json.Unmarshal([]byte(line), &env); err != nil {
continue
}
if env.PayloadType == "" || env.Payload == "" {
continue
}
envelopes = append(envelopes, env)
}
return json.Marshal(map[string]any{
"image": map[string]string{"digest": "sha256:" + hex},
"envelopes": envelopes,
"policy": map[string]any{
"trusted_builders": builders,
"require_sbom": requireSBOM,
},
})
}
// GateVerdict reads `opa eval --format json` output for GatePolicyQuery.
//
// Anything but a well-formed decision is an error, never an allow: an empty
// result set is what OPA returns when the package is not loaded at all.
func GateVerdict(opaOutput []byte) (bool, []string, error) {
var out struct {
Result []struct {
Expressions []struct {
Value struct {
Allowed *bool `json:"allowed"`
Deny []string `json:"deny"`
} `json:"value"`
} `json:"expressions"`
} `json:"result"`
}
if err := json.Unmarshal(opaOutput, &out); err != nil {
return false, nil, fmt.Errorf("opa output is not JSON: %w", err)
}
if len(out.Result) != 1 || len(out.Result[0].Expressions) != 1 {
return false, nil, fmt.Errorf("opa returned no decision for %s (is the policy loaded?)", GatePolicyQuery)
}
v := out.Result[0].Expressions[0].Value
if v.Allowed == nil {
return false, nil, fmt.Errorf("opa decision has no `allowed` field")
}
if *v.Allowed && len(v.Deny) > 0 {
return false, v.Deny, fmt.Errorf("opa decision is contradictory: allowed with %d deny reason(s)", len(v.Deny))
}
return *v.Allowed, v.Deny, nil
}
// blobName is what sign-blob may call its outputs: a plain file name, so the
// returned directory can never place a file outside itself.
var blobName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
// CheckBlobName refuses a sign-blob output name that is not a plain file name.
func CheckBlobName(name string) error {
if !blobName.MatchString(name) || strings.Contains(name, "..") {
return fmt.Errorf("name %q must be a plain file name ([A-Za-z0-9._-], no '..')", name)
}
return nil
}
+179
View File
@@ -0,0 +1,179 @@
package attestation
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
)
func TestRegistryHost(t *testing.T) {
cases := map[string]string{
"registry.example/team/orders@sha256:" + digestA: "registry.example",
"nexus.example:8082/orders:1": "nexus.example:8082",
"localhost/orders:1": "localhost",
"library/alpine:3.20": "docker.io",
"alpine": "docker.io",
}
for in, want := range cases {
if got := RegistryHost(in); got != want {
t.Errorf("RegistryHost(%q) = %q, want %q", in, got, want)
}
}
}
func TestRegistryAuthConfigLegitimate(t *testing.T) {
raw, err := RegistryAuthConfig("nexus.example:8082", "ci-bot", "p@ss w'rd\"$x")
if err != nil {
t.Fatal(err)
}
var cfg struct {
Auths map[string]struct {
Auth string `json:"auth"`
} `json:"auths"`
}
if err := json.Unmarshal(raw, &cfg); err != nil {
t.Fatal(err)
}
dec, _ := base64.StdEncoding.DecodeString(cfg.Auths["nexus.example:8082"].Auth)
// Shell metacharacters in the password are DATA here, never syntax.
if string(dec) != "ci-bot:p@ss w'rd\"$x" {
t.Fatalf("auth = %q", dec)
}
}
func TestRegistryAuthConfigDockerHubKey(t *testing.T) {
raw, err := RegistryAuthConfig("docker.io", "u", "p")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), "https://index.docker.io/v1/") {
t.Fatalf("docker hub must use the index key: %s", raw)
}
}
func TestRegistryAuthConfigRefuses(t *testing.T) {
bad := []struct{ host, user, pass string }{
{"evil.example; rm -rf /", "u", "p"},
{"host/with/path", "u", "p"},
{"", "u", "p"},
{"registry.example", "", "p"},
{"registry.example", "a:b", "p"},
{"registry.example", "a\nb", "p"},
{"registry.example", "u", ""},
}
for _, c := range bad {
if _, err := RegistryAuthConfig(c.host, c.user, c.pass); err == nil {
t.Errorf("RegistryAuthConfig(%q, %q, …) accepted", c.host, c.user)
}
}
}
func gateEnvelopeLine(t *testing.T, payloadType string) string {
t.Helper()
b, err := json.Marshal(map[string]any{
"payloadType": payloadType,
"payload": base64.StdEncoding.EncodeToString([]byte(`{"_type":"x"}`)),
"signatures": []map[string]string{{"sig": "c2ln"}},
})
if err != nil {
t.Fatal(err)
}
return string(b)
}
func TestGateInputKeepsEnvelopesAndDropsNoise(t *testing.T) {
out := strings.Join([]string{
"Verification for registry.example/team/orders --",
gateEnvelopeLine(t, "application/vnd.in-toto+json"),
"{not json",
`{"payloadType":"","payload":"x"}`,
"",
}, "\n")
raw, err := GateInput(imageA, out, []string{" https://ci.example/job/orders/ ", ""}, true)
if err != nil {
t.Fatal(err)
}
var in struct {
Image map[string]string `json:"image"`
Envelopes []map[string]any `json:"envelopes"`
Policy struct {
TrustedBuilders []string `json:"trusted_builders"`
RequireSBOM bool `json:"require_sbom"`
} `json:"policy"`
}
if err := json.Unmarshal(raw, &in); err != nil {
t.Fatal(err)
}
if in.Image["digest"] != "sha256:"+digestA {
t.Fatalf("digest = %q", in.Image["digest"])
}
if len(in.Envelopes) != 1 {
t.Fatalf("want 1 envelope, got %d", len(in.Envelopes))
}
if len(in.Policy.TrustedBuilders) != 1 || in.Policy.TrustedBuilders[0] != "https://ci.example/job/orders/" {
t.Fatalf("builders = %v", in.Policy.TrustedBuilders)
}
if !in.Policy.RequireSBOM {
t.Fatal("require_sbom lost")
}
}
func TestGateInputEmptyEnvelopeListIsAnArray(t *testing.T) {
raw, err := GateInput(imageA, "", []string{"https://ci.example/"}, false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), `"envelopes":[]`) {
t.Fatalf("envelopes must be [] not null: %s", raw)
}
}
func TestGateInputRefusesTagAndNoBuilder(t *testing.T) {
if _, err := GateInput("registry.example/team/orders:abc", "", []string{"https://ci.example/"}, false); err == nil {
t.Error("tag-only image accepted")
}
if _, err := GateInput(imageA, "", []string{" ", ""}, false); err == nil {
t.Error("empty trusted builder list accepted")
}
}
func TestGateVerdict(t *testing.T) {
allow := `{"result":[{"expressions":[{"value":{"allowed":true,"deny":[]},"text":"x"}]}]}`
ok, deny, err := GateVerdict([]byte(allow))
if err != nil || !ok || len(deny) != 0 {
t.Fatalf("allow: ok=%v deny=%v err=%v", ok, deny, err)
}
refuse := `{"result":[{"expressions":[{"value":{"allowed":false,"deny":["no provenance"]}}]}]}`
ok, deny, err = GateVerdict([]byte(refuse))
if err != nil || ok || len(deny) != 1 {
t.Fatalf("deny: ok=%v deny=%v err=%v", ok, deny, err)
}
}
func TestGateVerdictFailsClosed(t *testing.T) {
for _, raw := range []string{
`{}`, // package not loaded: empty result set
`{"result":[]}`, // same
`{"result":[{"expressions":[{"value":{}}]}]}`, // no allowed field
`{"result":[{"expressions":[{"value":{"allowed":true,"deny":["x"]}}]}]}`,
`not json`,
} {
if ok, _, err := GateVerdict([]byte(raw)); ok || err == nil {
t.Errorf("GateVerdict(%s) = ok=%v err=%v, want refusal", raw, ok, err)
}
}
}
func TestCheckBlobName(t *testing.T) {
for _, good := range []string{"SHA256SUMS", "sbom.cdx.json", "a_b-c.1"} {
if err := CheckBlobName(good); err != nil {
t.Errorf("%q refused: %v", good, err)
}
}
for _, bad := range []string{"", "../x", "a/b", ".hidden", "a..b", "x y", "a;b"} {
if err := CheckBlobName(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
+171
View File
@@ -0,0 +1,171 @@
package attestation
import (
"fmt"
"net/url"
"regexp"
)
// Transparency log (Rekor) policy for the cosign module (owner decision
// 2026-10-11).
//
// Uploading to the public Sigstore Rekor is OFF unless asked for. An entry
// there is public and permanent, and for an attestation it carries the
// provenance itself: registry and git hosts, repository paths, the CI job URL
// and the commit. A tenant opts in per pipeline (`--public-rekor`) or points
// the module at its own Rekor (`--rekor-url`), which wins when both are given.
//
// KEYLESS signing is the exception: a Fulcio certificate lives ten minutes, so
// a keyless signature with no log entry cannot be verified afterwards. Keyless
// calls therefore keep the public log unless --rekor-url names a private one
// (see KeylessTlogArgs). Owner decision 2026-10-18: keyless is an explicit
// per-service opt-in with a disclosure that the entry is public; keyed is the
// default (see SignMethodMode). Verifying against a private Rekor needs that
// log's public key (CheckRekorPublicKey).
// rekorURLPattern is what a Rekor URL may look like once validated: https, a
// host, an optional port and a plain path. No userinfo, query, fragment,
// quote, `$`, backtick, backslash or whitespace — Sign joins its arguments
// into an `sh -c` line, so the charset is the injection control too.
var rekorURLPattern = regexp.MustCompile(`^https://[A-Za-z0-9.-]{1,253}(:[0-9]{1,5})?(/[A-Za-z0-9._~/-]{0,256})?$`)
// CheckRekorURL refuses anything but a plain https Rekor base URL.
func CheckRekorURL(raw string) error {
if !rekorURLPattern.MatchString(raw) {
return fmt.Errorf("--rekor-url %q must be a plain https URL (host, optional port and path; no credentials, query or fragment)", raw)
}
u, err := url.Parse(raw)
if err != nil || u.Hostname() == "" || u.User != nil {
return fmt.Errorf("--rekor-url %q is not a usable https URL", raw)
}
return nil
}
// SignTlogArgs are the cosign flags for a KEYED sign/attest/sign-blob:
// a private Rekor when rekorURL is set, the public log only when publicRekor
// is set, otherwise no upload at all.
func SignTlogArgs(rekorURL string, publicRekor bool) ([]string, error) {
if rekorURL != "" {
if err := CheckRekorURL(rekorURL); err != nil {
return nil, err
}
return []string{"--rekor-url=" + rekorURL}, nil
}
if publicRekor {
return nil, nil // cosign's default log is the public Sigstore Rekor
}
return []string{"--tlog-upload=false"}, nil
}
// VerifyTlogArgs are the matching flags for a KEYED verification. A signature
// that was never uploaded has no log entry, so without an opted-in log the
// key alone is the trust anchor (`--insecure-ignore-tlog`, cosign's name for
// exactly that). The verifier must make the same choice the signer made.
func VerifyTlogArgs(rekorURL string, publicRekor bool) ([]string, error) {
if rekorURL != "" {
if err := CheckRekorURL(rekorURL); err != nil {
return nil, err
}
return []string{"--rekor-url=" + rekorURL}, nil
}
if publicRekor {
return nil, nil
}
return []string{"--insecure-ignore-tlog=true"}, nil
}
// KeylessTlogArgs are the flags for keyless signing or verification: the
// private Rekor when one is named, else cosign's default (the public log).
func KeylessTlogArgs(rekorURL string) ([]string, error) {
if rekorURL == "" {
return nil, nil
}
if err := CheckRekorURL(rekorURL); err != nil {
return nil, err
}
return []string{"--rekor-url=" + rekorURL}, nil
}
// RekorPublicKeyPath is where a private Rekor's public key is mounted inside
// the cosign container. cosign reads SIGSTORE_REKOR_PUBLIC_KEY as a PATH to a
// PEM file (pkg/cosign/tlog.go reads it with os.ReadFile), and when it is set
// that key REPLACES the public Sigstore Rekor keys from the TUF root.
const RekorPublicKeyPath = "/tmp/rekor.pub"
// CheckRekorPublicKey refuses a VERIFICATION against a private Rekor that has
// no public key to check the log entry with (owner decision 2026-10-18).
//
// cosign verifies a log entry's signed entry timestamp (SET) against the Rekor
// keys it trusts. Without SIGSTORE_REKOR_PUBLIC_KEY those are the public
// Sigstore keys, so an entry from a private log can never verify: the call
// fails, but only after a network round-trip and with an error that reads like
// a broken signature. Refusing up front says what is missing. Nothing here
// widens what passes: with the key, cosign still checks the SET, the inclusion
// proof and the signature.
func CheckRekorPublicKey(rekorURL string, hasKey bool) error {
if rekorURL != "" && !hasKey {
return fmt.Errorf("--rekor-url %q needs --rekor-public-key: cosign verifies the log entry against that log's own public key, and without it trusts only the public Sigstore Rekor, so the verification cannot pass", rekorURL)
}
return nil
}
// SignMethodMode decides how `sign-method --method cosign` signs.
//
// Keyed is the default a rendered pipeline asks for (owner decision
// 2026-10-18): `--key`. Keyless must be asked for (`--keyless`). Both at once
// is refused rather than guessed.
//
// NEITHER is the call every pipeline rendered before 2026-10-18 makes, and the
// modules are not version-pinned, so those pipelines run this code unchanged.
// It stays keyless — what it always did — and legacy=true makes the caller
// print LegacyKeylessNotice. Turning it into an error would break every
// existing pipeline at once; turning it into keyed would need a key nobody
// installed. Either would be a silent change of behaviour.
func SignMethodMode(hasKey, keyless bool) (mode string, legacy bool, err error) {
switch {
case hasKey && keyless:
return "", false, fmt.Errorf("--key and --keyless are mutually exclusive: choose keyed (--key) or keyless (--keyless)")
case hasKey:
return "keyed", false, nil
case keyless:
return "keyless", false, nil
default:
return "keyless", true, nil
}
}
// LegacyKeylessNotice is printed (and returned in SignResult.Notice) when a
// pipeline signs keyless only because it named no mode.
const LegacyKeylessNotice = "NOTICE: this pipeline signs KEYLESS because it names no signing mode " +
"(rendered before 2026-10-18). Keyless signing writes the signing identity and image digest " +
"to the PUBLIC Sigstore transparency log, permanently. New pipelines sign with a key and " +
"upload nowhere by default. To migrate: install a cosign key in the CI engine and set " +
"governance.image_signing_mode: keyed. (A private Rekor keeps signature entries private, " +
"but the public Fulcio CA still logs each signing certificate publicly.) See " +
"docs/customer-docs/image-signing.md."
// AnchorRegex makes a certificate identity / issuer regex match the WHOLE
// value (#2435). cosign matches with Go's regexp, which finds a match
// anywhere, so `https://token\.actions\.githubusercontent\.com` also accepted
// `https://token.actions.githubusercontent.com.attacker.example`. Wrapping is
// always done, even when the caller already wrote ^…$: `^a|b$` only anchors
// each side of the alternation, and `^(?:^a$)$` means the same as `^a$`.
//
// Callers must CheckRegex the raw value first: `x)|(.*` does not compile on
// its own, but wrapped it becomes `^(?:x)|(.*)$`, which compiles and matches
// anything.
func AnchorRegex(re string) string {
if re == "" {
return ""
}
return "^(?:" + re + ")$"
}
// CheckRegex refuses a regex that does not compile on its own, so that
// AnchorRegex's wrapper cannot be escaped with unbalanced parentheses.
func CheckRegex(flag, re string) error {
if _, err := regexp.Compile(re); err != nil {
return fmt.Errorf("%s is not a valid regular expression: %w", flag, err)
}
return nil
}
+202
View File
@@ -0,0 +1,202 @@
package attestation
import (
"regexp"
"strings"
"testing"
)
// MUTATION-CHECK (staging, both directions):
// - AnchorRegex returns re unchanged → TestAnchoredIssuerRefusesExtendedIssuers FAILS;
// - AnchorRegex over-tightens (e.g. QuoteMeta) → the legitimate issuer case FAILS;
// - SignTlogArgs returns nil by default → TestKeyedSigningDoesNotUploadByDefault FAILS;
// - SignTlogArgs ignores rekorURL → TestPrivateRekorWinsOverPublic FAILS;
// - CheckRekorURL accepts everything → TestRekorURLRefusesUnsafeValues FAILS;
// refuses everything → TestPrivateRekorWinsOverPublic FAILS.
const ghIssuer = `https://token\.actions\.githubusercontent\.com`
// #2435: cosign matches with Go's regexp, which finds a match anywhere. The
// anchored form must refuse an issuer that only CONTAINS the expected one.
func TestAnchoredIssuerRefusesExtendedIssuers(t *testing.T) {
re := regexp.MustCompile(AnchorRegex(ghIssuer))
if !re.MatchString("https://token.actions.githubusercontent.com") {
t.Fatal("the legitimate issuer must still match")
}
for _, bad := range []string{
"https://token.actions.githubusercontent.com.attacker.example",
"https://evil.example/?https://token.actions.githubusercontent.com",
"xhttps://token.actions.githubusercontent.com",
"https://token.actions.githubusercontent.com/",
} {
if re.MatchString(bad) {
t.Errorf("anchored issuer regex matched %q", bad)
}
// The control: the unanchored regex is what let these through.
if !regexp.MustCompile(ghIssuer).MatchString(bad) {
t.Errorf("control: unanchored regex should match %q (test is not exercising the bug)", bad)
}
}
}
// `^a|b$` anchors each side of the alternation only; the wrapper must anchor
// the whole expression.
func TestAnchorRegexAnchorsAlternation(t *testing.T) {
re := regexp.MustCompile(AnchorRegex(`^https://a\.example|https://b\.example$`))
if !re.MatchString("https://a.example") || !re.MatchString("https://b.example") {
t.Fatal("both alternatives must still match")
}
if re.MatchString("https://a.example.evil") || re.MatchString("evil-https://b.example") {
t.Fatal("an alternation must not escape the anchors")
}
if AnchorRegex("") != "" {
t.Fatal("an empty regex stays empty (caller decides what empty means)")
}
}
// Review finding: wrapping alone is escapable. `x)|(.*` compiles once wrapped
// and matches anything, so the raw value must compile on its own first.
// MUTANT: CheckRegex returns nil → this test FAILS.
func TestUnbalancedRegexCannotEscapeTheAnchor(t *testing.T) {
escape := `x)|(.*`
if _, err := regexp.Compile(AnchorRegex(escape)); err != nil {
t.Fatalf("control: the wrapped escape must compile (that is the bug): %v", err)
}
if err := CheckRegex("--issuer-regex", escape); err == nil {
t.Fatal("an unbalanced regex must be refused before it is wrapped")
}
if err := CheckRegex("--issuer-regex", ghIssuer); err != nil {
t.Fatalf("a legitimate regex must pass: %v", err)
}
}
func TestVerifyAttestationArgsAnchorsBothRegexes(t *testing.T) {
args := strings.Join(VerifyAttestationArgs(imageA, vBuilder, `.+@acme\.example`, ghIssuer), " ")
if !strings.Contains(args, "--certificate-oidc-issuer-regexp ^(?:"+ghIssuer+")$") {
t.Fatalf("issuer not anchored: %s", args)
}
if !strings.Contains(args, `--certificate-identity-regexp ^(?:.+@acme\.example)$`) {
t.Fatalf("identity not anchored: %s", args)
}
}
func TestKeyedSigningDoesNotUploadByDefault(t *testing.T) {
got, err := SignTlogArgs("", false)
if err != nil || strings.Join(got, " ") != "--tlog-upload=false" {
t.Fatalf("default sign args = %v, %v; want --tlog-upload=false", got, err)
}
got, err = VerifyTlogArgs("", false)
if err != nil || strings.Join(got, " ") != "--insecure-ignore-tlog=true" {
t.Fatalf("default verify args = %v, %v; want --insecure-ignore-tlog=true", got, err)
}
}
func TestPublicRekorIsAnExplicitOptIn(t *testing.T) {
for name, fn := range map[string]func(string, bool) ([]string, error){
"sign": SignTlogArgs, "verify": VerifyTlogArgs,
} {
got, err := fn("", true)
if err != nil || len(got) != 0 {
t.Fatalf("%s: opted-in public log must use cosign's default, got %v, %v", name, got, err)
}
}
}
func TestPrivateRekorWinsOverPublic(t *testing.T) {
const private = "https://rekor.acme.example:8443/base"
for name, fn := range map[string]func(string, bool) ([]string, error){
"sign": SignTlogArgs, "verify": VerifyTlogArgs,
} {
got, err := fn(private, true)
if err != nil || strings.Join(got, " ") != "--rekor-url="+private {
t.Fatalf("%s: got %v, %v; want --rekor-url=%s", name, got, err, private)
}
}
got, err := KeylessTlogArgs(private)
if err != nil || strings.Join(got, " ") != "--rekor-url="+private {
t.Fatalf("keyless: got %v, %v", got, err)
}
if got, err := KeylessTlogArgs(""); err != nil || len(got) != 0 {
t.Fatalf("keyless without a private log keeps cosign's default, got %v, %v", got, err)
}
}
// Owner decision 2026-10-18: verifying against a private Rekor needs its
// public key; without it the call is refused before cosign runs.
// MUTANTS (staging):
// - CheckRekorPublicKey returns nil → the "refused" case FAILS;
// - it refuses whenever rekorURL is set (ignores hasKey) → the "with key" case FAILS;
// - it refuses with no rekorURL → the public/keyed cases FAIL.
func TestPrivateRekorVerificationNeedsItsPublicKey(t *testing.T) {
const private = "https://rekor.acme.example"
if err := CheckRekorPublicKey(private, false); err == nil {
t.Fatal("a private Rekor without its public key must be refused")
} else if !strings.Contains(err.Error(), "--rekor-public-key") {
t.Fatalf("the refusal must name the missing flag, got %v", err)
}
if err := CheckRekorPublicKey(private, true); err != nil {
t.Fatalf("a private Rekor WITH its public key must pass: %v", err)
}
// No private log: public log (keyless) or no log (keyed) — no key needed.
if err := CheckRekorPublicKey("", false); err != nil {
t.Fatalf("no private Rekor needs no key: %v", err)
}
if err := CheckRekorPublicKey("", true); err != nil {
t.Fatalf("a key without a private Rekor is harmless: %v", err)
}
}
// MUTANTS (staging):
// - the default case returns ("keyed", false, nil) → legacy case FAILS (and
// every pre-2026-10-18 pipeline would break: no key installed);
// - the default case returns an error → legacy case FAILS;
// - hasKey&&keyless returns keyed → the conflict case FAILS.
func TestSignMethodModeKeyedExplicitKeylessAndLegacy(t *testing.T) {
cases := []struct {
name string
hasKey, keyles bool
mode string
legacy, errors bool
}{
{"keyed", true, false, "keyed", false, false},
{"explicit keyless", false, true, "keyless", false, false},
{"legacy (no mode named)", false, false, "keyless", true, false},
{"both refused", true, true, "", false, true},
}
for _, c := range cases {
mode, legacy, err := SignMethodMode(c.hasKey, c.keyles)
if (err != nil) != c.errors {
t.Fatalf("%s: err=%v, want error=%v", c.name, err, c.errors)
}
if mode != c.mode || legacy != c.legacy {
t.Fatalf("%s: got (%q, legacy=%v), want (%q, legacy=%v)", c.name, mode, legacy, c.mode, c.legacy)
}
}
if !strings.Contains(LegacyKeylessNotice, "PUBLIC") || !strings.Contains(LegacyKeylessNotice, "image_signing_mode") {
t.Fatal("the legacy notice must disclose the public log and name the migration setting")
}
}
func TestRekorURLRefusesUnsafeValues(t *testing.T) {
for _, bad := range []string{
"http://rekor.acme.example",
"https://user:pw@rekor.acme.example",
"https://rekor.acme.example/?x=1",
"https://rekor.acme.example/#frag",
"https://rekor.acme.example/$(id)",
"https://rekor.acme.example/a b",
"https://rekor.acme.example';id;'",
"rekor.acme.example",
"https://",
} {
if err := CheckRekorURL(bad); err == nil {
t.Errorf("CheckRekorURL accepted %q", bad)
}
if _, err := SignTlogArgs(bad, false); err == nil {
t.Errorf("SignTlogArgs accepted %q", bad)
}
}
if err := CheckRekorURL("https://rekor.acme.example"); err != nil {
t.Fatalf("a plain https URL must pass: %v", err)
}
}
+270
View File
@@ -0,0 +1,270 @@
package attestation
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"strings"
)
// InTotoPayloadType is the DSSE payloadType of an in-toto Statement.
const InTotoPayloadType = "application/vnd.in-toto+json"
// ProvenanceExpectation is what a verified provenance must say. Every field
// is compared exactly — never as a substring of the raw cosign output.
type ProvenanceExpectation struct {
// Image the attestations were fetched for; must be digest-pinned, and a
// statement only counts when one of its subjects carries that sha256.
Image string
// BuilderID must equal predicate.runDetails.builder.id byte for byte.
BuilderID string
// SourceRepo is the repository URI without a ref or commit, e.g.
// "https://github.com/acme/app". A resolvedDependency counts when its uri,
// with an optional `git+` prefix and `.git` suffix, is that repository
// alone or that repository followed by `@<ref>`.
SourceRepo string
}
// VerifiedProvenance describes the statement that satisfied the expectation.
type VerifiedProvenance struct {
BuilderID string
SourceURI string
Subjects []string // "<name>@sha256:<hex>" for each sha256 subject
}
type envelope struct {
PayloadType string `json:"payloadType"`
Payload string `json:"payload"`
Signatures []json.RawMessage `json:"signatures"`
}
type provenancePredicate struct {
BuildDefinition struct {
ResolvedDependencies []struct {
URI string `json:"uri"`
Digest map[string]string `json:"digest"`
} `json:"resolvedDependencies"`
} `json:"buildDefinition"`
RunDetails struct {
Builder struct {
ID string `json:"id"`
} `json:"builder"`
} `json:"runDetails"`
}
// VerifyAttestationArgs is the `cosign verify-attestation` command line for a
// keyless provenance check. The signer is the trust anchor, not the builder.id
// string inside what it signed: with no identityRegex the certificate identity
// must equal builderID exactly, so a statement that names the expected builder
// only counts when that builder signed it.
//
// Both regexes are anchored to the whole value (AnchorRegex, #2435): cosign
// matches anywhere in the string, so an unanchored issuer regex also admitted
// an issuer that merely contained the expected one.
func VerifyAttestationArgs(image, builderID, identityRegex, issuerRegex string) []string {
args := []string{
"cosign", "verify-attestation",
"--type", "slsaprovenance1",
"--certificate-oidc-issuer-regexp", AnchorRegex(issuerRegex),
}
if identityRegex != "" {
args = append(args, "--certificate-identity-regexp", AnchorRegex(identityRegex))
} else {
args = append(args, "--certificate-identity", builderID)
}
return append(args, image)
}
// VerifyProvenanceOutput checks the stdout of `cosign verify-attestation
// --type slsaprovenance1`: one DSSE envelope per verified attestation (cosign
// v2 prints `sig.Payload()` of each; certificate details go to stderr).
//
// cosign has already checked the signatures and the predicate type; this
// checks what the signed statement SAYS. It succeeds when at least one
// envelope decodes to an in-toto Statement whose predicate is SLSA v1
// provenance, whose subject includes the image digest, whose builder.id equals
// the expected builder, and whose SOURCE — the first resolvedDependency, which
// is where SLSA builders and both producers in this repo put it — is the
// expected repository pinned to a commit. Later dependencies are inputs, not
// the source: a repo that vendors the expected one must not pass as it.
//
// builder.id is a string the signer wrote; it is only as trustworthy as the
// signing identity cosign checked. The caller binds the two (VerifyProvenance
// passes --certificate-identity=<builder id> unless given a regex).
//
// Fail-closed: output that is not a stream of DSSE envelopes, an envelope that
// is not an in-toto payload or does not decode, and empty output are refused
// outright rather than skipped — cosign printing something we cannot read is
// not evidence of anything. The whole stream is read before deciding, so this
// holds after a match too. Well-formed statements that simply do not match
// (another builder signing the same digest) do not count, and the error names
// what each one got wrong.
func VerifyProvenanceOutput(out []byte, want ProvenanceExpectation) (*VerifiedProvenance, error) {
digest, err := ImageDigest(want.Image)
if err != nil {
return nil, err
}
if want.BuilderID == "" || strings.TrimSpace(want.BuilderID) != want.BuilderID {
return nil, fmt.Errorf("expected builder id %q must be non-empty with no surrounding whitespace", want.BuilderID)
}
repo := normaliseRepo(want.SourceRepo)
if repo == "" || strings.ContainsAny(want.SourceRepo, " \t\r\n") {
return nil, fmt.Errorf("expected source repo %q must be a non-empty URI without whitespace", want.SourceRepo)
}
if carriesRef(repo) {
// "…/app@refs/heads/main" as the expectation would make every ref of
// that branch name match, and reads as if the ref were checked.
return nil, fmt.Errorf("expected source repo %q must not carry a ref (drop the @<ref> suffix)", want.SourceRepo)
}
dec := json.NewDecoder(bytes.NewReader(out))
var mismatches []string
var found *VerifiedProvenance
n := 0
for {
var env envelope
if err := dec.Decode(&env); errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, fmt.Errorf("cosign output is not a stream of DSSE envelopes: %w", err)
}
n++
st, err := decodeEnvelope(env)
if err != nil {
return nil, fmt.Errorf("attestation %d: %w", n, err)
}
vp, why := matchStatement(st, digest, want.BuilderID, repo)
if vp != nil {
if found == nil {
found = vp
}
continue
}
mismatches = append(mismatches, fmt.Sprintf("attestation %d: %s", n, why))
}
if n == 0 {
return nil, fmt.Errorf("cosign verified no provenance attestation")
}
if found != nil {
return found, nil
}
return nil, fmt.Errorf("no provenance matches builder %q, source %q and sha256 %s (%s)",
want.BuilderID, want.SourceRepo, digest, strings.Join(mismatches, "; "))
}
func decodeEnvelope(env envelope) (*statement, error) {
if env.PayloadType != InTotoPayloadType {
return nil, fmt.Errorf("DSSE payloadType %q is not %s", env.PayloadType, InTotoPayloadType)
}
if len(env.Signatures) == 0 {
return nil, fmt.Errorf("DSSE envelope carries no signature")
}
raw, err := base64.StdEncoding.DecodeString(env.Payload)
if err != nil {
// Some producers emit URL-safe base64; DSSE allows either.
if raw, err = base64.URLEncoding.DecodeString(env.Payload); err != nil {
return nil, fmt.Errorf("DSSE payload is not base64: %w", err)
}
}
var st statement
if err := json.Unmarshal(raw, &st); err != nil {
return nil, fmt.Errorf("DSSE payload is not an in-toto Statement: %w", err)
}
switch st.Type {
case "https://in-toto.io/Statement/v1", "https://in-toto.io/Statement/v0.1":
default:
return nil, fmt.Errorf("statement _type %q is not an in-toto Statement", st.Type)
}
return &st, nil
}
// matchStatement returns the verified provenance, or why the statement does
// not satisfy the expectation.
func matchStatement(st *statement, digest, builderID, repo string) (*VerifiedProvenance, string) {
if st.PredicateType != SLSAProvenanceV1 {
return nil, fmt.Sprintf("predicateType %q is not %s", st.PredicateType, SLSAProvenanceV1)
}
var subjects []string
about := false
for _, s := range st.Subject {
d := strings.ToLower(s.Digest["sha256"])
if d == "" {
continue
}
subjects = append(subjects, s.Name+"@sha256:"+d)
if d == digest {
about = true
}
}
if !about {
return nil, fmt.Sprintf("no subject with sha256 %s", digest)
}
var p provenancePredicate
if err := json.Unmarshal(st.Predicate, &p); err != nil {
return nil, fmt.Sprintf("predicate is not SLSA v1 provenance: %v", err)
}
if got := p.RunDetails.Builder.ID; got != builderID {
return nil, fmt.Sprintf("builder.id is %q", got)
}
deps := p.BuildDefinition.ResolvedDependencies
if len(deps) == 0 {
return nil, "no resolvedDependencies: the source is not recorded"
}
src := deps[0]
if !sameRepo(src.URI, repo) {
return nil, fmt.Sprintf("source (first resolvedDependency) is %q", src.URI)
}
if !pinnedToCommit(src.Digest) {
return nil, "source is not pinned to a commit (gitCommit/sha1/sha256 of 40 or 64 hex)"
}
return &VerifiedProvenance{BuilderID: builderID, SourceURI: src.URI, Subjects: subjects}, ""
}
// pinnedToCommit reports a gitCommit / sha1 / sha256 digest that is a full
// commit id. `{"gitCommit": "main"}` is a branch name, not a pin.
func pinnedToCommit(d map[string]string) bool {
for _, k := range []string{"gitCommit", "sha1", "sha256"} {
if commitID.MatchString(strings.ToLower(d[k])) {
return true
}
}
return false
}
// normaliseRepo drops the `git+` transport prefix and a trailing `.git` / `/`.
func normaliseRepo(u string) string {
u = strings.TrimPrefix(strings.TrimSpace(u), "git+")
u = strings.TrimSuffix(u, "/")
return strings.TrimSuffix(u, ".git")
}
// carriesRef reports an "@" in the path of a URL ("https://h/o/r@ref"). The
// userinfo "@" of "https://u@h/o/r" and of scp-style "git@h:o/r" is allowed.
func carriesRef(repo string) bool {
i := strings.Index(repo, "://")
if i < 0 {
colon := strings.Index(repo, ":")
if colon < 0 {
return strings.Contains(repo, "@")
}
return strings.LastIndex(repo, "@") > colon
}
rest := repo[i+3:]
slash := strings.Index(rest, "/")
return slash >= 0 && strings.Contains(rest[slash:], "@")
}
// sameRepo reports whether a dependency uri names repo: exactly, or repo
// followed by "@<ref>". "…/app-evil@…" and "…/app/fork@…" do not match "…/app".
func sameRepo(uri, repo string) bool {
u := strings.TrimPrefix(strings.TrimSpace(uri), "git+")
for _, r := range []string{repo, repo + ".git"} {
if u == r || u == r+"/" || strings.HasPrefix(u, r+"@") {
return true
}
}
return false
}
+324
View File
@@ -0,0 +1,324 @@
package attestation
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"testing"
)
const (
vBuilder = "https://github.com/acme/app/.github/workflows/release.yml@refs/tags/v1.2.3"
vRepo = "https://github.com/acme/app"
vSource = "git+https://github.com/acme/app@refs/tags/v1.2.3"
)
var signer, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
// pae is the DSSE v1 pre-authentication encoding the signature covers.
func pae(payloadType string, payload []byte) []byte {
return []byte(fmt.Sprintf("DSSEv1 %d %s %d %s", len(payloadType), payloadType, len(payload), payload))
}
// envelopeLine builds a real, signed DSSE envelope exactly as cosign v2
// `verify-attestation` prints it: one compact JSON object per line.
func envelopeLine(t *testing.T, payloadType string, payload []byte) string {
t.Helper()
h := sha256.Sum256(pae(payloadType, payload))
sig, err := ecdsa.SignASN1(rand.Reader, signer, h[:])
if err != nil {
t.Fatal(err)
}
b, err := json.Marshal(map[string]any{
"payloadType": payloadType,
"payload": base64.StdEncoding.EncodeToString(payload),
"signatures": []map[string]string{{"keyid": "", "sig": base64.StdEncoding.EncodeToString(sig)}},
})
if err != nil {
t.Fatal(err)
}
return string(b) + "\n"
}
type stOpts struct {
typ, predicateType, builder, depURI, subjectDigest string
depDigest map[string]string
// extraDeps follow the source in resolvedDependencies; noDeps drops all.
extraDeps []map[string]any
noDeps bool
}
func defaults() stOpts {
return stOpts{
typ: "https://in-toto.io/Statement/v1",
predicateType: SLSAProvenanceV1,
builder: vBuilder,
depURI: vSource,
subjectDigest: digestA,
depDigest: map[string]string{"gitCommit": commit},
}
}
func statementJSON(t *testing.T, o stOpts) []byte {
t.Helper()
deps := append([]map[string]any{{"uri": o.depURI, "digest": o.depDigest}}, o.extraDeps...)
if o.noDeps {
deps = []map[string]any{}
}
b, err := json.Marshal(map[string]any{
"_type": o.typ,
"predicateType": o.predicateType,
"subject": []map[string]any{{
"name": "registry.example/team/orders",
"digest": map[string]string{"sha256": o.subjectDigest},
}},
"predicate": map[string]any{
"buildDefinition": map[string]any{
"buildType": "https://actions.github.io/buildtypes/workflow/v1",
// The expected builder id quoted where it does not count —
// a substring match over the decoded statement would pass.
"externalParameters": map[string]string{"source": o.depURI, "note": vBuilder + " " + vRepo},
"resolvedDependencies": deps,
},
"runDetails": map[string]any{
"builder": map[string]any{"id": o.builder, "version": map[string]string{"dagger-engine": "v0.21.7"}},
"metadata": map[string]string{"invocationId": "42"},
},
},
})
if err != nil {
t.Fatal(err)
}
return b
}
func provenanceLine(t *testing.T, mut func(*stOpts)) string {
o := defaults()
if mut != nil {
mut(&o)
}
return envelopeLine(t, InTotoPayloadType, statementJSON(t, o))
}
func expect() ProvenanceExpectation {
return ProvenanceExpectation{Image: imageA, BuilderID: vBuilder, SourceRepo: vRepo}
}
func TestVerifyProvenanceOutputAcceptsMatchingStatement(t *testing.T) {
vp, err := VerifyProvenanceOutput([]byte(provenanceLine(t, nil)), expect())
if err != nil {
t.Fatalf("legitimate provenance refused: %v", err)
}
if vp.BuilderID != vBuilder || vp.SourceURI != vSource {
t.Fatalf("wrong verified fields: %+v", vp)
}
if len(vp.Subjects) != 1 || vp.Subjects[0] != "registry.example/team/orders@sha256:"+digestA {
t.Fatalf("subjects: %v", vp.Subjects)
}
}
// Why #2337 exists: cosign prints the statement base64-encoded, so the old
// strings.Contains(out, builderID) could never see the builder id at all.
func TestBuilderIDIsNotPlainTextInCosignOutput(t *testing.T) {
out := provenanceLine(t, nil)
if strings.Contains(out, vBuilder) || strings.Contains(out, vRepo) {
t.Fatal("fixture is not shaped like cosign output: the statement must be base64 inside the envelope")
}
}
func TestVerifyProvenanceOutputAcceptsLegitimateVariants(t *testing.T) {
cases := map[string]struct {
out string
want func(*ProvenanceExpectation)
}{
"in-toto v0.1": {provenanceLine(t, func(o *stOpts) { o.typ = "https://in-toto.io/Statement/v0.1" }), nil},
"dep without git+ and with .git": {provenanceLine(t, func(o *stOpts) {
o.depURI = "https://github.com/acme/app.git@refs/heads/main"
}), nil},
"dep is the bare repo": {provenanceLine(t, func(o *stOpts) { o.depURI = vRepo }), nil},
"expected repo with git+ and trailing slash": {provenanceLine(t, nil), func(w *ProvenanceExpectation) {
w.SourceRepo = "git+https://github.com/acme/app/"
}},
"sha1 dep digest": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"sha1": commit} }), nil},
"uppercase subject hex": {provenanceLine(t, func(o *stOpts) { o.subjectDigest = strings.ToUpper(digestA) }), nil},
"image with registry port and no tag": {provenanceLine(t, nil), func(w *ProvenanceExpectation) {
w.Image = "registry.example:5000/team/orders@sha256:" + digestA
}},
"scp-style expected repo": {provenanceLine(t, func(o *stOpts) { o.depURI = "git+git@github.com:acme/app.git@refs/tags/v1" }),
func(w *ProvenanceExpectation) { w.SourceRepo = "git@github.com:acme/app" }},
// A second builder attesting the same digest is legitimate; the gate
// asks whether the EXPECTED builder vouched for it.
"other builder first, expected second": {
provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/other" }) + provenanceLine(t, nil), nil},
"dep with trailing slash": {provenanceLine(t, func(o *stOpts) { o.depURI = vRepo + "/" }), nil},
// carriesRef must allow the userinfo "@" of an https URL.
"https expected repo with userinfo": {provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://git@github.com/acme/app@refs/tags/v1" }),
func(w *ProvenanceExpectation) { w.SourceRepo = "https://git@github.com/acme/app" }},
"envelopes without trailing newline": {strings.TrimSuffix(provenanceLine(t, nil), "\n"), nil},
// Later dependencies are build inputs; only the first is the source.
"source first, other inputs after": {provenanceLine(t, func(o *stOpts) {
o.extraDeps = []map[string]any{{"uri": "pkg:golang/example.test/lib@v1", "digest": map[string]string{"sha256": digestB}}}
}), nil},
"uppercase commit hex": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": strings.ToUpper(commit)} }), nil},
"64-hex sha256 commit": {provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"sha256": digestA} }), nil},
}
for name, c := range cases {
w := expect()
if c.want != nil {
c.want(&w)
}
if _, err := VerifyProvenanceOutput([]byte(c.out), w); err != nil {
t.Errorf("%s: refused: %v", name, err)
}
}
}
func TestVerifyProvenanceOutputRefusesMismatches(t *testing.T) {
cases := map[string]string{
// Substring/prefix relations a strings.Contains check would accept.
"builder id extends expected": provenanceLine(t, func(o *stOpts) { o.builder = vBuilder + "-rc1" }),
"builder id is a prefix": provenanceLine(t, func(o *stOpts) { o.builder = strings.TrimSuffix(vBuilder, ".3") }),
"builder id differs in case": provenanceLine(t, func(o *stOpts) { o.builder = strings.ToUpper(vBuilder) }),
"builder only in a note": provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/attacker" }),
"repo name extended": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com/acme/app-evil@refs/tags/v1.2.3" }),
"repo is a sub path": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com/acme/app/fork@refs/tags/v1.2.3" }),
"repo on another host": provenanceLine(t, func(o *stOpts) { o.depURI = "git+https://github.com.evil.test/acme/app@refs/tags/v1" }),
"dep has no digest": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{} }),
"dep digest is blank": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": " "} }),
// A digest that is not a full commit id pins nothing.
"dep digest is a branch name": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": "main"} }),
"dep digest is a short sha": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"gitCommit": commit[:12]} }),
"dep digest under another key": provenanceLine(t, func(o *stOpts) { o.depDigest = map[string]string{"md5": commit} }),
"no resolvedDependencies": provenanceLine(t, func(o *stOpts) { o.noDeps = true }),
// A repo that vendors the expected one lists it as a later input; it
// must not pass as having been built from it.
"expected repo only as a later dependency": provenanceLine(t, func(o *stOpts) {
o.depURI = "git+https://github.com/attacker/app@refs/heads/main"
o.extraDeps = []map[string]any{{"uri": vSource, "digest": map[string]string{"gitCommit": commit}}}
}),
// The statement is about another artifact.
"subject is another digest": provenanceLine(t, func(o *stOpts) { o.subjectDigest = digestB }),
"wrong predicate type": provenanceLine(t, func(o *stOpts) { o.predicateType = "https://slsa.dev/provenance/v0.2" }),
}
for name, out := range cases {
if _, err := VerifyProvenanceOutput([]byte(out), expect()); err == nil {
t.Errorf("%s: must be refused", name)
}
}
}
func TestVerifyProvenanceOutputRefusesUnreadableOutput(t *testing.T) {
good := provenanceLine(t, nil)
notBase64, _ := json.Marshal(map[string]any{
"payloadType": InTotoPayloadType, "payload": "%%%not base64%%%",
"signatures": []map[string]string{{"sig": "AA=="}},
})
unsigned, _ := json.Marshal(map[string]any{
"payloadType": InTotoPayloadType,
"payload": base64.StdEncoding.EncodeToString(statementJSON(t, defaults())),
"signatures": []map[string]string{},
})
cases := map[string]string{
"empty output": "",
"only whitespace": "\n \n",
"plain text with the ids": "verified " + vBuilder + " from " + vRepo + " sha256:" + digestA + "\n",
"truncated envelope": good[:len(good)/2],
"wrong payload type": envelopeLine(t, "text/plain", statementJSON(t, defaults())),
"payload not base64": string(notBase64) + "\n",
"payload not json": envelopeLine(t, InTotoPayloadType, []byte("not json")),
"not an in-toto type": envelopeLine(t, InTotoPayloadType, statementJSON(t, stOpts{typ: "https://example.test/Statement", predicateType: SLSAProvenanceV1, builder: vBuilder, depURI: vSource, subjectDigest: digestA, depDigest: map[string]string{"gitCommit": commit}})),
"envelope with no signature": string(unsigned) + "\n",
// Fail-closed: an unreadable envelope is not skipped even when a
// good one follows — cosign printing something we cannot parse means
// our model of its output is wrong.
"garbage before a good envelope": envelopeLine(t, InTotoPayloadType, []byte("{")) + good,
// ...and the whole stream is read before deciding, so garbage after
// a match is refused too.
"garbage after a good envelope": good + envelopeLine(t, InTotoPayloadType, []byte("{")),
"truncated envelope after a good one": good + good[:len(good)/2],
}
for name, out := range cases {
if _, err := VerifyProvenanceOutput([]byte(out), expect()); err == nil {
t.Errorf("%s: must be refused", name)
}
}
}
func TestVerifyProvenanceOutputRefusesBadExpectations(t *testing.T) {
out := []byte(provenanceLine(t, nil))
cases := map[string]func(*ProvenanceExpectation){
"tag-only image": func(w *ProvenanceExpectation) { w.Image = "registry.example/team/orders:abc" },
"empty builder": func(w *ProvenanceExpectation) { w.BuilderID = "" },
"padded builder": func(w *ProvenanceExpectation) { w.BuilderID = " " + vBuilder },
"empty repo": func(w *ProvenanceExpectation) { w.SourceRepo = "" },
"repo with whitespace": func(w *ProvenanceExpectation) { w.SourceRepo = vRepo + " x" },
"repo carrying a ref": func(w *ProvenanceExpectation) { w.SourceRepo = vRepo + "@refs/tags/v1.2.3" },
"scp repo carrying a ref": func(w *ProvenanceExpectation) { w.SourceRepo = "git@github.com:acme/app@v1" },
}
for name, mut := range cases {
w := expect()
mut(&w)
if _, err := VerifyProvenanceOutput(out, w); err == nil {
t.Errorf("%s: must be refused", name)
}
}
}
// The refusal says which field was wrong, so an operator can tell a wrong
// --expected-builder-id from an image built elsewhere.
func TestVerifyProvenanceOutputNamesTheMismatch(t *testing.T) {
_, err := VerifyProvenanceOutput([]byte(provenanceLine(t, func(o *stOpts) { o.builder = "https://ci.example/other" })), expect())
if err == nil || !strings.Contains(err.Error(), `builder.id is "https://ci.example/other"`) {
t.Fatalf("error does not name the builder mismatch: %v", err)
}
}
// The signer, not the builder.id string it wrote, is the trust anchor: with no
// identity regex cosign must be told the exact identity = the expected builder.
func TestVerifyAttestationArgsBindsTheSignerToTheBuilder(t *testing.T) {
issuer := `https://token\.actions\.githubusercontent\.com`
got := strings.Join(VerifyAttestationArgs(imageA, vBuilder, "", issuer), " ")
want := "cosign verify-attestation --type slsaprovenance1 --certificate-oidc-issuer-regexp " +
"^(?:" + issuer + ")$ --certificate-identity " + vBuilder + " " + imageA
if got != want {
t.Fatalf("default args:\n got %s\nwant %s", got, want)
}
re := `^https://github\.com/acme/app/\.github/workflows/release\.yml@refs/tags/v.*$`
args := VerifyAttestationArgs(imageA, vBuilder, re, issuer)
joined := strings.Join(args, " ")
if !strings.Contains(joined, "--certificate-identity-regexp ^(?:"+re+")$") {
t.Fatalf("regex not passed: %s", joined)
}
for _, a := range args {
if a == "--certificate-identity" {
t.Fatalf("regex and exact identity both passed: %s", joined)
}
}
if args[len(args)-1] != imageA {
t.Fatalf("image must be the last argument: %s", joined)
}
}
// The ref check must be what refuses: here the dep would otherwise match the
// expectation exactly, so deleting carriesRef makes these pass.
func TestExpectedRepoCarryingARefIsRefusedEvenWhenTheDepMatches(t *testing.T) {
cases := map[string]string{
"https": vRepo + "@refs/tags/v1.2.3",
"scp": "git@github.com:acme/app@v1",
}
for name, repo := range cases {
out := provenanceLine(t, func(o *stOpts) { o.depURI = "git+" + repo })
w := expect()
w.SourceRepo = repo
_, err := VerifyProvenanceOutput([]byte(out), w)
if err == nil || !strings.Contains(err.Error(), "must not carry a ref") {
t.Errorf("%s: want the ref refusal, got %v", name, err)
}
}
}