Files

2111 lines
87 KiB
Go

// Package main implements the IntegraCI standard-build Dagger module.
//
// This module provides a standard build pipeline: lint → test → build → container image.
// It runs locally via `dagger call` or is triggered by CI connectors (GitHub Actions, GitLab CI, Jenkins).
//
// Usage:
//
// dagger call build --source . --language go
// dagger call build --source . --language python
// dagger call build --source . --language node
// dagger call test --source . --language node # lint + tests only, no image
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.
type StandardBuild struct{}
// BuildResult contains the output of a standard build.
type BuildResult struct {
Success bool `json:"success"`
Language string `json:"language"`
RuntimeVersion string `json:"runtime_version,omitempty"`
ImageRef string `json:"image_ref,omitempty"`
// ImageDigest is `sha256:<hex>` of the published manifest, empty when
// nothing was published. It is what `evidence` and every attestation must
// name: a tag moves, the digest is the artifact.
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.
//
// Dagger reports a failed exec as `exit code: N` and nothing more. For a lint
// gate that is worse than useless: `php -l` across a whole tree exits non-zero
// if ANY file fails, and the one thing the user needs — which file, and why — is
// in the output that the bare error throws away. Measured: a real build failed
// with `Error: exit code: 124`, and the actual cause (two vendored files using
// syntax removed in PHP 8) was only visible by scrolling the raw engine log.
func execDetail(err error) string {
var exec *dagger.ExecError
if !errors.As(err, &exec) {
return err.Error()
}
out := strings.TrimSpace(exec.Stderr)
if out == "" {
out = strings.TrimSpace(exec.Stdout)
}
const maxDetail = 4000
if len(out) > maxDetail {
out = "…" + out[len(out)-maxDetail:]
}
if out == "" {
return err.Error()
}
return fmt.Sprintf("exit code %d\n%s", exec.ExitCode, out)
}
// Build runs the full build pipeline: lint → test → build → container image.
//
// Supported languages: go, python, node, php.
//
// Publishing is opt-in and is driven by ONE argument, --image-ref, which is the
// full destination the caller wants (e.g. harbor.acme.internal/library/orders:abc123).
// With no --image-ref the image is built but not published (ImageRef stays
// empty) — the module never pushes tenant artifacts to a public anonymous
// registry.
//
// This used to take --registry plus --tag and publish to a HARDCODED
// "{registry}/integraci-build:{tag}", which ignored the service entirely: every
// service in a tenant published over the same repository, so the last build to
// finish was the only image anybody had. The rendered pipelines have always
// passed --image-ref (they build it from the service name), so the templates and
// the module simply disagreed and no publish could ever have worked.
// --registry/--tag are still accepted so an existing caller does not break; they
// are used only when --image-ref is absent, and then the repository is the
// service name, not a constant.
//
// A repository that ships a root Dockerfile is built FROM THAT DOCKERFILE,
// whatever --language says. See the block above the switch for why; pass
// --ignore-dockerfile to insist on the language lane.
func (m *StandardBuild) Build(
ctx context.Context,
// Source directory
source *dagger.Directory,
// Programming language: go, python, node, php
language string,
// Skip tests (default false)
// +optional
skipTests bool,
// Skip lint (default false)
// +optional
skipLint bool,
// Full destination image reference including tag, e.g.
// registry.example.com/team/service:abc123. Empty = build only.
// +optional
imageRef string,
// Service name, used as the repository when only --registry is given.
// +optional
service string,
// Container image tag (used only when --image-ref is absent)
// +optional
// +default="latest"
tag string,
// Target registry host + namespace (used only when --image-ref is absent).
// +optional
registry string,
// Registry username (paired with registryPassword).
// +optional
registryUsername string,
// Registry password/token as a Dagger secret.
// +optional
registryPassword *dagger.Secret,
// The destination registry is served over plain HTTP, so the push must not
// assume TLS. See publishImage for why this needs a different code path
// rather than a flag.
// +optional
registryInsecure bool,
// Language runtime version, e.g. "8.3" or "7.4" for PHP. The default is the
// current release, which is the right answer for new code and the WRONG one
// for the brownfield applications this module mostly serves: an application
// that has been running for a decade brings vendored libraries written
// against PHP 5, and `php -l` under 8.3 rejects them for syntax that was
// REMOVED from the language — a true finding about a version the customer
// never chose. Measured on a real import: `Array and string offset access
// syntax with curly braces is no longer supported`, in a bundled PDF
// library, which failed the build with `exit code: 124` and nothing else.
// +optional
// +default="8.3"
runtimeVersion string,
// Docker build args for the Dockerfile path, each `KEY=value`. Repeat the
// flag for more than one.
//
// python-ml, dotnet8-minimal-api and rust-axum have passed `--build-arg`
// since they were written — python-ml needs it to pin its CUDA base — and
// there was no such parameter, so those three builds died on an unknown flag
// before they could die on the unsupported language below. The contract gate
// pinned it as a known defect; this is the fix that lets that pin shrink.
// +optional
buildArg []string,
// Build with the language lane even when the repository has a root
// Dockerfile (default false: a Dockerfile wins). Only for a caller that
// knows the Dockerfile is not the deployable image — a dev-container
// recipe, say. Has no effect on a language outside the four lanes, which
// has nothing but the Dockerfile to build from.
// +optional
ignoreDockerfile bool,
// The service's directory in the checkout (ADR-0074 monorepo layout).
// Empty = the repository root, exactly as before. --source stays the
// checkout; this names where in it the service lives.
// +optional
subdir string,
// The Dockerfile, relative to --subdir. Empty = "Dockerfile".
// +optional
dockerfile string,
// "source_path" (default: --subdir is the build context) or "repo_root"
// (the whole checkout is the context: a Dockerfile that COPYs shared
// 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)
if err != nil {
return nil, err
}
pub := publishConfig{
imageRef: ref,
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.
lay, err := layout.Resolve(subdir, dockerfile, buildContext)
if err != nil {
return nil, err
}
bs, err := applyLayout(ctx, source, lay)
if err != nil {
return nil, err
}
pub.workdir = bs.workdir
source = bs.dir
// DOCKERFILE FIRST. A repository that carries a root Dockerfile has already
// said how it is containerised, and that statement outranks --language.
//
// The language lanes below exist for a tree that has NO Dockerfile: they
// invent a runtime image (node:22 running `npm run start` on 3000,
// php:<v>-apache on 80, ...) because nobody else will. Running that
// invention over a repository that brought its own recipe replaces a
// working image with a guess. MEASURED on a customer k3s cluster
// 2026-09-13: a Vite/React front-end whose Dockerfile is a two-stage node
// build into nginx:1.27-alpine, EXPOSE 80 — the ordinary SPA shape — was
// built with --language=node because the service's stack said "node". The
// lane published node:22-slim with ENTRYPOINT `npm run start` on 3000. On
// one commit package.json had no `start` script at all (`npm error Missing
// script: "start"`, CrashLoopBackOff); on a later one `start` was `npm run
// dev`, so production ran the Vite DEV SERVER, still on the wrong port for
// the Service in front of it. The Dockerfile beside it would have produced a
// working nginx image on 80 the whole time.
//
// So the check is on the TREE, not on the language: `case "node"` cannot
// tell a Node service from a Node-built static site, but the presence of a
// Dockerfile can. --ignore-dockerfile is the escape hatch, off by default,
// because the failure mode of a wrong default here is a crash-looping
// production pod behind a green pipeline, and the caller who wants the
// lane anyway can say so. The Dockerfile path runs no lint or tests (see
// buildFromDockerfile) — `Test` below covers that stage for such a tree.
if !ignoreDockerfile {
hasDockerfile := bs.hasDockerfile
if bs.dockerfile == "" {
hasDockerfile, err = hasRootDockerfile(ctx, source)
if err != nil {
return nil, err
}
}
if hasDockerfile {
return withDigest(m.buildFromDockerfile(ctx, source, bs.dockerfile, result, language, buildArg, pub))
}
}
if err := laneWorkdirProblem(language, bs.workdir); err != nil {
return nil, err
}
switch language {
case "go":
return withDigest(m.buildGo(ctx, source, result, skipTests, skipLint, pub, buildArg))
case "python":
return withDigest(m.buildPython(ctx, source, result, skipTests, skipLint, pub, buildArg))
case "node":
return withDigest(m.buildNode(ctx, source, result, skipTests, skipLint, pub, buildArg))
case "php":
return withDigest(m.buildPhp(ctx, source, result, skipTests, skipLint, pub, runtimeVersion, buildArg))
default:
// Everything else builds from the repository's own Dockerfile.
//
// The four cases above are the languages this module knows how to build
// WITHOUT one. Everything else used to fall straight to an error, and the
// templates do pass else: 8 of the 34 `standard-build` invocations name a
// language this switch does not implement — `java` 7 (java-spring across
// six engines, its Jenkinsfile twice) and `generic` 1. A java-spring
// service's build failed on the language before it failed on anything else.
//
// The counts here used to read "22 of 65 ... java 13", which attributed
// every `--language=` in catalog/templates to this module. `sast-scan`
// takes the same flag and owns 23 of those 65. See infra/dagger/README.md
// — count per module, not per repo.
//
// Every golden-path skeleton ships a Dockerfile, and the CI steps already
// gate the build on `exists: Dockerfile` / `hashFiles('Dockerfile')`, so
// this is the path they were written expecting. An unknown language with
// no Dockerfile still errors, and now says which of the two is missing.
return withDigest(m.buildFromDockerfile(ctx, source, bs.dockerfile, result, language, buildArg, pub))
}
}
// buildSource is the checkout once a build layout has been applied.
type buildSource struct {
// dir is what the lanes and the Dockerfile build read: the checkout, or
// the service directory when that is the context.
dir *dagger.Directory
// workdir is the service directory under /src for a language lane that
// reads the WHOLE checkout (context repo_root): the install runs at the
// workspace root, the rest in the member. "" = /src itself.
workdir string
// dockerfile is the Dockerfile path inside dir; "" = the root rule the
// module has always applied (a `Dockerfile` at the top of dir).
dockerfile string
// hasDockerfile is meaningful only when dockerfile != "".
hasDockerfile bool
}
// applyLayout resolves where in the checkout the build runs, and REFUSES a
// layout whose path components are not real directories (ADR-0074 §8.1).
//
// This is the authoritative symlink check. The platform's own check ran at
// onboarding, at another commit; a push after it can turn the service
// directory or its Dockerfile into a symlink to `../..` or to the agent's home,
// and `COPY . .` would then put the agent's files into a pushed image. Every
// component is read with Stat WITHOUT following symlinks, before any build
// step runs.
//
// The default layout (no --subdir, no --dockerfile, no --build-context) reads
// nothing and returns the checkout untouched: a root-layout repository builds
// exactly as it did before these arguments existed, including a root
// Dockerfile that is itself a symlink, which existing repositories may use.
func applyLayout(ctx context.Context, source *dagger.Directory, lay layout.Layout) (*buildSource, error) {
if lay.IsDefault() {
return &buildSource{dir: source}, nil
}
exists, err := layout.Confine(ctx, statWithoutFollowing(source), lay, false)
if err != nil {
return nil, err
}
bs := &buildSource{dir: source, dockerfile: lay.DockerfileInContext(), hasDockerfile: exists}
if d := lay.ContextDir(); d != "" {
bs.dir = source.Directory(d)
}
if lay.Context == layout.ContextRepoRoot {
bs.workdir = lay.Subdir
}
return bs, nil
}
// statWithoutFollowing reads a checkout path's type the way lstat would.
func statWithoutFollowing(source *dagger.Directory) layout.StatFunc {
return func(ctx context.Context, path string) (layout.Kind, error) {
ok, err := source.Exists(ctx, path, dagger.DirectoryExistsOpts{DoNotFollowSymlinks: true})
if err != nil {
return layout.Other, err
}
if !ok {
return layout.Missing, nil
}
ft, err := source.Stat(path, dagger.DirectoryStatOpts{DoNotFollowSymlinks: true}).FileType(ctx)
if err != nil {
return layout.Other, err
}
switch ft {
case dagger.FileTypeDirectory:
return layout.Directory, nil
case dagger.FileTypeRegular:
return layout.Regular, nil
case dagger.FileTypeSymlink:
return layout.Symlink, nil
default:
return layout.Other, nil
}
}
}
// laneWorkdirProblem refuses a language lane that cannot build a workspace
// member from the workspace root (context repo_root without a Dockerfile).
//
// The go lane runs in the member and `go` finds `go.work` upward; the node
// lane installs at the root (npm/yarn/pnpm workspaces keep one lockfile there)
// and lints, tests and builds in the member. The other lanes have no
// workspace form: python and php would install or serve the whole repository,
// and java's wrapper lookup is root-only. A Dockerfile with context repo_root
// is the way to build those.
func laneWorkdirProblem(language, workdir string) error {
if workdir == "" {
return nil
}
switch language {
case "go", "node":
return nil
}
return fmt.Errorf(
"build context repo_root with the %q language lane is not supported: only the go and "+
"node lanes build a workspace member from the workspace root. Add a Dockerfile, or use "+
"build context source_path",
language,
)
}
// laneDir is the directory a lane works in: /src, or the member under it.
func laneDir(pub publishConfig) string {
if pub.workdir == "" {
return "/src"
}
return "/src/" + pub.workdir
}
// Test runs ONLY the lint and test steps of a language lane: no image is
// assembled and nothing is published. ImageRef is always empty; Success is
// true when every step that ran exited 0, and the outputs are in LintOutput /
// TestOutput exactly as Build fills them.
//
// This exists because the rendered pipelines had a `Lint and Test` stage that
// ran the toolchain NATIVELY on the CI agent — `npm ci`, `python3 -m pip`,
// `corepack`, `golangci-lint` — while the Build stage right after it ran this
// module through `dagger call`. MEASURED on a customer Jenkins 2026-09-13: the
// agent is a plain container with Docker and nothing else, so every build died
// in that first stage with `npm: not found` (or the pip/corepack equivalent),
// and the stage that actually worked — Build, whose lanes already lint and
// test inside their own containers — was never reached. The toolchain the lint
// stage needs is the one the lanes already carry, so the stage calls the lane
// and stops before the image.
//
// A Dockerfile in the tree does NOT divert this the way it diverts Build. The
// Dockerfile says how the application is packaged; it says nothing about
// whether the code lints, and the customer front-end above is exactly a tree
// with a Dockerfile AND a `lint` script. So the language decides here, and a
// language outside its lanes (go, python, node, php, java) is an error that
// names it, rather than a
// silent green — there is no toolchain this module could honestly run for it.
func (m *StandardBuild) Test(
ctx context.Context,
// Source directory
source *dagger.Directory,
// Programming language: go, python, node, php, or java (Test only: Build
// has no java lane and builds a java service from its Dockerfile)
language string,
// Language runtime version, e.g. "8.3" or "7.4" for PHP — same meaning and
// same default as on Build; see the note there for why it is an argument.
// +optional
// +default="8.3"
runtimeVersion string,
// Skip tests (default false)
// +optional
skipTests bool,
// Skip lint (default false)
// +optional
skipLint bool,
// `KEY=value` pairs, each repeated, as on Build. A pipeline passes the same
// list to both calls; here they are applied to the lint/test container, so
// a suite that reads build-time configuration (Vitest resolving
// `import.meta.env.VITE_*` exactly as `vite build` would) sees what the
// image will be compiled with.
// +optional
buildArg []string,
// JDK major version the java lane lints and tests with: 11, 17 or 21
// (default 21). Ignored by every other language. A separate argument from
// --runtime-version on purpose: that one defaults to PHP's "8.3", so the
// java lane could never tell "not stated" from a PHP default. Gradle
// wrappers up to 7.x cannot run on JDK 21 at all (`Unsupported class file
// major version 65`, measured 2026-10-06 with a 7.6.4 wrapper), and the
// only other fix is to upgrade the customer's build tool.
// +optional
// +default="21"
javaVersion string,
// Same meaning as on Build: the service's directory in the checkout.
// +optional
subdir string,
// Same as on Build. Test builds no image; the Dockerfile is still checked
// for symlinks so one pipeline argument list serves both calls.
// +optional
dockerfile string,
// Same as on Build: "source_path" (default) or "repo_root".
// +optional
buildContext string,
) (*BuildResult, error) {
result := &BuildResult{Language: language, RuntimeVersion: runtimeVersion}
pub := publishConfig{testOnly: true}
lay, err := layout.Resolve(subdir, dockerfile, buildContext)
if err != nil {
return nil, err
}
bs, err := applyLayout(ctx, source, lay)
if err != nil {
return nil, err
}
if err := laneWorkdirProblem(language, bs.workdir); err != nil {
return nil, err
}
pub.workdir = bs.workdir
source = bs.dir
switch language {
case "go":
return m.buildGo(ctx, source, result, skipTests, skipLint, pub, buildArg)
case "python":
return m.buildPython(ctx, source, result, skipTests, skipLint, pub, buildArg)
case "node":
return m.buildNode(ctx, source, result, skipTests, skipLint, pub, buildArg)
case "php":
return m.buildPhp(ctx, source, result, skipTests, skipLint, pub, runtimeVersion, buildArg)
case "java":
return m.testJava(ctx, source, result, skipTests, skipLint, javaVersion, buildArg)
default:
return nil, fmt.Errorf(
"language %q has no lint/test lane (supported: go, python, node, php, java); "+
"a Dockerfile can build it but cannot say how to test it",
language,
)
}
}
// The JDK the java lane lints and tests with by default: the one the
// java-spring golden path targets (its Jenkinsfile used to demand
// `jdk 'temurin-21'` on the agent). Maven projects use the Maven image of the
// same JDK; Gradle projects bring their own Gradle through the wrapper.
const defaultJavaVersion = "21"
// javaVersions is the CLOSED set of JDKs the lane runs: the LTS releases that
// both image families publish. A closed set, never a pattern: the value picks
// an image tag, and a free-text tag is an image nobody vetted. The platform
// validates the same set on the service spec (`spec.pipeline.java_version`),
// so a value outside it is refused there, before any CI runs; this check is
// for a caller that does not come through the spec.
var javaVersions = map[string]bool{"11": true, "17": true, "21": true}
// javaImages returns the JDK version and its Maven and bare-JDK images, or an
// error naming the supported set. An empty version is the default.
func javaImages(version string) (string, string, string, error) {
if version == "" {
version = defaultJavaVersion
}
if !javaVersions[version] {
return "", "", "", fmt.Errorf(
"java version %q is not supported by the java lane (supported: 11, 17, 21)", version,
)
}
return version,
fmt.Sprintf("maven:3.9-eclipse-temurin-%s", version),
fmt.Sprintf("eclipse-temurin:%s-jdk", version),
nil
}
// testJava lints and tests a Maven or Gradle project. Test only: Build has no
// java lane — a java service is built from its own Dockerfile (the default arm
// of Build), and that path runs no lint or tests at all.
//
// This exists for the same reason Test does. MEASURED on platform-provisioned
// Jenkins agents (jnlp + a dagger-engine sidecar, nothing else): the
// java-spring template ran `mvn` on the agent and demanded a `temurin-21` JDK
// tool, neither of which exists there, so every java pipeline died before its
// first useful stage. The toolchain belongs in a container, like every other
// lane's.
//
// "Lint" is what the project itself binds to its lifecycle with tests skipped:
// `verify -DskipTests` runs compile plus every check the pom binds (the
// golden-path skeletons bind `spotless:check`), `gradlew check -x test` the
// Gradle equivalent. Never a plugin goal the project did not declare — the old
// template forced `spotless:check` on every repository, and on one that does
// not declare Spotless that goal does not even resolve. The repository's own
// Maven wrapper wins over the image's Maven when it ships one, as it would on
// a developer's machine. Tests then run in the container lint left behind, so
// nothing is compiled twice. A tree with neither a root `pom.xml` nor a root
// `gradlew` is an error that says so, not a silent green.
func (m *StandardBuild) testJava(
ctx context.Context, source *dagger.Directory,
result *BuildResult, skipTests, skipLint bool, javaVersion string, buildArg []string,
) (*BuildResult, error) {
javaVersion, javaMavenImage, javaJdkImage, err := javaImages(javaVersion)
if err != nil {
return nil, err
}
result.RuntimeVersion = javaVersion
hasPom, err := hasRootEntry(ctx, source, "pom.xml")
if err != nil {
return nil, err
}
hasMvnw, err := hasRootEntry(ctx, source, "mvnw")
if err != nil {
return nil, err
}
hasGradlew, err := hasRootEntry(ctx, source, "gradlew")
if err != nil {
return nil, err
}
var base *dagger.Container
var lintCmd, testCmd []string
switch {
case hasPom:
maven := []string{"mvn"}
if hasMvnw {
// `sh ./mvnw`: the wrapper's exec bit does not always survive a
// checkout, and the shell does not need it.
maven = []string{"sh", "./mvnw"}
}
base = dag.Container().
From(javaMavenImage).
// Persist the local repository so repeat runs don't re-download
// every dependency.
WithMountedCache("/root/.m2", dag.CacheVolume("maven-repo"))
lintCmd = withArgs(maven, "-B", "-ntp", "-DskipTests", "verify")
testCmd = withArgs(maven, "-B", "-ntp", "test")
case hasGradlew:
base = dag.Container().
From(javaJdkImage).
WithMountedCache("/root/.gradle", dag.CacheVolume("gradle-home"))
lintCmd = []string{"sh", "./gradlew", "--no-daemon", "check", "-x", "test"}
testCmd = []string{"sh", "./gradlew", "--no-daemon", "test"}
default:
return nil, fmt.Errorf(
"java lane needs a root pom.xml (Maven) or a root gradlew (Gradle wrapper); found neither",
)
}
base = lintTestBase(
base.WithDirectory("/src", source).WithWorkdir("/src"),
publishConfig{testOnly: true},
buildArg,
)
// Lint
if !skipLint {
linted := base.WithExec(lintCmd)
out, err := linted.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("java lint failed: %s", execDetail(err))
}
result.LintOutput = out
base = linted
}
// Test
if !skipTests {
out, err := base.WithExec(testCmd).Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("java tests failed: %s", execDetail(err))
}
result.TestOutput = out
}
return testsDone(result), nil
}
// withArgs is cmd followed by args, in a fresh slice: two commands built from
// one prefix must never share a backing array.
func withArgs(cmd []string, args ...string) []string {
out := make([]string, 0, len(cmd)+len(args))
out = append(out, cmd...)
return append(out, args...)
}
// hasRootEntry reports whether `name` exists at the source-tree root.
func hasRootEntry(ctx context.Context, source *dagger.Directory, name string) (bool, error) {
entries, err := source.Entries(ctx)
if err != nil {
return false, fmt.Errorf("reading source directory: %w", err)
}
for _, entry := range entries {
if entry == name {
return true, nil
}
}
return false, nil
}
// hasRootDockerfile reports whether the source tree carries a `Dockerfile` at
// its root — the one place `docker build .` and Directory.DockerBuild look.
// Only the root: a Dockerfile under `deploy/` or `docker/` is a recipe for
// something, but not necessarily for this tree, and guessing which one would
// reintroduce the wrong-image failure this check exists to prevent.
func hasRootDockerfile(ctx context.Context, source *dagger.Directory) (bool, error) {
return hasRootEntry(ctx, source, "Dockerfile")
}
// buildFromDockerfile builds the source tree's own Dockerfile.
//
// No test or lint phase: this module cannot know how an arbitrary stack runs
// them, and inventing a guess would be worse than leaving the CI template's own
// test job to do it — which is where those stages already live (and, for the
// languages Test has a lane for — go, python, node, php, java — `Test` is
// what that job should call).
//
// dockerfile is the Dockerfile's path inside source, already confined by
// applyLayout; "" keeps the root rule this function has always applied.
func (m *StandardBuild) buildFromDockerfile(
ctx context.Context, source *dagger.Directory, dockerfile string,
result *BuildResult, language string, buildArg []string, pub publishConfig,
) (*BuildResult, error) {
var hasDockerfile bool
var err error
if dockerfile == "" {
hasDockerfile, err = hasRootDockerfile(ctx, source)
} else {
// Read again without following symlinks, as a regular file: this is the
// file DockerBuild is about to read.
hasDockerfile, err = source.Exists(ctx, dockerfile, dagger.DirectoryExistsOpts{
ExpectedType: dagger.ExistsTypeRegularType,
DoNotFollowSymlinks: true,
})
}
if err != nil {
return nil, err
}
if !hasDockerfile {
return nil, fmt.Errorf(
"language %q has no built-in build (supported: go, python, node, php) "+
"and the source has no Dockerfile to fall back to",
language,
)
}
source, err = applyDockerfileIgnore(ctx, source, dockerfile)
if err != nil {
return nil, err
}
args := make([]dagger.BuildArg, 0, len(buildArg))
for _, raw := range buildArg {
name, value, found := strings.Cut(raw, "=")
if !found || name == "" {
return nil, fmt.Errorf("--build-arg must be KEY=value, got %q", raw)
}
args = append(args, dagger.BuildArg{Name: name, Value: value})
}
opts := dagger.DirectoryDockerBuildOpts{BuildArgs: args}
if dockerfile != "" {
opts.Dockerfile = dockerfile
}
image := source.DockerBuild(opts)
ref, err := publishImage(ctx, image, pub)
if err != nil {
return nil, err
}
result.Success = true
result.ImageRef = ref
return result, nil
}
// applyDockerfileIgnore applies `<Dockerfile>.dockerignore` to the build
// context in the mode layout.ContextFilters fixes: for the generated
// `.integraci/Dockerfile`, the context's root `.dockerignore` and then the
// sidecar's exclusions (no re-includes); for a customer's own Dockerfile,
// BuildKit's rule -- the sidecar alone, re-includes kept. See layout/ignore.go.
//
// No sidecar: the context is returned untouched, so a build without one
// behaves exactly as before -- except for the GENERATED Dockerfile, whose
// missing sidecar refuses the build (layout.GeneratedSidecarPresent). Ignore files are typed WITHOUT following
// symlinks; for the generated Dockerfile one that is not a regular file
// refuses the build (layout.IgnoreFileUsable), for a customer's it is left to
// the engine as before. source is the build context, and dockerfile its
// Dockerfile path inside it ("" = the root `Dockerfile`), already confined by
// applyLayout.
func applyDockerfileIgnore(ctx context.Context, source *dagger.Directory, dockerfile string) (*dagger.Directory, error) {
stat := statWithoutFollowing(source)
if dockerfile == "" {
dockerfile = layout.DefaultDockerfile
}
sidecar := layout.SidecarPath(dockerfile)
generated := layout.IsGeneratedDockerfile(dockerfile)
kind, err := stat(ctx, sidecar)
if err != nil {
return nil, fmt.Errorf("reading %q: %w", sidecar, err)
}
if generated {
// The generated pair is never built half: without its sidecar the
// generated `COPY . .` takes `.env` and keys into the image.
if err := layout.GeneratedSidecarPresent(sidecar, kind); err != nil {
return nil, err
}
}
useSidecar, err := layout.IgnoreFileUsable(sidecar, kind)
if !generated && err != nil {
// A customer's own sidecar that is not a regular file: left to the
// engine's Dockerfile frontend exactly as before this module read
// sidecars at all. Only the generated pair is refused (see
// layout.IgnoreFileUsable).
return source, nil
}
if err != nil || !useSidecar {
return source, err
}
sidecarBody, err := source.File(sidecar).Contents(ctx)
if err != nil {
return nil, fmt.Errorf("reading %q: %w", sidecar, err)
}
hasRoot := false
rootBody := ""
if generated {
rootKind, err := stat(ctx, layout.RootIgnoreFile)
if err != nil {
return nil, fmt.Errorf("reading %q: %w", layout.RootIgnoreFile, err)
}
hasRoot, err = layout.IgnoreFileUsable(layout.RootIgnoreFile, rootKind)
if err != nil {
return nil, err
}
}
if hasRoot {
rootBody, err = source.File(layout.RootIgnoreFile).Contents(ctx)
if err != nil {
return nil, fmt.Errorf("reading %q: %w", layout.RootIgnoreFile, err)
}
}
// The definition being built must survive whatever the patterns say.
definition := source.File(dockerfile)
for _, exclude := range layout.ContextFilters(rootBody, hasRoot, sidecarBody, generated) {
source = source.Filter(dagger.DirectoryFilterOpts{Exclude: exclude})
}
return source.WithFile(dockerfile, definition), nil
}
// buildEnv applies `KEY=value` pairs to a container as environment variables.
//
// `--build-arg` was a DOCKERFILE-only parameter: the four native lanes below
// ignored it entirely. That is exactly backwards for the stack that needs it
// most. A Vite/Next/CRA front-end reads its API base at BUILD time and inlines
// it into the bundle, and those are built by `buildNode`, not from a
// Dockerfile — so the one lane that could not receive build configuration was
// the one lane whose framework cannot be configured any other way.
//
// MEASURED on a customer front-end 2026-09-07: `VITE_API_URL` unset at build,
// so `axios.create({baseURL: import.meta.env.VITE_API_URL})` compiled to an
// empty base and every request went to the page's own origin, which answered
// 405. The workaround that had grown up instead was committing a
// `.env.production` into the application repository — one environment's backend
// hardcoded into every stage's image.
//
// Applied BEFORE the build exec so the framework sees it; malformed pairs are
// skipped rather than failing the build, because the caller-side renderer
// already refuses them and a second hard failure here would only turn a
// configuration mistake into a red pipeline with a worse message.
func buildEnv(c *dagger.Container, buildArg []string) *dagger.Container {
for _, raw := range buildArg {
name, value, found := strings.Cut(raw, "=")
if !found || name == "" {
continue
}
c = c.WithEnvVariable(name, value)
}
return c
}
// publishConfig carries the opt-in registry publish settings, and the one
// switch that makes a lane stop before it has anything to publish.
type publishConfig struct {
imageRef string
username string
password *dagger.Secret
insecure bool
// testOnly makes the lane return after its lint and test steps, with no
// image assembled and no publish attempted. Set by Test, never by Build.
// It rides in this struct rather than as a fifth positional bool so that
// the four lane signatures — which the contract tests pin — do not grow,
// and so that the lint/test code lives in exactly one place per lane
// instead of being copied into a second set of functions.
testOnly bool
// workdir is the workspace member a lane works in when it reads the whole
// checkout (context repo_root); "" = /src. Rides here for the same reason
// 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.
//
// In test-only mode the build-time configuration is applied HERE, because
// there is no build step after the tests for it to be applied to, and a
// parameter that is accepted and dropped is worse than one that is absent. In
// build mode the container is returned unchanged: Build has always run lint
// and tests without the build args and applied them only to the build exec,
// and this change does not alter what an existing pipeline's tests see.
func lintTestBase(base *dagger.Container, pub publishConfig, buildArg []string) *dagger.Container {
if pub.testOnly {
return buildEnv(base, buildArg)
}
return base
}
// testsDone is the result of a lane in test-only mode: green, and honest
// about carrying no image. Success here means "lint and tests passed", which
// is all the caller asked.
func testsDone(result *BuildResult) *BuildResult {
result.Success = true
result.ImageRef = ""
return result
}
// destinationRef resolves where the built image should be published.
//
// --image-ref wins outright: it is the whole destination and needs no
// assembly. Otherwise a destination is built from --registry, the SERVICE name
// and --tag; a --registry with no service is refused rather than silently
// substituting a shared repository name, which is how every service in a tenant
// came to overwrite one image.
func destinationRef(imageRef, registry, service, tag string) (string, error) {
if imageRef != "" {
return imageRef, nil
}
if registry == "" {
return "", nil // build-only: nothing to publish to
}
if service == "" {
return "", fmt.Errorf(
"--registry given without --service or --image-ref: refusing to publish " +
"to a shared repository name where every service would overwrite the last")
}
if tag == "" {
tag = "latest"
}
return fmt.Sprintf("%s/%s:%s", registry, service, tag), nil
}
// registryHost is the host portion of an image reference, which is what
// WithRegistryAuth authenticates against — "harbor.internal:30002" out of
// "harbor.internal:30002/library/orders:abc". A reference with no host segment
// (docker.io shorthand) yields "".
func registryHost(imageRef string) string {
head, _, found := strings.Cut(imageRef, "/")
if !found || (!strings.Contains(head, ".") && !strings.Contains(head, ":") && head != "localhost") {
return ""
}
return head
}
// publishImage pushes the image to the resolved destination, or skips
// publishing (leaving ImageRef empty) when there is none. A publish failure is
// returned, never swallowed — a build that could not deliver its artifact is
// not a success.
func publishImage(ctx context.Context, image *dagger.Container, pub publishConfig) (string, error) {
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)
}
if pub.password != nil {
image = image.WithRegistryAuth(registryHost(pub.imageRef), pub.username, pub.password)
}
ref, err := image.Publish(ctx, pub.imageRef)
if err != nil {
return "", fmt.Errorf("publish to %s failed: %w", pub.imageRef, err)
}
return ref, nil
}
// craneImage is the pusher used for a plain-HTTP registry. Apache-2.0.
//
// The `/debug` variant, which is the same crane plus a busybox shell. The plain
// image is DISTROLESS — no `sh` at all — so a shell step against it fails with
// `exit code: 1` and produces no output whatsoever, which is indistinguishable
// from the registry refusing the push. Measured twice before the cause was
// visible. A shell is needed here to feed the credential in on STDIN, which is
// what keeps it off the argv and out of the layer.
//
// 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.22.1"
// publishInsecure pushes to a registry that is served over plain HTTP.
//
// WHY THIS IS NOT A FLAG ON Publish. Dagger's publish goes through buildkit,
// which resolves every destination over HTTPS and has no per-call opt-out: the
// only way to tell it otherwise is an engine-level config file, which means
// getting a file into a sidecar of a pod template of a chart — a lot of moving
// parts, all of them the customer's, to change one boolean.
//
// This is the honest alternative and it is entirely inside the module: export
// the built image as a tarball and push it with crane, which takes --insecure as
// an argument. Nothing about the cluster has to change, and any deployment whose
// registry has no certificate (a managed registry on a private cluster with no
// ingress host is the normal case, not an exotic one) can deliver artifacts.
//
// The credential is a Dagger SECRET mounted as a file and read by `crane auth
// login --password-stdin`, so it is never an argv entry and never a layer.
func publishInsecure(ctx context.Context, image *dagger.Container, pub publishConfig) (string, error) {
host := registryHost(pub.imageRef)
if host == "" {
return "", fmt.Errorf("insecure publish needs a registry host in %q", pub.imageRef)
}
// Docker media types: `crane push` reads a docker-save-shaped archive.
tar := image.AsTarball(dagger.ContainerAsTarballOpts{
MediaTypes: dagger.ImageMediaTypesDockerMediaTypes,
})
pusher := dag.Container().
From(craneImage).
WithFile("/tmp/image.tar", tar)
login := "echo 'no registry credential supplied; pushing anonymously'"
if pub.password != nil {
pusher = pusher.WithMountedSecret("/tmp/registry-password", pub.password)
login = fmt.Sprintf(
"crane auth login %s -u %s --password-stdin < /tmp/registry-password",
shellQuote(host), shellQuote(pub.username),
)
}
// The step ALWAYS exits 0 and reports what happened on stdout, and success is
// judged by the confirmation line rather than by the exit status.
//
// That is not a shortcut, it is the only way to see the reason. A failing
// exec surfaces as `exit code: 1` with nothing attached — measured twice on
// a live build, once for `crane auth login` and once for the push — and a
// registry refusal, a wrong credential and an unreachable token realm are
// three completely different problems that all look identical that way.
out, err := pusher.WithExec([]string{
"sh", "-c",
fmt.Sprintf(
"{ %s; crane push --insecure /tmp/image.tar %s && echo PUSHED %s; } 2>&1; "+
"echo \"crane exit=$?\"",
login, shellQuote(pub.imageRef), shellQuote(pub.imageRef),
),
}).Stdout(ctx)
if err != nil {
return "", fmt.Errorf("insecure publish to %s failed: %s", pub.imageRef, execDetail(err))
}
if !strings.Contains(out, "PUSHED") {
return "", fmt.Errorf("insecure publish to %s did not confirm:\n%s", pub.imageRef, out)
}
// crane push prints the pushed manifest as `<repo>@sha256:<hex>`. Return
// the destination pinned to it — the same shape Publish returns on the TLS
// path — so ImageDigest is filled whichever path pushed. Without a printed
// digest the tag is all there is, and ImageDigest stays empty rather than
// guessed.
if pinned := evidence.DigestFromPushOutput(out); pinned != "" {
if d := evidence.DigestOf(pinned); d != "" {
return pub.imageRef + "@" + d, nil
}
}
return pub.imageRef, nil
}
// withDigest fills ImageDigest from the published reference. Publish returns
// `<repo>:<tag>@sha256:<hex>`; a reference without a digest leaves it empty.
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.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.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:
//
// sbom.cdx.json | sbom.spdx.json SBOM of the image, generated by syft
// provenance.intoto.json in-toto Statement, SLSA v1 provenance
// SHA256SUMS `sha256sum -c` manifest over the two above
//
// The caller exports the directory (`export --path=evidence`) and keeps it as
// a build artifact; `cosign attest-provenance --predicate` and
// `cosign attest-sbom` attach the SAME files to the digest, so the bytes a
// verifier fetches from the registry and the bytes archived with the build are
// one set. Nothing here signs: an unsigned statement is a claim, the
// signature makes it an attestation.
//
// --image-ref MUST be pinned to a digest (Build's `image_ref` is). A tag is
// refused rather than resolved: resolving it here would record whatever the
// tag points at by the time this step runs.
//
// One caveat, latent while Build publishes a single platform: if --image-ref
// names a multi-platform image INDEX, syft describes one platform's manifest
// while the provenance subject is the index digest. Run evidence per platform
// manifest digest when Build learns to publish more than one.
//
// Usage:
//
// dagger call evidence --source=. \
// --image-ref=registry.example/team/orders:abc@sha256:<hex> \
// --builder-id=https://ci.example/job/orders/ \
// --source-uri=git+https://git.example/team/orders@refs/heads/main \
// --source-revision=<full commit id> --invocation-id=$BUILD_ID \
// export --path=evidence
func (m *StandardBuild) Evidence(
ctx context.Context,
// Source directory (only used as the SBOM working directory; the SBOM
// describes the IMAGE, not the tree)
source *dagger.Directory,
// Published image, pinned: <repo>[:tag]@sha256:<64 hex>
imageRef string,
// Absolute URI identifying the pipeline that built the image
builderId string,
// Source repository URI, e.g. git+https://git.example/org/repo@refs/heads/main
sourceUri string,
// Full commit id the image was built from (40 or 64 hex)
sourceRevision string,
// Build recipe URI recorded as SLSA buildType
// +optional
buildType string,
// CI run identifier
// +optional
invocationId string,
// Build start time, RFC 3339
// +optional
startedOn string,
// Build finish time, RFC 3339
// +optional
finishedOn string,
// Build lane, recorded as an internal parameter
// +optional
language string,
// SBOM format: cyclonedx | spdx
// +optional
// +default="cyclonedx"
sbomFormat string,
// Registry username for pulling --image-ref
// +optional
registryUsername string,
// Registry password/token for pulling --image-ref
// +optional
registryPassword *dagger.Secret,
// The registry is served over plain HTTP (same opt-in as Build)
// +optional
registryInsecure bool,
) (*dagger.Directory, error) {
// Validate everything BEFORE pulling anything: a refused statement should
// not cost an SBOM run first.
provenance, err := evidence.ProvenanceStatement(evidence.ProvenanceInput{
ImageRef: imageRef,
BuilderID: builderId,
BuildType: buildType,
SourceURI: sourceUri,
SourceRevision: sourceRevision,
InvocationID: invocationId,
StartedOn: startedOn,
FinishedOn: finishedOn,
EngineVersion: daggerEngineVersion,
Language: language,
})
if err != nil {
return nil, err
}
sbomName, syftOutput, err := evidence.SBOMFileName(sbomFormat)
if err != nil {
return nil, err
}
// anchore/syft is distroless; copy the binary into alpine for a shell.
// The target is `registry:` explicitly — see sbom.syftTarget for the
// measured failure of a bare reference inside a Dagger container.
scanner := dag.Container().
From("alpine:3.20").
WithFile("/usr/local/bin/syft", dag.Container().From(syftImage).File("/syft")).
WithMountedDirectory("/src", source).
WithWorkdir("/src").
WithEnvVariable("IMAGE_REF", imageRef)
if registryInsecure {
scanner = scanner.
WithEnvVariable("SYFT_REGISTRY_INSECURE_USE_HTTP", "true").
WithEnvVariable("SYFT_REGISTRY_INSECURE_SKIP_TLS_VERIFY", "true")
}
if registryPassword != nil {
host := registryHost(imageRef)
if host == "" {
return nil, fmt.Errorf("registry credentials need a registry host in %q", imageRef)
}
scanner = scanner.
WithEnvVariable("SYFT_REGISTRY_AUTH_AUTHORITY", host).
WithEnvVariable("SYFT_REGISTRY_AUTH_USERNAME", registryUsername).
WithSecretVariable("SYFT_REGISTRY_AUTH_PASSWORD", registryPassword)
}
// The reference goes through the environment, not the command string: it
// is caller input, and ParseDigestRef has already pinned its shape.
sbom, err := scanner.
WithExec([]string{
"sh", "-c",
fmt.Sprintf(`mkdir -p /out && syft "registry:${IMAGE_REF}" -o %s=/out/%s`, syftOutput, sbomName),
}).
File("/out/" + sbomName).
Contents(ctx)
if err != nil {
return nil, fmt.Errorf("sbom for %s failed: %s", imageRef, execDetail(err))
}
files := map[string][]byte{
sbomName: []byte(sbom),
"provenance.intoto.json": provenance,
}
sums, err := evidence.SHA256Sums(files)
if err != nil {
return nil, err
}
dir := dag.Directory().WithNewFile("SHA256SUMS", string(sums))
for name, body := range files {
dir = dir.WithNewFile(name, string(body))
}
return dir, nil
}
// shellQuote wraps a value for single-quoted shell use. The values here are a
// registry host, a username and an image reference — all caller-supplied, so
// they are quoted rather than trusted.
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'"'"'`) + "'"
}
func (m *StandardBuild) buildGo(
ctx context.Context, source *dagger.Directory,
result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string,
) (*BuildResult, error) {
base := dag.Container().
From("golang:1.23-bookworm").
// Persist the module + build caches across runs so repeat builds
// don't re-download modules or recompile the standard library.
WithMountedCache("/go/pkg/mod", dag.CacheVolume("go-mod")).
WithMountedCache("/root/.cache/go-build", dag.CacheVolume("go-build")).
WithDirectory("/src", source).
// A workspace member (context repo_root) runs in its own directory;
// `go` finds the root `go.work` upward. "/src" otherwise, as before.
WithWorkdir(laneDir(pub))
base = lintTestBase(base, pub, buildArg)
// Lint
if !skipLint {
lint := base.WithExec([]string{"go", "vet", "./..."})
out, err := lint.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("go vet failed: %w", err)
}
result.LintOutput = out
}
// Test
if !skipTests {
test := base.WithExec([]string{"go", "test", "-race", "-v", "./..."})
out, err := test.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("go test failed: %w", err)
}
result.TestOutput = out
}
if pub.testOnly {
return testsDone(result), nil
}
// Build binary
build := buildEnv(base, buildArg).WithExec([]string{
"go", "build", "-o", "/out/app", ".",
})
// Container image
image := dag.Container().
From("gcr.io/distroless/static-debian12:nonroot").
WithFile("/app", build.File("/out/app")).
WithEntrypoint([]string{"/app"})
ref, err := publishImage(ctx, image, pub)
if err != nil {
return nil, err
}
result.Success = true
result.ImageRef = ref
return result, nil
}
// pythonEntrypointScript starts the project's declared console script, or fails
// with a sentence a person can act on.
//
// Read at RUN time, not build time, so the image stays a plain artefact and the
// message reflects the tree it was built from. `[project.scripts]` is the one
// place a Python project states how it is started; a project that declares none
// has not told anyone, and the honest response is to say which field to set
// rather than to start an interactive interpreter that exits immediately.
//
// A tree installed for its DEPENDENCIES only (pythonInstallPlanScript's
// `dependencies` mode) has no console script on PATH, so the script's own
// `module:function` target is started from the checkout instead; without that a
// project whose `[project.scripts]` the image used to install would exit 127.
// The target reaches python as an argument, never as code, and the reader runs
// with `-I` so nothing in the tree is imported while choosing.
const pythonEntrypointScript = `set -e
resolved=$(python -I - <<'PY'
import tomllib, pathlib
try:
data = tomllib.loads(pathlib.Path("pyproject.toml").read_text())
except Exception:
data = {}
scripts = (data.get("project") or {}).get("scripts") or {}
if isinstance(scripts, dict) and len(scripts) == 1:
name, target = next(iter(scripts.items()))
print(name)
print(str(target).split("[")[0].strip())
PY
)
script=$(printf '%s\n' "$resolved" | sed -n 1p)
target=$(printf '%s\n' "$resolved" | sed -n 2p)
if [ -n "$script" ] && command -v "$script" >/dev/null 2>&1; then exec "$script"; fi
if [ -n "$target" ]; then
exec python -c 'import importlib, sys
module, _, attr = sys.argv[1].partition(":")
obj = importlib.import_module(module.strip())
for part in attr.strip().split("."):
if part:
obj = getattr(obj, part)
sys.exit(obj())' "$target"
fi
echo "integraci: this image has no entrypoint." >&2
echo " The project declares no single [project.scripts] entry, so the build" >&2
echo " could not tell how to start it. Set deploy.runtime.command in the" >&2
echo " service spec, or declare a console script in pyproject.toml." >&2
exit 64
`
// pythonInstallPlanScript decides how a Python tree is installed, from what its
// pyproject.toml DECLARES rather than from the file existing.
//
// A pyproject.toml is not a promise that the tree is a package. Brownfield
// services ship one for tool settings only (`[tool.ruff]`), and installing such a
// tree with `pip install -e .[dev]` hands it to setuptools' automatic discovery,
// which refuses any flat layout with more than one top-level package
// ("Multiple top-level packages discovered in a flat-layout: ['app', 'agent',
// 'config', 'deploy']"). Measured on production 2026-10-12: two imported FastAPI
// services failed Lint and Test there, before ruff ran, on a file that only
// configured ruff.
//
// So, in order:
// - `package`: `[build-system]` is declared, or the tree carries setup.py /
// setup.cfg — the authors meant it to be built. Installed exactly as before
// (`-e .[dev]`, `.` for the image).
// - `dependencies`: `[project]` without `[build-system]` — its DEPENDENCIES are
// installed (`-r pyproject.toml`, plus the `dev` extra when it has one), the
// tree itself is never built, so its layout cannot fail the install.
// - `requirements`: no project declared, a requirements.txt present.
//
// requirements.txt is installed too when both exist: an application's
// pyproject.toml is as likely to hold its tool settings as its dependencies.
// Parsed with tomllib inside the build container, as pythonEntrypointScript
// does, so the module needs no TOML library of its own. Prints one JSON object.
// Run with `python -I`: plain `-c` puts the working directory — the tenant's
// tree — first on sys.path, so a root-level json.py or pathlib.py would run on
// import and could print any plan.
const pythonInstallPlanScript = `
import json, pathlib, tomllib
has_requirements = pathlib.Path("requirements.txt").is_file()
pyproject = pathlib.Path("pyproject.toml")
data = {}
if pyproject.is_file():
try:
data = tomllib.loads(pyproject.read_text())
except Exception as exc:
print(json.dumps({"error": "pyproject.toml is not valid TOML: %s" % exc}))
raise SystemExit(0)
tools = ["ruff", "pytest", "pytest-cov"]
requirements = ["-r", "requirements.txt"] if has_requirements else []
project = data.get("project")
package = {"mode": "package", "test": ["-e", ".[dev]"], "runtime": ["."]}
if isinstance(data.get("build-system"), dict):
plan = package
elif pathlib.Path("setup.py").is_file() or pathlib.Path("setup.cfg").is_file():
# A setuptools project configured the older way: its packaging lives in
# setup.py/setup.cfg, and its pyproject.toml may hold tool settings only.
plan = package
elif isinstance(project, dict):
extras = project.get("optional-dependencies")
dev = ["--extra", "dev"] if isinstance(extras, dict) and "dev" in extras else []
plan = {
"mode": "dependencies",
"test": ["-r", "pyproject.toml", *dev, *requirements, *tools],
"runtime": ["-r", "pyproject.toml", *requirements],
}
elif has_requirements:
plan = {"mode": "requirements", "test": [*requirements, *tools], "runtime": requirements}
else:
plan = {
"error": "pyproject.toml declares neither [project] nor [build-system] and there "
"is no requirements.txt, so there is nothing to install. List the dependencies "
"in requirements.txt or in [project].dependencies."
}
print(json.dumps(plan))
`
// pythonInstallPlan is pythonInstallPlanScript's answer.
type pythonInstallPlan struct {
Mode string `json:"mode"`
Test []string `json:"test"`
Runtime []string `json:"runtime"`
Error string `json:"error"`
}
// readPythonInstallPlan runs pythonInstallPlanScript against the source tree.
func readPythonInstallPlan(ctx context.Context, source *dagger.Directory) (*pythonInstallPlan, error) {
out, err := dag.Container().
From("python:3.12-slim").
WithDirectory("/src", source).
WithWorkdir("/src").
WithExec([]string{"python", "-I", "-c", pythonInstallPlanScript}).
Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("reading the python install plan: %s", execDetail(err))
}
var plan pythonInstallPlan
if err := json.Unmarshal([]byte(strings.TrimSpace(out)), &plan); err != nil {
return nil, fmt.Errorf("reading the python install plan: %w", err)
}
if plan.Error != "" {
return nil, fmt.Errorf("python lane: %s", plan.Error)
}
if plan.Mode == "" || len(plan.Test) == 0 || len(plan.Runtime) == 0 {
return nil, fmt.Errorf("python lane: the install plan is incomplete: %q", out)
}
return &plan, nil
}
func (m *StandardBuild) buildPython(
ctx context.Context, source *dagger.Directory,
result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string,
) (*BuildResult, error) {
// uv = fast, reproducible installs (mirrors apps/api/Dockerfile). The
// binary is copied from the pinned Astral uv image, exactly as the
// Dockerfile does (COPY --from=ghcr.io/astral-sh/uv:0.5.11 /uv ...).
uvBin := dag.Container().From("ghcr.io/astral-sh/uv:0.5.11").File("/uv")
hasPyproject, err := hasRootEntry(ctx, source, "pyproject.toml")
if err != nil {
return nil, err
}
hasRequirements, err := hasRootEntry(ctx, source, "requirements.txt")
if err != nil {
return nil, err
}
if !hasPyproject && !hasRequirements {
return nil, fmt.Errorf(
"python lane needs pyproject.toml or requirements.txt at the source root",
)
}
plan, err := readPythonInstallPlan(ctx, source)
if err != nil {
return nil, err
}
base := dag.Container().
From("python:3.12-slim").
WithFile("/usr/local/bin/uv", uvBin).
// Persist the uv download/wheel cache across runs.
WithMountedCache("/root/.cache/uv", dag.CacheVolume("uv")).
WithDirectory("/src", source).
WithWorkdir("/src")
// What gets installed is pythonInstallPlanScript's decision: the editable
// project + [dev] for a declared package, its dependencies (and ruff/pytest)
// for anything else. Brownfield FastAPI trees often only ship
// requirements.txt, or a pyproject.toml that configures ruff and nothing more.
base = base.WithExec(withArgs([]string{"uv", "pip", "install", "--system"}, plan.Test...))
if plan.Mode != "package" {
// Nothing was installed under the tree's own name, so tests import it
// from the checkout: the root, and `src/` for a src-layout.
base = base.WithEnvVariable("PYTHONPATH", "/src:/src/src")
}
base = lintTestBase(base, pub, buildArg)
if !skipLint {
lint := base.WithExec([]string{"ruff", "check", "."})
out, err := lint.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("ruff check failed: %w", err)
}
result.LintOutput = out
}
if !skipTests {
hasTests, err := hasRootEntry(ctx, source, "tests")
if err != nil {
return nil, err
}
// A declared package is tested with pytest as before. Anything else
// runs pytest only when it HAS tests: a pyproject.toml that configures
// ruff says nothing about tests, and pytest with nothing to collect exits 5.
if hasTests || plan.Mode == "package" {
test := base.WithExec([]string{"pytest", "-v"})
out, err := test.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("pytest failed: %w", err)
}
result.TestOutput = out
} else {
// requirements.txt apps often have no tests/ yet — still prove the
// tree imports (compileall) so Lint and Test is not a no-op.
compile := base.WithExec([]string{"python", "-m", "compileall", "-q", "."})
out, err := compile.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("compileall failed: %w", err)
}
result.TestOutput = out
if result.TestOutput == "" {
result.TestOutput = "no tests/ directory; compileall + ruff only\n"
}
}
}
if pub.testOnly {
return testsDone(result), nil
}
// THE IMAGE. This lane took `_ publishConfig` and returned here, so a Python
// service compiled, linted, tested, went green — and published NOTHING, for
// ever. It is the same defect the node lane carried until #1706/#1707 fixed
// that one and left this one, and it presents identically: `StandardBuild
// DONE`, an imageRef printed by the caller, and the registry answering
// NAME_UNKNOWN for it. The deploy then sits in ImagePullBackOff behind a
// green pipeline.
//
// Built from a SEPARATE, non-dev install rather than from `base`. `base`
// carries `.[dev]` — pytest, ruff, every test dependency — because that is
// what the lint and test steps above need. Publishing that layer would ship
// the test toolchain to production.
//
// The ENTRYPOINT is the part this lane cannot invent, and getting it wrong is
// worse than the bug being fixed: `python:3.12-slim` defaults to `python3`,
// which with no TTY reads EOF and exits 0 — so the pod goes Completed and
// then CrashLoopBackOff, behind a green pipeline, which is the same shape of
// failure as publishing nothing. So it is RESOLVED, not guessed: a project
// that declares a console script in `[project.scripts]` runs it, and a
// project that declares none gets an entrypoint that says so and exits
// non-zero, which reads as a configuration error in the pod's logs instead of
// a mystery restart loop. `deploy.runtime.command` overrides either.
//
// requirements.txt-only trees normally hit Build via their root Dockerfile
// (Dockerfile wins over --language). Publishing through this lane without a
// pyproject still installs deps from requirements.txt; entrypoint resolution
// still needs a console script or deploy.runtime.command.
runtime := dag.Container().
From("python:3.12-slim").
WithFile("/usr/local/bin/uv", uvBin).
WithMountedCache("/root/.cache/uv", dag.CacheVolume("uv")).
WithDirectory("/src", source).
WithWorkdir("/src")
// The same plan as the tests, without the dev tools: `.` for a declared
// package, the dependencies alone for anything else.
runtime = runtime.WithExec(withArgs([]string{"uv", "pip", "install", "--system"}, plan.Runtime...))
if plan.Mode != "package" {
runtime = runtime.WithEnvVariable("PYTHONPATH", "/src:/src/src")
}
image := buildEnv(runtime, buildArg).
WithWorkdir("/src").
WithExposedPort(8000).
WithEntrypoint([]string{"sh", "-c", pythonEntrypointScript})
ref, err := publishImage(ctx, image, pub)
if err != nil {
return nil, err
}
result.ImageRef = ref
result.Success = true
return result, nil
}
// phpLintCommand is the syntax gate for a PHP tree. Both of its awkward parts
// are load-bearing.
//
// `*/vendor/*`, NOT `./vendor/*`. Composer puts dependencies at the root, but an
// application that predates Composer vendors them wherever the tree grew —
// `lib/vendor/`, `application/vendor/`. A root-anchored pattern therefore lints
// third-party code, and third-party code is the one thing no runtime version can
// satisfy: measured across five real imports, the same tree carried a PDF
// library whose syntax was removed in PHP 8 AND a psr/log written in PHP 8 union
// types. Three of the five could not pass on ANY single version until the
// pattern stopped matching only the root; with it fixed all five pass on 7.4.
// buildPhp already assumes this shape further down — the composer step skips a
// tree "with libraries vendored under lib/".
//
// The `sh -c` wrapper is the other half. `php -l` exits 255 on a fatal, and
// xargs ABORTS the whole run the moment a command exits 255. So the gate
// reported exactly one bad file however many there were, and the files-checked
// count was however many happened to finish first — which reads as "one small
// problem" when it is really "we stopped looking". Translating the status lets
// xargs walk the whole tree and still exit non-zero (123), so a single run lists
// every file a person has to fix.
//
// A failure is written TWICE, and the second write is what makes the first
// useful. execDetail prefers stderr and keeps only the last 4000 bytes; folding
// php's own stderr into `out` left stderr empty, so the fallback took stdout —
// whose tail is `No syntax errors detected in …` repeated once per passing file.
// Measured on a 2001-file tree with one bad file: 98,085 bytes of output, the
// single `Parse error` line nowhere in the final 4000. The developer would be
// told the tree was rejected and then shown eighty lines of success. Echoing
// only the failures to stderr puts the filenames back in the message while
// stdout keeps the full transcript for LintOutput.
const phpLintCommand = `find . -type f -name '*.php' -not -path '*/vendor/*' -print0 | ` +
`xargs -0 -r -n1 -P4 sh -c 'out=$(php -l "$1" 2>&1); rc=$?; printf "%s\n" "$out"; ` +
`[ "$rc" -eq 0 ] || { printf "%s\n" "$out" >&2; exit 1; }' sh`
// buildPhp turns a PHP source tree into a runnable image with no Dockerfile.
//
// PHP is the case that most needs this. A large share of the internal
// applications customers bring have never been containerised, have no
// composer.json at the root (their libraries are vendored into the tree), and
// are served by dropping the directory into a webroot. Asking that team to
// author a Dockerfile is asking them to learn Docker before they can ship —
// which is the opposite of the promise.
//
// So the image is assembled here: php:<version>-apache with the extensions such
// an application almost always needs, the source copied into the document root,
// and nothing for the developer to write. Composer runs only when the project
// actually declares dependencies at the root; a vendored tree is left alone.
//
// THE VERSION IS AN ARGUMENT, AND THAT MATTERS MORE THAN IT LOOKS. It used to be
// pinned to 8.3. The applications this exists for are a decade old and carry
// vendored libraries written against PHP 5, and PHP has REMOVED syntax since:
// `$s{0}` string offsets are a fatal error from 8.0. So the newest runtime
// rejects, correctly, code the customer never wrote and did not choose to run on
// 8.3 — and the build fails for a version nobody picked. Measured on a real
// import: two files in a bundled PDF library. Defaulting to the current release
// is right for new code; being able to say 7.4 is what makes a migration
// possible at all.
//
// Lint is `php -l` across the tree — a syntax check is the honest gate for a
// codebase with no test suite, and it catches the parse error that would
// otherwise 500 in production. Tests run only if the project has phpunit.
func (m *StandardBuild) buildPhp(
ctx context.Context, source *dagger.Directory,
result *BuildResult, skipTests, skipLint bool, pub publishConfig, version string, buildArg []string,
) (*BuildResult, error) {
if version == "" {
version = "8.3"
}
phpImage := fmt.Sprintf("php:%s-apache", version)
base := dag.Container().
From(phpImage).
WithDirectory("/src", source).
WithWorkdir("/src")
base = lintTestBase(base, pub, buildArg)
if !skipLint {
// `find … | xargs php -l` returns non-zero when ANY file fails, so the
// step fails exactly when the code would not run.
lint := base.WithExec([]string{"sh", "-c", phpLintCommand})
out, err := lint.Stdout(ctx)
if err != nil {
// The output is the whole point of a lint gate: WHICH file, and why.
// Wrapping the bare error gave `exit code: 124` and nothing else.
return nil, fmt.Errorf(
"php -l rejected this tree on PHP %s — pass a runtime version the "+
"code was written for if these are vendored libraries:\n%s",
version, execDetail(err))
}
result.LintOutput = out
}
if !skipTests {
// Only when the project actually has a suite. A missing one is not a
// failure — most of these applications have never had tests, and
// refusing to build them would just block the migration we are enabling.
test := base.WithExec([]string{
"sh", "-c",
`if [ -f vendor/bin/phpunit ]; then vendor/bin/phpunit; ` +
`elif [ -f phpunit.xml ] || [ -f phpunit.xml.dist ]; then ` +
`echo "phpunit config present but not installed; skipping"; ` +
`else echo "no phpunit suite; skipping"; fi`,
})
out, err := test.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("phpunit failed: %s", execDetail(err))
}
result.TestOutput = out
}
if pub.testOnly {
return testsDone(result), nil
}
// The runtime image. Extensions first (they need the build toolchain), then
// the source into Apache's document root.
//
// `gd` and `zip` are here because COMPOSER REFUSES TO INSTALL WITHOUT THEM.
// Measured on a real customer application, 2026-08-27: it depends on
// mpdf/mpdf, which declares `ext-gd`, and composer answered
//
// mpdf/mpdf v8.1.5 requires ext-gd * -> it is missing from your system
//
// then installed nothing at all. The image still built and still published —
// the failure is a resolution error, not a build error — so what shipped was
// an app with no vendor/ directory that fatals on its first require_once.
//
// These are not a wish-list. `gd` (image handling, PDF/barcode generation)
// and `zip` (composer's own --prefer-dist path, and every export-to-xlsx
// library) are the two a decade-old PHP application declares most often, and
// a missing platform requirement fails the WHOLE resolution rather than
// skipping one package. `libpng`/`libjpeg`/`libzip` headers are needed to
// compile them, and are dropped again with the build toolchain.
//
// `pgsql`/`pdo_pgsql` are here for the other half of the database question.
// The lane compiled the MySQL drivers only, so a PHP application configured
// against PostgreSQL built green, published green, deployed green, and
// answered every request with
//
// Call to undefined function pg_connect()
//
// MEASURED on a customer application 2026-09-07: CodeIgniter's `postgre`
// driver, a PostgreSQL deployed beside it, and a runtime image that could
// not speak to it. Which database an application uses is the application's
// choice, not the lane's, and shipping only one of the two makes half of
// that choice unbuildable in a way nothing before runtime reports.
image := dag.Container().
From(phpImage).
WithExec([]string{
"sh", "-c",
`apt-get update && apt-get install -y --no-install-recommends ` +
`libpng-dev libjpeg62-turbo-dev libfreetype6-dev libzip-dev libpq-dev && ` +
`docker-php-ext-configure gd --with-freetype --with-jpeg && ` +
`docker-php-ext-install -j"$(nproc)" mysqli pdo_mysql pgsql pdo_pgsql gd zip && ` +
`a2enmod rewrite && rm -rf /var/lib/apt/lists/*`,
}).
WithDirectory("/var/www/html", source).
WithExec([]string{"chown", "-R", "www-data:www-data", "/var/www/html"}).
WithExposedPort(80)
// Composer runs wherever the project actually DECLARES dependencies, which is
// not always the root.
//
// The original rule was root-only, on the reasoning that a tree with libraries
// vendored under lib/ has nothing to install. Measured on a real customer
// application, 2026-08-27: it had BOTH. Vendored libraries beside a
// `lib/composer.json` whose `lib/vendor/` was EMPTY — and an empty directory
// is not something git can carry, so the import could not have preserved it
// even if the vendor drop had contained one. The image built, published,
// deployed, served HTTP 200, and every page was:
//
// Fatal error: require_once(): Failed opening required
// '/var/www/html/lib/vendor/autoload.php'
//
// So: every composer.json within two levels, skipping anything already inside
// a vendor/ directory. Depth-bounded because a deep scan of a large tree finds
// other projects' manifests and installs things nobody asked for. Still a
// no-op for a tree that declares nothing.
image = buildEnv(image, buildArg).WithExec([]string{
"sh", "-c",
`set -e; ` +
`manifests=$(find /var/www/html -maxdepth 3 -name composer.json -not -path '*/vendor/*' 2>/dev/null); ` +
`if [ -z "$manifests" ]; then echo "no composer.json; using the tree as-is"; exit 0; fi; ` +
// `unzip` is a convenience, not a requirement: the image compiles the
// `zip` extension above, and composer unpacks `--prefer-dist`
// archives with it when the binary is absent. `git` is NOT installed
// any more: composer only used it to read the root package version,
// and pulling it in dragged `libcurl3-gnutls` from the security
// pocket -- MEASURED 2026-09-13 on a customer's Jenkins, four builds
// in a row: the Debian CDN answered 404 for that one .deb (the
// ``%2b``-encoded ``+deb11u16`` path) and the whole build died in
// `sh: 1: git: not found` before composer ran. A build lane must not
// be one mirror hiccup away from failing on a tool it does not need.
`(apt-get update && apt-get install -y --no-install-recommends unzip) ` +
`|| echo "unzip not installable; composer falls back to the zip extension"; ` +
// git is needed for exactly one thing: a dependency with no `dist`
// archive (a `vcs`/`git` repository in composer.json -- a Gitea-hosted
// library, say) is fetched from `source`, which is `git clone`. Install
// it only when a manifest declares such a repository, so the common
// case never depends on it; and if that install fails, say so loudly
// rather than let composer fail three lines later for a reason nobody
// can see in the log.
`if grep -Eq '"type" *: *"(vcs|git)"' $manifests $(for m in $manifests; do echo "$(dirname "$m")/composer.lock"; done) 2>/dev/null; then ` +
`apt-get install -y --no-install-recommends git || { echo "a composer.json declares a vcs repository and git could not be installed" >&2; exit 1; }; ` +
`git config --global --add safe.directory '*'; fi; ` +
`curl -fsS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer; ` +
`command -v composer >/dev/null || { echo "composer could not be installed (is getcomposer.org reachable?)" >&2; exit 1; }; ` +
// A failed `composer install` used to be echoed and SKIPPED, so the image
// published with no `vendor/` and every page fataled on its first
// `require_once` -- the exact failure mode the comment above this exec
// describes. A resolution failure is a build failure.
`failed=0; for m in $manifests; do d=$(dirname "$m"); ` +
`echo "composer install in $d"; ` +
`(cd "$d" && composer install --no-dev --no-interaction --prefer-dist --no-progress) || ` +
`{ echo "composer install failed in $d" >&2; failed=1; }; done; ` +
`[ "$failed" = 0 ] || exit 1; ` +
`chown -R www-data:www-data /var/www/html`,
})
ref, err := publishImage(ctx, image, pub)
if err != nil {
return nil, err
}
result.ImageRef = ref
result.Success = true
return result, nil
}
func (m *StandardBuild) buildNode(
ctx context.Context, source *dagger.Directory,
result *BuildResult, skipTests, skipLint bool, pub publishConfig, buildArg []string,
) (*BuildResult, error) {
base := dag.Container().
From("node:22-slim").
// Persist the npm cache across runs so `npm ci` reuses tarballs.
WithMountedCache("/root/.npm", dag.CacheVolume("npm")).
WithDirectory("/src", source).
WithWorkdir("/src").
// `npm ci` refuses to run without a lockfile, and a lockfile is not
// something every repository carries -- MEASURED 2026-09-13 on the
// first `standard-build test` run for a service onboarded from a
// source archive: `npm error The npm ci command can only install with
// an existing package-lock.json`. The preset shell the Jenkins stage
// used before this lane got it right (`npm ci || npm install`); the
// lane did not. Reproducible installs when the repository pins them,
// a plain install when it does not -- the same choice a developer makes.
WithExec([]string{
"sh", "-c",
`if [ -f yarn.lock ]; then corepack enable && yarn install --immutable; elif [ -f package-lock.json ] || [ -f npm-shrinkwrap.json ]; then npm ci; else npm install; fi`,
})
if pub.workdir != "" {
// A workspace member (context repo_root): the install above ran at the
// workspace root, where the one lockfile is; lint, test, build and the
// image's start command run in the member.
base = base.WithWorkdir(laneDir(pub))
}
base = lintTestBase(base, pub, buildArg)
if !skipLint {
// `--if-present`: a project with no `lint` script is not a project that
// failed linting. Without it the whole build dies on a missing script,
// which is what the preset shell has always got right
// (`npm run build --if-present`) and this lane did not.
lint := base.WithExec([]string{"npm", "run", "lint", "--if-present"})
out, err := lint.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("npm lint failed: %w", err)
}
result.LintOutput = out
}
if !skipTests {
// Same reasoning as lint, and MEASURED: a customer front-end with
// scripts dev/build/lint/format and no `test` failed the entire image
// build on `npm error Missing script: "test"`.
test := base.WithExec([]string{"npm", "test", "--if-present"})
out, err := test.Stdout(ctx)
if err != nil {
return nil, fmt.Errorf("npm test failed: %w", err)
}
result.TestOutput = out
}
if pub.testOnly {
return testsDone(result), nil
}
// THE IMAGE. This lane used to take `_ publishConfig` and return here, so a
// node service compiled, tested, went green — and published NOTHING, for
// ever. MEASURED on a customer front-end 2026-08-27: `StandardBuild.build
// DONE`, an imageRef printed in the log by the caller, and the registry
// answering `NAME_UNKNOWN` for it. The deploy then sat in ImagePullBackOff
// behind a green pipeline, which is the same failure shape the deploy-side
// registry work exists to prevent.
//
// `npm run build --if-present` first: a framework that compiles (Next, Vite,
// CRA) needs it, and one that does not is unaffected. The runtime keeps
// node_modules from the install above rather than reinstalling, so what is
// published is what was tested.
// Build-time configuration BEFORE the build exec: a Vite/Next/CRA bundle
// reads these while compiling and inlines them. After the build they are
// unreachable — the value is already a string constant in the bundle.
built := buildEnv(base, buildArg).WithExec([]string{"npm", "run", "build", "--if-present"})
// PORT 3000 is the node convention and what every framework's `start`
// defaults to. It is declared so the chart's service can target it; nothing
// here can know a port the application never states.
image := built.
WithWorkdir(laneDir(pub)).
WithExposedPort(3000).
WithEntrypoint([]string{"npm", "run", "start"})
ref, err := publishImage(ctx, image, pub)
if err != nil {
return nil, err
}
result.ImageRef = ref
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))
}