Repository navigation
Expand file tree
/
Copy pathauth-audit.test.ts
More file actions
318 lines (281 loc) · 12.4 KB
/
Copy pathauth-audit.test.ts
File metadata and controls
318 lines (281 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
import { AuthConfigError } from "@/lib/auth-errors";
/**
* Threat: an authentication event that leaves no trace.
*
* Every way into and out of a session must produce exactly one audit record with a reason drawn
* from the closed union. The logout record in particular must carry the identity that was
* destroyed, which is only possible if getSession() runs BEFORE logout() clears the cookie.
*/
const mockGetSession = mock(
async (): Promise<{ role: string; username: string } | null> => ({ role: "admin", username: "admin@libredb.org" }),
);
const mockLogout = mock(async () => {});
const mockLogin = mock(async () => {});
mock.module("@/lib/auth", () => ({
getSession: mockGetSession,
readSession: mock(async () => {
const s = await mockGetSession();
return s ? { kind: "authenticated", session: s } : { kind: "anonymous" };
}),
logout: mockLogout,
login: mockLogin,
shouldMarkCookieSecure: mock(async () => false),
signJWT: mock(async () => "mock-token"),
verifyJWT: mock(async () => null),
}));
const mockDecryptState = mock(async () => ({
code_verifier: "verifier",
state: "state",
nonce: "nonce",
}));
/** An ID token's claims as openid-client hands them over: `iss` and `sub` are always there. */
const ID_TOKEN_CLAIMS = { iss: "https://example.auth0.com", sub: "user-123", email: "user@example.com" };
const mockExchangeCode = mock(
async () => ({ claims: { ...ID_TOKEN_CLAIMS }, idToken: "raw.id.token" }) as Record<string, unknown> | null,
);
const mockDiscoverProvider = mock(async () => "mock-config");
const mockGetOIDCConfig = mock(() => ({ roleClaim: "roles", adminRoles: ["admin"] }));
mock.module("@/lib/oidc", () => ({
getOIDCConfig: mockGetOIDCConfig,
discoverProvider: mockDiscoverProvider,
generateAuthUrl: mock(async () => ({})),
encryptState: mock(async () => ""),
decryptState: mockDecryptState,
exchangeCode: mockExchangeCode,
mapOIDCRole: mock(() => "user" as "admin" | "user"),
readRoleClaimValues: mock(() => []),
mapOIDCClaimRoles: mock(() => ({ roles: [], overflow: false })),
resetDiscoveryCache: mock(() => {}),
buildLogoutUrl: mock(async () => null as string | null),
getPublicOrigin: mock((req: Request) => new URL(req.url).origin),
}));
const cookieStore = {
get: mock((name: string) => (name === "oidc-state" ? { name, value: "state-cookie" } : undefined)),
set: mock(() => {}),
delete: mock(() => {}),
};
mock.module("next/headers", () => ({
cookies: mock(async () => cookieStore),
headers: mock(async () => new Headers()),
}));
const { POST: logoutRoute } = await import("@/app/api/auth/logout/route");
const { GET: oidcCallback } = await import("@/app/api/auth/oidc/callback/route");
function auditLines(spy: ReturnType<typeof spyOn>): Record<string, unknown>[] {
return spy.mock.calls.map((call: unknown[]) => JSON.parse(call[0] as string) as Record<string, unknown>);
}
function callbackRequest(): Request {
return new Request("http://localhost:3000/api/auth/oidc/callback?code=abc&state=state");
}
beforeEach(() => {
mockGetSession.mockImplementation(async () => ({ role: "admin", username: "admin@libredb.org" }));
mockLogout.mockClear();
cookieStore.get.mockImplementation((name: string) =>
name === "oidc-state" ? { name, value: "state-cookie" } : undefined,
);
mockDecryptState.mockImplementation(async () => ({ code_verifier: "v", state: "s", nonce: "n" }));
mockExchangeCode.mockImplementation(async () => ({ claims: { ...ID_TOKEN_CLAIMS }, idToken: "raw.id.token" }));
mockDiscoverProvider.mockImplementation(async () => "mock-config");
});
describe("logout", () => {
test("records the identity that was destroyed, not an anonymous one", async () => {
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await logoutRoute(new Request("http://localhost:3000/api/auth/logout", { method: "POST" }) as never);
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].event).toBe("logout");
expect(lines[0].actor).toBe("admin@libredb.org");
expect(lines[0].outcome).toBe("success");
expect(mockLogout).toHaveBeenCalledTimes(1);
} finally {
spy.mockRestore();
}
});
test("does not emit an audit line when there was no session to destroy", async () => {
// No session means no state transition occurred. "anonymous logged out" would be noise, and
// this route is public and unrated-limited, so recording it would let an unauthenticated
// caller flood the audit trail (and the admin UI's 1000-entry ring buffer) for free.
mockGetSession.mockImplementation(async () => null);
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await logoutRoute(new Request("http://localhost:3000/api/auth/logout", { method: "POST" }) as never);
expect(auditLines(spy)).toHaveLength(0);
} finally {
spy.mockRestore();
}
});
test("emits no audit line when logout() throws, even though a session existed", async () => {
// The property this task is named for: a failure between reading the identity and destroying
// the session must never produce a line asserting a logout that did not happen.
mockLogout.mockImplementationOnce(async () => {
throw new Error("cookie store unavailable");
});
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await logoutRoute(new Request("http://localhost:3000/api/auth/logout", { method: "POST" }) as never);
expect(auditLines(spy)).toHaveLength(0);
} finally {
spy.mockRestore();
}
});
test("does not fail the logout response when the audit emit itself throws", async () => {
// The emit is isolated in its own try/catch, separate from logout() above: an audit failure
// must never change the outcome of the logout it is recording.
const spy = spyOn(console, "log").mockImplementation(() => {
throw new Error("audit sink unavailable");
});
try {
const response = await logoutRoute(
new Request("http://localhost:3000/api/auth/logout", { method: "POST" }) as never,
);
expect(response.status).toBe(200);
} finally {
spy.mockRestore();
}
});
});
describe("the OIDC callback", () => {
test("records a successful federated login", async () => {
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].event).toBe("login_success");
expect(lines[0].actor).toBe("user@example.com");
expect(lines[0].route).toBe("GET /api/auth/oidc/callback");
} finally {
spy.mockRestore();
}
});
test("records a missing state cookie", async () => {
cookieStore.get.mockImplementation(() => undefined);
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].event).toBe("login_failure");
expect(lines[0].reason).toBe("oidc_state_missing");
expect(lines[0].actor).toBe("anonymous");
} finally {
spy.mockRestore();
}
});
test("records an undecryptable state cookie", async () => {
mockDecryptState.mockImplementation(async () => {
throw new Error("bad state");
});
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].reason).toBe("oidc_state_invalid");
} finally {
spy.mockRestore();
}
});
test("records a token exchange that returned no claims", async () => {
mockExchangeCode.mockImplementation(async () => null);
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].reason).toBe("oidc_no_claims");
} finally {
spy.mockRestore();
}
});
test("records a provider failure without leaking the error text", async () => {
mockDiscoverProvider.mockImplementation(async () => {
throw new Error("connect ECONNREFUSED 10.0.0.1:443 while reaching https://idp/.well-known");
});
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].reason).toBe("oidc_failed");
// The reason is a closed union, which is exactly why no driver string can reach the record.
expect(JSON.stringify(lines[0])).not.toContain("ECONNREFUSED");
expect(JSON.stringify(lines[0])).not.toContain("10.0.0.1");
} finally {
spy.mockRestore();
}
});
test("records a configuration failure with its own reason", async () => {
// A real AuthConfigError, not a plain Error whose message happens to contain "config": the
// classification in the route is `instanceof AuthConfigError`, not a message substring match,
// so this message deliberately does NOT contain the word "config" - a regression back to
// substring matching would make this specific message fail the assertion below while an
// instanceof check keeps passing it. The reverse case - a plain Error, classified oidc_failed
// regardless of its text - is already pinned above by "records a provider failure without
// leaking the error text".
mockDiscoverProvider.mockImplementation(async () => {
throw new AuthConfigError("JWT_SECRET is required for OIDC state encryption");
});
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
await oidcCallback(callbackRequest());
const lines = auditLines(spy);
expect(lines).toHaveLength(1);
expect(lines[0].reason).toBe("oidc_config");
} finally {
spy.mockRestore();
}
});
test("does not leak the authorization code or an access token when the exchange fails", async () => {
const authorizationCode = "SplxlOBeZQQYbYS6WxSbIA";
const accessToken = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U";
mockExchangeCode.mockImplementation(async () => {
throw new Error(`token exchange failed for code ${authorizationCode} with access_token ${accessToken}`);
});
const spy = spyOn(console, "log").mockImplementation(() => {});
try {
const request = new Request(`http://localhost:3000/api/auth/oidc/callback?code=${authorizationCode}&state=state`);
await oidcCallback(request);
const lines = auditLines(spy);
const emitted = JSON.stringify(lines[0]);
expect(lines).toHaveLength(1);
expect(lines[0].event).toBe("login_failure");
expect(lines[0].reason).toBe("oidc_failed");
expect(emitted).not.toContain(authorizationCode);
expect(emitted).not.toContain(accessToken);
expect(emitted).not.toContain("access_token");
} finally {
spy.mockRestore();
}
});
test("still redirects to the app when the success audit emit throws", async () => {
// The emit is isolated in its own try/catch, separate from login() above: a real session
// already exists by this point, so an audit failure must never turn a successful login into a
// recorded (or outer-catch-driven) login_failure, nor into an error redirect.
const spy = spyOn(console, "log").mockImplementation(() => {
throw new Error("audit sink unavailable");
});
try {
const response = await oidcCallback(callbackRequest());
expect(response.status).toBe(307);
expect(response.headers.get("location")).not.toContain("error=");
} finally {
spy.mockRestore();
}
});
test("still redirects with the original failure reason when the audit emit throws", async () => {
// auditFailure() swallows its own throw. Without that isolation, the outer catch would
// reclassify this as oidc_failed instead of the true oidc_state_missing.
cookieStore.get.mockImplementation(() => undefined);
const spy = spyOn(console, "log").mockImplementation(() => {
throw new Error("audit sink unavailable");
});
try {
const response = await oidcCallback(callbackRequest());
expect(response.headers.get("location")).toContain("error=oidc_state_missing");
} finally {
spy.mockRestore();
}
});
});