-
Notifications
You must be signed in to change notification settings - Fork 427
/
Copy pathgrant_privileges_to_account_role.go
1235 lines (1121 loc) · 42.3 KB
/
grant_privileges_to_account_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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package resources
import (
"context"
"errors"
"fmt"
"log"
"slices"
"strings"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/provider/resources"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/logging"
"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"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
var grantPrivilegesToAccountRoleSchema = map[string]*schema.Schema{
"account_role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: relatedResourceDescription("The fully qualified name of the account role to which privileges will be granted.", resources.AccountRole),
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
DiffSuppressFunc: suppressIdentifierQuoting,
},
// According to docs https://docs.snowflake.com/en/user-guide/data-exchange-marketplace-privileges#usage-notes IMPORTED PRIVILEGES
// will be returned as USAGE in SHOW GRANTS command. In addition, USAGE itself is a valid privilege, but both cannot be set at the
// same time (IMPORTED PRIVILEGES can only be granted to the database created from SHARE and USAGE in every other case).
// To handle both cases, additional logic was added in read operation where IMPORTED PRIVILEGES is replaced with USAGE.
"privileges": {
Type: schema.TypeSet,
Optional: true,
Description: "The privileges to grant on the account role. This field is case-sensitive; use only upper-case privileges.",
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 account role.",
ExactlyOneOf: []string{
"privileges",
"all_privileges",
},
},
"with_grant_option": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Description: "Specifies whether the grantee can grant the privileges to other users.",
},
"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_account": {
Type: schema.TypeBool,
Optional: true,
Default: false,
ForceNew: true,
Description: "If true, the privileges will be granted on the account.",
ExactlyOneOf: []string{
"on_account",
"on_account_object",
"on_schema",
"on_schema_object",
},
},
"on_account_object": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Specifies the account object on which privileges will be granted ",
MaxItems: 1,
ExactlyOneOf: []string{
"on_account",
"on_account_object",
"on_schema",
"on_schema_object",
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"object_type": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The object type of the account object on which privileges will be granted. Valid values are: USER | RESOURCE MONITOR | WAREHOUSE | COMPUTE POOL | DATABASE | INTEGRATION | FAILOVER GROUP | REPLICATION GROUP | EXTERNAL VOLUME",
ValidateFunc: validation.StringInSlice([]string{
"USER",
"RESOURCE MONITOR",
"WAREHOUSE",
"COMPUTE POOL",
"DATABASE",
"INTEGRATION",
"FAILOVER GROUP",
"REPLICATION GROUP",
"EXTERNAL VOLUME",
}, true),
},
"object_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The fully qualified name of the object on which privileges will be granted.",
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
DiffSuppressFunc: suppressIdentifierQuoting,
},
},
},
},
"on_schema": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
Description: "Specifies the schema on which privileges will be granted.",
MaxItems: 1,
ExactlyOneOf: []string{
"on_account",
"on_account_object",
"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](),
DiffSuppressFunc: suppressIdentifierQuoting,
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](),
DiffSuppressFunc: suppressIdentifierQuoting,
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](),
DiffSuppressFunc: suppressIdentifierQuoting,
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_account",
"on_account_object",
"on_schema",
"on_schema_object",
},
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"object_type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Description: fmt.Sprintf("The object type of the schema object on which privileges will be granted. Valid values are: %s", strings.Join(sdk.ValidGrantToObjectTypesString, " | ")),
RequiredWith: []string{
"on_schema_object.0.object_name",
},
ConflictsWith: []string{
"on_schema_object.0.all",
"on_schema_object.0.future",
},
ValidateDiagFunc: StringInSlice(sdk.ValidGrantToObjectTypesString, true),
},
"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",
},
DiffSuppressFunc: suppressIdentifierQuoting,
},
"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: getGrantPrivilegesOnAccountRoleBulkOperationSchema(sdk.ValidGrantToPluralObjectTypesString),
},
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: getGrantPrivilegesOnAccountRoleBulkOperationSchema(sdk.ValidGrantToFuturePluralObjectTypesString),
},
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",
},
},
},
},
},
}
func getGrantPrivilegesOnAccountRoleBulkOperationSchema(validGrantToObjectTypes []string) map[string]*schema.Schema {
return map[string]*schema.Schema{
"object_type_plural": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: fmt.Sprintf("The plural object type of the schema object on which privileges will be granted. Valid values are: %s.", strings.Join(validGrantToObjectTypes, " | ")),
ValidateDiagFunc: StringInSlice(validGrantToObjectTypes, true),
},
"in_database": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateDiagFunc: IsValidIdentifier[sdk.AccountObjectIdentifier](),
DiffSuppressFunc: suppressIdentifierQuoting,
},
"in_schema": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateDiagFunc: IsValidIdentifier[sdk.DatabaseObjectIdentifier](),
DiffSuppressFunc: suppressIdentifierQuoting,
},
}
}
func GrantPrivilegesToAccountRole() *schema.Resource {
return &schema.Resource{
CreateContext: TrackingCreateWrapper(resources.GrantPrivilegesToAccountRole, CreateGrantPrivilegesToAccountRole),
UpdateContext: TrackingUpdateWrapper(resources.GrantPrivilegesToAccountRole, UpdateGrantPrivilegesToAccountRole),
DeleteContext: TrackingDeleteWrapper(resources.GrantPrivilegesToAccountRole, DeleteGrantPrivilegesToAccountRole),
ReadContext: TrackingReadWrapper(resources.GrantPrivilegesToAccountRole, ReadGrantPrivilegesToAccountRole),
Schema: grantPrivilegesToAccountRoleSchema,
Importer: &schema.ResourceImporter{
StateContext: TrackingImportWrapper(resources.GrantPrivilegesToAccountRole, ImportGrantPrivilegesToAccountRole()),
},
}
}
func ImportGrantPrivilegesToAccountRole() func(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
return func(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
logging.DebugLogger.Printf("[DEBUG] Entering import grant privileges to account role")
id, err := ParseGrantPrivilegesToAccountRoleId(d.Id())
if err != nil {
return nil, err
}
logging.DebugLogger.Printf("[DEBUG] Imported identifier: %s", id.String())
if err := d.Set("account_role_name", id.RoleName.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
}
if err := d.Set("on_account", false); err != nil {
return nil, err
}
switch id.Kind {
case OnAccountAccountRoleGrantKind:
if err := d.Set("on_account", true); err != nil {
return nil, err
}
case OnAccountObjectAccountRoleGrantKind:
data := id.Data.(*OnAccountObjectGrantData)
onAccountObject := make(map[string]any)
onAccountObject["object_type"] = data.ObjectType.String()
onAccountObject["object_name"] = data.ObjectName.FullyQualifiedName()
if err := d.Set("on_account_object", []any{onAccountObject}); err != nil {
return nil, err
}
case OnSchemaAccountRoleGrantKind:
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 OnSchemaObjectAccountRoleGrantKind:
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 CreateGrantPrivilegesToAccountRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
logging.DebugLogger.Printf("[DEBUG] Entering create grant privileges to account role")
client := meta.(*provider.Context).Client
id, err := createGrantPrivilegesToAccountRoleIdFromSchema(d)
if err != nil {
return diag.FromErr(err)
}
logging.DebugLogger.Printf("[DEBUG] created identifier from schema: %s", id.String())
grantOn, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
err = client.Grants.GrantPrivilegesToAccountRole(
ctx,
getAccountRolePrivilegesFromSchema(d),
grantOn,
sdk.NewAccountObjectIdentifierFromFullyQualifiedName(d.Get("account_role_name").(string)),
&sdk.GrantPrivilegesToAccountRoleOptions{
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 account role",
Detail: fmt.Sprintf("Id: %s\nAccount role name: %s\nError: %s", id.String(), id.RoleName, err),
},
}
}
logging.DebugLogger.Printf("[DEBUG] Setting identifier to %s", id.String())
d.SetId(id.String())
return ReadGrantPrivilegesToAccountRole(ctx, d, meta)
}
func UpdateGrantPrivilegesToAccountRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
logging.DebugLogger.Printf("[DEBUG] Entering update grant privileges to account role")
client := meta.(*provider.Context).Client
id, err := ParseGrantPrivilegesToAccountRoleId(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),
},
}
}
logging.DebugLogger.Printf("[DEBUG] Parsed identifier to %s", id.String())
if d.HasChange("with_grant_option") {
id.WithGrantOption = d.Get("with_grant_option").(bool)
}
// handle all_privileges -> privileges change (revoke all privileges)
if d.HasChange("all_privileges") {
_, allPrivileges := d.GetChange("all_privileges")
if !allPrivileges.(bool) {
logging.DebugLogger.Printf("[DEBUG] Revoking all privileges")
grantOn, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
err = client.Grants.RevokePrivilegesFromAccountRole(ctx, &sdk.AccountRoleGrantPrivileges{
AllPrivileges: sdk.Bool(true),
},
grantOn,
id.RoleName,
new(sdk.RevokePrivilegesFromAccountRoleOptions),
)
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),
},
}
}
}
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())
logging.DebugLogger.Printf("[DEBUG] Changes in privileges. Before: %v, after: %v", privilegesBeforeChange, privilegesAfterChange)
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, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
if len(privilegesToAdd) > 0 {
logging.DebugLogger.Printf("[DEBUG] Granting privileges: %v", privilegesToAdd)
privilegesToGrant := getAccountRolePrivileges(
false,
privilegesToAdd,
id.Kind == OnAccountAccountRoleGrantKind,
id.Kind == OnAccountObjectAccountRoleGrantKind,
id.Kind == OnSchemaAccountRoleGrantKind,
id.Kind == OnSchemaObjectAccountRoleGrantKind,
)
if !id.WithGrantOption {
if err = client.Grants.RevokePrivilegesFromAccountRole(ctx, privilegesToGrant, grantOn, id.RoleName, &sdk.RevokePrivilegesFromAccountRoleOptions{
GrantOptionFor: sdk.Bool(true),
}); err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to revoke privileges to add",
Detail: fmt.Sprintf("Id: %s\nPrivileges to add: %v\nError: %s", d.Id(), privilegesToAdd, err.Error()),
},
}
}
}
err = client.Grants.GrantPrivilegesToAccountRole(ctx, privilegesToGrant, grantOn, id.RoleName, &sdk.GrantPrivilegesToAccountRoleOptions{WithGrantOption: sdk.Bool(id.WithGrantOption)})
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),
},
}
}
}
if len(privilegesToRemove) > 0 {
logging.DebugLogger.Printf("[DEBUG] Revoking privileges: %v", privilegesToRemove)
err = client.Grants.RevokePrivilegesFromAccountRole(
ctx,
getAccountRolePrivileges(
false,
privilegesToRemove,
id.Kind == OnAccountAccountRoleGrantKind,
id.Kind == OnAccountObjectAccountRoleGrantKind,
id.Kind == OnSchemaAccountRoleGrantKind,
id.Kind == OnSchemaObjectAccountRoleGrantKind,
),
grantOn,
id.RoleName,
new(sdk.RevokePrivilegesFromAccountRoleOptions),
)
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),
},
}
}
}
id.Privileges = privilegesAfterChange
}
}
// handle privileges -> all_privileges change (grant all privileges)
if d.HasChange("all_privileges") {
_, allPrivileges := d.GetChange("all_privileges")
if allPrivileges.(bool) {
logging.DebugLogger.Printf("[DEBUG] Granting all privileges")
grantOn, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
err = client.Grants.GrantPrivilegesToAccountRole(ctx, &sdk.AccountRoleGrantPrivileges{
AllPrivileges: sdk.Bool(true),
},
grantOn,
id.RoleName,
new(sdk.GrantPrivilegesToAccountRoleOptions),
)
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),
},
}
}
}
id.AllPrivileges = allPrivileges.(bool)
}
if d.HasChange("always_apply") {
id.AlwaysApply = d.Get("always_apply").(bool)
}
if id.AlwaysApply {
logging.DebugLogger.Printf("[DEBUG] Performing always_apply re-grant")
grantOn, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
err = client.Grants.GrantPrivilegesToAccountRole(
ctx,
getAccountRolePrivilegesFromSchema(d),
grantOn,
id.RoleName,
&sdk.GrantPrivilegesToAccountRoleOptions{
WithGrantOption: &id.WithGrantOption,
},
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Always apply. An error occurred when granting privileges to account role",
Detail: fmt.Sprintf("Id: %s\nAccount role name: %s\nError: %s", d.Id(), id.RoleName, err),
},
}
}
}
logging.DebugLogger.Printf("[DEBUG] Setting identifier to %s", id.String())
d.SetId(id.String())
return ReadGrantPrivilegesToAccountRole(ctx, d, meta)
}
func DeleteGrantPrivilegesToAccountRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
logging.DebugLogger.Printf("[DEBUG] Entering delete grant privileges to account role")
client := meta.(*provider.Context).Client
id, err := ParseGrantPrivilegesToAccountRoleId(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),
},
}
}
logging.DebugLogger.Printf("[DEBUG] Parsed identifier: %s", id.String())
grantOn, err := getAccountRoleGrantOn(d)
if err != nil {
return diag.FromErr(err)
}
err = client.Grants.RevokePrivilegesFromAccountRole(
ctx,
getAccountRolePrivilegesFromSchema(d),
grantOn,
id.RoleName,
&sdk.RevokePrivilegesFromAccountRoleOptions{},
)
if err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "An error occurred when revoking privileges from account role",
Detail: fmt.Sprintf("Id: %s\nAccount role name: %s\nError: %s", d.Id(), id.RoleName.FullyQualifiedName(), err),
},
}
}
d.SetId("")
return nil
}
func ReadGrantPrivilegesToAccountRole(ctx context.Context, d *schema.ResourceData, meta any) diag.Diagnostics {
logging.DebugLogger.Printf("[DEBUG] Entering read grant privileges to role")
id, err := ParseGrantPrivilegesToAccountRoleId(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),
},
}
}
logging.DebugLogger.Printf("[DEBUG] Parsed identifier: %s", id.String())
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),
},
}
}
// 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),
},
}
}
}
if id.AllPrivileges {
log.Printf("[INFO] Show with all_privileges option is skipped. No changes in privileges in Snowflake will be detected. Consider specyfying all privileges in 'privileges' block.")
return nil
}
opts, grantedOn := prepareShowGrantsRequestForAccountRole(id)
if opts == nil {
return nil
}
client := meta.(*provider.Context).Client
if _, err := client.Roles.ShowByID(ctx, id.RoleName); err != nil && errors.Is(err, sdk.ErrObjectNotFound) {
d.SetId("")
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Failed to retrieve account role. Marking the resource as removed.",
Detail: fmt.Sprintf("Id: %s", d.Id()),
},
}
}
logging.DebugLogger.Printf("[DEBUG] About to show grants")
grants, err := client.Grants.Show(ctx, opts)
if err != nil {
if errors.Is(err, sdk.ErrObjectNotExistOrAuthorized) {
d.SetId("")
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Failed to retrieve grants. Target object not found. Marking the resource as removed.",
Detail: fmt.Sprintf("Id: %s", d.Id()),
},
}
}
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Failed to retrieve grants",
Detail: fmt.Sprintf("Id: %s\nError: %s", d.Id(), err),
},
}
}
actualPrivileges := make([]string, 0)
expectedPrivileges := make([]string, 0)
expectedPrivileges = append(expectedPrivileges, id.Privileges...)
if slices.ContainsFunc(expectedPrivileges, func(s string) bool {
return strings.ToUpper(s) == sdk.AccountObjectPrivilegeImportedPrivileges.String()
}) {
expectedPrivileges = append(expectedPrivileges, sdk.AccountObjectPrivilegeUsage.String())
}
logging.DebugLogger.Printf("[DEBUG] Filtering grants to be set on account: count = %d", len(grants))
for _, grant := range grants {
// Accept only (account) ROLEs
if grant.GrantTo != sdk.ObjectTypeRole && grant.GrantedTo != sdk.ObjectTypeRole {
continue
}
// Only consider privileges that are already present in the ID, so we
// don't delete privileges managed by other resources.
if !slices.Contains(expectedPrivileges, grant.Privilege) {
continue
}
if grant.GrantOption == id.WithGrantOption && grant.GranteeName.Name() == id.RoleName.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.
// The same goes for the default SNOWFLAKE database, but we don't want to skip in this case
if (opts.Future == nil || !*opts.Future) && grant.GrantedBy.Name() == "" && grant.Name.Name() != "SNOWFLAKE" {
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
//
// To `grant privilege on application to a role` the user has to use `object_type = "DATABASE"`.
// It's because Snowflake treats applications as if they were databases. One exception to the rule is
// the default application named SNOWFLAKE that could be granted with `object_type = "APPLICATION"`.
// To make the logic simpler, we do not allow it and `object_type = "DATABASE"` should be used for all applications.
// TODO When implementing SNOW-991421 see if logic added in SNOW-887897 could be moved to the SDK to simplify the resource implementation.
if grantedOn == sdk.ObjectTypeDatabase && (sdk.ObjectTypeApplication == grant.GrantedOn || sdk.ObjectTypeApplication == grant.GrantOn) {
actualPrivileges = append(actualPrivileges, grant.Privilege)
} else if grantedOn == grant.GrantedOn || grantedOn == grant.GrantOn {
actualPrivileges = append(actualPrivileges, grant.Privilege)
}
}
}
usageIndex := slices.IndexFunc(actualPrivileges, func(s string) bool { return strings.ToUpper(s) == sdk.AccountObjectPrivilegeUsage.String() })
if slices.ContainsFunc(expectedPrivileges, func(s string) bool {
return strings.ToUpper(s) == sdk.AccountObjectPrivilegeImportedPrivileges.String()
}) && usageIndex >= 0 {
actualPrivileges[usageIndex] = sdk.AccountObjectPrivilegeImportedPrivileges.String()
}
logging.DebugLogger.Printf("[DEBUG] Setting privileges: %v", actualPrivileges)
if err := d.Set("privileges", actualPrivileges); err != nil {
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Error,
Summary: "Error setting privileges for account role",
Detail: fmt.Sprintf("Id: %s\nPrivileges: %v\nError: %s", d.Id(), actualPrivileges, err),
},
}
}
return nil
}
func prepareShowGrantsRequestForAccountRole(id GrantPrivilegesToAccountRoleId) (*sdk.ShowGrantOptions, sdk.ObjectType) {
opts := new(sdk.ShowGrantOptions)
var grantedOn sdk.ObjectType
switch id.Kind {
case OnAccountAccountRoleGrantKind:
grantedOn = sdk.ObjectTypeAccount
opts.On = &sdk.ShowGrantsOn{
Account: sdk.Bool(true),
}
case OnAccountObjectAccountRoleGrantKind:
data := id.Data.(*OnAccountObjectGrantData)
grantedOn = data.ObjectType
opts.On = &sdk.ShowGrantsOn{
Object: &sdk.Object{
ObjectType: data.ObjectType,
Name: data.ObjectName,
},
}
case OnSchemaAccountRoleGrantKind:
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:
log.Printf("[INFO] Show with on_schema.all_schemas_in_database option is skipped. No changes in privileges in Snowflake will be detected.")
return nil, ""
case OnFutureSchemasInDatabaseSchemaGrantKind:
opts.Future = sdk.Bool(true)
opts.In = &sdk.ShowGrantsIn{
Database: data.DatabaseName,
}
}
case OnSchemaObjectAccountRoleGrantKind:
data := id.Data.(*OnSchemaObjectGrantData)
switch data.Kind {
case OnObjectSchemaObjectGrantKind:
grantedOn = data.Object.ObjectType
opts.On = &sdk.ShowGrantsOn{
Object: data.Object,
}
case OnAllSchemaObjectGrantKind:
log.Printf("[INFO] Show with on_schema_object.on_all option is skipped. No changes in privileges in Snowflake will be detected.")
return nil, ""
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
}
func getAccountRolePrivilegesFromSchema(d *schema.ResourceData) *sdk.AccountRoleGrantPrivileges {
_, onAccountOk := d.GetOk("on_account")
_, onAccountObjectOk := d.GetOk("on_account_object")
_, onSchemaOk := d.GetOk("on_schema")
_, onSchemaObjectOk := d.GetOk("on_schema_object")
return getAccountRolePrivileges(
d.Get("all_privileges").(bool),
expandStringList(d.Get("privileges").(*schema.Set).List()),
onAccountOk,
onAccountObjectOk,
onSchemaOk,
onSchemaObjectOk,
)
}
func getAccountRolePrivileges(allPrivileges bool, privileges []string, onAccount bool, onAccountObject bool, onSchema bool, onSchemaObject bool) *sdk.AccountRoleGrantPrivileges {
accountRoleGrantPrivileges := new(sdk.AccountRoleGrantPrivileges)
if allPrivileges {
accountRoleGrantPrivileges.AllPrivileges = sdk.Bool(true)
return accountRoleGrantPrivileges
}
switch {
case onAccount:
globalPrivileges := make([]sdk.GlobalPrivilege, len(privileges))
for i, privilege := range privileges {
globalPrivileges[i] = sdk.GlobalPrivilege(privilege)
}
accountRoleGrantPrivileges.GlobalPrivileges = globalPrivileges
case onAccountObject:
accountObjectPrivileges := make([]sdk.AccountObjectPrivilege, len(privileges))
for i, privilege := range privileges {
accountObjectPrivileges[i] = sdk.AccountObjectPrivilege(privilege)
}
accountRoleGrantPrivileges.AccountObjectPrivileges = accountObjectPrivileges
case onSchema:
schemaPrivileges := make([]sdk.SchemaPrivilege, len(privileges))
for i, privilege := range privileges {
schemaPrivileges[i] = sdk.SchemaPrivilege(privilege)
}
accountRoleGrantPrivileges.SchemaPrivileges = schemaPrivileges
case onSchemaObject:
schemaObjectPrivileges := make([]sdk.SchemaObjectPrivilege, len(privileges))
for i, privilege := range privileges {
schemaObjectPrivileges[i] = sdk.SchemaObjectPrivilege(privilege)
}
accountRoleGrantPrivileges.SchemaObjectPrivileges = schemaObjectPrivileges
}