From 36eb62bd8972ac66c3f4b9f70c95c8afe15a1ce5 Mon Sep 17 00:00:00 2001 From: Rafa Moreno Date: Tue, 3 Nov 2026 13:30:29 +0100 Subject: [PATCH 1/2] Remove dashboard password sessions and server-token fallback --- .github/workflows/ci-workflow.yml | 15 ++ README.md | 3 + dashboard/README.md | 17 +- dashboard/app/api/auth/login/route.ts | 43 ---- dashboard/app/api/auth/logout/route.ts | 11 - dashboard/app/api/auth/route.ts | 59 ----- dashboard/app/api/config/route.ts | 61 ++--- dashboard/app/api/endpoints/[name]/route.ts | 33 +-- dashboard/app/api/sql/route.ts | 25 +- dashboard/components/AuthDialog.tsx | 248 ++++++-------------- dashboard/lib/hooks/use-login.ts | 60 +---- dashboard/lib/server.ts | 54 +---- dashboard/middleware.ts | 62 ----- dashboard/tests/credentials.cjs | 44 ++++ dashboard/tests/token-auth.mjs | 84 +++++++ 15 files changed, 275 insertions(+), 544 deletions(-) delete mode 100644 dashboard/app/api/auth/login/route.ts delete mode 100644 dashboard/app/api/auth/logout/route.ts delete mode 100644 dashboard/app/api/auth/route.ts delete mode 100644 dashboard/middleware.ts create mode 100644 dashboard/tests/credentials.cjs create mode 100644 dashboard/tests/token-auth.mjs diff --git a/.github/workflows/ci-workflow.yml b/.github/workflows/ci-workflow.yml index 7956f7d..0b6b645 100644 --- a/.github/workflows/ci-workflow.yml +++ b/.github/workflows/ci-workflow.yml @@ -25,6 +25,21 @@ jobs: run: pnpm run build env: CI: true + - name: Test dashboard credential isolation + env: + TINYBIRD_TOKEN: server-token-must-never-leave + TINYBIRD_HOST: http://127.0.0.1:1 + DISABLE_AUTH: 'true' + run: | + node dashboard/tests/credentials.cjs + pnpm --filter @tinybirdco/analytics-dashboard exec next start -p 3097 & + server_pid=$! + trap 'kill "$server_pid"' EXIT + for attempt in $(seq 1 30); do + if curl --silent --fail http://localhost:3097/ > /dev/null; then break; fi + sleep 1 + done + node dashboard/tests/token-auth.mjs middleware: runs-on: ubuntu-latest diff --git a/README.md b/README.md index e2329c2..ee54c0f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ # Web Analytics template for Tinybird +> **Security update (2026-11-03):** Earlier dashboard versions allowed a request-controlled host to receive the deployment's Tinybird token. Upgrade and redeploy the dashboard, remove its `TINYBIRD_TOKEN` deployment variable, and revoke/rotate any token configured in an exposed deployment. Password/session authentication is removed; dashboard access now requires a caller-supplied Tinybird token and host. Updating the code does not revoke previously leaked credentials. + + Build your own web analytics platform using [Tinybird](https://www.tinybird.co/)'s Events API and Endpoints. Built with privacy and speed as top priorities, this template lets you get real-time metrics in a pre-built dashboard in just a few minutes without any knowledge about Tinybird. After you've finished the basic setup, expand your analytics with custom events tailored to your specific use cases (eCommerce, marketing, etc.), keeping the same real-time performance. diff --git a/dashboard/README.md b/dashboard/README.md index 2326df1..130067b 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -41,34 +41,23 @@ You will find the app running at http://localhost:3000 Copy the .env.example file and rename it to .env. ```bash -# Tinybird Configuration (server-only, required) -TINYBIRD_TOKEN=your-tinybird-token -TINYBIRD_HOST=https://api.tinybird.co - # Dashboard URL (public) NEXT_PUBLIC_TINYBIRD_DASHBOARD_URL=http://localhost:3000 # Tracker token for analytics (public, optional) NEXT_PUBLIC_TINYBIRD_TRACKER_TOKEN= -# Dashboard Basic Auth (server-only, defaults to admin/admin if not set) -# DASHBOARD_USERNAME=admin -# DASHBOARD_PASSWORD=changeme - -# Optional: Set to "true" to disable auth during development -DISABLE_AUTH=false - # Optional: AI Chat NEXT_PUBLIC_ASK_TINYBIRD_ENDPOINT="https://ask-tb.tinybird.live/api/chat" ``` -To develop locally, start [Tinybird Local](https://www.tinybird.co/docs/cli/local-container) and use `http://localhost:7181` as TINYBIRD_HOST. +To develop locally, start [Tinybird Local](https://www.tinybird.co/docs/cli/local-container) and use `http://localhost:7181` as the host in the token access form. ### Authentication -The dashboard includes built-in authentication. By default, credentials are `admin/admin`. You can customize this by setting `DASHBOARD_USERNAME` and `DASHBOARD_PASSWORD` environment variables. +The dashboard supports Tinybird token access only. Use the token form or open a dashboard link with `token` and `host` parameters. API requests must provide both `X-Tinybird-Token` and `X-Tinybird-Host`; Tinybird enforces the token's permissions. -For local development, you can disable authentication by setting `DISABLE_AUTH=true`. +Password login, session cookies, and `DISABLE_AUTH` have been removed. The dashboard no longer reads `TINYBIRD_TOKEN` or `TINYBIRD_HOST` from its environment. Remove these deployment variables and use caller-supplied credentials. Credentials needed by the separate Tinybird deployment tooling or ingestion middleware remain separate. ### Build for Production diff --git a/dashboard/app/api/auth/login/route.ts b/dashboard/app/api/auth/login/route.ts deleted file mode 100644 index 863c8a1..0000000 --- a/dashboard/app/api/auth/login/route.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { cookies } from 'next/headers' -import { createHash } from 'crypto' - -const SESSION_COOKIE_NAME = 'dashboard_session' -const SESSION_MAX_AGE = 60 * 60 * 24 * 7 // 7 days - -function hashCredentials(username: string, password: string): string { - return createHash('sha256').update(`${username}:${password}`).digest('hex') -} - -export async function POST(request: NextRequest) { - try { - const { username, password } = await request.json() - - // Default to admin/admin if not configured - const expectedUsername = process.env.DASHBOARD_USERNAME || 'admin' - const expectedPassword = process.env.DASHBOARD_PASSWORD || 'admin' - - if (username === expectedUsername && password === expectedPassword) { - // Create session token with credentials hash for validation - const credentialsHash = hashCredentials(username, password) - const sessionToken = Buffer.from( - JSON.stringify({ username, hash: credentialsHash, timestamp: Date.now() }) - ).toString('base64') - - const cookieStore = await cookies() - cookieStore.set(SESSION_COOKIE_NAME, sessionToken, { - httpOnly: true, - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - maxAge: SESSION_MAX_AGE, - path: '/', - }) - - return NextResponse.json({ success: true }) - } - - return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 }) - } catch { - return NextResponse.json({ error: 'Invalid request' }, { status: 400 }) - } -} diff --git a/dashboard/app/api/auth/logout/route.ts b/dashboard/app/api/auth/logout/route.ts deleted file mode 100644 index 6729662..0000000 --- a/dashboard/app/api/auth/logout/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { NextResponse } from 'next/server' -import { cookies } from 'next/headers' - -const SESSION_COOKIE_NAME = 'dashboard_session' - -export async function POST() { - const cookieStore = await cookies() - cookieStore.delete(SESSION_COOKIE_NAME) - - return NextResponse.json({ success: true }) -} diff --git a/dashboard/app/api/auth/route.ts b/dashboard/app/api/auth/route.ts deleted file mode 100644 index 0a9f739..0000000 --- a/dashboard/app/api/auth/route.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { cookies } from 'next/headers' -import { createHash } from 'crypto' - -const SESSION_COOKIE_NAME = 'dashboard_session' - -function hashCredentials(username: string, password: string): string { - return createHash('sha256').update(`${username}:${password}`).digest('hex') -} - -function validateSession(sessionToken: string): boolean { - try { - const decoded = JSON.parse(Buffer.from(sessionToken, 'base64').toString()) - const { username, hash } = decoded - - // Get current credentials - const expectedUsername = process.env.DASHBOARD_USERNAME || 'admin' - const expectedPassword = process.env.DASHBOARD_PASSWORD || 'admin' - - // Verify username matches and hash is valid - if (username !== expectedUsername) { - return false - } - - const expectedHash = hashCredentials(expectedUsername, expectedPassword) - return hash === expectedHash - } catch { - // Invalid session format (could be old format), treat as invalid - return false - } -} - -// GET - Check auth status -export async function GET(request: NextRequest) { - // If auth is disabled, always return authenticated - if (process.env.DISABLE_AUTH === 'true') { - return NextResponse.json({ authenticated: true }) - } - - // Check for token auth from headers (passed from URL params by client) - const headerToken = request.headers.get('X-Tinybird-Token') - const headerHost = request.headers.get('X-Tinybird-Host') - if (headerToken && headerHost) { - return NextResponse.json({ authenticated: true }) - } - - const cookieStore = await cookies() - const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME) - - if (!sessionCookie?.value) { - return NextResponse.json({ authenticated: false }) - } - - const isValid = validateSession(sessionCookie.value) - - return NextResponse.json({ - authenticated: isValid, - }) -} diff --git a/dashboard/app/api/config/route.ts b/dashboard/app/api/config/route.ts index 28aba45..4b32699 100644 --- a/dashboard/app/api/config/route.ts +++ b/dashboard/app/api/config/route.ts @@ -1,5 +1,8 @@ import { NextRequest, NextResponse } from 'next/server' -import { getTinybirdConfig, getWorkspace, getWorkspaceWithCredentials } from '@/lib/server' +import { + getRequestCredentials, + getWorkspaceWithCredentials, +} from '@/lib/server' interface TinybirdRegionInfo { provider: string @@ -24,7 +27,8 @@ function extractWorkspaceNameFromToken(token: string): string | null { const json = Buffer.from(base64, 'base64').toString() const data = JSON.parse(json) // Skip 'frontend_jwt' as it's just a token label, not workspace name - const name = data.workspace_name || (data.name !== 'frontend_jwt' ? data.name : null) + const name = + data.workspace_name || (data.name !== 'frontend_jwt' ? data.name : null) return name || null } catch { return null @@ -81,51 +85,38 @@ async function getRegionInfoFromHost( } export async function GET(request: NextRequest) { - // Check for token from headers first (public mode), then fall back to env vars - const headerToken = request.headers.get('X-Tinybird-Token') - const headerHost = request.headers.get('X-Tinybird-Host') + const credentials = getRequestCredentials(request) + if (!credentials) { + return NextResponse.json( + { error: 'Tinybird token and host required' }, + { status: 401 } + ) + } + const { token, host } = credentials const headerWorkspace = request.headers.get('X-Tinybird-Workspace') - const { token: envToken, host: envHost } = getTinybirdConfig() - - const token = headerToken || envToken - const host = headerHost || envHost - - const missing: string[] = [] - if (!token) missing.push('TINYBIRD_TOKEN') - if (!host) missing.push('TINYBIRD_HOST') - const configured = missing.length === 0 - - // Include workspace info if configured - const regionInfo = host ? await getRegionInfoFromHost(host) : null + const regionInfo = await getRegionInfoFromHost(host) // Use workspace name from header if provided (avoids permission issues with scoped JWT) // Otherwise fetch using credentials let workspaceName = headerWorkspace - if (!workspaceName && configured) { - const tinybirdWorkspace = headerToken && headerHost - ? await getWorkspaceWithCredentials(headerToken, headerHost) - : await getWorkspace() + if (!workspaceName) { + const tinybirdWorkspace = await getWorkspaceWithCredentials(token, host) workspaceName = tinybirdWorkspace?.name || null } // If still no workspace name and we have a token, try to decode it - if (!workspaceName && headerToken) { - workspaceName = extractWorkspaceNameFromToken(headerToken) + if (!workspaceName) { + workspaceName = extractWorkspaceNameFromToken(token) } - const workspace = - configured && host && regionInfo - ? { - name: workspaceName || 'Unknown', - provider: regionInfo.provider, - region: regionInfo.region, - } - : null - return NextResponse.json({ - configured, - missing, - workspace, + configured: true, + missing: [], + workspace: { + name: workspaceName || 'Unknown', + provider: regionInfo.provider, + region: regionInfo.region, + }, }) } diff --git a/dashboard/app/api/endpoints/[name]/route.ts b/dashboard/app/api/endpoints/[name]/route.ts index 060317b..50b1525 100644 --- a/dashboard/app/api/endpoints/[name]/route.ts +++ b/dashboard/app/api/endpoints/[name]/route.ts @@ -1,5 +1,8 @@ import { NextRequest, NextResponse } from 'next/server' -import { getServerClient, getTinybirdConfig, createClientWithCredentials } from '@/lib/server' +import { + getRequestCredentials, + createClientWithCredentials, +} from '@/lib/server' const VALID_ENDPOINTS = [ 'currentVisitors', @@ -44,32 +47,16 @@ export async function GET( ) } - // Check for token from headers first (public mode), then fall back to env vars - const headerToken = request.headers.get('X-Tinybird-Token') - const headerHost = request.headers.get('X-Tinybird-Host') - const { token: envToken, host: envHost } = getTinybirdConfig() - - const token = headerToken || envToken - const host = headerHost || envHost - - if (!token || !host) { - const missing = [] - if (!token) missing.push('TINYBIRD_TOKEN') - if (!host) missing.push('TINYBIRD_HOST') + const credentials = getRequestCredentials(request) + if (!credentials) { return NextResponse.json( - { - error: `Tinybird configuration not found. Missing: ${missing.join( - ', ' - )}`, - }, - { status: 503 } + { error: 'Tinybird token and host required' }, + { status: 401 } ) } + const { token, host } = credentials + const client = createClientWithCredentials(token, host) - // Use header credentials if provided, otherwise use server client - const client = headerToken && headerHost - ? createClientWithCredentials(headerToken, headerHost) - : getServerClient() const searchParams = request.nextUrl.searchParams const queryParams: Record = {} diff --git a/dashboard/app/api/sql/route.ts b/dashboard/app/api/sql/route.ts index a125568..dd01326 100644 --- a/dashboard/app/api/sql/route.ts +++ b/dashboard/app/api/sql/route.ts @@ -1,5 +1,5 @@ import { NextRequest, NextResponse } from 'next/server' -import { getTinybirdConfig } from '@/lib/server' +import { getRequestCredentials } from '@/lib/server' const uiToApiHost: Record = { 'https://ui.tinybird.co': 'https://api.tinybird.co', @@ -14,27 +14,14 @@ export async function POST(request: NextRequest) { return NextResponse.json({ error: 'SQL query required' }, { status: 400 }) } - // Check for token from headers first (public mode), then fall back to env vars - const headerToken = request.headers.get('X-Tinybird-Token') - const headerHost = request.headers.get('X-Tinybird-Host') - const { token: envToken, host: envHost } = getTinybirdConfig() - - const token = headerToken || envToken - const host = headerHost || envHost - - if (!token || !host) { - const missing = [] - if (!token) missing.push('TINYBIRD_TOKEN') - if (!host) missing.push('TINYBIRD_HOST') + const credentials = getRequestCredentials(request) + if (!credentials) { return NextResponse.json( - { - error: `Tinybird configuration not found. Missing: ${missing.join( - ', ' - )}`, - }, - { status: 503 } + { error: 'Tinybird token and host required' }, + { status: 401 } ) } + const { token, host } = credentials const apiUrl = uiToApiHost[host] ?? host const response = await fetch( diff --git a/dashboard/components/AuthDialog.tsx b/dashboard/components/AuthDialog.tsx index 70c97d2..93468a6 100644 --- a/dashboard/components/AuthDialog.tsx +++ b/dashboard/components/AuthDialog.tsx @@ -14,11 +14,8 @@ import { Select } from '@/components/ui/Select' import { Link } from '@/components/ui/Link' import { Text } from '@/components/ui/Text' import { Loader } from '@/components/ui/Loader' -import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/Tabs' import { SignJWT } from 'jose' -type AuthMode = 'signin' | 'token' - const regionMap: Record = { 'gcp-europe-west2': 'https://api.europe-west2.gcp.tinybird.co', eu_shared: 'https://api.tinybird.co', @@ -129,52 +126,17 @@ export async function createJwt( interface AuthDialogProps { isLoading?: boolean - defaultMode?: AuthMode } export default function AuthDialog({ isLoading: isCheckingAuth, - defaultMode = 'signin', }: AuthDialogProps) { - const [mode, setMode] = useState(defaultMode) - - // Sign in state - const [username, setUsername] = useState('') - const [password, setPassword] = useState('') - const [signInError, setSignInError] = useState('') - const [isSubmitting, setIsSubmitting] = useState(false) - // Token state const [hostUrl, setHostUrl] = useState(regionValues[0]) const [hostName, setHostName] = useState('') const [tenantId, setTenantId] = useState('') const [tokenHasHost, setTokenHasHost] = useState(true) - async function handleSignIn(e: React.FormEvent) { - e.preventDefault() - setSignInError('') - setIsSubmitting(true) - - try { - const response = await fetch('/api/auth/login', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username, password }), - }) - - if (response.ok) { - window.location.reload() - } else { - const data = await response.json() - setSignInError(data.error || 'Invalid credentials') - setIsSubmitting(false) - } - } catch { - setSignInError('An error occurred. Please try again.') - setIsSubmitting(false) - } - } - const handleTokenChange = (e: React.ChangeEvent) => { const token = e.target.value const hostKey = extractHostFromToken(token) @@ -253,158 +215,88 @@ export default function AuthDialog({ Access Dashboard - Sign in with your credentials or use a Tinybird token directly. + Use a Tinybird token to access your dashboard. - setMode(value as AuthMode)}> - - Sign in - Tinybird Token - - - -
-
-
- - setUsername(e.target.value)} - placeholder="Enter username" - required - autoComplete="off" - autoFocus - /> -
- -
- - setPassword(e.target.value)} - placeholder="Enter password" - required - autoComplete="new-password" - /> - {!!signInError && ( - - {signInError} - - )} -
-
-
- -
-
-
- -
-
+ +
+
+ + + + Get your admin token + +
+ + {!tokenHasHost && ( + <>
- - - Get your admin token -
- {!tokenHasHost && ( - <> -
- - setHostName(e.target.value)} - /> -
- )} - + {hostUrl === 'other' && ( +
+ + setHostName(e.target.value)} + /> +
)} - -
- - setTenantId(e.target.value)} - /> -
-
-
- -
- - - + + )} + +
+ + setTenantId(e.target.value)} + /> +
+
+
+ +
+ ) diff --git a/dashboard/lib/hooks/use-login.ts b/dashboard/lib/hooks/use-login.ts index c347882..03ef396 100644 --- a/dashboard/lib/hooks/use-login.ts +++ b/dashboard/lib/hooks/use-login.ts @@ -1,6 +1,5 @@ 'use client' -import useSWR from 'swr' import { useSearchParams } from 'next/navigation' import { useCallback } from 'react' @@ -29,63 +28,18 @@ export function getStoredCredentials(): StoredCredentials | null { } } -function createFetcher(token: string | null, host: string | null) { - return (url: string) => { - const headers: HeadersInit = {} - if (token && host) { - headers['X-Tinybird-Token'] = token - headers['X-Tinybird-Host'] = host - } - return fetch(url, { headers }).then(res => res.json()) - } -} - export function useLogin() { const searchParams = useSearchParams() + const hasTokenAuth = + !!searchParams?.get('token') && !!searchParams?.get('host') - // Check URL params for token auth - const token = searchParams?.get('token') - const host = searchParams?.get('host') - const hasTokenAuth = !!token && !!host - - // Create fetcher with token/host to pass as headers - const fetcher = createFetcher(token, host) - - // Check server session auth - const { data, error, isLoading: isSessionLoading, mutate } = useSWR( - '/api/auth', - fetcher, - { - revalidateOnFocus: false, - revalidateOnReconnect: false, - } - ) - - const logout = useCallback(async () => { - // Clear URL params + const logout = useCallback(() => { const url = new URL(window.location.href) - url.searchParams.delete('token') - url.searchParams.delete('host') - url.searchParams.delete('tenant_id') - - // Also logout from server session if authenticated - if (data?.authenticated) { - await fetch('/api/auth/logout', { method: 'POST' }) - mutate({ authenticated: false }, false) + for (const param of ['token', 'host', 'tenant_id', 'workspace']) { + url.searchParams.delete(param) } - - // Navigate to URL without token params window.location.href = url.toString() - }, [data?.authenticated, mutate]) - - const isSessionAuth = data?.authenticated ?? false + }, []) - return { - isLoggedIn: isSessionAuth || hasTokenAuth, - isSessionAuth, - isTokenAuth: hasTokenAuth, - isLoading: isSessionLoading, - error, - logout, - } + return { isLoggedIn: hasTokenAuth, isLoading: false, logout } } diff --git a/dashboard/lib/server.ts b/dashboard/lib/server.ts index fb7442e..0d2b7db 100644 --- a/dashboard/lib/server.ts +++ b/dashboard/lib/server.ts @@ -1,62 +1,22 @@ -import { - AnalyticsClient, - createAnalyticsClient, -} from '@tinybirdco/analytics-client' +import { createAnalyticsClient } from '@tinybirdco/analytics-client' export interface TinybirdWorkspace { id: string name: string } -export function getTinybirdConfig() { - return { - token: process.env.TINYBIRD_TOKEN, - host: process.env.TINYBIRD_HOST, - } -} - -let client: AnalyticsClient | null = null - -export function isTinybirdConfigured(): boolean { - const { token, host } = getTinybirdConfig() - return !!token && !!host -} - -export function getServerClient() { - if (client) { - return client - } - - const { token, host } = getTinybirdConfig() - - if (!token || !host) { - const missing = [] - if (!token) missing.push('TINYBIRD_TOKEN') - if (!host) missing.push('TINYBIRD_HOST') - throw new Error( - `Tinybird configuration not found. Missing environment variables: ${missing.join( - ', ' - )}` - ) - } - - return createAnalyticsClient() +// Dashboard requests must supply their own complete credential pair. +// Never read deployment credentials here, even for legacy session cookies. +export function getRequestCredentials(request: Request) { + const token = request.headers.get('X-Tinybird-Token') + const host = request.headers.get('X-Tinybird-Host') + return token && host ? { token, host } : null } export function createClientWithCredentials(token: string, host: string) { return createAnalyticsClient({ token, baseUrl: host, devMode: false }) } -export async function getWorkspace(): Promise { - const { token, host } = getTinybirdConfig() - - if (!token || !host) { - return null - } - - return getWorkspaceWithCredentials(token, host) -} - export async function getWorkspaceWithCredentials( token: string, host: string diff --git a/dashboard/middleware.ts b/dashboard/middleware.ts deleted file mode 100644 index 35ad48b..0000000 --- a/dashboard/middleware.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' - -const SESSION_COOKIE_NAME = 'dashboard_session' - -export function middleware(request: NextRequest) { - // Skip auth if disabled (for development) - if (process.env.DISABLE_AUTH === 'true') { - return NextResponse.next() - } - - const { pathname } = request.nextUrl - - // Allow auth API routes - if (pathname.startsWith('/api/auth')) { - return NextResponse.next() - } - - // Allow static files and Next.js internals - if ( - pathname.startsWith('/_next') || - pathname.startsWith('/favicon') || - pathname.includes('.') - ) { - return NextResponse.next() - } - - // Check for token auth from headers (public mode) - const headerToken = request.headers.get('X-Tinybird-Token') - const headerHost = request.headers.get('X-Tinybird-Host') - if (headerToken && headerHost) { - return NextResponse.next() - } - - // Check for session cookie - const sessionCookie = request.cookies.get(SESSION_COOKIE_NAME) - - if (!sessionCookie?.value) { - // For API routes, return 401 - if (pathname.startsWith('/api')) { - return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) - } - // For pages, allow request but let client-side handle login dialog - // We use a custom header to signal auth status - const response = NextResponse.next() - response.headers.set('x-auth-status', 'unauthenticated') - return response - } - - return NextResponse.next() -} - -export const config = { - matcher: [ - /* - * Match all request paths except: - * - _next/static (static files) - * - _next/image (image optimization files) - * - favicon.ico (favicon file) - */ - '/((?!_next/static|_next/image|favicon.ico).*)', - ], -} diff --git a/dashboard/tests/credentials.cjs b/dashboard/tests/credentials.cjs new file mode 100644 index 0000000..2324216 --- /dev/null +++ b/dashboard/tests/credentials.cjs @@ -0,0 +1,44 @@ +const assert = require('node:assert/strict') +const fs = require('node:fs') +const vm = require('node:vm') +const ts = require('typescript') +const source = fs.readFileSync( + new URL('../lib/server.ts', `file://${__filename}`), + 'utf8' +) +const compiled = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS }, +}).outputText +const sandbox = { + exports: {}, + require: () => ({}), + process: { + env: { + TINYBIRD_TOKEN: 'server-secret', + TINYBIRD_HOST: 'https://server.example', + }, + }, +} +vm.runInNewContext(compiled, sandbox) +const credentials = sandbox.exports.getRequestCredentials +for (const headers of [ + {}, + { 'X-Tinybird-Host': 'https://caller.example' }, + { 'X-Tinybird-Token': 'caller-token' }, + { Cookie: 'dashboard_session=x' }, +]) { + assert.equal(credentials(new Request('http://dashboard', { headers })), null) +} +const result = credentials( + new Request('http://dashboard', { + headers: { + 'X-Tinybird-Host': 'https://caller.example', + 'X-Tinybird-Token': 'caller-token', + }, + }) +) +assert.equal(result.token, 'caller-token') +assert.equal(result.host, 'https://caller.example') +console.log( + 'Passed: credentials require both caller headers and never use the environment' +) diff --git a/dashboard/tests/token-auth.mjs b/dashboard/tests/token-auth.mjs new file mode 100644 index 0000000..7a8bf27 --- /dev/null +++ b/dashboard/tests/token-auth.mjs @@ -0,0 +1,84 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { once } from 'node:events' + +// Run against a local dashboard started with dummy deployment credentials and +// DISABLE_AUTH=true, so any accidental environment/session fallback is exercised. +const dashboard = process.env.TEST_DASHBOARD_URL || 'http://localhost:3097' +const requests = [] +const upstream = createServer((req, res) => { + requests.push({ url: req.url, authorization: req.headers.authorization }) + res.setHeader('Content-Type', 'application/json') + res.end( + JSON.stringify( + req.url === '/v1/workspace' + ? { id: 'test', name: 'Test workspace' } + : { data: [], meta: [], rows: 0, statistics: {} } + ) + ) +}) +upstream.listen(0, '127.0.0.1') +await once(upstream, 'listening') +const host = `http://127.0.0.1:${upstream.address().port}` +const token = 'caller-owned-test-token' +try { + for (const [path, method] of [ + ['/api/config', 'GET'], + ['/api/sql', 'POST'], + ['/api/endpoints/domains', 'GET'], + ]) { + for (const headers of [ + {}, + { Cookie: 'dashboard_session=x' }, + { 'X-Tinybird-Host': host, Cookie: 'dashboard_session=x' }, + { 'X-Tinybird-Token': token }, + ]) { + const response = await fetch(`${dashboard}${path}`, { + method, + headers: { ...headers, 'Content-Type': 'application/json' }, + ...(method === 'POST' && { body: JSON.stringify({ sql: 'SELECT 1' }) }), + }) + assert.equal( + response.status, + 401, + `${path} must reject incomplete credentials` + ) + } + assert.equal( + requests.length, + 0, + 'unauthorized requests must not reach upstream' + ) + } + for (const path of ['/api/auth', '/api/auth/login', '/api/auth/logout']) { + const response = await fetch(`${dashboard}${path}`, { + method: path === '/api/auth' ? 'GET' : 'POST', + }) + assert.equal(response.status, 404, `${path} must be removed`) + } + for (const [path, method] of [ + ['/api/config', 'GET'], + ['/api/sql', 'POST'], + ['/api/endpoints/domains', 'GET'], + ]) { + const before = requests.length + const response = await fetch(`${dashboard}${path}`, { + method, + headers: { + 'X-Tinybird-Token': token, + 'X-Tinybird-Host': host, + 'Content-Type': 'application/json', + }, + ...(method === 'POST' && { body: JSON.stringify({ sql: 'SELECT 1' }) }), + }) + assert.equal(response.status, 200, `${path}: ${await response.text()}`) + assert.ok(requests.length > before, `${path} must reach caller's upstream`) + } + assert.ok(requests.every(req => req.authorization === `Bearer ${token}`)) + console.log( + 'Passed: incomplete credentials, legacy cookie, removed auth routes, and caller-token forwarding on all three data routes' + ) +} finally { + upstream.closeAllConnections() + upstream.close() +} From 0e1deaed775991d7d4f7f28cacf26f2f87f423bd Mon Sep 17 00:00:00 2001 From: Rafa Moreno Date: Tue, 3 Nov 2026 13:49:33 +0100 Subject: [PATCH 2/2] Remove Tinybird preview and production deployment workflows --- .github/workflows/tinybird-cd.yml | 33 ------------------------ .github/workflows/tinybird-ci.yml | 43 ------------------------------- 2 files changed, 76 deletions(-) delete mode 100644 .github/workflows/tinybird-cd.yml delete mode 100644 .github/workflows/tinybird-ci.yml diff --git a/.github/workflows/tinybird-cd.yml b/.github/workflows/tinybird-cd.yml deleted file mode 100644 index 7560422..0000000 --- a/.github/workflows/tinybird-cd.yml +++ /dev/null @@ -1,33 +0,0 @@ -name: Tinybird - CD Workflow - -on: - workflow_dispatch: - push: - branches: - - main - -env: - TINYBIRD_HOST: ${{ secrets.TINYBIRD_HOST }} - TINYBIRD_TOKEN: ${{ secrets.TINYBIRD_TOKEN }} - -jobs: - cd: - runs-on: ubuntu-latest - defaults: - run: - working-directory: '.' - steps: - - uses: actions/checkout@v4 - - name: Install pnpm - uses: pnpm/action-setup@v4 - with: - version: 9 - - name: Use Node.js 22 - uses: actions/setup-node@v4 - with: - node-version: 22.x - cache: 'pnpm' - - name: Install dependencies - run: pnpm install - - name: Deploy to production - run: pnpm run tinybird:deploy diff --git a/.github/workflows/tinybird-ci.yml b/.github/workflows/tinybird-ci.yml deleted file mode 100644 index 44f273e..0000000 --- a/.github/workflows/tinybird-ci.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Tinybird - CI Workflow - -on: - workflow_dispatch: - pull_request: - branches: - - main - types: [opened, reopened, labeled, unlabeled, synchronize] - -concurrency: ${{ github.workflow }}-${{ github.event.pull_request.number }} - -env: - TINYBIRD_HOST: ${{ secrets.TINYBIRD_HOST }} - TINYBIRD_TOKEN: ${{ secrets.TINYBIRD_TOKEN }} - -jobs: - ci: - runs-on: ubuntu-latest - defaults: - run: - working-directory: '.' - services: - tinybird: - image: tinybirdco/tinybird-local:latest - ports: - - 7181:7181 - steps: - - uses: actions/checkout@v4 - - name: Install pnpm - uses: pnpm/action-setup@v4 - with: - version: 9 - - name: Use Node.js 22 - uses: actions/setup-node@v4 - with: - node-version: 22.x - cache: 'pnpm' - - name: Install dependencies - run: pnpm install - - name: Build locally - run: pnpm run tinybird:build -- --local - - name: Preview in a branch - run: pnpm run tinybird:preview