Skip to content

Commit 327e5ed

Browse files
feat: serve agent previews on strict preview hosts
Adds the hidden open-preview experiment and serves file and port previews on preview hosts under the wildcard app hostname, with the hosting mode chosen by the new previewhost package. Every preview response carries a sandboxing CSP, cross-preview origins and top-level opens are refused, and token issuance requires the experiment, a subdomain request and workspace ownership. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5e517bd commit 327e5ed

25 files changed

Lines changed: 1694 additions & 19 deletions

‎coderd/apidoc/docs.go‎

Lines changed: 7 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/apidoc/swagger.json‎

Lines changed: 7 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎coderd/coderd.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ import (
9797
"github.com/coder/coder/v2/coderd/webpush"
9898
"github.com/coder/coder/v2/coderd/workspaceapps"
9999
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
100+
"github.com/coder/coder/v2/coderd/workspaceapps/previewhost"
100101
"github.com/coder/coder/v2/coderd/workspaceconnwatcher"
101102
"github.com/coder/coder/v2/coderd/workspacestats"
102103
"github.com/coder/coder/v2/coderd/wsbuilder"
@@ -735,6 +736,21 @@ func New(options *Options) *API {
735736
AISeatTracker: aiseats.Noop{},
736737
}
737738

739+
api.previewsUnavailable = previewhost.CheckCookieConfig(options.DeploymentValues.HTTPCookies)
740+
switch {
741+
case api.previewsUnavailable != nil:
742+
if experiments.Enabled(codersdk.ExperimentOpenPreview) {
743+
options.Logger.Warn(ctx, "workspace previews are unavailable", slog.Error(api.previewsUnavailable))
744+
}
745+
case options.AppHostname == "":
746+
api.previewsUnavailable = xerrors.New("the deployment has no wildcard app hostname")
747+
default:
748+
api.previewHosting, err = previewhost.Strict(options.AppHostname, options.AccessURL, options.AccessURL)
749+
if err != nil {
750+
panic(xerrors.Errorf("create preview hosting: %w", err))
751+
}
752+
}
753+
738754
api.ExperimentEvaluator, err = experimentrules.New(
739755
options.Logger.Named("experiments"),
740756
experimentrules.NewDBStore(options.Database),
@@ -757,6 +773,7 @@ func New(options *Options) *API {
757773
options.WorkspaceAppAuditSessionTimeout,
758774
options.AppSigningKeyCache,
759775
options.PrometheusRegistry,
776+
experiments,
760777
)
761778

762779
f := appearance.NewDefaultFetcher(options.Database, api.DeploymentValues.DocsURL.String())
@@ -1078,6 +1095,7 @@ func New(options *Options) *API {
10781095
AccessURL: api.AccessURL,
10791096
Hostname: api.AppHostname,
10801097
HostnameRegex: api.AppHostnameRegex,
1098+
Previews: api.previewHosting,
10811099
RealIPConfig: options.RealIPConfig,
10821100

10831101
SignedTokenProvider: api.WorkspaceAppsProvider,
@@ -2254,6 +2272,10 @@ type API struct {
22542272

22552273
*Options
22562274
mcpHTTPClient *http.Client
2275+
// previewHosting is how this server hosts agent-authored previews. It is
2276+
// nil when previewsUnavailable says why not.
2277+
previewHosting *previewhost.Hosting
2278+
previewsUnavailable error
22572279
// ID is a uniquely generated ID on initialization.
22582280
// This is used to associate objects with a specific
22592281
// Coder API instance, like workspace agents to a

‎coderd/httpapi/cookie.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ func StripCoderCookies(header string) string {
2929
// subdomain hostname. See the workspaceapps package for more
3030
// details.
3131
strings.HasPrefix(name, codersdk.SubdomainAppSessionTokenCookie) ||
32+
// Preview hosts use the __Host- name over HTTPS and the plain
33+
// name over HTTP, so strip both.
34+
strings.TrimPrefix(name, "__Host-") == codersdk.PreviewSessionTokenCookie ||
3235
name == codersdk.SignedAppTokenCookie {
3336
continue
3437
}

‎coderd/httpapi/cookie_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ func TestStripCoderCookies(t *testing.T) {
3434
}, {
3535
"coder_signed_app_token=ok; wow=test",
3636
"wow=test",
37+
}, {
38+
"coder_preview_session_token=x; wow=test",
39+
"wow=test",
40+
}, {
41+
"__Host-coder_preview_session_token=x; wow=test",
42+
"wow=test",
3743
}} {
3844
t.Run(tc.Input, func(t *testing.T) {
3945
t.Parallel()

‎coderd/workspaceapps/appurl/appurl.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ func (a *ApplicationURL) ChangePortProtocol(target string) ApplicationURL {
154154
//
155155
// Where agent name is:
156156
// - REQUIRED for ports: 8080--agent--workspace--user, 8080s--agent--workspace--user
157+
// - REQUIRED for previews: preview--0123abcd--agent--workspace--user, preview--8080--agent--workspace--user
157158
// - OPTIONAL for app slugs: myapp--workspace--user (agent name omitted)
158159
//
159160
// Examples:
@@ -179,6 +180,23 @@ func ParseSubdomainAppURL(subdomain string) (ApplicationURL, error) {
179180
subdomain = prefixSegments[len(prefixSegments)-1]
180181
}
181182

183+
if rest, ok := strings.CutPrefix(subdomain, PreviewSlugPrefix); ok {
184+
matches := appURL.FindStringSubmatch(rest)
185+
if matches != nil {
186+
slug := PreviewSlugPrefix + matches[appURL.SubexpIndex("AppSlug")]
187+
agentName := matches[appURL.SubexpIndex("AgentName")]
188+
if _, ok := ParsePreviewSlug(slug); ok && agentName != "" {
189+
return ApplicationURL{
190+
Prefix: prefix,
191+
AppSlugOrPort: slug,
192+
AgentName: agentName,
193+
WorkspaceName: matches[appURL.SubexpIndex("WorkspaceName")],
194+
Username: matches[appURL.SubexpIndex("Username")],
195+
}, nil
196+
}
197+
}
198+
}
199+
182200
matches := appURL.FindStringSubmatch(subdomain)
183201
if matches == nil {
184202
return ApplicationURL{}, xerrors.Errorf("invalid application url format: %q", subdomain)

‎coderd/workspaceapps/appurl/appurl_test.go‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,31 @@ func TestParseSubdomainAppURL(t *testing.T) {
276276
Username: "user",
277277
},
278278
},
279+
{
280+
Name: "Preview--Agent--Workspace--User",
281+
Subdomain: "preview--0123abcd--agent--workspace--user",
282+
Expected: appurl.ApplicationURL{
283+
AppSlugOrPort: "preview--0123abcd",
284+
AgentName: "agent",
285+
WorkspaceName: "workspace",
286+
Username: "user",
287+
},
288+
},
289+
{
290+
Name: "Invalid_PreviewID",
291+
Subdomain: "preview--0123abc--agent--workspace--user",
292+
ExpectedError: "invalid application url format",
293+
},
294+
{
295+
Name: "PreviewWithoutAgentIsAppSlug",
296+
Subdomain: "preview--0123abcd--workspace--user",
297+
Expected: appurl.ApplicationURL{
298+
AppSlugOrPort: "preview",
299+
AgentName: "",
300+
WorkspaceName: "workspace",
301+
Username: "user",
302+
},
303+
},
279304
}
280305

281306
for _, c := range testCases {

‎coderd/workspaceapps/appurl/preview.go‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,15 @@ import (
44
"crypto/sha256"
55
"encoding/hex"
66
"regexp"
7+
"strconv"
8+
"strings"
79

810
"golang.org/x/xerrors"
911
)
1012

13+
// PreviewSlugPrefix starts the app slug of every preview.
14+
const PreviewSlugPrefix = "preview--"
15+
1116
var previewIDFormat = regexp.MustCompile(`^[0-9a-f]{8}$`)
1217

1318
// PreviewID identifies a file preview that a workspace agent serves, such as
@@ -31,3 +36,55 @@ func (id *PreviewID) UnmarshalText(text []byte) error {
3136
*id = PreviewID(text)
3237
return nil
3338
}
39+
40+
// Slug returns the app slug that serves the preview, such as
41+
// "preview--0123abcd".
42+
func (id PreviewID) Slug() string {
43+
return PreviewSlugPrefix + string(id)
44+
}
45+
46+
// PreviewTarget is what a preview slug serves: files a workspace agent
47+
// published under ID, or an HTTP server on Port. Exactly one is set.
48+
type PreviewTarget struct {
49+
ID PreviewID
50+
Port uint16
51+
}
52+
53+
// ParsePreviewSlug returns what slug serves, such as file preview "0123abcd"
54+
// for "preview--0123abcd" or port 8080 for "preview--8080". A port has no
55+
// leading zeros, so each port has one hostname.
56+
func ParsePreviewSlug(slug string) (PreviewTarget, bool) {
57+
target, ok := strings.CutPrefix(slug, PreviewSlugPrefix)
58+
if !ok {
59+
return PreviewTarget{}, false
60+
}
61+
if previewIDFormat.MatchString(target) {
62+
return PreviewTarget{ID: PreviewID(target)}, true
63+
}
64+
port, err := strconv.ParseUint(target, 10, 16)
65+
if err != nil || port == 0 || strconv.FormatUint(port, 10) != target {
66+
return PreviewTarget{}, false
67+
}
68+
return PreviewTarget{Port: uint16(port)}, true
69+
}
70+
71+
// ParsePreviewHostname returns the app and target of hostname when it is a
72+
// preview host under the wildcard app hostname pattern: after any
73+
// "prefix---", the wildcard part is exactly
74+
// "preview--{ID or port}--{agent}--{workspace}--{owner}". Names cannot hold
75+
// "--", so an app or port hostname, at most four parts, never matches.
76+
func ParsePreviewHostname(pattern *regexp.Regexp, hostname string) (ApplicationURL, PreviewTarget, bool) {
77+
subdomain, ok := ExecuteHostnamePattern(pattern, strings.ToLower(hostname))
78+
if !ok {
79+
return ApplicationURL{}, PreviewTarget{}, false
80+
}
81+
app, err := ParseSubdomainAppURL(subdomain)
82+
if err != nil {
83+
return ApplicationURL{}, PreviewTarget{}, false
84+
}
85+
target, ok := ParsePreviewSlug(app.AppSlugOrPort)
86+
if !ok {
87+
return ApplicationURL{}, PreviewTarget{}, false
88+
}
89+
return app, target, true
90+
}

‎coderd/workspaceapps/appurl/preview_test.go‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ package appurl_test
22

33
import (
44
"encoding/json"
5+
"regexp"
56
"testing"
67

78
"github.com/stretchr/testify/require"
89

910
"github.com/coder/coder/v2/coderd/workspaceapps/appurl"
11+
"github.com/coder/coder/v2/provisioner"
1012
)
1113

1214
func TestNewPreviewID(t *testing.T) {
@@ -27,3 +29,90 @@ func TestPreviewIDUnmarshalText(t *testing.T) {
2729
require.Error(t, json.Unmarshal([]byte(raw), &id), raw)
2830
}
2931
}
32+
33+
func TestPreviewSlugIsNeverAnAppSlug(t *testing.T) {
34+
t.Parallel()
35+
36+
for _, id := range []appurl.PreviewID{"00000000", "ffffffff", appurl.NewPreviewID("/home/coder/site")} {
37+
require.False(t, provisioner.AppSlugRegex.MatchString(id.Slug()), id.Slug())
38+
}
39+
for _, slug := range []string{"preview--9", "preview--8080", "preview--65535"} {
40+
require.False(t, provisioner.AppSlugRegex.MatchString(slug), slug)
41+
}
42+
}
43+
44+
func TestParsePreviewSlug(t *testing.T) {
45+
t.Parallel()
46+
47+
for slug, want := range map[string]appurl.PreviewTarget{
48+
"preview--0123abcd": {ID: "0123abcd"},
49+
"preview--8080": {Port: 8080},
50+
"preview--9": {Port: 9},
51+
"preview--65535": {Port: 65535},
52+
} {
53+
got, ok := appurl.ParsePreviewSlug(slug)
54+
require.True(t, ok, slug)
55+
require.Equal(t, want, got, slug)
56+
}
57+
58+
// A port has one hostname, so leading zeros are refused.
59+
for _, slug := range []string{"preview--08080", "preview--0", "preview--65536", "preview--8080s", "preview--", "8080", "preview--0123ABCD"} {
60+
_, ok := appurl.ParsePreviewSlug(slug)
61+
require.False(t, ok, slug)
62+
}
63+
}
64+
65+
func TestParsePreviewHostname(t *testing.T) {
66+
t.Parallel()
67+
68+
dotPattern, err := appurl.CompileHostnamePattern("*.apps.example.com")
69+
require.NoError(t, err)
70+
suffixPattern, err := appurl.CompileHostnamePattern("*--apps.example.com")
71+
require.NoError(t, err)
72+
portPreview := appurl.ApplicationURL{AppSlugOrPort: "preview--8080", AgentName: "agent", WorkspaceName: "workspace", Username: "user"}
73+
for _, tc := range []struct {
74+
name string
75+
pattern *regexp.Regexp
76+
hostname string
77+
wantApp appurl.ApplicationURL
78+
wantTarget appurl.PreviewTarget
79+
}{
80+
{
81+
name: "FilePreview",
82+
pattern: dotPattern,
83+
hostname: "preview--0123abcd--agent--workspace--user.apps.example.com",
84+
wantApp: appurl.ApplicationURL{AppSlugOrPort: "preview--0123abcd", AgentName: "agent", WorkspaceName: "workspace", Username: "user"},
85+
wantTarget: appurl.PreviewTarget{ID: "0123abcd"},
86+
},
87+
{name: "PortPreview", pattern: dotPattern, hostname: "preview--8080--agent--workspace--user.apps.example.com", wantApp: portPreview, wantTarget: appurl.PreviewTarget{Port: 8080}},
88+
{name: "UpperCaseWithPort", pattern: dotPattern, hostname: "PREVIEW--8080--agent--workspace--user.apps.example.com:8443", wantApp: portPreview, wantTarget: appurl.PreviewTarget{Port: 8080}},
89+
{name: "SuffixPattern", pattern: suffixPattern, hostname: "preview--8080--agent--workspace--user--apps.example.com", wantApp: portPreview, wantTarget: appurl.PreviewTarget{Port: 8080}},
90+
{
91+
name: "Prefixed",
92+
pattern: dotPattern,
93+
hostname: "x---preview--8080--agent--workspace--user.apps.example.com",
94+
wantApp: appurl.ApplicationURL{Prefix: "x---", AppSlugOrPort: "preview--8080", AgentName: "agent", WorkspaceName: "workspace", Username: "user"},
95+
wantTarget: appurl.PreviewTarget{Port: 8080},
96+
},
97+
// An app whose slug is "preview" is not a preview, whatever its agent
98+
// is named.
99+
{name: "AppNamedPreview", pattern: dotPattern, hostname: "preview--agent--workspace--user.apps.example.com"},
100+
{name: "AppNamedPreviewWithoutAgent", pattern: dotPattern, hostname: "preview--workspace--user.apps.example.com"},
101+
{name: "AppNamedPreviewOnAgentNamedLikePort", pattern: dotPattern, hostname: "preview--8080--workspace--user.apps.example.com"},
102+
{name: "AppNamedPreviewUnderSuffixPattern", pattern: suffixPattern, hostname: "preview--8080--workspace--user--apps.example.com"},
103+
{name: "InvalidPreviewSlug", pattern: dotPattern, hostname: "preview--garbage--agent--workspace--user.apps.example.com"},
104+
{name: "PortWithLeadingZero", pattern: dotPattern, hostname: "preview--08080--agent--workspace--user.apps.example.com"},
105+
{name: "ExtraPart", pattern: dotPattern, hostname: "preview--8080--agent--workspace--user--extra.apps.example.com"},
106+
{name: "PortApp", pattern: dotPattern, hostname: "8080--agent--workspace--user.apps.example.com"},
107+
{name: "OtherHostname", pattern: dotPattern, hostname: "preview--8080--agent--workspace--user.other.example.com"},
108+
} {
109+
t.Run(tc.name, func(t *testing.T) {
110+
t.Parallel()
111+
112+
app, target, ok := appurl.ParsePreviewHostname(tc.pattern, tc.hostname)
113+
require.Equal(t, tc.wantApp != appurl.ApplicationURL{}, ok)
114+
require.Equal(t, tc.wantApp, app)
115+
require.Equal(t, tc.wantTarget, target)
116+
})
117+
}
118+
}

0 commit comments

Comments
 (0)