Skip to content

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

feat(studio): add multiple network restrictions at once (#52035)

Drew McLellanfdf03de35f5c
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx
new file mode 100644
index 00000000000..d24c621563e
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.test.tsx
@@ -0,0 +1,257 @@
+import { QueryClient } from '@tanstack/react-query'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { apiV1Components as components } from 'api-types'
+import { mockAnimationsApi } from 'jsdom-testing-mocks'
+import { HttpResponse } from 'msw'
+import { toast } from 'sonner'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { AddRestrictionModal } from './AddRestrictionModal'
+import { networkRestrictionKeys } from '@/data/network-restrictions/keys'
+import { customRender } from '@/tests/lib/custom-render'
+import { addAPIMock } from '@/tests/lib/msw'
+
+vi.mock('sonner', () => ({
+ toast: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }),
+}))
+
+mockAnimationsApi()
+
+type NetworkRestrictionsResponse = components['schemas']['NetworkRestrictionsResponse_Output']
+
+type ApplyRequest = { ref: string | undefined; body: unknown }
+
+const mockExistingRestrictions = (dbAllowedCidrs: string[]) => {
+ addAPIMock({
+ method: 'get',
+ path: '/v1/projects/:ref/network-restrictions',
+ response: () =>
+ HttpResponse.json<NetworkRestrictionsResponse>({
+ entitlement: 'allowed',
+ status: 'applied',
+ config: { dbAllowedCidrs, dbAllowedCidrsV6: [] },
+ }),
+ })
+}
+
+const mockApply = () => {
+ const requests: ApplyRequest[] = []
+ addAPIMock({
+ method: 'post',
+ path: '/v1/projects/:ref/network-restrictions/apply',
+ response: async ({ request, params }) => {
+ requests.push({ ref: params.ref as string | undefined, body: await request.json() })
+ return HttpResponse.json<NetworkRestrictionsResponse>(
+ {
+ entitlement: 'allowed',
+ status: 'stored',
+ config: { dbAllowedCidrs: [], dbAllowedCidrsV6: [] },
+ },
+ { status: 201 }
+ )
+ },
+ })
+ return requests
+}
+
+const renderModal = (
+ props: Partial<React.ComponentProps<typeof AddRestrictionModal>> = {},
+ { cachedCidrs }: { cachedCidrs?: string[] } = {}
+) => {
+ const onClose = props.onClose ?? vi.fn()
+
+ // Seeding the cache means existing restrictions are available on first render,
+ // so tests that depend on them don't have to wait for the query to resolve
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ if (cachedCidrs) {
+ queryClient.setQueryData(networkRestrictionKeys.list('default'), {
+ config: { dbAllowedCidrs: cachedCidrs, dbAllowedCidrsV6: [] },
+ })
+ }
+
+ customRender(
+ <AddRestrictionModal
+ type="IPv4"
+ hasOverachingRestriction={false}
+ {...props}
+ onClose={onClose}
+ />,
+ { queryClient }
+ )
+ return { onClose }
+}
+
+const addEntry = async (address: string, cidrBlockSize?: string) => {
+ const ipInput = await screen.findByPlaceholderText('0.0.0.0')
+ await userEvent.type(ipInput, address)
+ if (cidrBlockSize !== undefined) {
+ const sizeInput = screen.getByPlaceholderText('32')
+ await userEvent.clear(sizeInput)
+ await userEvent.type(sizeInput, cidrBlockSize)
+ }
+ fireEvent.click(screen.getByRole('button', { name: 'Add to list' }))
+}
+
+describe('AddRestrictionModal', () => {
+ beforeEach(() => {
+ vi.mocked(toast.success).mockClear()
+ })
+
+ test('disables Save until an address is entered', async () => {
+ mockExistingRestrictions([])
+ renderModal()
+
+ expect(await screen.findByRole('button', { name: 'Save restrictions' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'Add to list' })).toBeDisabled()
+ })
+
+ test('moves an added address to the list and clears the fields', async () => {
+ mockExistingRestrictions([])
+ renderModal()
+
+ await addEntry('203.0.113.7')
+
+ expect(await screen.findByText('1 range to add')).toBeInTheDocument()
+ expect(screen.getByDisplayValue('203.0.113.7/32')).toBeInTheDocument()
+ expect(screen.getByPlaceholderText('0.0.0.0')).toHaveValue('')
+ })
+
+ test('saves every added address in a single request, appended to existing ones', async () => {
+ mockExistingRestrictions(['198.51.100.0/24'])
+ const requests = mockApply()
+ const { onClose } = renderModal({}, { cachedCidrs: ['198.51.100.0/24'] })
+
+ await addEntry('203.0.113.7')
+ await addEntry('192.0.2.0', '24')
+ expect(await screen.findByText('2 ranges to add')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Save restrictions' }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(requests).toEqual([
+ {
+ ref: 'default',
+ body: {
+ dbAllowedCidrs: ['198.51.100.0/24', '203.0.113.7/32', '192.0.2.0/24'],
+ dbAllowedCidrsV6: [],
+ },
+ },
+ ])
+ })
+
+ test('includes a valid address that was typed but not added to the list', async () => {
+ mockExistingRestrictions([])
+ const requests = mockApply()
+ const { onClose } = renderModal()
+
+ await addEntry('203.0.113.7')
+ await userEvent.type(screen.getByPlaceholderText('0.0.0.0'), '192.0.2.1')
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Save restrictions' }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(requests).toHaveLength(1)
+ expect(requests[0].body).toEqual({
+ dbAllowedCidrs: ['203.0.113.7/32', '192.0.2.1/32'],
+ dbAllowedCidrsV6: [],
+ })
+ expect(toast.success).toHaveBeenCalledWith('Restrictions added')
+ })
+
+ test('confirms a single restriction when only a typed address is saved', async () => {
+ mockExistingRestrictions([])
+ const requests = mockApply()
+ const { onClose } = renderModal()
+
+ await userEvent.type(await screen.findByPlaceholderText('0.0.0.0'), '192.0.2.1')
+ fireEvent.click(await screen.findByRole('button', { name: 'Save restriction' }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(requests).toHaveLength(1)
+ expect(toast.success).toHaveBeenCalledWith('Restriction added')
+ })
+
+ test('replaces an allow-all restriction instead of appending to it', async () => {
+ mockExistingRestrictions(['0.0.0.0/0'])
+ const requests = mockApply()
+ const { onClose } = renderModal({ hasOverachingRestriction: true })
+
+ await addEntry('203.0.113.7')
+ fireEvent.click(await screen.findByRole('button', { name: 'Save restriction' }))
+
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ expect(requests[0].body).toEqual({ dbAllowedCidrs: ['203.0.113.7/32'], dbAllowedCidrsV6: [] })
+ })
+
+ test('rejects an address that is already restricted', async () => {
+ mockExistingRestrictions(['203.0.113.7/32'])
+ renderModal({}, { cachedCidrs: ['203.0.113.7/32'] })
+
+ await addEntry('203.0.113.7')
+
+ expect(
+ await screen.findByText('The address 203.0.113.7/32 is already restricted')
+ ).toBeInTheDocument()
+ expect(screen.queryByText('1 range to add')).not.toBeInTheDocument()
+ })
+
+ test('rejects an address that is already in the list', async () => {
+ mockExistingRestrictions([])
+ renderModal()
+
+ await addEntry('203.0.113.7')
+ await addEntry('203.0.113.7')
+
+ expect(
+ await screen.findByText('The address 203.0.113.7/32 is already in the list')
+ ).toBeInTheDocument()
+ expect(screen.getByText('1 range to add')).toBeInTheDocument()
+ })
+
+ test('rejects private addresses', async () => {
+ mockExistingRestrictions([])
+ renderModal()
+
+ await addEntry('10.0.0.1')
+
+ expect(await screen.findByText('Private IP addresses are not supported')).toBeInTheDocument()
+ expect(screen.queryByText('1 range to add')).not.toBeInTheDocument()
+ })
+
+ test('removes an address from the list', async () => {
+ mockExistingRestrictions([])
+ renderModal()
+
+ await addEntry('203.0.113.7')
+ await userEvent.click(await screen.findByRole('button', { name: 'Remove 203.0.113.7/32' }))
+
+ expect(screen.queryByDisplayValue('203.0.113.7/32')).not.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Save restrictions' })).toBeDisabled()
+ })
+
+ test('asks for confirmation before discarding added addresses', async () => {
+ mockExistingRestrictions([])
+ const { onClose } = renderModal()
+
+ await addEntry('203.0.113.7')
+ await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
+
+ expect(await screen.findByText('Unsaved changes')).toBeInTheDocument()
+ expect(onClose).not.toHaveBeenCalled()
+
+ await userEvent.click(screen.getByRole('button', { name: 'Discard changes' }))
+ expect(onClose).toHaveBeenCalled()
+ })
+
+ test('closes without confirmation when nothing was entered', async () => {
+ mockExistingRestrictions([])
+ const { onClose } = renderModal()
+
+ await userEvent.click(await screen.findByRole('button', { name: 'Cancel' }))
+
+ expect(onClose).toHaveBeenCalled()
+ })
+})
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
index f69b4b0ae64..90eb9aa9d59 100644
--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx
@@ -1,7 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useParams } from 'common'
-import { HelpCircleIcon } from 'lucide-react'
-import { useEffect } from 'react'
+import { HelpCircleIcon, PlusIcon, TrashIcon } from 'lucide-react'
+import { useMemo, useState } from 'react'
import { useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import {
@@ -25,56 +25,33 @@ import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import * as z from 'zod'
import { checkIfPrivate, getAddressEndRange, normalize } from './NetworkRestrictions.utils'
+import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
import InformationBox from '@/components/ui/InformationBox'
import { useNetworkRestrictionsQuery } from '@/data/network-restrictions/network-restrictions-query'
import { useNetworkRestrictionsApplyMutation } from '@/data/network-restrictions/network-retrictions-apply-mutation'
+import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
import { DOCS_URL } from '@/lib/constants'
const IPV4_MAX_CIDR_BLOCK_SIZE = 32
const IPV6_MAX_CIDR_BLOCK_SIZE = 128
-interface AddRestrictionModalProps {
- type?: 'IPv4' | 'IPv6'
- hasOverachingRestriction: boolean
- onClose: () => void
-}
+type RestrictionType = 'IPv4' | 'IPv6'
-const AddRestrictionModal = ({
- type,
- hasOverachingRestriction,
- onClose,
-}: AddRestrictionModalProps) => {
- const formId = 'add-restriction-form'
- const { ref } = useParams()
+const getMaxCidrBlockSize = (type: RestrictionType | undefined) =>
+ type === 'IPv6' ? IPV6_MAX_CIDR_BLOCK_SIZE : IPV4_MAX_CIDR_BLOCK_SIZE
- const { data } = useNetworkRestrictionsQuery({ projectRef: ref }, { enabled: type !== undefined })
- const ipv4Restrictions = data?.config?.dbAllowedCidrs ?? []
- // @ts-ignore [Joshen] API typing issue
- const ipv6Restrictions = data?.config?.dbAllowedCidrsV6 ?? []
- const restrictedIps = ipv4Restrictions.concat(ipv6Restrictions)
-
- const { mutate: applyNetworkRestrictions, isPending: isApplying } =
- useNetworkRestrictionsApplyMutation({
- onSuccess: () => {
- toast.success('Successfully added restriction')
- onClose()
- },
- })
+const getFormSchema = (type: RestrictionType | undefined) => {
+ const maxCidrBlockSize = getMaxCidrBlockSize(type)
+ const cidrBlockSizeValidationMessage = `Size has to be between 0 to ${maxCidrBlockSize}`
- const cidrBlockSizeValidationMessage = `Size has to be between 0 to ${
- type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE
- }`
- const formSchema = z.object({
+ return z.object({
cidrBlockSize: z
.union([
z.literal(''),
z.coerce
.number()
.min(0, cidrBlockSizeValidationMessage)
- .max(
- type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,
- cidrBlockSizeValidationMessage
- ),
+ .max(maxCidrBlockSize, cidrBlockSizeValidationMessage),
])
.refine((value) => value !== '', 'Size is required'),
ipAddress: z
@@ -86,59 +63,124 @@ const AddRestrictionModal = ({
})
.refine((val) => !checkIfPrivate(type, val), 'Private IP addresses are not supported'),
})
+}
- const form = useForm<z.infer<typeof formSchema>>({
+type FormValues = z.infer<ReturnType<typeof getFormSchema>>
+
+interface AddRestrictionModalProps {
+ type?: RestrictionType
+ hasOverachingRestriction: boolean
+ onClose: () => void
+}
+
+export const AddRestrictionModal = ({
+ type,
+ hasOverachingRestriction,
+ onClose,
+}: AddRestrictionModalProps) => {
+ const { ref } = useParams()
+
+ // Normalized addresses that have been added to the list, pending save
+ const [stagedAddresses, setStagedAddresses] = useState<string[]>([])
+
+ const { data } = useNetworkRestrictionsQuery({ projectRef: ref }, { enabled: type !== undefined })
+ const ipv4Restrictions = data?.config?.dbAllowedCidrs ?? []
+ // @ts-ignore [Joshen] API typing issue
+ const ipv6Restrictions = data?.config?.dbAllowedCidrsV6 ?? []
+ const restrictedIps = ipv4Restrictions.concat(ipv6Restrictions)
+
+ const maxCidrBlockSize = getMaxCidrBlockSize(type)
+ const formSchema = useMemo(() => getFormSchema(type), [type])
+ const defaultValues: FormValues = { ipAddress: '', cidrBlockSize: maxCidrBlockSize }
+
+ const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
- defaultValues: {
- ipAddress: '',
- cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,
- },
+ defaultValues,
+ // Reset the draft fields when the dialog opens for a different type
+ values: defaultValues,
})
- const { reset, formState } = form
- const { errors } = formState
+ const { errors } = form.formState
- useEffect(() => {
- reset({
- ipAddress: '',
- cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE,
+ const [cidrBlockSize, ipAddress] = useWatch({
+ name: ['cidrBlockSize', 'ipAddress'],
+ control: form.control,
+ })
+ const hasDraft = ipAddress.trim() !== ''
+ const pendingCount = stagedAddresses.length + (hasDraft ? 1 : 0)
+
+ const handleClose = () => {
+ setStagedAddresses([])
+ form.reset()
+ onClose()
+ }
+
+ const {
+ confirmOnClose,
+ handleOpenChange,
+ modalProps: discardChangesModalProps,
+ } = useConfirmOnClose({
+ checkIsDirty: () => pendingCount > 0,
+ onClose: handleClose,
+ })
+
+ const { mutate: applyNetworkRestrictions, isPending: isApplying } =
+ useNetworkRestrictionsApplyMutation({
+ onSuccess: () => handleClose(),
})
- }, [type, reset])
- const onSubmit = async (values: any) => {
- if (!ref) return console.error('Project ref is required')
+ // Validates the draft fields and moves a valid entry to the list. Returns the
+ // updated list, or undefined if the draft was rejected.
+ const addDraftToList = async () => {
+ const isValid = await form.trigger()
+ if (!isValid) return
- const address = `${values.ipAddress}/${values.cidrBlockSize}`
+ const { ipAddress, cidrBlockSize } = form.getValues()
+ const address = `${ipAddress}/${cidrBlockSize}`
const normalizedAddress = normalize(address)
- const alreadyExists =
- restrictedIps.includes(address) || restrictedIps.includes(normalizedAddress)
- if (alreadyExists) {
- return toast(`The address ${address} is already restricted`)
+ if (restrictedIps.includes(address) || restrictedIps.includes(normalizedAddress)) {
+ form.setError('ipAddress', { message: `The address ${address} is already restricted` })
+ return
+ }
+ if (stagedAddresses.includes(normalizedAddress)) {
+ form.setError('ipAddress', { message: `The address ${address} is already in the list` })
+ return
+ }
+
+ const nextAddresses = [...stagedAddresses, normalizedAddress]
+ setStagedAddresses(nextAddresses)
+ form.reset()
+ return nextAddresses
+ }
+
+ const handleSave = async () => {
+ if (!ref) return console.error('Project ref is required')
+
+ // A valid entry that was typed but not yet added to the list is saved too
+ const addresses = hasDraft ? await addDraftToList() : stagedAddresses
+ if (addresses === undefined || addresses.length === 0) return
+
+ // Based on the submitted addresses, as the staged list may not have updated yet
+ const applyOptions = {
+ onSuccess: () =>
+ toast.success(addresses.length === 1 ? 'Restriction added' : 'Restrictions added'),
}
// Need to replace over arching restriction (allow all / disallow all)
if (hasOverachingRestriction) {
- const dbAllowedCidrs = type === 'IPv4' ? [normalizedAddress] : []
- const dbAllowedCidrsV6 = type === 'IPv6' ? [normalizedAddress] : []
- applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 })
+ const dbAllowedCidrs = type === 'IPv4' ? addresses : []
+ const dbAllowedCidrsV6 = type === 'IPv6' ? addresses : []
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 }, applyOptions)
} else {
const dbAllowedCidrs =
- type === 'IPv4' ? [...ipv4Restrictions, normalizedAddress] : ipv4Restrictions
+ type === 'IPv4' ? [...ipv4Restrictions, ...addresses] : ipv4Restrictions
const dbAllowedCidrsV6 =
- type === 'IPv6' ? [...ipv6Restrictions, normalizedAddress] : ipv6Restrictions
- applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 })
+ type === 'IPv6' ? [...ipv6Restrictions, ...addresses] : ipv6Restrictions
+ applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 }, applyOptions)
}
}
- const [cidrBlockSize, ipAddress] = useWatch({
- name: ['cidrBlockSize', 'ipAddress'],
- control: form.control,
- })
-
- const availableAddresses =
- type === 'IPv4'
- ? Math.pow(2, IPV4_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0))
- : Math.pow(2, IPV6_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0))
+ const availableAddresses = Math.pow(2, maxCidrBlockSize - (cidrBlockSize ?? 0))
const addressRange =
type !== undefined ? getAddressEndRange(type, `${ipAddress}/${cidrBlockSize}`) : undefined
@@ -151,136 +193,180 @@ const AddRestrictionModal = ({
: `${ipAddress}/${cidrBlockSize}`
return (
- <Dialog open={type !== undefined} onOpenChange={onClose}>
- <DialogContent size="medium">
- <DialogHeader>
- <DialogTitle>{`Add a new ${type} restriction`}</DialogTitle>
- </DialogHeader>
- <DialogSectionSeparator />
- <Form {...form}>
- <DialogSection className="space-y-4">
- <p className="text-sm text-foreground-light">
- This will add an IP address range to a list of allowed ranges that can access your
- database.
- </p>
- <InformationBox
- title="Note: Restrictions only apply to direct connections to your database and connection pooler"
- description="They do not currently apply to APIs offered over HTTPS, such as PostgREST, Storage, or Authentication."
- urlLabel="Learn more"
- url={`${DOCS_URL}/guides/platform/network-restrictions#limitations`}
- />
- <form
- id={formId}
- onSubmit={form.handleSubmit(onSubmit)}
- noValidate
- className="flex space-x-4"
- >
- <div className="w-[55%]">
- <FormField
- control={form.control}
- name="ipAddress"
- render={({ field }) => (
- <FormItemLayout layout="vertical" label={`${type} address`}>
- <FormControl>
- <Input {...field} placeholder={type === 'IPv4' ? '0.0.0.0' : '::0'} />
- </FormControl>
- </FormItemLayout>
- )}
- />
- </div>
- <div className="grow">
- <FormField
- control={form.control}
- name="cidrBlockSize"
- render={({ field }) => (
- <FormItemLayout
- layout="vertical"
- label={
- <div className="flex items-center space-x-2">
- <p>CIDR Block Size</p>
- <Tooltip>
- <TooltipTrigger>
- <HelpCircleIcon size="14" strokeWidth={2} />
- </TooltipTrigger>
- <TooltipContent side="bottom" className="w-80">
- Classless inter-domain routing (CIDR) notation is the notation used to
- identify networks and hosts in the networks. The block size tells us
- how many bits we need to take for the network prefix, and is a value
- between 0 to{' '}
- {type === 'IPv4'
- ? IPV4_MAX_CIDR_BLOCK_SIZE
- : IPV6_MAX_CIDR_BLOCK_SIZE}
- .
- </TooltipContent>
- </Tooltip>
- </div>
- }
- >
- <FormControl>
- <Input
- {...field}
- type="number"
- min={0}
- max={
- type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE
- }
- placeholder={
- type === 'IPv4'
- ? IPV4_MAX_CIDR_BLOCK_SIZE.toString()
- : IPV6_MAX_CIDR_BLOCK_SIZE.toString()
- }
- />
- </FormControl>
- </FormItemLayout>
- )}
- />
- </div>
- </form>
- </DialogSection>
+ <>
+ <Dialog open={type !== undefined} onOpenChange={handleOpenChange}>
+ <DialogContent size="medium">
+ <DialogHeader>
+ <DialogTitle>{`Add ${type} restrictions`}</DialogTitle>
+ </DialogHeader>
<DialogSectionSeparator />
- {isValidCIDR ? (
- <DialogSection className="space-y-1">
- <p className="text-sm">
- The address range <code className="text-code-inline">{normalizedAddress}</code> will
- be restricted
- </p>
- <p className="text-sm text-foreground-light">
- Selected address space:{' '}
- <code className="text-code-inline">{addressRange.start}</code> to{' '}
- <code className="text-code-inline">{addressRange.end}</code>{' '}
- </p>
+ <Form {...form}>
+ <DialogSection className="space-y-4">
<p className="text-sm text-foreground-light">
- Number of addresses: {availableAddresses}
+ This adds IP address ranges to the list of allowed ranges that can access your
+ database. Add as many as you need, then save them together.
</p>
+ <InformationBox
+ title="Note: Restrictions only apply to direct connections to your database and connection pooler"
+ description="They do not currently apply to APIs offered over HTTPS, such as PostgREST, Storage, or Authentication."
+ urlLabel="Learn more"
+ url={`${DOCS_URL}/guides/platform/network-restrictions#limitations`}
+ />
+ <form
+ noValidate
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ addDraftToList()
+ }}
+ >
+ <div className="flex space-x-4">
+ <div className="w-[55%]">
+ <FormField
+ control={form.control}
+ name="ipAddress"
+ render={({ field }) => (
+ <FormItemLayout layout="vertical" label={`${type} address`}>
+ <FormControl>
+ <Input {...field} placeholder={type === 'IPv4' ? '0.0.0.0' : '::0'} />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ <div className="grow">
+ <FormField
+ control={form.control}
+ name="cidrBlockSize"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="vertical"
+ label={
+ <div className="flex items-center space-x-2">
+ <p>CIDR Block Size</p>
+ <Tooltip>
+ <TooltipTrigger type="button">
+ <HelpCircleIcon size="14" strokeWidth={2} />
+ </TooltipTrigger>
+ <TooltipContent side="bottom" className="w-80">
+ Classless inter-domain routing (CIDR) notation is the notation
+ used to identify networks and hosts in the networks. The block
+ size tells us how many bits we need to take for the network
+ prefix, and is a value between 0 to {maxCidrBlockSize}.
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ }
+ >
+ <FormControl>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ max={maxCidrBlockSize}
+ placeholder={maxCidrBlockSize.toString()}
+ />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ </div>
+ <Button
+ variant="default"
+ size="tiny"
+ type="submit"
+ icon={<PlusIcon />}
+ disabled={isApplying || !hasDraft}
+ >
+ Add to list
+ </Button>
+ </form>
</DialogSection>
- ) : (
- <DialogSection>
- <div className="h-[68px] flex items-center">
+ {stagedAddresses.length > 0 && (
+ <>
+ <DialogSectionSeparator />
+ <DialogSection className="space-y-2">
+ <p className="text-sm">
+ {stagedAddresses.length === 1
+ ? '1 range to add'
+ : `${stagedAddresses.length} ranges to add`}
+ </p>
+ <ul className="space-y-2">
+ {stagedAddresses.map((address) => (
+ <li key={address} className="flex items-center space-x-2">
+ <Input
+ readOnly
+ size="small"
+ value={address}
+ aria-label={`Restriction ${address}`}
+ className="flex-1"
+ />
+ <Button
+ size="tiny"
+ icon={<TrashIcon size={12} />}
+ aria-label={`Remove ${address}`}
+ className="h-[34px] w-[34px] shrink-0"
+ disabled={isApplying}
+ onClick={() =>
+ setStagedAddresses((addresses) =>
+ addresses.filter((item) => item !== address)
+ )
+ }
+ />
+ </li>
+ ))}
+ </ul>
+ </DialogSection>
+ </>
+ )}
+ <DialogSectionSeparator />
+ {isValidCIDR ? (
+ <DialogSection className="space-y-1">
+ <p className="text-sm">
+ The address range <code className="text-code-inline">{normalizedAddress}</code>{' '}
+ will be restricted
+ </p>
<p className="text-sm text-foreground-light">
- A summary of your restriction will be shown here after entering a valid IP address
- and CIDR block size. IP addresses will also be normalized.
+ Selected address space:{' '}
+ <code className="text-code-inline">{addressRange.start}</code> to{' '}
+ <code className="text-code-inline">{addressRange.end}</code>{' '}
</p>
- </div>
- </DialogSection>
- )}
- <DialogFooter>
- <Button disabled={isApplying} onClick={() => onClose()}>
- Cancel
- </Button>
- <Button
- variant="primary"
- form={formId}
- type="submit"
- loading={isApplying}
- disabled={isApplying}
- >
- Save restriction
- </Button>
- </DialogFooter>
- </Form>
- </DialogContent>
- </Dialog>
+ <p className="text-sm text-foreground-light">
+ Number of addresses: {availableAddresses}
+ </p>
+ </DialogSection>
+ ) : (
+ <DialogSection>
+ <div className="h-[68px] flex items-center">
+ <p className="text-sm text-foreground-light">
+ A summary of your restriction will be shown here after entering a valid IP
+ address and CIDR block size. IP addresses will also be normalized.
+ </p>
+ </div>
+ </DialogSection>
+ )}
+ <DialogFooter>
+ <Button disabled={isApplying} onClick={confirmOnClose}>
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ type="button"
+ loading={isApplying}
+ disabled={isApplying || pendingCount === 0}
+ onClick={handleSave}
+ >
+ {pendingCount === 1 ? 'Save restriction' : 'Save restrictions'}
+ </Button>
+ </DialogFooter>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ <DiscardChangesConfirmationDialog
+ {...discardChangesModalProps}
+ description="Are you sure you want to discard your changes? Your restrictions will not be saved."
+ />
+ </>
)
}
-
-export default AddRestrictionModal
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx
index 31b7f1b7f99..dd301dc6328 100644
--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.tsx
@@ -24,7 +24,7 @@ import {
} from 'ui-patterns/PageSection'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
-import AddRestrictionModal from './AddRestrictionModal'
+import { AddRestrictionModal } from './AddRestrictionModal'
import AllowAllModal from './AllowAllModal'
import DisallowAllModal from './DisallowAllModal'
import RemoveRestrictionModal from './RemoveRestrictionModal'