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 all 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
2 changes: 1 addition & 1 deletion cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ func Server(newAPI func(*coderd.Options) *coderd.API) *cobra.Command {

cmd.Println("Waiting for WebSocket connections to close...")
_ = coderAPI.Close()
cmd.Println("Done wainting for WebSocket connections")
cmd.Println("Done waiting for WebSocket connections")

// Close tunnel after we no longer have in-flight connections.
if tunnel {
Expand Down
20 changes: 20 additions & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,26 @@ func New(options *Options) *API {
httpmw.Recover(api.Logger),
httpmw.Logger(api.Logger),
httpmw.Prometheus(options.PrometheusRegistry),
// handleSubdomainApplications checks if the first subdomain is a valid
// app URL. If it is, it will serve that application.
api.handleSubdomainApplications(
// Middleware to impose on the served application.
httpmw.RateLimitPerMinute(options.APIRateLimit),
httpmw.UseLoginURL(func() *url.URL {
if options.AccessURL == nil {
return nil
}

u := *options.AccessURL
u.Path = "/login"
return &u
}()),
// This should extract the application specific API key when we
// implement a scoped token.
httpmw.ExtractAPIKey(options.Database, oauthConfigs, true),
httpmw.ExtractUserParam(api.Database),
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
),
// Build-Version is helpful for debugging.
func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
4 changes: 4 additions & 0 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,12 @@ func newWithAPI(t *testing.T, options *Options) (*codersdk.Client, io.Closer, *c
srv.Start()
t.Cleanup(srv.Close)

tcpAddr, ok := srv.Listener.Addr().(*net.TCPAddr)
require.True(t, ok)

serverURL, err := url.Parse(srv.URL)
require.NoError(t, err)
serverURL.Host = fmt.Sprintf("localhost:%d", tcpAddr.Port)

derpPort, err := strconv.Atoi(serverURL.Port())
require.NoError(t, err)
Expand Down
100 changes: 100 additions & 0 deletions coderd/httpapi/url.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package httpapi

import (
"fmt"
"regexp"
"strconv"
"strings"

"golang.org/x/xerrors"
)

var (
// Remove the "starts with" and "ends with" regex components.
nameRegex = strings.Trim(UsernameValidRegex.String(), "^$")
appURL = regexp.MustCompile(fmt.Sprintf(
// {PORT/APP_NAME}--{AGENT_NAME}--{WORKSPACE_NAME}--{USERNAME}
`^(?P<AppName>%[1]s)--(?P<AgentName>%[1]s)--(?P<WorkspaceName>%[1]s)--(?P<Username>%[1]s)$`,
nameRegex))
)

// SplitSubdomain splits a subdomain from the rest of the hostname. 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, rest string, err error) {
toks := strings.SplitN(hostname, ".", 2)
if len(toks) < 2 {
return "", "", xerrors.New("no subdomain")
}

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

// ApplicationURL is a parsed application URL hostname.
type ApplicationURL struct {
// Only one of AppName or Port will be set.
AppName string
Port uint16
AgentName string
WorkspaceName string
Username string
// BaseHostname is the rest of the hostname minus the application URL part
// and the first dot.
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 ApplicationURL from the given hostname. If
// the subdomain is not a valid application URL hostname, returns a non-nil
// error.
//
// Subdomains should be in the form:
//
// {PORT/APP_NAME}--{AGENT_NAME}--{WORKSPACE_NAME}--{USERNAME}
// (eg. http://8080--main--dev--dean.hi.c8s.io)
func ParseSubdomainAppURL(hostname string) (ApplicationURL, error) {
subdomain, rest, err := SplitSubdomain(hostname)
if err != nil {
return ApplicationURL{}, xerrors.Errorf("split host domain %q: %w", hostname, err)
}

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

appName, port := AppNameOrPort(matchGroup[appURL.SubexpIndex("AppName")])
return ApplicationURL{
AppName: appName,
Port: port,
AgentName: matchGroup[appURL.SubexpIndex("AgentName")],
WorkspaceName: matchGroup[appURL.SubexpIndex("WorkspaceName")],
Username: matchGroup[appURL.SubexpIndex("Username")],
BaseHostname: rest,
}, nil
}

// AppNameOrPort takes a string and returns either the input string or a port
// number.
func AppNameOrPort(val string) (string, uint16) {
port, err := strconv.ParseUint(val, 10, 16)
if err != nil || port == 0 {
port = 0
} else {
val = ""
}

return val, uint16(port)
}
Loading