Skip to content

Replace signed preview-bridge handshake with an origin allowlist - #1173

Merged
railgrid-prow[bot] merged 2 commits into
mainfrom
preview-bridge-origin-allowlist
Nov 16, 2026
Merged

railgrid-prow[bot] merged 2 commits into
mainfrom
preview-bridge-origin-allowlist

Conversation

@cwilhit

@cwilhit cwilhit commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

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-sessions verb. 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:

  • postMessage origin. The browser stamps event.origin on every message and honours targetOrigin, 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.
  • Per-document binding. The bridge mints a documentID per page load. READY carries it, and START must echo it as generation. A reload is therefore a new session, and earlier annotations are marked stale as before.

No server session, no keys, no rotation.

Changes

  • dev-agent
    • The --install step writes /railgrid/bin/preview-bridge-config.json ({"portalOrigins":[...]}) from RAILGRID_PREVIEW_BRIDGE_PORTAL_ORIGINS.
    • It accepts 1–8 exact http(s) origins and fails open: if the setting is missing or invalid, it removes the config and the app still starts, just without the bridge.
    • The Vite plugin answers only those origins and sets frame-ancestors.
  • infrastructure
    • The allowlist defaults to the origin of the hub public URL.
    • Chart development.previewBridge.portalOrigins overrides it, and development.previewBridge.enabled: false turns the bridge off.
    • The operator propagates both settings to provider-serve.
  • app-studio
    • Removed the preview-bridge-sessions verb, PreviewBridgeSessionsRequest, its APIResourceSchema/CRD (codegen regenerated), the signing configuration and its chart values.
    • The portal controller no longer calls an API: it mints a random session ID per document.
  • dev tooling and docs
    • Removed hack/preview-bridge-dev-keys.mjs, its Makefile and Tilt wiring, and the previewBridge.enabled=false workarounds in railgrid dev and Tilt.
    • Rewrote the trust-model section of docs/app-studio-agent-browser.md.

Upgrade notes

  • Development pods pick up the new config only when they re-roll. Infrastructure re-applies the RGDs on startup and the dev Deployments roll on their own. A node that still has an old railgrid-dev-agent:latest cached keeps installing the old plugin, so make sure the new image is what gets pulled.
  • Portals served from a different origin than the hub must list that origin in development.previewBridge.portalOrigins. Infrastructure logs the resolved origins and their source at startup (preview bridge portal origins resolved). The log flags the case where publishing.hubPublicURL is unset and the allowlist fell back to the hub URL, which is usually cluster-internal.
  • Served-API removal. projects/preview-bridge-sessions is 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

  • Unit and contract tests:
    • dev-agent (GOWORK=off go test ./..., go vet), preview-bridge-plugin.test.mjs
    • infrastructure backend/kro and operator
    • app-studio go test ./api/... . and previewBridge.test.mjs, plus portal vue-tsc
    • pkg/cli
    • verify-tilt-browser-deployment.test.sh
    • make verify-provider-contract
    • golangci-lint
  • preview-bridge-keyboard.browser.mjs (ported to the origin handshake) passes in real Chromium.
  • Live Tilt stack: a newly created App Studio project (say-hi) shows Loaded with Annotate available. The dev page carries frame-ancestors 'self' <portal origin>, and the portal makes no preview-bridge-sessions requests. This was checked in headless Chromium and by hand over an SSH tunnel.
  • Foreign parent and reload are covered by dedicated plugin tests:
    • A non-allowlisted parent gets no READY, port or session. The test covers near-miss origins, a non-parent sender and a forged START.
    • A reloaded document refuses a START bound to its predecessor.
    • Each test fails if the origin or document-ID checks are removed (checked by mutation).
    • These were not exercised against the live stack; my scripted end-to-end run timed out before reporting.

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

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]>
@cwilhit

cwilhit commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

@mjudeikis-bot review.

@mjudeikis mjudeikis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.mjs passes, 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-sessions resource 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, and createPreviewBridgePlugin.
    • previewBridge.ts: connect, handleWindowMessage, bindBridge, handlePortMessage.
    • dev-agent/main.go: installSelf, atomicInstall, and the new previewBridgeConfig and exactPreviewBridgeOrigin.
    • backend.go: New and accessGateTokens. 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.yaml and README.
    • The seed-template shim assertions in install/seedtemplates_test.go, plus the app-studio server.go, main.go, manifest.yaml and APIExport hunks.
  • A repo-wide grep finds no leftover references to preview-bridge-sessions, the signing key, the verification JWKS or preview-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.yaml and the catalogentry, with no permission-claim change.
    • Provider contract: the verb table, manifest and catalogentry were all reduced together, and make verify-provider-contract passes.
    • API and codegen: the CRD, config/kcp and chart files/ copies and deepcopy are all consistent with the removed type. I did not re-run make verify-codegen.
    • Security: the event.origin and targetOrigin checks are exact, and frame-ancestors is 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.
  • Commands:
    • cd providers/infrastructure/dev-agent && GOWORK=off go vet ./... && go test -count=1 ./... passed.
    • node --test preview-bridge-plugin.test.mjs passed 5/5.
    • providers/infrastructure: go test -count=1 ./backend/kro/... ./operator/... ./install/... passed.
    • providers/app-studio: go build ./..., go vet ./api/... . and go test -count=1 ./api/... . passed.
    • make verify-provider-contract passed.
    • go build ./... in providers/infrastructure fails with assets.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.mjs could not run, because typescript is not installed in this checkout (no node_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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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] = origins

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@cwilhit

cwilhit commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Pushed b94e347; replies are on each inline note. On the two unanchored notes:

  • Foreign parent coverage. A foreign-origin PROBE was already asserted inside "bridge answers only the configured portal origin", but it was easy to miss. Two dedicated tests now cover it:

    • "bridge gives a non-allowlisted parent no READY, port or session": near-miss origins (http://, a different port, a subdomain, null), a non-parent sender on the right origin, and a forged START that carries its own port.
    • "a reloaded preview document refuses a session bound to its predecessor".

    Note that emitReady checks the origin a second time, so removing only the PROBE check doesn't fail anything. I removed both origin checks together, and separately the document-ID check; each mutation fails the matching test.

  • Served-API removal. Added to the PR description's upgrade notes. An older portal gets a 404 from projects/preview-bridge-sessions and shows the bridge as unavailable; the preview itself still loads. There's no shim because the bridge is optional and the portal ships in the same image.

@cwilhit

cwilhit commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator Author

/approve

@railgrid-prow

railgrid-prow Bot commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

[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

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@railgrid-prow
railgrid-prow Bot merged commit f44b028 into main Nov 16, 2026
18 checks passed
mjudeikis pushed a commit that referenced this pull request Nov 16, 2026
Replace signed preview-bridge handshake with an origin allowlist
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants