chore: publish IntegraCI build modules 732ec6c83925

This commit is contained in:
dhimaz0445 committed 2026-10-28 08:09:16 +00:00
1 parent 7a84930dea
commit 5f8a24d014
133 files changed
+18990 -2

No files matched your search

+159
View File
@@ -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)
}
}
+212
View File
@@ -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)
}
}
}
}
+239
View File
@@ -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
}
+171
View File
@@ -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)
}
}