forked from petoju/terraform-provider-mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_user.go
490 lines (425 loc) · 13.6 KB
/
resource_user.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
package mysql
import (
"context"
"errors"
"fmt"
"log"
"regexp"
"strings"
"github.com/hashicorp/go-version"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceUser() *schema.Resource {
return &schema.Resource{
CreateContext: CreateUser,
UpdateContext: UpdateUser,
ReadContext: ReadUser,
DeleteContext: DeleteUser,
Importer: &schema.ResourceImporter{
StateContext: ImportUser,
},
Schema: map[string]*schema.Schema{
"user": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"host": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "localhost",
},
"plaintext_password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
StateFunc: hashSum,
},
"password": {
Type: schema.TypeString,
Optional: true,
ConflictsWith: []string{"plaintext_password"},
Sensitive: true,
Deprecated: "Please use plaintext_password instead",
},
"auth_plugin": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
DiffSuppressFunc: NewEmptyStringSuppressFunc,
ConflictsWith: []string{"plaintext_password", "password"},
},
"aad_identity": {
Type: schema.TypeSet,
Optional: true,
ForceNew: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"type": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "user",
ValidateFunc: validation.StringInSlice([]string{
"user",
"group",
"service_principal",
}, false),
},
"identity": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
},
},
},
"auth_string_hashed": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DiffSuppressFunc: NewEmptyStringSuppressFunc,
ConflictsWith: []string{"plaintext_password", "password"},
},
"tls_option": {
Type: schema.TypeString,
Optional: true,
Default: "NONE",
},
"retain_old_password": {
Type: schema.TypeBool,
Optional: true,
},
},
}
}
func checkRetainCurrentPasswordSupport(ctx context.Context, meta interface{}) error {
ver, _ := version.NewVersion("8.0.14")
if getVersionFromMeta(ctx, meta).LessThan(ver) {
return errors.New("MySQL version must be at least 8.0.14")
}
return nil
}
func CreateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return diag.FromErr(err)
}
var authStm string
var auth string
var createObj = "USER"
if v, ok := d.GetOk("auth_plugin"); ok {
auth = v.(string)
}
if len(auth) > 0 {
if auth == "aad_auth" {
// aad_auth is plugin but Microsoft uses another statement to create this kind of users
createObj = "AADUSER"
if _, ok := d.GetOk("aad_identity"); !ok {
return diag.Errorf("aad_identity is required for aad_auth")
}
} else if auth == "AWSAuthenticationPlugin" {
authStm = " IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS'"
} else {
// mysql_no_login, auth_pam, ...
authStm = " IDENTIFIED WITH " + auth
}
}
if v, ok := d.GetOk("auth_string_hashed"); ok {
hashed := v.(string)
if hashed != "" {
if authStm == "" {
return diag.Errorf("auth_string_hashed is not supported for auth plugin %s", auth)
}
authStm = fmt.Sprintf("%s AS '%s'", authStm, hashed)
}
}
var stmtSQL string
if createObj == "AADUSER" {
var aadIdentity = d.Get("aad_identity").(*schema.Set).List()[0].(map[string]interface{})
if aadIdentity["type"].(string) == "service_principal" {
// CREATE AADUSER 'mysqlProtocolLoginName"@"mysqlHostRestriction' IDENTIFIED BY 'identityId'
stmtSQL = fmt.Sprintf("CREATE AADUSER '%s'@'%s' IDENTIFIED BY '%s'",
d.Get("user").(string),
d.Get("host").(string),
aadIdentity["identity"].(string))
} else {
// CREATE AADUSER 'identityName"@"mysqlHostRestriction' AS 'mysqlProtocolLoginName'
stmtSQL = fmt.Sprintf("CREATE AADUSER '%s'@'%s' AS '%s'",
aadIdentity["identity"].(string),
d.Get("host").(string),
d.Get("user").(string))
}
} else {
stmtSQL = fmt.Sprintf("CREATE USER '%s'@'%s'",
d.Get("user").(string),
d.Get("host").(string))
}
var password string
if v, ok := d.GetOk("plaintext_password"); ok {
password = v.(string)
} else {
password = d.Get("password").(string)
}
if auth == "AWSAuthenticationPlugin" && d.Get("host").(string) == "localhost" {
return diag.Errorf("cannot use IAM auth against localhost")
}
if authStm != "" {
stmtSQL = stmtSQL + authStm
} else if password != "" {
stmtSQL = stmtSQL + fmt.Sprintf(" IDENTIFIED BY '%s'", password)
}
requiredVersion, _ := version.NewVersion("5.7.0")
var updateStmtSql = ""
if getVersionFromMeta(ctx, meta).GreaterThan(requiredVersion) && d.Get("tls_option").(string) != "" {
if createObj == "AADUSER" {
updateStmtSql = fmt.Sprintf("ALTER USER '%s'@'%s' REQUIRE %s",
d.Get("user").(string),
d.Get("host").(string),
d.Get("tls_option").(string))
} else {
stmtSQL += fmt.Sprintf(" REQUIRE %s", d.Get("tls_option").(string))
}
}
retainPassword := d.Get("retain_old_password").(bool)
if retainPassword {
err := checkRetainCurrentPasswordSupport(ctx, meta)
if err != nil {
return diag.Errorf("cannot use retain_current_password: %v", err)
}
}
log.Println("[DEBUG] Executing statement:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed executing SQL: %v", err)
}
user := fmt.Sprintf("%s@%s", d.Get("user").(string), d.Get("host").(string))
d.SetId(user)
if updateStmtSql != "" {
log.Println("[DEBUG] Executing statement:", updateStmtSql)
_, err = db.ExecContext(ctx, updateStmtSql)
if err != nil {
d.Set("tls_option", "")
return diag.Errorf("failed executing SQL: %v", err)
}
}
return nil
}
func getSetPasswordStatement(ctx context.Context, meta interface{}, retainPassword bool) (string, error) {
if retainPassword {
return "ALTER USER ?@? IDENTIFIED BY ? RETAIN CURRENT PASSWORD", nil
}
/* ALTER USER syntax introduced in MySQL 5.7.6 deprecates SET PASSWORD (GH-8230) */
ver, _ := version.NewVersion("5.7.6")
if getVersionFromMeta(ctx, meta).LessThan(ver) {
return "SET PASSWORD FOR ?@? = PASSWORD(?)", nil
}
return "ALTER USER ?@? IDENTIFIED BY ?", nil
}
func UpdateUser(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return diag.FromErr(err)
}
var auth string
if v, ok := d.GetOk("auth_plugin"); ok {
auth = v.(string)
}
if len(auth) > 0 {
if d.HasChange("tls_option") || d.HasChange("auth_plugin") || d.HasChange("auth_string_hashed") {
var stmtSQL string
authString := ""
if d.Get("auth_string_hashed").(string) != "" {
authString = fmt.Sprintf("IDENTIFIED WITH %s AS '%s'", d.Get("auth_plugin"), d.Get("auth_string_hashed"))
}
stmtSQL = fmt.Sprintf("ALTER USER '%s'@'%s' %s REQUIRE %s",
d.Get("user").(string),
d.Get("host").(string),
authString,
d.Get("tls_option").(string))
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err := db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed running query: %v", err)
}
}
}
var newpw interface{}
if d.HasChange("plaintext_password") {
_, newpw = d.GetChange("plaintext_password")
} else if d.HasChange("password") {
_, newpw = d.GetChange("password")
} else {
newpw = nil
}
retainPassword := d.Get("retain_old_password").(bool)
if retainPassword {
err := checkRetainCurrentPasswordSupport(ctx, meta)
if err != nil {
return diag.Errorf("cannot use retain_current_password: %v", err)
}
}
if newpw != nil {
stmtSQL, err := getSetPasswordStatement(ctx, meta, retainPassword)
if err != nil {
return diag.Errorf("failed getting change password statement: %v", err)
}
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL,
d.Get("user").(string),
d.Get("host").(string),
newpw.(string))
if err != nil {
return diag.Errorf("failed changing password: %v", err)
}
}
requiredVersion, _ := version.NewVersion("5.7.0")
if d.HasChange("tls_option") && getVersionFromMeta(ctx, meta).GreaterThan(requiredVersion) {
var stmtSQL string
stmtSQL = fmt.Sprintf("ALTER USER '%s'@'%s' REQUIRE %s",
d.Get("user").(string),
d.Get("host").(string),
d.Get("tls_option").(string))
log.Println("[DEBUG] Executing query:", stmtSQL)
_, err := db.ExecContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed setting require tls option: %v", err)
}
}
return nil
}
func ReadUser(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return diag.FromErr(err)
}
requiredVersion, _ := version.NewVersion("5.7.0")
if getVersionFromMeta(ctx, meta).GreaterThan(requiredVersion) {
stmt := "SHOW CREATE USER ?@?"
var createUserStmt string
err := db.QueryRowContext(ctx, stmt, d.Get("user").(string), d.Get("host").(string)).Scan(&createUserStmt)
if err != nil {
errorNumber := mysqlErrorNumber(err)
if errorNumber == unknownUserErrCode || errorNumber == userNotFoundErrCode {
d.SetId("")
return nil
}
return diag.Errorf("failed getting user: %v", err)
}
// Examples of create user:
// CREATE USER 'some_app'@'%' IDENTIFIED WITH 'mysql_native_password' AS '*0something' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK
// CREATE USER `jdoe-tf-test-47`@`example.com` IDENTIFIED WITH 'caching_sha2_password' REQUIRE NONE PASSWORD EXPIRE DEFAULT ACCOUNT UNLOCK PASSWORD HISTORY DEFAULT PASSWORD REUSE INTERVAL DEFAULT PASSWORD REQUIRE CURRENT DEFAULT
// CREATE USER `jdoe`@`example.com` IDENTIFIED WITH 'caching_sha2_password' AS '$A$005$i`xay#fG/\' TrbkNA82' REQUIRE NONE PASSWORD
re := regexp.MustCompile("^CREATE USER ['`]([^'`]*)['`]@['`]([^'`]*)['`] IDENTIFIED WITH ['`]([^'`]*)['`] (?:AS '((?:.*?[^\\\\])?)' )?REQUIRE ([^ ]*)")
if m := re.FindStringSubmatch(createUserStmt); len(m) == 6 {
d.Set("user", m[1])
d.Set("host", m[2])
d.Set("auth_plugin", m[3])
d.Set("tls_option", m[5])
if m[3] == "aad_auth" {
// AADGroup:98e61c8d-e104-4f8c-b1a6-7ae873617fe6:upn:Doe_Family_Group
// AADUser:98e61c8d-e104-4f8c-b1a6-7ae873617fe6:upn:little.johny@does.onmicrosoft.com
// AADSP:98e61c8d-e104-4f8c-b1a6-7ae873617fe6:upn:mysqlUserName - for MySQL Flexible Server
// AADApp:98e61c8d-e104-4f8c-b1a6-7ae873617fe6:upn:mysqlUserName - for MySQL Single Server
parts := strings.Split(m[4], ":")
if parts[0] == "AADSP" || parts[0] == "AADApp" {
// service principals are referenced by UUID only
d.Set("aad_identity", []map[string]interface{}{
{
"type": "service_principal",
"identity": parts[1],
},
})
} else if len(parts) >= 4 {
// users and groups should be referenced by UPN / group name
if parts[0] == "AADUser" {
d.Set("aad_identity", []map[string]interface{}{
{
"type": "user",
"identity": strings.Join(parts[3:], ":"),
},
})
} else {
d.Set("aad_identity", []map[string]interface{}{
{
"type": "group",
"identity": strings.Join(parts[3:], ":"),
},
})
}
} else {
return diag.Errorf("AAD identity couldn't be parsed - it is %s", m[4])
}
} else {
d.Set("auth_string_hashed", m[4])
}
return nil
}
// Try 2 - just whether the user is there.
re2 := regexp.MustCompile("^CREATE USER")
if m := re2.FindStringSubmatch(createUserStmt); m != nil {
// Ok, we have at least something - it's probably in MariaDB.
return nil
}
return diag.Errorf("Create user couldn't be parsed - it is %s", createUserStmt)
} else {
// Worse user detection, only for compat with MySQL 5.6
stmtSQL := fmt.Sprintf("SELECT USER FROM mysql.user WHERE USER='%s'",
d.Get("user").(string))
log.Println("[DEBUG] Executing statement:", stmtSQL)
rows, err := db.QueryContext(ctx, stmtSQL)
if err != nil {
return diag.Errorf("failed getting user from DB: %v", err)
}
defer rows.Close()
if !rows.Next() && rows.Err() == nil {
d.SetId("")
return nil
}
if rows.Err() != nil {
return diag.Errorf("failed getting rows: %v", rows.Err())
}
}
return nil
}
func DeleteUser(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
db, err := getDatabaseFromMeta(ctx, meta)
if err != nil {
return diag.FromErr(err)
}
stmtSQL := fmt.Sprintf("DROP USER ?@?")
log.Println("[DEBUG] Executing statement:", stmtSQL)
_, err = db.ExecContext(ctx, stmtSQL,
d.Get("user").(string),
d.Get("host").(string))
if err == nil {
d.SetId("")
}
return diag.FromErr(err)
}
func ImportUser(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
userHost := strings.SplitN(d.Id(), "@", 2)
if len(userHost) != 2 {
return nil, fmt.Errorf("wrong ID format %s (expected USER@HOST)", d.Id())
}
user := userHost[0]
host := userHost[1]
d.Set("user", user)
d.Set("host", host)
err := ReadUser(ctx, d, meta)
var ferror error
if err.HasError() {
ferror = fmt.Errorf("failed reading user: %v", err)
}
return []*schema.ResourceData{d}, ferror
}
func NewEmptyStringSuppressFunc(k, old, new string, d *schema.ResourceData) bool {
if new == "" {
return true
}
return false
}