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
more devurls support stuff, everything should work now
  • Loading branch information
deansheather committed Sep 9, 2022
commit 25d776a2268dd8a777ae13cec4c271d8ad113e7c
2 changes: 1 addition & 1 deletion cli/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,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
78 changes: 50 additions & 28 deletions coderd/workspaceapps.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,21 @@ func (api *API) workspaceAppsProxyPath(rw http.ResponseWriter, r *http.Request)
return
}

// Determine the real path that was hit. The * URL parameter in Chi will not
// include the leading slash if it was present, so we need to add it back.
chiPath := chi.URLParam(r, "*")
basePath := strings.TrimSuffix(r.URL.Path, chiPath)
if strings.HasSuffix(basePath, "/") {
chiPath = "/" + chiPath
}

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

Expand Down Expand Up @@ -80,6 +91,7 @@ func (api *API) handleSubdomainApplications(middlewares ...func(http.Handler) ht
Agent: agent,
AppName: app.AppName,
Port: app.Port,
Path: r.URL.Path,
}, rw, r)
})).ServeHTTP(rw, r.WithContext(ctx))
})
Expand All @@ -94,6 +106,8 @@ type proxyApplication struct {
// Either AppName or Port must be set, but not both.
AppName string
Port uint16
// Path must either be empty or have a leading slash.
Path string
}

func (api *API) proxyWorkspaceApplication(proxyApp proxyApplication, rw http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -134,33 +148,21 @@ func (api *API) proxyWorkspaceApplication(proxyApp proxyApplication, rw http.Res
appURL, err := url.Parse(internalURL)
if err != nil {
httpapi.Write(rw, http.StatusInternalServerError, codersdk.Response{
Message: fmt.Sprintf("App url %q must be a valid url.", internalURL),
Message: fmt.Sprintf("App URL %q is invalid.", internalURL),
Detail: err.Error(),
})
return
}

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)
}
path := chi.URLParam(r, "*")
if !strings.HasSuffix(r.URL.Path, "/") && path == "" {
// Ensure path and query parameter correctness.
if proxyApp.Path == "" {
// Web applications typically request paths relative to the
// root URL. This allows for routing behind a proxy or subpath.
// See https://github.com/coder/code-server/issues/241 for examples.
r.URL.Path += "/"
http.Redirect(rw, r, r.URL.String(), http.StatusTemporaryRedirect)
http.Redirect(rw, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
return
}
if r.URL.RawQuery == "" && appURL.RawQuery != "" {
if proxyApp.Path == "/" && r.URL.RawQuery == "" && appURL.RawQuery != "" {
// If the application defines a default set of query parameters,
// we should always respect them. The reverse proxy will merge
// query parameters for server-side requests, but sometimes
Expand All @@ -170,7 +172,21 @@ func (api *API) proxyWorkspaceApplication(proxyApp proxyApplication, rw http.Res
http.Redirect(rw, r, r.URL.String(), http.StatusTemporaryRedirect)
return
}
r.URL.Path = path

r.URL.Path = proxyApp.Path
appURL.RawQuery = ""

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)
}

conn, release, err := api.workspaceAgentCache.Acquire(r, proxyApp.Agent.ID)
if err != nil {
Expand Down Expand Up @@ -238,17 +254,10 @@ func ParseSubdomainAppURL(hostname string) (ApplicationURL, error) {
}
matchGroup := matches[0]

appName := matchGroup[appURL.SubexpIndex("AppName")]
port, err := strconv.ParseUint(appName, 10, 16)
if err != nil || port == 0 {
port = 0
} else {
appName = ""
}

appName, port := AppNameOrPort(matchGroup[appURL.SubexpIndex("AppName")])
return ApplicationURL{
AppName: appName,
Port: uint16(port),
Port: port,
AgentName: matchGroup[appURL.SubexpIndex("AgentName")],
WorkspaceName: matchGroup[appURL.SubexpIndex("WorkspaceName")],
Username: matchGroup[appURL.SubexpIndex("Username")],
Expand All @@ -270,6 +279,19 @@ func SplitSubdomain(hostname string) (subdomain string, rest string, err error)
return toks[0], toks[1], 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)
}

// 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.
Expand Down
14 changes: 9 additions & 5 deletions scripts/coder-dev.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@ source "${SCRIPT_DIR}/lib.sh"

GOOS="$(go env GOOS)"
GOARCH="$(go env GOARCH)"
CODER_DEV_BIN="build/coder_${GOOS}_${GOARCH}"
RELATIVE_BINARY_PATH="build/coder_${GOOS}_${GOARCH}"

cdroot
mkdir -p ./.coderv2
CODER_DEV_DIR="$(realpath ./.coderv2)"
# To preserve the CWD when running the binary, we need to use pushd and popd to
# get absolute paths to everything.
pushd "$PROJECT_ROOT"
mkdir -p ./.coderv2
CODER_DEV_BIN="$(realpath "$RELATIVE_BINARY_PATH")"
CODER_DEV_DIR="$(realpath ./.coderv2)"
popd

if [[ ! -x "${CODER_DEV_BIN}" ]]; then
echo "Run this command first:"
echo " make $CODER_DEV_BIN"
echo " make $RELATIVE_BINARY_PATH"
exit 1
fi

Expand Down
18 changes: 11 additions & 7 deletions scripts/develop.sh
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,22 @@ CODER_DEV_SHIM="${PROJECT_ROOT}/scripts/coder-dev.sh"
# rather than leaving things in an inconsistent state.
trap 'kill -TERM -$$' ERR
cdroot
"${CODER_DEV_SHIM}" server --address 127.0.0.1:3000 --tunnel || kill -INT -$$ &
"${CODER_DEV_SHIM}" server --address 0.0.0.0:3000 --tunnel || kill -INT -$$ &

echo '== Waiting for Coder to become ready'
timeout 60s bash -c 'until curl -s --fail http://localhost:3000 > /dev/null 2>&1; do sleep 0.5; done'

# Try to create the initial admin user.
"${CODER_DEV_SHIM}" login http://127.0.0.1:3000 --username=admin --email=admin@coder.com --password="${password}" ||
echo 'Failed to create admin user. To troubleshoot, try running this command manually.'
if [ ! -f "${PROJECT_ROOT}/.coderv2/developsh-did-first-setup" ]; then
# Try to create the initial admin user.
"${CODER_DEV_SHIM}" login http://127.0.0.1:3000 --username=admin --email=admin@coder.com --password="${password}" ||
echo 'Failed to create admin user. To troubleshoot, try running this command manually.'

# Try to create a regular user.
"${CODER_DEV_SHIM}" users create --email=member@coder.com --username=member --password="${password}" ||
echo 'Failed to create regular user. To troubleshoot, try running this command manually.'
# Try to create a regular user.
"${CODER_DEV_SHIM}" users create --email=member@coder.com --username=member --password="${password}" ||
echo 'Failed to create regular user. To troubleshoot, try running this command manually.'

touch "${PROJECT_ROOT}/.coderv2/developsh-did-first-setup"
fi

# If we have docker available and the "docker" template doesn't already
# exist, then let's try to create a template!
Expand Down
5 changes: 4 additions & 1 deletion site/src/components/AppLink/AppLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ export const AppLink: FC<PropsWithChildren<AppLinkProps>> = ({
appIcon,
}) => {
const styles = useStyles()
const href = `/@${userName}/${workspaceName}.${agentName}/apps/${encodeURIComponent(appName)}`

// The backend redirects if the trailing slash isn't included, so we add it
// here to avoid extra roundtrips.
const href = `/@${userName}/${workspaceName}.${agentName}/apps/${encodeURIComponent(appName)}/`

return (
<Link
Expand Down
0