fix(security): self-healing secrets + auth/SSRF/header hardening (v0.16.10-beta)
Follow-up to the /terminal authorization fix: a full-codebase security review surfaced several more issues, fixed here. All changes are designed to roll out with no interruption to existing deployments — no forced migration, no manual re-key, no boot failure. Self-healing secret management (utils/secrets.ts): - JWT_SECRET / ENCRYPTION_KEY auto-generate to strong values on first boot and persist to the app_data volume (0600, outside the DB) when not set to a strong value in the environment. Replaces the prior behavior of running on the public repo defaults. - decrypt() tries the current key plus every legacy/default key, so existing device credentials keep decrypting after a key change; a startup sweep re-encrypts stale rows forward (db/reencryptCredentials.ts). - verifyToken() accepts the current signing secret plus prior *strong* secrets (never the public defaults), so rotation doesn't invalidate live sessions; sessions signed with a default secret require one re-login. - Dockerfile pre-creates /app/data as the app user so the non-root process can persist to a fresh named volume; app_data volume added to both compose files; compose secret defaults changed to empty (auto-gen). Authorization / input: - Default Socket.IO namespace now requires a valid JWT (was unauthenticated and broadcasting fleet-activity events); frontend sends the token and drops the shared socket on logout. - Webhook delivery blocks SSRF to loopback/private/link-local/CGNAT ranges and pins the request to the validated IP (WebhookService.ts). - Rate limit added to /auth/totp/verify; global mutation backstop on /api. - Password policy (>=10 chars, letter+digit) enforced on set/change/create. - system.ts used verifyToken as middleware (always 500); now requireAuth. Hardening: - CSP + HSTS/nosniff/frame-deny headers in nginx, scoped to allow the OpenStreetMap tile/geocoding hosts the maps use. Docs/tests: - README secret section rewritten for the self-healing model. - New unit tests for secret resolution, persistence, rotation, and legacy-key decryption (97 tests pass). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
27560fa1d6
commit
9e962939ea
@@ -25,6 +25,9 @@ import {
|
||||
} from './services/DeviceBulkAddWorker';
|
||||
import { netflowCollector } from './services/netflow/NetflowCollector';
|
||||
import { verifyToken, type AuthPayload } from './middleware/auth';
|
||||
import { rateLimitRedis } from './middleware/rateLimitRedis';
|
||||
import { initSecrets } from './utils/secrets';
|
||||
import { reencryptStaleCredentials } from './db/reencryptCredentials';
|
||||
import { decrypt } from './utils/crypto';
|
||||
import { corsMiddlewareOptions, socketIoCorsOptions } from './utils/corsOrigins';
|
||||
|
||||
@@ -59,6 +62,27 @@ import credentialPresetsRoutes from './routes/credentialPresets';
|
||||
import systemRoutes from './routes/system';
|
||||
import { auditMiddleware } from './middleware/auditMiddleware';
|
||||
|
||||
// ─── Secret hygiene ───────────────────────────────────────────────────────────
|
||||
// Self-healing: if JWT_SECRET / ENCRYPTION_KEY aren't set to strong values, we
|
||||
// auto-generate strong ones and persist them, so a deployment is never left on
|
||||
// the public repo defaults and never breaks on upgrade. See utils/secrets.ts.
|
||||
function provisionSecrets(): void {
|
||||
const info = initSecrets();
|
||||
const sourceLine = `secrets: jwt=${info.jwtSource}, encryption=${info.encSource}`;
|
||||
if (info.jwtSource === 'generated' || info.encSource === 'generated') {
|
||||
console.log(`[secrets] auto-generated strong secret(s) (${sourceLine})`);
|
||||
} else {
|
||||
console.log(`[secrets] ${sourceLine}`);
|
||||
}
|
||||
if (info.ephemeral) {
|
||||
console.error(
|
||||
'[secrets] WARNING: generated secrets could not be persisted (SECRETS_DIR not writable). ' +
|
||||
'They will change on restart — users will be logged out and credentials written now may not ' +
|
||||
'decrypt later. Mount a writable volume at SECRETS_DIR (default /app/data) or set JWT_SECRET/ENCRYPTION_KEY.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const app = express();
|
||||
// nginx sits exactly one hop in front; trust its X-Forwarded-For so req.ip is the real client IP
|
||||
app.set('trust proxy', 1);
|
||||
@@ -71,6 +95,19 @@ const io = new SocketServer(httpServer, {
|
||||
path: '/socket.io',
|
||||
});
|
||||
|
||||
// The default namespace broadcasts fleet-activity events (device/client/event
|
||||
// updates); require a valid JWT so unauthenticated clients can't subscribe.
|
||||
io.use((socket, next) => {
|
||||
const token = (socket.handshake.auth as { token?: string })?.token;
|
||||
if (!token) return next(new Error('No token'));
|
||||
try {
|
||||
socket.data.user = verifyToken(token);
|
||||
next();
|
||||
} catch {
|
||||
next(new Error('Invalid or expired token'));
|
||||
}
|
||||
});
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
console.log(`Socket connected: ${socket.id}`);
|
||||
socket.on('disconnect', () => {
|
||||
@@ -249,6 +286,10 @@ if (process.env.NODE_ENV !== 'test') {
|
||||
}
|
||||
app.use(auditMiddleware);
|
||||
|
||||
// Global backstop rate limit on mutating API requests (per user, falling back to
|
||||
// per IP before auth runs). Endpoints with stricter needs add their own limiter.
|
||||
app.use('/api', rateLimitRedis({ windowSec: 60, max: 120, keyPrefix: 'api-global' }));
|
||||
|
||||
// ─── Health Check ─────────────────────────────────────────────────────────────
|
||||
app.get('/api/health', (_req, res) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
@@ -288,6 +329,8 @@ app.use(errorHandler);
|
||||
|
||||
// ─── Startup ─────────────────────────────────────────────────────────────────
|
||||
async function start(): Promise<void> {
|
||||
provisionSecrets();
|
||||
|
||||
// Wait for DB to be ready
|
||||
for (let i = 0; i < 10; i++) {
|
||||
try {
|
||||
@@ -303,6 +346,12 @@ async function start(): Promise<void> {
|
||||
// Run migrations
|
||||
await runMigrations();
|
||||
|
||||
// Migrate any credentials still encrypted under a legacy/default key forward
|
||||
// to the current key (runs in the background; safe to skip on failure).
|
||||
reencryptStaleCredentials().catch((e) =>
|
||||
console.warn('[secrets] credential re-encryption sweep skipped:', (e as Error).message)
|
||||
);
|
||||
|
||||
// Reset vendor entries that were previously set to '' due to API rate-limiting,
|
||||
// so they get re-resolved by the new local OUI database.
|
||||
await query(`UPDATE clients SET vendor = NULL WHERE vendor = ''`).catch(() => {});
|
||||
|
||||
Reference in New Issue
Block a user