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 }