Skip to content

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

feat: add last used timestamp in the last 24h to legacy api keys (#35809)

Stojan Dimitrovski1862fe405bdf
diff --git a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
index 5f08ef14738..db92f12ed28 100644
--- a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
+++ b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.tsx
@@ -1,3 +1,4 @@
+import { useMemo } from 'react'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'
import { useParams } from 'common'
@@ -8,6 +9,8 @@ import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useFlag } from 'hooks/ui/useFlag'
import { AlertCircle, Loader2 } from 'lucide-react'
import { Input } from 'ui'
+import { toast } from 'sonner'
+import { useLastUsedAPIKeysLogQuery, getLastUsedAPIKeys } from './DisplayApiSettings.utils'
const DisplayApiSettings = ({
legacy,
@@ -42,6 +45,24 @@ const DisplayApiSettings = ({
// api keys should not be empty. However it can be populated with a delay on project creation
const isApiKeysEmpty = apiKeys.length === 0
+ const { isLoading: isLoadingLastUsed, logData: lastUsedLogData } = useLastUsedAPIKeysLogQuery(
+ projectRef!
+ )
+
+ const lastUsedAPIKeys = useMemo(() => {
+ if (apiKeys.length < 1 || !lastUsedLogData || lastUsedLogData.length < 1) {
+ return {}
+ }
+
+ try {
+ return getLastUsedAPIKeys(apiKeys, lastUsedLogData)
+ } catch (e: any) {
+ toast.error('Failed to identify when the anon and service_role keys were last used')
+ console.error(e)
+ return {}
+ }
+ }, [lastUsedLogData, apiKeys])
+
return (
<>
<Panel
@@ -143,6 +164,15 @@ const DisplayApiSettings = ({
(legacy ? 'Prefer using Secret API keys instead.' : '')
}
/>
+
+ <div
+ className="pt-2 text-foreground-lighter w-full text-sm data-[invisible=true]:invisible"
+ data-invisible={isLoadingLastUsed}
+ >
+ {lastUsedAPIKeys[x.api_key]
+ ? `Last request was ${lastUsedAPIKeys[x.api_key]} ago.`
+ : 'No requests in the past 24 hours.'}
+ </div>
</Panel.Content>
))
)}
diff --git a/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts
new file mode 100644
index 00000000000..2efcfa58841
--- /dev/null
+++ b/apps/studio/components/ui/ProjectSettings/DisplayApiSettings.utils.ts
@@ -0,0 +1,55 @@
+import dayjs from 'dayjs'
+import duration from 'dayjs/plugin/duration'
+import relativeTime from 'dayjs/plugin/relativeTime'
+
+import useLogsQuery from 'hooks/analytics/useLogsQuery'
+
+dayjs.extend(duration)
+dayjs.extend(relativeTime)
+
+export function useLastUsedAPIKeysLogQuery(projectRef: string, now: Date = new Date()) {
+ return useLogsQuery(projectRef, {
+ iso_timestamp_start: new Date(now.getTime() - 24 * 60 * 60 * 1000).toISOString(),
+ iso_timestamp_end: now.toISOString(),
+ sql: "-- last-used-anon--service_role-api-keys\nSELECT unix_millis(max(timestamp)) as timestamp, payload.role, payload.signature_prefix FROM edge_logs cross join unnest(metadata) as m cross join unnest(m.request) as request cross join unnest(request.sb) as sb cross join unnest(sb.jwt) as jwt cross join unnest(jwt.apikey) as apikey cross join unnest(apikey.payload) as payload WHERE apikey.invalid is null and payload.issuer = 'supabase' and payload.algorithm = 'HS256' and payload.role in ('anon', 'service_role') GROUP BY payload.role, payload.signature_prefix",
+ })
+}
+
+export function getLastUsedAPIKeys(
+ apiKeys: {
+ tags: string
+ api_key: string
+ }[],
+ logData:
+ | {
+ timestamp: number
+ role?: 'anon' | 'service_role' | string
+ signature_prefix?: string
+ }[]
+ | null
+) {
+ if (apiKeys.length < 1 || !logData || logData.length < 1) {
+ return {}
+ }
+
+ const now = dayjs()
+
+ return apiKeys.reduce(
+ (a, i) => {
+ const entry = logData?.find(
+ ({ role, signature_prefix }) =>
+ role &&
+ signature_prefix &&
+ i.tags.indexOf(role) >= 0 &&
+ i.api_key.split('.')[2]?.startsWith(signature_prefix)
+ )?.timestamp
+
+ if (entry) {
+ a[i.api_key] = dayjs.duration(now.diff(dayjs(entry))).humanize(false)
+ }
+
+ return a
+ },
+ {} as { [apikey: string]: string }
+ )
+}