-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
default_privilege.go
504 lines (467 loc) · 19.4 KB
/
default_privilege.go
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package catprivilege
import (
"fmt"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
)
var _ catalog.DefaultPrivilegeDescriptor = &immutable{}
var _ catalog.DefaultPrivilegeDescriptor = &Mutable{}
// immutable is a wrapper for a DefaultPrivilegeDescriptor
// that only exposes getters.
type immutable struct {
defaultPrivilegeDescriptor *descpb.DefaultPrivilegeDescriptor
}
// Mutable is a wrapper for a DefaultPrivilegeDescriptor
// that exposes getters and setters.
type Mutable struct {
immutable
}
// MakeNewDatabaseDefaultPrivilegeDescriptor returns a new
// DefaultPrivilegeDescriptor used for databases.
func MakeNewDatabaseDefaultPrivilegeDescriptor() *descpb.DefaultPrivilegeDescriptor {
var defaultPrivilegesForRole []descpb.DefaultPrivilegesForRole
return &descpb.DefaultPrivilegeDescriptor{
DefaultPrivilegesPerRole: defaultPrivilegesForRole,
Type: descpb.DefaultPrivilegeDescriptor_DATABASE,
}
}
// MakeNewSchemaDefaultPrivilegeDescriptor returns a new
// DefaultPrivilegeDescriptor used for schemas.
func MakeNewSchemaDefaultPrivilegeDescriptor() *descpb.DefaultPrivilegeDescriptor {
var defaultPrivilegesForRole []descpb.DefaultPrivilegesForRole
return &descpb.DefaultPrivilegeDescriptor{
DefaultPrivilegesPerRole: defaultPrivilegesForRole,
Type: descpb.DefaultPrivilegeDescriptor_SCHEMA,
}
}
// MakeDefaultPrivileges returns an immutable
// given a defaultPrivilegeDescriptor.
func MakeDefaultPrivileges(
defaultPrivilegeDescriptor *descpb.DefaultPrivilegeDescriptor,
) catalog.DefaultPrivilegeDescriptor {
return &immutable{
defaultPrivilegeDescriptor: defaultPrivilegeDescriptor,
}
}
// NewMutableDefaultPrivileges returns a Mutable
// given a defaultPrivilegeDescriptor.
func NewMutableDefaultPrivileges(
defaultPrivilegeDescriptor *descpb.DefaultPrivilegeDescriptor,
) *Mutable {
return &Mutable{
immutable{
defaultPrivilegeDescriptor: defaultPrivilegeDescriptor,
}}
}
// Calls expandPrivileges before calling the function passed in and calls
// foldPrivileges after calling grant/revoke if the DefaultPrivilegeDescriptor
// is for a database. If the DefaultPrivilegeDescriptor is for a schema we
// simply call grant/revoke.
func (d *immutable) grantOrRevokeDefaultPrivilegesHelper(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole,
role descpb.DefaultPrivilegesRole,
targetObject tree.AlterDefaultPrivilegesTargetObject,
grantee security.SQLUsername,
privList privilege.List,
withGrantOption bool,
isGrant bool,
) {
defaultPrivileges := defaultPrivilegesForRole.DefaultPrivilegesPerObject[targetObject]
// expandPrivileges turns flags on the DefaultPrivilegesForRole representing
// special privilege cases into real privileges on the PrivilegeDescriptor.
// foldPrivileges converts the real privileges back into flags.
// We only need to do this if the default privileges are defined globally
// (for the database) as schemas do not have this special case.
if d.IsDatabaseDefaultPrivilege() {
expandPrivileges(defaultPrivilegesForRole, role, &defaultPrivileges, targetObject)
}
if isGrant {
defaultPrivileges.Grant(grantee, privList, withGrantOption)
} else {
defaultPrivileges.Revoke(grantee, privList, targetObject.ToPrivilegeObjectType(), withGrantOption)
}
if d.IsDatabaseDefaultPrivilege() {
foldPrivileges(defaultPrivilegesForRole, role, &defaultPrivileges, targetObject)
}
defaultPrivilegesForRole.DefaultPrivilegesPerObject[targetObject] = defaultPrivileges
}
// GrantDefaultPrivileges grants privileges for the specified users.
func (d *Mutable) GrantDefaultPrivileges(
role descpb.DefaultPrivilegesRole,
privileges privilege.List,
grantees []security.SQLUsername,
targetObject tree.AlterDefaultPrivilegesTargetObject,
withGrantOption bool,
) {
defaultPrivilegesForRole := d.defaultPrivilegeDescriptor.FindOrCreateUser(role)
for _, grantee := range grantees {
d.grantOrRevokeDefaultPrivilegesHelper(defaultPrivilegesForRole, role, targetObject, grantee, privileges, withGrantOption, true /* isGrant */)
}
}
// RevokeDefaultPrivileges revokes privileges for the specified users.
func (d *Mutable) RevokeDefaultPrivileges(
role descpb.DefaultPrivilegesRole,
privileges privilege.List,
grantees []security.SQLUsername,
targetObject tree.AlterDefaultPrivilegesTargetObject,
grantOptionFor bool,
) {
defaultPrivilegesForRole := d.defaultPrivilegeDescriptor.FindOrCreateUser(role)
for _, grantee := range grantees {
d.grantOrRevokeDefaultPrivilegesHelper(defaultPrivilegesForRole, role, targetObject, grantee, privileges, grantOptionFor, false /* isGrant */)
}
defaultPrivilegesPerObject := defaultPrivilegesForRole.DefaultPrivilegesPerObject
// Check if there are any default privileges remaining on the descriptor.
// If there are no privileges left remaining and the descriptor is in the
// default state, we can remove it.
for _, defaultPrivs := range defaultPrivilegesPerObject {
if len(defaultPrivs.Users) != 0 {
return
}
}
// If the DefaultPrivilegeDescriptor is defined on a schema, the flags are
// not used and have no meaning.
if defaultPrivilegesForRole.IsExplicitRole() && d.IsDatabaseDefaultPrivilege() &&
(!GetRoleHasAllPrivilegesOnTargetObject(defaultPrivilegesForRole, tree.Tables) ||
!GetRoleHasAllPrivilegesOnTargetObject(defaultPrivilegesForRole, tree.Sequences) ||
!GetRoleHasAllPrivilegesOnTargetObject(defaultPrivilegesForRole, tree.Types) ||
!GetRoleHasAllPrivilegesOnTargetObject(defaultPrivilegesForRole, tree.Schemas)) ||
!GetPublicHasUsageOnTypes(defaultPrivilegesForRole) {
return
}
// There no entries remaining, remove the entry for the role.
d.defaultPrivilegeDescriptor.RemoveUser(role)
}
// CreatePrivilegesFromDefaultPrivileges creates privileges for a
// the specified object with the corresponding default privileges and
// the appropriate owner (node for system, the restoring user otherwise.)
// defaultPrivilegeDescriptors can either be len 1 or 2. It can be just
// the default privilege descriptor from the database or both the db and schema.
func CreatePrivilegesFromDefaultPrivileges(
defaultPrivilegeDescriptors []catalog.DefaultPrivilegeDescriptor,
dbID descpb.ID,
user security.SQLUsername,
targetObject tree.AlterDefaultPrivilegesTargetObject,
databasePrivileges *descpb.PrivilegeDescriptor,
) *descpb.PrivilegeDescriptor {
// If a new system table is being created (which should only be doable by
// an internal user account), make sure it gets the correct privileges.
if dbID == keys.SystemDatabaseID {
return descpb.NewBasePrivilegeDescriptor(security.NodeUserName())
}
newPrivs := descpb.NewBasePrivilegeDescriptor(user)
role := descpb.DefaultPrivilegesRole{Role: user}
for _, d := range defaultPrivilegeDescriptors {
if defaultPrivilegesForRole, found := d.GetDefaultPrivilegesForRole(role); !found {
// If default privileges are not defined for the creator role, we handle
// it as the case where the user has all privileges.
defaultPrivilegesForCreatorRole := descpb.InitDefaultPrivilegesForRole(role, d.GetDefaultPrivilegeDescriptorType())
for _, user := range GetUserPrivilegesForObject(defaultPrivilegesForCreatorRole, targetObject) {
applyDefaultPrivileges(
newPrivs,
user.UserProto.Decode(),
privilege.ListFromBitField(user.Privileges, targetObject.ToPrivilegeObjectType()),
privilege.ListFromBitField(user.WithGrantOption, targetObject.ToPrivilegeObjectType()),
)
}
} else {
// If default privileges were defined for the role, we create privileges
// using the default privileges.
for _, user := range GetUserPrivilegesForObject(*defaultPrivilegesForRole, targetObject) {
applyDefaultPrivileges(
newPrivs,
user.UserProto.Decode(),
privilege.ListFromBitField(user.Privileges, targetObject.ToPrivilegeObjectType()),
privilege.ListFromBitField(user.WithGrantOption, targetObject.ToPrivilegeObjectType()),
)
}
}
// The privileges for the object are the union of the default privileges
// defined for the object for the object creator and the default privileges
// defined for all roles.
defaultPrivilegesForAllRoles, found := d.GetDefaultPrivilegesForRole(descpb.DefaultPrivilegesRole{ForAllRoles: true})
if found {
for _, user := range GetUserPrivilegesForObject(*defaultPrivilegesForAllRoles, targetObject) {
applyDefaultPrivileges(
newPrivs,
user.UserProto.Decode(),
privilege.ListFromBitField(user.Privileges, targetObject.ToPrivilegeObjectType()),
privilege.ListFromBitField(user.WithGrantOption, targetObject.ToPrivilegeObjectType()),
)
}
}
}
newPrivs.Version = descpb.Version21_2
// TODO(richardjcai): Remove this depending on how we handle the migration.
// For backwards compatibility, also "inherit" privileges from the dbDesc.
// Issue #67378.
if targetObject == tree.Tables || targetObject == tree.Sequences {
for _, u := range databasePrivileges.Users {
applyDefaultPrivileges(
newPrivs,
u.UserProto.Decode(),
privilege.ListFromBitField(u.Privileges, privilege.Table),
privilege.ListFromBitField(u.WithGrantOption, privilege.Table),
)
}
} else if targetObject == tree.Schemas {
for _, u := range databasePrivileges.Users {
applyDefaultPrivileges(
newPrivs,
u.UserProto.Decode(),
privilege.ListFromBitField(u.Privileges, privilege.Schema),
privilege.ListFromBitField(u.WithGrantOption, privilege.Schema),
)
}
}
return newPrivs
}
// ForEachDefaultPrivilegeForRole implements the
// catalog.DefaultPrivilegeDescriptor interface.
// ForEachDefaultPrivilegeForRole loops through the DefaultPrivilegeDescriptior's
// DefaultPrivilegePerRole entry and calls f on it.
func (d *immutable) ForEachDefaultPrivilegeForRole(
f func(defaultPrivilegesForRole descpb.DefaultPrivilegesForRole) error,
) error {
if d.defaultPrivilegeDescriptor == nil {
return nil
}
for _, defaultPrivilegesForRole := range d.defaultPrivilegeDescriptor.DefaultPrivilegesPerRole {
if err := f(defaultPrivilegesForRole); err != nil {
return err
}
}
return nil
}
// GetDefaultPrivilegesForRole implements the
// catalog.DefaultPrivilegeDescriptor interface.
// GetDefaultPrivilegesForRole looks for a specific user in the list.
// Returns (nil, false) if not found, or (ptr, true) if found.
func (d *immutable) GetDefaultPrivilegesForRole(
role descpb.DefaultPrivilegesRole,
) (*descpb.DefaultPrivilegesForRole, bool) {
idx := d.defaultPrivilegeDescriptor.FindUserIndex(role)
if idx == -1 {
return nil, false
}
return &d.defaultPrivilegeDescriptor.DefaultPrivilegesPerRole[idx], true
}
// GetDefaultPrivilegeDescriptorType the Type of the default privilege descriptor.
func (d *immutable) GetDefaultPrivilegeDescriptorType() descpb.DefaultPrivilegeDescriptor_DefaultPrivilegeDescriptorType {
return d.defaultPrivilegeDescriptor.Type
}
// IsDatabaseDefaultPrivilege returns whether the Type of the default privilege
// descriptor is for databases.
func (d *immutable) IsDatabaseDefaultPrivilege() bool {
return d.defaultPrivilegeDescriptor.Type == descpb.DefaultPrivilegeDescriptor_DATABASE
}
// foldPrivileges folds ALL privileges for role and USAGE on public into
// the corresponding flag on the DefaultPrivilegesForRole object.
// For example, if after a Grant operation, role has ALL on tables, ALL
// privilege is removed from the UserPrivileges object and instead
// RoleHasAllPrivilegesOnTable is set to true.
// This is necessary as role having ALL privileges on tables is the default state
// and should not prevent the role from being dropped if it has ALL privileges.
func foldPrivileges(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole,
role descpb.DefaultPrivilegesRole,
privileges *descpb.PrivilegeDescriptor,
targetObject tree.AlterDefaultPrivilegesTargetObject,
) {
if targetObject == tree.Types &&
privileges.CheckPrivilege(security.PublicRoleName(), privilege.USAGE) {
publicUser, ok := privileges.FindUser(security.PublicRoleName())
if ok {
if !privilege.USAGE.IsSetIn(publicUser.WithGrantOption) {
setPublicHasUsageOnTypes(defaultPrivilegesForRole, true)
privileges.Revoke(
security.PublicRoleName(),
privilege.List{privilege.USAGE},
privilege.Type,
false, /* grantOptionFor */
)
}
}
}
// ForAllRoles cannot be a grantee, nothing left to do.
if role.ForAllRoles {
return
}
if privileges.HasAllPrivileges(role.Role, targetObject.ToPrivilegeObjectType()) {
user := privileges.FindOrCreateUser(role.Role)
if user.WithGrantOption == 0 {
setRoleHasAllOnTargetObject(defaultPrivilegesForRole, true, targetObject)
privileges.RemoveUser(role.Role)
}
}
}
// expandPrivileges expands the pseudo privilege flags on
// DefaultPrivilegesForRole into real privileges on the UserPrivileges object.
// After expandPrivileges, UserPrivileges can be Granted/Revoked from normally.
// For example - if RoleHasAllPrivilegesOnTables is true, ALL privilege is added
// into the UserPrivileges array for the Role.
func expandPrivileges(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole,
role descpb.DefaultPrivilegesRole,
privileges *descpb.PrivilegeDescriptor,
targetObject tree.AlterDefaultPrivilegesTargetObject,
) {
if targetObject == tree.Types && GetPublicHasUsageOnTypes(defaultPrivilegesForRole) {
privileges.Grant(security.PublicRoleName(), privilege.List{privilege.USAGE}, false /* withGrantOption */)
setPublicHasUsageOnTypes(defaultPrivilegesForRole, false)
}
// ForAllRoles cannot be a grantee, nothing left to do.
if role.ForAllRoles {
return
}
if GetRoleHasAllPrivilegesOnTargetObject(defaultPrivilegesForRole, targetObject) {
privileges.Grant(defaultPrivilegesForRole.GetExplicitRole().UserProto.Decode(), privilege.List{privilege.ALL}, false /* withGrantOption */)
setRoleHasAllOnTargetObject(defaultPrivilegesForRole, false, targetObject)
}
}
// GetUserPrivilegesForObject returns the set of []UserPrivileges constructed
// from the DefaultPrivilegesForRole.
func GetUserPrivilegesForObject(
p descpb.DefaultPrivilegesForRole, targetObject tree.AlterDefaultPrivilegesTargetObject,
) []descpb.UserPrivileges {
var userPrivileges []descpb.UserPrivileges
if privileges, ok := p.DefaultPrivilegesPerObject[targetObject]; ok {
userPrivileges = privileges.Users
}
if GetPublicHasUsageOnTypes(&p) && targetObject == tree.Types {
userPrivileges = append(userPrivileges, descpb.UserPrivileges{
UserProto: security.PublicRoleName().EncodeProto(),
Privileges: privilege.USAGE.Mask(),
})
}
// If ForAllRoles is specified, we can return early.
// ForAllRoles is not a real role and does not have implicit default privileges
// for itself.
if !p.IsExplicitRole() {
return userPrivileges
}
userProto := p.GetExplicitRole().UserProto
if GetRoleHasAllPrivilegesOnTargetObject(&p, targetObject) {
return append(userPrivileges, descpb.UserPrivileges{
UserProto: userProto,
Privileges: privilege.ALL.Mask(),
})
}
return userPrivileges
}
// GetPublicHasUsageOnTypes returns whether Public has Usage privilege on types.
func GetPublicHasUsageOnTypes(defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole) bool {
if defaultPrivilegesForRole.IsExplicitRole() {
return defaultPrivilegesForRole.GetExplicitRole().PublicHasUsageOnTypes
}
return defaultPrivilegesForRole.GetForAllRoles().PublicHasUsageOnTypes
}
// GetRoleHasAllPrivilegesOnTargetObject returns whether the creator role
// has all privileges on the default privileges target object.
func GetRoleHasAllPrivilegesOnTargetObject(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole,
targetObject tree.AlterDefaultPrivilegesTargetObject,
) bool {
if !defaultPrivilegesForRole.IsExplicitRole() {
// ForAllRoles is a pseudo role and does not actually have privileges on it.
return false
}
switch targetObject {
case tree.Tables:
return defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnTables
case tree.Sequences:
return defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnSequences
case tree.Types:
return defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnTypes
case tree.Schemas:
return defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnSchemas
default:
panic(fmt.Sprintf("unknown target object %s", targetObject))
}
}
// setPublicHasUsageOnTypes sets PublicHasUsageOnTypes to publicHasUsageOnTypes.
func setPublicHasUsageOnTypes(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole, publicHasUsageOnTypes bool,
) {
if defaultPrivilegesForRole.IsExplicitRole() {
defaultPrivilegesForRole.GetExplicitRole().PublicHasUsageOnTypes = publicHasUsageOnTypes
} else {
defaultPrivilegesForRole.GetForAllRoles().PublicHasUsageOnTypes = publicHasUsageOnTypes
}
}
// applyDefaultPrivileges adds new privileges to this descriptor and new grant options which
// could be different from the privileges. Unlike the normal grant, the privileges
// and the grant options being granted could be different
func applyDefaultPrivileges(
p *descpb.PrivilegeDescriptor,
user security.SQLUsername,
privList privilege.List,
grantOptionList privilege.List,
) {
userPriv := p.FindOrCreateUser(user)
if privilege.ALL.IsSetIn(userPriv.WithGrantOption) && privilege.ALL.IsSetIn(userPriv.Privileges) {
// User already has 'ALL' privilege: no-op.
// If userPriv.WithGrantOption has ALL, then userPriv.Privileges must also have ALL.
// It is possible however for userPriv.Privileges to have ALL but userPriv.WithGrantOption to not have ALL
return
}
privBits := privList.ToBitField()
grantBits := grantOptionList.ToBitField()
// Should not be possible for a privilege to be in grantOptionList that is not in privList.
if !privilege.ALL.IsSetIn(privBits) {
for _, grantOption := range grantOptionList {
if privBits&grantOption.Mask() == 0 {
return
}
}
}
if privilege.ALL.IsSetIn(privBits) {
userPriv.Privileges = privilege.ALL.Mask()
} else {
if !privilege.ALL.IsSetIn(userPriv.Privileges) {
userPriv.Privileges |= privBits
}
}
if privilege.ALL.IsSetIn(grantBits) {
userPriv.WithGrantOption = privilege.ALL.Mask()
} else {
if !privilege.ALL.IsSetIn(userPriv.WithGrantOption) {
userPriv.WithGrantOption |= grantBits
}
}
}
func setRoleHasAllOnTargetObject(
defaultPrivilegesForRole *descpb.DefaultPrivilegesForRole,
roleHasAll bool,
targetObject tree.AlterDefaultPrivilegesTargetObject,
) {
if !defaultPrivilegesForRole.IsExplicitRole() {
// ForAllRoles is a pseudo role and does not actually have privileges on it.
panic("DefaultPrivilegesForRole must be for an explicit role")
}
switch targetObject {
case tree.Tables:
defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnTables = roleHasAll
case tree.Sequences:
defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnSequences = roleHasAll
case tree.Types:
defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnTypes = roleHasAll
case tree.Schemas:
defaultPrivilegesForRole.GetExplicitRole().RoleHasAllPrivilegesOnSchemas = roleHasAll
default:
panic(fmt.Sprintf("unknown target object %s", targetObject))
}
}