{{ message }}
Repository navigation
Expand file tree
/
Copy pathauth-phase2-hardening.test.ts
More file actions
292 lines (245 loc) · 11.6 KB
/
Copy pathauth-phase2-hardening.test.ts
File metadata and controls
292 lines (245 loc) · 11.6 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
// SPDX-License-Identifier: AGPL-3.0-or-later
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import assert from "node:assert";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import request from "supertest";
process.env["NODE_ENV"] = "test";
import { createApp } from "../src/app.js";
import { LibraryDatabase } from "../src/database.js";
import { JWT_SECRET } from "../src/middleware/auth-middleware.js";
import { defaultLoginLimiter } from "../src/middleware/login-limiter.js";
import { defaultMailer } from "../src/services/mailer.js";
import { LibraryStorage } from "../src/storage.js";
test("Phase 2 Security & Hardening Integration Suite", async (t) => {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "phase2-auth-test-"));
const db = new LibraryDatabase(path.join(tmpDir, "db"));
const storage = new LibraryStorage(path.join(tmpDir, "storage"));
const app = createApp({ database: db, storage });
t.after(() => {
try {
db.db.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
} catch {
// ignore
}
});
await t.test("Task 2.1: Self-Service Password Reset Flow", async () => {
defaultMailer.clearSentMails();
// Create a verified active user
const initialHash = await bcrypt.hash("InitialPass123!", 10);
const user = db.createUser("alice_reset", "alice.reset@example.com", initialHash, {
emailVerified: true,
status: "active",
});
// 1. Request password reset via forgot-password
const forgotRes = await request(app)
.post("/api/v1/auth/forgot-password")
.send({ email: "alice.reset@example.com" });
assert.strictEqual(forgotRes.status, 200);
assert.strictEqual(forgotRes.body.success, true);
assert.ok(forgotRes.body.resetToken, "Test environment provides resetToken in payload");
const resetToken = forgotRes.body.resetToken;
// Small delay to ensure email service processed
await new Promise((r) => setTimeout(r, 50));
const sentMails = defaultMailer.getSentMails();
assert.ok(sentMails.length > 0);
assert.ok(
sentMails.some(
(m) => m.to === "alice.reset@example.com" && m.subject.includes("Reset your ModelScript password"),
),
);
// 2. Reject short password
const shortRes = await request(app)
.post("/api/v1/auth/reset-password")
.send({ token: resetToken, newPassword: "short" });
assert.strictEqual(shortRes.status, 400);
// 3. Successfully reset password
const resetRes = await request(app)
.post("/api/v1/auth/reset-password")
.send({ token: resetToken, newPassword: "BrandNewSecurePassword123!" });
assert.strictEqual(resetRes.status, 200);
assert.strictEqual(resetRes.body.success, true);
// 4. Token cannot be reused (instant revocation / single-use check)
const reuseRes = await request(app)
.post("/api/v1/auth/reset-password")
.send({ token: resetToken, newPassword: "AnotherNewPassword123!" });
assert.strictEqual(reuseRes.status, 400);
// 5. Can login with new password
const loginRes = await request(app)
.post("/api/v1/auth/login")
.send({ email: "alice.reset@example.com", password: "BrandNewSecurePassword123!" });
assert.strictEqual(loginRes.status, 200);
assert.ok(loginRes.body.token);
// Old password fails
const oldLoginRes = await request(app)
.post("/api/v1/auth/login")
.send({ email: "alice.reset@example.com", password: "InitialPass123!" });
assert.strictEqual(oldLoginRes.status, 401);
});
await t.test("Task 2.2: Login Brute-Force Rate Limiting & User Enumeration Defense", async () => {
const testIp = "192.168.10.55";
const testEmail = "victim@example.com";
defaultLoginLimiter.reset(testIp, testEmail);
// Make 5 failed attempts
for (let i = 0; i < 5; i++) {
const res = await request(app)
.post("/api/v1/auth/login")
.set("X-Forwarded-For", testIp)
.send({ email: testEmail, password: `WrongPassword${i}` });
assert.strictEqual(res.status, 401);
}
// 6th attempt should be blocked by rate limiter with 429
const blockedRes = await request(app)
.post("/api/v1/auth/login")
.set("X-Forwarded-For", testIp)
.send({ email: testEmail, password: "AnyPassword" });
assert.strictEqual(blockedRes.status, 429);
assert.ok(blockedRes.body.error.includes("Too many failed login attempts"));
assert.ok(blockedRes.body.retryAfterSeconds > 0);
// Test bypass header works
const bypassedRes = await request(app)
.post("/api/v1/auth/login")
.set("X-Forwarded-For", testIp)
.set("X-Test-Bypass-Rate-Limit", "true")
.send({ email: testEmail, password: "WrongPassword" });
assert.strictEqual(bypassedRes.status, 401);
// Clean up rate limiter
defaultLoginLimiter.reset();
});
await t.test("Task 2.2: OAuth account without password hash handles login attempt safely", async () => {
// Create an OAuth user with NULL password hash
const oauthUser = db.createOAuthUser("oauth_bob", "oauth.bob@example.com", "github", "gh_99999");
assert.ok(oauthUser);
const res = await request(app)
.post("/api/v1/auth/login")
.set("X-Test-Bypass-Rate-Limit", "true")
.send({ email: "oauth.bob@example.com", password: "SomeRandomPassword!" });
// Must return standard 401 without throwing error or crashing
assert.strictEqual(res.status, 401);
assert.strictEqual(res.body.error, "Invalid email or password");
});
await t.test("Task 2.3: Session Invalidation on Password Change and Revocation", async () => {
const passwordHash = await bcrypt.hash("OldPassSecret123!", 10);
const user = db.createUser("session_user", "session.user@example.com", passwordHash, {
emailVerified: true,
status: "active",
});
// Login and obtain initial JWT session
const loginRes = await request(app)
.post("/api/v1/auth/login")
.set("X-Test-Bypass-Rate-Limit", "true")
.send({ email: "session.user@example.com", password: "OldPassSecret123!" });
assert.strictEqual(loginRes.status, 200);
const originalToken = loginRes.body.token;
// Verify original token works on authenticated route
const meRes = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${originalToken}`);
assert.strictEqual(meRes.status, 200);
// Change password via PUT /api/v1/auth/password
const changePassRes = await request(app)
.put("/api/v1/auth/password")
.set("Authorization", `Bearer ${originalToken}`)
.send({ oldPassword: "OldPassSecret123!", newPassword: "UpdatedPassSecret456!" });
assert.strictEqual(changePassRes.status, 200);
assert.ok(changePassRes.body.token, "Returns refreshed session token");
const newToken = changePassRes.body.token;
// Original token should now be rejected as revoked (token_version mismatch)
const revokedCheckRes = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${originalToken}`);
assert.strictEqual(revokedCheckRes.status, 401);
assert.ok(revokedCheckRes.body.error.includes("Session has expired or was revoked"));
// New token works
const newMeRes = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${newToken}`);
assert.strictEqual(newMeRes.status, 200);
// Explicit revoke-sessions endpoint test
const revokeRes = await request(app)
.post("/api/v1/auth/revoke-sessions")
.set("Authorization", `Bearer ${newToken}`);
assert.strictEqual(revokeRes.status, 200);
assert.ok(revokeRes.body.token);
// newToken is now revoked
const afterRevokeCheck = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${newToken}`);
assert.strictEqual(afterRevokeCheck.status, 401);
});
await t.test("Task 2.3: Suspended / Frozen accounts are rejected with 403", async () => {
const passwordHash = await bcrypt.hash("ActivePass123!", 10);
const user = db.createUser("suspended_user", "suspended@example.com", passwordHash, {
emailVerified: true,
status: "active",
});
const loginRes = await request(app)
.post("/api/v1/auth/login")
.set("X-Test-Bypass-Rate-Limit", "true")
.send({ email: "suspended@example.com", password: "ActivePass123!" });
assert.strictEqual(loginRes.status, 200);
const token = loginRes.body.token;
// Suspend user in DB
db.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(user.id);
// Request with valid token should now be blocked with 403
const blockedRes = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${token}`);
assert.strictEqual(blockedRes.status, 403);
assert.ok(blockedRes.body.error.includes("suspended"));
// Login attempt should also be blocked with 403
const loginBlocked = await request(app)
.post("/api/v1/auth/login")
.set("X-Test-Bypass-Rate-Limit", "true")
.send({ email: "suspended@example.com", password: "ActivePass123!" });
assert.strictEqual(loginBlocked.status, 403);
});
await t.test(
"Task 2.4: OAuth user profile updates and initial password setting without current password",
async () => {
// Create an OAuth user (password_hash is NULL)
const oauthUser = db.createOAuthUser("oauth_carol", "carol.oauth@example.com", "github", "gh_carol_42");
const fullUser = db.getUserById(oauthUser.id)!;
// Generate JWT for this specific OAuth user
const token = jwt.sign(
{
id: fullUser.id,
username: fullUser.username,
email: fullUser.email,
tokenVersion: fullUser.token_version ?? 1,
},
JWT_SECRET,
{ expiresIn: "7d" },
);
// 1. Fetch /me: has_password should be false for OAuth user without password
const meRes = await request(app).get("/api/v1/auth/me").set("Authorization", `Bearer ${token}`);
assert.strictEqual(meRes.status, 200);
assert.strictEqual(meRes.body.user.has_password, false);
// 2. Update profile without password
const updateRes = await request(app).put("/api/v1/auth/account").set("Authorization", `Bearer ${token}`).send({
display_name: "Carol The Modeler",
bio: "Physical systems enthusiast",
avatar_url: "https://example.com/carol.png",
});
assert.strictEqual(updateRes.status, 200);
assert.strictEqual(updateRes.body.success, true);
const updatedUser = db.getUserById(fullUser.id)!;
assert.strictEqual(updatedUser.display_name, "Carol The Modeler");
assert.strictEqual(updatedUser.avatar_url, "https://example.com/carol.png");
// 3. Set password for the first time without oldPassword
const setPassRes = await request(app)
.put("/api/v1/auth/password")
.set("Authorization", `Bearer ${token}`)
.send({ newPassword: "CarolBrandNewPassword123!" });
assert.strictEqual(setPassRes.status, 200);
assert.strictEqual(setPassRes.body.success, true);
assert.ok(setPassRes.body.token);
// Now has_password should be true
const meAfterPass = await request(app)
.get("/api/v1/auth/me")
.set("Authorization", `Bearer ${setPassRes.body.token}`);
assert.strictEqual(meAfterPass.status, 200);
assert.strictEqual(meAfterPass.body.user.has_password, true);
// Subsequent password change now DOES require old password
const failChangeWithoutOld = await request(app)
.put("/api/v1/auth/password")
.set("Authorization", `Bearer ${setPassRes.body.token}`)
.send({ newPassword: "YetAnotherPassword123!" });
assert.strictEqual(failChangeWithoutOld.status, 400);
},
);
});
You can’t perform that action at this time.
