forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -2,17 +2,19 @@ package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHost = "localhost"
|
||||
defaultPort = 5432
|
||||
defaultDatabase = "messenger"
|
||||
defaultUser = "messenger"
|
||||
defaultSSLMode = "disable"
|
||||
defaultMaxConns = int32(10)
|
||||
defaultMinConns = int32(1)
|
||||
defaultMaxConnLifetime = time.Hour
|
||||
@@ -26,6 +28,9 @@ func normalize(cfg config.Postgres) (config.Postgres, error) {
|
||||
cfg.Host = defaultHost
|
||||
}
|
||||
|
||||
if strings.ContainsAny(cfg.Host, "/, \t\r\n") {
|
||||
return cfg, errors.New("postgres: host must be a single tcp hostname or ip address")
|
||||
}
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
@@ -34,12 +39,14 @@ func normalize(cfg config.Postgres) (config.Postgres, error) {
|
||||
cfg.Database = defaultDatabase
|
||||
}
|
||||
|
||||
if cfg.User == "" {
|
||||
cfg.User = defaultUser
|
||||
if cfg.User == "" || cfg.Password == "" {
|
||||
return cfg, errors.New("postgres: user and password are required")
|
||||
}
|
||||
|
||||
if cfg.SSLMode == "" {
|
||||
cfg.SSLMode = defaultSSLMode
|
||||
cfg.SSLMode = "verify-full"
|
||||
}
|
||||
if cfg.SSLMode != "verify-full" {
|
||||
return cfg, errors.New("postgres: ssl_mode must be verify-full")
|
||||
}
|
||||
|
||||
if cfg.MaxConns == 0 {
|
||||
@@ -72,3 +79,33 @@ func normalize(cfg config.Postgres) (config.Postgres, error) {
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// PoolConfig is shared by application pools and operator migration connections.
|
||||
// Every new connection verifies the hostname, current trust bundle and CRLs.
|
||||
func PoolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return poolConfig(cfg)
|
||||
}
|
||||
|
||||
func poolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
// pgx parse errors include the DSN, which contains a password.
|
||||
return nil, errors.New("postgres: invalid connection configuration")
|
||||
}
|
||||
poolCfg.ConnConfig.TLSConfig = clientTLS
|
||||
poolCfg.ConnConfig.Fallbacks = nil
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
return poolCfg, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user