fix(auth): make session revocation authoritative
This commit is contained in:
@@ -79,7 +79,7 @@ describe("api controls", () => {
|
||||
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 kvReads: string[] = [];
|
||||
const response = await withAuthenticatedApiControls(
|
||||
@@ -167,7 +167,6 @@ describe("api controls", () => {
|
||||
auditEvents,
|
||||
kvReads,
|
||||
rateLimitKeys,
|
||||
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
|
||||
}),
|
||||
"devices.list",
|
||||
["GET"],
|
||||
@@ -182,7 +181,7 @@ describe("api controls", () => {
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(await response.json(), { user_id: "user-01", device_id: "device-01" });
|
||||
assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]);
|
||||
assert.deepEqual(kvReads, [authSessionCacheKvKey("local", tokenHash)]);
|
||||
assert.deepEqual(kvReads, []);
|
||||
assert.equal(receivedTokenHash, tokenHash);
|
||||
assert.deepEqual(auditEvents[0]?.blobs, [
|
||||
"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 auditEvents: ElyAnalyticsDataPoint[] = [];
|
||||
const kvReads: string[] = [];
|
||||
@@ -246,7 +245,7 @@ describe("api controls", () => {
|
||||
device_id: "device-01",
|
||||
});
|
||||
assert.deepEqual(rateLimitKeys, [`local:devices.list:bearer:${tokenHash}`]);
|
||||
assert.deepEqual(kvReads, [authSessionCacheKvKey("local", tokenHash)]);
|
||||
assert.deepEqual(kvReads, []);
|
||||
assert.equal(d1Queries.length, 1);
|
||||
assert.match(d1Queries[0] ?? "", /FROM better_auth_session/);
|
||||
assert.deepEqual(d1Binds, [[ACCESS_TOKEN]]);
|
||||
@@ -262,19 +261,49 @@ describe("api controls", () => {
|
||||
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 kvReads: string[] = [];
|
||||
const d1Queries: string[] = [];
|
||||
const d1Binds: unknown[][] = [];
|
||||
const response = await withAuthenticatedApiControls(
|
||||
new Request("https://elydora.test/api/devices", {
|
||||
headers: { authorization: `Bearer ${ACCESS_TOKEN}` },
|
||||
}),
|
||||
testEnv({
|
||||
kvEntries: [
|
||||
[
|
||||
authSessionCacheKvKey("local", tokenHash),
|
||||
sessionDocument("2026-01-01T00:00:00.000Z"),
|
||||
kvEntries: [[authSessionCacheKvKey("local", tokenHash), sessionDocument()]],
|
||||
kvReads,
|
||||
d1: testD1Database({ firstRows: [], queries: d1Queries, binds: d1Binds }),
|
||||
}),
|
||||
"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",
|
||||
["GET"],
|
||||
@@ -383,11 +412,22 @@ interface TestD1DatabaseOptions {
|
||||
}
|
||||
|
||||
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;
|
||||
return {
|
||||
prepare(query: string) {
|
||||
options.queries?.push(query);
|
||||
return testD1PreparedStatement(options, () => firstIndex++);
|
||||
return testD1PreparedStatement(configuredOptions, () => firstIndex++);
|
||||
},
|
||||
batch() {
|
||||
return Promise.resolve([]);
|
||||
|
||||
@@ -223,26 +223,34 @@ describe("device routes", () => {
|
||||
assert.equal(d1.binds[0]?.[7], 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(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 sessionCacheKey = authSessionCacheKvKey("local", tokenHash);
|
||||
const kvPuts: [string, string][] = [];
|
||||
const d1 = testD1Database([
|
||||
{
|
||||
device_id: "device-01",
|
||||
public_key: PUBLIC_KEY,
|
||||
device_name: "MacBook Pro",
|
||||
platform: "macOS",
|
||||
approval_status: "pending",
|
||||
created_at: 1_780_000_100,
|
||||
approved_at: null,
|
||||
last_active_at: 1_780_000_100,
|
||||
revoked_at: null,
|
||||
const deviceRow = {
|
||||
device_id: "device-01",
|
||||
public_key: PUBLIC_KEY,
|
||||
device_name: "MacBook Pro",
|
||||
platform: "macOS",
|
||||
approval_status: "pending",
|
||||
created_at: 1_780_000_100,
|
||||
approved_at: null,
|
||||
last_active_at: 1_780_000_100,
|
||||
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(
|
||||
new Request("https://elydora.test/api/devices/register", {
|
||||
@@ -262,7 +270,7 @@ describe("device routes", () => {
|
||||
|
||||
assert.equal(response.status, 201);
|
||||
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 () => {
|
||||
|
||||
@@ -24,6 +24,8 @@ export interface TestEnvOptions {
|
||||
}
|
||||
|
||||
export interface RecordedD1Database extends ElyD1Database {
|
||||
authBinds: unknown[][];
|
||||
authQueries: string[];
|
||||
batches: number[];
|
||||
binds: unknown[][];
|
||||
queries: string[];
|
||||
@@ -38,8 +40,16 @@ export interface RecordedR2Put {
|
||||
interface TestD1DatabaseOptions {
|
||||
allRows?: 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 {
|
||||
const values = new Map(options.kvEntries ?? []);
|
||||
return {
|
||||
@@ -92,19 +102,35 @@ export function testEnv(options: TestEnvOptions): Env {
|
||||
}
|
||||
|
||||
export function testD1Database(rows: unknown[] | TestD1DatabaseOptions): RecordedD1Database {
|
||||
const authBinds: unknown[][] = [];
|
||||
const authQueries: string[] = [];
|
||||
const binds: unknown[][] = [];
|
||||
const batches: number[] = [];
|
||||
const queries: string[] = [];
|
||||
const allRows = Array.isArray(rows) ? rows : rows.allRows ?? [];
|
||||
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;
|
||||
return {
|
||||
authBinds,
|
||||
authQueries,
|
||||
batches,
|
||||
binds,
|
||||
queries,
|
||||
prepare(query: string) {
|
||||
queries.push(query);
|
||||
return testD1PreparedStatement(allRows, firstRows, () => firstIndex++, binds);
|
||||
const isAuthSessionQuery = query.includes("FROM better_auth_session AS session");
|
||||
(isAuthSessionQuery ? authQueries : queries).push(query);
|
||||
return testD1PreparedStatement(
|
||||
allRows,
|
||||
firstRows,
|
||||
() => firstIndex++,
|
||||
isAuthSessionQuery ? authBinds : binds,
|
||||
isAuthSessionQuery,
|
||||
sessionRow,
|
||||
);
|
||||
},
|
||||
batch(statements: ElyD1PreparedStatement[]) {
|
||||
batches.push(statements.length);
|
||||
@@ -131,6 +157,8 @@ function testD1PreparedStatement(
|
||||
firstRows: unknown[],
|
||||
nextFirstIndex: () => number,
|
||||
binds: unknown[][],
|
||||
isAuthSessionQuery: boolean,
|
||||
sessionRow: unknown | null,
|
||||
): ElyD1PreparedStatement {
|
||||
return {
|
||||
bind(...values: unknown[]) {
|
||||
@@ -138,6 +166,9 @@ function testD1PreparedStatement(
|
||||
return this;
|
||||
},
|
||||
first<T>() {
|
||||
if (isAuthSessionQuery) {
|
||||
return Promise.resolve(sessionRow as T | null);
|
||||
}
|
||||
return Promise.resolve((firstRows[nextFirstIndex()] as T | undefined) ?? null);
|
||||
},
|
||||
all<T>() {
|
||||
|
||||
Reference in New Issue
Block a user