diff --git a/CHANGELOG.md b/CHANGELOG.md index 2767b9e4..7d9ef94a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased +### Security +- [Dashboard] Never send the server `TINYBIRD_TOKEN` to a host taken from the `X-Tinybird-Host` header; only accept Tinybird API hosts in token mode +- [Dashboard] Validate signed, expiring session cookies in middleware and API routes +- [Dashboard] Remove the `admin/admin` default credentials; login requires `DASHBOARD_PASSWORD` +- [Dashboard] Remove the unused `/api/sql` route, which ran arbitrary SQL with the server `TINYBIRD_TOKEN` + - [Data project] Fix `top_devices` and `top_browsers` session count (#90) ## [1.4.0] - 2023-04-12 diff --git a/dashboard/.env.example b/dashboard/.env.example index d92566d2..341a4e3d 100644 --- a/dashboard/.env.example +++ b/dashboard/.env.example @@ -8,10 +8,14 @@ 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 Basic Auth (server-only). Login is disabled unless DASHBOARD_PASSWORD is set. # DASHBOARD_USERNAME=admin # DASHBOARD_PASSWORD=changeme +# Optional: extra Tinybird API hosts accepted in token mode (comma-separated). +# *.tinybird.co API hosts and TINYBIRD_HOST are always accepted. +# TINYBIRD_ALLOWED_HOSTS= + # Optional: Set to "true" to disable auth during development DISABLE_AUTH=false diff --git a/dashboard/README.md b/dashboard/README.md index 2326df1a..745eb952 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -51,10 +51,14 @@ 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 Basic Auth (server-only). Login is disabled unless DASHBOARD_PASSWORD is set. # DASHBOARD_USERNAME=admin # DASHBOARD_PASSWORD=changeme +# Optional: extra Tinybird API hosts accepted in token mode (comma-separated). +# *.tinybird.co API hosts and TINYBIRD_HOST are always accepted. +# TINYBIRD_ALLOWED_HOSTS= + # Optional: Set to "true" to disable auth during development DISABLE_AUTH=false @@ -66,7 +70,9 @@ To develop locally, start [Tinybird Local](https://www.tinybird.co/docs/cli/loca ### 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 includes built-in authentication. Set `DASHBOARD_PASSWORD` (and optionally `DASHBOARD_USERNAME`, defaults to `admin`) to enable username/password login; without `DASHBOARD_PASSWORD`, login is disabled. Sessions are signed and expire after 7 days; changing the password invalidates existing sessions. + +The server-side `TINYBIRD_TOKEN` is only ever sent to `TINYBIRD_HOST`. When signing in with a Tinybird token, the host must be a Tinybird API host (`https://api.*.tinybird.co`), `TINYBIRD_HOST`, or listed in `TINYBIRD_ALLOWED_HOSTS`. For local development, you can disable authentication by setting `DISABLE_AUTH=true`. diff --git a/dashboard/app/api/auth/login/route.ts b/dashboard/app/api/auth/login/route.ts index 863c8a1e..5aae62a3 100644 --- a/dashboard/app/api/auth/login/route.ts +++ b/dashboard/app/api/auth/login/route.ts @@ -1,37 +1,53 @@ 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') +import { createHash, timingSafeEqual } from 'crypto' +import { + SESSION_COOKIE_NAME, + SESSION_MAX_AGE, + createSessionToken, + getDashboardCredentials, +} from '@/lib/session' + +function safeEqual(a: string, b: string): boolean { + return timingSafeEqual( + createHash('sha256').update(a).digest(), + createHash('sha256').update(b).digest() + ) } 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 credentials = getDashboardCredentials() + if (!credentials) { + return NextResponse.json( + { + error: + 'Dashboard login is not configured. Set DASHBOARD_PASSWORD to enable it.', + }, + { status: 503 } + ) + } + if ( + typeof username === 'string' && + typeof password === 'string' && + safeEqual(username, credentials.username) && + safeEqual(password, credentials.password) + ) { 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: '/', - }) + cookieStore.set( + SESSION_COOKIE_NAME, + await createSessionToken(credentials), + { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + maxAge: SESSION_MAX_AGE, + path: '/', + } + ) return NextResponse.json({ success: true }) } diff --git a/dashboard/app/api/auth/route.ts b/dashboard/app/api/auth/route.ts index 0a9f7393..8f5f0b4b 100644 --- a/dashboard/app/api/auth/route.ts +++ b/dashboard/app/api/auth/route.ts @@ -1,34 +1,6 @@ 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 - } -} +import { SESSION_COOKIE_NAME, verifySessionToken } from '@/lib/session' // GET - Check auth status export async function GET(request: NextRequest) { @@ -47,13 +19,7 @@ export async function GET(request: NextRequest) { 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, + authenticated: await verifySessionToken(sessionCookie?.value), }) } diff --git a/dashboard/app/api/config/route.ts b/dashboard/app/api/config/route.ts index 28aba459..37281dbf 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 { + getWorkspaceWithCredentials, + resolveTinybirdCredentials, +} 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,43 @@ 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 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 + const result = resolveTinybirdCredentials(request.headers) + + if ('error' in result) { + if (result.missing) { + return NextResponse.json({ + configured: false, + missing: result.missing, + workspace: null, + }) + } + return NextResponse.json({ error: result.error }, { status: result.status }) + } - // Include workspace info if configured - const regionInfo = host ? await getRegionInfoFromHost(host) : null + const { token, host, fromHeaders } = result.credentials + 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 && fromHeaders) { + 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 060317b8..6bac5657 100644 --- a/dashboard/app/api/endpoints/[name]/route.ts +++ b/dashboard/app/api/endpoints/[name]/route.ts @@ -1,5 +1,9 @@ import { NextRequest, NextResponse } from 'next/server' -import { getServerClient, getTinybirdConfig, createClientWithCredentials } from '@/lib/server' +import { + createClientWithCredentials, + getServerClient, + resolveTinybirdCredentials, +} from '@/lib/server' const VALID_ENDPOINTS = [ 'currentVisitors', @@ -44,31 +48,17 @@ 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 credentialsResult = resolveTinybirdCredentials(request.headers) + if ('error' in credentialsResult) { return NextResponse.json( - { - error: `Tinybird configuration not found. Missing: ${missing.join( - ', ' - )}`, - }, - { status: 503 } + { error: credentialsResult.error }, + { status: credentialsResult.status } ) } - // Use header credentials if provided, otherwise use server client - const client = headerToken && headerHost - ? createClientWithCredentials(headerToken, headerHost) + const { token, host, fromHeaders } = credentialsResult.credentials + const client = fromHeaders + ? createClientWithCredentials(token, host) : 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 deleted file mode 100644 index a125568d..00000000 --- a/dashboard/app/api/sql/route.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { getTinybirdConfig } from '@/lib/server' - -const uiToApiHost: Record = { - 'https://ui.tinybird.co': 'https://api.tinybird.co', - 'https://ui.us-east.tinybird.co': 'https://api.us-east.tinybird.co', -} - -export async function POST(request: NextRequest) { - try { - const { sql } = await request.json() - - if (!sql || typeof sql !== 'string') { - 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') - return NextResponse.json( - { - error: `Tinybird configuration not found. Missing: ${missing.join( - ', ' - )}`, - }, - { status: 503 } - ) - } - - const apiUrl = uiToApiHost[host] ?? host - const response = await fetch( - `${apiUrl}/v0/sql?q=${encodeURIComponent(sql)}`, - { - headers: { - Authorization: `Bearer ${token}`, - }, - } - ) - - const data = await response.json() - - if (!response.ok) { - return NextResponse.json( - { error: data?.error ?? 'Query failed' }, - { status: response.status } - ) - } - - return NextResponse.json(data) - } catch (error) { - console.error('SQL query error:', error) - return NextResponse.json( - { error: error instanceof Error ? error.message : 'Query failed' }, - { status: 500 } - ) - } -} diff --git a/dashboard/lib/api.ts b/dashboard/lib/api.ts index e3be3340..959dd160 100644 --- a/dashboard/lib/api.ts +++ b/dashboard/lib/api.ts @@ -1,5 +1,5 @@ import fetch from 'cross-fetch' -import { PipeParams, QueryPipe, QuerySQL, QueryError } from './types/api' +import { PipeParams, QueryPipe, QueryError } from './types/api' import { getStoredCredentials } from './hooks/use-login' function getAuthHeaders(): HeadersInit { @@ -34,22 +34,3 @@ export async function queryPipe( return data } - -export async function querySQL(sql: string): Promise> { - const response = await fetch('/api/sql', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - ...getAuthHeaders(), - }, - body: JSON.stringify({ sql }), - }) - - const data = await response.json() - - if (!response.ok) { - throw new QueryError(data?.error ?? 'Something went wrong', response.status) - } - - return data -} diff --git a/dashboard/lib/server.ts b/dashboard/lib/server.ts index fb7442ea..9daae50d 100644 --- a/dashboard/lib/server.ts +++ b/dashboard/lib/server.ts @@ -47,16 +47,6 @@ 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 @@ -77,3 +67,95 @@ export async function getWorkspaceWithCredentials( const data = (await response.json()) as TinybirdWorkspace return data } + +const UI_TO_API_HOST: Record = { + 'https://ui.tinybird.co': 'https://api.tinybird.co', + 'https://ui.us-east.tinybird.co': 'https://api.us-east.tinybird.co', +} + +const TINYBIRD_API_HOSTNAME = /^api(\.[a-z0-9-]+)*\.tinybird\.co$/ +const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1']) + +function toApiOrigin(host: string): string | null { + try { + const { origin } = new URL(host) + return UI_TO_API_HOST[origin] ?? origin + } catch { + return null + } +} + +function getExtraAllowedOrigins(): string[] { + return [ + process.env.TINYBIRD_HOST, + ...(process.env.TINYBIRD_ALLOWED_HOSTS ?? '').split(','), + ] + .map(host => host?.trim()) + .filter((host): host is string => !!host) + .map(toApiOrigin) + .filter((origin): origin is string => !!origin) +} + +function isAllowedTinybirdOrigin(origin: string): boolean { + if (getExtraAllowedOrigins().includes(origin)) { + return true + } + const url = new URL(origin) + if ( + url.protocol === 'https:' && + !url.port && + TINYBIRD_API_HOSTNAME.test(url.hostname) + ) { + return true + } + return ( + process.env.NODE_ENV !== 'production' && LOCAL_HOSTNAMES.has(url.hostname) + ) +} + +export interface TinybirdCredentials { + token: string + host: string + fromHeaders: boolean +} + +export type TinybirdCredentialsResult = + | { credentials: TinybirdCredentials } + | { error: string; status: number; missing?: string[] } + +export function resolveTinybirdCredentials( + headers: Headers +): TinybirdCredentialsResult { + const headerToken = headers.get('X-Tinybird-Token') + if (headerToken) { + const headerHost = headers.get('X-Tinybird-Host') + const origin = headerHost ? toApiOrigin(headerHost) : null + if (!origin || !isAllowedTinybirdOrigin(origin)) { + return { error: 'Invalid or unsupported Tinybird host', status: 400 } + } + return { + credentials: { token: headerToken, host: origin, fromHeaders: true }, + } + } + + // The server token is only ever sent to the configured TINYBIRD_HOST, + // never to a host taken from the request. + const { token, host } = getTinybirdConfig() + if (!token || !host) { + const missing = [] + if (!token) missing.push('TINYBIRD_TOKEN') + if (!host) missing.push('TINYBIRD_HOST') + return { + error: `Tinybird configuration not found. Missing: ${missing.join(', ')}`, + status: 503, + missing, + } + } + return { + credentials: { + token, + host: UI_TO_API_HOST[host] ?? host, + fromHeaders: false, + }, + } +} diff --git a/dashboard/lib/session.ts b/dashboard/lib/session.ts new file mode 100644 index 00000000..11a2b9f6 --- /dev/null +++ b/dashboard/lib/session.ts @@ -0,0 +1,99 @@ +export const SESSION_COOKIE_NAME = 'dashboard_session' +export const SESSION_MAX_AGE = 60 * 60 * 24 * 7 // 7 days + +export interface DashboardCredentials { + username: string + password: string +} + +const encoder = new TextEncoder() +const decoder = new TextDecoder() + +export function getDashboardCredentials(): DashboardCredentials | null { + const password = process.env.DASHBOARD_PASSWORD + if (!password) { + return null + } + return { username: process.env.DASHBOARD_USERNAME || 'admin', password } +} + +function toBase64Url(bytes: Uint8Array): string { + let binary = '' + bytes.forEach(byte => { + binary += String.fromCharCode(byte) + }) + return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +function fromBase64Url(value: string): Uint8Array { + const base64 = + value.replace(/-/g, '+').replace(/_/g, '/') + + '==='.slice((value.length + 3) % 4) + return Uint8Array.from(atob(base64), char => char.charCodeAt(0)) +} + +function getSigningKey(credentials: DashboardCredentials): Promise { + return crypto.subtle.importKey( + 'raw', + encoder.encode(`${credentials.username}:${credentials.password}`), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign', 'verify'] + ) +} + +export async function createSessionToken( + credentials: DashboardCredentials +): Promise { + const payload = toBase64Url( + encoder.encode( + JSON.stringify({ + username: credentials.username, + exp: Date.now() + SESSION_MAX_AGE * 1000, + }) + ) + ) + const key = await getSigningKey(credentials) + const signature = await crypto.subtle.sign( + 'HMAC', + key, + encoder.encode(payload) + ) + return `${payload}.${toBase64Url(new Uint8Array(signature))}` +} + +export async function verifySessionToken( + sessionToken: string | undefined +): Promise { + const credentials = getDashboardCredentials() + if (!credentials || !sessionToken) { + return false + } + + const [payload, signature, ...rest] = sessionToken.split('.') + if (!payload || !signature || rest.length > 0) { + return false + } + + try { + const key = await getSigningKey(credentials) + const isValidSignature = await crypto.subtle.verify( + 'HMAC', + key, + fromBase64Url(signature), + encoder.encode(payload) + ) + if (!isValidSignature) { + return false + } + + const { username, exp } = JSON.parse(decoder.decode(fromBase64Url(payload))) + return ( + username === credentials.username && + typeof exp === 'number' && + exp > Date.now() + ) + } catch { + return false + } +} diff --git a/dashboard/lib/types/api.ts b/dashboard/lib/types/api.ts index 912f6571..8d9dae31 100644 --- a/dashboard/lib/types/api.ts +++ b/dashboard/lib/types/api.ts @@ -17,8 +17,6 @@ export type PipeParams = Record export type QueryPipe = ClientResponse -export type QuerySQL = ClientResponse - export class QueryError extends Error { constructor( message: string, diff --git a/dashboard/middleware.ts b/dashboard/middleware.ts index 35ad48b6..399def5b 100644 --- a/dashboard/middleware.ts +++ b/dashboard/middleware.ts @@ -1,8 +1,7 @@ import { NextRequest, NextResponse } from 'next/server' +import { SESSION_COOKIE_NAME, verifySessionToken } from '@/lib/session' -const SESSION_COOKIE_NAME = 'dashboard_session' - -export function middleware(request: NextRequest) { +export async function middleware(request: NextRequest) { // Skip auth if disabled (for development) if (process.env.DISABLE_AUTH === 'true') { return NextResponse.next() @@ -31,10 +30,9 @@ export function middleware(request: NextRequest) { return NextResponse.next() } - // Check for session cookie const sessionCookie = request.cookies.get(SESSION_COOKIE_NAME) - if (!sessionCookie?.value) { + if (!(await verifySessionToken(sessionCookie?.value))) { // For API routes, return 401 if (pathname.startsWith('/api')) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })