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
Emy 8000 rk 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
kyle comments
  • Loading branch information
deansheather committed Sep 12, 2022
commit 58653d4aa4963b848b133af47f26fc4e22a5feed
11 changes: 10 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,18 @@ func New(options *Options) *API {
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, false),
httpmw.ExtractAPIKey(options.Database, oauthConfigs, true),
httpmw.ExtractUserParam(api.Database),
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
),
Expand Down
13 changes: 5 additions & 8 deletions coderd/coderdtest/coderdtest.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ import (
)

type Options struct {
AccessURL *url.URL
AWSCertificates awsidentity.Certificates
Authorizer rbac.Authorizer
AzureCertificates x509.VerifyOptions
Expand Down Expand Up @@ -183,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 All @@ -205,19 +208,13 @@ func newWithAPI(t *testing.T, options *Options) (*codersdk.Client, io.Closer, *c
features.Auditor = options.Auditor
}

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: accessURL,
AccessURL: serverURL,
Logger: slogtest.Make(t, nil).Leveled(slog.LevelDebug),
CacheDir: t.TempDir(),
Database: db,
Expand Down
50 changes: 46 additions & 4 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"

Expand Down Expand Up @@ -58,6 +59,24 @@ const (
internalErrorMessage string = "An internal error occurred. Please try again or contact the system administrator."
)

type loginURLKey struct{}

func getLoginURL(r *http.Request) (*url.URL, bool) {
val, ok := r.Context().Value(loginURLKey{}).(*url.URL)
return val, ok
}

// UseLoginURL sets the login URL to use for the request for handlers like
// ExtractAPIKey.
func UseLoginURL(loginURL *url.URL) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
ctx := context.WithValue(r.Context(), loginURLKey{}, loginURL)
next.ServeHTTP(rw, r.WithContext(ctx))
})
}
}

// ExtractAPIKey requires authentication using a valid API key.
// It handles extending an API key if it comes close to expiry,
// updating the last used time in the database.
Expand All @@ -70,14 +89,37 @@ func ExtractAPIKey(db database.Store, oauth *OAuth2Configs, redirectToLogin bool
// pages like workspace applications.
write := func(code int, response codersdk.Response) {
if redirectToLogin {
var (
u = &url.URL{
Path: "/login",
}
redirectURL = func() string {
path := r.URL.Path
if r.URL.RawQuery != "" {
path += "?" + r.URL.RawQuery
}
return path
}()
)
if loginURL, ok := getLoginURL(r); ok {
u = loginURL
// Don't redirect to the current page, as it may be on
// a different domain and we have issues determining the
// scheme to redirect to.
redirectURL = ""
}

q := r.URL.Query()
q.Add("message", response.Message)
q.Add("redirect", r.URL.Path+"?"+r.URL.RawQuery)
r.URL.RawQuery = q.Encode()
r.URL.Path = "/login"
http.Redirect(rw, r, r.URL.String(), http.StatusTemporaryRedirect)
if redirectURL != "" {
q.Add("redirect", redirectURL)
}
u.RawQuery = q.Encode()

http.Redirect(rw, r, u.String(), http.StatusTemporaryRedirect)
return
}

httpapi.Write(rw, code, response)
}

Expand Down
8 changes: 1 addition & 7 deletions coderd/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"testing"
Expand Down Expand Up @@ -265,12 +264,7 @@ func TestPostLogout(t *testing.T) {
t.Run("Logout", func(t *testing.T) {
t.Parallel()

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

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

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
Expand Down
25 changes: 18 additions & 7 deletions coderd/workspaceapps_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func TestWorkspaceAppsProxyPath(t *testing.T) {
t.Parallel()
client, orgID, workspace, port := setupProxyTest(t)

t.Run("RedirectsWithoutAuth", func(t *testing.T) {
t.Run("LoginWithoutAuth", func(t *testing.T) {
t.Parallel()
client := codersdk.New(client.URL)
client.HTTPClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
Expand All @@ -141,13 +141,14 @@ func TestWorkspaceAppsProxyPath(t *testing.T) {
resp, err := client.Request(ctx, http.MethodGet, "/@me/"+workspace.Name+"/apps/example", nil)
require.NoError(t, err)
defer resp.Body.Close()
location, err := resp.Location()

loc, err := resp.Location()
require.NoError(t, err)
require.Equal(t, "/login", location.Path)
require.Equal(t, http.StatusTemporaryRedirect, resp.StatusCode)
require.True(t, loc.Query().Has("message"))
require.True(t, loc.Query().Has("redirect"))
})

t.Run("NoAccessShould401", func(t *testing.T) {
t.Run("NoAccessShould404", func(t *testing.T) {
t.Parallel()

userClient := coderdtest.CreateAnotherUser(t, client, orgID, rbac.RoleMember())
Expand Down Expand Up @@ -284,7 +285,7 @@ func TestWorkspaceAppsProxySubdomain(t *testing.T) {
}).String()
}

t.Run("NoAuthShould401", func(t *testing.T) {
t.Run("LoginWithoutAuth", func(t *testing.T) {
t.Parallel()
unauthedClient := codersdk.New(client.URL)
unauthedClient.HTTPClient.CheckRedirect = client.HTTPClient.CheckRedirect
Expand All @@ -296,7 +297,17 @@ func TestWorkspaceAppsProxySubdomain(t *testing.T) {
resp, err := unauthedClient.Request(ctx, http.MethodGet, proxyURL(t, proxyTestAppName), nil)
require.NoError(t, err)
defer resp.Body.Close()
require.Equal(t, http.StatusUnauthorized, resp.StatusCode)
require.Equal(t, http.StatusTemporaryRedirect, resp.StatusCode)

loc, err := resp.Location()
require.NoError(t, err)
require.True(t, loc.Query().Has("message"))
require.False(t, loc.Query().Has("redirect"))

expectedURL := *client.URL
expectedURL.Path = "/login"
loc.RawQuery = ""
require.Equal(t, &expectedURL, loc)
})

t.Run("NoAccessShould401", func(t *testing.T) {
Expand Down
0