Thanks to visit codestin.com
Credit goes to github.com

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 all commits
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
2 changes: 1 addition & 1 deletion cli/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func createToken() *cobra.Command {
return xerrors.Errorf("create codersdk client: %w", err)
}

res, err := client.CreateToken(cmd.Context(), codersdk.Me)
res, err := client.CreateToken(cmd.Context(), codersdk.Me, codersdk.CreateTokenRequest{})
if err != nil {
return xerrors.Errorf("create tokens: %w", err)
}
Expand Down
17 changes: 17 additions & 0 deletions coderd/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,23 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
return
}

var createToken codersdk.CreateTokenRequest
if !httpapi.Read(ctx, rw, r, &createToken) {
return
}

scope := database.APIKeyScopeAll
if scope != "" {
scope = database.APIKeyScope(createToken.Scope)
}

// tokens last 100 years
lifeTime := time.Hour * 876000
cookie, err := api.createAPIKey(ctx, createAPIKeyParams{
UserID: user.ID,
LoginType: database.LoginTypeToken,
ExpiresAt: database.Now().Add(lifeTime),
Scope: scope,
LifetimeSeconds: int64(lifeTime.Seconds()),
})
if err != nil {
Expand All @@ -54,6 +65,7 @@ func (api *API) postToken(rw http.ResponseWriter, r *http.Request) {
}

// Creates a new session key, used for logging in via the CLI.
// DEPRECATED: use postToken instead.
func (api *API) postAPIKey(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user := httpmw.UserParam(r)
Expand Down Expand Up @@ -229,6 +241,11 @@ func (api *API) createAPIKey(ctx context.Context, params createAPIKeyParams) (*h
if params.Scope != "" {
scope = params.Scope
}
switch scope {
case database.APIKeyScopeAll, database.APIKeyScopeApplicationConnect:
default:
return nil, xerrors.Errorf("invalid API key scope: %q", scope)
}

key, err := api.Database.InsertAPIKey(ctx, database.InsertAPIKeyParams{
ID: keyID,
Expand Down
73 changes: 52 additions & 21 deletions coderd/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,61 @@ import (

func TestTokens(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
_ = coderdtest.CreateFirstUser(t, client)
keys, err := client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.Empty(t, keys)

res, err := client.CreateToken(ctx, codersdk.Me)
require.NoError(t, err)
require.Greater(t, len(res.Key), 2)
t.Run("CRUD", func(t *testing.T) {
t.Parallel()

keys, err = client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.EqualValues(t, len(keys), 1)
require.Contains(t, res.Key, keys[0].ID)
// expires_at must be greater than 50 years
require.Greater(t, keys[0].ExpiresAt, time.Now().Add(time.Hour*438300))
ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)
keys, err := client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.Empty(t, keys)

err = client.DeleteAPIKey(ctx, codersdk.Me, keys[0].ID)
require.NoError(t, err)
keys, err = client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.Empty(t, keys)
res, err := client.CreateToken(ctx, codersdk.Me, codersdk.CreateTokenRequest{})
require.NoError(t, err)
require.Greater(t, len(res.Key), 2)

keys, err = client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.EqualValues(t, len(keys), 1)
require.Contains(t, res.Key, keys[0].ID)
// expires_at must be greater than 50 years
require.Greater(t, keys[0].ExpiresAt, time.Now().Add(time.Hour*438300))
require.Equal(t, codersdk.APIKeyScopeAll, keys[0].Scope)

// no update

err = client.DeleteAPIKey(ctx, codersdk.Me, keys[0].ID)
require.NoError(t, err)
keys, err = client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.Empty(t, keys)
})

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

ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitLong)
defer cancel()
client := coderdtest.New(t, nil)
_ = coderdtest.CreateFirstUser(t, client)

res, err := client.CreateToken(ctx, codersdk.Me, codersdk.CreateTokenRequest{
Scope: codersdk.APIKeyScopeApplicationConnect,
})
require.NoError(t, err)
require.Greater(t, len(res.Key), 2)

keys, err := client.GetTokens(ctx, codersdk.Me)
require.NoError(t, err)
require.EqualValues(t, len(keys), 1)
require.Contains(t, res.Key, keys[0].ID)
// expires_at must be greater than 50 years
require.Greater(t, keys[0].ExpiresAt, time.Now().Add(time.Hour*438300))
require.Equal(t, keys[0].Scope, codersdk.APIKeyScopeApplicationConnect)
})
}

func TestAPIKey(t *testing.T) {
Expand Down
20 changes: 15 additions & 5 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,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 @@ -214,8 +214,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 @@ -310,7 +320,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 @@ -389,7 +399,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 @@ -2324,6 +2324,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 @@ -2334,6 +2338,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
9 changes: 8 additions & 1 deletion coderd/database/dump.sql

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

5 changes: 5 additions & 0 deletions coderd/database/migrations/000060_app_sharing_level.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- Drop column sharing_level from workspace_apps
ALTER TABLE workspace_apps DROP COLUMN sharing_level;

-- Drop type app_sharing_level
DROP TYPE app_sharing_level;
12 changes: 12 additions & 0 deletions coderd/database/migrations/000060_app_sharing_level.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- Add enum app_sharing_level
CREATE TYPE app_sharing_level AS ENUM (
-- only the workspace owner can access the app
'owner',
-- any authenticated user on the site can access the app
'authenticated',
-- any user can access the app even if they are not authenticated
'public'
);

-- 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;
21 changes: 21 additions & 0 deletions coderd/database/models.go

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

18 changes: 13 additions & 5 deletions coderd/database/queries.sql.go

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

Loading