Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ PYTHON := $(if $(wildcard $(VENV_BIN)/python),$(VENV_BIN)/python,python3)
EGG_IMAGE_TAG := $(shell git describe --always --dirty 2>/dev/null || echo latest)

.PHONY: help \
setup deps venv sync-venv-if-uv install-linters check-linters \
setup deps venv sync-venv-if-uv sandbox-deps install-linters check-linters \
lint lint-python lint-shell lint-yaml lint-docker lint-actions lint-custom \
test test-all test-record-good security \
test-integration test-e2e test-security smoketest-long-poll \
Expand Down Expand Up @@ -123,6 +123,17 @@ venv:
sync-venv-if-uv:
@if command -v uv >/dev/null 2>&1; then $(MAKE) venv; fi

# Sync only third-party dependencies into .venv; do NOT install the local
# `egg` package. This is the variant invoked by sandbox image build_commands,
# which run in a synthetic context containing only watch_files (Makefile,
# pyproject.toml, uv.lock) — no source dirs, no README — so a full
# `uv sync` fails when the hatchling build backend tries to package the
# project. Dev tools (ruff, pytest, mypy, etc.) install fine without the
# project itself. Issue #2087.
sandbox-deps:
@echo "==> Syncing dev dependencies (no project install)..."
@uv sync --extra dev --no-install-project

# Install all linting tools
install-linters: venv
@echo "Installing linting tools..."
Expand Down
2 changes: 2 additions & 0 deletions config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ Each `build_commands` entry has:
- `persist_dirs`: Directories (relative to repo root) to preserve from the build context into the Docker image. After `commands` run, these directories are copied to `/opt/prebuilt-deps/<repo>/` and restored into the mounted repo at container startup by `entrypoint.py`. Use this for local dependencies like `node_modules` that would otherwise be lost when the build context is cleaned up.
- `persist_system_dirs`: Absolute-path system directories to preserve from the build stage into the final image. After `commands` run, these directories are copied to `/opt/prebuilt-deps/__egg_system_dirs__/<abs_path>/` and the Dockerfile restores them to their original absolute locations. Use this for system-level tool installations that land outside the repo directory (e.g., `/usr/local/go`, `/usr/local/node`). Top-level system paths (`/`, `/etc`, `/usr`, `/var`, etc.) and all paths under `/proc`, `/sys`, `/dev`, `/run`, `/boot` are blocked.

**Fail-fast contract (since #2087):** A non-zero exit from any command, a missing watch-files directory, or a `persist_dirs` / `persist_system_dirs` entry that doesn't exist after the commands run all abort the image build. Earlier behavior printed a warning and continued, which silently produced empty `/opt/prebuilt-deps/<repo>/` trees. Path-traversal rejection in `persist_dirs` remains warn-and-skip — it's a security control, not a misconfiguration we want to crash on.

**How it works:**
1. `create_dockerfile()` copies each repo's watch files from `local_repos.paths` into the build context at `~/.config/egg/repo-deps/<repo-name>/`
2. `compute_build_hash()` includes watch file contents, so the image rebuilds automatically when dependency files change
Expand Down
25 changes: 25 additions & 0 deletions config/repositories.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,31 @@ repo_settings:
# commands:
# - pip install -r requirements.txt
# - pip install -r requirements-dev.txt
#
# # Python project using uv + a build backend (hatchling, setuptools, ...).
# # NOTE: build_commands run in a synthetic context that contains ONLY the
# # files in `watch_files` — no source dirs, no README. A bare `uv sync`
# # tries to build the local project as a wheel and will fail. Use
# # `--no-install-project` (or a Makefile target that wraps it) so only
# # third-party deps go into the persisted .venv. The local project is not
# # needed for ruff / pytest / mypy / etc. to function in the sandbox. See #2087.
# YOUR_USERNAME/uv-python-project:
# build_commands:
# watch_files:
# - Makefile
# - pyproject.toml
# - uv.lock
# commands:
# - curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh
# - make sandbox-deps # ← `uv sync --extra dev --no-install-project`
# persist_dirs:
# - .venv
# persist_system_dirs:
# # ← carries `uv` itself (and anything else earlier setup steps put
# # under /usr/local/bin) into the runtime image. The persist machinery
# # only handles directories, not single files, so persisting just `uv`
# # would require a wrapper dir.
# - /usr/local/bin
# YOUR_USERNAME/go-service:
# build_commands:
# watch_files:
Expand Down
2 changes: 2 additions & 0 deletions sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,8 @@ Per-repo `build_commands` in `repositories.yaml` allow project-specific dependen

> **Note:** `persist_dirs` and `persist_system_dirs` are not included in `compute_build_hash()`. Changing only these fields won't trigger an automatic rebuild — add or modify a `watch_files` entry or use `egg --rebuild`.

> **Fail-fast contract (since #2087):** A non-zero exit from any command, a missing watch-files directory, or a `persist_dirs` / `persist_system_dirs` entry that doesn't exist after the commands run all abort the image build. Earlier behavior printed a warning and continued, which silently produced empty prebuilt-deps trees. Path-traversal rejection stays warn-and-skip (security control, not misconfiguration).

**Config propagation:** During Docker builds, `repositories.yaml` is not available in the build context. Both `build_commands` and `extra_packages` are propagated via a `manifest.json` file that `create_dockerfile()` writes into `repo-deps/`. The `docker-setup.py` script reads this manifest as a fallback when `repositories.yaml` is not found.

See [Configuration README](../config/README.md#per-repo-build-commands-dependency-caching) for configuration details.
Expand Down
68 changes: 49 additions & 19 deletions sandbox/docker-setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,14 +280,31 @@ def load_extra_packages_manifest(
return [], []


def run_build_commands(build_commands: list[dict[str, Any]]) -> None:
def run_build_commands(
build_commands: list[dict[str, Any]],
repo_deps_base: Path = Path("/tmp/repo-deps"),
) -> None:
"""Execute build commands for each repo during Docker image build.

Each repo's commands run in its watch files directory at /tmp/repo-deps/<repo-name>.
Commands run as root (same as the rest of docker-setup.py).
Each repo's commands run in its watch files directory at
`<repo_deps_base>/<repo-name>`. Commands run as root (same as the rest of
docker-setup.py).

Failure modes that abort the build (vs. earlier warn-and-continue behavior,
which silently produced broken images — see #2087):

- The repo's watch_files directory is missing (build manifest declared
commands but `_copy_repo_watch_files` produced no source for them).
- A command exits non-zero, or raises an exception (e.g. binary not found).

Args:
build_commands: List of dicts from get_build_commands()
repo_deps_base: Base path for repo build contexts (default: /tmp/repo-deps).
Mirrors persist_build_dirs's parameter so tests can use tmp_path
instead of touching the real /tmp/repo-deps tree.

Raises:
RuntimeError: When any of the failure modes above occurs.
"""
if not build_commands:
return
Expand All @@ -299,16 +316,16 @@ def run_build_commands(build_commands: list[dict[str, Any]]) -> None:
commands = entry["commands"]
# Sanitize repo name for directory path (owner/repo -> owner--repo)
repo_dir_name = repo.replace("/", "--")
work_dir = Path("/tmp/repo-deps") / repo_dir_name
work_dir = repo_deps_base / repo_dir_name

print(f"\n--- Build commands for {repo} ---")

if not work_dir.exists():
print(
f" Warning: Watch files directory {work_dir} does not exist, "
f"running commands in /tmp"
raise RuntimeError(
f"build_commands: watch files directory {work_dir} does not exist "
f"for {repo}; check watch_files config and that "
f"_copy_repo_watch_files ran"
)
work_dir = Path("/tmp")

for cmd in commands:
print(f" Running: {cmd}")
Expand All @@ -321,14 +338,19 @@ def run_build_commands(build_commands: list[dict[str, Any]]) -> None:
check=False,
capture_output=False,
)
if result.returncode != 0:
print(f" Warning: Command exited with code {result.returncode}: {cmd}")
except Exception as e:
print(f" Warning: Command failed: {cmd}: {e}")
raise RuntimeError(
f"build_commands: command for {repo} raised an exception: {cmd!r}: {e}"
) from e
if result.returncode != 0:
raise RuntimeError(
f"build_commands: command for {repo} exited with code "
f"{result.returncode}: {cmd!r}"
)

print("\n=== Build commands complete ===")

persist_build_dirs(build_commands)
persist_build_dirs(build_commands, repo_deps_base=repo_deps_base)


def persist_build_dirs(
Expand Down Expand Up @@ -362,16 +384,23 @@ def persist_build_dirs(
for rel_dir in persist_dirs:
src_dir = work_dir / rel_dir

# Defense-in-depth: validate path stays within work_dir
# Defense-in-depth: validate path stays within work_dir.
# Path traversal is rejected (not raised) so that a malformed config
# entry can't crash an otherwise valid build — but the legitimate
# absent-after-build case below IS raised (see #2087).
try:
src_dir.resolve().relative_to(work_dir.resolve())
except ValueError:
print(f" Warning: persist_dirs: {rel_dir} escapes build context, skipping")
continue

if not src_dir.is_dir():
print(f" Warning: persist_dirs: {rel_dir} does not exist after build, skipping")
continue
raise RuntimeError(
f"persist_dirs: {repo!r} declared persist_dir {rel_dir!r} but "
f"it does not exist at {src_dir} after build commands ran. "
f"Either the build commands failed silently, or the watch_files "
f"context is missing inputs the commands need."
)

dest_dir = dest_base / rel_dir
dest_dir.parent.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -417,11 +446,12 @@ def persist_build_dirs(

src_dir = resolved
if not src_dir.is_dir():
print(
f" Warning: persist_system_dirs: {abs_dir} does not exist "
f"after build ({repo}), skipping"
raise RuntimeError(
f"persist_system_dirs: {repo!r} declared {abs_dir!r} but it "
f"does not exist at {src_dir} after build commands ran. "
f"Either the build commands failed silently, or they did "
f"not produce that path."
)
continue

# Store under __egg_system_dirs__/<abs_path> so it can be restored to the same location
# Strip leading / for the destination path
Expand Down
Loading
Loading