feat(postgresql): add user and database authorization management (#14460)

* feat(postgresql): add user and database authorization management

* fix(postgresql): reuse existing roles during app recovery
This commit is contained in:
ssongliu
2026-11-18 09:53:22 +08:00
committed by GitHub
parent 6d8d3b25b1
commit 148e1981b0
46 changed files with 2113 additions and 366 deletions
+4 -1
View File
@@ -14,6 +14,8 @@ import (
)
type PostgresqlClient interface {
ExecSQL(command string, timeout uint) error
ExecSQLForRows(command string, timeout uint) ([]string, error)
Create(info client.CreateInfo) error
CreateUser(info client.CreateInfo, withDeleteDB bool) error
Delete(info client.DeleteInfo) error
@@ -28,7 +30,7 @@ type PostgresqlClient interface {
func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) {
if conn.From == "local" {
connArgs := []string{"exec", "-e", fmt.Sprintf("PGPASSWORD=%s", conn.Password), conn.Address, "psql", "-t", "-U", conn.Username, "-c"}
connArgs := []string{"exec", "-e", fmt.Sprintf("PGPASSWORD=%s", conn.Password), conn.Address, "psql", "-A", "-t", "-U", conn.Username, "-c"}
return client.NewLocal(connArgs, conn.Address, conn.Username, conn.Password, conn.Database), nil
}
escapedUsername := url.QueryEscape(conn.Username)
@@ -45,6 +47,7 @@ func NewPostgresqlClient(conn client.DBInfo) (PostgresqlClient, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(conn.Timeout)*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, err
}
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+5 -4
View File
@@ -19,10 +19,11 @@ type DBInfo struct {
}
type CreateInfo struct {
Name string `json:"name"`
Username string `json:"userName"`
Password string `json:"password"`
SuperUser bool `json:"superUser"`
ExistingUser bool `json:"existingUser"`
Name string `json:"name"`
Username string `json:"userName"`
Password string `json:"password"`
SuperUser bool `json:"superUser"`
Timeout uint `json:"timeout"` // second
}
+30 -38
View File
@@ -31,19 +31,26 @@ func NewLocal(command []string, containerName, username, password, database stri
}
func (r *Local) Create(info CreateInfo) error {
createSql := fmt.Sprintf("CREATE DATABASE \"%s\"", info.Name)
if err := r.ExecSQL(createSql, info.Timeout); err != nil {
if err := r.ExecSQL("CREATE DATABASE "+QuoteIdentifier(info.Name), info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
return buserr.New("ErrDatabaseIsExist")
}
return err
}
if err := r.CreateUser(info, true); err != nil {
_ = r.ExecSQL(fmt.Sprintf("DROP DATABASE \"%s\"", info.Name), info.Timeout)
var err error
if info.ExistingUser {
if !info.SuperUser {
err = GrantUser(r, info.Name, info.Username, false)
}
} else {
err = r.CreateUser(info, false)
}
if err != nil {
if cleanupErr := r.ExecSQL("DROP DATABASE "+QuoteIdentifier(info.Name), info.Timeout); cleanupErr != nil {
return fmt.Errorf("%w; cleanup database: %v", err, cleanupErr)
}
return err
}
return nil
}
@@ -52,48 +59,30 @@ func (r *Local) ChangePrivileges(info Privileges) error {
if !info.SuperUser {
super = "NOSUPERUSER"
}
changeSql := fmt.Sprintf("ALTER USER \"%s\" WITH %s", info.Username, super)
changeSql := "ALTER USER " + QuoteIdentifier(info.Username) + " WITH " + super
return r.ExecSQL(changeSql, info.Timeout)
}
func (r *Local) CreateUser(info CreateInfo, withDeleteDB bool) error {
createSql := fmt.Sprintf("CREATE USER \"%s\" WITH PASSWORD '%s'", info.Username, info.Password)
if err := r.ExecSQL(createSql, info.Timeout); err != nil {
privileges := "NOSUPERUSER"
if info.SuperUser {
privileges = "SUPERUSER"
}
statement := "CREATE USER " + QuoteIdentifier(info.Username) + " WITH " + privileges + " PASSWORD " + QuoteLiteral(info.Password)
if err := r.ExecSQL(statement, info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
return buserr.New("ErrUserIsExist")
}
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
}
return err
}
if info.SuperUser {
if err := r.ChangePrivileges(Privileges{SuperUser: true, Username: info.Username, Timeout: info.Timeout}); err != nil {
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
if info.Name != "" && !info.SuperUser {
if err := GrantUser(r, info.Name, info.Username, false); err != nil {
if cleanupErr := r.ExecSQL("DROP USER "+QuoteIdentifier(info.Username), info.Timeout); cleanupErr != nil {
return fmt.Errorf("%w; cleanup user: %v", err, cleanupErr)
}
return err
}
}
grantStr := fmt.Sprintf("GRANT ALL PRIVILEGES ON DATABASE \"%s\" TO \"%s\"", info.Name, info.Username)
if err := r.ExecSQL(grantStr, info.Timeout); err != nil {
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
}
return err
}
return nil
}
@@ -106,12 +95,15 @@ func (r *Local) Delete(info DeleteInfo) error {
if inUse && !info.ForceDelete {
return buserr.WithDetail("ErrInUsed", info.Name, nil)
}
dropSql := fmt.Sprintf("DROP DATABASE \"%s\"", info.Name)
dropSql := "DROP DATABASE " + QuoteIdentifier(info.Name)
if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete {
return fmt.Errorf("drop database failed, err: %v", err)
}
}
dropSql := fmt.Sprintf("DROP USER \"%s\"", info.Username)
if info.Username == "" {
return nil
}
dropSql := "DROP USER " + QuoteIdentifier(info.Username)
if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete {
return fmt.Errorf("drop user failed, err: %v", err)
}
@@ -119,7 +111,7 @@ func (r *Local) Delete(info DeleteInfo) error {
}
func (r *Local) ChangePassword(info PasswordChangeInfo) error {
changeSql := fmt.Sprintf("ALTER USER \"%s\" WITH PASSWORD '%s'", info.Username, info.Password)
changeSql := "ALTER USER " + QuoteIdentifier(info.Username) + " WITH PASSWORD " + QuoteLiteral(info.Password)
if err := r.ExecSQL(changeSql, info.Timeout); err != nil {
return err
}
+30 -36
View File
@@ -70,58 +70,49 @@ func NewRemote(db Remote) *Remote {
return &db
}
func (r *Remote) Create(info CreateInfo) error {
createSql := fmt.Sprintf("CREATE DATABASE \"%s\"", info.Name)
if err := r.ExecSQL(createSql, info.Timeout); err != nil {
if err := r.ExecSQL("CREATE DATABASE "+QuoteIdentifier(info.Name), info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
return buserr.New("ErrDatabaseIsExist")
}
return err
}
if err := r.CreateUser(info, true); err != nil {
var err error
if info.ExistingUser {
if !info.SuperUser {
err = GrantUser(r, info.Name, info.Username, false)
}
} else {
err = r.CreateUser(info, false)
}
if err != nil {
if cleanupErr := r.ExecSQL("DROP DATABASE "+QuoteIdentifier(info.Name), info.Timeout); cleanupErr != nil {
return fmt.Errorf("%w; cleanup database: %v", err, cleanupErr)
}
return err
}
return nil
}
func (r *Remote) CreateUser(info CreateInfo, withDeleteDB bool) error {
createSql := fmt.Sprintf("CREATE USER \"%s\" WITH PASSWORD '%s'", info.Username, info.Password)
if err := r.ExecSQL(createSql, info.Timeout); err != nil {
privileges := "NOSUPERUSER"
if info.SuperUser {
privileges = "SUPERUSER"
}
statement := "CREATE USER " + QuoteIdentifier(info.Username) + " WITH " + privileges + " PASSWORD " + QuoteLiteral(info.Password)
if err := r.ExecSQL(statement, info.Timeout); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "already exists") {
return buserr.New("ErrUserIsExist")
}
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
}
return err
}
if info.SuperUser {
if err := r.ChangePrivileges(Privileges{SuperUser: true, Username: info.Username, Timeout: info.Timeout}); err != nil {
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
if info.Name != "" && !info.SuperUser {
if err := GrantUser(r, info.Name, info.Username, false); err != nil {
if cleanupErr := r.ExecSQL("DROP USER "+QuoteIdentifier(info.Username), info.Timeout); cleanupErr != nil {
return fmt.Errorf("%w; cleanup user: %v", err, cleanupErr)
}
return err
}
}
grantSql := fmt.Sprintf("GRANT ALL PRIVILEGES ON DATABASE \"%s\" TO \"%s\"", info.Name, info.Username)
if err := r.ExecSQL(grantSql, info.Timeout); err != nil {
if withDeleteDB {
_ = r.Delete(DeleteInfo{
Name: info.Name,
Username: info.Username,
ForceDelete: true,
Timeout: 300})
}
return err
}
return nil
}
@@ -134,12 +125,15 @@ func (r *Remote) Delete(info DeleteInfo) error {
if inUse && !info.ForceDelete {
return buserr.WithDetail("ErrInUsed", info.Name, nil)
}
dropSql := fmt.Sprintf("DROP DATABASE \"%s\"", info.Name)
dropSql := "DROP DATABASE " + QuoteIdentifier(info.Name)
if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete {
return fmt.Errorf("drop database failed, err: %v", err)
}
}
dropSql := fmt.Sprintf("DROP USER \"%s\"", info.Username)
if info.Username == "" {
return nil
}
dropSql := "DROP USER " + QuoteIdentifier(info.Username)
if err := r.ExecSQL(dropSql, info.Timeout); err != nil && !info.ForceDelete {
return fmt.Errorf("drop user failed, err: %v", err)
}
@@ -169,11 +163,11 @@ func (r *Remote) ChangePrivileges(info Privileges) error {
if !info.SuperUser {
super = "NOSUPERUSER"
}
return r.ExecSQL(fmt.Sprintf("ALTER USER \"%s\" WITH %s", info.Username, super), info.Timeout)
return r.ExecSQL("ALTER USER "+QuoteIdentifier(info.Username)+" WITH "+super, info.Timeout)
}
func (r *Remote) ChangePassword(info PasswordChangeInfo) error {
return r.ExecSQL(fmt.Sprintf("ALTER USER \"%s\" WITH ENCRYPTED PASSWORD '%s'", info.Username, info.Password), info.Timeout)
return r.ExecSQL("ALTER USER "+QuoteIdentifier(info.Username)+" WITH PASSWORD "+QuoteLiteral(info.Password), info.Timeout)
}
func (r *Remote) Backup(info BackupInfo) error {
+73
View File
@@ -0,0 +1,73 @@
package client
import (
"context"
"encoding/json"
"strings"
"time"
)
type UserInfo struct {
Username string `json:"username"`
SuperUser bool `json:"superUser"`
Protected bool `json:"protected"`
Databases []string `json:"databases"`
}
type UserClient interface {
ExecSQL(command string, timeout uint) error
ExecSQLForRows(command string, timeout uint) ([]string, error)
}
func ListUsers(cli UserClient) ([]UserInfo, error) {
rows, err := cli.ExecSQLForRows(`SELECT COALESCE(json_agg(u ORDER BY u.username), '[]'::json)::text FROM (
SELECT r.rolname AS username, r.rolsuper AS "superUser",
(r.rolname = current_user OR r.rolname = 'postgres' OR r.rolname LIKE 'pg\_%') AS protected,
COALESCE((SELECT json_agg(d.datname ORDER BY d.datname) FROM pg_database d
WHERE NOT d.datistemplate AND EXISTS (
SELECT 1 FROM aclexplode(d.datacl) a WHERE a.grantee = r.oid
)), '[]'::json) AS databases
FROM pg_roles r WHERE r.rolcanlogin
) u`, 300)
if err != nil {
return nil, err
}
var users []UserInfo
err = json.Unmarshal([]byte(strings.TrimSpace(strings.Join(rows, "\n"))), &users)
return users, err
}
func GrantUser(cli UserClient, database, username string, revoke bool) error {
statement := "GRANT ALL PRIVILEGES ON DATABASE " + QuoteIdentifier(database) + " TO " + QuoteIdentifier(username)
if revoke {
statement = "REVOKE ALL PRIVILEGES ON DATABASE " + QuoteIdentifier(database) + " FROM " + QuoteIdentifier(username)
}
return cli.ExecSQL(statement, 300)
}
func QuoteIdentifier(value string) string {
return `"` + strings.ReplaceAll(value, `"`, `""`) + `"`
}
func QuoteLiteral(value string) string {
return `E'` + strings.ReplaceAll(strings.ReplaceAll(value, `\`, `\\`), `'`, `''`) + `'`
}
func (r *Remote) ExecSQLForRows(command string, timeout uint) ([]string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
rows, err := r.Client.QueryContext(ctx, command)
if err != nil {
return nil, err
}
defer rows.Close()
var result []string
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
return nil, err
}
result = append(result, value)
}
return result, rows.Err()
}