The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Support hardening api via custom schema in api settings (#27894)
Joshen Limb78eea5176d0
diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsxindex 583cde1526b..143937a8982 100644--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import { useParams } from 'common'-import { Check, Loader2 } from 'lucide-react'+import { Check, ExternalLink, Loader2 } from 'lucide-react'import Link from 'next/link'import { useEffect, useState } from 'react'import { useForm } from 'react-hook-form'@@ -26,7 +26,6 @@ import {FormMessage_Shadcn_,Form_Shadcn_,IconAlertCircle,- IconExternalLink,Input_Shadcn_,Modal,} from 'ui'@@ -165,7 +164,7 @@ const CreateBranchModal = ({ visible, onClose }: CreateBranchModalProps) => {target="_blank"rel="noreferrer">- <IconExternalLink size={14} strokeWidth={1.5} />+ <ExternalLink size={14} strokeWidth={1.5} /></Link></div></div>diff --git a/apps/studio/components/interfaces/Settings/API/HardenAPIModal.tsx b/apps/studio/components/interfaces/Settings/API/HardenAPIModal.tsxnew file mode 100644index 00000000000..d98e0646f5b--- /dev/null+++ b/apps/studio/components/interfaces/Settings/API/HardenAPIModal.tsx@@ -0,0 +1,263 @@+import { Check, ChevronDown, ExternalLink } from 'lucide-react'+import toast from 'react-hot-toast'++import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import InformationBox from 'components/ui/InformationBox'+import { useCreateAndExposeAPISchemaMutation } from 'data/api-settings/create-and-expose-api-schema-mutation'+import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'+import { useProjectPostgrestConfigUpdateMutation } from 'data/config/project-postgrest-config-update-mutation'+import { useSchemasQuery } from 'data/database/schemas-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'+import {+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Alert_Shadcn_,+ Button,+ CodeBlock,+ CollapsibleContent_Shadcn_,+ CollapsibleTrigger_Shadcn_,+ Collapsible_Shadcn_,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogSection,+ DialogSectionSeparator,+ DialogTitle,+} from 'ui'+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'++interface HardenAPIModalProps {+ visible: boolean+ onClose: () => void+}++export const HardenAPIModal = ({ visible, onClose }: HardenAPIModalProps) => {+ const project = useSelectedProject()++ const { data: schemas } = useSchemasQuery({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ })+ const { data: config } = useProjectPostgrestConfigQuery({ projectRef: project?.ref })++ const hasAPISchema = (schemas ?? []).find((schema) => schema.name === 'api')+ const exposedSchemas = config?.db_schema.split(',').map((x) => x.trim()) ?? []+ const isAPISchemaExposed = exposedSchemas.includes('api')+ const isPublicSchemaExposed = exposedSchemas.includes('public')++ const { mutate: createAndExposeAPISchema, isLoading: isCreatingAPISchema } =+ useCreateAndExposeAPISchemaMutation({+ onSuccess: () => {+ toast.success(`Successfully created api schema and exposed via Data API`)+ },+ })++ const { mutate: updatePostgrestConfig, isLoading: isUpdatingConfig } =+ useProjectPostgrestConfigUpdateMutation({+ onSuccess: () => {+ toast.success('Success removed public schema from exposed schemas')+ },+ })++ const onSelectCreateAndExposeAPISchema = () => {+ if (project === undefined) return console.error('Project is required')+ if (config === undefined) return console.error('Postgrest config is required')+ createAndExposeAPISchema({+ projectRef: project?.ref,+ connectionString: project?.connectionString,+ existingPostgrestConfig: {+ max_rows: config.max_rows,+ db_pool: config.db_pool,+ db_schema: config.db_schema,+ db_extra_search_path: config?.db_extra_search_path,+ },+ })+ }++ const onSelectRemovePublicSchema = () => {+ if (project === undefined) return console.error('Project is required')+ if (config === undefined) return console.error('Postgrest config is required')++ const updatedDbExtraSearchPath = config.db_extra_search_path+ .split(',')+ .map((x) => x.trim())+ .filter((x) => x !== 'public')+ .join(', ')+ const updatedDbSchema = config.db_schema+ .split(',')+ .map((x) => x.trim())+ .filter((x) => x !== 'public')+ .join(', ')+ updatePostgrestConfig({+ projectRef: project.ref,+ maxRows: config.max_rows,+ dbPool: config.db_pool,+ dbSchema: updatedDbSchema,+ dbExtraSearchPath: updatedDbExtraSearchPath,+ })+ }++ return (+ <Dialog open={visible} onOpenChange={onClose}>+ <DialogContent size="large">+ <DialogHeader>+ <DialogTitle>Switch the default API schema</DialogTitle>+ <DialogDescription>+ Expose a custom schema instead of the{' '}+ <code className="text-xs text-foreground">public</code> schema+ </DialogDescription>+ </DialogHeader>++ <DialogSectionSeparator />++ <DialogSection className="text-sm text-foreground-light">+ <p>+ By default, the <code className="text-xs text-foreground">public</code> schema is used+ to generate API routes. In some cases, it's better to use a custom schema. This is+ important if you use tools that generate tables in the{' '}+ <code className="text-xs text-foreground">public</code> schema to{' '}+ <span className="text-brand">prevent accidental exposure of data</span>.+ </p>+ <Button asChild type="default" icon={<ExternalLink />} className="w-min mt-4">+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/database/hardening-data-api"+ >+ Documentation+ </a>+ </Button>+ </DialogSection>++ <DialogSectionSeparator />++ <Collapsible_Shadcn_>+ <CollapsibleTrigger_Shadcn_ className="py-4 px-5 w-full flex items-center justify-between text-sm">+ <p>+ 1. Create a custom <code className="text-xs text-foreground">api</code> schema and+ expose it+ </p>+ {hasAPISchema && isAPISchemaExposed ? (+ <Check size={16} className="text-brand" />+ ) : (+ <ChevronDown+ size={16}+ className="transition data-open-parent:rotate-180 data-closed-parent:rotate-0"+ />+ )}+ </CollapsibleTrigger_Shadcn_>+ <CollapsibleContent_Shadcn_ className="text-sm text-foreground-light flex flex-col gap-y-4">+ <p className="mx-5">+ Click the button below to create a new schema named{' '}+ <code className="text-xs text-foreground">api</code> and grant the{' '}+ <code className="text-xs text-foreground">anon</code> and{' '}+ <code className="text-xs text-foreground">authenticated</code> roles usage privileges+ on this schema. This schema will thereafter also be exposed to the Data API.+ </p>++ <div className="px-5">+ <InformationBox+ title="How is the schema created?"+ description={+ <div className="flex flex-col gap-y-2">+ <p>+ The following query will be run to create the{' '}+ <code className="text-xs text-foreground">api</code> schema , as well as to+ grant the necessary privileges to the respective roles+ </p>+ <CodeBlock+ language="sql"+ className="p-1 language-bash prose dark:prose-dark max-w-[68.3ch]"+ >+ {`create schema if not exists api;\ngrant usage on schema api to anon, authenticated;`}+ </CodeBlock>+ </div>+ }+ />+ </div>++ <ButtonTooltip+ type="primary"+ className="w-min mx-5"+ onClick={onSelectCreateAndExposeAPISchema}+ disabled={hasAPISchema && isAPISchemaExposed}+ loading={isCreatingAPISchema}+ tooltip={{+ content: { side: 'right', text: 'Schema has already been created and exposed' },+ }}+ >+ Create and expose schema to Data API+ </ButtonTooltip>++ <div className="flex flex-col gap-y-4 px-5 pb-4">+ <p>+ Under these new settings, the <code className="text-xs text-foreground">anon</code>{' '}+ and <code className="text-xs text-foreground">authenticated</code> roles can execute+ functions defined in the <code className="text-xs text-foreground">api</code>{' '}+ schema, but they have no automatic permissions on any tables. On a table-by-table+ basis, you can grant them permissions by running the following command:+ </p>+ <CodeBlock+ language="sql"+ className="p-1 language-bash prose dark:prose-dark max-w-[68.3ch]"+ >+ {`grant select on table api.<your_table> to anon;\ngrant select, insert, update, delete on table api.<your_table> to authenticated;`}+ </CodeBlock>+ </div>+ </CollapsibleContent_Shadcn_>+ </Collapsible_Shadcn_>++ <DialogSectionSeparator />++ <Collapsible_Shadcn_>+ <CollapsibleTrigger_Shadcn_ className="py-4 px-5 w-full flex items-center justify-between text-sm">+ <p>+ 2. Remove the <code className="text-xs text-foreground">public</code> schema from the+ exposed schemas+ </p>+ {!isPublicSchemaExposed ? (+ <Check size={16} className="text-brand" />+ ) : (+ <ChevronDown+ size={16}+ className="transition data-open-parent:rotate-180 data-closed-parent:rotate-0"+ />+ )}+ </CollapsibleTrigger_Shadcn_>+ <CollapsibleContent_Shadcn_ className="text-sm text-foreground-light">+ <div className="px-5 pb-4 flex flex-col gap-y-4">+ <Alert_Shadcn_ variant="warning">+ <WarningIcon />+ <AlertTitle_Shadcn_ className="text-foreground">+ Ensure that your app is no longer using the{' '}+ <code className="text-xs text-foreground">public</code> schema+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ The <code className="text-xs text-foreground">public</code> schema will not be+ accessible via the API once its not exposed. You should be using the{' '}+ <code className="text-xs text-foreground">api</code> schema instead.+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ <p>+ Click the button below to remove the{' '}+ <code className="text-xs text-foreground">public</code> schema from both Exposed+ schemas and Extra search path in your API configuration.+ </p>+ <ButtonTooltip+ type="primary"+ className="w-min"+ disabled={!isPublicSchemaExposed}+ loading={isUpdatingConfig}+ tooltip={{ content: { side: 'right', text: 'Public schema no longer exposed' } }}+ onClick={onSelectRemovePublicSchema}+ >+ Remove public schema from exposed schemas+ </ButtonTooltip>+ </div>+ </CollapsibleContent_Shadcn_>+ </Collapsible_Shadcn_>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsxindex e5b3f84fd80..74a4e37997e 100644--- a/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx+++ b/apps/studio/components/interfaces/Settings/API/PostgrestConfig.tsx@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'import { indexOf } from 'lodash'import Link from 'next/link'-import { useEffect } from 'react'+import { useEffect, useState } from 'react'import { useForm } from 'react-hook-form'import toast from 'react-hot-toast'import { z } from 'zod'@@ -48,6 +48,8 @@ import {MultiSelectorList,MultiSelectorTrigger,} from 'ui-patterns/multi-select'+import { ExternalLink, Lock } from 'lucide-react'+import { HardenAPIModal } from './HardenAPIModal'const formSchema = z.object({@@ -75,10 +77,12 @@ const formSchema = z})-const PostgrestConfig = () => {+export const PostgrestConfig = () => {const { ref: projectRef } = useParams()const { project } = useProjectContext()+ const [showModal, setShowModal] = useState(false)+const { data: config, isError } = useProjectPostgrestConfigQuery({ projectRef })const { data: extensions } = useDatabaseExtensionsQuery({projectRef: project?.ref,@@ -185,266 +189,286 @@ const PostgrestConfig = () => {const isDataApiEnabledInForm = form.getValues('enableDataApi')return (- <Form_Shadcn_ {...form}>- <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>- <FormPanelContainer>- <FormPanelHeader>Data API Settings</FormPanelHeader>- <FormPanelContent>- {isError ? (- <Admonition type="destructive" title="Failed to retrieve API settings" />- ) : (- <>- <FormField_Shadcn_- control={form.control}- name="enableDataApi"- render={({ field }) => (- <FormItem_Shadcn_ className="w-full">- <FormItemLayout- className="w-full px-8 py-8"- layout="flex"- label="Enable Data API"- description="When enabled you will be able to use any Supabase client library and PostgREST endpoints with any schema configured below."- >- <FormControl_Shadcn_>- <Switch- size="large"- disabled={!canUpdatePostgrestConfig}- checked={field.value}- onCheckedChange={(value) => {- field.onChange(value)+ <>+ <Form_Shadcn_ {...form}>+ <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>+ <FormPanelContainer>+ <FormPanelHeader className="flex items-center justify-between">+ <span>Data API Settings</span>+ <div className="flex items-center gap-x-2">+ <Button asChild type="default" icon={<ExternalLink />}>+ <a+ target="_blank"+ rel="noreferrer"+ href="https://supabase.com/docs/guides/database/connecting-to-postgres#data-apis"+ >+ Documentation+ </a>+ </Button>+ <Button type="default" icon={<Lock />} onClick={() => setShowModal(true)}>+ Harden Data API+ </Button>+ </div>+ </FormPanelHeader>+ <FormPanelContent>+ {isError ? (+ <Admonition type="destructive" title="Failed to retrieve API settings" />+ ) : (+ <>+ <FormField_Shadcn_+ control={form.control}+ name="enableDataApi"+ render={({ field }) => (+ <FormItem_Shadcn_ className="w-full">+ <FormItemLayout+ className="w-full px-8 py-8"+ layout="flex"+ label="Enable Data API"+ description="When enabled you will be able to use any Supabase client library and PostgREST endpoints with any schema configured below."+ >+ <FormControl_Shadcn_>+ <Switch+ size="large"+ disabled={!canUpdatePostgrestConfig}+ checked={field.value}+ onCheckedChange={(value) => {+ field.onChange(value)- if (!value) {- /**- * reset the form to default values- */- resetForm({ enableDataApi: false, dbSchema: [] })- /**- * remove all the schema values when disabling the Data API- */- } else {- /**- * reset the form to default values- * when disabled the Data API- */+ if (!value) {+ /**+ * reset the form to default values+ */+ resetForm({ enableDataApi: false, dbSchema: [] })+ /**+ * remove all the schema values when disabling the Data API+ */+ } else {+ /**+ * reset the form to default values+ * when disabled the Data API+ */- resetForm({ enableDataApi: true })- }- }}- />- </FormControl_Shadcn_>- </FormItemLayout>+ resetForm({ enableDataApi: true })+ }+ }}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>- {!field.value && (- <>- <Separator />- <Alert_Shadcn_- variant="warning"- className="mb-0 border-none rounded-none"- >- <WarningIcon className="!left-[2rem]" />- <AlertTitle_Shadcn_ className="!pl-[3.5rem] !left-[6rem]">- No schemas can be queried- </AlertTitle_Shadcn_>- <AlertDescription_Shadcn_ className="!pl-[3.5rem]">- <p>- With this setting disabled, you will not be able to query any- schemas via the Data API.- </p>- <p>- You will see errors from the Postgrest endpoint- <code className="text-xs">/rest/v1/</code>.- </p>- </AlertDescription_Shadcn_>- </Alert_Shadcn_>- </>- )}- </FormItem_Shadcn_>- )}- />- <Collapsible_Shadcn_ open={form.getValues('enableDataApi')}>- <CollapsibleContent_Shadcn_ className="border-t divide-y transition-all data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">- <FormField_Shadcn_- control={form.control}- name="dbSchema"- render={({ field }) => (- <FormItem_Shadcn_ className="w-full">- <FormItemLayout- label="Exposed schemas"- description="The schemas to expose in your API. Tables, views and stored procedures in+ {!field.value && (+ <>+ <Separator />+ <Alert_Shadcn_+ variant="warning"+ className="mb-0 border-none rounded-none"+ >+ <WarningIcon className="!left-[2rem]" />+ <AlertTitle_Shadcn_ className="!pl-[3.5rem] !left-[6rem]">+ No schemas can be queried+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_ className="!pl-[3.5rem]">+ <p>+ With this setting disabled, you will not be able to query any+ schemas via the Data API.+ </p>+ <p>+ You will see errors from the Postgrest endpoint+ <code className="text-xs">/rest/v1/</code>.+ </p>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ </>+ )}+ </FormItem_Shadcn_>+ )}+ />+ <Collapsible_Shadcn_ open={form.getValues('enableDataApi')}>+ <CollapsibleContent_Shadcn_ className="border-t divide-y transition-all data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">+ <FormField_Shadcn_+ control={form.control}+ name="dbSchema"+ render={({ field }) => (+ <FormItem_Shadcn_ className="w-full">+ <FormItemLayout+ label="Exposed schemas"+ description="The schemas to expose in your API. Tables, views and stored procedures inthese schemas will get API endpoints."- layout="horizontal"- className="px-8 py-8"- >- {isLoadingSchemas ? (- <div className="col-span-12 flex flex-col gap-2 lg:col-span-7">- <Skeleton className="w-full h-[38px]" />- </div>- ) : (- <MultiSelector- onValuesChange={field.onChange}- values={field.value}- size={'small'}- disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}- >- <MultiSelectorTrigger>- <MultiSelectorInput placeholder="Select schemas for Data API..." />- </MultiSelectorTrigger>- <MultiSelectorContent>- {schema.length <= 0 ? (- <MultiSelectorList>- <MultiSelectorItem key={'empty'} value={'no'}>- no- </MultiSelectorItem>- </MultiSelectorList>- ) : (- <MultiSelectorList>- {schema.map((x, i) => (- <MultiSelectorItem key={x.id + '-' + i} value={x.name}>- {x.name}+ layout="horizontal"+ className="px-8 py-8"+ >+ {isLoadingSchemas ? (+ <div className="col-span-12 flex flex-col gap-2 lg:col-span-7">+ <Skeleton className="w-full h-[38px]" />+ </div>+ ) : (+ <MultiSelector+ onValuesChange={field.onChange}+ values={field.value}+ size={'small'}+ disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}+ >+ <MultiSelectorTrigger>+ <MultiSelectorInput placeholder="Select schemas for Data API..." />+ </MultiSelectorTrigger>+ <MultiSelectorContent>+ {schema.length <= 0 ? (+ <MultiSelectorList>+ <MultiSelectorItem key={'empty'} value={'no'}>+ no</MultiSelectorItem>- ))}- </MultiSelectorList>- )}- </MultiSelectorContent>- </MultiSelector>- )}-- {!field.value.includes('public') && field.value.length > 0 && (- <Admonition- type="default"- title="The public schema for this project is not exposed"- className="mt-2"- description={- <>- <p>- You will not be able to query tables and views in the{' '}- <code>public</code> schema via supabase-js or HTTP clients.- </p>- {isGraphqlExtensionEnabled && (- <>- <p>- Tables in the <code className="text-xs">public</code>{' '}- schema are still exposed over our GraphQL endpoints.- </p>- <Button asChild type="default">- <Link href={`/project/${projectRef}/database/extensions`}>- Disable the pg_graphql extension- </Link>- </Button>- </>+ </MultiSelectorList>+ ) : (+ <MultiSelectorList>+ {schema.map((x, i) => (+ <MultiSelectorItem key={x.id + '-' + i} value={x.name}>+ {x.name}+ </MultiSelectorItem>+ ))}+ </MultiSelectorList>)}- </>- }- />- )}- </FormItemLayout>- </FormItem_Shadcn_>- )}- />+ </MultiSelectorContent>+ </MultiSelector>+ )}- <FormField_Shadcn_- control={form.control}- name="dbExtraSearchPath"- render={({ field }) => (- <FormItem_Shadcn_ className="w-full">- <FormItemLayout- className="w-full px-8 py-8"- layout="horizontal"- label="Extra search path"- description="Extra schemas to add to the search path of every request. Multiple schemas must be comma-separated."- >- <FormControl_Shadcn_>- <Input_Shadcn_- size="small"- disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}- {...field}- />- </FormControl_Shadcn_>- </FormItemLayout>- </FormItem_Shadcn_>- )}- />+ {!field.value.includes('public') && field.value.length > 0 && (+ <Admonition+ type="default"+ title="The public schema for this project is not exposed"+ className="mt-2"+ description={+ <>+ <p>+ You will not be able to query tables and views in the{' '}+ <code>public</code> schema via supabase-js or HTTP clients.+ </p>+ {isGraphqlExtensionEnabled && (+ <>+ <p>+ Tables in the <code className="text-xs">public</code>{' '}+ schema are still exposed over our GraphQL endpoints.+ </p>+ <Button asChild type="default">+ <Link+ href={`/project/${projectRef}/database/extensions`}+ >+ Disable the pg_graphql extension+ </Link>+ </Button>+ </>+ )}+ </>+ }+ />+ )}+ </FormItemLayout>+ </FormItem_Shadcn_>+ )}+ />- <FormField_Shadcn_- control={form.control}- name="maxRows"- render={({ field }) => (- <FormItem_Shadcn_ className="w-full">- <FormItemLayout- className="w-full px-8 py-8"- layout="horizontal"- label="Max rows"- description="The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests."- >- <FormControl_Shadcn_>- <Input_Shadcn_- size="small"- disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}- {...field}- type="number"- {...form.register('maxRows', {- valueAsNumber: true, // Ensure the value is handled as a number- })}- />- </FormControl_Shadcn_>- </FormItemLayout>- </FormItem_Shadcn_>- )}- />+ <FormField_Shadcn_+ control={form.control}+ name="dbExtraSearchPath"+ render={({ field }) => (+ <FormItem_Shadcn_ className="w-full">+ <FormItemLayout+ className="w-full px-8 py-8"+ layout="horizontal"+ label="Extra search path"+ description="Extra schemas to add to the search path of every request. Multiple schemas must be comma-separated."+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ size="small"+ disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}+ {...field}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ </FormItem_Shadcn_>+ )}+ />- <FormField_Shadcn_- control={form.control}- name="dbPool"- render={({ field }) => (- <FormItem_Shadcn_ className="w-full">- <FormItemLayout- className="w-full px-8 py-8"- layout="horizontal"- label="Pool size"- description="Number of maximum connections to keep open in the Data API server's database pool. Unset to let it be configured automatically based on compute size."- >- <FormControl_Shadcn_>- <Input_Shadcn_- size="small"- disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}- {...field}- type="number"- placeholder="Configured automatically based on compute size"- onChange={(e) =>- field.onChange(- e.target.value === '' ? null : Number(e.target.value)- )- }- value={field.value === null ? '' : field.value}- />- </FormControl_Shadcn_>- </FormItemLayout>- </FormItem_Shadcn_>- )}- />- </CollapsibleContent_Shadcn_>- </Collapsible_Shadcn_>- </>- )}- <FormPanelFooter className="flex px-8 py-4">- <FormActions- form={formId}- isSubmitting={isUpdating}- hasChanges={form.formState.isDirty}- handleReset={resetForm}- disabled={!canUpdatePostgrestConfig}- helper={- !canUpdatePostgrestConfig- ? "You need additional permissions to update your project's API settings"- : undefined- }- />- </FormPanelFooter>- </FormPanelContent>- </FormPanelContainer>- </form>- </Form_Shadcn_>+ <FormField_Shadcn_+ control={form.control}+ name="maxRows"+ render={({ field }) => (+ <FormItem_Shadcn_ className="w-full">+ <FormItemLayout+ className="w-full px-8 py-8"+ layout="horizontal"+ label="Max rows"+ description="The maximum number of rows returned from a view, table, or stored procedure. Limits payload size for accidental or malicious requests."+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ size="small"+ disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}+ {...field}+ type="number"+ {...form.register('maxRows', {+ valueAsNumber: true, // Ensure the value is handled as a number+ })}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ </FormItem_Shadcn_>+ )}+ />++ <FormField_Shadcn_+ control={form.control}+ name="dbPool"+ render={({ field }) => (+ <FormItem_Shadcn_ className="w-full">+ <FormItemLayout+ className="w-full px-8 py-8"+ layout="horizontal"+ label="Pool size"+ description="Number of maximum connections to keep open in the Data API server's database pool. Unset to let it be configured automatically based on compute size."+ >+ <FormControl_Shadcn_>+ <Input_Shadcn_+ size="small"+ disabled={!canUpdatePostgrestConfig || !isDataApiEnabledInForm}+ {...field}+ type="number"+ placeholder="Configured automatically based on compute size"+ onChange={(e) =>+ field.onChange(+ e.target.value === '' ? null : Number(e.target.value)+ )+ }+ value={field.value === null ? '' : field.value}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ </FormItem_Shadcn_>+ )}+ />+ </CollapsibleContent_Shadcn_>+ </Collapsible_Shadcn_>+ </>+ )}+ <FormPanelFooter className="flex px-8 py-4">+ <FormActions+ form={formId}+ isSubmitting={isUpdating}+ hasChanges={form.formState.isDirty}+ handleReset={resetForm}+ disabled={!canUpdatePostgrestConfig}+ helper={+ !canUpdatePostgrestConfig+ ? "You need additional permissions to update your project's API settings"+ : undefined+ }+ />+ </FormPanelFooter>+ </FormPanelContent>+ </FormPanelContainer>+ </form>+ </Form_Shadcn_>++ <HardenAPIModal visible={showModal} onClose={() => setShowModal(false)} />+ </>)}--export default PostgrestConfigdiff --git a/apps/studio/components/interfaces/Settings/API/ServiceList.tsx b/apps/studio/components/interfaces/Settings/API/ServiceList.tsxindex 1f8cef611a3..601c58f4654 100644--- a/apps/studio/components/interfaces/Settings/API/ServiceList.tsx+++ b/apps/studio/components/interfaces/Settings/API/ServiceList.tsx@@ -21,7 +21,7 @@ import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { Badge, Input } from 'ui'import { JWT_SECRET_UPDATE_ERROR_MESSAGES } from './API.constants'import JWTSettings from './JWTSettings'-import PostgrestConfig from './PostgrestConfig'+import { PostgrestConfig } from './PostgrestConfig'const ServiceList = () => {const client = useQueryClient()diff --git a/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.tsnew file mode 100644index 00000000000..ae4643c084f--- /dev/null+++ b/apps/studio/data/api-settings/create-and-expose-api-schema-mutation.ts@@ -0,0 +1,87 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import toast from 'react-hot-toast'++import { executeSql } from 'data/sql/execute-sql-query'+import { sqlKeys } from 'data/sql/keys'+import type { ResponseError } from 'types'+import { handleError, patch } from 'data/fetchers'+import { components } from 'api-types'+import { configKeys } from 'data/config/keys'++export type CreateAndExposeAPISchemaVariables = {+ projectRef: string+ connectionString?: string+ existingPostgrestConfig: {+ db_pool: any+ max_rows: number+ db_extra_search_path: string+ db_schema: string+ }+}++export async function createAndExposeApiSchema({+ projectRef,+ connectionString,+ existingPostgrestConfig,+}: CreateAndExposeAPISchemaVariables) {+ const sql = `+create schema if not exists api;+grant usage on schema api to anon, authenticated;+ `.trim()++ await executeSql({ projectRef, connectionString, sql })++ const { db_extra_search_path, db_pool, db_schema, max_rows } = existingPostgrestConfig+ const { error } = await patch('/platform/projects/{ref}/config/postgrest', {+ params: { path: { ref: projectRef } },+ body: {+ db_pool,+ max_rows,+ db_extra_search_path,+ db_schema: `api, ${db_schema}`,+ },+ })++ if (error) handleError(error)+ return true+}++type CreateAndExposeAPISchemaData = Awaited<ReturnType<typeof createAndExposeApiSchema>>++export const useCreateAndExposeAPISchemaMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ CreateAndExposeAPISchemaData,+ ResponseError,+ CreateAndExposeAPISchemaVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ CreateAndExposeAPISchemaData,+ ResponseError,+ CreateAndExposeAPISchemaVariables+ >((vars) => createAndExposeApiSchema(vars), {+ async onSuccess(data, variables, context) {+ const { projectRef } = variables+ await Promise.all([+ queryClient.invalidateQueries(sqlKeys.query(projectRef, ['schemas', 'list'])),+ queryClient.invalidateQueries(configKeys.postgrest(projectRef)),+ ])+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to create and expose API schema: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/api-settings/remove-public-schema-from-expose-and-disable-pg_graphql-mutation.ts b/apps/studio/data/api-settings/remove-public-schema-from-expose-and-disable-pg_graphql-mutation.tsnew file mode 100644index 00000000000..e45410616ca--- /dev/null+++ b/apps/studio/data/api-settings/remove-public-schema-from-expose-and-disable-pg_graphql-mutation.ts@@ -0,0 +1,105 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import toast from 'react-hot-toast'++import { configKeys } from 'data/config/keys'+import { databaseExtensionsKeys } from 'data/database-extensions/keys'+import { del, handleError, patch } from 'data/fetchers'+import type { ResponseError } from 'types'++export type RemovePublicSchemaAndDisablePgGraphqlVariables = {+ projectRef: string+ connectionString?: string+ existingPostgrestConfig: {+ db_pool: any+ max_rows: number+ db_extra_search_path: string+ db_schema: string+ }+}++export async function removePublicFromExposedSchemasAndDisablePgGraphql({+ projectRef,+ connectionString,+ existingPostgrestConfig,+}: RemovePublicSchemaAndDisablePgGraphqlVariables) {+ const { db_extra_search_path, db_pool, db_schema, max_rows } = existingPostgrestConfig+ const updatedDbExtraSearchPath = db_extra_search_path+ .split(', ')+ .filter((x) => x !== 'public')+ .join(', ')+ const updatedDbSchema = db_schema+ .split(', ')+ .filter((x) => x !== 'public')+ .join(', ')++ const { error: configError } = await patch('/platform/projects/{ref}/config/postgrest', {+ params: { path: { ref: projectRef } },+ body: {+ db_pool,+ max_rows,+ db_extra_search_path: updatedDbExtraSearchPath,+ db_schema: updatedDbSchema,+ },+ })++ if (configError) handleError(configError)++ let headers = new Headers()+ if (connectionString) headers.set('x-connection-encrypted', connectionString)+ const { error: extensionsError } = await del('/platform/pg-meta/{ref}/extensions', {+ params: {+ header: { 'x-connection-encrypted': connectionString! },+ path: { ref: projectRef },+ query: { id: 'pg_graphql' },+ },+ headers,+ })++ if (extensionsError) handleError(extensionsError)++ return true+}++type RemovePublicSchemaAndDisablePgGraphqlData = Awaited<+ ReturnType<typeof removePublicFromExposedSchemasAndDisablePgGraphql>+>++export const useRemovePublicSchemaAndDisablePgGraphqlMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ RemovePublicSchemaAndDisablePgGraphqlData,+ ResponseError,+ RemovePublicSchemaAndDisablePgGraphqlVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<+ RemovePublicSchemaAndDisablePgGraphqlData,+ ResponseError,+ RemovePublicSchemaAndDisablePgGraphqlVariables+ >((vars) => removePublicFromExposedSchemasAndDisablePgGraphql(vars), {+ async onSuccess(data, variables, context) {+ const { projectRef } = variables+ await Promise.all([+ queryClient.invalidateQueries(configKeys.postgrest(projectRef)),+ queryClient.invalidateQueries(databaseExtensionsKeys.list(projectRef)),+ ])+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(+ `Failed to remove public schema and disable pg_graphql extension: ${data.message}`+ )+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}