8000 feat: Add serving applications on subdomains and port-based proxying by Emyrk · Pull Request #3753 · coder/coder · GitHub
[go: up one dir, main page]

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 1 commit
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
Prev Previous commit
Next Next commit
devurls working + tests
  • Loading branch information
deansheather committed Sep 12, 2022
commit f3c664576e7b14ec0b173fed14a3e9f919e668bf
9 changes: 8 additions & 1 deletion coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ import (
)

type Options struct {
AccessURL *url.URL
AWSCertificates awsidentity.Certificates
Authorizer rbac.Authorizer
AzureCertificates x509.VerifyOptions
Expand Down Expand Up @@ -197,13 +198,19 @@ func newWithAPI(t *testing.T, options *Options) (*codersdk.Client, io.Closer, *c
_ = turnServer.Close()
})

accessURL := options.AccessURL
if accessURL == nil {
accessURL, err = url.Parse(srv.URL)
require.NoError(t, err)
}

// We set the handler after server creation for the access URL.
coderAPI := options.APIBuilder(&coderd.Options{
AgentConnectionUpdateFrequency: 150 * time.Millisecond,
// Force a long disconnection timeout to ensure
// agents are not marked as disconnected during slow tests.
AgentInactiveDisconnectTimeout: testutil.WaitShort,
AccessURL: serverURL,
AccessURL: accessURL,
Logger: slogtest.Make(t, nil).Leveled(slog.LevelDebug),
CacheDir: t.TempDir(),
Database: db,
Expand Down
8 changes: 3 additions & 5 deletions coderd/httpmw/logger.go
< 10000 tr data-hunk="dd96477a6185e06bb6c44a4dbdeef66ccfc39aa97dbea3880ad6995eaf405d38" class="show-top-border">
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,13 @@ func Logger(log slog.Logger) func(next http.Handler) http.Handler {
)
}

// We should not log at level ERROR for 5xx status codes because 5xx
// includes proxy errors etc. It also causes slogtest to fail
// instantly without an error message by default.
logLevelFn := httplog.Debug
if sw.Status >= 400 {
logLevelFn = httplog.Warn
}
if sw.Status >= 500 {
// Server errors should be treated as an ERROR
// log level.
logLevelFn = httplog.Error
}

logLevelFn(r.Context(), r.Method)
})
Expand Down
6 changes: 2 additions & 4 deletions coderd/userauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,7 @@ func (api *API) userOAuth2Github(rw http.ResponseWriter, r *http.Request) {
return
}

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

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

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

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

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

httpapi.Write(rw, http.StatusCreated, codersdk.LoginWithPasswordResponse{
SessionToken: cookie.Value,
Expand Down Expand Up @@ -887,9 +886,12 @@ func (api *API) postLogout(rw http.ResponseWriter, r *http.Request) {
Name: codersdk.SessionTokenKey,
Path: "/",
}

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

devurlCookie := api.applicationCookie(cookie)
if devurlCookie != nil {
http.SetCookie(rw, devurlCookie)
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

api.setAuthCookie


// Delete the session token from database.
apiKey := httpmw.APIKey(r)
Expand Down Expand Up @@ -1069,6 +1071,15 @@ func (api *API) createUser(ctx context.Context, store database.Store, req create
})
}

func (api *API) setAuthCookie(rw http.ResponseWriter, cookie *http.Cookie) {
http.SetCookie(rw, cookie)

devurlCookie := api.applicationCookie(cookie)
if devurlCookie != nil {
http.SetCookie(rw, devurlCookie)
}
}

func convertUser(user database.User, organizationIDs []uuid.UUID) codersdk.User {
convertedUser := codersdk.User{
ID: user.ID,
Expand Down
8 changes: 7 additions & 1 deletion coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"testing"
Expand Down Expand Up @@ -261,7 +262,12 @@ func TestPostLogout(t *testing.T) {
t.Run("Logout", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, nil)
accessURL, err := url.Parse("http://somedomain.com")
require.NoError(t, err)

client := coderdtest.New(t, &coderdtest.Options{
AccessURL: accessURL,
})
admin := coderdtest.CreateFirstUser(t, client)

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
Expand Down
73 changes: 52 additions & 21 deletions coderd/workspaceapps.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package coderd

import (
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/url"
Expand Down Expand Up @@ -42,11 +43,12 @@ func (api *API) workspaceAppsProxyPath(rw http.ResponseWriter, r *http.Request)

appName, port := AppNameOrPort(chi.URLParam(r, "workspaceapp"))
api.proxyWorkspaceApplication(proxyApplication{
Workspace: workspace,
Agent: agent,
AppName: appName,
Port: port,
Path: chiPath,
Workspace: workspace,
Agent: agent,
AppName: appName,
Port: port,
Path: chiPath,
DashboardOnError: true,
}, rw, r)
}

Expand Down Expand Up @@ -87,11 +89,12 @@ func (api *API) handleSubdomainApplications(middlewares ...func(http.Handler) ht
agent := httpmw.WorkspaceAgentParam(r)

api.proxyWorkspaceApplication(proxyApplication{
Workspace: workspace,
Agent: agent,
AppName: app.AppName,
Port: app.Port,
Path: r.URL.Path,
Workspace: workspace,
Agent: agent,
AppName: app.AppName,
Port: app.Port,
Path: r.URL.Path,
DashboardOnError: false,
}, rw, r)
})).ServeHTTP(rw, r.WithContext(ctx))
})
Expand All @@ -108,6 +111,11 @@ type proxyApplication struct {
Port uint16
// Path must either be empty or have a leading slash.
Path string

// DashboardOnError determines whether or not the dashboard should be
// rendered on error. This should be set for proxy path URLs but not
// hostname based URLs.
DashboardOnError bool
}

func (api *API) proxyWorkspaceApplication(proxyApp proxyApplication, rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -178,14 +186,21 @@ func (api *API) proxyWorkspaceApplication(proxyApp proxyApplication, rw http.Res

proxy := httputil.NewSingleHostReverseProxy(appURL)
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
// This is a browser-facing route so JSON responses are not viable here.
// To pass friendly errors to the frontend, special meta tags are overridden
// in the index.html with the content passed here.
r = r.WithContext(site.WithAPIResponse(r.Context(), site.APIResponse{
StatusCode: http.StatusBadGateway,
Message: err.Error(),
}))
api.siteHandler.ServeHTTP(w, r)
if proxyApp.DashboardOnError {
// To pass friendly errors to the frontend, special meta tags are
// overridden in the index.html with the content passed here.
r = r.WithContext(site.WithAPIResponse(r.Context(), site.APIResponse{
StatusCode: http.StatusBadGateway,
Message: err.Error(),
}))
api.siteHandler.ServeHTTP(w, r)
return
}

httpapi.Write(w, http.StatusBadGateway, codersdk.Response{
Message: "Failed to proxy request to application.",
Detail: err.Error(),
})
}

conn, release, err := api.workspaceAgentCache.Acquire(r, proxyApp.Agent.ID)
Expand Down Expand Up @@ -234,6 +249,16 @@ type ApplicationURL struct {
BaseHostname string
}

// String returns the application URL hostname without scheme.
func (a ApplicationURL) String() string {
appNameOrPort := a.AppName
if a.Port != 0 {
appNameOrPort = strconv.Itoa(int(a.Port))
}

return fmt.Sprintf("%s--%s--%s--%s.%s", appNameOrPort, a.AgentName, a.WorkspaceName, a.Username, a.BaseHostname)
}

// ParseSubdomainAppURL parses an application from the subdomain of r's Host
// header. If the subdomain is not a valid application URL hostname, returns a
// non-nil error.
Expand Down Expand Up @@ -297,11 +322,17 @@ func AppNameOrPort(val string) (string, uint16) {
// 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.
//
// Returns nil if the access URL isn't a hostname.
func (api *API) applicationCookie(authCookie *http.Cookie) *http.Cookie {
if net.ParseIP(api.AccessURL.Hostname()) != nil {
return nil
}

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.
// 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()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is interesting... I didn't know we could apply to subdomains without requiring an authentication redirect, this is awesome.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We probably won't be doing this soon as we'll be implementing proper devurl auth similarly to v1

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@kylecarbs this is a stop gap. It will not work on apps hosted on another domain.

Also currently using the same full auth token. We should used scoped auth tokens.

return &appCookie
}
Loading
0