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>
This commit is contained in:
parent
297afca1ae
commit
bcb448d328
8 changed files with 1640 additions and 27 deletions
35
.github/workflows/ci.yml
vendored
35
.github/workflows/ci.yml
vendored
|
|
@ -7,10 +7,7 @@ name: CI
|
|||
# What this CI covers (and Vercel does not):
|
||||
# - Lint (cheap belt-and-suspenders)
|
||||
# - Schema-map drift check (docs/SCHEMA_MAP.md updated when scripts/add-*.js changes)
|
||||
#
|
||||
# NOTE: tcg-vault has no test runner installed yet. Re-enable the `test:` job
|
||||
# below once vitest (or equivalent) is adopted AND a `test:run` script exists
|
||||
# in package.json. See .convoys/ for the testing convoy.
|
||||
# - Unit tests (vitest)
|
||||
#
|
||||
# NOTE: tcg-vault is JavaScript (not TypeScript). No `npx tsc --noEmit` step.
|
||||
# Re-enable a type-check job if migrating to TypeScript.
|
||||
|
|
@ -116,20 +113,16 @@ jobs:
|
|||
fi
|
||||
echo "OK: no forbidden dev endpoints under pages/api/."
|
||||
|
||||
# test:
|
||||
# Disabled until a test runner is adopted. Re-enable as:
|
||||
#
|
||||
# test:
|
||||
# name: Unit + integration tests
|
||||
# runs-on: ubuntu-latest
|
||||
# steps:
|
||||
# - uses: actions/checkout@v4
|
||||
# - uses: actions/setup-node@v4
|
||||
# with:
|
||||
# node-version: ${{ env.NODE_VERSION }}
|
||||
# cache: npm
|
||||
# - run: npm ci
|
||||
# - run: npm run test:run
|
||||
# env:
|
||||
# JWT_SECRET: ci-secret-only-for-tests
|
||||
# POSTGRES_URL: postgres://ci:ci@localhost:5432/ci
|
||||
test:
|
||||
name: Unit tests (vitest)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION }}
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run test:run
|
||||
env:
|
||||
JWT_SECRET: ci-secret-only-for-tests-do-not-use-in-prod
|
||||
|
|
|
|||
1445
package-lock.json
generated
1445
package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -10,7 +10,9 @@
|
|||
"lint": "eslint .",
|
||||
"setup-db": "node scripts/setup-neon-db.js",
|
||||
"import-popular": "node scripts/import-popular-sets.js",
|
||||
"import-all": "node scripts/bulk-import-all.js"
|
||||
"import-all": "node scripts/bulk-import-all.js",
|
||||
"test": "vitest",
|
||||
"test:run": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@neondatabase/serverless": "^1.0.1",
|
||||
|
|
@ -33,6 +35,7 @@
|
|||
"eslint-config-next": "^16.2.6",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"typescript": "^5.9.3"
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
52
test/api/auth-utils.test.js
Normal file
52
test/api/auth-utils.test.js
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { describe, expect, it, vi } from 'vitest';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
vi.mock('../../lib/database.js', () => ({
|
||||
db: { query: vi.fn() },
|
||||
}));
|
||||
|
||||
import { JWT_SECRET } from '../../lib/auth-secret.js';
|
||||
import { generateToken, verifyToken } from '../../pages/api/auth-utils.js';
|
||||
|
||||
const ONE_DAY_IN_SECONDS = 24 * 60 * 60;
|
||||
|
||||
describe('pages/api/auth-utils generateToken', () => {
|
||||
it('issues a token whose lifetime is 24h (exp - iat === 86400)', () => {
|
||||
const token = generateToken({ id: 7, email: 'x@y.z', role: 'user' });
|
||||
const decoded = jwt.decode(token);
|
||||
expect(decoded.exp - decoded.iat).toBe(ONE_DAY_IN_SECONDS);
|
||||
});
|
||||
|
||||
it('includes userId, email, and role in the payload from the user arg', () => {
|
||||
const token = generateToken({ id: 7, email: 'x@y.z', role: 'admin' });
|
||||
const decoded = jwt.decode(token);
|
||||
expect(decoded.userId).toBe(7);
|
||||
expect(decoded.email).toBe('x@y.z');
|
||||
expect(decoded.role).toBe('admin');
|
||||
});
|
||||
});
|
||||
|
||||
describe('pages/api/auth-utils verifyToken', () => {
|
||||
it('returns the decoded payload for a valid token', () => {
|
||||
const token = generateToken({ id: 7, email: 'x@y.z', role: 'user' });
|
||||
const payload = verifyToken(token);
|
||||
expect(payload).not.toBeNull();
|
||||
expect(payload.userId).toBe(7);
|
||||
expect(payload.email).toBe('x@y.z');
|
||||
expect(payload.role).toBe('user');
|
||||
});
|
||||
|
||||
it('returns null for a malformed token', () => {
|
||||
expect(verifyToken('not-a-jwt')).toBeNull();
|
||||
});
|
||||
|
||||
it('returns null for a token signed with a different secret', () => {
|
||||
const token = jwt.sign(
|
||||
{ userId: 7, email: 'x@y.z', role: 'user' },
|
||||
'some-other-secret',
|
||||
{ expiresIn: '1h' }
|
||||
);
|
||||
expect(verifyToken(token)).toBeNull();
|
||||
expect(JWT_SECRET).not.toBe('some-other-secret');
|
||||
});
|
||||
});
|
||||
23
test/lib/auth-secret.test.js
Normal file
23
test/lib/auth-secret.test.js
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { JWT_SECRET, JWT_TOKEN_TTL } from '../../lib/auth-secret.js';
|
||||
|
||||
describe('lib/auth-secret', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('exports JWT_SECRET equal to the value set in test/setup.js', () => {
|
||||
expect(JWT_SECRET).toBe('test-secret-for-vitest-only-do-not-use-in-prod');
|
||||
});
|
||||
|
||||
it('exports JWT_TOKEN_TTL as the canonical 24h value', () => {
|
||||
expect(JWT_TOKEN_TTL).toBe('24h');
|
||||
});
|
||||
|
||||
it('throws at module load when JWT_SECRET is unset', async () => {
|
||||
vi.resetModules();
|
||||
vi.stubEnv('JWT_SECRET', '');
|
||||
await expect(import('../../lib/auth-secret.js')).rejects.toThrow(/JWT_SECRET/);
|
||||
});
|
||||
});
|
||||
92
test/lib/permission-middleware.test.js
Normal file
92
test/lib/permission-middleware.test.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
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: {} });
|
||||
expect(user).not.toEqual({
|
||||
userId: 1,
|
||||
email: 'admin@tcgvault.com',
|
||||
role: 'admin',
|
||||
});
|
||||
expect(user).toBeNull();
|
||||
});
|
||||
});
|
||||
2
test/setup.js
Normal file
2
test/setup.js
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
process.env.JWT_SECRET = 'test-secret-for-vitest-only-do-not-use-in-prod';
|
||||
process.env.NODE_ENV = 'test';
|
||||
11
vitest.config.js
Normal file
11
vitest.config.js
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
globals: false,
|
||||
setupFiles: ['./test/setup.js'],
|
||||
include: ['test/**/*.test.js'],
|
||||
testTimeout: 5000,
|
||||
},
|
||||
});
|
||||
Loading…
Reference in a new issue