deckhearth/test/lib/permission-middleware.test.js

147 lines
5.1 KiB
JavaScript
Raw Permalink Normal View History

test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) Closes AGENTS.md gotcha #11 (well, the relevant half of it — "Testing: None yet" line in §6 is now stale). Installs vitest@^3.2.4 (single devDep, no UI / coverage / jsdom) and adds 16 unit tests across 3 files that lock in post-Brief-1/2/4 behavior: test/lib/auth-secret.test.js (3 tests) - JWT_SECRET exports the env value - JWT_TOKEN_TTL is canonical 24h - Module throws at load when JWT_SECRET is empty test/lib/permission-middleware.test.js (8 tests) - getUserFromRequest returns null for: missing header, non-Bearer scheme, malformed token, wrong-secret token, expired token, valid-token-no-user-row - Returns user object for valid token + user row - Brief 2 regression lock: does NOT return the synthetic admin shape { userId: 1, email: 'admin@tcgvault.com', role: 'admin' } when no Authorization header is present test/api/auth-utils.test.js (5 tests) - generateToken issues 24h JWT (exp - iat === 86400) - Payload includes userId, email, role - verifyToken round-trips valid tokens - Returns null for malformed / wrong-secret tokens CI: re-enabled the previously commented-out test: job in .github/workflows/ci.yml. Blocking (no || true wrapper) — vitest is the first runner in this repo and we want CI red on test regression. JWT_SECRET is set via a CI-only fake; production secret is unaffected. Rate-limit (Brief 4) coverage deferred to a future expand-auth-tests convoy per architect's call (R11). package.json has "type": "module" so vitest's default Vite-based transform handles .js ESM out of the box — no transform config needed. Convoy: fix-auth-bypass / Brief 5 (last brief) Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 12:06:54 -04:00
import { beforeEach, describe, expect, it, vi } from 'vitest';
import jwt from 'jsonwebtoken';
vi.mock('../../lib/sql.js', () => ({ sql: vi.fn() }));
test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) Closes AGENTS.md gotcha #11 (well, the relevant half of it — "Testing: None yet" line in §6 is now stale). Installs vitest@^3.2.4 (single devDep, no UI / coverage / jsdom) and adds 16 unit tests across 3 files that lock in post-Brief-1/2/4 behavior: test/lib/auth-secret.test.js (3 tests) - JWT_SECRET exports the env value - JWT_TOKEN_TTL is canonical 24h - Module throws at load when JWT_SECRET is empty test/lib/permission-middleware.test.js (8 tests) - getUserFromRequest returns null for: missing header, non-Bearer scheme, malformed token, wrong-secret token, expired token, valid-token-no-user-row - Returns user object for valid token + user row - Brief 2 regression lock: does NOT return the synthetic admin shape { userId: 1, email: 'admin@tcgvault.com', role: 'admin' } when no Authorization header is present test/api/auth-utils.test.js (5 tests) - generateToken issues 24h JWT (exp - iat === 86400) - Payload includes userId, email, role - verifyToken round-trips valid tokens - Returns null for malformed / wrong-secret tokens CI: re-enabled the previously commented-out test: job in .github/workflows/ci.yml. Blocking (no || true wrapper) — vitest is the first runner in this repo and we want CI red on test regression. JWT_SECRET is set via a CI-only fake; production secret is unaffected. Rate-limit (Brief 4) coverage deferred to a future expand-auth-tests convoy per architect's call (R11). package.json has "type": "module" so vitest's default Vite-based transform handles .js ESM out of the box — no transform config needed. Convoy: fix-auth-bypass / Brief 5 (last brief) Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 12:06:54 -04:00
import { sql } from '../../lib/sql.js';
test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) Closes AGENTS.md gotcha #11 (well, the relevant half of it — "Testing: None yet" line in §6 is now stale). Installs vitest@^3.2.4 (single devDep, no UI / coverage / jsdom) and adds 16 unit tests across 3 files that lock in post-Brief-1/2/4 behavior: test/lib/auth-secret.test.js (3 tests) - JWT_SECRET exports the env value - JWT_TOKEN_TTL is canonical 24h - Module throws at load when JWT_SECRET is empty test/lib/permission-middleware.test.js (8 tests) - getUserFromRequest returns null for: missing header, non-Bearer scheme, malformed token, wrong-secret token, expired token, valid-token-no-user-row - Returns user object for valid token + user row - Brief 2 regression lock: does NOT return the synthetic admin shape { userId: 1, email: 'admin@tcgvault.com', role: 'admin' } when no Authorization header is present test/api/auth-utils.test.js (5 tests) - generateToken issues 24h JWT (exp - iat === 86400) - Payload includes userId, email, role - verifyToken round-trips valid tokens - Returns null for malformed / wrong-secret tokens CI: re-enabled the previously commented-out test: job in .github/workflows/ci.yml. Blocking (no || true wrapper) — vitest is the first runner in this repo and we want CI red on test regression. JWT_SECRET is set via a CI-only fake; production secret is unaffected. Rate-limit (Brief 4) coverage deferred to a future expand-auth-tests convoy per architect's call (R11). package.json has "type": "module" so vitest's default Vite-based transform handles .js ESM out of the box — no transform config needed. Convoy: fix-auth-bypass / Brief 5 (last brief) Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 12:06:54 -04:00
import { JWT_SECRET } from '../../lib/auth-secret.js';
import { getUserFromRequest, withAdmin } from '../../lib/permission-middleware.js';
test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) Closes AGENTS.md gotcha #11 (well, the relevant half of it — "Testing: None yet" line in §6 is now stale). Installs vitest@^3.2.4 (single devDep, no UI / coverage / jsdom) and adds 16 unit tests across 3 files that lock in post-Brief-1/2/4 behavior: test/lib/auth-secret.test.js (3 tests) - JWT_SECRET exports the env value - JWT_TOKEN_TTL is canonical 24h - Module throws at load when JWT_SECRET is empty test/lib/permission-middleware.test.js (8 tests) - getUserFromRequest returns null for: missing header, non-Bearer scheme, malformed token, wrong-secret token, expired token, valid-token-no-user-row - Returns user object for valid token + user row - Brief 2 regression lock: does NOT return the synthetic admin shape { userId: 1, email: 'admin@tcgvault.com', role: 'admin' } when no Authorization header is present test/api/auth-utils.test.js (5 tests) - generateToken issues 24h JWT (exp - iat === 86400) - Payload includes userId, email, role - verifyToken round-trips valid tokens - Returns null for malformed / wrong-secret tokens CI: re-enabled the previously commented-out test: job in .github/workflows/ci.yml. Blocking (no || true wrapper) — vitest is the first runner in this repo and we want CI red on test regression. JWT_SECRET is set via a CI-only fake; production secret is unaffected. Rate-limit (Brief 4) coverage deferred to a future expand-auth-tests convoy per architect's call (R11). package.json has "type": "module" so vitest's default Vite-based transform handles .js ESM out of the box — no transform config needed. Convoy: fix-auth-bypass / Brief 5 (last brief) Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 12:06:54 -04:00
function makeToken(payload, opts = {}) {
return jwt.sign(payload, JWT_SECRET, { expiresIn: opts.expiresIn ?? '1h' });
}
describe('getUserFromRequest', () => {
beforeEach(() => {
sql.mockReset();
sql.mockResolvedValue({ rows: [] });
vi.spyOn(console, 'error').mockImplementation(() => {});
});
it('returns null when the Authorization header is missing', async () => {
const user = await getUserFromRequest({ headers: {} });
expect(user).toBeNull();
expect(sql).not.toHaveBeenCalled();
});
it('returns null when the Authorization header is not a Bearer scheme', async () => {
const user = await getUserFromRequest({
headers: { authorization: 'Basic foo' },
});
expect(user).toBeNull();
expect(sql).not.toHaveBeenCalled();
});
it('returns null when the token is malformed', async () => {
const user = await getUserFromRequest({
headers: { authorization: 'Bearer not-a-jwt' },
});
expect(user).toBeNull();
expect(sql).not.toHaveBeenCalled();
});
it('returns null when the token signature uses a wrong secret', async () => {
const token = jwt.sign({ userId: 1 }, 'other-secret', { expiresIn: '1h' });
const user = await getUserFromRequest({
headers: { authorization: `Bearer ${token}` },
});
expect(user).toBeNull();
expect(sql).not.toHaveBeenCalled();
});
it('returns null when the token is expired', async () => {
const token = makeToken({ userId: 1 }, { expiresIn: '-1s' });
const user = await getUserFromRequest({
headers: { authorization: `Bearer ${token}` },
});
expect(user).toBeNull();
expect(sql).not.toHaveBeenCalled();
});
it('returns null when the token is valid but no user row matches', async () => {
sql.mockResolvedValue({ rows: [] });
const token = makeToken({ userId: 42 });
const user = await getUserFromRequest({
headers: { authorization: `Bearer ${token}` },
});
expect(user).toBeNull();
expect(sql).toHaveBeenCalledTimes(1);
});
it('returns the user object when the token is valid and the user row exists', async () => {
sql.mockResolvedValue({
rows: [{ id: 42, email: 'a@b.c', role: 'user' }],
});
const token = makeToken({ userId: 42 });
const user = await getUserFromRequest({
headers: { authorization: `Bearer ${token}` },
});
expect(user).toEqual({ userId: 42, email: 'a@b.c', role: 'user' });
expect(sql).toHaveBeenCalledTimes(1);
});
it('does NOT return the synthetic admin shape when no Authorization header is present (Brief 2 regression lock)', async () => {
const user = await getUserFromRequest({ headers: {} });
feat(brand): unify on Deck Hearth across in-repo strings + infra (P1 brand decision) Resolves the launch-blocking 'TCG Vault vs Deck Hearth' inconsistency called out in AGENTS.md line 5 since project setup. Operator gate-0 decision: Deck Hearth wins. Two briefs applied serially. B1 (mechanical): 7-file display + comment sweep. B2 (infrastructure): Redis prefix rename in lib/rate-limit.js (5 prefixes, accept one-time counter reset), package.json + lockfile regen (STOP-on-churn confirmed only name lines changed), admin/alice/bob email rename in seed scripts + login pre-fill + NEW idempotent migration script scripts/migrations/2026-05-24-rename-admin-email.js. Risk 4 PRESERVE applied: test/lib/permission-middleware.test.js retains admin@tcgvault.com literal with 7-line architect-authored why comment (documents pre-fix-auth-bypass bug shape; preserves historical truth per project's gotcha-documentation convention). All 5 D-decisions ratified at gate-1 (Deck Hearth / deck-hearth / deckhearth / admin@deckhearth.com / full deckhearth Redis prefix). Local: lint 128 baseline (B1 + B2), vitest 21/21 (B1 + B2). CI all green: Playwright smoke 3/3 against rebranded preview in 1m4s, forbidden-cors-headers pass, forbidden-endpoints pass, Screenshot diff pass, Vercel deployment complete. Cross-validation lineage: 4th convoy where the same 3-test smoke spec defends auth surface through sweeping change (after PR #15 Layout default-user, PR #19 CORS, PR #20 rate-limit, now this PR #21 brand rename). OPERATOR POST-MERGE ACTION REQUIRED: run 'node scripts/migrations/2026-05-24-rename-admin-email.js' against prod Neon DB before next admin login (ordering: migration FIRST, then any subsequent setup-db invocation). Migration is ESM, idempotent, UNIQUE-collision-safe. PR #21 architect-commit 50ce9ab, B1 ac8c998, B2 1c18d21.
2026-05-25 03:28:29 -04:00
// Email literal is the OLD `admin@tcgvault.com` (pre-`pick-a-name`
// convoy, 2026-05-24) — preserved as the exact pre-fix-auth-bypass
// synthetic-admin shape this assertion locks against. The
// `.toBeNull()` check below is the strong contract; this soft check
// documents the historical bug. Do NOT update to
// `admin@deckhearth.com` — that would weaken the regression-lock to
// a shape that never actually existed.
test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) Closes AGENTS.md gotcha #11 (well, the relevant half of it — "Testing: None yet" line in §6 is now stale). Installs vitest@^3.2.4 (single devDep, no UI / coverage / jsdom) and adds 16 unit tests across 3 files that lock in post-Brief-1/2/4 behavior: test/lib/auth-secret.test.js (3 tests) - JWT_SECRET exports the env value - JWT_TOKEN_TTL is canonical 24h - Module throws at load when JWT_SECRET is empty test/lib/permission-middleware.test.js (8 tests) - getUserFromRequest returns null for: missing header, non-Bearer scheme, malformed token, wrong-secret token, expired token, valid-token-no-user-row - Returns user object for valid token + user row - Brief 2 regression lock: does NOT return the synthetic admin shape { userId: 1, email: 'admin@tcgvault.com', role: 'admin' } when no Authorization header is present test/api/auth-utils.test.js (5 tests) - generateToken issues 24h JWT (exp - iat === 86400) - Payload includes userId, email, role - verifyToken round-trips valid tokens - Returns null for malformed / wrong-secret tokens CI: re-enabled the previously commented-out test: job in .github/workflows/ci.yml. Blocking (no || true wrapper) — vitest is the first runner in this repo and we want CI red on test regression. JWT_SECRET is set via a CI-only fake; production secret is unaffected. Rate-limit (Brief 4) coverage deferred to a future expand-auth-tests convoy per architect's call (R11). package.json has "type": "module" so vitest's default Vite-based transform handles .js ESM out of the box — no transform config needed. Convoy: fix-auth-bypass / Brief 5 (last brief) Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 12:06:54 -04:00
expect(user).not.toEqual({
userId: 1,
email: 'admin@tcgvault.com',
role: 'admin',
});
expect(user).toBeNull();
});
});
describe('withAdmin', () => {
beforeEach(() => {
sql.mockReset();
sql.mockResolvedValue({ rows: [] });
vi.spyOn(console, 'error').mockImplementation(() => {});
});
it('returns 401 when unauthenticated', async () => {
const inner = vi.fn();
const res = { status: vi.fn().mockReturnThis(), json: vi.fn() };
await withAdmin(inner)({ headers: {} }, res);
expect(res.status).toHaveBeenCalledWith(401);
expect(inner).not.toHaveBeenCalled();
});
it('returns 403 when user is not admin', async () => {
sql.mockResolvedValueOnce({
rows: [{ id: 2, email: 'alice@deckhearth.com', role: 'user' }],
});
const token = makeToken({ userId: 2, email: 'alice@deckhearth.com' });
const inner = vi.fn();
const res = { status: vi.fn().mockReturnThis(), json: vi.fn() };
await withAdmin(inner)(
{ headers: { authorization: `Bearer ${token}` } },
res
);
expect(res.status).toHaveBeenCalledWith(403);
expect(inner).not.toHaveBeenCalled();
});
it('calls inner handler with admin user', async () => {
sql.mockResolvedValueOnce({
rows: [{ id: 1, email: 'admin@deckhearth.com', role: 'admin' }],
});
const token = makeToken({ userId: 1, email: 'admin@deckhearth.com' });
const inner = vi.fn().mockResolvedValue(undefined);
const req = { headers: { authorization: `Bearer ${token}` } };
const res = {};
await withAdmin(inner)(req, res);
expect(inner).toHaveBeenCalledWith(req, res, {
userId: 1,
email: 'admin@deckhearth.com',
role: 'admin',
});
});
});