Repository navigation
feat(security): unified security schema, password policy, and API threat model #151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Sanjai-Gopal
wants to merge
18
commits into
sidd190:main
Choose a base branch
from
Sanjai-Gopal:feat/unified-security-schema-and-docs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
94f0a79
chore: add react react-dom axios to devDependencies for local test suite
66afb2c
feat(security): strengthen password policy and unify validation acros…
f8a287e
feat(security): separate JWT access and refresh secrets and add authM…
aa2a19e
fix(schema): de-duplicate createdAt and add hot-path indexes for emai…
8f200e6
feat(security): invalidate and rotate tokens on password change (clos…
0f189a7
docs: add comprehensive API reference, threat model, and llms.txt (cl…
77aacea
Merge branch 'feat/distinct-jwt-secrets-and-authmiddleware-tests' int…
2fa9544
Merge branch 'fix/schema-indexes-and-deduplication' into feat/unified…
781fae6
Merge branch 'feat/invalidate-tokens-on-password-change' into feat/un…
487f7a7
Merge branch 'docs/api-reference-threat-model-and-llms-txt' into feat…
8eb8d32
fix(schema): de-duplicate createdAt and add hot-path indexes for emai…
3a97f52
fix(schema): eliminate duplicate index declarations and verify unique…
910b02c
fix(frontend): align SetPasswordButton validation with password polic…
45e73a1
chore: sync schema index verification test in unified branch
4b19e69
Merge branch 'fix/strengthen-password-policy' into feat/unified-secur…
03f2761
fix(schema): remove duplicate index specifications and verify unique …
27b7f8d
feat(security): harden refresh-token rotation with hashed storage, re…
298db2b
test(security): mock session memory store in secretEnforcement to pre…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| const request = require('supertest'); | ||
| const express = require('express'); | ||
| const cookieParser = require('cookie-parser'); | ||
| const jwt = require('jsonwebtoken'); | ||
| const authMiddleware = require('../middleware/auth'); | ||
|
|
||
| describe('authMiddleware (Issue #19 & Issue #32)', () => { | ||
| const jwtSecret = 'test-distinct-access-secret-123'; | ||
| const jwtRefreshSecret = 'test-distinct-refresh-secret-456'; | ||
| let app; | ||
|
|
||
| beforeEach(() => { | ||
| app = express(); | ||
| app.use(cookieParser()); | ||
| app.locals.authConfig = { | ||
| jwtSecret, | ||
| jwtRefreshSecret | ||
| }; | ||
|
|
||
| app.get('/api/protected', authMiddleware, (req, res) => { | ||
| res.json({ | ||
| success: true, | ||
| user: req.user | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| it('allows access with a valid token in authToken cookie and attaches req.user', async () => { | ||
| const validToken = jwt.sign({ userId: 'user-789', role: 'admin' }, jwtSecret, { expiresIn: '15m' }); | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Cookie', [`authToken=${validToken}`]); | ||
|
|
||
| expect(res.statusCode).toBe(200); | ||
| expect(res.body.success).toBe(true); | ||
| expect(res.body.user.userId).toBe('user-789'); | ||
| expect(res.body.user.role).toBe('admin'); | ||
| }); | ||
|
|
||
| it('allows access with a valid token in Authorization Bearer header', async () => { | ||
| const validToken = jwt.sign({ userId: 'user-bearer-1', role: 'member' }, jwtSecret, { expiresIn: '15m' }); | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Authorization', `Bearer ${validToken}`); | ||
|
|
||
| expect(res.statusCode).toBe(200); | ||
| expect(res.body.success).toBe(true); | ||
| expect(res.body.user.userId).toBe('user-bearer-1'); | ||
| }); | ||
|
|
||
| it('returns 401 when no token is provided', async () => { | ||
| const res = await request(app).get('/api/protected'); | ||
|
|
||
| expect(res.statusCode).toBe(401); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.message).toMatch(/No token provided/i); | ||
| }); | ||
|
|
||
| it('returns 401 when token is malformed', async () => { | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Cookie', ['authToken=not-a-valid-jwt-token']); | ||
|
|
||
| expect(res.statusCode).toBe(401); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.message).toBe('Invalid token'); | ||
| }); | ||
|
|
||
| it('returns 401 when token is signed with a different secret', async () => { | ||
| const wrongSecretToken = jwt.sign({ userId: 'user-wrong' }, 'completely-wrong-secret'); | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Cookie', [`authToken=${wrongSecretToken}`]); | ||
|
|
||
| expect(res.statusCode).toBe(401); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.message).toBe('Invalid token'); | ||
| }); | ||
|
|
||
| it('returns 401 when token is expired', async () => { | ||
| const expiredToken = jwt.sign({ userId: 'user-expired' }, jwtSecret, { expiresIn: -10 }); | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Cookie', [`authToken=${expiredToken}`]); | ||
|
|
||
| expect(res.statusCode).toBe(401); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.message).toBe('Invalid token'); | ||
| }); | ||
|
|
||
| it('prevents refresh tokens from being accepted as access tokens (Issue #32)', async () => { | ||
| // Sign a refresh token with jwtRefreshSecret | ||
| const refreshToken = jwt.sign({ userId: 'user-refresh' }, jwtRefreshSecret, { expiresIn: '7d' }); | ||
|
|
||
| // Attempt to access protected route with the refresh token | ||
| const res = await request(app) | ||
| .get('/api/protected') | ||
| .set('Cookie', [`authToken=${refreshToken}`]); | ||
|
|
||
| expect(res.statusCode).toBe(401); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.message).toBe('Invalid token'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| const request = require('supertest'); | ||
| const express = require('express'); | ||
| const session = require('express-session'); | ||
|
|
||
| jest.mock('../models/User', () => { | ||
| const User = jest.fn(); | ||
| User.findOne = jest.fn(); | ||
| User.findById = jest.fn(); | ||
| return User; | ||
| }); | ||
| jest.mock('passport', () => ({ | ||
| authenticate: jest.fn(() => (req, res, next) => next()) | ||
| })); | ||
|
|
||
| const User = require('../models/User'); | ||
| const authRoutes = require('../routes/auth'); | ||
|
|
||
| describe('Password Policy & Credential Validation (Issue #38)', () => { | ||
| let app; | ||
| let mockUser; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockUser = { | ||
| _id: 'user-123', | ||
| id: 'user-123', | ||
| setPassword: jest.fn().mockResolvedValue(undefined), | ||
| save: jest.fn().mockResolvedValue(undefined), | ||
| toJSON: () => ({ username: 'alice', email: 'alice@example.com' }) | ||
| }; | ||
| User.mockImplementation(() => mockUser); | ||
| User.findOne.mockResolvedValue(null); | ||
| User.findById.mockResolvedValue(mockUser); | ||
|
|
||
| app = express(); | ||
| app.locals.authConfig = { | ||
| enableOAuth: false, | ||
| corsOrigin: 'https://app.example.com', | ||
| jwtSecret: 'test-access-secret', | ||
| jwtRefreshSecret: 'test-refresh-secret', | ||
| cookieMaxAge: 60000 | ||
| }; | ||
| app.use(express.json()); | ||
| app.use(session({ secret: 'test-session-secret', resave: false, saveUninitialized: false })); | ||
| app.use((req, res, next) => { | ||
| req.isAuthenticated = () => true; | ||
| req.user = mockUser; | ||
| req.login = (u, cb) => cb(); | ||
| next(); | ||
| }); | ||
| app.use('/api/auth', authRoutes); | ||
| }); | ||
|
|
||
| describe('Signup Password Validation', () => { | ||
| it.each([ | ||
| ['too short (6 chars)', 'Pass1a'], | ||
| ['too short (7 chars)', 'Pass1aa'], | ||
| ['no uppercase', 'password123'], | ||
| ['no lowercase', 'PASSWORD123'], | ||
| ['no number', 'PasswordOnly'] | ||
| ])('rejects non-compliant password: %s', async (desc, password) => { | ||
| const res = await request(app) | ||
| .post('/api/auth/signup') | ||
| .send({ | ||
| username: 'validuser', | ||
| email: 'valid@example.com', | ||
| password, | ||
| confirmPassword: password | ||
| }); | ||
|
|
||
| expect(res.statusCode).toBe(400); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.errors).toEqual( | ||
| expect.arrayContaining([expect.objectContaining({ field: 'password' })]) | ||
| ); | ||
| expect(User.findOne).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('accepts compliant passwords with at least 8 chars, uppercase, lowercase, and digit', async () => { | ||
| const res = await request(app) | ||
| .post('/api/auth/signup') | ||
| .send({ | ||
| username: 'validuser', | ||
| email: 'valid@example.com', | ||
| password: 'ValidPassword123', | ||
| confirmPassword: 'ValidPassword123' | ||
| }); | ||
|
|
||
| expect(res.statusCode).toBe(200); | ||
| expect(res.body.success).toBe(true); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Set-Password Validation', () => { | ||
| it.each([ | ||
| ['too short (<8 chars)', 'Short1'], | ||
| ['no uppercase', 'weakpass123'], | ||
| ['no number', 'NoDigitsHere'] | ||
| ])('rejects weak password on /set-password: %s', async (desc, password) => { | ||
| const res = await request(app) | ||
| .post('/api/auth/set-password') | ||
| .send({ password }); | ||
|
|
||
| expect(res.statusCode).toBe(400); | ||
| expect(res.body.success).toBe(false); | ||
| expect(res.body.errors).toEqual( | ||
| expect.arrayContaining([expect.objectContaining({ field: 'password' })]) | ||
| ); | ||
| expect(mockUser.setPassword).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('successfully updates password when compliant', async () => { | ||
| const res = await request(app) | ||
| .post('/api/auth/set-password') | ||
| .send({ password: 'StrongNewPass123' }); | ||
|
|
||
| expect(res.statusCode).toBe(200); | ||
| expect(res.body.success).toBe(true); | ||
| expect(mockUser.setPassword).toHaveBeenCalledWith('StrongNewPass123'); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| const mongoose = require('mongoose'); | ||
|
|
||
| jest.mock('connect-mongo', () => { | ||
| const session = require('express-session'); | ||
| return { | ||
| create: jest.fn().mockImplementation(() => new session.MemoryStore()) | ||
| }; | ||
| }); | ||
|
|
||
| const { createAuthBackend } = require('../index'); | ||
|
|
||
| describe('Production Secrets Enforcement (Issue #33 & Issue #32)', () => { | ||
| const originalEnv = process.env.NODE_ENV; | ||
| let connectSpy; | ||
|
|
||
| beforeAll(() => { | ||
| connectSpy = jest.spyOn(mongoose, 'connect').mockResolvedValue(undefined); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| connectSpy.mockRestore(); | ||
| await mongoose.disconnect(); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| process.env.NODE_ENV = originalEnv; | ||
| }); | ||
|
|
||
| it('allows default secrets in development mode', () => { | ||
| process.env.NODE_ENV = 'development'; | ||
| expect(() => { | ||
| createAuthBackend({ | ||
| mongoUri: 'mongodb://localhost:27017/test-dev' | ||
| }); | ||
| }).not.toThrow(); | ||
| }); | ||
|
|
||
| it('throws an error in production if jwtSecret uses an insecure default', () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| expect(() => { | ||
| createAuthBackend({ | ||
| jwtSecret: 'your-secret-key-change-in-production', | ||
| jwtRefreshSecret: 'a-secure-production-refresh-secret-12345' | ||
| }); | ||
| }).toThrow(/Insecure default or empty jwtSecret/i); | ||
| }); | ||
|
|
||
| it('throws an error in production if jwtRefreshSecret uses an insecure default', () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| expect(() => { | ||
| createAuthBackend({ | ||
| jwtSecret: 'a-secure-production-access-secret-12345', | ||
| jwtRefreshSecret: 'your-secret-key-change-in-production' | ||
| }); | ||
| }).toThrow(/Insecure default or empty jwtRefreshSecret/i); | ||
| }); | ||
|
|
||
| it('throws an error in production if jwtSecret equals jwtRefreshSecret', () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| const sharedSecret = 'identical-secret-shared-across-both-tokens'; | ||
| expect(() => { | ||
| createAuthBackend({ | ||
| jwtSecret: sharedSecret, | ||
| jwtRefreshSecret: sharedSecret | ||
| }); | ||
| }).toThrow(/jwtSecret and jwtRefreshSecret must be distinct/i); | ||
| }); | ||
|
|
||
| it('succeeds in production with distinct, secure secrets', () => { | ||
| process.env.NODE_ENV = 'production'; | ||
| expect(() => { | ||
| createAuthBackend({ | ||
| jwtSecret: 'super-secure-production-access-key-abc-xyz', | ||
| jwtRefreshSecret: 'another-super-secure-production-refresh-key-123-789' | ||
| }); | ||
| }).not.toThrow(); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.