Skip to content

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

fix: redirect urls (#47487)

Vaibhav804475fd3a6e
diff --git a/apps/studio/components/interfaces/Auth/Auth.constants.ts b/apps/studio/components/interfaces/Auth/Auth.constants.ts
index 27458458bc6..d85bf61150f 100644
--- a/apps/studio/components/interfaces/Auth/Auth.constants.ts
+++ b/apps/studio/components/interfaces/Auth/Auth.constants.ts
@@ -42,5 +42,22 @@ export function urlRegex(
)
}
+export function normalizeRedirectUrl(url: string): string {
+ return url.trim().replace(/\s*,\s*$/, '')
+}
+
+export function parseRedirectUrls(allowList?: string | null): string[] {
+ if (!allowList) return []
+
+ return Array.from(
+ new Set(
+ allowList
+ .split(',')
+ .map(normalizeRedirectUrl)
+ .filter((url) => url.length > 0)
+ )
+ )
+}
+
// Use a const string to represent no chars option. Represented as empty string on the backend side.
export const NO_REQUIRED_CHARACTERS = 'NO_REQUIRED_CHARS'
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx
index dc89c65f59e..43137ec556e 100644
--- a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx
+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.test.tsx
@@ -80,7 +80,7 @@ describe('AddNewURLModal', () => {
expect(toast.success).toHaveBeenCalledWith('Successfully added 1 URL')
})
- it('dedupes URLs after normalising a trailing comma before submitting', async () => {
+ it('normalizes a trailing-comma URL before submitting', async () => {
const user = userEvent.setup()
mutateMock.mockImplementation((_vars, callbacks) => callbacks?.onSuccess?.())
@@ -88,11 +88,7 @@ describe('AddNewURLModal', () => {
await screen.findByRole('dialog')
- await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com')
- await user.click(screen.getByRole('button', { name: 'Add URL' }))
-
- const urlInputs = screen.getAllByPlaceholderText('https://mydomain.com')
- await user.type(urlInputs[1], 'https://app.example.com,')
+ await user.type(screen.getByPlaceholderText('https://mydomain.com'), 'https://app.example.com,')
fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)
@@ -130,4 +126,24 @@ describe('AddNewURLModal', () => {
expect(await screen.findByText('URL already exists in the allow list')).toBeInTheDocument()
expect(mutateMock).not.toHaveBeenCalled()
})
+
+ it('rejects a whitespace-padded URL when it already exists in the allow list', async () => {
+ const user = userEvent.setup()
+
+ render(
+ <AddNewURLModal visible allowList={['https://existing.example.com']} onClose={vi.fn()} />
+ )
+
+ await screen.findByRole('dialog')
+
+ await user.type(
+ screen.getByPlaceholderText('https://mydomain.com'),
+ ' https://existing.example.com '
+ )
+
+ fireEvent.submit(screen.getByRole('dialog').querySelector('form') as HTMLFormElement)
+
+ expect(await screen.findByText('URL already exists in the allow list')).toBeInTheDocument()
+ expect(mutateMock).not.toHaveBeenCalled()
+ })
})
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
index fcd9160d02b..7e7cffa8b6c 100644
--- a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx
@@ -22,7 +22,7 @@ import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { SingleValueFieldArray } from 'ui-patterns/form/SingleValueFieldArray/SingleValueFieldArray'
import * as z from 'zod'
-import { urlRegex } from '../Auth.constants'
+import { normalizeRedirectUrl, parseRedirectUrls, urlRegex } from '../Auth.constants'
import { useAuthConfigUpdateMutation } from '@/data/auth/auth-config-update-mutation'
const MAX_URLS_LENGTH = 2 * 1024
@@ -33,61 +33,88 @@ interface AddNewURLModalProps {
onClose: () => void
}
-const normaliseUrl = (value: string) => value.replace(/,\s*$/, '')
-
-export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalProps) => {
- const { ref } = useParams()
- const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation()
+const createRedirectUrlsSchema = (normalizedAllowList: string[]) => {
const redirectUrlRegex = urlRegex()
- const FormSchema = z.object({
- urls: z
- .object({
- value: z
- .string()
- .min(1, 'Please provide a value')
- .refine(
- (value) => redirectUrlRegex.test(normaliseUrl(value)),
- 'Please provide a valid URL'
- )
- .refine((value) => !allowList.includes(normaliseUrl(value)), {
+ return z
+ .object({
+ urls: z
+ .object({
+ value: z.string().trim().min(1, 'Please provide a value').transform(normalizeRedirectUrl),
+ })
+ .array()
+ .default([]),
+ })
+ .superRefine((data, ctx) => {
+ const seenUrls = new Set<string>()
+
+ data.urls.forEach((url, index) => {
+ if (!redirectUrlRegex.test(url.value)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['urls', index, 'value'],
+ message: 'Please provide a valid URL',
+ })
+ }
+
+ if (normalizedAllowList.includes(url.value)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['urls', index, 'value'],
message: 'URL already exists in the allow list',
- }),
+ })
+ }
+
+ if (seenUrls.has(url.value)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['urls', index, 'value'],
+ message: 'URL already exists in this list',
+ })
+ }
+
+ seenUrls.add(url.value)
})
- .array()
- .default([]),
- })
+ })
+}
+
+export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalProps) => {
+ const { ref } = useParams()
+ const { mutate: updateAuthConfig, isPending: isUpdatingConfig } = useAuthConfigUpdateMutation()
+ const normalizedAllowList = parseRedirectUrls(allowList.join(','))
+ const formSchema = createRedirectUrlsSchema(normalizedAllowList)
const initialValues = { urls: [{ value: '' }] }
- const form = useForm<z.infer<typeof FormSchema>>({
- resolver: zodResolver(FormSchema),
+ const form = useForm<z.infer<typeof formSchema>>({
+ resolver: zodResolver(formSchema),
defaultValues: initialValues,
})
const urls = form.watch('urls')
- const onSubmit = (data: z.infer<typeof FormSchema>) => {
- const dedupedUrls = [...new Set(data.urls.map((url) => normaliseUrl(url.value)))]
- const payloadUrls = allowList.concat(dedupedUrls)
- const addedCount = dedupedUrls.length
- const payload = payloadUrls.toString()
+ const onSubmit = (data: z.infer<typeof formSchema>) => {
+ const payload = parseRedirectUrls(
+ normalizedAllowList.concat(data.urls.map((url) => url.value)).join(',')
+ )
+ const payloadString = payload.join(',')
+ const addedCount = payload.length - normalizedAllowList.length
- if (payload.length > MAX_URLS_LENGTH) {
+ if (payloadString.length > MAX_URLS_LENGTH) {
return toast.error('Too many redirect URLs, please remove some or try to use wildcards')
- } else {
- updateAuthConfig(
- { projectRef: ref!, config: { URI_ALLOW_LIST: payload } },
- {
- onError: (error) => {
- toast.error(`Failed to add URL(s): ${error?.message}`)
- },
- onSuccess: () => {
- toast.success(`Successfully added ${addedCount} URL${addedCount > 1 ? 's' : ''}`)
- form.reset(initialValues)
- onClose()
- },
- }
- )
}
+
+ updateAuthConfig(
+ { projectRef: ref!, config: { URI_ALLOW_LIST: payloadString } },
+ {
+ onError: (error) => {
+ toast.error(`Failed to add URL(s): ${error?.message}`)
+ },
+ onSuccess: () => {
+ toast.success(`Successfully added ${addedCount} URL${addedCount > 1 ? 's' : ''}`)
+ form.reset(initialValues)
+ onClose()
+ },
+ }
+ )
}
useEffect(() => {
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx
index f23ce4574bd..0441dfab252 100644
--- a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx
+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx
@@ -23,6 +23,7 @@ import {
PageSectionTitle,
} from 'ui-patterns/PageSection'
+import { parseRedirectUrls } from '../Auth.constants'
import { AddNewURLModal } from './AddNewURLModal'
import { RedirectUrlList } from './RedirectUrlList'
import { ValueContainer } from './ValueContainer'
@@ -46,9 +47,7 @@ export const RedirectUrls = () => {
useAuthConfigUpdateMutation()
const URI_ALLOW_LIST_ARRAY = useMemo(() => {
- return authConfig?.URI_ALLOW_LIST
- ? authConfig.URI_ALLOW_LIST.split(/\s*[,]+\s*/).filter((url: string) => url)
- : []
+ return parseRedirectUrls(authConfig?.URI_ALLOW_LIST)
}, [authConfig?.URI_ALLOW_LIST])
const [open, setOpen] = useState(false)
@@ -58,8 +57,7 @@ export const RedirectUrls = () => {
const onConfirmDeleteUrl = async (urls?: string[]) => {
if (!urls || urls.length === 0) return
- // Remove selectedUrl from array and update
- const payload = URI_ALLOW_LIST_ARRAY.filter((url: string) => !selectedUrls.includes(url))
+ const payload = URI_ALLOW_LIST_ARRAY.filter((url: string) => !urls.includes(url))
const payloadString = payload.join(',')
await updateAuthConfig(
{ projectRef: projectRef!, config: { URI_ALLOW_LIST: payloadString } },
diff --git a/apps/studio/tests/components/Auth/Auth.constants.test.ts b/apps/studio/tests/components/Auth/Auth.constants.test.ts
index f618b77136d..1beb569ed1d 100644
--- a/apps/studio/tests/components/Auth/Auth.constants.test.ts
+++ b/apps/studio/tests/components/Auth/Auth.constants.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest'
-import { urlRegex } from '@/components/interfaces/Auth/Auth.constants'
+import {
+ normalizeRedirectUrl,
+ parseRedirectUrls,
+ urlRegex,
+} from '@/components/interfaces/Auth/Auth.constants'
describe('Auth.constants: urlRegex', () => {
it('should match valid URLs', () => {
@@ -49,4 +53,16 @@ describe('Auth.constants: urlRegex', () => {
const simpleDomainUrl = 'smtp-pulse.com'
expect(urlRegex({ excludeSimpleDomains: false }).test(simpleDomainUrl)).toBe(true)
})
+
+ it('normalizes redirect URLs before saving', () => {
+ expect(normalizeRedirectUrl(' https://example.com/path , ')).toBe('https://example.com/path')
+ })
+
+ it('parses stored redirect URLs into trimmed unique values', () => {
+ expect(
+ parseRedirectUrls(
+ 'https://example.com/callback, https://example.com/callback , https://example.com/next'
+ )
+ ).toEqual(['https://example.com/callback', 'https://example.com/next'])
+ })
})