From efbbd1c9a9dd97cd5995ae2618da83dc69c827ad Mon Sep 17 00:00:00 2001 From: Pablo Abella Date: Wed, 4 Nov 2026 09:57:16 +0100 Subject: [PATCH 1/3] Scope Tinybird tokens per tenant and close SSRF in AI routes - Don't sign a JWT for users without an org (empty org read every org) - In multi-tenant mode, give logged-out users no shared read token - Allowlist x-custom-tinybird-api-url to Tinybird API hosts - Never send the server token to a caller-chosen URL - Log llm_events with a new append-only TINYBIRD_EVENTS_TOKEN, not the admin token - Remove token and session logging from middleware - Add input caps and a per-IP rate limit to the AI routes Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- TEMPLATE.md | 4 ++ .../app/api/extract-cost-parameters/route.ts | 21 +++++-- .../src/app/api/generate-embedding/route.ts | 11 +++- .../ai-analytics/src/app/api/search/route.ts | 15 ++++- .../src/components/ui/onboarding-modal.tsx | 2 +- dashboard/ai-analytics/src/lib/dimensions.ts | 14 ++++- .../ai-analytics/src/lib/tinybird-wrapper.ts | 5 +- dashboard/ai-analytics/src/middleware.ts | 60 ++++++++++++++----- tinybird/datasources/llm_events.datasource | 1 + 10 files changed, 110 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 5cbf251..fbe0cf0 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,9 @@ Edit the .env file with your Tinybird API key and other configuration. NEXT_PUBLIC_TINYBIRD_API_URL=http://localhost:7181 # read_pipes token NEXT_PUBLIC_TINYBIRD_API_KEY= +# optional: llm_events_append token (append-only on llm_events) to log the app's own AI calls. +# If unset, those calls are not logged. Never use the admin token here. +TINYBIRD_EVENTS_TOKEN= ``` Start the Next.js application: @@ -136,7 +139,7 @@ NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/ NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/ ``` -The [middleware](https://github.com/tinybirdco/ai-analytics-template/blob/main/dashboard/ai-analytics/src/middleware.ts) will get the `org:name` permission from the Clerk user and use it to create a Tinybird JWT token with the `organization` dimension fixed to that value. Read more about Tinybird JWT tokens [here](https://www.tinybird.co/docs/forward/get-started/authentication#json-web-tokens-jwts). +The [middleware](https://github.com/tinybirdco/ai-analytics-template/blob/main/dashboard/ai-analytics/src/middleware.ts) will get the `org:name` permission from the Clerk user and use it to create a Tinybird JWT token with the `organization` dimension fixed to that value. When `TINYBIRD_JWT_SECRET` is set, logged-out users and users without an organization get no Tinybird token and see an empty dashboard until they sign in with an organization. Read more about Tinybird JWT tokens [here](https://www.tinybird.co/docs/forward/get-started/authentication#json-web-tokens-jwts). ## Mock Data diff --git a/TEMPLATE.md b/TEMPLATE.md index 0d7e1ab..873cdff 100644 --- a/TEMPLATE.md +++ b/TEMPLATE.md @@ -44,6 +44,10 @@ tb --cloud token copy read_pipes && TINYBIRD_TOKEN=$(pbpaste) open https://llm-tracker.tinybird.live\?token\=$TINYBIRD_TOKEN ``` +## Log the app's own AI calls + +The dashboard's AI features log their LLM calls to `llm_events` when `TINYBIRD_EVENTS_TOKEN` is set. Use the `llm_events_append` token (append-only on `llm_events`), never the admin token. If it's unset, those calls aren't logged. + ## Local development, multi-tenancy, customization and more See [README.md](https://github.com/tinybirdco/llm-performance-tracker?tab=readme-ov-file#build-and-deploy-your-own-llm-tracker) diff --git a/dashboard/ai-analytics/src/app/api/extract-cost-parameters/route.ts b/dashboard/ai-analytics/src/app/api/extract-cost-parameters/route.ts index 4e832fa..7da23e9 100644 --- a/dashboard/ai-analytics/src/app/api/extract-cost-parameters/route.ts +++ b/dashboard/ai-analytics/src/app/api/extract-cost-parameters/route.ts @@ -3,20 +3,30 @@ import { createOpenAI } from '@ai-sdk/openai'; import { generateObject } from 'ai'; import { z } from 'zod'; import { NextResponse } from 'next/server'; -import { fetchAvailableDimensions } from '@/lib/dimensions'; +import { fetchAvailableDimensions, isAllowedTinybirdApiUrl } from '@/lib/dimensions'; import { extractDatesFromQuery } from '@/lib/dateUtils'; import { generateRandomChatId, hashApiKeyUser, wrapModelWithTinybird } from '@/lib/tinybird-wrapper'; +const MAX_QUERY_LENGTH = 1000; + // Update the POST function to properly map meta with data export async function POST(req: Request) { try { const { query, apiKey } = await req.json(); const token = req.headers.get('x-custom-tinybird-token'); const apiUrl = req.headers.get('x-custom-tinybird-api-url'); - + + if (apiUrl && !isAllowedTinybirdApiUrl(apiUrl)) { + return NextResponse.json({ error: 'Invalid Tinybird API URL' }, { status: 400 }); + } + if (!query) { return NextResponse.json({ error: 'Query is required' }, { status: 400 }); } + + if (typeof query !== 'string' || query.length > MAX_QUERY_LENGTH) { + return NextResponse.json({ error: `Query must be a string of at most ${MAX_QUERY_LENGTH} characters` }, { status: 400 }); + } if (!apiKey) { return NextResponse.json({ error: 'OpenAI API key is required' }, { status: 400 }); @@ -87,7 +97,7 @@ export async function POST(req: Request) { const wrappedOpenAI = wrapModelWithTinybird( openai('gpt-3.5-turbo'), process.env.NEXT_PUBLIC_TINYBIRD_API_URL!, - process.env.TINYBIRD_JWT_SECRET!, + process.env.TINYBIRD_EVENTS_TOKEN, { event: 'ai_cost_calculator', environment: process.env.NODE_ENV, @@ -145,8 +155,9 @@ export async function POST(req: Request) { // Fetch the llm_usage pipe definition const fetchPipeDefinition = async (token: string | null, apiUrl: string | null) => { - const TINYBIRD_API_URL = apiUrl || 'http://localhost:7181'; - const TINYBIRD_API_KEY = token || process.env.NEXT_PUBLIC_TINYBIRD_API_KEY; + // The server token only goes to the server URL. A caller-supplied URL needs the caller's own token. + const TINYBIRD_API_URL = apiUrl || process.env.NEXT_PUBLIC_TINYBIRD_API_URL || 'http://localhost:7181'; + const TINYBIRD_API_KEY = apiUrl ? token : (token || process.env.NEXT_PUBLIC_TINYBIRD_API_KEY); if (!TINYBIRD_API_KEY) { console.error('No Tinybird API key available'); diff --git a/dashboard/ai-analytics/src/app/api/generate-embedding/route.ts b/dashboard/ai-analytics/src/app/api/generate-embedding/route.ts index c531872..0888f52 100644 --- a/dashboard/ai-analytics/src/app/api/generate-embedding/route.ts +++ b/dashboard/ai-analytics/src/app/api/generate-embedding/route.ts @@ -6,6 +6,8 @@ import type { FeatureExtractionPipeline } from '@xenova/transformers/types/pipel // Cache the model to avoid reloading it for every request let embeddingPipeline: FeatureExtractionPipeline | null = null; +const MAX_TEXT_LENGTH = 1000; + async function getEmbeddingModel() { if (!embeddingPipeline) { embeddingPipeline = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') as FeatureExtractionPipeline; @@ -23,7 +25,14 @@ export async function POST(req: Request) { { status: 400 } ); } - + + if (text.length > MAX_TEXT_LENGTH) { + return NextResponse.json( + { error: `Invalid input: text must be at most ${MAX_TEXT_LENGTH} characters` }, + { status: 400 } + ); + } + // Get the model const model = await getEmbeddingModel(); diff --git a/dashboard/ai-analytics/src/app/api/search/route.ts b/dashboard/ai-analytics/src/app/api/search/route.ts index e1e6d83..455132f 100644 --- a/dashboard/ai-analytics/src/app/api/search/route.ts +++ b/dashboard/ai-analytics/src/app/api/search/route.ts @@ -2,14 +2,23 @@ import { createOpenAI } from '@ai-sdk/openai'; import { generateObject } from 'ai'; import { z } from 'zod'; import { generateRandomChatId, hashApiKeyUser, wrapModelWithTinybird } from '@/lib/tinybird-wrapper'; -import { fetchAvailableDimensions } from '@/lib/dimensions'; +import { fetchAvailableDimensions, isAllowedTinybirdApiUrl } from '@/lib/dimensions'; +const MAX_PROMPT_LENGTH = 1000; export async function POST(req: Request) { const { prompt, apiKey } = await req.json(); const token = req.headers.get('x-custom-tinybird-token'); const apiUrl = req.headers.get('x-custom-tinybird-api-url'); - + + if (apiUrl && !isAllowedTinybirdApiUrl(apiUrl)) { + return Response.json({ error: 'Invalid Tinybird API URL' }, { status: 400 }); + } + + if (typeof prompt !== 'string' || prompt.length > MAX_PROMPT_LENGTH) { + return Response.json({ error: `Prompt must be a string of at most ${MAX_PROMPT_LENGTH} characters` }, { status: 400 }); + } + if (!apiKey) { return Response.json({ error: 'OpenAI API key is required' }, { status: 400 }); } @@ -39,7 +48,7 @@ export async function POST(req: Request) { const wrappedOpenAI = wrapModelWithTinybird( openai('gpt-3.5-turbo'), process.env.NEXT_PUBLIC_TINYBIRD_API_URL!, - process.env.TINYBIRD_JWT_SECRET!, + process.env.TINYBIRD_EVENTS_TOKEN, { event: 'search_filter', environment: process.env.NODE_ENV, diff --git a/dashboard/ai-analytics/src/components/ui/onboarding-modal.tsx b/dashboard/ai-analytics/src/components/ui/onboarding-modal.tsx index 08e6e6c..9df4208 100644 --- a/dashboard/ai-analytics/src/components/ui/onboarding-modal.tsx +++ b/dashboard/ai-analytics/src/components/ui/onboarding-modal.tsx @@ -103,7 +103,7 @@ response = await acompletion( snippet: `const wrappedOpenAI = wrapModelWithTinybird( openai('gpt-3.5-turbo'), process.env.NEXT_PUBLIC_TINYBIRD_API_URL!, - process.env.TINYBIRD_JWT_SECRET!, + process.env.TINYBIRD_EVENTS_TOKEN, { event: 'search_filter', environment: process.env.NODE_ENV, diff --git a/dashboard/ai-analytics/src/lib/dimensions.ts b/dashboard/ai-analytics/src/lib/dimensions.ts index f73400e..3ce2164 100644 --- a/dashboard/ai-analytics/src/lib/dimensions.ts +++ b/dashboard/ai-analytics/src/lib/dimensions.ts @@ -1,9 +1,21 @@ +// Only Tinybird API hosts (plus localhost outside production) to avoid SSRF via caller-supplied URLs +export const isAllowedTinybirdApiUrl = (apiUrl: string | null) => { + if (!apiUrl) return false; + if (/^https:\/\/api\.([a-z0-9-]+\.)*tinybird\.co\/?$/.test(apiUrl)) return true; + return process.env.NODE_ENV !== 'production' && /^http:\/\/localhost(:\d+)?\/?$/.test(apiUrl); +}; + export const fetchAvailableDimensions = async (token: string | null, apiUrl: string | null) => { if (!token) { console.error('No Tinybird token available'); return null; } - + + if (!isAllowedTinybirdApiUrl(apiUrl)) { + console.error('Invalid Tinybird API URL'); + return null; + } + try { const url = `${apiUrl}/v0/pipes/llm_dimensions.json`; const response = await fetch(url, { diff --git a/dashboard/ai-analytics/src/lib/tinybird-wrapper.ts b/dashboard/ai-analytics/src/lib/tinybird-wrapper.ts index 955d268..3bb3d1a 100644 --- a/dashboard/ai-analytics/src/lib/tinybird-wrapper.ts +++ b/dashboard/ai-analytics/src/lib/tinybird-wrapper.ts @@ -13,9 +13,12 @@ type TinybirdConfig = { export function wrapModelWithTinybird( model: LanguageModelV1, tinybirdApiUrl: string, - tinybirdToken: string, + tinybirdToken: string | undefined, config: TinybirdConfig = {} ) { + // No append token configured: skip logging instead of falling back to another token + if (!tinybirdToken) return model; + const originalDoGenerate = model.doGenerate; const originalDoStream = model.doStream; diff --git a/dashboard/ai-analytics/src/middleware.ts b/dashboard/ai-analytics/src/middleware.ts index 620d63d..3017457 100644 --- a/dashboard/ai-analytics/src/middleware.ts +++ b/dashboard/ai-analytics/src/middleware.ts @@ -3,14 +3,45 @@ import { NextResponse } from "next/server" import * as jose from 'jose' import { getApiUrlFromHost, extractHostFromToken } from './lib/tinybird-utils' -console.log('MIDDLEWARE FILE LOADED!!!') +// Multi-tenant mode: users only get data through a per-org JWT, never the shared read token +const isMultiTenant = !!process.env.TINYBIRD_JWT_SECRET + +// Basic per-IP rate limit for the AI routes. In-memory, so it only applies per server +// instance (per isolate on Edge). Use a shared store if you need a global limit. +const RATE_LIMITED_ROUTES = ['/api/search', '/api/extract-cost-parameters', '/api/generate-embedding'] +const RATE_LIMIT_PER_MINUTE = 30 +const rateLimitHits = new Map() + +function isRateLimited(ip: string) { + const now = Date.now() + const entry = rateLimitHits.get(ip) + if (!entry || now > entry.reset) { + if (rateLimitHits.size > 10000) rateLimitHits.clear() + rateLimitHits.set(ip, { count: 1, reset: now + 60_000 }) + return false + } + entry.count++ + return entry.count > RATE_LIMIT_PER_MINUTE +} + +function responseWithoutJwt() { + const response = NextResponse.next() + if (!isMultiTenant) { + response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '') + } + return response +} export default clerkMiddleware(async (auth, request) => { - debugger; - console.log('🔥🔥🔥 MIDDLEWARE EXECUTING 🔥🔥🔥') + if (RATE_LIMITED_ROUTES.includes(request.nextUrl.pathname)) { + const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown' + if (isRateLimited(ip)) { + return NextResponse.json({ error: 'Too many requests' }, { status: 429 }) + } + } + const authentication = await auth() - const { userId, sessionId, sessionClaims, orgId, orgRole, orgPermissions } = authentication - console.log('Auth details:', { userId, sessionId, sessionClaims, orgId, orgRole, orgPermissions }) + const { userId, sessionId, orgPermissions } = authentication // Get the token from the URL if present const url = new URL(request.url); @@ -32,18 +63,21 @@ export default clerkMiddleware(async (auth, request) => { return response; } - // If user is not authenticated, continue without modification + // If user is not authenticated, continue without a JWT if (!userId || !sessionId) { console.log('No user or session found') - - const response = NextResponse.next() - response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '') - return response + return responseWithoutJwt() } try { const orgName = orgPermissions?.[0]?.split(':').pop() || '' + // An empty organization makes the pipes skip the filter and return every org, + // so users without an org are treated like logged-out visitors + if (!orgName) { + return responseWithoutJwt() + } + // Create Tinybird JWT const secret = new TextEncoder().encode(process.env.TINYBIRD_JWT_SECRET) const token = await new jose.SignJWT({ @@ -79,8 +113,6 @@ export default clerkMiddleware(async (auth, request) => { }) .setProtectedHeader({ alg: 'HS256' }) .sign(secret) - debugger; - console.log('Generated token:', token) // Clone the response and add token const response = NextResponse.next() @@ -89,9 +121,7 @@ export default clerkMiddleware(async (auth, request) => { return response } catch (error) { console.error('Middleware error:', error) - const response = NextResponse.next() - response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '') - return response + return responseWithoutJwt() } }) diff --git a/tinybird/datasources/llm_events.datasource b/tinybird/datasources/llm_events.datasource index 911a098..e3176fa 100644 --- a/tinybird/datasources/llm_events.datasource +++ b/tinybird/datasources/llm_events.datasource @@ -1,3 +1,4 @@ +TOKEN "llm_events_append" APPEND DESCRIPTION > Store LLM events with usage metrics, costs, and metadata From ce03c75f725620c04dfa14d4f9e0b480720bb3ae Mon Sep 17 00:00:00 2001 From: Pablo Abella Date: Wed, 4 Nov 2026 09:58:31 +0100 Subject: [PATCH 2/3] Skip JWT signing in single-tenant mode Co-Authored-By: Claude Opus 5.5 --- dashboard/ai-analytics/src/middleware.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dashboard/ai-analytics/src/middleware.ts b/dashboard/ai-analytics/src/middleware.ts index 3017457..997436b 100644 --- a/dashboard/ai-analytics/src/middleware.ts +++ b/dashboard/ai-analytics/src/middleware.ts @@ -69,6 +69,11 @@ export default clerkMiddleware(async (auth, request) => { return responseWithoutJwt() } + // Single-tenant mode has no secret to sign a JWT with: everyone uses the read token + if (!isMultiTenant) { + return responseWithoutJwt() + } + try { const orgName = orgPermissions?.[0]?.split(':').pop() || '' From 9861415a553236b409c9fc5cc89ed9a93e1719c8 Mon Sep 17 00:00:00 2001 From: Pablo Abella Date: Wed, 4 Nov 2026 10:37:41 +0100 Subject: [PATCH 3/3] Remove leftover FORWARD_QUERY from llm_events Tinybird flags it as no longer needed: the current schema is compatible with the live one. Co-Authored-By: Claude Opus 5.5 --- tinybird/datasources/llm_events.datasource | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/tinybird/datasources/llm_events.datasource b/tinybird/datasources/llm_events.datasource index e3176fa..d6e50d5 100644 --- a/tinybird/datasources/llm_events.datasource +++ b/tinybird/datasources/llm_events.datasource @@ -44,7 +44,4 @@ SCHEMA > ENGINE "MergeTree" ENGINE_PARTITION_KEY "toYYYYMM(timestamp)" ENGINE_SORTING_KEY "timestamp, organization, project, environment, user, chat_id" -ENGINE_PRIMARY_KEY "timestamp, organization, project" - -FORWARD_QUERY > - SELECT timestamp, organization, project, environment, user, chat_id, message_id, model, prompt_tokens, completion_tokens, total_tokens, response_time, duration, cost, exception, traceback, response_status, messages, response_choices, proxy_metadata, provider, llm_api_duration_ms, end_time, id, CAST(stream, 'Bool') AS stream, call_type, api_key, log_event_type, CAST(cache_hit, 'Bool') AS cache_hit, response, response_id, response_object, defaultValueOfTypeName('Array(Float32)') AS embedding \ No newline at end of file +ENGINE_PRIMARY_KEY "timestamp, organization, project" \ No newline at end of file