Skip to content

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

feat: UI for managing jit database access (#43735)

Etienne Stalmansc198a61951ac
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
index 73f75cfe798..987fee39f26 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
@@ -119,6 +119,12 @@ export const useIsPlatformWebhooksEnabled = () => {
return platformWebhooksEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]
}
+export const useIsJitDbAccessEnabled = () => {
+ const { flags } = useFeaturePreviewContext()
+ const jitDbAccessEnabled = useFlag('jitDbAccess')
+ return jitDbAccessEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]
+}
+
export const useIsTableFilterBarEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_TABLE_FILTER_BAR]
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
index 60cbac634f9..8e7b2a297ff 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewModal.tsx
@@ -29,6 +29,7 @@ import { AdvisorRulesPreview } from './AdvisorRulesPreview'
import { Branching2Preview } from './Branching2Preview'
import { CLSPreview } from './CLSPreview'
import { useFeaturePreviewContext, useFeaturePreviewModal } from './FeaturePreviewContext'
+import { JitDbAccessPreview } from './JitDbAccessPreview'
import { FloatingMobileToolbarPreview } from './FloatingMobileToolbarPreview'
import { PgDeltaDiffPreview } from './PgDeltaDiffPreview'
import { PlatformWebhooksPreview } from './PlatformWebhooksPreview'
@@ -49,6 +50,7 @@ const FEATURE_PREVIEW_KEY_TO_CONTENT: {
[LOCAL_STORAGE_KEYS.UI_PREVIEW_QUEUE_OPERATIONS]: <QueueOperationsPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_TABLE_FILTER_BAR]: <TableFilterBarPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]: <PlatformWebhooksPreview />,
+ [LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]: <JitDbAccessPreview />,
[LOCAL_STORAGE_KEYS.UI_PREVIEW_FLOATING_MOBILE_TOOLBAR]: <FloatingMobileToolbarPreview />,
}
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/JitDbAccessPreview.tsx b/apps/studio/components/interfaces/App/FeaturePreview/JitDbAccessPreview.tsx
new file mode 100644
index 00000000000..3724efd765a
--- /dev/null
+++ b/apps/studio/components/interfaces/App/FeaturePreview/JitDbAccessPreview.tsx
@@ -0,0 +1,23 @@
+import { useParams } from 'common'
+
+import { InlineLink } from '@/components/ui/InlineLink'
+
+export const JitDbAccessPreview = () => {
+ const { ref = '_' } = useParams()
+
+ return (
+ <div>
+ <p className="text-sm text-foreground-light mb-4">
+ Grant project members temporary database role access through Just-in-Time (JIT) controls in{' '}
+ <InlineLink href={`/project/${ref}/database/settings`}>Database Settings</InlineLink>.
+ </p>
+ <div className="space-y-2 !mt-4">
+ <p className="text-sm">Enabling this preview will:</p>
+ <ul className="list-disc pl-6 text-sm text-foreground-light space-y-1">
+ <li>Show JIT database access controls in Database Settings</li>
+ <li>Allow configuring role grants and member-level JIT rules</li>
+ </ul>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
index 19f506f33e7..f0e2fa61022 100644
--- a/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
+++ b/apps/studio/components/interfaces/App/FeaturePreview/useFeaturePreviews.ts
@@ -19,6 +19,7 @@ export const useFeaturePreviews = (): FeaturePreview[] => {
const pgDeltaDiffEnabled = useFlag('pgdeltaDiff')
const showFloatingMobileToolbar = useFlag('enableFloatingMobileToolbar')
const platformWebhooksEnabled = useFlag('platformWebhooks')
+ const jitDbAccessEnabled = useFlag('jitDbAccess')
return [
{
@@ -67,6 +68,15 @@ export const useFeaturePreviews = (): FeaturePreview[] => {
isDefaultOptIn: false,
enabled: platformWebhooksEnabled,
},
+ {
+ key: LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS,
+ name: 'JIT database access',
+ discussionsUrl: undefined,
+ isNew: true,
+ isPlatformOnly: true,
+ isDefaultOptIn: false,
+ enabled: jitDbAccessEnabled,
+ },
{
key: LOCAL_STORAGE_KEYS.UI_PREVIEW_API_SIDE_PANEL,
name: 'Project API documentation',
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.constants.ts b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.constants.ts
new file mode 100644
index 00000000000..86bbc9c2706
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.constants.ts
@@ -0,0 +1,12 @@
+import type { JitExpiryMode } from './JitDbAccess.types'
+
+export const JIT_EXPIRY_MODE_OPTIONS: Array<{ value: JitExpiryMode; label: string }> = [
+ { value: '1h', label: '1 hour' },
+ { value: '1d', label: '1 day' },
+ { value: '7d', label: '7 days' },
+ { value: '30d', label: '30 days' },
+ { value: 'custom', label: 'Custom' },
+ { value: 'never', label: 'Never' },
+]
+
+export const JIT_MAX_CUSTOM_EXPIRY_YEARS = 1
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.types.ts b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.types.ts
new file mode 100644
index 00000000000..8a098eff13e
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.types.ts
@@ -0,0 +1,50 @@
+export type JitExpiryMode = '1h' | '1d' | '7d' | '30d' | 'custom' | 'never'
+
+export type JitStatus = {
+ active: number
+ expired: number
+ activeIp: number
+ expiredIp: number
+}
+
+export type JitStatusBadge = {
+ label: string
+ variant: 'default' | 'success' | 'warning'
+}
+
+export type JitMemberOption = {
+ id: string
+ email: string
+ name?: string
+}
+
+export type JitRoleOption = {
+ id: string
+ label: string
+}
+
+export type JitRoleGrantDraft = {
+ roleId: string
+ enabled: boolean
+ expiryMode: JitExpiryMode
+ hasExpiry: boolean
+ expiry: string
+ hasIpRestriction: boolean
+ ipRanges: string
+}
+
+export type JitUserRuleDraft = {
+ memberId: string
+ grants: JitRoleGrantDraft[]
+}
+
+export type JitUserRule = {
+ id: string
+ memberId: string
+ email: string
+ name?: string
+ grants: JitRoleGrantDraft[]
+ status: JitStatus
+}
+
+export type SheetMode = 'add' | 'edit'
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.test.ts b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.test.ts
new file mode 100644
index 00000000000..b9230ed1b3a
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.test.ts
@@ -0,0 +1,156 @@
+import type { OrganizationMembersData } from 'data/organizations/organization-members-query'
+import dayjs from 'dayjs'
+import { describe, expect, it } from 'vitest'
+
+import type { JitUserRuleDraft } from './JitDbAccess.types'
+import {
+ computeStatusFromGrants,
+ createEmptyGrant,
+ getInvalidCidrs,
+ getJitMemberOptions,
+ getRelativeDatetimeByMode,
+ parseCommaSeparatedCidrs,
+ serializeDraftRolesForGrantMutation,
+} from './JitDbAccess.utils'
+
+describe('jitDbAccess.utils', () => {
+ it('returns empty expiry string for never/custom-only fallback modes', () => {
+ expect(getRelativeDatetimeByMode('never')).toBe('')
+ expect(getRelativeDatetimeByMode('custom')).toBe('')
+ })
+
+ it('creates future datetimes for preset expiry modes', () => {
+ const inOneHour = dayjs(getRelativeDatetimeByMode('1h'))
+ expect(inOneHour.isValid()).toBe(true)
+ expect(inOneHour.isAfter(dayjs())).toBe(true)
+ })
+
+ it('computes active and expired status counts including IP counts', () => {
+ const activeGrant = {
+ ...createEmptyGrant('role_active'),
+ enabled: true,
+ hasExpiry: true,
+ expiry: dayjs().add(1, 'day').toISOString(),
+ hasIpRestriction: true,
+ ipRanges: '192.0.2.0/24',
+ }
+
+ const expiredGrant = {
+ ...createEmptyGrant('role_expired'),
+ enabled: true,
+ hasExpiry: true,
+ expiry: dayjs().subtract(1, 'day').toISOString(),
+ hasIpRestriction: true,
+ ipRanges: '203.0.113.0/24',
+ }
+
+ const perpetualGrant = {
+ ...createEmptyGrant('role_never'),
+ enabled: true,
+ hasExpiry: false,
+ expiryMode: 'never' as const,
+ expiry: '',
+ }
+
+ expect(computeStatusFromGrants([activeGrant, expiredGrant, perpetualGrant])).toEqual({
+ active: 2,
+ expired: 1,
+ activeIp: 1,
+ expiredIp: 1,
+ })
+ })
+
+ it('parses comma-separated CIDR lists and trims whitespace', () => {
+ expect(parseCommaSeparatedCidrs('192.0.2.0/24, 2001:db8::/64 , ,203.0.113.4/32')).toEqual([
+ '192.0.2.0/24',
+ '2001:db8::/64',
+ '203.0.113.4/32',
+ ])
+ })
+
+ it('returns invalid CIDRs from comma-separated input', () => {
+ expect(
+ getInvalidCidrs('192.0.2.0/24, not-a-cidr, 10.0.0.1/33, 2001:db8::/64, 2001:db8::/129')
+ ).toEqual(['not-a-cidr', '10.0.0.1/33', '2001:db8::/129'])
+ })
+})
+
+describe('serializeDraftRolesForGrantMutation', () => {
+ it('serializes role expiry and IP restrictions for grant mutation payload', () => {
+ const expiry = '2026-06-01T12:00:00.000Z'
+ const draft: JitUserRuleDraft = {
+ memberId: 'user-1',
+ grants: [
+ {
+ ...createEmptyGrant('postgres'),
+ enabled: true,
+ hasExpiry: true,
+ expiryMode: 'custom',
+ expiry,
+ hasIpRestriction: true,
+ ipRanges: '192.0.2.0/24, 2001:db8::/64',
+ },
+ {
+ ...createEmptyGrant('supabase_read_only_user'),
+ enabled: true,
+ hasExpiry: false,
+ expiryMode: 'never',
+ expiry: '',
+ },
+ {
+ ...createEmptyGrant('ignored_disabled'),
+ enabled: false,
+ },
+ ],
+ }
+
+ expect(serializeDraftRolesForGrantMutation(draft)).toEqual([
+ {
+ role: 'postgres',
+ expires_at: dayjs(expiry).unix(),
+ allowed_networks: {
+ allowed_cidrs: [{ cidr: '192.0.2.0/24' }],
+ allowed_cidrs_v6: [{ cidr: '2001:db8::/64' }],
+ },
+ },
+ {
+ role: 'supabase_read_only_user',
+ },
+ ])
+ })
+})
+
+describe('getJitMemberOptions', () => {
+ it('excludes invited org members without gotrue IDs from selectable options', () => {
+ const organizationMembers: OrganizationMembersData = [
+ {
+ gotrue_id: 'de305d54-75b4-431b-adb2-eb6b9e546014',
+ primary_email: '[email protected]',
+ username: 'Active User',
+ is_sso_user: false,
+ mfa_enabled: false,
+ metadata: {},
+ role_ids: [],
+ },
+ {
+ gotrue_id: '',
+ invited_id: 123,
+ invited_at: '2026-03-01T00:00:00.000Z',
+ primary_email: '[email protected]',
+ username: 'e',
+ is_sso_user: false,
+ mfa_enabled: false,
+ metadata: {},
+ role_ids: [],
+ },
+ ]
+
+ expect(getJitMemberOptions(organizationMembers, [])).toEqual([
+ {
+ id: 'de305d54-75b4-431b-adb2-eb6b9e546014',
+ email: '[email protected]',
+ name: 'Active User',
+ },
+ ])
+ })
+})
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.ts b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.ts
new file mode 100644
index 00000000000..88778bc3d9b
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccess.utils.ts
@@ -0,0 +1,324 @@
+import { type DatabaseRolesData, type PgRole } from 'data/database-roles/database-roles-query'
+import type { JitDbAccessMembersData } from 'data/jit-db-access/jit-db-access-members-query'
+import type { OrganizationMembersData } from 'data/organizations/organization-members-query'
+import type { ProjectMembersData } from 'data/projects/project-members-query'
+import dayjs from 'dayjs'
+import { IPv4CidrRange, IPv6CidrRange } from 'ip-num'
+
+import type {
+ JitExpiryMode,
+ JitMemberOption,
+ JitRoleGrantDraft,
+ JitRoleOption,
+ JitStatus,
+ JitStatusBadge,
+ JitUserRule,
+ JitUserRuleDraft,
+} from './JitDbAccess.types'
+
+export function getRelativeDatetimeByMode(mode: JitExpiryMode) {
+ if (mode === '1h') return dayjs().add(1, 'hour').toISOString()
+ if (mode === '1d') return dayjs().add(1, 'day').toISOString()
+ if (mode === '7d') return dayjs().add(7, 'day').toISOString()
+ if (mode === '30d') return dayjs().add(30, 'day').toISOString()
+ return ''
+}
+
+function inferExpiryMode(grant: Pick<JitRoleGrantDraft, 'hasExpiry'>): JitExpiryMode {
+ if (!grant.hasExpiry) return 'never'
+ return 'custom'
+}
+
+export function createEmptyGrant(roleId: string): JitRoleGrantDraft {
+ return {
+ roleId,
+ enabled: false,
+ expiryMode: '1h',
+ hasExpiry: true,
+ expiry: getRelativeDatetimeByMode('1h'),
+ hasIpRestriction: false,
+ ipRanges: '',
+ }
+}
+
+function cloneGrants(grants: JitRoleGrantDraft[]) {
+ return grants.map((grant) => ({ ...grant }))
+}
+
+export function createDraft(roleIds: string[]): JitUserRuleDraft {
+ return { memberId: '', grants: roleIds.map((roleId) => createEmptyGrant(roleId)) }
+}
+
+function mergeRoleIds(baseRoleIds: string[], extraRoleIds: string[]) {
+ const seen = new Set<string>()
+ const merged: string[] = []
+
+ for (const roleId of [...baseRoleIds, ...extraRoleIds]) {
+ if (seen.has(roleId)) continue
+ seen.add(roleId)
+ merged.push(roleId)
+ }
+
+ return merged
+}
+
+export function draftFromRule(rule: JitUserRule, baseRoleIds: string[]): JitUserRuleDraft {
+ const byRoleId = new Map(rule.grants.map((grant) => [grant.roleId, grant]))
+ const mergedRoleIds = mergeRoleIds(
+ baseRoleIds,
+ rule.grants.map((grant) => grant.roleId)
+ )
+
+ return {
+ memberId: rule.memberId,
+ grants: mergedRoleIds.map((roleId) => {
+ const nextGrant = {
+ ...createEmptyGrant(roleId),
+ ...(byRoleId.get(roleId) ?? {}),
+ }
+
+ return {
+ ...nextGrant,
+ expiryMode: inferExpiryMode(nextGrant),
+ }
+ }),
+ }
+}
+
+export function computeStatusFromGrants(grants: JitRoleGrantDraft[]): JitStatus {
+ const enabledGrants = grants.filter((grant) => grant.enabled)
+
+ let active = 0
+ let expired = 0
+ let activeIp = 0
+ let expiredIp = 0
+
+ enabledGrants.forEach((grant) => {
+ const hasIp = grant.hasIpRestriction && grant.ipRanges.trim().length > 0
+
+ if (!grant.hasExpiry || !grant.expiry) {
+ active += 1
+ if (hasIp) activeIp += 1
+ return
+ }
+
+ const isExpired = dayjs(grant.expiry).isValid() && dayjs(grant.expiry).isBefore(dayjs())
+
+ if (isExpired) {
+ expired += 1
+ if (hasIp) expiredIp += 1
+ return
+ }
+
+ active += 1
+ if (hasIp) activeIp += 1
+ })
+
+ return { active, expired, activeIp, expiredIp }
+}
+
+function formatBadgeLabel(raw: string, showCount: boolean): string {
+ if (showCount) return raw
+ // If only one in count:
+ // Strip leading "N " and "· N " count segments, then capitalize first letter
+ return raw
+ .replace(/^\d+\s/, '')
+ .replace(/·\s*\d+\s/g, '· ')
+ .replace(/^./, (c) => c.toUpperCase())
+}
+
+export function getJitStatusDisplay(status: JitStatus): { badges: JitStatusBadge[] } {
+ const { active, expired, activeIp } = status
+ const badges: JitStatusBadge[] = []
+ const showCount = (active > 0 ? 1 : 0) + (expired > 0 ? 1 : 0) > 1
+
+ if (active > 0) {
+ const raw = activeIp > 0 ? `${active} active · ${activeIp} IP` : `${active} active`
+ badges.push({ label: formatBadgeLabel(raw, showCount), variant: 'success' })
+ }
+
+ if (expired > 0) {
+ const raw = `${expired} expired`
+ badges.push({ label: formatBadgeLabel(raw, showCount), variant: 'default' })
+ }
+
+ return { badges }
+}
+
+function toUnixSeconds(datetimeIso: string) {
+ const value = dayjs(datetimeIso)
+ if (!value.isValid()) return undefined
+ return value.unix()
+}
+
+export function parseCommaSeparatedCidrs(value: string) {
+ return value
+ .split(',')
+ .map((item) => item.trim())
+ .filter((item) => item.length > 0)
+}
+
+function isValidCidr(value: string) {
+ try {
+ if (value.includes(':')) {
+ IPv6CidrRange.fromCidr(value)
+ return true
+ }
+
+ IPv4CidrRange.fromCidr(value)
+ return true
+ } catch {
+ return false
+ }
+}
+
+export function getInvalidCidrs(value: string) {
+ return parseCommaSeparatedCidrs(value).filter((cidr) => !isValidCidr(cidr))
+}
+
+function isAssignableJitRole(role: PgRole) {
+ return (
+ role.canLogin &&
+ !role.isSuperuser &&
+ !role.name.startsWith('pg_') &&
+ (!role.name.startsWith('supabase_') || role.name === 'supabase_read_only_user') &&
+ !['pgbouncer', 'authenticator'].includes(role.name)
+ )
+}
+
+function serializeAllowedNetworks(roleObj: {
+ allowed_networks?: {
+ allowed_cidrs?: Array<{ cidr: string }>
+ allowed_cidrs_v6?: Array<{ cidr: string }>
+ }
+}) {
+ const cidrs = roleObj.allowed_networks?.allowed_cidrs?.map((item) => item.cidr) ?? []
+ const cidrsV6 = roleObj.allowed_networks?.allowed_cidrs_v6?.map((item) => item.cidr) ?? []
+ return [...cidrs, ...cidrsV6]
+}
+
+export function getAssignableJitRoleOptions(
+ databaseRoles?: DatabaseRolesData | null
+): JitRoleOption[] {
+ return (
+ databaseRoles
+ ?.filter(isAssignableJitRole)
+ .map((role) => ({ id: role.name, label: role.name }))
+ .sort((a, b) => a.label.localeCompare(b.label)) ?? []
+ )
+}
+
+export function getJitMemberOptions(
+ organizationMembers?: OrganizationMembersData | null,
+ projectMembers?: ProjectMembersData | null
+): JitMemberOption[] {
+ const byId = new Map<string, JitMemberOption>()
+
+ for (const member of organizationMembers ?? []) {
+ // JIT rules should only target accepted org members (invites can be expired/pending).
+ if (!member.gotrue_id) continue
+
+ const id = member.gotrue_id ?? member.primary_email
+ if (!id) continue
+
+ byId.set(id, {
+ id,
+ email: member.primary_email ?? id,
+ name: member.username || undefined,
+ })
+ }
+
+ for (const member of projectMembers ?? []) {
+ const id = member.user_id ?? member.primary_email
+ if (!id) continue
+
+ byId.set(id, {
+ id,
+ email: member.primary_email ?? byId.get(id)?.email ?? id,
+ name: member.username ?? byId.get(id)?.name,
+ })
+ }
+
+ return Array.from(byId.values()).sort((a, b) => a.email.localeCompare(b.email))
+}
+
+export function mapJitMembersToUserRules(
+ jitMembers: JitDbAccessMembersData | undefined,
+ projectMembers: ProjectMembersData | undefined,
+ roleOptions: JitRoleOption[]
+): JitUserRule[] {
+ const memberMap = new Map((projectMembers ?? []).map((member) => [member.user_id, member]))
+ const baseRoleIds = roleOptions.map((role) => role.id)
+
+ return (jitMembers ?? []).map((item) => {
+ const mappedMember = memberMap.get(item.user_id)
+ const assignedRoles: JitRoleGrantDraft[] = (item.user_roles ?? []).map((roleObj) => {
+ const expiresAt = typeof roleObj.expires_at === 'number' ? roleObj.expires_at : undefined
+ const hasExpiry = typeof expiresAt === 'number'
+ const allowedNetworks = serializeAllowedNetworks(roleObj)
+
+ return {
+ ...createEmptyGrant(roleObj.role),
+ roleId: roleObj.role,
+ enabled: true,
+ hasExpiry,
+ expiryMode: hasExpiry ? 'custom' : 'never',
+ expiry: hasExpiry ? new Date(expiresAt * 1000).toISOString() : '',
+ hasIpRestriction: allowedNetworks.length > 0,
+ ipRanges: allowedNetworks.join(', '),
+ }
+ })
+
+ const assignedByRoleId = new Map(assignedRoles.map((grant) => [grant.roleId, grant]))
+ const allRoleIds = mergeRoleIds(
+ baseRoleIds,
+ assignedRoles.map((grant) => grant.roleId)
+ )
+ const grants = allRoleIds.map((roleId) => ({
+ ...createEmptyGrant(roleId),
+ ...(assignedByRoleId.get(roleId) ?? {}),
+ roleId,
+ }))
+
+ const email = mappedMember?.primary_email ?? item.user_id
+ const name = mappedMember?.username ?? undefined
+
+ return {
+ id: item.user_id,
+ memberId: item.user_id,
+ email,
+ name,
+ grants: cloneGrants(grants),
+ status: computeStatusFromGrants(grants),
+ }
+ })
+}
+
+export function serializeDraftRolesForGrantMutation(draft: JitUserRuleDraft) {
+ const serializeAllowedNetworks = (value: string) => {
+ const cidrs = parseCommaSeparatedCidrs(value)
+ if (cidrs.length === 0) return undefined
+
+ const allowed_cidrs = cidrs.filter((cidr) => !cidr.includes(':')).map((cidr) => ({ cidr }))
+ const allowed_cidrs_v6 = cidrs.filter((cidr) => cidr.includes(':')).map((cidr) => ({ cidr }))
+
+ if (allowed_cidrs.length === 0 && allowed_cidrs_v6.length === 0) return undefined
+
+ return {
+ ...(allowed_cidrs.length > 0 ? { allowed_cidrs } : {}),
+ ...(allowed_cidrs_v6.length > 0 ? { allowed_cidrs_v6 } : {}),
+ }
+ }
+
+ return draft.grants
+ .filter((grant) => grant.enabled)
+ .map((grant) => {
+ const expires_at = grant.hasExpiry ? toUnixSeconds(grant.expiry) : undefined
+ const allowed_networks = serializeAllowedNetworks(grant.ipRanges)
+ return {
+ role: grant.roleId,
+ ...(typeof expires_at === 'number' ? { expires_at } : {}),
+ ...(allowed_networks ? { allowed_networks } : {}),
+ }
+ })
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx
new file mode 100644
index 00000000000..46c0b08c55d
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration.tsx
@@ -0,0 +1,436 @@
+import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/constants'
+import { useParams } from 'common'
+import { SupportLink } from 'components/interfaces/Support/SupportLink'
+import AlertError from 'components/ui/AlertError'
+import { DocsButton } from 'components/ui/DocsButton'
+import { InlineLinkClassName } from 'components/ui/InlineLink'
+import { useDatabaseRolesQuery } from 'data/database-roles/database-roles-query'
+import { useJitDbAccessMembersQuery } from 'data/jit-db-access/jit-db-access-members-query'
+import { useJitDbAccessQuery } from 'data/jit-db-access/jit-db-access-query'
+import { useJitDbAccessRevokeMutation } from 'data/jit-db-access/jit-db-access-revoke-mutation'
+import { useJitDbAccessUpdateMutation } from 'data/jit-db-access/jit-db-access-update-mutation'
+import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'
+import { useProjectMembersQuery } from 'data/projects/project-members-query'
+import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import { DOCS_URL } from 'lib/constants'
+import { Loader2 } from 'lucide-react'
+import Link from 'next/link'
+import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
+import { useEffect, useMemo, useState } from 'react'
+import { toast } from 'sonner'
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+ Card,
+ CardContent,
+ Switch,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import {
+ PageSection,
+ PageSectionContent,
+ PageSectionMeta,
+ PageSectionSummary,
+ PageSectionTitle,
+} from 'ui-patterns'
+import { Admonition } from 'ui-patterns/admonition'
+import { FormLayout } from 'ui-patterns/form/Layout/FormLayout'
+
+import type { JitUserRule, SheetMode } from './JitDbAccess.types'
+import {
+ getAssignableJitRoleOptions,
+ getJitMemberOptions,
+ mapJitMembersToUserRules,
+} from './JitDbAccess.utils'
+import { JitDbAccessDeleteDialog } from './JitDbAccessDeleteDialog'
+import { JitDbAccessRuleSheet } from './JitDbAccessRuleSheet'
+import { JitDbAccessRulesTable } from './JitDbAccessRulesTable'
+
+export const JitDbAccessConfiguration = () => {
+ const { ref } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+ const { data: organization } = useSelectedOrganizationQuery()
+
+ const [enabled, setEnabled] = useState(false)
+ const [, setShowCreateRuleSheet] = useQueryState('jit_new', parseAsBoolean.withDefault(false))
+ const [ruleIdToEdit, setRuleIdToEdit] = useQueryState('jit_edit', parseAsString)
+ const [showEnableJitDialog, setShowEnableJitDialog] = useState(false)
+ const [selectedUserToDelete, setSelectedUserToDelete] = useState<JitUserRule | null>(null)
+
+ const {
+ data: jitDbAccessConfiguration,
+ error: jitDbAccessConfigurationError,
+ isError: isErrorJitDbAccessConfiguration,
+ isLoading: isLoadingConfiguration,
+ isSuccess: isSuccessConfiguration,
+ } = useJitDbAccessQuery({ projectRef: ref })
+
+ const {
+ data: jitMembers,
+ error: jitMembersError,
+ isError: isErrorJitMembers,
+ isLoading: isLoadingJitMembers,
+ } = useJitDbAccessMembersQuery({ projectRef: ref })
+
+ const { data: projectMembers, isLoading: isLoadingProjectMembers } = useProjectMembersQuery({
+ projectRef: ref,
+ })
+
+ const { data: organizationMembers, isLoading: isLoadingOrganizationMembers } =
+ useOrganizationMembersQuery({ slug: organization?.slug })
+
+ const { data: databaseRoles, isLoading: isLoadingDatabaseRoles } = useDatabaseRolesQuery({
+ projectRef: ref,
+ connectionString: project?.connectionString,
+ })
+
+ const { can: canUpdateJitDbAccess } = useAsyncCheckPermissions(
+ PermissionAction.UPDATE,
+ 'projects',
+ { resource: { project_id: project?.id } }
+ )
+
+ const { mutate: updateJitDbAccess, isPending: isUpdatingJitDbAccess } =
+ useJitDbAccessUpdateMutation({
+ onSuccess: (_, variables) => {
+ const nextEnabled = variables.requestedConfig.state === 'enabled'
+
+ if (nextEnabled) {
+ toast.success('JIT access enabled')
+ } else {
+ toast.success(
+ activeRuleCount > 0
+ ? `JIT access disabled. ${activeRuleCount} configured member${activeRuleCount === 1 ? '' : 's'} can no longer request temporary database access.`
+ : 'JIT access disabled'
+ )
+ }
+ },
+ onError: (error) => {
+ setEnabled(initialIsEnabled ?? false)
+ toast.error(`Failed to update just-in-time (JIT) database access: ${error.message}`)
+ },
+ })
+
+ const { mutate: revokeUserAccess, isPending: isRevokingAccess } = useJitDbAccessRevokeMutation({
+ onSuccess: (_, variables) => {
+ toast.success('Successfully revoked user access')
+ setSelectedUserToDelete(null)
+ if (ruleIdToEdit === variables.userId) resetSheetState()
+ },
+ onError: (error) => {
+ toast.error(`Failed to revoke user access: ${error.message}`)
+ },
+ })
+
+ const isMutating = isUpdatingJitDbAccess || isRevokingAccess
+ const disableRuleActions = isMutating || isLoadingDatabaseRoles || isLoadingOrganizationMembers
+ const isRulesLoading = isLoadingJitMembers || isLoadingProjectMembers
+
+ const initialIsEnabled =
+ isSuccessConfiguration &&
+ !!jitDbAccessConfiguration &&
+ 'appliedSuccessfully' in jitDbAccessConfiguration &&
+ jitDbAccessConfiguration.appliedSuccessfully &&
+ 'state' in jitDbAccessConfiguration &&
+ (jitDbAccessConfiguration as { state: string }).state === 'enabled'
+
+ const hasAccessToJitDbAccess = !(
+ jitDbAccessConfiguration !== undefined &&
+ 'isUnavailable' in jitDbAccessConfiguration &&
+ jitDbAccessConfiguration.isUnavailable
+ )
+
+ const roleOptions = useMemo(() => getAssignableJitRoleOptions(databaseRoles), [databaseRoles])
+
+ const users = useMemo(
+ () => mapJitMembersToUserRules(jitMembers, projectMembers, roleOptions),
+ [jitMembers, projectMembers, roleOptions]
+ )
+
+ const allMembers = useMemo(
+ () => getJitMemberOptions(organizationMembers, projectMembers),
+ [organizationMembers, projectMembers]
+ )
+
+ const editingUser = useMemo(
+ () => users.find((user) => user.id === ruleIdToEdit) ?? null,
+ [users, ruleIdToEdit]
+ )
+
+ const sheetMode: SheetMode = ruleIdToEdit ? 'edit' : 'add'
+
+ const membersWithRules = useMemo(() => new Set(users.map((user) => user.memberId)), [users])
+
+ const availableMembersForAdd = useMemo(
+ () => allMembers.filter((member) => !membersWithRules.has(member.id)),
+ [allMembers, membersWithRules]
+ )
+
+ const memberOptionsForSheet = useMemo(() => {
+ if (sheetMode !== 'edit') return availableMembersForAdd
+ if (!editingUser) return allMembers
+
+ if (allMembers.some((member) => member.id === editingUser.memberId)) return allMembers
+
+ return [
+ {
+ id: editingUser.memberId,
+ email: editingUser.email,
+ name: editingUser.name,
+ },
+ ...allMembers,
+ ]
+ }, [sheetMode, availableMembersForAdd, allMembers, editingUser])
+
+ const activeRuleCount = useMemo(
+ () => users.filter((user) => user.status.active > 0).length,
+ [users]
+ )
+
+ const resetSheetState = () => {
+ setShowCreateRuleSheet(false)
+ setRuleIdToEdit(null)
+ }
+
+ const submitJitToggle = (nextEnabled: boolean) => {
+ if (!ref) return console.error('Project ref is required')
+
+ setEnabled(nextEnabled)
+ updateJitDbAccess({
+ projectRef: ref,
+ requestedConfig: { state: nextEnabled ? 'enabled' : 'disabled' },
+ })
+ }
+
+ const handleJitToggleChange = (checked: boolean) => {
+ if (!hasAccessToJitDbAccess || !canUpdateJitDbAccess) return
+
+ if (checked && !enabled) {
+ if (activeRuleCount > 0) {
+ return setShowEnableJitDialog(true)
+ }
+ return submitJitToggle(true)
+ }
+
+ if (!checked && enabled) {
+ submitJitToggle(false)
+ }
+ }
+
+ const handleConfirmEnableJit = () => {
+ setShowEnableJitDialog(false)
+ submitJitToggle(true)
+ }
+
+ const openAddRuleSheet = () => {
+ if (!canUpdateJitDbAccess) return
+ setRuleIdToEdit(null)
+ setShowCreateRuleSheet(true)
+ }
+
+ const openEditRuleSheet = (user: JitUserRule) => {
+ if (!canUpdateJitDbAccess) return
+ setShowCreateRuleSheet(false)
+ setRuleIdToEdit(user.id)
+ }
+
+ const openDeleteDialog = (user: JitUserRule) => {
+ if (!canUpdateJitDbAccess) return
+ setSelectedUserToDelete(user)
+ }
+
+ const handleConfirmDelete = () => {
+ if (!ref) return console.error('Project ref is required')
+ if (!selectedUserToDelete) return toast.error('User is required')
+ revokeUserAccess({ projectRef: ref, userId: selectedUserToDelete.memberId })
+ }
+
+ const switchDisabled = isLoadingConfiguration || isUpdatingJitDbAccess || !canUpdateJitDbAccess
+ const switchTooltipText = !canUpdateJitDbAccess ? 'Additional permissions required' : undefined
+
+ const showToggleFailedWarning =
+ isSuccessConfiguration &&
+ !!jitDbAccessConfiguration &&
+ 'appliedSuccessfully' in jitDbAccessConfiguration &&
+ !jitDbAccessConfiguration.appliedSuccessfully
+
+ useEffect(() => {
+ if (!isLoadingConfiguration && jitDbAccessConfiguration) {
+ setEnabled(initialIsEnabled ?? false)
+ }
+ }, [initialIsEnabled, isLoadingConfiguration, jitDbAccessConfiguration])
+
+ return (
+ <>
+ <PageSection id="jit-db-access-configuration">
+ <PageSectionMeta>
+ <PageSectionSummary>
+ <PageSectionTitle>Just-in-Time (JIT)</PageSectionTitle>
+ </PageSectionSummary>
+ <DocsButton href={`${DOCS_URL}/guides/platform/just-in-time-database-access`} />
+ </PageSectionMeta>
+
+ <PageSectionContent className="space-y-4">
+ {isErrorJitDbAccessConfiguration && (
+ <AlertError
+ projectRef={ref}
+ subject="Failed to retrieve JIT database access configuration"
+ error={jitDbAccessConfigurationError as { message: string } | null}
+ />
+ )}
+
+ {!isErrorJitDbAccessConfiguration && !hasAccessToJitDbAccess && (
+ <Admonition
+ type="note"
+ layout="responsive"
+ title="Postgres upgrade required"
+ description="Just-in-time access requires a newer Postgres version. Upgrade your project’s Postgres version to enable JIT access."
+ actions={
+ ref ? (
+ <Button type="default" asChild>
+ <Link href={`/project/${ref}/settings/infrastructure`}>Upgrade Postgres</Link>
+ </Button>
+ ) : undefined
+ }
+ />
+ )}
+
+ {!isErrorJitDbAccessConfiguration && hasAccessToJitDbAccess && (
+ <Card>
+ <CardContent className="space-y-4">
+ <FormLayout
+ layout="flex-row-reverse"
+ label="Enable JIT access"
+ description="Allow configured project members to request temporary database access."
+ >
+ <div className="flex w-fit flex-shrink-0 items-center justify-end gap-2">
+ {(isLoadingConfiguration || isUpdatingJitDbAccess) && (
+ <Loader2
+ className="animate-spin text-foreground-muted/50"
+ strokeWidth={2}
+ size={16}
+ />
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* [Joshen] Added div as tooltip is messing with data state property of toggle */}
+ <div>
+ <Switch
+ size="large"
+ checked={enabled}
+ onCheckedChange={handleJitToggleChange}
+ disabled={switchDisabled}
+ />
+ </div>
+ </TooltipTrigger>
+ {switchTooltipText && (
+ <TooltipContent side="bottom">{switchTooltipText}</TooltipContent>
+ )}
+ </Tooltip>
+ </div>
+ </FormLayout>
+ </CardContent>
+ {showToggleFailedWarning && (
+ <Admonition
+ type="warning"
+ layout="horizontal"
+ title="JIT access update failed"
+ description={
+ <>
+ The change didn’t apply. Try turning JIT access on or off again, or{' '}
+ <SupportLink
+ queryParams={{
+ category: SupportCategories.DASHBOARD_BUG,
+ subject: 'JIT access was not updated successfully',
+ }}
+ className={InlineLinkClassName}
+ >
+ contact support
+ </SupportLink>{' '}
+ if the issue persists.
+ </>
+ }
+ className="mb-0 rounded-none border-0"
+ />
+ )}
+ </Card>
+ )}
+
+ {enabled && hasAccessToJitDbAccess && !isUpdatingJitDbAccess && (
+ <>
+ {isErrorJitMembers && (
+ <AlertError
+ projectRef={ref}
+ subject="Failed to retrieve JIT access rules"
+ error={jitMembersError as { message: string } | null}
+ />
+ )}
+
+ <JitDbAccessRulesTable
+ users={users}
+ isLoading={isRulesLoading}
+ canUpdate={!!canUpdateJitDbAccess}
+ disableActions={disableRuleActions}
+ allProjectMembersHaveRules={availableMembersForAdd.length === 0}
+ onAddRule={openAddRuleSheet}
+ onEditRule={openEditRuleSheet}
+ onDeleteRule={openDeleteDialog}
+ />
+ </>
+ )}
+ </PageSectionContent>
+ </PageSection>
+
+ <JitDbAccessRuleSheet
+ memberOptions={memberOptionsForSheet}
+ membersWithRules={membersWithRules}
+ availableMembersForAddCount={availableMembersForAdd.length}
+ />
+
+ <JitDbAccessDeleteDialog
+ user={selectedUserToDelete}
+ isDeleting={isRevokingAccess}
+ onClose={() => setSelectedUserToDelete(null)}
+ onConfirm={handleConfirmDelete}
+ />
+
+ <AlertDialog open={showEnableJitDialog} onOpenChange={setShowEnableJitDialog}>
+ <AlertDialogContent size="small">
+ <AlertDialogHeader>
+ <AlertDialogTitle>JIT access will activate existing rules</AlertDialogTitle>
+ <AlertDialogDescription asChild>
+ <div className="text-sm">
+ <p>
+ Enabling JIT will allow {activeRuleCount} configured member
+ {activeRuleCount === 1 ? '' : 's'} to request temporary database access
+ immediately.
+ </p>
+ </div>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isUpdatingJitDbAccess}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="warning"
+ disabled={isUpdatingJitDbAccess}
+ onClick={handleConfirmEnableJit}
+ >
+ Enable JIT access
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx
new file mode 100644
index 00000000000..6f04c91e698
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessDeleteDialog.tsx
@@ -0,0 +1,66 @@
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+} from 'ui'
+
+import type { JitUserRule } from './JitDbAccess.types'
+
+interface JitDbAccessDeleteDialogProps {
+ user: JitUserRule | null
+ isDeleting: boolean
+ onClose: () => void
+ onConfirm: () => void
+}
+
+export function JitDbAccessDeleteDialog({
+ user,
+ isDeleting = false,
+ onClose,
+ onConfirm,
+}: JitDbAccessDeleteDialogProps) {
+ const userDisplayName = user?.name?.trim() || user?.email || 'this user'
+
+ return (
+ <AlertDialog open={!!user} onOpenChange={(open) => !open && !isDeleting && onClose()}>
+ <AlertDialogContent size="medium">
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete JIT access rule</AlertDialogTitle>
+ <AlertDialogDescription asChild>
+ <div className="space-y-2 text-sm">
+ <p>
+ Remove the JIT access rule for{' '}
+ <strong className="text-foreground">{userDisplayName}</strong>?
+ </p>
+ <p>
+ This revokes any assigned database roles for this member and removes their JIT
+ access configuration.
+ </p>
+ </div>
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction variant="danger" asChild>
+ <Button
+ loading={isDeleting}
+ disabled={isDeleting}
+ onClick={(e) => {
+ e.preventDefault()
+ onConfirm()
+ }}
+ >
+ Delete rule
+ </Button>
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRoleGrantFields.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRoleGrantFields.tsx
new file mode 100644
index 00000000000..ba7e7926fb4
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRoleGrantFields.tsx
@@ -0,0 +1,237 @@
+import { DatePicker } from 'components/ui/DatePicker'
+import { InlineLink } from 'components/ui/InlineLink'
+import dayjs from 'dayjs'
+import { DOCS_URL } from 'lib/constants'
+import {
+ Checkbox_Shadcn_,
+ Input_Shadcn_,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ WarningIcon,
+} from 'ui'
+import { TimestampInfo } from 'ui-patterns'
+import { Admonition } from 'ui-patterns/admonition'
+
+import { JIT_EXPIRY_MODE_OPTIONS, JIT_MAX_CUSTOM_EXPIRY_YEARS } from './JitDbAccess.constants'
+import type { JitRoleGrantDraft, JitRoleOption } from './JitDbAccess.types'
+import { getRelativeDatetimeByMode } from './JitDbAccess.utils'
+
+interface JitDbAccessRoleGrantFieldsProps {
+ role: JitRoleOption
+ grant: JitRoleGrantDraft
+ onChange: (next: JitRoleGrantDraft) => void
+}
+
+export function JitDbAccessRoleGrantFields({
+ role,
+ grant,
+ onChange,
+}: JitDbAccessRoleGrantFieldsProps) {
+ const isSuperuserRole = role.id === 'postgres'
+ const isReadOnlyRole = role.id === 'supabase_read_only_user'
+ const checkboxId = `jit-role-${role.id}`
+
+ return (
+ <div className={grant.enabled ? 'bg-surface-100' : 'bg-background'}>
+ <label
+ htmlFor={checkboxId}
+ className={`grid w-full cursor-pointer select-none grid-cols-[16px_minmax(0,1fr)] items-start gap-x-3 px-4 py-3 transition-colors ${
+ grant.enabled ? 'hover:bg-surface-200/40' : 'hover:bg-surface-100/50'
+ }`}
+ >
+ <Checkbox_Shadcn_
+ id={checkboxId}
+ checked={grant.enabled}
+ onCheckedChange={(value) => {
+ const isEnabled = value === true
+
+ if (!isEnabled) {
+ return onChange({ ...grant, enabled: false })
+ }
+
+ if (
+ (grant.hasExpiry && grant.expiry) ||
+ (!grant.hasExpiry && grant.expiryMode === 'never')
+ ) {
+ return onChange({ ...grant, enabled: true })
+ }
+
+ onChange({
+ ...grant,
+ enabled: true,
+ hasExpiry: true,
+ expiryMode: '1h',
+ expiry: getRelativeDatetimeByMode('1h'),
+ })
+ }}
+ aria-label={`Enable ${role.label}`}
+ className="mt-0.5"
+ />
+ <div className="min-w-0 flex-1">
+ <code className="text-code-inline dark:!bg-surface-300 dark:!border-control !tracking-normal">
+ {role.label}
+ </code>
+ </div>
+ </label>
+
+ {grant.enabled && (
+ <div className="grid grid-cols-[16px_minmax(0,1fr)] gap-x-3 px-4 pb-3">
+ <div aria-hidden />
+ <div className="space-y-4">
+ {isSuperuserRole && (
+ <Admonition
+ type="warning"
+ showIcon={false}
+ layout="vertical"
+ title="Grants full database control"
+ description={
+ <>
+ The selected role has unrestricted access and bypasses row-level security.
+ Consider using a{' '}
+ <InlineLink href={`${DOCS_URL}/guides/database/postgres/roles`}>
+ custom Postgres role
+ </InlineLink>{' '}
+ with only the permissions required.
+ </>
+ }
+ />
+ )}
+
+ {isReadOnlyRole && (
+ <Admonition
+ type="warning"
+ showIcon={false}
+ layout="vertical"
+ title="Grants read-only access to all schemas"
+ description={
+ <>
+ The selected role has read-only access to all schemas. Consider using a{' '}
+ <InlineLink href={`${DOCS_URL}/guides/database/postgres/roles`}>
+ custom Postgres role
+ </InlineLink>{' '}
+ with only the permissions required.
+ </>
+ }
+ className="rounded-md"
+ />
+ )}
+
+ <div className="space-y-2 border-t border-muted pt-3">
+ <p className="text-sm text-foreground">Expires in</p>
+ <div className="flex gap-2">
+ <div className="flex-1">
+ <Select_Shadcn_
+ value={grant.expiryMode}
+ onValueChange={(value) => {
+ const nextMode = value as JitRoleGrantDraft['expiryMode']
+
+ if (nextMode === 'never') {
+ return onChange({
+ ...grant,
+ expiryMode: nextMode,
+ hasExpiry: false,
+ expiry: '',
+ })
+ }
+
+ if (nextMode === 'custom') {
+ return onChange({
+ ...grant,
+ expiryMode: nextMode,
+ hasExpiry: true,
+ expiry: grant.expiry || getRelativeDatetimeByMode('1h'),
+ })
+ }
+
+ onChange({
+ ...grant,
+ expiryMode: nextMode,
+ hasExpiry: true,
+ expiry: getRelativeDatetimeByMode(nextMode),
+ })
+ }}
+ >
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Expires in" />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ {JIT_EXPIRY_MODE_OPTIONS.map((option) => (
+ <SelectItem_Shadcn_ key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </div>
+
+ {grant.expiryMode === 'custom' && (
+ <DatePicker
+ selectsRange={false}
+ triggerButtonSize="small"
+ contentSide="top"
+ to={grant.expiry || undefined}
+ minDate={new Date()}
+ maxDate={dayjs().add(JIT_MAX_CUSTOM_EXPIRY_YEARS, 'year').toDate()}
+ onChange={(value) => {
+ const selectedDate = value.to || value.from || ''
+ onChange({
+ ...grant,
+ hasExpiry: true,
+ expiry: selectedDate,
+ })
+ }}
+ triggerButtonClassName="min-w-[120px]"
+ >
+ {grant.expiry ? dayjs(grant.expiry).format('DD MMM, HH:mm') : 'Select date'}
+ </DatePicker>
+ )}
+ </div>
+
+ {grant.hasExpiry && grant.expiry && (
+ <p className="text-xs text-foreground-lighter">
+ Expires at{' '}
+ <TimestampInfo
+ utcTimestamp={grant.expiry}
+ className="text-foreground-lighter"
+ labelFormat="DD MMM, HH:mm"
+ />
+ </p>
+ )}
+
+ {grant.expiryMode === 'never' && (
+ <div className="mt-3 mx-0.5 flex w-full items-center gap-x-2">
+ <WarningIcon />
+ <span className="text-left text-xs text-foreground-lighter">
+ No expiry means ongoing database access until manually revoked.
+ </span>
+ </div>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-sm text-foreground">
+ Restricted IP addresses{' '}
+ <span className="font-normal text-foreground-lighter">(optional)</span>
+ </p>
+ <Input_Shadcn_
+ value={grant.ipRanges}
+ onChange={(event) =>
+ onChange({
+ ...grant,
+ hasIpRestriction: event.target.value.trim().length > 0,
+ ipRanges: event.target.value,
+ })
+ }
+ placeholder="e.g. 192.168.0.0/24, 203.0.113.4/32"
+ />
+ <p className="text-xs text-foreground-lighter">Comma-separated CIDR ranges</p>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRuleSheet.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRuleSheet.tsx
new file mode 100644
index 00000000000..2ab79f9fbfd
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRuleSheet.tsx
@@ -0,0 +1,346 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useParams } from 'common'
+import { InlineLink } from 'components/ui/InlineLink'
+import { DOCS_URL } from 'lib/constants'
+import { parseAsBoolean, parseAsString, useQueryState } from 'nuqs'
+import { useEffect, useMemo } from 'react'
+import { useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import {
+ Button,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ ScrollArea,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from 'ui'
+import { Admonition } from 'ui-patterns'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { z } from 'zod'
+
+import type {
+ JitExpiryMode,
+ JitMemberOption,
+ JitUserRuleDraft,
+ SheetMode,
+} from './JitDbAccess.types'
+import {
+ createDraft,
+ draftFromRule,
+ getAssignableJitRoleOptions,
+ getInvalidCidrs,
+ mapJitMembersToUserRules,
+ serializeDraftRolesForGrantMutation,
+} from './JitDbAccess.utils'
+import { JitDbAccessRoleGrantFields } from './JitDbAccessRoleGrantFields'
+import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
+import { useDatabaseRolesQuery } from '@/data/database-roles/database-roles-query'
+import { useJitDbAccessGrantMutation } from '@/data/jit-db-access/jit-db-access-grant-mutation'
+import { useJitDbAccessMembersQuery } from '@/data/jit-db-access/jit-db-access-members-query'
+import { useProjectMembersQuery } from '@/data/projects/project-members-query'
+import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
+import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
+
+const grantSchema = z.object({
+ roleId: z.string(),
+ enabled: z.boolean(),
+ expiryMode: z.custom<JitExpiryMode>(),
+ hasExpiry: z.boolean(),
+ expiry: z.string(),
+ hasIpRestriction: z.boolean(),
+ ipRanges: z.string(),
+})
+
+function createJitRuleSchema(mode: SheetMode, membersWithRules: Set<string>) {
+ return z
+ .object({
+ memberId: z.string().min(1, 'Select a member for this JIT access rule.'),
+ grants: z.array(grantSchema),
+ })
+ .superRefine((data, ctx) => {
+ if (mode === 'add' && membersWithRules.has(data.memberId)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['memberId'],
+ message:
+ 'This member already has a JIT access rule. Edit their existing rule from the list.',
+ })
+ }
+
+ const enabledGrants = data.grants.filter((g) => g.enabled)
+ if (enabledGrants.length === 0) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['grants'],
+ message: 'Select at least one role.',
+ })
+ return
+ }
+
+ for (const grant of enabledGrants) {
+ const invalidCidrs = getInvalidCidrs(grant.ipRanges)
+ if (invalidCidrs.length > 0) {
+ const preview = invalidCidrs.slice(0, 3).join(', ')
+ const overflow = invalidCidrs.length > 3
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['grants'],
+ message: `Invalid CIDR range${invalidCidrs.length > 1 ? 's' : ''} for role "${grant.roleId}": ${preview}${overflow ? ', ...' : ''}`,
+ })
+ break
+ }
+ }
+ })
+}
+
+interface JitDbAccessRuleSheetProps {
+ memberOptions: JitMemberOption[]
+ membersWithRules: Set<string>
+ availableMembersForAddCount: number
+}
+
+/**
+ * [Joshen] Form schema can be further refactored to simplify
+ * It's weird that we're rendering the role options based on the form, when it's just based on
+ * the available database roles - should decouple
+ */
+
+export function JitDbAccessRuleSheet({
+ memberOptions,
+ membersWithRules,
+ availableMembersForAddCount,
+}: JitDbAccessRuleSheetProps) {
+ const { ref: projectRef } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+
+ const [isNewRule, setIsNewRule] = useQueryState('jit_new', parseAsBoolean.withDefault(false))
+ const [ruleIdToEdit, setRuleIdToEdit] = useQueryState('jit_edit', parseAsString)
+
+ const { data: databaseRoles, isSuccess: isSuccessDatabaseRoles } = useDatabaseRolesQuery({
+ projectRef,
+ connectionString: project?.connectionString,
+ })
+ const roleOptions = useMemo(() => getAssignableJitRoleOptions(databaseRoles), [databaseRoles])
+ const roleIds = useMemo(() => roleOptions.map((role) => role.id), [roleOptions])
+
+ const { data: jitMembers, isSuccess: isSuccessJitMembers } = useJitDbAccessMembersQuery({
+ projectRef,
+ })
+ const { data: projectMembers, isSuccess: isSuccessProjectMembers } = useProjectMembersQuery({
+ projectRef,
+ })
+ const users = useMemo(
+ () => mapJitMembersToUserRules(jitMembers, projectMembers, roleOptions),
+ [jitMembers, projectMembers, roleOptions]
+ )
+ const user = users.find((x) => x.id === ruleIdToEdit)
+ const mode: SheetMode = !!user ? 'edit' : 'add'
+
+ const isDataReady = isSuccessDatabaseRoles && isSuccessJitMembers && isSuccessProjectMembers
+ const open = isNewRule || (!!ruleIdToEdit && !!user)
+
+ const defaultValues = !isNewRule && !!user ? draftFromRule(user, roleIds) : createDraft(roleIds)
+ const FormSchema = useMemo(
+ () => createJitRuleSchema(mode, membersWithRules),
+ [mode, membersWithRules]
+ )
+ const form = useForm<JitUserRuleDraft>({
+ defaultValues,
+ resolver: zodResolver(FormSchema),
+ })
+ const grants = form.watch('grants')
+
+ const onCloseSheet = () => {
+ setIsNewRule(false)
+ setRuleIdToEdit(null)
+ }
+
+ const {
+ confirmOnClose,
+ handleOpenChange,
+ modalProps: closeConfirmationModalProps,
+ } = useConfirmOnClose({
+ checkIsDirty: () => form.formState.isDirty,
+ onClose: onCloseSheet,
+ })
+
+ const { mutate: grantUserAccess, isPending: isSubmitting } = useJitDbAccessGrantMutation({
+ onSuccess: () => {
+ toast.success(
+ mode === 'edit' ? 'Successfully updated user access' : 'Successfully granted user access'
+ )
+ onCloseSheet()
+ },
+ onError: (error) => {
+ toast.error(`Failed to ${mode === 'edit' ? 'update' : 'grant'} user access: ${error.message}`)
+ },
+ })
+
+ const updateGrant = (
+ roleId: string,
+ updater: (grant: JitUserRuleDraft['grants'][number]) => JitUserRuleDraft['grants'][number]
+ ) => {
+ const nextGrants = grants.map((grant) => (grant.roleId === roleId ? updater(grant) : grant))
+ form.setValue('grants', nextGrants, { shouldDirty: true })
+ }
+
+ const handleSaveRule = (data: z.infer<typeof FormSchema>) => {
+ if (!projectRef) return console.error('Project ref is required')
+
+ const roles = serializeDraftRolesForGrantMutation(data)
+ if (roles.length === 0) return
+
+ grantUserAccess({ projectRef, userId: data.memberId, roles })
+ }
+
+ useEffect(() => {
+ if (!!ruleIdToEdit && isDataReady && !user) {
+ toast('Access rule cannot be found')
+ setRuleIdToEdit(null)
+ }
+ }, [isDataReady, ruleIdToEdit, setRuleIdToEdit, user])
+
+ useEffect(() => {
+ if (open && isDataReady) form.reset(defaultValues)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, isDataReady])
+
+ return (
+ <>
+ <Sheet open={open} onOpenChange={handleOpenChange}>
+ <SheetContent
+ showClose={false}
+ size="default"
+ className="flex h-full w-full max-w-full flex-col gap-0 sm:!w-[560px] sm:max-w-[560px]"
+ >
+ <SheetHeader>
+ <SheetTitle>
+ {mode === 'edit' ? 'Edit JIT access rule' : 'New JIT access rule'}
+ </SheetTitle>
+ <SheetDescription className="sr-only">
+ Configure which database roles a user can request with JIT access.
+ </SheetDescription>
+ </SheetHeader>
+
+ <Form_Shadcn_ {...form}>
+ <ScrollArea className="flex-1 max-h-[calc(100vh-116px)]">
+ <div className="space-y-8 px-5 py-6 sm:px-6">
+ <FormField_Shadcn_
+ control={form.control}
+ name="memberId"
+ render={({ field }) => (
+ <FormItemLayout layout="vertical" label="Member">
+ <FormControl_Shadcn_>
+ <Select_Shadcn_
+ value={field.value}
+ disabled={
+ mode === 'edit' || (mode === 'add' && availableMembersForAddCount === 0)
+ }
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger_Shadcn_>
+ <SelectValue_Shadcn_ placeholder="Select a member" />
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ {memberOptions.map((member) => (
+ <SelectItem_Shadcn_ key={member.id} value={member.id}>
+ {member.name ? (
+ <>
+ {member.name}{' '}
+ <span className="text-foreground-lighter">
+ ({member.email})
+ </span>
+ </>
+ ) : (
+ member.email
+ )}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ </FormControl_Shadcn_>
+
+ {mode === 'add' && availableMembersForAddCount === 0 && (
+ <p className="mt-2 text-foreground-lighter">
+ All project members already have JIT access rules. Edit an existing rule
+ from the table above.
+ </p>
+ )}
+ </FormItemLayout>
+ )}
+ />
+
+ <FormField_Shadcn_
+ control={form.control}
+ name="grants"
+ render={() => (
+ <FormItemLayout
+ layout="vertical"
+ label="Roles and settings"
+ description={
+ <>
+ Use{' '}
+ <InlineLink
+ href={`${DOCS_URL}/guides/database/postgres/roles`}
+ className="decoration-foreground-muted"
+ >
+ custom Postgres roles
+ </InlineLink>{' '}
+ with narrow permissions to reduce the impact of direct database access.
+ </>
+ }
+ >
+ {grants.length === 0 ? (
+ <Admonition
+ type="note"
+ title="No assignable roles found"
+ className="bg-background"
+ />
+ ) : (
+ <div className="overflow-hidden rounded-md border">
+ {grants.map((grant, index) => (
+ <div key={grant.roleId} className={index > 0 ? 'border-t' : ''}>
+ <JitDbAccessRoleGrantFields
+ role={{ id: grant.roleId, label: grant.roleId }}
+ grant={grant}
+ onChange={(next) => updateGrant(grant.roleId, () => next)}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ </ScrollArea>
+ </Form_Shadcn_>
+
+ <SheetFooter className="mt-auto w-full border-t py-4">
+ <Button type="default" onClick={confirmOnClose} disabled={isSubmitting}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ onClick={form.handleSubmit(handleSaveRule)}
+ loading={isSubmitting}
+ >
+ {mode === 'edit' ? 'Save rule' : 'Create rule'}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ <DiscardChangesConfirmationDialog {...closeConfirmationModalProps} />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx
new file mode 100644
index 00000000000..8df3cec319f
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessRulesTable.tsx
@@ -0,0 +1,213 @@
+import { EllipsisVertical, Pencil, Plus, Trash2 } from 'lucide-react'
+import {
+ Badge,
+ Button,
+ Card,
+ CardContent,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ Skeleton,
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+
+import type { JitUserRule } from './JitDbAccess.types'
+import { getJitStatusDisplay } from './JitDbAccess.utils'
+
+interface JitDbAccessRulesTableProps {
+ users: JitUserRule[]
+ isLoading?: boolean
+ canUpdate: boolean
+ disableActions?: boolean
+ allProjectMembersHaveRules?: boolean
+ onAddRule: () => void
+ onEditRule: (user: JitUserRule) => void
+ onDeleteRule: (user: JitUserRule) => void
+}
+
+export function JitDbAccessRulesTable({
+ users,
+ isLoading = false,
+ canUpdate,
+ disableActions = false,
+ allProjectMembersHaveRules = false,
+ onAddRule,
+ onEditRule,
+ onDeleteRule,
+}: JitDbAccessRulesTableProps) {
+ const addDisabled = disableActions || !canUpdate || allProjectMembersHaveRules
+ const addRuleTooltip = !canUpdate
+ ? 'Additional permissions required'
+ : allProjectMembersHaveRules
+ ? 'All project members already have JIT access rules'
+ : undefined
+
+ if (isLoading) {
+ return (
+ <Card>
+ <CardContent className="space-y-4 p-4">
+ <div className="flex items-center justify-between">
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-32" />
+ <Skeleton className="h-4 w-64" />
+ </div>
+ <Skeleton className="h-9 w-24" />
+ </div>
+ <Skeleton className="h-32 w-full" />
+ </CardContent>
+ </Card>
+ )
+ }
+
+ return (
+ <Card>
+ <CardContent className="space-y-4 p-0">
+ <div className="flex items-center justify-between px-4 pb-2 pt-6">
+ <div>
+ <h3 className="text-sm text-foreground">JIT access rules</h3>
+ <p className="text-sm text-foreground-light">
+ Configure which members can request temporary database access.
+ </p>
+ </div>
+
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <Button type="default" icon={<Plus />} onClick={onAddRule} disabled={addDisabled}>
+ Add rule
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {addRuleTooltip && <TooltipContent side="bottom">{addRuleTooltip}</TooltipContent>}
+ </Tooltip>
+ </div>
+
+ <Table className="border-t">
+ <TableHeader>
+ <TableRow>
+ <TableHead>Member</TableHead>
+ <TableHead>Roles</TableHead>
+ <TableHead>Status</TableHead>
+ <TableHead className="w-1">
+ <span className="sr-only">Actions</span>
+ </TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {users.length === 0 ? (
+ <TableRow className="[&>td]:hover:bg-inherit">
+ <TableCell colSpan={4}>
+ <p className="text-sm text-foreground">No JIT access rules</p>
+ <p className="text-sm text-foreground-lighter">
+ Add your first JIT access rule above
+ </p>
+ </TableCell>
+ </TableRow>
+ ) : (
+ users.map((user) => {
+ const statusDisplay = getJitStatusDisplay(user.status)
+ const enabledGrants = user.grants.filter((grant) => grant.enabled)
+ const rowIsInteractive = canUpdate && !disableActions
+
+ return (
+ <TableRow
+ key={user.id}
+ className={rowIsInteractive ? 'relative inset-focus cursor-pointer' : undefined}
+ onClick={
+ rowIsInteractive
+ ? (event) => {
+ if ((event.target as HTMLElement).closest('button')) return
+ onEditRule(user)
+ }
+ : undefined
+ }
+ onKeyDown={
+ rowIsInteractive
+ ? (event) => {
+ if ((event.target as HTMLElement).closest('button')) return
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault()
+ onEditRule(user)
+ }
+ }
+ : undefined
+ }
+ tabIndex={rowIsInteractive ? 0 : undefined}
+ >
+ <TableCell className="text-sm">
+ {user.name && <p>{user.name}</p>}
+ <p className="text-foreground-lighter">{user.email}</p>
+ </TableCell>
+ <TableCell className="text-sm text-foreground-light">
+ {enabledGrants.length} role{enabledGrants.length === 1 ? '' : 's'}
+ </TableCell>
+ <TableCell className="text-sm text-foreground-light">
+ {statusDisplay.badges.length > 0 ? (
+ <span className="flex flex-wrap gap-1.5">
+ {statusDisplay.badges.map((badge) => (
+ <Badge key={badge.label} variant={badge.variant}>
+ {badge.label}
+ </Badge>
+ ))}
+ </span>
+ ) : null}
+ </TableCell>
+ <TableCell className="text-right">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ icon={<EllipsisVertical />}
+ aria-label="More actions"
+ type="default"
+ size="tiny"
+ className="w-7"
+ disabled={!canUpdate || disableActions}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="bottom" className="w-40">
+ <DropdownMenuItem
+ className="gap-x-2"
+ onClick={(event) => {
+ event.stopPropagation()
+ onEditRule(user)
+ }}
+ disabled={!canUpdate || disableActions}
+ >
+ <Pencil size={14} className="text-foreground-lighter" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ className="gap-x-2"
+ onClick={(event) => {
+ event.stopPropagation()
+ onDeleteRule(user)
+ }}
+ disabled={!canUpdate || disableActions}
+ >
+ <Trash2 size={14} className="text-foreground-lighter" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </TableCell>
+ </TableRow>
+ )
+ })
+ )}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/apps/studio/data/jit-db-access/jit-db-access-grant-mutation.ts b/apps/studio/data/jit-db-access/jit-db-access-grant-mutation.ts
new file mode 100644
index 00000000000..7e5efa4e622
--- /dev/null
+++ b/apps/studio/data/jit-db-access/jit-db-access-grant-mutation.ts
@@ -0,0 +1,67 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { handleError, put } from 'data/fetchers'
+import { toast } from 'sonner'
+import type { ResponseError } from 'types'
+
+import { jitDbAccessKeys } from './keys'
+
+type JitDbAccessGrantVariables = {
+ projectRef: string
+ userId: string
+ roles: Array<{
+ role: string
+ expires_at?: number // Unix timestamp in seconds per role
+ allowed_networks?: {
+ allowed_cidrs?: Array<{ cidr: string }>
+ allowed_cidrs_v6?: Array<{ cidr: string }>
+ }
+ }>
+}
+
+async function grantJitDbAccess({ projectRef, userId, roles }: JitDbAccessGrantVariables) {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!userId) throw new Error('userId is required')
+ if (!roles || roles.length === 0) throw new Error('At least one role is required')
+
+ const { data, error } = await put(`/v1/projects/{ref}/database/jit`, {
+ params: { path: { ref: projectRef } },
+ body: {
+ user_id: userId,
+ roles,
+ },
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type JitDbAccessGrantData = Awaited<ReturnType<typeof grantJitDbAccess>>
+
+export const useJitDbAccessGrantMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<JitDbAccessGrantData, ResponseError, JitDbAccessGrantVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<JitDbAccessGrantData, ResponseError, JitDbAccessGrantVariables>({
+ mutationFn: (vars) => grantJitDbAccess(vars),
+
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.members(projectRef) })
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to grant JIT database access: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/jit-db-access/jit-db-access-members-query.ts b/apps/studio/data/jit-db-access/jit-db-access-members-query.ts
new file mode 100644
index 00000000000..214f5888030
--- /dev/null
+++ b/apps/studio/data/jit-db-access/jit-db-access-members-query.ts
@@ -0,0 +1,43 @@
+import { useQuery } from '@tanstack/react-query'
+import { get, handleError } from 'data/fetchers'
+import type { ResponseError, UseCustomQueryOptions } from 'types'
+
+import { jitDbAccessKeys } from './keys'
+
+type JitDbAccessMembersVariables = { projectRef?: string }
+
+async function getJitDbAccessMembers(
+ { projectRef }: JitDbAccessMembersVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await get(`/v1/projects/{ref}/database/jit/list`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) {
+ handleError(error)
+ }
+
+ return data.items
+}
+
+export type JitDbAccessMembersData = Awaited<ReturnType<typeof getJitDbAccessMembers>>
+type JitDbAccessMembersError = ResponseError
+
+export const useJitDbAccessMembersQuery = <TData = JitDbAccessMembersData>(
+ { projectRef }: JitDbAccessMembersVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<JitDbAccessMembersData, JitDbAccessMembersError, TData> = {}
+) =>
+ useQuery<JitDbAccessMembersData, JitDbAccessMembersError, TData>({
+ queryKey: jitDbAccessKeys.members(projectRef),
+ queryFn: ({ signal }) => getJitDbAccessMembers({ projectRef }, signal),
+ enabled: enabled && typeof projectRef !== 'undefined',
+ refetchOnWindowFocus: false,
+ ...options,
+ })
diff --git a/apps/studio/data/jit-db-access/jit-db-access-query.ts b/apps/studio/data/jit-db-access/jit-db-access-query.ts
new file mode 100644
index 00000000000..2ee784c810d
--- /dev/null
+++ b/apps/studio/data/jit-db-access/jit-db-access-query.ts
@@ -0,0 +1,51 @@
+import { useQuery } from '@tanstack/react-query'
+import { get, handleError } from 'data/fetchers'
+import type { ResponseError, UseCustomQueryOptions } from 'types'
+
+import { jitDbAccessKeys } from './keys'
+
+type JitDbAccessVariables = { projectRef?: string }
+
+async function getJitDbAccessConfiguration(
+ { projectRef }: JitDbAccessVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await get(`/v1/projects/{ref}/jit-access`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ // jit access might not be available on the project due to
+ // postgres version
+ if (error) {
+ const responseError = error as ResponseError
+ const isNotAvailableError =
+ responseError.code === 400 && responseError.message?.includes('unavailable')
+
+ if (isNotAvailableError) {
+ return {
+ appliedSuccessfully: false,
+ state: 'unavailable' as string,
+ isUnavailable: true,
+ } as const
+ } else {
+ handleError(error)
+ }
+ }
+ return data
+}
+
+type JitDbAccessData = Awaited<ReturnType<typeof getJitDbAccessConfiguration>>
+
+export const useJitDbAccessQuery = <TData = JitDbAccessData>(
+ { projectRef }: JitDbAccessVariables,
+ { enabled = true, ...options }: UseCustomQueryOptions<JitDbAccessData, ResponseError, TData> = {}
+) =>
+ useQuery<JitDbAccessData, ResponseError, TData>({
+ queryKey: jitDbAccessKeys.list(projectRef),
+ queryFn: ({ signal }) => getJitDbAccessConfiguration({ projectRef }, signal),
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ })
diff --git a/apps/studio/data/jit-db-access/jit-db-access-revoke-mutation.ts b/apps/studio/data/jit-db-access/jit-db-access-revoke-mutation.ts
new file mode 100644
index 00000000000..a4225be2740
--- /dev/null
+++ b/apps/studio/data/jit-db-access/jit-db-access-revoke-mutation.ts
@@ -0,0 +1,54 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { del, handleError } from 'data/fetchers'
+import { toast } from 'sonner'
+import type { ResponseError, UseCustomMutationOptions } from 'types'
+
+import { jitDbAccessKeys } from './keys'
+
+type JitDbAccessRevokeVariables = {
+ projectRef: string
+ userId: string
+}
+
+async function revokeJitDbAccess({ projectRef, userId }: JitDbAccessRevokeVariables) {
+ if (!projectRef) throw new Error('projectRef is required')
+ if (!userId) throw new Error('userId is required')
+
+ const { data, error } = await del('/v1/projects/{ref}/database/jit/{user_id}', {
+ params: { path: { ref: projectRef, user_id: userId } },
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type JitDbAccessRevokeData = Awaited<ReturnType<typeof revokeJitDbAccess>>
+
+export const useJitDbAccessRevokeMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<JitDbAccessRevokeData, ResponseError, JitDbAccessRevokeVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<JitDbAccessRevokeData, ResponseError, JitDbAccessRevokeVariables>({
+ mutationFn: (vars) => revokeJitDbAccess(vars),
+
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.members(projectRef) })
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to revoke JIT database access: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/jit-db-access/jit-db-access-update-mutation.ts b/apps/studio/data/jit-db-access/jit-db-access-update-mutation.ts
new file mode 100644
index 00000000000..ea445ef4894
--- /dev/null
+++ b/apps/studio/data/jit-db-access/jit-db-access-update-mutation.ts
@@ -0,0 +1,54 @@
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { handleError, put } from 'data/fetchers'
+import { toast } from 'sonner'
+import type { ResponseError, UseCustomMutationOptions } from 'types'
+
+import { jitDbAccessKeys } from './keys'
+
+type JitDbAccessUpdateVariables = {
+ projectRef: string
+ requestedConfig: { state: 'enabled' | 'disabled' | 'unavailable' }
+}
+
+async function updateJitDbAccess({ projectRef, requestedConfig }: JitDbAccessUpdateVariables) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await put(`/v1/projects/{ref}/jit-access`, {
+ params: { path: { ref: projectRef } },
+ body: requestedConfig,
+ })
+
+ if (error) handleError(error)
+ return data
+}
+
+type JitDbAccessUpdateData = Awaited<ReturnType<typeof updateJitDbAccess>>
+
+export const useJitDbAccessUpdateMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<JitDbAccessUpdateData, ResponseError, JitDbAccessUpdateVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<JitDbAccessUpdateData, ResponseError, JitDbAccessUpdateVariables>({
+ mutationFn: (vars) => updateJitDbAccess(vars),
+
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+ await queryClient.invalidateQueries({ queryKey: jitDbAccessKeys.list(projectRef) })
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to update just-in-time (JIT) database access: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/data/jit-db-access/keys.ts b/apps/studio/data/jit-db-access/keys.ts
new file mode 100644
index 00000000000..024a722fc6e
--- /dev/null
+++ b/apps/studio/data/jit-db-access/keys.ts
@@ -0,0 +1,7 @@
+export const jitDbAccessKeys = {
+ list: (projectRef: string | undefined) => ['projects', projectRef, 'jit-db-access'] as const,
+ status: (projectRef: string | undefined) =>
+ ['projects', projectRef, 'jit-db-access-status'] as const,
+ members: (projectRef: string | undefined) =>
+ ['projects', projectRef, 'jit-db-access-members'] as const,
+}
diff --git a/apps/studio/data/projects/keys.ts b/apps/studio/data/projects/keys.ts
index 810e41baf17..765133e6368 100644
--- a/apps/studio/data/projects/keys.ts
+++ b/apps/studio/data/projects/keys.ts
@@ -31,6 +31,8 @@ export const projectKeys = {
pauseStatus: (projectRef: string | undefined) =>
['projects', projectRef, 'pause-status'] as const,
+ projectMembers: (projectRef: string | undefined) => ['project', projectRef, 'members'] as const,
+
// Clone to new project
listCloneBackups: (projectRef: string | undefined) =>
['projects', projectRef, 'clone-backups'] as const,
diff --git a/apps/studio/data/projects/project-members-query.ts b/apps/studio/data/projects/project-members-query.ts
new file mode 100644
index 00000000000..98564067792
--- /dev/null
+++ b/apps/studio/data/projects/project-members-query.ts
@@ -0,0 +1,41 @@
+import { useQuery } from '@tanstack/react-query'
+import { get, handleError } from 'data/fetchers'
+import type { ResponseError, UseCustomQueryOptions } from 'types'
+
+import { projectKeys } from './keys'
+
+export type ProjectMembersVariables = {
+ projectRef?: string
+}
+
+export async function getProjectMembers(
+ { projectRef }: ProjectMembersVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { data, error } = await get(`/platform/projects/{ref}/members`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) handleError(error)
+ return data.members
+}
+
+export type ProjectMembersData = Awaited<ReturnType<typeof getProjectMembers>>
+export type ProjectMembersError = ResponseError
+
+export const useProjectMembersQuery = <TData = ProjectMembersData>(
+ { projectRef }: ProjectMembersVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseCustomQueryOptions<ProjectMembersData, ProjectMembersError, TData> = {}
+) =>
+ useQuery<ProjectMembersData, ProjectMembersError, TData>({
+ queryKey: projectKeys.projectMembers(projectRef),
+ queryFn: ({ signal }) => getProjectMembers({ projectRef }, signal),
+ enabled: enabled && typeof projectRef !== 'undefined',
+ ...options,
+ })
diff --git a/apps/studio/pages/project/[ref]/database/settings.tsx b/apps/studio/pages/project/[ref]/database/settings.tsx
index 4c90c843d39..46743d8b927 100644
--- a/apps/studio/pages/project/[ref]/database/settings.tsx
+++ b/apps/studio/pages/project/[ref]/database/settings.tsx
@@ -1,3 +1,4 @@
+import { useIsJitDbAccessEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { ConnectionPooling } from 'components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling'
import { DatabaseReadOnlyAlert } from 'components/interfaces/Settings/Database/DatabaseReadOnlyAlert'
import ResetDbPassword from 'components/interfaces/Settings/Database/DatabaseSettings/ResetDbPassword'
@@ -22,12 +23,14 @@ import { PageSection, PageSectionContent } from 'ui-patterns/PageSection'
import { DiskManagementPanelForm } from '@/components/interfaces/DiskManagement/DiskManagementPanelForm'
import { BannedIPs } from '@/components/interfaces/Settings/Database/BannedIPs'
import { DiskSizeConfiguration } from '@/components/interfaces/Settings/Database/DiskSizeConfiguration'
+import { JitDbAccessConfiguration } from '@/components/interfaces/Settings/Database/JitDatabaseAccess/JitDbAccessConfiguration'
import { NetworkRestrictions } from '@/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions'
import { SSLConfiguration } from '@/components/interfaces/Settings/Database/SSLConfiguration'
-const ProjectSettings: NextPageWithLayout = () => {
+const DatabaseSettings: NextPageWithLayout = () => {
const isAws = useIsAwsCloudProvider()
const isAwsK8s = useIsAwsK8sCloudProvider()
+ const jitDbAccessEnabled = useIsJitDbAccessEnabled()
const showNewDiskManagementUI = isAws || isAwsK8s
const { databaseNetworkRestrictions } = useIsFeatureEnabled(['database:network_restrictions'])
@@ -50,6 +53,7 @@ const ProjectSettings: NextPageWithLayout = () => {
<ResetDbPassword />
<ConnectionPooling />
<SSLConfiguration />
+ {jitDbAccessEnabled && <JitDbAccessConfiguration />}
{showNewDiskManagementUI ? (
// This form is hidden if Disk and Compute form is enabled, new form is on ./settings/compute-and-disk
<DiskManagementPanelForm />
@@ -74,10 +78,10 @@ const ProjectSettings: NextPageWithLayout = () => {
)
}
-ProjectSettings.getLayout = (page) => (
+DatabaseSettings.getLayout = (page) => (
<DefaultLayout>
<DatabaseLayout title="Settings">{page}</DatabaseLayout>
</DefaultLayout>
)
-export default ProjectSettings
+export default DatabaseSettings
diff --git a/packages/common/constants/local-storage.ts b/packages/common/constants/local-storage.ts
index c912b18d118..13be858ebf0 100644
--- a/packages/common/constants/local-storage.ts
+++ b/packages/common/constants/local-storage.ts
@@ -27,6 +27,7 @@ export const LOCAL_STORAGE_KEYS = {
UI_PREVIEW_PG_DELTA_DIFF: 'supabase-ui-pg-delta-diff',
UI_PREVIEW_FLOATING_MOBILE_TOOLBAR: 'supabase-ui-floating-mobile-toolbar',
UI_PREVIEW_PLATFORM_WEBHOOKS: 'supabase-ui-platform-webhooks',
+ UI_PREVIEW_JIT_DB_ACCESS: 'supabase-ui-jit-db-access',
NEW_LAYOUT_NOTICE_ACKNOWLEDGED: 'new-layout-notice-acknowledge',
TABS_INTERFACE_ACKNOWLEDGED: 'tabs-interface-acknowledge',
@@ -155,6 +156,7 @@ const LOCAL_STORAGE_KEYS_ALLOWLIST = [
LOCAL_STORAGE_KEYS.UI_PREVIEW_QUEUE_OPERATIONS,
LOCAL_STORAGE_KEYS.UI_PREVIEW_TABLE_FILTER_BAR,
LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS,
+ LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS,
LOCAL_STORAGE_KEYS.LAST_SIGN_IN_METHOD,
LOCAL_STORAGE_KEYS.HIDE_PROMO_TOAST,
LOCAL_STORAGE_KEYS.BLOG_VIEW,