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

100 lines
3.5 KiB
JavaScript
Raw 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('@vercel/postgres', () => ({ sql: vi.fn() }));
import { sql } from '@vercel/postgres';
import { JWT_SECRET } from '../../lib/auth-secret.js';
import { getUserFromRequest } from '../../lib/permission-middleware.js';
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): infrastructure + email migration for Deck Hearth (B2 of 2) Closes the pick-a-name convoy. Applies D1-D5 + Risk 4 PRESERVE per operator gate-1 ratification. Infrastructure renames: - lib/rate-limit.js: 5 Redis key prefixes tcgvault:* → deckhearth:* (D5). One-time per-15-min / per-1-hour counter reset accepted; no user impact because counter windows are short anyway. Existing rate-limit state in Upstash will accumulate at the new prefix on first request. - package.json: name field tcg-vault → deck-hearth (D2) - package-lock.json: regenerated for the name change; STOP-on-churn protocol confirmed only the two name lines changed (no dep churn) - All three test users (admin/alice/bob) renamed to @deckhearth.com (D4) - One-off migration script scripts/migrations/2026-05-24-rename-admin- email.js (NEW): ESM, idempotent, UNIQUE-collision-safe. Per the no-go-zones rule for new migrations. Operator MUST run post-deploy. - README.md + TESTING_GUIDE.md operator-caveat blockquotes flagged - pages/login.js demo-credential pre-fill updated PRESERVED per Risk 4: - test/lib/permission-middleware.test.js literal admin@tcgvault.com with 7-line architect-authored "why" comment block. This is the documented pre-fix-auth-bypass bug shape; the regression-lock literal stays as historical truth. Verification: - npm run lint: 128 problems (baseline preserved) - npm run test:run: 21/21 pass (preserved literal keeps green) - Grep across full repo: 0 hits for TCG Vault / tcgvault / tcg-vault except the explicit preserve in the test file + .convoys/ historical - lib/rate-limit.js: 5 deckhearth: prefixes, 0 tcgvault: prefixes - node --check on the new migration script: exit 0 - git diff package-lock.json: only the 2 "name": lines changed (no churn) Operator post-merge action: - Run `node scripts/migrations/2026-05-24-rename-admin-email.js` against the production Neon DB. Order matters: migration FIRST, then any subsequent `npm run setup-db` invocation. Migration script will refuse to run if collision detected (means setup-db already ran post-rename). Architect brief: .convoys/pick-a-name/brief-2-infrastructure-and-email-migration.md Architect commit: 50ce9ab Operator gate-1: D1-D5 + Risk 4 PRESERVE ratified. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 02:58:48 -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();
});
});