06

Preview Safely in an Isolated Runtime

Let a reviewer interact with generated code without granting it production data, identity, network, or permanence.

Run it in the public monorepo

This course is built around the public Zheta Kubernetes Lab monorepo. The excerpt below is runnable source, not pseudocode.

Source: services/control_plane/domain.py

def create(self, project_id: str, organization_id: str, name: str, actor: str, archetype: str) -> Project:
        project = Project(project_id, organization_id, name, actor, blueprint={"name": name, "archetype": archetype})
        project.collaborators.add(actor)
        with self.repository.transaction():
            self.repository.create(project)
            self._audit(project, actor, "project.created")
        return project

Code to reality

Declared intent
Create one tenant-owned project and its audit evidence as a single product operation.
Interpreter
Python executes the Forge domain model after the controller supplies authenticated command values.
Software effect
The repository durably owns the project while the event port publishes project.created evidence.
Hardware effect
The service process uses CPU and writes database pages to its persistent volume or managed database.
Observable evidence
A tenant-scoped GET plus a project.created evidence record proves both state and accountability.

Start with the people and the result they need

The source tables below remain the detailed contract. Begin with these customer paths:

  • D06-UC-01
    • Person: Application reviewer
    • Job: Open one generated revision and inspect its behavior
    • Observable result: Digest-matched preview becomes Ready at a short-lived authenticated URL
  • D06-UC-02
    • Person: Security reviewer
    • Job: Prove generated preview code cannot reach ungranted endpoints
    • Observable result: DNS and egress allowlist permit only required platform endpoints

Turn each customer job into a testable story

Now turn each customer job into a story with a result that an engineer can check:

  • D06-US-01
    • Story: As an application reviewer, I want an expiring preview tied to one artifact digest, so that my approval targets exact code
    • Observable acceptance: URL, digest, deployment UID, readiness, reviewer identity, and expiry agree
  • D06-US-02
    • Story: As a security reviewer, I want preview egress denied by default, so that generated code cannot discover enterprise or cloud services
    • Observable acceptance: Forbidden request is denied and traced; allowed health and artifact requests remain successful

Add real state and observable proof

Finally trace each story through the system that owns its state and the evidence that proves the outcome:

  • D06-FLOW-01
    • Trigger: Reviewer selects Preview on a successful generation run
    • Responsible systems: Preview Manager, Artifact Builder, Kubernetes API, Runtime Gateway
    • Authoritative state: Preview record in control-plane PostgreSQL; workload status in Kubernetes
    • Owned record: PreviewEnvironment
    • Observable evidence: Actor, digest, preview ID, namespace, workload identity, Pod UID, URL, HTTP result, expiry, trace ID
    • Failure signal: Missing artifact, failed admission, image pull, readiness, or route binding
  • D06-FLOW-02
    • Trigger: Preview code requests a forbidden network endpoint
    • Responsible systems: Network policy controller, DNS, workload identity, Audit Evidence
    • Authoritative state: NetworkPolicy desired state and flow/audit evidence
    • Owned record: PreviewBoundaryEvidence
    • Observable evidence: Denied destination, policy revision, flow log, positive-control probe, deletion UID and timestamp
    • Failure signal: Unexpected allowed flow, missing denial, or failed positive control

The enterprise problem and today’s slice

Enterprise problem: Generated code can be incorrect or hostile, and running it beside trusted services with ambient credentials turns a review feature into a path to customer data.

Whole-course context: The incoming source artifact has a deterministic digest; today deploys it to the local hosted-runtime store without publishing it.

Today’s slice: Run the implemented tenant-scoped preview deployment, then derive the namespace, identity, network, resource, hostname, and expiry controls still required for an isolated production preview.

End-of-day evidence: A preview response and tenant/app runtime row reference the same artifact digest, and preview.deployed is published; namespace isolation, denied egress, and expiry are explicitly not yet proved.

Still unsolved: Managed application data, enterprise connectors, human identity, sharing, publication, and cloud isolation remain deferred.

Customer use cases

Preview must make the app interactive while keeping production authority absent. These use cases prove a working URL and a denied network escape.

Use case IDActorCustomer jobSuccess outcomeDenial or recovery evidence
D06-UC-01Application reviewerOpen one generated revision and inspect its behaviorDigest-matched preview becomes Ready at a short-lived authenticated URLBuild or readiness failure is visible and no route becomes active
D06-UC-02Security reviewerProve generated preview code cannot reach ungranted endpointsDNS and egress allowlist permit only required platform endpointsProbe to a forbidden endpoint is denied while the preview health probe succeeds

Actor-centred user stories

A preview URL without isolation evidence is only convenient execution. These stories make both usability and containment observable.

Story IDUse case IDsUser storyObservable acceptance conditions
D06-US-01D06-UC-01As an application reviewer, I want an expiring preview tied to one artifact digest, so that my approval targets exact codeURL, digest, deployment UID, readiness, reviewer identity, and expiry agree
D06-US-02D06-UC-02As a security reviewer, I want preview egress denied by default, so that generated code cannot discover enterprise or cloud servicesForbidden request is denied and traced; allowed health and artifact requests remain successful

End-to-end product flows

Preview begins when a reviewer chooses an artifact in Forge Studio. The denial path executes inside the same sandbox so the evidence tests the actual boundary.

Flow IDUse case IDsPathTriggerNumbered stepsTerminal evidence
D06-FLOW-01D06-UC-01, D06-UC-02HappyReviewer selects Preview on a successful generation run1. Authorize artifact.; 2. Create preview record and namespace.; 3. Bind restricted ServiceAccount.; 4. Deploy digest.; 5. Wait for readiness.; 6. Issue expiring route.Actor, digest, preview ID, namespace, workload identity, Pod UID, URL, HTTP result, expiry, trace ID
D06-FLOW-02D06-UC-01, D06-UC-02DeniedPreview code requests a forbidden network endpoint1. Pod sends request.; 2. Network policy denies egress.; 3. Audit records destination and policy.; 4. Health probe confirms preview remains available.; 5. Expiry deletes sandbox.Denied destination, policy revision, flow log, positive-control probe, deletion UID and timestamp

The reviewer asks to interact with one exact artifact. That product action does not grant production publication or generated-app membership.

System design derived from the flows

Namespace isolation alone does not restrict network or cloud authority. Preview Manager composes several controls and owns the sandbox lifecycle, while Kubernetes controllers own reconciliation.

Use case IDEntry pointResponsible servicesAuthoritative storeFailure evidence
D06-UC-01Forge Studio preview actionPreview Manager, Artifact Builder, Kubernetes API, Runtime GatewayPreview record in control-plane PostgreSQL; workload status in KubernetesMissing artifact, failed admission, image pull, readiness, or route binding
D06-UC-02In-preview egress probeNetwork policy controller, DNS, workload identity, Audit EvidenceNetworkPolicy desired state and flow/audit evidenceUnexpected allowed flow, missing denial, or failed positive control

Preview Manager requests the sandbox; Kubernetes supplies isolated processes; Runtime Gateway exposes only a scoped, expiring route.

Data model and ownership

Preview lifecycle must survive a controller restart even though its workload is disposable. No generated-app domain database is needed to render fixture-backed archetypes.

Generated-application database: Not created in this slice — previews use versioned fixtures; durable preview lifecycle and evidence stay in provider stores.

Record or entityStore and ownerPrimary keyForeign key or opaque referenceTenant keyMaterial constraintLifecycle and deletionUse case IDs
PreviewEnvironmentControl-plane PostgreSQL, owned by Preview Managerpreview_idOpaque artifact digest, namespace UID, route IDorganization_idOne active preview per app revision and reviewer scope; mandatory expiryRequested, provisioning, ready/failed, expired; namespace deleted then tombstone retainedD06-UC-01, D06-UC-02
PreviewBoundaryEvidenceEvidence S3 bucket, owned by Audit Evidenceevidence_run_idPreview ID, policy revision, Pod UID, trace IDsorganization_idContains allowed health and denied egress in one observation windowImmutable retention; expires after review policy windowD06-UC-01, D06-UC-02

The lifecycle record enables cleanup after restart; paired network evidence proves the sandbox is useful and constrained.

Prove interaction and containment

A policy manifest proves only declared intent. The current monorepo implements preview as a tenant-scoped call to the runtime service and persists the payload in local SQLite; it does not yet create per-preview namespaces, enforce egress policy, or expire previews automatically. Kubernetes also requires a network plugin that implements NetworkPolicy; the API object alone is not enforcement (Kubernetes Network Policies). Read the exact operation in services/control_plane/domain.py.

def preview(self, project: Project, actor: str) -> dict[str, object]:
    self._authorize(project, actor)
    artifact = self._latest(project)
    payload = {"mode": "preview", **artifact, "source": self.artifacts.get(project.organization_id, artifact["artifact_id"])}
    result = self.runtime.deploy(project.organization_id, project.project_id, payload)
    self._audit(project, actor, "preview.deployed")
    return result
Declared intentInterpreterSoftware effectHardware effectEvidence
Deploy the latest authorized artifact as a preview payload for one organization and projectPython executes the Forge model; the injected RuntimeClient sends PUT /tenants/{organization_id}/apps/{app_id}The runtime upserts one tenant/app payload and audit publishes preview.deployed; no sandbox namespace or TTL state exists yetControl-plane and runtime CPU process the request, local networking carries it, and the runtime SQLite volume stores the payloadPOST /projects/{id}/preview, runtime GET /tenants/{org}/apps/{id}, and audit evidence prove the implemented path; isolation and expiry need separate future tests

Decision rules

Treat generated code as untrusted until publication policy says otherwise. The desired production design gives previews no ambient cloud or enterprise permissions, default-deny networking, resource limits, and reconciled expiry; the current local runtime does not prove those controls and must not be presented as a sandbox.