BlueGit

timfa filemanager

Files

filemanager / tests / auth.routes.test.js

auth.routes.test.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
auth.routes.test.js 11.0 KiB Download Raw
1'use strict';
2
3/**
4 * Integration tests for the auth routes.
5 * Spins up an in-memory Express app with a fresh in-memory SQLite database.
6 */
7
8const express = require('express');
9const { once } = require('events');
10const http = require('http');
11const crypto = require('crypto');
12
13// ── patch DB to use in-memory database before requiring routes ──────────────
14jest.mock('../server/db', () =>
15{
16 const { Database } = require('node-sqlite3-wasm');
17 let db;
18 function getDb ()
19 {
20 if (!db)
21 {
22 db = new Database(':memory:');
23 db.exec(`
24 CREATE TABLE IF NOT EXISTS users (
25 id INTEGER PRIMARY KEY AUTOINCREMENT,
26 username TEXT UNIQUE NOT NULL,
27 password_hash TEXT NOT NULL,
28 is_admin INTEGER NOT NULL DEFAULT 0,
29 permissions TEXT NOT NULL DEFAULT '{}'
30 );
31 CREATE TABLE IF NOT EXISTS file_meta (
32 file_path TEXT PRIMARY KEY,
33 uploader TEXT NOT NULL DEFAULT '',
34 downloaders TEXT NOT NULL DEFAULT '[]'
35 );
36 CREATE TABLE IF NOT EXISTS auth_sessions (
37 session_id TEXT PRIMARY KEY,
38 username TEXT NOT NULL,
39 ip TEXT NOT NULL,
40 region TEXT NOT NULL,
41 fp_hash TEXT NOT NULL,
42 created_at INTEGER NOT NULL,
43 last_seen_at INTEGER NOT NULL,
44 revoked_at INTEGER
45 );
46 `);
47 }
48 return db;
49 }
50 function initDb () { getDb(); }
51 return { getDb, initDb };
52});
53
54const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
55const { SESSION_IDLE_TIMEOUT_MS } = require('../server/auth');
56const authRoutes = require('../server/routes/auth');
57
58jest.setTimeout(30000);
59
60// ── build minimal app ──────────────────────────────────────────────────────
61
62let server;
63let baseUrl;
64
65beforeAll(async () =>
66{
67 ensureServerKeys();
68 const app = express();
69 app.use(express.json());
70 app.use('/api/auth', authRoutes);
71 app.use((err, req, res, next) =>
72 {
73 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
74 });
75 server = http.createServer(app);
76 server.listen(0);
77 await once(server, 'listening');
78 const port = server.address().port;
79 baseUrl = `http://127.0.0.1:${port}`;
80});
81
82afterAll(() => server.close());
83
84// ── helpers ────────────────────────────────────────────────────────────────
85
86function get (path)
87{
88 return new Promise((resolve, reject) =>
89 {
90 http.get(baseUrl + path, res =>
91 {
92 let body = '';
93 res.on('data', d => body += d);
94 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
95 }).on('error', reject);
96 });
97}
98
99function post (path, data)
100{
101 const payload = JSON.stringify(data);
102 return new Promise((resolve, reject) =>
103 {
104 const req = http.request(baseUrl + path, {
105 method: 'POST',
106 headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
107 }, res =>
108 {
109 let body = '';
110 res.on('data', d => body += d);
111 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
112 });
113 req.on('error', reject);
114 req.write(payload);
115 req.end();
116 });
117}
118
119function authed (method, path, token, fingerprint, data)
120{
121 const payload = data ? JSON.stringify(data) : undefined;
122 return new Promise((resolve, reject) =>
123 {
124 const req = http.request(baseUrl + path, {
125 method,
126 headers: {
127 Authorization: `Bearer ${token}`,
128 'X-Fp': fingerprint,
129 'Content-Type': 'application/json',
130 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
131 },
132 }, res =>
133 {
134 let body = '';
135 res.on('data', d => body += d);
136 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
137 });
138 req.on('error', reject);
139 if (payload) req.write(payload);
140 req.end();
141 });
142}
143
144/** Simulate the client-side hybrid encrypt targeting the server public key. */
145function clientEncrypt (obj)
146{
147 const jwk = getServerPublicKeyJwk();
148 const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
149 const plain = JSON.stringify(obj);
150 const aesKey = crypto.randomBytes(32);
151 const iv = crypto.randomBytes(12);
152 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
153 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
154 const tag = cipher.getAuthTag();
155 const ek = crypto.publicEncrypt(
156 { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
157 aesKey,
158 );
159 return {
160 encryptedKey: ek.toString('base64'),
161 iv: iv.toString('base64'),
162 ciphertext: ct.toString('base64'),
163 tag: tag.toString('base64'),
164 };
165}
166
167/** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */
168function makeClientKeyPair ()
169{
170 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
171 modulusLength: 2048,
172 publicKeyEncoding: { type: 'spki', format: 'pem' },
173 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
174 });
175 const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
176 return { privateKey, publicKeyJwk };
177}
178
179/** Decrypt the token the server sends back. */
180function clientDecrypt (payload, privateKey)
181{
182 const ek = Buffer.from(payload.encryptedKey, 'base64');
183 const iv = Buffer.from(payload.iv, 'base64');
184 const ct = Buffer.from(payload.ciphertext, 'base64');
185 const tg = Buffer.from(payload.tag, 'base64');
186 const rawAes = crypto.privateDecrypt(
187 { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
188 ek,
189 );
190 const decipher = crypto.createDecipheriv('aes-256-gcm', rawAes, iv);
191 decipher.setAuthTag(tg);
192 return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8');
193}
194
195// ── tests ──────────────────────────────────────────────────────────────────
196
197describe('GET /api/auth/server-key', () =>
198{
199 test('returns a JWK public key', async () =>
200 {
201 const { status, body } = await get('/api/auth/server-key');
202 expect(status).toBe(200);
203 expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) });
204 });
205});
206
207describe('GET /api/auth/setup-needed', () =>
208{
209 test('returns needed=true when no users exist', async () =>
210 {
211 const { status, body } = await get('/api/auth/setup-needed');
212 expect(status).toBe(200);
213 expect(body.needed).toBe(true);
214 });
215});
216
217describe('POST /api/auth/setup', () =>
218{
219 let kp;
220
221 beforeAll(() => { kp = makeClientKeyPair(); });
222
223 test('rejects weak password', async () =>
224 {
225 const encrypted = clientEncrypt({ username: 'admin', password: 'short' });
226 const { status, body } = await post('/api/auth/setup', {
227 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
228 });
229 expect(status).toBe(400);
230 });
231
232 test('creates admin and returns encrypted token', async () =>
233 {
234 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
235 const { status, body } = await post('/api/auth/setup', {
236 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
237 });
238 expect(status).toBe(200);
239 expect(body.encrypted).toMatchObject({
240 encryptedKey: expect.any(String),
241 iv: expect.any(String),
242 ciphertext: expect.any(String),
243 tag: expect.any(String),
244 });
245
246 // Token should be a valid JWT string
247 const token = clientDecrypt(body.encrypted, kp.privateKey);
248 expect(token.split('.').length).toBe(3);
249 });
250
251 test('setup-needed is now false', async () =>
252 {
253 const { body } = await get('/api/auth/setup-needed');
254 expect(body.needed).toBe(false);
255 });
256
257 test('cannot run setup again once a user exists', async () =>
258 {
259 const kp2 = makeClientKeyPair();
260 const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' });
261 const { status } = await post('/api/auth/setup', {
262 encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test',
263 });
264 expect(status).toBe(403);
265 });
266});
267
268describe('POST /api/auth/login', () =>
269{
270 let kp;
271 beforeAll(() => { kp = makeClientKeyPair(); });
272
273 test('rejects wrong password', async () =>
274 {
275 const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' });
276 const { status } = await post('/api/auth/login', {
277 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
278 });
279 expect(status).toBe(401);
280 });
281
282 test('returns encrypted token on correct credentials', async () =>
283 {
284 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
285 const { status, body } = await post('/api/auth/login', {
286 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
287 });
288 expect(status).toBe(200);
289 const token = clientDecrypt(body.encrypted, kp.privateKey);
290 expect(token.split('.').length).toBe(3);
291 });
292
293 test('rejects invalid encrypted payload', async () =>
294 {
295 const { status } = await post('/api/auth/login', {
296 encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' },
297 clientPublicKey: kp.publicKeyJwk,
298 fingerprint: 'test',
299 });
300 expect(status).toBe(400);
301 });
302});
303
304describe('session lifecycle', () =>
305{
306 const fingerprint = 'test';
307
308 async function loginAndGetToken ()
309 {
310 const kp = makeClientKeyPair();
311 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
312 const { status, body } = await post('/api/auth/login', {
313 encrypted,
314 clientPublicKey: kp.publicKeyJwk,
315 fingerprint,
316 });
317 expect(status).toBe(200);
318 return clientDecrypt(body.encrypted, kp.privateKey);
319 }
320
321 test('POST /api/auth/logout revokes active session', async () =>
322 {
323 const token = await loginAndGetToken();
324
325 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
326 expect(meBefore.status).toBe(200);
327
328 const logout = await authed('POST', '/api/auth/logout', token, fingerprint, {});
329 expect(logout.status).toBe(200);
330 expect(logout.body.ok).toBe(true);
331
332 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
333 expect(meAfter.status).toBe(401);
334 });
335
336 test('session expires after 1 hour of inactivity', async () =>
337 {
338 const token = await loginAndGetToken();
339
340 const meBefore = await authed('GET', '/api/auth/me', token, fingerprint);
341 expect(meBefore.status).toBe(200);
342
343 const realNow = Date.now;
344 try
345 {
346 const jumped = realNow() + SESSION_IDLE_TIMEOUT_MS + 1000;
347 Date.now = jest.fn(() => jumped);
348
349 const meAfter = await authed('GET', '/api/auth/me', token, fingerprint);
350 expect(meAfter.status).toBe(401);
351 } finally
352 {
353 Date.now = realNow;
354 }
355 });
356});