Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion dashboard/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 8 additions & 2 deletions dashboard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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`.

Expand Down
64 changes: 40 additions & 24 deletions dashboard/app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -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 })
}
Expand Down
38 changes: 2 additions & 36 deletions dashboard/app/api/auth/route.ts
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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),
})
}
66 changes: 31 additions & 35 deletions dashboard/app/api/config/route.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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,
},
})
}
34 changes: 12 additions & 22 deletions dashboard/app/api/endpoints/[name]/route.ts
Original file line number Diff line number Diff line change
@@ -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',
Expand Down Expand Up @@ -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<string, string> = {}
Expand Down
66 changes: 0 additions & 66 deletions dashboard/app/api/sql/route.ts

This file was deleted.

Loading
Loading