From b11bdaabe1e89644d6dacda8e4e66a9faf3bd12c Mon Sep 17 00:00:00 2001 From: burtenshaw Date: Thu, 26 Nov 2026 15:47:06 +0100 Subject: [PATCH 01/15] feat(harbor): add openenv harbor build-images for OCI registries and Kaniko on HF Jobs --- src/openenv/cli/commands/harbor.py | 337 ++- src/openenv/harbor/__init__.py | 1 + src/openenv/harbor/images.py | 2402 ++++++++++++++++++++ tests/test_cli/test_harbor_build_images.py | 805 +++++++ 4 files changed, 3544 insertions(+), 1 deletion(-) create mode 100644 src/openenv/harbor/images.py create mode 100644 tests/test_cli/test_harbor_build_images.py diff --git a/src/openenv/cli/commands/harbor.py b/src/openenv/cli/commands/harbor.py index 68a20b8519..4b1468325c 100644 --- a/src/openenv/cli/commands/harbor.py +++ b/src/openenv/cli/commands/harbor.py @@ -1,8 +1,9 @@ """`openenv harbor` — run Harbor tasks with token-level capture. -Five commands, in the order you would use them: +Six commands, in the order you would use them: openenv harbor info what can this machine run right now? + openenv harbor build-images tasks/ build/append/pin OCI images into task.toml (no Spaces) openenv harbor rollout --task-index 0 one rollout, end to end, no server openenv harbor export-sft results/ rollouts as SFT rows (messages + tools) openenv harbor serve the env server, for trainers and clients @@ -302,6 +303,340 @@ def info( raise typer.Exit(1) +@app.command("build-images") +def build_images( + path: Annotated[ + Path, + typer.Argument( + help="Harbor task directory (with task.toml) or dataset directory containing tasks." + ), + ], + registry: Annotated[ + str, + typer.Option( + "--registry", + help="Target OCI repository, e.g. ghcr.io/your-org/your-tasks (no Spaces required).", + ), + ] = "", + builder: Annotated[ + str, + typer.Option( + "--builder", + help="Builder for RUN Dockerfiles: auto | kaniko | docker | oci-append.", + ), + ] = "auto", + output_dir: Annotated[ + Optional[Path], + typer.Option( + "--output-dir", + help="Write updated Harbor task copies with pinned task.toml here (leaves input untouched).", + ), + ] = None, + in_place: Annotated[ + bool, + typer.Option( + "--in-place", + help="Rewrite [environment].docker_image directly in each task.toml.", + ), + ] = False, + receipts: Annotated[ + Optional[Path], + typer.Option( + "--receipts", + help="JSON manifest of resolved image digests (also used to resume interrupted batches).", + ), + ] = None, + per_task_receipts_dir: Annotated[ + Optional[Path], + typer.Option( + "--per-task-receipts-dir", + help="Directory for incremental `.json` receipts (resumable and directly consumable by downstream stages).", + ), + ] = None, + task: Annotated[ + Optional[list[str]], + typer.Option( + "--task", + help="Build only the named task ID(s) under `path` (repeatable).", + ), + ] = None, + extra_dockerfile: Annotated[ + Optional[Path], + typer.Option( + "--extra-dockerfile", + help="Optional Dockerfile fragment appended to each task's Dockerfile (e.g. harness installs).", + ), + ] = None, + tag_prefix: Annotated[ + str, + typer.Option("--tag-prefix", help="Prefix added to each pushed OCI tag."), + ] = "", + concurrency: Annotated[ + int, + typer.Option( + "--concurrency", + min=1, + help="Maximum parallel builds, OCI appends, or registry checks.", + ), + ] = 4, + namespace: Annotated[ + str, + typer.Option( + "--namespace", + help="Hugging Face namespace for Kaniko Jobs and temporary build-context bucket.", + ), + ] = "", + flavor: Annotated[ + str, + typer.Option( + "--flavor", + help="HF Jobs hardware flavor for --builder kaniko (e.g. cpu-basic, cpu-upgrade, cpu-xl).", + ), + ] = "cpu-basic", + timeout: Annotated[ + str, + typer.Option( + "--timeout", help="Max duration for each Kaniko HF Job (e.g. 30m, 1h)." + ), + ] = "30m", + kaniko_image: Annotated[ + str, + typer.Option( + "--kaniko-image", + help="Kaniko debug image used by --builder kaniko.", + ), + ] = "ghcr.io/osscontainertools/kaniko:debug", + bucket: Annotated[ + str, + typer.Option( + "--bucket", + help="Private HF Bucket name (or namespace/name) for temporary Kaniko context tarballs.", + ), + ] = "openenv-kaniko-builds", + cache_repo: Annotated[ + str, + typer.Option( + "--cache-repo", + help="Optional OCI repository for Kaniko / BuildKit layer cache (e.g. ghcr.io/org/repo-cache).", + ), + ] = "", + no_oci_append: Annotated[ + bool, + typer.Option( + "--no-oci-append", + help="Force COPY-only Dockerfiles through --builder instead of pure-Python OCI layer append.", + ), + ] = False, + rebuild_pinned: Annotated[ + bool, + typer.Option( + "--rebuild-pinned", + help="Rebuild tasks even when task.toml already has a @sha256-pinned docker_image.", + ), + ] = False, + strip_dockerfile: Annotated[ + bool, + typer.Option( + "--strip-dockerfile", + help="Remove environment/Dockerfile on shared-image tasks so Harbor uploads environment/ at start.", + ), + ] = False, + verify_public: Annotated[ + bool, + typer.Option( + "--verify-public/--no-verify-public", + help="Verify every pushed image is anonymously pullable as linux/amd64 (required by HF Sandbox).", + ), + ] = True, + plan_only: Annotated[ + bool, + typer.Option( + "--plan", + help="Audit, classify, and deduplicate tasks without building or pushing.", + ), + ] = False, + verify_only: Annotated[ + bool, + typer.Option( + "--verify-only", + help="Preflight-check that every task.toml points to a pullable linux/amd64 image.", + ), + ] = False, + require_digest_pin: Annotated[ + bool, + typer.Option( + "--require-digest-pin", + help="With --verify-only, fail if any docker_image uses a mutable tag instead of @sha256:...", + ), + ] = False, + no_push: Annotated[ + bool, + typer.Option( + "--no-push", + help="Build images without pushing to a registry (useful for Kaniko/Docker smoke tests).", + ), + ] = False, + registry_user: Annotated[ + str, + typer.Option( + "--registry-user", + help="Registry username (defaults to env GHCR_USERNAME / REGISTRY_USERNAME or ~/.docker/config.json).", + ), + ] = "", + registry_password: Annotated[ + str, + typer.Option( + "--registry-password", + help="Registry token/password (prefer env GHCR_TOKEN / REGISTRY_PASSWORD over CLI flags).", + ), + ] = "", + json_output: Annotated[ + bool, + typer.Option( + "--json", help="Emit JSON output instead of a human-readable summary." + ), + ] = False, +) -> None: + """Build, append, push, and verify OCI images for Harbor tasks (no Docker Spaces). + + Audits each task's `environment/`, deduplicates identical build contexts, uses pure-Python OCI + layer append for COPY-only Dockerfiles, runs Kaniko on HF Jobs (`--builder kaniko`) or Docker + Buildx (`--builder docker`) for RUN Dockerfiles, verifies `linux/amd64` pullability, and pins + `[environment].docker_image = "@sha256:"` in `task.toml`. + """ + from openenv.harbor.images import ( + HarborImageError, + build_harbor_images, + plan_harbor_images, + verify_harbor_images, + ) + + if plan_only and verify_only: + raise typer.BadParameter("Pass either --plan or --verify-only, not both.") + if output_dir is not None and in_place: + raise typer.BadParameter("Pass either --output-dir or --in-place, not both.") + + extra_text = ( + extra_dockerfile.read_text(encoding="utf-8") if extra_dockerfile else None + ) + + try: + if verify_only: + result = verify_harbor_images( + path, + anonymous=verify_public, + require_digest_pin=require_digest_pin, + concurrency=concurrency, + ) + if json_output: + print(json.dumps(result, indent=2, sort_keys=True)) + else: + print( + f"verified {result['ok']}/{result['total']} tasks pullable as linux/amd64" + ) + for tid, rec in sorted(result["tasks"].items()): + if not rec["ok"]: + print(f" FAIL {tid}: {rec['error']}") + if result["failed"]: + raise typer.Exit(1) + return + + if plan_only: + plans = plan_harbor_images( + path, + registry=registry or None, + tag_prefix=tag_prefix, + extra_dockerfile=extra_text, + skip_pinned=not rebuild_pinned, + allow_oci_append=not no_oci_append, + task_ids=task or None, + ) + unique_envs = len({(p.action, p.env_hash) for p in plans}) + payload = { + "total_tasks": len(plans), + "unique_environments": unique_envs, + "actions": { + action: sum(p.action == action for p in plans) + for action in ( + "keep_pinned", + "verify_shared", + "oci_append", + "build", + ) + }, + "tasks": [ + { + "task_id": p.task_id, + "action": p.action, + "env_hash": p.env_hash, + "base_image": p.base_image, + "target_tag": p.target_tag, + "reason": p.reason, + } + for p in plans + ], + } + if json_output: + print(json.dumps(payload, indent=2, sort_keys=True)) + else: + print( + f"plan {payload['total_tasks']} task(s), " + f"{payload['unique_environments']} unique environment(s): " + + ", ".join(f"{k}={v}" for k, v in payload["actions"].items() if v) + ) + for item in payload["tasks"]: + print( + f" {item['action']:<13} {item['task_id']} ({item['reason']})" + ) + return + + summary = build_harbor_images( + path, + registry=registry or None, + builder=builder, + output_dir=output_dir, + in_place=in_place, + receipts_path=receipts, + per_task_receipts_dir=per_task_receipts_dir, + task_ids=task or None, + tag_prefix=tag_prefix, + extra_dockerfile=extra_text, + skip_pinned=not rebuild_pinned, + allow_oci_append=not no_oci_append, + strip_dockerfile_for_shared=strip_dockerfile, + verify_public=verify_public, + no_push=no_push, + concurrency=concurrency, + namespace=namespace or None, + flavor=flavor, + timeout=timeout, + kaniko_image=kaniko_image, + bucket_name=bucket, + cache_repo=cache_repo or None, + registry_username=registry_user or None, + registry_password=registry_password or None, + progress=None if json_output else print, + ) + except (HarborImageError, FileNotFoundError, ValueError) as exc: + if json_output: + print(json.dumps({"error": str(exc)}, indent=2)) + else: + typer.echo(f"Error: {exc}", err=True) + raise typer.Exit(1) from exc + + if json_output: + print(json.dumps(summary, indent=2, sort_keys=True)) + else: + print( + f"done resolved={summary['resolved']} " + f"built_no_push={summary['built_no_push']} " + f"failed={summary['failed']} " + f"(unique_envs={summary['unique_environments']}/{summary['total_tasks']})" + ) + if summary["failed"]: + raise typer.Exit(1) + + @app.command("rollout") def rollout( llm_url: Annotated[str, typer.Option("--llm-url", help=_LLM_HELP)], diff --git a/src/openenv/harbor/__init__.py b/src/openenv/harbor/__init__.py index edf7c0ca29..f23aa84ae8 100644 --- a/src/openenv/harbor/__init__.py +++ b/src/openenv/harbor/__init__.py @@ -4,6 +4,7 @@ concurrency, pass@k. This package adds the OpenEnv side and nothing more: tasks.py dataset discovery over the Task API (HF repo | local dir | Harbor registry) + images.py audit, build/append, push and verify OCI images for Harbor task.toml pins seams.py how each agent is pointed at the capture proxy — the only per-agent knowledge install_fixes.py subclasses for agents whose Harbor wrapper cannot be configured as shipped atif.py cross-check captured tokens against Harbor's own ATIF trajectory diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py new file mode 100644 index 0000000000..aaf432094e --- /dev/null +++ b/src/openenv/harbor/images.py @@ -0,0 +1,2402 @@ +"""Build, append, push, and verify OCI container images for Harbor tasks. + +HF Sandbox (and other prebuilt-image Harbor runtimes) require each task's +``task.toml`` to set ``[environment].docker_image`` to an already-published, +publicly pullable ``linux/amd64`` image. This module provides a Spaces-free +workflow targeting standard OCI registries (GHCR, Docker Hub, private/local +OCI v2 registries): + +1. **Audit** each task's ``environment/`` directory for symlinks, unsafe + ``COPY``/``ADD`` paths, verifier/solution leakage, and embedded credentials. +2. **Classify & deduplicate** environments by content hash: + - Tasks with no ``environment/Dockerfile`` and an existing ``docker_image`` + only verify and digest-pin the shared image (Harbor uploads + ``environment/`` at sandbox start). + - Tasks whose ``Dockerfile`` is declarative ``COPY``/``WORKDIR``/``ENV`` + only (no ``RUN``) take the pure-Python **OCI layer append** fast path — + no Docker daemon and no remote build VM, <1 s per task with full base + layer deduplication. + - Tasks whose ``Dockerfile`` runs ``RUN`` instructions build via either + **Kaniko on Hugging Face Jobs** (``--builder kaniko``, no persistent VM + or cluster) or **Docker Buildx** (``--builder docker``). +3. **Pin & verify** every resulting manifest as ``@sha256:`` + (confirming ``linux/amd64`` config and anonymous public pullability) and + write ``[environment].docker_image`` into ``task.toml``. +""" + +from __future__ import annotations + +import base64 +import copy +import fnmatch +import gzip +import hashlib +import io +import json +import os +import re +import shlex +import shutil +import subprocess +import tarfile +import tempfile +import threading +import time +import uuid +from concurrent.futures import ThreadPoolExecutor, as_completed +from dataclasses import asdict, dataclass, field +from pathlib import Path, PurePosixPath +from typing import Any, Callable +from urllib.parse import quote, urljoin, urlsplit + +import httpx + +try: + import tomllib +except ModuleNotFoundError: # pragma: no cover - Python 3.10 fallback + import tomli as tomllib # type: ignore[no-redef] + +from .tasks import _task_dirs_from_directory + +DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") +PINNED_IMAGE_RE = re.compile(r"^[^\s@]+@sha256:[0-9a-f]{64}$") +DEFAULT_KANIKO_IMAGE = "ghcr.io/osscontainertools/kaniko:debug" +KANIKO_DIGEST_MARKER = "OPENENV_KANIKO_DIGEST=" + +_OCI_INDEX = "application/vnd.oci.image.index.v1+json" +_OCI_MANIFEST = "application/vnd.oci.image.manifest.v1+json" +_OCI_CONFIG = "application/vnd.oci.image.config.v1+json" +_OCI_LAYER_GZIP = "application/vnd.oci.image.layer.v1.tar+gzip" +_DOCKER_MANIFEST_LIST = "application/vnd.docker.distribution.manifest.list.v2+json" +_DOCKER_MANIFEST_V2 = "application/vnd.docker.distribution.manifest.v2+json" +_DOCKER_CONFIG = "application/vnd.docker.container.image.v1+json" +_DOCKER_LAYER_GZIP = "application/vnd.docker.image.rootfs.diff.tar.gzip" + +_ACCEPT_MANIFEST = ", ".join( + ( + _OCI_INDEX, + _OCI_MANIFEST, + _DOCKER_MANIFEST_LIST, + _DOCKER_MANIFEST_V2, + ) +) + +_COPY_ONLY_INSTRUCTIONS = frozenset( + {"FROM", "WORKDIR", "ENV", "COPY", "LABEL", "ARG", "EXPOSE"} +) + +_CREDENTIAL_PATTERNS = ( + ("huggingface token", re.compile(rb"\bhf_[A-Za-z0-9]{20,}\b")), + ("github classic token", re.compile(rb"\bgh[pousr]_[A-Za-z0-9]{20,}\b")), + ("github fine-grained token", re.compile(rb"\bgithub_pat_[A-Za-z0-9_]{20,}\b")), + ( + "private key", + re.compile(rb"-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----"), + ), +) + +_HIDDEN_VERIFIER_FILES = frozenset( + { + "test.sh", + "grade.py", + "contract.json", + "test_driver.py", + "test_results.py", + "expected.json", + "cases.json", + } +) + + +class HarborImageError(RuntimeError): + """Raised when auditing, building, pushing, or verifying a Harbor image fails.""" + + +@dataclass(frozen=True) +class ImageRef: + """Parsed OCI image reference.""" + + registry: str + display_registry: str + repository: str + tag: str | None = None + digest: str | None = None + + @property + def canonical_repo(self) -> str: + return f"{self.display_registry}/{self.repository}" + + @property + def reference(self) -> str: + if self.digest: + return self.digest + return self.tag or "latest" + + def with_tag(self, tag: str) -> "ImageRef": + return ImageRef( + registry=self.registry, + display_registry=self.display_registry, + repository=self.repository, + tag=tag, + digest=None, + ) + + def pinned(self, digest: str) -> str: + if not DIGEST_RE.fullmatch(digest): + raise ValueError(f"Invalid OCI digest: {digest!r}") + return f"{self.canonical_repo}@{digest}" + + def tagged(self, tag: str | None = None) -> str: + chosen = tag or self.tag or "latest" + return f"{self.canonical_repo}:{chosen}" + + +@dataclass(frozen=True) +class CopyOp: + """One declarative Dockerfile COPY operation.""" + + sources: tuple[str, ...] + destination: str + workdir: str + uid: int = 0 + gid: int = 0 + + +@dataclass(frozen=True) +class ParsedDockerfile: + """Structured view of a Dockerfile for classification and OCI layer append.""" + + base_image: str + is_copy_only: bool + reason: str + copy_ops: tuple[CopyOp, ...] = () + workdir: str | None = None + env: dict[str, str] = field(default_factory=dict) + labels: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class ResolvedImage: + """An immutable, verified linux/amd64 OCI image manifest.""" + + image: str + registry_digest: str + index_digest: str | None + config: dict[str, Any] + public_pull_verified: bool = False + tag: str | None = None + + +@dataclass(frozen=True) +class TaskImagePlan: + """Planned image operation for a single Harbor task.""" + + task_id: str + task_dir: Path + action: str # "keep_pinned" | "verify_shared" | "oci_append" | "build" + env_hash: str + reason: str + base_image: str | None = None + existing_docker_image: str | None = None + target_tag: str | None = None + parsed_dockerfile: ParsedDockerfile | None = None + context_files: dict[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class TaskImageReceipt: + """Recorded build/verification result for one Harbor task.""" + + task_id: str + status: str # "resolved" | "built_no_push" | "failed" + action: str + builder: str + env_hash: str + image: str | None = None + registry_digest: str | None = None + tag: str | None = None + config: dict[str, Any] | None = None + public_pull_verified: bool = False + context_files: dict[str, str] = field(default_factory=dict) + job_id: str | None = None + error: str | None = None + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _sha256_bytes(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def _is_localhost(registry: str) -> bool: + host = registry.split(":", 1)[0].lower() + return host in {"localhost", "127.0.0.1", "[::1]", "::1"} + + +def parse_image_ref(raw: str) -> ImageRef: + """Parse an OCI image reference into normalized registry, repo, tag, and digest.""" + value = raw.strip() + if not value or any(ch.isspace() for ch in value): + raise ValueError(f"Invalid OCI image reference: {raw!r}") + + digest: str | None = None + if "@" in value: + value, digest = value.split("@", 1) + if not DIGEST_RE.fullmatch(digest): + raise ValueError(f"Invalid digest in image reference: {raw!r}") + + slash_idx = value.find("/") + colon_idx = value.rfind(":") + tag: str | None = None + if colon_idx != -1 and colon_idx > slash_idx: + tag = value[colon_idx + 1 :] + value = value[:colon_idx] + if not tag: + raise ValueError(f"Empty tag in image reference: {raw!r}") + + parts = value.split("/") + first = parts[0] + if len(parts) == 1 or ( + "." not in first and ":" not in first and first != "localhost" + ): + display_registry = "docker.io" + registry = "registry-1.docker.io" + repository = f"library/{value}" if len(parts) == 1 else value + else: + display_registry = first.lower() + registry = ( + "registry-1.docker.io" + if display_registry in {"docker.io", "index.docker.io"} + else display_registry + ) + repository = "/".join(parts[1:]) + + if not repository or repository.startswith("/") or "//" in repository: + raise ValueError(f"Invalid repository path in image reference: {raw!r}") + + return ImageRef( + registry=registry, + display_registry=display_registry, + repository=repository, + tag=tag, + digest=digest, + ) + + +def sanitize_tag(name: str, *, prefix: str = "") -> str: + """Convert an arbitrary task ID into a valid OCI tag (<= 128 chars).""" + raw = f"{prefix}{name}" + cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "-", raw).lstrip(".-") + if not cleaned: + cleaned = "task" + if len(cleaned) <= 128 and cleaned == raw: + return cleaned + if len(cleaned) > 110: + digest = _sha256_bytes(raw.encode("utf-8"))[:12] + cleaned = f"{cleaned[:110].rstrip('.-')}-{digest}" + elif cleaned != raw: + digest = _sha256_bytes(raw.encode("utf-8"))[:8] + cleaned = f"{cleaned[:118].rstrip('.-')}-{digest}" + return cleaned[:128] + + +def discover_task_dirs(root: Path) -> list[tuple[str, Path]]: + """Return sorted ``(task_id, task_dir)`` pairs for a task or dataset directory.""" + resolved = root.resolve() + if not resolved.is_dir(): + raise FileNotFoundError(f"Task or dataset directory does not exist: {root}") + if (resolved / "task.toml").is_file(): + return [(resolved.name, resolved)] + + task_dirs = _task_dirs_from_directory(resolved, validate=False) + valid = [p for p in task_dirs if (p / "task.toml").is_file()] + if not valid: + raise HarborImageError(f"No Harbor tasks (task.toml) found under {root}") + + base = resolved / "tasks" if (resolved / "tasks").is_dir() else resolved + seen: set[str] = set() + out: list[tuple[str, Path]] = [] + for task_dir in valid: + rel = task_dir.relative_to(base).as_posix() + task_id = rel.replace("/", "__") if "/" in rel else task_dir.name + if task_id in seen: + raise HarborImageError(f"Duplicate task ID discovered: {task_id}") + seen.add(task_id) + out.append((task_id, task_dir)) + return out + + +def _join_dockerfile_lines(text: str) -> list[str]: + """Join backslash-continued Dockerfile lines and strip comments/blanks.""" + logical: list[str] = [] + buf = "" + for raw_line in text.splitlines(): + stripped = raw_line.strip() + if not buf and (not stripped or stripped.startswith("#")): + continue + if buf and stripped.startswith("#"): + # Dockerfile parsers allow comment lines between continuations. + continue + if raw_line.rstrip().endswith("\\"): + buf += raw_line.rstrip()[:-1] + " " + else: + buf += raw_line + if buf.strip(): + logical.append(buf.strip()) + buf = "" + if buf.strip(): + logical.append(buf.strip()) + return logical + + +def _expand_args(value: str, args: dict[str, str]) -> str: + def replace(match: re.Match[str]) -> str: + name = match.group(1) or match.group(2) + return args.get(name, match.group(0)) + + return re.sub( + r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)", replace, value + ) + + +def _parse_chown(spec: str) -> tuple[int, int] | None: + parts = spec.split(":", 1) + uid_str = parts[0] + gid_str = parts[1] if len(parts) == 2 else uid_str + if uid_str.isdigit() and gid_str.isdigit(): + return int(uid_str), int(gid_str) + return None + + +def _parse_kv_pairs(rest: str, args: dict[str, str]) -> dict[str, str]: + tokens = shlex.split(rest) + if not tokens: + return {} + if "=" in tokens[0]: + out: dict[str, str] = {} + for token in tokens: + if "=" not in token: + raise ValueError(f"Malformed KEY=VALUE pair: {rest!r}") + key, val = token.split("=", 1) + out[key] = _expand_args(val, args) + return out + # Legacy single-pair syntax: ENV KEY value with spaces + key, _, val = rest.strip().partition(" ") + return {key: _expand_args(val.strip(), args)} + + +def _normalize_container_path(path: str, workdir: str) -> str: + if path.startswith("/"): + joined = PurePosixPath(path) + else: + joined = PurePosixPath(workdir) / path + parts: list[str] = [] + for part in joined.parts: + if part in {"", "/", "."}: + continue + if part == "..": + if parts: + parts.pop() + else: + parts.append(part) + normalized = "/" + "/".join(parts) + if path.endswith("/") and not normalized.endswith("/"): + normalized += "/" + return normalized + + +def classify_dockerfile(text: str) -> ParsedDockerfile: + """Parse a Dockerfile and decide if pure-Python OCI layer append suffices.""" + instructions = _join_dockerfile_lines(text) + if not instructions: + raise HarborImageError("Dockerfile is empty") + + args: dict[str, str] = {} + from_count = 0 + base_image: str | None = None + is_copy_only = True + reasons: list[str] = [] + workdir = "/" + explicit_workdir: str | None = None + env: dict[str, str] = {} + labels: dict[str, str] = {} + copy_ops: list[CopyOp] = [] + + for line in instructions: + parts = line.split(None, 1) + op = parts[0].upper() + rest = parts[1].strip() if len(parts) > 1 else "" + + if op == "ARG": + if "=" in rest: + key, val = rest.split("=", 1) + args[key.strip()] = _expand_args( + val.strip().strip('"').strip("'"), args + ) + continue + + if op == "FROM": + from_count += 1 + tokens = shlex.split(rest) + filtered: list[str] = [] + idx = 0 + while idx < len(tokens): + tok = tokens[idx] + if tok.startswith("--platform="): + idx += 1 + continue + if tok.upper() == "AS": + # Stage alias is fine for single-stage, multi-stage is caught by from_count > 1. + idx += 2 + continue + filtered.append(tok) + idx += 1 + if not filtered: + raise HarborImageError(f"Malformed FROM instruction: {line!r}") + expanded = _expand_args(filtered[0], args) + if from_count == 1: + base_image = expanded + else: + is_copy_only = False + reasons.append("multi-stage Dockerfile") + continue + + if from_count == 0: + raise HarborImageError(f"Instruction before FROM: {line!r}") + + if op not in _COPY_ONLY_INSTRUCTIONS: + is_copy_only = False + if op not in reasons: + reasons.append(f"contains {op}") + continue + + if op == "WORKDIR": + raw_wd = _expand_args(shlex.split(rest)[0], args) if rest else "/" + workdir = _normalize_container_path(raw_wd, workdir).rstrip("/") or "/" + explicit_workdir = workdir + elif op == "ENV": + try: + env.update(_parse_kv_pairs(rest, args)) + except ValueError: + is_copy_only = False + reasons.append("complex ENV") + elif op == "LABEL": + try: + labels.update(_parse_kv_pairs(rest, args)) + except ValueError: + is_copy_only = False + reasons.append("complex LABEL") + elif op == "EXPOSE": + continue + elif op == "COPY": + uid, gid = 0, 0 + copy_rest = rest + # Strip leading COPY flags like --chown=... or --from=... + flag_tokens: list[str] = [] + while copy_rest.startswith("--"): + tok, _, tail = copy_rest.partition(" ") + flag_tokens.append(tok) + copy_rest = tail.lstrip() + + unsupported_flag = False + for flag in flag_tokens: + if flag.startswith("--chown="): + parsed_ids = _parse_chown(flag.split("=", 1)[1]) + if parsed_ids is None: + is_copy_only = False + unsupported_flag = True + reasons.append(f"non-numeric {flag}") + else: + uid, gid = parsed_ids + elif flag.startswith("--chmod="): + is_copy_only = False + unsupported_flag = True + reasons.append("COPY --chmod") + else: + is_copy_only = False + unsupported_flag = True + reasons.append(f"COPY {flag.split('=', 1)[0]}") + + if copy_rest.startswith("["): + try: + items = json.loads(copy_rest) + except json.JSONDecodeError as exc: + raise HarborImageError( + f"Invalid JSON COPY syntax: {line!r}" + ) from exc + if not isinstance(items, list) or len(items) < 2: + raise HarborImageError(f"Malformed COPY instruction: {line!r}") + items = [_expand_args(str(item), args) for item in items] + else: + items = [_expand_args(tok, args) for tok in shlex.split(copy_rest)] + if len(items) < 2: + raise HarborImageError(f"Malformed COPY instruction: {line!r}") + + if not unsupported_flag: + copy_ops.append( + CopyOp( + sources=tuple(items[:-1]), + destination=items[-1], + workdir=workdir, + uid=uid, + gid=gid, + ) + ) + + if base_image is None: + raise HarborImageError("Dockerfile is missing a FROM instruction") + + reason = ( + "declarative COPY/WORKDIR/ENV only (OCI layer append)" + if is_copy_only + else "; ".join(reasons) + ) + return ParsedDockerfile( + base_image=base_image, + is_copy_only=is_copy_only, + reason=reason, + copy_ops=tuple(copy_ops), + workdir=explicit_workdir, + env=env, + labels=labels, + ) + + +def audit_environment( + task_dir: Path, + *, + extra_dockerfile: str | None = None, +) -> dict[str, str]: + """Audit a task's ``environment/`` directory before building/pushing a public image. + + Returns a mapping of relative POSIX paths in ``environment/`` to their SHA-256 + hex digests. Raises ``HarborImageError`` on any safety or leakage violation. + """ + env_dir = task_dir / "environment" + if not env_dir.is_dir(): + return {} + + problems: list[str] = [] + file_hashes: dict[str, str] = {} + env_blobs: dict[str, bytes] = {} + + for path in sorted(env_dir.rglob("*")): + rel = path.relative_to(env_dir).as_posix() + if path.is_symlink(): + problems.append(f"symlink in environment/: {rel}") + continue + if path.is_dir(): + continue + data = path.read_bytes() + file_hashes[rel] = _sha256_bytes(data) + env_blobs[rel] = data + for label, pattern in _CREDENTIAL_PATTERNS: + if pattern.search(data): + problems.append(f"possible {label} in environment/{rel}") + + dockerfile_path = env_dir / "Dockerfile" + if dockerfile_path.is_file(): + df_text = dockerfile_path.read_text(encoding="utf-8") + if extra_dockerfile: + df_text = df_text.rstrip() + "\n" + extra_dockerfile.strip() + "\n" + for line in _join_dockerfile_lines(df_text): + parts = line.split(None, 1) + op = parts[0].upper() + if op not in {"COPY", "ADD"} or len(parts) < 2: + continue + rest = parts[1].strip() + while rest.startswith("--"): + _, _, rest = rest.partition(" ") + rest = rest.lstrip() + try: + items = json.loads(rest) if rest.startswith("[") else shlex.split(rest) + except (json.JSONDecodeError, ValueError): + items = rest.split() + for src in items[:-1]: + src_str = str(src) + if op == "ADD" and src_str.startswith(("http://", "https://")): + problems.append(f"remote URL in ADD instruction: {src_str}") + posix = PurePosixPath(src_str) + if ".." in posix.parts: + problems.append(f"parent traversal in {op}: {src_str}") + if posix.parts and posix.parts[0] in {"tests", "solution"}: + problems.append(f"Dockerfile {op} references {posix.parts[0]}/") + + # Check against hidden verifier/solution files if present alongside environment/. + tests_dir = task_dir / "tests" + if tests_dir.is_dir(): + hidden_digests: dict[str, str] = {} + for name in _HIDDEN_VERIFIER_FILES: + candidate = tests_dir / name + if candidate.is_file() and not candidate.is_symlink(): + raw = candidate.read_bytes() + if len(raw) >= 32: + hidden_digests[_sha256_bytes(raw)] = f"tests/{name}" + for rel, digest in file_hashes.items(): + if digest in hidden_digests: + problems.append( + f"environment/{rel} matches hidden {hidden_digests[digest]}" + ) + + solution_dir = task_dir / "solution" + if solution_dir.is_dir(): + sol_digests: dict[str, str] = {} + for p in sorted(solution_dir.rglob("*")): + if p.is_file() and not p.is_symlink(): + raw = p.read_bytes() + if len(raw) >= 16: + sol_digests[_sha256_bytes(raw)] = ( + "solution/" + p.relative_to(solution_dir).as_posix() + ) + for rel, digest in file_hashes.items(): + if digest in sol_digests: + problems.append(f"environment/{rel} matches {sol_digests[digest]}") + + if problems: + raise HarborImageError( + f"{task_dir.name}: environment audit failed: {'; '.join(problems)}" + ) + return file_hashes + + +def compute_environment_hash( + task_dir: Path, + *, + extra_dockerfile: str | None = None, + existing_docker_image: str | None = None, +) -> str: + """Deterministic SHA-256 of a task's effective build context.""" + env_dir = task_dir / "environment" + digest = hashlib.sha256() + if extra_dockerfile: + digest.update(b"EXTRA_DOCKERFILE\0") + digest.update(extra_dockerfile.strip().encode("utf-8") + b"\0") + if not env_dir.is_dir() or not (env_dir / "Dockerfile").is_file(): + digest.update(b"SHARED_IMAGE\0") + digest.update((existing_docker_image or "").encode("utf-8") + b"\0") + return digest.hexdigest() + + for path in sorted(env_dir.rglob("*")): + if path.is_dir() or path.is_symlink(): + continue + rel = path.relative_to(env_dir).as_posix() + mode = 0o755 if (path.stat().st_mode & 0o111) else 0o644 + raw = path.read_bytes() + digest.update(f"{rel}\0{mode:o}\0".encode("utf-8")) + digest.update(hashlib.sha256(raw).digest()) + return digest.hexdigest() + + +def _read_docker_config_auth(registry: str) -> tuple[str, str] | None: + """Read inline Basic auth from ~/.docker/config.json if present.""" + config_path = ( + Path(os.environ.get("DOCKER_CONFIG", str(Path.home() / ".docker"))) + / "config.json" + ) + if not config_path.is_file(): + return None + try: + data = json.loads(config_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + auths = data.get("auths") or {} + candidates = [ + registry, + f"https://{registry}", + f"https://{registry}/v1/", + f"https://{registry}/v2/", + ] + if registry in {"registry-1.docker.io", "docker.io"}: + candidates.extend( + [ + "https://index.docker.io/v1/", + "index.docker.io", + "docker.io", + "registry-1.docker.io", + ] + ) + for host in candidates: + entry = auths.get(host) + if isinstance(entry, dict) and entry.get("auth"): + try: + decoded = base64.b64decode(entry["auth"]).decode("utf-8") + if ":" in decoded: + user, pwd = decoded.split(":", 1) + return user, pwd + except Exception: # noqa: BLE001 + continue + return None + + +def resolve_registry_credentials( + registry: str, + *, + username: str | None = None, + password: str | None = None, +) -> tuple[str, str] | None: + """Resolve registry credentials from explicit args, env vars, or Docker config.""" + if username and password: + return username, password + + env_user = os.environ.get("OPENENV_REGISTRY_USERNAME") or os.environ.get( + "REGISTRY_USERNAME" + ) + env_pass = os.environ.get("OPENENV_REGISTRY_PASSWORD") or os.environ.get( + "REGISTRY_PASSWORD" + ) + if env_user and env_pass: + return env_user, env_pass + + if registry == "ghcr.io": + token = ( + password + or os.environ.get("GHCR_TOKEN") + or os.environ.get("CR_PAT") + or os.environ.get("GITHUB_TOKEN") + ) + user = ( + username + or os.environ.get("GHCR_USERNAME") + or os.environ.get("GITHUB_ACTOR") + or os.environ.get("GITHUB_USER") + or "x-access-token" + ) + if token: + return user, token + elif registry in {"registry-1.docker.io", "docker.io"}: + user = username or os.environ.get("DOCKER_USERNAME") + pwd = ( + password + or os.environ.get("DOCKER_PASSWORD") + or os.environ.get("DOCKER_TOKEN") + ) + if user and pwd: + return user, pwd + + return _read_docker_config_auth(registry) + + +def build_docker_config_json(registry: str, username: str, password: str) -> bytes: + """Build a minimal Docker ``config.json`` with Basic auth for one registry.""" + host = ( + "https://index.docker.io/v1/" + if registry == "registry-1.docker.io" + else registry + ) + encoded = base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii") + payload = {"auths": {host: {"auth": encoded}}} + return json.dumps(payload, separators=(",", ":")).encode("utf-8") + + +def _parse_www_authenticate(header: str) -> tuple[str, dict[str, str]]: + header = header.strip() + if " " not in header: + return header.lower(), {} + scheme, rest = header.split(" ", 1) + fields = dict(re.findall(r'(\w+)="([^"]*)"', rest)) + return scheme.lower(), fields + + +class OCIRegistryClient: + """Minimal OCI Distribution v2 client for manifest verification and layer append.""" + + def __init__( + self, + *, + http: httpx.Client | None = None, + username: str | None = None, + password: str | None = None, + anonymous: bool = False, + timeout: float = 60.0, + ) -> None: + self._owns_http = http is None + self._http = http or httpx.Client(timeout=timeout, follow_redirects=False) + self._username = None if anonymous else username + self._password = None if anonymous else password + self._anonymous = anonymous + self._tokens: dict[tuple[str, str], str] = {} + + def close(self) -> None: + if self._owns_http: + self._http.close() + + def __enter__(self) -> "OCIRegistryClient": + return self + + def __exit__(self, *args: Any) -> None: + self.close() + + def _base_url(self, registry: str) -> str: + scheme = "http" if _is_localhost(registry) else "https" + return f"{scheme}://{registry}" + + def _credentials_for(self, registry: str) -> tuple[str, str] | None: + if self._anonymous: + return None + return resolve_registry_credentials( + registry, username=self._username, password=self._password + ) + + def _send_with_redirects( + self, + method: str, + url: str, + *, + headers: dict[str, str] | None = None, + content: bytes | None = None, + params: dict[str, str] | None = None, + auth: httpx.Auth | None = None, + ) -> httpx.Response: + cur_url = url + cur_headers = dict(headers or {}) + cur_params = params + cur_auth = auth + for _ in range(8): + parsed = urlsplit(cur_url) + if parsed.scheme not in {"https", "http"} or ( + parsed.scheme == "http" and not _is_localhost(parsed.netloc) + ): + raise HarborImageError(f"Refusing insecure registry URL: {cur_url}") + req = self._http.build_request( + method, + cur_url, + headers=cur_headers, + content=content, + params=cur_params, + ) + resp = self._http.send(req, auth=cur_auth, follow_redirects=False) + if resp.status_code not in {301, 302, 303, 307, 308}: + return resp + location = resp.headers.get("Location") + if not location: + return resp + dest = urljoin(cur_url, location) + if urlsplit(dest).netloc != parsed.netloc: + cur_headers.pop("Authorization", None) + cur_auth = None + cur_url = dest + cur_params = None + raise HarborImageError(f"Too many redirects requesting {url}") + + def _request( + self, + method: str, + registry: str, + path_or_url: str, + *, + scope_key: str, + headers: dict[str, str] | None = None, + content: bytes | None = None, + params: dict[str, str] | None = None, + ) -> httpx.Response: + url = ( + path_or_url + if path_or_url.startswith(("http://", "https://")) + else f"{self._base_url(registry)}{path_or_url}" + ) + req_headers = dict(headers or {}) + token_cache_key = (registry, scope_key) + cached = self._tokens.get(token_cache_key) + if cached: + req_headers["Authorization"] = cached + + resp = self._send_with_redirects( + method, url, headers=req_headers, content=content, params=params + ) + if resp.status_code != 401: + return resp + + challenge = resp.headers.get("WWW-Authenticate", "") + scheme, fields = _parse_www_authenticate(challenge) + creds = self._credentials_for(registry) + + if scheme == "basic": + if not creds: + return resp + encoded = base64.b64encode(f"{creds[0]}:{creds[1]}".encode("utf-8")).decode( + "ascii" + ) + auth_header = f"Basic {encoded}" + self._tokens[token_cache_key] = auth_header + req_headers["Authorization"] = auth_header + return self._send_with_redirects( + method, url, headers=req_headers, content=content, params=params + ) + + if scheme != "bearer" or "realm" not in fields: + return resp + + token_params: dict[str, str] = {} + if "service" in fields: + token_params["service"] = fields["service"] + if "scope" in fields: + token_params["scope"] = fields["scope"] + + auth_resp = self._send_with_redirects( + "GET", + fields["realm"], + params=token_params, + auth=httpx.BasicAuth(creds[0], creds[1]) if creds else None, + ) + if auth_resp.status_code != 200: + return resp + payload = auth_resp.json() + bearer = payload.get("token") or payload.get("access_token") + if not bearer: + return resp + auth_header = f"Bearer {bearer}" + self._tokens[token_cache_key] = auth_header + req_headers["Authorization"] = auth_header + return self._send_with_redirects( + method, url, headers=req_headers, content=content, params=params + ) + + def _get_manifest_raw( + self, ref: ImageRef, reference: str | None = None + ) -> tuple[str, bytes, str]: + target_ref = reference or ref.reference + resp = self._request( + "GET", + ref.registry, + f"/v2/{ref.repository}/manifests/{target_ref}", + scope_key=f"pull:{ref.repository}", + headers={"Accept": _ACCEPT_MANIFEST}, + ) + if resp.status_code != 200: + raise HarborImageError( + f"Failed to read manifest {ref.canonical_repo}:{target_ref} " + f"(HTTP {resp.status_code})" + ) + raw = resp.content + computed = f"sha256:{_sha256_bytes(raw)}" + header_digest = resp.headers.get("Docker-Content-Digest") + if header_digest and header_digest != computed: + raise HarborImageError( + f"Manifest digest mismatch for {ref.canonical_repo}: " + f"header={header_digest} computed={computed}" + ) + if DIGEST_RE.fullmatch(target_ref) and target_ref != computed: + raise HarborImageError( + f"Pinned manifest digest mismatch for {ref.canonical_repo}@{target_ref}" + ) + media_type = resp.headers.get("Content-Type", "").split(";", 1)[0].strip() + return computed, raw, media_type + + def _get_blob(self, ref: ImageRef, digest: str) -> bytes: + resp = self._request( + "GET", + ref.registry, + f"/v2/{ref.repository}/blobs/{digest}", + scope_key=f"pull:{ref.repository}", + ) + if resp.status_code != 200: + raise HarborImageError( + f"Failed to read blob {ref.canonical_repo}@{digest} " + f"(HTTP {resp.status_code})" + ) + raw = resp.content + if f"sha256:{_sha256_bytes(raw)}" != digest: + raise HarborImageError( + f"Blob digest mismatch for {ref.canonical_repo}@{digest}" + ) + return raw + + def resolve_linux_amd64( + self, image: str | ImageRef + ) -> tuple[ResolvedImage, dict[str, Any], dict[str, Any]]: + """Resolve an image reference to a verified linux/amd64 manifest & config.""" + ref = parse_image_ref(image) if isinstance(image, str) else image + digest, raw, media_type = self._get_manifest_raw(ref) + document = json.loads(raw) + index_digest: str | None = None + + if "manifests" in document: + index_digest = digest + matches = [ + child + for child in document["manifests"] + if child.get("platform", {}).get("os") == "linux" + and child.get("platform", {}).get("architecture") == "amd64" + and not child.get("annotations", {}).get("vnd.docker.reference.type") + ] + if not matches: + raise HarborImageError( + f"Image {ref.canonical_repo}:{ref.reference} has no linux/amd64 manifest" + ) + child = matches[0] + digest, raw, media_type = self._get_manifest_raw(ref, child["digest"]) + if "size" in child and len(raw) != child["size"]: + raise HarborImageError("Child manifest size mismatch") + document = json.loads(raw) + + if document.get("schemaVersion") != 2 or "config" not in document: + raise HarborImageError( + f"Schema-2 OCI/Docker manifest required for {ref.canonical_repo}" + ) + if not document.get("mediaType") and media_type: + document["mediaType"] = media_type + + config_desc = document["config"] + config_raw = self._get_blob(ref, config_desc["digest"]) + if len(config_raw) != config_desc["size"]: + raise HarborImageError("Image config blob size mismatch") + config_doc = json.loads(config_raw) + if config_doc.get("os") != "linux" or config_doc.get("architecture") != "amd64": + raise HarborImageError( + f"Image {ref.canonical_repo}@{digest} is " + f"{config_doc.get('os')}/{config_doc.get('architecture')}, expected linux/amd64" + ) + + resolved = ResolvedImage( + image=ref.pinned(digest), + registry_digest=digest, + index_digest=index_digest, + config={ + "digest": config_desc["digest"], + "sha256": _sha256_bytes(config_raw), + "os": "linux", + "architecture": "amd64", + }, + public_pull_verified=self._anonymous, + tag=ref.tag, + ) + return resolved, document, config_doc + + def _blob_exists(self, ref: ImageRef, digest: str) -> bool: + resp = self._request( + "HEAD", + ref.registry, + f"/v2/{ref.repository}/blobs/{digest}", + scope_key=f"push:{ref.repository}", + ) + return resp.status_code == 200 + + def _mount_blob(self, target: ImageRef, source: ImageRef, digest: str) -> bool: + if target.registry != source.registry: + return False + resp = self._request( + "POST", + target.registry, + f"/v2/{target.repository}/blobs/uploads/", + scope_key=f"push:{target.repository}:pull:{source.repository}", + params={"mount": digest, "from": source.repository}, + ) + return resp.status_code == 201 + + def _upload_blob(self, target: ImageRef, digest: str, data: bytes) -> None: + if self._blob_exists(target, digest): + return + init = self._request( + "POST", + target.registry, + f"/v2/{target.repository}/blobs/uploads/", + scope_key=f"push:{target.repository}", + ) + if init.status_code not in {202, 201}: + raise HarborImageError( + f"Failed to initiate blob upload to {target.canonical_repo} " + f"(HTTP {init.status_code}): {init.text[:300]}" + ) + if init.status_code == 201: + return + location = init.headers.get("Location") + if not location: + raise HarborImageError("Registry did not return upload Location header") + upload_url = urljoin(f"{self._base_url(target.registry)}/", location) + sep = "&" if "?" in upload_url else "?" + final_url = f"{upload_url}{sep}digest={quote(digest, safe=':')}" + put = self._request( + "PUT", + target.registry, + final_url, + scope_key=f"push:{target.repository}", + headers={ + "Content-Type": "application/octet-stream", + "Content-Length": str(len(data)), + }, + content=data, + ) + if put.status_code not in {201, 202}: + raise HarborImageError( + f"Failed to upload blob {digest} to {target.canonical_repo} " + f"(HTTP {put.status_code}): {put.text[:300]}" + ) + + def _put_manifest( + self, target: ImageRef, tag: str, manifest_bytes: bytes, media_type: str + ) -> str: + resp = self._request( + "PUT", + target.registry, + f"/v2/{target.repository}/manifests/{tag}", + scope_key=f"push:{target.repository}", + headers={"Content-Type": media_type}, + content=manifest_bytes, + ) + if resp.status_code not in {200, 201}: + raise HarborImageError( + f"Failed to push manifest {target.tagged(tag)} " + f"(HTTP {resp.status_code}): {resp.text[:300]}" + ) + computed = f"sha256:{_sha256_bytes(manifest_bytes)}" + returned = resp.headers.get("Docker-Content-Digest") + if returned and returned != computed: + raise HarborImageError( + f"Pushed manifest digest mismatch: returned={returned} computed={computed}" + ) + return computed + + def append_layer( + self, + *, + base_image: str, + target_repo: str, + target_tag: str, + layer_tar_gz: bytes | None, + diff_id: str | None, + workdir: str | None = None, + env: dict[str, str] | None = None, + labels: dict[str, str] | None = None, + base_client: "OCIRegistryClient | None" = None, + ) -> ResolvedImage: + """Append a single deterministic layer + config updates to a base image.""" + base_ref = parse_image_ref(base_image) + target_ref = parse_image_ref(target_repo).with_tag(target_tag) + reader = base_client or self + + try: + _, base_manifest, base_config = reader.resolve_linux_amd64(base_ref) + except HarborImageError: + if reader is self: + raise + reader = self + _, base_manifest, base_config = reader.resolve_linux_amd64(base_ref) + manifest_mt = base_manifest.get("mediaType") or _OCI_MANIFEST + is_docker = "docker" in manifest_mt + config_mt = _DOCKER_CONFIG if is_docker else _OCI_CONFIG + layer_mt = _DOCKER_LAYER_GZIP if is_docker else _OCI_LAYER_GZIP + + # Ensure every base layer exists in target_repo (skipping already-present blobs). + layers = list(base_manifest.get("layers", [])) + for layer in layers: + digest = layer["digest"] + if self._blob_exists(target_ref, digest): + continue + if self._mount_blob(target_ref, base_ref, digest): + continue + blob = reader._get_blob(base_ref, digest) + self._upload_blob(target_ref, digest, blob) + + new_config = copy.deepcopy(base_config) + new_config["created"] = "1970-01-01T00:00:00Z" + cfg = new_config.setdefault("config", {}) + if workdir: + cfg["WorkingDir"] = workdir + if env: + existing_env: dict[str, str] = {} + for entry in cfg.get("Env") or []: + k, _, v = entry.partition("=") + existing_env[k] = v + existing_env.update(env) + cfg["Env"] = [f"{k}={v}" for k, v in sorted(existing_env.items())] + if labels: + existing_labels = dict(cfg.get("Labels") or {}) + existing_labels.update(labels) + cfg["Labels"] = existing_labels + + history = list(new_config.get("history") or []) + if layer_tar_gz is not None and diff_id is not None: + layer_digest = f"sha256:{_sha256_bytes(layer_tar_gz)}" + self._upload_blob(target_ref, layer_digest, layer_tar_gz) + layers.append( + { + "mediaType": layer_mt, + "size": len(layer_tar_gz), + "digest": layer_digest, + } + ) + new_config.setdefault("rootfs", {"type": "layers", "diff_ids": []}) + new_config["rootfs"]["diff_ids"].append(diff_id) + history.append( + { + "created": "1970-01-01T00:00:00Z", + "created_by": "openenv harbor build-images (oci-append)", + } + ) + else: + history.append( + { + "created": "1970-01-01T00:00:00Z", + "created_by": "openenv harbor build-images (config-only)", + "empty_layer": True, + } + ) + new_config["history"] = history + + config_bytes = json.dumps( + new_config, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + config_digest = f"sha256:{_sha256_bytes(config_bytes)}" + self._upload_blob(target_ref, config_digest, config_bytes) + + new_manifest = { + "schemaVersion": 2, + "mediaType": _DOCKER_MANIFEST_V2 if is_docker else _OCI_MANIFEST, + "config": { + "mediaType": config_mt, + "size": len(config_bytes), + "digest": config_digest, + }, + "layers": layers, + } + manifest_bytes = json.dumps( + new_manifest, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + manifest_digest = self._put_manifest( + target_ref, + target_tag, + manifest_bytes, + new_manifest["mediaType"], + ) + return ResolvedImage( + image=target_ref.pinned(manifest_digest), + registry_digest=manifest_digest, + index_digest=None, + config={ + "digest": config_digest, + "sha256": _sha256_bytes(config_bytes), + "os": "linux", + "architecture": "amd64", + }, + public_pull_verified=False, + tag=target_tag, + ) + + +def _resolve_copy_sources(context_dir: Path, pattern: str) -> list[Path]: + clean = pattern.lstrip("/") + if clean in {".", ""}: + return [context_dir] + if any(ch in clean for ch in ("*", "?", "[")): + matched = sorted( + p + for p in context_dir.rglob("*") + if fnmatch.fnmatch(p.relative_to(context_dir).as_posix(), clean) + ) + if not matched: + raise HarborImageError(f"COPY pattern matched no files: {pattern!r}") + return matched + candidate = (context_dir / clean).resolve() + ctx_resolved = context_dir.resolve() + if not (candidate == ctx_resolved or candidate.is_relative_to(ctx_resolved)): + raise HarborImageError(f"COPY source escapes build context: {pattern!r}") + if not candidate.exists(): + raise HarborImageError(f"COPY source not found in environment/: {pattern!r}") + return [candidate] + + +def build_copy_layer_tar( + context_dir: Path, copy_ops: tuple[CopyOp, ...] +) -> tuple[bytes | None, str | None]: + """Create a deterministic gzipped OCI layer tar for declarative COPY operations. + + Returns ``(gz_bytes, diff_id)`` where ``diff_id`` is ``sha256:``, + or ``(None, None)`` when there are no COPY operations. + """ + if not copy_ops: + return None, None + + entries: dict[str, tuple[str, bytes | None, int, int, int]] = {} + # path -> ("dir"|"file", bytes|None, mode, uid, gid) + + def ensure_parents(rel_posix: str, uid: int, gid: int) -> None: + parts = PurePosixPath(rel_posix).parts[:-1] + cur = "" + for part in parts: + cur = f"{cur}/{part}" if cur else part + entries.setdefault(cur, ("dir", None, 0o755, uid, gid)) + + for op in copy_ops: + dest_norm = _normalize_container_path(op.destination, op.workdir) + dest_is_dir = dest_norm.endswith("/") or len(op.sources) > 1 + dest_rel = dest_norm.strip("/") + + resolved_sources: list[Path] = [] + for src in op.sources: + resolved_sources.extend(_resolve_copy_sources(context_dir, src)) + + if len(resolved_sources) > 1: + dest_is_dir = True + + for src_path in resolved_sources: + if src_path.is_dir(): + if dest_rel: + ensure_parents(dest_rel + "/_", op.uid, op.gid) + for child in sorted(src_path.rglob("*")): + if child.is_symlink(): + raise HarborImageError( + f"Symlink not allowed in COPY source: {child}" + ) + sub = child.relative_to(src_path).as_posix() + target = f"{dest_rel}/{sub}" if dest_rel else sub + if child.is_dir(): + ensure_parents(target + "/_", op.uid, op.gid) + entries[target] = ("dir", None, 0o755, op.uid, op.gid) + else: + ensure_parents(target, op.uid, op.gid) + mode = 0o755 if (child.stat().st_mode & 0o111) else 0o644 + entries[target] = ( + "file", + child.read_bytes(), + mode, + op.uid, + op.gid, + ) + else: + target = ( + f"{dest_rel}/{src_path.name}" + if (dest_is_dir and dest_rel) + else (src_path.name if dest_is_dir else dest_rel) + ) + ensure_parents(target, op.uid, op.gid) + mode = 0o755 if (src_path.stat().st_mode & 0o111) else 0o644 + entries[target] = ( + "file", + src_path.read_bytes(), + mode, + op.uid, + op.gid, + ) + + raw_buf = io.BytesIO() + with tarfile.open(fileobj=raw_buf, mode="w", format=tarfile.PAX_FORMAT) as tar: + for path in sorted(entries): + kind, data, mode, uid, gid = entries[path] + info = tarfile.TarInfo(name=path) + info.uid = uid + info.gid = gid + info.uname = "" + info.gname = "" + info.mtime = 0 + info.mode = mode + if kind == "dir": + info.type = tarfile.DIRTYPE + tar.addfile(info) + else: + assert data is not None + info.type = tarfile.REGTYPE + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + + raw_bytes = raw_buf.getvalue() + diff_id = f"sha256:{_sha256_bytes(raw_bytes)}" + gz_buf = io.BytesIO() + with gzip.GzipFile( + filename="", mode="wb", fileobj=gz_buf, compresslevel=6, mtime=0 + ) as gz: + gz.write(raw_bytes) + return gz_buf.getvalue(), diff_id + + +def pack_build_context_tar_gz( + env_dir: Path, *, extra_dockerfile: str | None = None +) -> bytes: + """Pack an audited ``environment/`` directory into a deterministic ``.tar.gz``.""" + buf = io.BytesIO() + with gzip.GzipFile( + filename="", mode="wb", fileobj=buf, compresslevel=6, mtime=0 + ) as gz: + with tarfile.open(fileobj=gz, mode="w", format=tarfile.PAX_FORMAT) as tar: + for path in sorted(env_dir.rglob("*")): + if path.is_symlink() or path.is_dir(): + continue + rel = path.relative_to(env_dir).as_posix() + data = path.read_bytes() + if rel == "Dockerfile" and extra_dockerfile: + data = ( + data.decode("utf-8").rstrip() + + "\n" + + extra_dockerfile.strip() + + "\n" + ).encode("utf-8") + info = tarfile.TarInfo(name=rel) + info.size = len(data) + info.mode = 0o755 if (path.stat().st_mode & 0o111) else 0o644 + info.uid = 0 + info.gid = 0 + info.uname = "" + info.gname = "" + info.mtime = 0 + tar.addfile(info, io.BytesIO(data)) + return buf.getvalue() + + +def parse_kaniko_digest(logs: str) -> str: + """Extract the pinned ``sha256:...`` digest emitted by our Kaniko job wrapper.""" + matches = re.findall( + rf"{re.escape(KANIKO_DIGEST_MARKER)}(sha256:[0-9a-f]{{64}})", logs + ) + if not matches: + raise HarborImageError( + "Kaniko job finished without reporting a valid image digest" + ) + return matches[-1] + + +class KanikoHFJobsBuilder: + """Build and push Dockerfiles via Kaniko running inside Hugging Face Jobs.""" + + def __init__( + self, + *, + namespace: str | None = None, + flavor: str = "cpu-basic", + timeout: str = "30m", + kaniko_image: str = DEFAULT_KANIKO_IMAGE, + bucket_name: str = "openenv-kaniko-builds", + cache_repo: str | None = None, + poll_interval_s: float = 5.0, + no_push: bool = False, + hf_token: str | None = None, + api: Any | None = None, + ) -> None: + self.namespace = namespace + self.flavor = flavor + self.timeout = timeout + self.kaniko_image = kaniko_image + self.bucket_name = bucket_name + self.cache_repo = cache_repo + self.poll_interval_s = poll_interval_s + self.no_push = no_push + self.hf_token = hf_token + self._api = api + self._bucket_ready = False + self._bucket_lock = threading.Lock() + + def _get_api(self) -> Any: + if self._api is None: + from huggingface_hub import HfApi + + self._api = HfApi(token=self.hf_token) + return self._api + + def _effective_namespace(self) -> str: + with self._bucket_lock: + if self.namespace: + return self.namespace + who = self._get_api().whoami() + name = ( + who.get("name") if isinstance(who, dict) else getattr(who, "name", None) + ) + if not name: + raise HarborImageError( + "Could not determine Hugging Face namespace; pass --namespace" + ) + self.namespace = name + return name + + def _ensure_bucket(self) -> str: + ns = self._effective_namespace() + bucket_id = ( + self.bucket_name if "/" in self.bucket_name else f"{ns}/{self.bucket_name}" + ) + with self._bucket_lock: + if not self._bucket_ready: + self._get_api().create_bucket(bucket_id, private=True, exist_ok=True) + self._bucket_ready = True + return bucket_id + + def build_command( + self, + *, + context_filename: str, + destination: str, + has_auth_secret: bool, + ) -> list[str]: + """Build the ``/busybox/sh -c`` command executed inside the Kaniko HF Job.""" + kaniko_args = [ + "/kaniko/executor", + f"--context=tar:///context/{context_filename}", + "--dockerfile=Dockerfile", + f"--destination={destination}", + "--custom-platform=linux/amd64", + "--reproducible", + "--digest-file=/tmp/digest", + ] + if self.no_push: + kaniko_args.append("--no-push") + if self.cache_repo: + kaniko_args.extend( + [ + "--cache=true", + f"--cache-repo={self.cache_repo}", + "--cache-copy-layers", + ] + ) + + steps = ["set -eu"] + if has_auth_secret: + steps.extend( + [ + "umask 077", + "/busybox/mkdir -p /kaniko/.docker", + 'printf "%s" "$KANIKO_DOCKER_CONFIG_B64" | /busybox/base64 -d > /kaniko/.docker/config.json', + "unset KANIKO_DOCKER_CONFIG_B64", + ] + ) + steps.append(" ".join(shlex.quote(arg) for arg in kaniko_args)) + steps.append(f'printf "\\n{KANIKO_DIGEST_MARKER}%s\\n" "$(cat /tmp/digest)"') + return ["/busybox/sh", "-c", " && ".join(steps)] + + def build( + self, + *, + env_dir: Path, + env_hash: str, + target_repo: str, + target_tag: str, + extra_dockerfile: str | None = None, + registry_username: str | None = None, + registry_password: str | None = None, + ) -> tuple[str, str]: + """Run one Kaniko build on HF Jobs and return ``(digest, job_id)``.""" + from huggingface_hub import Volume + + api = self._get_api() + namespace = self._effective_namespace() + bucket_id = self._ensure_bucket() + target_ref = parse_image_ref(target_repo) + destination = target_ref.tagged(target_tag) + + secrets: dict[str, str] = {} + if not self.no_push: + creds = resolve_registry_credentials( + target_ref.registry, + username=registry_username, + password=registry_password, + ) + if not creds: + raise HarborImageError( + f"No push credentials found for {target_ref.registry}. " + "Set GHCR_TOKEN / REGISTRY_PASSWORD or pass --registry-user / --registry-password." + ) + cfg_bytes = build_docker_config_json( + target_ref.registry, creds[0], creds[1] + ) + secrets["KANIKO_DOCKER_CONFIG_B64"] = base64.b64encode(cfg_bytes).decode( + "ascii" + ) + + run_id = uuid.uuid4().hex[:12] + context_filename = f"{env_hash[:16]}.tar.gz" + bucket_folder = f"contexts/{run_id}" + bucket_path = f"{bucket_folder}/{context_filename}" + tar_bytes = pack_build_context_tar_gz( + env_dir, extra_dockerfile=extra_dockerfile + ) + api.batch_bucket_files(bucket_id, add=[(tar_bytes, bucket_path)]) + + job_id = "" + try: + command = self.build_command( + context_filename=context_filename, + destination=destination, + has_auth_secret=bool(secrets), + ) + job = api.run_job( + image=self.kaniko_image, + command=command, + secrets=secrets or None, + flavor=self.flavor, + timeout=self.timeout, + namespace=namespace, + name=f"openenv-kaniko-{env_hash[:10]}", + labels={ + "openenv-harbor-build": run_id, + "openenv-env-hash": env_hash[:16], + }, + volumes=[ + Volume( + type="bucket", + source=bucket_id, + mount_path="/context", + read_only=True, + path=bucket_folder, + ) + ], + ) + job_id = job.id + transient_errors = 0 + while True: + try: + info = api.inspect_job(job_id=job_id, namespace=namespace) + transient_errors = 0 + except Exception: # noqa: BLE001 - retry transient Hub polling glitches + transient_errors += 1 + if transient_errors > 5: + raise + time.sleep(min(30.0, self.poll_interval_s * transient_errors)) + continue + stage = getattr(getattr(info, "status", None), "stage", None) + if stage == "COMPLETED": + break + if stage in {"ERROR", "CANCELED", "CANCELLED", "TIMEOUT", "FAILED"}: + tail = "\n".join( + list( + api.fetch_job_logs( + job_id=job_id, namespace=namespace, follow=False + ) + )[-40:] + ) + raise HarborImageError( + f"Kaniko HF Job {job_id} ended with stage={stage}:\n{tail}" + ) + time.sleep(self.poll_interval_s) + + logs = "\n".join( + api.fetch_job_logs(job_id=job_id, namespace=namespace, follow=False) + ) + digest = parse_kaniko_digest(logs) + return digest, job_id + finally: + try: + api.batch_bucket_files(bucket_id, delete=[bucket_path]) + except Exception: # noqa: BLE001 - best-effort cleanup of temp context + pass + + +class DockerBuildxBuilder: + """Build and push Dockerfiles via local or VM ``docker buildx build``.""" + + def __init__( + self, + *, + cache_repo: str | None = None, + no_push: bool = False, + timeout_s: int = 2400, + ) -> None: + self.cache_repo = cache_repo + self.no_push = no_push + self.timeout_s = timeout_s + + def build( + self, + *, + env_dir: Path, + env_hash: str, # noqa: ARG002 - parity with KanikoHFJobsBuilder + target_repo: str, + target_tag: str, + extra_dockerfile: str | None = None, + registry_username: str | None = None, # noqa: ARG002 + registry_password: str | None = None, # noqa: ARG002 + ) -> tuple[str, str | None]: + target_ref = parse_image_ref(target_repo) + destination = target_ref.tagged(target_tag) + + with tempfile.TemporaryDirectory(prefix="openenv-buildx-") as tmp_str: + tmp = Path(tmp_str) + stage_dir = tmp / "context" + shutil.copytree(env_dir, stage_dir) + if extra_dockerfile: + df = stage_dir / "Dockerfile" + df.write_text( + df.read_text(encoding="utf-8").rstrip() + + "\n" + + extra_dockerfile.strip() + + "\n", + encoding="utf-8", + ) + meta_path = tmp / "metadata.json" + cmd = [ + "docker", + "buildx", + "build", + "--platform", + "linux/amd64", + "--provenance=false", + "--metadata-file", + str(meta_path), + "-t", + destination, + ] + if self.cache_repo: + cmd.extend( + [ + "--cache-from", + f"type=registry,ref={self.cache_repo}", + "--cache-to", + f"type=registry,ref={self.cache_repo},mode=max", + ] + ) + if self.no_push: + cmd.append("--load") + else: + cmd.append("--push") + cmd.append(str(stage_dir)) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=self.timeout_s, + check=False, + ) + if result.returncode != 0: + tail = (result.stderr or result.stdout)[-1200:] + raise HarborImageError( + f"docker buildx build failed for {destination}:\n{tail}" + ) + meta = json.loads(meta_path.read_text(encoding="utf-8")) + digest = meta.get("containerimage.digest") or meta.get( + "containerimage.config.digest" + ) + if not digest or not DIGEST_RE.fullmatch(digest): + raise HarborImageError( + f"docker buildx metadata missing valid containerimage.digest: {meta}" + ) + return digest, None + + +def update_task_toml( + task_toml_path: Path, + *, + docker_image: str, + workdir: str | None = None, +) -> str: + """Set ``[environment].docker_image`` (and optional ``workdir``) in ``task.toml``. + + Preserves surrounding formatting and validates the resulting TOML document. + """ + original = task_toml_path.read_text(encoding="utf-8") + # Confirm input parses cleanly before editing. + tomllib.loads(original) + + lines = original.splitlines(keepends=True) + env_start: int | None = None + env_end = len(lines) + section_re = re.compile(r"^\s*\[([^\]]+)\]\s*(?:#.*)?$") + key_re = re.compile(r"^(\s*)([A-Za-z0-9_-]+)\s*=") + + for idx, line in enumerate(lines): + m = section_re.match(line) + if m: + section = m.group(1).strip() + if section == "environment" and env_start is None: + env_start = idx + elif env_start is not None: + env_end = idx + break + + image_line = f"docker_image = {json.dumps(docker_image)}\n" + workdir_line = f"workdir = {json.dumps(workdir)}\n" if workdir is not None else None + + if env_start is None: + suffix = "" if (not original or original.endswith("\n")) else "\n" + addition = f"{suffix}\n[environment]\n{image_line}" + if workdir_line: + addition += workdir_line + updated = original + addition + else: + body = list(lines[env_start + 1 : env_end]) + replaced_image = False + replaced_workdir = False + for i, line in enumerate(body): + km = key_re.match(line) + if not km: + continue + key = km.group(2) + if key == "docker_image": + body[i] = f"{km.group(1)}{image_line}" + replaced_image = True + elif key == "workdir" and workdir_line is not None: + body[i] = f"{km.group(1)}{workdir_line}" + replaced_workdir = True + if not replaced_image: + body.insert(0, image_line) + if workdir_line is not None and not replaced_workdir: + body.insert(1, workdir_line) + updated = "".join(lines[: env_start + 1] + body + lines[env_end:]) + + parsed = tomllib.loads(updated) + if parsed.get("environment", {}).get("docker_image") != docker_image: + raise HarborImageError(f"Failed to update docker_image in {task_toml_path}") + if workdir is not None and parsed.get("environment", {}).get("workdir") != workdir: + raise HarborImageError(f"Failed to update workdir in {task_toml_path}") + + task_toml_path.write_text(updated, encoding="utf-8") + return updated + + +def plan_harbor_images( + root: Path, + *, + registry: str | None = None, + tag_prefix: str = "", + extra_dockerfile: str | None = None, + skip_pinned: bool = True, + allow_oci_append: bool = True, + task_ids: list[str] | None = None, +) -> list[TaskImagePlan]: + """Audit, classify, and plan image operations for every Harbor task under ``root``.""" + tasks = discover_task_dirs(root) + if task_ids is not None: + wanted = set(task_ids) + tasks = [(tid, tdir) for tid, tdir in tasks if tid in wanted] + missing = sorted(wanted - {tid for tid, _ in tasks}) + if missing: + raise HarborImageError( + f"Requested task ID(s) not found under {root}: {missing}" + ) + plans: list[TaskImagePlan] = [] + + for task_id, task_dir in tasks: + cfg = tomllib.loads((task_dir / "task.toml").read_text(encoding="utf-8")) + env_cfg = cfg.get("environment") or {} + existing = env_cfg.get("docker_image") + dockerfile_path = task_dir / "environment" / "Dockerfile" + has_dockerfile = dockerfile_path.is_file() + + context_files = audit_environment(task_dir, extra_dockerfile=extra_dockerfile) + env_hash = compute_environment_hash( + task_dir, + extra_dockerfile=extra_dockerfile, + existing_docker_image=existing, + ) + + if not has_dockerfile: + if not existing: + raise HarborImageError( + f"{task_id}: has neither environment/Dockerfile nor [environment].docker_image" + ) + action = ( + "keep_pinned" + if (skip_pinned and PINNED_IMAGE_RE.fullmatch(existing)) + else "verify_shared" + ) + plans.append( + TaskImagePlan( + task_id=task_id, + task_dir=task_dir, + action=action, + env_hash=env_hash, + reason=( + "already digest-pinned shared image (no Dockerfile)" + if action == "keep_pinned" + else "shared image without Dockerfile; resolve and pin linux/amd64 digest" + ), + base_image=existing, + existing_docker_image=existing, + context_files=context_files, + ) + ) + continue + + if ( + skip_pinned + and existing + and PINNED_IMAGE_RE.fullmatch(existing) + and not extra_dockerfile + ): + plans.append( + TaskImagePlan( + task_id=task_id, + task_dir=task_dir, + action="keep_pinned", + env_hash=env_hash, + reason="task.toml already has a digest-pinned docker_image", + base_image=existing, + existing_docker_image=existing, + context_files=context_files, + ) + ) + continue + + df_text = dockerfile_path.read_text(encoding="utf-8") + if extra_dockerfile: + df_text = df_text.rstrip() + "\n" + extra_dockerfile.strip() + "\n" + parsed = classify_dockerfile(df_text) + action = "oci_append" if (allow_oci_append and parsed.is_copy_only) else "build" + target_tag = sanitize_tag(task_id, prefix=tag_prefix) + if registry is not None: + parse_image_ref(registry) # validate target registry early + + plans.append( + TaskImagePlan( + task_id=task_id, + task_dir=task_dir, + action=action, + env_hash=env_hash, + reason=parsed.reason, + base_image=parsed.base_image, + existing_docker_image=existing, + target_tag=target_tag, + parsed_dockerfile=parsed, + context_files=context_files, + ) + ) + + return plans + + +def verify_harbor_images( + root: Path, + *, + anonymous: bool = True, + require_digest_pin: bool = False, + concurrency: int = 8, + registry_client: OCIRegistryClient | None = None, +) -> dict[str, Any]: + """Verify every Harbor task's ``docker_image`` is pullable as ``linux/amd64``.""" + tasks = discover_task_dirs(root) + results: dict[str, dict[str, Any]] = {} + + def check_one(item: tuple[str, Path]) -> tuple[str, dict[str, Any]]: + task_id, task_dir = item + cfg = tomllib.loads((task_dir / "task.toml").read_text(encoding="utf-8")) + image = (cfg.get("environment") or {}).get("docker_image") + if not image: + return task_id, { + "ok": False, + "image": None, + "error": "missing [environment].docker_image in task.toml", + } + if require_digest_pin and not PINNED_IMAGE_RE.fullmatch(image): + return task_id, { + "ok": False, + "image": image, + "error": "docker_image is not pinned to a @sha256 digest", + } + client = registry_client or OCIRegistryClient(anonymous=anonymous) + try: + resolved, _, _ = client.resolve_linux_amd64(image) + return task_id, { + "ok": True, + "image": image, + "pinned_image": resolved.image, + "registry_digest": resolved.registry_digest, + "public_pull_verified": resolved.public_pull_verified, + } + except Exception as exc: # noqa: BLE001 + return task_id, {"ok": False, "image": image, "error": str(exc)} + finally: + if registry_client is None: + client.close() + + with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool: + for task_id, rec in pool.map(check_one, tasks): + results[task_id] = rec + + ok_count = sum(1 for r in results.values() if r["ok"]) + return { + "total": len(results), + "ok": ok_count, + "failed": len(results) - ok_count, + "tasks": results, + } + + +def build_harbor_images( + root: Path, + *, + registry: str | None = None, + builder: str = "auto", + output_dir: Path | None = None, + in_place: bool = False, + receipts_path: Path | None = None, + per_task_receipts_dir: Path | None = None, + task_ids: list[str] | None = None, + tag_prefix: str = "", + extra_dockerfile: str | None = None, + skip_pinned: bool = True, + allow_oci_append: bool = True, + strip_dockerfile_for_shared: bool = False, + verify_public: bool = True, + no_push: bool = False, + concurrency: int = 4, + namespace: str | None = None, + flavor: str = "cpu-basic", + timeout: str = "30m", + kaniko_image: str = DEFAULT_KANIKO_IMAGE, + bucket_name: str = "openenv-kaniko-builds", + cache_repo: str | None = None, + registry_username: str | None = None, + registry_password: str | None = None, + run_builder: Any | None = None, + registry_client: OCIRegistryClient | None = None, + public_client: OCIRegistryClient | None = None, + progress: Callable[[str], None] | None = None, +) -> dict[str, Any]: + """Build/append/verify OCI images for Harbor tasks and stamp ``task.toml`` pins.""" + if builder not in {"auto", "kaniko", "docker", "oci-append"}: + raise ValueError(f"Unsupported builder: {builder!r}") + if output_dir is not None and in_place: + raise ValueError("Pass either output_dir or in_place, not both") + + plans = plan_harbor_images( + root, + registry=registry, + tag_prefix=tag_prefix, + extra_dockerfile=extra_dockerfile, + skip_pinned=skip_pinned, + allow_oci_append=allow_oci_append, + task_ids=task_ids, + ) + + needs_registry = any(p.action in {"oci_append", "build"} for p in plans) + if needs_registry and not registry and not no_push: + raise HarborImageError( + "A target --registry (e.g. ghcr.io/your-org/your-repo) is required to push built images" + ) + effective_registry = registry or "ghcr.io/local/no-push" + + # Load resumable receipts if present (single manifest and/or per-task directory). + prior_receipts: dict[str, dict[str, Any]] = {} + if receipts_path and receipts_path.is_file(): + loaded = json.loads(receipts_path.read_text(encoding="utf-8")) + prior_receipts.update( + loaded.get("tasks", loaded) if isinstance(loaded, dict) else {} + ) + if per_task_receipts_dir and per_task_receipts_dir.is_dir(): + for p in sorted(per_task_receipts_dir.glob("*.json")): + try: + rec = json.loads(p.read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + if isinstance(rec, dict) and rec.get("task_id"): + prior_receipts[rec["task_id"]] = rec + + # Choose RUN builder lazily only if needed. + needs_run_builder = any(p.action == "build" for p in plans) + active_run_builder = run_builder + active_builder_name = builder + if needs_run_builder and active_run_builder is None: + if builder == "oci-append": + run_tasks = [p.task_id for p in plans if p.action == "build"] + raise HarborImageError( + f"Tasks require RUN instructions (cannot use --builder oci-append): {run_tasks[:5]}" + ) + chosen = builder + if chosen == "auto": + chosen = ( + "kaniko" if (namespace or shutil.which("docker") is None) else "docker" + ) + active_builder_name = chosen + if chosen == "kaniko": + active_run_builder = KanikoHFJobsBuilder( + namespace=namespace, + flavor=flavor, + timeout=timeout, + kaniko_image=kaniko_image, + bucket_name=bucket_name, + cache_repo=cache_repo, + no_push=no_push, + ) + else: + active_run_builder = DockerBuildxBuilder( + cache_repo=cache_repo, + no_push=no_push, + ) + + # Deduplicate work by (action, env_hash). + groups: dict[tuple[str, str], list[TaskImagePlan]] = {} + for plan in plans: + groups.setdefault((plan.action, plan.env_hash), []).append(plan) + + own_reg = registry_client is None + own_pub = public_client is None + reg_client = registry_client or OCIRegistryClient( + username=registry_username, password=registry_password + ) + pub_client = public_client or OCIRegistryClient(anonymous=True) + + receipts_by_task: dict[str, TaskImageReceipt] = {} + + def verify_pinned(image_ref: str) -> ResolvedImage: + verifier = pub_client if verify_public else reg_client + resolved, _, _ = verifier.resolve_linux_amd64(image_ref) + return resolved + + def execute_group( + key: tuple[str, str], members: list[TaskImagePlan] + ) -> list[TaskImageReceipt]: + action, env_hash = key + rep = members[0] + + # Check resumable cache on representative task. + cached = prior_receipts.get(rep.task_id) + if ( + not no_push + and isinstance(cached, dict) + and cached.get("status") == "resolved" + and cached.get("env_hash") == env_hash + and cached.get("image") + and ( + action in {"keep_pinned", "verify_shared"} + or cached["image"].startswith( + parse_image_ref(effective_registry).canonical_repo + "@" + ) + ) + ): + if progress: + progress( + f"reuse {rep.task_id} ({len(members)} task(s)) -> {cached['image']}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="resolved", + action=m.action, + builder=cached.get("builder", "cached"), + env_hash=m.env_hash, + image=cached["image"], + registry_digest=cached.get("registry_digest"), + tag=cached.get("tag"), + config=cached.get("config"), + public_pull_verified=bool(cached.get("public_pull_verified")), + context_files=m.context_files, + job_id=cached.get("job_id"), + ) + for m in members + ] + + try: + if action in {"keep_pinned", "verify_shared"}: + assert rep.base_image is not None + resolved = verify_pinned(rep.base_image) + if progress: + progress( + f"verify {rep.task_id} ({len(members)} task(s)) -> {resolved.image}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="resolved", + action=m.action, + builder="verify", + env_hash=m.env_hash, + image=resolved.image, + registry_digest=resolved.registry_digest, + tag=resolved.tag, + config=resolved.config, + public_pull_verified=resolved.public_pull_verified, + context_files=m.context_files, + ) + for m in members + ] + + tag = rep.target_tag or sanitize_tag(rep.task_id, prefix=tag_prefix) + if len(members) > 1: + tag = sanitize_tag(f"env-{env_hash[:12]}", prefix=tag_prefix) + + if action == "oci_append": + assert rep.parsed_dockerfile is not None + layer_gz, diff_id = build_copy_layer_tar( + rep.task_dir / "environment", rep.parsed_dockerfile.copy_ops + ) + if no_push: + if progress: + progress( + f"dry-oci {rep.task_id} ({len(members)} task(s)) diff={diff_id}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="built_no_push", + action=m.action, + builder="oci-append", + env_hash=m.env_hash, + registry_digest=diff_id, + tag=tag, + context_files=m.context_files, + ) + for m in members + ] + pushed = reg_client.append_layer( + base_image=rep.parsed_dockerfile.base_image, + target_repo=effective_registry, + target_tag=tag, + layer_tar_gz=layer_gz, + diff_id=diff_id, + workdir=rep.parsed_dockerfile.workdir, + env=rep.parsed_dockerfile.env or None, + labels=rep.parsed_dockerfile.labels or None, + base_client=pub_client, + ) + resolved = verify_pinned(pushed.image) + if progress: + progress( + f"append {rep.task_id} ({len(members)} task(s)) -> {resolved.image}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="resolved", + action=m.action, + builder="oci-append", + env_hash=m.env_hash, + image=resolved.image, + registry_digest=resolved.registry_digest, + tag=tag, + config=resolved.config, + public_pull_verified=resolved.public_pull_verified, + context_files=m.context_files, + ) + for m in members + ] + + # Full RUN build (Kaniko on HF Jobs or Docker Buildx) + assert active_run_builder is not None + digest, job_id = active_run_builder.build( + env_dir=rep.task_dir / "environment", + env_hash=env_hash, + target_repo=effective_registry, + target_tag=tag, + extra_dockerfile=extra_dockerfile, + registry_username=registry_username, + registry_password=registry_password, + ) + if no_push: + if progress: + progress( + f"built {rep.task_id} ({len(members)} task(s)) digest={digest}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="built_no_push", + action=m.action, + builder=active_builder_name, + env_hash=m.env_hash, + registry_digest=digest, + tag=tag, + context_files=m.context_files, + job_id=job_id, + ) + for m in members + ] + pinned = parse_image_ref(effective_registry).pinned(digest) + resolved = verify_pinned(pinned) + if progress: + progress( + f"built {rep.task_id} ({len(members)} task(s)) -> {resolved.image}" + ) + return [ + TaskImageReceipt( + task_id=m.task_id, + status="resolved", + action=m.action, + builder=active_builder_name, + env_hash=m.env_hash, + image=resolved.image, + registry_digest=resolved.registry_digest, + tag=tag, + config=resolved.config, + public_pull_verified=resolved.public_pull_verified, + context_files=m.context_files, + job_id=job_id, + ) + for m in members + ] + except Exception as exc: # noqa: BLE001 + if progress: + progress(f"FAIL {rep.task_id}: {exc}") + return [ + TaskImageReceipt( + task_id=m.task_id, + status="failed", + action=m.action, + builder="oci-append" + if action == "oci_append" + else active_builder_name, + env_hash=m.env_hash, + context_files=m.context_files, + error=str(exc), + ) + for m in members + ] + + def _persist_per_task_receipt(receipt: TaskImageReceipt) -> None: + if per_task_receipts_dir is None: + return + per_task_receipts_dir.mkdir(parents=True, exist_ok=True) + dest = per_task_receipts_dir / f"{receipt.task_id}.json" + tmp = dest.with_suffix(".json.tmp") + tmp.write_text( + json.dumps(receipt.to_dict(), indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + tmp.replace(dest) + + try: + with ThreadPoolExecutor(max_workers=max(1, concurrency)) as pool: + futures = [ + pool.submit(execute_group, key, members) + for key, members in groups.items() + ] + for fut in as_completed(futures): + for receipt in fut.result(): + receipts_by_task[receipt.task_id] = receipt + _persist_per_task_receipt(receipt) + finally: + if own_reg: + reg_client.close() + if own_pub: + pub_client.close() + + # Materialize updated task.toml files when output_dir or in_place is requested. + if not no_push and (output_dir is not None or in_place): + for plan in plans: + rec = receipts_by_task[plan.task_id] + if rec.status != "resolved" or not rec.image: + continue + if output_dir is not None: + dest_dir = ( + output_dir + if (root.resolve() / "task.toml").is_file() + else output_dir / "tasks" / plan.task_id + ) + if dest_dir.exists(): + shutil.rmtree(dest_dir) + shutil.copytree(plan.task_dir, dest_dir) + target_task_dir = dest_dir + else: + target_task_dir = plan.task_dir + + if strip_dockerfile_for_shared and plan.action in { + "keep_pinned", + "verify_shared", + }: + df = target_task_dir / "environment" / "Dockerfile" + if df.is_file(): + df.unlink() + + update_task_toml(target_task_dir / "task.toml", docker_image=rec.image) + + summary = { + "total_tasks": len(plans), + "unique_environments": len(groups), + "resolved": sum(r.status == "resolved" for r in receipts_by_task.values()), + "built_no_push": sum( + r.status == "built_no_push" for r in receipts_by_task.values() + ), + "failed": sum(r.status == "failed" for r in receipts_by_task.values()), + "actions": { + action: sum(p.action == action for p in plans) + for action in ("keep_pinned", "verify_shared", "oci_append", "build") + }, + "registry": effective_registry if needs_registry else None, + "tasks": { + tid: receipts_by_task[tid].to_dict() for tid in sorted(receipts_by_task) + }, + } + + if receipts_path is not None: + receipts_path.parent.mkdir(parents=True, exist_ok=True) + tmp_receipts = receipts_path.with_suffix(receipts_path.suffix + ".tmp") + tmp_receipts.write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + tmp_receipts.replace(receipts_path) + + return summary diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py new file mode 100644 index 0000000000..2db9c9f87f --- /dev/null +++ b/tests/test_cli/test_harbor_build_images.py @@ -0,0 +1,805 @@ +"""Tests for `openenv.harbor.images` and `openenv harbor build-images`.""" + +from __future__ import annotations + +import base64 +import gzip +import hashlib +import io +import json +import tarfile +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import httpx +import pytest +from openenv.cli.commands.harbor import app +from openenv.harbor.images import ( + DockerBuildxBuilder, + HarborImageError, + KanikoHFJobsBuilder, + OCIRegistryClient, + audit_environment, + build_copy_layer_tar, + build_harbor_images, + classify_dockerfile, + parse_image_ref, + parse_kaniko_digest, + sanitize_tag, + update_task_toml, + verify_harbor_images, +) +from typer.testing import CliRunner + +try: + import tomllib +except ModuleNotFoundError: # pragma: no cover + import tomli as tomllib # type: ignore[no-redef] + + +def _sha(data: bytes) -> str: + return f"sha256:{hashlib.sha256(data).hexdigest()}" + + +class FakeOCIRegistry: + """In-memory OCI Distribution v2 registry supporting Bearer auth, multi-arch, and uploads.""" + + def __init__(self, *, require_push_auth: bool = True) -> None: + self.require_push_auth = require_push_auth + self.blobs: dict[str, dict[str, bytes]] = {} # repo -> {digest: bytes} + self.manifests: dict[ + str, dict[str, tuple[bytes, str]] + ] = {} # repo -> {ref: (bytes, media_type)} + self.uploads: dict[str, str] = {} # upload_id -> repo + self.blob_uploads_count = 0 + self.expected_creds = ("testuser", "testpass") + self.valid_push_token = "tok-push-ok" + self.valid_pull_token = "tok-pull-ok" + + def seed_image( + self, + repo: str, + tag: str, + *, + os_name: str = "linux", + arch: str = "amd64", + multi_arch: bool = False, + workdir: str = "/", + ) -> str: + layer_raw = b"base-layer-tar-bytes" + layer_gz = gzip.compress(layer_raw, mtime=0) + layer_digest = _sha(layer_gz) + config_doc = { + "os": os_name, + "architecture": arch, + "config": {"Env": ["PATH=/usr/bin:/bin"], "WorkingDir": workdir}, + "rootfs": {"type": "layers", "diff_ids": [_sha(layer_raw)]}, + "history": [{"created_by": "base"}], + } + config_bytes = json.dumps(config_doc, sort_keys=True).encode() + config_digest = _sha(config_bytes) + manifest_doc = { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "config": { + "mediaType": "application/vnd.oci.image.config.v1+json", + "size": len(config_bytes), + "digest": config_digest, + }, + "layers": [ + { + "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", + "size": len(layer_gz), + "digest": layer_digest, + } + ], + } + manifest_bytes = json.dumps(manifest_doc, sort_keys=True).encode() + manifest_digest = _sha(manifest_bytes) + + self.blobs.setdefault(repo, {})[layer_digest] = layer_gz + self.blobs[repo][config_digest] = config_bytes + self.manifests.setdefault(repo, {})[manifest_digest] = ( + manifest_bytes, + manifest_doc["mediaType"], + ) + + if multi_arch: + arm_doc = {**config_doc, "architecture": "arm64"} + arm_cfg = json.dumps(arm_doc, sort_keys=True).encode() + arm_cfg_d = _sha(arm_cfg) + self.blobs[repo][arm_cfg_d] = arm_cfg + arm_m = json.dumps( + { + **manifest_doc, + "config": { + "mediaType": "application/vnd.oci.image.config.v1+json", + "size": len(arm_cfg), + "digest": arm_cfg_d, + }, + }, + sort_keys=True, + ).encode() + arm_m_d = _sha(arm_m) + self.manifests[repo][arm_m_d] = (arm_m, manifest_doc["mediaType"]) + index_doc = { + "schemaVersion": 2, + "mediaType": "application/vnd.oci.image.index.v1+json", + "manifests": [ + { + "mediaType": manifest_doc["mediaType"], + "size": len(arm_m), + "digest": arm_m_d, + "platform": {"os": "linux", "architecture": "arm64"}, + }, + { + "mediaType": manifest_doc["mediaType"], + "size": len(manifest_bytes), + "digest": manifest_digest, + "platform": {"os": os_name, "architecture": arch}, + }, + ], + } + index_bytes = json.dumps(index_doc, sort_keys=True).encode() + index_digest = _sha(index_bytes) + self.manifests[repo][index_digest] = (index_bytes, index_doc["mediaType"]) + self.manifests[repo][tag] = (index_bytes, index_doc["mediaType"]) + return manifest_digest + + self.manifests[repo][tag] = (manifest_bytes, manifest_doc["mediaType"]) + return manifest_digest + + def handler(self, request: httpx.Request) -> httpx.Response: + path = request.url.path + if path == "/token": + scope = request.url.params.get("scope", "") + auth = request.headers.get("Authorization", "") + if "push" in scope and self.require_push_auth: + expected = ( + "Basic " + + base64.b64encode( + f"{self.expected_creds[0]}:{self.expected_creds[1]}".encode() + ).decode() + ) + if auth != expected: + return httpx.Response(401, json={"error": "unauthorized"}) + return httpx.Response(200, json={"token": self.valid_push_token}) + return httpx.Response(200, json={"token": self.valid_pull_token}) + + auth = request.headers.get("Authorization", "") + is_write = request.method in {"POST", "PUT"} + + if path.startswith("/v2/") and "/manifests/" in path: + rest = path[len("/v2/") :] + repo, ref = rest.split("/manifests/", 1) + if is_write: + if self.require_push_auth and auth != f"Bearer {self.valid_push_token}": + return httpx.Response( + 401, + headers={ + "WWW-Authenticate": ( + f'Bearer realm="{request.url.scheme}://{request.url.netloc.decode()}/token",' + f'service="fake",scope="repository:{repo}:pull,push"' + ) + }, + ) + raw = request.content + digest = _sha(raw) + mt = request.headers.get("Content-Type", "") + self.manifests.setdefault(repo, {})[ref] = (raw, mt) + self.manifests[repo][digest] = (raw, mt) + return httpx.Response(201, headers={"Docker-Content-Digest": digest}) + + if auth not in { + f"Bearer {self.valid_pull_token}", + f"Bearer {self.valid_push_token}", + }: + return httpx.Response( + 401, + headers={ + "WWW-Authenticate": ( + f'Bearer realm="{request.url.scheme}://{request.url.netloc.decode()}/token",' + f'service="fake",scope="repository:{repo}:pull"' + ) + }, + ) + entry = self.manifests.get(repo, {}).get(ref) + if not entry: + return httpx.Response(404) + raw, mt = entry + return httpx.Response( + 200, + content=raw, + headers={ + "Content-Type": mt, + "Docker-Content-Digest": _sha(raw), + }, + ) + + if path.startswith("/v2/") and "/blobs/uploads/" in path: + rest = path[len("/v2/") :] + repo, tail = rest.split("/blobs/uploads/", 1) + if self.require_push_auth and auth != f"Bearer {self.valid_push_token}": + return httpx.Response( + 401, + headers={ + "WWW-Authenticate": ( + f'Bearer realm="{request.url.scheme}://{request.url.netloc.decode()}/token",' + f'service="fake",scope="repository:{repo}:pull,push"' + ) + }, + ) + if request.method == "POST": + mount = request.url.params.get("mount") + src_repo = request.url.params.get("from") + if mount and src_repo and mount in self.blobs.get(src_repo, {}): + self.blobs.setdefault(repo, {})[mount] = self.blobs[src_repo][mount] + return httpx.Response(201) + uid = f"u{len(self.uploads) + 1}" + self.uploads[uid] = repo + return httpx.Response( + 202, headers={"Location": f"/v2/{repo}/blobs/uploads/{uid}"} + ) + if request.method == "PUT": + digest = request.url.params.get("digest", "") + raw = request.content + assert _sha(raw) == digest + self.blobs.setdefault(repo, {})[digest] = raw + self.blob_uploads_count += 1 + return httpx.Response(201, headers={"Docker-Content-Digest": digest}) + + if path.startswith("/v2/") and "/blobs/" in path: + rest = path[len("/v2/") :] + repo, digest = rest.split("/blobs/", 1) + if auth not in { + f"Bearer {self.valid_pull_token}", + f"Bearer {self.valid_push_token}", + }: + return httpx.Response( + 401, + headers={ + "WWW-Authenticate": ( + f'Bearer realm="{request.url.scheme}://{request.url.netloc.decode()}/token",' + f'service="fake",scope="repository:{repo}:pull"' + ) + }, + ) + blob = self.blobs.get(repo, {}).get(digest) + if blob is None: + return httpx.Response(404) + if request.method == "HEAD": + return httpx.Response(200, headers={"Content-Length": str(len(blob))}) + return httpx.Response(200, content=blob) + + return httpx.Response(404) + + +def _write_task( + root: Path, + name: str, + *, + dockerfile: str | None = None, + env_files: dict[str, str] | None = None, + docker_image: str | None = None, + tests_files: dict[str, str] | None = None, + solution_files: dict[str, str] | None = None, +) -> Path: + task_dir = root / name + (task_dir / "environment").mkdir(parents=True, exist_ok=True) + env_block = "[environment]\ncpus = 1\nmemory_mb = 512\n" + if docker_image is not None: + env_block = f'[environment]\ndocker_image = "{docker_image}"\ncpus = 1\nmemory_mb = 512\n' + (task_dir / "task.toml").write_text( + f'version = "1.0"\n[agent]\ntimeout_sec = 300\n{env_block}\n' + "[verifier]\ntimeout_sec = 300\n[verifier.environment]\ncpus = 1\n", + encoding="utf-8", + ) + (task_dir / "instruction.md").write_text("Fix the bug.\n", encoding="utf-8") + if dockerfile is not None: + (task_dir / "environment" / "Dockerfile").write_text( + dockerfile, encoding="utf-8" + ) + for rel, content in (env_files or {}).items(): + p = task_dir / "environment" / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content, encoding="utf-8") + for rel, content in (tests_files or {}).items(): + p = task_dir / "tests" / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content, encoding="utf-8") + for rel, content in (solution_files or {}).items(): + p = task_dir / "solution" / rel + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(content, encoding="utf-8") + return task_dir + + +def test_parse_image_ref_and_sanitize_tag(): + py = parse_image_ref("python:3.12-slim") + assert py.registry == "registry-1.docker.io" + assert py.display_registry == "docker.io" + assert py.repository == "library/python" + assert py.tag == "3.12-slim" + assert py.canonical_repo == "docker.io/library/python" + + ghcr = parse_image_ref("ghcr.io/harness-hub/scale800:my-tag") + assert ghcr.registry == "ghcr.io" + assert ghcr.repository == "harness-hub/scale800" + assert ghcr.tag == "my-tag" + + local = parse_image_ref("localhost:5000/org/app@sha256:" + "a" * 64) + assert local.registry == "localhost:5000" + assert local.digest == "sha256:" + "a" * 64 + + long_a = sanitize_tag("a" * 150 + "1") + long_b = sanitize_tag("a" * 150 + "2") + assert len(long_a) <= 128 and len(long_b) <= 128 and long_a != long_b + + +def test_classify_dockerfile_copy_only_vs_run(): + copy_only = classify_dockerfile( + """ + ARG BASE=ghcr.io/harness-hub/go-base:v1 + FROM --platform=linux/amd64 ${BASE} + WORKDIR /testbed + ENV CGO_ENABLED=0 PYTHONDONTWRITEBYTECODE=1 + COPY source/ /testbed/ + LABEL openenv.test="yes" + """ + ) + assert copy_only.is_copy_only is True + assert copy_only.base_image == "ghcr.io/harness-hub/go-base:v1" + assert copy_only.workdir == "/testbed" + assert copy_only.env == {"CGO_ENABLED": "0", "PYTHONDONTWRITEBYTECODE": "1"} + assert copy_only.labels == {"openenv.test": "yes"} + assert len(copy_only.copy_ops) == 1 + assert copy_only.copy_ops[0].sources == ("source/",) + + with_run = classify_dockerfile( + """ + FROM python:3.12-slim + WORKDIR /app + COPY source/ /app/ + RUN pip install pytest + """ + ) + assert with_run.is_copy_only is False + assert "RUN" in with_run.reason + + multi_stage = classify_dockerfile( + """ + FROM golang:1.22 AS build + FROM debian:bookworm-slim + COPY --from=build /bin/app /bin/app + """ + ) + assert multi_stage.is_copy_only is False + + non_numeric_chown = classify_dockerfile( + "FROM python:3.12-slim\nCOPY --chown=learner:learner source/ /app/\n" + ) + assert non_numeric_chown.is_copy_only is False + + +def test_audit_environment_blocks_leaks_symlinks_and_secrets(tmp_path: Path): + clean = _write_task( + tmp_path, + "clean", + dockerfile="FROM python:3.12-slim\nCOPY source/ /app/\n", + env_files={"source/app.py": "def f(): return 1\n"}, + tests_files={ + "grade.py": "assert f() == 2 # hidden grader content > 32 bytes\n" + }, + solution_files={"reference/app.py": "def f(): return 2 # reference fix\n"}, + ) + hashes = audit_environment(clean) + assert set(hashes) == {"Dockerfile", "source/app.py"} + + # Symlink rejected + sym = _write_task(tmp_path, "sym", dockerfile="FROM python:3.12-slim\n") + (sym / "environment" / "escape").symlink_to(tmp_path) + with pytest.raises(HarborImageError, match="symlink"): + audit_environment(sym) + + # Credential rejected + cred = _write_task( + tmp_path, + "cred", + dockerfile="FROM python:3.12-slim\n", + env_files={"source/cfg.py": "TOKEN = 'hf_ABCDEFGHIJKLMNOPQRSTUVWXYZ123456'\n"}, + ) + with pytest.raises(HarborImageError, match="huggingface token"): + audit_environment(cred) + + # Hidden grader leak rejected + leak = _write_task( + tmp_path, + "leak", + dockerfile="FROM python:3.12-slim\nCOPY source/ /app/\n", + env_files={ + "source/leaked.py": "assert f() == 2 # hidden grader content > 32 bytes\n" + }, + tests_files={ + "grade.py": "assert f() == 2 # hidden grader content > 32 bytes\n" + }, + ) + with pytest.raises(HarborImageError, match="matches hidden tests/grade.py"): + audit_environment(leak) + + # Parent traversal in COPY rejected + trav = _write_task( + tmp_path, + "trav", + dockerfile="FROM python:3.12-slim\nCOPY ../tests /tests\n", + ) + with pytest.raises(HarborImageError, match="parent traversal"): + audit_environment(trav) + + +def test_build_copy_layer_tar_matches_docker_copy_semantics(tmp_path: Path): + env_dir = tmp_path / "environment" + (env_dir / "source" / "sub").mkdir(parents=True) + (env_dir / "source" / "a.go").write_text("package a\n", encoding="utf-8") + script = env_dir / "source" / "sub" / "run.sh" + script.write_text("#!/bin/sh\necho ok\n", encoding="utf-8") + script.chmod(0o755) + + parsed = classify_dockerfile( + "FROM ghcr.io/org/base:v1\nWORKDIR /testbed\nCOPY source/ /testbed/\n" + ) + gz1, diff1 = build_copy_layer_tar(env_dir, parsed.copy_ops) + gz2, diff2 = build_copy_layer_tar(env_dir, parsed.copy_ops) + assert gz1 == gz2 and diff1 == diff2 + assert gz1 is not None + + with tarfile.open(fileobj=io.BytesIO(gzip.decompress(gz1)), mode="r:") as tar: + names = {m.name: m for m in tar.getmembers()} + assert "testbed/a.go" in names + assert "testbed/sub/run.sh" in names + assert "testbed/source/a.go" not in names + assert names["testbed/sub/run.sh"].mode == 0o755 + + +def test_oci_registry_resolve_multiarch_and_append_layer(tmp_path: Path): + fake = FakeOCIRegistry() + base_digest = fake.seed_image( + "harness-hub/base", "v1", multi_arch=True, workdir="/orig" + ) + transport = httpx.MockTransport(fake.handler) + + with ( + OCIRegistryClient( + http=httpx.Client(transport=transport), anonymous=True + ) as pub, + OCIRegistryClient( + http=httpx.Client(transport=transport), + username="testuser", + password="testpass", + ) as reg, + ): + resolved_base, _, _ = pub.resolve_linux_amd64("ghcr.io/harness-hub/base:v1") + assert resolved_base.registry_digest == base_digest + assert resolved_base.public_pull_verified is True + + env_dir = tmp_path / "environment" + (env_dir / "source").mkdir(parents=True) + (env_dir / "source" / "main.go").write_text("package main\n", encoding="utf-8") + parsed = classify_dockerfile( + "FROM ghcr.io/harness-hub/base:v1\nWORKDIR /testbed\nENV GOFLAGS=-mod=readonly\nCOPY source/ /testbed/\n" + ) + gz, diff_id = build_copy_layer_tar(env_dir, parsed.copy_ops) + + pushed = reg.append_layer( + base_image=parsed.base_image, + target_repo="ghcr.io/harness-hub/scale800", + target_tag="task-1", + layer_tar_gz=gz, + diff_id=diff_id, + workdir=parsed.workdir, + env=parsed.env, + base_client=pub, + ) + assert pushed.image.startswith("ghcr.io/harness-hub/scale800@sha256:") + + # Confirm anonymous public pull resolves the pushed amd64 image & updated config + verified, manifest, config = pub.resolve_linux_amd64(pushed.image) + assert verified.registry_digest == pushed.registry_digest + assert verified.public_pull_verified is True + assert len(manifest["layers"]) == 2 + assert config["config"]["WorkingDir"] == "/testbed" + assert "GOFLAGS=-mod=readonly" in config["config"]["Env"] + assert config["rootfs"]["diff_ids"][-1] == diff_id + + # Second identical append deduplicates blobs (0 additional uploads) + uploads_before = fake.blob_uploads_count + reg.append_layer( + base_image=parsed.base_image, + target_repo="ghcr.io/harness-hub/scale800", + target_tag="task-2", + layer_tar_gz=gz, + diff_id=diff_id, + workdir=parsed.workdir, + env=parsed.env, + base_client=pub, + ) + assert fake.blob_uploads_count == uploads_before + + +def test_oci_registry_rejects_arm64_only_image(): + fake = FakeOCIRegistry() + fake.seed_image("org/arm", "v1", os_name="linux", arch="arm64") + with OCIRegistryClient( + http=httpx.Client(transport=httpx.MockTransport(fake.handler)), + anonymous=True, + ) as client: + with pytest.raises(HarborImageError, match="expected linux/amd64"): + client.resolve_linux_amd64("ghcr.io/org/arm:v1") + + +def test_kaniko_hf_jobs_builder_uploads_runs_and_cleans_up(tmp_path: Path): + env_dir = tmp_path / "environment" + env_dir.mkdir() + (env_dir / "Dockerfile").write_text( + "FROM python:3.12-slim\nRUN pip install packaging\n", encoding="utf-8" + ) + expected_digest = "sha256:" + "9" * 64 + + calls: dict[str, Any] = {"added": [], "deleted": [], "run_job": None} + + class FakeHfApi: + def whoami(self) -> dict[str, str]: + return {"name": "harness-hub"} + + def create_bucket(self, bucket_id: str, **kwargs: Any) -> None: + calls["bucket"] = (bucket_id, kwargs) + + def batch_bucket_files( + self, bucket_id: str, *, add: Any = None, delete: Any = None + ) -> None: + if add: + calls["added"].extend(add) + if delete: + calls["deleted"].extend(delete) + + def run_job(self, **kwargs: Any) -> SimpleNamespace: + calls["run_job"] = kwargs + return SimpleNamespace(id="job-kaniko-123") + + def inspect_job(self, *, job_id: str, namespace: str) -> SimpleNamespace: + return SimpleNamespace( + id=job_id, + namespace=namespace, + status=SimpleNamespace(stage="COMPLETED"), + ) + + def fetch_job_logs( + self, *, job_id: str, namespace: str, follow: bool = False + ) -> list[str]: + return [ + "INFO[0001] Building stage", + f"OPENENV_KANIKO_DIGEST={expected_digest}", + ] + + builder = KanikoHFJobsBuilder( + namespace="harness-hub", + flavor="cpu-upgrade", + cache_repo="ghcr.io/harness-hub/cache", + poll_interval_s=0.0, + api=FakeHfApi(), + ) + digest, job_id = builder.build( + env_dir=env_dir, + env_hash="abcdef0123456789" * 4, + target_repo="ghcr.io/harness-hub/tasks", + target_tag="task-1", + registry_username="bot", + registry_password="secret-token-value", + ) + + assert digest == expected_digest + assert job_id == "job-kaniko-123" + assert calls["bucket"] == ( + "harness-hub/openenv-kaniko-builds", + {"private": True, "exist_ok": True}, + ) + assert len(calls["added"]) == 1 + assert calls["deleted"] == [calls["added"][0][1]] + + spec = calls["run_job"] + assert spec["flavor"] == "cpu-upgrade" + assert "secret-token-value" not in " ".join(spec["command"]) + assert "KANIKO_DOCKER_CONFIG_B64" in spec["secrets"] + decoded_cfg = json.loads( + base64.b64decode(spec["secrets"]["KANIKO_DOCKER_CONFIG_B64"]).decode() + ) + assert "ghcr.io" in decoded_cfg["auths"] + assert "--cache=true" in spec["command"][-1] + assert "--cache-repo=ghcr.io/harness-hub/cache" in spec["command"][-1] + assert ( + parse_kaniko_digest(f"x\nOPENENV_KANIKO_DIGEST={expected_digest}\n") + == expected_digest + ) + + +def test_update_task_toml_preserves_verifier_environment(tmp_path: Path): + toml_path = tmp_path / "task.toml" + toml_path.write_text( + 'version = "1.0"\n[environment]\ncpus = 1\n[verifier.environment]\ncpus = 2\n', + encoding="utf-8", + ) + pinned = "ghcr.io/harness-hub/tasks@sha256:" + "c" * 64 + update_task_toml(toml_path, docker_image=pinned, workdir="/workspace") + parsed = tomllib.loads(toml_path.read_text(encoding="utf-8")) + assert parsed["environment"]["docker_image"] == pinned + assert parsed["environment"]["workdir"] == "/workspace" + assert "docker_image" not in parsed["verifier"]["environment"] + + # Replacing an existing tag updates in-place cleanly + pinned2 = "ghcr.io/harness-hub/tasks@sha256:" + "d" * 64 + update_task_toml(toml_path, docker_image=pinned2) + parsed2 = tomllib.loads(toml_path.read_text(encoding="utf-8")) + assert parsed2["environment"]["docker_image"] == pinned2 + + +def test_build_harbor_images_deduplicates_routes_and_resumes(tmp_path: Path): + fake = FakeOCIRegistry() + fake.seed_image("harness-hub/go-base", "v1") + shared_digest = fake.seed_image("harness-hub/office", "v1") + run_digest = fake.seed_image("harness-hub/corpus", "run-built") + transport = httpx.MockTransport(fake.handler) + + src = tmp_path / "src" / "tasks" + # Two identical COPY-only tasks -> should deduplicate into ONE oci_append + for name in ("go-a", "go-b"): + _write_task( + src, + name, + dockerfile="FROM ghcr.io/harness-hub/go-base:v1\nWORKDIR /testbed\nCOPY source/ /testbed/\n", + env_files={"source/main.go": "package main\n"}, + ) + # One RUN task -> routes to run_builder + _write_task( + src, + "py-run", + dockerfile="FROM ghcr.io/harness-hub/go-base:v1\nRUN echo hi\n", + ) + # One shared-image task (no Dockerfile) -> verifies & pins digest + _write_task( + src, + "office-1", + docker_image="ghcr.io/harness-hub/office:v1", + env_files={"inputs/data.csv": "a,b\n1,2\n"}, + ) + + run_calls: list[str] = [] + + class StubRunBuilder: + def build(self, **kwargs: Any) -> tuple[str, str]: + run_calls.append(kwargs["target_tag"]) + return run_digest, "job-run-1" + + out_dir = tmp_path / "out" + receipts_file = tmp_path / "receipts.json" + per_task_dir = tmp_path / "per-task-receipts" + + with ( + OCIRegistryClient( + http=httpx.Client(transport=transport), + username="testuser", + password="testpass", + ) as reg, + OCIRegistryClient( + http=httpx.Client(transport=transport), anonymous=True + ) as pub, + ): + summary = build_harbor_images( + tmp_path / "src", + registry="ghcr.io/harness-hub/corpus", + builder="kaniko", + output_dir=out_dir, + receipts_path=receipts_file, + per_task_receipts_dir=per_task_dir, + run_builder=StubRunBuilder(), + registry_client=reg, + public_client=pub, + ) + + assert summary["total_tasks"] == 4 + assert summary["unique_environments"] == 3 # go-a & go-b deduped! + assert summary["resolved"] == 4 + assert summary["failed"] == 0 + assert run_calls == ["py-run"] + assert summary["tasks"]["go-a"]["image"] == summary["tasks"]["go-b"]["image"] + assert ( + summary["tasks"]["office-1"]["image"] + == f"ghcr.io/harness-hub/office@{shared_digest}" + ) + assert sorted(p.name for p in per_task_dir.glob("*.json")) == [ + "go-a.json", + "go-b.json", + "office-1.json", + "py-run.json", + ] + + # Every emitted task.toml has a pullable pinned linux/amd64 image + verified = verify_harbor_images( + out_dir, anonymous=True, require_digest_pin=True, registry_client=pub + ) + assert ( + verified["total"] == 4 and verified["ok"] == 4 and verified["failed"] == 0 + ) + + # Resuming from per_task_receipts_dir alone skips all builds (even for a subset) + run_calls.clear() + resumed = build_harbor_images( + tmp_path / "src", + registry="ghcr.io/harness-hub/corpus", + builder="kaniko", + per_task_receipts_dir=per_task_dir, + task_ids=["py-run", "go-a"], + run_builder=StubRunBuilder(), + registry_client=reg, + public_client=pub, + ) + assert resumed["total_tasks"] == 2 + assert resumed["resolved"] == 2 + assert run_calls == [] + + +def test_cli_build_images_plan_json(tmp_path: Path): + src = tmp_path / "suite" / "tasks" + _write_task( + src, + "t-copy", + dockerfile="FROM python:3.12-slim\nWORKDIR /app\nCOPY source/ /app/\n", + env_files={"source/app.py": "x = 1\n"}, + ) + _write_task( + src, + "t-run", + dockerfile="FROM python:3.12-slim\nRUN pip install pytest\n", + ) + result = CliRunner().invoke( + app, ["build-images", str(tmp_path / "suite"), "--plan", "--json"] + ) + assert result.exit_code == 0, result.output + data = json.loads(result.stdout) + assert data["total_tasks"] == 2 + assert data["actions"]["oci_append"] == 1 + assert data["actions"]["build"] == 1 + + +def test_docker_buildx_builder_invokes_amd64_and_reads_digest( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + env_dir = tmp_path / "environment" + env_dir.mkdir() + (env_dir / "Dockerfile").write_text( + "FROM python:3.12-slim\nRUN echo ok\n", encoding="utf-8" + ) + expected = "sha256:" + "7" * 64 + seen_cmd: list[str] = [] + + def fake_run(cmd: list[str], **kwargs: Any) -> SimpleNamespace: + seen_cmd.extend(cmd) + meta_idx = cmd.index("--metadata-file") + 1 + Path(cmd[meta_idx]).write_text( + json.dumps({"containerimage.digest": expected}), encoding="utf-8" + ) + return SimpleNamespace(returncode=0, stdout="", stderr="") + + monkeypatch.setattr("openenv.harbor.images.subprocess.run", fake_run) + builder = DockerBuildxBuilder(cache_repo="ghcr.io/org/cache") + digest, job_id = builder.build( + env_dir=env_dir, + env_hash="0" * 64, + target_repo="ghcr.io/org/repo", + target_tag="t1", + extra_dockerfile="RUN echo extra", + ) + assert digest == expected + assert job_id is None + assert "--platform" in seen_cmd and "linux/amd64" in seen_cmd + assert "--push" in seen_cmd + assert "type=registry,ref=ghcr.io/org/cache" in seen_cmd From d5dd1d783e76f14f1ce887dc7df3f23ddc05c7fa Mon Sep 17 00:00:00 2001 From: burtenshaw Date: Thu, 26 Nov 2026 15:48:33 +0100 Subject: [PATCH 02/15] style: sort imports with usort --- src/openenv/cli/commands/harbor.py | 2 +- src/openenv/harbor/images.py | 2 +- tests/test_cli/test_harbor_build_images.py | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/openenv/cli/commands/harbor.py b/src/openenv/cli/commands/harbor.py index 4b1468325c..e8f5f8a1c6 100644 --- a/src/openenv/cli/commands/harbor.py +++ b/src/openenv/cli/commands/harbor.py @@ -505,8 +505,8 @@ def build_images( `[environment].docker_image = "@sha256:"` in `task.toml`. """ from openenv.harbor.images import ( - HarborImageError, build_harbor_images, + HarborImageError, plan_harbor_images, verify_harbor_images, ) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index aaf432094e..f4c45cd33f 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -43,7 +43,7 @@ import threading import time import uuid -from concurrent.futures import ThreadPoolExecutor, as_completed +from concurrent.futures import as_completed, ThreadPoolExecutor from dataclasses import asdict, dataclass, field from pathlib import Path, PurePosixPath from typing import Any, Callable diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 2db9c9f87f..29c8eb4913 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -16,14 +16,14 @@ import pytest from openenv.cli.commands.harbor import app from openenv.harbor.images import ( - DockerBuildxBuilder, - HarborImageError, - KanikoHFJobsBuilder, - OCIRegistryClient, audit_environment, build_copy_layer_tar, build_harbor_images, classify_dockerfile, + DockerBuildxBuilder, + HarborImageError, + KanikoHFJobsBuilder, + OCIRegistryClient, parse_image_ref, parse_kaniko_digest, sanitize_tag, From ff1b9c1de719022164749deceac940c71e1da57a Mon Sep 17 00:00:00 2001 From: burtenshaw Date: Thu, 26 Nov 2026 15:56:35 +0100 Subject: [PATCH 03/15] fix(harbor): address Bugbot review on COPY destinations, globs, output-dir guard, and --verify-only --task --- src/openenv/cli/commands/harbor.py | 1 + src/openenv/harbor/images.py | 57 ++++++++++++++++-- tests/test_cli/test_harbor_build_images.py | 69 ++++++++++++++++++++++ 3 files changed, 122 insertions(+), 5 deletions(-) diff --git a/src/openenv/cli/commands/harbor.py b/src/openenv/cli/commands/harbor.py index e8f5f8a1c6..bd5776029d 100644 --- a/src/openenv/cli/commands/harbor.py +++ b/src/openenv/cli/commands/harbor.py @@ -527,6 +527,7 @@ def build_images( anonymous=verify_public, require_digest_pin=require_digest_pin, concurrency=concurrency, + task_ids=task or None, ) if json_output: print(json.dumps(result, indent=2, sort_keys=True)) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index f4c45cd33f..07dfef3bd7 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -28,7 +28,6 @@ import base64 import copy -import fnmatch import gzip import hashlib import io @@ -1278,17 +1277,21 @@ def _resolve_copy_sources(context_dir: Path, pattern: str) -> list[Path]: clean = pattern.lstrip("/") if clean in {".", ""}: return [context_dir] + ctx_resolved = context_dir.resolve() if any(ch in clean for ch in ("*", "?", "[")): + if "**" in PurePosixPath(clean).parts: + raise HarborImageError( + f"Recursive '**' COPY globs are not supported by OCI append: {pattern!r}" + ) matched = sorted( p - for p in context_dir.rglob("*") - if fnmatch.fnmatch(p.relative_to(context_dir).as_posix(), clean) + for p in context_dir.glob(clean) + if (p.resolve() == ctx_resolved or p.resolve().is_relative_to(ctx_resolved)) ) if not matched: raise HarborImageError(f"COPY pattern matched no files: {pattern!r}") return matched candidate = (context_dir / clean).resolve() - ctx_resolved = context_dir.resolve() if not (candidate == ctx_resolved or candidate.is_relative_to(ctx_resolved)): raise HarborImageError(f"COPY source escapes build context: {pattern!r}") if not candidate.exists(): @@ -1296,6 +1299,22 @@ def _resolve_copy_sources(context_dir: Path, pattern: str) -> list[Path]: return [candidate] +def _copy_destination_is_dir(op: CopyOp, dest_norm: str) -> bool: + raw = op.destination.strip() + if ( + raw in {".", "..", "/"} + or raw.endswith(("/", "/.", "/..")) + or dest_norm == "/" + or dest_norm.endswith("/") + or len(op.sources) > 1 + ): + return True + # Destination equal to WORKDIR (e.g. WORKDIR /app + COPY f /app) is an existing directory. + if op.workdir and dest_norm.rstrip("/") == op.workdir.rstrip("/"): + return True + return False + + def build_copy_layer_tar( context_dir: Path, copy_ops: tuple[CopyOp, ...] ) -> tuple[bytes | None, str | None]: @@ -1319,7 +1338,7 @@ def ensure_parents(rel_posix: str, uid: int, gid: int) -> None: for op in copy_ops: dest_norm = _normalize_container_path(op.destination, op.workdir) - dest_is_dir = dest_norm.endswith("/") or len(op.sources) > 1 + dest_is_dir = _copy_destination_is_dir(op, dest_norm) dest_rel = dest_norm.strip("/") resolved_sources: list[Path] = [] @@ -1945,10 +1964,19 @@ def verify_harbor_images( anonymous: bool = True, require_digest_pin: bool = False, concurrency: int = 8, + task_ids: list[str] | None = None, registry_client: OCIRegistryClient | None = None, ) -> dict[str, Any]: """Verify every Harbor task's ``docker_image`` is pullable as ``linux/amd64``.""" tasks = discover_task_dirs(root) + if task_ids is not None: + wanted = set(task_ids) + tasks = [(tid, tdir) for tid, tdir in tasks if tid in wanted] + missing = sorted(wanted - {tid for tid, _ in tasks}) + if missing: + raise HarborImageError( + f"Requested task ID(s) not found under {root}: {missing}" + ) results: dict[str, dict[str, Any]] = {} def check_one(item: tuple[str, Path]) -> tuple[str, dict[str, Any]]: @@ -2043,6 +2071,25 @@ def build_harbor_images( task_ids=task_ids, ) + if output_dir is not None: + out_resolved = output_dir.resolve() + src_resolved = root.resolve() + if ( + out_resolved == src_resolved + or out_resolved.is_relative_to(src_resolved) + or src_resolved.is_relative_to(out_resolved) + or any( + out_resolved == p.task_dir.resolve() + or out_resolved.is_relative_to(p.task_dir.resolve()) + or p.task_dir.resolve().is_relative_to(out_resolved) + for p in plans + ) + ): + raise HarborImageError( + "output_dir must not overlap the input task/dataset directory; " + "use --in-place to update task.toml in place" + ) + needs_registry = any(p.action in {"oci_append", "build"} for p in plans) if needs_registry and not registry and not no_push: raise HarborImageError( diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 29c8eb4913..818cf0bc24 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -803,3 +803,72 @@ def fake_run(cmd: list[str], **kwargs: Any) -> SimpleNamespace: assert "--platform" in seen_cmd and "linux/amd64" in seen_cmd assert "--push" in seen_cmd assert "type=registry,ref=ghcr.io/org/cache" in seen_cmd + + +def test_copy_dot_destination_and_single_segment_globs(tmp_path: Path): + env_dir = tmp_path / "environment" + (env_dir / "nested").mkdir(parents=True) + (env_dir / "app.py").write_text("root = 1\n", encoding="utf-8") + (env_dir / "nested" / "app.py").write_text("nested = 2\n", encoding="utf-8") + + # `COPY app.py .` with `WORKDIR /app` must land at `app/app.py`, not overwrite `app` as a file. + parsed_dot = classify_dockerfile( + "FROM python:3.12-slim\nWORKDIR /app\nCOPY app.py .\n" + ) + gz_dot, _ = build_copy_layer_tar(env_dir, parsed_dot.copy_ops) + assert gz_dot is not None + with tarfile.open(fileobj=io.BytesIO(gzip.decompress(gz_dot)), mode="r:") as tar: + names = {m.name: m for m in tar.getmembers()} + assert "app/app.py" in names + assert names["app/app.py"].isfile() + assert names["app"].isdir() + + # `COPY *.py /app/` must only match top-level `app.py`, not `nested/app.py`. + parsed_glob = classify_dockerfile( + "FROM python:3.12-slim\nWORKDIR /app\nCOPY *.py /app/\n" + ) + gz_glob, _ = build_copy_layer_tar(env_dir, parsed_glob.copy_ops) + assert gz_glob is not None + with tarfile.open(fileobj=io.BytesIO(gzip.decompress(gz_glob)), mode="r:") as tar: + extracted = tar.extractfile("app/app.py") + assert extracted is not None + assert extracted.read() == b"root = 1\n" + + +def test_output_dir_overlap_rejected_and_verify_only_honors_task_filter( + tmp_path: Path, +): + fake = FakeOCIRegistry() + good_digest = fake.seed_image("harness-hub/good", "v1") + transport = httpx.MockTransport(fake.handler) + + suite = tmp_path / "suite" + single = _write_task( + suite / "tasks", + "good-task", + docker_image=f"ghcr.io/harness-hub/good@{good_digest}", + ) + _write_task(suite / "tasks", "missing-image-task") + + with OCIRegistryClient( + http=httpx.Client(transport=transport), anonymous=True + ) as pub: + # Overlapping output_dir must fail before deleting source task. + with pytest.raises(HarborImageError, match="output_dir must not overlap"): + build_harbor_images( + single, + output_dir=single, + public_client=pub, + registry_client=pub, + ) + assert (single / "task.toml").is_file() + + # Filtering verify_harbor_images to only good-task ignores missing-image-task. + res = verify_harbor_images( + suite, + anonymous=True, + require_digest_pin=True, + task_ids=["good-task"], + registry_client=pub, + ) + assert res["total"] == 1 and res["ok"] == 1 and res["failed"] == 0 From 1505e6eefc7a96810719aeb882b061fecc421f97 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 14:57:40 +0000 Subject: [PATCH 04/15] Fix Harbor image build edge cases --- tests/test_cli/test_harbor_build_images.py | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 818cf0bc24..274abb8d41 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -461,6 +461,23 @@ def test_build_copy_layer_tar_matches_docker_copy_semantics(tmp_path: Path): assert names["testbed/sub/run.sh"].mode == 0o755 +def test_build_copy_layer_tar_copies_file_into_explicit_workdir(tmp_path: Path): + env_dir = tmp_path / "environment" + env_dir.mkdir() + (env_dir / "app.py").write_text("print('ok')\n", encoding="utf-8") + parsed = classify_dockerfile( + "FROM python:3.12-slim\nWORKDIR /app\nCOPY app.py /app\n" + ) + + gz, _ = build_copy_layer_tar(env_dir, parsed.copy_ops) + assert gz is not None + with tarfile.open(fileobj=io.BytesIO(gzip.decompress(gz)), mode="r:") as tar: + names = {member.name: member for member in tar.getmembers()} + + assert names["app"].isdir() + assert names["app/app.py"].isfile() + + def test_oci_registry_resolve_multiarch_and_append_layer(tmp_path: Path): fake = FakeOCIRegistry() base_digest = fake.seed_image( @@ -770,6 +787,34 @@ def test_cli_build_images_plan_json(tmp_path: Path): assert data["actions"]["build"] == 1 +def test_cli_verify_only_forwards_task_filter( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + captured: dict[str, Any] = {} + + def fake_verify(root: Path, **kwargs: Any) -> dict[str, Any]: + captured["root"] = root + captured.update(kwargs) + return {"total": 0, "ok": 0, "failed": 0, "tasks": {}} + + monkeypatch.setattr("openenv.harbor.images.verify_harbor_images", fake_verify) + + result = CliRunner().invoke( + app, + [ + "build-images", + str(tmp_path), + "--verify-only", + "--task", + "selected", + "--json", + ], + ) + + assert result.exit_code == 0, result.output + assert captured["task_ids"] == ["selected"] + + def test_docker_buildx_builder_invokes_amd64_and_reads_digest( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): From dd71b37ef74c0b20cb519b8df114c12d315ee2b8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 15:08:43 +0000 Subject: [PATCH 05/15] Fix recursive COPY glob builder fallback --- src/openenv/harbor/images.py | 7 +++++++ tests/test_cli/test_harbor_build_images.py | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 07dfef3bd7..93711cbf99 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -532,6 +532,13 @@ def classify_dockerfile(text: str) -> ParsedDockerfile: if len(items) < 2: raise HarborImageError(f"Malformed COPY instruction: {line!r}") + if any( + "**" in PurePosixPath(source.lstrip("/")).parts for source in items[:-1] + ): + is_copy_only = False + unsupported_flag = True + reasons.append("recursive '**' COPY glob") + if not unsupported_flag: copy_ops.append( CopyOp( diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 274abb8d41..bdf8692cd3 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -381,6 +381,10 @@ def test_classify_dockerfile_copy_only_vs_run(): ) assert non_numeric_chown.is_copy_only is False + recursive_glob = classify_dockerfile("FROM python:3.12-slim\nCOPY **/*.py /app/\n") + assert recursive_glob.is_copy_only is False + assert "recursive '**' COPY glob" in recursive_glob.reason + def test_audit_environment_blocks_leaks_symlinks_and_secrets(tmp_path: Path): clean = _write_task( From 6267807aaa8ec13641a05c243e9bfce6f0ad2031 Mon Sep 17 00:00:00 2001 From: Younes Belkada Date: Fri, 27 Nov 2026 11:33:31 +0400 Subject: [PATCH 06/15] fix(harbor): hash only what build-images copies into the image compute_environment_hash covered every file under environment/, so tasks with the same Dockerfile but different files the Dockerfile never reads (e.g. a source tree Harbor uploads at runtime) got different hashes and were each built and pushed again. On harness-hub/harness-adapters scale800_v1, 847 tasks share 14 Dockerfiles, none with COPY: 14 builds instead of hundreds. The hash now covers the Dockerfile and the files its COPY/ADD instructions read from the context. It falls back to the whole context when that cannot be told statically (RUN --mount, ARG-expanded or recursive '**' sources). Co-Authored-By: Claude Opus 5.5 --- src/openenv/harbor/images.py | 52 +++++++++++++++++++++- tests/test_cli/test_harbor_build_images.py | 47 +++++++++++++++++++ 2 files changed, 97 insertions(+), 2 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 93711cbf99..e1ffd7b82e 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -666,13 +666,50 @@ def audit_environment( return file_hashes +def _context_sources(dockerfile_text: str) -> list[str] | None: + """Build-context paths a Dockerfile reads through COPY/ADD, or ``None`` when that cannot be told statically. + + Files under ``environment/`` that no instruction reads (e.g. a source tree Harbor uploads at runtime) cannot + change the image, so they must not split otherwise identical builds. + """ + sources: list[str] = [] + for line in _join_dockerfile_lines(dockerfile_text): + op, _, rest = line.partition(" ") + if "--mount" in rest: # RUN --mount=type=bind reads the context without COPY + return None + if op.upper() not in {"COPY", "ADD"}: + continue + flags = [] + rest = rest.strip() + while rest.startswith("--"): + flag, _, rest = rest.partition(" ") + flags.append(flag) + rest = rest.lstrip() + if any( + flag.startswith("--from=") for flag in flags + ): # another stage or image, not the context + continue + try: + items = json.loads(rest) if rest.startswith("[") else shlex.split(rest) + except (json.JSONDecodeError, ValueError): + return None + for source in items[:-1]: + source = str(source) + if op.upper() == "ADD" and "://" in source: # a URL, not the context + continue + if "$" in source or "**" in PurePosixPath(source.lstrip("/")).parts: + return None + sources.append(source) + return sources + + def compute_environment_hash( task_dir: Path, *, extra_dockerfile: str | None = None, existing_docker_image: str | None = None, ) -> str: - """Deterministic SHA-256 of a task's effective build context.""" + """Deterministic SHA-256 of a task's effective build context: the Dockerfile and the files it copies.""" env_dir = task_dir / "environment" digest = hashlib.sha256() if extra_dockerfile: @@ -683,7 +720,18 @@ def compute_environment_hash( digest.update((existing_docker_image or "").encode("utf-8") + b"\0") return digest.hexdigest() - for path in sorted(env_dir.rglob("*")): + dockerfile = env_dir / "Dockerfile" + sources = _context_sources( + dockerfile.read_text(encoding="utf-8") + "\n" + (extra_dockerfile or "") + ) + if sources is None: + paths = set(env_dir.rglob("*")) + else: + paths = {dockerfile} + for source in sources: + for match in _resolve_copy_sources(env_dir, source): + paths |= {match, *match.rglob("*")} if match.is_dir() else {match} + for path in sorted(paths): if path.is_dir() or path.is_symlink(): continue rel = path.relative_to(env_dir).as_posix() diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index bdf8692cd3..aec1667bf5 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -20,6 +20,7 @@ build_copy_layer_tar, build_harbor_images, classify_dockerfile, + compute_environment_hash, DockerBuildxBuilder, HarborImageError, KanikoHFJobsBuilder, @@ -768,6 +769,52 @@ def build(self, **kwargs: Any) -> tuple[str, str]: assert run_calls == [] +def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Path): + run_df = "FROM python:3.12-slim\nWORKDIR /testbed\nRUN pip install pytest\n" + a = _write_task( + tmp_path, "a", dockerfile=run_df, env_files={"source/app.py": "x = 1\n"} + ) + b = _write_task( + tmp_path, "b", dockerfile=run_df, env_files={"source/app.py": "x = 2\n"} + ) + # Uploaded by Harbor at runtime, not baked into the image: one build serves both tasks + assert compute_environment_hash(a) == compute_environment_hash(b) + + copy_df = "FROM python:3.12-slim\nCOPY source/ /app/\n" + c = _write_task( + tmp_path, + "c", + dockerfile=copy_df, + env_files={"source/app.py": "x = 1\n", "notes.txt": "a"}, + ) + d = _write_task( + tmp_path, + "d", + dockerfile=copy_df, + env_files={"source/app.py": "x = 2\n", "notes.txt": "a"}, + ) + e = _write_task( + tmp_path, + "e", + dockerfile=copy_df, + env_files={"source/app.py": "x = 1\n", "notes.txt": "b"}, + ) + assert compute_environment_hash(c) != compute_environment_hash( + d + ) # copied file differs + assert compute_environment_hash(c) == compute_environment_hash( + e + ) # only an uncopied file differs + + # A bind mount reads the context without COPY: every file counts + mount_df = ( + "FROM python:3.12-slim\nRUN --mount=type=bind,target=/src pip install /src\n" + ) + f = _write_task(tmp_path, "f", dockerfile=mount_df, env_files={"setup.py": "a"}) + g = _write_task(tmp_path, "g", dockerfile=mount_df, env_files={"setup.py": "b"}) + assert compute_environment_hash(f) != compute_environment_hash(g) + + def test_cli_build_images_plan_json(tmp_path: Path): src = tmp_path / "suite" / "tasks" _write_task( From 66b5089a560cc90d26306521a4c1018db19abb89 Mon Sep 17 00:00:00 2001 From: Younes Belkada Date: Fri, 27 Nov 2026 11:51:59 +0400 Subject: [PATCH 07/15] fix(harbor): handle tabs, .dockerignore and heredocs in the environment hash Addresses the Bugbot review on #1758: - split instructions and COPY/ADD flags on any whitespace, like classify_dockerfile - hash .dockerignore with the copied files, since Kaniko and Buildx filter the context through it - fall back to the whole context for heredoc Dockerfiles, whose bodies are not instructions Co-Authored-By: Claude Opus 5.5 --- src/openenv/harbor/images.py | 12 +++++--- tests/test_cli/test_harbor_build_images.py | 33 ++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index e1ffd7b82e..f045949824 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -672,9 +672,13 @@ def _context_sources(dockerfile_text: str) -> list[str] | None: Files under ``environment/`` that no instruction reads (e.g. a source tree Harbor uploads at runtime) cannot change the image, so they must not split otherwise identical builds. """ + if ( + "<<" in dockerfile_text + ): # heredocs: their bodies are not instructions, and a COPY heredoc has no context path + return None sources: list[str] = [] for line in _join_dockerfile_lines(dockerfile_text): - op, _, rest = line.partition(" ") + op, rest = (line.split(None, 1) + [""])[:2] if "--mount" in rest: # RUN --mount=type=bind reads the context without COPY return None if op.upper() not in {"COPY", "ADD"}: @@ -682,9 +686,8 @@ def _context_sources(dockerfile_text: str) -> list[str] | None: flags = [] rest = rest.strip() while rest.startswith("--"): - flag, _, rest = rest.partition(" ") + flag, rest = (rest.split(None, 1) + [""])[:2] flags.append(flag) - rest = rest.lstrip() if any( flag.startswith("--from=") for flag in flags ): # another stage or image, not the context @@ -727,7 +730,8 @@ def compute_environment_hash( if sources is None: paths = set(env_dir.rglob("*")) else: - paths = {dockerfile} + # Kaniko and Buildx filter the context through .dockerignore + paths = {dockerfile, env_dir / ".dockerignore"} & set(env_dir.iterdir()) for source in sources: for match in _resolve_copy_sources(env_dir, source): paths |= {match, *match.rglob("*")} if match.is_dir() else {match} diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index aec1667bf5..4aeb8553e9 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -815,6 +815,39 @@ def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Pa assert compute_environment_hash(f) != compute_environment_hash(g) +def test_environment_hash_tabs_dockerignore_and_heredocs(tmp_path: Path): + tab_df = "FROM python:3.12-slim\nCOPY\tsource/ /app/\n" + a = _write_task( + tmp_path, "a", dockerfile=tab_df, env_files={"source/app.py": "x = 1\n"} + ) + b = _write_task( + tmp_path, "b", dockerfile=tab_df, env_files={"source/app.py": "x = 2\n"} + ) + assert compute_environment_hash(a) != compute_environment_hash(b) + + copy_df = "FROM python:3.12-slim\nCOPY source/ /app/\n" + c = _write_task( + tmp_path, + "c", + dockerfile=copy_df, + env_files={"source/app.py": "x\n", ".dockerignore": "*.pyc\n"}, + ) + d = _write_task( + tmp_path, + "d", + dockerfile=copy_df, + env_files={"source/app.py": "x\n", ".dockerignore": "*.md\n"}, + ) + assert compute_environment_hash(c) != compute_environment_hash(d) + + heredoc_df = "FROM python:3.12-slim\nCOPY < Date: Fri, 27 Nov 2026 12:03:18 +0400 Subject: [PATCH 08/15] fix(harbor): parse heredocs in the environment hash instead of hashing everything Addresses the follow-up Bugbot review on #1758: any `<<` (RUN heredocs, comments, --extra-dockerfile snippets) forced a full-context hash, bringing back the per-task rebuilds this change removes. Heredoc bodies are now skipped before parsing and COPY/ADD heredoc sources are ignored, since their payload lives in the already-hashed Dockerfile. Co-Authored-By: Claude Opus 5.5 --- src/openenv/harbor/images.py | 20 ++++++++++++++------ tests/test_cli/test_harbor_build_images.py | 15 +++++++++------ 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index f045949824..0a6494d304 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -672,12 +672,18 @@ def _context_sources(dockerfile_text: str) -> list[str] | None: Files under ``environment/`` that no instruction reads (e.g. a source tree Harbor uploads at runtime) cannot change the image, so they must not split otherwise identical builds. """ - if ( - "<<" in dockerfile_text - ): # heredocs: their bodies are not instructions, and a COPY heredoc has no context path - return None + # Heredoc bodies are not instructions: drop them before parsing (the Dockerfile itself is hashed anyway) + lines, end = [], None + for raw_line in dockerfile_text.splitlines(): + if end is not None: + end = None if raw_line.strip() == end else end + continue + lines.append(raw_line) + marker = re.search(r"<<-?\s*[\"']?([A-Za-z_][A-Za-z0-9_]*)", raw_line) + if marker and not raw_line.lstrip().startswith("#"): + end = marker.group(1) sources: list[str] = [] - for line in _join_dockerfile_lines(dockerfile_text): + for line in _join_dockerfile_lines("\n".join(lines)): op, rest = (line.split(None, 1) + [""])[:2] if "--mount" in rest: # RUN --mount=type=bind reads the context without COPY return None @@ -698,7 +704,9 @@ def _context_sources(dockerfile_text: str) -> list[str] | None: return None for source in items[:-1]: source = str(source) - if op.upper() == "ADD" and "://" in source: # a URL, not the context + if source.startswith("<<") or ( + op.upper() == "ADD" and "://" in source + ): # heredoc or URL continue if "$" in source or "**" in PurePosixPath(source.lstrip("/")).parts: return None diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 4aeb8553e9..ccb4a6f266 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -840,12 +840,15 @@ def test_environment_hash_tabs_dockerignore_and_heredocs(tmp_path: Path): ) assert compute_environment_hash(c) != compute_environment_hash(d) - heredoc_df = "FROM python:3.12-slim\nCOPY < Date: Fri, 27 Nov 2026 09:35:09 +0100 Subject: [PATCH 09/15] fix(harbor): make selective build context hashing explicit --- src/openenv/cli/commands/harbor.py | 9 ++ src/openenv/harbor/images.py | 99 ++++++++++++---------- tests/test_cli/test_harbor_build_images.py | 91 +++++++++++++++----- 3 files changed, 133 insertions(+), 66 deletions(-) diff --git a/src/openenv/cli/commands/harbor.py b/src/openenv/cli/commands/harbor.py index bd5776029d..f0842aeca3 100644 --- a/src/openenv/cli/commands/harbor.py +++ b/src/openenv/cli/commands/harbor.py @@ -420,6 +420,13 @@ def build_images( help="Optional OCI repository for Kaniko / BuildKit layer cache (e.g. ghcr.io/org/repo-cache).", ), ] = "", + assume_static_context: Annotated[ + bool, + typer.Option( + "--assume-static-context", + help="Deduplicate using literal Dockerfile inputs when base images have no inherited ONBUILD triggers.", + ), + ] = False, no_oci_append: Annotated[ bool, typer.Option( @@ -550,6 +557,7 @@ def build_images( extra_dockerfile=extra_text, skip_pinned=not rebuild_pinned, allow_oci_append=not no_oci_append, + assume_static_context=assume_static_context, task_ids=task or None, ) unique_envs = len({(p.action, p.env_hash) for p in plans}) @@ -604,6 +612,7 @@ def build_images( extra_dockerfile=extra_text, skip_pinned=not rebuild_pinned, allow_oci_append=not no_oci_append, + assume_static_context=assume_static_context, strip_dockerfile_for_shared=strip_dockerfile, verify_public=verify_public, no_push=no_push, diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 0a6494d304..9ef65fcc5b 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -667,48 +667,39 @@ def audit_environment( def _context_sources(dockerfile_text: str) -> list[str] | None: - """Build-context paths a Dockerfile reads through COPY/ADD, or ``None`` when that cannot be told statically. + """Return literal context sources, or None when the syntax is ambiguous.""" + if re.search(r"(?im)^\s*#\s*(?:escape|syntax)\s*=", dockerfile_text): + return None - Files under ``environment/`` that no instruction reads (e.g. a source tree Harbor uploads at runtime) cannot - change the image, so they must not split otherwise identical builds. - """ - # Heredoc bodies are not instructions: drop them before parsing (the Dockerfile itself is hashed anyway) - lines, end = [], None + sources: list[str] = [] for raw_line in dockerfile_text.splitlines(): - if end is not None: - end = None if raw_line.strip() == end else end + line = raw_line.strip() + if not line or line.startswith("#"): continue - lines.append(raw_line) - marker = re.search(r"<<-?\s*[\"']?([A-Za-z_][A-Za-z0-9_]*)", raw_line) - if marker and not raw_line.lstrip().startswith("#"): - end = marker.group(1) - sources: list[str] = [] - for line in _join_dockerfile_lines("\n".join(lines)): + if "<<" in line or line.endswith("\\"): + return None op, rest = (line.split(None, 1) + [""])[:2] - if "--mount" in rest: # RUN --mount=type=bind reads the context without COPY + op = op.upper() + if op == "ONBUILD" or (op == "RUN" and "--mount" in rest): return None - if op.upper() not in {"COPY", "ADD"}: - continue - flags = [] - rest = rest.strip() - while rest.startswith("--"): - flag, rest = (rest.split(None, 1) + [""])[:2] - flags.append(flag) - if any( - flag.startswith("--from=") for flag in flags - ): # another stage or image, not the context + if op not in {"COPY", "ADD"}: continue + + if rest.startswith("--"): + return None try: - items = json.loads(rest) if rest.startswith("[") else shlex.split(rest) - except (json.JSONDecodeError, ValueError): + if rest.startswith("["): + items = json.loads(rest) + elif any(char in rest for char in ("\\", '"', "'")): + return None + else: + items = rest.split() + except ValueError: + return None + if len(items) < 2 or not all(isinstance(item, str) and item for item in items): return None for source in items[:-1]: - source = str(source) - if source.startswith("<<") or ( - op.upper() == "ADD" and "://" in source - ): # heredoc or URL - continue - if "$" in source or "**" in PurePosixPath(source.lstrip("/")).parts: + if any(char in source for char in "$*?[\\") or "://" in source: return None sources.append(source) return sources @@ -719,9 +710,10 @@ def compute_environment_hash( *, extra_dockerfile: str | None = None, existing_docker_image: str | None = None, + assume_static_context: bool = False, ) -> str: - """Deterministic SHA-256 of a task's effective build context: the Dockerfile and the files it copies.""" - env_dir = task_dir / "environment" + """Hash the context, optionally limiting it to literal Dockerfile inputs.""" + env_dir = (task_dir / "environment").resolve() digest = hashlib.sha256() if extra_dockerfile: digest.update(b"EXTRA_DOCKERFILE\0") @@ -732,17 +724,28 @@ def compute_environment_hash( return digest.hexdigest() dockerfile = env_dir / "Dockerfile" - sources = _context_sources( - dockerfile.read_text(encoding="utf-8") + "\n" + (extra_dockerfile or "") - ) - if sources is None: + paths = None + if assume_static_context: + text = dockerfile.read_text(encoding="utf-8") + if extra_dockerfile: + text = text.rstrip() + "\n" + extra_dockerfile.strip() + "\n" + sources = _context_sources(text) + if sources is not None: + paths = { + dockerfile, + env_dir / ".dockerignore", + env_dir / "Dockerfile.dockerignore", + } & set(env_dir.iterdir()) + try: + for source in sources: + for match in _resolve_copy_sources(env_dir, source): + paths.add(match) + if match.is_dir(): + paths.update(match.rglob("*")) + except HarborImageError: + paths = None + if paths is None: paths = set(env_dir.rglob("*")) - else: - # Kaniko and Buildx filter the context through .dockerignore - paths = {dockerfile, env_dir / ".dockerignore"} & set(env_dir.iterdir()) - for source in sources: - for match in _resolve_copy_sources(env_dir, source): - paths |= {match, *match.rglob("*")} if match.is_dir() else {match} for path in sorted(paths): if path.is_dir() or path.is_symlink(): continue @@ -1922,6 +1925,7 @@ def plan_harbor_images( extra_dockerfile: str | None = None, skip_pinned: bool = True, allow_oci_append: bool = True, + assume_static_context: bool = False, task_ids: list[str] | None = None, ) -> list[TaskImagePlan]: """Audit, classify, and plan image operations for every Harbor task under ``root``.""" @@ -1948,6 +1952,7 @@ def plan_harbor_images( task_dir, extra_dockerfile=extra_dockerfile, existing_docker_image=existing, + assume_static_context=assume_static_context, ) if not has_dockerfile: @@ -1989,7 +1994,7 @@ def plan_harbor_images( task_id=task_id, task_dir=task_dir, action="keep_pinned", - env_hash=env_hash, + env_hash=_sha256_bytes(existing.encode("utf-8")), reason="task.toml already has a digest-pinned docker_image", base_image=existing, existing_docker_image=existing, @@ -2105,6 +2110,7 @@ def build_harbor_images( extra_dockerfile: str | None = None, skip_pinned: bool = True, allow_oci_append: bool = True, + assume_static_context: bool = False, strip_dockerfile_for_shared: bool = False, verify_public: bool = True, no_push: bool = False, @@ -2135,6 +2141,7 @@ def build_harbor_images( extra_dockerfile=extra_dockerfile, skip_pinned=skip_pinned, allow_oci_append=allow_oci_append, + assume_static_context=assume_static_context, task_ids=task_ids, ) diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index ccb4a6f266..0d71c2e2d6 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -778,7 +778,9 @@ def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Pa tmp_path, "b", dockerfile=run_df, env_files={"source/app.py": "x = 2\n"} ) # Uploaded by Harbor at runtime, not baked into the image: one build serves both tasks - assert compute_environment_hash(a) == compute_environment_hash(b) + assert compute_environment_hash( + a, assume_static_context=True + ) == compute_environment_hash(b, assume_static_context=True) copy_df = "FROM python:3.12-slim\nCOPY source/ /app/\n" c = _write_task( @@ -799,11 +801,13 @@ def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Pa dockerfile=copy_df, env_files={"source/app.py": "x = 1\n", "notes.txt": "b"}, ) - assert compute_environment_hash(c) != compute_environment_hash( - d - ) # copied file differs - assert compute_environment_hash(c) == compute_environment_hash( - e + assert compute_environment_hash( + c, assume_static_context=True + ) != compute_environment_hash(d, assume_static_context=True) # copied file differs + assert compute_environment_hash( + c, assume_static_context=True + ) == compute_environment_hash( + e, assume_static_context=True ) # only an uncopied file differs # A bind mount reads the context without COPY: every file counts @@ -812,10 +816,13 @@ def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Pa ) f = _write_task(tmp_path, "f", dockerfile=mount_df, env_files={"setup.py": "a"}) g = _write_task(tmp_path, "g", dockerfile=mount_df, env_files={"setup.py": "b"}) - assert compute_environment_hash(f) != compute_environment_hash(g) + assert compute_environment_hash( + f, assume_static_context=True + ) != compute_environment_hash(g, assume_static_context=True) -def test_environment_hash_tabs_dockerignore_and_heredocs(tmp_path: Path): +@pytest.mark.parametrize("ignore_file", [".dockerignore", "Dockerfile.dockerignore"]) +def test_environment_hash_tabs_and_ignore_rules(tmp_path: Path, ignore_file: str): tab_df = "FROM python:3.12-slim\nCOPY\tsource/ /app/\n" a = _write_task( tmp_path, "a", dockerfile=tab_df, env_files={"source/app.py": "x = 1\n"} @@ -823,32 +830,76 @@ def test_environment_hash_tabs_dockerignore_and_heredocs(tmp_path: Path): b = _write_task( tmp_path, "b", dockerfile=tab_df, env_files={"source/app.py": "x = 2\n"} ) - assert compute_environment_hash(a) != compute_environment_hash(b) + assert compute_environment_hash( + a, assume_static_context=True + ) != compute_environment_hash(b, assume_static_context=True) copy_df = "FROM python:3.12-slim\nCOPY source/ /app/\n" c = _write_task( tmp_path, "c", dockerfile=copy_df, - env_files={"source/app.py": "x\n", ".dockerignore": "*.pyc\n"}, + env_files={"source/app.py": "x\n", ignore_file: "*.pyc\n"}, ) d = _write_task( tmp_path, "d", dockerfile=copy_df, - env_files={"source/app.py": "x\n", ".dockerignore": "*.md\n"}, + env_files={"source/app.py": "x\n", ignore_file: "*.md\n"}, ) - assert compute_environment_hash(c) != compute_environment_hash(d) + assert compute_environment_hash( + c, assume_static_context=True + ) != compute_environment_hash(d, assume_static_context=True) + + +@pytest.mark.parametrize( + "instructions", + [ + 'ENV TEMPLATE="<>"\nCOPY source/ /app/\n', + "RUN < Date: Wed, 2 Dec 2026 11:44:59 +0000 Subject: [PATCH 10/15] fix(harbor): scope explicit registry credentials to the push registry Co-authored-by: burtenshaw --- src/openenv/harbor/images.py | 37 +++++++++++++++------- tests/test_cli/test_harbor_build_images.py | 19 +++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 9ef65fcc5b..84b6f53dc1 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -803,19 +803,27 @@ def resolve_registry_credentials( *, username: str | None = None, password: str | None = None, + registry_scoped: bool = True, ) -> tuple[str, str] | None: - """Resolve registry credentials from explicit args, env vars, or Docker config.""" + """Resolve registry credentials from explicit args, env vars, or Docker config. + + Explicit arguments and the registry-agnostic ``REGISTRY_*`` variables are only + used when ``registry_scoped`` is true, i.e. when ``registry`` is the push target. + """ + if not registry_scoped: + username = password = None if username and password: return username, password - env_user = os.environ.get("OPENENV_REGISTRY_USERNAME") or os.environ.get( - "REGISTRY_USERNAME" - ) - env_pass = os.environ.get("OPENENV_REGISTRY_PASSWORD") or os.environ.get( - "REGISTRY_PASSWORD" - ) - if env_user and env_pass: - return env_user, env_pass + if registry_scoped: + env_user = os.environ.get("OPENENV_REGISTRY_USERNAME") or os.environ.get( + "REGISTRY_USERNAME" + ) + env_pass = os.environ.get("OPENENV_REGISTRY_PASSWORD") or os.environ.get( + "REGISTRY_PASSWORD" + ) + if env_user and env_pass: + return env_user, env_pass if registry == "ghcr.io": token = ( @@ -877,8 +885,10 @@ def __init__( username: str | None = None, password: str | None = None, anonymous: bool = False, + credential_registry: str | None = None, timeout: float = 60.0, ) -> None: + self._credential_registry = credential_registry self._owns_http = http is None self._http = http or httpx.Client(timeout=timeout, follow_redirects=False) self._username = None if anonymous else username @@ -904,7 +914,10 @@ def _credentials_for(self, registry: str) -> tuple[str, str] | None: if self._anonymous: return None return resolve_registry_credentials( - registry, username=self._username, password=self._password + registry, + username=self._username, + password=self._password, + registry_scoped=self._credential_registry in {None, registry}, ) def _send_with_redirects( @@ -2227,7 +2240,9 @@ def build_harbor_images( own_reg = registry_client is None own_pub = public_client is None reg_client = registry_client or OCIRegistryClient( - username=registry_username, password=registry_password + username=registry_username, + password=registry_password, + credential_registry=parse_image_ref(effective_registry).registry, ) pub_client = public_client or OCIRegistryClient(anonymous=True) diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 0d71c2e2d6..9c512d91b8 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -27,6 +27,7 @@ OCIRegistryClient, parse_image_ref, parse_kaniko_digest, + resolve_registry_credentials, sanitize_tag, update_task_toml, verify_harbor_images, @@ -1055,3 +1056,21 @@ def test_output_dir_overlap_rejected_and_verify_only_honors_task_filter( registry_client=pub, ) assert res["total"] == 1 and res["ok"] == 1 and res["failed"] == 0 + + +def test_explicit_credentials_are_only_sent_to_the_push_registry(monkeypatch): + for var in ("GHCR_TOKEN", "CR_PAT", "GITHUB_TOKEN", "DOCKER_PASSWORD"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setenv("DOCKER_CONFIG", "/nonexistent") + monkeypatch.setenv("REGISTRY_USERNAME", "env-user") + monkeypatch.setenv("REGISTRY_PASSWORD", "env-pass") + + client = OCIRegistryClient( + username="user", password="secret", credential_registry="ghcr.io" + ) + try: + assert client._credentials_for("ghcr.io") == ("user", "secret") + assert client._credentials_for("untrusted.example") is None + finally: + client.close() + assert resolve_registry_credentials("other.example", registry_scoped=False) is None From fc0d5812d6c5a173c35df0bb500e43011e1d08b7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 11:45:22 +0000 Subject: [PATCH 11/15] docs(harbor): document openenv harbor build-images Co-authored-by: burtenshaw --- docs/source/environments/harbor.md | 56 +++++++++++++++++++++++++++++- docs/source/reference/cli.md | 1 + 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/docs/source/environments/harbor.md b/docs/source/environments/harbor.md index 25dbe55117..90278ec478 100644 --- a/docs/source/environments/harbor.md +++ b/docs/source/environments/harbor.md @@ -383,7 +383,7 @@ What the UI guarantees whatever the settings: ## CLI reference -Four commands. Every flag below is the complete set, with its type and default. +Five commands. Every flag below is the complete set, with its type and default. `openenv harbor --help` prints the same thing. Exit codes: @@ -531,6 +531,60 @@ openenv harbor push --llm-url $LLM --dataset org/train,org/eval \ at `/capture`, and a private Space requires an auth header the sandboxed agent does not send. Use it only to park a deployment. +### `openenv harbor build-images` + +Turn Harbor task directories into tasks whose `task.toml` pins a public, digest-pinned +`linux/amd64` image (`[environment].docker_image = "@sha256:"`), as required by +prebuilt-image sandboxes such as HF Sandbox. It pushes to any OCI registry (GHCR, Docker Hub, a +local `registry:2`) and does not need the `harbor` extra. + +`PATH` is a single task directory (with `task.toml`) or a dataset directory of tasks. Each task's +`environment/` is audited first (symlinks, `COPY`/`ADD` of `tests/` or `solution/`, files that +duplicate verifier or solution bytes, embedded tokens or private keys), then tasks with the same +build context are deduplicated and routed: + +| `environment/Dockerfile` | what runs | +|---|---| +| none, existing `docker_image` | the image is verified and digest-pinned | +| only `FROM`, `COPY`, `WORKDIR`, `ENV`, `LABEL`, `ARG`, `EXPOSE` | pure-Python OCI layer append, no Docker daemon | +| has `RUN` or multiple stages | `--builder kaniko` (Kaniko on HF Jobs) or `--builder docker` (local `docker buildx`) | + +| flag | type | default | meaning | +|---|---|---|---| +| `--registry` | str | `""` | Target OCI repository, e.g. `ghcr.io/org/tasks`. Required unless nothing needs pushing | +| `--builder` | str | `auto` | `auto`, `kaniko`, `docker` or `oci-append`. `auto` picks Kaniko when `--namespace` is set or Docker is missing | +| `--plan` | flag | off | Audit, classify and deduplicate only; build and push nothing | +| `--verify-only` | flag | off | Check that every `task.toml` points to a pullable `linux/amd64` image | +| `--require-digest-pin` | flag | off | With `--verify-only`, fail on mutable tags | +| `--output-dir` / `--in-place` | path / flag | none | Write pinned copies of the tasks to a new directory, or rewrite each `task.toml`. Mutually exclusive; without either, only receipts are written | +| `--receipts` | path | none | JSON manifest of resolved digests, also used to resume | +| `--per-task-receipts-dir` | path | none | One `.json` receipt per task, written as each finishes | +| `--task` | str | all | Only this task id. Repeatable | +| `--extra-dockerfile` | path | none | Fragment appended to every task's Dockerfile | +| `--tag-prefix` | str | `""` | Prefix for pushed tags | +| `--concurrency` | int | `4` | Parallel builds, appends and registry checks | +| `--namespace`, `--flavor`, `--timeout`, `--kaniko-image`, `--bucket`, `--cache-repo` | str | see `--help` | Kaniko on HF Jobs: namespace, hardware flavor, job timeout, Kaniko image, private bucket holding the temporary build context, optional layer-cache repository | +| `--no-oci-append` | flag | off | Send `COPY`-only Dockerfiles through `--builder` too | +| `--rebuild-pinned` | flag | off | Rebuild tasks that already pin a digest | +| `--strip-dockerfile` | flag | off | Remove `environment/Dockerfile` from shared-image tasks | +| `--assume-static-context` | flag | off | Hash only the files the Dockerfile copies. Use when base images have no `ONBUILD` triggers | +| `--verify-public/--no-verify-public` | flag | on | Verify the pushed image pulls anonymously | +| `--no-push` | flag | off | Build without pushing | +| `--registry-user`, `--registry-password` | str | `""` | Push credentials. Prefer `GHCR_TOKEN`, `DOCKER_PASSWORD` or `REGISTRY_USERNAME`/`REGISTRY_PASSWORD`, or `~/.docker/config.json`. Explicit and `REGISTRY_*` credentials are only sent to the `--registry` host | +| `--json` | flag | off | Machine-readable output | + +Kaniko builds authenticate to the Hub with your usual `HF_TOKEN` / `hf auth login`. The push +credential is passed to the job as an HF Jobs secret and written to `/kaniko/.docker/config.json` +inside it. Kaniko is not a sandbox: `RUN` steps can read that file, so only build Dockerfiles you +trust, and use a push token scoped to the target repository. + +```bash +openenv harbor build-images tasks/ --plan --registry ghcr.io/org/tasks +openenv harbor build-images tasks/ --registry ghcr.io/org/tasks --builder kaniko \ + --namespace org --output-dir tasks-pinned/ --receipts receipts.json +openenv harbor build-images tasks-pinned/ --verify-only --require-digest-pin +``` + ### Migration notes for the new UI - `serve` binds `0.0.0.0` by default and therefore uses the network-safe UI defaults. Visitor diff --git a/docs/source/reference/cli.md b/docs/source/reference/cli.md index 3c1e743e37..ccebe81403 100644 --- a/docs/source/reference/cli.md +++ b/docs/source/reference/cli.md @@ -469,6 +469,7 @@ captures the token ids and logprobs of every model call. Requires | `openenv harbor rollout` | Runs one or more rollouts end to end without a server. | | `openenv harbor serve` | Serves Harbor tasks over the Task API and MCP, with a UI at `/web`. | | `openenv harbor push` | Deploys the same server to a Hugging Face Space. | +| `openenv harbor build-images` | Builds or appends, pushes and digest-pins the OCI images Harbor tasks need for prebuilt-image sandboxes. Does not need the `harbor` extra. | ```bash openenv harbor info --llm-url $LLM --dataset AdithyaSK/data_agent_rl_environment_eval From 81a472e28fd899141b4951bb06acd10465ea9591 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 11:47:11 +0000 Subject: [PATCH 12/15] docs(harbor): document build-images in the harbor_env README and synced stub Co-authored-by: burtenshaw --- envs/harbor_env/README.md | 56 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/envs/harbor_env/README.md b/envs/harbor_env/README.md index 6fea5666a5..a8822eb338 100644 --- a/envs/harbor_env/README.md +++ b/envs/harbor_env/README.md @@ -395,7 +395,7 @@ What the UI guarantees whatever the settings: ## CLI reference -Four commands. Every flag below is the complete set, with its type and default. +Five commands. Every flag below is the complete set, with its type and default. `openenv harbor --help` prints the same thing. Exit codes: @@ -543,6 +543,60 @@ openenv harbor push --llm-url $LLM --dataset org/train,org/eval \ at `/capture`, and a private Space requires an auth header the sandboxed agent does not send. Use it only to park a deployment. +### `openenv harbor build-images` + +Turn Harbor task directories into tasks whose `task.toml` pins a public, digest-pinned +`linux/amd64` image (`[environment].docker_image = "@sha256:"`), as required by +prebuilt-image sandboxes such as HF Sandbox. It pushes to any OCI registry (GHCR, Docker Hub, a +local `registry:2`) and does not need the `harbor` extra. + +`PATH` is a single task directory (with `task.toml`) or a dataset directory of tasks. Each task's +`environment/` is audited first (symlinks, `COPY`/`ADD` of `tests/` or `solution/`, files that +duplicate verifier or solution bytes, embedded tokens or private keys), then tasks with the same +build context are deduplicated and routed: + +| `environment/Dockerfile` | what runs | +|---|---| +| none, existing `docker_image` | the image is verified and digest-pinned | +| only `FROM`, `COPY`, `WORKDIR`, `ENV`, `LABEL`, `ARG`, `EXPOSE` | pure-Python OCI layer append, no Docker daemon | +| has `RUN` or multiple stages | `--builder kaniko` (Kaniko on HF Jobs) or `--builder docker` (local `docker buildx`) | + +| flag | type | default | meaning | +|---|---|---|---| +| `--registry` | str | `""` | Target OCI repository, e.g. `ghcr.io/org/tasks`. Required unless nothing needs pushing | +| `--builder` | str | `auto` | `auto`, `kaniko`, `docker` or `oci-append`. `auto` picks Kaniko when `--namespace` is set or Docker is missing | +| `--plan` | flag | off | Audit, classify and deduplicate only; build and push nothing | +| `--verify-only` | flag | off | Check that every `task.toml` points to a pullable `linux/amd64` image | +| `--require-digest-pin` | flag | off | With `--verify-only`, fail on mutable tags | +| `--output-dir` / `--in-place` | path / flag | none | Write pinned copies of the tasks to a new directory, or rewrite each `task.toml`. Mutually exclusive; without either, only receipts are written | +| `--receipts` | path | none | JSON manifest of resolved digests, also used to resume | +| `--per-task-receipts-dir` | path | none | One `.json` receipt per task, written as each finishes | +| `--task` | str | all | Only this task id. Repeatable | +| `--extra-dockerfile` | path | none | Fragment appended to every task's Dockerfile | +| `--tag-prefix` | str | `""` | Prefix for pushed tags | +| `--concurrency` | int | `4` | Parallel builds, appends and registry checks | +| `--namespace`, `--flavor`, `--timeout`, `--kaniko-image`, `--bucket`, `--cache-repo` | str | see `--help` | Kaniko on HF Jobs: namespace, hardware flavor, job timeout, Kaniko image, private bucket holding the temporary build context, optional layer-cache repository | +| `--no-oci-append` | flag | off | Send `COPY`-only Dockerfiles through `--builder` too | +| `--rebuild-pinned` | flag | off | Rebuild tasks that already pin a digest | +| `--strip-dockerfile` | flag | off | Remove `environment/Dockerfile` from shared-image tasks | +| `--assume-static-context` | flag | off | Hash only the files the Dockerfile copies. Use when base images have no `ONBUILD` triggers | +| `--verify-public/--no-verify-public` | flag | on | Verify the pushed image pulls anonymously | +| `--no-push` | flag | off | Build without pushing | +| `--registry-user`, `--registry-password` | str | `""` | Push credentials. Prefer `GHCR_TOKEN`, `DOCKER_PASSWORD` or `REGISTRY_USERNAME`/`REGISTRY_PASSWORD`, or `~/.docker/config.json`. Explicit and `REGISTRY_*` credentials are only sent to the `--registry` host | +| `--json` | flag | off | Machine-readable output | + +Kaniko builds authenticate to the Hub with your usual `HF_TOKEN` / `hf auth login`. The push +credential is passed to the job as an HF Jobs secret and written to `/kaniko/.docker/config.json` +inside it. Kaniko is not a sandbox: `RUN` steps can read that file, so only build Dockerfiles you +trust, and use a push token scoped to the target repository. + +```bash +openenv harbor build-images tasks/ --plan --registry ghcr.io/org/tasks +openenv harbor build-images tasks/ --registry ghcr.io/org/tasks --builder kaniko \ + --namespace org --output-dir tasks-pinned/ --receipts receipts.json +openenv harbor build-images tasks-pinned/ --verify-only --require-digest-pin +``` + ### Migration notes for the new UI - `serve` binds `0.0.0.0` by default and therefore uses the network-safe UI defaults. Visitor From d4906111c7feacba598b55ae03d9879d00718077 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 12:01:00 +0000 Subject: [PATCH 13/15] fix(harbor): drop registry auth on cross-host uploads, fall back from OCI append for unresolved vars and .dockerignore, resume from any dedup sibling Co-authored-by: burtenshaw --- src/openenv/harbor/images.py | 36 ++++++++++- tests/test_cli/test_harbor_build_images.py | 71 ++++++++++++++++++++++ 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 84b6f53dc1..d134f8ef7c 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -28,6 +28,7 @@ import base64 import copy +import dataclasses import gzip import hashlib import io @@ -472,6 +473,9 @@ def classify_dockerfile(text: str) -> ParsedDockerfile: if op == "WORKDIR": raw_wd = _expand_args(shlex.split(rest)[0], args) if rest else "/" + if "$" in raw_wd: + is_copy_only = False + reasons.append("unresolved variable in WORKDIR") workdir = _normalize_container_path(raw_wd, workdir).rstrip("/") or "/" explicit_workdir = workdir elif op == "ENV": @@ -532,6 +536,11 @@ def classify_dockerfile(text: str) -> ParsedDockerfile: if len(items) < 2: raise HarborImageError(f"Malformed COPY instruction: {line!r}") + if any("$" in item for item in items): + is_copy_only = False + unsupported_flag = True + reasons.append("unresolved variable in COPY") + if any( "**" in PurePosixPath(source.lstrip("/")).parts for source in items[:-1] ): @@ -978,6 +987,10 @@ def _request( else f"{self._base_url(registry)}{path_or_url}" ) req_headers = dict(headers or {}) + if urlsplit(url).netloc != registry: + return self._send_with_redirects( + method, url, headers=req_headers, content=content, params=params + ) token_cache_key = (registry, scope_key) cached = self._tokens.get(token_cache_key) if cached: @@ -2020,6 +2033,16 @@ def plan_harbor_images( if extra_dockerfile: df_text = df_text.rstrip() + "\n" + extra_dockerfile.strip() + "\n" parsed = classify_dockerfile(df_text) + env_dir = task_dir / "environment" + if parsed.is_copy_only and any( + (env_dir / name).exists() + for name in (".dockerignore", "Dockerfile.dockerignore") + ): + parsed = dataclasses.replace( + parsed, + is_copy_only=False, + reason=".dockerignore is not applied by OCI append", + ) action = "oci_append" if (allow_oci_append and parsed.is_copy_only) else "build" target_tag = sanitize_tag(task_id, prefix=tag_prefix) if registry is not None: @@ -2208,7 +2231,7 @@ def build_harbor_images( if builder == "oci-append": run_tasks = [p.task_id for p in plans if p.action == "build"] raise HarborImageError( - f"Tasks require RUN instructions (cannot use --builder oci-append): {run_tasks[:5]}" + f"Tasks cannot use the OCI append path (RUN, multi-stage or unsupported COPY): {run_tasks[:5]}" ) chosen = builder if chosen == "auto": @@ -2259,8 +2282,15 @@ def execute_group( action, env_hash = key rep = members[0] - # Check resumable cache on representative task. - cached = prior_receipts.get(rep.task_id) + cached = next( + ( + prior_receipts[m.task_id] + for m in members + if isinstance(prior_receipts.get(m.task_id), dict) + and prior_receipts[m.task_id].get("env_hash") == env_hash + ), + None, + ) if ( not no_push and isinstance(cached, dict) diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 9c512d91b8..cf1716c1b9 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -27,6 +27,7 @@ OCIRegistryClient, parse_image_ref, parse_kaniko_digest, + plan_harbor_images, resolve_registry_credentials, sanitize_tag, update_task_toml, @@ -769,6 +770,23 @@ def build(self, **kwargs: Any) -> tuple[str, str]: assert resumed["resolved"] == 2 assert run_calls == [] + # A receipt for any member of a deduplicated group is enough to resume it. + (per_task_dir / "go-a.json").unlink() + progress: list[str] = [] + build_harbor_images( + tmp_path / "src", + registry="ghcr.io/harness-hub/corpus", + builder="kaniko", + per_task_receipts_dir=per_task_dir, + task_ids=["go-a", "go-b"], + run_builder=StubRunBuilder(), + registry_client=reg, + public_client=pub, + progress=progress.append, + ) + assert any(line.startswith("reuse") for line in progress) + assert not any(line.startswith("append") for line in progress) + def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Path): run_df = "FROM python:3.12-slim\nWORKDIR /testbed\nRUN pip install pytest\n" @@ -1074,3 +1092,56 @@ def test_explicit_credentials_are_only_sent_to_the_push_registry(monkeypatch): finally: client.close() assert resolve_registry_credentials("other.example", registry_scoped=False) is None + + +def test_unresolved_variables_and_dockerignore_disable_oci_append(tmp_path: Path): + assert ( + classify_dockerfile( + "FROM base\nENV APP=/app\nWORKDIR $APP\nCOPY a.txt .\n" + ).is_copy_only + is False + ) + assert ( + classify_dockerfile("FROM base\nENV APP=/app\nCOPY a.txt $APP/\n").is_copy_only + is False + ) + assert ( + classify_dockerfile( + "FROM base\nARG APP=/app\nWORKDIR $APP\nCOPY a.txt .\n" + ).is_copy_only + is True + ) + + dockerfile = "FROM ghcr.io/harness-hub/base:v1\nCOPY a.txt /a.txt\n" + _write_task(tmp_path, "plain", dockerfile=dockerfile, env_files={"a.txt": "a"}) + _write_task( + tmp_path, + "ignored", + dockerfile=dockerfile, + env_files={"a.txt": "a", ".dockerignore": "b.txt\n"}, + ) + actions = {p.task_id: p.action for p in plan_harbor_images(tmp_path, registry=None)} + assert actions == {"plain": "oci_append", "ignored": "build"} + + +def test_registry_auth_is_not_sent_to_other_hosts(): + seen: list[tuple[str, str | None]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append((request.url.host, request.headers.get("Authorization"))) + return httpx.Response(201) + + client = OCIRegistryClient( + http=httpx.Client(transport=httpx.MockTransport(handler)), + username="user", + password="secret", + ) + client._tokens[("ghcr.io", "push:org/repo")] = "Bearer cached" + for url in ( + "https://ghcr.io/v2/org/repo/blobs/uploads/x", + "https://storage.example/x", + ): + client._request( + "PUT", "ghcr.io", url, scope_key="push:org/repo", content=b"data" + ) + assert seen == [("ghcr.io", "Bearer cached"), ("storage.example", None)] From 191ded6f60f7a777e93c8936476974aa6c7e0db8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 12:01:17 +0000 Subject: [PATCH 14/15] Fix Harbor image build edge cases --- src/openenv/harbor/images.py | 131 +++++++++++++++++---- tests/test_cli/test_harbor_build_images.py | 85 +++++++++++++ 2 files changed, 192 insertions(+), 24 deletions(-) diff --git a/src/openenv/harbor/images.py b/src/openenv/harbor/images.py index 84b6f53dc1..d31140dabd 100644 --- a/src/openenv/harbor/images.py +++ b/src/openenv/harbor/images.py @@ -28,6 +28,7 @@ import base64 import copy +import fnmatch import gzip import hashlib import io @@ -470,19 +471,20 @@ def classify_dockerfile(text: str) -> ParsedDockerfile: reasons.append(f"contains {op}") continue + variables = {**args, **env} if op == "WORKDIR": - raw_wd = _expand_args(shlex.split(rest)[0], args) if rest else "/" + raw_wd = _expand_args(shlex.split(rest)[0], variables) if rest else "/" workdir = _normalize_container_path(raw_wd, workdir).rstrip("/") or "/" explicit_workdir = workdir elif op == "ENV": try: - env.update(_parse_kv_pairs(rest, args)) + env.update(_parse_kv_pairs(rest, variables)) except ValueError: is_copy_only = False reasons.append("complex ENV") elif op == "LABEL": try: - labels.update(_parse_kv_pairs(rest, args)) + labels.update(_parse_kv_pairs(rest, variables)) except ValueError: is_copy_only = False reasons.append("complex LABEL") @@ -526,9 +528,9 @@ def classify_dockerfile(text: str) -> ParsedDockerfile: ) from exc if not isinstance(items, list) or len(items) < 2: raise HarborImageError(f"Malformed COPY instruction: {line!r}") - items = [_expand_args(str(item), args) for item in items] + items = [_expand_args(str(item), variables) for item in items] else: - items = [_expand_args(tok, args) for tok in shlex.split(copy_rest)] + items = [_expand_args(tok, variables) for tok in shlex.split(copy_rest)] if len(items) < 2: raise HarborImageError(f"Malformed COPY instruction: {line!r}") @@ -979,14 +981,16 @@ def _request( ) req_headers = dict(headers or {}) token_cache_key = (registry, scope_key) - cached = self._tokens.get(token_cache_key) - if cached: - req_headers["Authorization"] = cached + is_registry_url = urlsplit(url).netloc.lower() == registry.lower() + if is_registry_url: + cached = self._tokens.get(token_cache_key) + if cached: + req_headers["Authorization"] = cached resp = self._send_with_redirects( method, url, headers=req_headers, content=content, params=params ) - if resp.status_code != 401: + if resp.status_code != 401 or not is_registry_url: return resp challenge = resp.headers.get("WWW-Authenticate", "") @@ -1382,6 +1386,73 @@ def _resolve_copy_sources(context_dir: Path, pattern: str) -> list[Path]: return [candidate] +def _match_dockerignore_path(path: str, pattern: str) -> bool: + path_parts = PurePosixPath(path).parts + pattern_parts = PurePosixPath(pattern).parts + + def match(path_idx: int, pattern_idx: int) -> bool: + if pattern_idx == len(pattern_parts): + return path_idx == len(path_parts) + if pattern_parts[pattern_idx] == "**": + return match(path_idx, pattern_idx + 1) or ( + path_idx < len(path_parts) and match(path_idx + 1, pattern_idx) + ) + return ( + path_idx < len(path_parts) + and fnmatch.fnmatchcase(path_parts[path_idx], pattern_parts[pattern_idx]) + and match(path_idx + 1, pattern_idx + 1) + ) + + return match(0, 0) + + +def _dockerignore_patterns(context_dir: Path) -> list[tuple[str, bool]]: + ignore_path = context_dir / "Dockerfile.dockerignore" + if not ignore_path.is_file(): + ignore_path = context_dir / ".dockerignore" + if not ignore_path.is_file(): + return [] + + patterns: list[tuple[str, bool]] = [] + for raw in ignore_path.read_text(encoding="utf-8").splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + negated = line.startswith("!") + if negated: + line = line[1:].strip() + pattern = line.strip("/") + if pattern and pattern != ".": + patterns.append((pattern, negated)) + return patterns + + +def _is_dockerignored( + path: Path, + context_dir: Path, + patterns: list[tuple[str, bool]], +) -> bool: + rel = path.relative_to(context_dir).as_posix() + if rel == ".": + return False + + parts = PurePosixPath(rel).parts + for idx in range(1, len(parts) + 1): + candidate = "/".join(parts[:idx]) + ignored = False + for pattern, negated in patterns: + matches = ( + fnmatch.fnmatchcase(parts[idx - 1], pattern) + if "/" not in pattern + else _match_dockerignore_path(candidate, pattern) + ) + if matches: + ignored = not negated + if ignored: + return True + return False + + def _copy_destination_is_dir(op: CopyOp, dest_norm: str) -> bool: raw = op.destination.strip() if ( @@ -1409,6 +1480,7 @@ def build_copy_layer_tar( if not copy_ops: return None, None + ignore_patterns = _dockerignore_patterns(context_dir) entries: dict[str, tuple[str, bytes | None, int, int, int]] = {} # path -> ("dir"|"file", bytes|None, mode, uid, gid) @@ -1426,7 +1498,13 @@ def ensure_parents(rel_posix: str, uid: int, gid: int) -> None: resolved_sources: list[Path] = [] for src in op.sources: - resolved_sources.extend(_resolve_copy_sources(context_dir, src)) + resolved_sources.extend( + path + for path in _resolve_copy_sources(context_dir, src) + if not _is_dockerignored(path, context_dir, ignore_patterns) + ) + if not resolved_sources: + raise HarborImageError("COPY sources are excluded by .dockerignore") if len(resolved_sources) > 1: dest_is_dir = True @@ -1436,6 +1514,8 @@ def ensure_parents(rel_posix: str, uid: int, gid: int) -> None: if dest_rel: ensure_parents(dest_rel + "/_", op.uid, op.gid) for child in sorted(src_path.rglob("*")): + if _is_dockerignored(child, context_dir, ignore_patterns): + continue if child.is_symlink(): raise HarborImageError( f"Symlink not allowed in COPY source: {child}" @@ -2259,21 +2339,24 @@ def execute_group( action, env_hash = key rep = members[0] - # Check resumable cache on representative task. - cached = prior_receipts.get(rep.task_id) - if ( - not no_push - and isinstance(cached, dict) - and cached.get("status") == "resolved" - and cached.get("env_hash") == env_hash - and cached.get("image") - and ( - action in {"keep_pinned", "verify_shared"} - or cached["image"].startswith( - parse_image_ref(effective_registry).canonical_repo + "@" + # Any member receipt represents the shared environment for this group. + cached = None + expected_repo = parse_image_ref(effective_registry).canonical_repo + "@" + for member in members: + candidate = prior_receipts.get(member.task_id) + if ( + isinstance(candidate, dict) + and candidate.get("status") == "resolved" + and candidate.get("env_hash") == env_hash + and candidate.get("image") + and ( + action in {"keep_pinned", "verify_shared"} + or candidate["image"].startswith(expected_repo) ) - ) - ): + ): + cached = candidate + break + if not no_push and cached is not None: if progress: progress( f"reuse {rep.task_id} ({len(members)} task(s)) -> {cached['image']}" diff --git a/tests/test_cli/test_harbor_build_images.py b/tests/test_cli/test_harbor_build_images.py index 9c512d91b8..fe0b186107 100644 --- a/tests/test_cli/test_harbor_build_images.py +++ b/tests/test_cli/test_harbor_build_images.py @@ -358,6 +358,19 @@ def test_classify_dockerfile_copy_only_vs_run(): assert len(copy_only.copy_ops) == 1 assert copy_only.copy_ops[0].sources == ("source/",) + env_paths = classify_dockerfile( + """ + FROM python:3.12-slim + ENV APP=/app SOURCE=source + WORKDIR $APP + COPY $SOURCE/ ${APP}/ + """ + ) + assert env_paths.is_copy_only is True + assert env_paths.workdir == "/app" + assert env_paths.copy_ops[0].sources == ("source/",) + assert env_paths.copy_ops[0].destination == "/app/" + with_run = classify_dockerfile( """ FROM python:3.12-slim @@ -467,6 +480,26 @@ def test_build_copy_layer_tar_matches_docker_copy_semantics(tmp_path: Path): assert names["testbed/sub/run.sh"].mode == 0o755 +def test_build_copy_layer_tar_applies_dockerignore(tmp_path: Path): + env_dir = tmp_path / "environment" + (env_dir / "source" / "cache").mkdir(parents=True) + (env_dir / "source" / "app.py").write_text("print('ok')\n", encoding="utf-8") + (env_dir / "source" / "app.pyc").write_bytes(b"compiled") + (env_dir / "source" / "cache" / "state.json").write_text("{}", encoding="utf-8") + (env_dir / ".dockerignore").write_text("*.pyc\nsource/cache/\n", encoding="utf-8") + parsed = classify_dockerfile("FROM python:3.12-slim\nCOPY source/ /app/\n") + + gz, _ = build_copy_layer_tar(env_dir, parsed.copy_ops) + assert gz is not None + with tarfile.open(fileobj=io.BytesIO(gzip.decompress(gz)), mode="r:") as tar: + names = {member.name for member in tar.getmembers()} + + assert "app/app.py" in names + assert "app/app.pyc" not in names + assert "app/cache" not in names + assert "app/cache/state.json" not in names + + def test_build_copy_layer_tar_copies_file_into_explicit_workdir(tmp_path: Path): env_dir = tmp_path / "environment" env_dir.mkdir() @@ -769,6 +802,28 @@ def build(self, **kwargs: Any) -> tuple[str, str]: assert resumed["resolved"] == 2 assert run_calls == [] + # A receipt from any member resumes the full deduplicated group. + sibling_receipts = tmp_path / "sibling-receipts" + build_harbor_images( + tmp_path / "src", + registry="ghcr.io/harness-hub/corpus", + task_ids=["go-b"], + per_task_receipts_dir=sibling_receipts, + registry_client=reg, + public_client=pub, + ) + messages: list[str] = [] + build_harbor_images( + tmp_path / "src", + registry="ghcr.io/harness-hub/corpus", + task_ids=["go-a", "go-b"], + per_task_receipts_dir=sibling_receipts, + registry_client=reg, + public_client=pub, + progress=messages.append, + ) + assert any(message.startswith("reuse go-a") for message in messages) + def test_environment_hash_ignores_files_the_dockerfile_never_copies(tmp_path: Path): run_df = "FROM python:3.12-slim\nWORKDIR /testbed\nRUN pip install pytest\n" @@ -1074,3 +1129,33 @@ def test_explicit_credentials_are_only_sent_to_the_push_registry(monkeypatch): finally: client.close() assert resolve_registry_credentials("other.example", registry_scoped=False) is None + + +def test_blob_upload_does_not_send_registry_auth_to_cross_host_location(): + seen_upload_auth: list[str | None] = [] + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.host == "registry.example": + if request.method == "HEAD": + return httpx.Response(404) + assert request.headers.get("Authorization") == "Bearer push-secret" + return httpx.Response( + 202, + headers={"Location": "https://storage.example/upload?signature=valid"}, + ) + seen_upload_auth.append(request.headers.get("Authorization")) + return httpx.Response(201) + + client = OCIRegistryClient( + http=httpx.Client(transport=httpx.MockTransport(handler)) + ) + client._tokens[("registry.example", "push:org/repo")] = "Bearer push-secret" + try: + data = b"layer" + client._upload_blob( + parse_image_ref("registry.example/org/repo:v1"), _sha(data), data + ) + finally: + client.close() + + assert seen_upload_auth == [None] From 5acc7e75b187d2a5d5c6f94ae4f77382e41ac293 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 12:09:36 +0000 Subject: [PATCH 15/15] ci: retrigger checks after uv install timeout on test (3.11) Co-authored-by: burtenshaw