// 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 }