Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/unauthenticated-refusal-audit.md
Original file line number Diff line number Diff line change
@@ -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.
27 changes: 24 additions & 3 deletions docs/security-posture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
18 changes: 3 additions & 15 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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.' });
Expand All @@ -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' });
});

Expand Down
18 changes: 13 additions & 5 deletions src/controllers/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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' });
}
Expand Down
6 changes: 3 additions & 3 deletions src/controllers/internalSecurity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
9 changes: 7 additions & 2 deletions src/middleware/verifyBearerAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
12 changes: 10 additions & 2 deletions src/services/authEventService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ interface AuthEventContextOptions {
metadata?: Record<string, unknown> | 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;
}
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
57 changes: 57 additions & 0 deletions src/services/unauthenticatedRefusals.ts
Original file line number Diff line number Diff line change
@@ -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<UnauthenticatedRefusal, number>();
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<Record<UnauthenticatedRefusal, number>> {
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;
}
10 changes: 1 addition & 9 deletions tests/integration/health/health.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
42 changes: 28 additions & 14 deletions tests/unit/app.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReturnType<typeof createApp>>;

Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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 () => {
Expand All @@ -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 });
});
});

Expand Down
Loading