Files
coder/coderd/x/previewhost/request.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

114 lines
4.5 KiB
Go

package previewhost
import (
"net"
"net/http"
"net/http/httputil"
"net/url"
"regexp"
"strings"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
)
// Refusal is why a preview host refuses a request: the status and the
// sentence its error page shows. The caller renders the page.
type Refusal struct {
Status int
Description string
}
// FromOtherPreviewRefusal refuses a request that FromOtherPreview reports.
var FromOtherPreviewRefusal = Refusal{
Status: http.StatusForbidden,
Description: "Preview pages cannot send requests to other apps.",
}
// Prepare checks a request to a preview host of h before the caller resolves
// a ticket for it. It returns the writer that every later response must go
// through, so each one carries h's policy, and the app that host names. When
// it refuses the request, it returns the refusal instead, which the caller
// writes through the returned writer.
func (h *Hosts) Prepare(rw http.ResponseWriter, r *http.Request, host string) (http.ResponseWriter, appurl.ApplicationURL, *Refusal) {
rw = h.Wrap(rw)
// A service worker outlives the page that registered it, so it could
// keep answering on this host after the port or files change. Browsers
// send this header only for service worker scripts.
if r.Header.Get("Service-Worker") == "script" {
return rw, appurl.ApplicationURL{}, &Refusal{Status: http.StatusForbidden, Description: "Preview pages cannot register service workers."}
}
if FromOtherPreview(h.pattern, r, host) {
refusal := FromOtherPreviewRefusal
return rw, appurl.ApplicationURL{}, &refusal
}
app, _, err := h.Parse(host)
if err != nil {
return rw, appurl.ApplicationURL{}, &Refusal{Status: http.StatusBadRequest, Description: "This is not a valid preview address."}
}
// A preview loaded as the top-level page has no wrapper to keep it on
// its own host, so it is refused. Fetch metadata is missing from
// non-browser clients and from plain-HTTP origins other than localhost,
// so a request without it is treated as a page load. Chromium sends no
// fetch metadata with a WebSocket handshake, which never loads a page.
dest := r.Header.Get("Sec-Fetch-Dest")
if dest == "document" || (dest == "" && !httpapi.IsWebsocketUpgrade(r)) {
description := "Previews open only inside a Coder chat. Open this preview from its chat."
if dest == "" && h.scheme == "http" && !isLocalhostName(host) {
description = "Previews need an HTTPS access URL."
}
return rw, appurl.ApplicationURL{}, &Refusal{Status: http.StatusForbidden, Description: description}
}
return rw, app, nil
}
// WrapProxy makes proxy apply h's policy to every response it proxies before
// proxy's own ModifyResponse runs. ReverseProxy writes a WebSocket upgrade
// response to the hijacked connection, where the writer from Prepare never
// sees it. Call WrapProxy after setting proxy.ModifyResponse.
func (h *Hosts) WrapProxy(proxy *httputil.ReverseProxy) {
next := proxy.ModifyResponse
proxy.ModifyResponse = func(r *http.Response) error {
h.ApplyPolicy(r.Header)
if next == nil {
return nil
}
return next(r)
}
}
// FromOtherPreview reports whether r's Origin is a preview host of this server
// other than host. pattern is the server's app wildcard pattern.
//
// A browser sets Origin, so a preview page cannot forge it. The browser also
// adds the user's cookies for the target, so the request would act as the
// user. The preview CSP already blocks these requests. This check also
// refuses them where a browser does not enforce the CSP. Only this server's
// pattern identifies its preview hosts, so previews on other servers, such as
// workspace proxies, rely on their CSP. Callers check every app request, with
// or without preview hosts, because an open preview page keeps running after
// previews are turned off.
func FromOtherPreview(pattern *regexp.Regexp, r *http.Request, host string) bool {
origin, err := url.Parse(r.Header.Get("Origin"))
if err != nil || origin.Host == "" || pattern == nil || appurl.HostnamesMatch(origin.Host, host) {
return false
}
_, _, ok := appurl.ParsePreviewHostname(pattern, origin.Host)
return ok
}
// isLocalhostName reports whether host, with or without a port, is localhost
// or a subdomain of it, the only plain-HTTP hosts that browsers send fetch
// metadata to. A preview host is never an IP address.
func isLocalhostName(host string) bool {
if hostname, _, err := net.SplitHostPort(host); err == nil {
host = hostname
}
host = strings.ToLower(host)
return host == "localhost" || strings.HasSuffix(host, ".localhost")
}