PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
FEATURE (postgresql): Add SSL mode + client-certificate (mTLS) support
Rostislav Dugin294224d9fd54
diff --git a/.env.example b/.env.exampleindex ab6459ce..3ae5da42 100644--- a/.env.example+++ b/.env.example@@ -67,6 +67,7 @@ TEST_MONGODB_60_PORT=27060TEST_MONGODB_70_PORT=27070TEST_MONGODB_82_PORT=27082TEST_POSTGRES_SSL_PORT=5180+TEST_POSTGRES_MTLS_PORT=5181TEST_MARIADB_SSL_PORT=33181TEST_MYSQL_SSL_PORT=33182TEST_MONGODB_SSL_PORT=27183diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.ymlindex 7fbd3808..13876f0f 100644--- a/.github/workflows/ci-release.yml+++ b/.github/workflows/ci-release.yml@@ -467,6 +467,8 @@ jobs:# Wait for SSL/TLS test containersecho "Waiting for PostgreSQL SSL..."timeout 120 bash -c 'until docker exec test-postgres-ssl pg_isready -U testuser -d testdb 2>/dev/null; do sleep 2; done'+ echo "Waiting for PostgreSQL mTLS..."+ timeout 120 bash -c 'until docker exec test-postgres-mtls pg_isready -U testuser -d testdb 2>/dev/null; do sleep 2; done'echo "Waiting for MariaDB SSL..."timeout 120 bash -c 'until docker exec test-mariadb-ssl healthcheck.sh --connect --innodb_initialized 2>/dev/null; do sleep 2; done'echo "Waiting for MySQL SSL..."diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex d94b599a..f75b776d 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -109,10 +109,11 @@ type EnvVariables struct {TestMongodb70Port string `env:"TEST_MONGODB_70_PORT"`TestMongodb82Port string `env:"TEST_MONGODB_82_PORT"`- TestPostgresSslPort string `env:"TEST_POSTGRES_SSL_PORT"`- TestMariadbSslPort string `env:"TEST_MARIADB_SSL_PORT"`- TestMysqlSslPort string `env:"TEST_MYSQL_SSL_PORT"`- TestMongodbSslPort string `env:"TEST_MONGODB_SSL_PORT"`+ TestPostgresSslPort string `env:"TEST_POSTGRES_SSL_PORT"`+ TestPostgresMtlsPort string `env:"TEST_POSTGRES_MTLS_PORT"`+ TestMariadbSslPort string `env:"TEST_MARIADB_SSL_PORT"`+ TestMysqlSslPort string `env:"TEST_MYSQL_SSL_PORT"`+ TestMongodbSslPort string `env:"TEST_MONGODB_SSL_PORT"`// oauthGitHubClientID string `env:"GITHUB_CLIENT_ID"`diff --git a/backend/internal/features/backups/backups/usecases/postgresql/create_backup_uc.go b/backend/internal/features/backups/backups/usecases/postgresql/create_backup_uc.goindex 19556425..e5b05be5 100644--- a/backend/internal/features/backups/backups/usecases/postgresql/create_backup_uc.go+++ b/backend/internal/features/backups/backups/usecases/postgresql/create_backup_uc.go@@ -125,24 +125,19 @@ func (uc *CreatePostgresqlBackupUsecase) streamToStorage(ctx, cancel := uc.createBackupContext(parentCtx)defer cancel()- pgpassFile, err := uc.setupPgpassFile(db.Postgresql, password)+ credentials, err := pgtypes.WriteCredentialFiles(db.Postgresql, password, uc.fieldEncryptor)if err != nil {- return nil, err+ return nil, fmt.Errorf("failed to create credential files: %w", err)}- defer func() {- if pgpassFile != "" {- // Remove the entire temp directory (which contains the .pgpass file)- _ = os.RemoveAll(filepath.Dir(pgpassFile))- }- }()+ defer credentials.Remove()cmd := exec.CommandContext(ctx, pgBin, args...)uc.logger.Info("Executing PostgreSQL backup command", "command", cmd.String())if err := uc.setupPgEnvironment(cmd,- pgpassFile,- db.Postgresql.IsHttps,+ credentials,+ db.Postgresql.SslMode,password,db.Postgresql.CpuCount,pgBin,@@ -423,49 +418,21 @@ func (uc *CreatePostgresqlBackupUsecase) createBackupContext(return ctx, cancel}-func (uc *CreatePostgresqlBackupUsecase) setupPgpassFile(- pgConfig *pgtypes.PostgresqlDatabase,- password string,-) (string, error) {- pgpassFile, err := uc.createTempPgpassFile(pgConfig, password)- if err != nil {- return "", fmt.Errorf("failed to create temporary .pgpass file: %w", err)- }-- if pgpassFile == "" {- return "", fmt.Errorf("temporary .pgpass file was not created")- }-- if info, err := os.Stat(pgpassFile); err == nil {- uc.logger.Info("Temporary .pgpass file created successfully",- "pgpassFile", pgpassFile,- "size", info.Size(),- "mode", info.Mode(),- )- } else {- return "", fmt.Errorf("failed to verify .pgpass file: %w", err)- }-- return pgpassFile, nil-}-func (uc *CreatePostgresqlBackupUsecase) setupPgEnvironment(cmd *exec.Cmd,- pgpassFile string,- shouldRequireSSL bool,+ credentials *pgtypes.CredentialFiles,+ sslMode pgtypes.PostgresSslMode,password string,cpuCount int,pgBin string,) error {cmd.Env = os.Environ()- cmd.Env = append(cmd.Env, "PGPASSFILE="+pgpassFile)+ cmd.Env = append(cmd.Env, "PGPASSFILE="+credentials.PgpassPath)- uc.logger.Info("Using temporary .pgpass file for authentication", "pgpassFile", pgpassFile)uc.logger.Info("Setting up PostgreSQL environment","passwordLength", len(password),"passwordEmpty", password == "","pgBin", pgBin,- "usingPgpassFile", true,"parallelJobs", cpuCount,)@@ -476,20 +443,19 @@ func (uc *CreatePostgresqlBackupUsecase) setupPgEnvironment("LANG=C.UTF-8",)- if shouldRequireSSL {- cmd.Env = append(cmd.Env, "PGSSLMODE=require")- uc.logger.Info("Using required SSL mode", "configuredHttps", shouldRequireSSL)- } else {- cmd.Env = append(cmd.Env, "PGSSLMODE=prefer")- uc.logger.Info("Using preferred SSL mode", "configuredHttps", shouldRequireSSL)+ resolvedSslMode := sslMode+ if resolvedSslMode == "" {+ resolvedSslMode = pgtypes.PostgresSslModeDisable}cmd.Env = append(cmd.Env,- "PGSSLCERT=",- "PGSSLKEY=",- "PGSSLROOTCERT=",+ "PGSSLMODE="+string(resolvedSslMode),+ "PGSSLCERT="+credentials.ClientCertPath,+ "PGSSLKEY="+credentials.ClientKeyPath,+ "PGSSLROOTCERT="+credentials.RootCertPath,"PGSSLCRL=",)+ uc.logger.Info("Using SSL mode", "sslMode", resolvedSslMode)if _, err := exec.LookPath(pgBin); err != nil {return fmt.Errorf("PostgreSQL executable not found or not accessible: %s - %w", pgBin, err)@@ -750,47 +716,6 @@ func (uc *CreatePostgresqlBackupUsecase) handleConnectionErrors(return fmt.Errorf("PostgreSQL connection or authentication error. stderr: %s", stderrStr)}-func (uc *CreatePostgresqlBackupUsecase) createTempPgpassFile(- pgConfig *pgtypes.PostgresqlDatabase,- password string,-) (string, error) {- if pgConfig == nil || password == "" {- return "", nil- }-- escapedHost := tools.EscapePgpassField(pgConfig.Host)- escapedUsername := tools.EscapePgpassField(pgConfig.Username)- escapedPassword := tools.EscapePgpassField(password)-- pgpassContent := fmt.Sprintf("%s:%d:*:%s:%s",- escapedHost,- pgConfig.Port,- escapedUsername,- escapedPassword,- )-- // Credential files use OS temp dir (/tmp) because some filesystems- // (e.g. ZFS on TrueNAS) ignore chmod, causing "group or world access" errors.- tempDir, err := os.MkdirTemp(os.TempDir(), "pgpass_"+uuid.New().String())- if err != nil {- return "", fmt.Errorf("failed to create temporary directory: %w", err)- }-- if err := os.Chmod(tempDir, 0o700); err != nil {- _ = os.RemoveAll(tempDir)- return "", fmt.Errorf("failed to set temporary directory permissions: %w", err)- }-- pgpassFile := filepath.Join(tempDir, ".pgpass")- err = os.WriteFile(pgpassFile, []byte(pgpassContent), 0o600)- if err != nil {- _ = os.RemoveAll(tempDir)- return "", fmt.Errorf("failed to write temporary .pgpass file: %w", err)- }-- return pgpassFile, nil-}-func containsIgnoreCase(str, substr string) bool {return strings.Contains(strings.ToLower(str), strings.ToLower(substr))}diff --git a/backend/internal/features/databases/databases/postgresql/credentialfiles.go b/backend/internal/features/databases/databases/postgresql/credentialfiles.gonew file mode 100644index 00000000..2cf188a8--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/credentialfiles.go@@ -0,0 +1,212 @@+package postgresql++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"++ "databasus-backend/internal/util/encryption"+ "databasus-backend/internal/util/tools"+)++// CredentialFiles is the temporary directory and files libpq needs for one+// pg_dump / pg_restore / pgx invocation: a .pgpass file plus the optional client+// certificate, client key, and server CA certificate. Remove the whole directory+// to clean every file up at once.+type CredentialFiles struct {+ Dir string+ PgpassPath string+ ClientCertPath string+ ClientKeyPath string+ RootCertPath string+}++// WriteCredentialFiles materializes the connection credentials of p into a fresh+// 0700 temp directory. password must already be decrypted; certificate fields are+// decrypted here via encryptor (decryption is a no-op for plaintext input, so this+// also works for the restore target whose config is never persisted).+func WriteCredentialFiles(+ p *PostgresqlDatabase,+ password string,+ encryptor encryption.FieldEncryptor,+) (*CredentialFiles, error) {+ // Credential files use the OS temp dir because some filesystems+ // (e.g. ZFS on TrueNAS) ignore chmod, causing "group or world access" errors.+ dir, err := os.MkdirTemp(os.TempDir(), "pgcreds_"+uuid.New().String())+ if err != nil {+ return nil, fmt.Errorf("failed to create temporary directory: %w", err)+ }++ if err := os.Chmod(dir, 0o700); err != nil {+ _ = os.RemoveAll(dir)+ return nil, fmt.Errorf("failed to set temporary directory permissions: %w", err)+ }++ files := &CredentialFiles{Dir: dir}++ if err := files.writePgpass(p, password); err != nil {+ _ = os.RemoveAll(dir)+ return nil, err+ }++ if p.SslMode != PostgresSslModeDisable && p.SslMode != "" {+ if err := files.writeCertFiles(p, encryptor); err != nil {+ _ = os.RemoveAll(dir)+ return nil, err+ }+ }++ return files, nil+}++// Remove deletes the temp directory and every credential file inside it.+func (f *CredentialFiles) Remove() {+ if f == nil || f.Dir == "" {+ return+ }++ _ = os.RemoveAll(f.Dir)+}++func (f *CredentialFiles) writePgpass(p *PostgresqlDatabase, password string) error {+ content := fmt.Sprintf("%s:%d:*:%s:%s",+ tools.EscapePgpassField(p.Host),+ p.Port,+ tools.EscapePgpassField(p.Username),+ tools.EscapePgpassField(password),+ )++ path := filepath.Join(f.Dir, ".pgpass")+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {+ return fmt.Errorf("failed to write .pgpass file: %w", err)+ }++ f.PgpassPath = path++ return nil+}++func (f *CredentialFiles) writeCertFiles(+ p *PostgresqlDatabase,+ encryptor encryption.FieldEncryptor,+) error {+ var err error++ if f.ClientCertPath, err = f.writeCert("client.crt", p.SslClientCert, encryptor); err != nil {+ return fmt.Errorf("failed to write client certificate: %w", err)+ }++ if f.ClientKeyPath, err = f.writeCert("client.key", p.SslClientKey, encryptor); err != nil {+ return fmt.Errorf("failed to write client key: %w", err)+ }++ if f.RootCertPath, err = f.writeCert("root.crt", p.SslRootCert, encryptor); err != nil {+ return fmt.Errorf("failed to write server CA certificate: %w", err)+ }++ return nil+}++func (f *CredentialFiles) writeCert(+ fileName, encryptedPEM string,+ encryptor encryption.FieldEncryptor,+) (string, error) {+ if encryptedPEM == "" {+ return "", nil+ }++ pem, err := decryptFieldIfNeeded(encryptedPEM, encryptor)+ if err != nil {+ return "", err+ }++ path := filepath.Join(f.Dir, fileName)+ if err := os.WriteFile(path, []byte(pem), 0o600); err != nil {+ return "", err+ }++ return path, nil+}++// openPgConn writes p's credential files, opens a pgx connection to dbName, and+// removes the files once the TLS handshake has completed.+func openPgConn(+ ctx context.Context,+ p *PostgresqlDatabase,+ dbName string,+ encryptor encryption.FieldEncryptor,+) (*pgx.Conn, error) {+ password, err := decryptFieldIfNeeded(p.Password, encryptor)+ if err != nil {+ return nil, fmt.Errorf("failed to decrypt password: %w", err)+ }++ files, err := WriteCredentialFiles(p, password, encryptor)+ if err != nil {+ return nil, err+ }+ defer files.Remove()++ return pgx.Connect(ctx, buildConnectionStringForDB(p, dbName, password, files))+}++// buildConnectionStringForDB builds a libpq connection string for a specific database.+func buildConnectionStringForDB(+ p *PostgresqlDatabase,+ dbName, password string,+ files *CredentialFiles,+) string {+ sslMode := p.SslMode+ if sslMode == "" {+ sslMode = PostgresSslModeDisable+ }++ connStr := fmt.Sprintf(+ "host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s default_query_exec_mode=simple_protocol standard_conforming_strings=on client_encoding=UTF8",+ p.Host,+ p.Port,+ p.Username,+ escapeConnectionStringValue(password),+ dbName,+ sslMode,+ )++ if files != nil {+ if files.ClientCertPath != "" {+ connStr += fmt.Sprintf(" sslcert='%s'", escapeConnectionStringValue(files.ClientCertPath))+ }++ if files.ClientKeyPath != "" {+ connStr += fmt.Sprintf(" sslkey='%s'", escapeConnectionStringValue(files.ClientKeyPath))+ }++ if files.RootCertPath != "" {+ connStr += fmt.Sprintf(" sslrootcert='%s'", escapeConnectionStringValue(files.RootCertPath))+ }+ }++ return connStr+}++func escapeConnectionStringValue(value string) string {+ value = strings.ReplaceAll(value, `\`, `\\`)+ value = strings.ReplaceAll(value, `'`, `\'`)++ return value+}++func decryptFieldIfNeeded(+ value string,+ encryptor encryption.FieldEncryptor,+) (string, error) {+ if encryptor == nil {+ return value, nil+ }++ return encryptor.Decrypt(value)+}diff --git a/backend/internal/features/databases/databases/postgresql/enums.go b/backend/internal/features/databases/databases/postgresql/enums.gonew file mode 100644index 00000000..10dce616--- /dev/null+++ b/backend/internal/features/databases/databases/postgresql/enums.go@@ -0,0 +1,10 @@+package postgresql++type PostgresSslMode string++const (+ PostgresSslModeDisable PostgresSslMode = "disable"+ PostgresSslModeRequire PostgresSslMode = "require"+ PostgresSslModeVerifyCA PostgresSslMode = "verify-ca"+ PostgresSslModeVerifyFull PostgresSslMode = "verify-full"+)diff --git a/backend/internal/features/databases/databases/postgresql/model.go b/backend/internal/features/databases/databases/postgresql/model.goindex ebf28b68..074165b6 100644--- a/backend/internal/features/databases/databases/postgresql/model.go+++ b/backend/internal/features/databases/databases/postgresql/model.go@@ -41,7 +41,12 @@ type PostgresqlDatabase struct {Username string `json:"username" gorm:"type:text"`Password string `json:"password" gorm:"type:text"`Database *string `json:"database" gorm:"type:text"`- IsHttps bool `json:"isHttps" gorm:"type:boolean;default:false"`++ // SSL / TLS connection settings+ SslMode PostgresSslMode `json:"sslMode" gorm:"column:ssl_mode;type:text;not null;default:'disable'"`+ SslClientCert string `json:"sslClientCert" gorm:"column:ssl_client_cert;type:text;not null;default:''"`+ SslClientKey string `json:"sslClientKey" gorm:"column:ssl_client_key;type:text;not null;default:''"`+ SslRootCert string `json:"sslRootCert" gorm:"column:ssl_root_cert;type:text;not null;default:''"`// backup settingsIncludeSchemas []string `json:"includeSchemas" gorm:"-"`@@ -97,6 +102,10 @@ func (p *PostgresqlDatabase) Validate() error {p.BackupType = PostgresBackupTypePgDump}+ if p.SslMode == "" {+ p.SslMode = PostgresSslModeDisable+ }+if p.BackupType != PostgresBackupTypePgDump && config.GetEnv().IsCloud {return errors.New("only PG_DUMP backup type is supported in cloud mode")}@@ -123,6 +132,10 @@ func (p *PostgresqlDatabase) Validate() error {return errors.New("cpu count must be greater than 0")}+ if err := p.validateSslConfig(); err != nil {+ return err+ }+// Prevent Databasus from backing up itself// Databasus runs an internal PostgreSQL instance that should not be backed up through the UI// because it would expose internal metadata to non-system administrators.@@ -191,14 +204,7 @@ func (p *PostgresqlDatabase) GetRawDbSizeMb(return 0, nil}- password, err := decryptPasswordIfNeeded(p.Password, encryptor)- if err != nil {- return 0, fmt.Errorf("failed to decrypt password: %w", err)- }-- connStr := buildConnectionStringForDB(p, *p.Database, password)-- conn, err := pgx.Connect(ctx, connStr)+ conn, err := openPgConn(ctx, p, *p.Database, encryptor)if err != nil {return 0, fmt.Errorf("failed to connect to database '%s': %w", *p.Database, err)}@@ -222,6 +228,7 @@ func (p *PostgresqlDatabase) HideSensitiveData() {}p.Password = ""+ p.SslClientKey = ""}func (p *PostgresqlDatabase) ValidateUpdate(old *PostgresqlDatabase) error {@@ -244,7 +251,9 @@ func (p *PostgresqlDatabase) Update(incoming *PostgresqlDatabase) {p.Port = incoming.Portp.Username = incoming.Usernamep.Database = incoming.Database- p.IsHttps = incoming.IsHttps+ p.SslMode = incoming.SslMode+ p.SslClientCert = incoming.SslClientCert+ p.SslRootCert = incoming.SslRootCertp.IncludeSchemas = incoming.IncludeSchemasp.ExcludeTables = incoming.ExcludeTablesp.CpuCount = incoming.CpuCount@@ -252,17 +261,31 @@ func (p *PostgresqlDatabase) Update(incoming *PostgresqlDatabase) {if incoming.Password != "" {p.Password = incoming.Password}++ if incoming.SslClientKey != "" {+ p.SslClientKey = incoming.SslClientKey+ }}func (p *PostgresqlDatabase) EncryptSensitiveFields(encryptor encryption.FieldEncryptor,) error {- if p.Password != "" {- encrypted, err := encryptor.Encrypt(p.Password)+ for _, field := range []*string{+ &p.Password,+ &p.SslClientCert,+ &p.SslClientKey,+ &p.SslRootCert,+ } {+ if *field == "" {+ continue+ }++ encrypted, err := encryptor.Encrypt(*field)if err != nil {return err}- p.Password = encrypted++ *field = encrypted}return nil@@ -293,14 +316,7 @@ func (p *PostgresqlDatabase) PopulateVersion(ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()- password, err := decryptPasswordIfNeeded(p.Password, encryptor)- if err != nil {- return fmt.Errorf("failed to decrypt password: %w", err)- }-- connStr := buildConnectionStringForDB(p, *p.Database, password)-- conn, err := pgx.Connect(ctx, connStr)+ conn, err := openPgConn(ctx, p, *p.Database, encryptor)if err != nil {return fmt.Errorf("failed to connect to database: %w", err)}@@ -342,14 +358,7 @@ func (p *PostgresqlDatabase) IsUserReadOnly(return false, nil, errors.New("read-only check is not supported for WAL backup type")}- password, err := decryptPasswordIfNeeded(p.Password, encryptor)- if err != nil {- return false, nil, fmt.Errorf("failed to decrypt password: %w", err)- }-- connStr := buildConnectionStringForDB(p, *p.Database, password)-- conn, err := pgx.Connect(ctx, connStr)+ conn, err := openPgConn(ctx, p, *p.Database, encryptor)if err != nil {return false, nil, fmt.Errorf("failed to connect to database: %w", err)}@@ -517,14 +526,7 @@ func (p *PostgresqlDatabase) CreateReadOnlyUser(return "", "", errors.New("read-only user creation is not supported for WAL backup type")}- password, err := decryptPasswordIfNeeded(p.Password, encryptor)- if err != nil {- return "", "", fmt.Errorf("failed to decrypt password: %w", err)- }-- connStr := buildConnectionStringForDB(p, *p.Database, password)-- conn, err := pgx.Connect(ctx, connStr)+ conn, err := openPgConn(ctx, p, *p.Database, encryptor)if err != nil {return "", "", fmt.Errorf("failed to connect to database: %w", err)}@@ -949,6 +951,30 @@ func (p *PostgresqlDatabase) CreateReadOnlyUser(return "", "", errors.New("failed to generate unique username after 3 attempts")}+func (p *PostgresqlDatabase) validateSslConfig() error {+ switch p.SslMode {+ case PostgresSslModeDisable, PostgresSslModeRequire, PostgresSslModeVerifyCA, PostgresSslModeVerifyFull:+ default:+ return fmt.Errorf("invalid SSL mode: %s", p.SslMode)+ }++ hasClientCert := p.SslClientCert != ""+ hasClientKey := p.SslClientKey != ""++ if hasClientCert != hasClientKey {+ return errors.New("client certificate and client key must be provided together")+ }++ if p.SslMode == PostgresSslModeDisable &&+ (hasClientCert || hasClientKey || p.SslRootCert != "") {+ return errors.New(+ "SSL certificates require SSL to be enabled (set SSL mode to require, verify-ca or verify-full)",+ )+ }++ return nil+}+// testSingleDatabaseConnection tests connection to a specific database for pg_dumpfunc testSingleDatabaseConnection(logger *slog.Logger,@@ -961,17 +987,8 @@ func testSingleDatabaseConnection(return errors.New("database name is required for single database backup (pg_dump)")}- // Decrypt password if needed- password, err := decryptPasswordIfNeeded(postgresDb.Password, encryptor)- if err != nil {- return fmt.Errorf("failed to decrypt password: %w", err)- }-- // Build connection string for the specific database- connStr := buildConnectionStringForDB(postgresDb, *postgresDb.Database, password)-// Test connection- conn, err := pgx.Connect(ctx, connStr)+ conn, err := openPgConn(ctx, postgresDb, *postgresDb.Database, encryptor)if err != nil {// TODO make more readable errors:// - handle wrong creds@@ -1162,40 +1179,6 @@ func checkBackupPermissions(return nil}-// buildConnectionStringForDB builds connection string for specific database-func buildConnectionStringForDB(p *PostgresqlDatabase, dbName, password string) string {- sslMode := "disable"- if p.IsHttps {- sslMode = "require"- }-- return fmt.Sprintf(- "host=%s port=%d user=%s password='%s' dbname=%s sslmode=%s default_query_exec_mode=simple_protocol standard_conforming_strings=on client_encoding=UTF8",- p.Host,- p.Port,- p.Username,- escapeConnectionStringValue(password),- dbName,- sslMode,- )-}--func escapeConnectionStringValue(value string) string {- value = strings.ReplaceAll(value, `\`, `\\`)- value = strings.ReplaceAll(value, `'`, `\'`)- return value-}--func decryptPasswordIfNeeded(- password string,- encryptor encryption.FieldEncryptor,-) (string, error) {- if encryptor == nil {- return password, nil- }- return encryptor.Decrypt(password)-}-func isSupabaseConnection(host, username string) bool {return strings.Contains(strings.ToLower(host), "supabase") ||strings.Contains(strings.ToLower(username), "supabase")diff --git a/backend/internal/features/databases/databases/postgresql/model_test.go b/backend/internal/features/databases/databases/postgresql/model_test.goindex c3d892c8..1df9369d 100644--- a/backend/internal/features/databases/databases/postgresql/model_test.go+++ b/backend/internal/features/databases/databases/postgresql/model_test.go@@ -72,7 +72,7 @@ func Test_TestConnection_PasswordContainingSpaces_TestedSuccessfully(t *testing.Username: usernameWithSpaces,Password: passwordWithSpaces,Database: &container.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,CpuCount: 1,}@@ -142,7 +142,7 @@ func Test_TestConnection_InsufficientPermissions_ReturnsError(t *testing.T) {Username: limitedUsername,Password: limitedPassword,Database: &container.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,CpuCount: 1,}@@ -229,7 +229,7 @@ func Test_TestConnection_SufficientPermissions_Success(t *testing.T) {Username: backupUsername,Password: backupPassword,Database: &container.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,CpuCount: 1,}@@ -304,7 +304,7 @@ func Test_IsUserReadOnly_ReadOnlyUser_ReturnsTrue(t *testing.T) {Username: username,Password: password,Database: pgModel.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,CpuCount: 1,}@@ -372,7 +372,7 @@ func Test_CreateReadOnlyUser_UserCanReadButNotWrite(t *testing.T) {Username: username,Password: password,Database: pgModel.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,}isReadOnly, privileges, err := readOnlyModel.IsUserReadOnly(@@ -559,7 +559,7 @@ func Test_CreateReadOnlyUser_DatabaseNameWithDash_Success(t *testing.T) {Username: container.Username,Password: container.Password,Database: &dashDbName,- IsHttps: false,+ SslMode: PostgresSslModeDisable,}logger := slog.New(slog.NewTextHandler(os.Stdout, nil))@@ -644,7 +644,7 @@ func Test_CreateReadOnlyUser_WithPublicSchema_Success(t *testing.T) {Username: username,Password: password,Database: pgModel.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,}isReadOnly, privileges, err := readOnlyModel.IsUserReadOnly(@@ -751,7 +751,7 @@ func Test_CreateReadOnlyUser_WithoutPublicSchema_Success(t *testing.T) {Username: username,Password: password,Database: pgModel.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,}isReadOnly, privileges, err := readOnlyModel.IsUserReadOnly(@@ -898,7 +898,7 @@ func Test_CreateReadOnlyUser_PublicSchemaExistsButNoPermissions_ReturnsError(t *Username: limitedAdminUsername,Password: limitedAdminPassword,Database: &container.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,}logger := slog.New(slog.NewTextHandler(os.Stdout, nil))@@ -1616,7 +1616,7 @@ func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *Username: "appuser",Password: "supersecret",Database: &databaseName,- IsHttps: true,+ SslMode: PostgresSslModeRequire,IncludeSchemas: []string{"public"},ExcludeTables: []string{"audit_logs"},CpuCount: 4,@@ -1629,7 +1629,7 @@ func Test_HideSensitiveData_WhenCalled_ClearsPasswordAndPreservesOtherFields(t *assert.Equal(t, 5432, pgModel.Port)assert.Equal(t, "appuser", pgModel.Username)assert.Equal(t, &databaseName, pgModel.Database)- assert.True(t, pgModel.IsHttps)+ assert.Equal(t, PostgresSslModeRequire, pgModel.SslMode)assert.Equal(t, PostgresBackupTypePgDump, pgModel.BackupType)assert.Equal(t, []string{"public"}, pgModel.IncludeSchemas)assert.Equal(t, []string{"audit_logs"}, pgModel.ExcludeTables)@@ -1644,6 +1644,208 @@ func Test_HideSensitiveData_WhenReceiverIsNil_DoesNotPanic(t *testing.T) {})}+type stubEncryptor struct{}++func (stubEncryptor) Encrypt(value string) (string, error) {+ if value == "" || strings.HasPrefix(value, "enc:") {+ return value, nil+ }++ return "enc:" + value, nil+}++func (stubEncryptor) Decrypt(value string) (string, error) {+ return strings.TrimPrefix(value, "enc:"), nil+}++func Test_HideSensitiveData_WhenCertsSet_ClearsOnlyClientKey(t *testing.T) {+ databaseName := "appdb"+ pgModel := &PostgresqlDatabase{+ Host: "db.example.com",+ Port: 5432,+ Username: "appuser",+ Password: "supersecret",+ Database: &databaseName,+ SslMode: PostgresSslModeVerifyFull,+ SslClientCert: "client-cert-pem",+ SslClientKey: "client-key-pem",+ SslRootCert: "root-cert-pem",+ CpuCount: 1,+ }++ pgModel.HideSensitiveData()++ assert.Empty(t, pgModel.Password)+ assert.Empty(t, pgModel.SslClientKey)+ assert.Equal(t, "client-cert-pem", pgModel.SslClientCert)+ assert.Equal(t, "root-cert-pem", pgModel.SslRootCert)+ assert.Equal(t, PostgresSslModeVerifyFull, pgModel.SslMode)+}++func Test_EncryptSensitiveFields_WhenCertsSet_EncryptsEverySecret(t *testing.T) {+ pgModel := &PostgresqlDatabase{+ Password: "supersecret",+ SslMode: PostgresSslModeVerifyFull,+ SslClientCert: "client-cert-pem",+ SslClientKey: "client-key-pem",+ SslRootCert: "root-cert-pem",+ }++ err := pgModel.EncryptSensitiveFields(stubEncryptor{})+ assert.NoError(t, err)+ assert.Equal(t, "enc:supersecret", pgModel.Password)+ assert.Equal(t, "enc:client-cert-pem", pgModel.SslClientCert)+ assert.Equal(t, "enc:client-key-pem", pgModel.SslClientKey)+ assert.Equal(t, "enc:root-cert-pem", pgModel.SslRootCert)++ err = pgModel.EncryptSensitiveFields(stubEncryptor{})+ assert.NoError(t, err)+ assert.Equal(t, "enc:supersecret", pgModel.Password)+ assert.Equal(t, "enc:client-key-pem", pgModel.SslClientKey)+}++func Test_EncryptSensitiveFields_WhenCertsEmpty_LeavesThemEmpty(t *testing.T) {+ pgModel := &PostgresqlDatabase{Password: "supersecret"}++ err := pgModel.EncryptSensitiveFields(stubEncryptor{})+ assert.NoError(t, err)+ assert.Equal(t, "enc:supersecret", pgModel.Password)+ assert.Empty(t, pgModel.SslClientCert)+ assert.Empty(t, pgModel.SslClientKey)+ assert.Empty(t, pgModel.SslRootCert)+}++func Test_Update_WhenIncomingClientKeyEmpty_PreservesExistingKey(t *testing.T) {+ databaseName := "appdb"+ existing := &PostgresqlDatabase{+ Host: "old-host",+ Port: 5432,+ Username: "olduser",+ Password: "enc:oldpass",+ Database: &databaseName,+ SslMode: PostgresSslModeVerifyCA,+ SslClientCert: "enc:old-cert",+ SslClientKey: "enc:old-key",+ SslRootCert: "enc:old-root",+ CpuCount: 1,+ }++ incoming := &PostgresqlDatabase{+ Host: "new-host",+ Port: 5433,+ Username: "newuser",+ Database: &databaseName,+ SslMode: PostgresSslModeRequire,+ SslClientCert: "new-cert",+ SslClientKey: "",+ SslRootCert: "new-root",+ CpuCount: 2,+ }++ existing.Update(incoming)++ assert.Equal(t, PostgresSslModeRequire, existing.SslMode)+ assert.Equal(t, "new-cert", existing.SslClientCert)+ assert.Equal(t, "enc:old-key", existing.SslClientKey)+ assert.Equal(t, "new-root", existing.SslRootCert)+}++func Test_Validate_SslConfig_EnforcesCertRules(t *testing.T) {+ databaseName := "appdb"+ baseModel := func() *PostgresqlDatabase {+ return &PostgresqlDatabase{+ Host: "db.example.com",+ Port: 5432,+ Username: "appuser",+ Password: "secret",+ Database: &databaseName,+ CpuCount: 1,+ }+ }++ testCases := []struct {+ name string+ mutate func(*PostgresqlDatabase)+ expectedError string+ }{+ {+ name: "client cert without key",+ mutate: func(p *PostgresqlDatabase) {+ p.SslMode = PostgresSslModeRequire+ p.SslClientCert = "cert"+ },+ expectedError: "client certificate and client key must be provided together",+ },+ {+ name: "client key without cert",+ mutate: func(p *PostgresqlDatabase) {+ p.SslMode = PostgresSslModeRequire+ p.SslClientKey = "key"+ },+ expectedError: "client certificate and client key must be provided together",+ },+ {+ name: "certificates with SSL disabled",+ mutate: func(p *PostgresqlDatabase) {+ p.SslMode = PostgresSslModeDisable+ p.SslClientCert = "cert"+ p.SslClientKey = "key"+ },+ expectedError: "SSL certificates require SSL to be enabled",+ },+ {+ name: "unknown SSL mode",+ mutate: func(p *PostgresqlDatabase) {+ p.SslMode = "bogus"+ },+ expectedError: "invalid SSL mode",+ },+ {+ name: "client certificate pair with verify-full",+ mutate: func(p *PostgresqlDatabase) {+ p.SslMode = PostgresSslModeVerifyFull+ p.SslClientCert = "cert"+ p.SslClientKey = "key"+ p.SslRootCert = "root"+ },+ expectedError: "",+ },+ }++ for _, tc := range testCases {+ t.Run(tc.name, func(t *testing.T) {+ model := baseModel()+ tc.mutate(model)++ err := model.Validate()++ if tc.expectedError == "" {+ assert.NoError(t, err)+ } else {+ assert.Error(t, err)+ assert.Contains(t, err.Error(), tc.expectedError)+ }+ })+ }+}++func Test_Validate_WhenSslModeEmpty_DefaultsToDisable(t *testing.T) {+ databaseName := "appdb"+ model := &PostgresqlDatabase{+ Host: "db.example.com",+ Port: 5432,+ Username: "appuser",+ Password: "secret",+ Database: &databaseName,+ CpuCount: 1,+ }++ err := model.Validate()++ assert.NoError(t, err)+ assert.Equal(t, PostgresSslModeDisable, model.SslMode)+}+func connectToPostgresContainer(t *testing.T, port string) *PostgresContainer {dbName := "testdb"password := "testpassword"@@ -1689,7 +1891,7 @@ func createPostgresModel(container *PostgresContainer) *PostgresqlDatabase {Username: container.Username,Password: container.Password,Database: &container.Database,- IsHttps: false,+ SslMode: PostgresSslModeDisable,CpuCount: 1,}}diff --git a/backend/internal/features/databases/service.go b/backend/internal/features/databases/service.goindex 584b0ddc..ec5f8f3f 100644--- a/backend/internal/features/databases/service.go+++ b/backend/internal/features/databases/service.go@@ -464,7 +464,10 @@ func (s *DatabaseService) CopyDatabase(Username: existingDatabase.Postgresql.Username,Password: existingDatabase.Postgresql.Password,Database: existingDatabase.Postgresql.Database,- IsHttps: existingDatabase.Postgresql.IsHttps,+ SslMode: existingDatabase.Postgresql.SslMode,+ SslClientCert: existingDatabase.Postgresql.SslClientCert,+ SslClientKey: existingDatabase.Postgresql.SslClientKey,+ SslRootCert: existingDatabase.Postgresql.SslRootCert,IncludeSchemas: existingDatabase.Postgresql.IncludeSchemas,CpuCount: existingDatabase.Postgresql.CpuCount,}diff --git a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.goindex 55f34492..f7692ede 100644--- a/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go+++ b/backend/internal/features/restores/usecases/postgresql/restore_backup_uc.go@@ -175,37 +175,18 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaStdin(}}()- // Create temporary .pgpass file for authentication+ // Materialize connection credentials (.pgpass + optional client certificates)fieldEncryptor := util_encryption.GetFieldEncryptor()decryptedPassword, err := fieldEncryptor.Decrypt(pg.Password)if err != nil {return fmt.Errorf("failed to decrypt password: %w", err)}- pgpassFile, err := uc.createTempPgpassFile(pg, decryptedPassword)+ credentials, err := pgtypes.WriteCredentialFiles(pg, decryptedPassword, fieldEncryptor)if err != nil {- return fmt.Errorf("failed to create temporary .pgpass file: %w", err)- }- defer func() {- if pgpassFile != "" {- _ = os.RemoveAll(filepath.Dir(pgpassFile))- }- }()-- // Verify .pgpass file was created successfully- if pgpassFile == "" {- return fmt.Errorf("temporary .pgpass file was not created")- }-- if info, err := os.Stat(pgpassFile); err == nil {- uc.logger.Info("Temporary .pgpass file created successfully",- "pgpassFile", pgpassFile,- "size", info.Size(),- "mode", info.Mode(),- )- } else {- return fmt.Errorf("failed to verify .pgpass file: %w", err)+ return fmt.Errorf("failed to create credential files: %w", err)}+ defer credentials.Remove()// Get backup stream from storagerawReader, err := storage.GetFile(fieldEncryptor, backup.FileName)@@ -262,7 +243,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreViaStdin(uc.logger.Info("Executing PostgreSQL restore command via stdin", "command", cmd.String())// Setup environment variables- uc.setupPgRestoreEnvironment(cmd, pgpassFile, pg)+ uc.setupPgRestoreEnvironment(cmd, credentials, pg)// Verify executable exists and is accessibleif _, err := exec.LookPath(pgBin); err != nil {@@ -457,31 +438,16 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(}}()- // Create temporary .pgpass file for authentication- pgpassFile, err := uc.createTempPgpassFile(pgConfig, password)+ // Materialize connection credentials (.pgpass + optional client certificates)+ credentials, err := pgtypes.WriteCredentialFiles(+ pgConfig,+ password,+ util_encryption.GetFieldEncryptor(),+ )if err != nil {- return fmt.Errorf("failed to create temporary .pgpass file: %w", err)- }- defer func() {- if pgpassFile != "" {- _ = os.RemoveAll(filepath.Dir(pgpassFile))- }- }()-- // Verify .pgpass file was created successfully- if pgpassFile == "" {- return fmt.Errorf("temporary .pgpass file was not created")- }-- if info, err := os.Stat(pgpassFile); err == nil {- uc.logger.Info("Temporary .pgpass file created successfully",- "pgpassFile", pgpassFile,- "size", info.Size(),- "mode", info.Mode(),- )- } else {- return fmt.Errorf("failed to verify .pgpass file: %w", err)+ return fmt.Errorf("failed to create credential files: %w", err)}+ defer credentials.Remove()// Download backup to temporary filetempBackupFile, cleanupFunc, err := uc.downloadBackupToTempFile(ctx, backup, storage)@@ -496,7 +462,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(ctx,pgBin,tempBackupFile,- pgpassFile,+ credentials,pgConfig,)if err != nil {@@ -513,7 +479,7 @@ func (uc *RestorePostgresqlBackupUsecase) restoreFromStorage(// Add the temporary backup file as the last argument to pg_restoreargs = append(args, tempBackupFile)- return uc.executePgRestore(ctx, database, pgBin, args, pgpassFile, pgConfig)+ return uc.executePgRestore(ctx, database, pgBin, args, credentials, pgConfig)}// downloadBackupToTempFile downloads backup data from storage to a temporary file@@ -636,14 +602,14 @@ func (uc *RestorePostgresqlBackupUsecase) executePgRestore(database *databases.Database,pgBin string,args []string,- pgpassFile string,+ credentials *pgtypes.CredentialFiles,pgConfig *pgtypes.PostgresqlDatabase,) error {cmd := exec.CommandContext(ctx, pgBin, args...)uc.logger.Info("Executing PostgreSQL restore command", "command", cmd.String())// Setup environment variables- uc.setupPgRestoreEnvironment(cmd, pgpassFile, pgConfig)+ uc.setupPgRestoreEnvironment(cmd, credentials, pgConfig)// Verify executable exists and is accessibleif _, err := exec.LookPath(pgBin); err != nil {@@ -713,40 +679,37 @@ func (uc *RestorePostgresqlBackupUsecase) executePgRestore(// setupPgRestoreEnvironment configures environment variables for pg_restorefunc (uc *RestorePostgresqlBackupUsecase) setupPgRestoreEnvironment(cmd *exec.Cmd,- pgpassFile string,+ credentials *pgtypes.CredentialFiles,pgConfig *pgtypes.PostgresqlDatabase,) {- // Start with system environment variablescmd.Env = os.Environ()- // Use the .pgpass file for authentication- cmd.Env = append(cmd.Env, "PGPASSFILE="+pgpassFile)- uc.logger.Info("Using temporary .pgpass file for authentication", "pgpassFile", pgpassFile)-- // Add PostgreSQL-specific environment variables- cmd.Env = append(cmd.Env, "PGCLIENTENCODING=UTF8")- cmd.Env = append(cmd.Env, "PGCONNECT_TIMEOUT=30")-- // Add encoding-related environment variables- cmd.Env = append(cmd.Env, "LC_ALL=C.UTF-8")- cmd.Env = append(cmd.Env, "LANG=C.UTF-8")+ cmd.Env = append(cmd.Env, "PGPASSFILE="+credentials.PgpassPath)+ uc.logger.Info(+ "Using temporary .pgpass file for authentication",+ "pgpassFile", credentials.PgpassPath,+ )- shouldRequireSSL := pgConfig.IsHttps+ cmd.Env = append(cmd.Env,+ "PGCLIENTENCODING=UTF8",+ "PGCONNECT_TIMEOUT=30",+ "LC_ALL=C.UTF-8",+ "LANG=C.UTF-8",+ )- // Configure SSL settings- if shouldRequireSSL {- cmd.Env = append(cmd.Env, "PGSSLMODE=require")- uc.logger.Info("Using required SSL mode", "configuredHttps", pgConfig.IsHttps)- } else {- cmd.Env = append(cmd.Env, "PGSSLMODE=prefer")- uc.logger.Info("Using preferred SSL mode", "configuredHttps", pgConfig.IsHttps)+ sslMode := pgConfig.SslMode+ if sslMode == "" {+ sslMode = pgtypes.PostgresSslModeDisable}- // Set other SSL parameters to avoid certificate issues- cmd.Env = append(cmd.Env, "PGSSLCERT=")- cmd.Env = append(cmd.Env, "PGSSLKEY=")- cmd.Env = append(cmd.Env, "PGSSLROOTCERT=")- cmd.Env = append(cmd.Env, "PGSSLCRL=")+ cmd.Env = append(cmd.Env,+ "PGSSLMODE="+string(sslMode),+ "PGSSLCERT="+credentials.ClientCertPath,+ "PGSSLKEY="+credentials.ClientKeyPath,+ "PGSSLROOTCERT="+credentials.RootCertPath,+ "PGSSLCRL=",+ )+ uc.logger.Info("Using SSL mode", "sslMode", sslMode)}// handlePgRestoreError processes and formats pg_restore errors@@ -915,14 +878,14 @@ func (uc *RestorePostgresqlBackupUsecase) generateFilteredTocList(ctx context.Context,pgBin string,backupFile string,- pgpassFile string,+ credentials *pgtypes.CredentialFiles,pgConfig *pgtypes.PostgresqlDatabase,) (string, error) {uc.logger.Info("Generating filtered TOC list to exclude extensions", "backupFile", backupFile)// Run pg_restore -l to get the TOC listlistCmd := exec.CommandContext(ctx, pgBin, "-l", backupFile)- uc.setupPgRestoreEnvironment(listCmd, pgpassFile, pgConfig)+ uc.setupPgRestoreEnvironment(listCmd, credentials, pgConfig)tocOutput, err := listCmd.Output()if err != nil {@@ -977,45 +940,3 @@ func (uc *RestorePostgresqlBackupUsecase) generateFilteredTocList(return tocFilePath, nil}--// createTempPgpassFile creates a temporary .pgpass file with the given password-func (uc *RestorePostgresqlBackupUsecase) createTempPgpassFile(- pgConfig *pgtypes.PostgresqlDatabase,- password string,-) (string, error) {- if pgConfig == nil || password == "" {- return "", nil- }-- escapedHost := tools.EscapePgpassField(pgConfig.Host)- escapedUsername := tools.EscapePgpassField(pgConfig.Username)- escapedPassword := tools.EscapePgpassField(password)-- pgpassContent := fmt.Sprintf("%s:%d:*:%s:%s",- escapedHost,- pgConfig.Port,- escapedUsername,- escapedPassword,- )-- // Credential files use OS temp dir (/tmp) because some filesystems- // (e.g. ZFS on TrueNAS) ignore chmod, causing "group or world access" errors.- tempDir, err := os.MkdirTemp(os.TempDir(), "pgpass_"+uuid.New().String())- if err != nil {- return "", fmt.Errorf("failed to create temporary directory: %w", err)- }-- if err := os.Chmod(tempDir, 0o700); err != nil {- _ = os.RemoveAll(tempDir)- return "", fmt.Errorf("failed to set temporary directory permissions: %w", err)- }-- pgpassFile := filepath.Join(tempDir, ".pgpass")- err = os.WriteFile(pgpassFile, []byte(pgpassContent), 0o600)- if err != nil {- _ = os.RemoveAll(tempDir)- return "", fmt.Errorf("failed to write temporary .pgpass file: %w", err)- }-- return pgpassFile, nil-}diff --git a/backend/internal/features/tests/mtls_backup_restore_test.go b/backend/internal/features/tests/mtls_backup_restore_test.gonew file mode 100644index 00000000..e99e58c2--- /dev/null+++ b/backend/internal/features/tests/mtls_backup_restore_test.go@@ -0,0 +1,248 @@+package tests++import (+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "strconv"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ "github.com/jmoiron/sqlx"+ "github.com/stretchr/testify/assert"++ "databasus-backend/internal/config"+ backups_core "databasus-backend/internal/features/backups/backups/core"+ backups_config "databasus-backend/internal/features/backups/config"+ "databasus-backend/internal/features/databases"+ pgtypes "databasus-backend/internal/features/databases/databases/postgresql"+ restores_core "databasus-backend/internal/features/restores/core"+ "databasus-backend/internal/features/storages"+ users_enums "databasus-backend/internal/features/users/enums"+ users_testing "databasus-backend/internal/features/users/testing"+ workspaces_testing "databasus-backend/internal/features/workspaces/testing"+ test_utils "databasus-backend/internal/util/testing"+)++func Test_BackupAndRestorePostgresqlMtls_Succeeds(t *testing.T) {+ port := config.GetEnv().TestPostgresMtlsPort+ if port == "" {+ t.Skip("TEST_POSTGRES_MTLS_PORT not configured")+ }++ host := config.GetEnv().TestLocalhost+ portInt, err := strconv.Atoi(port)+ if err != nil {+ t.Fatalf("failed to parse mTLS port: %v", err)+ }++ clientCert, clientKey, rootCert := readMtlsCerts(t)+ certDir := writeMtlsCertFiles(t, clientCert, clientKey, rootCert)++ originalDB, err := sqlx.Connect("postgres", buildMtlsDSN(host, portInt, "testdb", certDir))+ if err != nil {+ t.Fatalf("failed to connect to mTLS Postgres: %v", err)+ }+ defer originalDB.Close()++ tableName := "test_data_mtls"+ _, err = originalDB.Exec(createAndFillTableQuery(tableName))+ assert.NoError(t, err)++ router := createTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Postgres mTLS Workspace", user, router)+ storage := storages.CreateTestStorage(workspace.ID)++ dbName := "testdb"+ database := createPostgresqlMtlsDatabaseViaAPI(+ t, router, "Postgres mTLS DB", workspace.ID,+ host, portInt, "testuser", "testpassword", dbName,+ clientCert, clientKey, rootCert, user.Token,+ )++ enableBackupsViaAPI(+ t, router, database.ID, storage.ID,+ backups_config.BackupEncryptionNone, user.Token,+ )+ createBackupViaAPI(t, router, database.ID, user.Token)++ backup := waitForBackupCompletion(t, router, database.ID, user.Token, 5*time.Minute)+ assert.Equal(t, backups_core.BackupStatusCompleted, backup.Status)++ newDBName := "restoreddb_pg_mtls"+ _, err = originalDB.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", newDBName))+ assert.NoError(t, err)+ _, err = originalDB.Exec(fmt.Sprintf("CREATE DATABASE %s;", newDBName))+ assert.NoError(t, err)++ newDB, err := sqlx.Connect("postgres", buildMtlsDSN(host, portInt, newDBName, certDir))+ assert.NoError(t, err)+ defer newDB.Close()++ createPostgresqlMtlsRestoreViaAPI(+ t, router, backup.ID,+ host, portInt, "testuser", "testpassword", newDBName,+ clientCert, clientKey, rootCert, user.Token,+ )++ restore := waitForRestoreCompletion(t, router, backup.ID, user.Token, 5*time.Minute)+ assert.Equal(t, restores_core.RestoreStatusCompleted, restore.Status)++ verifyDataIntegrity(t, originalDB, newDB, tableName)++ _ = os.Remove(filepath.Join(config.GetEnv().DataFolder, backup.ID.String()))+ test_utils.MakeDeleteRequest(+ t, router, "/api/v1/databases/"+database.ID.String(),+ "Bearer "+user.Token, http.StatusNoContent,+ )+ storages.RemoveTestStorage(storage.ID)+ workspaces_testing.RemoveTestWorkspace(workspace, router)+}++func Test_CreatePostgresqlMtls_WhenClientCertMissing_IsRejected(t *testing.T) {+ port := config.GetEnv().TestPostgresMtlsPort+ if port == "" {+ t.Skip("TEST_POSTGRES_MTLS_PORT not configured")+ }++ host := config.GetEnv().TestLocalhost+ portInt, err := strconv.Atoi(port)+ if err != nil {+ t.Fatalf("failed to parse mTLS port: %v", err)+ }++ router := createTestRouter()+ user := users_testing.CreateTestUser(users_enums.UserRoleMember)+ workspace := workspaces_testing.CreateTestWorkspace("Postgres mTLS Reject Workspace", user, router)+ defer workspaces_testing.RemoveTestWorkspace(workspace, router)++ dbName := "testdb"+ request := databases.Database{+ Name: "Postgres mTLS no client cert",+ WorkspaceID: &workspace.ID,+ Type: databases.DatabaseTypePostgres,+ Postgresql: &pgtypes.PostgresqlDatabase{+ Host: host,+ Port: portInt,+ Username: "testuser",+ Password: "testpassword",+ Database: &dbName,+ SslMode: pgtypes.PostgresSslModeRequire,+ CpuCount: 1,+ },+ }++ response := workspaces_testing.MakeAPIRequest(+ router, "POST", "/api/v1/databases/create", "Bearer "+user.Token, request,+ )+ assert.NotEqual(+ t, http.StatusCreated, response.Code,+ "creating an mTLS database without a client certificate must fail",+ )+}++func readMtlsCerts(t *testing.T) (clientCert, clientKey, rootCert string) {+ t.Helper()++ read := func(name string) string {+ content, err := os.ReadFile(filepath.Join("testdata", "mtls", name))+ if err != nil {+ t.Fatalf("failed to read mTLS test certificate %s: %v", name, err)+ }++ return string(content)+ }++ return read("client.crt"), read("client.key"), read("ca.crt")+}++// writeMtlsCertFiles writes the PEMs to a 0600 temp directory because the lib/pq+// driver refuses a client key file that is group- or world-readable.+func writeMtlsCertFiles(t *testing.T, clientCert, clientKey, rootCert string) string {+ t.Helper()++ dir := t.TempDir()+ for name, content := range map[string]string{+ "client.crt": clientCert,+ "client.key": clientKey,+ "ca.crt": rootCert,+ } {+ if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {+ t.Fatalf("failed to write %s: %v", name, err)+ }+ }++ return dir+}++func buildMtlsDSN(host string, port int, dbName, certDir string) string {+ return fmt.Sprintf(+ "host=%s port=%d user=testuser password=testpassword dbname=%s "++ "sslmode=verify-ca sslrootcert=%s sslcert=%s sslkey=%s",+ host, port, dbName,+ filepath.ToSlash(filepath.Join(certDir, "ca.crt")),+ filepath.ToSlash(filepath.Join(certDir, "client.crt")),+ filepath.ToSlash(filepath.Join(certDir, "client.key")),+ )+}++func createPostgresqlMtlsDatabaseViaAPI(+ t *testing.T,+ router *gin.Engine,+ name string,+ workspaceID uuid.UUID,+ host string,+ port int,+ username, password, database string,+ clientCert, clientKey, rootCert, token string,+) *databases.Database {+ request := databases.Database{+ Name: name,+ WorkspaceID: &workspaceID,+ Type: databases.DatabaseTypePostgres,+ Postgresql: &pgtypes.PostgresqlDatabase{+ Host: host,+ Port: port,+ Username: username,+ Password: password,+ Database: &database,+ SslMode: pgtypes.PostgresSslModeVerifyCA,+ SslClientCert: clientCert,+ SslClientKey: clientKey,+ SslRootCert: rootCert,+ CpuCount: 1,+ },+ }++ return submitCreateDatabase(t, router, "Postgres mTLS", request, token)+}++func createPostgresqlMtlsRestoreViaAPI(+ t *testing.T,+ router *gin.Engine,+ backupID uuid.UUID,+ host string,+ port int,+ username, password, database string,+ clientCert, clientKey, rootCert, token string,+) {+ request := restores_core.RestoreBackupRequest{+ PostgresqlDatabase: &pgtypes.PostgresqlDatabase{+ Host: host,+ Port: port,+ Username: username,+ Password: password,+ Database: &database,+ SslMode: pgtypes.PostgresSslModeVerifyCA,+ SslClientCert: clientCert,+ SslClientKey: clientKey,+ SslRootCert: rootCert,+ CpuCount: 1,+ },+ }+ submitRestore(t, router, backupID, request, token)+}diff --git a/backend/internal/features/tests/ssl_backup_restore_test.go b/backend/internal/features/tests/ssl_backup_restore_test.goindex 5d29e7ac..93075c02 100644--- a/backend/internal/features/tests/ssl_backup_restore_test.go+++ b/backend/internal/features/tests/ssl_backup_restore_test.go@@ -391,7 +391,7 @@ func createPostgresqlSSLDatabaseViaAPI(Username: username,Password: password,Database: &database,- IsHttps: true,+ SslMode: pgtypes.PostgresSslModeRequire,CpuCount: 1,},}@@ -414,7 +414,7 @@ func createPostgresqlSSLRestoreViaAPI(Username: username,Password: password,Database: &database,- IsHttps: true,+ SslMode: pgtypes.PostgresSslModeRequire,CpuCount: 1,},}diff --git a/backend/internal/features/tests/testdata/mtls/README.md b/backend/internal/features/tests/testdata/mtls/README.mdnew file mode 100644index 00000000..e2cd94f5--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/README.md@@ -0,0 +1,34 @@+# mTLS test certificates++Certificate chain for the `test-postgres-mtls` container, which enforces mutual TLS -+it rejects any TCP client that does not present a client certificate signed by+`ca.crt`. This reproduces a Cloud SQL instance with "Require trusted client+certificates" enabled. Not used in production.++- `ca.crt` / `ca.key` - test certificate authority that signs the server and client certs+- `server.crt` / `server.key` - server cert, CA-signed, `CN=localhost`, SAN `localhost,127.0.0.1`+- `client.crt` / `client.key` - client cert, CA-signed, `CN=testuser`+- `pg_hba.conf` - requires `clientcert=verify-ca` on every TLS connection++The container mounts `ca.crt` as `ssl_ca_file`; the backup/restore tests pass+`client.crt`, `client.key`, and `ca.crt` through the database API.++To regenerate (run from this directory, requires Bash for the SAN process substitution):++```+openssl req -x509 -newkey rsa:2048 -keyout ca.key -out ca.crt -days 3650 -nodes \+ -subj "/CN=Databasus Test CA"++openssl req -newkey rsa:2048 -keyout server.key -out server.csr -nodes \+ -subj "/CN=localhost"+openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \+ -out server.crt -days 3650 \+ -extfile <(printf "subjectAltName=DNS:localhost,IP:127.0.0.1")++openssl req -newkey rsa:2048 -keyout client.key -out client.csr -nodes \+ -subj "/CN=testuser"+openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \+ -out client.crt -days 3650++rm server.csr client.csr ca.srl+```diff --git a/backend/internal/features/tests/testdata/mtls/ca.crt b/backend/internal/features/tests/testdata/mtls/ca.crtnew file mode 100644index 00000000..2e74bcd8--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/ca.crt@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDGTCCAgGgAwIBAgIUHHdPK923iWkx3chRFdumcxqztvowDQYJKoZIhvcNAQEL+BQAwHDEaMBgGA1UEAwwRRGF0YWJhc3VzIFRlc3QgQ0EwHhcNMjYwNTIyMTUzNTUw+WhcNMzYwNTE5MTUzNTUwWjAcMRowGAYDVQQDDBFEYXRhYmFzdXMgVGVzdCBDQTCC+ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL/qYzYzuRugaudvEXiwSCW9+jpFQR6a3Ra38MiSF7AZONhdtpgG1clbvO8ud/ixcDvaFzZS4KnYiPG6YvRfy48kQ+jyBxjjYz0lkSm6YeFjXJ4hAHqMy42HsxOkb9NtHWyGrTDsBpthLjORDq8K5Mf0fO+te9iysLhrSHWrv502/e1ME3mRHubp8hs24sZFKiMajACUzPlAVlDvhQ2RPJs/R9b+CtmJGE72aoZQzxisgbA55aTI2Tmr8U5Jy8d1c3YFPtAGyWwAi2XNI5UWbPdt/ySl+4pa9xWOjuxj1BUEbqROA44FMsux+EMEeRPGuLo/F3gnmcRy4AX4yXwwZqGEORa8C+AwEAAaNTMFEwHQYDVR0OBBYEFEEDzWXZuSrfSA3E1/CcF23Y+dqPMB8GA1UdIwQY+MBaAFEEDzWXZuSrfSA3E1/CcF23Y+dqPMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI+hvcNAQELBQADggEBAHrGgaJkMNOANxTKuWwe5kCrcvvvEk1cQxxFCrHHI29itrPM+pxGedrJOg8A+F+NG7rB6iLjyDmyiVoZQypTQGHUta1kZsoe6qj3XNzvvS/sirVQw+uobeSwAVf11c3iespJPG4AyE6FX2VPwir55XRjj7UowUMgOwUeaDALGmWnanX7ln+f6qbjHLp8I52jFcyd3pGoj9Z1m5U+mvx/syEONKyn9d1XLM3Hn90iR4c5Y1IZ83m+cLnIsXCNtHI+8GwzXqEe8GeYGtrS44HAW7lw3gxmqpFsWK0JT56U31BpMMosTBXe+ZAQJdrthc7poSLPNusL+KtzBPcDlFQ7X5Vmj+lE=+-----END CERTIFICATE-----diff --git a/backend/internal/features/tests/testdata/mtls/ca.key b/backend/internal/features/tests/testdata/mtls/ca.keynew file mode 100644index 00000000..dbed2b68--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/ca.key@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/6mM2M7kboGrn+bxF4sEglvY6RUEemt0Wt/DIkhewGTjYXbaYBtXJW7zvLnf4sXA72hc2UuCp2Ijxu+mL0X8uPJEI8gcY42M9JZEpumHhY1yeIQB6jMuNh7MTpG/TbR1shq0w7AabYS4zkQ+6vCuTH9HzrXvYsrC4a0h1q7+dNv3tTBN5kR7m6fIbNuLGRSojGowAlMz5QFZQ74U+NkTybP0fWwrZiRhO9mqGUM8YrIGwOeWkyNk5q/FOScvHdXN2BT7QBslsAItlzSOV+Fmz3bf8kpeKWvcVjo7sY9QVBG6kTgOOBTLLsfhDBHkTxri6Pxd4J5nEcuAF+Ml8M+GahhDkWvAgMBAAECggEANRVwhswMvgsDtus+YmskMag6eJBDmWYlNGhHOFoAvIfC+p31RRzS4oTpACGS1qvB1xROilynPuOhkXdUKrMam4fUeGcO/KdfwrWmbuvmkfBFQ+4c00kBfq7TxjGcKteKJXwlCJyogS8CuAm+DYXOXU6PhQ05u4aOpCWNNIiSKqu1ub+7ZFpMjoJT4/40fm9X0eBaarqpEMend6te6X3dS5jWNqF3wCGdeud6DRy8JOy5QOh+e32n5q3H1pAMQpPC2faeI3d+J3/HW9lsfQdVSIXU8giEEW8z/MIGeM7dPeSQSF4m+sCdwPhmJ4lrAU9ONXFqJbddHEv4EGlhDjvnQJY8jgQKBgQD18rwwcfTGVpxFe9pc+2VCG3wwDRJOn89MimT1E7miM5bxPhJ7CDEXtBZzWfb6B8vX9Pv0KfSPxmfBqgfRa+TFtFn5WQRl7hltLLrB6t+i6GnkkBeVgmT8pf1ti1lb+OOGAHcdjUW2dqUZID0K6o+TxPXgD3cbqHr0yFFM/UVbqalLwKBgQDHwlRJKAhQ8Bk2EJCHrknhXW1qF/qa+Qim+H7c9E/TXC5rPR2iyHnqhcjyi9fdnnn/tWlHkaMbrhq35cYI8c3BPoUUIfwTTA+dk+ykaUKm4lJG0MPqTRvc82p+fYuLqr8sUUJj55kHaPrBoWitauLz3orZbqRVObS1sE+kqnbhctHgQKBgQCcQno6NUyU7tYed1AHCbLV3cReFyXQ4WLVapK4xtf6HMQFqXbM+RsvuiVBaHk35dgm/ulM+ZL9/cpSCtsouzLB4jamSnoMNxKts55AebQM+WDZ+D0Bo+Ju2m8nOA+wFXNI4ebMCcOu57aBPjBKTTHlq24i1rbYbGs79Bnn8p/ME31QKBgDxD+QOAtBo08Ua7AwolcKAeoAskd4Ml91YEgUkxHx/ZUFujvVwNdNIueBfL3lyKYa2l0+dP4eKdyF7dgxySNpg/lR4pyUjSUHqXf7md07C62C1q75+wkXZPrNHqF/4TjcbV4N+x40u6sWfGuOwEOHNeLTIIZ4dOgLAcf3oLPv/2fqBAoGAQkQsAEmAYVgKOje58X1n+TA7oQrVnjSnTPVYlOCaE/r3MhmLX+y6RiGe+sbnvrhwn5LhiL02SpwL81ZBAJmsH+6m2BxMNt3XO90U4mSLMyyE7m+FfJMBnudTvzgBUWrqpdcDW+HTPPuI9ZBxrIJt2w+uqA/BHGp2I4HuxInj6V6SKo=+-----END PRIVATE KEY-----diff --git a/backend/internal/features/tests/testdata/mtls/client.crt b/backend/internal/features/tests/testdata/mtls/client.crtnew file mode 100644index 00000000..adf227c0--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/client.crt@@ -0,0 +1,17 @@+-----BEGIN CERTIFICATE-----+MIICtjCCAZ4CFEwnKUVs6AIUNZZ3A+CL0c1fmqZ9MA0GCSqGSIb3DQEBCwUAMBwx+GjAYBgNVBAMMEURhdGFiYXN1cyBUZXN0IENBMB4XDTI2MDUyMjE1MzU1MFoXDTM2+MDUxOTE1MzU1MFowEzERMA8GA1UEAwwIdGVzdHVzZXIwggEiMA0GCSqGSIb3DQEB+AQUAA4IBDwAwggEKAoIBAQCqMqYdeNTKmdfXGliiHsy5yNWc+ww6NW4Jdx0P/8OW+mFOz11RUSB4F2IXM+7KVQZe8i0Ik3YI3heJuNYF3uNMROSSEfyIPSXtkVr08Dv8u+yxQZWR6yIv4/BJ5wfm9Q/rTYZ7Z/ujoTJBhCu9etcOBU9At5rapx9+QFYtRQCg95+VTZ48NuEhVyxHX8mBlfxP+CXo5FHcZXUt1krC/WoCF+lPslgiwbgWTxCfoM8SifC+KobdmQ9oGYMs9fTgnVnGErXwRlqEHd3wq8ooqqu9NQIU5BAL+mNrhr4tNJQKyzPR+Cw2+s4xdgMlsvoYyPBdywjgqRN4XbfF85IJNPGK8SwolAgMBAAEwDQYJKoZIhvcN+AQELBQADggEBAJmZu7UHWIsixD6MY0ccOpOL+OdlgTXvClJUPTsy0ApV/fsgTClm+XxRwrji2nBFSj17VaBb91bofom4EE5EvrG+224MrY24lnr0VOEQUGrrVp4N3VL5t+SEk5t22C3bzUhLu7hfdtF9uxtpzfz2CReXs5Obd6I+et9n7W+i4q/V1/zF7l41nU+yguwvdcZEAcP3pBbZhun+BUXpRhWRbB/9hy0aXL+tSbQDRdzl5L+MxRIufSDEQsg+yKQhFFLMRCYUgV8mAqoCgIvj/mvf/EUC4MKGviWi4UpIBkQSPtPNw5zk/IvIfP9Z+D5w4mlFO+C/CA82X1el60ttzxYsjqJaGtTw=+-----END CERTIFICATE-----diff --git a/backend/internal/features/tests/testdata/mtls/client.key b/backend/internal/features/tests/testdata/mtls/client.keynew file mode 100644index 00000000..f4de8a5b--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/client.key@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCqMqYdeNTKmdfX+GliiHsy5yNWc+ww6NW4Jdx0P/8OWmFOz11RUSB4F2IXM+7KVQZe8i0Ik3YI3heJu+NYF3uNMROSSEfyIPSXtkVr08Dv8uyxQZWR6yIv4/BJ5wfm9Q/rTYZ7Z/ujoTJBhC+u9etcOBU9At5rapx9+QFYtRQCg95VTZ48NuEhVyxHX8mBlfxP+CXo5FHcZXUt1kr+C/WoCF+lPslgiwbgWTxCfoM8SifCKobdmQ9oGYMs9fTgnVnGErXwRlqEHd3wq8oo+qqu9NQIU5BAL+mNrhr4tNJQKyzPRCw2+s4xdgMlsvoYyPBdywjgqRN4XbfF85IJN+PGK8SwolAgMBAAECgf9PvFxEcF/F9U9KyDzrx59SBMDjOvicqDl/ElchH2TqioNv+/D2Bno6HCzSE9W606o9PVVBveB73vrdHpfMviaXRacQeMbhERXn1wnMGsi278F3e+HEZiXk112vKNRIUP/sEWgCbN5ku/ShsqfeDL1WL9FIx1XiOXQTIC45MM2bpmIyHC+gUy9K2wmsZlufsIhQVQlecpEbsVqvpKE9sgeEqeV2hE/78v1SoIcZrZURPw+mz0D+ciCdpwRHs2ZTJHKzxl4SsyaJQsaduLP7OKyptGuUGAYOPqnzCWFBTbhLquuBC0sm+r4KhnDauqTv2+woipRAFOYHnabYyt5oBY4dUPAECgYEA25NI8rk3I1MCZjCTvQeV++bpPLsY5wBTc+YGBe/jUE3GRPyMQSE0caR0kpA0oBq8ygpQox6M0i/0H3h5uWLg/+aJYSbhaP5YDl5NnX82rfhEibLeUlwpAkci13/0SOcVVfFZ9MDg5s56YaHJ7b1Blv+fv+xQh/oZK/S6mWHiKn6AdkCgYEAxm5yu3vUrqKc2EZSaG7pC16h0CwpQzlsypHj+dsBUjvqmIAKkYW/xqPgPgeTht9r9bJhTS1EGpvv4EuvARRlteo2mwsdmqHTR5mS2+ClayI2N7gK/w3w3lvdcpqsQ/Vijv7Ie+aU+9f0cH/e6LV7wdLnrL59KShJKb19IE+hwwFDy0CgYBNs9lky9aPUZjPwPEHO9/+98d9rfhR2RA523KPBIdIOjBEP4xLib48+FGwbAezgMK+XNgcYXtEBmRFnsS0riEgoIrNy8dkKRosUaWLaaT+f+HGx1B2AtLGx+FhYY55Hg2W1EoZKwhrpTX5xt9GmmrTmfn6yC0ffTacUh3bwQyNYIQQKBgDlOhoYM+0jSJNADl9kDA3z7wWo0TY+tNN1UdYvLVwtX0H2wZNz4IpWMmGNxrrKB7dzsYlt2m+jeRF2rQkL8gE+vAs3p9cFRLLgh8msMg1l4bO4UkeBtN0YQg9joQJ3zzT386QuXYS+mGicq/szHDz/T/IvdpoB31y4NpfSyInz97YVAoGBAMye9ngRiBev/9erIVpVmQxV+9RLB0xixJQgX/J4tkaztmzRiEd4tN/ZR6IdCMQpkSF82ejihNhVg3UX0io2Y+yce+tuyFqy/BXK4+O4MSRvd8tfyP9jhvYhGn/5E1rgCMHbor8jB8UHJfoofYFytyJiHS+AYhSdYSMWivLx5AgX92d+-----END PRIVATE KEY-----diff --git a/backend/internal/features/tests/testdata/mtls/pg_hba.conf b/backend/internal/features/tests/testdata/mtls/pg_hba.confnew file mode 100644index 00000000..b12d646e--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/pg_hba.conf@@ -0,0 +1,10 @@+# mTLS-enforcing pg_hba.conf used only by the test-postgres-mtls container.+# Local Unix-socket connections are trusted (so the entrypoint can run initdb),+# but every TCP connection MUST present a client certificate signed by ca.crt+# over TLS - plaintext TCP and uncertified TLS are both rejected.+# This reproduces a Cloud SQL instance with "Require trusted client certificates".+local all all trust+hostssl all all 0.0.0.0/0 scram-sha-256 clientcert=verify-ca+hostssl all all ::/0 scram-sha-256 clientcert=verify-ca+hostnossl all all 0.0.0.0/0 reject+hostnossl all all ::/0 rejectdiff --git a/backend/internal/features/tests/testdata/mtls/server.crt b/backend/internal/features/tests/testdata/mtls/server.crtnew file mode 100644index 00000000..2facc662--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/server.crt@@ -0,0 +1,19 @@+-----BEGIN CERTIFICATE-----+MIIDHDCCAgSgAwIBAgIUTCcpRWzoAhQ1lncD4IvRzV+apnwwDQYJKoZIhvcNAQEL+BQAwHDEaMBgGA1UEAwwRRGF0YWJhc3VzIFRlc3QgQ0EwHhcNMjYwNTIyMTUzNTUw+WhcNMzYwNTE5MTUzNTUwWjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqG+SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC5AloOGCBC4fK0C1QnuTUe50udrqnrdfaD+Cs+eNjByMpwik7buJ9ZGn5iGiP5vXllwBu79azXYYr1xDgdTuoIhFSdC4Gt2n0LE+l807x/AU1akiBg+XSogS8tHVNqCtzIuFPKGUGEVwhlkVlf0mdRufrJWgVqiYA5VV+88/HiSR0L2kkKr9GoE8qOswgX4A9itVw5rVOtQM1DGRGlOrZbSr2DUrP9XQukrIo++X9BxWPcQdzbJIsWChi1oyWlKaC4k1nX5F9wkgsFoQuJpjXJ1AkEq7EGdzj1yJ8s+zkTYBv0VA0BHMFz2MBEH4Rnb/RDNvJ5CJpfyC93OE02m/YMq8cDpAgMBAAGjXjBc+MBoGA1UdEQQTMBGCCWxvY2FsaG9zdIcEfwAAATAdBgNVHQ4EFgQUII3YE9aRGQov+KBGj7Uhc1b7YJZgwHwYDVR0jBBgwFoAUQQPNZdm5Kt9IDcTX8JwXbdj52o8wDQYJ+KoZIhvcNAQELBQADggEBAKCafKjf7Bgdn6ECht/Rt79WFEknGv09dC+n1dxmKgAi+GjNO8H63veAtspHBLLxIXh2cQO73R2MpzkFEATXZ16BNynY+qPqgJWDrIN3k4z20+gHGiw/1ES4/V5DccYD9fI25VW/fAVSSd8Z+z4VBxsU2ccGSd7GEVu8RQEV+S5YcX+pS2cAsRBjoSFdvD9CLfckoIA4mGnt14WRYpUkCr1SqeHBZDluL2gtHvB/OLyzEiR+XTRYy16oEEQ35mvp5T1idRONZDP8/+H7k17gxmtRMunLZ0mhPJv8sTmZeqXOCEje+W1D2SVDcasI6TCkXp6EChelRWIyx69Du5cGsW50E4LQ=+-----END CERTIFICATE-----diff --git a/backend/internal/features/tests/testdata/mtls/server.key b/backend/internal/features/tests/testdata/mtls/server.keynew file mode 100644index 00000000..bc269ad8--- /dev/null+++ b/backend/internal/features/tests/testdata/mtls/server.key@@ -0,0 +1,28 @@+-----BEGIN PRIVATE KEY-----+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC5AloOGCBC4fK0+C1QnuTUe50udrqnrdfaDCs+eNjByMpwik7buJ9ZGn5iGiP5vXllwBu79azXYYr1x+DgdTuoIhFSdC4Gt2n0LEl807x/AU1akiBg+XSogS8tHVNqCtzIuFPKGUGEVwhlkV+lf0mdRufrJWgVqiYA5VV88/HiSR0L2kkKr9GoE8qOswgX4A9itVw5rVOtQM1DGRG+lOrZbSr2DUrP9XQukrIo+X9BxWPcQdzbJIsWChi1oyWlKaC4k1nX5F9wkgsFoQuJ+pjXJ1AkEq7EGdzj1yJ8szkTYBv0VA0BHMFz2MBEH4Rnb/RDNvJ5CJpfyC93OE02m+/YMq8cDpAgMBAAECggEAKaW24g9aS9QTT6ZxNlQB+kf1BLUJ+UBf0tX/MM1gEIUG+Et6PwoLjQJiyvC5goG9r0MUuzYtx3pkzrhyLV7TXkFzzrqFYb6agYCMQB1IV4IrM+fSVCIzua8DELPWUDvLwb+E1SzkS8dP05VpuiFiMsqcAvGp4Ha9j6qBOvhWqA80pK+rv5EsJ0tFcFKlWH2K3jJ5C+LXrZ46f5fpbgFEnewU2gZtK7FBMHmFgBd8au8hG26+N61o4m5Oympfpa/8JHbdWzt5G1s1GP7XKJVU3x+/H9KAJ6f2n6wOGER86o+t7Xo3+VEGuFEbZdMvJRPOyzwscbIG/dftHzWNaC0XYpPM5kQKBgQDqcDiH363XlWdBHYaT+bIeXMT2b3jlMvGATNwQH3Zs6QR33bodMSchK9CZW7rB2MVbWzr5LD8J3jZX40ad9+vKNCqjC7oy5kqUHr1jKpMaMYlE4GuhpGOrdpQkT1MWdygids4YuOzVOhAs7vHBPh++bWQCcXsY18ep67oZBiiWAV/zQKBgQDKBlYRUM7LuW7x/GZxEaat3Bos4xBcJN+U+9YsK4sAAX9TPLSgXjlM2U4xPAJx/29j7t3u0jHZs049MuAdNTIFDjAPWNshEwAKZ+IDC8C6BAJWAT3hqWdPyH1M0Rr0EeTy6MS8ndPVaRhB79QZX/6WypwaZFbP+OXFsA+GnKP4OTRjQKBgQCJYrZeOeDgg7d821awMlvLaJnYLAScSZBr8kO0cFO1cc+j3uv++8wYjlqyZKUvUF9nyDDpMNrIZ6alHpWVoNBHg0We5rklTyDTPhjkuGd6gWtjW7FzV+ZzdwwdszbX5YBpogHpTwXLdzlfe6/FNSjEmwXWnVu+5UQqQnn/EnwjmGyQKBgQCw+t3Ar/2KVJCSfOiil+UmyxViEMS8LWxnUZCD3KbfH3Av8GcT7Lf0uBVEzfhZnZXjd+XvevzDp/IWQ1OLjybdyYqG5mwE7YjJj5NwZKR2UrF0Z+uobJW5XWf1fOg13T1HGk+OVtf0prZ+RdeczNxws7Rg1odWqYE8laLtZbGsnOVtQKBgQCfONT51XkI29BVp+Zq+4YGcu3Y8xZa33sYz1HNM1k/m0UnRBISaQEZqT9j5FbyTQZgfJNqvcoWp5vXHIH7l+d89T/5Q88Kuptq8c5l5vSS4lcwmrPRlRu5YMZHWIe1WHSL7RyxdZ4Z+GelwfBdyN+DFadarfIjjtUEtCxHKm4qs2c0g==+-----END PRIVATE KEY-----diff --git a/backend/migrations/20260522161848_add_postgresql_ssl_config.sql b/backend/migrations/20260522161848_add_postgresql_ssl_config.sqlnew file mode 100644index 00000000..7a40ba6e--- /dev/null+++ b/backend/migrations/20260522161848_add_postgresql_ssl_config.sql@@ -0,0 +1,35 @@+-- +goose Up+-- +goose StatementBegin++ALTER TABLE postgresql_databases+ ADD COLUMN ssl_mode TEXT NOT NULL DEFAULT 'disable',+ ADD COLUMN ssl_client_cert TEXT NOT NULL DEFAULT '',+ ADD COLUMN ssl_client_key TEXT NOT NULL DEFAULT '',+ ADD COLUMN ssl_root_cert TEXT NOT NULL DEFAULT '';++UPDATE postgresql_databases+SET ssl_mode = 'require'+WHERE is_https = TRUE;++ALTER TABLE postgresql_databases+ DROP COLUMN is_https;++-- +goose StatementEnd++-- +goose Down+-- +goose StatementBegin++ALTER TABLE postgresql_databases+ ADD COLUMN is_https BOOLEAN NOT NULL DEFAULT FALSE;++UPDATE postgresql_databases+SET is_https = TRUE+WHERE ssl_mode <> 'disable';++ALTER TABLE postgresql_databases+ DROP COLUMN ssl_mode,+ DROP COLUMN ssl_client_cert,+ DROP COLUMN ssl_client_key,+ DROP COLUMN ssl_root_cert;++-- +goose StatementEnddiff --git a/docker-compose.yml b/docker-compose.ymlindex 29466e6a..fa19dd9f 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -683,6 +683,34 @@ services:timeout: 5sretries: 10+ # Enforces mutual TLS - rejects TCP clients without a CA-signed client cert.+ test-postgres-mtls:+ build:+ context: ./backend/internal/features/tests/testdata/mtls+ dockerfile_inline: |+ FROM postgres:18+ COPY server.key /etc/ssl-test/server.key+ COPY server.crt /etc/ssl-test/server.crt+ COPY ca.crt /etc/ssl-test/ca.crt+ COPY pg_hba.conf /etc/ssl-test/pg_hba.conf+ RUN chown postgres:postgres /etc/ssl-test/server.key /etc/ssl-test/server.crt /etc/ssl-test/ca.crt /etc/ssl-test/pg_hba.conf \+ && chmod 600 /etc/ssl-test/server.key \+ && chmod 644 /etc/ssl-test/server.crt /etc/ssl-test/ca.crt /etc/ssl-test/pg_hba.conf+ ports:+ - "${TEST_POSTGRES_MTLS_PORT:-5181}:5432"+ environment:+ - POSTGRES_DB=testdb+ - POSTGRES_USER=testuser+ - POSTGRES_PASSWORD=testpassword+ command: postgres -c ssl=on -c ssl_cert_file=/etc/ssl-test/server.crt -c ssl_key_file=/etc/ssl-test/server.key -c ssl_ca_file=/etc/ssl-test/ca.crt -c hba_file=/etc/ssl-test/pg_hba.conf+ container_name: test-postgres-mtls+ shm_size: 1gb+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U testuser -d testdb"]+ interval: 5s+ timeout: 5s+ retries: 10+test-mariadb-ssl:image: mariadb:11.8ports:diff --git a/frontend/src/entity/databases/index.ts b/frontend/src/entity/databases/index.tsindex 5ce49aee..f470aad5 100644--- a/frontend/src/entity/databases/index.ts+++ b/frontend/src/entity/databases/index.ts@@ -4,6 +4,7 @@ export { DatabaseType } from './model/DatabaseType';export { getDatabaseLogoFromType } from './model/getDatabaseLogoFromType';export { Period } from './model/Period';export { PostgresBackupType } from './model/postgresql/PostgresBackupType';+export { PostgresSslMode } from './model/postgresql/PostgresSslMode';export { type PostgresqlDatabase } from './model/postgresql/PostgresqlDatabase';export { PostgresqlVersion } from './model/postgresql/PostgresqlVersion';export { type MysqlDatabase } from './model/mysql/MysqlDatabase';diff --git a/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.test.ts b/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.test.tsindex 1cf5e944..8354e5fa 100644--- a/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.test.ts+++ b/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.test.ts@@ -5,6 +5,7 @@ import {type ParseError,type ParseResult,} from './ConnectionStringParser';+import { PostgresSslMode } from './PostgresSslMode';describe('ConnectionStringParser', () => {// Helper to assert successful parse@@ -30,7 +31,7 @@ describe('ConnectionStringParser', () => {expect(result.username).toBe('myuser');expect(result.password).toBe('mypassword');expect(result.database).toBe('mydb');- expect(result.isHttps).toBe(false);+ expect(result.sslMode).toBe(PostgresSslMode.Disable);});it('should default port to 5432 when not specified', () => {@@ -147,7 +148,7 @@ describe('ConnectionStringParser', () => {),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);});it('should return error for JDBC without user parameter', () => {@@ -223,7 +224,7 @@ describe('ConnectionStringParser', () => {expect(result.port).toBe(25060);expect(result.username).toBe('doadmin');expect(result.database).toBe('defaultdb');- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);});});@@ -253,7 +254,7 @@ describe('ConnectionStringParser', () => {expect(result.username).toBe('myuser');expect(result.password).toBe('mypassword');expect(result.database).toBe('mydb');- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);});});@@ -281,47 +282,71 @@ describe('ConnectionStringParser', () => {expect(result.host).toBe('free-tier.gcp-us-central1.cockroachlabs.cloud');expect(result.port).toBe(26257);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.VerifyFull);});});describe('SSL Mode Handling', () => {- it('should set isHttps=true for sslmode=require', () => {+ it('should set sslMode=require for sslmode=require', () => {const result = expectSuccess(ConnectionStringParser.parse('postgresql://u:p@host:5432/db?sslmode=require'),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);});- it('should set isHttps=true for sslmode=verify-ca', () => {+ it('should set sslMode=verify-ca for sslmode=verify-ca', () => {const result = expectSuccess(ConnectionStringParser.parse('postgresql://u:p@host:5432/db?sslmode=verify-ca'),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.VerifyCa);});- it('should set isHttps=true for sslmode=verify-full', () => {+ it('should set sslMode=verify-full for sslmode=verify-full', () => {const result = expectSuccess(ConnectionStringParser.parse('postgresql://u:p@host:5432/db?sslmode=verify-full'),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.VerifyFull);});- it('should set isHttps=false for sslmode=disable', () => {+ it('should set sslMode=disable for sslmode=disable', () => {const result = expectSuccess(ConnectionStringParser.parse('postgresql://u:p@host:5432/db?sslmode=disable'),);- expect(result.isHttps).toBe(false);+ expect(result.sslMode).toBe(PostgresSslMode.Disable);});- it('should set isHttps=false when no sslmode specified', () => {+ it('should derive sslMode=require from a remote host when no sslmode specified', () => {const result = expectSuccess(ConnectionStringParser.parse('postgresql://u:p@host:5432/db'));- expect(result.isHttps).toBe(false);+ expect(result.sslMode).toBe(PostgresSslMode.Require);+ });++ it('should derive sslMode=disable from localhost when no sslmode specified', () => {+ const result = expectSuccess(+ ConnectionStringParser.parse('postgresql://u:p@localhost:5432/db'),+ );++ expect(result.sslMode).toBe(PostgresSslMode.Disable);+ });++ it('should derive sslMode=disable from an IPv4 host when no sslmode specified', () => {+ const result = expectSuccess(+ ConnectionStringParser.parse('postgresql://u:[email protected]:5432/db'),+ );++ expect(result.sslMode).toBe(PostgresSslMode.Disable);+ });++ it('should treat sslmode=prefer as disable', () => {+ const result = expectSuccess(+ ConnectionStringParser.parse('postgresql://u:p@host:5432/db?sslmode=prefer'),+ );++ expect(result.sslMode).toBe(PostgresSslMode.Disable);});});@@ -395,7 +420,7 @@ describe('ConnectionStringParser', () => {),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);});it('should return error for libpq format missing host', () => {@@ -513,7 +538,7 @@ describe('ConnectionStringParser', () => {),);- expect(result.isHttps).toBe(true);+ expect(result.sslMode).toBe(PostgresSslMode.Require);expect(result.database).toBe('db');});diff --git a/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.ts b/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.tsindex e581317d..d3432e28 100644--- a/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.ts+++ b/frontend/src/entity/databases/model/postgresql/ConnectionStringParser.ts@@ -1,10 +1,14 @@+import { PostgresSslMode } from './PostgresSslMode';++const IPV4_PATTERN = /^\d{1,3}(\.\d{1,3}){3}$/;+export type ParseResult = {host: string;port: number;username: string;password: string;database: string;- isHttps: boolean;+ sslMode: PostgresSslMode;};export type ParseError = {@@ -81,7 +85,7 @@ export class ConnectionStringParser {if (azureMatch) {const [, user, , password, host, port, database, queryString] = azureMatch;- const isHttps = this.checkSslMode(queryString);+ const sslMode = this.checkSslMode(queryString, host);return {host: host,@@ -89,7 +93,7 @@ export class ConnectionStringParser {username: decodeURIComponent(user),password: decodeURIComponent(password),database: decodeURIComponent(database),- isHttps,+ sslMode,};}@@ -101,7 +105,7 @@ export class ConnectionStringParser {const username = decodeURIComponent(url.username);const password = decodeURIComponent(url.password);const database = decodeURIComponent(url.pathname.slice(1)); // Remove leading /- const isHttps = this.checkSslMode(url.search);+ const sslMode = this.checkSslMode(url.search, host);// Validate required fieldsif (!host) {@@ -126,7 +130,7 @@ export class ConnectionStringParser {username,password,database,- isHttps,+ sslMode,};} catch (e) {return {@@ -162,7 +166,7 @@ export class ConnectionStringParser {const params = new URLSearchParams(queryString);const username = params.get('user');const password = params.get('password');- const isHttps = this.checkSslMode(queryString);+ const sslMode = this.checkSslMode(queryString, host);if (!username) {return {@@ -184,7 +188,7 @@ export class ConnectionStringParser {username: decodeURIComponent(username),password: decodeURIComponent(password),database: decodeURIComponent(database),- isHttps,+ sslMode,};} catch (e) {return {@@ -245,7 +249,7 @@ export class ConnectionStringParser {};}- const isHttps = this.isSslEnabled(sslmode);+ const sslMode = this.resolveSslMode(sslmode, host);return {host,@@ -253,7 +257,7 @@ export class ConnectionStringParser {username,password,database,- isHttps,+ sslMode,};} catch (e) {return {@@ -263,22 +267,46 @@ export class ConnectionStringParser {}}- private static checkSslMode(queryString: string | undefined | null): boolean {- if (!queryString) return false;+ private static checkSslMode(+ queryString: string | undefined | null,+ host: string,+ ): PostgresSslMode {+ const normalizedQuery = queryString?.startsWith('?')+ ? queryString.slice(1)+ : (queryString ?? '');+ const params = new URLSearchParams(normalizedQuery);- const params = new URLSearchParams(- queryString.startsWith('?') ? queryString.slice(1) : queryString,- );- const sslmode = params.get('sslmode');+ return this.resolveSslMode(params.get('sslmode'), host);+ }- return this.isSslEnabled(sslmode);+ private static resolveSslMode(sslmode: string | null | undefined, host: string): PostgresSslMode {+ return this.parseSslMode(sslmode) ?? this.deriveSslModeFromHost(host);}- private static isSslEnabled(sslmode: string | null | undefined): boolean {- if (!sslmode) return false;+ private static parseSslMode(sslmode: string | null | undefined): PostgresSslMode | null {+ switch (sslmode?.toLowerCase()) {+ case 'require':+ return PostgresSslMode.Require;+ case 'verify-ca':+ return PostgresSslMode.VerifyCa;+ case 'verify-full':+ return PostgresSslMode.VerifyFull;+ case 'disable':+ case 'prefer':+ case 'allow':+ return PostgresSslMode.Disable;+ default:+ return null;+ }+ }++ private static deriveSslModeFromHost(host: string): PostgresSslMode {+ const bareHost = host.trim().toLowerCase();++ if (bareHost === 'localhost' || IPV4_PATTERN.test(bareHost)) {+ return PostgresSslMode.Disable;+ }- // These modes require SSL- const sslModes = ['require', 'verify-ca', 'verify-full'];- return sslModes.includes(sslmode.toLowerCase());+ return PostgresSslMode.Require;}}diff --git a/frontend/src/entity/databases/model/postgresql/PostgresSslMode.ts b/frontend/src/entity/databases/model/postgresql/PostgresSslMode.tsnew file mode 100644index 00000000..6788361b--- /dev/null+++ b/frontend/src/entity/databases/model/postgresql/PostgresSslMode.ts@@ -0,0 +1,6 @@+export enum PostgresSslMode {+ Disable = 'disable',+ Require = 'require',+ VerifyCa = 'verify-ca',+ VerifyFull = 'verify-full',+}diff --git a/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts b/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.tsindex 04db8d72..68e89ace 100644--- a/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts+++ b/frontend/src/entity/databases/model/postgresql/PostgresqlDatabase.ts@@ -1,4 +1,5 @@import type { PostgresBackupType } from './PostgresBackupType';+import type { PostgresSslMode } from './PostgresSslMode';import type { PostgresqlVersion } from './PostgresqlVersion';export interface PostgresqlDatabase {@@ -12,7 +13,12 @@ export interface PostgresqlDatabase {username: string;password: string;database?: string;- isHttps: boolean;++ // SSL / TLS+ sslMode: PostgresSslMode;+ sslClientCert?: string;+ sslClientKey?: string;+ sslRootCert?: string;// backup settingsincludeSchemas?: string[];diff --git a/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsxindex 3d47a70e..55a0dca3 100644--- a/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/edit/EditPostgreSqlSpecificDataComponent.tsx@@ -1,9 +1,15 @@import { CopyOutlined, DownOutlined, InfoCircleOutlined, UpOutlined } from '@ant-design/icons';-import { App, Button, Checkbox, Input, InputNumber, Select, Switch, Tooltip } from 'antd';+import { App, Button, Checkbox, Input, InputNumber, Select, Tooltip } from 'antd';import { useEffect, useState } from 'react';import { IS_CLOUD } from '../../../../constants';-import { type Database, PostgresBackupType, databaseApi } from '../../../../entity/databases';+import {+ type Database,+ PostgresBackupType,+ PostgresSslMode,+ type PostgresqlDatabase,+ databaseApi,+} from '../../../../entity/databases';import { ConnectionStringParser } from '../../../../entity/databases/model/postgresql/ConnectionStringParser';import { ClipboardHelper } from '../../../../shared/lib/ClipboardHelper';import { ToastHelper } from '../../../../shared/toast';@@ -26,6 +32,33 @@ interface Props {isRestoreMode?: boolean;}+const IPV4_PATTERN = /^\d{1,3}(\.\d{1,3}){3}$/;++const deriveSslModeFromHost = (rawHost: string): PostgresSslMode | null => {+ const trimmed = rawHost.trim().toLowerCase();++ if (trimmed.startsWith('https://')) return PostgresSslMode.Require;+ if (trimmed.startsWith('http://')) return PostgresSslMode.Disable;++ const bareHost = trimmed.split(':')[0];+ if (bareHost === 'localhost' || IPV4_PATTERN.test(bareHost)) {+ return PostgresSslMode.Disable;+ }++ return null;+};++const applySslMode = (+ postgresql: PostgresqlDatabase,+ sslMode: PostgresSslMode,+): PostgresqlDatabase => {+ if (sslMode === PostgresSslMode.Disable) {+ return { ...postgresql, sslMode, sslClientCert: '', sslClientKey: '', sslRootCert: '' };+ }++ return { ...postgresql, sslMode };+};+export const EditPostgreSqlSpecificDataComponent = ({database,@@ -50,14 +83,20 @@ export const EditPostgreSqlSpecificDataComponent = ({const [isTestingConnection, setIsTestingConnection] = useState(false);const [isConnectionFailed, setIsConnectionFailed] = useState(false);- const hasAdvancedValues = isRestoreMode- ? !!database.postgresql?.isExcludeExtensions ||- !!database.postgresql?.isRestoreOwnership ||- !!database.postgresql?.isRestorePrivileges- : !!database.postgresql?.includeSchemas?.length || !!database.postgresql?.excludeTables?.length;+ const hasAdvancedValues =+ !!database.postgresql?.sslClientCert ||+ !!database.postgresql?.sslRootCert ||+ (isRestoreMode+ ? !!database.postgresql?.isExcludeExtensions ||+ !!database.postgresql?.isRestoreOwnership ||+ !!database.postgresql?.isRestorePrivileges+ : !!database.postgresql?.includeSchemas?.length ||+ !!database.postgresql?.excludeTables?.length);const [isShowAdvanced, setShowAdvanced] = useState(hasAdvancedValues);const [hasAutoAddedPublicSchema, setHasAutoAddedPublicSchema] = useState(false);+ const [hasUserChosenSslMode, setHasUserChosenSslMode] = useState(!!database.id);+ const [isReplacingCerts, setIsReplacingCerts] = useState(false);const [isShowPasteModal, setIsShowPasteModal] = useState(false);@@ -87,11 +126,12 @@ export const EditPostgreSqlSpecificDataComponent = ({username: result.username,password: result.password,database: result.database,- isHttps: result.isHttps,+ sslMode: result.sslMode,cpuCount: 1,},};+ setHasUserChosenSslMode(true);setEditingDatabase(autoAddPublicSchemaForSupabase(updatedDatabase));setIsConnectionTested(false);message.success('Connection string parsed successfully');@@ -190,11 +230,42 @@ export const EditPostgreSqlSpecificDataComponent = ({onSaved(trimmedDatabase);};+ const updatePostgresqlCert = (+ field: 'sslClientCert' | 'sslClientKey' | 'sslRootCert',+ value: string,+ ) => {+ if (!editingDatabase?.postgresql) return;++ setEditingDatabase({+ ...editingDatabase,+ postgresql: { ...editingDatabase.postgresql, [field]: value },+ });+ setIsConnectionTested(false);+ };++ const startReplacingCerts = () => {+ if (!editingDatabase?.postgresql) return;++ setIsReplacingCerts(true);+ setEditingDatabase({+ ...editingDatabase,+ postgresql: {+ ...editingDatabase.postgresql,+ sslClientCert: '',+ sslClientKey: '',+ sslRootCert: '',+ },+ });+ setIsConnectionTested(false);+ };+useEffect(() => {setIsSaving(false);setIsConnectionTested(false);setIsTestingConnection(false);setIsConnectionFailed(false);+ setIsReplacingCerts(false);+ setHasUserChosenSslMode(!!database.id);setEditingDatabase({ ...database });}, [database]);@@ -253,6 +324,74 @@ export const EditPostgreSqlSpecificDataComponent = ({</div>);+ const renderSslCertSection = () => {+ const sslMode = editingDatabase.postgresql?.sslMode ?? PostgresSslMode.Disable;+ if (sslMode === PostgresSslMode.Disable) return null;++ const hadSslCert = !!database.postgresql?.sslClientCert;+ if (hadSslCert && !isReplacingCerts) {+ return (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">Client certificate</div>+ <div className="flex items-center">+ <span className="mr-3">*************</span>+ <Button size="small" onClick={startReplacingCerts}>+ Replace+ </Button>+ </div>+ </div>+ );+ }++ return (+ <>+ <div className="mb-1 flex w-full items-start">+ <div className="min-w-[150px]">Client certificate</div>+ <Input.TextArea+ value={editingDatabase.postgresql?.sslClientCert || ''}+ onChange={(e) => updatePostgresqlCert('sslClientCert', e.target.value)}+ size="small"+ className="max-w-[300px] grow"+ placeholder="-----BEGIN CERTIFICATE-----"+ autoSize={{ minRows: 2, maxRows: 5 }}+ />+ </div>++ <div className="mb-1 flex w-full items-start">+ <div className="min-w-[150px]">Client key</div>+ <Input.TextArea+ value={editingDatabase.postgresql?.sslClientKey || ''}+ onChange={(e) => updatePostgresqlCert('sslClientKey', e.target.value)}+ size="small"+ className="max-w-[300px] grow"+ placeholder="-----BEGIN PRIVATE KEY-----"+ autoSize={{ minRows: 2, maxRows: 5 }}+ />+ </div>++ <div className="mb-1 flex w-full items-start">+ <div className="flex min-w-[150px] items-center">+ <span>Server CA certificate</span>+ <Tooltip+ className="cursor-pointer"+ title="Optional. When provided, the server certificate is verified against this CA (verify-ca / verify-full)."+ >+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />+ </Tooltip>+ </div>+ <Input.TextArea+ value={editingDatabase.postgresql?.sslRootCert || ''}+ onChange={(e) => updatePostgresqlCert('sslRootCert', e.target.value)}+ size="small"+ className="max-w-[300px] grow"+ placeholder="-----BEGIN CERTIFICATE-----"+ autoSize={{ minRows: 2, maxRows: 5 }}+ />+ </div>+ </>+ );+ };+const renderPgDumpForm = () => {let isAllFieldsFilled = true;if (!editingDatabase.postgresql?.host) isAllFieldsFilled = false;@@ -289,12 +428,29 @@ export const EditPostgreSqlSpecificDataComponent = ({onChange={(e) => {if (!editingDatabase.postgresql) return;+ const rawHost = e.target.value;+ const basePostgresql = {+ ...editingDatabase.postgresql,+ host: rawHost.trim().replace('https://', '').replace('http://', ''),+ };+ const isHttpsHost = rawHost.trim().toLowerCase().startsWith('https://');+ const currentSslMode = basePostgresql.sslMode ?? PostgresSslMode.Disable;++ let derivedSslMode: PostgresSslMode | null = null;+ if (hasUserChosenSslMode) {+ if (isHttpsHost && currentSslMode === PostgresSslMode.Disable) {+ derivedSslMode = PostgresSslMode.Require;+ }+ } else {+ derivedSslMode = deriveSslModeFromHost(rawHost);+ }+const updatedDatabase = {...editingDatabase,- postgresql: {- ...editingDatabase.postgresql,- host: e.target.value.trim().replace('https://', '').replace('http://', ''),- },+ postgresql:+ derivedSslMode !== null+ ? applySslMode(basePostgresql, derivedSslMode)+ : basePostgresql,};setEditingDatabase(autoAddPublicSchemaForSupabase(updatedDatabase));setIsConnectionTested(false);@@ -426,19 +582,27 @@ export const EditPostgreSqlSpecificDataComponent = ({)}<div className="mb-1 flex w-full items-center">- <div className="min-w-[150px]">Use HTTPS</div>- <Switch- checked={editingDatabase.postgresql?.isHttps}- onChange={(checked) => {+ <div className="min-w-[150px]">SSL mode</div>+ <Select+ value={editingDatabase.postgresql?.sslMode ?? PostgresSslMode.Disable}+ onChange={(value: PostgresSslMode) => {if (!editingDatabase.postgresql) return;+ setHasUserChosenSslMode(true);setEditingDatabase({...editingDatabase,- postgresql: { ...editingDatabase.postgresql, isHttps: checked },+ postgresql: applySslMode(editingDatabase.postgresql, value),});setIsConnectionTested(false);}}+ options={[+ { label: 'Disable', value: PostgresSslMode.Disable },+ { label: 'Require', value: PostgresSslMode.Require },+ { label: 'Verify CA', value: PostgresSslMode.VerifyCa },+ { label: 'Verify full', value: PostgresSslMode.VerifyFull },+ ]}size="small"+ className="max-w-[200px] grow"/></div>@@ -624,6 +788,8 @@ export const EditPostgreSqlSpecificDataComponent = ({/></div>)}++ {renderSslCertSection()}</>)}diff --git a/frontend/src/features/databases/ui/show/ShowPostgreSqlSpecificDataComponent.tsx b/frontend/src/features/databases/ui/show/ShowPostgreSqlSpecificDataComponent.tsxindex 395a3b42..5b910b4a 100644--- a/frontend/src/features/databases/ui/show/ShowPostgreSqlSpecificDataComponent.tsx+++ b/frontend/src/features/databases/ui/show/ShowPostgreSqlSpecificDataComponent.tsx@@ -1,4 +1,9 @@-import { type Database, PostgresBackupType, PostgresqlVersion } from '../../../../entity/databases';+import {+ type Database,+ PostgresBackupType,+ PostgresSslMode,+ PostgresqlVersion,+} from '../../../../entity/databases';interface Props {database: Database;@@ -19,6 +24,13 @@ const backupTypeLabels: Record<string, string> = {[PostgresBackupType.WAL_V1]: 'Agent (physical)',};+const sslModeLabels: Record<string, string> = {+ [PostgresSslMode.Disable]: 'Disable',+ [PostgresSslMode.Require]: 'Require',+ [PostgresSslMode.VerifyCa]: 'Verify CA',+ [PostgresSslMode.VerifyFull]: 'Verify full',+};+export const ShowPostgreSqlSpecificDataComponent = ({ database }: Props) => {const backupType = database.postgresql?.backupType;const backupTypeLabel = backupType@@ -60,10 +72,18 @@ export const ShowPostgreSqlSpecificDataComponent = ({ database }: Props) => {</div><div className="mb-1 flex w-full items-center">- <div className="min-w-[150px]">Use HTTPS</div>- <div>{database.postgresql?.isHttps ? 'Yes' : 'No'}</div>+ <div className="min-w-[150px]">SSL mode</div>+ <div>{sslModeLabels[database.postgresql?.sslMode ?? PostgresSslMode.Disable]}</div></div>+ {!!database.postgresql?.sslClientCert &&+ database.postgresql?.sslMode !== PostgresSslMode.Disable && (+ <div className="mb-1 flex w-full items-center">+ <div className="min-w-[150px]">Client certificate</div>+ <div>*************</div>+ </div>+ )}+{!!database.postgresql?.includeSchemas?.length && (<div className="mb-1 flex w-full items-center"><div className="min-w-[150px]">Include schemas</div>