Skip to content

fix(platform): repair boot and serving-shell dead-ends - #3132

Merged
larryro merged 6 commits into
mainfrom
fix/scim-boot-shell
Sep 3, 2026
Merged

larryro merged 6 commits into
mainfrom
fix/scim-boot-shell

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Fixes the boot/serving-shell dead-end class from the deep review: five verified findings, each with a regression test that fails on main (or a structural guard where the artifact is a Dockerfile).

1. SCIM per-resource ops broken on the advertised /http_api tenant URL (critical)

extractPathParts sliced prefix.length chars without checking the path starts with the prefix. On the advertised alias mount (/http_api/scim/v2, which app.ts:171 mounts and the proxy forwards path-preserved) /http_api/scim/ is exactly as long as /scim/v2/Users/, so every per-resource op parsed id: 'v2' — an IdP configured with the tenant URL the admin UI advertises (getPublicHttpApiUrl() + /scim/v2, also meta.location) could create/list users but never update, deactivate, or delete them.

  • Fix: extractPathParts now locates the prefix in the pathname (every prefix starts with /, so a match always sits on a segment boundary) and answers an empty id when absent (backend/core/lib/rest/helpers.ts).
  • Caller sweep: rg shows exactly two callers — the SCIM Users/Groups dispatchers. No other module uses the helper.
  • Tests: parser cases for both mounts + absent-prefix + subPath (helpers.test.ts); dispatcher-level tests pinning that GET/DELETE on /http_api/scim/v2/Users/:id and /Groups/:id resolve the real id (backend/core/scim/http_actions.test.ts). Verified failing on main: the three alias-mount cases fail, the bare-mount ones pass — exactly the reported asymmetry.

2. Backend roles never receive WEBDAV_APP_PASSWORD_HMAC_KEY in containers (high)

The entrypoint's api|worker|all branch execs node (line ~145) before the web lane sources env.sh and derives the key from INSTANCE_SECRET (line ~265) — and the web-tier process (server.ts) doesn't even read the key, while the backend process that needs it (webdav hash/verify, hostcall tokens, sandbox stage tokens — all reading raw process.env) never got it.

  • Fix: loadEnv() (backend boot) now calls the existing ensureWebdavHmacKey from lib/webdav/hmac-key.ts — the single derivation, already pinned by test to be byte-identical to the entrypoint's shell sha256. It caches the key onto the boot env so all four lazy readers pick it up; an explicit WEBDAV_APP_PASSWORD_HMAC_KEY still wins, and no INSTANCE_SECRET leaves behavior exactly as before. No shell duplication; single source of truth kept.
  • Role→env trace (by reading, not execution):
    • web: entrypoint web flow → env.sh → ensure_instance_secret → shell derivation → bun server.ts (unchanged).
    • api/worker/all containers: compose env_file: .env (the CLI's ensure-env.ts:647 writes INSTANCE_SECRET=<64-hex> there) → exec node main.ts → new: loadEnv() derives the key.
    • host dev: scripts/dev-engine.ts / dev-secrets.ts already call ensureWebdavHmacKey (unchanged; the boot call is idempotent).
  • Verification limits: unit-tested derivation (fails on main); bash -n docker-entrypoint.sh clean (script untouched); the compose/env_file wiring was traced by reading, not by running a container.

3. Squash stage drops KNOWLEDGE_MIGRATIONS_DIR (high)

The FROM scratch squash re-declares the runner's ENV by hand and dropped exactly one var: KNOWLEDGE_MIGRATIONS_DIR. findMigrationsDir's fallback walks for a repo checkout a flat image doesn't have, so BYO-corpus preparation degraded to "apply the migrations yourself" in every shipped image — the exact production bug backend/MIGRATION.md:127 records as fixed "with a guard test" that did not exist.

  • Fix: the var is re-declared in the squash ENV block; diffing the two blocks shows it was the only casualty.
  • Guard (tests/guards/dockerfile-env-parity.guard.test.ts, the promised one): parses the Dockerfile's runner + squash stages and pins the ENV blocks equal name-and-value (any future squash drop fails with the variable named), pins the DDL COPY + both pointer lines, and (follow-up commit) the builder/dev-stage copy + workspace-layout pointer — completing the MIGRATION.md promise. Verified failing on main's Dockerfile.
  • Verification limits: no docker build was run; the guard asserts the Dockerfile text, and the squash inherits the runner filesystem via COPY --from=runner / /, so the ENV pointer is the only missing piece.

4. Graceful shutdown hangs on open /events streams → SIGKILL (high)

shutdown() awaited a bare server.close(), which waits for every open connection; SSE responses never end on their own (15s heartbeats, loop exits only on client abort). One connected browser parked shutdown past the orchestrator's grace (compose default 10s, backend-api sets none) → SIGKILL with boss.stop({graceful}), sql.end, and the error flush unreached — in-flight jobs (including retryLimit-0 sends) died mid-write.

  • Fix:
    • realtime/sse.ts keeps a registry of live streams; endAllEventStreams() aborts them (hono's abort() cancels the response readable, so the connection goes idle immediately and the loop exits on its next tick).
    • New backend/http-shutdown.ts closeServerGracefully(): ends the streams, then closes with a periodic closeIdleConnections() sweep and a 5s closeAllConnections() backstop for connections the registry cannot see (long streaming responses) — well under the 10s SIGKILL so the graceful job stop still runs. The sweep matters: close() reaps idle connections only at the moment it is called, and a connection that goes idle a tick later otherwise lingers until the client's keep-alive timer (observed: undici's 4s) — found empirically while writing the test.
    • main.ts uses the helper.
  • Test (backend/http-shutdown.test.ts, real serve() socket + the real events handler over stubbed sql): (a) the premise — a bare server.close() does NOT fire within 500ms while one SSE client is connected; (b) closeServerGracefully resolves well before the force deadline with an open SSE client, and the client observes its stream end; (c) the force backstop closes an unregistered never-ending response at the deadline. (a) pins main's behavior directly; the helper/registry don't exist on main, so the file as a whole also fails there.

5. Email-attachment URLs mint the retired /http_api/storage route (high)

buildBlobServeUrl/buildDownloadUrl minted ${SITE_URL}${BASE_PATH}/http_api/storage?.... The 0.5 backend mounts no such route and the proxy injects only four /http_api lanes (sso, scim, trusted-headers, cloud-import oauth) — the URL fell through to the SPA catch-all. Every mail-connector attachment stored a dead link (sole live caller: materialize_email_attachments.ts, via syncMailbox).

  • Decision — re-point, not re-mount: consumers of the stored URL are exclusively same-origin browser fetches (the conversation download anchor and inline cid <img>es; outbound connector sends re-presign fresh per send and never read the stored field — swept every consumer). The live serving contract is a presigned S3 GET minted at open time, which cannot be stored (it expires). So the builder now mints a stable, session + org-membership-gated redirect: GET /api/app/files/serve?orgId&ref&filename → 302 to a fresh presigned GET (attachment disposition when a filename is given). Reviving the retired unauthenticated /http_api/storage door would have required a new proxy lane AND reintroduced a capability-URL surface that outlives conversation access — the gated lane matches how every other /api/app surface authorizes, and the proxy's existing /api/app/* lane forwards it.
  • Changes: /serve route in domains/files/routes.ts (declared before /:fileId); getFileUrl gains an optional filename (presign disposition — object keys are nameless <org>/<uuid> by design); buildBlobServeUrl re-pointed (+ getPublicAppApiUrl); buildDownloadUrl deleted — its branch was unreachable (0.5's putOrgBlobBytes always answers s3: refs) and it had no other importer; the ingest caller now has one lane.
  • Tests: public_storage_url.test.ts asserts the minted URL against the REAL router (createApp with stub deps): the path must reach the mounted lane (the session gate's 401, not Hono's 404), the retired path must stay unmounted, plus param/BASE_PATH shape; materialize_email_attachments.test.ts pins the stored URL. Verified failing on main — the route-existence test fails there with expected 404 to be 401, i.e. the minted URL literally 404s against main's router.
  • Known bound: attachment rows stored BEFORE this fix keep their old dead URLs (reuse_stored_attachments carries pointers forward); re-pointing them would be a data backfill over conversation metadata — deliberately out of this PR. New syncs mint working links.

Refuted findings

None — all five verified in code before changing anything.

Gates run

  • Touched/new test files (scim, rest helpers, env + hmac-key, http-shutdown, storage-url, materialize, Dockerfile guard): green; each code-level regression test verified to fail against main's sources (stash-swap runs quoted above).
  • bun run --filter @tale/platform typecheck — exit 0.
  • bun run --filter @tale/platform lint (oxlint --type-aware) — exit 0.
  • bash -n services/platform/docker-entrypoint.sh — clean.
  • backend:integration (throwaway tale-db + MinIO per backend/README.md, ITEST_S3_ENDPOINT on :59001 to leave the dev stack's store untouched) — run because main.ts + app routing were touched: 279/279 checks passed, exit 0 (includes the live /events stream + Last-Event-ID replay checks against the patched handler, and the suite's own server.close() teardown).
  • Final consolidated run of all touched + adjacent test files (scim, rest helpers, env, hmac-key, http-shutdown, storage-url, materialize, both guards, backend/realtime): 10 files / 135 tests passed; lint + typecheck re-run green after the last merge.

Verified by reading only (no execution)

  • The compose env_file/CLI .env path that delivers INSTANCE_SECRET to backend containers (finding 2).
  • The Dockerfile squash semantics (no image build; text-level guard + the COPY --from=runner / / inheritance argument, finding 3).
  • The proxy lane list (Caddyfile + proxy entrypoint read, not a live proxy, findings 1/5).

@larryro
larryro marked this pull request as ready for review September 3, 2026 03:50
@larryro
larryro merged commit 31a8329 into main Sep 3, 2026
32 of 33 checks passed
@larryro
larryro deleted the fix/scim-boot-shell branch September 3, 2026 03:50
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.

1 participant