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 4 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
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 @@ -726,9 +727,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 @@ -1190,6 +1190,92 @@ func TestAcc_GrantPrivilegesToAccountRole_MLPrivileges(t *testing.T) {
})
}

// 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 @@ -1252,7 +1338,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 @@ -1263,6 +1349,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 @@ -641,8 +642,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