Skip to content

feat(studio): bootstrap the Mecatl Studio web UI as apps/ - #1754

Merged
samuv merged 1 commit into
plan/studio-bootstrapfrom
studio/bootstrap
Sep 23, 2026
Merged

samuv merged 1 commit into
plan/studio-bootstrapfrom
studio/bootstrap

Conversation

@samuv

@samuv samuv commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary

What lands

  • apps/ pnpm workspace (pnpm 12.4.2, Node 24): contracts (Zod → OpenAPI → generated client, drift-gated), server (Hono BFF), web (Vite + React shell). Depends on @stacklok-oss/mecatl-sdk 0.3.0 from npm; nothing references sdk/typescript.
  • Server: spawn / mock / external runtime modes; RFC 9728 discovery (MECATL_RESOURCE_URL or derived from MECATL_BASE_URL, fail-closed on anything but 404); PKCE login with AES-GCM-sealed HttpOnly cookies; server-side 401 gating; single-flight refresh; secureHeaders + CSP; same-origin + double-submit CSRF on mutations; per-client rate limiting with STUDIO_TRUSTED_PROXY_HOPS; structured audit records; SPA serving with cache rules; STUDIO_IMAGE=1 refusals and the STUDIO_ALLOW_UNAUTHENTICATED=1 opt-in.
  • Web: workspace shell, auth gate (sign-in only for mode: oidc), connection banner, CSRF request interceptor.
  • Packaging: multi-stage apps/Dockerfile (Chainguard node pinned by digest), apps/docker/mecated.Dockerfile, apps/docker-compose.yml, task studio:*.
  • CI / release: studio relevance category and job (install, lint, typecheck, test, generated-check, no-push image build); publish-studio release job cloned from the Slack bot's; ac-trace vitest resolver accepts apps/ proofs.
  • Docs: apps/README.md, docs/architecture.md Studio section, AGENTS.md apps/ bullet.

Amended after review

Eleven review findings are fixed in this layer; the resolution comment below lists each with its evidence and proof. In short: local .env files are excluded from every Docker build context; the authorization request sends the discovered audience, as the Go client does; the login transaction carries and enforces its own expiry; clearing a session clears the CSRF cookie; a login is audited complete only after verification and sealing; the login route uses the contract's return_to; MECATL_BASE_URL is validated as an authority; gRPC errors map from their string code; the contracts package no longer ships into the runtime image; a manual release labels the revision it built; and the Node 24 workspace versus Node 26 runtime difference is documented where the digest is pinned.

Studio is stated as early access in the README and on the image (org.stacklok.mecatl.studio.stability=early-access). The stack is rebased onto current main, and the Studio ADR is renumbered to 0351 because main merged its own ADR 0350.

Verification

Gate Result
task studio:check — Biome, typecheck ×3, 26 server + 3 web Vitest, generated-drift pass
task lint:actions, task docs, task ac-trace (28/28 proofs resolve) pass
Smoke: bundled BFF against a spawned mecated --mock health / runtime / session / CSRF / SPA / 404 correct
docker build -f apps/Dockerfile apps + container start builds; fails closed on discovery as designed

A secure-code-reviewer pass over apps/server is owed per the plan's Definition of done.

Further amendments

Implements the amended bootstrap contract (see the plan layer below):

  • The hostAllowlist middleware answers 421 host_not_allowed for a Host other than the public URL's host (loopback only without one). /api/health stays reachable for probes.
  • The mutation check requires a matching Origin whenever one is present.
  • The BFF binds 127.0.0.1 outside the image unless STUDIO_HOST says otherwise, and the Vite dev proxy targets 127.0.0.1.
  • The auth limiter exempts the session poll and covers /oauth/callback. A login_state_mismatch callback keeps the existing session.
  • A defaultHook turns request-validation failures into problem details. gRPC errors fall back to the Connect code's HTTP class.
  • CI reads the Node version from apps/.node-version, and apps/.dockerignore drops nested .env files.
  • The early-access label wording is unified.

New proofs: the Host allowlist, loopback bind, negative return_to, the validation hook, and the Connect-class fallback. Re-verified: task studio:check passes (34 server + 3 web Vitest).

  • Readiness. A readiness middleware makes feature routes wait for negotiation. The public /api/openapi.json route is removed, because generation uses getOpenAPIDocument and the contract makes /api/health the only route outside /api/v1.
  • Refresh. The single-flight refresh keeps a successful grant shared for 60 seconds. It is tested against a fake issuer that rejects reused refresh tokens.
  • Account data. An opaque account key (a hash of the subject) is added to the session response. lib/account-storage.ts clears user-scoped storage on sign-out and on an account change.
  • Release. A gate step skips publish-studio for tags that predate Studio, and for a dispatch whose checked-out revision differs from github.sha.
  • Plan status. This layer's diff moves its acceptance plan to landed (header and index), per the plan lifecycle; the transition is authoritative only when this PR merges, and task ac-trace-strict now gates the plan.

Re-verified on the rebased stack: task studio:check passes (37 server + 6 web Vitest), and task ac-trace-strict passes with every Studio plan gated as landed (141 ACs, 0 failures).

Development stage

  • Plan / Interface
  • Implementation
  • Combined
  • Spike / Routine / Cleanup

Contract linkage

  • Work classification: Architectural
  • Classification rationale: a new system boundary (a browser-facing BFF holding user credentials in front of a mecatl deployment), a new released deployment artifact, and a durable dependency decision (Studio consumes only the published SDK)
  • Decision record: ADR 0351
  • Human waiver of spine: Yes — the directing human chose stacked (gh stack) delivery for the whole Studio series: nothing merges until every layer is reviewed, so the plan's approval-by-merge event is deferred to the end (recorded in each plan's Delivery line), and each implementation layer records the exact plan commit it built against.
  • Acceptance plan: docs/acceptance/studio-bootstrap.md
  • Human decisions resolved and recorded: Yes
  • Plan / Interface PR: docs(plan): Mecatl Studio bootstrap acceptance plan and ADR 0351 #1753
  • Approved commit baseline: e344835ed203c0400565fe8364109aff7c7ac2b5 (the plan layer below; not yet merged — stacking exception above)
  • Combined/exemption rationale: N/A

Interface conformance

  • Matches the plan's contract. One wording amendment folded into the plan layer during implementation: the Chainguard node runtime ships busybox sh and Node's bundled npm (no pnpm, no OS package manager, no sources, no dev deps).

Issue relationship

Relates to #1746 (parent #1736; stack #1766). Non-closing: the step completes when both of its layers merge.

Type of change

  • Behavioral/interface plan
  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation/process

Test plan

Baseline checks

  • Acceptance-plan checker
  • Linting (task lint)
  • Offline test suite (task test)
  • Offline demo (go run ./cmd/mecademo)
  • Markdown changed: docs generation/link checks (task docs)

Studio gates (this workspace is not covered by task lint / task test, which are Go-only): task studio:check (Biome, typecheck, Vitest, generated-drift), task ac-trace, task lint:actions — all pass; see Verification above.

User-facing change

A new browser client image ghcr.io/stacklok/mecatl/studio (bootstrap: login, runtime status, shell).

Special notes for reviewers

Part of a fourteen-layer stack; review bottom-up. Nothing merges until the whole series is reviewed.

@samuv
samuv added this pull request to stack #1766 September 22, 2026 08:01
@samuv samuv self-assigned this Sep 22, 2026
@kantord

kantord commented Sep 22, 2026

Copy link
Copy Markdown
Member

Review findings

Reviewed the bootstrap commit against its immediate plan/ADR parent, without assuming later stack layers repair it.

  • P1 — Local Compose sends provider credentials into the mecated build context. The documented flow creates apps/.env, while the mecated service builds from the repository root and executes COPY . .. The root .dockerignore does not exclude .env files, so API keys are transmitted to BuildKit and retained in an intermediate layer/cache. apps/docker-compose.yml:22, apps/docker-compose.yml:27, apps/docker/mecated.Dockerfile:17, .dockerignore:1

  • P1 — OIDC authorization omits the discovered audience. Discovery requires and stores com.stacklok.mecatl.audience, but the authorization URL never sends it. Issuers that require an explicit audience will issue the wrong token or reject the request; Mecatl then rejects login. The existing Go OIDC client does send this parameter. apps/server/src/auth/service.ts:187, apps/server/src/auth/service.ts:421

  • P1 — The 10-minute login transaction lifetime is not enforced server-side. LoginTransaction contains no issuance/expiry time, and validation checks only field shapes. Max-Age controls normal browser behavior but does not prevent replay of a copied sealed cookie after ten minutes, contrary to AC3.6. apps/server/src/auth/service.ts:45, apps/server/src/auth/service.ts:265, apps/server/src/auth/service.ts:410, apps/server/src/auth/service.ts:705

  • P2 — Real gRPC errors are mostly converted to HTTP 500. MecatlError.status is an HTTP status only for HTTP transport; for gRPC it contains Connect codes such as 5 for NotFound. errorStatus compares those values to HTTP status numbers. The test hides this by constructing the impossible combination transport: "grpc", status: 404. apps/server/src/app.ts:194, apps/server/src/app.test.ts:56

  • P2 — The public return_to parameter is implemented as returnTo. The acceptance contract exposes /auth/login?return_to=…, but the route, generated client, tests, and web shell use camel case. Contract-compliant deep links are silently discarded and redirect to /workspace. apps/server/src/routes/auth.ts:37, apps/web/src/features/auth/auth-gate.tsx:53

  • P2 — Session invalidation leaves the CSRF cookie active. clear() removes access, refresh, and login cookies but not studio_csrf. Logout, failed refresh, callback failure, and upstream authentication rejection therefore violate the requirement to clear all four cookies. The logout test only checks two. apps/server/src/auth/service.ts:255, apps/server/src/routes/auth.test.ts:114

  • P2 — Failed logins can be audited as successful. auth.login.complete is emitted immediately after token exchange, before Mecatl verifies the credential and before the cookies are successfully sealed. A rejected credential or session-size failure therefore leaves a success audit record, and the Mecatl-rejection path adds no matching failure record. apps/server/src/auth/service.ts:284, apps/server/src/routes/auth.ts:117

  • P2 — The released runtime uses an unsupported Node major. The workspace declares and builds for Node 24, but the pinned Chainguard digest is explicitly Node 26.9.0. CI therefore tests a different major than the published container runs. apps/package.json:7, apps/Dockerfile:57, apps/Dockerfile:82

  • P2 — The runtime image ships TypeScript sources despite the image contract. Although the server bundle inlines @mecatl-studio/contracts, that workspace package remains a production dependency, so pnpm deploy --prod copies its entire src/ tree into runtime node_modules. I reproduced this locally; generated and handwritten .ts files are included. apps/server/package.json:18, apps/Dockerfile:73, apps/Dockerfile:91

  • P2 — Manual releases attest and label the wrong revision. A dispatch checks out inputs.tag, but the OCI revision label and GitHub provenance use the workflow invocation’s github.sha, normally the default-branch commit. Republishing an older tag therefore builds one commit while identifying another. .github/workflows/release.yml:684, .github/workflows/release.yml:717, .github/workflows/release.yml:743

  • P2 — MECATL_BASE_URL is not validated as an authority. Values containing credentials, query strings, fragments, or non-root paths pass startup validation even though the interface contract defines this setting as the gRPC listener authority. Such misconfiguration fails later inside the SDK rather than before listening. apps/server/src/mecatl/runtime.ts:73, apps/server/src/mecatl/runtime.ts:259

task studio:check passes, so these are behavioral and artifact-contract gaps rather than current gate failures.

@samuv

samuv commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Review findings addressed

All eleven confirmed against the code and fixed in this layer. Where a fix needed evidence, I checked it first rather than reading the finding at face value.

P1

  • Provider keys sent into the mecated build context. Confirmed: the root .dockerignore excluded only build artifacts, and apps/docker/mecated.Dockerfile runs COPY . . from the repository root, so the documented apps/.env reached BuildKit and a layer. .dockerignore now excludes **/.env and **/.env.* (keeping .env.example) for every build context, with a comment saying why.
  • OIDC authorization omitted the discovered audience. Confirmed by reading the Go client: internal/adapter/oidcclient/authorization.go sends oauth2.SetAuthURLParam("audience", …). The BFF now sends the same audience parameter from the protected-resource document, and the callback test asserts it on the authorization URL.
  • The login transaction lifetime was not enforced server-side. LoginTransaction now carries expiresAt, set at issue, and validation refuses a transaction past it, so a copied sealed cookie cannot be replayed after ten minutes regardless of Max-Age. A test replays a captured transaction eleven minutes later and gets 400 login_state_mismatch.

P2

  • gRPC errors mapped to 500. Right: over gRPC MecatlError.status is a Connect code. errorStatus now maps from the stable string code first and honours status only when transport is http. The test that constructed the impossible transport: "grpc", status: 404 now uses status: 5, and a new test covers NotFound, Unauthenticated, InvalidArgument, ResourceExhausted, Unimplemented, Unavailable, an unknown code, and the HTTP path.
  • return_to implemented as returnTo. The route, generated client, auth gate, and tests now use the contract's return_to.
  • CSRF cookie left behind on session invalidation. clear() now deletes studio_csrf too, so logout, failed refresh, callback failure, and upstream rejection all clear the four cookies. The logout test checks all four.
  • Failed logins audited as successful. completeLogin no longer emits auth.login.complete. The route calls a new noteLoginComplete only after Mecatl verifies the credential and the session is sealed, and calls noteLoginFailure on the rejection and sealing paths. A test proves a rejected credential leaves a failure record and no completion.
  • Runtime Node major. The pinned Chainguard runtime ships Node 26 while the workspace builds and tests on 24. The bundle targets node24 and runs unchanged on 26, so I kept the runtime and made it honest: engines is >=24, and the Dockerfile documents the difference where the digest is pinned, with a note to re-check on every digest bump. Say so if you would rather pin a Node 24 runtime digest instead; that is a one-line change.
  • TypeScript sources in the runtime image. @mecatl-studio/contracts moved to devDependencies, since the bundle inlines it (the built dist/index.js contains no import of it), so pnpm deploy --prod no longer copies its src/ tree.
  • Manual releases labelled the wrong revision. publish-studio now resolves the checked-out commit with git rev-parse HEAD after checkout and uses it for the OCI revision label, so republishing an older tag identifies the commit it actually built.
  • MECATL_BASE_URL not validated as an authority. Startup now rejects credentials, a query, a fragment, or a path, naming the variable, before listening. MECATL_RESOURCE_URL may carry a path, since a protected resource can be namespaced, but nothing else.

The interface change for the audit hooks also touched the AuthenticationService fakes in the chat, schedules, knowledge, and settings layers; each was fixed in its own layer so every PR in the stack stays green on its own.

Also in this round

  • The stack is rebased onto current main. main merged its own ADR 0350 while this stack was open, so the Studio ADR is now ADR 0351 everywhere it is cited, in every layer, PR body, and issue. main's ADR 0350 is untouched.
  • Studio is now stated as early access in the README, the image (org.stacklok.mecatl.studio.stability=early-access), and the user documentation: the interface, the /api/v1 surface, configuration, and browser storage can change between releases without a deprecation period.

Implementation layer of docs/acceptance/studio-bootstrap.md (ADR 0351):
a self-contained pnpm workspace at apps/ — contracts (Zod → OpenAPI →
generated Hey API client, drift-gated), server (Hono BFF over the
PUBLISHED @stacklok-oss/mecatl-sdk: spawn/mock/external runtime modes,
RFC 9728 discovery with MECATL_RESOURCE_URL, PKCE login with sealed
HttpOnly cookies, 401 gating, single-flight refresh, CSP and security
headers, same-origin + double-submit CSRF, per-client rate limiting,
trusted-proxy hops, audit records, SPA serving), and web (React shell,
auth gate, connection banner, empty workspace).

Ships apps/Dockerfile (multi-stage, Chainguard node by digest,
STUDIO_IMAGE=1), a Studio-owned mecated.Dockerfile plus compose, the
studio:* Taskfile namespace, a `studio` CI job with a no-push image
build, the `publish-studio` release job cloned from the Slack bot's,
ac-trace resolver support for apps/ proofs, and the in-repo docs
(apps/README.md, docs/architecture.md, AGENTS.md).

26 server + 3 web Vitest proofs cover the plan's Scenario 2–4 ACs;
smoke-tested against a spawned `mecated --mock` and the built image.

Tracking: #1736

Signed-off-by: Samuele Verzi <[email protected]>

Answers eleven review findings against this layer.

Security and correctness: local .env files are excluded from every Docker
build context, so the documented Compose flow no longer sends provider
keys to BuildKit through the mecated image's root context; the
authorization request carries the discovered audience, as the Go client
does, so issuers that bind tokens to an audience mint the right one; the
login transaction carries its own expiry and is refused past it, so a
copied sealed cookie cannot be replayed after ten minutes; clearing a
session now clears the CSRF cookie too; and a login is audited complete
only after Mecatl verifies the credential and the session is sealed,
with a failure record on the rejection path.

Contract: the login route exposes `return_to`, the name the acceptance
plan states, instead of camel case; MECATL_BASE_URL is validated as an
authority and rejects credentials, a query, a fragment, or a path before
listening; and gRPC errors map from their stable string code rather than
from `status`, which over gRPC carries a Connect code and not an HTTP
status.

Image: the contracts workspace package moves to devDependencies, since
the bundle inlines it, so the pruned runtime no longer ships its
TypeScript sources; the Node major difference between the Node 24
workspace and the Node 26 runtime is documented where the digest is
pinned, and `engines` widened to `>=24` to match; and a manual release
labels the revision it actually checked out rather than the branch
commit that started the run.

The image and the README now state plainly that Studio is early access
and may change between releases without a deprecation period.

CI relevance: the go and macOS classifiers now treat apps/ as irrelevant,
alongside docs and the site. apps/ holds no Go package, no go.mod, and
nothing a Go build or test reads (the one repo-wide Go walker collects
go.mod files only), so a Studio-only change no longer runs the Go and
macOS matrices and inherits unrelated flaky Go tests; the studio category
owns its checks. Classifier tests cover the skip and the mixed cases, and
the macOS closure guard still passes.
@samuv
samuv merged commit a8a720d into main Sep 23, 2026
38 checks passed
@samuv
samuv deleted the studio/bootstrap branch September 23, 2026 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants