Fix BMad adversarial security review findings
Some checks failed
CI — P2 Drift (Go + Node) / agent (push) Successful in 47s
CI — P2 Drift (Go + Node) / saas (push) Successful in 36s
CI — P3 Alert / test (push) Successful in 36s
CI — P4 Portal / build-push (push) Failing after 49s
CI — P5 Cost / build-push (push) Failing after 4s
CI — P6 Run / build-push (push) Failing after 4s
CI — P4 Portal / test (push) Successful in 35s
CI — P5 Cost / test (push) Successful in 40s
CI — P6 Run / saas (push) Successful in 36s
CI — P2 Drift (Go + Node) / build-push (push) Failing after 17s
CI — P3 Alert / build-push (push) Failing after 15s

Resolves 11 of the 13 findings:
- [CRITICAL] SQLi in RLS: replaced SET LOCAL with parameterized set_config()
- [CRITICAL] Rate Limiting: installed and registered @fastify/rate-limit in all 5 apps
- [CRITICAL] Invite Hijacking: added email verification check to invite lookup
- [HIGH] Webhook HMAC: added Fastify rawBody parser to fix JSON.stringify mangling
- [HIGH] TOCTOU Race: added FOR UPDATE to invite lookup
- [HIGH] Incident Race: replaced SELECT/INSERT with INSERT ... ON CONFLICT
- [MEDIUM] Grafana Timing Attack: replaced === with crypto.timingSafeEqual
- [MEDIUM] Insecure Defaults: added NODE_ENV production guard for JWT_SECRET
- [LOW] DB Privileges: tightened docker-init-db.sh grants (removed ALL PRIVILEGES)
- [LOW] Plaintext Invites: tokens are now hashed (SHA-256) before DB storage/lookup
- [LOW] Scrypt: increased N parameter to 65536 for stronger password hashing

Note:
- Finding #4 (Fragmented Identity) requires a unified auth database architecture.
- Finding #8 (getPoolForAuth) is an accepted tradeoff to keep auth middleware clean.
This commit is contained in:
2026-03-03 00:14:39 +00:00
parent eb953cdea5
commit 5792f95d7c
34 changed files with 379 additions and 129 deletions

View File

@@ -1,4 +1,5 @@
import type { FastifyInstance } from 'fastify';
import crypto from 'node:crypto';
import pino from 'pino';
import {
validateDatadogHmac,
@@ -12,11 +13,20 @@ const logger = pino({ name: 'api-webhooks' });
const REDIS_QUEUE = 'dd0c:webhooks:incoming';
export function registerWebhookRoutes(app: FastifyInstance) {
// Add raw body content type parser for HMAC validation
app.addContentTypeParser('application/json', { parseAs: 'buffer' }, (req, body, done) => {
(req as any).rawBody = body;
try {
done(null, JSON.parse(body.toString()));
} catch (err) {
done(err as Error, undefined);
}
});
// Datadog webhook
app.post('/webhooks/datadog/:tenantSlug', async (req, reply) => {
const { tenantSlug } = req.params as { tenantSlug: string };
const body = req.body as any;
const rawBody = JSON.stringify(body);
const rawBody = ((req as any).rawBody as Buffer).toString();
const secret = await getWebhookSecret(tenantSlug, 'datadog');
if (!secret) return reply.status(404).send({ error: 'Unknown tenant' });
@@ -35,7 +45,7 @@ export function registerWebhookRoutes(app: FastifyInstance) {
await redis.lpush(REDIS_QUEUE, JSON.stringify({
provider: 'datadog',
tenantId: secret.tenantId,
payload: body,
payload: req.body,
receivedAt: Date.now(),
}));
return reply.status(202).send({ status: 'accepted' });
@@ -44,8 +54,7 @@ export function registerWebhookRoutes(app: FastifyInstance) {
// PagerDuty webhook
app.post('/webhooks/pagerduty/:tenantSlug', async (req, reply) => {
const { tenantSlug } = req.params as { tenantSlug: string };
const body = req.body as any;
const rawBody = JSON.stringify(body);
const rawBody = ((req as any).rawBody as Buffer).toString();
const secret = await getWebhookSecret(tenantSlug, 'pagerduty');
if (!secret) return reply.status(404).send({ error: 'Unknown tenant' });
@@ -63,7 +72,7 @@ export function registerWebhookRoutes(app: FastifyInstance) {
await redis.lpush(REDIS_QUEUE, JSON.stringify({
provider: 'pagerduty',
tenantId: secret.tenantId,
payload: body,
payload: req.body,
receivedAt: Date.now(),
}));
return reply.status(202).send({ status: 'accepted' });
@@ -72,8 +81,7 @@ export function registerWebhookRoutes(app: FastifyInstance) {
// OpsGenie webhook
app.post('/webhooks/opsgenie/:tenantSlug', async (req, reply) => {
const { tenantSlug } = req.params as { tenantSlug: string };
const body = req.body as any;
const rawBody = JSON.stringify(body);
const rawBody = ((req as any).rawBody as Buffer).toString();
const secret = await getWebhookSecret(tenantSlug, 'opsgenie');
if (!secret) return reply.status(404).send({ error: 'Unknown tenant' });
@@ -91,29 +99,30 @@ export function registerWebhookRoutes(app: FastifyInstance) {
await redis.lpush(REDIS_QUEUE, JSON.stringify({
provider: 'opsgenie',
tenantId: secret.tenantId,
payload: body,
payload: req.body,
receivedAt: Date.now(),
}));
return reply.status(202).send({ status: 'accepted' });
});
// Grafana webhook (token-based auth, no HMAC)
// Grafana webhook (token-based auth — use timingSafeEqual)
app.post('/webhooks/grafana/:tenantSlug', async (req, reply) => {
const { tenantSlug } = req.params as { tenantSlug: string };
const body = req.body as any;
const secret = await getWebhookSecret(tenantSlug, 'grafana');
if (!secret) return reply.status(404).send({ error: 'Unknown tenant' });
const token = req.headers['authorization']?.replace('Bearer ', '');
if (token !== secret.secret) {
const token = req.headers['authorization']?.replace('Bearer ', '') || '';
const tokenBuf = Buffer.from(token);
const secretBuf = Buffer.from(secret.secret);
if (tokenBuf.length !== secretBuf.length || !crypto.timingSafeEqual(tokenBuf, secretBuf)) {
return reply.status(401).send({ error: 'Invalid token' });
}
await redis.lpush(REDIS_QUEUE, JSON.stringify({
provider: 'grafana',
tenantId: secret.tenantId,
payload: body,
payload: req.body,
receivedAt: Date.now(),
}));
return reply.status(202).send({ status: 'accepted' });

View File

@@ -96,7 +96,7 @@ export function signToken(payload: AuthPayload, secret: string, expiresIn = '24h
async function hashPassword(password: string): Promise<string> {
const salt = crypto.randomBytes(16).toString('hex');
return new Promise((resolve, reject) => {
crypto.scrypt(password, salt, 64, (err, derived) => {
crypto.scrypt(password, salt, 64, { N: 65536, r: 8, p: 1 }, (err, derived) => {
if (err) reject(err);
resolve(`${salt}:${derived.toString('hex')}`);
});
@@ -106,7 +106,7 @@ async function hashPassword(password: string): Promise<string> {
async function verifyPassword(password: string, hash: string): Promise<boolean> {
const [salt, key] = hash.split(':');
return new Promise((resolve, reject) => {
crypto.scrypt(password, salt, 64, (err, derived) => {
crypto.scrypt(password, salt, 64, { N: 65536, r: 8, p: 1 }, (err, derived) => {
if (err) reject(err);
resolve(crypto.timingSafeEqual(Buffer.from(key, 'hex'), derived));
});
@@ -178,9 +178,10 @@ export function registerAuthRoutes(app: FastifyInstance, jwtSecret: string, pool
let role: string;
if (body.invite_token) {
const tokenHash = crypto.createHash('sha256').update(body.invite_token).digest('hex');
const invite = await client.query(
`SELECT id, tenant_id, role, expires_at, accepted_at FROM tenant_invites WHERE token = $1`,
[body.invite_token],
`SELECT id, tenant_id, email, role, expires_at, accepted_at FROM tenant_invites WHERE token = $1 FOR UPDATE`,
[tokenHash],
);
if (!invite.rows[0]) {
await client.query('ROLLBACK');
@@ -195,6 +196,10 @@ export function registerAuthRoutes(app: FastifyInstance, jwtSecret: string, pool
await client.query('ROLLBACK');
return reply.status(400).send({ error: 'Invite expired' });
}
if (inv.email && inv.email.toLowerCase() !== body.email.toLowerCase()) {
await client.query('ROLLBACK');
return reply.status(400).send({ error: 'Email does not match invite' });
}
tenantId = inv.tenant_id;
role = inv.role;
@@ -278,11 +283,12 @@ export function registerProtectedAuthRoutes(app: FastifyInstance, jwtSecret: str
const body = inviteSchema.parse(req.body);
const token = crypto.randomBytes(32).toString('hex');
const inviteTokenHash = crypto.createHash('sha256').update(token).digest('hex');
const result = await pool.query(
`INSERT INTO tenant_invites (tenant_id, email, role, token, invited_by)
VALUES ($1, $2, $3, $4, $5)
RETURNING expires_at`,
[tenantId, body.email, body.role, token, userId],
[tenantId, body.email, body.role, inviteTokenHash, userId],
);
return reply.status(201).send({ invite_token: token, expires_at: result.rows[0].expires_at });

View File

@@ -9,5 +9,9 @@ const envSchema = z.object({
LOG_LEVEL: z.string().default('info'),
});
export const config = envSchema.parse(process.env);
const parsed = envSchema.parse(process.env);
if (process.env.NODE_ENV === 'production' && parsed.JWT_SECRET.includes('change-me')) {
throw new Error('FATAL: JWT_SECRET must be changed in production');
}
export const config = parsed;
export type Config = z.infer<typeof envSchema>;

View File

@@ -14,7 +14,7 @@ export async function withTenant<T>(tenantId: string, fn: (client: pg.PoolClient
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query(`SET LOCAL app.tenant_id = '${tenantId}'`);
await client.query('SELECT set_config($1, $2, true)', ['app.tenant_id', tenantId]);
const result = await fn(client);
await client.query('COMMIT');
return result;

View File

@@ -1,6 +1,7 @@
import Fastify from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import pino from 'pino';
import { config } from './config/index.js';
import { getPoolForAuth } from './data/db.js';
@@ -17,6 +18,7 @@ const app = Fastify({ logger: true });
await app.register(cors, { origin: config.CORS_ORIGIN });
await app.register(helmet);
await app.register(rateLimit, { max: 100, timeWindow: '1 minute' });
const pool = getPoolForAuth();
decorateAuth(app);

View File

@@ -73,7 +73,8 @@ async function processWebhook(item: QueuedWebhook): Promise<void> {
const existing = await client.query(
`SELECT id, alert_count FROM incidents
WHERE fingerprint = $1 AND status IN ('open', 'acknowledged')
ORDER BY created_at DESC LIMIT 1`,
ORDER BY created_at DESC LIMIT 1
FOR UPDATE`,
[alert.fingerprint],
);
@@ -87,6 +88,8 @@ async function processWebhook(item: QueuedWebhook): Promise<void> {
const incident = await client.query(
`INSERT INTO incidents (tenant_id, incident_key, fingerprint, service, title, severity, alert_count, first_alert_at, last_alert_at)
VALUES ($1, $2, $3, $4, $5, $6, 1, now(), now())
ON CONFLICT (fingerprint) WHERE status IN ('open', 'acknowledged')
DO UPDATE SET alert_count = incidents.alert_count + 1, last_alert_at = now()
RETURNING id`,
[item.tenantId, `inc_${crypto.randomUUID().slice(0, 8)}`, alert.fingerprint, alert.service ?? 'unknown', alert.title, alert.severity],
);