Skip to content

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

Refactor API settings page and show keys based on abac perms

Joshen Limb2c818ef630b
diff --git a/studio/components/interfaces/Settings/API/API.constants.ts b/studio/components/interfaces/Settings/API/API.constants.ts
new file mode 100644
index 00000000000..4090595ed24
--- /dev/null
+++ b/studio/components/interfaces/Settings/API/API.constants.ts
@@ -0,0 +1,23 @@
+import { JwtSecretUpdateError, JwtSecretUpdateProgress } from '@supabase/shared-types/out/events'
+
+export const JWT_SECRET_UPDATE_ERROR_MESSAGES = {
+ [JwtSecretUpdateError.APIServicesConfigurationUpdateFailed]:
+ 'failed to update configuration for API services',
+ [JwtSecretUpdateError.APIServicesRestartFailed]: 'failed to restart API services',
+ [JwtSecretUpdateError.DatabaseAdminAPIConfigurationUpdateFailed]:
+ 'failed to update configuration for database admin API',
+ [JwtSecretUpdateError.PostgreSQLRestartFailed]: 'failed to restart PostgreSQL service',
+ [JwtSecretUpdateError.SupabaseAPIKeyUpdateFailed]: 'failed to update Supabase API key',
+ [JwtSecretUpdateError.APIGatewayUpdateFailed]: 'failed to update API Gateway',
+}
+
+export const JWT_SECRET_UPDATE_PROGRESS_MESSAGES = {
+ [JwtSecretUpdateProgress.RestartedAPIServices]: 'restarted API services',
+ [JwtSecretUpdateProgress.RestartedPostgreSQL]: 'restarted PostgreSQL service',
+ [JwtSecretUpdateProgress.Started]: 'started updating',
+ [JwtSecretUpdateProgress.UpdatedAPIServicesConfiguration]:
+ 'updated configuration for API services',
+ [JwtSecretUpdateProgress.UpdatedDatabaseAdminAPIConfiguration]:
+ 'updated configuration for database admin API',
+ [JwtSecretUpdateProgress.UpdatedAPIGatewayConfiguration]: 'updated configuration for API Gateway',
+}
diff --git a/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
new file mode 100644
index 00000000000..f6cc1ba8e52
--- /dev/null
+++ b/studio/components/interfaces/Settings/API/PostgrestConfig.tsx
@@ -0,0 +1,137 @@
+import { useContext, useState } from 'react'
+import { indexOf } from 'lodash'
+import { AutoField } from 'uniforms-bootstrap4'
+import { observer } from 'mobx-react-lite'
+import { IconAlertCircle } from '@supabase/ui'
+
+import { useStore } from 'hooks'
+import { API_URL } from 'lib/constants'
+import { patch } from 'lib/common/fetch'
+import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
+import MultiSelect from 'components/ui/MultiSelect'
+import { PageContext } from 'pages/project/[ref]/settings/api'
+
+const PostgrestConfig = observer(({ config, projectRef }: any) => {
+ const PageState: any = useContext(PageContext)
+ const { ui } = useStore()
+ const { meta } = PageState
+
+ const [updates, setUpdates] = useState({
+ db_schema: config.db_schema,
+ max_rows: config.max_rows,
+ db_extra_search_path: config.db_extra_search_path || '',
+ })
+
+ const updateConfig = async (updatedConfig: any) => {
+ try {
+ const response = await patch(
+ `${API_URL}/projects/${projectRef}/config/postgrest`,
+ updatedConfig
+ )
+ if (response.error) {
+ throw response.error
+ } else {
+ ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
+ }
+ } catch (error: any) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to update config: ${error.message}`,
+ })
+ }
+ }
+
+ // manually filter out following schema
+ const hiddenSchema = ['auth', 'pgbouncer', 'hooks', 'extensions']
+ // following schema is permament
+ const permanentSchema = ['public', 'storage']
+ // construct list of schema for input controller
+ const schema =
+ meta.schemas
+ .list(
+ (x: any) => {
+ const find = indexOf(hiddenSchema, x.name)
+ if (find < 0) return x
+ },
+ { allSchemas: true }
+ )
+ .map((x: any) => {
+ return {
+ id: x.id,
+ value: x.name,
+ name: x.name,
+ disabled: indexOf(permanentSchema, x.name) >= 0 ? true : false,
+ }
+ }) ?? []
+
+ return (
+ <>
+ <SchemaFormPanel
+ title="Settings"
+ schema={{
+ properties: {
+ db_schema: {
+ title: 'Schema',
+ type: 'string',
+ help: 'The schema to expose in your API. Tables, views and stored procedures in this schema will get API endpoints. Multiple schemas must be comma-separated.',
+ },
+ max_rows: {
+ title: 'Max Rows',
+ type: 'integer',
+ help: 'The maximum number of rows returns from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.',
+ },
+ db_extra_search_path: {
+ title: 'Extra search path',
+ type: 'string',
+ help: 'Extra schemas to add to the search_path of every request. Multiple schemas must be comma-separated.',
+ },
+ },
+ required: ['max_rows'],
+ type: 'object',
+ }}
+ model={updates}
+ onSubmit={(model: any) => updateConfig(model)}
+ onReset={() => setUpdates(config)}
+ >
+ <div className="space-y-6 py-4">
+ {schema.length >= 1 && (
+ <MultiSelect
+ options={schema}
+ // value must be passed as array of strings
+ value={updates.db_schema.replace(/ /g, '').split(',')}
+ // onChange returns array of strings
+ onChange={(event) => {
+ let payload = updates
+ payload.db_schema = event.join(', ') // permanentSchema.concat(event).join(', ')
+ setUpdates({ ...payload })
+ updateConfig({ ...payload })
+ }}
+ label={'Schema'}
+ descriptionText={
+ <>
+ The schema to expose in your API. Tables, views and stored procedures in this
+ schema will get API endpoints.<code>public</code> and <code>storage</code> are
+ protected by default.
+ </>
+ }
+ emptyMessage={
+ <>
+ <IconAlertCircle strokeWidth={2} />
+ <div className="mt-2 flex flex-col text-center">
+ <p className="text-sm align-center">No schema available to choose</p>
+ <p className="text-xs opacity-50">New schemas you create will appear here</p>
+ </div>
+ </>
+ }
+ />
+ )}
+ <AutoField name="db_extra_search_path" showInlineError errorMessage="Must be a string." />
+ <AutoField name="max_rows" showInlineError errorMessage="Must be a number." />
+ </div>
+ </SchemaFormPanel>
+ </>
+ )
+})
+
+export default PostgrestConfig
diff --git a/studio/components/interfaces/Settings/API/ServiceList.tsx b/studio/components/interfaces/Settings/API/ServiceList.tsx
new file mode 100644
index 00000000000..eeb0471f7d8
--- /dev/null
+++ b/studio/components/interfaces/Settings/API/ServiceList.tsx
@@ -0,0 +1,368 @@
+import useSWR from 'swr'
+import { Dispatch, FC, SetStateAction, useEffect, useRef, useState } from 'react'
+import { useRouter } from 'next/router'
+import {
+ JwtSecretUpdateError,
+ JwtSecretUpdateProgress,
+ JwtSecretUpdateStatus,
+} from '@supabase/shared-types/out/events'
+import {
+ Alert,
+ Typography,
+ Input,
+ Modal,
+ IconKey,
+ Button,
+ Dropdown,
+ IconPenTool,
+ IconRefreshCw,
+ IconChevronDown,
+ IconLoader,
+ IconEye,
+ IconEyeOff,
+} from '@supabase/ui'
+
+import { API_URL } from 'lib/constants'
+import { uuidv4 } from 'lib/helpers'
+import { patch, get } from 'lib/common/fetch'
+import { useStore, useJwtSecretUpdateStatus } from 'hooks'
+
+import Panel from 'components/ui/Panel'
+import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
+import PostgrestConfig from './PostgrestConfig'
+import { DisplayApiSettings } from 'components/ui/ProjectSettings'
+import {
+ JWT_SECRET_UPDATE_ERROR_MESSAGES,
+ JWT_SECRET_UPDATE_PROGRESS_MESSAGES,
+} from './API.constants'
+
+interface Props {
+ projectRef: string
+}
+
+const ServiceList: FC<Props> = ({ projectRef }) => {
+ const { ui } = useStore()
+ const router = useRouter()
+ const { ref } = router.query
+
+ const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)
+ const [customToken, setCustomToken] = useState<string>('')
+ const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)
+ const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)
+ const [isSubmittingJwtSecretUpdateRequest, setIsSubmittingJwtSecretUpdateRequest] =
+ useState<boolean>(false)
+
+ const {
+ data,
+ error,
+ mutate: mutateSettings,
+ }: any = useSWR(`${API_URL}/props/project/${projectRef}/settings`, get)
+ const { data: config, mutate: mutateConfig }: any = useSWR(
+ `${API_URL}/projects/${projectRef}/config/postgrest`,
+ get
+ )
+ const {
+ changeTrackingId,
+ isError: isJwtSecretUpdateStatusError,
+ isLoading: isJwtSecretUpdateStatusLoading,
+ jwtSecretUpdateError,
+ jwtSecretUpdateProgress,
+ jwtSecretUpdateStatus,
+ mutateJwtSecretUpdateStatus,
+ }: any = useJwtSecretUpdateStatus(ref)
+
+ const { Failed, Updated, Updating } = JwtSecretUpdateStatus
+
+ const isJwtSecretUpdateFailed = jwtSecretUpdateStatus === Failed
+ const isNotUpdatingJwtSecret =
+ jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === Updated
+ const isUpdatingJwtSecret = jwtSecretUpdateStatus === Updating
+ const jwtSecretUpdateErrorMessage =
+ JWT_SECRET_UPDATE_ERROR_MESSAGES[jwtSecretUpdateError as JwtSecretUpdateError]
+ const jwtSecretUpdateProgressMessage =
+ JWT_SECRET_UPDATE_PROGRESS_MESSAGES[jwtSecretUpdateProgress as JwtSecretUpdateProgress]
+
+ const previousJwtSecretUpdateStatus = useRef()
+
+ useEffect(() => {
+ if (previousJwtSecretUpdateStatus.current === Updating) {
+ switch (jwtSecretUpdateStatus) {
+ case Updated:
+ mutateConfig()
+ mutateSettings()
+ ui.setNotification({ category: 'success', message: 'Successfully updated JWT secret' })
+ break
+ case Failed:
+ ui.setNotification({
+ category: 'error',
+ message: `JWT secret update failed: ${jwtSecretUpdateErrorMessage}`,
+ })
+ break
+ }
+ }
+
+ previousJwtSecretUpdateStatus.current = jwtSecretUpdateStatus
+ }, [jwtSecretUpdateStatus])
+
+ if (error || isJwtSecretUpdateStatusError) {
+ return (
+ <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">
+ <Typography.Title level={3}>Error loading API settings</Typography.Title>
+ </div>
+ )
+ }
+ if (!data || isJwtSecretUpdateStatusLoading) {
+ return (
+ <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">
+ <Typography.Title level={3}>Loading...</Typography.Title>
+ </div>
+ )
+ }
+
+ const { services } = data
+
+ // Get the API service
+ const API_SERVICE_ID = 1
+ const apiService = services.find((x: any) => x.app.id == API_SERVICE_ID)
+ const apiConfig = apiService?.app_config
+
+ async function handleJwtSecretUpdate(
+ jwt_secret: string,
+ setModalVisibility: Dispatch<SetStateAction<boolean>>
+ ) {
+ setIsSubmittingJwtSecretUpdateRequest(true)
+ try {
+ const trackingId = uuidv4()
+ const res = await patch(`${API_URL}/projects/${ref}/config/secrets`, {
+ jwt_secret,
+ change_tracking_id: trackingId,
+ })
+ if (res.error) throw res.error
+ setModalVisibility(false)
+ mutateJwtSecretUpdateStatus()
+ ui.setNotification({
+ category: 'info',
+ message:
+ 'Successfully submitted JWT secret update request. Please wait while your project is updated.',
+ })
+ } catch (error: any) {
+ ui.setNotification({ category: 'error', message: error.message })
+ } finally {
+ setIsSubmittingJwtSecretUpdateRequest(false)
+ }
+ }
+
+ return (
+ <>
+ <div className="max-w-4xl p-4">
+ <section>
+ <Panel
+ title={
+ <Typography.Title level={5} className="mb-0">
+ Project URL
+ </Typography.Title>
+ }
+ >
+ <Panel.Content>
+ <Input
+ copy
+ label="URL"
+ readOnly
+ disabled
+ className="input-mono"
+ value={`https://${apiConfig?.endpoint ?? '-'}`}
+ descriptionText="A RESTful endpoint for querying and managing your database."
+ layout="horizontal"
+ />
+ </Panel.Content>
+ </Panel>
+ </section>
+
+ <section>
+ <DisplayApiSettings key="DisplayAPISettings" />
+ </section>
+
+ <section>
+ <Panel
+ title={
+ <Typography.Title level={5} className="mb-0">
+ JWT Settings
+ </Typography.Title>
+ }
+ >
+ <Panel.Content className="border-panel-border-interior-light dark:border-panel-border-interior-dark space-y-6 border-t">
+ <Input
+ label="JWT Secret"
+ readOnly
+ copy={isNotUpdatingJwtSecret}
+ reveal={isNotUpdatingJwtSecret}
+ disabled
+ value={
+ isJwtSecretUpdateFailed
+ ? 'JWT secret update failed'
+ : isUpdatingJwtSecret
+ ? 'Updating JWT secret...'
+ : config?.jwt_secret || ''
+ }
+ className="input-mono"
+ descriptionText={
+ 'Used to decode your JWTs. You can also use this to mint your own JWTs.'
+ }
+ layout="horizontal"
+ />
+ <div className="space-y-3">
+ <div className="dark:bg-bg-alt-dark bg-bg-alt-light dark:border-dark rounded-md border p-3 px-6 shadow-sm">
+ {isUpdatingJwtSecret ? (
+ <div className="flex items-center space-x-2">
+ <IconLoader className="animate-spin" size={14} />
+ <p className="text-sm">
+ Updating JWT secret: {jwtSecretUpdateProgressMessage}
+ </p>
+ </div>
+ ) : (
+ <div className="w-full space-y-2">
+ <div className="flex w-full items-center justify-between">
+ <div className="flex flex-col space-y-1">
+ <Typography.Text>Generate a new JWT secret</Typography.Text>
+ <p className="text-sm opacity-50">
+ A random secret will be created, or you can create your own.
+ </p>
+ </div>
+ <div className="flex flex-col items-end">
+ {isUpdatingJwtSecret ? (
+ <Button loading type="secondary">
+ Updating JWT secret...
+ </Button>
+ ) : (
+ <Dropdown
+ align="end"
+ side="bottom"
+ overlay={
+ <>
+ <Dropdown.Item
+ onClick={() => setIsGeneratingKey(true)}
+ icon={<IconRefreshCw size={16} />}
+ >
+ Generate a random secret
+ </Dropdown.Item>
+ <Dropdown.Seperator />
+ <Dropdown.Item
+ onClick={() => setIsCreatingKey(true)}
+ icon={<IconPenTool size={16} />}
+ >
+ Create my own secret
+ </Dropdown.Item>
+ </>
+ }
+ >
+ <Button as="span" type="default" iconRight={<IconChevronDown />}>
+ Generate a new secret
+ </Button>
+ </Dropdown>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ {isJwtSecretUpdateFailed ? (
+ <Alert withIcon variant="warning" title="Failed to update JWT secret">
+ Please try again. If the failures persist, please contact Supabase support with
+ the following details: <br />
+ Change tracking ID: {changeTrackingId} <br />
+ Error message: {jwtSecretUpdateErrorMessage}
+ </Alert>
+ ) : (
+ <Alert
+ withIcon
+ variant="warning"
+ title="This will invalidate all existing API keys!"
+ >
+ Generating a new JWT secret will invalidate <u>all</u> of your API keys,
+ including your <code>service_role</code> and <code>anon</code> keys. Your
+ project will also be restarted during this process, which will terminate any
+ existing connections.
+ </Alert>
+ )}
+ </div>
+ </Panel.Content>
+ </Panel>
+ </section>
+
+ <section>{config && <PostgrestConfig config={config} projectRef={projectRef} />}</section>
+ </div>
+
+ <ConfirmModal
+ danger
+ visible={isRegeneratingKey}
+ title="Are you absolutely sure?"
+ description="This action cannot be undone and the old JWT secret will be lost. All existing API keys
+ will be invalidated, and any open connections will be terminated."
+ buttonLabel="Generate new secret"
+ buttonLoadingLabel="Generating"
+ onSelectCancel={() => setIsGeneratingKey(false)}
+ onSelectConfirm={() => handleJwtSecretUpdate('ROLL', setIsGeneratingKey)}
+ />
+
+ <Modal
+ closable
+ header="Create a custom JWT secret"
+ visible={isCreatingKey}
+ size="medium"
+ variant="danger"
+ loading={isSubmittingJwtSecretUpdateRequest}
+ customFooter={
+ <div className="space-x-2">
+ <Button type="default" onClick={() => setIsCreatingKey(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="primary"
+ disabled={
+ customToken.length < 32 || customToken.includes('@') || customToken.includes('$')
+ }
+ loading={isSubmittingJwtSecretUpdateRequest}
+ onClick={() => handleJwtSecretUpdate(customToken, setIsCreatingKey)}
+ >
+ Apply new JWT secret
+ </Button>
+ </div>
+ }
+ >
+ <Modal.Content>
+ <div className="space-y-2 py-4">
+ <p className="text-scale-1100 text-sm">
+ Create a custom JWT secret. Make sure it is a strong combination of characters that
+ cannot be guessed easily.
+ </p>
+ <Alert
+ withIcon
+ variant="warning"
+ title="All existing API keys will be invalidated, and any open connections will be terminated."
+ />
+ <Input
+ onChange={(e: any) => setCustomToken(e.target.value)}
+ value={customToken}
+ icon={<IconKey />}
+ type={showCustomTokenInput ? 'text' : 'password'}
+ className="w-full text-left"
+ label="Custom JWT secret"
+ descriptionText="Minimally 32 characters long, '@' and '$' are not allowed."
+ actions={
+ <div className="mr-1 flex items-center justify-center">
+ <Button
+ type="default"
+ icon={showCustomTokenInput ? <IconEye /> : <IconEyeOff />}
+ onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}
+ />
+ </div>
+ }
+ />
+ </div>
+ </Modal.Content>
+ </Modal>
+ </>
+ )
+}
+
+export default ServiceList
diff --git a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
index 1691104ff96..c7aa65e11ae 100644
--- a/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
+++ b/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
@@ -1,11 +1,12 @@
-import { FC } from 'react'
import { useRouter } from 'next/router'
import { Input } from '@supabase/ui'
import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'
-import { useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'
-import { SettingsLoadingState } from './SettingsLoadingState'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+
+import { checkPermissions, useJwtSecretUpdateStatus, useProjectSettings } from 'hooks'
import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'
import Panel from 'components/ui/Panel'
+import { SettingsLoadingState } from './SettingsLoadingState'
const DisplayApiSettings = () => {
const router = useRouter()
@@ -21,6 +22,8 @@ const DisplayApiSettings = () => {
jwtSecretUpdateStatus,
}: any = useJwtSecretUpdateStatus(ref)
+ const canReadAPIKeys = checkPermissions(PermissionAction.READ, 'service_api_keys')
+
const isNotUpdatingJwtSecret =
jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated
// Get the API service
@@ -30,7 +33,18 @@ const DisplayApiSettings = () => {
const isApikeysEmpty = apiKeys.length === 0
return (
- <ApiContentWrapper>
+ <Panel
+ title={
+ <div className="space-y-3">
+ <h5 className="text-base">Project API keys</h5>
+ <p className="text-sm text-scale-1000">
+ Your API is secured behind an API gateway which requires an API Key for every request.
+ <br />
+ You can use the keys below to use Supabase client libraries.
+ </p>
+ </div>
+ }
+ >
{isProjectSettingsLoading || isJwtSecretUpdateStatusLoading || isApikeysEmpty ? (
<SettingsLoadingState
isError={isProjectSettingsError || isJwtSecretUpdateStatusError}
@@ -46,7 +60,10 @@ const DisplayApiSettings = () => {
}
>
<Input
+ readOnly
+ disabled
layout="horizontal"
+ className="input-mono"
// @ts-ignore
label={
<>
@@ -63,13 +80,12 @@ const DisplayApiSettings = () => {
{x.tags === 'anon' && <code className="text-xs text-code">{'public'}</code>}
</>
}
- readOnly
- copy={isNotUpdatingJwtSecret}
- className="input-mono"
- disabled
- reveal={x.tags !== 'anon' && isNotUpdatingJwtSecret}
+ copy={canReadAPIKeys && isNotUpdatingJwtSecret}
+ reveal={x.tags !== 'anon' && canReadAPIKeys && isNotUpdatingJwtSecret}
value={
- jwtSecretUpdateStatus === JwtSecretUpdateStatus.Failed
+ !canReadAPIKeys
+ ? 'You need additional permissions to read API keys'
+ : jwtSecretUpdateStatus === JwtSecretUpdateStatus.Failed
? 'JWT secret update failed, new API key may have issues'
: jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating
? 'Updating JWT secret...'
@@ -85,26 +101,7 @@ const DisplayApiSettings = () => {
</Panel.Content>
))
)}
- </ApiContentWrapper>
- )
-}
-export default DisplayApiSettings
-
-const ApiContentWrapper: FC = ({ children }) => {
- return (
- <Panel
- title={
- <div className="space-y-3">
- <h5 className="text-base">Project API keys</h5>
- <p className="text-sm text-scale-1000">
- Your API is secured behind an API gateway which requires an API Key for every request.
- <br />
- You can use the keys below to use Supabase client libraries.
- </p>
- </div>
- }
- >
- {children}
</Panel>
)
}
+export default DisplayApiSettings
diff --git a/studio/pages/project/[ref]/settings/api.tsx b/studio/pages/project/[ref]/settings/api.tsx
index 6ae9964c73a..db3cb144865 100644
--- a/studio/pages/project/[ref]/settings/api.tsx
+++ b/studio/pages/project/[ref]/settings/api.tsx
@@ -1,78 +1,13 @@
-import useSWR from 'swr'
-import {
- Dispatch,
- FC,
- SetStateAction,
- createContext,
- useContext,
- useEffect,
- useRef,
- useState,
-} from 'react'
-import { indexOf } from 'lodash'
+import { createContext } from 'react'
import { useRouter } from 'next/router'
-import { AutoField } from 'uniforms-bootstrap4'
import { observer, useLocalObservable } from 'mobx-react-lite'
-import {
- JwtSecretUpdateError,
- JwtSecretUpdateProgress,
- JwtSecretUpdateStatus,
-} from '@supabase/shared-types/out/events'
-import {
- Alert,
- Typography,
- Input,
- IconAlertCircle,
- Modal,
- IconKey,
- Button,
- Dropdown,
- IconPenTool,
- IconRefreshCw,
- IconChevronDown,
- IconLoader,
- IconEye,
- IconEyeOff,
-} from '@supabase/ui'
-import { API_URL } from 'lib/constants'
-import { uuidv4 } from 'lib/helpers'
-import { patch, get } from 'lib/common/fetch'
-import { useStore, useJwtSecretUpdateStatus } from 'hooks'
-
-import Panel from 'components/ui/Panel'
-import SchemaFormPanel from 'components/to-be-cleaned/forms/SchemaFormPanel'
-
-import { SettingsLayout } from 'components/layouts'
-import Flag from 'components/ui/Flag/Flag'
-import ConfirmModal from 'components/ui/Dialogs/ConfirmDialog'
-import MultiSelect from 'components/ui/MultiSelect'
-import { DisplayApiSettings } from 'components/ui/ProjectSettings'
+import { useStore } from 'hooks'
import { NextPageWithLayout } from 'types'
+import { SettingsLayout } from 'components/layouts'
+import ServiceList from 'components/interfaces/Settings/API/ServiceList'
-const JWT_SECRET_UPDATE_ERROR_MESSAGES = {
- [JwtSecretUpdateError.APIServicesConfigurationUpdateFailed]:
- 'failed to update configuration for API services',
- [JwtSecretUpdateError.APIServicesRestartFailed]: 'failed to restart API services',
- [JwtSecretUpdateError.DatabaseAdminAPIConfigurationUpdateFailed]:
- 'failed to update configuration for database admin API',
- [JwtSecretUpdateError.PostgreSQLRestartFailed]: 'failed to restart PostgreSQL service',
- [JwtSecretUpdateError.SupabaseAPIKeyUpdateFailed]: 'failed to update Supabase API key',
- [JwtSecretUpdateError.APIGatewayUpdateFailed]: 'failed to update API Gateway',
-}
-
-const JWT_SECRET_UPDATE_PROGRESS_MESSAGES = {
- [JwtSecretUpdateProgress.RestartedAPIServices]: 'restarted API services',
- [JwtSecretUpdateProgress.RestartedPostgreSQL]: 'restarted PostgreSQL service',
- [JwtSecretUpdateProgress.Started]: 'started updating',
- [JwtSecretUpdateProgress.UpdatedAPIServicesConfiguration]:
- 'updated configuration for API services',
- [JwtSecretUpdateProgress.UpdatedDatabaseAdminAPIConfiguration]:
- 'updated configuration for database admin API',
- [JwtSecretUpdateProgress.UpdatedAPIGatewayConfiguration]: 'updated configuration for API Gateway',
-}
-
-const PageContext: any = createContext(null)
+export const PageContext: any = createContext(null)
const ApiSettings: NextPageWithLayout = () => {
const router = useRouter()
@@ -81,7 +16,6 @@ const ApiSettings: NextPageWithLayout = () => {
const { meta, ui } = useStore()
const project = ui.selectedProject
- // page context
const PageState: any = useLocalObservable(() => ({
project: null,
projectRef: ref,
@@ -104,7 +38,7 @@ const ApiSettings: NextPageWithLayout = () => {
return (
<PageContext.Provider value={PageState}>
<div className="content h-full w-full overflow-y-auto">
- <ServiceList projectRef={ref} />
+ <ServiceList projectRef={ref as string} />
</div>
</PageContext.Provider>
)
@@ -113,451 +47,3 @@ const ApiSettings: NextPageWithLayout = () => {
ApiSettings.getLayout = (page) => <SettingsLayout title="API Settings">{page}</SettingsLayout>
export default observer(ApiSettings)
-
-const ServiceList: FC<any> = ({ projectRef }) => {
- const { ui } = useStore()
- const router = useRouter()
- const { ref } = router.query
-
- const [showCustomTokenInput, setShowCustomTokenInput] = useState(false)
- const [customToken, setCustomToken] = useState<string>('')
- const [isRegeneratingKey, setIsGeneratingKey] = useState<boolean>(false)
- const [isCreatingKey, setIsCreatingKey] = useState<boolean>(false)
- const [isSubmittingJwtSecretUpdateRequest, setIsSubmittingJwtSecretUpdateRequest] =
- useState<boolean>(false)
-
- const {
- data,
- error,
- mutate: mutateSettings,
- }: any = useSWR(`${API_URL}/props/project/${projectRef}/settings`, get)
- const { data: config, mutate: mutateConfig }: any = useSWR(
- `${API_URL}/projects/${projectRef}/config/postgrest`,
- get
- )
- const {
- changeTrackingId,
- isError: isJwtSecretUpdateStatusError,
- isLoading: isJwtSecretUpdateStatusLoading,
- jwtSecretUpdateError,
- jwtSecretUpdateProgress,
- jwtSecretUpdateStatus,
- mutateJwtSecretUpdateStatus,
- }: any = useJwtSecretUpdateStatus(ref)
-
- const { Failed, Updated, Updating } = JwtSecretUpdateStatus
-
- const isJwtSecretUpdateFailed = jwtSecretUpdateStatus === Failed
- const isNotUpdatingJwtSecret =
- jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === Updated
- const isUpdatingJwtSecret = jwtSecretUpdateStatus === Updating
- const jwtSecretUpdateErrorMessage =
- JWT_SECRET_UPDATE_ERROR_MESSAGES[jwtSecretUpdateError as JwtSecretUpdateError]
- const jwtSecretUpdateProgressMessage =
- JWT_SECRET_UPDATE_PROGRESS_MESSAGES[jwtSecretUpdateProgress as JwtSecretUpdateProgress]
-
- const previousJwtSecretUpdateStatus = useRef()
-
- useEffect(() => {
- if (previousJwtSecretUpdateStatus.current === Updating) {
- switch (jwtSecretUpdateStatus) {
- case Updated:
- mutateConfig()
- mutateSettings()
- ui.setNotification({ category: 'success', message: 'Successfully updated JWT secret' })
- break
- case Failed:
- ui.setNotification({
- category: 'error',
- message: `JWT secret update failed: ${jwtSecretUpdateErrorMessage}`,
- })
- break
- }
- }
-
- previousJwtSecretUpdateStatus.current = jwtSecretUpdateStatus
- }, [jwtSecretUpdateStatus])
-
- if (error || isJwtSecretUpdateStatusError) {
- return (
- <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">
- <Typography.Title level={3}>Error loading API settings</Typography.Title>
- </div>
- )
- }
- if (!data || isJwtSecretUpdateStatusLoading) {
- return (
- <div className="mx-auto p-6 text-center sm:w-full md:w-3/4">
- <Typography.Title level={3}>Loading...</Typography.Title>
- </div>
- )
- }
-
- const { services } = data
-
- // Get the API service
- const API_SERVICE_ID = 1
- const apiService = services.find((x: any) => x.app.id == API_SERVICE_ID)
- const apiConfig = apiService?.app_config
-
- async function handleJwtSecretUpdate(
- jwt_secret: string,
- setModalVisibility: Dispatch<SetStateAction<boolean>>
- ) {
- setIsSubmittingJwtSecretUpdateRequest(true)
- try {
- const trackingId = uuidv4()
- const res = await patch(`${API_URL}/projects/${ref}/config/secrets`, {
- jwt_secret,
- change_tracking_id: trackingId,
- })
- if (res.error) throw res.error
- setModalVisibility(false)
- mutateJwtSecretUpdateStatus()
- ui.setNotification({
- category: 'info',
- message:
- 'Successfully submitted JWT secret update request. Please wait while your project is updated.',
- })
- } catch (error: any) {
- ui.setNotification({ category: 'error', message: error.message })
- } finally {
- setIsSubmittingJwtSecretUpdateRequest(false)
- }
- }
-
- return (
- <>
- <div className="max-w-4xl p-4">
- <section>
- <Panel
- title={
- <Typography.Title level={5} className="mb-0">
- Project URL
- </Typography.Title>
- }
- >
- <Panel.Content>
- <Input
- copy
- label="URL"
- readOnly
- disabled
- className="input-mono"
- value={`https://${apiConfig?.endpoint ?? '-'}`}
- descriptionText="A RESTful endpoint for querying and managing your database."
- layout="horizontal"
- />
- </Panel.Content>
- </Panel>
- </section>
-
- <section>
- <DisplayApiSettings key="DisplayAPISettings" />
- </section>
-
- <section>
- <Panel
- title={
- <Typography.Title level={5} className="mb-0">
- JWT Settings
- </Typography.Title>
- }
- >
- <Panel.Content className="border-panel-border-interior-light dark:border-panel-border-interior-dark space-y-6 border-t">
- <Input
- label="JWT Secret"
- readOnly
- copy={isNotUpdatingJwtSecret}
- reveal={isNotUpdatingJwtSecret}
- disabled
- value={
- isJwtSecretUpdateFailed
- ? 'JWT secret update failed'
- : isUpdatingJwtSecret
- ? 'Updating JWT secret...'
- : config?.jwt_secret || ''
- }
- className="input-mono"
- descriptionText={
- 'Used to decode your JWTs. You can also use this to mint your own JWTs.'
- }
- layout="horizontal"
- />
- <div className="space-y-3">
- <div className="dark:bg-bg-alt-dark bg-bg-alt-light dark:border-dark rounded-md border p-3 px-6 shadow-sm">
- {isUpdatingJwtSecret ? (
- <div className="flex items-center space-x-2">
- <IconLoader className="animate-spin" size={14} />
- <p className="text-sm">
- Updating JWT secret: {jwtSecretUpdateProgressMessage}
- </p>
- </div>
- ) : (
- <div className="w-full space-y-2">
- <div className="flex w-full items-center justify-between">
- <div className="flex flex-col space-y-1">
- <Typography.Text>Generate a new JWT secret</Typography.Text>
- <p className="text-sm opacity-50">
- A random secret will be created, or you can create your own.
- </p>
- </div>
- <div className="flex flex-col items-end">
- {isUpdatingJwtSecret ? (
- <Button loading type="secondary">
- Updating JWT secret...
- </Button>
- ) : (
- <Dropdown
- align="end"
- side="bottom"
- overlay={
- <>
- <Dropdown.Item
- onClick={() => setIsGeneratingKey(true)}
- icon={<IconRefreshCw size={16} />}
- >
- Generate a random secret
- </Dropdown.Item>
- <Dropdown.Seperator />
- <Dropdown.Item
- onClick={() => setIsCreatingKey(true)}
- icon={<IconPenTool size={16} />}
- >
- Create my own secret
- </Dropdown.Item>
- </>
- }
- >
- <Button as="span" type="default" iconRight={<IconChevronDown />}>
- Generate a new secret
- </Button>
- </Dropdown>
- )}
- </div>
- </div>
- </div>
- )}
- </div>
- {isJwtSecretUpdateFailed ? (
- <Alert withIcon variant="warning" title="Failed to update JWT secret">
- Please try again. If the failures persist, please contact Supabase support with
- the following details: <br />
- Change tracking ID: {changeTrackingId} <br />
- Error message: {jwtSecretUpdateErrorMessage}
- </Alert>
- ) : (
- <Alert
- withIcon
- variant="warning"
- title="This will invalidate all existing API keys!"
- >
- Generating a new JWT secret will invalidate <u>all</u> of your API keys,
- including your <code>service_role</code> and <code>anon</code> keys. Your
- project will also be restarted during this process, which will terminate any
- existing connections.
- </Alert>
- )}
- </div>
- </Panel.Content>
- </Panel>
- </section>
-
- <section>{config && <PostgrestConfig config={config} projectRef={projectRef} />}</section>
- </div>
-
- <ConfirmModal
- danger
- visible={isRegeneratingKey}
- title="Are you absolutely sure?"
- description="This action cannot be undone and the old JWT secret will be lost. All existing API keys
- will be invalidated, and any open connections will be terminated."
- buttonLabel="Generate new secret"
- buttonLoadingLabel="Generating"
- onSelectCancel={() => setIsGeneratingKey(false)}
- onSelectConfirm={() => handleJwtSecretUpdate('ROLL', setIsGeneratingKey)}
- />
-
- <Modal
- closable
- header="Create a custom JWT secret"
- visible={isCreatingKey}
- size="medium"
- variant="danger"
- loading={isSubmittingJwtSecretUpdateRequest}
- customFooter={
- <div className="space-x-2">
- <Button type="default" onClick={() => setIsCreatingKey(false)}>
- Cancel
- </Button>
- <Button
- type="primary"
- disabled={
- customToken.length < 32 || customToken.includes('@') || customToken.includes('$')
- }
- loading={isSubmittingJwtSecretUpdateRequest}
- onClick={() => handleJwtSecretUpdate(customToken, setIsCreatingKey)}
- >
- Apply new JWT secret
- </Button>
- </div>
- }
- >
- <Modal.Content>
- <div className="space-y-2 py-4">
- <p className="text-scale-1100 text-sm">
- Create a custom JWT secret. Make sure it is a strong combination of characters that
- cannot be guessed easily.
- </p>
- <Alert
- withIcon
- variant="warning"
- title="All existing API keys will be invalidated, and any open connections will be terminated."
- />
- <Input
- onChange={(e: any) => setCustomToken(e.target.value)}
- value={customToken}
- icon={<IconKey />}
- type={showCustomTokenInput ? 'text' : 'password'}
- className="w-full text-left"
- label="Custom JWT secret"
- descriptionText="Minimally 32 characters long, '@' and '$' are not allowed."
- actions={
- <div className="mr-1 flex items-center justify-center">
- <Button
- type="default"
- icon={showCustomTokenInput ? <IconEye /> : <IconEyeOff />}
- onClick={() => setShowCustomTokenInput(!showCustomTokenInput)}
- />
- </div>
- }
- />
- </div>
- </Modal.Content>
- </Modal>
- </>
- )
-}
-
-const PostgrestConfig = observer(({ config, projectRef }: any) => {
- const PageState: any = useContext(PageContext)
- const { ui } = useStore()
- const { meta } = PageState
-
- const [updates, setUpdates] = useState({
- db_schema: config.db_schema,
- max_rows: config.max_rows,
- db_extra_search_path: config.db_extra_search_path || '',
- })
-
- const updateConfig = async (updatedConfig: any) => {
- try {
- const response = await patch(
- `${API_URL}/projects/${projectRef}/config/postgrest`,
- updatedConfig
- )
- if (response.error) {
- throw response.error
- } else {
- ui.setNotification({ category: 'success', message: 'Successfully saved settings' })
- }
- } catch (error: any) {
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to update config: ${error.message}`,
- })
- }
- }
-
- // manually filter out following schema
- const hiddenSchema = ['auth', 'pgbouncer', 'hooks', 'extensions']
- // following schema is permament
- const permanentSchema = ['public', 'storage']
- // construct list of schema for input controller
- const schema =
- meta.schemas
- .list(
- (x: any) => {
- const find = indexOf(hiddenSchema, x.name)
- if (find < 0) return x
- },
- { allSchemas: true }
- )
- .map((x: any) => {
- return {
- id: x.id,
- value: x.name,
- name: x.name,
- disabled: indexOf(permanentSchema, x.name) >= 0 ? true : false,
- }
- }) ?? []
-
- return (
- <>
- <SchemaFormPanel
- title="Settings"
- schema={{
- properties: {
- db_schema: {
- title: 'Schema',
- type: 'string',
- help: 'The schema to expose in your API. Tables, views and stored procedures in this schema will get API endpoints. Multiple schemas must be comma-separated.',
- },
- max_rows: {
- title: 'Max Rows',
- type: 'integer',
- help: 'The maximum number of rows returns from a view, table, or stored procedure. Limits payload size for accidental or malicious requests.',
- },
- db_extra_search_path: {
- title: 'Extra search path',
- type: 'string',
- help: 'Extra schemas to add to the search_path of every request. Multiple schemas must be comma-separated.',
- },
- },
- required: ['max_rows'],
- type: 'object',
- }}
- model={updates}
- onSubmit={(model: any) => updateConfig(model)}
- onReset={() => setUpdates(config)}
- >
- <div className="space-y-6 py-4">
- {schema.length >= 1 && (
- <MultiSelect
- options={schema}
- // value must be passed as array of strings
- value={updates.db_schema.replace(/ /g, '').split(',')}
- // onChange returns array of strings
- onChange={(event) => {
- let payload = updates
- payload.db_schema = event.join(', ') // permanentSchema.concat(event).join(', ')
- setUpdates({ ...payload })
- updateConfig({ ...payload })
- }}
- label={'Schema'}
- descriptionText={
- <>
- The schema to expose in your API. Tables, views and stored procedures in this
- schema will get API endpoints.<code>public</code> and <code>storage</code> are
- protected by default.
- </>
- }
- emptyMessage={
- <>
- <IconAlertCircle strokeWidth={2} />
- <div className="mt-2 flex flex-col text-center">
- <p className="text-sm align-center">No schema available to choose</p>
- <p className="text-xs opacity-50">New schemas you create will appear here</p>
- </div>
- </>
- }
- />
- )}
- <AutoField name="db_extra_search_path" showInlineError errorMessage="Must be a string." />
- <AutoField name="max_rows" showInlineError errorMessage="Must be a number." />
- </div>
- </SchemaFormPanel>
- </>
- )
-})