Skip to content

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

feat(auth): add audit logs configuration page (#37409)

Cemal Kılıç97c16123b122
diff --git a/apps/studio/components/interfaces/Auth/AuditLogsForm.tsx b/apps/studio/components/interfaces/Auth/AuditLogsForm.tsx
new file mode 100644
index 00000000000..85e11b049e0
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/AuditLogsForm.tsx
@@ -0,0 +1,190 @@
+import { yupResolver } from '@hookform/resolvers/yup'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useEffect } from 'react'
+import { useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+import { boolean, object } from 'yup'
+
+import { useParams } from 'common'
+import { ScaffoldSection, ScaffoldSectionTitle } from 'components/layouts/Scaffold'
+import { InlineLink } from 'components/ui/InlineLink'
+import { NoPermission } from 'components/ui/NoPermission'
+import { useAuthConfigQuery } from 'data/auth/auth-config-query'
+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
+import { useTablesQuery } from 'data/tables/tables-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ Card,
+ CardContent,
+ CardFooter,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Form_Shadcn_,
+ Switch,
+ WarningIcon,
+} from 'ui'
+import { Admonition } from 'ui-patterns'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+
+const schema = object({
+ AUDIT_LOG_DISABLE_POSTGRES: boolean().required(),
+})
+
+const AUDIT_LOG_ENTRIES_TABLE = 'audit_log_entries'
+
+export const AuditLogsForm = () => {
+ const { ref: projectRef } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+ const canReadConfig = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')
+ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
+
+ const { data: tables = [] } = useTablesQuery({
+ projectRef: project?.ref,
+ connectionString: project?.connectionString,
+ includeColumns: false,
+ schema: 'auth',
+ })
+ const auditLogTable = tables.find((x) => x.name === AUDIT_LOG_ENTRIES_TABLE)
+
+ const { data: authConfig, error: authConfigError, isError } = useAuthConfigQuery({ projectRef })
+
+ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation({
+ onError: (error) => {
+ toast.error(`Failed to update audit logs: ${error?.message}`)
+ },
+ onSuccess: () => {
+ toast.success('Successfully updated audit logs settings')
+ },
+ })
+
+ const form = useForm({
+ resolver: yupResolver(schema),
+ defaultValues: { AUDIT_LOG_DISABLE_POSTGRES: false },
+ })
+ const { AUDIT_LOG_DISABLE_POSTGRES: formValueDisablePostgres } = form.watch()
+ const currentlyDisabled = authConfig?.AUDIT_LOG_DISABLE_POSTGRES ?? false
+ const isDisabling = !currentlyDisabled && formValueDisablePostgres
+
+ const onSubmitAuditLogs = (values: any) => {
+ if (!projectRef) return console.error('Project ref is required')
+ updateAuthConfig({ projectRef: projectRef, config: values })
+ }
+
+ useEffect(() => {
+ if (authConfig) {
+ form.reset({ AUDIT_LOG_DISABLE_POSTGRES: authConfig?.AUDIT_LOG_DISABLE_POSTGRES ?? false })
+ }
+ }, [authConfig])
+
+ if (isError) {
+ return (
+ <Alert_Shadcn_ variant="destructive">
+ <WarningIcon />
+ <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )
+ }
+
+ if (!canReadConfig) {
+ return <NoPermission resourceText="view audit logs settings" />
+ }
+
+ return (
+ <ScaffoldSection isFullWidth>
+ <div className="space-y-4">
+ <ScaffoldSectionTitle className="mb-4">Settings</ScaffoldSectionTitle>
+
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onSubmitAuditLogs)} className="space-y-4">
+ <Card>
+ <CardContent>
+ <FormField_Shadcn_
+ control={form.control}
+ name="AUDIT_LOG_DISABLE_POSTGRES"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="flex-row-reverse"
+ label="Disable writing auth audit logs to project database"
+ description={
+ <p className="text-sm prose text-foreground-lighter max-w-full">
+ Audit logs will no longer be stored in the{' '}
+ <InlineLink
+ target="_blank"
+ rel="noopener noreferrer"
+ href={`/project/${projectRef}/editor/${auditLogTable?.id}`}
+ >
+ <code className="text-xs bg-surface-200 px-1 py-0.5 rounded">
+ {AUDIT_LOG_ENTRIES_TABLE}
+ </code>
+ </InlineLink>{' '}
+ table in your project's database, which will reduce database storage
+ usage. Audit logs will subsequently still be available in the{' '}
+ <InlineLink
+ href={`/project/${projectRef}/logs/explorer?q=select%0A++cast(timestamp+as+datetime)+as+timestamp%2C%0A++event_message%2C+metadata+%0Afrom+auth_audit_logs+%0Alimit+10%0A`}
+ >
+ auth logs
+ </InlineLink>
+ .
+ </p>
+ }
+ >
+ <FormControl_Shadcn_>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={!canUpdateConfig}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ {isDisabling && (
+ <Admonition
+ type="warning"
+ className="mt-4"
+ title="Disabling PostgreSQL storage will not automatically migrate or transfer existing audit log data"
+ >
+ <p className="!mb-0 !leading-normal prose text-foreground-light text-sm max-w-full">
+ Future audit logs will only appear in the project's{' '}
+ <InlineLink
+ target="_blank"
+ rel="noopener noreferrer"
+ href={`/project/${projectRef}/logs/auth-logs?s=auth_audit_event`}
+ >
+ auth logs
+ </InlineLink>
+ . You are responsible for backing up, copying, or migrating existing data from
+ the <code>{AUDIT_LOG_ENTRIES_TABLE}</code> table if needed.
+ </p>
+ </Admonition>
+ )}
+ </CardContent>
+
+ <CardFooter className="justify-end space-x-2">
+ {form.formState.isDirty && (
+ <Button type="default" onClick={() => form.reset()}>
+ Cancel
+ </Button>
+ )}
+ <Button
+ type="primary"
+ htmlType="submit"
+ disabled={!canUpdateConfig || isUpdatingConfig || !form.formState.isDirty}
+ loading={isUpdatingConfig}
+ >
+ Save changes
+ </Button>
+ </CardFooter>
+ </Card>
+ </form>
+ </Form_Shadcn_>
+ </div>
+ </ScaffoldSection>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
index 9a6ae741a99..bc0eaaa21c0 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.constants.ts
@@ -199,6 +199,18 @@ where
regexp_contains(event_message,"level.{3}(info|warning||error|fatal)")
-- and regexp_contains(event_message,"path.{3}(/token|/recover|/signup|/otp)")
limit 100
+`,
+ for: ['database'],
+ },
+ {
+ label: 'Auth Audit Logs',
+ description: 'Audit logs for auth events',
+ mode: 'custom',
+ searchString: `select
+ cast(timestamp as datetime) as timestamp,
+ event_message, metadata
+from auth_audit_logs
+limit 10
`,
for: ['database'],
},
@@ -369,6 +381,7 @@ export enum LogsTableName {
FUNCTIONS = 'function_logs',
FN_EDGE = 'function_edge_logs',
AUTH = 'auth_logs',
+ AUTH_AUDIT = 'auth_audit_logs',
REALTIME = 'realtime_logs',
STORAGE = 'storage_logs',
POSTGREST = 'postgrest_logs',
@@ -400,7 +413,8 @@ export const LOGS_SOURCE_DESCRIPTION = {
[LogsTableName.POSTGRES]: 'Database logs obtained directly from Postgres',
[LogsTableName.FUNCTIONS]: 'Function logs generated from runtime execution',
[LogsTableName.FN_EDGE]: 'Function call logs, containing the request and response',
- [LogsTableName.AUTH]: 'Authentication logs from GoTrue',
+ [LogsTableName.AUTH]: 'Errors, warnings, and performance details from the auth service',
+ [LogsTableName.AUTH_AUDIT]: 'Audit records of user signups, logins, and account changes',
[LogsTableName.REALTIME]: 'Realtime server for Postgres logical replication broadcasting',
[LogsTableName.STORAGE]: 'Object storage logs',
[LogsTableName.POSTGREST]: 'RESTful API web server logs',
diff --git a/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx b/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
index ff2e816a347..8e1151139b1 100644
--- a/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
+++ b/apps/studio/components/interfaces/Settings/Logs/LogsQueryPanel.tsx
@@ -111,7 +111,7 @@ const LogsQueryPanel = ({
<DropdownMenuContent
side="bottom"
align="start"
- className="max-h-[70vh] overflow-auto"
+ className="max-h-[390px] overflow-auto"
>
{logsTableNames
.sort((a, b) => a.localeCompare(b))
diff --git a/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts b/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts
index 8bf8dd7da55..e40c51f9af4 100644
--- a/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts
+++ b/apps/studio/components/layouts/AuthLayout/AuthLayout.utils.ts
@@ -108,6 +108,13 @@ export const generateAuthMenu = (
items: [],
label: 'BETA',
},
+ {
+ name: 'Audit Logs',
+ key: 'audit-logs',
+ url: `/project/${ref}/auth/audit-logs`,
+ items: [],
+ label: 'BETA',
+ },
...(authenticationAdvanced
? [
{
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
index b4a6b32e9fb..3ec68b9cc24 100644
--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
@@ -109,7 +109,7 @@ export const generateSettingsMenu = (
url: isProjectBuilding ? buildingUrl : `/project/${ref}/integrations/vault/overview`,
items: [],
rightIcon: <ArrowUpRight strokeWidth={1} className="h-4 w-4" />,
- label: 'Alpha',
+ label: 'ALPHA',
},
],
},
diff --git a/apps/studio/components/ui/NoPermission.tsx b/apps/studio/components/ui/NoPermission.tsx
index af4fe364fb9..01bc25ce8b0 100644
--- a/apps/studio/components/ui/NoPermission.tsx
+++ b/apps/studio/components/ui/NoPermission.tsx
@@ -5,7 +5,7 @@ interface NoPermissionProps {
isFullPage?: boolean
}
-const NoPermission = ({ resourceText, isFullPage = false }: NoPermissionProps) => {
+export const NoPermission = ({ resourceText, isFullPage = false }: NoPermissionProps) => {
const NoPermissionMessage = () => (
<div
className={[
diff --git a/apps/studio/pages/project/[ref]/auth/audit-logs.tsx b/apps/studio/pages/project/[ref]/auth/audit-logs.tsx
new file mode 100644
index 00000000000..0b3554b0bee
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/auth/audit-logs.tsx
@@ -0,0 +1,57 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+
+import { useParams } from 'common'
+import { AuditLogsForm } from 'components/interfaces/Auth/AuditLogsForm'
+import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
+import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
+import { ScaffoldContainer } from 'components/layouts/Scaffold'
+import { DocsButton } from 'components/ui/DocsButton'
+import NoPermission from 'components/ui/NoPermission'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { useAuthConfigQuery } from 'data/auth/auth-config-query'
+import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
+import type { NextPageWithLayout } from 'types'
+
+const AuditLogsPage: NextPageWithLayout = () => {
+ const { ref: projectRef } = useParams()
+ const isPermissionsLoaded = usePermissionsLoaded()
+ const { isLoading: isLoadingConfig } = useAuthConfigQuery({ projectRef })
+ const canReadAuthSettings = useCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')
+
+ if (isPermissionsLoaded && !canReadAuthSettings) {
+ return <NoPermission isFullPage resourceText="access your project's audit logs settings" />
+ }
+
+ return (
+ <ScaffoldContainer>
+ {!isPermissionsLoaded || isLoadingConfig ? (
+ <div className="mt-12">
+ <GenericSkeletonLoader />
+ </div>
+ ) : (
+ <AuditLogsForm />
+ )}
+ </ScaffoldContainer>
+ )
+}
+
+const secondaryActions = [
+ <DocsButton key="docs" href="https://supabase.com/docs/guides/auth/audit-logs" />,
+]
+
+AuditLogsPage.getLayout = (page) => (
+ <DefaultLayout>
+ <AuthLayout>
+ <PageLayout
+ title="Audit Logs"
+ subtitle="Track and monitor auth events in your project"
+ secondaryActions={secondaryActions}
+ >
+ {page}
+ </PageLayout>
+ </AuthLayout>
+ </DefaultLayout>
+)
+
+export default AuditLogsPage