BlueGit

timfa filemanager

Files

filemanager / tests / admin.routes.test.js

admin.routes.test.js

block mobile
timfa Tim Falken · pushed by timfa · 6 months ago
4a4ba9a7 History
admin.routes.test.js 8.8 KiB Download Raw
1'use strict';
2
3/**
4 * Unit tests for server/routes/admin.js — user CRUD and config management.
5 */
6
7const express = require('express');
8const http = require('http');
9const { once } = require('events');
10const crypto = require('crypto');
11
12// ── in-memory DB mock ───────────────────────────────────────────────────────
13jest.mock('../server/db', () =>
14{
15 const { Database } = require('node-sqlite3-wasm');
16 let db;
17 function getDb ()
18 {
19 if (!db)
20 {
21 db = new Database(':memory:');
22 db.exec(`
23 CREATE TABLE IF NOT EXISTS users (
24 id INTEGER PRIMARY KEY AUTOINCREMENT,
25 username TEXT UNIQUE NOT NULL,
26 password_hash TEXT NOT NULL,
27 is_admin INTEGER NOT NULL DEFAULT 0,
28 permissions TEXT NOT NULL DEFAULT '{}'
29 );
30 CREATE TABLE IF NOT EXISTS file_meta (
31 file_path TEXT PRIMARY KEY,
32 uploader TEXT NOT NULL DEFAULT '',
33 downloaders TEXT NOT NULL DEFAULT '[]'
34 );
35 `);
36 }
37 return db;
38 }
39 return { getDb, initDb: getDb };
40});
41
42// ── config mock ─────────────────────────────────────────────────────────────
43const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] };
44jest.mock('../server/config', () => ({
45 loadConfig: () => ({ ...mockConfig }),
46 saveConfig: (c) => Object.assign(mockConfig, c),
47 getEffectivePaths: (p) => p,
48 getAllowedRoot: () => null,
49}));
50
51// ── auth mock — bypass JWT verification ─────────────────────────────────────
52let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} };
53jest.mock('../server/auth', () => ({
54 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
55 requireAdmin: (req, res, next) =>
56 {
57 if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' });
58 next();
59 },
60 createToken: () => 'mock-token',
61 getClientIp: () => '127.0.0.1',
62 getRegion: () => 'US:CA',
63}));
64
65const adminRoutes = require('../server/routes/admin');
66const { getDb } = require('../server/db');
67const bcrypt = require('bcrypt');
68
69jest.setTimeout(30000);
70
71// ── seed a default admin before anything runs ────────────────────────────────
72beforeAll(() =>
73{
74 const db = getDb();
75 const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed
76 db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)')
77 .run(['admin', hash, '{}']);
78});
79
80// ── build minimal app ────────────────────────────────────────────────────────
81let server;
82let baseUrl;
83let shutdownForRestartMock;
84
85beforeAll(async () =>
86{
87 const app = express();
88 shutdownForRestartMock = jest.fn();
89 app.set('shutdownForRestart', shutdownForRestartMock);
90 app.use(express.json());
91 app.use('/api/admin', adminRoutes);
92 app.use((err, req, res, next) =>
93 {
94 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
95 });
96 server = http.createServer(app);
97 server.listen(0);
98 await once(server, 'listening');
99 baseUrl = `http://127.0.0.1:${server.address().port}`;
100});
101
102afterAll(() => server.close());
103
104// ── helpers ──────────────────────────────────────────────────────────────────
105function req (method, path, body)
106{
107 const payload = body ? JSON.stringify(body) : undefined;
108 return new Promise((resolve, reject) =>
109 {
110 const r = http.request(baseUrl + path, {
111 method,
112 headers: {
113 'Content-Type': 'application/json',
114 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
115 },
116 }, res =>
117 {
118 let data = '';
119 res.on('data', d => data += d);
120 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
121 });
122 r.on('error', reject);
123 if (payload) r.write(payload);
124 r.end();
125 });
126}
127
128// ── tests ─────────────────────────────────────────────────────────────────────
129
130describe('GET /api/admin/users', () =>
131{
132 test('returns the list of users', async () =>
133 {
134 const { status, body } = await req('GET', '/api/admin/users');
135 expect(status).toBe(200);
136 expect(Array.isArray(body.users)).toBe(true);
137 expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true });
138 });
139});
140
141describe('POST /api/admin/users', () =>
142{
143 test('creates a new user', async () =>
144 {
145 const { status, body } = await req('POST', '/api/admin/users', {
146 username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {},
147 });
148 expect(status).toBe(201);
149 expect(body.ok).toBe(true);
150 });
151
152 test('rejects duplicate username', async () =>
153 {
154 const { status } = await req('POST', '/api/admin/users', {
155 username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {},
156 });
157 expect(status).toBe(409);
158 });
159
160 test('rejects short password', async () =>
161 {
162 const { status } = await req('POST', '/api/admin/users', {
163 username: 'carol', password: 'short', isAdmin: false, permissions: {},
164 });
165 expect(status).toBe(400);
166 });
167});
168
169describe('PATCH /api/admin/users/:id', () =>
170{
171 let bobId;
172
173 beforeAll(async () =>
174 {
175 const { body } = await req('GET', '/api/admin/users');
176 bobId = body.users.find(u => u.username === 'bob').id;
177 });
178
179 test('updates permissions', async () =>
180 {
181 const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, {
182 permissions: { data: { read: true, write: false } },
183 });
184 expect(status).toBe(200);
185 expect(body.ok).toBe(true);
186 });
187
188 test('returns 404 for unknown user', async () =>
189 {
190 const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false });
191 expect(status).toBe(404);
192 });
193});
194
195describe('DELETE /api/admin/users/:id', () =>
196{
197 let bobId;
198
199 beforeAll(async () =>
200 {
201 const { body } = await req('GET', '/api/admin/users');
202 bobId = body.users.find(u => u.username === 'bob').id;
203 });
204
205 test('cannot delete own account', async () =>
206 {
207 // mock user id is 1 (admin); bob is a different id — but we test self-delete guard
208 const adminId = mockUser.id;
209 const { status } = await req('DELETE', `/api/admin/users/${adminId}`);
210 expect(status).toBe(400);
211 });
212
213 test('deletes another user', async () =>
214 {
215 const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`);
216 expect(status).toBe(200);
217 expect(body.ok).toBe(true);
218 });
219
220 test('cannot delete the last admin', async () =>
221 {
222 // Only 'admin' left; try to delete them (switch mockUser to be different)
223 const { body: users } = await req('GET', '/api/admin/users');
224 const adminUser = users.users.find(u => u.username === 'admin');
225 const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`);
226 // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account"
227 expect([400]).toContain(status);
228 });
229});
230
231describe('GET /api/admin/config', () =>
232{
233 test('returns port and paths', async () =>
234 {
235 const { status, body } = await req('GET', '/api/admin/config');
236 expect(status).toBe(200);
237 expect(body.port).toBe(3000);
238 expect(Array.isArray(body.paths)).toBe(true);
239 });
240});
241
242describe('PUT /api/admin/config', () =>
243{
244 test('saves new paths', async () =>
245 {
246 const { status, body } = await req('PUT', '/api/admin/config', {
247 paths: ['/mnt/newpath'],
248 });
249 expect(status).toBe(200);
250 expect(body.ok).toBe(true);
251 });
252
253 test('rejects non-array paths', async () =>
254 {
255 const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' });
256 expect(status).toBe(400);
257 });
258
259 test('rejects invalid port', async () =>
260 {
261 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
262 expect(status).toBe(400);
263 });
264});
265
266describe('POST /api/admin/shutdown', () =>
267{
268 test('responds ok and invokes shutdown callback', async () =>
269 {
270 shutdownForRestartMock.mockClear();
271 const { status, body } = await req('POST', '/api/admin/shutdown');
272 expect(status).toBe(200);
273 expect(body.ok).toBe(true);
274
275 // Shutdown invocation is deferred via setImmediate().
276 await new Promise(resolve => setImmediate(resolve));
277 expect(shutdownForRestartMock).toHaveBeenCalledTimes(1);
278 });
279});