Repository navigation
Replace signed preview-bridge handshake with an origin allowlist - #1173
Conversation
The App Studio preview bridge authenticated its parent with a signed,
single-use capability: App Studio minted ES256 JWTs through a
preview-bridge-sessions verb, the dev-agent shipped the JWKS into every
development pod, and Tilt generated and rotated a dev key pair. Any gap
in that chain left the preview "Loaded unverified" with annotations off.
The browser already enforces what the signature was proving.
postMessage stamps event.origin on every message and honours
targetOrigin, so an exact-origin allowlist decides who may drive the
bridge. A CSP frame-ancestors header keeps any other origin from
framing the dev server, and a per-document ID echoed in START binds a
session to one page load, so reloads still mark annotations stale.
- dev-agent: write {"portalOrigins": [...]} from
RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS at install, failing open;
the Vite plugin answers only those origins and sets frame-ancestors
on HTML responses.
- infrastructure: default the allowlist to the hub public URL origin,
with an override and RAILGRID_PREVIEW_BRIDGE_ENABLED=false kill
switch (chart development.previewBridge.*).
- app-studio: remove the preview-bridge-sessions verb, its request
type, schema, signing config and portal session API; the portal mints
its own session ID per document.
- Remove the dev key generator, its Makefile/Tilt wiring and the
previewBridge.enabled=false workarounds; update docs.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@mjudeikis-bot review. |
mjudeikis
left a comment
There was a problem hiding this comment.
Four notes, no Critical or Warning. The origin-allowlist design holds up against the code. On the plugin side, READY goes out with an exact targetOrigin for each configured origin. PROBE is honoured only from window.parent on an allowlisted event.origin. START must echo the per-document documentID and arrives on the transferred port. On the portal side, READY is accepted only from the iframe's contentWindow on the expected origin.
Not anchored
- Note: the foreign-parent and reload-stale cases have no automated coverage. The PR body says the live-stack run timed out. Nothing in the reviewed tests drives a non-allowlisted parent against the plugin.
preview-bridge-plugin.test.mjspasses, but I did not find a case that posts a PROBE from a non-allowlisted origin and asserts no READY. That is the security property that replaced the signature, so I would add that case. - Note: the removed
projects/preview-bridge-sessionsresource is a served-API removal. The PR body says nothing about older portals. An old portal that calls the verb against a new provider gets a 404 and shows the preview as unavailable. That is acceptable for an optional dev feature, but say so in the upgrade notes.
Checked
- Read beyond the diff:
preview-bridge-plugin.mjs: the whole client handshake (emitReady,onStart,onMessage),portalOrigins, andcreatePreviewBridgePlugin.previewBridge.ts:connect,handleWindowMessage,bindBridge,handlePortMessage.dev-agent/main.go:installSelf,atomicInstall, and the newpreviewBridgeConfigandexactPreviewBridgeOrigin.backend.go:NewandaccessGateTokens.devoverlay.go: the init-container env wiring.rgd.go:substituteTokens, to confirm the config key is not substituted into templates.operator/serve.go: the env propagation.- The chart
deployment.yaml,operator.yaml,values.yamland README. - The seed-template shim assertions in
install/seedtemplates_test.go, plus the app-studioserver.go,main.go,manifest.yamland APIExport hunks.
- A repo-wide grep finds no leftover references to
preview-bridge-sessions, the signing key, the verification JWKS orpreview-bridge-dev-keys, apart from the new negative assertions in the tests. - Hunt outcomes:
- Correctness: two notes (IDN mismatch,
$replacement). The fail-open paths remove a stale config as the docs say. - Concurrency: not applicable. The change is a browser handshake and a one-shot init step. Handshake ports are keyed per origin and closed on replace.
- Tenancy and kcp: no client or lister calls added. The APIExport resource removal matches
manifest.yamland the catalogentry, with no permission-claim change. - Provider contract: the verb table, manifest and catalogentry were all reduced together, and
make verify-provider-contractpasses. - API and codegen: the CRD,
config/kcpand chartfiles/copies and deepcopy are all consistent with the removed type. I did not re-runmake verify-codegen. - Security: the
event.originandtargetOriginchecks are exact, andframe-ancestorsis set only on HTML GETs. No credential is involved any more. The app-code-in-iframe trust boundary is unchanged from before. - Portal: no portalkit or agentkit copies touched, and no visible UI change.
- Tests: the dev-agent origin parsing, the plugin and the kro/operator env wiring each have tests. The foreign-parent case is the gap noted above.
- Correctness: two notes (IDN mismatch,
- Commands:
cd providers/infrastructure/dev-agent && GOWORK=off go vet ./... && go test -count=1 ./...passed.node --test preview-bridge-plugin.test.mjspassed 5/5.providers/infrastructure:go test -count=1 ./backend/kro/... ./operator/... ./install/...passed.providers/app-studio:go build ./...,go vet ./api/... .andgo test -count=1 ./api/... .passed.make verify-provider-contractpassed.go build ./...inproviders/infrastructurefails withassets.go:23: pattern all:portal/dist: no matching files found. The portal bundle is not built in this checkout, so the failure is environmental and not caused by the PR.node --test portal/src/previewBridge.test.mjscould not run, becausetypescriptis not installed in this checkout (nonode_modules).
- Not run:
make lint,make verify-codegen,make verify-boilerplate,vue-tsc, and the e2e and browser suites. These need a full toolchain or a Tilt/Chromium stack that is not available in this runner.
| (parsed.Path != "" && parsed.Path != "/") { | ||
| return "", fmt.Errorf("%q must be an http(s) origin without path, query or credentials", raw) | ||
| } | ||
| host := strings.ToLower(parsed.Host) |
There was a problem hiding this comment.
Note: Go accepts origins the plugin rejects, so the bridge turns off with no log
exactPreviewBridgeOrigin lowercases the host and strips default ports, but it does not punycode IDN hosts. RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS=https://münchen.de passes here and is written to preview-bridge-config.json. portalOrigins() in preview-bridge-plugin.mjs then throws, because new URL(...).origin is the punycode form and !== origin. I confirmed that throw with node. The Vite shim swallows it and never logs, so the operator sees "installed" and the preview shows "Loaded unverified". Normalise through one definition, or log in the shim. Cheapest fix is to reject non-ASCII hosts here, so the failure shows up in the init container log:
if strings.ContainsFunc(host, func(r rune) bool { return r > 127 }) {
return "", fmt.Errorf("%q must use the punycode (ASCII) form of the host", raw)
}There was a problem hiding this comment.
Fixed in b94e347. Rejecting only non-ASCII would still leave other parser disagreements: percent-escapes, $ and similar host characters, leading-zero ports, IPv6 spelling. So exactPreviewBridgeOrigin now accepts only the host form that Go and the browser canonicalise the same way: lowercase ASCII DNS labels or IPv4, and a port of 1–65535 without leading zeros. Anything else fails in the installer log. Punycode works.
TestPreviewBridgeConfigRejectsNonOrigins adds the IDN, $&, %2e, trailing-dot, :0443, IPv6 and out-of-range-port cases. A new TestPreviewBridgeConfigCanonicalizesToBrowserOrigins pins the accepted outputs, and each of them equals new URL(x).origin in node.
| const encoded = JSON.stringify(keys).replaceAll("<", "\\u003c"); | ||
| return previewBridgeClient.replace("__RAILGRID_PREVIEW_BRIDGE_VERIFICATION_KEYS__", encoded); | ||
| const encoded = JSON.stringify(portalOrigins(configuration)).replaceAll("<", "\\u003c"); | ||
| return previewBridgeClient.replace("__RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS__", encoded); |
There was a problem hiding this comment.
Note: String.replace with a string replacement interprets $ patterns in the origin list
previewBridgeClient.replace(placeholder, encoded) expands $&, $' and $` inside encoded. previewBridgeClientSource({portalOrigins:["http://a$&b"]}) produces ["http://a__RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS__b"], which I reproduced with node. $ is a legal host character in both Go's url.Parse and WHATWG URL. The value is operator-controlled and the result fails closed, but it is not the allowlist that was configured. Use a replacer function:
return previewBridgeClient.replace("__RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS__", () => encoded);There was a problem hiding this comment.
Fixed in b94e347: the replacement is now () => encoded. The new test "client source embeds origins verbatim, without replacement patterns" fails with the old string replacement. The Go side now also rejects $ in hosts, so this only matters for direct plugin callers.
| if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Host == "" { | ||
| return "" | ||
| } | ||
| return parsed.Scheme + "://" + parsed.Host |
There was a problem hiding this comment.
Note: the default allowlist silently becomes the in-cluster hub URL when publishing.hubPublicURL is unset
resolvePreviewBridgePortalOrigins reads tokens[hubPublicURLToken]. accessGateTokens fills that from RAILGRID_ACCESS_HUB_PUBLIC_URL, then falls back to RAILGRID_ACCESS_HUB_URL, then hub.url. The chart's hub.url is normally a cluster-internal address. In that case the allowlist and frame-ancestors carry an origin no browser is on, so the bridge stays off and frame-ancestors blocks nothing it should allow. The chart README documents the fallback, but nothing logs or surfaces it. Consider logging the resolved origins once in New, so an operator can tell why Annotate is missing:
origins := resolvePreviewBridgePortalOrigins(tokens[hubPublicURLToken])
log.Printf("preview bridge portal origins: %q", origins)
tokens[previewBridgePortalOriginsConfigKey] = originsThere was a problem hiding this comment.
Done in b94e347. New logs preview bridge portal origins resolved once with the origins and their source. resolvePreviewBridgePortalOrigins now returns that source:
- the override env
RAILGRID_ACCESS_HUB_PUBLIC_URL- the kill switch
- no usable URL
- "hub URL fallback (RAILGRID_ACCESS_HUB_PUBLIC_URL unset; set publishing.hubPublicURL if this origin is not browser-reachable)"
The fallback case is what you described. The test covers each source.
- dev-agent: accept only the host form Go and the browser URL parser agree on (ASCII DNS name or IPv4, port without leading zeros), so an IDN, percent-escaped or otherwise non-canonical origin fails in the installer log instead of silently disabling the bridge in Vite. - plugin: embed the origin list with a replacer function so `$` patterns in an origin are not expanded. - infrastructure: log the resolved portal origins and their source once at startup, flagging the cluster-internal hub URL fallback. - tests: dedicated cases for a non-allowlisted parent (near-miss origins, non-parent sender, forged START) and for a reloaded document refusing its predecessor's session; both fail when the origin or document-ID checks are removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review. Pushed b94e347; replies are on each inline note. On the two unanchored notes:
|
|
/approve |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: cwilhit The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
Replace signed preview-bridge handshake with an origin allowlist
Summary
The App Studio preview bridge, which powers Annotate on the live preview, authenticated its parent window with a signed, single-use capability. App Studio minted ES256 tokens through a
preview-bridge-sessionsverb. The dev-agent installed the JWKS into every development pod, and Tilt generated a dev key pair. When any link in that chain was missing (no keys, a stale JWKS in a pod, a skipped Tilt resource), the preview showed "Loaded unverified" and Annotate disappeared.The browser already enforces what the signature was proving:
postMessageorigin. The browser stampsevent.originon every message and honourstargetOrigin, so an exact-origin allowlist decides who can open or drive the bridge.Content-Security-Policy: frame-ancestors 'self' <portal origins>. Set on the dev server's HTML responses, it stops any other origin from framing the preview.documentIDper page load. READY carries it, and START must echo it asgeneration. A reload is therefore a new session, and earlier annotations are marked stale as before.No server session, no keys, no rotation.
Changes
--installstep writes/railgrid/bin/preview-bridge-config.json({"portalOrigins":[...]}) fromRAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS.frame-ancestors.development.previewBridge.portalOriginsoverrides it, anddevelopment.previewBridge.enabled: falseturns the bridge off.preview-bridge-sessionsverb,PreviewBridgeSessionsRequest, its APIResourceSchema/CRD (codegen regenerated), the signing configuration and its chart values.hack/preview-bridge-dev-keys.mjs, its Makefile and Tilt wiring, and thepreviewBridge.enabled=falseworkarounds inrailgrid devand Tilt.docs/app-studio-agent-browser.md.Upgrade notes
railgrid-dev-agent:latestcached keeps installing the old plugin, so make sure the new image is what gets pulled.development.previewBridge.portalOrigins. Infrastructure logs the resolved origins and their source at startup (preview bridge portal origins resolved). The log flags the case wherepublishing.hubPublicURLis unset and the allowlist fell back to the hub URL, which is usually cluster-internal.projects/preview-bridge-sessionsis no longer served. An App Studio portal bundle older than this provider gets a 404 from that verb and shows the preview bridge as unavailable; the preview itself still loads. The bridge is an optional development feature, so there is no compatibility shim. Portal and provider ship together in one image, so this only lasts until a stale browser tab reloads.Testing
GOWORK=off go test ./...,go vet),preview-bridge-plugin.test.mjsbackend/kroandoperatorgo test ./api/... .andpreviewBridge.test.mjs, plus portalvue-tscpkg/cliverify-tilt-browser-deployment.test.shmake verify-provider-contractgolangci-lintpreview-bridge-keyboard.browser.mjs(ported to the origin handshake) passes in real Chromium.say-hi) shows Loaded with Annotate available. The dev page carriesframe-ancestors 'self' <portal origin>, and the portal makes nopreview-bridge-sessionsrequests. This was checked in headless Chromium and by hand over an SSH tunnel.TestPersistentExecCancellationAndWorkspaceConfinement(dev-agent exec server, not touched here) failed while I ran several suites at once. It passed 30/30 runs afterwards. It cancels after a fixed 30 ms sleep and looks timing-sensitive under load.🤖 Generated with Claude Code