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:
1 parent
d455a26333
commit
eeb5039a3c
21 files changed
+1455
No files matched your search
@@ -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>;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
@@ -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' });
|
||||
@@ -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>;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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'] });
|
||||
Reference in new issue
Block a user