diff --git a/.github/workflows/ci-workflow.yml b/.github/workflows/ci-workflow.yml index 7956f7d..6e3ac27 100644 --- a/.github/workflows/ci-workflow.yml +++ b/.github/workflows/ci-workflow.yml @@ -25,6 +25,22 @@ 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 + TINYBIRD_ALLOWED_HOSTS: http://127.0.0.1:3098 + 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/.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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d9ef94..00f98ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## 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] Restrict token-mode upstreams to Tinybird API origins or explicitly configured allowed origins +- [Dashboard] Remove password/session authentication, including the development auth bypass; require caller-supplied Tinybird token and host headers +- [Dashboard] Remove deployment-token fallback while preserving the allowed-host policy - [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) 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/.env.example b/dashboard/.env.example index 341a4e3..99b44ef 100644 --- a/dashboard/.env.example +++ b/dashboard/.env.example @@ -1,23 +1,12 @@ -# 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). 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 +# Optional: extra API origins accepted for caller-supplied tokens (comma-separated) +# HTTPS Tinybird API origins are always accepted; localhost is accepted in development. +# TINYBIRD_ALLOWED_HOSTS=https://my-tinybird.example # Optional: AI Chat NEXT_PUBLIC_ASK_TINYBIRD_ENDPOINT="https://ask-tb.tinybird.live/api/chat" diff --git a/dashboard/README.md b/dashboard/README.md index 745eb95..8d9f2c1 100644 --- a/dashboard/README.md +++ b/dashboard/README.md @@ -41,40 +41,28 @@ 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). 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 +# Optional: extra API origins accepted for caller-supplied tokens (comma-separated) +# TINYBIRD_ALLOWED_HOSTS=https://my-tinybird.example # 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. 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 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. -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`. +Password login, session cookies, and `DISABLE_AUTH` have been removed. The dashboard no longer uses `TINYBIRD_TOKEN`; remove it from dashboard deployments and use caller-supplied credentials. `TINYBIRD_HOST`, if set, only adds an allowed origin and never supplies request credentials. Credentials needed by the separate Tinybird deployment tooling or ingestion middleware remain separate. -For local development, you can disable authentication by setting `DISABLE_AUTH=true`. +The host restrictions introduced by the security fix remain: HTTPS Tinybird API origins are accepted, as are origins explicitly configured in `TINYBIRD_ALLOWED_HOSTS` or `TINYBIRD_HOST`. Localhost origins are also accepted during development. Both credential headers are required even when an allowed host is configured. ### 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 5aae62a..0000000 --- a/dashboard/app/api/auth/login/route.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { cookies } from 'next/headers' -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() - - 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, - await createSessionToken(credentials), - { - 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 8f5f0b4..0000000 --- a/dashboard/app/api/auth/route.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { cookies } from 'next/headers' -import { SESSION_COOKIE_NAME, verifySessionToken } from '@/lib/session' - -// 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) - - return NextResponse.json({ - authenticated: await verifySessionToken(sessionCookie?.value), - }) -} diff --git a/dashboard/app/api/config/route.ts b/dashboard/app/api/config/route.ts index 37281db..929d9aa 100644 --- a/dashboard/app/api/config/route.ts +++ b/dashboard/app/api/config/route.ts @@ -89,17 +89,10 @@ export async function GET(request: NextRequest) { 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 }) } - const { token, host, fromHeaders } = result.credentials + const { token, host } = result.credentials const regionInfo = await getRegionInfoFromHost(host) // Use workspace name from header if provided (avoids permission issues with scoped JWT) @@ -111,7 +104,7 @@ export async function GET(request: NextRequest) { } // If still no workspace name and we have a token, try to decode it - if (!workspaceName && fromHeaders) { + if (!workspaceName) { workspaceName = extractWorkspaceNameFromToken(token) } diff --git a/dashboard/app/api/endpoints/[name]/route.ts b/dashboard/app/api/endpoints/[name]/route.ts index 6bac565..1137979 100644 --- a/dashboard/app/api/endpoints/[name]/route.ts +++ b/dashboard/app/api/endpoints/[name]/route.ts @@ -1,7 +1,6 @@ import { NextRequest, NextResponse } from 'next/server' import { createClientWithCredentials, - getServerClient, resolveTinybirdCredentials, } from '@/lib/server' @@ -56,10 +55,8 @@ export async function GET( ) } - const { token, host, fromHeaders } = credentialsResult.credentials - const client = fromHeaders - ? createClientWithCredentials(token, host) - : getServerClient() + const { token, host } = credentialsResult.credentials + const client = createClientWithCredentials(token, host) const searchParams = request.nextUrl.searchParams const queryParams: Record = {} diff --git a/dashboard/app/page.tsx b/dashboard/app/page.tsx index 3764b1f..fb5f56c 100644 --- a/dashboard/app/page.tsx +++ b/dashboard/app/page.tsx @@ -23,7 +23,7 @@ import AuthDialog from '@/components/AuthDialog' import { useLogin } from '@/lib/hooks/use-login' export default function DashboardPage() { - const { isLoggedIn, isLoading: isLoginLoading, logout } = useLogin() + const { isLoggedIn, logout } = useLogin() const { value: timeRangeValue, setValue: setTimeRangeValue, @@ -34,12 +34,12 @@ export default function DashboardPage() { const insights = createInsightsFromData(insightsData) const currentVisitors = useCurrentVisitors() - const showLoginDialog = isLoginLoading || !isLoggedIn + const showLoginDialog = !isLoggedIn return ( {/* Show login dialog overlay when not logged in */} - {showLoginDialog && } + {showLoginDialog && } <> {process.env.NODE_ENV === 'production' && ( diff --git a/dashboard/components/AuthDialog.tsx b/dashboard/components/AuthDialog.tsx index 70c97d2..0877a34 100644 --- a/dashboard/components/AuthDialog.tsx +++ b/dashboard/components/AuthDialog.tsx @@ -13,12 +13,8 @@ import { Button } from '@/components/ui/Button' 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', @@ -127,54 +123,13 @@ export async function createJwt( .sign(key) } -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) - +export default function AuthDialog() { // 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) @@ -239,172 +194,94 @@ export default function AuthDialog({ { value: 'other', label: 'Other' }, ] - if (isCheckingAuth) { - return ( -
- -
- ) - } - return ( 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..32aa533 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,19 @@ 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, - } + // Credential availability is synchronous; data hooks still consume isLoading. + return { isLoggedIn: hasTokenAuth, isLoading: false, logout } } diff --git a/dashboard/lib/server.ts b/dashboard/lib/server.ts index 9daae50..f34c247 100644 --- a/dashboard/lib/server.ts +++ b/dashboard/lib/server.ts @@ -1,48 +1,10 @@ -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() -} - export function createClientWithCredentials(token: string, host: string) { return createAnalyticsClient({ token, baseUrl: host, devMode: false }) } @@ -116,46 +78,25 @@ function isAllowedTinybirdOrigin(origin: string): boolean { export interface TinybirdCredentials { token: string host: string - fromHeaders: boolean } export type TinybirdCredentialsResult = | { credentials: TinybirdCredentials } - | { error: string; status: number; missing?: string[] } + | { error: string; status: number } 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() + const token = headers.get('X-Tinybird-Token') + const host = headers.get('X-Tinybird-Host') 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 { error: 'Tinybird token and host required', status: 401 } } - return { - credentials: { - token, - host: UI_TO_API_HOST[host] ?? host, - fromHeaders: false, - }, + + const origin = toApiOrigin(host) + if (!origin || !isAllowedTinybirdOrigin(origin)) { + return { error: 'Invalid or unsupported Tinybird host', status: 400 } } + + return { credentials: { token, host: origin } } } diff --git a/dashboard/lib/session.ts b/dashboard/lib/session.ts deleted file mode 100644 index 11a2b9f..0000000 --- a/dashboard/lib/session.ts +++ /dev/null @@ -1,99 +0,0 @@ -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/middleware.ts b/dashboard/middleware.ts deleted file mode 100644 index 399def5..0000000 --- a/dashboard/middleware.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server' -import { SESSION_COOKIE_NAME, verifySessionToken } from '@/lib/session' - -export async 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() - } - - const sessionCookie = request.cookies.get(SESSION_COOKIE_NAME) - - if (!(await verifySessionToken(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..ec866bf --- /dev/null +++ b/dashboard/tests/credentials.cjs @@ -0,0 +1,76 @@ +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 env = { + NODE_ENV: 'production', + TINYBIRD_TOKEN: 'server-secret', + TINYBIRD_HOST: 'https://server.example', + TINYBIRD_ALLOWED_HOSTS: ' https://custom.example , https://second.example ', + DASHBOARD_USERNAME: 'admin', + DASHBOARD_PASSWORD: 'admin', + DISABLE_AUTH: 'true', +} +const sandbox = { exports: {}, require: () => ({}), process: { env }, URL } +vm.runInNewContext(compiled, sandbox) +const resolve = headers => + sandbox.exports.resolveTinybirdCredentials(new Headers(headers)) +for (const headers of [ + {}, + { 'X-Tinybird-Host': 'https://api.tinybird.co' }, + { 'X-Tinybird-Token': 'caller-token' }, + { Cookie: 'dashboard_session=x' }, + { + 'X-Tinybird-Host': 'https://server.example', + Cookie: 'dashboard_session=x', + }, +]) { + assert.equal(resolve(headers).status, 401) +} +function withHost(host) { + return resolve({ + 'X-Tinybird-Host': host, + 'X-Tinybird-Token': 'caller-token', + }) +} +for (const host of [ + 'https://api.tinybird.co', + 'https://api.eu-central-1.aws.tinybird.co', + 'https://ui.tinybird.co', + 'https://ui.us-east.tinybird.co', + 'https://server.example', + 'https://custom.example', + 'https://second.example', +]) { + const { credentials } = withHost(host) + assert.equal(credentials.token, 'caller-token') + assert.equal(credentials.host, host.replace('https://ui.', 'https://api.')) +} +for (const host of [ + 'not a URL', + 'https://attacker.example', + 'https://api.tinybird.co.attacker.example', + 'http://api.tinybird.co', + 'https://api.tinybird.co:8443', + 'http://localhost:7181', + 'http://127.0.0.1:7181', +]) { + assert.equal(withHost(host).status, 400, host) +} +env.NODE_ENV = 'development' +assert.equal( + withHost('http://localhost:7181').credentials.token, + 'caller-token' +) +assert.equal( + withHost('http://127.0.0.1:7181').credentials.token, + 'caller-token' +) +console.log('Passed: caller-only credentials and preserved allowed-host policy') diff --git a/dashboard/tests/token-auth.mjs b/dashboard/tests/token-auth.mjs new file mode 100644 index 0000000..4ff00f7 --- /dev/null +++ b/dashboard/tests/token-auth.mjs @@ -0,0 +1,94 @@ +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: {} } + ) + ) +}) +// Explicitly allow this test origin via TINYBIRD_ALLOWED_HOSTS on the dashboard. +upstream.listen(Number(process.env.TEST_UPSTREAM_PORT || 3098), '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 of ['/api/config', '/api/endpoints/domains']) { + 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}`, { + headers: { ...headers, 'Content-Type': 'application/json' }, + }) + 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', + '/api/sql', + ]) { + const response = await fetch(`${dashboard}${path}`, { + method: path === '/api/auth' ? 'GET' : 'POST', + }) + assert.equal(response.status, 404, `${path} must be removed`) + } + for (const path of ['/api/config', '/api/endpoints/domains']) { + const before = requests.length + const response = await fetch(`${dashboard}${path}`, { + headers: { + 'X-Tinybird-Token': token, + 'X-Tinybird-Host': host, + 'Content-Type': 'application/json', + }, + }) + assert.equal(response.status, 200, `${path}: ${await response.text()}`) + assert.ok(requests.length > before, `${path} must reach caller's upstream`) + } + const before = requests.length + for (const path of ['/api/config', '/api/endpoints/domains']) { + const response = await fetch(`${dashboard}${path}`, { + headers: { + 'X-Tinybird-Token': token, + // Same local upstream, but a hostname that is not on the allowlist. + 'X-Tinybird-Host': `http://localhost:${upstream.address().port}`, + }, + }) + assert.equal(response.status, 400, `${path} must reject unapproved hosts`) + } + assert.equal( + requests.length, + before, + 'unapproved hosts must not receive a request' + ) + assert.ok(requests.every(req => req.authorization === `Bearer ${token}`)) + console.log( + 'Passed: incomplete credentials, legacy cookie, removed auth/SQL routes, allowed hosts, and caller-token forwarding' + ) +} finally { + upstream.closeAllConnections() + upstream.close() +}