Skip to content

feat: Add user roles, but do not yet enforce them #1199

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

Closed
wants to merge 9 commits into from
Closed
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
5 changes: 5 additions & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ func New(options *Options) (http.Handler, func()) {
r.Get("/listen", api.provisionerDaemonsListen)
})
})

r.Route("/users", func(r chi.Router) {
r.Get("/first", api.firstUser)
r.Post("/first", api.postFirstUser)
Expand All @@ -173,6 +174,10 @@ func New(options *Options) (http.Handler, func()) {
r.Use(httpmw.ExtractUserParam(options.Database))
r.Get("/", api.userByName)
r.Put("/profile", api.putUserProfile)
// TODO: @emyrk Might want to move these to a /roles group instead of /user.
// As we include more roles like org roles, it makes less sense to scope these here.
r.Put("/roles", api.putUserRoles)
r.Get("/roles", api.getUserRoles)
r.Get("/organizations", api.organizationsByUser)
r.Post("/organizations", api.postOrganizationsByUser)
r.Post("/keys", api.postAPIKey)
Expand Down
46 changes: 46 additions & 0 deletions coderd/database/databasefake/databasefake.go
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,21 @@ func (q *fakeQuerier) GetOrganizationMemberByUserID(_ context.Context, arg datab
return database.OrganizationMember{}, sql.ErrNoRows
}

func (q *fakeQuerier) GetOrganizationMembershipsByUserID(ctx context.Context, userID uuid.UUID) ([]database.OrganizationMember, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()

var memberships []database.OrganizationMember
for _, organizationMember := range q.organizationMembers {
mem := organizationMember
if mem.UserID != userID {
continue
}
memberships = append(memberships, mem)
}
return memberships, nil
}

func (q *fakeQuerier) GetProvisionerDaemons(_ context.Context) ([]database.ProvisionerDaemon, error) {
q.mutex.RLock()
defer q.mutex.RUnlock()
Expand Down Expand Up @@ -1118,11 +1133,42 @@ func (q *fakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
CreatedAt: arg.CreatedAt,
UpdatedAt: arg.UpdatedAt,
Username: arg.Username,
RbacRoles: arg.RbacRoles,
}
q.users = append(q.users, user)
return user, nil
}

func (q *fakeQuerier) GrantUserRole(ctx context.Context, arg database.GrantUserRoleParams) (database.User, error) {
q.mutex.Lock()
defer q.mutex.Unlock()

for index, user := range q.users {
if user.ID != arg.ID {
continue
}

// Append the new roles
user.RbacRoles = append(user.RbacRoles, arg.GrantedRoles...)
// Remove duplicates and sort
uniqueRoles := make([]string, 0, len(user.RbacRoles))
exist := make(map[string]struct{})
for _, r := range user.RbacRoles {
if _, ok := exist[r]; ok {
continue
}
exist[r] = struct{}{}
uniqueRoles = append(uniqueRoles, r)
}
sort.Strings(uniqueRoles)
user.RbacRoles = uniqueRoles

q.users[index] = user
return user, nil
}
return database.User{}, sql.ErrNoRows
}

func (q *fakeQuerier) UpdateUserProfile(_ context.Context, arg database.UpdateUserProfileParams) (database.User, error) {
q.mutex.Lock()
defer q.mutex.Unlock()
Expand Down
3 changes: 2 additions & 1 deletion coderd/database/dump.sql

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

2 changes: 2 additions & 0 deletions coderd/database/migrations/000007_rbac_user_roles.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ALTER TABLE ONLY workspaces
DROP COLUMN IF EXISTS rbac_roles;
18 changes: 18 additions & 0 deletions coderd/database/migrations/000007_rbac_user_roles.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
ALTER TABLE ONLY users
ADD COLUMN IF NOT EXISTS rbac_roles text[] DEFAULT '{}' NOT NULL;

-- All users are site members. So give them the standard role.
-- Also give them membership to the first org we retrieve. We should only have
-- 1 organization at this point in the product.
UPDATE
users
SET
rbac_roles = ARRAY ['member', 'organization-member:' || (SELECT id FROM organizations LIMIT 1)];

-- Give the first user created the admin role
UPDATE
users
SET
rbac_roles = rbac_roles || ARRAY ['admin']
WHERE
id = (SELECT id FROM users ORDER BY created_at ASC LIMIT 1)
1 change: 1 addition & 0 deletions coderd/database/models.go

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

2 changes: 2 additions & 0 deletions coderd/database/querier.go

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

89 changes: 83 additions & 6 deletions coderd/database/queries.sql.go

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

9 changes: 9 additions & 0 deletions coderd/database/queries/organizationmembers.sql
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ INSERT INTO
)
VALUES
($1, $2, $3, $4, $5) RETURNING *;


-- name: GetOrganizationMembershipsByUserID :many
SELECT
*
FROM
organization_members
WHERE
user_id = $1;
15 changes: 13 additions & 2 deletions coderd/database/queries/users.sql
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,11 @@ INSERT INTO
username,
hashed_password,
created_at,
updated_at
updated_at,
rbac_roles
)
VALUES
($1, $2, $3, $4, $5, $6) RETURNING *;
($1, $2, $3, $4, $5, $6, $7) RETURNING *;

-- name: UpdateUserProfile :one
UPDATE
Expand All @@ -48,6 +49,16 @@ SET
WHERE
id = $1 RETURNING *;

-- name: GrantUserRole :one
UPDATE
users
SET
-- Append new roles and remove duplicates just to keep things clean.
rbac_roles = ARRAY(SELECT DISTINCT UNNEST(rbac_roles || @granted_roles :: text[]))
WHERE
id = @id
RETURNING *;

-- name: GetUsers :many
SELECT
*
Expand Down
17 changes: 17 additions & 0 deletions coderd/rbac/authz.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,23 @@ type authSubject struct {
Roles []Role `json:"roles"`
}

// AuthorizeByRoleName will expand all roleNames into roles before calling Authorize().
// This is the function intended to be used outside this package.
// The role is fetched from the builtin map located in memory.
func (a RegoAuthorizer) AuthorizeByRoleName(ctx context.Context, subjectID string, roleNames []RoleName, action Action, object Object) error {
roles := make([]Role, 0, len(roleNames))
for _, n := range roleNames {
r, err := RoleByName(n)
if err != nil {
return xerrors.Errorf("get role permissions: %w", err)
}
roles = append(roles, r)
}
return a.Authorize(ctx, subjectID, roles, action, object)
}

// Authorize allows passing in custom Roles.
// This is really helpful for unit testing, as we can create custom roles to exercise edge cases.
func (a RegoAuthorizer) Authorize(ctx context.Context, subjectID string, roles []Role, action Action, object Object) error {
input := map[string]interface{}{
"subject": authSubject{
Expand Down
Loading