Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: grant read operation #2665

Merged
merged 8 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/gookit/color v1.5.4
github.com/hashicorp/go-cty v1.4.1-0.20200414143053-d3edf31b6320
github.com/hashicorp/go-uuid v1.0.3
github.com/hashicorp/terraform-json v0.18.0
github.com/hashicorp/terraform-plugin-framework v1.4.2
github.com/hashicorp/terraform-plugin-framework-validators v0.12.0
github.com/hashicorp/terraform-plugin-go v0.20.0
Expand Down Expand Up @@ -87,7 +88,6 @@ require (
github.com/hashicorp/hcl/v2 v2.19.1 // indirect
github.com/hashicorp/logutils v1.0.0 // indirect
github.com/hashicorp/terraform-exec v0.19.0 // indirect
github.com/hashicorp/terraform-json v0.18.0 // indirect
github.com/hashicorp/terraform-registry-address v0.2.3 // indirect
github.com/hashicorp/terraform-svchost v0.1.1 // indirect
github.com/hashicorp/yamux v0.1.1 // indirect
Expand Down
3 changes: 2 additions & 1 deletion pkg/architests/resources_acceptance_tests_arch_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package architests

import (
"regexp"
"testing"

"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/architest"
Expand All @@ -25,7 +26,7 @@ func TestArchCheck_AcceptanceTests_Resources(t *testing.T) {
})

t.Run("there are no acceptance tests in other test files in the directory", func(t *testing.T) {
otherTestFiles := resourcesFiles.Filter(architest.FileNameFilterWithExclusionsProvider(architest.TestFileRegex, architest.AcceptanceTestFileRegex))
otherTestFiles := resourcesFiles.Filter(architest.FileNameFilterWithExclusionsProvider(architest.TestFileRegex, architest.AcceptanceTestFileRegex, regexp.MustCompile("helpers_test.go")))

otherTestFiles.All(func(file *architest.File) {
file.ExportedMethods().All(func(method *architest.Method) {
Expand Down
23 changes: 23 additions & 0 deletions pkg/resources/database_acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,3 +489,26 @@ func checkAccountAndDatabaseDataRetentionTime(id sdk.AccountObjectIdentifier, ex
return nil
}
}

func createDatabaseOutsideTerraform(t *testing.T, name string) func() {
t.Helper()
client, err := sdk.NewDefaultClient()
if err != nil {
t.Fatal(err)
}
ctx := context.Background()

if err := client.Databases.Create(ctx, sdk.NewAccountObjectIdentifier(name), new(sdk.CreateDatabaseOptions)); err != nil {
if err != nil {
t.Fatal(err)
}
}

return func() {
if err := client.Databases.Drop(ctx, sdk.NewAccountObjectIdentifier(name), new(sdk.DropDatabaseOptions)); err != nil {
if err != nil {
t.Fatal(err)
}
}
}
}
23 changes: 23 additions & 0 deletions pkg/resources/grant_privileges_to_account_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resources

import (
"context"
"errors"
"fmt"
"log"
"slices"
Expand Down Expand Up @@ -738,9 +739,31 @@ func ReadGrantPrivilegesToAccountRole(ctx context.Context, d *schema.ResourceDat

client := meta.(*provider.Context).Client

// TODO(SNOW-891217): Use custom error. Right now, "object does not exist" error is hidden in sdk/internal/collections package
if _, err := client.Roles.ShowByID(ctx, sdk.NewShowByIdRoleRequest(id.RoleName)); err != nil && err.Error() == "object does not exist" {
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,
Expand Down
96 changes: 94 additions & 2 deletions pkg/resources/grant_privileges_to_account_role_acceptance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ func TestAcc_GrantPrivilegesToAccountRole_OnSchemaObject_OnObject_OwnershipPrivi
CheckDestroy: testAccCheckAccountRolePrivilegesRevoked(name),
Steps: []resource.TestStep{
{
PreConfig: func() { createDatabaseRoleOutsideTerraform(t, name) },
PreConfig: func() { createAccountRoleOutsideTerraform(t, name) },
ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToAccountRole/OnSchemaObject_OnObject"),
ConfigVariables: configVariables,
ExpectError: regexp.MustCompile("Unsupported privilege 'OWNERSHIP'"),
Expand Down Expand Up @@ -1358,6 +1358,92 @@ func revokeAndGrantPrivilegesOnTableToAccountRole(
}
}

// proves https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2621 doesn't apply to this resource
func TestAcc_GrantPrivilegesToAccountRole_RemoveGrantedObjectOutsideTerraform(t *testing.T) {
name := strings.ToUpper(acctest.RandStringFromCharSet(10, acctest.CharSetAlpha))
roleName := sdk.NewAccountObjectIdentifier(name).FullyQualifiedName()
databaseName := strings.ToUpper(acctest.RandStringFromCharSet(10, acctest.CharSetAlpha))
configVariables := config.Variables{
"name": config.StringVariable(roleName),
"database": config.StringVariable(databaseName),
"privileges": config.ListVariable(
config.StringVariable(string(sdk.AccountObjectPrivilegeCreateDatabaseRole)),
config.StringVariable(string(sdk.AccountObjectPrivilegeCreateSchema)),
),
"with_grant_option": config.BoolVariable(true),
}

var databaseCleanup func()
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories,
PreCheck: func() { acc.TestAccPreCheck(t) },
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.RequireAbove(tfversion.Version1_5_0),
},
CheckDestroy: testAccCheckAccountRolePrivilegesRevoked(name),
Steps: []resource.TestStep{
{
PreConfig: func() {
databaseCleanup = createDatabaseOutsideTerraform(t, databaseName)
createAccountRoleOutsideTerraform(t, name)
},
ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToAccountRole/OnAccountObject"),
ConfigVariables: configVariables,
},
{
PreConfig: func() { databaseCleanup() },
ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToAccountRole/OnAccountObject"),
ConfigVariables: configVariables,
// The error occurs in the Create operation, indicating the Read operation removed the resource from the state in the previous step.
ExpectError: regexp.MustCompile("An error occurred when granting privileges to account role"),
},
},
})
}

// proves https://github.com/Snowflake-Labs/terraform-provider-snowflake/issues/2621 doesn't apply to this resource
func TestAcc_GrantPrivilegesToAccountRole_RemoveAccountRoleOutsideTerraform(t *testing.T) {
name := strings.ToUpper(acctest.RandStringFromCharSet(10, acctest.CharSetAlpha))
roleName := sdk.NewAccountObjectIdentifier(name).FullyQualifiedName()
databaseName := strings.ToUpper(acctest.RandStringFromCharSet(10, acctest.CharSetAlpha))
configVariables := config.Variables{
"name": config.StringVariable(roleName),
"database": config.StringVariable(databaseName),
"privileges": config.ListVariable(
config.StringVariable(string(sdk.AccountObjectPrivilegeCreateDatabaseRole)),
config.StringVariable(string(sdk.AccountObjectPrivilegeCreateSchema)),
),
"with_grant_option": config.BoolVariable(true),
}

var roleCleanup func()
resource.Test(t, resource.TestCase{
ProtoV6ProviderFactories: acc.TestAccProtoV6ProviderFactories,
PreCheck: func() { acc.TestAccPreCheck(t) },
TerraformVersionChecks: []tfversion.TerraformVersionCheck{
tfversion.RequireAbove(tfversion.Version1_5_0),
},
CheckDestroy: testAccCheckAccountRolePrivilegesRevoked(name),
Steps: []resource.TestStep{
{
PreConfig: func() {
t.Cleanup(createDatabaseOutsideTerraform(t, databaseName))
roleCleanup = createAccountRoleOutsideTerraform(t, name)
},
ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToAccountRole/OnAccountObject"),
ConfigVariables: configVariables,
},
{
PreConfig: func() { roleCleanup() },
ConfigDirectory: acc.ConfigurationDirectory("TestAcc_GrantPrivilegesToAccountRole/OnAccountObject"),
ConfigVariables: configVariables,
// The error occurs in the Create operation, indicating the Read operation removed the resource from the state in the previous step.
ExpectError: regexp.MustCompile("An error occurred when granting privileges to account role"),
},
},
})
}

func getSecondaryAccountName(t *testing.T) (string, error) {
t.Helper()
config, err := sdk.ProfileConfig(testprofiles.Secondary)
Expand Down Expand Up @@ -1420,7 +1506,7 @@ func dropSharedDatabaseOnSecondaryAccount(t *testing.T, databaseName string, sha
)
}

func createAccountRoleOutsideTerraform(t *testing.T, name string) {
func createAccountRoleOutsideTerraform(t *testing.T, name string) func() {
t.Helper()
client, err := sdk.NewDefaultClient()
if err != nil {
Expand All @@ -1431,6 +1517,12 @@ func createAccountRoleOutsideTerraform(t *testing.T, name string) {
if err := client.Roles.Create(ctx, sdk.NewCreateRoleRequest(roleId).WithOrReplace(true)); err != nil {
t.Fatal(fmt.Errorf("error account role (%s): %w", roleId.FullyQualifiedName(), err))
}

return func() {
if err := client.Roles.Drop(ctx, sdk.NewDropRoleRequest(roleId).WithIfExists(true)); err != nil {
t.Fatal(fmt.Errorf("error account role (%s): %w", roleId.FullyQualifiedName(), err))
}
}
}

func testAccCheckAccountRolePrivilegesRevoked(name string) func(*terraform.State) error {
Expand Down
23 changes: 23 additions & 0 deletions pkg/resources/grant_privileges_to_database_role.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resources

import (
"context"
"errors"
"fmt"
"log"
"slices"
Expand Down Expand Up @@ -653,8 +654,30 @@ func ReadGrantPrivilegesToDatabaseRole(ctx context.Context, d *schema.ResourceDa
}

client := meta.(*provider.Context).Client
// TODO(SNOW-891217): Use custom error. Right now, "object does not exist" error is hidden in sdk/internal/collections package
if _, err := client.DatabaseRoles.ShowByID(ctx, id.DatabaseRoleName); err != nil && err.Error() == "object does not exist" {
d.SetId("")
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: "Failed to retrieve database role. Marking the resource as removed.",
Detail: fmt.Sprintf("Id: %s", d.Id()),
},
}
}

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,
Expand Down
Loading
Loading