-
Notifications
You must be signed in to change notification settings - Fork 424
/
grant_privileges_to_database_role.go
943 lines (849 loc) · 30.5 KB
/
grant_privileges_to_database_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
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
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
package resources
import (
"context"
"database/sql"
"fmt"
"slices"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
// TODO: Handle IMPORTED PRIVILEGES privilege (after second account will be added - SNOW-976501)
var grantPrivilegesToDatabaseRoleSchema = map[string]*schema.Schema{
"database_role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The fully qualified name of the database role to which privileges will be granted.",
ValidateDiagFunc: IsValidIdentifier[sdk.DatabaseObjectIdentifier](),
},
"privileges": {
Type: schema.TypeSet,
Optional: true,
Description: "The privileges to grant on the database role.",
ExactlyOneOf: []string{
"privileges",
"all_privileges",
},
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateDiagFunc: isNotOwnershipGrant(),
},
},
"all_privileges": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Grant all privileges on the database role.",
ExactlyOneOf: []string{
"privileges",
"all_privileges",
},
},
"with_grant_option": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Description: "If specified, allows the recipient role to grant the privileges to other roles.",
},
"always_apply": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "If true, the resource will always produce a “plan” and on “apply” it will re-grant defined privileges. It is supposed to be used only in “grant privileges on all X’s in database / schema Y” or “grant all privileges to X” scenarios to make sure that every new object in a given database / schema is granted by the account role and every new privilege is granted to the database role. Important note: this flag is not compliant with the Terraform assumptions of the config being eventually convergent (producing an empty plan).",
},
"always_apply_trigger": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "This is a helper field and should not be set. Its main purpose is to help to achieve the functionality described by the always_apply field.",
},
"on_database": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The fully qualified name of the database on which privileges will be granted.",
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
ExactlyOneOf: []string{
"on_database",
"on_schema",
"on_schema_object",
},
},
"on_schema": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Specifies the schema on which privileges will be granted.",
MaxItems: 1,
ExactlyOneOf: []string{
"on_database",
"on_schema",
"on_schema_object",
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"schema_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The fully qualified name of the schema.",
ValidateDiagFunc: IsValidIdentifier[sdk.DatabaseObjectIdentifier](),
ExactlyOneOf: []string{
"on_schema.0.schema_name",
"on_schema.0.all_schemas_in_database",
"on_schema.0.future_schemas_in_database",
},
},
"all_schemas_in_database": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The fully qualified name of the database.",
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
ExactlyOneOf: []string{
"on_schema.0.schema_name",
"on_schema.0.all_schemas_in_database",
"on_schema.0.future_schemas_in_database",
},
},
"future_schemas_in_database": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The fully qualified name of the database.",
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
ExactlyOneOf: []string{
"on_schema.0.schema_name",
"on_schema.0.all_schemas_in_database",
"on_schema.0.future_schemas_in_database",
},
},
},
},
},
"on_schema_object": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Specifies the schema object on which privileges will be granted.",
MaxItems: 1,
ExactlyOneOf: []string{
"on_database",
"on_schema",
"on_schema_object",
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"object_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The object type of the schema object on which privileges will be granted. Valid values are: ALERT | DYNAMIC TABLE | EVENT TABLE | FILE FORMAT | FUNCTION | PROCEDURE | SECRET | SEQUENCE | PIPE | MASKING POLICY | PASSWORD POLICY | ROW ACCESS POLICY | SESSION POLICY | TAG | STAGE | STREAM | TABLE | EXTERNAL TABLE | TASK | VIEW | MATERIALIZED VIEW | NETWORK RULE | PACKAGES POLICY | ICEBERG TABLE",
RequiredWith: []string{
"on_schema_object.0.object_name",
},
ConflictsWith: []string{
"on_schema_object.0.all",
"on_schema_object.0.future",
},
ValidateDiagFunc: ValidGrantedObjectType(),
},
"object_name": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: "The fully qualified name of the object on which privileges will be granted.",
RequiredWith: []string{
"on_schema_object.0.object_type",
},
ExactlyOneOf: []string{
"on_schema_object.0.object_name",
"on_schema_object.0.all",
"on_schema_object.0.future",
},
ValidateDiagFunc: IsValidIdentifier[sdk.SchemaObjectIdentifier](),
},
"all": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Configures the privilege to be granted on all objects in either a database or schema.",
MaxItems: 1,
Elem: &schema.Resource{
Schema: grantPrivilegesOnDatabaseRoleBulkOperationSchema,
},
ConflictsWith: []string{
"on_schema_object.0.object_type",
},
ExactlyOneOf: []string{
"on_schema_object.0.object_name",
"on_schema_object.0.all",
"on_schema_object.0.future",
},
},
"future": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Configures the privilege to be granted on future objects in either a database or schema.",
MaxItems: 1,
Elem: &schema.Resource{
Schema: grantPrivilegesOnDatabaseRoleBulkOperationSchema,
},
ConflictsWith: []string{
"on_schema_object.0.object_type",
},
ExactlyOneOf: []string{
"on_schema_object.0.object_name",
"on_schema_object.0.all",
"on_schema_object.0.future",
},
},
},
},
},
}
var grantPrivilegesOnDatabaseRoleBulkOperationSchema = map[string]*schema.Schema{
"object_type_plural": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The plural object type of the schema object on which privileges will be granted. Valid values are: ALERTS | DYNAMIC TABLES | EVENT TABLES | FILE FORMATS | FUNCTIONS | PROCEDURES | SECRETS | SEQUENCES | PIPES | MASKING POLICIES | PASSWORD POLICIES | ROW ACCESS POLICIES | SESSION POLICIES | TAGS | STAGES | STREAMS | TABLES | EXTERNAL TABLES | TASKS | VIEWS | MATERIALIZED VIEWS | NETWORK RULES | PACKAGES POLICIES | ICEBERG TABLES",
ValidateDiagFunc: ValidGrantedPluralObjectType(),
},
"in_database": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
},
"in_schema": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateDiagFunc: IsValidIdentifier[sdk.DatabaseObjectIdentifier](),
},
}
func GrantPrivilegesToDatabaseRole() *schema.Resource {
return &schema.Resource{
CreateContext: CreateGrantPrivilegesToDatabaseRole,
UpdateContext: UpdateGrantPrivilegesToDatabaseRole,
DeleteContext: DeleteGrantPrivilegesToDatabaseRole,
ReadContext: ReadGrantPrivilegesToDatabaseRole,
Schema: grantPrivilegesToDatabaseRoleSchema,
Importer: &schema.ResourceImporter{
StateContext: ImportGrantPrivilegesToDatabaseRole,
},
}
}
func ImportGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceData, meta any) ([]*schema.ResourceData, error) {
id, err := ParseGrantPrivilegesToDatabaseRoleId(d.Id())
if err != nil {
return nil, err
}
if err := d.Set("database_role_name", id.DatabaseRoleName.FullyQualifiedName()); err != nil {
return nil, err
}
if err := d.Set("with_grant_option", id.WithGrantOption); err != nil {
return nil, err
}
if err := d.Set("always_apply", id.AlwaysApply); err != nil {
return nil, err
}
if err := d.Set("all_privileges", id.AllPrivileges); err != nil {
return nil, err
}
if err := d.Set("privileges", id.Privileges); err != nil {
return nil, err
}
switch id.Kind {
case OnDatabaseDatabaseRoleGrantKind:
if err := d.Set("on_database", id.Data.(*OnDatabaseGrantData).DatabaseName.FullyQualifiedName()); err != nil {
return nil, err
}
case OnSchemaDatabaseRoleGrantKind:
data := id.Data.(*OnSchemaGrantData)
onSchema := make(map[string]any)
switch data.Kind {
case OnSchemaSchemaGrantKind:
onSchema["schema_name"] = data.SchemaName.FullyQualifiedName()
case OnAllSchemasInDatabaseSchemaGrantKind:
onSchema["all_schemas_in_database"] = data.DatabaseName.FullyQualifiedName()
case OnFutureSchemasInDatabaseSchemaGrantKind:
onSchema["future_schemas_in_database"] = data.DatabaseName.FullyQualifiedName()
}
if err := d.Set("on_schema", []any{onSchema}); err != nil {
return nil, err
}
case OnSchemaObjectDatabaseRoleGrantKind:
data := id.Data.(*OnSchemaObjectGrantData)
onSchemaObject := make(map[string]any)
switch data.Kind {
case OnObjectSchemaObjectGrantKind:
onSchemaObject["object_type"] = data.Object.ObjectType.String()
onSchemaObject["object_name"] = data.Object.Name.FullyQualifiedName()
case OnAllSchemaObjectGrantKind:
onAll := make(map[string]any)
onAll["object_type_plural"] = data.OnAllOrFuture.ObjectNamePlural.String()
switch data.OnAllOrFuture.Kind {
case InDatabaseBulkOperationGrantKind:
onAll["in_database"] = data.OnAllOrFuture.Database.FullyQualifiedName()
case InSchemaBulkOperationGrantKind:
onAll["in_schema"] = data.OnAllOrFuture.Schema.FullyQualifiedName()
}
onSchemaObject["all"] = []any{onAll}
case OnFutureSchemaObjectGrantKind:
onFuture := make(map[string]any)
onFuture["object_type_plural"] = data.OnAllOrFuture.ObjectNamePlural.String()
switch data.OnAllOrFuture.Kind {
case InDatabaseBulkOperationGrantKind:
onFuture["in_database"] = data.OnAllOrFuture.Database.FullyQualifiedName()
case InSchemaBulkOperationGrantKind:
onFuture["in_schema"] = data.OnAllOrFuture.Schema.FullyQualifiedName()
}
onSchemaObject["future"] = []any{onFuture}
}
if err := d.Set("on_schema_object", []any{onSchemaObject}); err != nil {
return nil, err
}
}
return []*schema.ResourceData{d}, nil
}
func CreateGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
db := meta.(*sql.DB)
client := sdk.NewClientFromDB(db)
id := createGrantPrivilegesToDatabaseRoleIdFromSchema(d)
err := client.Grants.GrantPrivilegesToDatabaseRole(
ctx,
getDatabaseRolePrivilegesFromSchema(d),
getDatabaseRoleGrantOn(d),
sdk.NewDatabaseObjectIdentifierFromFullyQualifiedName(d.Get("database_role_name").(string)),
&sdk.GrantPrivilegesToDatabaseRoleOptions{
WithGrantOption: sdk.Bool(d.Get("with_grant_option").(bool)),
},
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "An error occurred when granting privileges to database role",
Detail: fmt.Sprintf("Id: %s\nDatabase role name: %s\nError: %s", id.String(), id.DatabaseRoleName, err.Error()),
},
}
}
d.SetId(id.String())
return ReadGrantPrivilegesToDatabaseRole(ctx, d, meta)
}
func UpdateGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
db := meta.(*sql.DB)
client := sdk.NewClientFromDB(db)
id, err := ParseGrantPrivilegesToDatabaseRoleId(d.Id())
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to parse internal identifier",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
// handle all_privileges -> privileges change (revoke all privileges)
if d.HasChange("all_privileges") {
_, allPrivileges := d.GetChange("all_privileges")
if !allPrivileges.(bool) {
err = client.Grants.RevokePrivilegesFromDatabaseRole(ctx, &sdk.DatabaseRoleGrantPrivileges{
AllPrivileges: sdk.Bool(true),
},
getDatabaseRoleGrantOn(d),
id.DatabaseRoleName,
new(sdk.RevokePrivilegesFromDatabaseRoleOptions),
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to revoke all privileges",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
}
id.AllPrivileges = allPrivileges.(bool)
}
if d.HasChange("privileges") {
shouldHandlePrivilegesChange := true
// Skip if all_privileges was set to true
if d.HasChange("all_privileges") {
if _, allPrivileges := d.GetChange("all_privileges"); allPrivileges.(bool) {
shouldHandlePrivilegesChange = false
id.Privileges = []string{}
}
}
if shouldHandlePrivilegesChange {
before, after := d.GetChange("privileges")
privilegesBeforeChange := expandStringList(before.(*schema.Set).List())
privilegesAfterChange := expandStringList(after.(*schema.Set).List())
var privilegesToAdd, privilegesToRemove []string
for _, privilegeBeforeChange := range privilegesBeforeChange {
if !slices.Contains(privilegesAfterChange, privilegeBeforeChange) {
privilegesToRemove = append(privilegesToRemove, privilegeBeforeChange)
}
}
for _, privilegeAfterChange := range privilegesAfterChange {
if !slices.Contains(privilegesBeforeChange, privilegeAfterChange) {
privilegesToAdd = append(privilegesToAdd, privilegeAfterChange)
}
}
grantOn := getDatabaseRoleGrantOn(d)
if len(privilegesToAdd) > 0 {
err = client.Grants.GrantPrivilegesToDatabaseRole(
ctx,
getDatabaseRolePrivileges(
false,
privilegesToAdd,
id.Kind == OnDatabaseDatabaseRoleGrantKind,
id.Kind == OnSchemaDatabaseRoleGrantKind,
id.Kind == OnSchemaObjectDatabaseRoleGrantKind,
),
grantOn,
id.DatabaseRoleName,
new(sdk.GrantPrivilegesToDatabaseRoleOptions),
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to grant added privileges",
Detail: fmt.Sprintf("Id: %s\nPrivileges to add: %v\nError: %s", d.Id(), privilegesToAdd, err.Error()),
},
}
}
}
if len(privilegesToRemove) > 0 {
err = client.Grants.RevokePrivilegesFromDatabaseRole(
ctx,
getDatabaseRolePrivileges(
false,
privilegesToRemove,
id.Kind == OnDatabaseDatabaseRoleGrantKind,
id.Kind == OnSchemaDatabaseRoleGrantKind,
id.Kind == OnSchemaObjectDatabaseRoleGrantKind,
),
grantOn,
id.DatabaseRoleName,
new(sdk.RevokePrivilegesFromDatabaseRoleOptions),
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to revoke removed privileges",
Detail: fmt.Sprintf("Id: %s\nPrivileges to remove: %v\nError: %s", d.Id(), privilegesToRemove, err.Error()),
},
}
}
}
id.Privileges = privilegesAfterChange
}
}
// handle privileges -> all_privileges change (grant all privileges)
if d.HasChange("all_privileges") {
_, allPrivileges := d.GetChange("all_privileges")
if allPrivileges.(bool) {
err = client.Grants.GrantPrivilegesToDatabaseRole(ctx, &sdk.DatabaseRoleGrantPrivileges{
AllPrivileges: sdk.Bool(true),
},
getDatabaseRoleGrantOn(d),
id.DatabaseRoleName,
new(sdk.GrantPrivilegesToDatabaseRoleOptions),
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to grant all privileges",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
}
id.AllPrivileges = allPrivileges.(bool)
}
if d.HasChange("always_apply") {
id.AlwaysApply = d.Get("always_apply").(bool)
}
if id.AlwaysApply {
err := client.Grants.GrantPrivilegesToDatabaseRole(
ctx,
getDatabaseRolePrivilegesFromSchema(d),
getDatabaseRoleGrantOn(d),
id.DatabaseRoleName,
&sdk.GrantPrivilegesToDatabaseRoleOptions{
WithGrantOption: &id.WithGrantOption,
},
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Always apply. An error occurred when granting privileges to database role",
Detail: fmt.Sprintf("Id: %s\nDatabase role name: %s\nError: %s", d.Id(), id.DatabaseRoleName, err.Error()),
},
}
}
}
d.SetId(id.String())
return ReadGrantPrivilegesToDatabaseRole(ctx, d, meta)
}
func DeleteGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
db := meta.(*sql.DB)
client := sdk.NewClientFromDB(db)
id, err := ParseGrantPrivilegesToDatabaseRoleId(d.Id())
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to parse internal identifier",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
err = client.Grants.RevokePrivilegesFromDatabaseRole(
ctx,
getDatabaseRolePrivilegesFromSchema(d),
getDatabaseRoleGrantOn(d),
id.DatabaseRoleName,
&sdk.RevokePrivilegesFromDatabaseRoleOptions{},
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "An error occurred when revoking privileges from database role",
Detail: fmt.Sprintf("Id: %s\nDatabase role name: %s\nError: %s", d.Id(), id.DatabaseRoleName, err.Error()),
},
}
}
d.SetId("")
return nil
}
func ReadGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
id, err := ParseGrantPrivilegesToDatabaseRoleId(d.Id())
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to parse internal identifier",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
if id.AlwaysApply {
// The Trigger is a string rather than boolean that would be flipped on every terraform apply
// because it's easier to think about and not to worry about edge cases that may occur with 1bit values.
// The only place to have the "flip" is Read operation, because there we can set value and produce a plan
// that later on will be executed in the Update operation.
//
// The following example shows that we can end up with the same value as before, which may lead to empty plans:
// 1. Create configuration with always_apply = false (let's say trigger will be false by default)
// 2. terraform apply: Create (Read will update it to false)
// 3. Update config so that always_apply = true
// 4. terraform apply: Read (updated trigger to false) -> change is not detected (no plan; no Update)
triggerId, err := uuid.GenerateUUID()
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to generate UUID",
Detail: fmt.Sprintf("Original error: %s", err.Error()),
},
}
}
// Change the value of always_apply_trigger to produce a plan
if err := d.Set("always_apply_trigger", triggerId); err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Error setting always_apply_trigger for database role",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
}
if id.AllPrivileges {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Show with all_privileges option is skipped.",
// TODO: link to the design decisions doc (SNOW-990811)
Detail: "See our document on design decisions for grants: <LINK (coming soon)>",
},
}
}
opts, grantedOn, diags := prepareShowGrantsRequest(id)
if len(diags) != 0 {
return diags
}
db := meta.(*sql.DB)
client := sdk.NewClientFromDB(db)
grants, err := client.Grants.Show(ctx, opts)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to retrieve grants",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err.Error()),
},
}
}
var privileges []string
for _, grant := range grants {
// Accept only DATABASE ROLEs
if grant.GrantTo != sdk.ObjectTypeDatabaseRole && grant.GrantedTo != sdk.ObjectTypeDatabaseRole {
continue
}
// Only consider privileges that are already present in the ID, so we
// don't delete privileges managed by other resources.
if !slices.Contains(id.Privileges, grant.Privilege) {
continue
}
if id.WithGrantOption == grant.GrantOption && id.DatabaseRoleName.Name() == grant.GranteeName.Name() {
// Future grants do not have grantedBy, only current grants do.
// If grantedby is an empty string, it means terraform could not have created the grant
if (opts.Future == nil || !*opts.Future) && grant.GrantedBy.Name() == "" {
continue
}
// grant_on is for future grants, granted_on is for current grants.
// They function the same way though in a test for matching the object type
if grantedOn == grant.GrantedOn || grantedOn == grant.GrantOn {
privileges = append(privileges, grant.Privilege)
}
}
}
if err := d.Set("privileges", privileges); err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Error setting privileges for database role",
Detail: fmt.Sprintf("Id: %s\nPrivileges: %v\nError: %s", d.Id(), privileges, err.Error()),
},
}
}
return nil
}
func prepareShowGrantsRequest(id GrantPrivilegesToDatabaseRoleId) (*sdk.ShowGrantOptions, sdk.ObjectType, diag.Diagnostics) {
opts := new(sdk.ShowGrantOptions)
var grantedOn sdk.ObjectType
switch id.Kind {
case OnDatabaseDatabaseRoleGrantKind:
grantedOn = sdk.ObjectTypeDatabase
data := id.Data.(*OnDatabaseGrantData)
opts.On = &sdk.ShowGrantsOn{
Object: &sdk.Object{
ObjectType: sdk.ObjectTypeDatabase,
Name: data.DatabaseName,
},
}
case OnSchemaDatabaseRoleGrantKind:
grantedOn = sdk.ObjectTypeSchema
data := id.Data.(*OnSchemaGrantData)
switch data.Kind {
case OnSchemaSchemaGrantKind:
opts.On = &sdk.ShowGrantsOn{
Object: &sdk.Object{
ObjectType: sdk.ObjectTypeSchema,
Name: data.SchemaName,
},
}
case OnAllSchemasInDatabaseSchemaGrantKind:
return nil, "", diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Show with OnAllSchemasInDatabase option is skipped.",
// TODO: link to the design decisions doc (SNOW-990811)
Detail: "See our document on design decisions for grants: <LINK (coming soon)>",
},
}
case OnFutureSchemasInDatabaseSchemaGrantKind:
opts.Future = sdk.Bool(true)
opts.In = &sdk.ShowGrantsIn{
Database: data.DatabaseName,
}
}
case OnSchemaObjectDatabaseRoleGrantKind:
data := id.Data.(*OnSchemaObjectGrantData)
switch data.Kind {
case OnObjectSchemaObjectGrantKind:
grantedOn = data.Object.ObjectType
opts.On = &sdk.ShowGrantsOn{
Object: data.Object,
}
case OnAllSchemaObjectGrantKind:
return nil, "", diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Show with OnAll option is skipped.",
// TODO: link to the design decisions doc (SNOW-990811)
Detail: "See our document on design decisions for grants: <LINK (coming soon)>",
},
}
case OnFutureSchemaObjectGrantKind:
grantedOn = data.OnAllOrFuture.ObjectNamePlural.Singular()
opts.Future = sdk.Bool(true)
switch data.OnAllOrFuture.Kind {
case InDatabaseBulkOperationGrantKind:
opts.In = &sdk.ShowGrantsIn{
Database: data.OnAllOrFuture.Database,
}
case InSchemaBulkOperationGrantKind:
opts.In = &sdk.ShowGrantsIn{
Schema: data.OnAllOrFuture.Schema,
}
}
}
}
return opts, grantedOn, nil
}
func getDatabaseRolePrivilegesFromSchema(d *schema.ResourceData) *sdk.DatabaseRoleGrantPrivileges {
_, onDatabaseOk := d.GetOk("on_database")
_, onSchemaOk := d.GetOk("on_schema")
_, onSchemaObjectOk := d.GetOk("on_schema_object")
return getDatabaseRolePrivileges(
d.Get("all_privileges").(bool),
expandStringList(d.Get("privileges").(*schema.Set).List()),
onDatabaseOk,
onSchemaOk,
onSchemaObjectOk,
)
}
func getDatabaseRolePrivileges(allPrivileges bool, privileges []string, onDatabase bool, onSchema bool, onSchemaObject bool) *sdk.DatabaseRoleGrantPrivileges {
databaseRoleGrantPrivileges := new(sdk.DatabaseRoleGrantPrivileges)
if allPrivileges {
databaseRoleGrantPrivileges.AllPrivileges = sdk.Bool(true)
return databaseRoleGrantPrivileges
}
switch {
case onDatabase:
databasePrivileges := make([]sdk.AccountObjectPrivilege, len(privileges))
for i, privilege := range privileges {
databasePrivileges[i] = sdk.AccountObjectPrivilege(privilege)
}
databaseRoleGrantPrivileges.DatabasePrivileges = databasePrivileges
case onSchema:
schemaPrivileges := make([]sdk.SchemaPrivilege, len(privileges))
for i, privilege := range privileges {
schemaPrivileges[i] = sdk.SchemaPrivilege(privilege)
}
databaseRoleGrantPrivileges.SchemaPrivileges = schemaPrivileges
case onSchemaObject:
schemaObjectPrivileges := make([]sdk.SchemaObjectPrivilege, len(privileges))
for i, privilege := range privileges {
schemaObjectPrivileges[i] = sdk.SchemaObjectPrivilege(privilege)
}
databaseRoleGrantPrivileges.SchemaObjectPrivileges = schemaObjectPrivileges
}
return databaseRoleGrantPrivileges
}
func getDatabaseRoleGrantOn(d *schema.ResourceData) *sdk.DatabaseRoleGrantOn {
onDatabase, onDatabaseOk := d.GetOk("on_database")
onSchemaBlock, onSchemaOk := d.GetOk("on_schema")
onSchemaObjectBlock, onSchemaObjectOk := d.GetOk("on_schema_object")
on := new(sdk.DatabaseRoleGrantOn)
switch {
case onDatabaseOk:
on.Database = sdk.Pointer(sdk.NewAccountObjectIdentifierFromFullyQualifiedName(onDatabase.(string)))
case onSchemaOk:
onSchema := onSchemaBlock.([]any)[0].(map[string]any)
grantOnSchema := new(sdk.GrantOnSchema)
schemaName := onSchema["schema_name"].(string)
schemaNameOk := len(schemaName) > 0
allSchemasInDatabase := onSchema["all_schemas_in_database"].(string)
allSchemasInDatabaseOk := len(allSchemasInDatabase) > 0
futureSchemasInDatabase := onSchema["future_schemas_in_database"].(string)
futureSchemasInDatabaseOk := len(futureSchemasInDatabase) > 0
switch {
case schemaNameOk:
grantOnSchema.Schema = sdk.Pointer(sdk.NewDatabaseObjectIdentifierFromFullyQualifiedName(schemaName))
case allSchemasInDatabaseOk:
grantOnSchema.AllSchemasInDatabase = sdk.Pointer(sdk.NewAccountObjectIdentifierFromFullyQualifiedName(allSchemasInDatabase))
case futureSchemasInDatabaseOk:
grantOnSchema.FutureSchemasInDatabase = sdk.Pointer(sdk.NewAccountObjectIdentifierFromFullyQualifiedName(futureSchemasInDatabase))
}
on.Schema = grantOnSchema
case onSchemaObjectOk:
onSchemaObject := onSchemaObjectBlock.([]any)[0].(map[string]any)
grantOnSchemaObject := new(sdk.GrantOnSchemaObject)
objectType := onSchemaObject["object_type"].(string)
objectTypeOk := len(objectType) > 0
objectName := onSchemaObject["object_name"].(string)
objectNameOk := len(objectName) > 0
all := onSchemaObject["all"].([]any)
allOk := len(all) > 0
future := onSchemaObject["future"].([]any)
futureOk := len(future) > 0
switch {
case objectTypeOk && objectNameOk:
grantOnSchemaObject.SchemaObject = &sdk.Object{
ObjectType: sdk.ObjectType(objectType),
Name: sdk.NewSchemaObjectIdentifierFromFullyQualifiedName(objectName),
}
case allOk:
grantOnSchemaObject.All = getGrantOnSchemaObjectIn(all[0].(map[string]any))
case futureOk:
grantOnSchemaObject.Future = getGrantOnSchemaObjectIn(future[0].(map[string]any))
}
on.SchemaObject = grantOnSchemaObject
}
return on
}
func createGrantPrivilegesToDatabaseRoleIdFromSchema(d *schema.ResourceData) *GrantPrivilegesToDatabaseRoleId {
id := new(GrantPrivilegesToDatabaseRoleId)
id.DatabaseRoleName = sdk.NewDatabaseObjectIdentifierFromFullyQualifiedName(d.Get("database_role_name").(string))
id.AllPrivileges = d.Get("all_privileges").(bool)
if p, ok := d.GetOk("privileges"); ok {
id.Privileges = expandStringList(p.(*schema.Set).List())
}
id.WithGrantOption = d.Get("with_grant_option").(bool)
on := getDatabaseRoleGrantOn(d)
switch {
case on.Database != nil:
id.Kind = OnDatabaseDatabaseRoleGrantKind
id.Data = &OnDatabaseGrantData{
DatabaseName: *on.Database,
}
case on.Schema != nil:
onSchemaGrantData := new(OnSchemaGrantData)
switch {
case on.Schema.Schema != nil:
onSchemaGrantData.Kind = OnSchemaSchemaGrantKind
onSchemaGrantData.SchemaName = on.Schema.Schema
case on.Schema.AllSchemasInDatabase != nil:
onSchemaGrantData.Kind = OnAllSchemasInDatabaseSchemaGrantKind
onSchemaGrantData.DatabaseName = on.Schema.AllSchemasInDatabase
case on.Schema.FutureSchemasInDatabase != nil:
onSchemaGrantData.Kind = OnFutureSchemasInDatabaseSchemaGrantKind
onSchemaGrantData.DatabaseName = on.Schema.FutureSchemasInDatabase
}
id.Kind = OnSchemaDatabaseRoleGrantKind
id.Data = onSchemaGrantData
case on.SchemaObject != nil:
onSchemaObjectGrantData := new(OnSchemaObjectGrantData)
switch {
case on.SchemaObject.SchemaObject != nil:
onSchemaObjectGrantData.Kind = OnObjectSchemaObjectGrantKind
onSchemaObjectGrantData.Object = on.SchemaObject.SchemaObject
case on.SchemaObject.All != nil:
onSchemaObjectGrantData.Kind = OnAllSchemaObjectGrantKind
onSchemaObjectGrantData.OnAllOrFuture = getBulkOperationGrantData(on.SchemaObject.All)
case on.SchemaObject.Future != nil:
onSchemaObjectGrantData.Kind = OnFutureSchemaObjectGrantKind
onSchemaObjectGrantData.OnAllOrFuture = getBulkOperationGrantData(on.SchemaObject.Future)
}
id.Kind = OnSchemaObjectDatabaseRoleGrantKind
id.Data = onSchemaObjectGrantData
}
return id
}