Skip to content

Commit 93db0f4

Browse files
VJ-yadavVijay Yadav
andcommitted
fix: URL-encode special characters in connection string passwords
sanitizeConnectionString existed but was never called. Wire it into normalizeConfig so every driver benefits automatically. Also fix the userinfo regex to split on the LAST '@' (greedy match) instead of the first, since passwords themselves may contain '@'. Closes #589 Co-Authored-By: Vijay Yadav <[email protected]>
1 parent 99270e5 commit 93db0f4

3 files changed

Lines changed: 176 additions & 2 deletions

File tree

‎packages/drivers/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
export type { Connector, ConnectorResult, SchemaColumn, ConnectionConfig } from "./types"
33

44
// Re-export config normalization
5-
export { normalizeConfig } from "./normalize"
5+
export { normalizeConfig, sanitizeConnectionString } from "./normalize"
66

77
// Re-export driver connect functions
88
export { connect as connectPostgres } from "./postgres"

‎packages/drivers/src/normalize.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,60 @@ const DRIVER_ALIASES: Record<string, AliasMap> = {
111111
// duckdb and sqlite have simple configs — no aliases needed
112112
}
113113

114+
// ---------------------------------------------------------------------------
115+
// Connection string password encoding
116+
// ---------------------------------------------------------------------------
117+
118+
/**
119+
* URI-style connection strings (postgres://, mongodb://, etc.) embed
120+
* credentials in the userinfo section: `scheme://user:password@host/db`.
121+
* If the password contains special characters (@, #, :, /, ?, etc.) and
122+
* they are NOT percent-encoded, drivers will mis-parse the URI and fail
123+
* with cryptic auth errors.
124+
*
125+
* This function detects an unencoded password in the userinfo portion and
126+
* re-encodes it so the connection string is valid. Already-encoded
127+
* passwords (containing %XX sequences) are left untouched.
128+
*/
129+
export function sanitizeConnectionString(connectionString: string): string {
130+
// Match scheme://userinfo@host... — we only touch the userinfo part.
131+
// Schemes: postgresql, postgres, mongodb, mongodb+srv, clickhouse, http, https, redshift
132+
//
133+
// IMPORTANT: The password itself may contain '@' characters, so we must
134+
// split on the LAST '@' before the host portion. The regex below uses a
135+
// greedy (.+) for userinfo so it consumes everything up to the final '@'.
136+
const uriMatch = connectionString.match(
137+
/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)(.+)@([^@]+)$/,
138+
)
139+
if (!uriMatch) return connectionString // No userinfo section — nothing to fix
140+
141+
const [, scheme, userinfo, rest] = uriMatch
142+
143+
// Split userinfo into user:password on the FIRST colon only
144+
const colonIdx = userinfo.indexOf(":")
145+
if (colonIdx < 0) return connectionString // No password in userinfo
146+
147+
const user = userinfo.slice(0, colonIdx)
148+
const password = userinfo.slice(colonIdx + 1)
149+
150+
// If the password already contains percent-encoded sequences, assume
151+
// the caller encoded it properly and leave it alone.
152+
if (/%[0-9A-Fa-f]{2}/.test(password)) return connectionString
153+
154+
// Check if the password contains characters that need encoding.
155+
// RFC 3986 unreserved: A-Z a-z 0-9 - . _ ~
156+
// We also allow ! * ' ( ) which are sub-delimiters often safe in passwords.
157+
// Everything else (especially @ : / ? # [ ]) MUST be encoded.
158+
const needsEncoding = /[@:#/?[\]%]/.test(password)
159+
if (!needsEncoding) return connectionString
160+
161+
// Re-encode both user and password to be safe
162+
const encodedUser = encodeURIComponent(decodeURIComponent(user))
163+
const encodedPassword = encodeURIComponent(password)
164+
165+
return `${scheme}${encodedUser}:${encodedPassword}@${rest}`
166+
}
167+
114168
// ---------------------------------------------------------------------------
115169
// Core logic
116170
// ---------------------------------------------------------------------------
@@ -178,6 +232,15 @@ export function normalizeConfig(config: ConnectionConfig): ConnectionConfig {
178232
const aliases = DRIVER_ALIASES[type]
179233
let result = aliases ? applyAliases(config, aliases) : { ...config }
180234

235+
// Sanitize connection_string: if the password contains special characters
236+
// (@, #, :, /, etc.) that are not percent-encoded, URI-based drivers will
237+
// mis-parse the string and fail with cryptic auth errors. This is the
238+
// single integration point — every caller of normalizeConfig() gets the
239+
// fix automatically.
240+
if (typeof result.connection_string === "string") {
241+
result.connection_string = sanitizeConnectionString(result.connection_string)
242+
}
243+
181244
// Type-specific post-processing
182245
// Note: MySQL SSL fields (ssl_ca, ssl_cert, ssl_key) are NOT constructed
183246
// into an ssl object here. They stay as top-level fields so the credential

‎packages/opencode/test/altimate/driver-normalize.test.ts‎

Lines changed: 112 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, test } from "bun:test"
2-
import { normalizeConfig } from "@altimateai/drivers"
2+
import { normalizeConfig, sanitizeConnectionString } from "@altimateai/drivers"
33
import { isSensitiveField } from "../../src/altimate/native/connections/credential-store"
44

55
// ---------------------------------------------------------------------------
@@ -947,3 +947,114 @@ describe("normalizeConfig — ClickHouse", () => {
947947
expect(result.ssl_key).toBeUndefined()
948948
})
949949
})
950+
951+
// ---------------------------------------------------------------------------
952+
// sanitizeConnectionString — special character encoding
953+
// ---------------------------------------------------------------------------
954+
955+
describe("sanitizeConnectionString", () => {
956+
test("encodes @ in password", () => {
957+
const input = "postgresql://user:p@ss@localhost:5432/db"
958+
const result = sanitizeConnectionString(input)
959+
expect(result).toBe("postgresql://user:p%40ss@localhost:5432/db")
960+
})
961+
962+
test("encodes # in password", () => {
963+
const input = "postgresql://admin:pass#word@localhost/db"
964+
const result = sanitizeConnectionString(input)
965+
expect(result).toBe("postgresql://admin:pass%23word@localhost/db")
966+
})
967+
968+
test("encodes : in password", () => {
969+
const input = "postgresql://admin:pass:word@localhost/db"
970+
const result = sanitizeConnectionString(input)
971+
expect(result).toBe("postgresql://admin:pass%3Aword@localhost/db")
972+
})
973+
974+
test("encodes multiple special characters", () => {
975+
const input = "postgresql://admin:p@ss#w:rd@localhost/db"
976+
const result = sanitizeConnectionString(input)
977+
expect(result).toBe("postgresql://admin:p%40ss%23w%3Ard@localhost/db")
978+
})
979+
980+
test("leaves already-encoded passwords untouched", () => {
981+
const input = "postgresql://admin:p%40ss%23word@localhost/db"
982+
expect(sanitizeConnectionString(input)).toBe(input)
983+
})
984+
985+
test("leaves passwords without special characters untouched", () => {
986+
const input = "postgresql://admin:simplepassword@localhost/db"
987+
expect(sanitizeConnectionString(input)).toBe(input)
988+
})
989+
990+
test("leaves non-URI strings untouched", () => {
991+
const input = "host=localhost dbname=mydb"
992+
expect(sanitizeConnectionString(input)).toBe(input)
993+
})
994+
995+
test("handles mongodb scheme", () => {
996+
const input = "mongodb://user:p@ss@localhost:27017/mydb"
997+
const result = sanitizeConnectionString(input)
998+
expect(result).toBe("mongodb://user:p%40ss@localhost:27017/mydb")
999+
})
1000+
1001+
test("handles mongodb+srv scheme", () => {
1002+
const input = "mongodb+srv://user:p@[email protected]/mydb"
1003+
const result = sanitizeConnectionString(input)
1004+
expect(result).toBe("mongodb+srv://user:p%[email protected]/mydb")
1005+
})
1006+
1007+
test("leaves URIs without password untouched", () => {
1008+
const input = "postgresql://admin@localhost/db"
1009+
expect(sanitizeConnectionString(input)).toBe(input)
1010+
})
1011+
})
1012+
1013+
// ---------------------------------------------------------------------------
1014+
// normalizeConfig — connection_string sanitization integration
1015+
// ---------------------------------------------------------------------------
1016+
1017+
describe("normalizeConfig — connection_string sanitization", () => {
1018+
test("sanitizes connection_string with special chars in password", () => {
1019+
const result = normalizeConfig({
1020+
type: "postgres",
1021+
connection_string: "postgresql://admin:p@ss#word@localhost/db",
1022+
})
1023+
expect(result.connection_string).toBe(
1024+
"postgresql://admin:p%40ss%23word@localhost/db",
1025+
)
1026+
})
1027+
1028+
test("sanitizes connectionString alias with special chars", () => {
1029+
const result = normalizeConfig({
1030+
type: "postgres",
1031+
connectionString: "postgresql://admin:p@ss@localhost/db",
1032+
})
1033+
// alias resolved to connection_string, then sanitized
1034+
expect(result.connection_string).toBe(
1035+
"postgresql://admin:p%40ss@localhost/db",
1036+
)
1037+
expect(result.connectionString).toBeUndefined()
1038+
})
1039+
1040+
test("does not alter connection_string without special chars", () => {
1041+
const result = normalizeConfig({
1042+
type: "redshift",
1043+
connection_string: "postgresql://admin:password@host:5439/dev",
1044+
})
1045+
expect(result.connection_string).toBe(
1046+
"postgresql://admin:password@host:5439/dev",
1047+
)
1048+
})
1049+
1050+
test("does not alter config without connection_string", () => {
1051+
const result = normalizeConfig({
1052+
type: "postgres",
1053+
host: "localhost",
1054+
password: "p@ss#word",
1055+
})
1056+
// Individual fields are NOT URI-encoded — drivers handle them natively
1057+
expect(result.password).toBe("p@ss#word")
1058+
expect(result.connection_string).toBeUndefined()
1059+
})
1060+
})

0 commit comments

Comments
 (0)