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: ALL implicit privileges equality check #339

Merged
merged 16 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
29 changes: 29 additions & 0 deletions postgresql/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,35 @@ func validatePrivileges(d *schema.ResourceData) error {
return nil
}

func resourcePrivilegesEqual(granted *schema.Set, d *schema.ResourceData) bool {
objectType := d.Get("object_type").(string)
wanted := d.Get("privileges").(*schema.Set)

if granted.Equal(wanted) {
return true
}

if !wanted.Contains("ALL") {
return false
}

// implicit check: e.g. for object_type schema -> ALL == ["CREATE", "USAGE"]
log.Printf("The wanted privilege is 'ALL'. therefore, we will check if the current privileges are ALL implicitely")
implicits := make([]string, 0)
for _, p := range allowedPrivileges[objectType] {
if p != "ALL" {
implicits = append(implicits, p)
}
}

s := make([]interface{}, len(implicits))
for i, privilege := range implicits {
s[i] = privilege
}
wantedSet := schema.NewSet(schema.HashString, s)
talbx marked this conversation as resolved.
Show resolved Hide resolved
return granted.Equal(wantedSet)
}

func pgArrayToSet(arr pq.ByteaArray) *schema.Set {
s := make([]interface{}, len(arr))
for i, v := range arr {
Expand Down
76 changes: 76 additions & 0 deletions postgresql/helpers_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package postgresql

import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -45,3 +46,78 @@ func TestQuoteTableName(t *testing.T) {
})
}
}

func TestArePrivilegesEqual(t *testing.T) {
Copy link
Owner

Choose a reason for hiding this comment

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

Cool 👍


type PrivilegesTestObject struct {
d *schema.ResourceData
granted *schema.Set
wanted *schema.Set
assertion bool
}

tt := []PrivilegesTestObject{
{
buildResourceData("database", t),
buildPrivilegesSet("CONNECT", "CREATE", "TEMPORARY"),
buildPrivilegesSet("ALL"),
true,
},
{
buildResourceData("database", t),
buildPrivilegesSet("CREATE", "USAGE"),
buildPrivilegesSet("USAGE"),
false,
},
{
buildResourceData("table", t),
buildPrivilegesSet("SELECT", "INSERT", "UPDATE", "DELETE", "TRUNCATE", "REFERENCES", "TRIGGER"),
buildPrivilegesSet("ALL"),
true,
},
{
buildResourceData("table", t),
buildPrivilegesSet("SELECT"),
buildPrivilegesSet("SELECT, INSERT"),
false,
},
{
buildResourceData("schema", t),
buildPrivilegesSet("CREATE", "USAGE"),
buildPrivilegesSet("ALL"),
true,
},
{
buildResourceData("schema", t),
buildPrivilegesSet("CREATE"),
buildPrivilegesSet("ALL"),
false,
},
}

for _, configuration := range tt {
err := configuration.d.Set("privileges", configuration.wanted)
assert.NoError(t, err)
equal := resourcePrivilegesEqual(configuration.granted, configuration.d)
assert.Equal(t, configuration.assertion, equal)
}
}

func buildPrivilegesSet(grants ...interface{}) *schema.Set {
return schema.NewSet(schema.HashString, grants)
}

func buildResourceData(objectType string, t *testing.T) *schema.ResourceData {
var testSchema = map[string]*schema.Schema{
"object_type": {Type: schema.TypeString},
"privileges": {
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},
}

m := make(map[string]any)
m["object_type"] = objectType
return schema.TestResourceDataRaw(t, testSchema, m)
}
8 changes: 6 additions & 2 deletions postgresql/resource_postgresql_default_privileges.go
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,12 @@ func readRoleDefaultPrivileges(txn *sql.Tx, d *schema.ResourceData) error {
}

privilegesSet := pgArrayToSet(privileges)
d.Set("privileges", privilegesSet)
d.SetId(generateDefaultPrivilegesID(d))
privilegesEqual := resourcePrivilegesEqual(privilegesSet, d)

if !privilegesEqual {
d.Set("privileges", privilegesSet)
d.SetId(generateDefaultPrivilegesID(d))
Copy link
Owner

Choose a reason for hiding this comment

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

Why the SetId is in the if? It's not the case for postgresql_grant and I think we want to set it in any cases.

Currently this works anyway because the ID is based on fields that recreate the resource if they change so it will never change here, but this is still totally unrelated to privileges

Copy link
Contributor Author

Choose a reason for hiding this comment

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

you are right, this was probably just a slip.
changed this with c35441d

}

return nil
}
Expand Down
32 changes: 21 additions & 11 deletions postgresql/resource_postgresql_grant.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ func resourcePostgreSQLGrantDelete(db *DBConnection, d *schema.ResourceData) err
return nil
}

func readDatabaseRolePriviges(txn *sql.Tx, d *schema.ResourceData, roleOID uint32) error {
func readDatabaseRolePrivileges(txn *sql.Tx, d *schema.ResourceData, roleOID uint32) error {
dbName := d.Get("database").(string)
query := `
SELECT array_agg(privilege_type)
Expand All @@ -269,12 +269,14 @@ WHERE grantee = $2
if err := txn.QueryRow(query, dbName, roleOID).Scan(&privileges); err != nil {
return fmt.Errorf("could not read privileges for database %s: %w", dbName, err)
}

d.Set("privileges", pgArrayToSet(privileges))
granted := pgArrayToSet(privileges)
if !resourcePrivilegesEqual(granted, d) {
return d.Set("privileges", granted)
}
return nil
}

func readSchemaRolePriviges(txn *sql.Tx, d *schema.ResourceData, roleOID uint32) error {
func readSchemaRolePrivileges(txn *sql.Tx, d *schema.ResourceData, roleOID uint32) error {
dbName := d.Get("schema").(string)
query := `
SELECT array_agg(privilege_type)
Expand All @@ -289,7 +291,10 @@ WHERE grantee = $2
return fmt.Errorf("could not read privileges for schema %s: %w", dbName, err)
}

d.Set("privileges", pgArrayToSet(privileges))
granted := pgArrayToSet(privileges)
if !resourcePrivilegesEqual(granted, d) {
return d.Set("privileges", granted)
}
return nil
}

Expand All @@ -309,7 +314,10 @@ WHERE grantee = $2
return fmt.Errorf("could not read privileges for foreign data wrapper %s: %w", fdwName, err)
}

d.Set("privileges", pgArrayToSet(privileges))
granted := pgArrayToSet(privileges)
if !resourcePrivilegesEqual(granted, d) {
return d.Set("privileges", granted)
}
return nil
}

Expand All @@ -329,7 +337,10 @@ WHERE grantee = $2
return fmt.Errorf("could not read privileges for foreign server %s: %w", srvName, err)
}

d.Set("privileges", pgArrayToSet(privileges))
granted := pgArrayToSet(privileges)
if !resourcePrivilegesEqual(granted, d) {
return d.Set("privileges", granted)
}
return nil
}

Expand Down Expand Up @@ -426,10 +437,10 @@ func readRolePrivileges(txn *sql.Tx, d *schema.ResourceData) error {

switch objectType {
case "database":
return readDatabaseRolePriviges(txn, d, roleOID)
return readDatabaseRolePrivileges(txn, d, roleOID)

case "schema":
return readSchemaRolePriviges(txn, d, roleOID)
return readSchemaRolePrivileges(txn, d, roleOID)

case "foreign_data_wrapper":
return readForeignDataWrapperRolePrivileges(txn, d, roleOID)
Expand Down Expand Up @@ -502,8 +513,7 @@ GROUP BY pg_class.relname
}

privilegesSet := pgArrayToSet(privileges)

if !privilegesSet.Equal(d.Get("privileges").(*schema.Set)) {
if !resourcePrivilegesEqual(privilegesSet, d) {
// If any object doesn't have the same privileges as saved in the state,
// we return its privileges to force an update.
log.Printf(
Expand Down
77 changes: 77 additions & 0 deletions postgresql/resource_postgresql_grant_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1139,6 +1139,83 @@ resource "postgresql_grant" "test" {
})
}

func TestAccPostgresqlImplicitGrants(t *testing.T) {
Copy link
Owner

Choose a reason for hiding this comment

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

💪

skipIfNotAcc(t)

dbSuffix, teardown := setupTestDatabase(t, true, true)
defer teardown()

testTables := []string{"test_schema.test_table"}
createTestTables(t, dbSuffix, testTables, "")

dbName, roleName := getTestDBNames(dbSuffix)

// create a TF config with placeholder for privileges
// it will be filled in each step.
var testGrant = fmt.Sprintf(`
resource "postgresql_grant" "test" {
database = "%s"
role = "%s"
schema = "test_schema"
object_type = "table"
objects = ["test_table"]
privileges = %%s
}
`, dbName, roleName)

var testCheckTableGrants = func(grants ...string) resource.TestCheckFunc {
return func(*terraform.State) error {
return testCheckTablesPrivileges(t, dbName, roleName, []string{testTables[0]}, grants)
}
}
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testCheckCompatibleVersion(t, featurePrivileges)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(testGrant, `["ALL"]`),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"postgresql_grant.test", "id", fmt.Sprintf("%s_%s_test_schema_table_test_table", roleName, dbName),
),
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.#", "1"),
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.0", "test_table"),
testCheckTableGrants("SELECT", "INSERT", "UPDATE", "DELETE"),
),
},
{
Config: fmt.Sprintf(testGrant, `["SELECT"]`),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.#", "1"),
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.0", "test_table"),
testCheckTableGrants("SELECT"),
),
},
{
// Empty list means that privileges will be applied on all tables.
Config: fmt.Sprintf(testGrant, `["SELECT", "INSERT", "UPDATE", "DELETE"]`),
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.#", "1"),
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.0", "test_table"),
testCheckTableGrants("SELECT", "INSERT", "UPDATE", "DELETE"),
),
},
{
Config: fmt.Sprintf(testGrant, `[]`),
Destroy: true,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.#", "1"),
resource.TestCheckResourceAttr("postgresql_grant.test", "objects.0", "test_table"),
testCheckTableGrants(""),
),
},
},
})
}

func TestAccPostgresqlGrantSchema(t *testing.T) {
// create a TF config with placeholder for privileges
// it will be filled in each step.
Expand Down
Loading