Files
supabase/apps/studio/components/interfaces/ProjectHome/ProjectConnectionPopover.tsx
Alaister Young fc5e03f9e3 [FE-4019] fix(studio): direct-only connection strings with SSL params for Multigres (#48433)
Multigres (high-availability) projects only accept TLS connections with
direct SSL negotiation, and they don't support connection pooling at all
— neither Supavisor nor the dedicated PgBouncer pooler exists for them.
Studio previously showed pooler connection strings that would fail with
"server closed the connection unexpectedly". This PR makes every
connection-string surface direct-only for HA projects and appends
`?sslmode=require&sslnegotiation=direct` to the examples. Non-HA
projects are unchanged.

Addresses
[FE-4019](https://linear.app/supabase/issue/FE-4019/append-ssl-params-to-multigres-connection-string-examples-in-ui)

**Changed:**

- `buildConnectionStringPooler` gets an HA branch that collapses every
slot in the bag to the direct connection string with the SSL params
appended (mirroring the existing CLI branch, which also has no pooler) —
dedicated slots come back `undefined` and
`ipv4SupportedForDedicatedPooler` is forced off. Since HA never reaches
the pooler layout anymore, the earlier per-URI SSL-append logic on
pooler strings is removed
- `useConnectState` coerces `connectionMethod` to `direct` and
`useSharedPooler` to `false` for HA projects. The Connect sheet restores
the last-used method from localStorage shared across projects, so a
"Transaction pooler" selection made on a regular project could otherwise
leak pooler-flavored notices, badges, and telemetry into an HA project
- Prisma and Drizzle ORM tabs get an HA branch:
`DATABASE_URL`/`DIRECT_URL` both use the direct connection, no
`?pgbouncer=true` appended, with a comment explaining Multigres doesn't
support pooling. The 5-arm nested ternaries in both files are flattened
into `getEnvCode` helpers that switch on a shared
`resolveOrmConnectionScenario` helper (`OrmConnection.utils.ts`), so the
deployment-mode/HA branching lives in one tested place and each file
keeps only its own formatting
- The PgBouncer and Supavisor config queries are disabled (`enabled:
!isHighAvailability`) in the Connect sheet — those endpoints serve
pooler config that doesn't exist on Multigres
- `parseConnectionParams` keeps the URI's query string in a new `search`
field so formats rebuilt from parsed parts can carry it
- psql switches from the `-h/-p/-d/-U` flag form to the quoted-URI form
when query params are present (flags can't express them; psql still
prompts for the password)
- JDBC appends the params using pgJDBC's casing (`sslNegotiation`,
supported since 42.7.4)
- Prisma's `?pgbouncer=true` appends are query-aware (join with `&` when
the URI already has a query string) via a new
`appendConnectionStringParams` helper
- The project home "Direct connection string" copy item also appends the
params for HA projects

**Added:**

- Unit tests for the HA collapse behavior (all slots direct, dedicated
config and IPv4 add-on ignored, no SSL params on non-HA output), the
`useConnectState` coercion, the psql/JDBC builders (moved from
`content.tsx` into `ConnectionString.utils.ts` so they're testable), and
`resolveOrmConnectionScenario` (every deployment-mode/HA/pooler branch)

**Known gaps (left out deliberately):**

- The grid ExportDialog psql/pg_dump commands, the .NET
`appsettings.json` (Npgsql only supports direct negotiation from v9 via
`SSL Negotiation=Direct`), and the SQLAlchemy keyword-style `.env` are
flag/keyword forms that can't carry the URI params — these would still
fail against Multigres and need a follow-up
- Settings > Database's Connection Pooling section and the pooler logs
page have no HA gating yet — they'd still render pooler config UI for a
Multigres project and should be hidden in a follow-up

## To test

On a **Multigres (HA) project** (staging only supports `us-east-1` for
Multigres):

- Open the Connect sheet → Direct tab: there's no connection-method
picker, and the connection string is the direct one ending with
`?sslmode=require&sslnegotiation=direct` for the URI, PHP, and psql
(quoted-URI form) types; JDBC includes
`&sslmode=require&sslNegotiation=direct`
- ORM tab → Prisma: both `DATABASE_URL` and `DIRECT_URL` are the direct
connection string with the SSL params, no `pgbouncer=true`, with a
"Multigres does not support connection pooling" comment. Drizzle
likewise shows the direct string only
- Framework tabs (e.g. Next.js): every `DATABASE_URL` carries the direct
string with the params exactly once
- Open the network tab: no requests to `/config/pgbouncer` or
`/config/supavisor` while using the Connect sheet
- To check the localStorage coercion: on a **regular** project pick
"Transaction pooler" in the Connect sheet, then open the sheet on the
Multigres project — no pooler badge/notices, string is still direct
- Copy the URI, substitute your password, and `psql "<string>"` — it
should connect
- Project home → Copy dropdown → "Direct connection string" includes the
params

On a **regular (non-Multigres) project** — confirm nothing changed:

- Connect sheet: direct/session/transaction strings for all connection
types (URI, psql flag form, JDBC, PHP) look the same as before, no SSL
params appended
- Prisma/Drizzle tabs render identically (`?pgbouncer=true` still
appended with `?`, dedicated-pooler alternatives still shown per IPv4
add-on state)
- Project home copy dropdown is unchanged


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Enhanced connection-string generation for high-availability projects,
including required SSL settings for direct connections.
* Preserved URI query parameters in PostgreSQL, `psql`, JDBC, and
generated environment configurations.
* Improved ORM environment templates with clearer handling for pooler
and high-availability connection scenarios.

* **Bug Fixes**
* High-availability projects now consistently use direct connections
instead of pooler options.
* Connection strings and generated templates update correctly when
availability settings change.

* **Tests**
* Expanded coverage for query parameters, high-availability behavior,
and connection scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-31 14:34:31 +08:00

257 lines
8.6 KiB
TypeScript

import { PermissionAction } from '@supabase/shared-types/out/constants'
import { Check, ChevronDown, Copy, Database, KeyRound, Link2, Terminal } from 'lucide-react'
import { parseAsBoolean, useQueryState } from 'nuqs'
import { useEffect, useMemo, useState } from 'react'
import {
Button,
cn,
copyToClipboard,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { getConnectionStrings } from '@/components/interfaces/Connect/DatabaseSettings.utils'
import { appendHighAvailabilitySslParams } from '@/components/interfaces/ConnectSheet/DatabaseSettings.utils'
import { useAPIKeys } from '@/data/api-keys/api-keys-query'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useReadReplicasQuery } from '@/data/read-replicas/replicas-query'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
import { useIsHighAvailability } from '@/hooks/misc/useSelectedProject'
import { IS_PLATFORM } from '@/lib/constants'
import { pluckObjectFields } from '@/lib/helpers'
const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user'] as const
const EMPTY_CONNECTION_INFO = {
db_user: '',
db_host: '',
db_port: '',
db_name: '',
}
interface ProjectConnectionPopoverProps {
projectRef?: string
}
export const ProjectConnectionPopover = ({ projectRef }: ProjectConnectionPopoverProps) => {
const [open, setOpen] = useState(false)
const [copiedItem, setCopiedItem] = useState<string | null>(null)
const [, setShowConnect] = useQueryState('showConnect', parseAsBoolean.withDefault(false))
const { isLoading: isLoadingPermissions, can: canReadAPIKeys } = useAsyncCheckPermissions(
PermissionAction.READ,
'service_api_keys'
)
const { data: projectUrl, isPending: isLoadingApiUrl } = useProjectApiUrl({ projectRef })
const { data, isLoading: isLoadingKeys } = useAPIKeys(
{ projectRef },
{ enabled: open && canReadAPIKeys }
)
const { publishableKey } = data ?? {}
const { data: databases, isLoading: isLoadingDatabases } = useReadReplicasQuery(
{ projectRef },
{ enabled: IS_PLATFORM && open && !!projectRef }
)
const primaryDatabase = databases?.find((db) => db.identifier === projectRef)
const isHighAvailability = useIsHighAvailability()
const directConnectionString = useMemo(() => {
if (
!primaryDatabase?.db_host ||
!primaryDatabase?.db_name ||
!primaryDatabase?.db_user ||
!primaryDatabase?.db_port
) {
return ''
}
const connectionInfo = pluckObjectFields(primaryDatabase, [...DB_FIELDS])
const uri = getConnectionStrings({
connectionInfo: { ...EMPTY_CONNECTION_INFO, ...connectionInfo },
metadata: { projectRef },
}).direct.uri
return isHighAvailability ? appendHighAvailabilitySslParams(uri) : uri
}, [primaryDatabase, projectRef, isHighAvailability])
const cliCommands = useMemo(
() =>
[
'supabase login',
'supabase init',
`supabase link --project-ref ${projectRef ?? 'PROJECT_REF_UNAVAILABLE'}`,
].join('\n'),
[projectRef]
)
// Self-hosted projects may not have a publishable key configured. Rather
// than show a permanently-disabled "Publishable key unavailable" row, hide
// the entry entirely on !IS_PLATFORM when the key isn't available. Platform
// behavior is unchanged.
const showPublishableKey = IS_PLATFORM || !!publishableKey?.api_key
const menuItems = useMemo(
() => [
{
label: 'Project URL',
value: projectUrl ?? '',
displayValue: isLoadingApiUrl
? 'Loading project URL...'
: (projectUrl ?? 'Project URL unavailable'),
disabled: isLoadingApiUrl || !projectUrl,
icon: Link2,
},
...(showPublishableKey
? [
{
label: 'Publishable key',
value: publishableKey?.api_key ?? '',
displayValue:
isLoadingPermissions || isLoadingKeys
? 'Loading publishable key...'
: canReadAPIKeys
? (publishableKey?.api_key ?? 'Publishable key unavailable')
: "You don't have permission to view API keys.",
disabled:
isLoadingPermissions ||
isLoadingKeys ||
!canReadAPIKeys ||
!publishableKey?.api_key,
icon: KeyRound,
},
]
: []),
...(IS_PLATFORM
? [
{
label: 'Direct connection string',
value: directConnectionString,
displayValue: isLoadingDatabases
? 'Loading connection string...'
: directConnectionString || 'Connection string unavailable',
disabled: isLoadingDatabases || !directConnectionString,
icon: Database,
},
{
label: 'CLI setup commands',
value: cliCommands,
displayValue: cliCommands.replace(/\n/g, ' - '),
disabled: !projectRef,
icon: Terminal,
},
]
: []),
],
[
canReadAPIKeys,
cliCommands,
directConnectionString,
isLoadingApiUrl,
isLoadingDatabases,
isLoadingKeys,
isLoadingPermissions,
projectRef,
projectUrl,
publishableKey?.api_key,
showPublishableKey,
]
)
useEffect(() => {
if (!open) {
setCopiedItem(null)
}
}, [open])
return (
<div className="mt-3 flex items-center gap-3">
{isLoadingApiUrl ? (
<ShimmeringLoader className="w-80" />
) : (
<span className="min-w-0 max-w-[400px] truncate text-left text-foreground-light">
{projectUrl ?? 'Project URL unavailable'}
</span>
)}
{!isLoadingApiUrl && (
<DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild>
<Button
size="tiny"
variant="default"
iconRight={
<ChevronDown
size={14}
className={cn('transition-transform', open && 'rotate-180')}
/>
}
>
Copy <span className="sr-only">project URL and API keys</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="center" className="w-80 p-1">
{menuItems.map((item) => {
const Icon = item.icon
return (
<DropdownMenuItem
key={item.label}
className="group relative items-center gap-3 pr-10"
disabled={item.disabled}
onSelect={(event) => {
event.preventDefault()
if (item.disabled) return
copyToClipboard(item.value)
setCopiedItem(item.label)
}}
>
<Icon size={14} className="mt-0.5 shrink-0 text-foreground-light" />
<div className="min-w-0 flex-1">
<div className="text-sm text-foreground">
{copiedItem !== item.label ? <span className="sr-only">Copy</span> : null}
{item.label}
{copiedItem === item.label ? (
<span className="sr-only">copied to your clipboard</span>
) : null}
</div>
<div className="truncate text-sm text-foreground-lighter">
{item.displayValue}
</div>
</div>
<div
className={cn(
'absolute right-2 top-1/2 -translate-y-1/2 text-foreground-lighter opacity-0 transition-opacity group-hover:opacity-100',
copiedItem === item.label && 'opacity-100 text-brand'
)}
>
{copiedItem === item.label ? <Check size={14} /> : <Copy size={14} />}
</div>
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
<div className="p-1">
<Button
variant="default"
size="tiny"
className="w-full"
onClick={() => {
setOpen(false)
setShowConnect(true)
}}
>
Get Connected
</Button>
</div>
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
)
}