Skip to content

Commit 0d47365

Browse files
VJ-yadavanandgupta42
authored andcommitted
fix: address code review findings on URI sanitizer
Multi-model code review flagged three real bugs in sanitizeConnectionString: 1. CRITICAL — greedy regex corrupted URIs with '@' in query/path Example: postgresql://u:p@host/[email protected] Rightmost '@' was in the query string, not the userinfo separator. The sanitizer treated host/db?email=alice as part of the password and percent-encoded it, producing a broken URI. 2. MAJOR — short-circuit on %XX skipped passwords with mixed encoding Example: postgresql://user:p%20ss@word@host/db Partially-encoded password contained both a valid %20 and a raw '@'. The 'already-encoded, leave alone' check bailed early and left '@' unencoded. 3. MINOR — username-only userinfo (no colon) was skipped entirely Example: postgresql://[email protected]@host/db Email-as-username with unencoded '@' broke URI parsing because we returned early on missing colon. Changes: - Scan for the LAST '@' in the afterScheme portion directly instead of first parsing out an 'authority' segment. The URI spec disallows unencoded path/query/fragment delimiters in authority, but real-world passwords do contain them — so we honor user intent over spec. - Replace the %XX short-circuit + needsEncoding pre-check with a single idempotent encoder (decode → encode) applied to both user and password components. This round-trips already-encoded values unchanged and encodes raw values correctly in one pass. - Handle username-only userinfo by encoding it when no colon is present. - Add an ambiguity guard: when the rightmost '@' is followed by no path/query/fragment delimiter but preceded by one, the '@' is in the query/path/fragment — return the URI unchanged and expect the caller to pre-encode. Test coverage added for all three bugs plus IPv6 hosts, URIs with no port, URIs with no path, path-with-@, fragment-with-@, and the ambiguous both-password-and-query-have-@ case.
1 parent 258a4cb commit 0d47365

2 files changed

Lines changed: 147 additions & 40 deletions

File tree

‎packages/drivers/src/normalize.ts‎

Lines changed: 68 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -127,49 +127,77 @@ const DRIVER_ALIASES: Record<string, AliasMap> = {
127127
* passwords (containing %XX sequences) are left untouched.
128128
*/
129129
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
130+
// Only touch scheme://... URIs.
131+
const schemeMatch = connectionString.match(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//)
132+
if (!schemeMatch) return connectionString
133+
134+
const scheme = schemeMatch[0]
135+
const afterScheme = connectionString.slice(scheme.length)
136+
137+
// Find the userinfo/host separator. A password can legitimately contain
138+
// '@', '#', '/', '?', or ':' characters, so the URI spec is ambiguous
139+
// when those are unencoded. We use the LAST '@' as the separator because
140+
// that correctly handles the common case of passwords with special
141+
// characters (the stated purpose of this function — see issue #589).
132142
//
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-
// decodeURIComponent can throw on malformed percent sequences — fall back to
163-
// encoding the raw value if that happens.
164-
let encodedUser: string
165-
try {
166-
encodedUser = encodeURIComponent(decodeURIComponent(user))
167-
} catch {
168-
encodedUser = encodeURIComponent(user)
143+
// The known trade-off: if the query string or path also contains an
144+
// unencoded '@' (e.g. `[email protected]`), the rightmost '@'
145+
// is NOT the userinfo separator. We detect this ambiguous case below
146+
// with a guard and bail to avoid corrupting the URI.
147+
const lastAt = afterScheme.lastIndexOf("@")
148+
if (lastAt < 0) return connectionString // No userinfo — nothing to fix
149+
150+
const beforeAt = afterScheme.slice(0, lastAt)
151+
const afterAt = afterScheme.slice(lastAt + 1)
152+
153+
// Ambiguity guard: if the content AFTER the '@' has no path/query/
154+
// fragment delimiter ('/', '?', or '#') but the content BEFORE the
155+
// '@' does, then the '@' is almost certainly inside a path, query,
156+
// or fragment — not the userinfo separator. Bail and leave the URI
157+
// untouched so the caller can pre-encode explicitly.
158+
//
159+
// Examples that trigger the guard (correctly left alone):
160+
// postgresql://u:p@host/[email protected] ('@' in query)
161+
// postgresql://u:p@host:5432/db@archive ('@' in path)
162+
// postgresql://u:p@host/db#at@frag ('@' in fragment)
163+
//
164+
// Examples that pass the guard (correctly encoded):
165+
// postgresql://u:p@ss@host/db (last '@' has '/' after)
166+
// postgresql://u:f@ke#PLACEHOLDER@host/db (last '@' has '/' after)
167+
const afterAtHasDelim = /[/?#]/.test(afterAt)
168+
const beforeAtHasDelim = /[/?#]/.test(beforeAt)
169+
if (!afterAtHasDelim && beforeAtHasDelim) {
170+
return connectionString
171+
}
172+
173+
// Idempotent re-encoding: decode any existing percent-escapes and
174+
// re-encode. Already-encoded values round-trip unchanged; raw values
175+
// with special characters get encoded. Malformed percent sequences
176+
// fall back to encoding the raw input.
177+
const encodeIdempotent = (v: string): string => {
178+
if (v.length === 0) return v
179+
try {
180+
return encodeURIComponent(decodeURIComponent(v))
181+
} catch {
182+
return encodeURIComponent(v)
183+
}
184+
}
185+
186+
// Split userinfo on the FIRST ':' only (password may contain ':').
187+
const colonIdx = beforeAt.indexOf(":")
188+
let encodedUserinfo: string
189+
if (colonIdx < 0) {
190+
// Username-only userinfo: still encode if it contains special chars
191+
// (e.g. email addresses used as usernames).
192+
encodedUserinfo = encodeIdempotent(beforeAt)
193+
} else {
194+
const user = beforeAt.slice(0, colonIdx)
195+
const password = beforeAt.slice(colonIdx + 1)
196+
encodedUserinfo = `${encodeIdempotent(user)}:${encodeIdempotent(password)}`
169197
}
170-
const encodedPassword = encodeURIComponent(password)
171198

172-
return `${scheme}${encodedUser}:${encodedPassword}@${rest}`
199+
const rebuilt = `${scheme}${encodedUserinfo}@${afterAt}`
200+
return rebuilt === connectionString ? connectionString : rebuilt
173201
}
174202

175203
// ---------------------------------------------------------------------------

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

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1027,6 +1027,85 @@ describe("sanitizeConnectionString", () => {
10271027
const input = "postgresql://testuser@localhost:5432/testdb"
10281028
expect(sanitizeConnectionString(input)).toBe(input)
10291029
})
1030+
1031+
test("preserves @ in query string (does not misinterpret as userinfo)", () => {
1032+
const input =
1033+
"postgresql://testuser:simpleval@localhost:5432/[email protected]"
1034+
expect(sanitizeConnectionString(input)).toBe(input)
1035+
})
1036+
1037+
test("bails on ambiguous URIs where both password and query contain @", () => {
1038+
// When both the password and the query string contain unencoded '@',
1039+
// there's no way to deterministically pick the userinfo separator.
1040+
// We return the URI untouched and expect the caller to pre-encode.
1041+
const input =
1042+
"postgresql://testuser:p@ss@localhost:5432/[email protected]"
1043+
expect(sanitizeConnectionString(input)).toBe(input)
1044+
})
1045+
1046+
test("encodes @ in username-only userinfo (no password)", () => {
1047+
// Email-as-username with no password: the '@' in the email must be
1048+
// encoded so the driver doesn't treat the domain as the host.
1049+
const input = "postgresql://[email protected]@localhost:5432/testdb"
1050+
const result = sanitizeConnectionString(input)
1051+
expect(result).toBe(
1052+
"postgresql://alice%40example.com@localhost:5432/testdb",
1053+
)
1054+
})
1055+
1056+
test("encodes @ in partially-encoded password (not short-circuited by %XX)", () => {
1057+
// Password contains an encoded space (%20) AND a raw '@'. Previous
1058+
// logic short-circuited on seeing %XX and left '@' unencoded,
1059+
// producing a broken URI.
1060+
const input = "postgresql://testuser:p%20ss@word@localhost:5432/testdb"
1061+
const result = sanitizeConnectionString(input)
1062+
expect(result).toBe(
1063+
"postgresql://testuser:p%20ss%40word@localhost:5432/testdb",
1064+
)
1065+
})
1066+
1067+
test("encodes # in partially-encoded password", () => {
1068+
const input = "postgresql://testuser:pa%40ss#word@localhost:5432/testdb"
1069+
const result = sanitizeConnectionString(input)
1070+
// %40 is preserved; raw '#' gets encoded to %23
1071+
expect(result).toBe(
1072+
"postgresql://testuser:pa%40ss%23word@localhost:5432/testdb",
1073+
)
1074+
})
1075+
1076+
test("handles malformed percent sequence in password gracefully", () => {
1077+
// '%ZZ' is not a valid percent-escape. Falls back to encoding raw.
1078+
const input = "postgresql://testuser:bad%ZZpass@localhost:5432/testdb"
1079+
const result = sanitizeConnectionString(input)
1080+
// Raw-encoded password contains %25 (encoded '%') and ZZ literal
1081+
expect(result).toBe(
1082+
"postgresql://testuser:bad%25ZZpass@localhost:5432/testdb",
1083+
)
1084+
})
1085+
1086+
test("preserves @ in path after authority", () => {
1087+
// A path segment with '@' is unusual but valid and must not be
1088+
// treated as userinfo.
1089+
const input = "postgresql://testuser:simpleval@localhost:5432/db@archive"
1090+
expect(sanitizeConnectionString(input)).toBe(input)
1091+
})
1092+
1093+
test("preserves @ in fragment", () => {
1094+
const input = "postgresql://testuser:simpleval@localhost:5432/testdb#at@frag"
1095+
expect(sanitizeConnectionString(input)).toBe(input)
1096+
})
1097+
1098+
test("handles scheme-only URI with no path", () => {
1099+
const input = "postgresql://testuser:p@ss@localhost:5432"
1100+
const result = sanitizeConnectionString(input)
1101+
expect(result).toBe("postgresql://testuser:p%40ss@localhost:5432")
1102+
})
1103+
1104+
test("handles URI with no port", () => {
1105+
const input = "postgresql://testuser:p@ss@localhost/testdb"
1106+
const result = sanitizeConnectionString(input)
1107+
expect(result).toBe("postgresql://testuser:p%40ss@localhost/testdb")
1108+
})
10301109
})
10311110

10321111
// ---------------------------------------------------------------------------

0 commit comments

Comments
 (0)