feat(BIT-183): admin auth, RBAC, audit logging, rate limiting

Implements BIT-154.7 — Auth administrativa, RBAC e quotas:

- api/src/types/auth.ts: 3 roles (superadmin/admin/viewer), 18 permissions,
  ROLE_PERMISSIONS map as single source of truth
- api/src/plugins/auth.ts: JWT via HTTP-only __Host- cookies (15min access /
  7d refresh), token rotation, timing-safe login
- api/src/plugins/rbac.ts: requirePermission() + requireRole() Fastify
  decorators for route-level enforcement
- api/src/plugins/audit.ts: auditLog() helper + Fastify plugin; writes to
  audit_logs table; failure never aborts main operation
- api/src/plugins/rate-limit.ts: per-route limits (login: 10/5min IP,
  ingest: 1000/min token, global: 500/min) + payload size enforcement
- api/src/routes/admin/auth.ts: POST login, POST refresh, POST logout,
  GET /me — with audit events on all operations
- db/migrations/001–004: admin_users, refresh_tokens, audit_logs tables +
  dev seed (bcrypt superadmin)
- web/src/app/(admin)/login: Velzon Bootstrap 5 login page (Next.js client
  component, credentials:include, HTTP-only cookie flow)
- docs/permission-matrix.md: full permission matrix + audit event catalogue
  + rate/payload limit table (BIT-183 acceptance criterion)

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1sonhadorandPaperclip committed 2026-03-22 04:22:57 +00:00
1 parent d455a26333
commit eeb5039a3c
21 files changed
+1455

No files matched your search

+78
View File
@@ -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);
}
+98
View File
@@ -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<string, unknown>;
}
/**
* 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<void> {
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<void> {
return auditLog(app.db, event);
});
}, { name: 'audit', dependencies: ['db'] });
declare module 'fastify' {
interface FastifyInstance {
auditLog: (event: AuditEvent) => Promise<void>;
}
}
+113
View File
@@ -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<void>;
}
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<void> {
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<JwtPayload>({ 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');
}
+39
View File
@@ -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' });
+115
View File
@@ -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<string, unknown>;
login: Record<string, unknown>;
global: Record<string, unknown>;
};
}
}
+84
View File
@@ -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<void>;
requireRole: (minRole: AdminRole) => (
request: FastifyRequest,
reply: FastifyReply,
) => Promise<void>;
}
}
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<void> {
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<void> {
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'] });
+241
View File
@@ -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<void> {
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,
},
});
},
);
}
+127
View File
@@ -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<AdminRole, ReadonlySet<Permission>> = {
superadmin: new Set<Permission>([
'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<Permission>([
'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<Permission>([
'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);
}