chore: publish IntegraCI build modules a11ec75d3e09

This commit is contained in:
dhimaz0445 committed 2026-11-11 03:41:55 +00:00
1 parent 694710104a
commit 3c2b80914e
78 files changed
+4982 -405

No files matched your search

+268 -3
View File
@@ -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))
}