diff --git a/internal/component/database_observability/postgres/collector/dsn.go b/internal/component/database_observability/postgres/collector/dsn.go index c89cc13b0ba..bd2ce3f99d1 100644 --- a/internal/component/database_observability/postgres/collector/dsn.go +++ b/internal/component/database_observability/postgres/collector/dsn.go @@ -8,7 +8,7 @@ import ( type databaseConnectionFactory func(dsn string) (*sql.DB, error) -var dsnParseRegex = regexp.MustCompile(`^(\w+:\/\/.+\/)(?[\w\-_\$]+)(\??.*$)`) +var dsnParseRegex = regexp.MustCompile(`^(\w+:\/\/[\w:@.\-_]*\/)(?[\w\-_\$]+)((?:\?\S*)?)`) var defaultDbConnectionFactory = func(dsn string) (*sql.DB, error) { return sql.Open("postgres", dsn) } diff --git a/internal/component/database_observability/postgres/collector/dsn_test.go b/internal/component/database_observability/postgres/collector/dsn_test.go index cbd37b207df..36ef32f06ba 100644 --- a/internal/component/database_observability/postgres/collector/dsn_test.go +++ b/internal/component/database_observability/postgres/collector/dsn_test.go @@ -39,17 +39,35 @@ func TestReplaceDatabaseNameInDSN(t *testing.T) { expected: "postgres://postgres:password@localhost:5432/testdb", }, { - name: "database name appears in password", + name: "problematic case - database name appears in password", dsn: "postgres://user:mydb123@localhost:5432/mydb", newDBName: "newdb", expected: "postgres://user:mydb123@localhost:5432/newdb", }, { - name: "database name with special characters", + name: "problematic case - database name with special characters", dsn: "postgres://user:pass@localhost:5432/my-db_test$1", newDBName: "new_db", expected: "postgres://user:pass@localhost:5432/new_db", }, + { + name: "unix socket - minimum postgres DSN", + dsn: "postgres:///mydb?host=/run/postgresql", + newDBName: "newdb", + expected: "postgres:///newdb?host=/run/postgresql", + }, + { + name: "unix socket - general postgres DSN", + dsn: "postgres://user:@/mydb?host=/run/postgresql", + newDBName: "newdb", + expected: "postgres://user:@/newdb?host=/run/postgresql", + }, + { + name: "unix socket problematic case - hostname and dbname with special characters", + dsn: "postgres://user:pass@ex-amp_le.com:5432/my-db_test$1?host=/run/postgresql", + newDBName: "new_db", + expected: "postgres://user:pass@ex-amp_le.com:5432/new_db?host=/run/postgresql", + }, { name: "invalid DSN format", dsn: "invalid-dsn-format", @@ -62,6 +80,18 @@ func TestReplaceDatabaseNameInDSN(t *testing.T) { newDBName: "newdb", expectError: true, }, + { + name: "DSN with space", + dsn: "postgres://user:pass @localhost:5432/", + newDBName: "newdb", + expectError: true, + }, + { + name: "DSN with space in query parameters", + dsn: "postgres://user:pass@localhost:5432/mydb?sslmode=disable &connect_timeout=10", + newDBName: "newdb", + expectError: true, + }, } for _, tt := range tests {