// Package main implements the IntegraCI Cosign Dagger module. // // Signs container images with Cosign (Sigstore) using either keyless OIDC // (recommended for CI) or a key pair stored in OpenBao. Verification uses the // same modes. Outputs: signature reference, transparency log entry URL. // // Usage (sign with keyless): // // dagger call sign \ // --image ghcr.io/integraci/payments-api:1.2.3 \ // --keyless \ // --identity-token env:ACTIONS_ID_TOKEN_REQUEST_TOKEN // // Usage (sign with key from OpenBao): // // dagger call sign \ // --image ghcr.io/integraci/payments-api:1.2.3 \ // --private-key file:cosign.key \ // --password env:COSIGN_PASSWORD // // Usage (verify): // // dagger call verify --image ghcr.io/integraci/payments-api:1.2.3 --public-key file:cosign.pub package main import ( "context" "crypto/sha256" "dagger/cosign/attestation" "dagger/cosign/internal/dagger" _ "embed" "encoding/hex" "fmt" "os" "strings" "time" ) // gatePolicy is the attestation gate, byte-identical to // infra/policies/bundles/attestation-gate/attestation_gate.rego (a test in // apps/api/tests/test_supply_chain_phase2.py keeps the two in step). // //go:embed policy/attestation_gate.rego var gatePolicy string // opaImage evaluates the gate. Tag-pinned, the same version the platform's // own OPA runs; no digest is pinned because none was looked up (#2143). const opaImage = "openpolicyagent/opa:1.0.0" // daggerEngineVersion is the engine every module's dagger.json pins; recorded // as the provenance builder version. Before #2143 this said v0.15.0. const daggerEngineVersion = "v0.21.11" // Cosign is the IntegraCI artifact signing module. type Cosign struct{} // SignResult contains the output of a signing operation. type SignResult struct { Image string `json:"image"` Signature string `json:"signature"` // Cosign signature reference (e.g., image:tag.sig) TransparencyLog string `json:"transparency_log"` // Rekor entry URL (keyless mode) BundlePath string `json:"bundle_path,omitempty"` Success bool `json:"success"` KeylessIdentity string `json:"keyless_identity,omitempty"` // Notice is set when the call relied on a deprecated default (see // attestation.LegacyKeylessNotice); also printed to stderr. Notice string `json:"notice,omitempty"` } // VerifyResult contains the output of a verification operation. type VerifyResult struct { Image string `json:"image"` Verified bool `json:"verified"` Subjects []string `json:"subjects,omitempty"` // Subject identities from cert (keyless) Error string `json:"error,omitempty"` } // cosignContainer returns a fresh Cosign container with an isolated home so // runs don't pollute each other's keychain / SIGSTORE_* state. func (m *Cosign) cosignContainer() *dagger.Container { return dag.Container(). From("gcr.io/projectsigstore/cosign:v3.1.4"). WithEnvVariable("HOME", "/tmp/cosign-home"). WithEnvVariable("COSIGN_YES", "true"). // non-interactive // cosign v3 (2026-11-04 bump, docs/security/vuln-remediation-20261104.md) // defaults to a TUF-fetched signing config, which REFUSES the keyed // `--tlog-upload=false` this module signs with (v3.1.4 // signcommon.ValidateSigningOptions) and fetches from the public TUF root // on every call. cosign reads every flag from COSIGN_ (options/ // root.go BindViper), and an explicit flag still wins: these two keep // the v2.4.1 behaviour every caller and verifier here was written for. WithEnvVariable("COSIGN_USE_SIGNING_CONFIG", "false"). WithEnvVariable("COSIGN_NEW_BUNDLE_FORMAT", "false") } // Sign signs a container image with Cosign. // // Mode selection: // - If keyless == true: use OIDC identity (Fulcio + Rekor). Requires ambient // OIDC token (GitHub Actions, GitLab CI) or --identity-token override. // - Else: use the supplied --private-key (file or env). Optional --password. func (m *Cosign) Sign( ctx context.Context, // Full image reference including digest or tag (e.g. ghcr.io/org/app:1.0.0) image string, // Use keyless signing via Fulcio/Rekor (recommended for CI) // +optional keyless bool, // Private key (Cosign-format) for keyed signing // +optional privateKey *dagger.Secret, // Password for the private key (if encrypted) // +optional password *dagger.Secret, // Identity token (OIDC) override — when not running on a supported CI // +optional identityToken *dagger.Secret, // Registry username (for pushing the .sig artifact) // +optional registryUser string, // Registry password / token // +optional registryPassword *dagger.Secret, // Annotations to attach (key=value, comma-separated) // +optional annotations string, // Upload the keyed signature to the PUBLIC Sigstore Rekor (off by default: // an entry there is public and permanent) // +optional publicRekor bool, // Private Rekor to upload to instead (https; wins over --public-rekor) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url // +optional rekorPublicKey *dagger.Secret, ) (*SignResult, error) { if image == "" { return nil, fmt.Errorf("--image is required") } if !keyless && privateKey == nil { return nil, fmt.Errorf("either --keyless or --private-key must be provided") } tlog, err := signTlog(keyless, rekorURL, publicRekor) if err != nil { return nil, err } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) // Registry auth (so we can push the signature artifact) if registryUser != "" && registryPassword != nil { c = c. WithSecretVariable("REG_PASSWORD", registryPassword). WithExec([]string{ "sh", "-c", fmt.Sprintf("cosign login %s -u %s -p $REG_PASSWORD", registryHost(image), registryUser), }) } args := []string{"cosign", "sign"} if annotations != "" { for _, kv := range strings.Split(annotations, ",") { kv = strings.TrimSpace(kv) if kv == "" { continue } args = append(args, "-a", kv) } } result := &SignResult{Image: image} if keyless { // Use Sigstore Public Good Instance for Fulcio + Rekor. c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") if identityToken != nil { c = c.WithSecretVariable("COSIGN_IDENTITY_TOKEN", identityToken) args = append(args, "--identity-token", "$COSIGN_IDENTITY_TOKEN") } // Joined into `sh -c` below: CheckRekorURL's charset keeps it inert. args = append(args, tlog...) args = append(args, image) out, err := c.WithExec([]string{"sh", "-c", strings.Join(args, " ")}).Stderr(ctx) if err != nil { return nil, fmt.Errorf("cosign keyless sign failed: %w", err) } result.TransparencyLog = extractRekorURL(out) result.KeylessIdentity = extractIdentity(out) } else { c = c.WithMountedSecret("/tmp/cosign.key", privateKey) if password != nil { c = c.WithSecretVariable("COSIGN_PASSWORD", password) } args = append(args, "--key", "/tmp/cosign.key") args = append(args, tlog...) args = append(args, image) if _, err := c.WithExec(args).Sync(ctx); err != nil { return nil, fmt.Errorf("cosign keyed sign failed: %w", err) } } result.Signature = signatureRef(image) result.Success = true return result, nil } // SignMethod is the engine-agnostic signing entrypoint. It dispatches to the // requested signing backend so ANY CI engine can sign an image via a single // `dagger call sign-method` invocation, mirroring // security_pipeline_adapter.build_signing_step. // // Supported methods: // - cosign: Sigstore cosign. KEYED with --key (the default rendered // pipelines use since 2026-10-18; no transparency-log upload unless // --public-rekor / --rekor-url). KEYLESS only with --keyless: the signing // identity and digest go to the PUBLIC Sigstore Rekor unless --rekor-url // names a private one. With neither flag the call behaves as it always did // (keyless) and prints a deprecation notice: pipelines rendered before // 2026-10-18 make exactly that call and must keep working. // - notation: NotaryProject `notation sign` (COSE) using the supplied key. // - gpg: GPG detached-sign of the image manifest. // - in-toto: in-toto CLI attestation (link metadata) over the manifest. // - none: no-op skip (mirrors the adapter's _comment_skip). // // Usage (keyed cosign — the default): // // dagger call sign-method --method cosign --image-ref ghcr.io/org/app:1.0.0 --key env://COSIGN_PRIVATE_KEY // // Usage (keyless cosign against a private Rekor): // // dagger call sign-method --method cosign --image-ref ghcr.io/org/app:1.0.0 --keyless \ // --identity-token env://SIGSTORE_ID_TOKEN \ // --rekor-url https://rekor.example.internal --rekor-public-key env://COSIGN_REKOR_PUBLIC_KEY func (m *Cosign) SignMethod( ctx context.Context, // Signing method: cosign | notation | gpg | in-toto | none // +optional // +default="cosign" method string, // Full image reference including digest or tag imageRef string, // Signing key material. Interpretation depends on method: // cosign -> Cosign private key (keyless when omitted) // notation-> signing key (PEM) // gpg -> ASCII-armored GPG private key to import // in-toto -> in-toto functionary signing key (PEM) // +optional key *dagger.Secret, // cosign only: upload a keyed signature to the PUBLIC Sigstore Rekor (off // by default) // +optional publicRekor bool, // cosign only: private Rekor to use instead (https; wins over --public-rekor) // +optional rekorURL string, // cosign only: sign KEYLESS (Fulcio certificate + transparency log). The // entry is PUBLIC unless --rekor-url names a private Rekor. Mutually // exclusive with --key. // +optional keyless bool, // cosign keyless only: OIDC identity token for Fulcio. Handed to cosign // through SIGSTORE_ID_TOKEN, never on the command line (argv is visible in // Dagger traces). Without it cosign looks for an ambient provider, which a // Dagger container does not inherit from the CI runner. // +optional identityToken *dagger.Secret, // cosign keyed only: password of an encrypted private key. Without it an // empty password is assumed (cosign would otherwise wait on a terminal). // +optional password *dagger.Secret, // cosign only: public key (PEM) of the private Rekor at --rekor-url. cosign // checks the log entry it gets back against it. // +optional rekorPublicKey *dagger.Secret, ) (*SignResult, error) { if method == "" { method = "cosign" } if method != "cosign" && (keyless || identityToken != nil || rekorPublicKey != nil) { return nil, fmt.Errorf("--keyless, --identity-token and --rekor-public-key apply to --method cosign only") } if method != "none" && imageRef == "" { return nil, fmt.Errorf("--image-ref is required") } switch method { case "none": // No-op skip, mirroring the adapter's _comment_skip intent. return &SignResult{ Image: imageRef, Success: true, }, nil case "cosign": mode, legacy, err := attestation.SignMethodMode(key != nil, keyless) if err != nil { return nil, err } if mode == "keyed" && identityToken != nil { return nil, fmt.Errorf("--identity-token is for keyless signing; keyed signing uses --key") } tlog, err := signTlog(mode == "keyless", rekorURL, publicRekor) if err != nil { return nil, err } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) if mode == "keyless" { notice := "" if legacy { // Printed so it lands in the CI log of every pipeline that still // relies on the old default, whether or not it is ever re-rendered. notice = attestation.LegacyKeylessNotice fmt.Fprintln(os.Stderr, notice) } // Keyless OIDC (Fulcio + Rekor). c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") if identityToken != nil { c = c.WithSecretVariable("SIGSTORE_ID_TOKEN", identityToken) } args := append([]string{"cosign", "sign", "--yes"}, tlog...) out, err := c.WithExec(append(args, imageRef)).Stderr(ctx) if err != nil { return nil, fmt.Errorf("cosign keyless sign failed: %w", err) } return &SignResult{ Image: imageRef, Signature: signatureRef(imageRef), TransparencyLog: extractRekorURL(out), KeylessIdentity: extractIdentity(out), Success: true, Notice: notice, }, nil } // Keyed signing via env://COSIGN_PRIVATE_KEY. c = c.WithSecretVariable("COSIGN_PRIVATE_KEY", key) if password != nil { c = c.WithSecretVariable("COSIGN_PASSWORD", password) } else { c = c.WithEnvVariable("COSIGN_PASSWORD", "") } args := append([]string{"cosign", "sign", "--yes", "--key", "env://COSIGN_PRIVATE_KEY"}, tlog...) if _, err := c.WithExec(append(args, imageRef)).Sync(ctx); err != nil { return nil, fmt.Errorf("cosign keyed sign failed: %w", err) } return &SignResult{ Image: imageRef, Signature: signatureRef(imageRef), Success: true, }, nil case "notation": if key == nil { return nil, fmt.Errorf("--key is required for notation signing") } // NotaryProject notation CLI: sign with a COSE signature. c := dag.Container(). From("notaryproject/notation:v1.3.1"). WithEnvVariable("HOME", "/tmp/notation-home"). WithMountedSecret("/tmp/notation.key", key) if _, err := c.WithExec([]string{ "notation", "sign", "--signature-format", "cose", "--key", "/tmp/notation.key", imageRef, }).Sync(ctx); err != nil { return nil, fmt.Errorf("notation sign failed: %w", err) } return &SignResult{ Image: imageRef, Signature: imageRef + " (notation cose signature)", Success: true, }, nil case "gpg": if key == nil { return nil, fmt.Errorf("--key is required for gpg signing") } // Import the GPG key, inspect the manifest, and produce a detached // armored signature over it. c := dag.Container(). From("alpine:3.20"). WithExec([]string{"apk", "add", "--no-cache", "gnupg", "skopeo"}). WithMountedSecret("/tmp/gpg.key", key). WithEnvVariable("CACHEBUST", imageRef) script := strings.Join([]string{ "gpg --batch --import /tmp/gpg.key", fmt.Sprintf("skopeo inspect --raw docker://%s > manifest.json", imageRef), "gpg --batch --yes --detach-sign --armor manifest.json", }, " && ") if _, err := c.WithExec([]string{"sh", "-c", script}).Sync(ctx); err != nil { return nil, fmt.Errorf("gpg sign failed: %w", err) } return &SignResult{ Image: imageRef, Signature: imageRef + " (gpg detached manifest.json.asc)", Success: true, }, nil case "in-toto": if key == nil { return nil, fmt.Errorf("--key is required for in-toto attestation") } // in-toto CLI: record a link-metadata attestation over the image. c := dag.Container(). From("python:3.12-slim"). WithExec([]string{"pip", "install", "--no-cache-dir", "in-toto"}). WithMountedSecret("/tmp/intoto.key", key). WithEnvVariable("CACHEBUST", imageRef) script := strings.Join([]string{ fmt.Sprintf(`in-toto-run --step-name sign --key /tmp/intoto.key --products "%s" --no-command`, imageRef), }, " && ") if _, err := c.WithExec([]string{"sh", "-c", script}).Sync(ctx); err != nil { return nil, fmt.Errorf("in-toto attestation failed: %w", err) } return &SignResult{ Image: imageRef, Signature: imageRef + " (in-toto link attestation)", Success: true, }, nil default: return nil, fmt.Errorf("unsupported signing method: %q (want cosign|notation|gpg|in-toto|none)", method) } } // Verify checks that an image carries a valid Cosign signature. func (m *Cosign) Verify( ctx context.Context, image string, // Public key for keyed verification // +optional publicKey *dagger.Secret, // Expect a keyless signature; --identity-regex / --issuer-regex required if so. // +optional keyless bool, // Regex for the signing identity (e.g. ".+@integraci\\.io") // +optional identityRegex string, // Regex for the OIDC issuer (e.g. "https://token\\.actions\\.githubusercontent\\.com") // +optional issuerRegex string, // Keyed: the signature was uploaded to the PUBLIC Rekor (same choice as // at signing; without it the key alone is checked) // +optional publicRekor bool, // Private Rekor the signature was uploaded to (https) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url; required with it // (the log entry's SET is checked against this key) // +optional rekorPublicKey *dagger.Secret, ) (*VerifyResult, error) { if image == "" { return nil, fmt.Errorf("--image is required") } tlog, err := verifyTlog(keyless, rekorURL, publicRekor) if err != nil { return nil, err } if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { return nil, err } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey) args := []string{"cosign", "verify"} if keyless { c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") if identityRegex == "" || issuerRegex == "" { return nil, fmt.Errorf("--identity-regex and --issuer-regex required for keyless verify") } if err := attestation.CheckRegex("--identity-regex", identityRegex); err != nil { return nil, err } if err := attestation.CheckRegex("--issuer-regex", issuerRegex); err != nil { return nil, err } // Anchored to the whole value (#2435): cosign matches anywhere. args = append(args, "--certificate-identity-regexp", attestation.AnchorRegex(identityRegex), "--certificate-oidc-issuer-regexp", attestation.AnchorRegex(issuerRegex), ) } else { if publicKey == nil { return nil, fmt.Errorf("--public-key required for keyed verify") } c = c.WithMountedSecret("/tmp/cosign.pub", publicKey) args = append(args, "--key", "/tmp/cosign.pub") } args = append(args, tlog...) args = append(args, image) out, err := c.WithExec(args).Stdout(ctx) if err != nil { return &VerifyResult{Image: image, Verified: false, Error: err.Error()}, nil } return &VerifyResult{ Image: image, Verified: true, Subjects: extractSubjects(out), }, nil } // AttestProvenance generates an SLSA Build Level 3 provenance predicate // (in-toto attestation) and attaches it to the image. The predicate is // built in-process from the supplied build metadata so it is consistent // regardless of the underlying CI provider. // // SLSA L3 requires: // - Build platform is hardened (e.g. ephemeral GitHub Actions runner // or Dagger engine in an isolated VM). // - Provenance is signed by the build platform (we sign with Cosign // keyless using the workflow's OIDC identity). // - Provenance is non-falsifiable (the OIDC subject is bound to the // workflow ref + commit SHA — verifiable at consumption time). // // The predicate type is `https://slsa.dev/provenance/v1` (SLSA v1.0). // // Usage (from a GitHub Actions release job): // // dagger call attest-provenance \ // --image ghcr.io/integraci/payments-api:1.2.3@sha256:<64 hex image digest> \ // --builder-id https://github.com/integraci/integraci/.github/workflows/release.yml@refs/tags/v1.2.3 \ // --source-uri git+https://github.com/integraci/integraci@refs/tags/v1.2.3 \ // --source-digest "$(git rev-parse HEAD)" \ // --build-type https://actions.github.io/buildtypes/workflow/v1 \ // --invocation-id ${{ github.run_id }} \ // --keyless // // Usage (attach the statement standard-build `evidence` wrote — preferred, // so the archived evidence and the registry attestation are one set): // // dagger call attest-provenance \ // --image registry.example/team/orders:abc@sha256: \ // --predicate evidence/provenance.intoto.json --keyless func (m *Cosign) AttestProvenance( ctx context.Context, // Image reference pinned to a digest: [:tag]@sha256:<64 hex> image string, // SLSA `builder.id` — fully-qualified workflow ref. For GitHub Actions: // "https://github.com///.github/workflows/.yml@" // Required unless --predicate is given. // +optional builderID string, // SLSA `buildType` — e.g. "https://actions.github.io/buildtypes/workflow/v1" // +optional // +default="https://actions.github.io/buildtypes/workflow/v1" buildType string, // VCS source URI — "git+https://github.com//@". // Required unless --predicate is given. // +optional sourceURI string, // Full source commit id (40 or 64 hex; a `sha1:`/`sha256:` prefix is // tolerated) — pinpoints the exact commit. Required unless --predicate. // +optional sourceDigest string, // Build invocation ID (e.g. GitHub Actions run_id) for traceability. // +optional invocationID string, // Build start time in RFC3339. Defaults to now (the attest time — pass the // real value from CI when it matters). // +optional startedOn string, // Build finish time in RFC3339. Defaults to now. // +optional finishedOn string, // Use keyless OIDC signing (recommended for CI). // +optional keyless bool, // Private key for keyed signing. // +optional privateKey *dagger.Secret, // in-toto Statement (SLSA v1 provenance) written by standard-build // `evidence` — provenance.intoto.json. When given, its predicate is what // is attached, after checking its subject is --image's digest; --image // must then be digest-pinned, and the builder/source flags are ignored. // +optional predicate *dagger.File, // Registry username, so cosign can push the attestation to a private // registry. Paired with --registry-password. // +optional registryUsername string, // Registry password/token for --registry-username. // +optional registryPassword *dagger.Secret, // The registry is served over plain HTTP / self-signed TLS (same opt-in // as standard-build's --registry-insecure) // +optional registryInsecure bool, // Upload a keyed attestation to the PUBLIC Sigstore Rekor. Off by default: // the entry publishes the provenance (registry and git hosts, repository // paths, CI job URL, commit) permanently. // +optional publicRekor bool, // Private Rekor to upload to instead (https; wins over --public-rekor) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url // +optional rekorPublicKey *dagger.Secret, ) (*SignResult, error) { if image == "" { return nil, fmt.Errorf("--image is required") } tlog, err := signTlog(keyless, rekorURL, publicRekor) if err != nil { return nil, err } // Digest-pinned on BOTH paths. cosign resolves a tag at attest time, so a // tag pushed again between build and attest would sign provenance about // another build's image — the gap `standard-build evidence` refuses too. if _, err := attestation.ImageDigest(image); err != nil { return nil, fmt.Errorf("--image: %w", err) } if predicate == nil && builderID == "" { return nil, fmt.Errorf("--builder-id is required (must be a stable, verifiable URI)") } if predicate == nil && (sourceURI == "" || sourceDigest == "") { return nil, fmt.Errorf("--source-uri and --source-digest are required") } if buildType == "" { buildType = "https://actions.github.io/buildtypes/workflow/v1" } var predicateBody []byte if predicate != nil { // Attach the statement standard-build's `evidence` wrote, byte for // byte its predicate — so what a verifier pulls from the registry is // what was archived with the build. Only after checking the statement // is about THIS digest. raw, err := predicate.Contents(ctx) if err != nil { return nil, fmt.Errorf("reading --predicate: %w", err) } predicateBody, err = attestation.PredicateFromStatement([]byte(raw), image) if err != nil { return nil, err } } else { var err error predicateBody, err = attestation.ProvenancePredicate(attestation.ProvenanceInput{ BuilderID: builderID, BuildType: buildType, SourceURI: sourceURI, SourceDigest: sourceDigest, InvocationID: invocationID, StartedOn: startedOn, FinishedOn: finishedOn, EngineVersion: daggerEngineVersion, Now: time.Now(), }) if err != nil { return nil, err } } c, err := withRegistryAuth(ctx, withRekorPublicKey(m.cosignContainer(), rekorPublicKey), image, registryUsername, registryPassword) if err != nil { return nil, err } c = c.WithNewFile("/tmp/provenance.json", string(predicateBody)) args := []string{ "cosign", "attest", "--type", "slsaprovenance1", "--predicate", "/tmp/provenance.json", } args = append(args, insecureRegistryArgs(registryInsecure)...) if keyless { c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") } else { if privateKey == nil { return nil, fmt.Errorf("--private-key required when not keyless") } // An empty COSIGN_PASSWORD is what a key generated with an empty // password needs; without it cosign asks a terminal there is none of. c = c.WithMountedSecret("/tmp/cosign.key", privateKey). WithEnvVariable("COSIGN_PASSWORD", "") args = append(args, "--key", "/tmp/cosign.key") } args = append(args, tlog...) args = append(args, image) out, err := c.WithExec(args).Stderr(ctx) if err != nil { return nil, fmt.Errorf("cosign attest provenance failed: %w", err) } return &SignResult{ Image: image, Signature: image + ".att (slsaprovenance1)", TransparencyLog: extractRekorURL(out), KeylessIdentity: extractIdentity(out), Success: true, }, nil } // VerifyProvenance verifies that an image carries an SLSA v1 provenance // attestation that was issued by the expected builder. This is the // gate consumers (e.g. Argo CD admission controller) should call before // promoting an image to production. // // cosign checks the signature; this then decodes each DSSE envelope and // requires one in-toto statement whose subject is --image's digest, whose // runDetails.builder.id equals --expected-builder-id exactly, and whose source // (first resolvedDependency) is --expected-source-repo pinned to a commit (see // attestation.VerifyProvenanceOutput). // // builder.id is only a string inside what was signed, so the trust anchor is // the SIGNER: by default the certificate identity must equal // --expected-builder-id (for GitHub Actions keyless signing both are // `https://github.com///.github/workflows/.yml@`). A // broad --identity-regex replaces that binding — then any workflow it admits // can claim the builder id. func (m *Cosign) VerifyProvenance( ctx context.Context, // Image reference pinned to a digest: [:tag]@sha256:<64 hex> image string, // Expected builder.id — must match exactly, and by default is also the // exact certificate identity the attestation must be signed by. expectedBuilderID string, // Expected source repository URI (without ref or commit digest). expectedSourceRepo string, // Cert-identity regex for the OIDC subject (keyless). Replaces the default // exact identity (= --expected-builder-id); anchor it (^…$). // +optional identityRegex string, // OIDC issuer regex (keyless). Matched against the WHOLE issuer: it is // anchored (^(?:…)$) before cosign sees it (#2435). // +optional // +default="https://token\\.actions\\.githubusercontent\\.com" issuerRegex string, // Private Rekor the attestation was logged in (https). Without it cosign // checks the public Sigstore Rekor, which a keyless signature needs. // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url; required with it // +optional rekorPublicKey *dagger.Secret, ) (*VerifyResult, error) { if image == "" { return nil, fmt.Errorf("--image is required") } if expectedBuilderID == "" || expectedSourceRepo == "" { return nil, fmt.Errorf("--expected-builder-id and --expected-source-repo are required") } tlog, err := attestation.KeylessTlogArgs(rekorURL) if err != nil { return nil, err } if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { return nil, err } if err := attestation.CheckRegex("--issuer-regex", issuerRegex); err != nil { return nil, err } if err := attestation.CheckRegex("--identity-regex", identityRegex); err != nil { return nil, err } // The statement's subject is compared with this digest, and a tag could // move between this check and the deploy it gates. if _, err := attestation.ImageDigest(image); err != nil { return nil, fmt.Errorf("--image: %w", err) } if issuerRegex == "" { issuerRegex = `https://token\.actions\.githubusercontent\.com` } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithEnvVariable("COSIGN_EXPERIMENTAL", "1") // Before #2337 an empty regex passed no identity flag at all, which cosign // v2 refuses for keyless verification — so the gate could not pass. Now the // signer is bound to the builder the statement must name. args := attestation.VerifyAttestationArgs(image, expectedBuilderID, identityRegex, issuerRegex) // The image stays the last argument; the log flags go before it. args = append(append(args[:len(args)-1:len(args)-1], tlog...), image) // Both refusals below are errors, so `dagger call verify-provenance` exits // non-zero: a gate written as `verify-provenance … && deploy` must stop. // Before #2337 they returned Verified:false with a nil error — exit 0 — // and only a caller that parsed .verified was protected. out, err := c.WithExec(args).Stdout(ctx) if err != nil { return nil, fmt.Errorf("provenance of %s not verified: cosign: %w", image, err) } // Decide on what the signed statement SAYS, field by field. Before #2337 // this was strings.Contains over the raw output — but cosign prints DSSE // envelopes whose payload is base64, so the builder id never appeared in // plain text, and a substring match would also have accepted a prefix of // the expected repo or the id quoted anywhere in the statement. vp, err := attestation.VerifyProvenanceOutput([]byte(out), attestation.ProvenanceExpectation{ Image: image, BuilderID: expectedBuilderID, SourceRepo: expectedSourceRepo, }) if err != nil { return nil, fmt.Errorf("provenance of %s not verified: %w", image, err) } return &VerifyResult{ Image: image, Verified: true, Subjects: vp.Subjects, }, nil } // withRegistryAuth logs cosign into the image's registry by mounting a // docker config.json as a secret. No shell and no argv carries the username or // password (compare Sign's `cosign login` line). Both empty = no auth, which // is the existing behaviour; exactly one of them is refused. func withRegistryAuth( ctx context.Context, c *dagger.Container, image, username string, password *dagger.Secret, ) (*dagger.Container, error) { if username == "" && password == nil { return c, nil } if username == "" || password == nil { return nil, fmt.Errorf("--registry-username and --registry-password go together") } plain, err := password.Plaintext(ctx) if err != nil { return nil, fmt.Errorf("reading --registry-password: %w", err) } host := attestation.RegistryHost(image) cfg, err := attestation.RegistryAuthConfig(host, username, plain) if err != nil { return nil, err } // Named by host and username only. The config holds the password, and a // secret's NAME can surface in traces, so it must not be derived from it. sum := sha256.Sum256([]byte(host + "\x00" + username)) secret := dag.SetSecret("cosign-registry-auth-"+hex.EncodeToString(sum[:8]), string(cfg)) // DOCKER_CONFIG, not $HOME/.docker: a mount under HOME would create HOME // owned by root, and cosign keeps its TUF cache there. Owned by 65532, the // nonroot user of the cosign image (harmless if it runs as root). return c. WithEnvVariable("DOCKER_CONFIG", "/tmp/docker-auth"). WithMountedSecret("/tmp/docker-auth/config.json", secret, cosignOwned), nil } // insecureRegistryArgs are cosign's flags for a registry without trusted TLS. func insecureRegistryArgs(insecure bool) []string { if !insecure { return nil } return []string{"--allow-insecure-registry", "--allow-http-registry"} } // cosignOwned makes a mounted secret readable by the cosign image's nonroot // user (65532). var cosignOwned = dagger.ContainerWithMountedSecretOpts{Owner: "65532"} // SignBlob signs a file with cosign `sign-blob` and returns a directory // holding `.sig` (base64 signature) and `.bundle` (signature, // certificate and transparency-log entry, for an offline verify-blob). // // Written for the SHA256SUMS that standard-build `evidence` emits (#2143 // phase 2). An unsigned SHA256SUMS detects CORRUPTION only: anyone who can // change a file can rewrite its line too. Signed, it detects TAMPERING: // // cosign verify-blob --key cosign.pub \ // --signature SHA256SUMS.sig --bundle SHA256SUMS.bundle SHA256SUMS // sha256sum -c --strict SHA256SUMS // // Keyed signing does NOT upload to a transparency log unless asked for // (--public-rekor, or --rekor-url for a private Rekor; owner decision // 2026-10-11), so it works air-gapped. Without a log entry, verify with // `cosign verify-blob --insecure-ignore-tlog=true …`: the key alone is the // trust anchor then. Keyless signing still needs a log (public unless // --rekor-url). func (m *Cosign) SignBlob( ctx context.Context, // The file to sign blob *dagger.File, // Base name for the outputs (plain file name) // +optional // +default="SHA256SUMS" name string, // Use keyless OIDC signing // +optional keyless bool, // Private key for keyed signing // +optional privateKey *dagger.Secret, // Password for the private key (if encrypted) // +optional password *dagger.Secret, // Upload a keyed signature to the PUBLIC Sigstore Rekor (off by default) // +optional publicRekor bool, // Private Rekor to upload to instead (https; wins over --public-rekor) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url // +optional rekorPublicKey *dagger.Secret, ) (*dagger.Directory, error) { if name == "" { name = "SHA256SUMS" } tlog, err := signTlog(keyless, rekorURL, publicRekor) if err != nil { return nil, err } if err := attestation.CheckBlobName(name); err != nil { return nil, err } if blob == nil { return nil, fmt.Errorf("--blob is required") } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithMountedFile("/tmp/blob", blob) args := []string{ "cosign", "sign-blob", "--yes", "--output-signature", "/tmp/out/" + name + ".sig", "--bundle", "/tmp/out/" + name + ".bundle", } if keyless { c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") } else { if privateKey == nil { return nil, fmt.Errorf("either --keyless or --private-key must be provided") } c = c.WithMountedSecret("/tmp/cosign.key", privateKey, cosignOwned) if password != nil { c = c.WithSecretVariable("COSIGN_PASSWORD", password) } else { c = c.WithEnvVariable("COSIGN_PASSWORD", "") } args = append(args, "--key", "/tmp/cosign.key") } args = append(args, tlog...) args = append(args, "/tmp/blob") out := c. WithDirectory("/tmp/out", dag.Directory(), dagger.ContainerWithDirectoryOpts{Owner: "65532"}). WithExec(args) if _, err := out.Sync(ctx); err != nil { return nil, fmt.Errorf("cosign sign-blob failed: %w", err) } return dag.Directory(). WithFile(name+".sig", out.File("/tmp/out/"+name+".sig")). WithFile(name+".bundle", out.File("/tmp/out/"+name+".bundle")), nil } // GateResult is the attestation gate's decision for one digest. type GateResult struct { Image string `json:"image"` Allowed bool `json:"allowed"` Deny []string `json:"deny,omitempty"` // Notes are cosign failures that left a predicate type with no verified // envelope (no attestation, wrong key, registry unreachable). The gate // then denies; the note says why. Notes []string `json:"notes,omitempty"` } // VerifyAttestationGate is the attestation-verifying gate (#2143 phase 2). // // cosign verifies the signatures (`verify-attestation --key`), then the // attestation-gate OPA policy judges the decoded statements: SLSA v1 // provenance whose subject IS --image's digest, whose builder.id exactly // equals one of --trusted-builder, and which pins a full commit; plus an SBOM // attestation about the same digest when --require-sbom is set. // // It returns an ERROR when the gate denies, so a CI stage that calls it fails. // Unlike verify-provenance it never substring-matches cosign's raw output. // // Usage: // // dagger call verify-attestation-gate \ // --image=registry.example/team/orders:abc@sha256: \ // --public-key=env://COSIGN_PUB --trusted-builder=https://ci.example/job/orders/ func (m *Cosign) VerifyAttestationGate( ctx context.Context, // Image reference pinned to a digest: [:tag]@sha256:<64 hex> image string, // Cosign public key the attestations must verify against publicKey *dagger.Secret, // builder.id values to trust, exact match. Repeat for more than one. trustedBuilder []string, // Also require a CycloneDX SBOM attestation about the digest // +optional requireSbom bool, // Registry username for pulling attestations from a private registry // +optional registryUsername string, // Registry password/token for --registry-username // +optional registryPassword *dagger.Secret, // The registry is served over plain HTTP / self-signed TLS // +optional registryInsecure bool, // The attestations were uploaded to the PUBLIC Rekor (the choice made at // attest time); without it, and without --rekor-url, the key alone is checked // +optional publicRekor bool, // Private Rekor the attestations were uploaded to (https) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url; required with it // +optional rekorPublicKey *dagger.Secret, ) (*GateResult, error) { if _, err := attestation.ImageDigest(image); err != nil { return nil, fmt.Errorf("--image: %w", err) } if publicKey == nil { return nil, fmt.Errorf("--public-key is required") } tlog, err := attestation.VerifyTlogArgs(rekorURL, publicRekor) if err != nil { return nil, err } if err := attestation.CheckRekorPublicKey(rekorURL, rekorPublicKey != nil); err != nil { return nil, err } c, err := withRegistryAuth(ctx, withRekorPublicKey(m.cosignContainer(), rekorPublicKey), image, registryUsername, registryPassword) if err != nil { return nil, err } c = c.WithMountedSecret("/tmp/cosign.pub", publicKey, cosignOwned) types := []string{"slsaprovenance1"} if requireSbom { types = append(types, "cyclonedx") } result := &GateResult{Image: image} var envelopes []string for _, typ := range types { args := []string{"cosign", "verify-attestation", "--key", "/tmp/cosign.pub", "--type", typ} args = append(args, insecureRegistryArgs(registryInsecure)...) args = append(args, tlog...) out, err := c.WithExec(append(args, image)).Stdout(ctx) if err != nil { // Fail closed: no verified envelope for this type. The policy // denies; the note keeps cosign's reason. result.Notes = append(result.Notes, fmt.Sprintf("cosign verify-attestation --type %s: %v", typ, err)) continue } envelopes = append(envelopes, out) } input, err := attestation.GateInput(image, strings.Join(envelopes, "\n"), trustedBuilder, requireSbom) if err != nil { return nil, err } opaOut, err := dag.Container(). From(opaImage). WithNewFile("/policy/attestation_gate.rego", gatePolicy). WithNewFile("/input.json", string(input)). WithExec([]string{ "/opa", "eval", "--format", "json", "--data", "/policy", "--input", "/input.json", attestation.GatePolicyQuery, }). Stdout(ctx) if err != nil { return nil, fmt.Errorf("opa eval failed: %w", err) } allowed, deny, err := attestation.GateVerdict([]byte(opaOut)) if err != nil { return nil, err } result.Allowed = allowed result.Deny = deny if !allowed { msg := strings.Join(deny, "; ") if len(result.Notes) > 0 { msg += " (" + strings.Join(result.Notes, "; ") + ")" } return result, fmt.Errorf("attestation gate denied %s: %s", image, msg) } return result, nil } // AttestSBOM attaches an SBOM (CycloneDX/SPDX) to the image as a Cosign // attestation — e.g. the sbom.cdx.json `standard-build evidence` wrote. // --image must be pinned to a digest. func (m *Cosign) AttestSBOM( ctx context.Context, image string, // SBOM file (CycloneDX JSON) sbom *dagger.File, // Predicate type — "cyclonedx" or "spdxjson" // +optional // +default="cyclonedx" predicateType string, // +optional keyless bool, // +optional privateKey *dagger.Secret, // Upload a keyed attestation to the PUBLIC Sigstore Rekor (off by default) // +optional publicRekor bool, // Private Rekor to upload to instead (https; wins over --public-rekor) // +optional rekorURL string, // Public key (PEM) of the private Rekor at --rekor-url // +optional rekorPublicKey *dagger.Secret, ) (*SignResult, error) { if predicateType == "" { predicateType = "cyclonedx" } tlog, err := signTlog(keyless, rekorURL, publicRekor) if err != nil { return nil, err } // Same rule as attest-provenance: the SBOM is about one digest. if _, err := attestation.ImageDigest(image); err != nil { return nil, fmt.Errorf("--image: %w", err) } c := withRekorPublicKey(m.cosignContainer(), rekorPublicKey).WithMountedFile("/tmp/sbom.json", sbom) args := []string{ "cosign", "attest", "--type", predicateType, "--predicate", "/tmp/sbom.json", } if keyless { c = c.WithEnvVariable("COSIGN_EXPERIMENTAL", "1") } else { if privateKey == nil { return nil, fmt.Errorf("--private-key required when not keyless") } c = c.WithMountedSecret("/tmp/cosign.key", privateKey) args = append(args, "--key", "/tmp/cosign.key") } args = append(args, tlog...) args = append(args, image) if _, err := c.WithExec(args).Sync(ctx); err != nil { return nil, fmt.Errorf("cosign attest failed: %w", err) } return &SignResult{ Image: image, Signature: image + ".att", Success: true, }, nil } // ───── helpers ───── // signTlog picks the transparency-log flags for a signing call (see // attestation/tlog.go): keyed signing uploads nowhere unless asked; keyless // needs a log and keeps the public one unless a private Rekor is named. func signTlog(keyless bool, rekorURL string, publicRekor bool) ([]string, error) { if keyless { return attestation.KeylessTlogArgs(rekorURL) } return attestation.SignTlogArgs(rekorURL, publicRekor) } // withRekorPublicKey mounts a private Rekor's public key and points cosign at // it (SIGSTORE_REKOR_PUBLIC_KEY is a path). nil leaves the container as is, so // cosign keeps the public Sigstore keys from its TUF root. func withRekorPublicKey(c *dagger.Container, key *dagger.Secret) *dagger.Container { if key == nil { return c } return c. WithMountedSecret(attestation.RekorPublicKeyPath, key, cosignOwned). WithEnvVariable("SIGSTORE_REKOR_PUBLIC_KEY", attestation.RekorPublicKeyPath) } // verifyTlog is signTlog's counterpart for verification. func verifyTlog(keyless bool, rekorURL string, publicRekor bool) ([]string, error) { if keyless { return attestation.KeylessTlogArgs(rekorURL) } return attestation.VerifyTlogArgs(rekorURL, publicRekor) } // signatureRef returns the OCI reference Cosign uses for the .sig artifact. // Cosign convention: replace the tag with `sha256-.sig`. func signatureRef(image string) string { // We don't resolve the digest here — let consumers query the registry if // they need the canonical reference. Returning a human-readable hint. return image + " (sig artifact at .sig tag)" } func registryHost(image string) string { if i := strings.IndexByte(image, '/'); i > 0 { return image[:i] } return "docker.io" } func extractRekorURL(out string) string { const marker = "tlog entry created with index:" if idx := strings.Index(out, marker); idx >= 0 { rest := out[idx+len(marker):] if nl := strings.IndexByte(rest, '\n'); nl > 0 { id := strings.TrimSpace(rest[:nl]) return "https://search.sigstore.dev/?logIndex=" + id } } return "" } func extractIdentity(out string) string { const marker = "Certificate subject:" for _, line := range strings.Split(out, "\n") { if strings.HasPrefix(strings.TrimSpace(line), marker) { return strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(line), marker)) } } return "" } func extractSubjects(out string) []string { var subjects []string for _, line := range strings.Split(out, "\n") { if strings.Contains(line, "Subject:") { parts := strings.SplitN(line, "Subject:", 2) if len(parts) == 2 { subjects = append(subjects, strings.TrimSpace(parts[1])) } } } return subjects }