chore: publish IntegraCI build modules 732ec6c83925
This commit is contained in:
1 parent
7a84930dea
commit
5f8a24d014
133 files changed
+18990
-2
No files matched your search
@@ -0,0 +1,24 @@
|
||||
# IntegraCI — Standard Build Dagger Module
|
||||
|
||||
Standard build pipeline: lint → test → build → container image.
|
||||
|
||||
## Functions
|
||||
|
||||
| Function | What it does |
|
||||
|----------|--------------|
|
||||
| `build` | lint → test → image (→ publish when `--image-ref` is given). **A root `Dockerfile` wins over `--language`**: the tree is built from it and the language lane is skipped (`--ignore-dockerfile=true` forces the lane). Languages outside go/python/node/php always need a Dockerfile. A `<Dockerfile>.dockerignore` beside the Dockerfile being built is applied by the module itself. For the `.integraci/Dockerfile` IntegraCI generates: after the context's root `.dockerignore` and without the sidecar's `!` re-includes, so no rule can bring back what it excludes, and a symlinked or non-regular ignore file refuses the build. For your own Dockerfile: BuildKit's rule -- the sidecar replaces the root file and keeps its `!` lines. |
|
||||
| `test` | lint + tests of the language lane only — no image, no publish. `image_ref` is always empty. Runs the lane even when a Dockerfile is present (a Dockerfile says how to package, not how to test); an unknown language is an error. Python accepts `pyproject.toml` (`uv pip install -e ".[dev]"`) or brownfield `requirements.txt` (+ ruff/pytest). Use this for the pipeline's "Lint and Test" stage instead of running `npm ci` / `pip` / `golangci-lint` / `docker run` natively on an agent that has no toolchains. |
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
dagger call build --source . --language go
|
||||
dagger call build --source . --language python
|
||||
dagger call build --source . --language node
|
||||
dagger call build --source . --language php # no Dockerfile: php:8.3-apache + your tree
|
||||
dagger call build --source . --language node --ignore-dockerfile=true # lane, even with a Dockerfile
|
||||
|
||||
dagger call test --source . --language node # lint + tests, no image
|
||||
dagger call test --source . --language php --runtime-version 7.4
|
||||
dagger call test --source . --language java --java-version 17 # JDK 11, 17 or 21 (default 21)
|
||||
```
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "standard-build",
|
||||
"engineVersion": "v0.21.7",
|
||||
"sdk": {
|
||||
"source": "go"
|
||||
},
|
||||
"source": ".",
|
||||
"include": [
|
||||
"./main.go",
|
||||
"./evidence/evidence.go",
|
||||
"./layout/layout.go",
|
||||
"./layout/ignore.go"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
// Package evidence builds the supply-chain evidence files a build leaves behind
|
||||
// (ADR-0068 Layer 2, #2143 phase 1): an in-toto Statement carrying an SLSA v1
|
||||
// provenance predicate for ONE image digest, and a SHA256SUMS manifest over the
|
||||
// evidence set.
|
||||
//
|
||||
// It is a separate package, standard library only, for the reason db-migration
|
||||
// keeps its logic in verdict/: the generated `dagger` package panics at init
|
||||
// without a Dagger session, so nothing in package main can run under a plain
|
||||
// `go test`. Everything here is pure and deterministic — the same inputs give
|
||||
// the same bytes — which is what a later golden test comparing the Dagger and
|
||||
// render-only paths (#2143 acceptance criterion 1) needs.
|
||||
//
|
||||
// What this package does NOT do: sign. A statement written here is evidence of
|
||||
// what the build claims; it becomes an attestation only when cosign signs it
|
||||
// (`cosign attest-provenance --predicate`), and the deploy-time gate that
|
||||
// verifies the signature is a later phase.
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// StatementType is the in-toto Statement v1 `_type`.
|
||||
StatementType = "https://in-toto.io/Statement/v1"
|
||||
// SLSAProvenanceV1 is the SLSA v1.0 provenance predicate type.
|
||||
SLSAProvenanceV1 = "https://slsa.dev/provenance/v1"
|
||||
// DefaultBuildType names the recipe this module runs. A verifier keys its
|
||||
// interpretation of externalParameters off this URI, so it is stable.
|
||||
DefaultBuildType = "https://integraci.co/buildtypes/dagger-standard-build/v1"
|
||||
)
|
||||
|
||||
// digestRef matches a reference pinned to a sha256 manifest digest, with or
|
||||
// without a tag before it: host/repo@sha256:<64>, host/repo:tag@sha256:<64>.
|
||||
var digestRef = regexp.MustCompile(`^([^@\s]+)@sha256:([0-9a-f]{64})$`)
|
||||
|
||||
// gitRevision is a full commit id: 40 hex (SHA-1 repositories) or 64 hex
|
||||
// (SHA-256 repositories). An abbreviated id is refused — it does not pin a
|
||||
// commit, and provenance that does not pin its source is not provenance.
|
||||
var gitRevision = regexp.MustCompile(`^([0-9a-f]{40}|[0-9a-f]{64})$`)
|
||||
|
||||
// Subject is the artifact a statement is about.
|
||||
type Subject struct {
|
||||
Name string `json:"name"`
|
||||
Digest map[string]string `json:"digest"`
|
||||
}
|
||||
|
||||
// ParseDigestRef splits a digest-pinned image reference into the subject name
|
||||
// (repository, no tag) and the hex sha256.
|
||||
//
|
||||
// A TAG-ONLY reference is an error, not a lookup. A tag moves; a statement
|
||||
// about a tag says nothing about the bytes that will be deployed, and resolving
|
||||
// the tag here would record whatever it points at by the time this step runs —
|
||||
// possibly another build's image.
|
||||
func ParseDigestRef(ref string) (Subject, error) {
|
||||
m := digestRef.FindStringSubmatch(strings.TrimSpace(ref))
|
||||
if m == nil {
|
||||
return Subject{}, fmt.Errorf(
|
||||
"image reference %q is not pinned to a sha256 digest (want <repo>[:tag]@sha256:<64 hex>)", ref)
|
||||
}
|
||||
name := m[1]
|
||||
// Strip a tag, but not a registry port: the tag is after the LAST slash.
|
||||
if slash := strings.LastIndexByte(name, '/'); strings.LastIndexByte(name, ':') > slash {
|
||||
name = name[:strings.LastIndexByte(name, ':')]
|
||||
}
|
||||
if name == "" {
|
||||
return Subject{}, fmt.Errorf("image reference %q has no repository", ref)
|
||||
}
|
||||
return Subject{Name: name, Digest: map[string]string{"sha256": m[2]}}, nil
|
||||
}
|
||||
|
||||
// ProvenanceInput is everything the provenance statement records. Every field
|
||||
// is supplied by the caller (the CI step) — nothing is read from the
|
||||
// environment here, so nothing in the output is a placeholder.
|
||||
type ProvenanceInput struct {
|
||||
ImageRef string // digest-pinned
|
||||
BuilderID string // absolute URI identifying the build platform/pipeline
|
||||
BuildType string // empty -> DefaultBuildType
|
||||
SourceURI string // e.g. git+https://git.example/org/repo@refs/heads/main
|
||||
SourceRevision string // full commit id
|
||||
InvocationID string // CI run id; optional
|
||||
StartedOn string // RFC 3339; optional, omitted when empty
|
||||
FinishedOn string // RFC 3339; optional, omitted when empty
|
||||
EngineVersion string // Dagger engine version the module is pinned to
|
||||
Language string // build lane; optional
|
||||
}
|
||||
|
||||
type resourceDescriptor struct {
|
||||
URI string `json:"uri"`
|
||||
Digest map[string]string `json:"digest"`
|
||||
}
|
||||
|
||||
type buildDefinition struct {
|
||||
BuildType string `json:"buildType"`
|
||||
ExternalParameters map[string]string `json:"externalParameters"`
|
||||
InternalParameters map[string]string `json:"internalParameters,omitempty"`
|
||||
ResolvedDependencies []resourceDescriptor `json:"resolvedDependencies"`
|
||||
}
|
||||
|
||||
type builder struct {
|
||||
ID string `json:"id"`
|
||||
Version map[string]string `json:"version,omitempty"`
|
||||
}
|
||||
|
||||
type buildMetadata struct {
|
||||
InvocationID string `json:"invocationId,omitempty"`
|
||||
StartedOn string `json:"startedOn,omitempty"`
|
||||
FinishedOn string `json:"finishedOn,omitempty"`
|
||||
}
|
||||
|
||||
type runDetails struct {
|
||||
Builder builder `json:"builder"`
|
||||
Metadata *buildMetadata `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type provenancePredicate struct {
|
||||
BuildDefinition buildDefinition `json:"buildDefinition"`
|
||||
RunDetails runDetails `json:"runDetails"`
|
||||
}
|
||||
|
||||
type statement struct {
|
||||
Type string `json:"_type"`
|
||||
Subject []Subject `json:"subject"`
|
||||
PredicateType string `json:"predicateType"`
|
||||
Predicate provenancePredicate `json:"predicate"`
|
||||
}
|
||||
|
||||
// ProvenanceStatement renders the in-toto Statement (SLSA v1 provenance) for
|
||||
// one image digest, indented and newline-terminated. It refuses — rather than
|
||||
// writes something a verifier would later have to distrust — when the subject
|
||||
// is not digest-pinned, the builder is not an absolute URI, the source does
|
||||
// not pin a full commit, or a timestamp is not RFC 3339.
|
||||
func ProvenanceStatement(in ProvenanceInput) ([]byte, error) {
|
||||
subject, err := ParseDigestRef(in.ImageRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := absoluteURI("builder id", in.BuilderID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buildType := in.BuildType
|
||||
if buildType == "" {
|
||||
buildType = DefaultBuildType
|
||||
}
|
||||
if err := absoluteURI("build type", buildType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(in.SourceURI) == "" || strings.ContainsAny(in.SourceURI, " \t\r\n") {
|
||||
return nil, fmt.Errorf("source uri %q must be a non-empty URI without whitespace", in.SourceURI)
|
||||
}
|
||||
rev := strings.ToLower(strings.TrimSpace(in.SourceRevision))
|
||||
if !gitRevision.MatchString(rev) {
|
||||
return nil, fmt.Errorf("source revision %q is not a full commit id (40 or 64 hex)", in.SourceRevision)
|
||||
}
|
||||
for name, ts := range map[string]string{"started-on": in.StartedOn, "finished-on": in.FinishedOn} {
|
||||
if ts == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := time.Parse(time.RFC3339, ts); err != nil {
|
||||
return nil, fmt.Errorf("%s %q is not RFC 3339: %w", name, ts, err)
|
||||
}
|
||||
}
|
||||
if strings.ContainsAny(in.InvocationID, "\r\n") {
|
||||
return nil, fmt.Errorf("invocation id must be a single line")
|
||||
}
|
||||
|
||||
external := map[string]string{"source": in.SourceURI, "revision": rev}
|
||||
var internal map[string]string
|
||||
if in.Language != "" {
|
||||
internal = map[string]string{"language": in.Language}
|
||||
}
|
||||
var version map[string]string
|
||||
if in.EngineVersion != "" {
|
||||
version = map[string]string{"dagger-engine": in.EngineVersion}
|
||||
}
|
||||
var meta *buildMetadata
|
||||
if in.InvocationID != "" || in.StartedOn != "" || in.FinishedOn != "" {
|
||||
meta = &buildMetadata{InvocationID: in.InvocationID, StartedOn: in.StartedOn, FinishedOn: in.FinishedOn}
|
||||
}
|
||||
|
||||
st := statement{
|
||||
Type: StatementType,
|
||||
Subject: []Subject{subject},
|
||||
PredicateType: SLSAProvenanceV1,
|
||||
Predicate: provenancePredicate{
|
||||
BuildDefinition: buildDefinition{
|
||||
BuildType: buildType,
|
||||
ExternalParameters: external,
|
||||
InternalParameters: internal,
|
||||
// `gitCommit` is the in-toto DigestSet key for a commit id. The
|
||||
// old cosign predicate labelled it `sha1` after stripping a
|
||||
// `sha256:` prefix — a digest under the wrong algorithm name.
|
||||
ResolvedDependencies: []resourceDescriptor{{
|
||||
URI: in.SourceURI,
|
||||
Digest: map[string]string{"gitCommit": rev},
|
||||
}},
|
||||
},
|
||||
RunDetails: runDetails{
|
||||
Builder: builder{ID: in.BuilderID, Version: version},
|
||||
Metadata: meta,
|
||||
},
|
||||
},
|
||||
}
|
||||
out, err := json.MarshalIndent(st, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(out, '\n'), nil
|
||||
}
|
||||
|
||||
func absoluteURI(what, raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme == "" || (u.Host == "" && u.Opaque == "") || strings.ContainsAny(raw, " \t\r\n") {
|
||||
return fmt.Errorf("%s %q must be an absolute URI", what, raw)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fileName is what may appear in a SHA256SUMS line: a plain name, so a
|
||||
// manifest can never point a verifier outside the evidence directory.
|
||||
var fileName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
|
||||
|
||||
// SHA256Sums renders a `sha256sum -c`-compatible manifest over the given
|
||||
// files, sorted by name so the output is deterministic.
|
||||
func SHA256Sums(files map[string][]byte) ([]byte, error) {
|
||||
names := make([]string, 0, len(files))
|
||||
for name := range files {
|
||||
if !fileName.MatchString(name) {
|
||||
return nil, fmt.Errorf("evidence file name %q is not a plain file name", name)
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
var b strings.Builder
|
||||
for _, name := range names {
|
||||
sum := sha256.Sum256(files[name])
|
||||
fmt.Fprintf(&b, "%s %s\n", hex.EncodeToString(sum[:]), name)
|
||||
}
|
||||
return []byte(b.String()), nil
|
||||
}
|
||||
|
||||
// SBOMFileName maps an SBOM format to the file name the evidence set uses.
|
||||
func SBOMFileName(format string) (name string, syftOutput string, err error) {
|
||||
switch format {
|
||||
case "", "cyclonedx":
|
||||
return "sbom.cdx.json", "cyclonedx-json", nil
|
||||
case "spdx":
|
||||
return "sbom.spdx.json", "spdx-json", nil
|
||||
default:
|
||||
return "", "", fmt.Errorf("unsupported sbom format %q (want cyclonedx|spdx)", format)
|
||||
}
|
||||
}
|
||||
|
||||
// DigestFromPushOutput finds the digest reference a push printed. crane push
|
||||
// prints `<repo>@sha256:<64>` on success; Dagger's Publish returns
|
||||
// `<repo>:<tag>@sha256:<64>`. Empty when no such reference is present.
|
||||
func DigestFromPushOutput(out string) string {
|
||||
for _, field := range strings.Fields(out) {
|
||||
field = strings.Trim(field, `'"`)
|
||||
if digestRef.MatchString(field) {
|
||||
return field
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// DigestOf returns `sha256:<hex>` for a digest-pinned reference, else "".
|
||||
func DigestOf(ref string) string {
|
||||
if m := digestRef.FindStringSubmatch(ref); m != nil {
|
||||
return "sha256:" + m[2]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package evidence
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const (
|
||||
hexDigest = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
commit = "89abcdef0123456789abcdef0123456789abcdef"
|
||||
)
|
||||
|
||||
func validInput() ProvenanceInput {
|
||||
return ProvenanceInput{
|
||||
ImageRef: "registry.example:5000/team/orders:abc123@sha256:" + hexDigest,
|
||||
BuilderID: "https://jenkins.example/job/orders/",
|
||||
SourceURI: "git+https://git.example/team/orders@refs/heads/main",
|
||||
SourceRevision: commit,
|
||||
InvocationID: "42",
|
||||
StartedOn: "2026-10-11T08:00:00Z",
|
||||
FinishedOn: "2026-10-11T08:05:00Z",
|
||||
EngineVersion: "v0.21.7",
|
||||
Language: "go",
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDigestRefKeepsPortStripsTag(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"registry.example:5000/team/orders:abc@sha256:" + hexDigest: "registry.example:5000/team/orders",
|
||||
"registry.example:5000/team/orders@sha256:" + hexDigest: "registry.example:5000/team/orders",
|
||||
"ghcr.io/acme/app@sha256:" + hexDigest: "ghcr.io/acme/app",
|
||||
}
|
||||
for ref, want := range cases {
|
||||
s, err := ParseDigestRef(ref)
|
||||
if err != nil {
|
||||
t.Fatalf("%q: %v", ref, err)
|
||||
}
|
||||
if s.Name != want || s.Digest["sha256"] != hexDigest {
|
||||
t.Fatalf("%q -> %+v, want name %q", ref, s, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A tag is never accepted as a subject: it moves, and a statement about a tag
|
||||
// says nothing about the bytes that get deployed.
|
||||
func TestParseDigestRefRefusesUnpinned(t *testing.T) {
|
||||
for _, ref := range []string{
|
||||
"",
|
||||
"ghcr.io/acme/app:1.0.0",
|
||||
"ghcr.io/acme/app@sha256:" + hexDigest[:63], // short
|
||||
"ghcr.io/acme/app@sha256:" + strings.ToUpper(hexDigest), // not lowercase hex
|
||||
"ghcr.io/acme/app@sha512:" + hexDigest,
|
||||
"@sha256:" + hexDigest,
|
||||
"ghcr.io/acme/app@sha256:" + hexDigest + "\nextra",
|
||||
} {
|
||||
if _, err := ParseDigestRef(ref); err == nil {
|
||||
t.Fatalf("%q must be refused", ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenanceStatementShape(t *testing.T) {
|
||||
out, err := ProvenanceStatement(validInput())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var st map[string]any
|
||||
if err := json.Unmarshal(out, &st); err != nil {
|
||||
t.Fatalf("not JSON: %v", err)
|
||||
}
|
||||
if st["_type"] != StatementType || st["predicateType"] != SLSAProvenanceV1 {
|
||||
t.Fatalf("wrong types: %v / %v", st["_type"], st["predicateType"])
|
||||
}
|
||||
subj := st["subject"].([]any)[0].(map[string]any)
|
||||
if subj["name"] != "registry.example:5000/team/orders" {
|
||||
t.Fatalf("subject name %v", subj["name"])
|
||||
}
|
||||
if subj["digest"].(map[string]any)["sha256"] != hexDigest {
|
||||
t.Fatalf("subject digest %v", subj["digest"])
|
||||
}
|
||||
bd := st["predicate"].(map[string]any)["buildDefinition"].(map[string]any)
|
||||
if bd["buildType"] != DefaultBuildType {
|
||||
t.Fatalf("buildType %v", bd["buildType"])
|
||||
}
|
||||
dep := bd["resolvedDependencies"].([]any)[0].(map[string]any)
|
||||
if dep["digest"].(map[string]any)["gitCommit"] != commit {
|
||||
t.Fatalf("source dependency digest %v", dep["digest"])
|
||||
}
|
||||
// The old cosign predicate shipped literal shell placeholders that nothing
|
||||
// ever expanded. None may appear here.
|
||||
if strings.Contains(string(out), "${") {
|
||||
t.Fatalf("statement carries an unexpanded placeholder:\n%s", out)
|
||||
}
|
||||
if !strings.HasSuffix(string(out), "}\n") {
|
||||
t.Fatal("statement must end with a newline")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenanceStatementIsDeterministic(t *testing.T) {
|
||||
a, err := ProvenanceStatement(validInput())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := ProvenanceStatement(validInput())
|
||||
if string(a) != string(b) {
|
||||
t.Fatal("same input must give the same bytes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenanceStatementOmitsUnsetMetadata(t *testing.T) {
|
||||
in := validInput()
|
||||
in.InvocationID, in.StartedOn, in.FinishedOn = "", "", ""
|
||||
out, err := ProvenanceStatement(in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(out), "metadata") {
|
||||
t.Fatalf("unset metadata must be omitted, not invented:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProvenanceStatementRefusesBadInput(t *testing.T) {
|
||||
mutate := map[string]func(*ProvenanceInput){
|
||||
"tag-only image": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app:1.0.0" },
|
||||
"relative builder": func(in *ProvenanceInput) { in.BuilderID = "jenkins/job/orders" },
|
||||
"empty builder": func(in *ProvenanceInput) { in.BuilderID = "" },
|
||||
"builder whitespace": func(in *ProvenanceInput) { in.BuilderID = "https://ci.example/a b" },
|
||||
"relative build type": func(in *ProvenanceInput) { in.BuildType = "standard-build" },
|
||||
"empty source": func(in *ProvenanceInput) { in.SourceURI = "" },
|
||||
"source newline": func(in *ProvenanceInput) { in.SourceURI = "git+https://x\n\"evil\"" },
|
||||
"short revision": func(in *ProvenanceInput) { in.SourceRevision = commit[:12] },
|
||||
"branch as revision": func(in *ProvenanceInput) { in.SourceRevision = "main" },
|
||||
"bad started-on": func(in *ProvenanceInput) { in.StartedOn = "yesterday" },
|
||||
"placeholder ts": func(in *ProvenanceInput) { in.FinishedOn = "${BUILD_FINISHED_ON}" },
|
||||
"multiline run id": func(in *ProvenanceInput) { in.InvocationID = "1\n2" },
|
||||
}
|
||||
for name, m := range mutate {
|
||||
in := validInput()
|
||||
m(&in)
|
||||
if _, err := ProvenanceStatement(in); err == nil {
|
||||
t.Fatalf("%s: must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Legitimate values a strict-looking validator must not reject.
|
||||
func TestProvenanceStatementAcceptsLegitimateValues(t *testing.T) {
|
||||
ok := map[string]func(*ProvenanceInput){
|
||||
"sha256 repository commit": func(in *ProvenanceInput) { in.SourceRevision = hexDigest },
|
||||
"uppercase commit": func(in *ProvenanceInput) { in.SourceRevision = strings.ToUpper(commit) },
|
||||
"urn builder": func(in *ProvenanceInput) { in.BuilderID = "urn:integraci:builder:jenkins" },
|
||||
"ssh source": func(in *ProvenanceInput) { in.SourceURI = "git+ssh://git@git.example:2222/team/orders.git" },
|
||||
"offset timestamp": func(in *ProvenanceInput) { in.StartedOn = "2026-10-11T15:00:00+07:00" },
|
||||
"no tag before digest": func(in *ProvenanceInput) { in.ImageRef = "ghcr.io/acme/app@sha256:" + hexDigest },
|
||||
"no language": func(in *ProvenanceInput) { in.Language = "" },
|
||||
}
|
||||
for name, m := range ok {
|
||||
in := validInput()
|
||||
m(&in)
|
||||
if _, err := ProvenanceStatement(in); err != nil {
|
||||
t.Fatalf("%s: legitimate value refused: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSHA256SumsFormat(t *testing.T) {
|
||||
out, err := SHA256Sums(map[string][]byte{"b.json": []byte("b"), "a.json": []byte("")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 a.json\n" +
|
||||
"3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d b.json\n"
|
||||
if string(out) != want {
|
||||
t.Fatalf("got\n%s\nwant\n%s", out, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSHA256SumsRefusesPathNames(t *testing.T) {
|
||||
for _, name := range []string{"../x", "dir/x", "", ".hidden", "a b", "x\ny"} {
|
||||
if _, err := SHA256Sums(map[string][]byte{name: nil}); err == nil {
|
||||
t.Fatalf("%q must be refused", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSBOMFileName(t *testing.T) {
|
||||
if n, o, err := SBOMFileName(""); err != nil || n != "sbom.cdx.json" || o != "cyclonedx-json" {
|
||||
t.Fatalf("default: %q %q %v", n, o, err)
|
||||
}
|
||||
if n, o, err := SBOMFileName("spdx"); err != nil || n != "sbom.spdx.json" || o != "spdx-json" {
|
||||
t.Fatalf("spdx: %q %q %v", n, o, err)
|
||||
}
|
||||
if _, _, err := SBOMFileName("cyclonedx-json; rm -rf /"); err == nil {
|
||||
t.Fatal("unknown format must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDigestFromPushOutput(t *testing.T) {
|
||||
ref := "registry.example:5000/team/orders@sha256:" + hexDigest
|
||||
out := "logged in\n2026/10/11 pushed blob: sha256:aaaa\n" + ref + "\nPUSHED 'registry.example:5000/team/orders:abc'\ncrane exit=0\n"
|
||||
if got := DigestFromPushOutput(out); got != ref {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
if got := DigestFromPushOutput("pushed blob: sha256:" + hexDigest + "\n"); got != "" {
|
||||
t.Fatalf("a bare blob digest is not an image reference, got %q", got)
|
||||
}
|
||||
if DigestOf(ref) != "sha256:"+hexDigest || DigestOf("ghcr.io/a:1") != "" {
|
||||
t.Fatal("DigestOf")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package layout
|
||||
|
||||
// Per-Dockerfile ignore files (`<Dockerfile>.dockerignore`).
|
||||
//
|
||||
// IntegraCI commits a generated Dockerfile at `.integraci/Dockerfile` with an
|
||||
// `.integraci/Dockerfile.dockerignore` beside it. That sidecar is the only thing
|
||||
// between the generated `COPY . .` and a `.env` or a private key committed to
|
||||
// the repository: whatever the build context holds is readable by every layer,
|
||||
// and a secret copied in is a secret published with the image.
|
||||
//
|
||||
// Two modes (ContextFilters), chosen by WHOSE Dockerfile is built:
|
||||
//
|
||||
// The generated `.integraci/Dockerfile` (IsGeneratedDockerfile) -- STRICT. The
|
||||
// module applies the sidecar ITSELF, before DockerBuild, instead of trusting
|
||||
// the engine's Dockerfile frontend to find it, and applies the context's root
|
||||
// `.dockerignore` as well (BuildKit ignores the root file whenever a
|
||||
// per-Dockerfile one exists, so the sidecar IntegraCI wrote would otherwise
|
||||
// silently re-include everything the customer had excluded). Two filters, not
|
||||
// one merged list:
|
||||
//
|
||||
// 1. the root `.dockerignore`, re-includes (`!`) kept, so an allowlist such
|
||||
// as `*` then `!src` keeps working;
|
||||
// 2. the sidecar's exclusions, its `!` lines DROPPED, applied to what is left.
|
||||
//
|
||||
// A root `!.env` therefore cannot bring back a `.env` the sidecar excludes,
|
||||
// whatever order the engine's matcher gives patterns inside one list.
|
||||
//
|
||||
// A customer's own Dockerfile -- BuildKit semantics, unchanged: its
|
||||
// `<Dockerfile>.dockerignore` REPLACES the root file, and its `!` lines are
|
||||
// kept. A customer sidecar written as an allowlist (`*`, `!src`,
|
||||
// `!package.json`) is the ordinary BuildKit idiom; dropping its re-includes
|
||||
// would empty the build context.
|
||||
//
|
||||
// Pure functions, no Dagger import, for the same reason as the rest of this
|
||||
// package: the rules are unit tested without an engine.
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SidecarSuffix is appended to a Dockerfile's path to name its ignore file.
|
||||
const SidecarSuffix = ".dockerignore"
|
||||
|
||||
// RootIgnoreFile is the build context's own ignore file.
|
||||
const RootIgnoreFile = ".dockerignore"
|
||||
|
||||
// GeneratedDockerfile is where IntegraCI commits a Dockerfile it generated,
|
||||
// relative to the service's directory (containerization.GENERATED_DOCKERFILE_PATH).
|
||||
const GeneratedDockerfile = ".integraci/Dockerfile"
|
||||
|
||||
// IsGeneratedDockerfile reports whether dockerfile (a path inside the build
|
||||
// context) is the one IntegraCI generates: `.integraci/Dockerfile` at the
|
||||
// context root, or under the service's directory when the whole checkout is
|
||||
// the context.
|
||||
func IsGeneratedDockerfile(dockerfile string) bool {
|
||||
return dockerfile == GeneratedDockerfile || strings.HasSuffix(dockerfile, "/"+GeneratedDockerfile)
|
||||
}
|
||||
|
||||
// SidecarPath is the ignore file that belongs to dockerfile (a path inside the
|
||||
// build context). An empty dockerfile is the default `Dockerfile`.
|
||||
func SidecarPath(dockerfile string) string {
|
||||
if dockerfile == "" {
|
||||
dockerfile = DefaultDockerfile
|
||||
}
|
||||
return dockerfile + SidecarSuffix
|
||||
}
|
||||
|
||||
// IgnorePatterns reads a .dockerignore body into exclude patterns: one per
|
||||
// non-empty, non-comment line, cleaned the way Docker's own reader cleans them
|
||||
// (surrounding whitespace trimmed, a leading `/` dropped, path.Clean applied),
|
||||
// so `/secrets` matches here too. `!` re-include lines are kept only when
|
||||
// keepNegations is set; see ContextFilters for why the sidecar drops them.
|
||||
func IgnorePatterns(body string, keepNegations bool) []string {
|
||||
var out []string
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
negate := strings.HasPrefix(line, "!")
|
||||
if negate && !keepNegations {
|
||||
continue
|
||||
}
|
||||
pattern := strings.TrimSpace(strings.TrimPrefix(line, "!"))
|
||||
pattern = strings.TrimPrefix(pattern, "/")
|
||||
if pattern == "" {
|
||||
continue
|
||||
}
|
||||
pattern = path.Clean(pattern)
|
||||
if pattern == "." {
|
||||
continue
|
||||
}
|
||||
if negate {
|
||||
pattern = "!" + pattern
|
||||
}
|
||||
out = append(out, pattern)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ContextFilters is the ordered list of exclude-pattern lists the module
|
||||
// applies to the build context, one Directory.Filter each.
|
||||
//
|
||||
// generated: the root `.dockerignore` (with its re-includes) and then the
|
||||
// sidecar's exclusions (without any). Otherwise BuildKit's rule: the sidecar
|
||||
// alone, re-includes kept, the root file not applied. An empty list is
|
||||
// omitted. hasRoot is false when the context has no root `.dockerignore`.
|
||||
func ContextFilters(rootBody string, hasRoot bool, sidecarBody string, generated bool) [][]string {
|
||||
var out [][]string
|
||||
if !generated {
|
||||
if sidecar := IgnorePatterns(sidecarBody, true); len(sidecar) > 0 {
|
||||
out = append(out, sidecar)
|
||||
}
|
||||
return out
|
||||
}
|
||||
if hasRoot {
|
||||
if root := IgnorePatterns(rootBody, true); len(root) > 0 {
|
||||
out = append(out, root)
|
||||
}
|
||||
}
|
||||
if sidecar := IgnorePatterns(sidecarBody, false); len(sidecar) > 0 {
|
||||
out = append(out, sidecar)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// GeneratedSidecarPresent refuses a GENERATED Dockerfile built without its
|
||||
// sidecar. The platform always commits the pair, and the sidecar is the only
|
||||
// thing between the generated `COPY . .` and `.env`, keys and `.git`: building
|
||||
// without it would put them in the image behind a green build. Whatever the
|
||||
// cause (deleted in the repository, never committed), the build stops and
|
||||
// says why; onboarding again restores the pair. A customer's own Dockerfile
|
||||
// is not asked this question.
|
||||
func GeneratedSidecarPresent(sidecar string, kind Kind) error {
|
||||
if kind == Missing {
|
||||
return refuse("the generated Dockerfile's ignore file %q is missing; onboard the service again to restore it", sidecar)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// IgnoreFileUsable says whether an ignore file of this kind is read.
|
||||
//
|
||||
// Missing is "no ignore file" (false, nil). A regular file is read. Anything
|
||||
// else is refused rather than skipped: a sidecar replaced by a symlink (to
|
||||
// `/dev/null`, or to a file outside the checkout) or by a directory would
|
||||
// otherwise switch the exclusions off and put `.env` back in the image behind
|
||||
// a green build. The same holds for the root file once a sidecar is in play,
|
||||
// because the root rules are applied with it.
|
||||
func IgnoreFileUsable(name string, kind Kind) (bool, error) {
|
||||
switch kind {
|
||||
case Missing:
|
||||
return false, nil
|
||||
case Regular:
|
||||
return true, nil
|
||||
default:
|
||||
return false, refuse("the ignore file %q is a %s, not a regular file", name, kind)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIgnorePatternsCleansLikeDocker(t *testing.T) {
|
||||
body := "# comment\n\n .env \n/secrets\nsrc/../keys\n./build/\n/\n.\n!keep.txt\n"
|
||||
got := IgnorePatterns(body, false)
|
||||
want := []string{".env", "secrets", "keys", "build"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("IgnorePatterns(no negations) = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnorePatternsKeepsNegationsOnlyWhenAsked(t *testing.T) {
|
||||
body := "*\n!src\n! /docs\n!\n"
|
||||
if got, want := IgnorePatterns(body, true), []string{"*", "!src", "!docs"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("keepNegations=true: got %q, want %q", got, want)
|
||||
}
|
||||
if got, want := IgnorePatterns(body, false), []string{"*"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("keepNegations=false: got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedContextFiltersOrderRootThenSidecar(t *testing.T) {
|
||||
got := ContextFilters("*\n!src\n", true, ".env\n!.env\n*.pem\n", true)
|
||||
want := [][]string{{"*", "!src"}, {".env", "*.pem"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("ContextFilters = %q, want %q", got, want)
|
||||
}
|
||||
// The sidecar's list never carries a re-include: that is what makes it
|
||||
// impossible for any rule to bring back what it excludes.
|
||||
last := got[len(got)-1]
|
||||
for _, p := range last {
|
||||
if strings.HasPrefix(p, "!") {
|
||||
t.Fatalf("sidecar filter carries a re-include %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextFiltersWithoutRootOrEmptyLists(t *testing.T) {
|
||||
if got := ContextFilters("ignored\n", false, ".env\n", true); !reflect.DeepEqual(got, [][]string{{".env"}}) {
|
||||
t.Fatalf("no root file: got %q", got)
|
||||
}
|
||||
if got := ContextFilters("# only comments\n", true, "\n", true); len(got) != 0 {
|
||||
t.Fatalf("empty bodies must produce no filter, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// survives models the module's sequence of Directory.Filter calls: each list
|
||||
// is applied in turn to what the previous one left, and within one list the
|
||||
// LAST matching pattern decides (Docker's rule, `!` = keep). A path matches a
|
||||
// pattern when the pattern matches it or one of its parent directories. It is
|
||||
// a model of the engine, not the engine; what it pins is the ORDERING
|
||||
// property ContextFilters is responsible for.
|
||||
func survives(p string, filters [][]string) bool {
|
||||
for _, list := range filters {
|
||||
excluded := false
|
||||
for _, pat := range list {
|
||||
neg := strings.HasPrefix(pat, "!")
|
||||
if matchesPathOrParent(strings.TrimPrefix(pat, "!"), p) {
|
||||
excluded = !neg
|
||||
}
|
||||
}
|
||||
if excluded {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func matchesPathOrParent(pattern, p string) bool {
|
||||
for cur := p; cur != "." && cur != "/" && cur != ""; cur = path.Dir(cur) {
|
||||
if ok, _ := path.Match(pattern, cur); ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestGeneratedRootNegationCannotReincludeWhatTheSidecarExcludes(t *testing.T) {
|
||||
root := "*.log\n!.env\n"
|
||||
sidecar := ".env\n*.pem\n"
|
||||
filters := ContextFilters(root, true, sidecar, true)
|
||||
if survives(".env", filters) {
|
||||
t.Fatal("a root `!.env` re-included the .env the sidecar excludes")
|
||||
}
|
||||
if survives("certs/server.pem", filters) {
|
||||
t.Fatal("a sidecar-excluded key survived")
|
||||
}
|
||||
if survives("app.log", filters) {
|
||||
t.Fatal("the root .dockerignore was not applied with the sidecar")
|
||||
}
|
||||
if !survives("src/main.go", filters) {
|
||||
t.Fatal("an ordinary source file was excluded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootAllowlistKeepsWorkingWithASidecar(t *testing.T) {
|
||||
// `*` then `!src`: only src/ reaches the build. Dropping the root's
|
||||
// negations (the sidecar's rule) would exclude everything.
|
||||
filters := ContextFilters("*\n!src\n", true, ".env\n", true)
|
||||
if !survives("src/app.py", filters) {
|
||||
t.Fatal("the root allowlist's re-include was lost")
|
||||
}
|
||||
if survives("README.md", filters) {
|
||||
t.Fatal("the root allowlist excluded nothing")
|
||||
}
|
||||
if survives(".env", filters) {
|
||||
t.Fatal("the sidecar's .env exclusion was not applied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSidecarPath(t *testing.T) {
|
||||
if got := SidecarPath(""); got != "Dockerfile.dockerignore" {
|
||||
t.Fatalf("default: %q", got)
|
||||
}
|
||||
if got := SidecarPath(".integraci/Dockerfile"); got != ".integraci/Dockerfile.dockerignore" {
|
||||
t.Fatalf("generated: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoreFileUsableRefusesWhatIsNotARegularFile(t *testing.T) {
|
||||
if ok, err := IgnoreFileUsable("x", Missing); ok || err != nil {
|
||||
t.Fatalf("missing: (%v, %v)", ok, err)
|
||||
}
|
||||
if ok, err := IgnoreFileUsable("x", Regular); !ok || err != nil {
|
||||
t.Fatalf("regular: (%v, %v)", ok, err)
|
||||
}
|
||||
for _, k := range []Kind{Symlink, Directory, Other} {
|
||||
ok, err := IgnoreFileUsable(".integraci/Dockerfile.dockerignore", k)
|
||||
if ok || !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("%s: (%v, %v), want a refusal", k, ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneratedSidecarPresentRefusesOnlyAMissingSidecar(t *testing.T) {
|
||||
err := GeneratedSidecarPresent(".integraci/Dockerfile.dockerignore", Missing)
|
||||
if !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("missing: %v, want a refusal", err)
|
||||
}
|
||||
// Legitimate: a regular sidecar builds; the other kinds are refused by
|
||||
// IgnoreFileUsable, not here.
|
||||
for _, k := range []Kind{Regular, Symlink, Directory, Other} {
|
||||
if err := GeneratedSidecarPresent(".integraci/Dockerfile.dockerignore", k); err != nil {
|
||||
t.Fatalf("%s: %v, want nil", k, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsGeneratedDockerfile(t *testing.T) {
|
||||
for _, p := range []string{".integraci/Dockerfile", "apps/web/.integraci/Dockerfile"} {
|
||||
if !IsGeneratedDockerfile(p) {
|
||||
t.Errorf("%q is the generated Dockerfile", p)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{"Dockerfile", "docker/Dockerfile", ".integraci/Dockerfile.prod", "x.integraci/Dockerfile", ""} {
|
||||
if IsGeneratedDockerfile(p) {
|
||||
t.Errorf("%q is a customer's Dockerfile", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A customer's `Dockerfile.dockerignore` written as BuildKit's allowlist idiom
|
||||
// must keep its re-includes: dropping them (the generated-Dockerfile rule)
|
||||
// empties the build context. Review finding F1 on #2168.
|
||||
func TestCustomerSidecarAllowlistKeepsItsReincludes(t *testing.T) {
|
||||
filters := ContextFilters("", false, "*\n!src\n!package.json\n", false)
|
||||
if want := [][]string{{"*", "!src", "!package.json"}}; !reflect.DeepEqual(filters, want) {
|
||||
t.Fatalf("ContextFilters(customer) = %q, want %q", filters, want)
|
||||
}
|
||||
if !survives("src/app.py", filters) || !survives("package.json", filters) {
|
||||
t.Fatal("a customer allowlist sidecar emptied the context")
|
||||
}
|
||||
if survives("README.md", filters) {
|
||||
t.Fatal("the customer allowlist excluded nothing")
|
||||
}
|
||||
}
|
||||
|
||||
// BuildKit ignores the root .dockerignore when a per-Dockerfile one exists;
|
||||
// for a customer's Dockerfile the module does the same.
|
||||
func TestCustomerSidecarReplacesTheRootIgnoreFile(t *testing.T) {
|
||||
filters := ContextFilters("*.log\nsecrets\n", true, "node_modules\n", false)
|
||||
if want := [][]string{{"node_modules"}}; !reflect.DeepEqual(filters, want) {
|
||||
t.Fatalf("ContextFilters(customer, root present) = %q, want %q", filters, want)
|
||||
}
|
||||
if !survives("app.log", filters) {
|
||||
t.Fatal("the root file was applied beside a customer sidecar")
|
||||
}
|
||||
}
|
||||
|
||||
// The other direction: the generated pair still cannot be re-opened, even by
|
||||
// an allowlist-shaped sidecar or a root `!.env`.
|
||||
func TestGeneratedSidecarStillCannotReincludeEnv(t *testing.T) {
|
||||
filters := ContextFilters("!.env\n", true, "*\n!src\n.env\n!.env\n", true)
|
||||
if survives(".env", filters) {
|
||||
t.Fatal("the generated sidecar's .env exclusion was undone")
|
||||
}
|
||||
for _, list := range filters[1:] {
|
||||
for _, p := range list {
|
||||
if strings.HasPrefix(p, "!") {
|
||||
t.Fatalf("generated sidecar filter carries a re-include %q", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Package layout decides WHERE in a checkout standard-build builds (ADR-0074
|
||||
// §4, §8.1, rollout PR 3): the service's directory (--subdir), its Dockerfile
|
||||
// (--dockerfile, relative to that directory) and the build context
|
||||
// (--build-context: "source_path" = that directory, "repo_root" = the whole
|
||||
// checkout).
|
||||
//
|
||||
// It is a separate package with no Dagger import so that its rules can be unit
|
||||
// tested without an engine, the same reason `evidence` is one.
|
||||
//
|
||||
// Two checks, both before any build step runs:
|
||||
//
|
||||
// - Resolve is lexical. It mirrors the platform's path validator
|
||||
// (apps/api/app/catalog/services/source_paths.py): POSIX separators, no
|
||||
// leading '/', no '.'/'..' or empty segment, no segment starting with '-'
|
||||
// or ending with '.', no '.git' segment in any letter case, segment charset
|
||||
// [A-Za-z0-9._@-], depth <= 16, length <= 512. The platform validated these
|
||||
// values when it recorded them; the module checks again because a pipeline
|
||||
// file in a repository can be edited by anyone who can push.
|
||||
// - Confine walks the tree as it is AT BUILD TIME. The platform's own check
|
||||
// ran at onboarding, at another commit; a later push can turn `apps/web` or
|
||||
// its Dockerfile into a symlink to `../..` or to the agent's home, and then
|
||||
// `COPY . .` would put the agent's files into a pushed image. Every path
|
||||
// component must be a real directory and the Dockerfile a regular file:
|
||||
// a symlink anywhere on the way is refused, never followed.
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The two build contexts (ADR-0074 D8). An enumeration, never a path, so a
|
||||
// parent directory cannot be expressed at all.
|
||||
const (
|
||||
ContextSourcePath = "source_path"
|
||||
ContextRepoRoot = "repo_root"
|
||||
)
|
||||
|
||||
// DefaultDockerfile is what `docker build .` and Directory.DockerBuild read.
|
||||
const DefaultDockerfile = "Dockerfile"
|
||||
|
||||
// Limits mirrored from source_paths.py.
|
||||
const (
|
||||
MaxPathLength = 512
|
||||
MaxPathDepth = 16
|
||||
)
|
||||
|
||||
var segmentRE = regexp.MustCompile(`^[A-Za-z0-9._@-]+$`)
|
||||
|
||||
// Layout is a resolved, lexically valid build layout.
|
||||
type Layout struct {
|
||||
// Subdir is the service's directory relative to the checkout; "" = root.
|
||||
Subdir string
|
||||
// Dockerfile is relative to Subdir; never empty after Resolve.
|
||||
Dockerfile string
|
||||
// Context is ContextSourcePath or ContextRepoRoot.
|
||||
Context string
|
||||
}
|
||||
|
||||
// PathProblem is why value is not an acceptable repository path, or "".
|
||||
// allowRoot accepts "" (only a directory may be the root).
|
||||
func PathProblem(value string, allowRoot bool) string {
|
||||
if value == "" {
|
||||
if allowRoot {
|
||||
return ""
|
||||
}
|
||||
return "must not be empty"
|
||||
}
|
||||
if len(value) > MaxPathLength {
|
||||
return fmt.Sprintf("must be at most %d characters", MaxPathLength)
|
||||
}
|
||||
if strings.HasPrefix(value, "/") {
|
||||
return "must be relative to the repository (no leading '/')"
|
||||
}
|
||||
segments := strings.Split(value, "/")
|
||||
if len(segments) > MaxPathDepth {
|
||||
return fmt.Sprintf("must be at most %d directories deep", MaxPathDepth)
|
||||
}
|
||||
for _, seg := range segments {
|
||||
switch {
|
||||
case seg == "":
|
||||
return "must not contain an empty segment ('a//b' or a trailing '/')"
|
||||
case seg == "." || seg == "..":
|
||||
return "must not contain '.' or '..' segments"
|
||||
case strings.HasSuffix(seg, "."):
|
||||
return "must not contain a segment that ends with '.'"
|
||||
case strings.HasPrefix(seg, "-"):
|
||||
return "must not contain a segment that starts with '-'"
|
||||
case strings.EqualFold(seg, ".git"):
|
||||
return "must not contain a '.git' segment"
|
||||
case !segmentRE.MatchString(seg):
|
||||
return "may only contain letters, digits, '.', '_', '@' and '-' in each segment"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Resolve validates the three arguments and fills the defaults.
|
||||
func Resolve(subdir, dockerfile, buildContext string) (Layout, error) {
|
||||
if p := PathProblem(subdir, true); p != "" {
|
||||
return Layout{}, fmt.Errorf("--subdir %s", p)
|
||||
}
|
||||
if dockerfile == "" {
|
||||
dockerfile = DefaultDockerfile
|
||||
}
|
||||
if p := PathProblem(dockerfile, false); p != "" {
|
||||
return Layout{}, fmt.Errorf("--dockerfile %s", p)
|
||||
}
|
||||
switch buildContext {
|
||||
case "":
|
||||
buildContext = ContextSourcePath
|
||||
case ContextSourcePath, ContextRepoRoot:
|
||||
default:
|
||||
return Layout{}, fmt.Errorf(
|
||||
"--build-context must be %q or %q, got %q", ContextSourcePath, ContextRepoRoot, buildContext,
|
||||
)
|
||||
}
|
||||
return Layout{Subdir: subdir, Dockerfile: dockerfile, Context: buildContext}, nil
|
||||
}
|
||||
|
||||
// IsDefault reports whether this is today's layout: the root, its
|
||||
// `Dockerfile`, the root as context. The module then behaves exactly as it
|
||||
// did before these arguments existed.
|
||||
func (l Layout) IsDefault() bool {
|
||||
return l.Subdir == "" && l.Dockerfile == DefaultDockerfile && l.Context == ContextSourcePath
|
||||
}
|
||||
|
||||
func join(a, b string) string {
|
||||
if a == "" {
|
||||
return b
|
||||
}
|
||||
return a + "/" + b
|
||||
}
|
||||
|
||||
// DockerfilePath is the Dockerfile's path from the checkout root.
|
||||
func (l Layout) DockerfilePath() string { return join(l.Subdir, l.Dockerfile) }
|
||||
|
||||
// ContextDir is the build context relative to the checkout: "" for the root.
|
||||
func (l Layout) ContextDir() string {
|
||||
if l.Context == ContextRepoRoot {
|
||||
return ""
|
||||
}
|
||||
return l.Subdir
|
||||
}
|
||||
|
||||
// DockerfileInContext is the Dockerfile path relative to ContextDir.
|
||||
func (l Layout) DockerfileInContext() string {
|
||||
if l.Context == ContextRepoRoot {
|
||||
return l.DockerfilePath()
|
||||
}
|
||||
return l.Dockerfile
|
||||
}
|
||||
|
||||
// Kind is a tree entry's type, read WITHOUT following symlinks.
|
||||
type Kind int
|
||||
|
||||
const (
|
||||
Missing Kind = iota
|
||||
Directory
|
||||
Regular
|
||||
Symlink
|
||||
Other
|
||||
)
|
||||
|
||||
func (k Kind) String() string {
|
||||
switch k {
|
||||
case Missing:
|
||||
return "missing"
|
||||
case Directory:
|
||||
return "directory"
|
||||
case Regular:
|
||||
return "regular file"
|
||||
case Symlink:
|
||||
return "symlink"
|
||||
default:
|
||||
return "special file"
|
||||
}
|
||||
}
|
||||
|
||||
// StatFunc reports the type of a checkout-relative path without following
|
||||
// symlinks. The module passes one backed by Directory.Stat; tests pass a map.
|
||||
type StatFunc func(ctx context.Context, path string) (Kind, error)
|
||||
|
||||
// ErrRefused marks a layout the module will not build.
|
||||
var ErrRefused = errors.New("build layout refused")
|
||||
|
||||
func refuse(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: "+format, append([]any{ErrRefused}, args...)...)
|
||||
}
|
||||
|
||||
// Confine checks the tree for l and reports whether the Dockerfile exists.
|
||||
//
|
||||
// Every component of Subdir must be a directory, and so must every directory
|
||||
// on the way to the Dockerfile. A symlink anywhere is refused — the resolved
|
||||
// context and Dockerfile would otherwise be able to point outside the
|
||||
// checkout. A missing Subdir is refused; a missing Dockerfile is reported
|
||||
// (false) unless requireDockerfile, because the language lane builds a
|
||||
// directory that has none.
|
||||
func Confine(ctx context.Context, stat StatFunc, l Layout, requireDockerfile bool) (bool, error) {
|
||||
walked := ""
|
||||
if l.Subdir != "" {
|
||||
for _, seg := range strings.Split(l.Subdir, "/") {
|
||||
walked = join(walked, seg)
|
||||
kind, err := stat(ctx, walked)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reading %q: %w", walked, err)
|
||||
}
|
||||
if kind != Directory {
|
||||
return false, refuse("%q in --subdir is a %s, not a directory", walked, kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
parts := strings.Split(l.Dockerfile, "/")
|
||||
for i, seg := range parts {
|
||||
walked = join(walked, seg)
|
||||
kind, err := stat(ctx, walked)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reading %q: %w", walked, err)
|
||||
}
|
||||
last := i == len(parts)-1
|
||||
switch {
|
||||
case kind == Missing:
|
||||
if requireDockerfile {
|
||||
return false, refuse("the Dockerfile %q does not exist", l.DockerfilePath())
|
||||
}
|
||||
return false, nil
|
||||
case kind == Symlink:
|
||||
return false, refuse("%q is a symlink; the build never follows one", walked)
|
||||
case !last && kind != Directory:
|
||||
return false, refuse("%q on the way to the Dockerfile is a %s", walked, kind)
|
||||
case last && kind != Regular:
|
||||
return false, refuse("the Dockerfile %q is a %s, not a regular file", walked, kind)
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package layout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveDefaultsAreTodaysLayout(t *testing.T) {
|
||||
l, err := Resolve("", "", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !l.IsDefault() {
|
||||
t.Fatalf("empty arguments must be the root layout, got %+v", l)
|
||||
}
|
||||
if l.DockerfilePath() != "Dockerfile" || l.ContextDir() != "" || l.DockerfileInContext() != "Dockerfile" {
|
||||
t.Fatalf("root layout resolved to %+v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveRefusesWhatTheValidatorRefuses(t *testing.T) {
|
||||
for _, bad := range []string{
|
||||
"..", "a/../b", "/a", `a\b`, "a//b", "a/", "-x", ".git/x", "a/.GIT", "a/.git.",
|
||||
"a/b c", "a/b+c", "a/[b]", "a/~b", "a/b\x00", "a/b\n", strings.Repeat("a/", 17) + "a",
|
||||
} {
|
||||
if _, err := Resolve(bad, "", ""); err == nil {
|
||||
t.Errorf("--subdir %q was accepted", bad)
|
||||
}
|
||||
if _, err := Resolve("apps/web", bad, ""); err == nil {
|
||||
t.Errorf("--dockerfile %q was accepted", bad)
|
||||
}
|
||||
}
|
||||
if _, err := Resolve("apps/web", "", "../.."); err == nil {
|
||||
t.Error("a --build-context that is a path was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveAcceptsLegitimatePaths(t *testing.T) {
|
||||
// The second mutant of PR 1, mirrored: a charset narrowed to [a-z0-9/-]
|
||||
// would refuse these.
|
||||
for _, good := range []string{"apps/web", "services/Billing-API", "packages/@scope.ui", "a_b/c.d"} {
|
||||
if _, err := Resolve(good, "docker/Dockerfile.prod", ContextRepoRoot); err != nil {
|
||||
t.Errorf("%q refused: %v", good, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPlacement(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "Dockerfile", ContextSourcePath)
|
||||
if l.ContextDir() != "apps/web" || l.DockerfileInContext() != "Dockerfile" {
|
||||
t.Fatalf("source_path context: %+v -> %q %q", l, l.ContextDir(), l.DockerfileInContext())
|
||||
}
|
||||
r, _ := Resolve("apps/web", "Dockerfile", ContextRepoRoot)
|
||||
if r.ContextDir() != "" || r.DockerfileInContext() != "apps/web/Dockerfile" {
|
||||
t.Fatalf("repo_root context: %+v -> %q %q", r, r.ContextDir(), r.DockerfileInContext())
|
||||
}
|
||||
}
|
||||
|
||||
// tree is a fake checkout: path -> kind, read without following symlinks.
|
||||
func tree(entries map[string]Kind) StatFunc {
|
||||
return func(_ context.Context, p string) (Kind, error) {
|
||||
if k, ok := entries[p]; ok {
|
||||
return k, nil
|
||||
}
|
||||
return Missing, nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineAcceptsARealDirectoryAndDockerfile(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
ok, err := Confine(context.Background(), tree(map[string]Kind{
|
||||
"apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Regular,
|
||||
}), l, true)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("got (%v, %v)", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// "Dockerfile turned into a symlink after onboarding" (ADR-0074 rollout PR 3).
|
||||
// Mutant: remove the symlink check in Confine -> this test fails.
|
||||
func TestConfineRefusesADockerfileTurnedIntoASymlink(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
_, err := Confine(context.Background(), tree(map[string]Kind{
|
||||
"apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Symlink,
|
||||
}), l, false)
|
||||
if !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("a symlinked Dockerfile was not refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineRefusesASymlinkedSourceDirectory(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
for _, entries := range []map[string]Kind{
|
||||
// the service directory itself
|
||||
{"apps": Directory, "apps/web": Symlink},
|
||||
// an ancestor of it
|
||||
{"apps": Symlink, "apps/web": Directory, "apps/web/Dockerfile": Regular},
|
||||
} {
|
||||
if _, err := Confine(context.Background(), tree(entries), l, false); !errors.Is(err, ErrRefused) {
|
||||
t.Errorf("%v: a symlinked path component was not refused: %v", entries, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineRefusesASymlinkOnTheWayToTheDockerfile(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "docker/Dockerfile", "")
|
||||
_, err := Confine(context.Background(), tree(map[string]Kind{
|
||||
"apps": Directory, "apps/web": Directory, "apps/web/docker": Symlink,
|
||||
"apps/web/docker/Dockerfile": Regular,
|
||||
}), l, false)
|
||||
if !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("a symlinked Dockerfile directory was not refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineMissingDockerfile(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
entries := map[string]Kind{"apps": Directory, "apps/web": Directory}
|
||||
ok, err := Confine(context.Background(), tree(entries), l, false)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("a directory with no Dockerfile is a language-lane build: (%v, %v)", ok, err)
|
||||
}
|
||||
if _, err := Confine(context.Background(), tree(entries), l, true); !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("a required Dockerfile that is missing was not refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineRefusesAMissingOrFileSubdir(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
for _, entries := range []map[string]Kind{
|
||||
{"apps": Directory},
|
||||
{"apps": Directory, "apps/web": Regular},
|
||||
} {
|
||||
if _, err := Confine(context.Background(), tree(entries), l, false); !errors.Is(err, ErrRefused) {
|
||||
t.Errorf("%v: accepted", entries)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineRefusesADockerfileThatIsADirectory(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
_, err := Confine(context.Background(), tree(map[string]Kind{
|
||||
"apps": Directory, "apps/web": Directory, "apps/web/Dockerfile": Directory,
|
||||
}), l, false)
|
||||
if !errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("a Dockerfile directory was not refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfineAtTheRootChecksOnlyTheDockerfile(t *testing.T) {
|
||||
l, _ := Resolve("", "deploy/Dockerfile", "")
|
||||
ok, err := Confine(context.Background(), tree(map[string]Kind{
|
||||
"deploy": Directory, "deploy/Dockerfile": Regular,
|
||||
}), l, true)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("got (%v, %v)", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfinePropagatesAReadError(t *testing.T) {
|
||||
l, _ := Resolve("apps/web", "", "")
|
||||
boom := errors.New("engine unreachable")
|
||||
_, err := Confine(context.Background(), func(context.Context, string) (Kind, error) {
|
||||
return Other, boom
|
||||
}, l, false)
|
||||
if !errors.Is(err, boom) || errors.Is(err, ErrRefused) {
|
||||
t.Fatalf("a read error must surface as itself, not as a verdict: %v", err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user