feat(errors): migrate error-reporting stack from PostgreSQL to MariaDB (BIT-255)

Replace Postgres with MariaDB 11 in docker-compose; convert all
database/error_reporting and db/migrations SQL to InnoDB-friendly syntax
(DATETIME(6), AUTO_INCREMENT, ON DUPLICATE KEY). Run admin portal DDL in the
same migrate one-shot as error_reporting.

Switch ingest-api, collector-worker, and api from pg to mysql2 (pools,
parameterized queries, transactions). Align ingest writes with
er_incident_occurrences and include project_id on idempotency inserts.

Add scripts/run-mysql-migrations.sh for host-side applies; update LXC
run-migrate/verify, deployment docs, and .env.example (mysql://, ER_MYSQL_*).

Verified: npm run build + npm test in ingest-api and collector-worker;
npm run build in api. Full docker compose not run here (no local daemon).

Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
1sonhadorandPaperclip committed 2026-03-22 19:29:11 +00:00
1 parent b0b733d5e1
commit 4604606033
44 files changed
+1547 -993

No files matched your search

+5 -37
View File
@@ -6,42 +6,12 @@
* 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
* Schema: db/migrations/003_audit_logs.sql (MariaDB).
*/
import fp from 'fastify-plugin';
import type { FastifyInstance } from 'fastify';
import type { Pool } from 'pg';
import type { Pool } from 'mysql2/promise';
export interface AuditEvent {
action: string;
@@ -52,7 +22,7 @@ export interface AuditEvent {
}
/**
* Write an audit log entry. Accepts a pg Pool or PoolClient so it can
* Write an audit log entry. Accepts a mysql2 Pool or PoolConnection so it can
* participate in an ongoing transaction if needed.
*/
export async function auditLog(
@@ -60,9 +30,9 @@ export async function auditLog(
event: AuditEvent,
): Promise<void> {
try {
await db.query(
await db.execute(
`INSERT INTO audit_logs (action, actor_id, actor_ip, target, metadata)
VALUES ($1, $2, $3::inet, $4, $5::jsonb)`,
VALUES (?, ?, ?, ?, ?)`,
[
event.action,
event.actor_id ?? null,
@@ -72,8 +42,6 @@ export async function auditLog(
],
);
} 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),
+16 -13
View File
@@ -1,10 +1,10 @@
/**
* 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.
* MariaDB / MySQL connection pool plugin.
* Decorates app with app.db (mysql2 Pool).
* Env: DATABASE_URL (mysql://user:pass@host:port/db) or discrete DB_* vars.
*/
import fp from 'fastify-plugin';
import { Pool } from 'pg';
import mysql, { type Pool } from 'mysql2/promise';
import type { FastifyInstance } from 'fastify';
declare module 'fastify' {
@@ -14,18 +14,21 @@ declare module 'fastify' {
}
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,
const _url = process.env.DATABASE_URL;
if (typeof _url !== 'string' || _url.trim() === '') {
throw new Error('DATABASE_URL is required');
}
const pool = mysql.createPool({
uri: _url.trim(),
connectionLimit: parseInt(process.env.DB_POOL_MAX ?? '10', 10),
waitForConnections: true,
enableKeepAlive: true,
});
// Verify connection on startup
const client = await pool.connect();
const client = await pool.getConnection();
try {
await client.query('SELECT 1');
app.log.info('PostgreSQL connected');
app.log.info('MariaDB connected');
} finally {
client.release();
}
@@ -34,6 +37,6 @@ export default fp(async function dbPlugin(app: FastifyInstance) {
app.addHook('onClose', async () => {
await pool.end();
app.log.info('PostgreSQL pool closed');
app.log.info('MariaDB pool closed');
});
}, { name: 'db' });
+47 -55
View File
@@ -8,6 +8,7 @@
*/
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import type { RowDataPacket } from 'mysql2';
import bcrypt from 'bcrypt';
import {
setAccessCookie,
@@ -24,14 +25,8 @@ interface LoginBody {
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
const db = app.db;
/**
* POST /admin/auth/login
@@ -55,28 +50,29 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
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;
}>(
const [rows] = await db.execute<RowDataPacket[]>(
`SELECT id, email, role, password_hash, is_active
FROM admin_users
WHERE email = $1
WHERE LOWER(email) = LOWER(?)
LIMIT 1`,
[email.toLowerCase()],
[email],
);
const user = result.rows[0];
const user = rows[0] as
| {
id: string;
email: string;
role: string;
password_hash: string;
is_active: number | boolean;
}
| undefined;
// 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) {
const _active = user ? Boolean(user.is_active) : false;
if (!user || !password_ok || !_active) {
await auditLog(db, {
action: 'auth.login_failed',
actor_id: null,
@@ -87,16 +83,15 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
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 payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as JwtPayload['role'] };
const access_token = app.jwt.sign(payload, { expiresIn: '15m' });
const refresh_token = generateRefreshToken();
const refresh_hash = hashRefreshToken(refresh_token);
await db.query(
await db.execute(
`INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, NOW() + INTERVAL '7 days')`,
VALUES (?, ?, DATE_ADD(NOW(6), INTERVAL 7 DAY))`,
[user.id, refresh_hash],
);
@@ -121,9 +116,9 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
* POST /admin/auth/refresh
* Rotates the refresh token and issues a new access token.
*/
app.post<{ Cookies: RefreshCookies }>(
app.post(
'/admin/auth/refresh',
async (request: FastifyRequest<{ Cookies: RefreshCookies }>, reply: FastifyReply) => {
async (request: FastifyRequest, reply: FastifyReply) => {
const refresh_token = request.cookies['__Host-refresh'];
if (!refresh_token) {
return reply.code(401).send({ error: 'No refresh token' });
@@ -131,58 +126,55 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
const refresh_hash = hashRefreshToken(refresh_token);
const result = await db.query<{
id: string;
user_id: string;
expires_at: Date;
revoked_at: Date | null;
}>(
const [rows] = await db.execute<RowDataPacket[]>(
`SELECT id, user_id, expires_at, revoked_at
FROM admin_refresh_tokens
WHERE token_hash = $1
WHERE token_hash = ?
LIMIT 1`,
[refresh_hash],
);
const token_row = result.rows[0];
const token_row = rows[0] as
| {
id: string;
user_id: string;
expires_at: Date;
revoked_at: Date | null;
}
| undefined;
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`,
await db.execute(
`UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE id = ?`,
[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`,
const [userRows] = await db.execute<RowDataPacket[]>(
`SELECT id, email, role, is_active FROM admin_users WHERE id = ?`,
[token_row.user_id],
);
const user = user_result.rows[0];
if (!user || !user.is_active) {
const user = userRows[0] as
| { id: string; email: string; role: string; is_active: number | boolean }
| undefined;
const _uActive = user ? Boolean(user.is_active) : false;
if (!user || !_uActive) {
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 payload: JwtPayload = { sub: user.id, email: user.email, role: user.role as JwtPayload['role'] };
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(
await db.execute(
`INSERT INTO admin_refresh_tokens (user_id, token_hash, expires_at)
VALUES ($1, $2, NOW() + INTERVAL '7 days')`,
VALUES (?, ?, DATE_ADD(NOW(6), INTERVAL 7 DAY))`,
[user.id, new_refresh_hash],
);
@@ -202,10 +194,10 @@ export default async function adminAuthRoutes(app: FastifyInstance): Promise<voi
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],
const rh = hashRefreshToken(refresh_token);
await db.execute(
`UPDATE admin_refresh_tokens SET revoked_at = NOW(6) WHERE token_hash = ?`,
[rh],
);
}