fix(auth): make session revocation authoritative

This commit is contained in:
2026-07-10 02:06:09 -04:00
parent b7500b4f91
commit f6ee99c3c2
6 changed files with 122 additions and 114 deletions
+4 -4
View File
@@ -2,7 +2,7 @@ import type { Env } from "./bindings.js";
import { import {
type AuthContext, type AuthContext,
AuthError, AuthError,
AuthSessionCacheSchemaError, AuthSessionSchemaError,
authenticatedRateLimitKey, authenticatedRateLimitKey,
readAuthContext, readAuthContext,
} from "./auth.js"; } from "./auth.js";
@@ -87,13 +87,13 @@ export async function withAuthenticatedApiControls(
recordApiAuditEvent(request, env, route, response, error.code); recordApiAuditEvent(request, env, route, response, error.code);
return response; return response;
} }
if (error instanceof AuthSessionCacheSchemaError) { if (error instanceof AuthSessionSchemaError) {
const response = jsonResponse( const response = jsonResponse(
{ error: "auth_session_cache_invalid" }, { error: "auth_session_invalid" },
500, 500,
{ "Cache-Control": "no-store" }, { "Cache-Control": "no-store" },
); );
recordApiAuditEvent(request, env, route, response, "auth_session_cache_invalid"); recordApiAuditEvent(request, env, route, response, "auth_session_invalid");
return response; return response;
} }
throw error; throw error;
+9 -61
View File
@@ -45,16 +45,16 @@ export class AuthError extends Error {
} }
} }
export class AuthSessionCacheSchemaError extends Error { export class AuthSessionSchemaError extends Error {
constructor(message: string) { constructor(message: string) {
super(message); super(message);
this.name = "AuthSessionCacheSchemaError"; this.name = "AuthSessionSchemaError";
} }
} }
export function authSessionCacheKvKey(environment: string, tokenHash: string): string { export function authSessionCacheKvKey(environment: string, tokenHash: string): string {
if (!/^[a-f0-9]{64}$/.test(tokenHash)) { if (!/^[a-f0-9]{64}$/.test(tokenHash)) {
throw new AuthSessionCacheSchemaError("token_hash_invalid"); throw new AuthSessionSchemaError("token_hash_invalid");
} }
return `${prefixedKvKey(environment, AUTH_SESSION_CACHE_NAMESPACE)}:${tokenHash}`; return `${prefixedKvKey(environment, AUTH_SESSION_CACHE_NAMESPACE)}:${tokenHash}`;
} }
@@ -90,17 +90,7 @@ export async function readAuthContext(
} }
const tokenHash = await sha256Hex(token); const tokenHash = await sha256Hex(token);
const cacheKey = authSessionCacheKvKey(env.ELY_ENVIRONMENT, tokenHash);
const document = await env.ELY_KV.get(cacheKey);
if (document === null) {
return readBetterAuthSessionContext(env, token, tokenHash, now); return readBetterAuthSessionContext(env, token, tokenHash, now);
}
const session = parseAuthSessionCacheDocument(document, tokenHash);
if (Date.parse(session.expiresAt) <= now.getTime()) {
throw new AuthError("session_expired");
}
return session;
} }
async function readBetterAuthSessionContext( async function readBetterAuthSessionContext(
@@ -152,45 +142,16 @@ function bearerToken(request: Request): string | null {
return token; return token;
} }
function parseAuthSessionCacheDocument(value: string, tokenHash: string): AuthContext {
let parsed: unknown;
try {
parsed = JSON.parse(value);
} catch {
throw new AuthSessionCacheSchemaError("auth_session_cache_json_invalid");
}
if (!isRecord(parsed)) {
throw new AuthSessionCacheSchemaError("auth_session_cache_must_be_object");
}
assertOnlyFields(parsed, ["version", "user_id", "session_id", "device_id", "expires_at"]);
if (parsed.version !== 1) {
throw new AuthSessionCacheSchemaError("auth_session_cache_version_invalid");
}
const context: AuthContext = {
userId: subjectId(stringField(parsed, "user_id"), "user_id"),
sessionId: subjectId(stringField(parsed, "session_id"), "session_id"),
tokenHash,
expiresAt: isoTimestamp(stringField(parsed, "expires_at"), "expires_at"),
};
const deviceId = optionalStringField(parsed, "device_id");
if (deviceId !== undefined) {
context.deviceId = deviceIdValue(deviceId);
}
return context;
}
function subjectId(value: string, label: string): string { function subjectId(value: string, label: string): string {
if (!SUBJECT_ID_PATTERN.test(value)) { if (!SUBJECT_ID_PATTERN.test(value)) {
throw new AuthSessionCacheSchemaError(`${label}_invalid`); throw new AuthSessionSchemaError(`${label}_invalid`);
} }
return value; return value;
} }
function deviceIdValue(value: string): string { function deviceIdValue(value: string): string {
if (!DEVICE_ID_PATTERN.test(value)) { if (!DEVICE_ID_PATTERN.test(value)) {
throw new AuthSessionCacheSchemaError("device_id_invalid"); throw new AuthSessionSchemaError("device_id_invalid");
} }
return value; return value;
} }
@@ -198,7 +159,7 @@ function deviceIdValue(value: string): string {
function isoTimestamp(value: string, label: string): string { function isoTimestamp(value: string, label: string): string {
const timestamp = Date.parse(value); const timestamp = Date.parse(value);
if (!Number.isFinite(timestamp)) { if (!Number.isFinite(timestamp)) {
throw new AuthSessionCacheSchemaError(`${label}_invalid`); throw new AuthSessionSchemaError(`${label}_invalid`);
} }
return new Date(timestamp).toISOString(); return new Date(timestamp).toISOString();
} }
@@ -214,13 +175,13 @@ function timestampField(value: Record<string, unknown>, field: string): string {
if (fieldValue instanceof Date) { if (fieldValue instanceof Date) {
return fieldValue.toISOString(); return fieldValue.toISOString();
} }
throw new AuthSessionCacheSchemaError(`${field}_required`); throw new AuthSessionSchemaError(`${field}_required`);
} }
function stringField(value: Record<string, unknown>, field: string): string { function stringField(value: Record<string, unknown>, field: string): string {
const fieldValue = value[field]; const fieldValue = value[field];
if (typeof fieldValue !== "string" || fieldValue.trim() === "") { if (typeof fieldValue !== "string" || fieldValue.trim() === "") {
throw new AuthSessionCacheSchemaError(`${field}_required`); throw new AuthSessionSchemaError(`${field}_required`);
} }
return fieldValue.trim(); return fieldValue.trim();
} }
@@ -231,24 +192,11 @@ function optionalStringField(value: Record<string, unknown>, field: string): str
return undefined; return undefined;
} }
if (typeof fieldValue !== "string" || fieldValue.trim() === "") { if (typeof fieldValue !== "string" || fieldValue.trim() === "") {
throw new AuthSessionCacheSchemaError(`${field}_invalid`); throw new AuthSessionSchemaError(`${field}_invalid`);
} }
return fieldValue.trim(); return fieldValue.trim();
} }
function assertOnlyFields(value: Record<string, unknown>, fields: string[]): void {
const allowed = new Set(fields);
for (const field of Object.keys(value)) {
if (!allowed.has(field)) {
throw new AuthSessionCacheSchemaError(`unexpected_field:${field}`);
}
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
async function sha256Hex(value: string): Promise<string> { async function sha256Hex(value: string): Promise<string> {
const bytes = new TextEncoder().encode(value); const bytes = new TextEncoder().encode(value);
const digest = await crypto.subtle.digest("SHA-256", bytes); const digest = await crypto.subtle.digest("SHA-256", bytes);
-19
View File
@@ -1,5 +1,4 @@
import type { AuthContext } from "./auth.js"; import type { AuthContext } from "./auth.js";
import { authSessionCacheKvKey } from "./auth.js";
import type { Env } from "./bindings.js"; import type { Env } from "./bindings.js";
import { import {
type DeviceApprovalDocument, type DeviceApprovalDocument,
@@ -228,7 +227,6 @@ export async function registerDeviceDocument(
throw new DevicePersistenceError("device_registration_missing"); throw new DevicePersistenceError("device_registration_missing");
} }
await bindSessionDeviceContext(env, context, registration.deviceId, nowSeconds); await bindSessionDeviceContext(env, context, registration.deviceId, nowSeconds);
await refreshSessionDeviceCache(env, context, registration.deviceId);
return { return {
version: 1, version: 1,
@@ -248,23 +246,6 @@ async function bindSessionDeviceContext(
.run(); .run();
} }
async function refreshSessionDeviceCache(
env: Env,
context: AuthContext,
deviceId: string,
): Promise<void> {
await env.ELY_KV.put(
authSessionCacheKvKey(env.ELY_ENVIRONMENT, context.tokenHash),
JSON.stringify({
version: 1,
user_id: context.userId,
session_id: context.sessionId,
device_id: deviceId,
expires_at: context.expiresAt,
}),
);
}
export async function approveDeviceDocument( export async function approveDeviceDocument(
request: Request, request: Request,
env: Env, env: Env,
+52 -12
View File
@@ -79,7 +79,7 @@ describe("api controls", () => {
assert.equal(auditEvents[0]?.doubles?.[0], 405); assert.equal(auditEvents[0]?.doubles?.[0], 405);
}); });
it("rate limits authenticated API routes before reading session cache", async () => { it("rate limits authenticated API routes before reading session state", async () => {
const auditEvents: ElyAnalyticsDataPoint[] = []; const auditEvents: ElyAnalyticsDataPoint[] = [];
const kvReads: string[] = []; const kvReads: string[] = [];
const response = await withAuthenticatedApiControls( const response = await withAuthenticatedApiControls(
@@ -167,7 +167,6 @@ describe("api controls", () => {
auditEvents, auditEvents,
kvReads, kvReads,
rateLimitKeys, rateLimitKeys,
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
}), }),
"devices.list", "devices.list",
["GET"], ["GET"],
@@ -182,7 +181,7 @@ describe("api controls", () => {
assert.equal(response.status, 200); assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { user_id: "user-01", device_id: "device-01" }); assert.deepEqual(await response.json(), { user_id: "user-01", device_id: "device-01" });
assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]); assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]);
assert.deepEqual(kvReads, [authSessionCacheKvKey("local", tokenHash)]); assert.deepEqual(kvReads, []);
assert.equal(receivedTokenHash, tokenHash); assert.equal(receivedTokenHash, tokenHash);
assert.deepEqual(auditEvents[0]?.blobs, [ assert.deepEqual(auditEvents[0]?.blobs, [
"devices.list", "devices.list",
@@ -196,7 +195,7 @@ describe("api controls", () => {
]); ]);
}); });
it("uses Better Auth D1 sessions when the session cache is cold", async () => { it("uses Better Auth D1 sessions as the authoritative source", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN); const tokenHash = await authTokenHash(ACCESS_TOKEN);
const auditEvents: ElyAnalyticsDataPoint[] = []; const auditEvents: ElyAnalyticsDataPoint[] = [];
const kvReads: string[] = []; const kvReads: string[] = [];
@@ -246,7 +245,7 @@ describe("api controls", () => {
device_id: "device-01", device_id: "device-01",
}); });
assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]); assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]);
assert.deepEqual(kvReads, [authSessionCacheKvKey("local", tokenHash)]); assert.deepEqual(kvReads, []);
assert.equal(d1Queries.length, 1); assert.equal(d1Queries.length, 1);
assert.match(d1Queries[0] ?? "", /FROM better_auth_session/); assert.match(d1Queries[0] ?? "", /FROM better_auth_session/);
assert.deepEqual(d1Binds, [[ACCESS_TOKEN]]); assert.deepEqual(d1Binds, [[ACCESS_TOKEN]]);
@@ -262,20 +261,50 @@ describe("api controls", () => {
assert.equal(auditEvents[0]?.blobs?.[7], "device-01"); assert.equal(auditEvents[0]?.blobs?.[7], "device-01");
}); });
it("rejects expired authenticated sessions", async () => { it("rejects a legacy cached session after D1 revocation", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN); const tokenHash = await authTokenHash(ACCESS_TOKEN);
const kvReads: string[] = [];
const d1Queries: string[] = [];
const d1Binds: unknown[][] = [];
const response = await withAuthenticatedApiControls( const response = await withAuthenticatedApiControls(
new Request("https://elydora.test/api/devices", { new Request("https://elydora.test/api/devices", {
headers: { authorization: `Bearer ${ACCESS_TOKEN}` }, headers: { authorization: `Bearer ${ACCESS_TOKEN}` },
}), }),
testEnv({ testEnv({
kvEntries: [ kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
[ kvReads,
authSessionCacheKvKey("local", tokenHash), d1: testD1Database({ firstRows: [], queries: d1Queries, binds: d1Binds }),
sessionDocument("2026-01-01T00:00:00.000Z"), }),
], "devices.list",
["GET"],
() => Promise.resolve(jsonResponse({ ok: true }, 200)),
);
assert.equal(response.status, 401);
assert.deepEqual(await response.json(), { error: "session_not_found" });
assert.deepEqual(kvReads, []);
assert.equal(d1Queries.length, 1);
assert.match(d1Queries[0] ?? "", /FROM better_auth_session/);
assert.deepEqual(d1Binds, [[ACCESS_TOKEN]]);
});
it("rejects expired authenticated sessions", async () => {
const response = await withAuthenticatedApiControls(
new Request("https://elydora.test/api/devices", {
headers: { authorization: `Bearer ${ACCESS_TOKEN}` },
}),
testEnv({
d1: testD1Database({
firstRows: [
{
id: "session-01",
userId: "user-01",
expiresAt: "2026-01-01T00:00:00.000Z",
deviceId: "device-01",
},
], ],
}), }),
}),
"devices.list", "devices.list",
["GET"], ["GET"],
() => Promise.resolve(jsonResponse({ ok: true }, 200)), () => Promise.resolve(jsonResponse({ ok: true }, 200)),
@@ -383,11 +412,22 @@ interface TestD1DatabaseOptions {
} }
function testD1Database(options: TestD1DatabaseOptions = {}): Env["ELY_DB"] { function testD1Database(options: TestD1DatabaseOptions = {}): Env["ELY_DB"] {
const configuredOptions: TestD1DatabaseOptions = {
...options,
firstRows: options.firstRows ?? [
{
id: "session-01",
userId: "user-01",
expiresAt: "2099-01-01T00:00:00.000Z",
deviceId: "device-01",
},
],
};
let firstIndex = 0; let firstIndex = 0;
return { return {
prepare(query: string) { prepare(query: string) {
options.queries?.push(query); options.queries?.push(query);
return testD1PreparedStatement(options, () => firstIndex++); return testD1PreparedStatement(configuredOptions, () => firstIndex++);
}, },
batch() { batch() {
return Promise.resolve([]); return Promise.resolve([]);
+14 -6
View File
@@ -223,15 +223,14 @@ describe("device routes", () => {
assert.equal(d1.binds[0]?.[7], IDEMPOTENCY_KEY); assert.equal(d1.binds[0]?.[7], IDEMPOTENCY_KEY);
assert.deepEqual(d1.binds[1], ["user-01", IDEMPOTENCY_KEY]); assert.deepEqual(d1.binds[1], ["user-01", IDEMPOTENCY_KEY]);
assert.deepEqual(d1.binds[2]?.slice(0, 3), ["session-01", "user-01", "device-01"]); assert.deepEqual(d1.binds[2]?.slice(0, 3), ["session-01", "user-01", "device-01"]);
assert.deepEqual(kvPuts, [[sessionCacheKey, sessionDocument("device-01")]]); assert.deepEqual(kvPuts, []);
}); });
it("registers and caches device context for sessions without a current device", async () => { it("registers D1 device context for sessions without a current device", async () => {
const tokenHash = await authTokenHash(ACCESS_TOKEN); const tokenHash = await authTokenHash(ACCESS_TOKEN);
const sessionCacheKey = authSessionCacheKvKey("local", tokenHash); const sessionCacheKey = authSessionCacheKvKey("local", tokenHash);
const kvPuts: [string, string][] = []; const kvPuts: [string, string][] = [];
const d1 = testD1Database([ const deviceRow = {
{
device_id: "device-01", device_id: "device-01",
public_key: PUBLIC_KEY, public_key: PUBLIC_KEY,
device_name: "MacBook Pro", device_name: "MacBook Pro",
@@ -241,8 +240,17 @@ describe("device routes", () => {
approved_at: null, approved_at: null,
last_active_at: 1_780_000_100, last_active_at: 1_780_000_100,
revoked_at: null, revoked_at: null,
};
const d1 = testD1Database({
allRows: [deviceRow],
firstRows: [deviceRow],
sessionRow: {
id: "session-01",
userId: "user-01",
expiresAt: "2099-01-01T00:00:00.000Z",
deviceId: null,
}, },
]); });
const response = await handleRequest( const response = await handleRequest(
new Request("https://elydora.test/api/devices/register", { new Request("https://elydora.test/api/devices/register", {
@@ -262,7 +270,7 @@ describe("device routes", () => {
assert.equal(response.status, 201); assert.equal(response.status, 201);
assert.deepEqual(d1.binds[2]?.slice(0, 3), ["session-01", "user-01", "device-01"]); assert.deepEqual(d1.binds[2]?.slice(0, 3), ["session-01", "user-01", "device-01"]);
assert.deepEqual(kvPuts, [[sessionCacheKey, sessionDocument("device-01")]]); assert.deepEqual(kvPuts, []);
}); });
it("rejects invalid device registration payloads before D1 writes", async () => { it("rejects invalid device registration payloads before D1 writes", async () => {
+33 -2
View File
@@ -24,6 +24,8 @@ export interface TestEnvOptions {
} }
export interface RecordedD1Database extends ElyD1Database { export interface RecordedD1Database extends ElyD1Database {
authBinds: unknown[][];
authQueries: string[];
batches: number[]; batches: number[];
binds: unknown[][]; binds: unknown[][];
queries: string[]; queries: string[];
@@ -38,8 +40,16 @@ export interface RecordedR2Put {
interface TestD1DatabaseOptions { interface TestD1DatabaseOptions {
allRows?: unknown[]; allRows?: unknown[];
firstRows?: unknown[]; firstRows?: unknown[];
sessionRow?: unknown | null;
} }
const DEFAULT_AUTH_SESSION_ROW = {
id: "session-01",
userId: "user-01",
expiresAt: "2099-01-01T00:00:00.000Z",
deviceId: "device-01",
};
export function testEnv(options: TestEnvOptions): Env { export function testEnv(options: TestEnvOptions): Env {
const values = new Map(options.kvEntries ?? []); const values = new Map(options.kvEntries ?? []);
return { return {
@@ -92,19 +102,35 @@ export function testEnv(options: TestEnvOptions): Env {
} }
export function testD1Database(rows: unknown[] | TestD1DatabaseOptions): RecordedD1Database { export function testD1Database(rows: unknown[] | TestD1DatabaseOptions): RecordedD1Database {
const authBinds: unknown[][] = [];
const authQueries: string[] = [];
const binds: unknown[][] = []; const binds: unknown[][] = [];
const batches: number[] = []; const batches: number[] = [];
const queries: string[] = []; const queries: string[] = [];
const allRows = Array.isArray(rows) ? rows : rows.allRows ?? []; const allRows = Array.isArray(rows) ? rows : rows.allRows ?? [];
const firstRows = Array.isArray(rows) ? rows : rows.firstRows ?? []; const firstRows = Array.isArray(rows) ? rows : rows.firstRows ?? [];
const sessionRow =
!Array.isArray(rows) && Object.hasOwn(rows, "sessionRow")
? rows.sessionRow ?? null
: DEFAULT_AUTH_SESSION_ROW;
let firstIndex = 0; let firstIndex = 0;
return { return {
authBinds,
authQueries,
batches, batches,
binds, binds,
queries, queries,
prepare(query: string) { prepare(query: string) {
queries.push(query); const isAuthSessionQuery = query.includes("FROM better_auth_session AS session");
return testD1PreparedStatement(allRows, firstRows, () => firstIndex++, binds); (isAuthSessionQuery ? authQueries : queries).push(query);
return testD1PreparedStatement(
allRows,
firstRows,
() => firstIndex++,
isAuthSessionQuery ? authBinds : binds,
isAuthSessionQuery,
sessionRow,
);
}, },
batch(statements: ElyD1PreparedStatement[]) { batch(statements: ElyD1PreparedStatement[]) {
batches.push(statements.length); batches.push(statements.length);
@@ -131,6 +157,8 @@ function testD1PreparedStatement(
firstRows: unknown[], firstRows: unknown[],
nextFirstIndex: () => number, nextFirstIndex: () => number,
binds: unknown[][], binds: unknown[][],
isAuthSessionQuery: boolean,
sessionRow: unknown | null,
): ElyD1PreparedStatement { ): ElyD1PreparedStatement {
return { return {
bind(...values: unknown[]) { bind(...values: unknown[]) {
@@ -138,6 +166,9 @@ function testD1PreparedStatement(
return this; return this;
}, },
first<T>() { first<T>() {
if (isAuthSessionQuery) {
return Promise.resolve(sessionRow as T | null);
}
return Promise.resolve((firstRows[nextFirstIndex()] as T | undefined) ?? null); return Promise.resolve((firstRows[nextFirstIndex()] as T | undefined) ?? null);
}, },
all<T>() { all<T>() {