'use strict'; /** * Unit tests for server/routes/admin.js — user CRUD and config management. */ const express = require('express'); const http = require('http'); const { once } = require('events'); const crypto = require('crypto'); // ── in-memory DB mock ─────────────────────────────────────────────────────── jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; function getDb () { if (!db) { db = new Database(':memory:'); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]' ); `); } return db; } return { getDb, initDb: getDb }; }); // ── config mock ───────────────────────────────────────────────────────────── const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] }; jest.mock('../server/config', () => ({ loadConfig: () => ({ ...mockConfig }), saveConfig: (c) => Object.assign(mockConfig, c), getEffectivePaths: (p) => p, getAllowedRoot: () => null, })); // ── auth mock — bypass JWT verification ───────────────────────────────────── let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} }; jest.mock('../server/auth', () => ({ requireAuth: (req, res, next) => { req.user = mockUser; next(); }, requireAdmin: (req, res, next) => { if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' }); next(); }, createToken: () => 'mock-token', getClientIp: () => '127.0.0.1', getRegion: () => 'US:CA', })); const adminRoutes = require('../server/routes/admin'); const { getDb } = require('../server/db'); const bcrypt = require('bcrypt'); jest.setTimeout(30000); // ── seed a default admin before anything runs ──────────────────────────────── beforeAll(() => { const db = getDb(); const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)') .run(['admin', hash, '{}']); }); // ── build minimal app ──────────────────────────────────────────────────────── let server; let baseUrl; let shutdownForRestartMock; beforeAll(async () => { const app = express(); shutdownForRestartMock = jest.fn(); app.set('shutdownForRestart', shutdownForRestartMock); app.use(express.json()); app.use('/api/admin', adminRoutes); app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: err.message || 'Internal error' }); }); server = http.createServer(app); server.listen(0); await once(server, 'listening'); baseUrl = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => server.close()); // ── helpers ────────────────────────────────────────────────────────────────── function req (method, path, body) { const payload = body ? JSON.stringify(body) : undefined; return new Promise((resolve, reject) => { const r = http.request(baseUrl + path, { method, headers: { 'Content-Type': 'application/json', ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), }, }, res => { let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); }); r.on('error', reject); if (payload) r.write(payload); r.end(); }); } // ── tests ───────────────────────────────────────────────────────────────────── describe('GET /api/admin/users', () => { test('returns the list of users', async () => { const { status, body } = await req('GET', '/api/admin/users'); expect(status).toBe(200); expect(Array.isArray(body.users)).toBe(true); expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true }); }); }); describe('POST /api/admin/users', () => { test('creates a new user', async () => { const { status, body } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {}, }); expect(status).toBe(201); expect(body.ok).toBe(true); }); test('rejects duplicate username', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {}, }); expect(status).toBe(409); }); test('rejects short password', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'carol', password: 'short', isAdmin: false, permissions: {}, }); expect(status).toBe(400); }); }); describe('PATCH /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('updates permissions', async () => { const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, { permissions: { data: { read: true, write: false } }, }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('returns 404 for unknown user', async () => { const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false }); expect(status).toBe(404); }); }); describe('DELETE /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('cannot delete own account', async () => { // mock user id is 1 (admin); bob is a different id — but we test self-delete guard const adminId = mockUser.id; const { status } = await req('DELETE', `/api/admin/users/${adminId}`); expect(status).toBe(400); }); test('deletes another user', async () => { const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('cannot delete the last admin', async () => { // Only 'admin' left; try to delete them (switch mockUser to be different) const { body: users } = await req('GET', '/api/admin/users'); const adminUser = users.users.find(u => u.username === 'admin'); const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`); // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account" expect([400]).toContain(status); }); }); describe('GET /api/admin/config', () => { test('returns port and paths', async () => { const { status, body } = await req('GET', '/api/admin/config'); expect(status).toBe(200); expect(body.port).toBe(3000); expect(Array.isArray(body.paths)).toBe(true); }); }); describe('PUT /api/admin/config', () => { test('saves new paths', async () => { const { status, body } = await req('PUT', '/api/admin/config', { paths: ['/mnt/newpath'], }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('rejects non-array paths', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' }); expect(status).toBe(400); }); test('rejects invalid port', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 }); expect(status).toBe(400); }); }); describe('POST /api/admin/shutdown', () => { test('responds ok and invokes shutdown callback', async () => { shutdownForRestartMock.mockClear(); const { status, body } = await req('POST', '/api/admin/shutdown'); expect(status).toBe(200); expect(body.ok).toBe(true); // Shutdown invocation is deferred via setImmediate(). await new Promise(resolve => setImmediate(resolve)); expect(shutdownForRestartMock).toHaveBeenCalledTimes(1); }); });