The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(logs): brand Observability/EdgeFunctions SQL with SafeLogSqlFragment (#8) (#46466)
Charis9bdb757b6a8e
diff --git a/apps/studio/components/interfaces/Observability/usePostgrestOverviewMetrics.ts b/apps/studio/components/interfaces/Observability/usePostgrestOverviewMetrics.tsindex 13f0e43c01d..99bbffca30b 100644--- a/apps/studio/components/interfaces/Observability/usePostgrestOverviewMetrics.ts+++ b/apps/studio/components/interfaces/Observability/usePostgrestOverviewMetrics.ts@@ -1,7 +1,8 @@import { useQuery } from '@tanstack/react-query'import type { LogsBarChartDatum } from '../ProjectHome/ProjectUsage.metrics'-import { get } from '@/data/fetchers'+import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'+import { safeSql, type SafeLogSqlFragment } from '@/data/logs/safe-analytics-sql'type PostgrestMetricsVariables = {projectRef: string@@ -10,26 +11,26 @@ type PostgrestMetricsVariables = {interval: '1hr' | '1day' | '7day'}-const getIntervalTrunc = (interval: '1hr' | '1day' | '7day') => {+function getIntervalTrunc(interval: '1hr' | '1day' | '7day'): SafeLogSqlFragment {switch (interval) {case '1hr':- return 'minute' // 1-minute buckets for 1 hour+ return safeSql`minute` // 1-minute buckets for 1 hourcase '1day':- return 'hour' // 1-hour buckets for 1 day+ return safeSql`hour` // 1-hour buckets for 1 daycase '7day':- return 'day' // 1-day buckets for 7 days+ return safeSql`day` // 1-day buckets for 7 daysdefault:- return 'hour'+ return safeSql`hour`}}-const POSTGREST_METRICS_SQL = (interval: '1hr' | '1day' | '7day') => {- const truncInterval = getIntervalTrunc(interval)+const POSTGREST_METRICS_SQL = (interval: '1hr' | '1day' | '7day'): SafeLogSqlFragment => {+ const trunc = getIntervalTrunc(interval)- return `+ return safeSql`-- postgrest-overview-metricsselect- cast(timestamp_trunc(t.timestamp, ${truncInterval}) as datetime) as timestamp,+ cast(timestamp_trunc(t.timestamp, ${trunc}) as datetime) as timestamp,countif(response.status_code < 300) as ok_count,countif(response.status_code >= 300 and response.status_code < 400) as warning_count,countif(response.status_code >= 400) as error_count@@ -59,21 +60,17 @@ async function fetchPostgrestMetrics() {const sql = POSTGREST_METRICS_SQL(interval)- const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {- params: {- path: { ref: projectRef },- query: {- sql,- iso_timestamp_start: startDate,- iso_timestamp_end: endDate,- },- },+ const data = await executeAnalyticsSql({+ projectRef,+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',+ sql,+ iso_timestamp_start: startDate,+ iso_timestamp_end: endDate,+ method: 'get',signal,})- if (error || data?.error) {- throw error || data?.error- }+ if (data?.error) throw data.errorreturn (data?.result || []) as MetricsRow[]}diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.test.ts b/apps/studio/components/interfaces/Reports/Reports.constants.test.tsindex 5ece03218c7..e9ef58cf375 100644--- a/apps/studio/components/interfaces/Reports/Reports.constants.test.ts+++ b/apps/studio/components/interfaces/Reports/Reports.constants.test.ts@@ -1,11 +1,11 @@import { describe, expect, it } from 'vitest'-import { generateRegexpWhere } from './Reports.constants'+import { generateRegexpWhereSafe } from './Reports.constants'import type { ReportFilterItem } from './Reports.types'-describe('generateRegexpWhere', () => {- it('should return empty string when no filters provided', () => {- const result = generateRegexpWhere([])+describe('generateRegexpWhereSafe', () => {+ it('should return empty fragment when no filters provided', () => {+ const result = generateRegexpWhereSafe([])expect(result).toBe('')})@@ -17,8 +17,8 @@ describe('generateRegexpWhere', () => {compare: 'is',},]- const result = generateRegexpWhere(filters, true)- expect(result).toBe("WHERE request.path = '/api/users'")+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe("WHERE `request`.`path` = '/api/users'")})it('should generate AND clause for single filter with prepend=false', () => {@@ -29,8 +29,8 @@ describe('generateRegexpWhere', () => {compare: 'is',},]- const result = generateRegexpWhere(filters, false)- expect(result).toBe("AND request.path = '/api/users'")+ const result = generateRegexpWhereSafe(filters, false)+ expect(result).toBe("AND `request`.`path` = '/api/users'")})it('should handle different comparison operators', () => {@@ -46,61 +46,76 @@ describe('generateRegexpWhere', () => {compare: 'is',},]- const result = generateRegexpWhere(filters, true)+ const result = generateRegexpWhereSafe(filters, true)expect(result).toBe(- "WHERE REGEXP_CONTAINS(request.path, '/api/*') AND response.status_code = 404"+ "WHERE REGEXP_CONTAINS(`request`.`path`, '/api/*') AND `response`.`status_code` = 404")})- it('should handle values with quotes', () => {+ it('should handle numbers', () => {const filters: ReportFilterItem[] = [{- key: 'request.path',- value: '"/api/users"',+ key: 'request.status_code',+ value: 200,compare: 'is',},]-- const result = generateRegexpWhere(filters, true)- expect(result).toBe(`WHERE request.path = "/api/users"`)+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe('WHERE `request`.`status_code` = 200')})- it('should handle values without quotes', () => {+ it('should escape single quotes in string values', () => {const filters: ReportFilterItem[] = [{key: 'request.path',- value: '/api/users',+ value: "/it's/here",compare: 'is',},]-- const result = generateRegexpWhere(filters, true)- expect(result).toBe("WHERE request.path = '/api/users'")+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe("WHERE `request`.`path` = '/it''s/here'")})- it('should handle values with quotes and lowercase', () => {+ it('should drop filters with injection-attempt keys (OR injection)', () => {const filters: ReportFilterItem[] = [{- key: 'request.path',- value: '"/Api/Users"',+ key: 'level OR id IS NOT NULL',+ value: 'info',compare: 'is',},]-- const result = generateRegexpWhere(filters, true)- expect(result).toBe(`WHERE request.path = "/api/users"`)+ // Key contains spaces — quotedIdent rejects it, predicate is dropped entirely+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe('')})- it('should handle numbers', () => {+ it('should drop filters with injection-attempt keys (semicolon injection)', () => {const filters: ReportFilterItem[] = [{- key: 'request.status_code',- value: 200,+ key: 'request.method); DROP TABLE edge_logs; --',+ value: 'GET',compare: 'is',},]+ // Key fails ident validation — predicate dropped entirely, no SQL emitted+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe('')+ })- const result = generateRegexpWhere(filters, true)- expect(result).toBe(`WHERE request.status_code = 200`)+ it('should drop invalid keys but keep valid ones', () => {+ const filters: ReportFilterItem[] = [+ {+ key: 'bad key!',+ value: 'anything',+ compare: 'is',+ },+ {+ key: 'request.method',+ value: 'GET',+ compare: 'is',+ },+ ]+ const result = generateRegexpWhereSafe(filters, true)+ expect(result).toBe("WHERE `request`.`method` = 'get'")})})diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.tsindex 11b0dd34cbf..7871ef0a188 100644--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts@@ -90,58 +90,7 @@ function rewriteWhereToAnd(sql: SafeSqlFragment): SafeSqlFragment {return sql.replace(/^WHERE/, 'AND') as SafeSqlFragment}-export const generateRegexpWhere = (filters: ReportFilterItem[], prepend = true) => {- if (filters.length === 0) return ''- const conditions = filters- .map((filter) => {- const splitKey = filter.key.split('.')- const normalizedKey = [splitKey[splitKey.length - 2], splitKey[splitKey.length - 1]].join('.')- const filterKey = filter.key.includes('.') ? normalizedKey : filter.key-- const hasQuotes =- filter.value.toString().includes('"') || filter.value.toString().includes("'")-- const valueIsNumber = !isNaN(Number(filter.value))- const valueWithQuotes = !valueIsNumber && hasQuotes ? filter.value : `'${filter.value}'`- const lowercaseValue = !valueIsNumber && String(valueWithQuotes).toLowerCase()-- const finalValue = valueIsNumber ? filter.value : lowercaseValue-- // Handle different comparison operators- switch (filter.compare) {- case 'matches':- return `REGEXP_CONTAINS(${filterKey}, ${finalValue})`- case 'is':- return `${filterKey} = ${finalValue}`- case '!=':- return `${filterKey} != ${finalValue}`- case '>=':- return `${filterKey} >= ${finalValue}`- case '<=':- return `${filterKey} <= ${finalValue}`- case '>':- return `${filterKey} > ${finalValue}`- case '<':- return `${filterKey} < ${finalValue}`- default:- // Fallback to exact match for unknown operators- return `${filterKey} = ${finalValue}`- }- })- .filter(Boolean) // Remove any null/undefined conditions- .join(' AND ')-- if (conditions === '') return ''-- if (prepend) {- return 'WHERE ' + conditions- } else {- return 'AND ' + conditions- }-}--// Unlike the legacy `generateRegexpWhere`, this function requires filter values-// to be raw (unquoted) strings or numbers. `analyticsLiteral` handles all+// Filter values must be raw (unquoted) strings or numbers. `analyticsLiteral` handles all// quoting and escaping — callers must NOT pre-wrap values in single quotes.export function generateRegexpWhereSafe(filters: ReportFilterItem[],diff --git a/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.ts b/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.tsindex df24a2355a2..a1b6305bb7d 100644--- a/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.ts+++ b/apps/studio/data/edge-functions/edge-functions-last-hour-stats-query.ts@@ -2,8 +2,14 @@ import { useQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import { edgeFunctionsKeys } from './keys'-import { handleError, post } from '@/data/fetchers'-import { quoteLiteral } from '@/lib/pg-format'+import { handleError } from '@/data/fetchers'+import { executeAnalyticsSql } from '@/data/logs/execute-analytics-sql'+import {+ analyticsLiteral,+ joinSqlFragments,+ safeSql,+ type SafeLogSqlFragment,+} from '@/data/logs/safe-analytics-sql'import type { ResponseError, UseCustomQueryOptions } from '@/types'export type EdgeFunctionsLastHourStatsVariables = { projectRef?: string; functionIds?: string[] }@@ -17,13 +23,13 @@ export type EdgeFunctionLastHourStats = {export type EdgeFunctionsLastHourStatsResponse = Record<string, EdgeFunctionLastHourStats>-function getEdgeFunctionsLastHourStatsSql(functionIds: string[]) {- const functionIdFilter =+function getEdgeFunctionsLastHourStatsSql(functionIds: string[]): SafeLogSqlFragment {+ const functionIdFilter: SafeLogSqlFragment =functionIds.length > 0- ? ` and function_id in (${functionIds.map(quoteLiteral).join(', ')})\n`- : ''+ ? safeSql` and function_id in (${joinSqlFragments(functionIds.map(analyticsLiteral), ', ')})\n`+ : safeSql``- return `+ return safeSql`-- edge-functions-last-hour-statsselectfunction_id,@@ -50,23 +56,17 @@ export async function getEdgeFunctionsLastHourStats(const endDate = dayjs().toISOString()const startDate = dayjs().subtract(1, 'hour').toISOString()- const { data, error } = await post(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {- params: {- path: { ref: projectRef },- // @ts-ignore [Joshen] Just to easily identify this request in the network tools- query: { key: 'last-hour-stats' },- },- body: {- sql: getEdgeFunctionsLastHourStatsSql(functionIds),- iso_timestamp_start: startDate,- iso_timestamp_end: endDate,- },+ const data = await executeAnalyticsSql({+ projectRef,+ endpoint: '/platform/projects/{ref}/analytics/endpoints/logs.all',+ sql: getEdgeFunctionsLastHourStatsSql(functionIds),+ iso_timestamp_start: startDate,+ iso_timestamp_end: endDate,+ key: 'last-hour-stats',signal,})- if (error || data?.error) {- handleError(error ?? data?.error)- }+ if (data?.error) handleError(data.error)const result = (data?.result ?? []) as {function_id: stringdiff --git a/apps/studio/data/logs/execute-analytics-sql.ts b/apps/studio/data/logs/execute-analytics-sql.tsindex 4fcd36abb1d..696e650218c 100644--- a/apps/studio/data/logs/execute-analytics-sql.ts+++ b/apps/studio/data/logs/execute-analytics-sql.ts@@ -29,6 +29,11 @@ export interface ExecuteAnalyticsSqlVariables {iso_timestamp_end: string/** Defaults to 'post'. Use 'get' to preserve wire behavior when migrating legacy GET callers. */method?: 'get' | 'post'+ /**+ * Optional query-string key for network-tool identification.+ * Not part of the OpenAPI schema; accepted by the server and visible in DevTools.+ */+ key?: stringsignal?: AbortSignalheaders?: HeadersInit}@@ -40,6 +45,7 @@ export async function executeAnalyticsSql({iso_timestamp_start,iso_timestamp_end,method = 'post',+ key,signal,headers: headersInit,}: ExecuteAnalyticsSqlVariables) {@@ -49,7 +55,7 @@ export async function executeAnalyticsSql({const { data, error } = await get(endpoint, {params: {path: { ref: projectRef },- query: { sql, iso_timestamp_start, iso_timestamp_end },+ query: { sql, iso_timestamp_start, iso_timestamp_end, ...(key ? { key } : {}) },},signal,headers,@@ -59,7 +65,8 @@ export async function executeAnalyticsSql({}const { data, error } = await post(endpoint, {- params: { path: { ref: projectRef } },+ // @ts-ignore key is not in the OpenAPI schema; included only for network-tool identification+ params: { path: { ref: projectRef }, ...(key ? { query: { key } } : {}) },body: { sql, iso_timestamp_start, iso_timestamp_end },signal,headers,diff --git a/apps/studio/data/logs/safe-analytics-sql.ts b/apps/studio/data/logs/safe-analytics-sql.tsindex 409f03cb67c..0f5842d6959 100644--- a/apps/studio/data/logs/safe-analytics-sql.ts+++ b/apps/studio/data/logs/safe-analytics-sql.ts@@ -105,7 +105,7 @@ export function analyticsLiteral(value: string | number | boolean): SafeLogSqlFrreturn rawSql(String(value))}if (typeof value === 'boolean') {- return rawSql(value ? 'true' : 'false')+ return value ? safeSql`true` : safeSql`false`}if (typeof value !== 'string') {throw new Error('analyticsLiteral: only string, number, or boolean inputs are supported')