Repository navigation
fix(sessions): handle Cloud SQL Unix socket connections - #871
kalenkevich merged 14 commits into
Conversation
…d real-driver query-param test
…ides a TCP hostname
…onsFromUri for mysql:// and mariadb://
AmaadMartin
left a comment
There was a problem hiding this comment.
Reviewed alongside #869, since the two change the same function and carry near-identical parsers. This one is the better-built of the pair: parseSocketUri wraps its whole body in try/catch so a malformed percent-escape returns null instead of throwing, and routing the socket through driverOptions.connection.socketPath rather than host is the right call for mysql2/mariadb — your description justifies the asymmetry with Postgres, and that justification holds up. Checking ?host= before falling back to clientUrl is also correct, and warning only when it overrides a genuine TCP host is a nice touch.
The gap is that the guard you added to parseSocketUri is missing from buildMySqlFamilyOptions, which decodes the same untrusted fields on the path where new URL() succeeds. I verified both branches throw. Details inline.
Coordination, which matters more than either nit: I test-merged this against #869 and they conflict in 7 hunks across both files. #869 rewrites the whole if/else chain into early returns while this PR edits the mysql/mariadb arms of that chain in place, and parseSocketUri here and parsePostgresSocketUri there are close to character-identical apart from socketPath vs host and schema. Whichever lands first forces a real rebase on the other, and the natural end state is two copies of the same 40-line hand-rolled parser in one file. Since the guard question already has a right answer here and a wrong one there, folding these into one PR — or stacking this on #869 and extracting one shared parser — would settle both problems at once. That's a maintainer call, not mine, but it's worth making deliberately rather than discovering it at merge time.
| password: parsedUrl.password | ||
| ? decodeURIComponent(parsedUrl.password) | ||
| : undefined, | ||
| dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined, |
There was a problem hiding this comment.
Not a nit. parseSocketUri guards its decodes; this branch doesn't, and it runs whenever new URL() succeeds — which the guard in the manual parser never covers.
dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined,I ran both socket branches of buildMySqlFamilyOptions:
mysql://u:p@%2Fcloudsql%2Fa/db%ZZ -> UNCAUGHT URIError (url-sock branch)
mysql://u:p@host/db%ZZ?host=/cloudsql/p:r:i -> UNCAUGHT URIError (url-host branch)
new URL() does not validate percent-escapes, so it accepts both and hands you a pathname that decodeURIComponent then rejects. The identical line at 163 and the username/password decodes above have the same exposure — six call sites in total across the two branches.
You already made the decision correctly once, at line 58 ("Malformed percent-encoding falls back to null instead of throwing"). Extending it to a shared helper covers every site:
function safeDecode(value: string): string | undefined {
try {
return decodeURIComponent(value);
} catch {
return undefined;
}
}One caveat I did not verify: what mysql2 does with database: undefined versus the raw undecoded string. Passing the raw value through may be the friendlier fallback, since a database actually named db%ZZ is more plausible than the user wanting the name dropped.
| : undefined, | ||
| dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined, | ||
| driverOptions: { | ||
| connection: {socketPath: queryHost}, |
There was a problem hiding this comment.
Nit, optional — the socket branches drop every query parameter.
connection: {socketPath: queryHost},The returned options carry no clientUrl, and unlike #869 (which at least forwards schema and port) this one forwards nothing beyond user, password and dbName. So on a URI like mysql://u:p@host/db?host=/cloudsql/p:r:i&charset=utf8mb4&connectTimeout=10000, both charset and connectTimeout are silently discarded where previously they rode along on clientUrl.
charset in particular tends to be load-bearing for MySQL. Either forward the leftover parameters into driverOptions.connection, or state in the doc comment that the socket path supports only the credentials and database name — the current silence reads like an oversight rather than a decision.
Flagging rather than asserting: I have not checked how mysql2 merges driverOptions.connection with MikroORM's own parsed options, so the right shape for forwarding may not be a straight spread.
|
Folded the PostgreSQL changes from #869 into this PR and merged the latest upstream/main. All 50 operations tests are passing. |
| expect(resolved).not.toHaveProperty('connect_timeout'); | ||
| }); | ||
|
|
||
| it('should leave a percent-encoded Unix-socket host with escaped colons as clientUrl, since MikroORM already decodes it correctly', async () => { |
There was a problem hiding this comment.
The title says MikroORM "decodes it correctly" — it decodes the host, not the port. +url.port on a portless clientUrl is 0 (@mikro-orm/core/connections/Connection.js:62), and pg dials host + '/.s.PGSQL.' + port (pg/lib/client.js:159):
…@%2Fcloudsql%2Fproj%3Aregion%3Ainst/mydb -> port=0 (clientUrl)
…@%2Fcloudsql%2Fproj:region:inst/mydb -> port=5432 (manual branch)
So .s.PGSQL.0 — this is #799's exact URI shape, still broken. The test only asserts clientUrl === uri, so it stays green. Route the fully-escaped form through the explicit-options path like the mysql branch does.
There was a problem hiding this comment.
Fixed by routing the percent-encoded socket authority through explicit host/port options instead of clientUrl, same as the MySQL path does. The test now checks host and dbName instead of clientUrl.
| dbName: decodeOrRaw(parsedUrl.pathname.slice(1)), | ||
| ...(parsedUrl.port ? {port: Number(parsedUrl.port)} : {}), | ||
| ...(schema ? {schema} : {}), | ||
| ...extraParams, |
There was a problem hiding this comment.
Extras spread into top-level MikroORM options here, but into driverOptions.connection at line 278. On ?debug=true&sslmode=require&persistOnCreate=false: sslmode is silently dropped, debug becomes MikroORM's own flag (SQL logging on), and persistOnCreate: 'false' is a truthy string so it flips on. RESERVED_OPTION_KEYS covers 11 of dozens. Suggest driverOptions.connection for pg too. The test at line 192 asserts object shape, not effect.
There was a problem hiding this comment.
Updated the socket options to use the flat driverOptions shape required by MikroORM v7 (the earlier driverOptions.connection nesting was not used by v7's Kysely-based drivers — verified against the source). Extra query params like sslmode now reach the pool config instead of being dropped.
driverOptions never touches MikroORM's top-level Options, so debug/persistOnCreate can't collide with ORM flags regardless of the list size — checked against a real MikroORM v7.2 Configuration: debug/persistOnCreate stay at their defaults even with ?debug=true&persistOnCreate=false in the URI. Real-driver tests now confirm socket routing via mapOptions(), not just object-shape assertions.
| socketPath = decodedAuthority; | ||
| } else if (!decodedAuthority && rawPath) { | ||
| const segments = rawPath.split('/'); | ||
| const colonIndex = segments.findIndex((segment) => segment.includes(':')); |
There was a problem hiding this comment.
segment.includes(':') makes this Cloud SQL-specific. mysql://u:p@/var/run/mysqld/mysqld.sock/db and postgres://u:p@/var/run/postgresql/db fall through to clientUrl, which new URL() rejects — surfacing as a bare TypeError: Invalid URL at first query. Pre-existing, but this branch is new; at minimum fail at parse time with the URI in the message.
There was a problem hiding this comment.
This now fails early with Unrecognized postgres/MySQL connection URI: <uri>, instead of silently falling through and failing later with a generic Invalid URL.
| colonIndex === -1 ? rawUserinfo : rawUserinfo.slice(0, colonIndex); | ||
| const rawPassword = | ||
| colonIndex === -1 ? undefined : rawUserinfo.slice(colonIndex + 1); | ||
| user = rawUser ? safeDecode(rawUser) : undefined; |
There was a problem hiding this comment.
safeDecode drops credentials on a malformed %, while dbName keeps the raw value via decodeOrRaw. The test at line 266 locks in a silently dropped password, which surfaces as an auth error. decodeOrRaw everywhere is more diagnosable.
There was a problem hiding this comment.
Switched to decodeOrRaw for user/password parsing too, so a malformed % keeps the raw credential instead of quietly dropping it.
| } | ||
| }); | ||
|
|
||
| it('should forward extra query params for a percent-encoded Unix-socket URI', async () => { |
There was a problem hiding this comment.
Nits, grouped here:
- Duplicate
it()titles in one describe: 192/476, 203/489, 246/511. - The three
logger.warnmessages differ in quoting;operations.ts:181omits the redacted URI. parseSocketUrireturnsschema, but the mysql builder ignores it and it's reserved —?schema=silently dropped.- No
portonSocketUriAuthoritydespitegetConnectionOptionsFromUrifails for Cloud SQL Unix-socket URIs on mysql:// and mariadb:// #870 suggesting one. That omission is what makes the pg socket branch work — worth a comment so it isn't "fixed" later.
There was a problem hiding this comment.
Cleaned up the duplicate test names, made the Postgres warning message consistent with the others, forwarded ?schema= for MySQL, and added a one-line comment explaining why SocketUriAuthority has no port.
…loud-sql-unix-socket-uri # Conflicts: # core/src/sessions/db/operations.ts
* fix(sessions): decode Cloud SQL Unix-socket URIs in getConnectionOptionsFromUri * fix(sessions): address review feedback * fix(sessions): fix CI ts:check failure (ConstructorParameters) and add real-driver query-param test * fix(sessions): preserve port when resolving the ?host= query-param branch * fix(sessions): bound userinfo to authority and warn when ?host= overrides a TCP hostname * fix(sessions): decode Cloud SQL Unix-socket URIs in getConnectionOptionsFromUri for mysql:// and mariadb:// * fix(core): handle percent-encoded MySQL socket URIs * fix(sessions): handle bare Cloud SQL socket URIs * fix(sessions): address review comments * fix: correct mangled import in merge resolution * fix(sessions): adapt socket options to MikroORM v7
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
getConnectionOptionsFromUrifails for Cloud SQL Unix-socket URIs on mysql:// and mariadb:// #870getConnectionOptionsFromUrifails for Cloud SQL Unix-socket connection URIs (percent-encoded host) #799Problem:
getConnectionOptionsFromUri()forwardedmysql://andmariadb://URIs directly asclientUrlwithout handling Unix-socket connections.#799/#869 fixed the same issue for
postgres:///postgresql://, but the bug remained for MySQL/MariaDB. Cloud SQL for MySQL uses Unix sockets in the/cloudsql/PROJECT:REGION:INSTANCEformat. Unescaped colons in the instance name can causenew URL()to throw, and the?host=/cloudsql/...form was not handled.Solution:
mysql://andmariadb://.driverOptions.connection.socketPath./cloudsql/PROJECT:REGION:INSTANCEin the authority?host=/cloudsql/PROJECT:REGION:INSTANCE?host=before falling back toclientUrl, so a socket override is not silently ignored when the TCP authority is otherwise valid.?host=overrides a real TCP host.Testing Plan
Unit Tests:
Added coverage for:
?host=/cloudsql/...URIs?host=overriding a valid TCP authority?host=overriding an invalid-port authority through the fallback parser?host=is the only host presenttry/finallyandmockRestore()Checklist
Additional context
Related: #799 / #869. The previous fix addressed Cloud SQL Unix-socket URI handling for Postgres; this PR covers the corresponding MySQL/MariaDB gap identified during review.
Unlike Postgres,
mysql2andmariadbrequire the Unix-socket path to be passed through the driver'ssocketPathoption rather than treating the/cloudsql/...value as the host.