-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathgrant_role.go
223 lines (195 loc) · 7.09 KB
/
grant_role.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
// Copyright 2020 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"
"strings"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"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/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
)
// GrantRoleNode creates entries in the system.role_members table.
// This is called from GRANT <ROLE>
type GrantRoleNode struct {
roles []security.SQLUsername
members []security.SQLUsername
adminOption bool
run grantRoleRun
}
type grantRoleRun struct {
rowsAffected int
}
// GrantRole represents a GRANT ROLE statement.
func (p *planner) GrantRole(ctx context.Context, n *tree.GrantRole) (planNode, error) {
return p.GrantRoleNode(ctx, n)
}
func (p *planner) GrantRoleNode(ctx context.Context, n *tree.GrantRole) (*GrantRoleNode, error) {
sqltelemetry.IncIAMGrantCounter(n.AdminOption)
ctx, span := tracing.ChildSpan(ctx, n.StatementTag())
defer span.Finish()
hasAdminRole, err := p.HasAdminRole(ctx)
if err != nil {
return nil, err
}
// Check permissions on each role.
allRoles, err := p.MemberOfWithAdminOption(ctx, p.User())
if err != nil {
return nil, err
}
inputRoles := make([]security.SQLUsername, len(n.Roles))
inputMembers := make([]security.SQLUsername, len(n.Members))
for i, role := range n.Roles {
normalizedRole, err := security.MakeSQLUsernameFromUserInput(string(role), security.UsernameValidation)
if err != nil {
return nil, err
}
inputRoles[i] = normalizedRole
}
for i, member := range n.Members {
normalizedMember, err := security.MakeSQLUsernameFromUserInput(string(member), security.UsernameValidation)
if err != nil {
return nil, err
}
inputMembers[i] = normalizedMember
}
for _, r := range inputRoles {
// If the user is an admin, don't check if the user is allowed to add/drop
// roles in the role. However, if the role being modified is the admin role, then
// make sure the user is an admin with the admin option.
if hasAdminRole && !r.IsAdminRole() {
continue
}
if isAdmin, ok := allRoles[r]; !ok || !isAdmin {
if r.IsAdminRole() {
return nil, pgerror.Newf(pgcode.InsufficientPrivilege,
"%s is not a role admin for role %s", p.User(), r)
}
return nil, pgerror.Newf(pgcode.InsufficientPrivilege,
"%s is not a superuser or role admin for role %s", p.User(), r)
}
}
// Check that roles exist.
// TODO(mberhault): just like GRANT/REVOKE privileges, we fetch the list of all roles.
// This is wasteful when we have a LOT of roles compared to the number of roles being operated on.
roles, err := p.GetAllRoles(ctx)
if err != nil {
return nil, err
}
// NOTE: membership manipulation involving the "public" pseudo-role fails with
// "role public does not exist". This matches postgres behavior.
for _, r := range inputRoles {
if _, ok := roles[r]; !ok {
maybeOption := strings.ToUpper(r.Normalized())
for name := range roleoption.ByName {
if maybeOption == name {
return nil, errors.WithHintf(
pgerror.Newf(pgcode.UndefinedObject,
"role/user %s does not exist", r),
"%s is a role option, try using ALTER ROLE to change a role's options.", maybeOption)
}
}
return nil, pgerror.Newf(pgcode.UndefinedObject, "role/user %s does not exist", r)
}
}
for _, m := range inputMembers {
if _, ok := roles[m]; !ok {
return nil, pgerror.Newf(pgcode.UndefinedObject, "role/user %s does not exist", m)
}
}
// Given an acyclic directed membership graph, adding a new edge (grant.Member ∈ grant.Role)
// means checking whether we have an expanded relationship (grant.Role ∈ ... ∈ grant.Member)
// For each grant.Role, we lookup all the roles it is a member of.
// After adding a given edge (grant.Member ∈ grant.Role), we add the edge to the list as well.
allRoleMemberships := make(map[security.SQLUsername]map[security.SQLUsername]bool)
for _, r := range inputRoles {
allRoles, err := p.MemberOfWithAdminOption(ctx, r)
if err != nil {
return nil, err
}
allRoleMemberships[r] = allRoles
}
// Since we perform no queries here, check all role/member pairs for cycles.
// Only if there are no errors do we proceed to write them.
for _, r := range inputRoles {
for _, m := range inputMembers {
if r == m {
// self-cycle.
return nil, pgerror.Newf(pgcode.InvalidGrantOperation, "%s cannot be a member of itself", m)
}
// Check if grant.Role ∈ ... ∈ grant.Member
if memberOf, ok := allRoleMemberships[r]; ok {
if _, ok = memberOf[m]; ok {
return nil, pgerror.Newf(pgcode.InvalidGrantOperation,
"making %s a member of %s would create a cycle", m, r)
}
}
// Add the new membership. We don't care about the actual bool value.
if _, ok := allRoleMemberships[m]; !ok {
allRoleMemberships[m] = make(map[security.SQLUsername]bool)
}
allRoleMemberships[m][r] = false
}
}
return &GrantRoleNode{
roles: inputRoles,
members: inputMembers,
adminOption: n.AdminOption,
}, nil
}
func (n *GrantRoleNode) startExec(params runParams) error {
opName := "grant-role"
// Add memberships. Existing memberships are allowed.
// If admin option is false, we do not remove it from existing memberships.
memberStmt := `INSERT INTO system.role_members ("role", "member", "isAdmin") VALUES ($1, $2, $3) ON CONFLICT ("role", "member")`
if n.adminOption {
// admin option: true, set "isAdmin" even if the membership exists.
memberStmt += ` DO UPDATE SET "isAdmin" = true`
} else {
// admin option: false, do not clear it from existing memberships.
memberStmt += ` DO NOTHING`
}
var rowsAffected int
for _, r := range n.roles {
for _, m := range n.members {
affected, err := params.extendedEvalCtx.ExecCfg.InternalExecutor.ExecEx(
params.ctx,
opName,
params.p.txn,
sessiondata.InternalExecutorOverride{User: security.RootUserName()},
memberStmt,
r.Normalized(), m.Normalized(), n.adminOption,
)
if err != nil {
return err
}
rowsAffected += affected
}
}
// We need to bump the table version to trigger a refresh if anything changed.
if rowsAffected > 0 {
if err := params.p.BumpRoleMembershipTableVersion(params.ctx); err != nil {
return err
}
}
n.run.rowsAffected += rowsAffected
return nil
}
// Next implements the planNode interface.
func (*GrantRoleNode) Next(runParams) (bool, error) { return false, nil }
// Values implements the planNode interface.
func (*GrantRoleNode) Values() tree.Datums { return tree.Datums{} }
// Close implements the planNode interface.
func (*GrantRoleNode) Close(context.Context) {}