Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

[MUL-1417] feat(studio): show SSL enforcement as always on for HA projects (#49524)

Alaister Young3811e75140a3
diff --git a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx
new file mode 100644
index 00000000000..0d701f78f69
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.test.tsx
@@ -0,0 +1,172 @@
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import type { components, paths } from 'api-types'
+import { HttpResponse } from 'msw'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { SSLConfiguration } from './SSLConfiguration'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+type ProjectSettingsResponse = components['schemas']['ProjectSettingsResponse']
+type SslEnforcementResponse = components['schemas']['SslEnforcementResponse']
+type JitAccessConfigResponse =
+ paths['/v1/projects/{ref}/jit-access']['get']['responses'][200]['content']['application/json']
+
+const { mockUseAsyncCheckPermissions, mockUseHighAvailability, mockUseSelectedProjectQuery } =
+ vi.hoisted(() => ({
+ mockUseAsyncCheckPermissions: vi.fn(),
+ mockUseHighAvailability: vi.fn(),
+ mockUseSelectedProjectQuery: vi.fn(),
+ }))
+
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: mockUseAsyncCheckPermissions,
+}))
+
+vi.mock('@/hooks/misc/useHighAvailability', () => ({
+ useHighAvailability: mockUseHighAvailability,
+}))
+
+vi.mock('@/hooks/misc/useSelectedProject', () => ({
+ useSelectedProjectQuery: mockUseSelectedProjectQuery,
+}))
+
+const HA_TOOLTIP = 'SSL is always enforced on High Availability projects'
+
+function mockProjectSettings() {
+ addAPIMock({
+ method: 'get',
+ path: '/platform/projects/:ref/settings',
+ response: () =>
+ HttpResponse.json<ProjectSettingsResponse>({
+ app_config: {
+ db_schema: 'public',
+ endpoint: 'default.supabase.co',
+ storage_endpoint: 'storage.default.supabase.co',
+ },
+ cloud_provider: 'AWS',
+ db_dns_name: 'default.supabase.co',
+ db_host: 'default.supabase.co',
+ db_ip_addr_config: 'ipv4',
+ db_name: 'postgres',
+ db_port: 5432,
+ db_user: 'postgres',
+ inserted_at: '2025-02-16T22:24:42.115195',
+ name: 'default',
+ ref: 'default',
+ region: 'us-east-1',
+ ssl_enforced: true,
+ status: 'ACTIVE_HEALTHY',
+ }),
+ })
+}
+
+function mockJitDbAccess() {
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/jit-access',
+ response: () =>
+ HttpResponse.json<JitAccessConfigResponse>({ state: 'disabled', appliedSuccessfully: true }),
+ })
+}
+
+/** Registers the SSL enforcement GET and returns a counter of how often it was hit. */
+function mockSSLEnforcement(config: SslEnforcementResponse) {
+ const requests = { count: 0 }
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/ssl-enforcement',
+ response: () => {
+ requests.count += 1
+ return HttpResponse.json<SslEnforcementResponse>(config)
+ },
+ })
+ return requests
+}
+
+describe('SSLConfiguration', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+
+ mockUseSelectedProjectQuery.mockReturnValue({ data: { id: 1, ref: 'default' } })
+ mockUseAsyncCheckPermissions.mockReturnValue({ can: true })
+ mockProjectSettings()
+ mockJitDbAccess()
+ })
+
+ it('shows SSL enforcement as always on for High Availability projects', async () => {
+ mockUseHighAvailability.mockReturnValue({ isHighAvailability: true, isPending: false })
+ const sslEnforcementRequests = mockSSLEnforcement({
+ appliedSuccessfully: true,
+ currentConfig: { database: false },
+ })
+
+ customRender(<SSLConfiguration />)
+
+ const sslSwitch = await screen.findByRole('switch')
+ expect(sslSwitch).toBeChecked()
+ expect(sslSwitch).toBeDisabled()
+ // Nothing is loading for HA projects, so there is no announcement to make
+ expect(screen.getByRole('status')).toBeEmptyDOMElement()
+
+ // The tooltip trigger is the wrapper around the (disabled) switch
+ await userEvent.hover(sslSwitch.parentElement!)
+ expect((await screen.findAllByText(HA_TOOLTIP, {}, { timeout: 2000 })).length).toBeGreaterThan(
+ 0
+ )
+
+ expect(sslEnforcementRequests.count).toBe(0)
+ })
+
+ it('does not open the confirm dialog around a disabled switch on High Availability projects', async () => {
+ mockUseHighAvailability.mockReturnValue({ isHighAvailability: true, isPending: false })
+ mockSSLEnforcement({ appliedSuccessfully: true, currentConfig: { database: false } })
+
+ customRender(<SSLConfiguration />)
+
+ const sslSwitch = await screen.findByRole('switch')
+ // Clicking the disabled switch and the row wrapper around it must not open the dialog
+ await userEvent.click(sslSwitch)
+ await userEvent.click(sslSwitch.parentElement!.parentElement!)
+
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+
+ it('reflects the fetched SSL enforcement config for other projects', async () => {
+ mockUseHighAvailability.mockReturnValue({ isHighAvailability: false, isPending: false })
+ const sslEnforcementRequests = mockSSLEnforcement({
+ appliedSuccessfully: true,
+ currentConfig: { database: false },
+ })
+
+ customRender(<SSLConfiguration />)
+
+ const sslSwitch = await screen.findByRole('switch')
+ expect(sslSwitch).not.toBeChecked()
+ expect(sslSwitch).toBeEnabled()
+ expect(screen.getByRole('status')).toBeEmptyDOMElement()
+ expect(sslEnforcementRequests.count).toBe(1)
+ })
+
+ it('opens the confirm dialog from the switch and leaves it unchanged on cancel', async () => {
+ mockUseHighAvailability.mockReturnValue({ isHighAvailability: false, isPending: false })
+ mockSSLEnforcement({ appliedSuccessfully: true, currentConfig: { database: false } })
+
+ customRender(<SSLConfiguration />)
+
+ const sslSwitch = await screen.findByRole('switch')
+ await userEvent.click(sslSwitch)
+
+ const dialog = await screen.findByRole('alertdialog')
+ expect(dialog).toHaveTextContent('Updating SSL enforcement involves a brief downtime')
+ expect(screen.getByRole('button', { name: 'Enable SSL' })).toBeInTheDocument()
+ // Controlled switch must not flip while the dialog is open
+ expect(sslSwitch).not.toBeChecked()
+
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ expect(sslSwitch).not.toBeChecked()
+ })
+})
diff --git a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
index 0b6222cf43a..7790f871e3d 100644
--- a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
@@ -2,7 +2,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import { template } from 'lodash'
import { Download, Loader2 } from 'lucide-react'
-import { useMemo } from 'react'
+import { useMemo, useState } from 'react'
import { toast } from 'sonner'
import { Button, Card, CardContent, Switch, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
@@ -26,21 +26,30 @@ import { useSSLEnforcementQuery } from '@/data/ssl-enforcement/ssl-enforcement-q
import { useSSLEnforcementUpdateMutation } from '@/data/ssl-enforcement/ssl-enforcement-update-mutation'
import { useCustomContent } from '@/hooks/custom-content/useCustomContent'
import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
+import { useHighAvailability } from '@/hooks/misc/useHighAvailability'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
export const SSLConfiguration = () => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
+ const [isConfirmDialogOpen, setIsConfirmDialogOpen] = useState(false)
const { data: settings } = useProjectSettingsV2Query({ projectRef: ref })
+
+ // High Availability projects always enforce SSL and the API rejects any
+ // attempt to read or change the setting, so skip the query for them and
+ // show the setting as always on.
+ const { isHighAvailability, isPending: isHighAvailabilityPending } = useHighAvailability()
+ const canLoadSSLEnforcement = !isHighAvailability && !isHighAvailabilityPending
const {
data: sslEnforcementConfiguration,
- isPending: isLoading,
- isSuccess,
- } = useSSLEnforcementQuery({
- projectRef: ref,
- })
+ isPending: isSSLEnforcementPending,
+ isSuccess: isSSLEnforcementSuccess,
+ } = useSSLEnforcementQuery({ projectRef: ref }, { enabled: canLoadSSLEnforcement })
+
+ const isLoading = isHighAvailabilityPending || (!isHighAvailability && isSSLEnforcementPending)
+ const isSuccess = isHighAvailability || isSSLEnforcementSuccess
const { data: jitDbAccessConfiguration } = useJitDbAccessQuery({ projectRef: ref })
const { mutateAsync: updateSSLEnforcement, isPending: isSubmitting } =
useSSLEnforcementUpdateMutation({
@@ -67,9 +76,10 @@ export const SSLConfiguration = () => {
// reflected here too, instead of relying on a mirrored local state that
// would only resync on the initial load.
const isEnforced =
- isSuccess &&
- sslEnforcementConfiguration.appliedSuccessfully &&
- sslEnforcementConfiguration.currentConfig.database
+ isHighAvailability ||
+ (isSSLEnforcementSuccess &&
+ sslEnforcementConfiguration.appliedSuccessfully &&
+ sslEnforcementConfiguration.currentConfig.database)
const hasAccessToSSLEnforcement = !(
sslEnforcementConfiguration !== undefined &&
@@ -85,12 +95,15 @@ export const SSLConfiguration = () => {
const isSwitchDisabled =
isLoading ||
isSubmitting ||
+ isHighAvailability ||
!canUpdateSSLEnforcement ||
!hasAccessToSSLEnforcement ||
isTemporaryAccessEnabled
let switchTooltipMessage: string | undefined
- if (!canUpdateSSLEnforcement) {
+ if (isHighAvailability) {
+ switchTooltipMessage = 'SSL is always enforced on High Availability projects'
+ } else if (!canUpdateSSLEnforcement) {
switchTooltipMessage =
'You need additional permissions to update SSL enforcement for your project'
} else if (!hasAccessToSSLEnforcement) {
@@ -100,6 +113,13 @@ export const SSLConfiguration = () => {
'Temporary access must first be disabled before SSL enforcement can be disabled'
}
+ let loadingAnnouncement = ''
+ if (isSubmitting) {
+ loadingAnnouncement = 'Updating SSL enforcement'
+ } else if (isLoading) {
+ loadingAnnouncement = 'Loading SSL configuration'
+ }
+
const env = process.env.NEXT_PUBLIC_ENVIRONMENT === 'prod' ? 'prod' : 'staging'
const hasSSLCertificate =
settings?.inserted_at !== undefined && new Date(settings.inserted_at) >= new Date('2021-04-30')
@@ -131,34 +151,53 @@ export const SSLConfiguration = () => {
label="Enforce SSL on incoming connections"
description="Reject non-SSL connections to your database"
>
+ <div className="flex items-center justify-end mt-2.5 space-x-2">
+ {(isLoading || isSubmitting) && (
+ <Loader2
+ aria-hidden="true"
+ className="animate-spin motion-reduce:animate-none"
+ strokeWidth={1.5}
+ size={16}
+ />
+ )}
+ {isSuccess && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* [Joshen] Added div as tooltip is messing with data state property of toggle */}
+ {/* A disabled switch can't take focus, so the wrapper becomes the focus
+ target to keep the tooltip reachable by keyboard */}
+ <div tabIndex={isSwitchDisabled ? 0 : undefined}>
+ {/* The dialog is opened from the switch itself rather than a wrapping
+ trigger, so a disabled switch can never open it. */}
+ <Switch
+ size="large"
+ checked={isEnforced}
+ disabled={isSwitchDisabled}
+ onCheckedChange={() => setIsConfirmDialogOpen(true)}
+ />
+ </div>
+ </TooltipTrigger>
+ {switchTooltipMessage && (
+ <TooltipContent side="bottom" className="w-64 text-center">
+ {switchTooltipMessage}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ )}
+ {/* Kept mounted so screen readers announce loading state changes */}
+ <span className="sr-only" role="status">
+ {loadingAnnouncement}
+ </span>
+ </div>
<SSLEnforcementConfirmDialog
+ open={isConfirmDialogOpen}
+ onOpenChange={setIsConfirmDialogOpen}
isTargetEnforced={!isEnforced}
isSubmitting={isSubmitting}
onConfirm={toggleSSLEnforcement}
- >
- <div className="flex items-center justify-end mt-2.5 space-x-2">
- {(isLoading || isSubmitting) && (
- <Loader2 className="animate-spin" strokeWidth={1.5} size={16} />
- )}
- {isSuccess && (
- <Tooltip>
- <TooltipTrigger asChild>
- {/* [Joshen] Added div as tooltip is messing with data state property of toggle */}
- <div>
- <Switch size="large" checked={isEnforced} disabled={isSwitchDisabled} />
- </div>
- </TooltipTrigger>
- {switchTooltipMessage && (
- <TooltipContent side="bottom" className="w-64 text-center">
- {switchTooltipMessage}
- </TooltipContent>
- )}
- </Tooltip>
- )}
- </div>
- </SSLEnforcementConfirmDialog>
+ />
</FormLayout>
- {isSuccess && !sslEnforcementConfiguration?.appliedSuccessfully && (
+ {isSSLEnforcementSuccess && !sslEnforcementConfiguration.appliedSuccessfully && (
<Admonition
type="warning"
layout="horizontal"
diff --git a/apps/studio/components/interfaces/Settings/Database/SSLEnforcementConfirmDialog.tsx b/apps/studio/components/interfaces/Settings/Database/SSLEnforcementConfirmDialog.tsx
index d0aabb173d9..9a716cfec8c 100644
--- a/apps/studio/components/interfaces/Settings/Database/SSLEnforcementConfirmDialog.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/SSLEnforcementConfirmDialog.tsx
@@ -15,17 +15,26 @@ interface SSLEnforcementConfirmDialogProps {
isTargetEnforced: boolean
isSubmitting: boolean
onConfirm: () => Promise<void>
+ /**
+ * Controlled mode for callers whose control can't act as the dialog trigger
+ * (e.g. a switch, where a disabled control must never open the dialog).
+ * Omit both, and pass `children`, to render the children as the trigger.
+ */
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
}
export const SSLEnforcementConfirmDialog = ({
isTargetEnforced,
isSubmitting,
onConfirm,
+ open,
+ onOpenChange,
children,
}: PropsWithChildren<SSLEnforcementConfirmDialogProps>) => {
return (
- <AlertDialog>
- <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ {children !== undefined && <AlertDialogTrigger asChild>{children}</AlertDialogTrigger>}
<AlertDialogContent size="medium">
<AlertDialogHeader>
<AlertDialogTitle>Updating SSL enforcement involves a brief downtime</AlertDialogTitle>