Add authentication mismatch detection and pgpass support

Phase 1: Detection & Guidance
- Detect OS user vs DB user mismatch
- Identify PostgreSQL authentication method (peer/ident/md5)
- Show helpful error messages with 4 solutions:
  1. sudo -u <user> (for peer auth)
  2. ~/.pgpass file (recommended)
  3. PGPASSWORD env variable
  4. --password flag

Phase 2: pgpass Support
- Auto-load passwords from ~/.pgpass file
- Support standard PostgreSQL pgpass format
- Check file permissions (must be 0600)
- Support wildcard matching (host:port:db:user:pass)

Tested on CentOS Stream 10 with PostgreSQL 16
This commit is contained in:
2025-11-07 14:43:34 +00:00
parent 1c72bf5e64
commit f5f302a11c
5 changed files with 737 additions and 0 deletions

View File

@ -9,6 +9,7 @@ import (
"strings"
"time"
"dbbackup/internal/auth"
"dbbackup/internal/config"
"dbbackup/internal/logger"
@ -35,6 +36,20 @@ func NewPostgreSQL(cfg *config.Config, log logger.Logger) *PostgreSQL {
// Connect establishes a connection to PostgreSQL using pgx for better performance
func (p *PostgreSQL) Connect(ctx context.Context) error {
// Try to load password from .pgpass if not provided
if p.cfg.Password == "" {
if password, found := auth.LoadPasswordFromPgpass(p.cfg); found {
p.cfg.Password = password
p.log.Debug("Loaded password from .pgpass file")
}
}
// Check for authentication mismatch before attempting connection
if mismatch, msg := auth.CheckAuthenticationMismatch(p.cfg); mismatch {
fmt.Println(msg)
return fmt.Errorf("authentication configuration required")
}
// Build PostgreSQL DSN (pgx format)
dsn := p.buildPgxDSN()
p.dsn = dsn