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

Handle UC Resource Grants with Spaces #3292

Closed
wants to merge 31 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
207dda6
Add Tests to Demonstrate Problem
ledbutter Feb 22, 2024
49e2d1e
Validate Privs for Create/Update
ledbutter Feb 22, 2024
88d1245
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 22, 2024
aabb111
Fix format
ledbutter Feb 22, 2024
7111b11
Switch to normalizing privs
ledbutter Feb 22, 2024
3138f7a
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 23, 2024
74572d7
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 23, 2024
78f1b38
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 26, 2024
2e3318d
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 27, 2024
e346ea8
Add Test for resource_grant (same scenario)
ledbutter Feb 28, 2024
c99e9ac
Port fix for resource_grant
ledbutter Feb 28, 2024
33646bc
Merge branch 'main' into resourceGrantsHyphens
ledbutter Feb 28, 2024
daa9a87
Merge branch 'main' into resourceGrantsHyphens
ledbutter Mar 6, 2024
681aa8d
Merge branch 'main' into resourceGrantsHyphens
ledbutter Mar 12, 2024
600c288
Point check-in: Figuring Out CustomizeDiff Testing
Mar 19, 2024
ebfa348
Implement CustomizeDiff with Error
ledbutter Mar 19, 2024
dfaa252
Account for non-string diffs for now
ledbutter Mar 26, 2024
8aa6781
Merge branch 'main' into resourceGrantsHyphens
ledbutter Mar 26, 2024
79d9520
Use DiffSuppressFunc Instead
ledbutter Mar 29, 2024
18dfb09
Clean up
ledbutter Mar 29, 2024
ef02c08
Switch to debug log when suppressing
ledbutter Apr 1, 2024
1327aa6
Merge branch 'main' into resourceGrantsHyphens
ledbutter Apr 2, 2024
0c523a0
Add unit test and speculative acceptance test
ledbutter Apr 3, 2024
4a39e67
Saving is hard
ledbutter Apr 3, 2024
c4e9df0
Merge branch 'main' into resourceGrantsHyphens
ledbutter Apr 3, 2024
8b079a1
Simplify integration tests from feedback
ledbutter Apr 5, 2024
a85126a
Merge branch 'main' into resourceGrantsHyphens
ledbutter Apr 5, 2024
71bd3ae
Roll back unrelated changes
ledbutter Apr 25, 2024
7275f52
Merge branch 'main' into resourceGrantsHyphens
ledbutter Apr 25, 2024
3981b53
Merge branch 'main' into resourceGrantsHyphens
ledbutter May 17, 2024
4c6f714
Merge branch 'main' into resourceGrantsHyphens
ledbutter Jun 5, 2024
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
11 changes: 11 additions & 0 deletions catalog/permissions/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"strings"
"time"

"github.com/databricks/databricks-sdk-go"
Expand Down Expand Up @@ -144,3 +145,13 @@ func SliceWithoutString(in []string, without string) (out []string) {
}
return
}

// If a privilege/permission only differs with underscores replacing spaces
// then we can suppress the change
func PrivilegesSuppressWhitespaceChange(k, old, new string, _ *schema.ResourceData) bool {
if (new == strings.ReplaceAll(old, " ", "_")) || (old == strings.ReplaceAll(new, " ", "_")) {
log.Printf("[DEBUG] Ignoring configuration drift from %s to %s", old, new)
return true
}
return false
}
17 changes: 15 additions & 2 deletions catalog/resource_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,24 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

// normalizePrivileges return an array of catalog.Privilege with privilege values normalized to match API behavior
func normalizePrivileges(privileges []catalog.Privilege) []catalog.Privilege {
normalizedPrivileges := []catalog.Privilege{}
for _, p := range privileges {
normalizedPriv := strings.ReplaceAll(p.String(), " ", "_")
normalizedPrivileges = append(normalizedPrivileges, catalog.Privilege(normalizedPriv))
}
return normalizedPrivileges
}

// diffPermissionsForPrincipal returns an array of catalog.PermissionsChange of this permissions list with `diff` privileges removed
func diffPermissionsForPrincipal(principal string, desired catalog.PermissionsList, existing catalog.PermissionsList) (diff []catalog.PermissionsChange) {
// diffs change sets for principal
configured := map[string]*schema.Set{}
for _, v := range desired.PrivilegeAssignments {
if v.Principal == principal {
configured[v.Principal] = permissions.SliceToSet(v.Privileges)
normalizedPrivileges := normalizePrivileges(v.Privileges)
configured[v.Principal] = permissions.SliceToSet(normalizedPrivileges)
}
}
// existing permissions that needs removal for principal
Expand Down Expand Up @@ -122,7 +133,6 @@ func parseSecurableId(d *schema.ResourceData) (string, string, string, error) {
func ResourceGrant() common.Resource {
s := common.StructToSchema(permissions.UnityCatalogPrivilegeAssignment{},
func(m map[string]*schema.Schema) map[string]*schema.Schema {

m["principal"].ForceNew = true

allFields := []string{}
Expand All @@ -138,6 +148,9 @@ func ResourceGrant() common.Resource {
ConflictsWith: permissions.SliceWithoutString(allFields, field),
}
}

m["privileges"].DiffSuppressFunc = permissions.PrivilegesSuppressWhitespaceChange
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ledbutter integration test failed, so I looked at this in a bit more details. DiffSuppressFunc only works for primitive, i.e. string-like attributes. For lists, we need to look at CustomizeDiff instead.

@tanmay-db we probably need to re-add a lightweight version of CustomizeDiff to handle this scenario, as it is causing permanent drifts

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I initially tried using CustomizeDiff, but that only works for computed keys, as I mentioned here. Are you saying that there needs to be a lower level change before this can be accomplished?


return m
})

Expand Down
31 changes: 31 additions & 0 deletions catalog/resource_grant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

"github.com/databricks/databricks-sdk-go/service/catalog"
"github.com/databricks/terraform-provider-databricks/catalog/permissions"
"github.com/databricks/terraform-provider-databricks/qa"
"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -585,6 +586,29 @@ func TestResourceGrantPermissionsList_Diff_LocalRemoteDiff(t *testing.T) {
assert.Equal(t, catalog.Privilege("c"), diff[0].Remove[0])
}

func TestResourceGrantPermissionsList_Diff_Spaces(t *testing.T) {
diff := diffPermissionsForPrincipal(
"a",
catalog.PermissionsList{ // config
PrivilegeAssignments: []catalog.PrivilegeAssignment{
{
Principal: "a",
Privileges: []catalog.Privilege{"a b"},
},
},
},
catalog.PermissionsList{
PrivilegeAssignments: []catalog.PrivilegeAssignment{ // platform
{
Principal: "a",
Privileges: []catalog.Privilege{"a_b"},
},
},
},
)
assert.Len(t, diff, 0)
}

func TestResourceGrantShareGrantCreate(t *testing.T) {
qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
Expand Down Expand Up @@ -834,3 +858,10 @@ func TestResourceGrantModelGrantCreate(t *testing.T) {
`,
}.ApplyNoError(t)
}

func TestPrivilegesSuppressWhitespaceChange(t *testing.T) {
assert.True(t, permissions.PrivilegesSuppressWhitespaceChange("", "a", "a", nil))
assert.True(t, permissions.PrivilegesSuppressWhitespaceChange("", "a_b", "a b", nil))
assert.True(t, permissions.PrivilegesSuppressWhitespaceChange("", "a b", "a_b", nil))
assert.False(t, permissions.PrivilegesSuppressWhitespaceChange("", "a", "b", nil))
}
13 changes: 12 additions & 1 deletion catalog/resource_grants.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,14 @@ type PermissionsList struct {
func diffPermissions(pl catalog.PermissionsList, existing catalog.PermissionsList) (diff []catalog.PermissionsChange) {
// diffs change sets
configured := map[string]*schema.Set{}
// normalize the configured privileges to match API behavior by treating spaces as underscores
for _, v := range pl.PrivilegeAssignments {
configured[v.Principal] = permissions.SliceToSet(v.Privileges)
normalizedPrivileges := []catalog.Privilege{}
for _, p := range v.Privileges {
normalizedPriv := strings.ReplaceAll(p.String(), " ", "_")
normalizedPrivileges = append(normalizedPrivileges, catalog.Privilege(normalizedPriv))
}
configured[v.Principal] = permissions.SliceToSet(normalizedPrivileges)
}
// existing permissions that needs removal
remote := map[string]*schema.Set{}
Expand Down Expand Up @@ -80,6 +86,7 @@ func replaceAllPermissions(a permissions.UnityCatalogPermissionsAPI, securable s
if err != nil {
return err
}

err = a.UpdatePermissions(securableType, name, diffPermissions(list, *existing))
if err != nil {
return err
Expand Down Expand Up @@ -128,6 +135,9 @@ func parseId(d *schema.ResourceData) (string, string, error) {
func ResourceGrants() common.Resource {
s := common.StructToSchema(PermissionsList{},
func(s map[string]*schema.Schema) map[string]*schema.Schema {

common.CustomizeSchemaPath(s, "grant", "privileges").SetCustomSuppressDiff(permissions.PrivilegesSuppressWhitespaceChange)

alof := []string{}
for field := range permissions.Mappings {
s[field] = &schema.Schema{
Expand All @@ -137,6 +147,7 @@ func ResourceGrants() common.Resource {
}
alof = append(alof, field)
}

for field := range permissions.Mappings {
s[field].AtLeastOneOf = alof
}
Expand Down
22 changes: 22 additions & 0 deletions catalog/resource_grants_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,28 @@ func TestPermissionsList_Diff_LocalRemoteDiff(t *testing.T) {
assert.Equal(t, catalog.Privilege("c"), diff[0].Remove[0])
}

func TestPermissionsList_Diff_Spaces(t *testing.T) {
diff := diffPermissions(
catalog.PermissionsList{ // config
PrivilegeAssignments: []catalog.PrivilegeAssignment{
{
Principal: "a",
Privileges: []catalog.Privilege{"a b"},
},
},
},
catalog.PermissionsList{
PrivilegeAssignments: []catalog.PrivilegeAssignment{ // platform
{
Principal: "a",
Privileges: []catalog.Privilege{"a_b"},
},
},
},
)
assert.Len(t, diff, 0)
}

func TestShareGrantCreate(t *testing.T) {
qa.ResourceFixture{
Fixtures: []qa.HTTPFixture{
Expand Down
1 change: 0 additions & 1 deletion common/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,6 @@ var NoAuth string = "default auth: cannot configure default credentials, " +
func AddAccountIdField(s map[string]*schema.Schema) map[string]*schema.Schema {
s["account_id"] = &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
Deprecated: "Configuring `account_id` at the resource-level is deprecated; please specify it in the `provider {}` configuration block instead",
}
Expand Down
24 changes: 24 additions & 0 deletions internal/acceptance/grant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,27 @@ func TestUcAccGrantForIdChange(t *testing.T) {
ExpectError: regexp.MustCompile(`cannot create grant: Privilege abc is not applicable to this entity`),
})
}

func grantTemplateForUnderscoreChange(permission string) string {
return fmt.Sprintf(`
resource "databricks_storage_credential" "external" {
name = "cred-{var.STICKY_RANDOM}-hyphens"
aws_iam_role {
role_arn = "{env.TEST_METASTORE_DATA_ACCESS_ARN}"
}
comment = "Managed by TF"
}

resource "databricks_grant" "cred" {
storage_credential = databricks_storage_credential.external.id
principal = "{env.TEST_DATA_ENG_GROUP}"
privileges = ["%s"]
}
`, permission)
}

func TestUcAccGrantForUnderscoreChange(t *testing.T) {
unityWorkspaceLevel(t, step{
Template: grantTemplateForUnderscoreChange("ALL PRIVILEGES"),
})
}
26 changes: 26 additions & 0 deletions internal/acceptance/grants_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,29 @@ func TestUcAccGrantsForIdChange(t *testing.T) {
ExpectError: regexp.MustCompile(`Error: cannot create grants: Privilege abc is not applicable to this entity`),
})
}

func grantsTemplateForUnderscoreChange(permission string) string {
return fmt.Sprintf(`
resource "databricks_storage_credential" "external" {
name = "cred-{var.STICKY_RANDOM}-underscores"
aws_iam_role {
role_arn = "{env.TEST_METASTORE_DATA_ACCESS_ARN}"
}
comment = "Managed by TF"
}

resource "databricks_grants" "cred" {
storage_credential = databricks_storage_credential.external.id
grant {
principal = "{env.TEST_DATA_ENG_GROUP}"
privileges = ["%s"]
}
}
`, permission)
}

func TestUcAccGrantsForUnderscoreChange(t *testing.T) {
unityWorkspaceLevel(t, step{
Template: grantsTemplateForUnderscoreChange("ALL PRIVILEGES"),
})
}
Loading