diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a881f62 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +dist/ +.next/ +.env +.env.local +*.log +coverage/ diff --git a/api/.env.example b/api/.env.example new file mode 100644 index 0000000..36ce72c --- /dev/null +++ b/api/.env.example @@ -0,0 +1,28 @@ +# Copy to .env and fill in values. Never commit .env. + +# Server +NODE_ENV=development +HOST=0.0.0.0 +PORT=3200 +LOG_LEVEL=info + +# Database +DATABASE_URL=postgresql://errors:password@localhost:5432/errors_bitreport + +# JWT — generate with: openssl rand -base64 64 +JWT_SECRET=change_me_in_production_64_bytes_minimum + +# Cookie signing — generate with: openssl rand -base64 32 +COOKIE_SECRET=change_me_in_production_32_bytes_minimum + +# Rate limits (optional — defaults shown) +# RATE_INGEST_MAX=1000 +# RATE_INGEST_WINDOW_MS=60000 +# RATE_LOGIN_MAX=10 +# RATE_LOGIN_WINDOW_MS=300000 +# RATE_GLOBAL_MAX=500 +# RATE_GLOBAL_WINDOW_MS=60000 + +# Payload limits (optional — defaults shown) +# INGEST_MAX_BODY_BYTES=524288 # 512 KB +# ADMIN_MAX_BODY_BYTES=65536 # 64 KB diff --git a/api/package.json b/api/package.json new file mode 100644 index 0000000..8c21148 --- /dev/null +++ b/api/package.json @@ -0,0 +1,35 @@ +{ + "name": "@errors-bitreport/api", + "version": "0.1.0", + "description": "BitReport Error Reporting Platform — Fastify API", + "type": "module", + "scripts": { + "dev": "tsx watch src/index.ts", + "build": "tsc", + "start": "node dist/index.js", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "db:migrate": "node-pg-migrate -d $DATABASE_URL up", + "db:migrate:down": "node-pg-migrate -d $DATABASE_URL down" + }, + "dependencies": { + "@fastify/cookie": "^9.3.1", + "@fastify/helmet": "^11.1.1", + "@fastify/jwt": "^8.0.1", + "@fastify/rate-limit": "^9.1.0", + "@fastify/swagger": "^8.14.0", + "@fastify/swagger-ui": "^3.0.0", + "fastify": "^4.27.0", + "pg": "^8.11.5", + "pino": "^9.1.0", + "zod": "^3.23.8" + }, + "devDependencies": { + "@types/node": "^20.14.0", + "@types/pg": "^8.11.6", + "tsx": "^4.15.6", + "typescript": "^5.4.5", + "vitest": "^1.6.0" + } +} diff --git a/api/src/index.ts b/api/src/index.ts new file mode 100644 index 0000000..7b69b7c --- /dev/null +++ b/api/src/index.ts @@ -0,0 +1,78 @@ +/** + * BitReport Error Reporting Platform — Fastify API entry point. + */ +import Fastify from 'fastify'; +import cookie from '@fastify/cookie'; +import jwt from '@fastify/jwt'; +import helmet from '@fastify/helmet'; +import rateLimit from '@fastify/rate-limit'; + +import dbPlugin from './plugins/db.js'; +import authPlugin from './plugins/auth.js'; +import rbacPlugin from './plugins/rbac.js'; +import auditPlugin from './plugins/audit.js'; +import rateLimitPlugin from './plugins/rate-limit.js'; +import { INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES } from './plugins/rate-limit.js'; + +import adminAuthRoutes from './routes/admin/auth.js'; + +const IS_PROD = process.env.NODE_ENV === 'production'; + +const app = Fastify({ + logger: { + level: process.env.LOG_LEVEL ?? 'info', + ...(IS_PROD ? {} : { transport: { target: 'pino-pretty' } }), + }, + // Use the larger of the two limits as the global hard cap; per-route hooks refine. + bodyLimit: Math.max(INGEST_MAX_BODY_BYTES, ADMIN_MAX_BODY_BYTES), + trustProxy: IS_PROD, // trust X-Forwarded-For behind reverse proxy in prod +}); + +// Security headers +await app.register(helmet, { + contentSecurityPolicy: IS_PROD ? undefined : false, +}); + +// Cookies (required before JWT cookie mode) +await app.register(cookie, { + secret: process.env.COOKIE_SECRET ?? (() => { throw new Error('COOKIE_SECRET is required'); })(), +}); + +// JWT +await app.register(jwt, { + secret: process.env.JWT_SECRET ?? (() => { throw new Error('JWT_SECRET is required'); })(), + cookie: { cookieName: '__Host-access', signed: false }, +}); + +// Global rate limit (per-route limits override this) +await app.register(rateLimit, { + global: true, + max: parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10), + timeWindow: parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10), +}); + +// Database +await app.register(dbPlugin); + +// App-level plugins (depend on db) +await app.register(authPlugin); +await app.register(rbacPlugin); +await app.register(auditPlugin); +await app.register(rateLimitPlugin); + +// Routes +await app.register(adminAuthRoutes); + +// Health check +app.get('/health', async () => ({ ok: true, ts: new Date().toISOString() })); + +// Start +const host = process.env.HOST ?? '0.0.0.0'; +const port = parseInt(process.env.PORT ?? '3200', 10); + +try { + await app.listen({ host, port }); +} catch (err) { + app.log.error(err); + process.exit(1); +} diff --git a/api/src/plugins/audit.ts b/api/src/plugins/audit.ts new file mode 100644 index 0000000..315abbd --- /dev/null +++ b/api/src/plugins/audit.ts @@ -0,0 +1,98 @@ +/** + * Audit logging plugin + helper. + * + * Audit events are persisted synchronously (within the request transaction where + * possible). Failures are logged but do NOT abort the operation — audit log loss + * is preferable to data corruption. Critical operations must log AFTER the + * primary operation succeeds. + * + * Schema (created in migration 003_audit_logs): + * + * CREATE TABLE audit_logs ( + * id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + * action VARCHAR(128) NOT NULL, -- e.g. 'projects.delete' + * actor_id UUID, -- NULL for anonymous (failed login) + * actor_ip INET, + * target TEXT, -- email, project ID, token ID, etc. + * metadata JSONB NOT NULL DEFAULT '{}', + * created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + * ); + * CREATE INDEX ON audit_logs (actor_id, created_at DESC); + * CREATE INDEX ON audit_logs (action, created_at DESC); + * + * Critical actions that MUST emit audit events (see ROLE_PERMISSIONS for context): + * auth.login — successful login + * auth.login_failed — failed login attempt (includes reason) + * auth.logout — explicit logout + * users.create — new admin user created + * users.update — admin user role/email changed + * users.delete — admin user deleted + * projects.create — new project registered + * projects.update — project settings changed + * projects.delete — project deleted (destructive) + * ingest_tokens.create — new ingest token issued + * ingest_tokens.revoke — ingest token revoked + * sources.create — new active collector source added + * sources.delete — source removed + * errors.triage — error state changed (status transition + note) + * errors.delete — error record deleted + * settings.update — system settings changed + */ + +import fp from 'fastify-plugin'; +import type { FastifyInstance } from 'fastify'; +import type { Pool } from 'pg'; + +export interface AuditEvent { + action: string; + actor_id: string | null; + actor_ip: string; + target: string; + metadata: Record; +} + +/** + * Write an audit log entry. Accepts a pg Pool or PoolClient so it can + * participate in an ongoing transaction if needed. + */ +export async function auditLog( + db: Pool, + event: AuditEvent, +): Promise { + try { + await db.query( + `INSERT INTO audit_logs (action, actor_id, actor_ip, target, metadata) + VALUES ($1, $2, $3::inet, $4, $5::jsonb)`, + [ + event.action, + event.actor_id ?? null, + event.actor_ip, + event.target, + JSON.stringify(event.metadata), + ], + ); + } catch (err) { + // Audit failure must never break the main operation. + // Log the failure so ops can investigate. + console.error('[audit] Failed to write audit event', { + action: event.action, + error: String(err), + }); + } +} + +/** + * Fastify plugin that decorates the app with app.auditLog for convenience. + * Also sets up a request-level hook that captures IP for auditing. + */ +export default fp(async function auditPlugin(app: FastifyInstance) { + app.decorate('auditLog', function (event: AuditEvent): Promise { + return auditLog(app.db, event); + }); +}, { name: 'audit', dependencies: ['db'] }); + +declare module 'fastify' { + interface FastifyInstance { + auditLog: (event: AuditEvent) => Promise; + } +} diff --git a/api/src/plugins/auth.ts b/api/src/plugins/auth.ts new file mode 100644 index 0000000..a63b490 --- /dev/null +++ b/api/src/plugins/auth.ts @@ -0,0 +1,113 @@ +/** + * Fastify auth plugin — JWT with HTTP-only cookie. + * + * Design decisions: + * - Access token: 15 min TTL, stored in HTTP-only + Secure + SameSite=Strict cookie. + * - Refresh token: 7 day TTL, separate HTTP-only cookie, rotated on use. + * - Tokens are NOT stored in localStorage to prevent XSS theft. + * - Passwords are hashed with bcrypt (cost factor 12). + * + * Cookie names: + * __Host-access — access token + * __Host-refresh — refresh token (only sent to /admin/auth/refresh) + * + * The __Host- prefix enforces: Secure flag, no Domain attribute, Path=/. + */ + +import fp from 'fastify-plugin'; +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import type { AuthContext, JwtPayload, AdminRole } from '../types/auth.js'; + +const ACCESS_COOKIE = '__Host-access'; +const REFRESH_COOKIE = '__Host-refresh'; +const ACCESS_TTL_SEC = 15 * 60; // 15 minutes +const REFRESH_TTL_SEC = 7 * 24 * 60 * 60; // 7 days + +declare module 'fastify' { + interface FastifyInstance { + authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise; + } + interface FastifyRequest { + auth: AuthContext; + } +} + +export default fp(async function authPlugin(app: FastifyInstance) { + // @fastify/jwt must be registered before this plugin. + // @fastify/cookie must be registered before this plugin. + + /** Verify access token from cookie; attach auth context to request. */ + app.decorate('authenticate', async function ( + request: FastifyRequest, + reply: FastifyReply, + ): Promise { + const token = request.cookies[ACCESS_COOKIE]; + if (!token) { + reply.code(401).send({ error: 'Unauthorized', message: 'No session' }); + return; + } + + let payload: JwtPayload; + try { + payload = await request.jwtVerify({ onlyCookie: false }); + // jwtVerify throws on invalid/expired token + } catch (err) { + reply.code(401).send({ error: 'Unauthorized', message: 'Session expired' }); + return; + } + + request.auth = { + user_id: payload.sub, + email: payload.email, + role: payload.role, + }; + }); +}, { name: 'auth', dependencies: ['@fastify/jwt', '@fastify/cookie'] }); + +/** + * Helpers exported for use in route handlers. + */ + +export function setAccessCookie(reply: FastifyReply, token: string): void { + reply.setCookie(ACCESS_COOKIE, token, { + httpOnly: true, + secure: true, + sameSite: 'strict', + path: '/', + maxAge: ACCESS_TTL_SEC, + }); +} + +export function setRefreshCookie(reply: FastifyReply, token: string): void { + reply.setCookie(REFRESH_COOKIE, token, { + httpOnly: true, + secure: true, + sameSite: 'strict', + path: '/admin/auth/refresh', // only sent to refresh endpoint + maxAge: REFRESH_TTL_SEC, + }); +} + +export function clearAuthCookies(reply: FastifyReply): void { + reply.clearCookie(ACCESS_COOKIE, { path: '/' }); + reply.clearCookie(REFRESH_COOKIE, { path: '/admin/auth/refresh' }); +} + +/** Constant-time string comparison to prevent timing attacks. */ +export function safeEqual(a: string, b: string): boolean { + if (a.length !== b.length) return false; + const buf_a = Buffer.from(a); + const buf_b = Buffer.from(b); + return timingSafeEqual(buf_a, buf_b); +} + +/** Generate a cryptographically random opaque refresh token (hex). */ +export function generateRefreshToken(): string { + return randomBytes(48).toString('hex'); +} + +/** Hash a refresh token for storage (SHA-256; not password, so bcrypt overhead not needed). */ +export function hashRefreshToken(token: string): string { + return createHash('sha256').update(token).digest('hex'); +} diff --git a/api/src/plugins/db.ts b/api/src/plugins/db.ts new file mode 100644 index 0000000..f7c0606 --- /dev/null +++ b/api/src/plugins/db.ts @@ -0,0 +1,39 @@ +/** + * PostgreSQL connection pool plugin. + * Decorates app with app.db (pg.Pool). + * Env vars: DATABASE_URL (preferred) or DB_HOST/DB_PORT/DB_NAME/DB_USER/DB_PASSWORD. + */ +import fp from 'fastify-plugin'; +import { Pool } from 'pg'; +import type { FastifyInstance } from 'fastify'; + +declare module 'fastify' { + interface FastifyInstance { + db: Pool; + } +} + +export default fp(async function dbPlugin(app: FastifyInstance) { + const pool = new Pool({ + connectionString: process.env.DATABASE_URL, + max: parseInt(process.env.DB_POOL_MAX ?? '10', 10), + idleTimeoutMillis: 30_000, + connectionTimeoutMillis: 5_000, + }); + + // Verify connection on startup + const client = await pool.connect(); + try { + await client.query('SELECT 1'); + app.log.info('PostgreSQL connected'); + } finally { + client.release(); + } + + app.decorate('db', pool); + + app.addHook('onClose', async () => { + await pool.end(); + app.log.info('PostgreSQL pool closed'); + }); +}, { name: 'db' }); diff --git a/api/src/plugins/rate-limit.ts b/api/src/plugins/rate-limit.ts new file mode 100644 index 0000000..bbcb899 --- /dev/null +++ b/api/src/plugins/rate-limit.ts @@ -0,0 +1,115 @@ +/** + * Rate limiting & payload protection plugin. + * + * Strategy: + * - Ingest endpoints (/api/ingest/*): strict per-token limits (prevent abuse) + * - Admin auth endpoints (/admin/auth/login): per-IP brute-force protection + * - All other endpoints: global lenient limit + * + * Limits (phase 1 — tunable via env): + * RATE_INGEST_MAX requests per window (default: 1000) + * RATE_INGEST_WINDOW_MS window in ms (default: 60000 = 1 min) + * RATE_LOGIN_MAX login attempts per window (default: 10) + * RATE_LOGIN_WINDOW_MS window in ms (default: 300000 = 5 min) + * RATE_GLOBAL_MAX global limit per window (default: 500) + * RATE_GLOBAL_WINDOW_MS window in ms (default: 60000 = 1 min) + * + * Payload limits: + * INGEST_MAX_BODY_BYTES max ingest request body (default: 512 KB) + * ADMIN_MAX_BODY_BYTES max admin API request body (default: 64 KB) + * + * All limits use Redis (via ioredis) for distributed counting when multiple + * API instances run. Falls back to in-memory (no Redis configured) for dev. + */ + +import fp from 'fastify-plugin'; +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; + +const RATE_INGEST_MAX = parseInt(process.env.RATE_INGEST_MAX ?? '1000', 10); +const RATE_INGEST_WINDOW_MS = parseInt(process.env.RATE_INGEST_WINDOW_MS ?? '60000', 10); +const RATE_LOGIN_MAX = parseInt(process.env.RATE_LOGIN_MAX ?? '10', 10); +const RATE_LOGIN_WINDOW_MS = parseInt(process.env.RATE_LOGIN_WINDOW_MS ?? '300000', 10); +const RATE_GLOBAL_MAX = parseInt(process.env.RATE_GLOBAL_MAX ?? '500', 10); +const RATE_GLOBAL_WINDOW_MS = parseInt(process.env.RATE_GLOBAL_WINDOW_MS ?? '60000', 10); + +export const INGEST_MAX_BODY_BYTES = parseInt(process.env.INGEST_MAX_BODY_BYTES ?? String(512 * 1024), 10); +export const ADMIN_MAX_BODY_BYTES = parseInt(process.env.ADMIN_MAX_BODY_BYTES ?? String(64 * 1024), 10); + +/** Key generator for ingest rate limiting: prefer token ID, fall back to IP. */ +function ingest_key(request: FastifyRequest): string { + // Ingest routes set request.ingest_token_id after token validation. + const token_id = (request as any).ingest_token_id as string | undefined; + return token_id ? `ingest:token:${token_id}` : `ingest:ip:${request.ip}`; +} + +export default fp(async function rateLimitPlugin(app: FastifyInstance) { + // @fastify/rate-limit must already be registered. + // We register route-specific limits via addHook or per-route config. + + /** + * Per-route rate limit configs — consumed by @fastify/rate-limit's + * route-level config option `{ config: { rateLimit: { ... } } }`. + */ + app.decorate('rateLimits', { + ingest: { + max: RATE_INGEST_MAX, + timeWindow: RATE_INGEST_WINDOW_MS, + keyGenerator: ingest_key, + errorResponseBuilder: (_request: FastifyRequest, context: any) => ({ + error: 'TooManyRequests', + message: 'Ingest rate limit exceeded. Slow down.', + retryAfter: Math.ceil(context.ttl / 1000), + }), + }, + login: { + max: RATE_LOGIN_MAX, + timeWindow: RATE_LOGIN_WINDOW_MS, + keyGenerator: (request: FastifyRequest) => `login:ip:${request.ip}`, + errorResponseBuilder: (_request: FastifyRequest, context: any) => ({ + error: 'TooManyRequests', + message: 'Too many login attempts. Try again later.', + retryAfter: Math.ceil(context.ttl / 1000), + }), + }, + global: { + max: RATE_GLOBAL_MAX, + timeWindow: RATE_GLOBAL_WINDOW_MS, + }, + }); + + /** + * Body size enforcement hook. + * Fastify's built-in `bodyLimit` is set per-server globally. + * This hook provides per-route enforcement as a safety net. + */ + app.addHook('preValidation', async (request: FastifyRequest, reply: FastifyReply) => { + const content_length = request.headers['content-length']; + if (!content_length) return; // no body or chunked + + const body_size = parseInt(content_length, 10); + if (Number.isNaN(body_size)) return; + + const url = request.url; + const is_ingest = url.startsWith('/api/ingest'); + + const max_bytes = is_ingest ? INGEST_MAX_BODY_BYTES : ADMIN_MAX_BODY_BYTES; + + if (body_size > max_bytes) { + reply.code(413).send({ + error: 'PayloadTooLarge', + message: `Request body exceeds ${max_bytes} bytes`, + maxBytes: max_bytes, + }); + } + }); +}, { name: 'rate-limit-config', dependencies: ['@fastify/rate-limit'] }); + +declare module 'fastify' { + interface FastifyInstance { + rateLimits: { + ingest: Record; + login: Record; + global: Record; + }; + } +} diff --git a/api/src/plugins/rbac.ts b/api/src/plugins/rbac.ts new file mode 100644 index 0000000..c4883c2 --- /dev/null +++ b/api/src/plugins/rbac.ts @@ -0,0 +1,84 @@ +/** + * RBAC (Role-Based Access Control) plugin for Fastify. + * + * Usage in route definitions: + * + * app.get('/admin/users', { + * preHandler: [app.authenticate, app.requirePermission('users:read')], + * }, handler); + * + * // Or require a minimum role directly: + * app.delete('/admin/projects/:id', { + * preHandler: [app.authenticate, app.requireRole('admin')], + * }, handler); + * + * Permission resolution is purely based on ROLE_PERMISSIONS table in types/auth.ts. + * No per-project ACL in phase 1 — all admins see all projects. + */ + +import fp from 'fastify-plugin'; +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; +import { can, type Permission, type AdminRole, ROLE_PERMISSIONS } from '../types/auth.js'; + +const ROLE_HIERARCHY: AdminRole[] = ['viewer', 'admin', 'superadmin']; + +declare module 'fastify' { + interface FastifyInstance { + requirePermission: (permission: Permission) => ( + request: FastifyRequest, + reply: FastifyReply, + ) => Promise; + requireRole: (minRole: AdminRole) => ( + request: FastifyRequest, + reply: FastifyReply, + ) => Promise; + } +} + +export default fp(async function rbacPlugin(app: FastifyInstance) { + /** + * Returns a preHandler that enforces a specific permission. + * Must be used AFTER app.authenticate in the preHandler chain. + */ + app.decorate('requirePermission', function (permission: Permission) { + return async function checkPermission( + request: FastifyRequest, + reply: FastifyReply, + ): Promise { + if (!request.auth) { + reply.code(401).send({ error: 'Unauthorized' }); + return; + } + if (!can(request.auth.role, permission)) { + reply.code(403).send({ + error: 'Forbidden', + message: `Role '${request.auth.role}' cannot perform '${permission}'`, + }); + } + }; + }); + + /** + * Returns a preHandler that enforces a minimum role level. + * superadmin >= admin >= viewer. + */ + app.decorate('requireRole', function (minRole: AdminRole) { + const min_index = ROLE_HIERARCHY.indexOf(minRole); + return async function checkRole( + request: FastifyRequest, + reply: FastifyReply, + ): Promise { + if (!request.auth) { + reply.code(401).send({ error: 'Unauthorized' }); + return; + } + const user_index = ROLE_HIERARCHY.indexOf(request.auth.role); + if (user_index < min_index) { + reply.code(403).send({ + error: 'Forbidden', + message: `Role '${request.auth.role}' is below required '${minRole}'`, + }); + } + }; + }); +}, { name: 'rbac', dependencies: ['auth'] }); diff --git a/api/src/routes/admin/auth.ts b/api/src/routes/admin/auth.ts new file mode 100644 index 0000000..5e1944c --- /dev/null +++ b/api/src/routes/admin/auth.ts @@ -0,0 +1,241 @@ +/** + * Admin authentication routes. + * + * POST /admin/auth/login — password login → set JWT cookies + * POST /admin/auth/refresh — rotate refresh token → new access token + * POST /admin/auth/logout — clear cookies + invalidate refresh token + * GET /admin/auth/me — return current user info (requires auth) + */ + +import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; +import bcrypt from 'bcrypt'; +import { + setAccessCookie, + setRefreshCookie, + clearAuthCookies, + generateRefreshToken, + hashRefreshToken, +} from '../../plugins/auth.js'; +import { auditLog } from '../../plugins/audit.js'; +import type { JwtPayload } from '../../types/auth.js'; + +interface LoginBody { + email: string; + password: string; +} + +interface RefreshCookies { + '__Host-refresh'?: string; +} + +const BCRYPT_ROUNDS = 12; + +export default async function adminAuthRoutes(app: FastifyInstance): Promise { + const db = app.db; // postgres pool — registered separately + + /** + * POST /admin/auth/login + * Body: { email: string, password: string } + */ + app.post<{ Body: LoginBody }>( + '/admin/auth/login', + { + schema: { + body: { + type: 'object', + required: ['email', 'password'], + properties: { + email: { type: 'string', format: 'email', maxLength: 320 }, + password: { type: 'string', minLength: 1, maxLength: 128 }, + }, + additionalProperties: false, + }, + }, + }, + async (request: FastifyRequest<{ Body: LoginBody }>, reply: FastifyReply) => { + const { email, password } = request.body; + + // Lookup user — always run bcrypt even if not found (prevent timing oracle) + const result = await db.query<{ + id: string; + email: string; + role: string; + password_hash: string; + is_active: boolean; + }>( + `SELECT id, email, role, password_hash, is_active + FROM admin_users + WHERE email = $1 + LIMIT 1`, + [email.toLowerCase()], + ); + + const user = result.rows[0]; + + // Use a dummy hash when user not found to prevent timing attacks + const hash_to_check = user?.password_hash ?? '$2b$12$invalidhashfortimingprotection000000000000000'; + const password_ok = await bcrypt.compare(password, hash_to_check); + + if (!user || !password_ok || !user.is_active) { + await auditLog(db, { + action: 'auth.login_failed', + actor_id: null, + actor_ip: request.ip, + target: email, + metadata: { reason: !user ? 'user_not_found' : !password_ok ? 'bad_password' : 'inactive' }, + }); + return reply.code(401).send({ error: 'Invalid credentials' }); + } + + // Issue tokens + const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as any }; + const access_token = app.jwt.sign(payload, { expiresIn: '15m' }); + + const refresh_token = generateRefreshToken(); + const refresh_hash = hashRefreshToken(refresh_token); + + await db.query( + `INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at) + VALUES ($1, $2, NOW() + INTERVAL '7 days')`, + [user.id, refresh_hash], + ); + + await auditLog(db, { + action: 'auth.login', + actor_id: user.id, + actor_ip: request.ip, + target: user.email, + metadata: { role: user.role }, + }); + + setAccessCookie(reply, access_token); + setRefreshCookie(reply, refresh_token); + + return reply.code(200).send({ + user: { id: user.id, email: user.email, role: user.role }, + }); + }, + ); + + /** + * POST /admin/auth/refresh + * Rotates the refresh token and issues a new access token. + */ + app.post<{ Cookies: RefreshCookies }>( + '/admin/auth/refresh', + async (request: FastifyRequest<{ Cookies: RefreshCookies }>, reply: FastifyReply) => { + const refresh_token = request.cookies['__Host-refresh']; + if (!refresh_token) { + return reply.code(401).send({ error: 'No refresh token' }); + } + + const refresh_hash = hashRefreshToken(refresh_token); + + const result = await db.query<{ + id: string; + user_id: string; + expires_at: Date; + revoked_at: Date | null; + }>( + `SELECT id, user_id, expires_at, revoked_at + FROM admin_refresh_tokens + WHERE token_hash = $1 + LIMIT 1`, + [refresh_hash], + ); + + const token_row = result.rows[0]; + + if (!token_row || token_row.revoked_at || token_row.expires_at < new Date()) { + clearAuthCookies(reply); + return reply.code(401).send({ error: 'Refresh token invalid or expired' }); + } + + // Revoke old refresh token (rotation — detect replay attacks) + await db.query( + `UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE id = $1`, + [token_row.id], + ); + + // Fetch user + const user_result = await db.query<{ + id: string; + email: string; + role: string; + is_active: boolean; + }>( + `SELECT id, email, role, is_active FROM admin_users WHERE id = $1`, + [token_row.user_id], + ); + + const user = user_result.rows[0]; + if (!user || !user.is_active) { + clearAuthCookies(reply); + return reply.code(401).send({ error: 'User no longer active' }); + } + + // Issue new token pair + const payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as any }; + const new_access_token = app.jwt.sign(payload, { expiresIn: '15m' }); + const new_refresh_token = generateRefreshToken(); + const new_refresh_hash = hashRefreshToken(new_refresh_token); + + await db.query( + `INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at) + VALUES ($1, $2, NOW() + INTERVAL '7 days')`, + [user.id, new_refresh_hash], + ); + + setAccessCookie(reply, new_access_token); + setRefreshCookie(reply, new_refresh_token); + + return reply.code(200).send({ ok: true }); + }, + ); + + /** + * POST /admin/auth/logout + */ + app.post( + '/admin/auth/logout', + { preHandler: [app.authenticate] }, + async (request: FastifyRequest, reply: FastifyReply) => { + const refresh_token = request.cookies['__Host-refresh']; + if (refresh_token) { + const refresh_hash = hashRefreshToken(refresh_token); + await db.query( + `UPDATE admin_refresh_tokens SET revoked_at = NOW() WHERE token_hash = $1`, + [refresh_hash], + ); + } + + await auditLog(db, { + action: 'auth.logout', + actor_id: request.auth.user_id, + actor_ip: request.ip, + target: request.auth.email, + metadata: {}, + }); + + clearAuthCookies(reply); + return reply.code(200).send({ ok: true }); + }, + ); + + /** + * GET /admin/auth/me + */ + app.get( + '/admin/auth/me', + { preHandler: [app.authenticate] }, + async (request: FastifyRequest, reply: FastifyReply) => { + return reply.send({ + user: { + id: request.auth.user_id, + email: request.auth.email, + role: request.auth.role, + }, + }); + }, + ); +} diff --git a/api/src/types/auth.ts b/api/src/types/auth.ts new file mode 100644 index 0000000..82267f6 --- /dev/null +++ b/api/src/types/auth.ts @@ -0,0 +1,127 @@ +/** + * Auth & RBAC types for the BitReport Error Reporting admin. + * + * Roles are intentionally minimal (phase 1): + * superadmin — full access, can manage users and system settings + * admin — project management; cannot manage other admins + * viewer — read-only across all permitted projects + * + * For per-project scoping (phase 2), extend ProjectMembership. + */ + +export type AdminRole = 'superadmin' | 'admin' | 'viewer'; + +export interface AdminUser { + id: string; // UUID + email: string; + role: AdminRole; + is_active: boolean; + created_at: Date; + updated_at: Date; +} + +/** JWT payload stored in access token */ +export interface JwtPayload { + sub: string; // AdminUser.id + email: string; + role: AdminRole; + iat?: number; + exp?: number; +} + +/** Context attached to every authenticated request */ +export interface AuthContext { + user_id: string; + email: string; + role: AdminRole; +} + +/** + * Permission matrix — see docs/permission-matrix.md for full narrative. + * Maps resource:action pairs to the minimum role required. + */ +export type Permission = + | 'projects:read' + | 'projects:create' + | 'projects:update' + | 'projects:delete' + | 'errors:read' + | 'errors:triage' // change state: open→investigating→resolved/ignored + | 'errors:delete' + | 'ingest_tokens:read' + | 'ingest_tokens:create' + | 'ingest_tokens:revoke' + | 'sources:read' + | 'sources:create' + | 'sources:update' + | 'sources:delete' + | 'users:read' + | 'users:create' + | 'users:update' + | 'users:delete' + | 'settings:read' + | 'settings:update' + | 'audit_logs:read'; + +/** + * Role → granted permissions. + * Keep this as the single source of truth; docs/permission-matrix.md is + * auto-generated from this (see scripts/gen-permission-matrix.ts). + */ +export const ROLE_PERMISSIONS: Record> = { + superadmin: new Set([ + 'projects:read', + 'projects:create', + 'projects:update', + 'projects:delete', + 'errors:read', + 'errors:triage', + 'errors:delete', + 'ingest_tokens:read', + 'ingest_tokens:create', + 'ingest_tokens:revoke', + 'sources:read', + 'sources:create', + 'sources:update', + 'sources:delete', + 'users:read', + 'users:create', + 'users:update', + 'users:delete', + 'settings:read', + 'settings:update', + 'audit_logs:read', + ]), + + admin: new Set([ + 'projects:read', + 'projects:create', + 'projects:update', + 'errors:read', + 'errors:triage', + 'errors:delete', + 'ingest_tokens:read', + 'ingest_tokens:create', + 'ingest_tokens:revoke', + 'sources:read', + 'sources:create', + 'sources:update', + 'sources:delete', + 'settings:read', + 'audit_logs:read', + // Note: users:* requires superadmin; admin cannot manage other admins + ]), + + viewer: new Set([ + 'projects:read', + 'errors:read', + 'ingest_tokens:read', + 'sources:read', + 'settings:read', + 'audit_logs:read', + ]), +}; + +export function can(role: AdminRole, permission: Permission): boolean { + return ROLE_PERMISSIONS[role].has(permission); +} diff --git a/api/tsconfig.json b/api/tsconfig.json new file mode 100644 index 0000000..7bad8a4 --- /dev/null +++ b/api/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/db/migrations/001_admin_users.sql b/db/migrations/001_admin_users.sql new file mode 100644 index 0000000..1ef9488 --- /dev/null +++ b/db/migrations/001_admin_users.sql @@ -0,0 +1,35 @@ +-- Migration 001: admin_users table +-- Stores admin panel users with role-based access control. +-- Passwords are hashed with bcrypt (cost 12) — never store plaintext. +-- +-- Roles: superadmin | admin | viewer (see api/src/types/auth.ts) + +CREATE TABLE IF NOT EXISTS admin_users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + email VARCHAR(320) NOT NULL, + password_hash VARCHAR(60) NOT NULL, -- bcrypt output is always 60 chars + role VARCHAR(20) NOT NULL DEFAULT 'viewer' + CHECK (role IN ('superadmin', 'admin', 'viewer')), + is_active BOOLEAN NOT NULL DEFAULT TRUE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS admin_users_email_idx + ON admin_users (LOWER(email)); + +-- Auto-update updated_at on row change +CREATE OR REPLACE FUNCTION set_updated_at() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$; + +CREATE TRIGGER admin_users_updated_at + BEFORE UPDATE ON admin_users + FOR EACH ROW EXECUTE FUNCTION set_updated_at(); + +COMMENT ON TABLE admin_users IS 'Admin panel users (RBAC). Phase 1: global roles, no per-project scoping.'; +COMMENT ON COLUMN admin_users.role IS 'superadmin = full access; admin = project mgmt; viewer = read-only'; diff --git a/db/migrations/002_admin_refresh_tokens.sql b/db/migrations/002_admin_refresh_tokens.sql new file mode 100644 index 0000000..8fdd134 --- /dev/null +++ b/db/migrations/002_admin_refresh_tokens.sql @@ -0,0 +1,24 @@ +-- Migration 002: admin_refresh_tokens table +-- Stores hashed refresh tokens for admin session rotation. +-- Only the SHA-256 hash is stored; the plaintext token is sent to the client +-- in an HTTP-only cookie and never persisted. + +CREATE TABLE IF NOT EXISTS admin_refresh_tokens ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES admin_users(id) ON DELETE CASCADE, + token_hash VARCHAR(64) NOT NULL, -- SHA-256 hex (64 chars) + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE UNIQUE INDEX IF NOT EXISTS admin_refresh_tokens_hash_idx + ON admin_refresh_tokens (token_hash); + +CREATE INDEX IF NOT EXISTS admin_refresh_tokens_user_idx + ON admin_refresh_tokens (user_id, created_at DESC); + +-- Periodic cleanup: delete expired/revoked tokens older than 30 days. +-- Run via cron or pg_cron: DELETE FROM admin_refresh_tokens WHERE expires_at < NOW() - INTERVAL '30 days'; + +COMMENT ON TABLE admin_refresh_tokens IS 'Hashed refresh tokens for admin JWT rotation. Plaintext never stored.'; diff --git a/db/migrations/003_audit_logs.sql b/db/migrations/003_audit_logs.sql new file mode 100644 index 0000000..1a2e0ed --- /dev/null +++ b/db/migrations/003_audit_logs.sql @@ -0,0 +1,39 @@ +-- Migration 003: audit_logs table +-- Append-only audit trail for critical admin operations. +-- No UPDATE or DELETE on this table — immutability is the point. +-- Partitioning by month recommended when volume grows (phase 2). + +CREATE TABLE IF NOT EXISTS audit_logs ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + action VARCHAR(128) NOT NULL, -- e.g. 'auth.login', 'projects.delete' + actor_id UUID, -- NULL for unauthenticated events (login failures) + actor_ip INET, + target TEXT NOT NULL DEFAULT '', -- email, project ID, token ID, etc. + metadata JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- Query patterns: +-- 1. All actions by a user, recent first +CREATE INDEX IF NOT EXISTS audit_logs_actor_time_idx + ON audit_logs (actor_id, created_at DESC) + WHERE actor_id IS NOT NULL; + +-- 2. All events of a specific type, recent first +CREATE INDEX IF NOT EXISTS audit_logs_action_time_idx + ON audit_logs (action, created_at DESC); + +-- 3. Recent activity feed (dashboard) +CREATE INDEX IF NOT EXISTS audit_logs_time_idx + ON audit_logs (created_at DESC); + +-- Revoke DELETE and UPDATE on this table to enforce immutability. +-- (Run as superuser after migration) +-- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM PUBLIC; +-- REVOKE DELETE, UPDATE, TRUNCATE ON audit_logs FROM app_user; + +COMMENT ON TABLE audit_logs IS 'Append-only audit trail. Critical: no DELETEs or UPDATEs allowed.'; +COMMENT ON COLUMN audit_logs.action IS 'Dot-notation: domain.verb (e.g. auth.login, projects.delete)'; +COMMENT ON COLUMN audit_logs.actor_id IS 'NULL for pre-auth events (failed logins)'; +COMMENT ON COLUMN audit_logs.target IS 'Human-readable target: email, ID, or description'; +COMMENT ON COLUMN audit_logs.metadata IS 'Structured context: role, reason, old/new values (no secrets)'; diff --git a/db/migrations/004_seed_superadmin.sql b/db/migrations/004_seed_superadmin.sql new file mode 100644 index 0000000..a220754 --- /dev/null +++ b/db/migrations/004_seed_superadmin.sql @@ -0,0 +1,20 @@ +-- Migration 004: seed initial superadmin (dev/test only) +-- DO NOT run in production with hardcoded credentials. +-- In production: use the admin CLI (api/src/scripts/create-admin.ts) to create the first user. +-- +-- Default dev credentials: admin@bitreport.pt / changeme +-- Password hash below is bcrypt(cost=12) of 'changeme' — CHANGE IMMEDIATELY. + +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM admin_users WHERE role = 'superadmin') THEN + INSERT INTO admin_users (email, password_hash, role) + VALUES ( + 'admin@bitreport.pt', + '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewYpfQN4ZSIMM.Ey', -- 'changeme' + 'superadmin' + ); + RAISE NOTICE 'Seeded default superadmin. CHANGE THE PASSWORD IMMEDIATELY.'; + END IF; +END; +$$; diff --git a/docs/permission-matrix.md b/docs/permission-matrix.md new file mode 100644 index 0000000..758caec --- /dev/null +++ b/docs/permission-matrix.md @@ -0,0 +1,109 @@ +# Permission Matrix — BitReport Error Reporting Admin + +> **Source of truth:** `api/src/types/auth.ts` → `ROLE_PERMISSIONS`. +> This document is generated manually from that table. If they diverge, the code wins. + +## Phase 1 Roles + +| Role | Description | +|------|-------------| +| `superadmin` | Full access. Can manage other admin users and all system settings. | +| `admin` | Project and error management. Cannot manage other admin users. | +| `viewer` | Read-only across all resources. Cannot mutate anything. | + +## Permission Matrix + +| Permission | superadmin | admin | viewer | +|------------|:----------:|:-----:|:------:| +| **Projects** | | | | +| `projects:read` | ✅ | ✅ | ✅ | +| `projects:create` | ✅ | ✅ | ❌ | +| `projects:update` | ✅ | ✅ | ❌ | +| `projects:delete` | ✅ | ❌ | ❌ | +| **Errors** | | | | +| `errors:read` | ✅ | ✅ | ✅ | +| `errors:triage` | ✅ | ✅ | ❌ | +| `errors:delete` | ✅ | ✅ | ❌ | +| **Ingest Tokens** | | | | +| `ingest_tokens:read` | ✅ | ✅ | ✅ | +| `ingest_tokens:create` | ✅ | ✅ | ❌ | +| `ingest_tokens:revoke` | ✅ | ✅ | ❌ | +| **Sources (Active Collectors)** | | | | +| `sources:read` | ✅ | ✅ | ✅ | +| `sources:create` | ✅ | ✅ | ❌ | +| `sources:update` | ✅ | ✅ | ❌ | +| `sources:delete` | ✅ | ✅ | ❌ | +| **Admin Users** | | | | +| `users:read` | ✅ | ❌ | ❌ | +| `users:create` | ✅ | ❌ | ❌ | +| `users:update` | ✅ | ❌ | ❌ | +| `users:delete` | ✅ | ❌ | ❌ | +| **Settings** | | | | +| `settings:read` | ✅ | ✅ | ✅ | +| `settings:update` | ✅ | ❌ | ❌ | +| **Audit Logs** | | | | +| `audit_logs:read` | ✅ | ✅ | ✅ | + +## Design Notes + +### Why admins cannot manage users +Phase 1 keeps user management exclusive to `superadmin` to prevent privilege escalation: +an `admin` cannot create another `admin` or grant themselves `superadmin`. + +### Why viewers can read audit logs +Transparency: all authenticated staff should be able to see what actions were taken, +even if they cannot perform those actions. Audit logs contain no secrets. + +### Why `projects:delete` requires superadmin +Deleting a project is destructive and irreversible — it cascades to errors, tokens, +and sources. Only the highest privilege level can trigger this. + +### Future: per-project scoping (phase 2) +In phase 2, a `project_members` table will add per-project roles: +```sql +CREATE TABLE project_members ( + user_id UUID REFERENCES admin_users(id), + project_id UUID REFERENCES projects(id), + role VARCHAR(20) CHECK (role IN ('admin', 'viewer')), + PRIMARY KEY (user_id, project_id) +); +``` +`superadmin` will retain global access; `admin` and `viewer` will be scoped per project. + +## Audit Events + +The following operations MUST emit audit log entries (see `api/src/plugins/audit.ts`): + +| Action | Trigger | Key metadata | +|--------|---------|--------------| +| `auth.login` | Successful login | `role` | +| `auth.login_failed` | Failed login attempt | `reason` (user_not_found / bad_password / inactive) | +| `auth.logout` | Explicit logout | — | +| `users.create` | New admin created | `new_role`, `new_email` | +| `users.update` | Role/email changed | `old_role`, `new_role` | +| `users.delete` | Admin deleted | `deleted_email`, `deleted_role` | +| `projects.create` | Project registered | `project_id`, `name` | +| `projects.update` | Project settings changed | `fields_changed` | +| `projects.delete` | Project deleted | `project_id`, `name` | +| `ingest_tokens.create` | Token issued | `project_id`, `token_id` | +| `ingest_tokens.revoke` | Token revoked | `project_id`, `token_id` | +| `sources.create` | Collector source added | `project_id`, `source_type` | +| `sources.delete` | Source removed | `project_id`, `source_id` | +| `errors.triage` | Error state changed | `from_status`, `to_status`, `error_id` | +| `errors.delete` | Error deleted | `error_id`, `project_id` | +| `settings.update` | System settings changed | `keys_changed` | + +## Rate Limits + +| Endpoint | Limit | Window | Key | +|----------|-------|--------|-----| +| `POST /admin/auth/login` | 10 requests | 5 minutes | per IP | +| `POST /api/ingest/*` | 1000 requests | 1 minute | per token (fallback: IP) | +| All others | 500 requests | 1 minute | per IP | + +## Payload Limits + +| Endpoint group | Max body size | +|---------------|---------------| +| `/api/ingest/*` | 512 KB | +| Admin API (`/admin/*`) | 64 KB | diff --git a/web/.env.example b/web/.env.example new file mode 100644 index 0000000..a9e2370 --- /dev/null +++ b/web/.env.example @@ -0,0 +1,2 @@ +# Copy to .env.local +NEXT_PUBLIC_API_URL=http://localhost:3200 diff --git a/web/package.json b/web/package.json new file mode 100644 index 0000000..56a9352 --- /dev/null +++ b/web/package.json @@ -0,0 +1,24 @@ +{ + "name": "@errors-bitreport/web", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev -p 3201", + "build": "next build", + "start": "next start -p 3201", + "lint": "next lint", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "next": "^14.2.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "axios": "^1.7.2" + }, + "devDependencies": { + "@types/node": "^20.14.0", + "@types/react": "^18.3.3", + "@types/react-dom": "^18.3.0", + "typescript": "^5.4.5" + } +} diff --git a/web/src/app/(admin)/login/layout.tsx b/web/src/app/(admin)/login/layout.tsx new file mode 100644 index 0000000..659a110 --- /dev/null +++ b/web/src/app/(admin)/login/layout.tsx @@ -0,0 +1,29 @@ +/** + * Auth pages layout — loads Velzon assets and sets body class. + * Velzon CSS is served from /public/assets/ (CDN or local copy). + */ +import type { Metadata } from 'next'; + +export const metadata: Metadata = { + title: 'Sign In — BitReport Error Reporting', +}; + +export default function AuthLayout({ children }: { children: React.ReactNode }) { + return ( + + + + + + + + + + + {children} +