policy.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import { generateText, Output, stepCountIs } from 'ai'
  2. import { IS_PLATFORM } from 'common'
  3. import { source } from 'common-tags'
  4. import { NextApiRequest, NextApiResponse } from 'next'
  5. import { z } from 'zod'
  6. import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
  7. import { getOrgAIDetails } from '@/lib/ai/ai-details'
  8. import { getModel } from '@/lib/ai/model'
  9. import { DEFAULT_COMPLETION_MODEL } from '@/lib/ai/model.utils'
  10. import { RLS_PROMPT } from '@/lib/ai/prompts'
  11. import { getTools } from '@/lib/ai/tools'
  12. import apiWrapper from '@/lib/api/apiWrapper'
  13. const policySchema = z.object({
  14. sql: z.string().describe('The generated Postgres CREATE POLICY statement.'),
  15. name: z.string().describe('The name of the policy.'),
  16. command: z
  17. .enum(['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALL'])
  18. .describe('The SQL command this policy applies to.'),
  19. definition: z
  20. .string()
  21. .optional()
  22. .describe('The USING clause expression (for SELECT, UPDATE, DELETE).'),
  23. check: z.string().optional().describe('The WITH CHECK clause expression (for INSERT, UPDATE).'),
  24. action: z
  25. .enum(['PERMISSIVE', 'RESTRICTIVE'])
  26. .default('PERMISSIVE')
  27. .describe('Whether the policy is PERMISSIVE or RESTRICTIVE.'),
  28. roles: z.array(z.string()).default(['public']).describe('The roles this policy applies to.'),
  29. })
  30. const requestBodySchema = z.object({
  31. tableName: z.string().min(1),
  32. schema: z.string().default('public'),
  33. columns: z.array(z.string()).optional(),
  34. projectRef: z.string().min(1),
  35. connectionString: z.string().min(1),
  36. orgSlug: z.string().optional(),
  37. message: z.string().optional(),
  38. })
  39. async function handler(req: NextApiRequest, res: NextApiResponse) {
  40. const { method } = req
  41. switch (method) {
  42. case 'POST':
  43. return handlePost(req, res)
  44. default:
  45. res.setHeader('Allow', ['POST'])
  46. res.status(405).json({ data: null, error: { message: `Method ${method} Not Allowed` } })
  47. }
  48. }
  49. export async function handlePost(req: NextApiRequest, res: NextApiResponse) {
  50. const authorization = req.headers.authorization
  51. const accessToken = authorization?.replace('Bearer ', '')
  52. if (IS_PLATFORM && !accessToken) {
  53. return res.status(401).json({ error: 'Authorization token is required' })
  54. }
  55. const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
  56. const { data, error: parseError } = requestBodySchema.safeParse(body)
  57. if (parseError) {
  58. return res.status(400).json({ error: 'Invalid request body', issues: parseError.issues })
  59. }
  60. const { tableName, schema, columns = [], projectRef, connectionString, orgSlug, message } = data
  61. let aiOptInLevel: AiOptInLevel = 'disabled'
  62. if (!IS_PLATFORM) {
  63. aiOptInLevel = 'schema'
  64. }
  65. if (IS_PLATFORM && orgSlug && authorization) {
  66. try {
  67. const { aiOptInLevel: orgAIOptInLevel } = await getOrgAIDetails({
  68. orgSlug,
  69. authorization,
  70. })
  71. aiOptInLevel = orgAIOptInLevel
  72. } catch (error) {
  73. return res.status(400).json({
  74. error: 'There was an error fetching your organization details',
  75. })
  76. }
  77. }
  78. try {
  79. const { modelParams, error: modelError } = await getModel({
  80. provider: 'openai',
  81. modelEntry: DEFAULT_COMPLETION_MODEL,
  82. })
  83. if (modelError) {
  84. return res.status(500).json({ error: modelError.message })
  85. }
  86. const tools = await getTools({
  87. projectRef,
  88. connectionString,
  89. authorization,
  90. aiOptInLevel,
  91. accessToken,
  92. })
  93. const { experimental_output } = await generateText({
  94. ...modelParams,
  95. stopWhen: stepCountIs(5),
  96. prompt: source`
  97. You are a Postgres RLS (Row Level Security) expert.
  98. Determine the most appropriate policies for the "${schema}"."${tableName}" table within a Briven project.
  99. ${columns.length > 0 ? `Table columns: ${columns.join(', ')}` : 'No column metadata provided.'}
  100. ${message ? `User request: ${message}` : ''}
  101. RLS Guide: ${RLS_PROMPT}
  102. Requirements:
  103. - 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.
  104. - Ensure policies strictly adhere to the existing schema
  105. - Return a curated list of recommended CREATE POLICY statements as JSON.
  106. - Each policy must include: name, sql, command (SELECT/INSERT/UPDATE/DELETE/ALL), action (PERMISSIVE/RESTRICTIVE), roles (array of role names).
  107. - Include "definition" (USING clause expression without the USING keyword) for SELECT, UPDATE, DELETE policies.
  108. - Include "check" (WITH CHECK clause expression without the WITH CHECK keywords) for INSERT, UPDATE policies.
  109. - Avoid duplicating existing policies and reference the public schema and typical Briven best practices when deciding the coverage.
  110. - Prefer PERMISSIVE policies unless a RESTRICTIVE policy is explicitly required
  111. `,
  112. tools,
  113. experimental_output: Output.object({
  114. schema: z.object({
  115. policies: z.array(policySchema),
  116. }),
  117. }),
  118. })
  119. // Add table and schema to each policy from the request
  120. const policies = (experimental_output?.policies ?? []).map((policy) => ({
  121. ...policy,
  122. table: tableName,
  123. schema,
  124. }))
  125. return res.json(policies)
  126. } catch (error) {
  127. if (error instanceof Error) {
  128. console.error(`AI policy generation failed: ${error.message}`)
  129. return res.status(500).json({
  130. error: 'Failed to generate policy. Please try again.',
  131. })
  132. }
  133. return res.status(500).json({
  134. error: 'An unknown error occurred.',
  135. })
  136. }
  137. }
  138. const wrapper = (req: NextApiRequest, res: NextApiResponse) =>
  139. apiWrapper(req, res, handler, { withAuth: true })
  140. export default wrapper