chore: publish IntegraCI build modules a11ec75d3e09
This commit is contained in:
1 parent
694710104a
commit
3c2b80914e
78 files changed
+4982
-405
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "standard-build",
|
||||
"engineVersion": "v0.21.7",
|
||||
"engineVersion": "v0.21.11",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
@@ -9,6 +9,7 @@
|
||||
"./main.go",
|
||||
"./evidence/evidence.go",
|
||||
"./layout/layout.go",
|
||||
"./layout/ignore.go"
|
||||
"./layout/ignore.go",
|
||||
"./pushgate/pushgate.go"
|
||||
]
|
||||
}
|
||||
@@ -20,7 +20,7 @@ func validInput() ProvenanceInput {
|
||||
InvocationID: "42",
|
||||
StartedOn: "2026-10-11T08:00:00Z",
|
||||
FinishedOn: "2026-10-11T08:05:00Z",
|
||||
EngineVersion: "v0.21.7",
|
||||
EngineVersion: "v0.21.11",
|
||||
Language: "go",
|
||||
}
|
||||
}
|
||||
|
||||
+268
-3
@@ -12,14 +12,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"dagger/standard-build/evidence"
|
||||
"dagger/standard-build/internal/dagger"
|
||||
"dagger/standard-build/layout"
|
||||
"dagger/standard-build/pushgate"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StandardBuild is the IntegraCI standard build pipeline module.
|
||||
@@ -37,6 +42,17 @@ type BuildResult struct {
|
||||
ImageDigest string `json:"image_digest,omitempty"`
|
||||
TestOutput string `json:"test_output,omitempty"`
|
||||
LintOutput string `json:"lint_output,omitempty"`
|
||||
// ArchiveDigest is `sha256:<hex>` of the image's manifest in the OCI
|
||||
// archive written with --archive (scan before push, ADR-0093 §5): what the
|
||||
// scan describes and the verdict judges. Empty when nothing was archived.
|
||||
ArchiveDigest string `json:"archive_digest,omitempty"`
|
||||
// Archive is the OCI image layout (index.json, oci-layout, blobs/) of the
|
||||
// built image, read through `archive-layout`. EXPORTED on purpose: Dagger
|
||||
// serializes a returned object between chained calls, and an unexported
|
||||
// field would be empty by the time `archive-layout` runs. `+private` keeps
|
||||
// it out of the module's API.
|
||||
// +private
|
||||
Archive *dagger.Directory `json:"archive,omitempty"`
|
||||
}
|
||||
|
||||
// execDetail turns a failed step into something a person can act on.
|
||||
@@ -168,6 +184,13 @@ func (m *StandardBuild) Build(
|
||||
// packages, or a workspace whose lockfile lives at the root).
|
||||
// +optional
|
||||
buildContext string,
|
||||
// Build to an OCI ARCHIVE and push nothing (scan before push, ADR-0093 §5).
|
||||
// --image-ref still names the image (it is the archive's ref name); no
|
||||
// registry is contacted. Chain `archive-layout export --path=<dir>` to
|
||||
// write the layout, `archive-digest` to read its manifest digest. Then
|
||||
// security-scan `archive-scan`, `push-verdict`, and `push-archive`.
|
||||
// +optional
|
||||
archive bool,
|
||||
) (*BuildResult, error) {
|
||||
result := &BuildResult{Language: language, RuntimeVersion: runtimeVersion}
|
||||
ref, err := destinationRef(imageRef, registry, service, tag)
|
||||
@@ -179,6 +202,11 @@ func (m *StandardBuild) Build(
|
||||
username: registryUsername,
|
||||
password: registryPassword,
|
||||
insecure: registryInsecure,
|
||||
archive: archive,
|
||||
result: result,
|
||||
}
|
||||
if archive && ref == "" {
|
||||
return nil, fmt.Errorf("--archive needs --image-ref: the archive names the image it will be pushed as")
|
||||
}
|
||||
// WHERE in the checkout, checked BEFORE any build step. The default layout
|
||||
// returns the checkout untouched and reads nothing. See applyLayout.
|
||||
@@ -829,6 +857,10 @@ type publishConfig struct {
|
||||
// testOnly does: the lane signatures stay as they are. Only the go and node
|
||||
// lanes read it (laneWorkdirProblem refuses the others).
|
||||
workdir string
|
||||
// archive makes publishImage export an OCI layout into result instead of
|
||||
// pushing (ADR-0093 §5, scan before push). Rides here for the same reason.
|
||||
archive bool
|
||||
result *BuildResult
|
||||
}
|
||||
|
||||
// lintTestBase is the container a lane lints and tests in.
|
||||
@@ -900,6 +932,9 @@ func publishImage(ctx context.Context, image *dagger.Container, pub publishConfi
|
||||
if pub.imageRef == "" {
|
||||
return "", nil // build-only: no destination configured
|
||||
}
|
||||
if pub.archive {
|
||||
return archiveImage(ctx, image, pub)
|
||||
}
|
||||
if pub.insecure {
|
||||
return publishInsecure(ctx, image, pub)
|
||||
}
|
||||
@@ -925,7 +960,7 @@ func publishImage(ctx context.Context, image *dagger.Container, pub publishConfi
|
||||
// Tags are checked against the registry's own list rather than assumed: v0.20.2
|
||||
// looks like a plausible release and was never published, so an earlier build
|
||||
// failed with `not found` after every other stage had succeeded.
|
||||
const craneImage = "gcr.io/go-containerregistry/crane/debug:v0.21.9"
|
||||
const craneImage = "gcr.io/go-containerregistry/crane/debug:v0.22.1"
|
||||
|
||||
// publishInsecure pushes to a registry that is served over plain HTTP.
|
||||
//
|
||||
@@ -1005,19 +1040,67 @@ func withDigest(result *BuildResult, err error) (*BuildResult, error) {
|
||||
if err != nil || result == nil {
|
||||
return result, err
|
||||
}
|
||||
if result.Archive != nil {
|
||||
// Nothing was pushed: the archive's digest is the only one there is.
|
||||
result.ImageDigest = ""
|
||||
return result, nil
|
||||
}
|
||||
result.ImageDigest = evidence.DigestOf(result.ImageRef)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// archiveImage writes the built image as an OCI image layout and records its
|
||||
// manifest digest (ADR-0093 §5 step 1). No registry is contacted.
|
||||
//
|
||||
// The layout is exported, not a tarball, so the digest is READ from
|
||||
// index.json rather than recomputed: the bytes `push-archive` later sends are
|
||||
// exactly these, and the registry's digest is compared with this one.
|
||||
// OCI media types, one platform: pushgate.ManifestDigestFromIndex refuses an
|
||||
// index of several manifests (the scan would describe one of them).
|
||||
func archiveImage(ctx context.Context, image *dagger.Container, pub publishConfig) (string, error) {
|
||||
// AsTarball's default media types are OCI (Dagger's ImageMediaTypes
|
||||
// default), the layout crane and trivy read as a directory.
|
||||
tar := image.AsTarball()
|
||||
layout := dag.Container().
|
||||
From(craneImage).
|
||||
WithFile("/tmp/image.tar", tar).
|
||||
WithExec([]string{"sh", "-c", "mkdir -p /out && tar -xf /tmp/image.tar -C /out"}).
|
||||
Directory("/out")
|
||||
index, err := layout.File("index.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the built image's OCI layout has no index.json: %w", err)
|
||||
}
|
||||
digest, err := pushgate.ManifestDigestFromIndex([]byte(index))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if pub.result != nil {
|
||||
pub.result.Archive = layout
|
||||
pub.result.ArchiveDigest = digest
|
||||
}
|
||||
// The ref the image WILL be pushed as, unpinned: nothing is published yet.
|
||||
return pub.imageRef, nil
|
||||
}
|
||||
|
||||
// ArchiveLayout is the OCI image layout `build --archive` wrote. Export it:
|
||||
//
|
||||
// dagger call build ... --archive=true archive-layout export --path=.integraci-image.oci
|
||||
func (r *BuildResult) ArchiveLayout() (*dagger.Directory, error) {
|
||||
if r.Archive == nil {
|
||||
return nil, fmt.Errorf("no archive: call build with --archive=true")
|
||||
}
|
||||
return r.Archive, nil
|
||||
}
|
||||
|
||||
// daggerEngineVersion is the engine every module's dagger.json pins. It is
|
||||
// recorded in the provenance `builder.version`, and
|
||||
// tools/scripts/dagger-mirror-manifest.py fails when it and dagger.json
|
||||
// disagree.
|
||||
const daggerEngineVersion = "v0.21.7"
|
||||
const daggerEngineVersion = "v0.21.11"
|
||||
|
||||
// syftImage is the SBOM generator the evidence set uses — the same pin as the
|
||||
// sbom module, so both paths describe an image the same way.
|
||||
const syftImage = "anchore/syft:v1.18.1"
|
||||
const syftImage = "anchore/syft:v1.56.0"
|
||||
|
||||
// Evidence writes the supply-chain evidence for ONE published image digest
|
||||
// (ADR-0068 Layer 2, #2143 phase 1) and returns it as a directory:
|
||||
@@ -1843,3 +1926,185 @@ func (m *StandardBuild) buildNode(
|
||||
result.Success = true
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// PushVerdict asks the platform whether the scanned archive may be pushed
|
||||
// (ADR-0093 §5 step 3): POST /api/v1/secure-delivery/push-verdict with the
|
||||
// archive's manifest digest and the tag it was built as. Prints one line:
|
||||
// `push` or `refuse`, then the reason. The build pushes only on `push`.
|
||||
//
|
||||
// Only an explicit refusal stops the push (pushgate.Judge): an unreachable
|
||||
// platform pushes and says so, because this step is hygiene and the deploy
|
||||
// gate still judges the pushed digest. A refusal makes this call FAIL, so a
|
||||
// pipeline that chains it before `push-archive` stops there with
|
||||
// "verdict: block (<families>)".
|
||||
//
|
||||
// +cache="never"
|
||||
func (m *StandardBuild) PushVerdict(
|
||||
ctx context.Context,
|
||||
// IntegraCI API base URL
|
||||
apiURL string,
|
||||
// The pipeline's scans:ingest token. Absent = nothing can refuse (said).
|
||||
// +optional
|
||||
token *dagger.Secret,
|
||||
serviceID string,
|
||||
// The archive's manifest digest (`archive-digest`), sha256:<hex>
|
||||
imageDigest string,
|
||||
// The tag the archive was built as
|
||||
version string,
|
||||
) (string, error) {
|
||||
body, err := pushgate.RequestBody(serviceID, imageDigest, version)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if strings.TrimSpace(apiURL) == "" || token == nil {
|
||||
// No platform to ask: nothing can refuse, and the deploy gate judges
|
||||
// the digest. Said, not silent.
|
||||
return "push\nverdict NOT asked (no --api-url/--token): pushed; the deploy gate judges this digest\n", nil
|
||||
}
|
||||
tokenStr, err := token.Plaintext(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read token secret: %w", err)
|
||||
}
|
||||
endpoint := strings.TrimRight(apiURL, "/") + "/api/v1/secure-delivery/push-verdict"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("build request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+tokenStr)
|
||||
status, answer := 0, []byte(nil)
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
if resp, err := client.Do(req); err == nil {
|
||||
status = resp.StatusCode
|
||||
answer, _ = io.ReadAll(io.LimitReader(resp.Body, 64<<10))
|
||||
resp.Body.Close()
|
||||
}
|
||||
out := pushgate.Judge(status, answer)
|
||||
if !out.Push {
|
||||
return "", fmt.Errorf("%s", out.Message)
|
||||
}
|
||||
return "push\n" + out.Message + "\n", nil
|
||||
}
|
||||
|
||||
// PushArchive pushes the OCI layout `build --archive` wrote, and fails unless
|
||||
// the registry reports the SAME manifest digest the archive carries
|
||||
// (ADR-0093 §5 step 2: a re-compressing registry fails the push rather than
|
||||
// rebinding the evidence). Returns `<image-ref>@<digest>`, the shape Build
|
||||
// returns after a push, so `build_digest_capture` keeps working.
|
||||
//
|
||||
// TLS registry: the layout is imported and published by the engine, with the
|
||||
// same login the build's publish always used (--registry-username/-password,
|
||||
// or the client's own docker login, which Dagger forwards). Plain-HTTP
|
||||
// registry: crane (Apache-2.0) pushes the layout directory byte for byte, as
|
||||
// publishInsecure does for a built image. Either way the digest the REGISTRY
|
||||
// reports is compared with the archive's; nothing about it is trusted.
|
||||
//
|
||||
// +cache="never"
|
||||
func (m *StandardBuild) PushArchive(
|
||||
ctx context.Context,
|
||||
// The exported OCI layout directory
|
||||
layout *dagger.Directory,
|
||||
// Destination, `<registry>/<repo>:<tag>`; the archive's own ref name
|
||||
imageRef string,
|
||||
// The archive's manifest digest the scan and the verdict described
|
||||
archiveDigest string,
|
||||
// +optional
|
||||
registryUsername string,
|
||||
// +optional
|
||||
registryPassword *dagger.Secret,
|
||||
// +optional
|
||||
registryInsecure bool,
|
||||
) (string, error) {
|
||||
if !pushgate.IsDigest(archiveDigest) {
|
||||
return "", fmt.Errorf("--archive-digest %q is not sha256", archiveDigest)
|
||||
}
|
||||
if strings.TrimSpace(imageRef) == "" || strings.Contains(imageRef, "@") {
|
||||
return "", fmt.Errorf("--image-ref must be <registry>/<repo>:<tag>, got %q", imageRef)
|
||||
}
|
||||
index, err := layout.File("index.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("--layout is not an OCI image layout: %w", err)
|
||||
}
|
||||
inLayout, err := pushgate.ManifestDigestFromIndex([]byte(index))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// The directory must be the archive that was scanned, not another one.
|
||||
if err := pushgate.SameDigest(archiveDigest, inLayout); err != nil {
|
||||
return "", fmt.Errorf("--layout is not the scanned archive: %w", err)
|
||||
}
|
||||
var registryDigest string
|
||||
if registryInsecure {
|
||||
registryDigest, err = pushLayoutInsecure(ctx, layout, imageRef, registryUsername, registryPassword)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
} else {
|
||||
tar := dag.Container().
|
||||
From(craneImage).
|
||||
WithDirectory("/tmp/layout", layout).
|
||||
WithExec([]string{"sh", "-c", "tar -cf /tmp/image.tar -C /tmp/layout ."}).
|
||||
File("/tmp/image.tar")
|
||||
ref, err := publishImage(ctx, dag.Container().Import(tar), publishConfig{
|
||||
imageRef: imageRef,
|
||||
username: registryUsername,
|
||||
password: registryPassword,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
registryDigest = evidence.DigestOf(ref)
|
||||
}
|
||||
if err := pushgate.SameDigest(archiveDigest, registryDigest); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return imageRef + "@" + archiveDigest, nil
|
||||
}
|
||||
|
||||
// pushLayoutInsecure pushes an OCI layout to a plain-HTTP registry with crane
|
||||
// and returns the digest the registry then reports for the reference. Same
|
||||
// reporting shape as publishInsecure: the step always exits 0 and the outcome
|
||||
// is read from stdout, because a failing exec carries no reason.
|
||||
func pushLayoutInsecure(
|
||||
ctx context.Context, layout *dagger.Directory, imageRef, username string, password *dagger.Secret,
|
||||
) (string, error) {
|
||||
host := registryHost(imageRef)
|
||||
if host == "" {
|
||||
return "", fmt.Errorf("insecure push needs a registry host in %q", imageRef)
|
||||
}
|
||||
pusher := dag.Container().From(craneImage).WithDirectory("/tmp/layout", layout)
|
||||
login := "echo 'no registry credential supplied; pushing anonymously'"
|
||||
if password != nil {
|
||||
pusher = pusher.WithMountedSecret("/tmp/registry-password", password)
|
||||
login = fmt.Sprintf("crane auth login %s -u %s --password-stdin --insecure < /tmp/registry-password",
|
||||
shellQuote(host), shellQuote(username))
|
||||
}
|
||||
out, err := pusher.WithExec([]string{
|
||||
"sh", "-c",
|
||||
fmt.Sprintf(
|
||||
"{ %s && crane push --insecure /tmp/layout %s && echo PUSHED && "+
|
||||
"printf '%s%%s\\n' \"$(crane digest --insecure %s)\"; } 2>&1; echo \"crane exit=$?\"",
|
||||
login, shellQuote(imageRef), pushgate.RegistryDigestPrefix, shellQuote(imageRef),
|
||||
),
|
||||
}).Stdout(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("insecure push of %s failed: %s", imageRef, execDetail(err))
|
||||
}
|
||||
if !strings.Contains(out, "PUSHED") {
|
||||
return "", fmt.Errorf("insecure push of %s did not confirm:\n%s", imageRef, out)
|
||||
}
|
||||
return pushgate.RegistryDigestFrom(out), nil
|
||||
}
|
||||
|
||||
// ArchiveDigest reads the manifest digest of an exported OCI layout, so a
|
||||
// pipeline that exported `archive-layout` can name it without parsing JSON.
|
||||
func (m *StandardBuild) ArchiveDigest(
|
||||
ctx context.Context,
|
||||
layout *dagger.Directory,
|
||||
) (string, error) {
|
||||
index, err := layout.File("index.json").Contents(ctx)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("--layout is not an OCI image layout: %w", err)
|
||||
}
|
||||
return pushgate.ManifestDigestFromIndex([]byte(index))
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// Package pushgate holds the pure half of scan-before-push (ADR-0093 §5,
|
||||
// WP-06): which digest an OCI archive carries, whether the registry kept it,
|
||||
// and what the platform's pre-push verdict says.
|
||||
//
|
||||
// Standard library only, for the reason evidence/ is: the generated `dagger`
|
||||
// package panics at init without a Dagger session, so nothing in package main
|
||||
// runs under a plain `go test`.
|
||||
//
|
||||
// The order every rendered engine runs (ADR-0093 §5):
|
||||
//
|
||||
// build to an OCI archive -> scan the archive -> ask the verdict for the
|
||||
// archive's manifest digest -> push only if the answer is not `refuse` ->
|
||||
// the registry's digest must equal the archive's (mismatch fails).
|
||||
//
|
||||
// The push step runs in the build job, which has executed the change's code,
|
||||
// so it is hygiene, not a control. The control is G3: the deploy gate judges
|
||||
// the pushed DIGEST (ADR-0093 §5.4).
|
||||
package pushgate
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var digestRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
|
||||
|
||||
// versionRE is the tag grammar of the platform's deploy endpoint and of the
|
||||
// security verdict (`security_verdict._VERSION_RE`).
|
||||
var versionRE = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$`)
|
||||
|
||||
// manifestMediaTypes are the single-image manifests an archive may name. An
|
||||
// image INDEX is refused: the scan describes one platform's image, and a
|
||||
// pushed index would carry a digest no scan describes.
|
||||
var manifestMediaTypes = map[string]bool{
|
||||
"application/vnd.oci.image.manifest.v1+json": true,
|
||||
"application/vnd.docker.distribution.manifest.v2+json": true,
|
||||
}
|
||||
|
||||
// RegistryDigestPrefix starts the line the push script prints with the digest
|
||||
// the REGISTRY reports for the pushed reference.
|
||||
const RegistryDigestPrefix = "REGISTRY_DIGEST "
|
||||
|
||||
// IsDigest reports whether s is `sha256:<64 lower-case hex>`.
|
||||
func IsDigest(s string) bool { return digestRE.MatchString(s) }
|
||||
|
||||
// ManifestDigestFromIndex returns the manifest digest an OCI image layout's
|
||||
// index.json names. Exactly one manifest, of a single-image media type.
|
||||
func ManifestDigestFromIndex(indexJSON []byte) (string, error) {
|
||||
var index struct {
|
||||
Manifests []struct {
|
||||
MediaType string `json:"mediaType"`
|
||||
Digest string `json:"digest"`
|
||||
} `json:"manifests"`
|
||||
}
|
||||
if err := json.Unmarshal(indexJSON, &index); err != nil {
|
||||
return "", fmt.Errorf("the archive's index.json is not JSON: %w", err)
|
||||
}
|
||||
if len(index.Manifests) != 1 {
|
||||
return "", fmt.Errorf(
|
||||
"the archive names %d manifests; one platform per digest is supported", len(index.Manifests))
|
||||
}
|
||||
m := index.Manifests[0]
|
||||
if !manifestMediaTypes[m.MediaType] {
|
||||
return "", fmt.Errorf("the archive's manifest has media type %q, not a single image", m.MediaType)
|
||||
}
|
||||
if !IsDigest(m.Digest) {
|
||||
return "", fmt.Errorf("the archive's manifest digest %q is not sha256", m.Digest)
|
||||
}
|
||||
return m.Digest, nil
|
||||
}
|
||||
|
||||
// RegistryDigestFrom returns the digest on the push script's
|
||||
// RegistryDigestPrefix line, or "" when there is none (or it is not sha256).
|
||||
func RegistryDigestFrom(out string) string {
|
||||
for _, line := range strings.Split(out, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if rest, ok := strings.CutPrefix(line, RegistryDigestPrefix); ok {
|
||||
rest = strings.TrimSpace(rest)
|
||||
if IsDigest(rest) {
|
||||
return rest
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// SameDigest fails unless the registry kept the archive's manifest byte for
|
||||
// byte. On a mismatch the caller must FAIL and record nothing: the scan and
|
||||
// the verdict described the archive's digest, never the registry's
|
||||
// (ADR-0093 §5.2, "the push step fails rather than rebinding evidence").
|
||||
func SameDigest(archive, registry string) error {
|
||||
if !IsDigest(archive) {
|
||||
return fmt.Errorf("archive digest %q is not sha256", archive)
|
||||
}
|
||||
if !IsDigest(registry) {
|
||||
return errors.New("the registry reported no sha256 digest for the pushed reference")
|
||||
}
|
||||
if archive != registry {
|
||||
return fmt.Errorf(
|
||||
"registry digest %s differs from the scanned archive's %s: the registry rewrote the image; "+
|
||||
"nothing is recorded for it", registry, archive)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Request is the body of POST /api/v1/secure-delivery/push-verdict.
|
||||
type Request struct {
|
||||
ServiceID string `json:"service_id"`
|
||||
ImageDigest string `json:"image_digest"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// RequestBody validates and encodes the verdict request.
|
||||
func RequestBody(serviceID, digest, version string) ([]byte, error) {
|
||||
if strings.TrimSpace(serviceID) == "" {
|
||||
return nil, errors.New("push-verdict needs --service-id")
|
||||
}
|
||||
if !IsDigest(digest) {
|
||||
return nil, fmt.Errorf("push-verdict: %q is not a sha256 digest", digest)
|
||||
}
|
||||
if !versionRE.MatchString(version) {
|
||||
return nil, fmt.Errorf("push-verdict: version %q is not an image tag", version)
|
||||
}
|
||||
return json.Marshal(Request{ServiceID: serviceID, ImageDigest: digest, Version: version})
|
||||
}
|
||||
|
||||
// Answer is the platform's reply (app/security/schemas/push_verdict.py
|
||||
// PushVerdictRead). apps/api/tests/test_scan_before_push.py holds the JSON
|
||||
// names equal on both sides.
|
||||
type Answer struct {
|
||||
Decision string `json:"decision"`
|
||||
Result string `json:"result"`
|
||||
Mode string `json:"mode"`
|
||||
Reasons []string `json:"reasons"`
|
||||
WouldBlock []string `json:"would_block"`
|
||||
}
|
||||
|
||||
// Outcome is what the push step does with an answer.
|
||||
type Outcome struct {
|
||||
Push bool
|
||||
Message string
|
||||
}
|
||||
|
||||
// Judge turns the platform's HTTP answer into the push decision.
|
||||
//
|
||||
// An explicit, well-formed `refuse` stops the push, and so does an explicit
|
||||
// AUTHORIZATION refusal (401/403): the caller configured a token, and the
|
||||
// platform said this token may not ask about this service or revision
|
||||
// (expired, revoked, `scan-token-wrong-revision`, `scan-token-unbound`).
|
||||
// Pushing then would let a refused binding publish silently, with no server
|
||||
// trace (WP-06 review, 2026-11-04).
|
||||
//
|
||||
// Anything else -- the platform unreachable (a Jenkins on a customer network
|
||||
// often cannot call back), a 5xx or other non-2xx, an unreadable body, an
|
||||
// unknown decision -- pushes and says so loudly: this step is hygiene, and the
|
||||
// deploy gate (G3) still judges the pushed digest. Failing closed on transport
|
||||
// errors would stop every build whose CI cannot reach the platform, without
|
||||
// making anything safer.
|
||||
func Judge(status int, body []byte) Outcome {
|
||||
if status == 401 || status == 403 {
|
||||
return Outcome{false, fmt.Sprintf(
|
||||
"verdict refused the request (HTTP %d: the token may not ask for this service/revision): "+
|
||||
"image NOT pushed", status)}
|
||||
}
|
||||
if status < 200 || status >= 300 {
|
||||
return Outcome{true, fmt.Sprintf(
|
||||
"verdict NOT answered (HTTP %d): pushed; the deploy gate judges this digest", status)}
|
||||
}
|
||||
var a Answer
|
||||
if err := json.Unmarshal(body, &a); err != nil {
|
||||
return Outcome{true, "verdict NOT readable: pushed; the deploy gate judges this digest"}
|
||||
}
|
||||
switch a.Decision {
|
||||
case "refuse":
|
||||
families := "unknown"
|
||||
if len(a.Reasons) > 0 {
|
||||
names := make([]string, 0, len(a.Reasons))
|
||||
for _, r := range a.Reasons {
|
||||
name, _, _ := strings.Cut(r, ":")
|
||||
names = append(names, strings.TrimSpace(name))
|
||||
}
|
||||
families = strings.Join(names, ", ")
|
||||
}
|
||||
return Outcome{false, fmt.Sprintf(
|
||||
"verdict: block (%s): image NOT pushed. %s", families, strings.Join(a.Reasons, "; "))}
|
||||
case "push":
|
||||
msg := fmt.Sprintf("verdict: %s (mode %s): pushing", a.Result, a.Mode)
|
||||
if len(a.WouldBlock) > 0 {
|
||||
msg += fmt.Sprintf("; would block in enforce: %s (recorded as secure_delivery.would_block)",
|
||||
strings.Join(a.WouldBlock, ", "))
|
||||
}
|
||||
return Outcome{true, msg}
|
||||
default:
|
||||
return Outcome{true, fmt.Sprintf(
|
||||
"verdict answered %q, which is not push/refuse: pushed; the deploy gate judges this digest",
|
||||
a.Decision)}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package pushgate
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
hexA = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
hexB = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
)
|
||||
|
||||
func TestManifestDigestFromIndexTakesTheOneImage(t *testing.T) {
|
||||
index := `{"schemaVersion":2,"manifests":[{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha256:` + hexA + `","size":1}]}`
|
||||
got, err := ManifestDigestFromIndex([]byte(index))
|
||||
if err != nil || got != "sha256:"+hexA {
|
||||
t.Fatalf("got %q, %v", got, err)
|
||||
}
|
||||
docker := strings.Replace(index, "application/vnd.oci.image.manifest.v1+json",
|
||||
"application/vnd.docker.distribution.manifest.v2+json", 1)
|
||||
if _, err := ManifestDigestFromIndex([]byte(docker)); err != nil {
|
||||
t.Fatalf("a docker v2 manifest is a single image too: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManifestDigestFromIndexRefusesWhatIsNotOneImage(t *testing.T) {
|
||||
m := `{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha256:` + hexA + `"}`
|
||||
for name, index := range map[string]string{
|
||||
"two manifests": `{"manifests":[` + m + `,` + m + `]}`,
|
||||
"none": `{"manifests":[]}`,
|
||||
"an index": `{"manifests":[{"mediaType":"application/vnd.oci.image.index.v1+json","digest":"sha256:` + hexA + `"}]}`,
|
||||
"sha512": `{"manifests":[{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha512:` + hexA + `"}]}`,
|
||||
"upper hex": `{"manifests":[{"mediaType":"application/vnd.oci.image.manifest.v1+json","digest":"sha256:` + strings.ToUpper(hexA) + `"}]}`,
|
||||
"not json": `manifests`,
|
||||
} {
|
||||
if _, err := ManifestDigestFromIndex([]byte(index)); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryDigestFromReadsOnlyItsLine(t *testing.T) {
|
||||
out := "logged in\npushed blob sha256:" + hexB + "\nPUSHED x\n" + RegistryDigestPrefix + "sha256:" + hexA + "\n"
|
||||
if got := RegistryDigestFrom(out); got != "sha256:"+hexA {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if got := RegistryDigestFrom("pushed blob sha256:" + hexA); got != "" {
|
||||
t.Fatalf("a blob digest is not the registry's manifest digest, got %q", got)
|
||||
}
|
||||
if got := RegistryDigestFrom(RegistryDigestPrefix + "sha256:abc"); got != "" {
|
||||
t.Fatalf("a short digest is not a digest, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Mutant: make SameDigest return nil unconditionally -> this test fails.
|
||||
func TestSameDigestFailsOnAMismatch(t *testing.T) {
|
||||
if err := SameDigest("sha256:"+hexA, "sha256:"+hexA); err != nil {
|
||||
t.Fatalf("equal digests: %v", err)
|
||||
}
|
||||
err := SameDigest("sha256:"+hexA, "sha256:"+hexB)
|
||||
if err == nil || !strings.Contains(err.Error(), "differs") {
|
||||
t.Fatalf("mismatch accepted: %v", err)
|
||||
}
|
||||
if SameDigest("sha256:"+hexA, "") == nil {
|
||||
t.Fatal("a registry that reported no digest was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestBodyValidates(t *testing.T) {
|
||||
if _, err := RequestBody("svc", "sha256:"+hexA, "0123456789ab"); err != nil {
|
||||
t.Fatalf("legitimate request refused: %v", err)
|
||||
}
|
||||
if _, err := RequestBody("svc", "sha256:"+hexA, "0123456789ab-rc-build.7"); err != nil {
|
||||
t.Fatalf("a UAT rebuild tag is a legitimate version: %v", err)
|
||||
}
|
||||
for name, args := range map[string][3]string{
|
||||
"no service": {"", "sha256:" + hexA, "v1"},
|
||||
"tag digest": {"svc", "latest", "v1"},
|
||||
"bad version": {"svc", "sha256:" + hexA, "../x"},
|
||||
"empty version": {"svc", "sha256:" + hexA, ""},
|
||||
} {
|
||||
if _, err := RequestBody(args[0], args[1], args[2]); err == nil {
|
||||
t.Errorf("%s: accepted", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mutant: make Judge push on `refuse` -> this test fails.
|
||||
func TestJudgeRefusesOnlyAnExplicitRefusal(t *testing.T) {
|
||||
refused := Judge(200, []byte(`{"decision":"refuse","result":"block","mode":"enforce","reasons":["cve: 2 critical"],"would_block":[]}`))
|
||||
if refused.Push || !strings.Contains(refused.Message, "verdict: block (cve)") {
|
||||
t.Fatalf("refusal: %+v", refused)
|
||||
}
|
||||
}
|
||||
|
||||
// Mutant (legal direction): make Judge refuse everything -> this test fails.
|
||||
func TestJudgePushesInShadowAndSaysWhatWouldBlock(t *testing.T) {
|
||||
shadow := Judge(200, []byte(`{"decision":"push","result":"block","mode":"shadow","reasons":[],"would_block":["cve"]}`))
|
||||
if !shadow.Push || !strings.Contains(shadow.Message, "would block in enforce: cve") {
|
||||
t.Fatalf("shadow: %+v", shadow)
|
||||
}
|
||||
for name, o := range map[string]Outcome{
|
||||
"unreachable": Judge(0, nil),
|
||||
"server error": Judge(503, nil),
|
||||
"not found": Judge(404, nil),
|
||||
"garbage": Judge(200, []byte(`<html>`)),
|
||||
"unknown word": Judge(200, []byte(`{"decision":"maybe"}`)),
|
||||
} {
|
||||
if !o.Push {
|
||||
t.Errorf("%s: refused a push without an explicit refusal (%s)", name, o.Message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mutant: drop the 401/403 branch in Judge -> this test fails (a refused token
|
||||
// binding would push silently). WP-06 review, 2026-11-04.
|
||||
func TestJudgeRefusesAnAuthorizationRefusal(t *testing.T) {
|
||||
for _, status := range []int{401, 403} {
|
||||
o := Judge(status, []byte(`{"type":"scan-token-wrong-revision"}`))
|
||||
if o.Push || !strings.Contains(o.Message, "image NOT pushed") {
|
||||
t.Errorf("HTTP %d: %+v", status, o)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user