Skip to content

Commit 8b9e3bc

Browse files
committed
Add fake for GrantRoles
1 parent baf4843 commit 8b9e3bc

File tree

6 files changed

+150
-91
lines changed

6 files changed

+150
-91
lines changed

coderd/database/databasefake/databasefake.go

+30
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,36 @@ func (q *fakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
11231123
return user, nil
11241124
}
11251125

1126+
func (q *fakeQuerier) GrantUserRole(ctx context.Context, arg database.GrantUserRoleParams) (database.User, error) {
1127+
q.mutex.Lock()
1128+
defer q.mutex.Unlock()
1129+
1130+
for index, user := range q.users {
1131+
if user.ID != arg.ID {
1132+
continue
1133+
}
1134+
1135+
// Append the new roles
1136+
user.RbacRoles = append(user.RbacRoles, arg.GrantedRoles...)
1137+
// Remove duplicates and sort
1138+
uniqueRoles := make([]string, 0, len(user.RbacRoles))
1139+
exist := make(map[string]struct{})
1140+
for _, r := range user.RbacRoles {
1141+
if _, ok := exist[r]; ok {
1142+
continue
1143+
}
1144+
exist[r] = struct{}{}
1145+
uniqueRoles = append(uniqueRoles, r)
1146+
}
1147+
sort.Strings(uniqueRoles)
1148+
user.RbacRoles = uniqueRoles
1149+
1150+
q.users[index] = user
1151+
return user, nil
1152+
}
1153+
return database.User{}, sql.ErrNoRows
1154+
}
1155+
11261156
func (q *fakeQuerier) UpdateUserProfile(_ context.Context, arg database.UpdateUserProfileParams) (database.User, error) {
11271157
q.mutex.Lock()
11281158
defer q.mutex.Unlock()

coderd/rbac/authz.go

+17
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,23 @@ type authSubject struct {
3838
Roles []Role `json:"roles"`
3939
}
4040

41+
// AuthorizeByRoleName will expand all roleNames into roles before calling Authorize().
42+
// This is the function intended to be used outside this package.
43+
// The role is fetched from the builtin map located in memory.
44+
func (a RegoAuthorizer) AuthorizeByRoleName(ctx context.Context, subjectID string, roleNames []RoleName, action Action, object Object) error {
45+
roles := make([]Role, 0, len(roleNames))
46+
for _, n := range roleNames {
47+
r, err := RoleByName(n)
48+
if err != nil {
49+
return xerrors.Errorf("get role permissions: %w", err)
50+
}
51+
roles = append(roles, r)
52+
}
53+
return a.Authorize(ctx, subjectID, roles, action, object)
54+
}
55+
56+
// Authorize allows passing in custom Roles.
57+
// This is really helpful for unit testing, as we can create custom roles to exercise edge cases.
4158
func (a RegoAuthorizer) Authorize(ctx context.Context, subjectID string, roles []Role, action Action, object Object) error {
4259
input := map[string]interface{}{
4360
"subject": authSubject{

0 commit comments

Comments
 (0)