Repository navigation
feat(rbac): implement organization RBAC middleware and membership models (Fixes #106) #155
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,282 @@ | ||
| const mongoose = require('mongoose'); | ||
| const { requireRole, ROLE_HIERARCHY } = require('../middleware/rbac'); | ||
| const Organization = require('../models/Organization'); | ||
|
|
||
| describe('Organization RBAC Middleware (Issue #106)', () => { | ||
| const userId = new mongoose.Types.ObjectId().toString(); | ||
| const orgId = new mongoose.Types.ObjectId().toString(); | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| }); | ||
|
|
||
| describe('Configuration & Role Validation', () => { | ||
| it('throws synchronously when initialized with an invalid or undeclared role', () => { | ||
| expect(() => requireRole('superadmin')).toThrow(/Invalid role requirement/); | ||
| expect(() => requireRole(null)).toThrow(/Invalid role requirement/); | ||
| expect(() => requireRole(123)).toThrow(/Invalid role requirement/); | ||
| expect(() => requireRole('constructor')).toThrow(/Invalid role requirement/); | ||
| }); | ||
|
|
||
| it('exports expected role hierarchy with monotonic numeric ranks', () => { | ||
| expect(ROLE_HIERARCHY.member).toBeLessThan(ROLE_HIERARCHY.admin); | ||
| expect(ROLE_HIERARCHY.admin).toBeLessThan(ROLE_HIERARCHY.owner); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Authentication & Identity Guards', () => { | ||
| it('rejects with 401 if req.user is absent', async () => { | ||
| const middleware = requireRole('member'); | ||
| const req = { params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| success: false, | ||
| message: expect.stringContaining('Authentication required') | ||
| })); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rejects with 401 if req.user lacks userId, id, and _id', async () => { | ||
| const middleware = requireRole('member'); | ||
| const req = { user: {}, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(401); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('successfully resolves identity when req.user contains userId from verified JWT', async () => { | ||
| const mockOrg = { | ||
| _id: orgId, | ||
| members: [{ userId: new mongoose.Types.ObjectId(userId), role: 'member' }] | ||
| }; | ||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue(mockOrg) | ||
| }); | ||
|
|
||
| const middleware = requireRole('member'); | ||
| const req = { user: { userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(next).toHaveBeenCalledWith(); | ||
| expect(req.orgMembership.role).toBe('member'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Organization Context Resolution & Validation', () => { | ||
| it('rejects with 400 if no orgId context is provided across params, query, or headers', async () => { | ||
| const middleware = requireRole('member'); | ||
| const req = { user: { id: userId }, params: {}, query: {}, headers: {} }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| success: false, | ||
| message: expect.stringContaining('Active organization context') | ||
| })); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rejects with 400 when query parameter orgId is array-valued', async () => { | ||
| const middleware = requireRole('member'); | ||
| const req = { user: { id: userId }, query: { orgId: [orgId, 'another-id'] } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rejects with 400 when orgId has invalid ObjectId format', async () => { | ||
| const middleware = requireRole('member'); | ||
| const req = { user: { id: userId }, params: { orgId: 'invalid-non-hex-id' } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(400); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| success: false, | ||
| message: 'Invalid organization ID format.' | ||
| })); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('returns 404 when organization does not exist in database', async () => { | ||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue(null) | ||
| }); | ||
|
|
||
| const middleware = requireRole('member'); | ||
| const req = { user: { id: userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(404); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('Membership & Permission Enforcement', () => { | ||
| it('returns 403 when user is not a member of the organization', async () => { | ||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue({ | ||
| _id: orgId, | ||
| members: [{ userId: new mongoose.Types.ObjectId(), role: 'admin' }] | ||
| }) | ||
| }); | ||
|
|
||
| const middleware = requireRole('member'); | ||
| const req = { user: { id: userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(403); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| message: expect.stringContaining('not a member') | ||
| })); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('skips null or corrupted membership entries and finds matching user membership', async () => { | ||
| const mockOrg = { | ||
| _id: orgId, | ||
| members: [ | ||
| null, | ||
| undefined, | ||
| { userId: null, role: 'admin' }, | ||
| { userId: new mongoose.Types.ObjectId(userId), role: 'admin' } | ||
| ] | ||
| }; | ||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue(mockOrg) | ||
| }); | ||
|
|
||
| const middleware = requireRole('admin'); | ||
| const req = { user: { id: userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(next).toHaveBeenCalledWith(); | ||
| expect(req.orgMembership.role).toBe('admin'); | ||
| }); | ||
|
|
||
| it('returns 403 when user role is below required threshold (member requesting admin)', async () => { | ||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue({ | ||
| _id: orgId, | ||
| members: [{ userId: new mongoose.Types.ObjectId(userId), role: 'member' }] | ||
| }) | ||
| }); | ||
|
|
||
| const middleware = requireRole('admin'); | ||
| const req = { user: { id: userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(res.status).toHaveBeenCalledWith(403); | ||
| expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ | ||
| message: expect.stringContaining('Requires "admin" role or higher') | ||
| })); | ||
| expect(next).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('allows access and attaches org context when user satisfies role requirement', async () => { | ||
| const mockOrg = { | ||
| _id: orgId, | ||
| name: 'Engineering', | ||
| members: [{ userId: new mongoose.Types.ObjectId(userId), role: 'admin' }] | ||
| }; | ||
|
|
||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue(mockOrg) | ||
| }); | ||
|
|
||
| const middleware = requireRole('admin'); | ||
| const req = { user: { id: userId }, params: { orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(next).toHaveBeenCalledWith(); | ||
| expect(req.organization).toBeDefined(); | ||
| expect(req.orgMembership.role).toBe('admin'); | ||
| }); | ||
|
|
||
| it('allows owner to access admin and member endpoints with header context', async () => { | ||
| const mockOrg = { | ||
| _id: orgId, | ||
| name: 'Founders', | ||
| members: [{ userId: new mongoose.Types.ObjectId(userId), role: 'owner' }] | ||
| }; | ||
|
|
||
| jest.spyOn(Organization, 'findById').mockReturnValue({ | ||
| lean: jest.fn().mockResolvedValue(mockOrg) | ||
| }); | ||
|
|
||
| const middleware = requireRole('admin'); | ||
| const req = { user: { id: userId }, params: {}, query: {}, headers: { 'x-organization-id': orgId } }; | ||
| const res = { | ||
| status: jest.fn().mockReturnThis(), | ||
| json: jest.fn() | ||
| }; | ||
| const next = jest.fn(); | ||
|
|
||
| await middleware(req, res, next); | ||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(next).toHaveBeenCalledWith(); | ||
| expect(req.orgMembership.role).toBe('owner'); | ||
| }); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,114 @@ | ||||||||||
| const mongoose = require('mongoose'); | ||||||||||
| const Organization = require('../models/Organization'); | ||||||||||
|
|
||||||||||
| const ROLE_HIERARCHY = { | ||||||||||
| member: 1, | ||||||||||
| admin: 2, | ||||||||||
| owner: 3 | ||||||||||
| }; | ||||||||||
|
|
||||||||||
| /** | ||||||||||
| * Route middleware that enforces a minimum role within the active organization. | ||||||||||
| * Expects `req.user` to be populated by authMiddleware. | ||||||||||
| * Looks for organization ID via params (`:orgId`), query (`?orgId=`), or header (`x-organization-id`). | ||||||||||
| * | ||||||||||
| * Usage: | ||||||||||
| * router.post('/settings', authMiddleware, requireRole('admin'), updateOrgSettings) | ||||||||||
| */ | ||||||||||
| function requireRole(minRole = 'member') { | ||||||||||
| if (typeof minRole !== 'string' || !Object.prototype.hasOwnProperty.call(ROLE_HIERARCHY, minRole)) { | ||||||||||
| throw new Error(`Invalid role requirement: "${minRole}". Must be one of: member, admin, owner.`); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| return async function roleMiddleware(req, res, next) { | ||||||||||
| try { | ||||||||||
| if (!req.user) { | ||||||||||
| return res.status(401).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'Authentication required before role verification.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // Resolve user identity: prioritize token payload userId, then id / _id fallbacks | ||||||||||
| const resolvedId = req.user.userId || req.user.id || req.user._id; | ||||||||||
| if (!resolvedId) { | ||||||||||
| return res.status(401).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'Authentication required before role verification.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
| const userId = resolvedId.toString(); | ||||||||||
|
|
||||||||||
| // Resolve organization ID context with route > query > header precedence | ||||||||||
| let rawOrgId; | ||||||||||
| if (req.params && req.params.orgId !== undefined) { | ||||||||||
| rawOrgId = req.params.orgId; | ||||||||||
| } else if (req.query && req.query.orgId !== undefined) { | ||||||||||
| rawOrgId = req.query.orgId; | ||||||||||
| } else if (req.headers && req.headers['x-organization-id'] !== undefined) { | ||||||||||
| rawOrgId = req.headers['x-organization-id']; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // Reject missing, array-valued, or non-string query parameters | ||||||||||
| if (!rawOrgId || typeof rawOrgId !== 'string' || Array.isArray(rawOrgId)) { | ||||||||||
| return res.status(400).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'Active organization context (orgId) is required and must be a single string.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| const orgId = rawOrgId.trim(); | ||||||||||
|
|
||||||||||
| // Reject malformed ObjectId strings before query | ||||||||||
| if (!mongoose.isValidObjectId(orgId)) { | ||||||||||
| return res.status(400).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'Invalid organization ID format.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // Query organization membership | ||||||||||
| const organization = await Organization.findById(orgId).lean(); | ||||||||||
| if (!organization) { | ||||||||||
| return res.status(404).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'Organization not found.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // Safely find membership skipping any null or malformed entries | ||||||||||
| const membership = organization.members?.find( | ||||||||||
| m => m && m.userId && m.userId.toString() === userId | ||||||||||
| ); | ||||||||||
|
|
||||||||||
| if (!membership) { | ||||||||||
| return res.status(403).json({ | ||||||||||
| success: false, | ||||||||||
| message: 'User is not a member of this organization.' | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| const userRoleRank = ROLE_HIERARCHY[membership.role] || 0; | ||||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Deny access when the membership role is not a recognized rank. The rank lookup reads any property reachable from Schema validation normally blocks non-enum roles on save, so this path requires a stored value that bypasses validation. Check the lookup against the declared ranks so that the check fails closed. Suggested fix
Committable suggestion
|
||||||||||
| const requiredRoleRank = ROLE_HIERARCHY[minRole]; | ||||||||||
|
|
||||||||||
| if (userRoleRank < requiredRoleRank) { | ||||||||||
| return res.status(403).json({ | ||||||||||
| success: false, | ||||||||||
| message: `Insufficient permissions. Requires "${minRole}" role or higher.` | ||||||||||
| }); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| // Attach active organization and user membership details to request | ||||||||||
| req.organization = organization; | ||||||||||
| req.orgMembership = membership; | ||||||||||
| next(); | ||||||||||
| } catch (err) { | ||||||||||
| next(err); | ||||||||||
| } | ||||||||||
| }; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| module.exports = { | ||||||||||
| requireRole, | ||||||||||
| ROLE_HIERARCHY | ||||||||||
| }; | ||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Validate the HTTP ID format before looking up the organization.
The locked Mongoose 7.8.13 and BSON 5.5.1 versions accept
abcdefghijklas a 12-byte ObjectId. The guard lets it reachfindById, which casts it. If no organization matches, the middleware returns 404 instead of 400. Require a string with exactly 24 hexadecimal characters after trimming. Valid IDs will still reach the lookup, where they can return 404 if the organization does not exist. (raw.githubusercontent.com)Based on learnings, the standard ObjectId string representation is exactly 24 hexadecimal characters.
Source: Learnings