Files
coder/coderd/workspaceapps/preview.go
T
Danielle MaywoodandClaude Opus 5.5 02567e9194 feat: serve agent previews on strict preview hosts (#32439)
Agent-written pages are untrusted, because a prompt-injected agent can
write any HTML. The security review (coder/security-assessments#437)
showed that serving them like ordinary apps lets them reach the user's
apps in every workspace. Previews therefore get their own strict host
mode instead of the app path: a sandboxing CSP, framing only by the
dashboard, no shared app cookie, and no top-level loads.

Preview hosts sit under the existing wildcard app hostname, so operators
need no new DNS or certificates. The experiment stays out of the safe
experiments, so `--experiments='*'` does not enable it, until we have
more experience running previews. That is a rollout choice, not a known
safety problem.

<details>
<summary>Implementation details</summary>

Adds the `open-preview` experiment, which is hidden from
`--experiments='*'` and must be named explicitly, and serves agent
previews on preview hosts under the existing wildcard app hostname in a
strict mode. A security review (coder/security-assessments#437) showed
that agent-written pages served like ordinary apps can reach the user's
apps in every workspace, so preview hosts are locked down:

- `preview--<id>--<agent>--<workspace>--<owner>` serves a file preview
from the agent API (port 4), and `preview--<port>--…` serves a port.
Both use the owner sharing level and ignore port shares. The port
forwarding display app only hides the dashboard's ports UI, so it does
not gate port previews, just as it does not gate port URLs. Connection
logs record file previews as `workspace_app` and port previews as
`port_forwarding`, under the `preview--` slug.
- `coderd/x/previewhost` decides how previews are hosted. Coderd and
workspace proxies build one `Hosting` at startup with
`previewhost.Strict`, and every preview host request goes through
`servePreview`. A later preview domain on another site would add a
second constructor. `Hosting.Sandbox`, `Hosting.URL` and
`PreviewID.Slug` are used by the sign-in (#32522) and tool (#32440) PRs.
`API.previewsUnavailable` and `previewhost.ErrHostPrefixCookieOff` have
no reader here beyond the startup log; the sign-in (#32522) and tool
(#32440) PRs read them.
- `Hosting.ApplyPolicy` adds the CSP (`sandbox`, `default-src 'self'`,
`form-action 'self'`, `frame-ancestors` the dashboard) and drops `Link`
headers, `Clear-Site-Data` and cookies with a `Domain` attribute. A
response writer applies it to every response coderd writes on a preview
host, including its own sign-in, error and 403 pages, at `WriteHeader`,
because Go's `ReverseProxy` clears response headers after a 1xx. The
writer drops 1xx responses other than 101. `ReverseProxy` writes a
WebSocket 101 to the hijacked connection instead, so the proxy also
applies the policy to every proxied response in `ModifyResponse`.
- Requests whose `Origin` is another preview host of the same server get
a 403, before CORS is applied.
- `DBTokenProvider.Issue` refuses previews unless the experiment is on,
`--host-prefix-cookie` is enabled, the request is a subdomain request,
and the caller owns the workspace. The host-prefix requirement keeps a
preview's script from replacing the user's Coder session cookie; without
it, coderd still starts and logs a warning.
- A preview without a session gets a 401 page that posts a
`coder-preview-sign-in-needed` message to the dashboard, which then
signs the user in once (see #32522).
- A top-level open of a preview host gets a 403 page that links to the
dashboard, so a preview never loads outside the dashboard's wrapper.
Browsers send no fetch metadata to a plain-HTTP host other than
localhost, so there the page says previews need an HTTPS access URL.
Service workers are refused.

</details>

**Stack** (review bottom-up). Replaces the closed #31282 stack. Security
review: coder/security-assessments#437.

1. #32438 Agent file previews
2. #32439 Strict preview hosting and experiment, this PR
3. #32522 Preview sign-in
4. #32440 open_preview chat tool
5. #32441 Agents UI
6. #32442 Docs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 10:42:54 +00:00

95 lines
3.6 KiB
Go

package workspaceapps
import (
"html/template"
"net/http"
"net/url"
"github.com/go-chi/chi/v5"
"github.com/coder/coder/v2/coderd/x/previewhost"
"github.com/coder/coder/v2/site"
)
// servePreview serves a request to a preview host. previewhost checks the
// request and wraps the writer, so every response coderd writes carries the
// preview policy, and proxyWorkspaceApp applies the same policy to proxied
// responses, WebSocket upgrades included.
func (s *Server) servePreview(rw http.ResponseWriter, r *http.Request, host string, middlewares []func(http.Handler) http.Handler) {
rw, app, refusal := s.PreviewHosts.Prepare(rw, r, host)
if refusal != nil {
writePreviewError(rw, r, s.DashboardURL, refusal.Status, refusal.Description)
return
}
// The smuggled API key sets a cookie on the whole app wildcard, which a
// preview must never do.
if r.URL.Query().Has(SubdomainProxyAPIKeyParam) {
writePreviewError(rw, r, s.DashboardURL, http.StatusBadRequest, "Previews sign in only from the dashboard.")
return
}
token, ok := ResolveRequest(rw, r, ResolveRequestOptions{
Logger: s.Logger,
Cookies: s.cookies,
CookieCfg: s.CookiesConfig,
SignedTokenProvider: s.SignedTokenProvider,
DashboardURL: s.DashboardURL,
PathAppBaseURL: s.AccessURL,
AppHostname: s.Hostname,
AppRequest: Request{
AccessMethod: AccessMethodSubdomain,
BasePath: "/",
UsernameOrID: app.Username,
WorkspaceNameOrID: app.WorkspaceName,
AgentNameOrID: app.AgentName,
AppSlugOrPort: app.AppSlugOrPort,
},
AppPath: r.URL.Path,
AppQuery: r.URL.RawQuery,
})
if !ok {
return
}
// Previews never get the app's CORS handling, so ModifyResponse strips
// any CORS headers the preview server sends.
chi.Chain(middlewares...).HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
s.proxyWorkspaceApp(rw, r, *token, r.URL.Path, app)
}).ServeHTTP(rw, r)
}
func writePreviewError(rw http.ResponseWriter, r *http.Request, dashboardURL *url.URL, status int, description string) {
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: status,
Title: http.StatusText(status),
Description: description,
Actions: []site.Action{{URL: dashboardURL.String(), Text: "Back to site"}},
})
}
// previewSignInNeeded is what a preview host's signed-out page posts to the
// dashboard that frames it. The dashboard accepts it only from the preview
// frame's origin and window, and then signs the preview in.
const previewSignInNeeded = "coder-preview-sign-in-needed"
// writePreviewSignedOut answers a preview request that has no session.
func writePreviewSignedOut(rw http.ResponseWriter, r *http.Request, dashboardURL *url.URL) {
// JSEscapeString escapes quotes, <, > and &, so its strings are safe in a
// quoted script string.
message := `"` + template.JSEscapeString(previewSignInNeeded) + `"`
dashboardOrigin := `"` + template.JSEscapeString(dashboardURL.Scheme+"://"+dashboardURL.Host) + `"`
site.RenderStaticErrorPage(rw, r, site.ErrorPageData{
Status: http.StatusUnauthorized,
Title: http.StatusText(http.StatusUnauthorized),
Description: "<p>Reopen this preview from Coder to sign in again.</p>" +
"<script>window.top.postMessage(" + message + ", " + dashboardOrigin + ")</script>",
RenderDescriptionMarkdown: true,
Actions: []site.Action{{URL: dashboardURL.String(), Text: "Back to site"}},
})
}
func writeFromOtherPreview(rw http.ResponseWriter, r *http.Request, dashboardURL *url.URL) {
writePreviewError(rw, r, dashboardURL, previewhost.FromOtherPreviewRefusal.Status, previewhost.FromOtherPreviewRefusal.Description)
}