diff --git a/tests/auth.test.js b/tests/auth.test.js new file mode 100644 index 0000000..3d9c34b --- /dev/null +++ b/tests/auth.test.js @@ -0,0 +1,61 @@ +import { test, describe, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { adminGuard } from '../src/auth.js'; + +function ctx(headers = {}) { + const lower = {}; + for (const [k, v] of Object.entries(headers)) lower[k.toLowerCase()] = v; + return { + req: { header: (name) => lower[name.toLowerCase()] ?? null }, + json: (_body, status) => ({ __json: true, status }), + }; +} + +const OK = { __next: true }; + +describe('adminGuard', () => { + beforeEach(() => { + delete process.env.ADMIN_TOKEN; + }); + + test('rejects with 401 when no ADMIN_TOKEN is configured', async () => { + const res = await adminGuard(ctx({ 'x-admin-token': 'ignored' }), async () => OK); + assert.equal(res.status, 401); + }); + + test('rejects with 401 when no token is provided', async () => { + process.env.ADMIN_TOKEN = 'secret-token'; + const res = await adminGuard(ctx(), async () => OK); + assert.equal(res.status, 401); + }); + + test('rejects with 401 on a wrong token', async () => { + process.env.ADMIN_TOKEN = 'secret-token'; + const res = await adminGuard(ctx({ 'x-admin-token': 'wrong' }), async () => OK); + assert.equal(res.status, 401); + }); + + test('accepts via the X-Admin-Token header', async () => { + process.env.ADMIN_TOKEN = 'secret-token'; + const res = await adminGuard(ctx({ 'x-admin-token': 'secret-token' }), async () => OK); + assert.deepEqual(res, OK); + }); + + test('accepts via the Authorization: Bearer header', async () => { + process.env.ADMIN_TOKEN = 'secret-token'; + const res = await adminGuard(ctx({ authorization: 'Bearer secret-token' }), async () => OK); + assert.deepEqual(res, OK); + }); + + test('trims surrounding whitespace from provided tokens', async () => { + process.env.ADMIN_TOKEN = 'secret-token'; + const res = await adminGuard(ctx({ 'x-admin-token': ' secret-token ' }), async () => OK); + assert.deepEqual(res, OK); + }); + + test('rejects a token of different length (401)', async () => { + process.env.ADMIN_TOKEN = 'very-long-secret-token-value'; + const res = await adminGuard(ctx({ 'x-admin-token': 'short' }), async () => OK); + assert.equal(res.status, 401); + }); +});