-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathrole.go
More file actions
318 lines (279 loc) · 10.1 KB
/
role.go
File metadata and controls
318 lines (279 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package idpsync
import (
"context"
"encoding/json"
"slices"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/rbac"
"github.com/coder/coder/v2/coderd/rbac/rolestore"
"github.com/coder/coder/v2/coderd/runtimeconfig"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
)
type RoleParams struct {
// SyncEntitled if false will skip syncing the user's roles at
// all levels.
SyncEntitled bool
SyncSiteWide bool
SiteWideRoles []string
// MergedClaims are passed to the organization level for syncing
MergedClaims jwt.MapClaims
}
func (AGPLIDPSync) RoleSyncEntitled() bool {
// AGPL does not support syncing groups.
return false
}
func (AGPLIDPSync) OrganizationRoleSyncEnabled(_ context.Context, _ database.Store, _ uuid.UUID) (bool, error) {
return false, nil
}
func (AGPLIDPSync) SiteRoleSyncEnabled() bool {
return false
}
func (s AGPLIDPSync) UpdateRoleSyncSettings(ctx context.Context, orgID uuid.UUID, db database.Store, settings RoleSyncSettings) error {
orgResolver := s.Manager.OrganizationResolver(db, orgID)
err := s.SyncSettings.Role.SetRuntimeValue(ctx, orgResolver, &settings)
if err != nil {
return xerrors.Errorf("update role sync settings: %w", err)
}
return nil
}
func (s AGPLIDPSync) RoleSyncSettings(ctx context.Context, orgID uuid.UUID, db database.Store) (*RoleSyncSettings, error) {
rlv := s.Manager.OrganizationResolver(db, orgID)
settings, err := s.Role.Resolve(ctx, rlv)
if err != nil {
if !xerrors.Is(err, runtimeconfig.ErrEntryNotFound) {
return nil, xerrors.Errorf("resolve role sync settings: %w", err)
}
return &RoleSyncSettings{}, nil
}
return settings, nil
}
func (s AGPLIDPSync) ParseRoleClaims(_ context.Context, _ jwt.MapClaims) (RoleParams, *HTTPError) {
return RoleParams{
SyncEntitled: s.RoleSyncEntitled(),
SyncSiteWide: s.SiteRoleSyncEnabled(),
}, nil
}
func (s AGPLIDPSync) SyncRoles(ctx context.Context, db database.Store, user database.User, params RoleParams) error {
// Nothing happens if sync is not enabled
if !params.SyncEntitled {
return nil
}
// nolint:gocritic // all syncing is done as a system user
ctx = dbauthz.AsSystemRestricted(ctx)
err := db.InTx(func(tx database.Store) error {
if params.SyncSiteWide {
if err := s.syncSiteWideRoles(ctx, tx, user, params); err != nil {
return err
}
}
// sync roles per organization
orgMemberships, err := tx.OrganizationMembers(ctx, database.OrganizationMembersParams{
OrganizationID: uuid.Nil,
UserID: user.ID,
IncludeSystem: false,
GithubUserID: 0,
})
if err != nil {
return xerrors.Errorf("get organizations by user id: %w", err)
}
// Sync for each organization
// If a key for a given org exists in the map, the user's roles will be
// updated to the value of that key.
expectedRoles := make(map[uuid.UUID][]rbac.RoleIdentifier)
existingRoles := make(map[uuid.UUID][]string)
allExpected := make([]rbac.RoleIdentifier, 0)
for _, member := range orgMemberships {
orgID := member.OrganizationMember.OrganizationID
settings, err := s.RoleSyncSettings(ctx, orgID, tx)
if err != nil {
// No entry means no role syncing for this organization
continue
}
if settings.Field == "" {
// Explicitly disabled role sync for this organization
continue
}
existingRoles[orgID] = member.OrganizationMember.Roles
orgRoleClaims, err := s.RolesFromClaim(settings.Field, params.MergedClaims)
if err != nil {
s.Logger.Error(ctx, "failed to parse roles from claim",
slog.F("field", settings.Field),
slog.F("organization_id", orgID),
slog.F("user_id", user.ID),
slog.F("username", user.Username),
slog.Error(err),
)
// TODO: If rolesync fails, we might want to reset a user's
// roles to prevent stale roles from existing.
// Eg: `expectedRoles[orgID] = []rbac.RoleIdentifier{}`
// However, implementing this could lock an org admin out
// of fixing their configuration.
// There is also no current method to notify an org admin of
// a configuration issue.
// So until org admins can be notified of configuration issues,
// and they will not be locked out, this code will do nothing to
// the user's roles.
// Do not return an error, because that would prevent a user
// from logging in. A misconfigured organization should not
// stop a user from logging into the site.
continue
}
expected := make([]rbac.RoleIdentifier, 0, len(orgRoleClaims))
for _, role := range orgRoleClaims {
if mappedRoles, ok := settings.Mapping[role]; ok {
for _, mappedRole := range mappedRoles {
expected = append(expected, rbac.RoleIdentifier{OrganizationID: orgID, Name: mappedRole})
}
continue
}
expected = append(expected, rbac.RoleIdentifier{OrganizationID: orgID, Name: role})
}
expectedRoles[orgID] = expected
allExpected = append(allExpected, expected...)
}
// Now mass sync the user's org membership roles.
validRoles, err := rolestore.Expand(ctx, tx, allExpected)
if err != nil {
return xerrors.Errorf("expand roles: %w", err)
}
validMap := make(map[string]struct{}, len(validRoles))
for _, validRole := range validRoles {
validMap[validRole.Identifier.UniqueName()] = struct{}{}
}
// For each org, do the SQL query to update the user's roles.
// TODO: Would be better to batch all these into a single SQL query.
for orgID, roles := range expectedRoles {
validExpected := make([]string, 0, len(roles))
for _, role := range roles {
if _, ok := validMap[role.UniqueName()]; ok {
validExpected = append(validExpected, role.Name)
}
}
// The implicit role set (organization-member plus the org's
// default_org_member_roles) is applied at request time by
// GetAuthorizationUserRoles. Filter both sides of the diff so
// IdP sync neither tries to grant implicit roles explicitly nor
// remove them.
org, err := tx.GetOrganizationByID(ctx, orgID)
if err != nil {
return xerrors.Errorf("get organization %s for default roles: %w", orgID, err)
}
implicit := make(map[string]struct{}, len(org.DefaultOrgMemberRoles)+1)
implicit[rbac.RoleOrgMember()] = struct{}{}
for _, r := range org.DefaultOrgMemberRoles {
implicit[r] = struct{}{}
}
isImplicit := func(s string) bool {
_, ok := implicit[s]
return ok
}
validExpected = slices.DeleteFunc(validExpected, isImplicit)
existingFound := existingRoles[orgID]
existingFound = slices.DeleteFunc(existingFound, isImplicit)
// Only care about unique roles. So remove all duplicates
existingFound = slice.Unique(existingFound)
validExpected = slice.Unique(validExpected)
// A sort is required for the equality check
slices.Sort(existingFound)
slices.Sort(validExpected)
// Is there a difference between the expected roles and the existing roles?
if !slices.Equal(existingFound, validExpected) {
// TODO: Write a unit test to verify we do no db call on no diff
_, err = tx.UpdateMemberRoles(ctx, database.UpdateMemberRolesParams{
GrantedRoles: validExpected,
UserID: user.ID,
OrgID: orgID,
})
if err != nil {
return xerrors.Errorf("update member roles(%s): %w", user.ID.String(), err)
}
}
}
return nil
}, nil)
if err != nil {
return xerrors.Errorf("sync user roles(%s): %w", user.ID.String(), err)
}
return nil
}
func (s AGPLIDPSync) syncSiteWideRoles(ctx context.Context, tx database.Store, user database.User, params RoleParams) error {
// Apply site wide roles to a user.
// ignored is the list of roles that are not valid Coder roles and will
// be skipped.
ignored := make([]string, 0)
filtered := make([]string, 0, len(params.SiteWideRoles))
for _, role := range params.SiteWideRoles {
// Because we are only syncing site wide roles, we intentionally will always
// omit 'OrganizationID' from the RoleIdentifier.
// TODO: If custom site wide roles are introduced, this needs to use the
// database to verify the role exists.
if _, err := rbac.RoleByName(rbac.RoleIdentifier{Name: role}); err == nil {
filtered = append(filtered, role)
} else {
ignored = append(ignored, role)
}
}
if len(ignored) > 0 {
s.Logger.Debug(ctx, "OIDC roles ignored in assignment",
slog.F("ignored", ignored),
slog.F("assigned", filtered),
slog.F("user_id", user.ID),
slog.F("username", user.Username),
)
}
filtered = slice.Unique(filtered)
slices.Sort(filtered)
existing := slice.Unique(user.RBACRoles)
slices.Sort(existing)
if !slices.Equal(existing, filtered) {
_, err := tx.UpdateUserRoles(ctx, database.UpdateUserRolesParams{
GrantedRoles: filtered,
ID: user.ID,
})
if err != nil {
return xerrors.Errorf("set site wide roles: %w", err)
}
}
return nil
}
func (AGPLIDPSync) RolesFromClaim(field string, claims jwt.MapClaims) ([]string, error) {
rolesRow, ok := claims[field]
if !ok {
// If no claim is provided than we can assume the user is just
// a member. This is because there is no way to tell the difference
// between []string{} and nil for OIDC claims. IDPs omit claims
// if they are empty ([]string{}).
// Use []interface{}{} so the next typecast works.
rolesRow = []interface{}{}
}
parsedRoles, err := ParseStringSliceClaim(rolesRow)
if err != nil {
return nil, xerrors.Errorf("failed to parse roles from claim: %w", err)
}
return parsedRoles, nil
}
type RoleSyncSettings codersdk.RoleSyncSettings
func (s *RoleSyncSettings) Set(v string) error {
return json.Unmarshal([]byte(v), s)
}
func (s *RoleSyncSettings) String() string {
if s.Mapping == nil {
s.Mapping = make(map[string][]string)
}
return runtimeconfig.JSONString(s)
}
func (s *RoleSyncSettings) MarshalJSON() ([]byte, error) {
if s.Mapping == nil {
s.Mapping = make(map[string][]string)
}
// Aliasing the struct to avoid infinite recursion when calling json.Marshal
// on the struct itself.
type Alias RoleSyncSettings
return json.Marshal(&struct{ *Alias }{Alias: (*Alias)(s)})
}