Skip to content

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

feat(studio): scoped oauth apps, admins can see an app grants (#50979)

Gildas Garcia690ef5e7f774
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.test.tsx
new file mode 100644
index 00000000000..0eb418be695
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.test.tsx
@@ -0,0 +1,72 @@
+import { screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { mockIntersectionObserver } from 'jsdom-testing-mocks'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import { OAuthAppsAuthorizedList } from '@/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList'
+import { customRender } from '@/tests/lib/custom-render'
+
+vi.mock('sonner', () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}))
+
+vi.mock('common', async (importOriginal) => {
+ const actual = (await importOriginal()) as typeof import('common')
+ return { ...actual, useParams: () => ({ slug: 'northwind-traders' }) }
+})
+
+let canRevoke = true
+
+mockIntersectionObserver()
+
+vi.mock('@/hooks/misc/useCheckPermissions', () => ({
+ useAsyncCheckPermissions: (action: string) => ({
+ can: action === 'write:Delete' ? canRevoke : true,
+ isSuccess: true,
+ isLoading: false,
+ }),
+}))
+
+const rowFor = async (name: string) => {
+ const cell = await screen.findByText(name)
+ const row = cell.closest('tr')
+ if (!row) throw new Error(`No row for ${name}`)
+ return row
+}
+
+const openRowMenu = async (name: string) => {
+ const row = await rowFor(name)
+ await userEvent.click(within(row).getByRole('button'))
+}
+
+beforeEach(() => {
+ canRevoke = true
+ vi.clearAllMocks()
+})
+
+describe('OAuthAppsAuthorizedList', () => {
+ test('expands a member to show their projects and permission groups', async () => {
+ customRender(<OAuthAppsAuthorizedList />)
+
+ await openRowMenu('Vercel')
+ await userEvent.click(await screen.findByText('View grants'))
+
+ expect(await screen.findByText('Member grants for Vercel')).toBeInTheDocument()
+ await userEvent.click(await screen.findByText('[email protected]'))
+
+ expect(await screen.findByText('northwind-storefront, northwind-cms')).toBeInTheDocument()
+ expect(
+ await screen.findByText('database:read, database:write, projects:read')
+ ).toBeInTheDocument()
+ })
+
+ test('labels an organization-bound grant and reports it as covering all projects', async () => {
+ customRender(<OAuthAppsAuthorizedList />)
+
+ await openRowMenu('Contoso Analytics')
+ await userEvent.click(await screen.findByText('View grants'))
+
+ expect(await screen.findByText('Organization-wide')).toBeInTheDocument()
+ expect(await screen.findByText(/All projects/)).toBeInTheDocument()
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.tsx
index 430987e69ae..c4d272242fb 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedList.tsx
@@ -107,12 +107,15 @@ export const OAuthAppsAuthorizedList = () => {
<TableHead className={cn(!hasAuthorizedApps && 'text-foreground-muted')}>
Access
</TableHead>
+ <TableHead className="text-right">
+ <span className="sr-only">Actions</span>
+ </TableHead>
</TableRow>
</TableHeader>
<TableBody>
{data.pages.length === 0 ? (
<TableRow className="[&>td]:hover:bg-inherit">
- <TableCell colSpan={3}>
+ <TableCell colSpan={4}>
<p className="text-sm text-foreground">No results found</p>
<p className="text-sm text-foreground-lighter">
No apps have been authorized in this organization yet.
@@ -141,7 +144,7 @@ export const OAuthAppsAuthorizedList = () => {
ref={sentinelRef}
className={cn('[&>td]:hover:bg-inherit', !isFetchingNextPage && 'hidden')}
>
- <TableCell colSpan={3}>
+ <TableCell colSpan={4}>
<p className="text-sm text-foreground-lighter">
{isFetchingNextPage ? 'Loading...' : ''}
</p>
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedRow.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedRow.tsx
index 89cc20da275..af2400a35bf 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedRow.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsAuthorizedRow.tsx
@@ -1,5 +1,21 @@
-import { TableCell, TableRow } from 'ui'
+import { MoreVerticalIcon } from 'lucide-react'
+import { useRef, useState } from 'react'
+import {
+ Button,
+ Dialog,
+ DialogTrigger,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ TableCell,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { OAuthAppsMemberGrantsDialogContent } from './OAuthAppsMemberGrantsDialogContent'
import type { OAuthApprovalItem, OAuthApprovalTarget } from '@/data/oauth-apps/types'
export interface OAuthAppsAuthorizedRowProps {
@@ -8,6 +24,10 @@ export interface OAuthAppsAuthorizedRowProps {
}
export const OAuthAppsAuthorizedRow = ({ approval, className }: OAuthAppsAuthorizedRowProps) => {
+ const [isDialogOpen, setIsDialogOpen] = useState(false)
+ const [dialogContent, setDialogContent] = useState<'grants' | 'revoke' | null>(null)
+ const menuTriggerRef = useRef<HTMLButtonElement | null>(null)
+
return (
<TableRow className={className}>
<TableCell className="pr-2">
@@ -27,6 +47,53 @@ export const OAuthAppsAuthorizedRow = ({ approval, className }: OAuthAppsAuthori
</div>
</TableCell>
<TableCell>{getGrantTargetLabel(approval.grant_target)}</TableCell>
+ <TableCell className="text-right">
+ <Dialog
+ open={isDialogOpen}
+ onOpenChange={(open) => {
+ setIsDialogOpen(open)
+ // When users close the dialogs, we need to restore the focus on the menu button
+ // Done in a setTimeout because the dialog tries to restore focus on the trigger despite onCloseAutoFocus being cancelled in the dialog contents
+ setTimeout(() => {
+ if (!open && menuTriggerRef.current) {
+ menuTriggerRef.current.focus()
+ }
+ })
+ }}
+ >
+ <DropdownMenu>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DropdownMenuTrigger asChild>
+ <Button
+ ref={menuTriggerRef}
+ icon={<MoreVerticalIcon />}
+ className="px-1"
+ aria-label="Manage app"
+ aria-describedby={undefined}
+ />
+ </DropdownMenuTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Manage app</TooltipContent>
+ </Tooltip>
+ <DropdownMenuContent align="end" side="bottom" className="w-40">
+ <DialogTrigger asChild>
+ <DropdownMenuItem onClick={() => setDialogContent('grants')}>
+ View grants
+ </DropdownMenuItem>
+ </DialogTrigger>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {dialogContent === 'grants' && (
+ <OAuthAppsMemberGrantsDialogContent
+ approval={approval}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault()
+ }}
+ />
+ )}
+ </Dialog>
+ </TableCell>
</TableRow>
)
}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsMemberGrantsDialogContent.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsMemberGrantsDialogContent.tsx
new file mode 100644
index 00000000000..53fe6aa020c
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppsMemberGrantsDialogContent.tsx
@@ -0,0 +1,172 @@
+import { useIntersectionObserver } from '@uidotdev/usehooks'
+import { useParams } from 'common'
+import { Building2, User } from 'lucide-react'
+import { ComponentProps, Fragment, useEffect, useMemo } from 'react'
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Button,
+ cn,
+ DialogClose,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ ScrollArea,
+} from 'ui'
+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
+
+import { AlertError } from '@/components/ui/AlertError'
+import { useOAuthAppMemberGrantsQuery } from '@/data/oauth-apps/oauth-apps-member-grants-query'
+import type { OAuthApprovalItem, OAuthGrantItem } from '@/data/oauth-apps/types'
+
+export interface OAuthAppsMemberGrantsDialogProps extends ComponentProps<typeof DialogContent> {
+ approval?: OAuthApprovalItem
+}
+
+export const OAuthAppsMemberGrantsDialogContent = ({
+ approval,
+ ...props
+}: OAuthAppsMemberGrantsDialogProps) => {
+ const { slug } = useParams()
+ const {
+ data,
+ error,
+ isPending,
+ isError,
+ isSuccess,
+ hasNextPage,
+ fetchNextPage,
+ isFetchingNextPage,
+ } = useOAuthAppMemberGrantsQuery(
+ { slug, appId: approval?.app?.id },
+ { enabled: Boolean(approval) }
+ )
+
+ const [sentinelRef, entry] = useIntersectionObserver({
+ root: null,
+ threshold: 0,
+ rootMargin: '0px',
+ })
+
+ useEffect(() => {
+ if (hasNextPage && entry?.isIntersecting && !isFetchingNextPage) {
+ fetchNextPage()
+ }
+ }, [hasNextPage, entry?.isIntersecting, fetchNextPage, isFetchingNextPage])
+
+ const statusText = useMemo(() => {
+ if (isFetchingNextPage) return 'Loading more grants...'
+ if (isPending) return 'Loading grants...'
+ if (isError) return ''
+ return 'Grants loaded'
+ }, [isPending, isFetchingNextPage, isError])
+
+ const isEmpty = !data || data.pages.length === 0 || data.pages[0].data.length === 0
+
+ if (!approval) return null
+
+ return (
+ <DialogContent size="small" {...props}>
+ <DialogHeader>
+ <DialogTitle>Member grants for {approval.app.name}</DialogTitle>
+ </DialogHeader>
+
+ <p aria-live="polite" className="sr-only">
+ {statusText}
+ </p>
+
+ {isPending && (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ </div>
+ )}
+
+ {isError && <AlertError subject="Failed to retrieve grants" error={error} />}
+
+ {isSuccess && (
+ <ScrollArea className="px-4 h-90">
+ <p
+ className={cn('text-sm text-foreground-lighter', !isEmpty && 'sr-only')}
+ aria-live="polite"
+ >
+ {isEmpty ? 'No grants have been authorized for this application.' : ''}
+ </p>
+
+ <Accordion type="multiple" className="divide-y! divide-border!">
+ {data.pages.map((page, pageIndex) => (
+ <Fragment key={pageIndex}>
+ {page.data.map((grant) => (
+ <GrantAccordionItem key={grant.grant_id} grant={grant} />
+ ))}
+ </Fragment>
+ ))}
+ </Accordion>
+ <p ref={sentinelRef} className="text-sm text-foreground-lighter">
+ {isFetchingNextPage ? 'Loading...' : ''}
+ </p>
+ </ScrollArea>
+ )}
+
+ <DialogFooter>
+ <DialogClose asChild>
+ <Button variant="default">Close</Button>
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ )
+}
+
+const GrantAccordionItem = ({ grant }: { grant: OAuthGrantItem }) => {
+ const isOrganizationBound = grant.kind === 'organization_bound'
+ const permissionCount = grant.approved_scopes.length
+
+ return (
+ <AccordionItem value={grant.grant_id} className="border-b-0">
+ <AccordionTrigger className="hover:no-underline">
+ {isOrganizationBound ? (
+ <Building2 size={16} className="shrink-0 text-foreground-lighter rotate-0!" />
+ ) : (
+ <User size={16} className="shrink-0 text-foreground-lighter rotate-0!" />
+ )}
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm text-foreground">{getGrantLabel(grant)}</p>
+ <p className="text-xs text-foreground-lighter">
+ {grant.projects == null
+ ? 'All projects'
+ : `${grant.projects.length} ${grant.projects.length === 1 ? 'project' : 'projects'}`}
+ {' · '}
+ {permissionCount} {permissionCount === 1 ? 'permission' : 'permissions'}
+ </p>
+ </div>
+ </AccordionTrigger>
+ <AccordionContent>
+ <div className="flex flex-col gap-3 pl-6">
+ {grant.projects != null && grant.projects.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <p className="font-mono text-[11px] uppercase tracking-wider text-foreground-light">
+ Projects
+ </p>
+ <p className="text-xs text-foreground">
+ {grant.projects.map((project) => project.name).join(', ')}
+ </p>
+ </div>
+ )}
+ <div className="flex flex-col gap-1">
+ <p className="font-mono text-[11px] uppercase tracking-wider text-foreground-light">
+ Permissions
+ </p>
+ <p className="text-xs text-foreground">{grant.approved_scopes.join(', ')}</p>
+ </div>
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ )
+}
+
+const getGrantLabel = (grant: OAuthGrantItem) => {
+ if (grant.user) return grant.user.email
+ return 'Organization-wide'
+}
diff --git a/apps/studio/data/oauth-apps/mocks.ts b/apps/studio/data/oauth-apps/mocks.ts
index eab1016a5fc..73164f9a56d 100644
--- a/apps/studio/data/oauth-apps/mocks.ts
+++ b/apps/studio/data/oauth-apps/mocks.ts
@@ -379,18 +379,20 @@ const MOCK_APP_GRANTS: Record<string, ListOrgAppGrantsResponse> = {
approved_scopes: ['database:read', 'database:write', 'projects:read'],
approved_at: '2026-08-18T09:12:00.000Z',
},
- {
- grant_id: 'grant-vercel-developer',
- kind: 'member_bound',
- user: {
- gotrue_id: 'b1d3e2f4-0000-4000-8000-000000000002',
- email: '[email protected]',
- avatar_url: 'https://avatars.example/developer.png',
- },
- projects: [{ ref: 'northwindcms1', name: 'northwind-cms' }],
- approved_scopes: ['projects:read'],
- approved_at: '2026-08-16T11:30:00.000Z',
- },
+ ...Array(50)
+ .keys()
+ .map((index) => ({
+ grant_id: `grant-vercel-developer-${index}`,
+ kind: 'member_bound' as const,
+ user: {
+ gotrue_id: `b1d3e2f4-0000-4000-8000-0000000000${index.toString().padStart(2, '0')}`,
+ email: `developer${index}@example.com`,
+ avatar_url: 'https://avatars.example/developer.png',
+ },
+ projects: [{ ref: 'northwindcms1', name: 'northwind-cms' }],
+ approved_scopes: ['projects:read'],
+ approved_at: '2026-08-16T11:30:00.000Z',
+ })),
],
pagination: { next_cursor: null },
},
diff --git a/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts b/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts
index 6cef0997500..a9aa919c126 100644
--- a/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts
+++ b/apps/studio/data/oauth-apps/oauth-apps-member-grants-query.ts
@@ -1,9 +1,9 @@
-import { useQuery } from '@tanstack/react-query'
+import { InfiniteData, useInfiniteQuery } from '@tanstack/react-query'
import { oauthAppsKeys } from './keys'
import { getMockOAuthAppGrants, USE_MOCKS } from './mocks'
import type { ListOrgAppGrantsResponse } from './types'
-import type { ResponseError, UseCustomQueryOptions } from '@/types'
+import type { ResponseError, UseCustomInfiniteQueryOptions } from '@/types'
export type OAuthAppMemberGrantsVariables = {
slug?: string
@@ -33,11 +33,19 @@ export const useOAuthAppMemberGrantsQuery = <TData = OAuthAppMemberGrantsData>(
{
enabled = true,
...options
- }: UseCustomQueryOptions<OAuthAppMemberGrantsData, OAuthAppMemberGrantsError, TData> = {}
+ }: UseCustomInfiniteQueryOptions<
+ OAuthAppMemberGrantsData,
+ OAuthAppMemberGrantsError,
+ InfiniteData<TData>,
+ readonly unknown[],
+ string | undefined
+ > = {}
) =>
- useQuery<OAuthAppMemberGrantsData, OAuthAppMemberGrantsError, TData>({
+ useInfiniteQuery({
queryKey: oauthAppsKeys.appMemberGrants(slug, appId, cursor),
- queryFn: () => getOAuthAppMemberGrants({ slug, appId, cursor }),
+ queryFn: ({ pageParam }) => getOAuthAppMemberGrants({ slug, appId, cursor: pageParam }),
+ initialPageParam: cursor,
+ getNextPageParam: (lastPage) => lastPage.pagination.next_cursor,
enabled: enabled && USE_MOCKS && Boolean(slug) && Boolean(appId),
...options,
})