8000 feat: app sharing (now open source!) by deansheather · Pull Request #4378 · coder/coder · GitHub
[go: up one dir, main page]

Skip to content

feat: app sharing (now open source!) #4378

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 16 commits into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
feat: app sharing pt.3
  • Loading branch information
deansheather committed Oct 6, 2022
commit d7403ec8ea1cc148c09e40206dad5dcd7a6564e9
20 changes: 15 additions & 5 deletions coderd/coderd.go
8000
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ func New(options *Options) *API {
RedirectToLogin: false,
Optional: true,
}),
httpmw.ExtractUserParam(api.Database),
httpmw.ExtractUserParam(api.Database, false),
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
),
// Build-Version is helpful for debugging.
Expand All @@ -221,8 +221,18 @@ func New(options *Options) *API {
r.Use(
tracing.Middleware(api.TracerProvider),
httpmw.RateLimitPerMinute(options.APIRateLimit),
apiKeyMiddlewareRedirect,
httpmw.ExtractUserParam(api.Database),
httpmw.ExtractAPIKey(httpmw.ExtractAPIKeyConfig{
DB: options.Database,
OAuth2Configs: oauthConfigs,
// Optional is true to allow for public apps. If an
// authorization check fails and the user is not authenticated,
// they will be redirected to the login page by the app handler.
RedirectToLogin: false,
Optional: true,
}),
// Redirect to the login page if the user tries to open an app with
// "me" as the username and they are not logged in.
httpmw.ExtractUserParam(api.Database, true),
// Extracts the <workspace.agent> from the url
httpmw.ExtractWorkspaceAndAgentParam(api.Database),
)
Expand Down Expand Up @@ -312,7 +322,7 @@ func New(options *Options) *API {
r.Get("/roles", api.assignableOrgRoles)
r.Route("/{user}", func(r chi.Router) {
r.Use(
httpmw.ExtractUserParam(options.Database),
httpmw.ExtractUserParam(options.Database, false),
httpmw.ExtractOrganizationMemberParam(options.Database),
)
r.Put("/roles", api.putMemberRoles)
Expand Down Expand Up @@ -391,7 +401,7 @@ func New(options *Options) *API {
r.Get("/", api.assignableSiteRoles)
})
r.Route("/{user}", func(r chi.Router) {
r.Use(httpmw.ExtractUserParam(options.Database))
r.Use(httpmw.ExtractUserParam(options.Database, false))
r.Delete("/", api.deleteUser)
r.Get("/", api.userByName)
r.Put("/profile", api.putUserProfile)
Expand Down
5 changes: 5 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -2060,6 +2060,10 @@ func (q *fakeQuerier) InsertWorkspaceApp(_ context.Context, arg database.InsertW
q.mutex.Lock()
defer q.mutex.Unlock()

if arg.SharingLevel == "" {
arg.SharingLevel = database.AppSharingLevelOwner
}

// nolint:gosimple
workspaceApp := database.WorkspaceApp{
ID: arg.ID,
Expand All @@ -2070,6 +2074,7 @@ func (q *fakeQuerier) InsertWorkspaceApp(_ context.Context, arg database.InsertW
Command: arg.Command,
Url: arg.Url,
Subdomain: arg.Subdomain,
SharingLevel: arg.SharingLevel,
HealthcheckUrl: arg.HealthcheckUrl,
HealthcheckInterval: arg.HealthcheckInterval,
HealthcheckThreshold: arg.HealthcheckThreshold,
Expand Down
4 changes: 2 additions & 2 deletions coderd/database/dump.sql

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
-- Add enum app_share_level
CREATE TYPE app_share_level AS ENUM (
-- Add enum app_sharing_level
CREATE TYPE app_sharing_level AS ENUM (
-- only the workspace owner can access the app
'owner',
-- the workspace owner and other users that can read the workspace template
Expand All @@ -11,5 +11,5 @@ CREATE TYPE app_share_level AS ENUM (
'public'
);

-- Add share_level column to workspace_apps table
ALTER TABLE workspace_apps ADD COLUMN share_level app_share_level NOT NULL DEFAULT 'owner'::app_share_level;
-- Add sharing_level column to workspace_apps table
ALTER TABLE workspace_apps ADD COLUMN sharing_level app_sharing_level NOT NULL DEFAULT 'owner'::app_sharing_level;
20 changes: 10 additions & 10 deletions coderd/database/models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 13 additions & 10 deletions coderd/database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion coderd/database/queries/workspaceapps.sql
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ INSERT INTO
command,
url,
subdomain,
sharing_level,
healthcheck_url,
healthcheck_interval,
healthcheck_threshold,
health
)
VALUES
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING *;
($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) RETURNING *;

-- name: UpdateWorkspaceAppHealthByID :exec
UPDATE
Expand Down
51 changes: 29 additions & 22 deletions coderd/httpmw/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ type OAuth2Configs struct {
}

const (
signedOutErrorMessage string = "You are signed out or your session has expired. Please sign in again to continue."
internalErrorMessage string = "An internal error occurred. Please try again or contact the system administrator."
SignedOutErrorMessage = "You are signed out or your session has expired. Please sign in again to continue."
internalErrorMessage = "An internal error occurred. Please try again or contact the system administrator."
)

type ExtractAPIKeyConfig struct {
Expand Down Expand Up @@ -118,21 +118,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
// like workspace applications.
write := func(code int, response codersdk.Response) {
if cfg.RedirectToLogin {
path := r.URL.Path
if r.URL.RawQuery != "" {
path += "?" + r.URL.RawQuery
}

q := url.Values{}
q.Add("message", response.Message)
q.Add("redirect", path)

u := &url.URL{
Path: "/login",
RawQuery: q.Encode(),
}

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

Expand All @@ -156,7 +142,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
token := apiTokenFromRequest(r)
if token == "" {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: signedOutErrorMessage,
Message: SignedOutErrorMessage,
Detail: fmt.Sprintf("Cookie %q or query parameter must be provided.", codersdk.SessionTokenKey),
})
return
Expand All @@ -165,7 +151,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
keyID, keySecret, err := SplitAPIToken(token)
if err != nil {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: signedOutErrorMessage,
Message: SignedOutErrorMessage,
Detail: "Invalid API key format: " + err.Error(),
})
return
Expand All @@ -175,7 +161,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: signedOutErrorMessage,
Message: SignedOutErrorMessage,
Detail: "API key is invalid.",
})
return
Expand All @@ -191,7 +177,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
hashedSecret := sha256.Sum256([]byte(keySecret))
if subtle.ConstantTimeCompare(key.HashedSecret, hashedSecret[:]) != 1 {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: signedOutErrorMessage,
Message: SignedOutErrorMessage,
Detail: "API key secret is invalid.",
})
return
Expand Down Expand Up @@ -254,7 +240,7 @@ func ExtractAPIKey(cfg ExtractAPIKeyConfig) func(http.Handler) http.Handler {
// Checking if the key is expired.
if key.ExpiresAt.Before(now) {
optionalWrite(http.StatusUnauthorized, codersdk.Response{
Message: signedOutErrorMessage,
Message: SignedOutErrorMessage,
Detail: fmt.Sprintf("API key expired at %q.", key.ExpiresAt.String()),
})
return
Expand Down Expand Up @@ -420,3 +406,24 @@ func SplitAPIToken(token string) (id string, secret string, err error) {

return keyID, keySecret, nil
}

// RedirectToLogin redirects the user to the login page with the `message` and
// `redirect` query parameters set.
func RedirectToLogin(rw http.ResponseWriter, r *http.Request, message string) {
path := r.URL.Path
if r.URL.RawQuery != "" {
path += "?" + r.URL.RawQuery
}

q := url.Values{}
q.Add("message", message)
q.Add("redirect", path)

u := &url.URL{
Path: "/login",
RawQuery: q.Encode(),
}

http.Redirect(rw, r, u.String(), http.StatusTemporaryRedirect)
return
}
4 changes: 2 additions & 2 deletions coderd/httpmw/organizationparam_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func TestOrganizationParam(t *testing.T) {
DB: db,
RedirectToLogin: false,
}),
httpmw.ExtractUserParam(db),
httpmw.ExtractUserParam(db, false),
httpmw.ExtractOrganizationParam(db),
httpmw.ExtractOrganizationMemberParam(db),
)
Expand Down Expand Up @@ -189,7 +189,7 @@ func TestOrganizationParam(t *testing.T) {
RedirectToLogin: false,
}),
httpmw.ExtractOrganizationParam(db),
httpmw.ExtractUserParam(db),
httpmw.ExtractUserParam(db, false),
httpmw.ExtractOrganizationMemberParam(db),
)
rtr.Get("/", func(rw http.ResponseWriter, r *http.Request) {
Expand Down
Loading
0