-
Notifications
You must be signed in to change notification settings - Fork 399
/
grant_helpers.go
392 lines (345 loc) · 10.3 KB
/
grant_helpers.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
package resources
import (
"bytes"
"database/sql"
"encoding/csv"
"fmt"
"reflect"
"strings"
"time"
"github.com/chanzuckerberg/terraform-provider-snowflake/pkg/snowflake"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/jmoiron/sqlx"
)
// TerraformGrantResource augments terraform's *schema.Resource with extra context
type TerraformGrantResource struct {
Resource *schema.Resource
ValidPrivs PrivilegeSet
}
type TerraformGrantResources map[string]*TerraformGrantResource
func (t TerraformGrantResources) GetTfSchemas() map[string]*schema.Resource {
out := map[string]*schema.Resource{}
for name, grant := range t {
out[name] = grant.Resource
}
return out
}
const (
grantIDDelimiter = '|'
)
// currentGrant represents a generic grant of a privilege from a grant (the target) to a
// grantee. This type can be used in conjunction with github.com/jmoiron/sqlx to
// build a nice go representation of a grant
type currentGrant struct {
CreatedOn time.Time `db:"created_on"`
Privilege string `db:"privilege"`
GrantType string `db:"granted_on"`
GrantName string `db:"name"`
GranteeType string `db:"granted_to"`
GranteeName string `db:"grantee_name"`
GrantOption bool `db:"grant_option"`
GrantedBy string `db:"granted_by"`
}
// futureGrant represents the columns in the response from `SHOW FUTURE GRANTS
// IN SCHEMA...` and can be used in conjunction with sqlx.
type futureGrant struct {
CreatedOn time.Time `db:"created_on"`
Privilege string `db:"privilege"`
GrantType string `db:"grant_on"`
GrantName string `db:"name"`
GranteeType string `db:"grant_to"`
GranteeName string `db:"grantee_name"`
GrantOption bool `db:"grant_option"`
}
// grant is simply the least common denominator of fields in currentGrant and
// futureGrant.
type grant struct {
CreatedOn time.Time
Privilege string
GrantType string
GrantName string
GranteeType string
GranteeName string
GrantOption bool
}
// grantID contains identifying elements that allow unique access privileges
type grantID struct {
ResourceName string
SchemaName string
ObjectName string
Privilege string
GrantOption bool
}
// String() takes in a grantID object and returns a pipe-delimited string:
// resourceName|schemaName|ObjectName|Privilege|GrantOption
func (gi *grantID) String() (string, error) {
var buf bytes.Buffer
csvWriter := csv.NewWriter(&buf)
csvWriter.Comma = grantIDDelimiter
grantOption := fmt.Sprintf("%v", gi.GrantOption)
dataIdentifiers := [][]string{{gi.ResourceName, gi.SchemaName, gi.ObjectName, gi.Privilege, grantOption}}
err := csvWriter.WriteAll(dataIdentifiers)
if err != nil {
return "", err
}
strGrantID := strings.TrimSpace(buf.String())
return strGrantID, nil
}
// grantIDFromString() takes in a pipe-delimited string: resourceName|schemaName|ObjectName|Privilege
// and returns a grantID object
func grantIDFromString(stringID string) (*grantID, error) {
reader := csv.NewReader(strings.NewReader(stringID))
reader.Comma = grantIDDelimiter
lines, err := reader.ReadAll()
if err != nil {
return nil, fmt.Errorf("Not CSV compatible")
}
if len(lines) != 1 {
return nil, fmt.Errorf("1 line per grant")
}
if len(lines[0]) != 4 && len(lines[0]) != 5 {
return nil, fmt.Errorf("4 or 5 fields allowed")
}
grantOption := false
if len(lines[0]) == 5 && lines[0][4] == "true" {
grantOption = true
}
grantResult := &grantID{
ResourceName: lines[0][0],
SchemaName: lines[0][1],
ObjectName: lines[0][2],
Privilege: lines[0][3],
GrantOption: grantOption,
}
return grantResult, nil
}
func createGenericGrant(d *schema.ResourceData, meta interface{}, builder snowflake.GrantBuilder) error {
db := meta.(*sql.DB)
priv := d.Get("privilege").(string)
grantOption := d.Get("with_grant_option").(bool)
roles, shares := expandRolesAndShares(d)
if len(roles)+len(shares) == 0 {
return fmt.Errorf("no roles or shares specified for this grant")
}
for _, role := range roles {
err := snowflake.Exec(db, builder.Role(role).Grant(priv, grantOption))
if err != nil {
return err
}
}
for _, share := range shares {
err := snowflake.Exec(db, builder.Share(share).Grant(priv, grantOption))
if err != nil {
return err
}
}
return nil
}
func readGenericGrant(
d *schema.ResourceData,
meta interface{},
schema map[string]*schema.Schema,
builder snowflake.GrantBuilder,
futureObjects bool,
validPrivileges PrivilegeSet) error {
db := meta.(*sql.DB)
var grants []*grant
var err error
if futureObjects {
grants, err = readGenericFutureGrants(db, builder)
} else {
grants, err = readGenericCurrentGrants(db, builder)
}
if err != nil {
return err
}
priv := d.Get("privilege").(string)
grantOption := d.Get("with_grant_option").(bool)
// This is the only way how I can test that this function is reading VIEW grants or TABLE grants
// is checking what kind of builder we have. If it is future grant, then I double check if the
// privilegeSet has only one member - SELECT - then it is a VIEW, if it has 6 members and contains
// Truncate then it must be Table
futureGrantOnViews := false
futureGrantOnTables := false
if reflect.TypeOf(builder) == reflect.TypeOf(&snowflake.FutureGrantBuilder{}) {
if _, ok := validPrivileges[privilegeSelect]; ok && len(validPrivileges) == 1 {
futureGrantOnViews = true
}
if _, ok := validPrivileges[privilegeTruncate]; ok && len(validPrivileges) == 6 {
futureGrantOnTables = true
}
}
// Map of roles to privileges
rolePrivileges := map[string]PrivilegeSet{}
sharePrivileges := map[string]PrivilegeSet{}
// List of all grants for each schema_database
for _, grant := range grants {
switch grant.GranteeType {
case "ROLE":
roleName := grant.GranteeName
// Find set of privileges
privileges, ok := rolePrivileges[roleName]
if !ok {
// If not there, create an empty set
privileges = PrivilegeSet{}
}
// Add privilege to the set but consider valid privileges only
// for VIEW in ReadViewGrant
// and for non-VIEW in ReadTableGrant
if futureGrantOnViews || futureGrantOnTables {
if (futureGrantOnViews && grant.GrantType == "VIEW") || (futureGrantOnTables && grant.GrantType == "TABLE") {
privileges.addString(grant.Privilege)
}
} else { // Other grants
privileges.addString(grant.Privilege)
}
// Reassign set back
rolePrivileges[roleName] = privileges
case "SHARE":
granteeNameStrippedAccount := StripAccountFromName(grant.GranteeName)
// Find set of privileges
privileges, ok := sharePrivileges[granteeNameStrippedAccount]
if !ok {
// If not there, create an empty set
privileges = PrivilegeSet{}
}
// Add privilege to the set
privileges.addString(grant.Privilege)
// Reassign set back
sharePrivileges[granteeNameStrippedAccount] = privileges
default:
return fmt.Errorf("unknown grantee type %s", grant.GranteeType)
}
}
var roles, shares []string
// Now see which roles have our privilege
for roleName, privileges := range rolePrivileges {
// Where priv is not all so it should match exactly
if privileges.hasString(priv) {
roles = append(roles, roleName)
}
}
// Now see which shares have our privilege
for shareName, privileges := range sharePrivileges {
// Where priv is not all so it should match exactly
if privileges.hasString(priv) {
shares = append(shares, shareName)
}
}
err = d.Set("privilege", priv)
if err != nil {
return err
}
err = d.Set("roles", roles)
if err != nil {
return err
}
_, sharesOk := schema["shares"]
if sharesOk && !futureObjects {
err = d.Set("shares", shares)
if err != nil {
return err
}
}
err = d.Set("with_grant_option", grantOption)
if err != nil {
return err
}
return nil
}
func readGenericCurrentGrants(db *sql.DB, builder snowflake.GrantBuilder) ([]*grant, error) {
stmt := builder.Show()
rows, err := snowflake.Query(db, stmt)
if err != nil {
return nil, err
}
defer rows.Close()
var grants []*grant
for rows.Next() {
currentGrant := ¤tGrant{}
err := rows.StructScan(currentGrant)
if err != nil {
return nil, err
}
if currentGrant.GrantedBy == "" {
// If GrantedBy is empty string, terraform can't
// manage the grant because the grant is a default
// grant seeded by Snowflake.
continue
}
grant := &grant{
CreatedOn: currentGrant.CreatedOn,
Privilege: currentGrant.Privilege,
GrantType: currentGrant.GrantType,
GrantName: currentGrant.GrantName,
GranteeType: currentGrant.GranteeType,
GranteeName: currentGrant.GranteeName,
GrantOption: currentGrant.GrantOption,
}
grants = append(grants, grant)
}
return grants, nil
}
func readGenericFutureGrants(db *sql.DB, builder snowflake.GrantBuilder) ([]*grant, error) {
conn := sqlx.NewDb(db, "snowflake")
stmt := builder.Show()
rows, err := conn.Queryx(stmt)
if err != nil {
return nil, err
}
defer rows.Close()
var grants []*grant
for rows.Next() {
futureGrant := &futureGrant{}
err := rows.StructScan(futureGrant)
if err != nil {
return nil, err
}
grant := &grant{
CreatedOn: futureGrant.CreatedOn,
Privilege: futureGrant.Privilege,
GrantType: futureGrant.GrantType,
GrantName: futureGrant.GrantName,
GranteeType: futureGrant.GranteeType,
GranteeName: futureGrant.GranteeName,
GrantOption: futureGrant.GrantOption,
}
grants = append(grants, grant)
}
return grants, nil
}
func deleteGenericGrant(d *schema.ResourceData, meta interface{}, builder snowflake.GrantBuilder) error {
db := meta.(*sql.DB)
priv := d.Get("privilege").(string)
var roles, shares []string
if _, ok := d.GetOk("roles"); ok {
roles = expandStringList(d.Get("roles").(*schema.Set).List())
}
if _, ok := d.GetOk("shares"); ok {
shares = expandStringList(d.Get("shares").(*schema.Set).List())
}
for _, role := range roles {
err := snowflake.Exec(db, builder.Role(role).Revoke(priv))
if err != nil {
return err
}
}
for _, share := range shares {
err := snowflake.Exec(db, builder.Share(share).Revoke(priv))
if err != nil {
return err
}
}
d.SetId("")
return nil
}
func expandRolesAndShares(d *schema.ResourceData) ([]string, []string) {
var roles, shares []string
if _, ok := d.GetOk("roles"); ok {
roles = expandStringList(d.Get("roles").(*schema.Set).List())
}
if _, ok := d.GetOk("shares"); ok {
shares = expandStringList(d.Get("shares").(*schema.Set).List())
}
return roles, shares
}