forked from hashicorp/terraform-provider-postgresql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_postgresql_grant_role.go
218 lines (178 loc) · 4.96 KB
/
resource_postgresql_grant_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
package postgresql
import (
"database/sql"
"fmt"
"log"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/lib/pq"
)
const (
// This returns the role membership for role, grant_role
getGrantRoleQuery = `
SELECT
pg_get_userbyid(member) as role,
pg_get_userbyid(roleid) as grant_role,
admin_option
FROM
pg_auth_members
WHERE
pg_get_userbyid(member) = $1 AND
pg_get_userbyid(roleid) = $2;
`
)
func resourcePostgreSQLGrantRole() *schema.Resource {
return &schema.Resource{
Create: resourcePostgreSQLGrantRoleCreate,
Read: resourcePostgreSQLGrantRoleRead,
Delete: resourcePostgreSQLGrantRoleDelete,
Schema: map[string]*schema.Schema{
"role": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the role to grant grant_role",
},
"grant_role": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The name of the role that is granted to role",
},
"with_admin_option": {
Type: schema.TypeBool,
Optional: true,
ForceNew: true,
Default: false,
Description: "Permit the grant recipient to grant it to others",
},
},
}
}
func resourcePostgreSQLGrantRoleRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
if !client.featureSupported(featurePrivileges) {
return fmt.Errorf(
"postgresql_grant_role resource is not supported for this Postgres version (%s)",
client.version,
)
}
client.catalogLock.RLock()
defer client.catalogLock.RUnlock()
return readGrantRole(client.DB(), d)
}
func resourcePostgreSQLGrantRoleCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
if !client.featureSupported(featurePrivileges) {
return fmt.Errorf(
"postgresql_grant_role resource is not supported for this Postgres version (%s)",
client.version,
)
}
client.catalogLock.Lock()
defer client.catalogLock.Unlock()
txn, err := startTransaction(client, "")
if err != nil {
return err
}
defer deferredRollback(txn)
// Revoke the granted roles before granting them again.
if err = revokeRole(txn, d); err != nil {
return err
}
if err = grantRole(txn, d); err != nil {
return err
}
if err = txn.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
d.SetId(generateGrantRoleID(d))
return readGrantRole(client.DB(), d)
}
func resourcePostgreSQLGrantRoleDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*Client)
if !client.featureSupported(featurePrivileges) {
return fmt.Errorf(
"postgresql_grant_role resource is not supported for this Postgres version (%s)",
client.version,
)
}
client.catalogLock.Lock()
defer client.catalogLock.Unlock()
txn, err := startTransaction(client, "")
if err != nil {
return err
}
defer deferredRollback(txn)
if err = revokeRole(txn, d); err != nil {
return err
}
if err = txn.Commit(); err != nil {
return fmt.Errorf("could not commit transaction: %w", err)
}
return nil
}
func readGrantRole(db QueryAble, d *schema.ResourceData) error {
var roleName, grantRoleName string
var withAdminOption bool
grantRoleID := d.Id()
values := []interface{}{
&roleName,
&grantRoleName,
&withAdminOption,
}
err := db.QueryRow(getGrantRoleQuery, d.Get("role"), d.Get("grant_role")).Scan(values...)
switch {
case err == sql.ErrNoRows:
log.Printf("[WARN] PostgreSQL grant role (%q) not found", grantRoleID)
d.SetId("")
return nil
case err != nil:
return fmt.Errorf("Error reading grant role: %w", err)
}
d.Set("role", roleName)
d.Set("grant_role", grantRoleName)
d.Set("with_admin_option", withAdminOption)
d.SetId(generateGrantRoleID(d))
return nil
}
func createGrantRoleQuery(d *schema.ResourceData) string {
grantRole, _ := d.Get("grant_role").(string)
role, _ := d.Get("role").(string)
query := fmt.Sprintf(
"GRANT %s TO %s",
pq.QuoteIdentifier(grantRole),
pq.QuoteIdentifier(role),
)
if wao, _ := d.Get("with_admin_option").(bool); wao {
query = query + " WITH ADMIN OPTION"
}
return query
}
func createRevokeRoleQuery(d *schema.ResourceData) string {
grantRole, _ := d.Get("grant_role").(string)
role, _ := d.Get("role").(string)
return fmt.Sprintf(
"REVOKE %s FROM %s",
pq.QuoteIdentifier(grantRole),
pq.QuoteIdentifier(role),
)
}
func grantRole(txn *sql.Tx, d *schema.ResourceData) error {
query := createGrantRoleQuery(d)
if _, err := txn.Exec(query); err != nil {
return fmt.Errorf("could not execute grant query: %w", err)
}
return nil
}
func revokeRole(txn *sql.Tx, d *schema.ResourceData) error {
query := createRevokeRoleQuery(d)
if _, err := txn.Exec(query); err != nil {
return fmt.Errorf("could not execute revoke query: %w", err)
}
return nil
}
func generateGrantRoleID(d *schema.ResourceData) string {
return strings.Join([]string{d.Get("role").(string), d.Get("grant_role").(string), strconv.FormatBool(d.Get("with_admin_option").(bool))}, "_")
}