diff --git a/backend/__tests__/rbac.test.js b/backend/__tests__/rbac.test.js new file mode 100644 index 0000000..32c7410 --- /dev/null +++ b/backend/__tests__/rbac.test.js @@ -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'); + }); + }); +}); diff --git a/backend/middleware/rbac.js b/backend/middleware/rbac.js new file mode 100644 index 0000000..fe7276e --- /dev/null +++ b/backend/middleware/rbac.js @@ -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; + 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 +}; diff --git a/backend/models/Organization.js b/backend/models/Organization.js new file mode 100644 index 0000000..fccd2f9 --- /dev/null +++ b/backend/models/Organization.js @@ -0,0 +1,46 @@ +const mongoose = require('mongoose'); + +const OrganizationMemberSchema = new mongoose.Schema({ + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + }, + role: { + type: String, + enum: ['member', 'admin', 'owner'], + default: 'member', + required: true + }, + joinedAt: { + type: Date, + default: Date.now + } +}, { _id: false }); + +const OrganizationSchema = new mongoose.Schema({ + name: { + type: String, + required: true, + trim: true, + maxlength: 100 + }, + slug: { + type: String, + required: true, + unique: true, + lowercase: true, + trim: true + }, + ownerId: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + }, + members: [OrganizationMemberSchema] +}, { timestamps: true }); + +// Note: slug index is uniquely created by { unique: true } on field definition +OrganizationSchema.index({ 'members.userId': 1 }); + +module.exports = mongoose.models.Organization || mongoose.model('Organization', OrganizationSchema);