Skip to content

fix(sessions): handle Cloud SQL Unix socket connections - #871

Merged
kalenkevich merged 14 commits into
google:mainfrom
AnupamKumar-1:fix/mysql-mariadb-cloud-sql-unix-socket-uri
Sep 10, 2026
Merged

kalenkevich merged 14 commits into
google:mainfrom
AnupamKumar-1:fix/mysql-mariadb-cloud-sql-unix-socket-uri

Conversation

@AnupamKumar-1

@AnupamKumar-1 AnupamKumar-1 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

getConnectionOptionsFromUri() forwarded mysql:// and mariadb:// URIs directly as clientUrl without 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:INSTANCE format. Unescaped colons in the instance name can cause new URL() to throw, and the ?host=/cloudsql/... form was not handled.

Solution:

  • Added Unix-socket URI parsing for mysql:// and mariadb://.
  • Passes the socket path through driverOptions.connection.socketPath.
  • Supports both socket forms:
    • /cloudsql/PROJECT:REGION:INSTANCE in the authority
    • ?host=/cloudsql/PROJECT:REGION:INSTANCE
  • Preserves existing behavior for normal TCP and fully percent-encoded socket URIs.
  • Checks ?host= before falling back to clientUrl, so a socket override is not silently ignored when the TCP authority is otherwise valid.
  • Logs a warning when ?host= overrides a real TCP host.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally (25/25).

Added coverage for:

  • MySQL and MariaDB Unix-socket URIs with unescaped colons
  • MySQL and MariaDB ?host=/cloudsql/... URIs
  • Normal TCP and fully percent-encoded socket URIs remaining unchanged
  • ?host= overriding a valid TCP authority
  • ?host= overriding an invalid-port authority through the fallback parser
  • No warning when ?host= is the only host present
  • Logger spy cleanup with try/finally and mockRestore()

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

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, mysql2 and mariadb require the Unix-socket path to be passed through the driver's socketPath option rather than treating the /cloudsql/... value as the host.

@AmaadMartin AmaadMartin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/src/sessions/db/operations.ts Outdated
password: parsedUrl.password
? decodeURIComponent(parsedUrl.password)
: undefined,
dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/src/sessions/db/operations.ts Outdated
: undefined,
dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined,
driverOptions: {
connection: {socketPath: queryHost},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@AnupamKumar-1

Copy link
Copy Markdown
Contributor Author

Folded the PostgreSQL changes from #869 into this PR and merged the latest upstream/main. All 50 operations tests are passing.

@AnupamKumar-1 AnupamKumar-1 changed the title fix(sessions): decode Cloud SQL Unix-socket URIs in getConnectionOptionsFromUri for mysql:// and mariadb:// fix(sessions): handle Cloud SQL Unix socket connections Sep 9, 2026
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 () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread core/src/sessions/db/operations.ts Outdated
dbName: decodeOrRaw(parsedUrl.pathname.slice(1)),
...(parsedUrl.port ? {port: Number(parsedUrl.port)} : {}),
...(schema ? {schema} : {}),
...extraParams,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@AnupamKumar-1 AnupamKumar-1 Sep 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(':'));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now fails early with Unrecognized postgres/MySQL connection URI: <uri>, instead of silently falling through and failing later with a generic Invalid URL.

Comment thread core/src/sessions/db/operations.ts Outdated
colonIndex === -1 ? rawUserinfo : rawUserinfo.slice(0, colonIndex);
const rawPassword =
colonIndex === -1 ? undefined : rawUserinfo.slice(colonIndex + 1);
user = rawUser ? safeDecode(rawUser) : undefined;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 () => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nits, grouped here:

  • Duplicate it() titles in one describe: 192/476, 203/489, 246/511.
  • The three logger.warn messages differ in quoting; operations.ts:181 omits the redacted URI.
  • parseSocketUri returns schema, but the mysql builder ignores it and it's reserved — ?schema= silently dropped.
  • No port on SocketUriAuthority despite getConnectionOptionsFromUri fails 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@kalenkevich
kalenkevich merged commit 3b59a2c into google:main Sep 10, 2026
13 checks passed
@kalenkevich kalenkevich mentioned this pull request Sep 10, 2026
@AnupamKumar-1
AnupamKumar-1 deleted the fix/mysql-mariadb-cloud-sql-unix-socket-uri branch September 20, 2026 18:30
prasanna8585 pushed a commit to prasanna8585/adk-js that referenced this pull request Nov 10, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants