Skip to content

feat: Add serving applications on subdomains and port-based proxying #3753

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Sep 13, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
35ee5d6
chore: Add subdomain parser for applications
Emyrk Aug 26, 2022
a7e5bd6
Add basic router for applications using same codepath
Emyrk Aug 26, 2022
03c697d
Merge remote-tracking branch 'origin/main' into stevenmasley/unnamed-…
Emyrk Aug 29, 2022
3e30cdd
Handle ports as app names
Emyrk Aug 29, 2022
8397306
Add comments
Emyrk Aug 30, 2022
f994ec3
Cleanup
Emyrk Aug 30, 2022
fda80b8
Linting
Emyrk Aug 30, 2022
6b09a0f
Push cookies to subdomains on the access url as well
Emyrk Aug 30, 2022
634cd2e
Fix unit test
Emyrk Aug 30, 2022
82df6f1
Fix comment
Emyrk Aug 30, 2022
49084e2
Reuse regex from validation
Emyrk Aug 30, 2022
4696bf9
Export valid name regex
Emyrk Aug 31, 2022
b5d1f6a
Move to workspaceapps.go
Emyrk Aug 31, 2022
0578588
Change app url name order
Emyrk Aug 31, 2022
77d3452
Import order
Emyrk Aug 31, 2022
931ecb2
Merge remote-tracking branch 'origin/main' into stevenmasley/unnamed-…
Emyrk Aug 31, 2022
54f2bdd
Deleted duplicate code
Emyrk Aug 31, 2022
f1d7670
Rename subdomain handler
Emyrk Aug 31, 2022
46e0900
Merge branch 'main' into stevenmasley/unnamed-apps
deansheather Sep 8, 2022
56c1d00
Change the devurl syntax to app--agent--workspace--user
deansheather Sep 8, 2022
25d776a
more devurls support stuff, everything should work now
deansheather Sep 9, 2022
f3c6645
devurls working + tests
deansheather Sep 12, 2022
75c4713
Merge branch 'main' into stevenmasley/unnamed-apps
deansheather Sep 12, 2022
1f8a1f0
Move stuff to httpapi
deansheather Sep 12, 2022
2c7bcc1
fixup! Move stuff to httpapi
deansheather Sep 12, 2022
dc0d348
Merge branch 'main' into stevenmasley/unnamed-apps
deansheather Sep 12, 2022
58653d4
kyle comments
deansheather Sep 12, 2022
5321bef
fixup! kyle comments
deansheather Sep 13, 2022
ad53b42
fixup! kyle comments
deansheather Sep 13, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,17 @@ func New(options *Options) *API {
})
},
httpmw.Prometheus(options.PrometheusRegistry),
// handleSubdomain checks if the first subdomain is a valid app url.
// If it is, it will serve that application.
api.handleSubdomain(
// Middleware to impose on the served application.
httpmw.RateLimitPerMinute(options.APIRateLimit),
// This should extract the application specific API key when we
// implement a scoped token.
httpmw.ExtractAPIKey(options.Database, oauthConfigs, false),
httpmw.ExtractUserParam(api.Database),
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
),
)

apps := func(r chi.Router) {
Expand Down
152 changes: 152 additions & 0 deletions coderd/subdomain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package coderd

import (
"fmt"
"net/http"
"regexp"
"strings"

"github.com/coder/coder/coderd/httpmw"

"github.com/go-chi/chi/v5"

"golang.org/x/xerrors"
)

const (
// XForwardedHostHeader is a header used by proxies to indicate the
// original host of the request.
XForwardedHostHeader = "X-Forwarded-Host"
)

// ApplicationURL is a parsed application url into it's components
type ApplicationURL struct {
AppName string
WorkspaceName string
Agent string
Username string
Path string
Domain string
}

func (api *API) handleSubdomain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
app, err := ParseSubdomainAppURL(r)

if err != nil {
// Subdomain is not a valid application url. Pass through.
// TODO: @emyrk we should probably catch invalid subdomains. Meaning
// an invalid application should not route to the coderd.
// To do this we would need to know the list of valid access urls
// though?
next.ServeHTTP(rw, r)
return
}

workspaceAgentKey := app.WorkspaceName
if app.Agent != "" {
workspaceAgentKey += "." + app.Agent
}
chiCtx := chi.RouteContext(ctx)
chiCtx.URLParams.Add("workspace_and_agent", workspaceAgentKey)
chiCtx.URLParams.Add("user", app.Username)

// Use the passed in app middlewares before passing to the proxy app.
mws := chi.Middlewares(middlewares)
mws.Handler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
workspace := httpmw.WorkspaceParam(r)
agent := httpmw.WorkspaceAgentParam(r)

api.proxyWorkspaceApplication(proxyApplication{
Workspace: workspace,
Agent: agent,
AppName: app.AppName,
}, rw, r)
})).ServeHTTP(rw, r.WithContext(ctx))
})
}
}

var (
nameRegex = `[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*`
appURL = regexp.MustCompile(fmt.Sprintf(
// {USERNAME}--{WORKSPACE_NAME}}--{{AGENT_NAME}}--{{PORT}}
`^(?P<UserName>%[1]s)--(?P<WorkspaceName>%[1]s)(--(?P<AgentName>%[1]s))?--(?P<AppName>%[1]s)$`,
nameRegex))
)

// ParseSubdomainAppURL parses an application from the subdomain of r's Host header.
// If the application string is not valid, returns a non-nil error.
// 1) {USERNAME}--{WORKSPACE_NAME}}--{{AGENT_NAME}}--{{PORT/AppName}}
// (eg. http://admin--myenv--main--8080.cdrdeploy.c8s.io)
func ParseSubdomainAppURL(r *http.Request) (ApplicationURL, error) {
host := RequestHost(r)
if host == "" {
return ApplicationURL{}, xerrors.Errorf("no host header")
}

subdomain, domain, err := SplitSubdomain(host)
if err != nil {
return ApplicationURL{}, xerrors.Errorf("split host domain: %w", err)
}

matches := appURL.FindAllStringSubmatch(subdomain, -1)
if len(matches) == 0 {
return ApplicationURL{}, xerrors.Errorf("invalid application url format: %q", subdomain)
}

if len(matches) > 1 {
return ApplicationURL{}, xerrors.Errorf("multiple matches (%d) for application url: %q", len(matches), subdomain)
}
matchGroup := matches[0]

return ApplicationURL{
AppName: matchGroup[appURL.SubexpIndex("AppName")],
WorkspaceName: matchGroup[appURL.SubexpIndex("WorkspaceName")],
Agent: matchGroup[appURL.SubexpIndex("AgentName")],
Username: matchGroup[appURL.SubexpIndex("UserName")],
Path: r.URL.Path,
Domain: domain,
}, nil
}

// RequestHost returns the name of the host from the request. It prioritizes
// 'X-Forwarded-Host' over r.Host since most requests are being proxied.
func RequestHost(r *http.Request) string {
host := r.Header.Get(XForwardedHostHeader)
if host != "" {
return host
}

return r.Host
}

// SplitSubdomain splits a subdomain from a domain. E.g.:
// - "foo.bar.com" becomes "foo", "bar.com"
// - "foo.bar.baz.com" becomes "foo", "bar.baz.com"
//
// An error is returned if the string doesn't contain a period.
func SplitSubdomain(hostname string) (subdomain string, domain string, err error) {
toks := strings.SplitN(hostname, ".", 2)
if len(toks) < 2 {
return "", "", xerrors.Errorf("no domain")
}

return toks[0], toks[1], nil
}

// applicationCookie is a helper function to copy the auth cookie to also
// support subdomains. Until we support creating authentication cookies that can
// only do application authentication, we will just reuse the original token.
// This code should be temporary and be replaced with something that creates
// a unique session_token.
func (api *API) applicationCookie(authCookie *http.Cookie) *http.Cookie {
appCookie := *authCookie
// We only support setting this cookie on the access url subdomains.
// This is to ensure we don't accidentally leak the auth cookie to subdomains
// on another hostname.
appCookie.Domain = "." + api.AccessURL.Hostname()
return &appCookie
}
116 changes: 116 additions & 0 deletions coderd/subdomain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package coderd_test

import (
"net/http/httptest"
"testing"

"github.com/stretchr/testify/require"

"github.com/coder/coder/coderd"
)

func TestParseSubdomainAppURL(t *testing.T) {
t.Parallel()
testCases := []struct {
Name string
URL string
Expected coderd.ApplicationURL
ExpectedError string
}{
{
Name: "Empty",
URL: "https://example.com",
Expected: coderd.ApplicationURL{},
ExpectedError: "invalid application url format",
},
{
Name: "Workspace.Agent+App",
URL: "https://workspace.agent--app.coder.com",
Expected: coderd.ApplicationURL{},
ExpectedError: "invalid application url format",
},
{
Name: "Workspace+App",
URL: "https://workspace--app.coder.com",
Expected: coderd.ApplicationURL{},
ExpectedError: "invalid application url format",
},
// Correct
{
Name: "User+Workspace+App",
URL: "https://user--workspace--app.coder.com",
Expected: coderd.ApplicationURL{
AppName: "app",
WorkspaceName: "workspace",
Agent: "",
Username: "user",
Path: "",
Domain: "coder.com",
},
},
{
Name: "User+Workspace+Port",
URL: "https://user--workspace--8080.coder.com",
Expected: coderd.ApplicationURL{
AppName: "8080",
WorkspaceName: "workspace",
Agent: "",
Username: "user",
Path: "",
Domain: "coder.com",
},
},
{
Name: "User+Workspace.Agent+App",
URL: "https://user--workspace--agent--app.coder.com",
Expected: coderd.ApplicationURL{
AppName: "app",
WorkspaceName: "workspace",
Agent: "agent",
Username: "user",
Path: "",
Domain: "coder.com",
},
},
{
Name: "User+Workspace.Agent+Port",
URL: "https://user--workspace--agent--8080.coder.com",
Expected: coderd.ApplicationURL{
AppName: "8080",
WorkspaceName: "workspace",
Agent: "agent",
Username: "user",
Path: "",
Domain: "coder.com",
},
},
{
Name: "HyphenatedNames",
URL: "https://admin-user--workspace-thing--agent-thing--app-name.coder.com",
Expected: coderd.ApplicationURL{
AppName: "app-name",
WorkspaceName: "workspace-thing",
Agent: "agent-thing",
Username: "admin-user",
Path: "",
Domain: "coder.com",
},
},
}

for _, c := range testCases {
c := c
t.Run(c.Name, func(t *testing.T) {
t.Parallel()
r := httptest.NewRequest("GET", c.URL, nil)

app, err := coderd.ParseSubdomainAppURL(r)
if c.ExpectedError == "" {
require.NoError(t, err)
require.Equal(t, c.Expected, app, "expected app")
} else {
require.ErrorContains(t, err, c.ExpectedError, "expected error")
}
})
}
}
2 changes: 2 additions & 0 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
}

http.SetCookie(rw, cookie)
http.SetCookie(rw, api.applicationCookie(cookie))

redirect := state.Redirect
if redirect == "" {
Expand Down Expand Up @@ -274,6 +275,7 @@ func (api *API) userOIDC(rw http.ResponseWriter, r *http.Request) {
}

http.SetCookie(rw, cookie)
http.SetCookie(rw, api.applicationCookie(cookie))

redirect := state.Redirect
if redirect == "" {
Expand Down
2 changes: 2 additions & 0 deletions coderd/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,7 @@ func (api *API) postLogin(rw http.ResponseWriter, r *http.Request) {
}

http.SetCookie(rw, cookie)
http.SetCookie(rw, api.applicationCookie(cookie))

httpapi.Write(rw, http.StatusCreated, codersdk.LoginWithPasswordResponse{
SessionToken: cookie.Value,
Expand Down Expand Up @@ -874,6 +875,7 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) {
}

http.SetCookie(rw, cookie)
http.SetCookie(rw, api.applicationCookie(cookie))

// Delete the session token from database.
apiKey := httpmw.APIKey(r)
Expand Down
5 changes: 3 additions & 2 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,10 @@ func TestPostLogout(t *testing.T) {
require.Equal(t, http.StatusOK, res.StatusCode)

cookies := res.Cookies()
require.Len(t, cookies, 1, "Exactly one cookie should be returned")
require.Len(t, cookies, 2, "Exactly two cookies should be returned")

require.Equal(t, codersdk.SessionTokenKey, cookies[0].Name, "Cookie should be the auth cookie")
require.Equal(t, codersdk.SessionTokenKey, cookies[0].Name, "Cookie should be the auth & app cookie")
require.Equal(t, codersdk.SessionTokenKey, cookies[1].Name, "Cookie should be the auth & app cookie")
require.Equal(t, -1, cookies[0].MaxAge, "Cookie should be set to delete")

_, err = client.GetAPIKey(ctx, admin.UserID.String(), keyID)
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy