BlueGit

timfa filemanager

Files

filemanager / tests / auth.routes.test.js

auth.routes.test.js

import project
timfa Tim Falken · pushed by timfa · 6 months ago
d3c0b911 History
auth.routes.test.js 8.4 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 const { Database } = require('node-sqlite3-wasm');
16 let db;
17 function getDb() {
18 if (!db) {
19 db = new Database(':memory:');
20 db.exec(`
21 CREATE TABLE IF NOT EXISTS users (
22 id INTEGER PRIMARY KEY AUTOINCREMENT,
23 username TEXT UNIQUE NOT NULL,
24 password_hash TEXT NOT NULL,
25 is_admin INTEGER NOT NULL DEFAULT 0,
26 permissions TEXT NOT NULL DEFAULT '{}'
27 );
28 CREATE TABLE IF NOT EXISTS file_meta (
29 file_path TEXT PRIMARY KEY,
30 uploader TEXT NOT NULL DEFAULT '',
31 downloaders TEXT NOT NULL DEFAULT '[]'
32 );
33 `);
34 }
35 return db;
36 }
37 function initDb() { getDb(); }
38 return { getDb, initDb };
39});
40
41const { ensureServerKeys, getServerPublicKeyJwk, hybridEncryptForClient, hybridDecrypt } = require('../server/crypto');
42const authRoutes = require('../server/routes/auth');
43
44jest.setTimeout(30000);
45
46// ── build minimal app ──────────────────────────────────────────────────────
47
48let server;
49let baseUrl;
50
51beforeAll(async () => {
52 ensureServerKeys();
53 const app = express();
54 app.use(express.json());
55 app.use('/api/auth', authRoutes);
56 app.use((err, req, res, next) => {
57 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
58 });
59 server = http.createServer(app);
60 server.listen(0);
61 await once(server, 'listening');
62 const port = server.address().port;
63 baseUrl = `http://127.0.0.1:${port}`;
64});
65
66afterAll(() => server.close());
67
68// ── helpers ────────────────────────────────────────────────────────────────
69
70function get(path) {
71 return new Promise((resolve, reject) => {
72 http.get(baseUrl + path, res => {
73 let body = '';
74 res.on('data', d => body += d);
75 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
76 }).on('error', reject);
77 });
78}
79
80function post(path, data) {
81 const payload = JSON.stringify(data);
82 return new Promise((resolve, reject) => {
83 const req = http.request(baseUrl + path, {
84 method: 'POST',
85 headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) },
86 }, res => {
87 let body = '';
88 res.on('data', d => body += d);
89 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(body) }));
90 });
91 req.on('error', reject);
92 req.write(payload);
93 req.end();
94 });
95}
96
97/** Simulate the client-side hybrid encrypt targeting the server public key. */
98function clientEncrypt(obj) {
99 const jwk = getServerPublicKeyJwk();
100 const pubKey = crypto.createPublicKey({ key: jwk, format: 'jwk' });
101 const plain = JSON.stringify(obj);
102 const aesKey = crypto.randomBytes(32);
103 const iv = crypto.randomBytes(12);
104 const cipher = crypto.createCipheriv('aes-256-gcm', aesKey, iv);
105 const ct = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
106 const tag = cipher.getAuthTag();
107 const ek = crypto.publicEncrypt(
108 { key: pubKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
109 aesKey,
110 );
111 return {
112 encryptedKey: ek.toString('base64'),
113 iv: iv.toString('base64'),
114 ciphertext: ct.toString('base64'),
115 tag: tag.toString('base64'),
116 };
117}
118
119/** Generate a throwaway RSA key pair and return { privateKey, publicKeyJwk } */
120function makeClientKeyPair() {
121 const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
122 modulusLength: 2048,
123 publicKeyEncoding: { type: 'spki', format: 'pem' },
124 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
125 });
126 const publicKeyJwk = crypto.createPublicKey(publicKey).export({ format: 'jwk' });
127 return { privateKey, publicKeyJwk };
128}
129
130/** Decrypt the token the server sends back. */
131function clientDecrypt(payload, privateKey) {
132 const ek = Buffer.from(payload.encryptedKey, 'base64');
133 const iv = Buffer.from(payload.iv, 'base64');
134 const ct = Buffer.from(payload.ciphertext, 'base64');
135 const tg = Buffer.from(payload.tag, 'base64');
136 const rawAes = crypto.privateDecrypt(
137 { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
138 ek,
139 );
140 const decipher = crypto.createDecipheriv('aes-256-gcm', rawAes, iv);
141 decipher.setAuthTag(tg);
142 return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8');
143}
144
145// ── tests ──────────────────────────────────────────────────────────────────
146
147describe('GET /api/auth/server-key', () => {
148 test('returns a JWK public key', async () => {
149 const { status, body } = await get('/api/auth/server-key');
150 expect(status).toBe(200);
151 expect(body.publicKey).toMatchObject({ kty: 'RSA', n: expect.any(String) });
152 });
153});
154
155describe('GET /api/auth/setup-needed', () => {
156 test('returns needed=true when no users exist', async () => {
157 const { status, body } = await get('/api/auth/setup-needed');
158 expect(status).toBe(200);
159 expect(body.needed).toBe(true);
160 });
161});
162
163describe('POST /api/auth/setup', () => {
164 let kp;
165
166 beforeAll(() => { kp = makeClientKeyPair(); });
167
168 test('rejects weak password', async () => {
169 const encrypted = clientEncrypt({ username: 'admin', password: 'short' });
170 const { status, body } = await post('/api/auth/setup', {
171 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
172 });
173 expect(status).toBe(400);
174 });
175
176 test('creates admin and returns encrypted token', async () => {
177 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
178 const { status, body } = await post('/api/auth/setup', {
179 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
180 });
181 expect(status).toBe(200);
182 expect(body.encrypted).toMatchObject({
183 encryptedKey: expect.any(String),
184 iv: expect.any(String),
185 ciphertext: expect.any(String),
186 tag: expect.any(String),
187 });
188
189 // Token should be a valid JWT string
190 const token = clientDecrypt(body.encrypted, kp.privateKey);
191 expect(token.split('.').length).toBe(3);
192 });
193
194 test('setup-needed is now false', async () => {
195 const { body } = await get('/api/auth/setup-needed');
196 expect(body.needed).toBe(false);
197 });
198
199 test('cannot run setup again once a user exists', async () => {
200 const kp2 = makeClientKeyPair();
201 const encrypted = clientEncrypt({ username: 'hacker', password: 'hackpass1' });
202 const { status } = await post('/api/auth/setup', {
203 encrypted, clientPublicKey: kp2.publicKeyJwk, fingerprint: 'test',
204 });
205 expect(status).toBe(403);
206 });
207});
208
209describe('POST /api/auth/login', () => {
210 let kp;
211 beforeAll(() => { kp = makeClientKeyPair(); });
212
213 test('rejects wrong password', async () => {
214 const encrypted = clientEncrypt({ username: 'admin', password: 'wrongpass' });
215 const { status } = await post('/api/auth/login', {
216 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
217 });
218 expect(status).toBe(401);
219 });
220
221 test('returns encrypted token on correct credentials', async () => {
222 const encrypted = clientEncrypt({ username: 'admin', password: 'adminpass1' });
223 const { status, body } = await post('/api/auth/login', {
224 encrypted, clientPublicKey: kp.publicKeyJwk, fingerprint: 'test',
225 });
226 expect(status).toBe(200);
227 const token = clientDecrypt(body.encrypted, kp.privateKey);
228 expect(token.split('.').length).toBe(3);
229 });
230
231 test('rejects invalid encrypted payload', async () => {
232 const { status } = await post('/api/auth/login', {
233 encrypted: { encryptedKey: 'bad', iv: 'bad', ciphertext: 'bad', tag: 'bad' },
234 clientPublicKey: kp.publicKeyJwk,
235 fingerprint: 'test',
236 });
237 expect(status).toBe(400);
238 });
239});