-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
authorization.go
800 lines (710 loc) · 25.8 KB
/
authorization.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
// Copyright 2017 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 sql
import (
"context"
"fmt"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/dbdesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schemadesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/tabledesc"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/typedesc"
"github.com/cockroachdb/cockroach/pkg/sql/memsize"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/privilege"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessioninit"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/errors"
)
// MembershipCache is a shared cache for role membership information.
type MembershipCache struct {
syncutil.Mutex
tableVersion descpb.DescriptorVersion
boundAccount mon.BoundAccount
// userCache is a mapping from username to userRoleMembership.
userCache map[security.SQLUsername]userRoleMembership
}
// NewMembershipCache initializes a new MembershipCache.
func NewMembershipCache(account mon.BoundAccount) *MembershipCache {
return &MembershipCache{
boundAccount: account,
}
}
// userRoleMembership is a mapping of "rolename" -> "with admin option".
type userRoleMembership map[security.SQLUsername]bool
// AuthorizationAccessor for checking authorization (e.g. desc privileges).
type AuthorizationAccessor interface {
// CheckPrivilege verifies that the user has `privilege` on `descriptor`.
CheckPrivilegeForUser(
ctx context.Context, descriptor catalog.Descriptor, privilege privilege.Kind, user security.SQLUsername,
) error
// CheckPrivilege verifies that the current user has `privilege` on `descriptor`.
CheckPrivilege(
ctx context.Context, descriptor catalog.Descriptor, privilege privilege.Kind,
) error
// CheckAnyPrivilege returns nil if user has any privileges at all.
CheckAnyPrivilege(ctx context.Context, descriptor catalog.Descriptor) error
// UserHasAdminRole returns tuple of bool and error:
// (true, nil) means that the user has an admin role (i.e. root or node)
// (false, nil) means that the user has NO admin role
// (false, err) means that there was an error running the query on
// the `system.users` table
UserHasAdminRole(ctx context.Context, user security.SQLUsername) (bool, error)
// HasAdminRole checks if the current session's user has admin role.
HasAdminRole(ctx context.Context) (bool, error)
// RequireAdminRole is a wrapper on top of HasAdminRole.
// It errors if HasAdminRole errors or if the user isn't a super-user.
// Includes the named action in the error message.
RequireAdminRole(ctx context.Context, action string) error
// MemberOfWithAdminOption looks up all the roles (direct and indirect) that 'member' is a member
// of and returns a map of role -> isAdmin.
MemberOfWithAdminOption(ctx context.Context, member security.SQLUsername) (map[security.SQLUsername]bool, error)
// HasRoleOption converts the roleoption to its SQL column name and checks if
// the user belongs to a role where the option has value true. Requires a
// valid transaction to be open.
//
// This check should be done on the version of the privilege that is stored in
// the role options table. Example: CREATEROLE instead of NOCREATEROLE.
// NOLOGIN instead of LOGIN.
HasRoleOption(ctx context.Context, roleOption roleoption.Option) (bool, error)
}
var _ AuthorizationAccessor = &planner{}
// CheckPrivilegeForUser implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
func (p *planner) CheckPrivilegeForUser(
ctx context.Context,
descriptor catalog.Descriptor,
privilege privilege.Kind,
user security.SQLUsername,
) error {
// Verify that the txn is valid in any case, so that
// we don't get the risk to say "OK" to root requests
// with an invalid API usage.
if p.txn == nil || !p.txn.IsOpen() {
return errors.AssertionFailedf("cannot use CheckPrivilege without a txn")
}
// Test whether the object is being audited, and if so, record an
// audit event. We place this check here to increase the likelihood
// it will not be forgotten if features are added that access
// descriptors (since every use of descriptors presumably need a
// permission check).
p.maybeAudit(descriptor, privilege)
privs := descriptor.GetPrivileges()
// Check if the 'public' pseudo-role has privileges.
if privs.CheckPrivilege(security.PublicRoleName(), privilege) {
return nil
}
hasPriv, err := p.checkRolePredicate(ctx, user, func(role security.SQLUsername) bool {
return IsOwner(descriptor, role) || privs.CheckPrivilege(role, privilege)
})
if err != nil {
return err
}
if hasPriv {
return nil
}
return pgerror.Newf(pgcode.InsufficientPrivilege,
"user %s does not have %s privilege on %s %s",
user, privilege, descriptor.DescriptorType(), descriptor.GetName())
}
// CheckPrivilege implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
// TODO(arul): This CheckPrivileges method name is rather deceptive,
// it should be probably be called CheckPrivilegesOrOwnership and return
// a better error.
func (p *planner) CheckPrivilege(
ctx context.Context, descriptor catalog.Descriptor, privilege privilege.Kind,
) error {
return p.CheckPrivilegeForUser(ctx, descriptor, privilege, p.User())
}
// CheckGrantOptionsForUser calls PrivilegeDescriptor.CheckGrantOptions, which
// will return an error if a user tries to grant a privilege it does not have
// grant options for. Owners implicitly have all grant options, and also grant
// options are inherited from parent roles.
func (p *planner) CheckGrantOptionsForUser(
ctx context.Context,
descriptor catalog.Descriptor,
privList privilege.List,
user security.SQLUsername,
isGrant bool,
) error {
// Always allow the command to go through if performed by a superuser or the
// owner of the object
if isAdmin, err := p.UserHasAdminRole(ctx, user); err != nil {
return err
} else if isAdmin {
return nil
}
privs := descriptor.GetPrivileges()
hasPriv, err := p.checkRolePredicate(ctx, user, func(role security.SQLUsername) bool {
return IsOwner(descriptor, role) || privs.CheckGrantOptions(role, privList)
})
if err != nil {
return err
}
if hasPriv {
return nil
}
code := pgcode.WarningPrivilegeNotGranted
if !isGrant {
code = pgcode.WarningPrivilegeNotRevoked
}
if privList.Len() > 1 {
return pgerror.Newf(
code, "user %s missing WITH GRANT OPTION privilege on one or more of %s",
user, privList.String(),
)
}
return pgerror.Newf(
code, "user %s missing WITH GRANT OPTION privilege on %s",
user, privList.String(),
)
}
func getOwnerOfDesc(desc catalog.Descriptor) security.SQLUsername {
// Descriptors created prior to 20.2 do not have owners set.
owner := desc.GetPrivileges().Owner()
if owner.Undefined() {
// If the descriptor is ownerless and the descriptor is part of the system db,
// node is the owner.
if catalog.IsSystemDescriptor(desc) {
owner = security.NodeUserName()
} else {
// This check is redundant in this case since admin already has privilege
// on all non-system objects.
owner = security.AdminRoleName()
}
}
return owner
}
// IsOwner returns if the role has ownership on the descriptor.
func IsOwner(desc catalog.Descriptor, role security.SQLUsername) bool {
return role == getOwnerOfDesc(desc)
}
// HasOwnership returns if the role or any role the role is a member of
// has ownership privilege of the desc.
// TODO(richardjcai): SUPERUSER has implicit ownership.
// We do not have SUPERUSER privilege yet but should we consider root a superuser?
func (p *planner) HasOwnership(ctx context.Context, descriptor catalog.Descriptor) (bool, error) {
user := p.SessionData().User()
return p.checkRolePredicate(ctx, user, func(role security.SQLUsername) bool {
return IsOwner(descriptor, role)
})
}
// checkRolePredicate checks if the predicate is true for the user or
// any roles the user is a member of.
func (p *planner) checkRolePredicate(
ctx context.Context, user security.SQLUsername, predicate func(role security.SQLUsername) bool,
) (bool, error) {
if ok := predicate(user); ok {
return ok, nil
}
memberOf, err := p.MemberOfWithAdminOption(ctx, user)
if err != nil {
return false, err
}
for role := range memberOf {
if ok := predicate(role); ok {
return ok, nil
}
}
return false, nil
}
// CheckAnyPrivilege implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
func (p *planner) CheckAnyPrivilege(ctx context.Context, descriptor catalog.Descriptor) error {
// Verify that the txn is valid in any case, so that
// we don't get the risk to say "OK" to root requests
// with an invalid API usage.
if p.txn == nil || !p.txn.IsOpen() {
return errors.AssertionFailedf("cannot use CheckAnyPrivilege without a txn")
}
user := p.SessionData().User()
privs := descriptor.GetPrivileges()
// Check if 'user' itself has privileges.
if privs.AnyPrivilege(user) {
return nil
}
// Check if 'public' has privileges.
if privs.AnyPrivilege(security.PublicRoleName()) {
return nil
}
// Expand role memberships.
memberOf, err := p.MemberOfWithAdminOption(ctx, user)
if err != nil {
return err
}
// Iterate over the roles that 'user' is a member of. We don't care about the admin option.
for role := range memberOf {
if privs.AnyPrivilege(role) {
return nil
}
}
return pgerror.Newf(pgcode.InsufficientPrivilege,
"user %s has no privileges on %s %s",
p.SessionData().User(), descriptor.DescriptorType(), descriptor.GetName())
}
// UserHasAdminRole implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
func (p *planner) UserHasAdminRole(ctx context.Context, user security.SQLUsername) (bool, error) {
if user.Undefined() {
return false, errors.AssertionFailedf("empty user")
}
// Verify that the txn is valid in any case, so that
// we don't get the risk to say "OK" to root requests
// with an invalid API usage.
if p.txn == nil || !p.txn.IsOpen() {
return false, errors.AssertionFailedf("cannot use HasAdminRole without a txn")
}
// Check if user is either 'admin', 'root' or 'node'.
// TODO(knz): planner HasAdminRole has no business authorizing
// the "node" principal - node should not be issuing SQL queries.
if user.IsAdminRole() || user.IsRootUser() || user.IsNodeUser() {
return true, nil
}
// Expand role memberships.
memberOf, err := p.MemberOfWithAdminOption(ctx, user)
if err != nil {
return false, err
}
// Check is 'user' is a member of role 'admin'.
if _, ok := memberOf[security.AdminRoleName()]; ok {
return true, nil
}
return false, nil
}
// HasAdminRole implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
func (p *planner) HasAdminRole(ctx context.Context) (bool, error) {
return p.UserHasAdminRole(ctx, p.User())
}
// RequireAdminRole implements the AuthorizationAccessor interface.
// Requires a valid transaction to be open.
func (p *planner) RequireAdminRole(ctx context.Context, action string) error {
ok, err := p.HasAdminRole(ctx)
if err != nil {
return err
}
if !ok {
// raise error if user is not a super-user
return pgerror.Newf(pgcode.InsufficientPrivilege,
"only users with the admin role are allowed to %s", action)
}
return nil
}
// MemberOfWithAdminOption is a wrapper around the MemberOfWithAdminOption
// method.
func (p *planner) MemberOfWithAdminOption(
ctx context.Context, member security.SQLUsername,
) (map[security.SQLUsername]bool, error) {
return MemberOfWithAdminOption(
ctx,
p.execCfg,
p.ExecCfg().InternalExecutor,
p.Descriptors(),
p.Txn(),
member,
)
}
// MemberOfWithAdminOption looks up all the roles 'member' belongs to (direct and indirect) and
// returns a map of "role" -> "isAdmin".
// The "isAdmin" flag applies to both direct and indirect members.
// Requires a valid transaction to be open.
func MemberOfWithAdminOption(
ctx context.Context,
execCfg *ExecutorConfig,
ie sqlutil.InternalExecutor,
descsCol *descs.Collection,
txn *kv.Txn,
member security.SQLUsername,
) (map[security.SQLUsername]bool, error) {
if txn == nil || !txn.IsOpen() {
return nil, errors.AssertionFailedf("cannot use MemberOfWithAdminoption without a txn")
}
roleMembersCache := execCfg.RoleMemberCache
// Lookup table version.
_, tableDesc, err := descsCol.GetImmutableTableByName(
ctx,
txn,
&roleMembersTableName,
tree.ObjectLookupFlagsWithRequired(),
)
if err != nil {
return nil, err
}
tableVersion := tableDesc.GetVersion()
if tableDesc.IsUncommittedVersion() {
return resolveMemberOfWithAdminOption(ctx, member, ie, txn)
}
// We loop in case the table version changes while we're looking up memberships.
for {
// Check version and maybe clear cache while holding the mutex.
// We use a closure here so that we release the lock here, then keep
// going and re-lock if adding the looked-up entry.
userMapping, found := func() (userRoleMembership, bool) {
roleMembersCache.Lock()
defer roleMembersCache.Unlock()
if roleMembersCache.tableVersion != tableVersion {
// Update version and drop the map.
roleMembersCache.tableVersion = tableVersion
roleMembersCache.userCache = make(map[security.SQLUsername]userRoleMembership)
roleMembersCache.boundAccount.Empty(ctx)
}
userMapping, ok := roleMembersCache.userCache[member]
return userMapping, ok
}()
if found {
// Found: return.
return userMapping, nil
}
// Lookup memberships outside the lock.
memberships, err := resolveMemberOfWithAdminOption(ctx, member, ie, txn)
if err != nil {
return nil, err
}
finishedLoop := func() bool {
// Update membership.
roleMembersCache.Lock()
defer roleMembersCache.Unlock()
if roleMembersCache.tableVersion != tableVersion {
// Table version has changed while we were looking, unlock and start over.
tableVersion = roleMembersCache.tableVersion
return false
}
// Table version remains the same: update map, unlock, return.
sizeOfEntry := int64(len(member.Normalized()))
for m := range memberships {
sizeOfEntry += int64(len(m.Normalized()))
sizeOfEntry += memsize.Bool
}
if err := roleMembersCache.boundAccount.Grow(ctx, sizeOfEntry); err != nil {
// If there is no memory available to cache the entry, we can still
// proceed so that the query has a chance to succeed..
log.Ops.Warningf(ctx, "no memory available to cache role membership info: %v", err)
} else {
roleMembersCache.userCache[member] = memberships
}
return true
}()
if finishedLoop {
return memberships, nil
}
}
}
// resolveMemberOfWithAdminOption performs the actual recursive role membership lookup.
// TODO(mberhault): this is the naive way and performs a full lookup for each user,
// we could save detailed memberships (as opposed to fully expanded) and reuse them
// across users. We may then want to lookup more than just this user.
func resolveMemberOfWithAdminOption(
ctx context.Context, member security.SQLUsername, ie sqlutil.InternalExecutor, txn *kv.Txn,
) (map[security.SQLUsername]bool, error) {
ret := map[security.SQLUsername]bool{}
// Keep track of members we looked up.
visited := map[security.SQLUsername]struct{}{}
toVisit := []security.SQLUsername{member}
lookupRolesStmt := `SELECT "role", "isAdmin" FROM system.role_members WHERE "member" = $1`
for len(toVisit) > 0 {
// Pop first element.
m := toVisit[0]
toVisit = toVisit[1:]
if _, ok := visited[m]; ok {
continue
}
visited[m] = struct{}{}
it, err := ie.QueryIterator(
ctx, "expand-roles", txn, lookupRolesStmt, m.Normalized(),
)
if err != nil {
return nil, err
}
var ok bool
for ok, err = it.Next(ctx); ok; ok, err = it.Next(ctx) {
row := it.Cur()
roleName := tree.MustBeDString(row[0])
isAdmin := row[1].(*tree.DBool)
// system.role_members stores pre-normalized usernames.
role := security.MakeSQLUsernameFromPreNormalizedString(string(roleName))
ret[role] = bool(*isAdmin)
// We need to expand this role. Let the "pop" worry about already-visited elements.
toVisit = append(toVisit, role)
}
if err != nil {
return nil, err
}
}
return ret, nil
}
// HasRoleOption implements the AuthorizationAccessor interface.
func (p *planner) HasRoleOption(ctx context.Context, roleOption roleoption.Option) (bool, error) {
// Verify that the txn is valid in any case, so that
// we don't get the risk to say "OK" to root requests
// with an invalid API usage.
if p.txn == nil || !p.txn.IsOpen() {
return false, errors.AssertionFailedf("cannot use HasRoleOption without a txn")
}
user := p.SessionData().User()
if user.IsRootUser() || user.IsNodeUser() {
return true, nil
}
hasAdmin, err := p.HasAdminRole(ctx)
if err != nil {
return false, err
}
if hasAdmin {
// Superusers have all role privileges.
return true, nil
}
hasRolePrivilege, err := p.ExecCfg().InternalExecutor.QueryRowEx(
ctx, "has-role-option", p.Txn(),
sessiondata.InternalExecutorOverride{User: security.RootUserName()},
fmt.Sprintf(
`SELECT 1 from %s WHERE option = '%s' AND username = $1 LIMIT 1`,
sessioninit.RoleOptionsTableName, roleOption.String()), user.Normalized())
if err != nil {
return false, err
}
if len(hasRolePrivilege) != 0 {
return true, nil
}
return false, nil
}
// CheckRoleOption checks if the current user has roleOption and returns an
// insufficient privilege error if the user does not have roleOption.
func (p *planner) CheckRoleOption(ctx context.Context, roleOption roleoption.Option) error {
hasRoleOption, err := p.HasRoleOption(ctx, roleOption)
if err != nil {
return err
}
if !hasRoleOption {
return pgerror.Newf(pgcode.InsufficientPrivilege,
"user %s does not have %s privilege", p.User(), roleOption)
}
return nil
}
// ConnAuditingClusterSettingName is the name of the cluster setting
// for the cluster setting that enables pgwire-level connection audit
// logs.
//
// This name is defined here because it is needed in the telemetry
// counts in SetClusterSetting() and importing pgwire here would
// create a circular dependency.
const ConnAuditingClusterSettingName = "server.auth_log.sql_connections.enabled"
// AuthAuditingClusterSettingName is the name of the cluster setting
// for the cluster setting that enables pgwire-level authentication audit
// logs.
//
// This name is defined here because it is needed in the telemetry
// counts in SetClusterSetting() and importing pgwire here would
// create a circular dependency.
const AuthAuditingClusterSettingName = "server.auth_log.sql_sessions.enabled"
// MaxNumConnectionsClusterSettingName is the maximum number of SQL connections to the server allowed at a given time.
// none if 0
// unlimited if < 0
const MaxNumConnectionsClusterSettingName = "server.max_connections_per_gateway"
// shouldCheckPublicSchema indicates whether canCreateOnSchema should check
// CREATE privileges for the public schema.
type shouldCheckPublicSchema bool
const (
checkPublicSchema shouldCheckPublicSchema = true
skipCheckPublicSchema shouldCheckPublicSchema = false
)
// canCreateOnSchema returns whether a user has permission to create new objects
// on the specified schema. For `public` schemas, it checks if the user has
// CREATE privileges on the specified dbID. Note that skipCheckPublicSchema may
// be passed to skip this check, since some callers check this separately.
//
// Privileges on temporary schemas are not validated. This is the caller's
// responsibility.
func (p *planner) canCreateOnSchema(
ctx context.Context,
schemaID descpb.ID,
dbID descpb.ID,
user security.SQLUsername,
checkPublicSchema shouldCheckPublicSchema,
) error {
scDesc, err := p.Descriptors().GetImmutableSchemaByID(
ctx, p.Txn(), schemaID, tree.SchemaLookupFlags{Required: true})
if err != nil {
return err
}
switch kind := scDesc.SchemaKind(); kind {
case catalog.SchemaPublic:
// The public schema is valid to create in if the parent database is.
if !checkPublicSchema {
// The caller wishes to skip this check.
return nil
}
_, dbDesc, err := p.Descriptors().GetImmutableDatabaseByID(
ctx, p.Txn(), dbID, tree.DatabaseLookupFlags{Required: true})
if err != nil {
return err
}
return p.CheckPrivilegeForUser(ctx, dbDesc, privilege.CREATE, user)
case catalog.SchemaTemporary:
// Callers must check whether temporary schemas are valid to create in.
return nil
case catalog.SchemaVirtual:
return pgerror.Newf(pgcode.InsufficientPrivilege,
"cannot CREATE on schema %s", scDesc.GetName())
case catalog.SchemaUserDefined:
return p.CheckPrivilegeForUser(ctx, scDesc, privilege.CREATE, user)
default:
panic(errors.AssertionFailedf("unknown schema kind %d", kind))
}
}
func (p *planner) canResolveDescUnderSchema(
ctx context.Context, scDesc catalog.SchemaDescriptor, desc catalog.Descriptor,
) error {
// We can't always resolve temporary schemas by ID (for example in the temporary
// object cleaner which accesses temporary schemas not in the current session).
// To avoid an internal error, we just don't check usage on temporary tables.
if tbl, ok := desc.(catalog.TableDescriptor); ok && tbl.IsTemporary() {
return nil
}
switch kind := scDesc.SchemaKind(); kind {
case catalog.SchemaPublic, catalog.SchemaTemporary, catalog.SchemaVirtual:
// Anyone can resolve under temporary, public or virtual schemas.
return nil
case catalog.SchemaUserDefined:
return p.CheckPrivilegeForUser(ctx, scDesc, privilege.USAGE, p.User())
default:
panic(errors.AssertionFailedf("unknown schema kind %d", kind))
}
}
// checkCanAlterToNewOwner checks that the new owner exists and the current user
// has privileges to alter the owner of the object. If the current user is not
// a superuser, it also checks that they are a member of the new owner role.
func (p *planner) checkCanAlterToNewOwner(
ctx context.Context, desc catalog.MutableDescriptor, newOwner security.SQLUsername,
) error {
// Make sure the newOwner exists.
roleExists, err := RoleExists(ctx, p.ExecCfg(), p.Txn(), newOwner)
if err != nil {
return err
}
if !roleExists {
return pgerror.Newf(pgcode.UndefinedObject, "role/user %q does not exist", newOwner)
}
// If the user is a superuser, skip privilege checks.
hasAdmin, err := p.HasAdminRole(ctx)
if err != nil {
return err
}
if hasAdmin {
return nil
}
var objType string
switch desc.(type) {
case *typedesc.Mutable:
objType = "type"
case *tabledesc.Mutable:
objType = "table"
case *schemadesc.Mutable:
objType = "schema"
case *dbdesc.Mutable:
objType = "database"
default:
return errors.AssertionFailedf("unknown object descriptor type %v", desc)
}
hasOwnership, err := p.HasOwnership(ctx, desc)
if err != nil {
return err
}
if !hasOwnership {
return pgerror.Newf(pgcode.InsufficientPrivilege,
"must be owner of %s %s", tree.Name(objType), tree.Name(desc.GetName()))
}
// To alter the owner, you must also be a direct or indirect member of the new
// owning role.
if p.User() == newOwner {
return nil
}
memberOf, err := p.MemberOfWithAdminOption(ctx, p.User())
if err != nil {
return err
}
if _, ok := memberOf[newOwner]; ok {
return nil
}
return pgerror.Newf(pgcode.InsufficientPrivilege, "must be member of role %q", newOwner)
}
// HasOwnershipOnSchema checks if the current user has ownership on the schema.
// For schemas, we cannot always use HasOwnership as not every schema has a
// descriptor.
func (p *planner) HasOwnershipOnSchema(
ctx context.Context, schemaID descpb.ID, dbID descpb.ID,
) (bool, error) {
if dbID == keys.SystemDatabaseID {
// Only the node user has ownership over the system database.
return p.User().IsNodeUser(), nil
}
scDesc, err := p.Descriptors().GetImmutableSchemaByID(
ctx, p.Txn(), schemaID, tree.SchemaLookupFlags{Required: true},
)
if err != nil {
return false, err
}
hasOwnership := false
switch kind := scDesc.SchemaKind(); kind {
case catalog.SchemaPublic:
// admin is the owner of the public schema.
hasOwnership, err = p.UserHasAdminRole(ctx, p.User())
if err != nil {
return false, err
}
case catalog.SchemaVirtual:
// Cannot drop on virtual schemas.
case catalog.SchemaTemporary:
// The user owns all the temporary schemas that they created in the session.
hasOwnership = p.SessionData() != nil &&
p.SessionData().IsTemporarySchemaID(uint32(scDesc.GetID()))
case catalog.SchemaUserDefined:
hasOwnership, err = p.HasOwnership(ctx, scDesc)
if err != nil {
return false, err
}
default:
panic(errors.AssertionFailedf("unknown schema kind %d", kind))
}
return hasOwnership, nil
}
func (p *planner) HasViewActivityOrViewActivityRedactedRole(ctx context.Context) (bool, error) {
hasAdmin, err := p.HasAdminRole(ctx)
if err != nil {
return hasAdmin, err
}
if !hasAdmin {
hasViewActivity, err := p.HasRoleOption(ctx, roleoption.VIEWACTIVITY)
if err != nil {
return hasViewActivity, err
}
if !hasViewActivity {
hasViewActivityRedacted, err := p.HasRoleOption(ctx, roleoption.VIEWACTIVITYREDACTED)
if err != nil {
return hasViewActivityRedacted, err
}
if !hasViewActivityRedacted {
return false, nil
}
}
}
return true, nil
}