feat(auth): enhance security and audit logging
- Integrate webhook alerts for admin login lockouts. - Implement detailed audit logging for login, logout, and setup actions. - Improve client revocation event tracking. - Standardize error handling in profile updates. - Enforce 'operator' role for event API access.
This commit is contained in:
1 parent
5c977d6977
commit
8132087085
52 files changed
+4434
-407
No files matched your search
@@ -10,6 +10,7 @@ import {
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
@@ -70,6 +71,17 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
SettingsManager.triggerWebhookAlert({
|
||||
event: "ADMIN_LOGIN_LOCKOUT",
|
||||
severity: "warning",
|
||||
title: "Admin Login Lockout Triggered",
|
||||
message: `Admin sign-in throttled for ${email} from IP ${clientIp} (${throttleDecision.retryAfterSeconds}s lockout).`,
|
||||
details: {
|
||||
email,
|
||||
clientIp,
|
||||
retryAfterSeconds: throttleDecision.retryAfterSeconds,
|
||||
},
|
||||
});
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { getSessionCookieOptions } from "@/core/auth/adminSession";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import {
|
||||
revokeAdminSessions,
|
||||
verifyRequestAdminSession,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
@@ -13,7 +15,20 @@ export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const check = await verifyRequestAdminSession(token);
|
||||
if (check.valid) {
|
||||
await revokeAdminSessions();
|
||||
await revokeAdminSessions({
|
||||
memberId: check.session.memberId,
|
||||
email: check.session.email,
|
||||
});
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: check.session.email,
|
||||
actorRole: check.session.role || "owner",
|
||||
action: "ADMIN_LOGOUT",
|
||||
target: check.session.email,
|
||||
ipAddress: extractClientIp(request),
|
||||
metadata: {
|
||||
memberId: check.session.memberId || "owner-1",
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// Still clear client cookie even if server revocation encounters transient DB error
|
||||
|
||||
@@ -125,9 +125,13 @@ export async function PUT(request: NextRequest) {
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const isConflict = result.code === "ADMIN_EMAIL_CONFLICT";
|
||||
return NextResponse.json(
|
||||
{ error: result.error, code: "INVALID_PASSWORD" },
|
||||
{ status: 401 },
|
||||
{
|
||||
error: result.error,
|
||||
code: result.code || "INVALID_PASSWORD",
|
||||
},
|
||||
{ status: isConflict ? 409 : 401 },
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import {
|
||||
AdminDatabaseRequiredError,
|
||||
clearAdminLoginAttempts,
|
||||
@@ -128,6 +129,17 @@ export async function POST(request: NextRequest) {
|
||||
clientIp,
|
||||
).catch(() => undefined);
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: email,
|
||||
actorRole: "owner",
|
||||
action: "ADMIN_SETUP",
|
||||
target: email,
|
||||
ipAddress: clientIp,
|
||||
metadata: {
|
||||
memberId: "owner-1",
|
||||
},
|
||||
});
|
||||
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
|
||||
@@ -271,7 +271,7 @@ export async function PATCH(
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || "owner",
|
||||
action: "CLIENT_UPDATED",
|
||||
action: updates.status === "revoked" ? "CLIENT_REVOKED" : "CLIENT_UPDATED",
|
||||
target: updated.clientId,
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: updates,
|
||||
|
||||
+3
-14
@@ -1,5 +1,4 @@
|
||||
import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { verifyRequestAdminSession } from '@/core/auth/adminUsers';
|
||||
import { AuthService } from '@/core/auth/jwt';
|
||||
import { DataBufferEngine, REDIS_BUFFER_KEY } from '@/core/data/buffer';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
@@ -22,7 +21,6 @@ import crypto from 'node:crypto';
|
||||
import { extractClientIp, requireAdminApiSession } from '@/lib/adminAuth';
|
||||
import type { BufferedBucket, BufferedSummary } from '@/lib/vconUiHelpers';
|
||||
|
||||
const SESSION_COOKIE = 'datastack_admin_session';
|
||||
const SINGLE_EVENT_ENVELOPE_KEYS = new Set(['eventId', 'timestamp', 'data', 'clientId']);
|
||||
const MAX_SINGLE_CLIENT_SCAN_FILES = 10;
|
||||
const MAX_ALL_CLIENTS_PER_CLIENT_FILES = 2;
|
||||
@@ -376,9 +374,8 @@ export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const settings = await SettingsManager.getSettingsAsync();
|
||||
|
||||
// Verify either Client Bearer JWT or Admin Session Cookie
|
||||
// Verify either Client Bearer JWT or Admin Session Cookie (minRole: operator)
|
||||
const authHeader = req.headers.get('authorization');
|
||||
const sessionCookie = req.cookies.get(SESSION_COOKIE)?.value;
|
||||
|
||||
let tokenClientId: string | null = null;
|
||||
let tokenRateLimit: number | undefined;
|
||||
@@ -396,17 +393,9 @@ export async function POST(req: NextRequest) {
|
||||
tokenClientId = verified.payload.clientId;
|
||||
tokenRateLimit = verified.payload.rateLimit;
|
||||
} else {
|
||||
const auth = await verifyRequestAdminSession(sessionCookie);
|
||||
const auth = await requireAdminApiSession(req, { minRole: 'operator' });
|
||||
if (!auth.valid) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
auth.reason === 'UNAUTHORIZED'
|
||||
? 'Authentication required. Provide a valid Client Bearer JWT or Admin Session.'
|
||||
: 'Admin authentication is temporarily unavailable.',
|
||||
},
|
||||
{ status: auth.reason === 'UNAUTHORIZED' ? 401 : 503 },
|
||||
);
|
||||
return auth.response;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { AuthService } from '@/core/auth/jwt';
|
||||
import { DataBufferEngine } from '@/core/data/buffer';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { isClientIpAllowed, isClientTokenExpired } from '@/core/Security/ipAllowlist';
|
||||
import { extractClientIp } from '@/lib/adminAuth';
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
@@ -67,6 +69,27 @@ export async function GET(req: NextRequest) {
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
if (isClientTokenExpired(registeredClient.expiresAt)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'error',
|
||||
code: 'CLIENT_TOKEN_EXPIRED',
|
||||
error: `CLIENT_TOKEN_EXPIRED: Client '${clientId}' token has expired (${registeredClient.expiresAt}).`,
|
||||
},
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
const clientIp = extractClientIp(req);
|
||||
if (!isClientIpAllowed(clientIp, registeredClient.allowedIps)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
status: 'error',
|
||||
code: 'CLIENT_IP_FORBIDDEN',
|
||||
error: `CLIENT_IP_FORBIDDEN: IP '${clientIp}' is not in the allowlist for client '${clientId}'.`,
|
||||
},
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const bufferStats = await DataBufferEngine.getBufferStatsAsync();
|
||||
|
||||
@@ -2,6 +2,7 @@ import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { verifyRequestAdminSession } from "@/core/auth/adminUsers";
|
||||
import { DataBufferEngine } from "@/core/data/buffer";
|
||||
import { SDKManager } from "@/core/sdk/sdkManager";
|
||||
import { isClientTokenExpired } from "@/core/Security/ipAllowlist";
|
||||
import { getInternalIngestionHeaders } from "@/core/Security/security";
|
||||
import { CSVStorageManager } from "@/core/Storage/csvStorage";
|
||||
import { ADMIN_SESSION_COOKIE } from "@/lib/adminAuth";
|
||||
@@ -116,13 +117,17 @@ export async function GET(req: NextRequest) {
|
||||
? bufferStats.redisBufferSize
|
||||
: remoteBufferSize);
|
||||
|
||||
const nowMs = Date.now();
|
||||
let activeClientsCount = 0;
|
||||
let expiredClientsCount = 0;
|
||||
let revokedClientsCount = 0;
|
||||
let totalEventsCounter = 0;
|
||||
for (const c of clients) {
|
||||
totalEventsCounter += Math.max(0, Number(c.totalEvents) || 0);
|
||||
if (c.status === "revoked") {
|
||||
revokedClientsCount += 1;
|
||||
} else if (isClientTokenExpired(c.expiresAt, nowMs)) {
|
||||
expiredClientsCount += 1;
|
||||
} else {
|
||||
activeClientsCount += 1;
|
||||
}
|
||||
@@ -165,6 +170,7 @@ export async function GET(req: NextRequest) {
|
||||
"# HELP datastack_clients_total Number of registered SDK clients partitioned by status.",
|
||||
"# TYPE datastack_clients_total gauge",
|
||||
`datastack_clients_total{status="active"} ${activeClientsCount}`,
|
||||
`datastack_clients_total{status="expired"} ${expiredClientsCount}`,
|
||||
`datastack_clients_total{status="revoked"} ${revokedClientsCount}`,
|
||||
"# HELP datastack_client_events_total Cumulative ingested events per registered client.",
|
||||
"# TYPE datastack_client_events_total counter",
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { SettingsManager } from "@/core/adminSettings/settingsManager";
|
||||
import { dispatchWebhookAlertAsync } from "@/core/alerts/webhookNotifier";
|
||||
import { recordAdminAuditLogAsync } from "@/core/auth/auditLog";
|
||||
import { SecretVaultError } from "@/core/Security/secretVault";
|
||||
import {
|
||||
decryptSecret,
|
||||
SecretVaultError,
|
||||
} from "@/core/Security/secretVault";
|
||||
import { extractClientIp, requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -28,17 +31,20 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
try {
|
||||
const savedConfig = await SettingsManager.getDecryptedWebhookConfigAsync();
|
||||
const saved = await SettingsManager.getSettingsAsync();
|
||||
const webhookUrl =
|
||||
typeof body.webhookUrl === "string"
|
||||
? body.webhookUrl.trim()
|
||||
: savedConfig.webhookUrl.trim();
|
||||
: saved.webhookUrl.trim();
|
||||
const clearWebhookSecret = body.clearWebhookSecret === true;
|
||||
const webhookSecret = clearWebhookSecret
|
||||
? ""
|
||||
: typeof body.webhookSecret === "string" && body.webhookSecret.trim()
|
||||
const draftSecret =
|
||||
typeof body.webhookSecret === "string" && body.webhookSecret.trim()
|
||||
? body.webhookSecret.trim()
|
||||
: savedConfig.webhookSecret;
|
||||
: "";
|
||||
let webhookSecret = draftSecret;
|
||||
if (!webhookSecret && !clearWebhookSecret && saved.webhookSecretEnc) {
|
||||
webhookSecret = decryptSecret(saved.webhookSecretEnc);
|
||||
}
|
||||
|
||||
if (!webhookUrl) {
|
||||
return NextResponse.json(
|
||||
@@ -81,7 +87,7 @@ export async function POST(req: NextRequest) {
|
||||
enabled: true,
|
||||
webhookUrl,
|
||||
webhookSecret,
|
||||
cooldownSec: savedConfig.cooldownSec,
|
||||
cooldownSec: saved.webhookCooldownSec,
|
||||
},
|
||||
{ bypassCooldown: true },
|
||||
);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { SettingsManager } from '@/core/adminSettings/settingsManager';
|
||||
import { recordAdminAuditLogAsync } from '@/core/auth/auditLog';
|
||||
import { SDKManager } from '@/core/sdk/sdkManager';
|
||||
import { getInternalIngestionHeaders } from '@/core/Security/security';
|
||||
import { CSVStorageManager } from '@/core/Storage/csvStorage';
|
||||
import { DataBufferEngine } from '@/core/data/buffer';
|
||||
import { requireAdminApiSession } from '@/lib/adminAuth';
|
||||
import { extractClientIp, requireAdminApiSession } from '@/lib/adminAuth';
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req);
|
||||
@@ -42,7 +43,18 @@ export async function GET(req: NextRequest) {
|
||||
|
||||
const stats = CSVStorageManager.formatStorageStats(files);
|
||||
|
||||
return NextResponse.json({ stats, files, diskUsage });
|
||||
return NextResponse.json({
|
||||
stats,
|
||||
files,
|
||||
diskUsage: diskUsage ?? {
|
||||
available: false,
|
||||
usedPct: 0,
|
||||
availableBytes: 0,
|
||||
freeBytes: 0,
|
||||
totalBytes: 0,
|
||||
checkedAt: Date.now(),
|
||||
},
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Storage stats failed';
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
@@ -150,10 +162,24 @@ export async function POST(req: NextRequest) {
|
||||
const combinedFiles = Array.from(
|
||||
new Set([...localRes.files, ...remoteFiles]),
|
||||
);
|
||||
const totalFlushed = localRes.count + remoteCount;
|
||||
|
||||
await recordAdminAuditLogAsync({
|
||||
actorEmail: auth.auth.session.email,
|
||||
actorRole: auth.auth.session.role || 'owner',
|
||||
action: 'STORAGE_FLUSH_TRIGGERED',
|
||||
target: 'storage_buffer',
|
||||
ipAddress: extractClientIp(req),
|
||||
metadata: {
|
||||
flushedCount: totalFlushed,
|
||||
filesUpdated: combinedFiles.length,
|
||||
ingestionFlushed,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
flushedCount: localRes.count + remoteCount,
|
||||
flushedCount: totalFlushed,
|
||||
filesUpdated: combinedFiles,
|
||||
ingestionFlushed,
|
||||
...(warning ? { warning } : {}),
|
||||
|
||||
@@ -11,7 +11,7 @@ import { requireAdminApiSession } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const auth = await requireAdminApiSession(req, { minRole: "operator" });
|
||||
const auth = await requireAdminApiSession(req, { minRole: "owner" });
|
||||
if (!auth.valid) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user