Files
integraci-dagger-modules/cosign/attestation/verify_test.go
T

325 lines
15 KiB
Go

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.11"}},
"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)
}
}
}