GridHeaderActions.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // @ts-nocheck
  2. import { PermissionAction } from '@supabase/shared-types/out/constants'
  3. import { useParams } from 'common'
  4. import { Realtime } from 'icons'
  5. import { BookOpenText, Lightbulb, Lock, MoreVertical, PlusCircle, Unlock } from 'lucide-react'
  6. import Link from 'next/link'
  7. import { parseAsBoolean, useQueryState } from 'nuqs'
  8. import { useState } from 'react'
  9. import { toast } from 'sonner'
  10. import {
  11. Button,
  12. cn,
  13. DropdownMenu,
  14. DropdownMenuContent,
  15. DropdownMenuItem,
  16. DropdownMenuSeparator,
  17. DropdownMenuTrigger,
  18. Popover,
  19. PopoverContent,
  20. PopoverTrigger,
  21. Tooltip,
  22. TooltipContent,
  23. TooltipTrigger,
  24. } from 'ui'
  25. import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
  26. import { EnableIndexAdvisorDialog } from '../QueryPerformance/IndexAdvisor/EnableIndexAdvisorButton'
  27. import { RoleImpersonationPopover } from '../RoleImpersonationSelector/RoleImpersonationPopover'
  28. import { InsertButton } from './InsertButton'
  29. import { RealtimeToggleDialog } from './RealtimeToggleDialog'
  30. import { SecurityDefinerViewPopover } from './SecurityDefinerViewPopover'
  31. import { ViewEntityAutofixSecurityModal } from './ViewEntityAutofixSecurityModal'
  32. import { RefreshButton } from '@/components/grid/components/header/RefreshButton'
  33. import { useTableIndexAdvisor } from '@/components/grid/context/TableIndexAdvisorContext'
  34. import {
  35. getEntityLintDetails,
  36. getTablePoliciesUrl,
  37. } from '@/components/interfaces/TableGridEditor/TableEntity.utils'
  38. import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
  39. import { useDatabasePoliciesQuery } from '@/data/database-policies/database-policies-query'
  40. import { useIsTableRealtimeEnabled } from '@/data/database-publications/database-publications-query'
  41. import { useProjectLintsQuery } from '@/data/lint/lint-query'
  42. import {
  43. Entity,
  44. isTableLike,
  45. isForeignTable as isTableLikeForeignTable,
  46. isMaterializedView as isTableLikeMaterializedView,
  47. isView as isTableLikeView,
  48. } from '@/data/table-editor/table-editor-types'
  49. import { useTableUpdateMutation } from '@/data/tables/table-update-mutation'
  50. import { useSendEventMutation } from '@/data/telemetry/send-event-mutation'
  51. import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'
  52. import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
  53. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  54. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  55. import { useIsProtectedSchema } from '@/hooks/useProtectedSchemas'
  56. import { DOCS_URL } from '@/lib/constants'
  57. import { useTrack } from '@/lib/telemetry/track'
  58. import { useAppStateSnapshot } from '@/state/app-state'
  59. import { useTableEditorTableStateSnapshot } from '@/state/table-editor-table'
  60. export interface GridHeaderActionsProps {
  61. table: Entity
  62. isRefetching: boolean
  63. }
  64. export const GridHeaderActions = ({ table, isRefetching }: GridHeaderActionsProps) => {
  65. const track = useTrack()
  66. const { ref } = useParams()
  67. const appSnap = useAppStateSnapshot()
  68. const snap = useTableEditorTableStateSnapshot()
  69. const { data: project } = useSelectedProjectQuery()
  70. const { data: org } = useSelectedOrganizationQuery()
  71. const { mutate: sendEvent } = useSendEventMutation()
  72. const [rlsConfirmModalOpen, setRlsConfirmModalOpen] = useState(false)
  73. const [realtimeDialogOpen, setRealtimeDialogOpen] = useState(false)
  74. const [indexAdvisorDialogOpen, setIndexAdvisorDialogOpen] = useState(false)
  75. const [isAutofixViewSecurityModalOpen, setIsAutofixViewSecurityModalOpen] = useState(false)
  76. const [showWarning, setShowWarning] = useQueryState(
  77. 'showWarning',
  78. parseAsBoolean.withDefault(false)
  79. )
  80. // need project lints to get security status for views
  81. const { data: lints = [] } = useProjectLintsQuery({ projectRef: project?.ref })
  82. // Use table-specific index advisor context
  83. const { isAvailable: isIndexAdvisorAvailable, isEnabled: isIndexAdvisorEnabled } =
  84. useTableIndexAdvisor()
  85. const isTable = isTableLike(table)
  86. const isForeignTable = isTableLikeForeignTable(table)
  87. const isView = isTableLikeView(table)
  88. const isMaterializedView = isTableLikeMaterializedView(table)
  89. const { realtimeAll: realtimeEnabled } = useIsFeatureEnabled(['realtime:all'])
  90. const { isSchemaLocked } = useIsProtectedSchema({ schema: table.schema })
  91. const isRealtimeEnabled = useIsTableRealtimeEnabled({ id: table.id })
  92. const { mutate: updateTable, isPending: isUpdatingTable } = useTableUpdateMutation({
  93. onError: (error) => {
  94. toast.error(`Failed to toggle RLS: ${error.message}`)
  95. },
  96. onSettled: () => {
  97. closeConfirmModal()
  98. },
  99. })
  100. const showHeaderActions = snap.selectedRows.size === 0
  101. const projectRef = project?.ref
  102. const { data } = useDatabasePoliciesQuery({
  103. projectRef: project?.ref,
  104. connectionString: project?.connectionString,
  105. })
  106. const policies = (data ?? []).filter(
  107. (policy) => policy.schema === table.schema && policy.table === table.name
  108. )
  109. const { can: canSqlWriteTables, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
  110. PermissionAction.TENANT_SQL_ADMIN_WRITE,
  111. 'tables'
  112. )
  113. const { can: canSqlWriteColumns } = useAsyncCheckPermissions(
  114. PermissionAction.TENANT_SQL_ADMIN_WRITE,
  115. 'columns'
  116. )
  117. const isReadOnly = !isLoadingPermissions && !canSqlWriteTables && !canSqlWriteColumns
  118. // This will change when we allow autogenerated API docs for schemas other than `public`
  119. const doesHaveAutoGeneratedAPIDocs = table.schema === 'public'
  120. const { hasLint: tableHasLints } = getEntityLintDetails(
  121. table.name,
  122. 'rls_disabled_in_public',
  123. ['ERROR'],
  124. lints,
  125. table.schema
  126. )
  127. const { hasLint: viewHasLints, matchingLint: matchingViewLint } = getEntityLintDetails(
  128. table.name,
  129. 'security_definer_view',
  130. ['ERROR', 'WARN'],
  131. lints,
  132. table.schema
  133. )
  134. const { hasLint: materializedViewHasLints, matchingLint: matchingMaterializedViewLint } =
  135. getEntityLintDetails(
  136. table.name,
  137. 'materialized_view_in_api',
  138. ['ERROR', 'WARN'],
  139. lints,
  140. table.schema
  141. )
  142. const closeConfirmModal = () => {
  143. setRlsConfirmModalOpen(false)
  144. }
  145. const onViewAPIDocs = () => {
  146. appSnap.setActiveDocsSection(['entities', table.name])
  147. appSnap.setShowProjectApiDocs(true)
  148. sendEvent({
  149. action: 'api_docs_opened',
  150. properties: {
  151. source: 'table_editor',
  152. },
  153. groups: {
  154. project: ref ?? 'Unknown',
  155. organization: org?.slug ?? 'Unknown',
  156. },
  157. })
  158. }
  159. const onToggleRLS = async () => {
  160. const payload = {
  161. id: table.id,
  162. rls_enabled: !(isTable && table.rls_enabled),
  163. }
  164. updateTable({
  165. projectRef: project?.ref!,
  166. connectionString: project?.connectionString,
  167. id: table.id,
  168. name: table.name,
  169. schema: table.schema,
  170. payload: payload,
  171. })
  172. track('table_rls_enabled', {
  173. method: 'table_editor',
  174. schema_name: table.schema,
  175. table_name: table.name,
  176. })
  177. }
  178. return (
  179. <div className="sb-grid-header__inner">
  180. {showHeaderActions && (
  181. <div className="flex items-center gap-x-2">
  182. {isReadOnly && (
  183. <Tooltip>
  184. <TooltipTrigger asChild>
  185. <div className="border border-strong rounded-sm bg-overlay-hover px-3 py-1 text-xs">
  186. Viewing as read-only
  187. </div>
  188. </TooltipTrigger>
  189. <TooltipContent side="bottom">
  190. You need additional permissions to manage your project's data
  191. </TooltipContent>
  192. </Tooltip>
  193. )}
  194. {isTable && !isSchemaLocked ? (
  195. table.rls_enabled ? (
  196. <>
  197. {policies.length < 1 && !isSchemaLocked ? (
  198. <ButtonTooltip
  199. asChild
  200. type="default"
  201. className="group"
  202. icon={<PlusCircle strokeWidth={1.5} className="text-foreground-muted" />}
  203. tooltip={{
  204. content: {
  205. side: 'bottom',
  206. className: 'w-[280px]',
  207. text: 'RLS is enabled for this table, but no policies are set. Select queries may return 0 results.',
  208. },
  209. }}
  210. >
  211. <Link passHref href={getTablePoliciesUrl(projectRef, table.schema, table.name)}>
  212. Add RLS policy
  213. </Link>
  214. </ButtonTooltip>
  215. ) : (
  216. <Button
  217. asChild
  218. type={policies.length < 1 && !isSchemaLocked ? 'warning' : 'default'}
  219. className="group"
  220. icon={
  221. isSchemaLocked || policies.length > 0 ? (
  222. <div
  223. className={cn(
  224. 'flex items-center justify-center rounded-full bg-border-stronger h-[16px]',
  225. policies.length > 9 ? ' px-1' : 'w-[16px]',
  226. ''
  227. )}
  228. >
  229. <span className="text-[11px] text-foreground font-mono text-center">
  230. {policies.length}
  231. </span>
  232. </div>
  233. ) : (
  234. <PlusCircle strokeWidth={1.5} />
  235. )
  236. }
  237. >
  238. <Link passHref href={getTablePoliciesUrl(projectRef, table.schema, table.name)}>
  239. RLS {policies.length > 1 ? 'policies' : 'policy'}
  240. </Link>
  241. </Button>
  242. )}
  243. </>
  244. ) : tableHasLints ? (
  245. <Popover modal={false} open={showWarning} onOpenChange={setShowWarning}>
  246. <PopoverTrigger asChild>
  247. <Button type="danger" icon={<Lock strokeWidth={1.5} />}>
  248. RLS disabled
  249. </Button>
  250. </PopoverTrigger>
  251. <PopoverContent className="w-80 text-sm" align="end">
  252. <h4 className="flex items-center gap-2">
  253. <Lock size={16} /> Row Level Security (RLS)
  254. </h4>
  255. <div className="grid gap-2 mt-4 text-foreground-light text-xs">
  256. <p>
  257. You can restrict and control who can read, write and update data in this table
  258. using Row Level Security.
  259. </p>
  260. <p>
  261. With RLS enabled, anonymous users will not be able to read/write data in the
  262. table.
  263. </p>
  264. {!isSchemaLocked && (
  265. <Button
  266. type="default"
  267. className="mt-2 w-min"
  268. onClick={() => setRlsConfirmModalOpen(!rlsConfirmModalOpen)}
  269. >
  270. Enable RLS for this table
  271. </Button>
  272. )}
  273. </div>
  274. </PopoverContent>
  275. </Popover>
  276. ) : null
  277. ) : null}
  278. {isView && viewHasLints && (
  279. <SecurityDefinerViewPopover
  280. lint={matchingViewLint}
  281. onAutofix={() => {
  282. setIsAutofixViewSecurityModalOpen(true)
  283. }}
  284. />
  285. )}
  286. {isMaterializedView && materializedViewHasLints && (
  287. <SecurityDefinerViewPopover lint={matchingMaterializedViewLint} />
  288. )}
  289. {isForeignTable && table.schema === 'public' && (
  290. <Popover modal={false} open={showWarning} onOpenChange={setShowWarning}>
  291. <PopoverTrigger asChild>
  292. <Button type="warning" icon={<Unlock strokeWidth={1.5} />}>
  293. Unprotected Data API access
  294. </Button>
  295. </PopoverTrigger>
  296. <PopoverContent className="min-w-[395px] text-sm" align="end">
  297. <h3 className="flex items-center gap-2">
  298. <Unlock size={16} /> Secure Foreign table
  299. </h3>
  300. <div className="grid gap-2 mt-4 text-foreground-light text-sm">
  301. <p>
  302. Foreign tables do not enforce RLS, which may allow unrestricted access. To
  303. secure them, either move foreign tables to a private schema not exposed by
  304. PostgREST, or <a href="">disable PostgREST access</a> entirely.
  305. </p>
  306. <div className="mt-2">
  307. <Button type="default" asChild>
  308. <Link
  309. target="_blank"
  310. href={`${DOCS_URL}/guides/database/extensions/wrappers/overview#security`}
  311. >
  312. Learn more
  313. </Link>
  314. </Button>
  315. </div>
  316. </div>
  317. </PopoverContent>
  318. </Popover>
  319. )}
  320. <RoleImpersonationPopover header="View data as a role" align="center" />
  321. <DropdownMenu>
  322. <DropdownMenuTrigger asChild>
  323. <Button
  324. type="default"
  325. icon={<MoreVertical />}
  326. className="h-7 w-7"
  327. aria-label="More actions"
  328. />
  329. </DropdownMenuTrigger>
  330. <DropdownMenuContent className="w-48">
  331. {isTable && realtimeEnabled && (
  332. <DropdownMenuItem className="gap-x-2" onClick={() => setRealtimeDialogOpen(true)}>
  333. <Realtime size={14} className={isRealtimeEnabled ? 'text-brand' : ''} />
  334. <span>{isRealtimeEnabled ? 'Disable' : 'Enable'} Realtime</span>
  335. </DropdownMenuItem>
  336. )}
  337. {doesHaveAutoGeneratedAPIDocs && (
  338. <DropdownMenuItem className="gap-x-2" onClick={() => onViewAPIDocs()}>
  339. <BookOpenText size={14} />
  340. <span>View API docs</span>
  341. </DropdownMenuItem>
  342. )}
  343. {isTable && isIndexAdvisorAvailable && !isIndexAdvisorEnabled && (
  344. <>
  345. <DropdownMenuSeparator />
  346. <DropdownMenuItem
  347. className="gap-x-2"
  348. onClick={() => setIndexAdvisorDialogOpen(true)}
  349. >
  350. <Lightbulb size={14} />
  351. <span>Enable Index Advisor</span>
  352. </DropdownMenuItem>
  353. </>
  354. )}
  355. </DropdownMenuContent>
  356. </DropdownMenu>
  357. <RefreshButton tableId={table.id} isRefetching={isRefetching} />
  358. {showHeaderActions && <InsertButton />}
  359. </div>
  360. )}
  361. <ViewEntityAutofixSecurityModal
  362. table={table}
  363. isAutofixViewSecurityModalOpen={isAutofixViewSecurityModalOpen}
  364. setIsAutofixViewSecurityModalOpen={setIsAutofixViewSecurityModalOpen}
  365. />
  366. {isTable && (
  367. <ConfirmationModal
  368. visible={rlsConfirmModalOpen}
  369. variant={table.rls_enabled ? 'destructive' : 'default'}
  370. title={`${table.rls_enabled ? 'Disable' : 'Enable'} Row Level Security`}
  371. description={`Are you sure you want to ${
  372. table.rls_enabled ? 'disable' : 'enable'
  373. } Row Level Security for this table?`}
  374. confirmLabel={`${table.rls_enabled ? 'Disable' : 'Enable'} RLS`}
  375. confirmLabelLoading={`${table.rls_enabled ? 'Disabling' : 'Enabling'} RLS`}
  376. loading={isUpdatingTable}
  377. onCancel={closeConfirmModal}
  378. onConfirm={onToggleRLS}
  379. />
  380. )}
  381. <RealtimeToggleDialog
  382. table={table}
  383. open={realtimeDialogOpen}
  384. setOpen={setRealtimeDialogOpen}
  385. />
  386. <EnableIndexAdvisorDialog open={indexAdvisorDialogOpen} setOpen={setIndexAdvisorDialogOpen} />
  387. </div>
  388. )
  389. }