-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathsql.go
87 lines (70 loc) · 2.1 KB
/
sql.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
package credsutil
import (
"context"
"fmt"
"strings"
"time"
"github.com/hashicorp/vault/sdk/database/dbplugin"
)
const (
NoneLength int = -1
)
// SQLCredentialsProducer implements CredentialsProducer and provides a generic credentials producer for most sql database types.
type SQLCredentialsProducer struct {
DisplayNameLen int
RoleNameLen int
UsernameLen int
Separator string
LowercaseUsername bool
}
func (scp *SQLCredentialsProducer) GenerateCredentials(ctx context.Context) (string, error) {
password, err := scp.GeneratePassword()
if err != nil {
return "", err
}
return password, nil
}
func (scp *SQLCredentialsProducer) GenerateUsername(config dbplugin.UsernameConfig) (string, error) {
username := "v"
displayName := config.DisplayName
if scp.DisplayNameLen > 0 && len(displayName) > scp.DisplayNameLen {
displayName = displayName[:scp.DisplayNameLen]
} else if scp.DisplayNameLen == NoneLength {
displayName = ""
}
if len(displayName) > 0 {
username = fmt.Sprintf("%s%s%s", username, scp.Separator, displayName)
}
roleName := config.RoleName
if scp.RoleNameLen > 0 && len(roleName) > scp.RoleNameLen {
roleName = roleName[:scp.RoleNameLen]
} else if scp.RoleNameLen == NoneLength {
roleName = ""
}
if len(roleName) > 0 {
username = fmt.Sprintf("%s%s%s", username, scp.Separator, roleName)
}
userUUID, err := RandomAlphaNumeric(20, false)
if err != nil {
return "", err
}
username = fmt.Sprintf("%s%s%s", username, scp.Separator, userUUID)
username = fmt.Sprintf("%s%s%s", username, scp.Separator, fmt.Sprint(time.Now().Unix()))
if scp.UsernameLen > 0 && len(username) > scp.UsernameLen {
username = username[:scp.UsernameLen]
}
if scp.LowercaseUsername {
username = strings.ToLower(username)
}
return username, nil
}
func (scp *SQLCredentialsProducer) GeneratePassword() (string, error) {
password, err := RandomAlphaNumeric(20, true)
if err != nil {
return "", err
}
return password, nil
}
func (scp *SQLCredentialsProducer) GenerateExpiration(ttl time.Time) (string, error) {
return ttl.Format("2006-01-02 15:04:05-0700"), nil
}