Files
supabase/apps/studio/pages/api/ai/sql/policy.ts
T
Matt Rossman a133ef60a6 fix(studio): correct the Assistant's blocked-tool privacy message (#50411)
When the Assistant calls a tool that's blocked on permissions, the
response had two problems.

First, it told users their data goes to Amazon Bedrock when production
inference [routes to
OpenAI](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/pages/api/ai/sql/generate-v4.ts#L170-L172).
It now says "third-party AI providers" like the [opt-in
settings](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/components/interfaces/Organization/GeneralSettings/AIOptInLevelSelector.tsx#L84-L88)
do. I verified that was the last user-facing Bedrock mention.

Second, HIPAA-restricted projects got that same copy telling them to
change data opt-in settings, but for those projects `getAIDetails`
[forces their level to
`disabled`](https://github.com/supabase/supabase/blob/b824acdfd204071f931a0aee01bee953ef164b6b/apps/studio/lib/ai/ai-details.ts#L70-L73).
They get separate copy now to prevent confusion.

Closes AI-1154


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
  - Added HIPAA-aware AI controls for eligible projects.
  - AI opt-in is automatically disabled when HIPAA requirements apply.
- Privacy messages now distinguish standard AI opt-in restrictions from
HIPAA-related restrictions.
- AI-assisted SQL and tool experiences consistently apply HIPAA
restrictions when determining available capabilities.
- **Bug Fixes**
- Improved handling of AI settings for HIPAA-sensitive projects and
invalid project or organization configurations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-09-16 08:16:49 -04:00

187 lines
6.9 KiB
TypeScript

import type { JwtPayload } from '@supabase/supabase-js'
import { generateText, isStepCount, Output } from 'ai'
import { IS_PLATFORM } from 'common'
import { source } from 'common-tags'
import { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
import { getAIDetails } from '@/lib/ai/ai-details'
import { isExplorerEnabled } from '@/lib/ai/is-explorer-enabled'
import { getModel } from '@/lib/ai/model'
import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
import { RLS_PROMPT } from '@/lib/ai/prompts'
import { getTools } from '@/lib/ai/tools'
import { apiWrapper } from '@/lib/api/apiWrapper'
import { trustedUserEmail } from '@/lib/server/configcat'
const policySchema = z.object({
sql: z.string().describe('The generated Postgres CREATE POLICY statement.'),
name: z.string().describe('The name of the policy.'),
command: z
.enum(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALL'])
.describe('The SQL command this policy applies to.'),
definition: z
.string()
.optional()
.describe('The USING clause expression (for SELECT, UPDATE, DELETE).'),
check: z.string().optional().describe('The WITH CHECK clause expression (for INSERT, UPDATE).'),
action: z
.enum(['PERMISSIVE', 'RESTRICTIVE'])
.default('PERMISSIVE')
.describe('Whether the policy is PERMISSIVE or RESTRICTIVE.'),
roles: z.array(z.string()).default(['public']).describe('The roles this policy applies to.'),
})
const requestBodySchema = z.object({
tableName: z.string().min(1),
schema: z.string().default('public'),
columns: z.array(z.string()).optional(),
projectRef: z.string().min(1),
connectionString: z.string().min(1),
orgSlug: z.string().optional(),
message: z.string().optional(),
})
async function handler(req: NextApiRequest, res: NextApiResponse, claims?: JwtPayload) {
const { method } = req
switch (method) {
case 'POST':
return handlePost(req, res, claims)
default:
res.setHeader('Allow', ['POST'])
res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
}
}
export async function handlePost(req: NextApiRequest, res: NextApiResponse, claims?: JwtPayload) {
const authorization = req.headers.authorization
const accessToken = authorization?.replace('Bearer ', '')
if (IS_PLATFORM && !accessToken) {
return res.status(401).json({ error: 'Authorization token is required' })
}
const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
const { data, error: parseError } = requestBodySchema.safeParse(body)
if (parseError) {
return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
}
const { tableName, schema, columns = [], projectRef, connectionString, orgSlug, message } = data
let aiOptInLevel: AiOptInLevel = 'disabled'
let isRestrictedByHipaa = false
if (!IS_PLATFORM) {
aiOptInLevel = 'schema'
}
if (IS_PLATFORM && orgSlug && authorization && projectRef) {
try {
const aiDetails = await getAIDetails({ orgSlug, projectRef, authorization })
aiOptInLevel = aiDetails.aiOptInLevel
isRestrictedByHipaa = aiDetails.isRestrictedByHipaa
} catch (error) {
return res.status(400).json({
error: 'There was an error fetching your organization details',
})
}
}
const explorerEnabled = await isExplorerEnabled(trustedUserEmail(claims?.email))
try {
const { modelParams, error: modelError } = await getModel({
provider: 'openai',
modelEntry: DEFAULT_COMPLETION_MODEL,
})
if (modelError) {
return res.status(500).json({ error: modelError.message })
}
// Closes the remote MCP connection opened in getTools when generation is done,
// if anything below throws, or if the client disconnects mid-generation so the
// connection isn't held until generateText resolves on its own (mirrors the
// request-scoped cleanup in generate-v4.ts).
const toolsAbortController = new AbortController()
req.on('close', () => toolsAbortController.abort())
req.on('aborted', () => toolsAbortController.abort())
// Fires when the response finishes or the connection drops.
res.on('close', () => toolsAbortController.abort())
try {
const tools = await getTools({
projectRef,
connectionString,
authorization,
aiOptInLevel,
isRestrictedByHipaa,
accessToken,
isExplorerEnabled: explorerEnabled,
signal: toolsAbortController.signal,
})
const { output } = await generateText({
...modelParams,
stopWhen: isStepCount(5),
prompt: source`
You are a Postgres RLS (Row Level Security) expert.
Determine the most appropriate policies for the "${schema}"."${tableName}" table within a Supabase project.
${columns.length > 0 ? `Table columns: ${columns.join(', ')}` : 'No column metadata provided.'}
${message ? `User request: ${message}` : ''}
RLS Guide: ${RLS_PROMPT}
Requirements:
- Use the available planning and schema tools (like "list_policies" or "list_tables") to inspect the "${schema}" schema and existing policies before generating new ones.
- Ensure policies strictly adhere to the existing schema
- Return a curated list of recommended CREATE POLICY statements as JSON.
- Each policy must include: name, sql, command (SELECT/INSERT/UPDATE/DELETE/ALL), action (PERMISSIVE/RESTRICTIVE), roles (array of role names).
- Include "definition" (USING clause expression without the USING keyword) for SELECT, UPDATE, DELETE policies.
- Include "check" (WITH CHECK clause expression without the WITH CHECK keywords) for INSERT, UPDATE policies.
- Avoid duplicating existing policies and reference the public schema and typical Supabase best practices when deciding the coverage.
- Prefer PERMISSIVE policies unless a RESTRICTIVE policy is explicitly required
`,
tools,
output: Output.object({
schema: z.object({
policies: z.array(policySchema),
}),
}),
})
// Add table and schema to each policy from the request
const policies = (output?.policies ?? []).map((policy) => ({
...policy,
table: tableName,
schema,
}))
return res.json(policies)
} finally {
toolsAbortController.abort()
}
} catch (error) {
if (error instanceof Error) {
console.error(`AI policy generation failed: ${error.message}`)
return res.status(500).json({
error: 'Failed to generate policy. Please try again.',
})
}
return res.status(500).json({
error: 'An unknown error occurred.',
})
}
}
const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
apiWrapper(req, res, handler, { withAuth: true })
export default wrapper