diff --git a/.changeset/unauthenticated-refusal-audit.md b/.changeset/unauthenticated-refusal-audit.md new file mode 100644 index 00000000..c753967b --- /dev/null +++ b/.changeset/unauthenticated-refusal-audit.md @@ -0,0 +1,5 @@ +--- +'seamless-auth-api': minor +--- + +Refusals anyone can produce for free no longer write audit events (#596). A request from a disallowed origin (`403`), a request to an unknown route (`404`), and `POST /refresh` with no token or one that matches no session (`401`) used to each write a hash-chained `request_suspicious` or `refresh_token_failed` row, taking the chain head lock. They are now counted in process, and each instance logs a one-line summary at most once a minute. Responses are unchanged. Expect far fewer `request_suspicious` rows in the trail and the security anomaly view. A refresh token that matches a revoked session is still recorded, now against that session and its user. The stored audit user agent is capped at 512 characters and a refused bearer's recorded route at 256. diff --git a/docs/security-posture.md b/docs/security-posture.md index 5542681a..17b000fa 100644 --- a/docs/security-posture.md +++ b/docs/security-posture.md @@ -389,9 +389,8 @@ Two kinds of request are deliberately not refused: The refusal carries no `Access-Control-Allow-Origin` header. Naming an allowed origin to a caller that is not one discloses part of the allowlist and helps the browser not at all. -The refusal is recorded as one `request_suspicious` auth event with the real client address and user -agent, and the rejected origin in an `origin` metadata field. It used to be recorded with the origin -string in the `ipAddress` field, which made the trail hard to read. +The refusal writes no audit event. Any caller can send any `Origin`, so it is counted instead; see +[Refusals at the auth gate](#refusals-at-the-auth-gate). ## Refresh rotation @@ -826,6 +825,28 @@ Widening this waits on retention and bulk export ([issue #173](https://github.com/fells-code/seamless-auth-api/issues/173)). Until a window can be pruned, a high-volume event type costs the trail more than it adds. +### Other free refusals + +The same rule holds outside the bearer gate. These answer exactly as before but write no +audit event: + +- a request from an origin `APP_ORIGINS` does not allow (`403`) +- a request to a route that does not exist (`404`) +- `POST /refresh` with no bearer token, or with one that matches no session (`401`) + +Each audit row is part of the hash chain, and writing one takes the chain head row lock, so +a scanner at the general rate limit used to grow the trail and queue real sign-ins behind +its writes. These refusals are counted in process instead, and each instance logs a +one-line summary (`Unauthenticated refusals in the last 60s: ...`) at most once a minute, +when it sees one. Alert on that line, not on the trail. + +A refresh token that does match a session is still recorded as `refresh_token_failed`, +against that session and its user, whether the session expired, idled out or was revoked. +This server issued that token, so the row names somebody. + +Where audit rows are still written, the caller-chosen parts are capped: the stored user +agent at 512 characters, and the route a refused bearer records at 256. + ### The subject is metadata, not `user_id` A refused token has established no principal, so the event records `userId: null`. The diff --git a/src/app.ts b/src/app.ts index b460c7db..01ac022f 100644 --- a/src/app.ts +++ b/src/app.ts @@ -16,7 +16,7 @@ import { logRoute } from './middleware/routeLogger.js'; import { dynamicSlowDown } from './middleware/slowDown.js'; import { applyTrustedClientContext } from './middleware/trustedClientContext.js'; import { generateOpenApiDocument } from './openapi/document.js'; -import { AuthEventService } from './services/authEventService.js'; +import { countUnauthenticatedRefusal } from './services/unauthenticatedRefusals.js'; import getLogger from './utils/logger.js'; const logger = getLogger('app'); @@ -145,12 +145,7 @@ export async function createApp() { app.use((err: Error, req: Request, res: Response, next: NextFunction) => { if (err.message === CORS_REJECTION) { - // Recorded here rather than in the delegate so the event carries the real - // client address and user agent, with the origin in a field that says origin. - void AuthEventService.requestSuspicious(req, { - reason: 'Request from an unexpected origin', - origin: req.headers.origin ?? null, - }); + countUnauthenticatedRefusal('cors_origin_refused'); // No Access-Control-Allow-Origin: naming an allowed origin to a caller that // is not one tells it part of the allowlist and helps the browser not at all. return res.status(403).json({ message: 'CORS policy does not allow this origin.' }); @@ -175,14 +170,7 @@ export async function createApp() { }); app.use((req: Request, res: Response) => { - logger.warn( - `[${req.ip}] ${req.method} ${req.originalUrl} did not match any route. Tracking suspicious behavior`, - ); - void AuthEventService.requestSuspicious(req, { - reason: 'Request to an unknown route.', - method: req.method, - path: req.originalUrl, - }); + countUnauthenticatedRefusal('unknown_route'); return res.status(404).json({ error: 'Not Found' }); }); diff --git a/src/controllers/authentication.ts b/src/controllers/authentication.ts index bd3885e5..b1bf1a8b 100644 --- a/src/controllers/authentication.ts +++ b/src/controllers/authentication.ts @@ -51,6 +51,7 @@ import { replayRefreshRotation, revokeSessionChain, } from '../services/sessionService.js'; +import { countUnauthenticatedRefusal } from '../services/unauthenticatedRefusals.js'; import { AuthenticatedRequest } from '../types/types.js'; import getLogger from '../utils/logger.js'; import { @@ -650,7 +651,7 @@ export const refreshSession = async (req: Request, res: Response) => { if (!refreshToken) { logger.error('Refresh token provided is not of expected type for auth server configurations'); - await AuthEventService.refreshTokenFailed(req, { reason: 'Missing refresh token' }); + countUnauthenticatedRefusal('refresh_token_missing'); res.status(401).json({ error: 'Not allowed' }); return; } @@ -691,11 +692,18 @@ export const refreshSession = async (req: Request, res: Response) => { chainStartedAt: (presented.chainStartedAt ?? presented.createdAt)?.toISOString(), }, }); - } else { - await AuthEventService.refreshTokenFailed(req, { - reason: 'No refresh session found for refresh token', - tokenFormat: looksLikeJwt ? 'jwt_like' : 'opaque', + } else if (presented) { + await AuthEventService.log({ + userId: presented.userId, + sessionId: presented.id, + type: 'refresh_token_failed', + req, + metadata: { reason: 'Refresh session revoked', refusal: 'revoked' }, }); + } else { + // Matches no session, so anybody could have sent it. A token this server issued + // and later revoked is still recorded, above. + countUnauthenticatedRefusal('refresh_token_unknown'); } return res.status(401).json({ error: 'invalid_refresh_token' }); } diff --git a/src/controllers/internalSecurity.ts b/src/controllers/internalSecurity.ts index a22ab9fc..85cc7198 100644 --- a/src/controllers/internalSecurity.ts +++ b/src/controllers/internalSecurity.ts @@ -18,9 +18,9 @@ const logger = getLogger('internalSecurity'); /** * Rows one call will return. * - * Bounded because the matched set is attacker-controlled: `request_suspicious` is - * recorded for every unmatched route and every refused origin, so a scanner alone can - * make a day's window arbitrarily large. + * Bounded because the matched set can be driven by callers: failed sign-ins and + * suspicious requests are recorded per attempt, so one busy attacker can make a day's + * window large. */ const ANOMALY_LIMIT = 200; diff --git a/src/middleware/verifyBearerAuth.ts b/src/middleware/verifyBearerAuth.ts index dab3c9f2..50b6b5f3 100644 --- a/src/middleware/verifyBearerAuth.ts +++ b/src/middleware/verifyBearerAuth.ts @@ -14,11 +14,16 @@ import getLogger from '../utils/logger.js'; const logger = getLogger('verifyBearerAuth'); -/** The matched route pattern, so path parameters do not turn one route into many. */ +const MAX_ROUTE_LABEL_LENGTH = 256; + +/** + * The matched route pattern, so path parameters do not turn one route into many. Capped, + * since without a matched route it falls back to the request path the caller chose. + */ function routeLabel(req: Request): string { const pattern = typeof req.route?.path === 'string' ? req.route.path : req.path; - return `${req.baseUrl ?? ''}${pattern ?? ''}`; + return `${req.baseUrl ?? ''}${pattern ?? ''}`.slice(0, MAX_ROUTE_LABEL_LENGTH); } /** diff --git a/src/services/authEventService.ts b/src/services/authEventService.ts index 4e173065..0e6e3ef8 100644 --- a/src/services/authEventService.ts +++ b/src/services/authEventService.ts @@ -77,6 +77,13 @@ interface AuthEventContextOptions { metadata?: Record | null; } +// Real user agents run to a few hundred characters; the header itself is unbounded. +const MAX_AUDIT_USER_AGENT_LENGTH = 512; + +function capUserAgent(userAgent: string | null | undefined) { + return userAgent?.slice(0, MAX_AUDIT_USER_AGENT_LENGTH) || null; +} + function deploymentId() { return process.env.APP_ID?.trim() || null; } @@ -109,6 +116,7 @@ export class AuthEventService { metadata = null, }: AuthEventContextOptions) { const normalizedType = normalizeAuthEventType(type); + const cappedUserAgent = capUserAgent(userAgent); // Counted before the audit write and in its own statement, so a trail that // cannot be written no longer takes the lockout control down with it. This @@ -123,9 +131,9 @@ export class AuthEventService { session_id: sessionId, type: normalizedType, ip_address: ipAddress || 'unknown', - user_agent: userAgent || 'unknown', + user_agent: cappedUserAgent || 'unknown', deployment_id: deploymentId(), - device_class: classifyDeviceClass(userAgent), + device_class: classifyDeviceClass(cappedUserAgent), mail_provider: mailProviderFor(subjectEmail), owner: subjectEmail ? isOwnerEmail(subjectEmail) : null, attempt_id: attemptId, diff --git a/src/services/unauthenticatedRefusals.ts b/src/services/unauthenticatedRefusals.ts new file mode 100644 index 00000000..636d4667 --- /dev/null +++ b/src/services/unauthenticatedRefusals.ts @@ -0,0 +1,57 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import getLogger from '../utils/logger.js'; + +const logger = getLogger('unauthenticatedRefusals'); + +export type UnauthenticatedRefusal = + 'cors_origin_refused' | 'unknown_route' | 'refresh_token_missing' | 'refresh_token_unknown'; + +/** How often the counts are written to the application log, at most. */ +export const REFUSAL_SUMMARY_INTERVAL_MS = 60 * 1000; + +let counts = new Map(); +let windowStartedAt = Date.now(); + +function flush(now: number) { + const summary = [...counts.entries()].map(([kind, count]) => `${kind}=${count}`).join(' '); + + logger.warn( + `Unauthenticated refusals in the last ${Math.round((now - windowStartedAt) / 1000)}s: ${summary}`, + ); + + counts = new Map(); + windowStartedAt = now; +} + +/** + * Counts a refusal that any caller can produce for nothing: an origin that is not allowed, + * a route that does not exist, or a refresh token that is missing or matches no session. + * + * These used to be audit events. Each one took the audit chain head lock and added a + * permanent row, so a scanner at the general rate limit could grow the trail and queue + * real sign-ins behind its writes. A count in the application log keeps the signal for + * monitoring without either cost. See "Refusals at the auth gate" in + * docs/security-posture.md. + */ +export function countUnauthenticatedRefusal(kind: UnauthenticatedRefusal, now = Date.now()) { + counts.set(kind, (counts.get(kind) ?? 0) + 1); + + if (now - windowStartedAt >= REFUSAL_SUMMARY_INTERVAL_MS) { + flush(now); + } +} + +export function getUnauthenticatedRefusalCounts(): Partial> { + return Object.fromEntries(counts); +} + +/** Test seam. Process-level state has to be resettable between cases. */ +export function resetUnauthenticatedRefusalsForTests(now = Date.now()) { + counts = new Map(); + windowStartedAt = now; +} diff --git a/tests/integration/health/health.spec.ts b/tests/integration/health/health.spec.ts index a5444eb1..62855b39 100644 --- a/tests/integration/health/health.spec.ts +++ b/tests/integration/health/health.spec.ts @@ -75,14 +75,6 @@ describe('Health Routes', () => { const res = await request(app).get('/health/unknown'); expect(res.status).toBe(404); - expect(AuthEventService.requestSuspicious).toHaveBeenCalledWith( - expect.objectContaining({ - originalUrl: '/health/unknown', - }), - expect.objectContaining({ - reason: 'Request to an unknown route.', - path: '/health/unknown', - }), - ); + expect(AuthEventService.requestSuspicious).not.toHaveBeenCalled(); }); }); diff --git a/tests/unit/app.spec.ts b/tests/unit/app.spec.ts index 408be295..906053eb 100644 --- a/tests/unit/app.spec.ts +++ b/tests/unit/app.spec.ts @@ -4,6 +4,10 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import app, { createApp } from '../../src/app.js'; import { AuthEventService } from '../../src/services/authEventService.js'; +import { + getUnauthenticatedRefusalCounts, + resetUnauthenticatedRefusalsForTests, +} from '../../src/services/unauthenticatedRefusals.js'; let built: Awaited>; @@ -71,13 +75,18 @@ describe('CORS origin handling', () => { expect(res.body).toEqual({ message: 'CORS policy does not allow this origin.' }); expect(routeRan).not.toHaveBeenCalled(); expect(res.headers['access-control-allow-origin']).toBeUndefined(); - expect(AuthEventService.requestSuspicious).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - reason: 'Request from an unexpected origin', - origin: 'http://evil.example', - }), - ); + }); + + // Anybody can send any Origin, so a refusal is counted rather than written to the audit + // chain, where each row takes the chain head lock. + it('counts a refused origin without writing an audit event', async () => { + resetUnauthenticatedRefusalsForTests(); + + await request(built).get('/__test_route_ran').set('Origin', 'http://evil.example'); + + expect(AuthEventService.requestSuspicious).not.toHaveBeenCalled(); + expect(AuthEventService.log).not.toHaveBeenCalled(); + expect(getUnauthenticatedRefusalCounts()).toEqual({ cors_origin_refused: 1 }); }); it('refuses a preflight from an unknown origin rather than answering it', async () => { @@ -136,13 +145,14 @@ describe('createApp error handling', () => { expect(res.body).toEqual({ error: 'Internal server error' }); }); - // The 404 handler records the caller as suspicious. A fault on this side is not the - // caller misbehaving, and letting it land there put server bugs into the signal the - // anomaly views read. - it('does not record a server error as suspicious activity', async () => { + // A fault on this side is not the caller misbehaving, so it is not counted as an + // unknown route either. + it('does not count a server error as an unknown route', async () => { + resetUnauthenticatedRefusalsForTests(); + await request(built).get('/__test_plain_error'); - expect(AuthEventService.requestSuspicious).not.toHaveBeenCalled(); + expect(getUnauthenticatedRefusalCounts()).toEqual({}); }); it('falls back to a 500 when the error pipeline itself throws', async () => { @@ -152,12 +162,16 @@ describe('createApp error handling', () => { expect(res.body).toEqual({ error: 'Internal server error' }); }); - it('returns 404 and records suspicious activity for an unknown route', async () => { + it('returns 404 for an unknown route and counts it without writing an audit event', async () => { + resetUnauthenticatedRefusalsForTests(); + const res = await request(built).get('/__definitely_not_a_route'); expect(res.status).toBe(404); expect(res.body).toEqual({ error: 'Not Found' }); - expect(AuthEventService.requestSuspicious).toHaveBeenCalled(); + expect(AuthEventService.requestSuspicious).not.toHaveBeenCalled(); + expect(AuthEventService.log).not.toHaveBeenCalled(); + expect(getUnauthenticatedRefusalCounts()).toEqual({ unknown_route: 1 }); }); }); diff --git a/tests/unit/controllers/authentication.spec.ts b/tests/unit/controllers/authentication.spec.ts index e6003b62..a6986f4f 100644 --- a/tests/unit/controllers/authentication.spec.ts +++ b/tests/unit/controllers/authentication.spec.ts @@ -6,6 +6,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + getUnauthenticatedRefusalCounts, + resetUnauthenticatedRefusalsForTests, +} from '../../../src/services/unauthenticatedRefusals.js'; import { buildUser } from '../../factories/userFactory.js'; function mockReqRes(authorization?: string) { @@ -61,6 +65,7 @@ async function loadAuthenticationModule() { beforeEach(() => { vi.clearAllMocks(); + resetUnauthenticatedRefusalsForTests(); }); describe('refreshSession', () => { @@ -70,12 +75,9 @@ describe('refreshSession', () => { await refreshSession(req, res); - expect(AuthEventService.refreshTokenFailed).toHaveBeenCalledWith( - req, - expect.objectContaining({ - reason: 'Missing refresh token', - }), - ); + expect(AuthEventService.refreshTokenFailed).not.toHaveBeenCalled(); + expect(AuthEventService.log).not.toHaveBeenCalled(); + expect(getUnauthenticatedRefusalCounts()).toEqual({ refresh_token_missing: 1 }); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); @@ -91,14 +93,38 @@ describe('refreshSession', () => { await refreshSession(req, res); expect(findRefreshSessionByToken).toHaveBeenCalledWith('raw-refresh-token'); - expect(AuthEventService.refreshTokenFailed).toHaveBeenCalledWith( - req, + expect(AuthEventService.refreshTokenFailed).not.toHaveBeenCalled(); + expect(AuthEventService.log).not.toHaveBeenCalled(); + expect(getUnauthenticatedRefusalCounts()).toEqual({ refresh_token_unknown: 1 }); + expect(res.status).toHaveBeenCalledWith(401); + expect(res.json).toHaveBeenCalledWith({ error: 'invalid_refresh_token' }); + }); + + it('still records a revoked session it issued, against its user', async () => { + const { refreshSession, AuthEventService, findRefreshSessionByToken } = + await loadAuthenticationModule(); + const { req, res } = mockReqRes('Bearer raw-refresh-token'); + + (findRefreshSessionByToken as any).mockResolvedValue({ + id: 'session-1', + userId: 'user-1', + replacedBySessionId: null, + revokedAt: new Date(), + expiresAt: new Date(Date.now() + 60_000), + idleExpiresAt: new Date(Date.now() + 60_000), + }); + + await refreshSession(req, res); + + expect(AuthEventService.log).toHaveBeenCalledWith( expect.objectContaining({ - reason: 'No refresh session found for refresh token', - tokenFormat: 'opaque', + userId: 'user-1', + sessionId: 'session-1', + type: 'refresh_token_failed', + metadata: { reason: 'Refresh session revoked', refusal: 'revoked' }, }), ); - expect(res.status).toHaveBeenCalledWith(401); + expect(getUnauthenticatedRefusalCounts()).toEqual({}); expect(res.json).toHaveBeenCalledWith({ error: 'invalid_refresh_token' }); }); diff --git a/tests/unit/middleware/verifyBearerAuth.spec.ts b/tests/unit/middleware/verifyBearerAuth.spec.ts index e083d3a9..33900489 100644 --- a/tests/unit/middleware/verifyBearerAuth.spec.ts +++ b/tests/unit/middleware/verifyBearerAuth.spec.ts @@ -246,6 +246,19 @@ describe('verifyBearerAuth', () => { ); }); + it('caps the recorded path, which the caller chooses', async () => { + req.headers.authorization = bearerOfType('access'); + req.path = `/${'a'.repeat(5000)}`; + + (validateBearerToken as any).mockResolvedValue(null); + (verifyJwtWithKid as any).mockResolvedValue({ typ: 'access', sub: 'user-1' }); + + await verifyBearerAuth(req, res, next, 'ephemeral'); + + const [{ metadata }] = (AuthEventService.log as any).mock.calls[0]; + expect(metadata.route).toHaveLength(256); + }); + it('records nothing for an ordinary refusal of the expected token type', async () => { req.headers.authorization = bearerOfType('access'); diff --git a/tests/unit/services/authEventService.spec.ts b/tests/unit/services/authEventService.spec.ts index 362b24e6..7ae7809b 100644 --- a/tests/unit/services/authEventService.spec.ts +++ b/tests/unit/services/authEventService.spec.ts @@ -33,6 +33,19 @@ describe('AuthEventService', () => { vi.clearAllMocks(); }); + it('caps the stored user agent, which the caller chooses', async () => { + const { AuthEvent } = await import('../../../src/models/authEvents.js'); + const { AuthEventService } = await import('../../../src/services/authEventService.js'); + + await AuthEventService.log({ + type: 'login_failed', + req: buildReq({ headers: { 'user-agent': 'x'.repeat(10_000) } }), + }); + + const stored = vi.mocked(AuthEvent.create).mock.calls[0][0] as { user_agent: string }; + expect(stored.user_agent).toHaveLength(512); + }); + it('logs event successfully', async () => { const { AuthEvent } = await import('../../../src/models/authEvents.js'); const { AuthEventService } = await import('../../../src/services/authEventService.js'); diff --git a/tests/unit/services/unauthenticatedRefusals.spec.ts b/tests/unit/services/unauthenticatedRefusals.spec.ts new file mode 100644 index 00000000..d1e653fb --- /dev/null +++ b/tests/unit/services/unauthenticatedRefusals.spec.ts @@ -0,0 +1,48 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const warn = vi.fn(); + +vi.mock('../../../src/utils/logger.js', () => ({ + default: () => ({ warn, error: vi.fn(), info: vi.fn(), debug: vi.fn() }), +})); + +const { + REFUSAL_SUMMARY_INTERVAL_MS, + countUnauthenticatedRefusal, + getUnauthenticatedRefusalCounts, + resetUnauthenticatedRefusalsForTests, +} = await import('../../../src/services/unauthenticatedRefusals.js'); + +beforeEach(() => { + resetUnauthenticatedRefusalsForTests(0); +}); + +describe('countUnauthenticatedRefusal', () => { + it('counts each kind without logging inside the window', () => { + countUnauthenticatedRefusal('unknown_route', 10); + countUnauthenticatedRefusal('unknown_route', 20); + countUnauthenticatedRefusal('refresh_token_missing', 30); + + expect(getUnauthenticatedRefusalCounts()).toEqual({ + unknown_route: 2, + refresh_token_missing: 1, + }); + expect(warn).not.toHaveBeenCalled(); + }); + + it('logs one summary per window and starts counting again', () => { + countUnauthenticatedRefusal('cors_origin_refused', 10); + countUnauthenticatedRefusal('refresh_token_unknown', REFUSAL_SUMMARY_INTERVAL_MS); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + 'Unauthenticated refusals in the last 60s: cors_origin_refused=1 refresh_token_unknown=1', + ); + expect(getUnauthenticatedRefusalCounts()).toEqual({}); + + countUnauthenticatedRefusal('unknown_route', REFUSAL_SUMMARY_INTERVAL_MS + 1); + + expect(getUnauthenticatedRefusalCounts()).toEqual({ unknown_route: 1 }); + expect(warn).toHaveBeenCalledTimes(1); + }); +});