Skip to content

fix(sessions): decode Cloud SQL Unix-socket URIs in getConnectionOptionsFromUri - #869

Closed
AnupamKumar-1 wants to merge 5 commits into
google:mainfrom
AnupamKumar-1:fix/cloud-sql-unix-socket-uri
Closed

AnupamKumar-1 wants to merge 5 commits into
google:mainfrom
AnupamKumar-1:fix/cloud-sql-unix-socket-uri

Conversation

@AnupamKumar-1

Copy link
Copy Markdown
Contributor

Recreated from #802 after accidentally deleting my fork. This contains the same changes and review fixes from the original PR.

Link to Issue or Description of Change

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

@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.

I reviewed this together with #871, since they change the same function and share a parser. The core approach is right — only falling back to a manual parse for URIs new URL() genuinely cannot represent, and leaving everything else on clientUrl, is the conservative call and the doc comment explaining why is the best thing in the diff. Splitting userinfo on the last @ is also correct, and I checked it handles the [email protected] IAM-user case your test covers.

Two things to fix, and one coordination problem.

The main one: parsePostgresSocketUri calls decodeURIComponent on four different fields with no guard, so a malformed percent-escape escapes getConnectionOptionsFromUri as a raw URIError: URI malformed rather than your Unsupported database URI error. I ran your parser verbatim — four of five malformed probes throw. #871 already fixes exactly this: its parseSocketUri wraps the whole body in try/catch with the comment "Malformed percent-encoding falls back to null instead of throwing." Same author, same parser, and only one branch has the guard — worth landing the guarded version in both.

The coordination problem: I test-merged this against #871 and they conflict in 7 hunks across both files. This PR rewrites the whole if/else chain into early returns while #871 edits the mysql/mariadb arms of that same chain in place, and the two hand-rolled parsers are close to character-identical apart from host vs socketPath and schema. Whichever lands first forces a non-trivial rebase on the other, and the likely outcome is two near-duplicate parsers in one file. Stacking #871 on this branch, or folding them together, would avoid both.

No credential-leak risk in any of this, for what it's worth: URIError's message is the literal string "URI malformed" and carries none of the URI.

if (queryHost?.startsWith('/')) {
host = queryHost;
} else {
const decodedAuthority = decodeURIComponent(rawAuthority);

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. This decode is unguarded, and so are the three below it, so a malformed percent-escape leaves this function as a URIError instead of your intended error.

    const decodedAuthority = decodeURIComponent(rawAuthority);

I transcribed parsePostgresSocketUri verbatim and ran it:

postgresql://u:p@%ZZcloudsql:region:inst/db      -> UNCAUGHT URIError: URI malformed
postgresql://u:%ZZ@%2Fcloudsql%2Fa:b:c/db        -> UNCAUGHT URIError: URI malformed
postgresql://%ZZ:p@%2Fcloudsql%2Fa:b:c/db        -> UNCAUGHT URIError: URI malformed
postgresql://u:p@%2Fcloudsql%2Fa:b:c/db%ZZ       -> UNCAUGHT URIError: URI malformed
postgresql://user:pass@%2Fcloudsql%2Fmy-project:us-central1:my-instance/mydb  -> parses fine

All four reach the manual parser because new URL() rejects them first, so this is the only thing standing between a typo'd URI and an unhandled exception. Before this PR the same inputs fell through to clientUrl and failed inside the driver with a connection error.

Your own #871 solves this the way I'd suggest — wrap the body and return null:

  try {
    // ... existing body, unchanged ...
  } catch {
    return null;
  }

Returning null puts these URIs back on the clientUrl path they took before this PR, which is the pre-existing behaviour rather than a new one, so nothing else has to change.

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, same root cause on the other branch — this one fires even when new URL() succeeds.

        dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined,
postgresql://u:p@host/db%ZZ?host=/cloudsql/p:r:i  -> UNCAUGHT URIError
postgresql://%ZZ:p@host/db?host=/cloudsql/p:r:i   -> UNCAUGHT URIError

new URL() accepts both — it does not validate percent-escapes — so the manual-parser guard won't cover this even once you add it. The username and password decodes just above have the same exposure. A small helper used by both branches would cover all of them at once:

function safeDecode(value: string): string | undefined {
  try {
    return decodeURIComponent(value);
  } catch {
    return undefined;
  }
}

I have not checked what MikroORM does when handed a dbName of undefined versus a percent-literal string, so decide whether the fallback should be undefined or the raw undecoded value — the raw value is probably friendlier here, since a database genuinely named db%ZZ is likelier than the user wanting the connection silently dropped.

: undefined,
dbName: decodeURIComponent(parsedUrl.pathname.slice(1)) || undefined,
...(parsedUrl.port ? {port: Number(parsedUrl.port)} : {}),
...(schema ? {schema} : {}),

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 — this branch quietly drops every query parameter it doesn't name.

        ...(schema ? {schema} : {}),

You forward schema and port explicitly, but the returned options carry no clientUrl, so anything else in the query string is gone. I confirmed the parameters survive parsing and then simply aren't read:

postgresql://u:p@localhost:5432/db?host=/cloudsql/p:r:i&sslmode=require&connect_timeout=10
  searchParams present: host, sslmode, connect_timeout
  forwarded:            host only

Before this PR all of it rode along on clientUrl. sslmode is arguably moot over a Unix socket, but connect_timeout, application_name and options are not. Worth either forwarding the remaining parameters or saying in the doc comment that the socket path deliberately supports only schema and port, so the next person doesn't treat it as an oversight.

@AnupamKumar-1

Copy link
Copy Markdown
Contributor Author

Closing in favor of #871 — folded this branch’s PostgreSQL Unix-socket handling in there so it doesn’t duplicate a near-identical parser. #871 now closes both #870 and #799.

@AnupamKumar-1
AnupamKumar-1 deleted the fix/cloud-sql-unix-socket-uri branch September 9, 2026 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

getConnectionOptionsFromUri fails for Cloud SQL Unix-socket connection URIs (percent-encoded host)

2 participants