Files
Connor Davis c920e07d9c feat(studio): review a pending network restrictions change (#52984)
## Problem

A network restrictions change that was never applied can now wait for
the customer's review ([API
Docs](https://api.supabase.com/api/v1#tag/projects/POST/v1/projects/{ref}/network-restrictions/review),
[CTRL-1934](https://linear.app/supabase/issue/CTRL-1934)). Studio
doesn't show it. Lists with an entry that isn't a valid IP range also
fail to save without saying which entry is wrong.

## Solution

- A change in review shows one callout with **Apply change** and
**Discard change**, and both lists together: added entries in green,
removed ones in red. Editing is disabled until it's resolved, and
discarding asks for confirmation. Only the change on screen is resolved
(`pending_requested_at`).
- A list the worker is still applying shows as applying and is polled,
instead of showing the "not applied correctly" error.
- Entries that aren't valid ranges are marked Invalid with a suggested
correction, and can be saved corrected. The add dialog rejects
IPv4-mapped IPv6 addresses and finds duplicates spelled differently.

There's no way to create a review yet: a change only ends up in review
when the backend fails to apply a list. I tested the review state
locally by editing the database directly.

Stacked on #53046, which syncs the API types with production, including
the review endpoint. This PR will be retargeted to `master` once that
merges.

## Screenshots

<img width="712" height="473" alt="Screenshot 2026-11-04 at 5 10 19 PM"
src="https://github.com/user-attachments/assets/c72cc38d-f7b4-4269-a787-f27dfe382086"
/>

### If pressing `apply`

<img width="704" height="150" alt="Screenshot 2026-11-04 at 5 19 27 PM"
src="https://github.com/user-attachments/assets/92dce8e5-8d58-48b8-8899-ed01c9f242c2"
/>

### If pressing `discard`

<img width="712" height="473" alt="Screenshot 2026-11-04 at 5 10 38 PM"
src="https://github.com/user-attachments/assets/85656004-d510-4cef-89c1-80d9f95ebb83"
/>

### Invalid

<img width="754" height="596" alt="Image"
src="https://github.com/user-attachments/assets/4ba480f6-af4c-4253-9693-2c545fb77ab1"
/>

### Invalid repair

<img width="704" height="680" alt="Screenshot 2026-11-04 at 6 03 20 PM"
src="https://github.com/user-attachments/assets/ed4e3dcf-8d9b-4588-afc0-938248c78712"
/>

### Invalid and Pending

<img width="704" height="593" alt="Image"
src="https://github.com/user-attachments/assets/7ad76b50-0d08-4505-89ad-b6afff6865af"
/>

### Invalid and Pending repair

<img width="704" height="585" alt="Screenshot 2026-11-04 at 6 05 04 PM"
src="https://github.com/user-attachments/assets/b123453f-0f30-452d-b84c-a556c52458a0"
/>

## Review instructions

1. Locally, put a project's network restrictions into review by editing
the database directly. There's no API that creates one.
2. Open Database Settings > Network restrictions and check the callout
and the added and removed entries.
3. Apply or discard the change.

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
2026-11-06 13:15:46 -05:00

293 lines
9.8 KiB
TypeScript

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[], dbAllowedCidrsV6: 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, cachedCidrsV6 = [] }: { cachedCidrs?: string[]; cachedCidrsV6?: 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: cachedCidrsV6 },
})
}
customRender(
<AddRestrictionModal
type="IPv4"
hasOverachingRestriction={false}
{...props}
onClose={onClose}
/>,
{ queryClient }
)
return { onClose }
}
const user = userEvent.setup()
// Pasting rather than typing: keystroke-level input isn't the behaviour under test
const enterValue = async (input: HTMLElement, value: string) => {
await user.clear(input)
await user.paste(value)
}
const enterAddress = async (address: string) =>
enterValue(await screen.findByPlaceholderText('0.0.0.0'), address)
const addEntry = async (address: string, cidrBlockSize?: string) => {
await enterAddress(address)
if (cidrBlockSize !== undefined) {
await enterValue(screen.getByPlaceholderText('32'), 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 enterAddress('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 enterAddress('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 a range already restricted in another spelling', async () => {
mockExistingRestrictions([], ['2001:DB8::/32'])
renderModal({ type: 'IPv6' }, { cachedCidrs: [], cachedCidrsV6: ['2001:DB8::/32'] })
await enterValue(await screen.findByPlaceholderText('::0'), '2001:db8::')
await enterValue(screen.getByPlaceholderText('128'), '32')
fireEvent.click(screen.getByRole('button', { name: 'Add to list' }))
expect(
await screen.findByText('The address 2001:db8::/32 is already restricted')
).toBeInTheDocument()
})
test('rejects an IPv4-mapped IPv6 address', async () => {
mockExistingRestrictions([])
renderModal({ type: 'IPv6' })
await enterValue(await screen.findByPlaceholderText('::0'), '::ffff:102:304')
fireEvent.click(screen.getByRole('button', { name: 'Add to list' }))
expect(
await screen.findByText(
"IPv4-mapped IPv6 addresses aren't supported. Add the address as an IPv4 restriction instead."
)
).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 user.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 user.click(screen.getByRole('button', { name: 'Cancel' }))
expect(await screen.findByText('Unsaved changes')).toBeInTheDocument()
expect(onClose).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: 'Discard changes' }))
expect(onClose).toHaveBeenCalled()
})
test('closes without confirmation when nothing was entered', async () => {
mockExistingRestrictions([])
const { onClose } = renderModal()
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
expect(onClose).toHaveBeenCalled()
})
})