Secure, Fast, and Extensible Sandbox runtime for AI agents.
feat(server): resolve overlaybd templates via OCI manifestRef and restore OCI snapshots
高然095f5324217c
diff --git a/server/configuration.md b/server/configuration.mdindex ad553d809..fa73ec86e 100644--- a/server/configuration.md+++ b/server/configuration.md@@ -166,7 +166,8 @@ The kubernetes runtime also serves fsb (`fsb-`) sandboxes side by side; these fi| `fastpath_timeout_seconds` | number | `30.0` | Per-RPC gRPC deadline. || `fastpath_wait_ready_seconds` | number | `30.0` | Bounded readiness wait for DataPlaneReady after Create. || `fastpath_resource_pool` | string | `"default-pool"` | SandboxPool when `extensions.poolRef` is unset. |-| `template_s3_publish_secret` | string | `"sandbox-oss-credentials"` | Object-store credentials secret for server-created SandboxTemplates. |+| `template_s3_publish_secret` | string | `"sandbox-oss-credentials"` | Object-store credentials secret for server-created SandboxTemplates (`format: native`). |+| `template_oci_publish_secret` | string \| omitted | `null` | Name of a `kubernetes.io/dockerconfigjson` Secret in each template's namespace, used as `output.publishSecretRef` for `format: overlaybd` SandboxTemplate builds (fast-sandbox OCI publication). Required when creating overlaybd templates; native templates keep using `template_s3_publish_secret`. || `template_mitm_ca_secret` | string \| omitted | `null` | Secret holding the pinned cluster MITM CA certificate (OSEP-0022). When set, server-created SandboxTemplates bake `spec.egressMitmCertificate` from it (certificate entry only, never the private key); unset keeps templates CA-free. The Secret must exist in each template's namespace (ops-runbook distribution); a missed copy fails the build observably. || `template_mitm_ca_secret_key` | string | `"ca.crt"` | Secret entry holding the CA certificate when `template_mitm_ca_secret` is set. |diff --git a/server/opensandbox_server/api/schema.py b/server/opensandbox_server/api/schema.pyindex caee392c6..fc7fec5cb 100644--- a/server/opensandbox_server/api/schema.py+++ b/server/opensandbox_server/api/schema.py@@ -1697,7 +1697,14 @@ class CreateFsbTemplateRequest(BaseModel):publish: str = Field(...,min_length=1,- description="S3-compatible publish target for the built artifacts, e.g. 's3://bucket/publish'",+ description=(+ "Artifact publish destination for the built snapshot set. "+ "format=overlaybd (default) requires a repository-only OCI "+ "target, e.g. 'oci://registry.example.com/sandbox/templates' "+ "(tags and digests are rejected; the system generates an "+ "immutable per-build tag pair). format=native requires an "+ "S3-compatible target, e.g. 's3://bucket/publish'."+ ),)format: Literal["native", "overlaybd"] = Field("overlaybd",diff --git a/server/opensandbox_server/config.py b/server/opensandbox_server/config.pyindex c10b304bd..8e952f07c 100644--- a/server/opensandbox_server/config.py+++ b/server/opensandbox_server/config.py@@ -812,6 +812,18 @@ class KubernetesRuntimeConfig(BaseModel):"credentials referenced by server-created SandboxTemplates."),)+ template_oci_publish_secret: Optional[str] = Field(+ default=None,+ min_length=1,+ description=(+ "Name of a kubernetes.io/dockerconfigjson Secret in each "+ "template's namespace, used as output.publishSecretRef for "+ "format: overlaybd SandboxTemplate builds (fast-sandbox OCI "+ "publication). Required when creating overlaybd templates; "+ "native templates keep using "+ "kubernetes.template_s3_publish_secret."+ ),+ )template_mitm_ca_secret: Optional[str] = Field(default=None,min_length=1,diff --git a/server/opensandbox_server/services/fast_sandbox/snapshot_runtime.py b/server/opensandbox_server/services/fast_sandbox/snapshot_runtime.pyindex 8c3a85d77..1ef880de6 100644--- a/server/opensandbox_server/services/fast_sandbox/snapshot_runtime.py+++ b/server/opensandbox_server/services/fast_sandbox/snapshot_runtime.py@@ -51,6 +51,12 @@ from opensandbox_server.services.snapshot_runtime import (GROUP = "sandbox.fast.io"VERSION = "v1alpha2"PLURAL = "sandboxsnapshots"+SANDBOX_PLURAL = "sandboxes"++# fast-sandbox OCI artifacts (templates, snapshots, checkpoints) carry this+# prefix; restore/create image references that start with it take the OCI+# publication path upstream.+OCI_IMAGE_PREFIX = "oci://"# FastPath validates snapshot metadata keys as DNS-1123 labels and projects# them onto CR labels as "metadata.sandbox.fast.io/<key>" (same convention as@@ -146,11 +152,31 @@ class FastSandboxSnapshotRuntime:ns = namespace if namespace is not None else self._namespaceself._ensure_namespace_watch(ns)+ source_image = self._source_sandbox_image(ns, sandbox_id)+ if source_image is None:+ # The artifact encoding decides template_name semantics: native+ # requires it, OCI must omit it. Without the source image the+ # wrong branch is a guaranteed upstream rejection, so fail here.+ return SnapshotRuntimeStatus(+ state=SnapshotState.FAILED,+ reason="snapshot_runtime_create_failed",+ message=(+ f"Cannot snapshot sandbox {sandbox_id}: its Sandbox CR "+ "image could not be read to determine the artifact "+ "encoding (native vs OCI)."+ ),+ )+request = pb2.CreateSandboxSnapshotRequest(request_id=snapshot_name,sandbox=namespaced_reference(ns, sandbox_id),- template_name=snapshot_name,)+ if not source_image.startswith(OCI_IMAGE_PREFIX):+ # native + S3 snapshots publish under a template-name index key.+ # OCI snapshots must omit it: their rootfs/snapfiles tags are+ # derived from the Fastlet-assigned random snapshot_id, and the+ # restore image is the returned manifest_ref.+ request.template_name = snapshot_namerequest.metadata[SNAPSHOT_ID_METADATA_KEY] = snapshot_idtry:self._fastpath.create_sandbox_snapshot(request)@@ -184,6 +210,26 @@ class FastSandboxSnapshotRuntime:backend=_BACKEND_FSB,)+ def _source_sandbox_image(self, namespace: str, sandbox_id: str) -> Optional[str]:+ """Read the source Sandbox CR's image to classify the artifact encoding.++ Returns None when the CR is unreadable (missing or API errors) — the+ caller must not guess template_name semantics in that case.+ """+ try:+ cr = self._k8s_client.get_custom_object(+ GROUP, VERSION, namespace, SANDBOX_PLURAL, sandbox_id+ )+ except Exception as exc: # noqa: BLE001 - any read failure blocks the branch decision+ logger.warning(+ f"Failed to read Sandbox CR {namespace}/{sandbox_id} before "+ f"snapshot: {exc}"+ )+ return None+ spec = cr.get("spec") if isinstance(cr, dict) else None+ image = spec.get("image") if isinstance(spec, dict) else None+ return str(image) if image else None+def get_snapshot_status(self, snapshot_id: str) -> SnapshotRuntimeStatus:return self.inspect_snapshot(snapshot_id)@@ -308,23 +354,36 @@ class FastSandboxSnapshotRuntime:template_name = (getattr(info, "template_name", "") or "").strip() or Noneif phase_name in _TERMINAL_READY_PHASES:- # The restore image is the snapshot's template name: the artifact- # set is published under index/<sha256(templateName)>.json, the- # same content-addressed layout as template golden images. The- # manifest_ref points at the raw manifest object and is not- # resolvable as a CreateSandbox image.- if not template_name:+ # The restore image depends on the publication mode. Native + S3+ # snapshots publish under index/<sha256(templateName)>.json (same+ # content-addressed layout as template golden images), keyed by+ # the snapshot's template name. OCI snapshots omit the template+ # name and restore from the returned immutable snapfiles+ # manifest reference. A success carrying neither is unpublishable.+ if template_name:return SnapshotRuntimeStatus(- state=SnapshotState.FAILED,- reason="snapshot_runtime_missing_image",- message="fsb snapshot succeeded without a template name.",+ state=SnapshotState.READY,+ image=template_name,+ reason="snapshot_runtime_ready",+ message="fsb snapshot artifacts published successfully.",+ backend=_BACKEND_FSB,+ )+ manifest_ref = (getattr(info, "manifest_ref", "") or "").strip()+ if manifest_ref.startswith(OCI_IMAGE_PREFIX):+ return SnapshotRuntimeStatus(+ state=SnapshotState.READY,+ image=manifest_ref,+ reason="snapshot_runtime_ready",+ message="fsb snapshot OCI artifacts published successfully.",backend=_BACKEND_FSB,)return SnapshotRuntimeStatus(- state=SnapshotState.READY,- image=template_name,- reason="snapshot_runtime_ready",- message="fsb snapshot artifacts published successfully.",+ state=SnapshotState.FAILED,+ reason="snapshot_runtime_missing_image",+ message=(+ "fsb snapshot succeeded without a template name or an "+ "OCI manifest_ref; no runnable restore image."+ ),backend=_BACKEND_FSB,)diff --git a/server/opensandbox_server/services/templates/template_service.py b/server/opensandbox_server/services/templates/template_service.pyindex ba7f7b0c9..5a59882de 100644--- a/server/opensandbox_server/services/templates/template_service.py+++ b/server/opensandbox_server/services/templates/template_service.py@@ -77,12 +77,62 @@ TEMPLATE_RESOURCE_KEYS = frozenset({"cpu", "memory", "disk"})# here turns a would-be failed build into a 400 at template creation._VALID_ENV_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")+# Artifact encodings accepted for SandboxTemplate builds. overlaybd is the+# fast-sandbox OCI path: output.publish must be a repository-only oci://+# target (the builder generates the per-build <uuid>_rootfs/_snapfiles tags+# itself). native stays on the object-store path.+_TEMPLATE_FORMATS = ("native", "overlaybd")+_TEMPLATE_NOT_FOUND = {"code": SandboxErrorCodes.FSB_TEMPLATE_NOT_FOUND,"message": "Template not found.",}+def _publish_validation_error(format: str, publish: str) -> Optional[str]:+ """Return a rejection reason for a format/publish pair, or None.++ Mirrors the SandboxTemplate builder's output validation so an invalid+ destination fails as a 400 at creation instead of a failed build Pod.+ overlaybd requires ``oci://host/repository``: the host may carry a port,+ the repository path must be non-empty and free of tag (``:``) or digest+ (``@``) suffixes — the system generates the build tags itself. native+ requires an ``s3://`` object-store target.+ """+ if format == "overlaybd":+ if not publish.startswith("oci://"):+ return (+ "overlaybd templates publish to an OCI registry: "+ "publish must be 'oci://registry/repository' "+ "(S3-compatible stores are not supported for overlaybd)."+ )+ remainder = publish[len("oci://"):]+ host, _, repository = remainder.partition("/")+ if not host or not repository:+ return (+ "publish must be 'oci://registry/repository' with a "+ "non-empty registry host and repository path."+ )+ if "@" in repository or ":" in repository:+ return (+ "publish must be repository-only: tags and digests are "+ "rejected because the system generates an immutable "+ "per-build tag pair."+ )+ return None+ if format == "native":+ if not publish.startswith("s3://"):+ return (+ "native templates publish to an S3-compatible store: "+ "publish must be 's3://bucket/prefix'."+ )+ return None+ return (+ f"Unsupported template format {format!r}; "+ f"supported formats: {', '.join(_TEMPLATE_FORMATS)}."+ )++class FastSandboxTemplateService:"""Template catalog + SandboxTemplate CRD orchestration for fsb."""@@ -218,6 +268,32 @@ class FastSandboxTemplateService:),},)+ publish = request.publish.strip()+ publish_error = _publish_validation_error(request.format, publish)+ if publish_error:+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": SandboxErrorCodes.INVALID_PARAMETER,+ "message": publish_error,+ },+ )+ if (+ request.format == "overlaybd"+ and not self._k8s_config.template_oci_publish_secret+ ):+ raise HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={+ "code": SandboxErrorCodes.INVALID_PARAMETER,+ "message": (+ "Server is not configured for overlaybd templates: "+ "set [kubernetes].template_oci_publish_secret to a "+ "kubernetes.io/dockerconfigjson Secret in the "+ "template namespace."+ ),+ },+ )namespace = self._resolve_namespace()template_id = f"tpl-{uuid.uuid4()}"now = datetime.now(timezone.utc)@@ -233,7 +309,7 @@ class FastSandboxTemplateService:if request.readiness is not Noneelse None),- "publish": request.publish.strip(),+ "publish": publish,"format": request.format,}record = FastSandboxTemplateRecord(@@ -343,18 +419,25 @@ class FastSandboxTemplateService:self._repo().delete(template_id, namespace)def resolve_template_artifact(self, template_id: str) -> tuple[str, list[str]]:- """Resolve a Succeeded template to its artifact identity + entrypoint.-- The returned image reference is the TEMPLATE ID (tpl-<uuid>): the- builder publishes the content-addressed index under that key, so the- runtime pulls and caches this template's exact artifact set — two- templates of the same source image never alias each other. The- legacy sha256(image) index stays a last-writer-wins fallback for- warmImages and older clients. Template-mode Create uses this:- unknown or non-Succeeded templates both yield 404, so no existence- information leaks.-- Reads the DB row only; the watch reactor converges build phase.+ """Resolve a Succeeded template to its runnable artifact + entrypoint.++ The returned reference depends on the template's output format:++ - ``native``: the TEMPLATE ID (tpl-<uuid>). The builder publishes+ the content-addressed index under that key, so the runtime pulls+ and caches this template's exact artifact set — two templates of+ the same source image never alias each other. The legacy+ sha256(image) index stays a last-writer-wins fallback for+ warmImages and older clients.+ - ``overlaybd``: the template's immutable OCI ``manifest_ref``+ (oci://registry/repo@sha256:...) from the CRD status — the+ fast-sandbox OCI publication is the only runnable reference;+ ``output.publish`` is a build destination, not an image.++ Template-mode Create uses this: unknown, non-Succeeded, or+ manifest-less templates all yield 404, so no existence information+ leaks. Reads the DB row only; the watch reactor converges build+ phase."""namespace = self._resolve_namespace()record = self._repo().get(template_id, namespace)@@ -366,10 +449,39 @@ class FastSandboxTemplateService:if record.phase is not FastSandboxTemplatePhase.SUCCEEDED:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=_TEMPLATE_NOT_FOUND)entrypoint = list(record.spec.get("entrypoint") or DEFAULT_ENTRYPOINT)- return record.template_id, entrypoint+ if str(record.spec.get("format") or "overlaybd") != "overlaybd":+ return record.template_id, entrypoint+ manifest_ref = record.manifest_ref or ""+ if not manifest_ref.startswith("oci://"):+ # Succeeded without a resolvable OCI publication: either the CRD+ # status has not landed yet (transient) or the row predates the+ # fast-sandbox OCI contract (legacy overlaybd+S3 artifacts are+ # rejected upstream and can never become runnable). Both are+ # 404s; the legacy case gets an actionable message for the owner.+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail={+ "code": SandboxErrorCodes.FSB_TEMPLATE_NOT_FOUND,+ "message": (+ "Template artifact is not runnable: overlaybd "+ "templates require an OCI manifestRef from a build "+ "against the current fast-sandbox contract; rebuild "+ "the template."+ ),+ },+ )+ return manifest_ref, entrypoint# -- CRD mapping -----------------------------------------------------------+ def _publish_secret_name(self, format: str) -> str:+ """Publish secret for a template format: overlaybd builds publish to+ an OCI registry (dockerconfigjson Secret), native builds to the+ object store (S3 credentials)."""+ if format == "overlaybd":+ return self._k8s_config.template_oci_publish_secret or ""+ return self._k8s_config.template_s3_publish_secret+def _build_crd(self, record: FastSandboxTemplateRecord) -> dict:limits = record.spec.get("resourceLimits") or {}vcpu = str(limits.get("cpu") or DEFAULT_VCPU)@@ -377,6 +489,7 @@ class FastSandboxTemplateService:# resourceLimits.disk (parallel to cpu/memory) is the logical size of# the guest rootfs; artifacts are stored and pulled at this size.rootfs_size = str(limits.get("disk") or DEFAULT_ROOTFS_SIZE)+ fmt = str(record.spec.get("format") or "overlaybd")spec: dict = {"image": record.source_image,# Per-template artifact identity: the builder publishes the image@@ -392,9 +505,9 @@ class FastSandboxTemplateService:"machine": {"vcpu": vcpu, "memory": memory},"output": {"rootfsSize": rootfs_size,- "format": record.spec.get("format", "overlaybd"),+ "format": fmt,"publish": record.publish,- "publishSecretRef": {"name": self._k8s_config.template_s3_publish_secret},+ "publishSecretRef": {"name": self._publish_secret_name(fmt)},},}env = record.spec.get("env") or {}diff --git a/server/tests/test_config.py b/server/tests/test_config.pyindex 270658171..b9462a87a 100644--- a/server/tests/test_config.py+++ b/server/tests/test_config.py@@ -205,6 +205,36 @@ def test_kubernetes_pool_acquisition_timeout_defaults_and_validates():config_module.KubernetesRuntimeConfig(pool_acquisition_timeout_seconds=0)+def test_kubernetes_template_publish_secrets_defaults():+ """native templates fall back to the S3 secret; the OCI publish secret+ for overlaybd templates is opt-in and defaults to unset."""+ kubernetes_cfg = config_module.KubernetesRuntimeConfig()+ assert kubernetes_cfg.template_s3_publish_secret == "sandbox-oss-credentials"+ assert kubernetes_cfg.template_oci_publish_secret is None++ configured = config_module.KubernetesRuntimeConfig(+ template_oci_publish_secret="registry-credentials"+ )+ assert configured.template_oci_publish_secret == "registry-credentials"++ with pytest.raises(ValueError):+ config_module.KubernetesRuntimeConfig(template_oci_publish_secret="")+++def test_kubernetes_template_oci_publish_secret_from_toml():+ app_cfg = config_module.AppConfig.model_validate(+ {+ "server": {"host": "127.0.0.1", "port": 8000},+ "runtime": {"type": "kubernetes", "execd_image": "opensandbox/execd:latest"},+ "kubernetes": {+ "template_oci_publish_secret": "registry-credentials",+ },+ }+ )+ assert app_cfg.kubernetes is not None+ assert app_cfg.kubernetes.template_oci_publish_secret == "registry-credentials"++def test_server_config_uvicorn_tuning_defaults():"""ServerConfig exposes uvicorn concurrency knobs with sensible defaults."""server_cfg = ServerConfig()diff --git a/server/tests/test_fsb_snapshot_runtime.py b/server/tests/test_fsb_snapshot_runtime.pyindex 562057c61..aac6490e9 100644--- a/server/tests/test_fsb_snapshot_runtime.py+++ b/server/tests/test_fsb_snapshot_runtime.py@@ -110,22 +110,42 @@ class WatchRecordingK8sClient:self.watch_calls: list[tuple[str, str, str, str]] = []self.watch_handlers: list = []self.stopped = 0+ self.sandbox_crs: dict[tuple[str, str], dict] = {}+ self.sandbox_cr_error: Exception | None = None+ self.custom_object_reads: list[tuple[str, str, str, str, str]] = []def watch_custom_objects(self, group, version, namespace, plural, event_handler):self.watch_calls.append((group, version, namespace, plural))self.watch_handlers.append(event_handler)return object()+ def get_custom_object(self, group, version, namespace, plural, name):+ self.custom_object_reads.append((group, version, namespace, plural, name))+ if self.sandbox_cr_error is not None:+ raise self.sandbox_cr_error+ cr = self.sandbox_crs.get((namespace, name))+ if cr is None:+ raise KeyError((namespace, name))+ return cr+def stop_informers(self) -> None:self.stopped += 1+def _sandbox_cr(image: str) -> dict:+ return {"spec": {"image": image}}++def _runtime(fastpath: FakeFastPathClient | None = None,k8s: WatchRecordingK8sClient | None = None,) -> tuple[FastSandboxSnapshotRuntime, FakeFastPathClient, WatchRecordingK8sClient]:fastpath = fastpath or FakeFastPathClient()k8s = k8s or WatchRecordingK8sClient()+ # Default the source sandbox to a native image so the create path keeps+ # setting template_name; OCI-source tests override the image explicitly.+ for namespace in ("default", "tenant-a"):+ k8s.sandbox_crs.setdefault((namespace, SANDBOX_ID), _sandbox_cr("alpine:3.19"))runtime = FastSandboxSnapshotRuntime(cast(FastPathClient, fastpath),cast(object, k8s),@@ -196,6 +216,48 @@ def test_create_snapshot_maps_failed_precondition_to_conflict() -> None:assert "already has snapshot" in (status.message or "")+def test_create_snapshot_reads_source_sandbox_cr_for_encoding() -> None:+ runtime, fastpath, k8s = _runtime()++ status = runtime.create_snapshot(SNAPSHOT_ID, SANDBOX_ID, namespace="tenant-a")++ assert status.state == SnapshotState.CREATING+ assert k8s.custom_object_reads == [+ ("sandbox.fast.io", "v1alpha2", "tenant-a", "sandboxes", SANDBOX_ID)+ ]+ # Native source image: the template-name index key is required.+ assert fastpath.create_requests[0].template_name == build_public_snapshot_name(SNAPSHOT_ID)+++def test_create_snapshot_oci_source_omits_template_name() -> None:+ fastpath = FakeFastPathClient()+ k8s = WatchRecordingK8sClient()+ k8s.sandbox_crs[("tenant-a", SANDBOX_ID)] = _sandbox_cr(+ "oci://registry.example.com/sandbox/templates@sha256:abc123"+ )+ runtime, fastpath, _ = _runtime(fastpath=fastpath, k8s=k8s)++ status = runtime.create_snapshot(SNAPSHOT_ID, SANDBOX_ID, namespace="tenant-a")++ assert status.state == SnapshotState.CREATING+ request = fastpath.create_requests[0]+ assert request.template_name == ""+++def test_create_snapshot_unreadable_sandbox_cr_fails_without_rpc() -> None:+ fastpath = FakeFastPathClient()+ k8s = WatchRecordingK8sClient()+ k8s.sandbox_cr_error = KeyError("api unavailable")+ runtime, fastpath, _ = _runtime(fastpath=fastpath, k8s=k8s)++ status = runtime.create_snapshot(SNAPSHOT_ID, SANDBOX_ID)++ assert status.state == SnapshotState.FAILED+ assert status.reason == "snapshot_runtime_create_failed"+ assert "image could not be read" in (status.message or "")+ assert fastpath.create_requests == []++def test_inspect_maps_succeeded_phase_to_ready_with_template_name_image() -> None:fastpath = FakeFastPathClient()snapshot_name = build_public_snapshot_name(SNAPSHOT_ID)@@ -231,6 +293,37 @@ def test_inspect_fails_when_succeeded_without_template_name() -> None:assert status.reason == "snapshot_runtime_missing_image"+def test_inspect_succeeded_oci_manifest_restores_from_manifest_ref() -> None:+ """OCI snapshots omit the template name; the immutable snapfiles+ manifest reference is the runnable restore image."""+ fastpath = FakeFastPathClient()+ manifest_ref = "oci://registry.example.com/sandbox/snapshots@sha256:def456"+ fastpath.get_by_name[("default", build_public_snapshot_name(SNAPSHOT_ID))] = _Response(+ _Info(pb2.SNAPSHOT_PHASE_SUCCEEDED, manifest_ref=manifest_ref, template_name="")+ )+ runtime, _, _ = _runtime(fastpath=fastpath)++ status = runtime.inspect_snapshot(SNAPSHOT_ID)++ assert status.state == SnapshotState.READY+ assert status.image == manifest_ref+ assert status.backend == "fsb"+ assert status.reason == "snapshot_runtime_ready"+++def test_inspect_succeeded_without_template_name_or_oci_manifest_fails() -> None:+ fastpath = FakeFastPathClient()+ fastpath.get_by_name[("default", build_public_snapshot_name(SNAPSHOT_ID))] = _Response(+ _Info(pb2.SNAPSHOT_PHASE_SUCCEEDED, manifest_ref="", template_name="")+ )+ runtime, _, _ = _runtime(fastpath=fastpath)++ status = runtime.inspect_snapshot(SNAPSHOT_ID)++ assert status.state == SnapshotState.FAILED+ assert status.reason == "snapshot_runtime_missing_image"++def test_inspect_maps_failed_phase_with_message() -> None:fastpath = FakeFastPathClient()fastpath.get_by_name[("default", build_public_snapshot_name(SNAPSHOT_ID))] = _Response(diff --git a/server/tests/test_templates.py b/server/tests/test_templates.pyindex 37aa1be2f..7490c8867 100644--- a/server/tests/test_templates.py+++ b/server/tests/test_templates.py@@ -19,7 +19,7 @@ from copy import deepcopyfrom datetime import datetime, timezoneimport pytest-from fastapi import FastAPI+from fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClientfrom kubernetes.client import ApiException, CustomObjectsApi, V1APIResource, V1APIResourceListfrom unittest.mock import Mock, patch@@ -475,6 +475,132 @@ def test_resolve_restarts_watch_for_non_terminal_rows(service, crs, repo):assert "ns-1" in service._watched_namespaces+# -- overlaybd (OCI publication) ------------------------------------------------+++def _overlaybd_config(**overrides) -> KubernetesRuntimeConfig:+ return KubernetesRuntimeConfig(+ namespace="ns-1",+ template_s3_publish_secret="sandbox-oss-credentials",+ template_oci_publish_secret="registry-credentials",+ **overrides,+ )+++def overlaybd_service(repo, crs, monkeypatch):+ monkeypatch.setattr(WorkloadInformer, "start", lambda self: None)+ with patch.object(K8sClient, "_load_config"):+ k8s = K8sClient(KubernetesRuntimeConfig())+ crs.install(k8s)+ config = _config()+ config.kubernetes = _overlaybd_config()+ svc = FastSandboxTemplateService(config, repository=repo, k8s_client=k8s)+ yield svc+ svc.close()+++def _overlaybd_request(**overrides) -> CreateFsbTemplateRequest:+ overrides.setdefault("publish", "oci://registry.example.com/sandbox/templates")+ overrides.setdefault("format", "overlaybd")+ return _create_request(**overrides)+++def test_create_overlaybd_projects_oci_output(overlaybd_service, crs):+ record = overlaybd_service.create_template(_overlaybd_request())+ spec = crs.created[-1]["spec"]+ assert spec["output"] == {+ "rootfsSize": "5Gi",+ "format": "overlaybd",+ "publish": "oci://registry.example.com/sandbox/templates",+ "publishSecretRef": {"name": "registry-credentials"},+ }+ assert record.spec["format"] == "overlaybd"+++def test_resolve_overlaybd_returns_manifest_ref(overlaybd_service, crs):+ record = overlaybd_service.create_template(_overlaybd_request(entrypoint=["sleep", "1"]))+ manifest_ref = "oci://registry.example.com/sandbox/templates@sha256:abc123"+ crs.set_status("ns-1", record.crd_name, {"phase": "Succeeded", "manifestRef": manifest_ref})+ _converge(overlaybd_service, crs, "ns-1", record.crd_name)+ artifact_ref, entrypoint = overlaybd_service.resolve_template_artifact(record.template_id)+ assert artifact_ref == manifest_ref+ assert entrypoint == ["sleep", "1"]+++def test_resolve_overlaybd_without_manifest_ref_404(overlaybd_service, crs):+ record = overlaybd_service.create_template(_overlaybd_request())+ crs.set_status("ns-1", record.crd_name, {"phase": "Succeeded"})+ _converge(overlaybd_service, crs, "ns-1", record.crd_name)+ with pytest.raises(HTTPException) as excinfo:+ overlaybd_service.resolve_template_artifact(record.template_id)+ assert excinfo.value.status_code == 404+++def test_resolve_overlaybd_legacy_s3_manifest_demands_rebuild(overlaybd_service, crs):+ """Pre-OCI overlaybd+S3 rows can never become runnable: the resolve gate+ says so instead of handing out a dead artifact reference."""+ record = overlaybd_service.create_template(_overlaybd_request())+ crs.set_status(+ "ns-1", record.crd_name, {"phase": "Succeeded", "manifestRef": "s3://b/legacy/manifest"}+ )+ _converge(overlaybd_service, crs, "ns-1", record.crd_name)+ with pytest.raises(HTTPException) as excinfo:+ overlaybd_service.resolve_template_artifact(record.template_id)+ assert excinfo.value.status_code == 404+ assert "rebuild" in str(excinfo.value.detail).lower()+++def test_create_overlaybd_requires_oci_publish_secret(repo, crs, monkeypatch):+ monkeypatch.setattr(WorkloadInformer, "start", lambda self: None)+ with patch.object(K8sClient, "_load_config"):+ k8s = K8sClient(KubernetesRuntimeConfig())+ crs.install(k8s)+ svc = FastSandboxTemplateService(_config(), repository=repo, k8s_client=k8s)+ try:+ with pytest.raises(HTTPException) as excinfo:+ svc.create_template(_overlaybd_request())+ assert excinfo.value.status_code == 400+ assert "template_oci_publish_secret" in str(excinfo.value.detail)+ finally:+ svc.close()+++ "publish",+ [+ "s3://sandbox-images/publish",+ "registry.example.com/sandbox/templates",+ "oci://registry.example.com",+ "oci:///templates",+ "oci://registry.example.com/sandbox/templates:v1",+ "oci://registry.example.com/sandbox/templates@sha256:abc",+ ],+)+def test_create_overlaybd_rejects_invalid_publish(service, publish):+ with pytest.raises(HTTPException) as excinfo:+ service.create_template(_overlaybd_request(publish=publish))+ assert excinfo.value.status_code == 400+++def test_create_overlaybd_allows_registry_host_port(overlaybd_service, crs):+ overlaybd_service.create_template(+ _overlaybd_request(publish="oci://registry.example.com:5000/sandbox/templates")+ )+ assert crs.created[-1]["spec"]["output"]["publish"] == (+ "oci://registry.example.com:5000/sandbox/templates"+ )+++def test_create_native_rejects_oci_publish(service):+ with pytest.raises(HTTPException) as excinfo:+ service.create_template(+ _create_request(publish="oci://registry.example.com/sandbox/templates")+ )+ assert excinfo.value.status_code == 400+ assert "s3://" in str(excinfo.value.detail)++@pytest.fixturedef client(service, monkeypatch):app = FastAPI()