@@ -13,11 +13,19 @@ type PostgreSQLUser struct {
1313 GrantRoles []string
1414}
1515
16+ type UserAuthenticationType string
17+
18+ const (
19+ UserAuthenticationTypeIAM UserAuthenticationType = "iam"
20+ UserAuthenticationTypePassword UserAuthenticationType = "password"
21+ )
22+
1623// Make sure that the given users exist in database cluster and have only the
17- // role memberships specified. If withPasswords is true, set each user's password
18- // to its username. Otherwise remove each user's password.
24+ // role memberships specified. If authType is UserAuthenticationTypePassword,
25+ // set each user's password to its username. Otherwise remove each user's password
26+ // and also add the rds_iam role for each user.
1927// All operations are done in a single transaction.
20- func EnsureUsersWithRoles (db * sqlx.DB , users []PostgreSQLUser , withPasswords bool ) error {
28+ func EnsureUsersWithRoles (db * sqlx.DB , users []PostgreSQLUser , authType UserAuthenticationType ) error {
2129 tx , err := db .Begin ()
2230 if err != nil {
2331 return fmt .Errorf ("Error starting transaction: %w" , err )
@@ -75,7 +83,11 @@ func EnsureUsersWithRoles(db *sqlx.DB, users []PostgreSQLUser, withPasswords boo
7583 // But we will just worry about roles.
7684
7785 // Add roles
78- for _ , role := range user .GrantRoles {
86+ roles := user .GrantRoles
87+ if authType == UserAuthenticationTypeIAM {
88+ roles = append (roles , "rds_iam" )
89+ }
90+ for _ , role := range roles {
7991 grantSQL := fmt .Sprintf ("GRANT %s TO %s" , pq .QuoteIdentifier (role ), pq .QuoteIdentifier (user .Username ))
8092 _ , err = tx .Exec (grantSQL )
8193 if err != nil {
@@ -84,7 +96,8 @@ func EnsureUsersWithRoles(db *sqlx.DB, users []PostgreSQLUser, withPasswords boo
8496 }
8597
8698 // Set or remove password
87- if withPasswords {
99+ switch authType {
100+ case UserAuthenticationTypePassword :
88101 _ , err = tx .Exec (
89102 fmt .Sprintf ("ALTER USER %s WITH PASSWORD %s" ,
90103 pq .QuoteIdentifier (user .Username ),
@@ -93,14 +106,16 @@ func EnsureUsersWithRoles(db *sqlx.DB, users []PostgreSQLUser, withPasswords boo
93106 if err != nil {
94107 return fmt .Errorf ("Failed to set password for user %q: %w" , user .Username , err )
95108 }
96- } else {
109+ case UserAuthenticationTypeIAM :
97110 _ , err = tx .Exec (
98111 fmt .Sprintf ("ALTER USER %s WITH PASSWORD NULL" ,
99112 pq .QuoteIdentifier (user .Username )),
100113 )
101114 if err != nil {
102115 return fmt .Errorf ("Failed to remove password for user %q: %w" , user .Username , err )
103116 }
117+ default :
118+ return fmt .Errorf ("Invalid authType %q" , authType )
104119 }
105120 }
106121
0 commit comments