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>
118 lines
3.9 KiB
Go
118 lines
3.9 KiB
Go
package workspaceapps
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
|
|
"cdr.dev/slog/v3"
|
|
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
|
|
"github.com/coder/coder/v2/codersdk"
|
|
)
|
|
|
|
const (
|
|
// TODO(@deansheather): configurable expiry
|
|
DefaultTokenExpiry = time.Minute
|
|
|
|
// RedirectURIQueryParam is the query param for the app URL to be passed
|
|
// back to the API auth endpoint on the main access URL.
|
|
RedirectURIQueryParam = "redirect_uri"
|
|
)
|
|
|
|
type ResolveRequestOptions struct {
|
|
Logger slog.Logger
|
|
SignedTokenProvider SignedTokenProvider
|
|
Cookies AppCookies
|
|
CookieCfg codersdk.HTTPCookieConfig
|
|
|
|
DashboardURL *url.URL
|
|
PathAppBaseURL *url.URL
|
|
AppHostname string
|
|
|
|
AppRequest Request
|
|
// TODO: Replace these 2 fields with a "BrowserURL" field which is used for
|
|
// redirecting the user back to their initial request after authenticating.
|
|
// AppPath is the path under the app that was hit.
|
|
AppPath string
|
|
// AppQuery is the raw query of the request.
|
|
AppQuery string
|
|
}
|
|
|
|
func ResolveRequest(rw http.ResponseWriter, r *http.Request, opts ResolveRequestOptions) (*SignedToken, bool) {
|
|
appReq := opts.AppRequest.Normalize()
|
|
err := appReq.Check()
|
|
if err != nil {
|
|
// This is a 500 since it's a coder server or proxy that's making this
|
|
// request struct based on details from the request. The values should
|
|
// already be validated before they are put into the struct.
|
|
WriteWorkspaceApp500(opts.Logger, opts.DashboardURL, rw, r, &appReq, err, "invalid app request")
|
|
return nil, false
|
|
}
|
|
|
|
token, ok := opts.SignedTokenProvider.FromRequest(r)
|
|
if ok && token.MatchesRequest(appReq) {
|
|
// The request has a valid signed app token and it matches the request.
|
|
return token, true
|
|
}
|
|
|
|
sessionToken := opts.Cookies.TokenFromRequest(r, appReq.AccessMethod)
|
|
if _, isPreview := appurl.ParsePreviewSlug(appReq.AppSlugOrPort); isPreview {
|
|
// A preview accepts only the cookie its own sign-in set, never the
|
|
// app wildcard cookie, a header, or a query parameter.
|
|
sessionToken = ""
|
|
if cookie, err := r.Cookie(codersdk.PreviewSessionTokenCookie); err == nil {
|
|
sessionToken = cookie.Value
|
|
}
|
|
}
|
|
|
|
issueReq := IssueTokenRequest{
|
|
AppRequest: appReq,
|
|
PathAppBaseURL: opts.PathAppBaseURL.String(),
|
|
AppHostname: opts.AppHostname,
|
|
SessionToken: sessionToken,
|
|
AppPath: opts.AppPath,
|
|
AppQuery: opts.AppQuery,
|
|
}
|
|
|
|
token, tokenStr, ok := opts.SignedTokenProvider.Issue(r.Context(), rw, r, issueReq)
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
|
|
// Write the signed app token cookie.
|
|
//
|
|
// For path apps, this applies to only the path app base URL on the current
|
|
// domain, e.g.
|
|
// /@user/workspace[.agent]/apps/path-app/
|
|
//
|
|
// For subdomain apps, this applies to the entire subdomain, e.g.
|
|
// app--agent--workspace--user.apps.example.com
|
|
http.SetCookie(rw, opts.CookieCfg.Apply(&http.Cookie{
|
|
Name: codersdk.SignedAppTokenCookie,
|
|
Value: tokenStr,
|
|
Path: appReq.BasePath,
|
|
HttpOnly: true,
|
|
Expires: token.Expiry.Time(),
|
|
}))
|
|
|
|
return token, true
|
|
}
|
|
|
|
// SignedTokenProvider provides signed workspace app tokens (aka. app tickets).
|
|
type SignedTokenProvider interface {
|
|
// FromRequest returns a parsed token from the request. If the request does
|
|
// not contain a signed app token or is is invalid (expired, invalid
|
|
// signature, etc.), it returns false.
|
|
FromRequest(r *http.Request) (*SignedToken, bool)
|
|
// Issue mints a new token for the given app request. It uses the long-lived
|
|
// session token in the HTTP request to authenticate and authorize the
|
|
// client for the given workspace app. The token is returned in struct and
|
|
// string form. The string form should be written as a cookie.
|
|
//
|
|
// If the request is invalid or the user is not authorized to access the
|
|
// app, false is returned. An error page is written to the response writer
|
|
// in this case.
|
|
Issue(ctx context.Context, rw http.ResponseWriter, r *http.Request, appReq IssueTokenRequest) (*SignedToken, string, bool)
|
|
}
|