test(auth): add vitest harness + 16 auth-focused unit tests (Brief 5 of fix-auth-bypass) #11
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):
|
# What this CI covers (and Vercel does not):
|
||||||
# - Lint (cheap belt-and-suspenders)
|
# - Lint (cheap belt-and-suspenders)
|
||||||
# - Schema-map drift check (docs/SCHEMA_MAP.md updated when scripts/add-*.js changes)
|
# - Schema-map drift check (docs/SCHEMA_MAP.md updated when scripts/add-*.js changes)
|
||||||
#
|
# - Unit tests (vitest)
|
||||||
# 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.
|
|
||||||
#
|
#
|
||||||
# NOTE: tcg-vault is JavaScript (not TypeScript). No `npx tsc --noEmit` step.
|
# NOTE: tcg-vault is JavaScript (not TypeScript). No `npx tsc --noEmit` step.
|
||||||
# Re-enable a type-check job if migrating to TypeScript.
|
# Re-enable a type-check job if migrating to TypeScript.
|
||||||
|
|
@ -116,20 +113,16 @@ jobs:
|
||||||
fi
|
fi
|
||||||
echo "OK: no forbidden dev endpoints under pages/api/."
|
echo "OK: no forbidden dev endpoints under pages/api/."
|
||||||
|
|
||||||
# test:
|
test:
|
||||||
# Disabled until a test runner is adopted. Re-enable as:
|
name: Unit tests (vitest)
|
||||||
#
|
runs-on: ubuntu-latest
|
||||||
# test:
|
steps:
|
||||||
# name: Unit + integration tests
|
- uses: actions/checkout@v4
|
||||||
# runs-on: ubuntu-latest
|
- uses: actions/setup-node@v4
|
||||||
# steps:
|
with:
|
||||||
# - uses: actions/checkout@v4
|
node-version: ${{ env.NODE_VERSION }}
|
||||||
# - uses: actions/setup-node@v4
|
cache: npm
|
||||||
# with:
|
- run: npm ci
|
||||||
# node-version: ${{ env.NODE_VERSION }}
|
- run: npm run test:run
|
||||||
# cache: npm
|
env:
|
||||||
# - run: npm ci
|
JWT_SECRET: ci-secret-only-for-tests-do-not-use-in-prod
|
||||||
# - run: npm run test:run
|
|
||||||
# env:
|
|
||||||
# JWT_SECRET: ci-secret-only-for-tests
|
|
||||||
# POSTGRES_URL: postgres://ci:ci@localhost:5432/ci
|
|
||||||
|
|
|
||||||
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 .",
|
"lint": "eslint .",
|
||||||
"setup-db": "node scripts/setup-neon-db.js",
|
"setup-db": "node scripts/setup-neon-db.js",
|
||||||
"import-popular": "node scripts/import-popular-sets.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": {
|
"dependencies": {
|
||||||
"@neondatabase/serverless": "^1.0.1",
|
"@neondatabase/serverless": "^1.0.1",
|
||||||
|
|
@ -33,6 +35,7 @@
|
||||||
"eslint-config-next": "^16.2.6",
|
"eslint-config-next": "^16.2.6",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"tailwindcss": "^3.4.17",
|
"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