feat(phase-3): workstream 1 — Multi-Tenancy

Introduces full multi-tenant organization model to AgentIdP:

Schema:
- 6 migrations: organizations + organization_members tables; organization_id FK
  added to agents, credentials, audit_logs; PostgreSQL RLS policies on all three
  tables; system org seed + backfill

API:
- 6 new /api/v1/organizations endpoints (CRUD + members) gated by admin:orgs scope
- OPA scopes.json updated with 6 new org endpoint → admin:orgs mappings

Implementation:
- OrgRepository, OrgService, OrgController, createOrgsRouter
- OrgContextMiddleware: sets app.organization_id session variable so RLS enforces
  per-request org isolation at the database layer
- JWT payload extended with organization_id claim; auth.ts backfills org_system
  for backward-compatible tokens
- New error classes: OrgNotFoundError, OrgHasActiveAgentsError, AlreadyMemberError

Tests: 373 passing, 80.64% branch coverage, zero any types

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
SentryAgent.ai Developer
2026-03-30 00:29:32 +00:00
parent cb7d079ef6
commit d252097f71
31 changed files with 3043 additions and 35 deletions

View File

@@ -26,6 +26,7 @@ const MOCK_USER: ITokenPayload = {
const MOCK_AGENT: IAgent = {
agentId: 'agent-id-001',
organizationId: 'org_system',
email: 'agent@sentryagent.ai',
agentType: 'screener',
version: '1.0.0',

View File

@@ -0,0 +1,136 @@
/**
* Unit tests for src/middleware/orgContext.ts
*/
import { Request, Response, NextFunction } from 'express';
import { Pool } from 'pg';
import { ITokenPayload } from '../../../src/types/index';
// Mock pg Pool
jest.mock('pg', () => {
const mockQuery = jest.fn();
return {
Pool: jest.fn().mockImplementation(() => ({ query: mockQuery })),
};
});
import { createOrgContextMiddleware } from '../../../src/middleware/orgContext';
/** Builds a minimal ITokenPayload for test requests. */
function makeUser(overrides: Partial<ITokenPayload> = {}): ITokenPayload {
return {
sub: 'agent-abc-123',
client_id: 'agent-abc-123',
scope: 'agents:read',
jti: 'jti-001',
iat: 1000,
exp: 9999999999,
...overrides,
};
}
describe('createOrgContextMiddleware', () => {
let pool: jest.Mocked<Pool>;
let mockQuery: jest.Mock;
let next: jest.MockedFunction<NextFunction>;
const originalDefaultOrgId = process.env['DEFAULT_ORG_ID'];
beforeEach(() => {
jest.clearAllMocks();
// Get the mocked pool instance and its query function
pool = new Pool() as jest.Mocked<Pool>;
mockQuery = pool.query as jest.Mock;
mockQuery.mockResolvedValue({ rows: [], rowCount: 0 });
next = jest.fn();
});
afterEach(() => {
if (originalDefaultOrgId === undefined) {
delete process.env['DEFAULT_ORG_ID'];
} else {
process.env['DEFAULT_ORG_ID'] = originalDefaultOrgId;
}
});
it('should set app.organization_id from req.user.organization_id when present', async () => {
const middleware = createOrgContextMiddleware(pool);
const req = {
user: makeUser({ organization_id: 'org_TENANT123' }),
} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(mockQuery).toHaveBeenCalledWith('SET app.organization_id = $1', ['org_TENANT123']);
expect(next).toHaveBeenCalledWith();
expect(next).toHaveBeenCalledTimes(1);
});
it('should fall back to DEFAULT_ORG_ID env var when req.user has no organization_id', async () => {
process.env['DEFAULT_ORG_ID'] = 'org_default_from_env';
const middleware = createOrgContextMiddleware(pool);
const req = {
user: makeUser({ organization_id: undefined }),
} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(mockQuery).toHaveBeenCalledWith('SET app.organization_id = $1', ['org_default_from_env']);
expect(next).toHaveBeenCalledWith();
});
it('should fall back to "org_system" when req.user is absent and DEFAULT_ORG_ID is not set', async () => {
delete process.env['DEFAULT_ORG_ID'];
const middleware = createOrgContextMiddleware(pool);
const req = {} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(mockQuery).toHaveBeenCalledWith('SET app.organization_id = $1', ['org_system']);
expect(next).toHaveBeenCalledWith();
});
it('should fall back to "org_system" when DEFAULT_ORG_ID is not set and user has no organization_id', async () => {
delete process.env['DEFAULT_ORG_ID'];
const middleware = createOrgContextMiddleware(pool);
const req = {
user: makeUser({ organization_id: undefined }),
} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(mockQuery).toHaveBeenCalledWith('SET app.organization_id = $1', ['org_system']);
expect(next).toHaveBeenCalledWith();
});
it('should call next(err) when pool.query throws', async () => {
const dbError = new Error('Database connection failed');
mockQuery.mockRejectedValue(dbError);
const middleware = createOrgContextMiddleware(pool);
const req = {
user: makeUser({ organization_id: 'org_TENANT123' }),
} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(next).toHaveBeenCalledWith(dbError);
expect(next).toHaveBeenCalledTimes(1);
});
it('should call next(err) with pool error when req.user is absent and pool throws', async () => {
const dbError = new Error('Pool exhausted');
mockQuery.mockRejectedValue(dbError);
delete process.env['DEFAULT_ORG_ID'];
const middleware = createOrgContextMiddleware(pool);
const req = {} as Request;
const res = {} as Response;
await middleware(req, res, next);
expect(next).toHaveBeenCalledWith(dbError);
});
});

View File

@@ -18,6 +18,7 @@ jest.mock('pg', () => ({
const AGENT_ROW = {
agent_id: 'a1b2c3d4-0000-0000-0000-000000000001',
organization_id: 'org_system',
email: 'agent@sentryagent.ai',
agent_type: 'screener',
version: '1.0.0',
@@ -31,6 +32,7 @@ const AGENT_ROW = {
const EXPECTED_AGENT: IAgent = {
agentId: AGENT_ROW.agent_id,
organizationId: AGENT_ROW.organization_id,
email: AGENT_ROW.email,
agentType: 'screener',
version: AGENT_ROW.version,

View File

@@ -25,6 +25,7 @@ const MockAuditService = AuditService as jest.MockedClass<typeof AuditService>;
const MOCK_AGENT: IAgent = {
agentId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
organizationId: 'org_system',
email: 'agent@sentryagent.ai',
agentType: 'screener',
version: '1.0.0',
@@ -159,6 +160,69 @@ describe('AgentService', () => {
agentService.updateAgent(MOCK_AGENT.agentId, { version: '2.0.0' }, IP, UA),
).rejects.toThrow(AgentAlreadyDecommissionedError);
});
it('should throw AgentNotFoundError when update() returns null (race condition)', async () => {
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
agentRepo.update.mockResolvedValue(null);
await expect(
agentService.updateAgent(MOCK_AGENT.agentId, { version: '2.0.0' }, IP, UA),
).rejects.toThrow(AgentNotFoundError);
});
it('should log agent.suspended audit action when status changes to suspended', async () => {
const updated = { ...MOCK_AGENT, status: 'suspended' as const };
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
agentRepo.update.mockResolvedValue(updated);
auditService.logEvent.mockResolvedValue({} as never);
await agentService.updateAgent(MOCK_AGENT.agentId, { status: 'suspended' }, IP, UA);
expect(auditService.logEvent).toHaveBeenCalledWith(
MOCK_AGENT.agentId,
'agent.suspended',
'success',
IP,
UA,
expect.any(Object),
);
});
it('should log agent.reactivated audit action when status changes from suspended to active', async () => {
const suspended = { ...MOCK_AGENT, status: 'suspended' as const };
const reactivated = { ...MOCK_AGENT, status: 'active' as const };
agentRepo.findById.mockResolvedValue(suspended);
agentRepo.update.mockResolvedValue(reactivated);
auditService.logEvent.mockResolvedValue({} as never);
await agentService.updateAgent(suspended.agentId, { status: 'active' }, IP, UA);
expect(auditService.logEvent).toHaveBeenCalledWith(
suspended.agentId,
'agent.reactivated',
'success',
IP,
UA,
expect.any(Object),
);
});
it('should log agent.decommissioned audit action when status changes to decommissioned via update', async () => {
const updated = { ...MOCK_AGENT, status: 'decommissioned' as const };
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
agentRepo.update.mockResolvedValue(updated);
auditService.logEvent.mockResolvedValue({} as never);
await agentService.updateAgent(MOCK_AGENT.agentId, { status: 'decommissioned' }, IP, UA);
expect(auditService.logEvent).toHaveBeenCalledWith(
MOCK_AGENT.agentId,
'agent.decommissioned',
'success',
IP,
UA,
expect.any(Object),
);
});
});
// ────────────────────────────────────────────────────────────────

View File

@@ -31,6 +31,7 @@ const CREDENTIAL_ID = uuidv4();
const MOCK_AGENT: IAgent = {
agentId: AGENT_ID,
organizationId: 'org_system',
email: 'agent@sentryagent.ai',
agentType: 'screener',
version: '1.0.0',

View File

@@ -36,6 +36,7 @@ const MockAuditService = AuditService as jest.MockedClass<typeof AuditService>;
const MOCK_AGENT_ID = uuidv4();
const MOCK_AGENT: IAgent = {
agentId: MOCK_AGENT_ID,
organizationId: 'org_system',
email: 'agent@sentryagent.ai',
agentType: 'screener',
version: '1.0.0',

View File

@@ -0,0 +1,297 @@
/**
* Unit tests for src/services/OrgService.ts
*/
import { OrgService } from '../../../src/services/OrgService';
import { OrgRepository } from '../../../src/repositories/OrgRepository';
import { AgentRepository } from '../../../src/repositories/AgentRepository';
import {
OrgNotFoundError,
OrgHasActiveAgentsError,
AlreadyMemberError,
ValidationError,
AgentNotFoundError,
} from '../../../src/utils/errors';
import { IOrganization, IOrgMember } from '../../../src/types/organization';
import { IAgent } from '../../../src/types/index';
// Mock dependencies
jest.mock('../../../src/repositories/OrgRepository');
jest.mock('../../../src/repositories/AgentRepository');
const MockOrgRepository = OrgRepository as jest.MockedClass<typeof OrgRepository>;
const MockAgentRepository = AgentRepository as jest.MockedClass<typeof AgentRepository>;
const MOCK_ORG: IOrganization = {
organizationId: 'org_01ABCDEFGHIJKLMNOPQRSTU',
name: 'Acme Corp',
slug: 'acme-corp',
planTier: 'pro',
maxAgents: 100,
maxTokensPerMonth: 10000,
status: 'active',
createdAt: new Date('2026-03-28T09:00:00Z'),
updatedAt: new Date('2026-03-28T09:00:00Z'),
};
const MOCK_AGENT: IAgent = {
agentId: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
organizationId: MOCK_ORG.organizationId,
email: 'agent@sentryagent.ai',
agentType: 'screener',
version: '1.0.0',
capabilities: ['resume:read'],
owner: 'team-a',
deploymentEnv: 'production',
status: 'active',
createdAt: new Date('2026-03-28T09:00:00Z'),
updatedAt: new Date('2026-03-28T09:00:00Z'),
};
const MOCK_MEMBER: IOrgMember = {
memberId: 'mem_01ABCDEFGHIJKLMNOPQRSTU',
organizationId: MOCK_ORG.organizationId,
agentId: MOCK_AGENT.agentId,
role: 'member',
joinedAt: new Date('2026-03-28T09:00:00Z'),
};
describe('OrgService', () => {
let orgService: OrgService;
let orgRepo: jest.Mocked<OrgRepository>;
let agentRepo: jest.Mocked<AgentRepository>;
beforeEach(() => {
jest.clearAllMocks();
orgRepo = new MockOrgRepository({} as never) as jest.Mocked<OrgRepository>;
agentRepo = new MockAgentRepository({} as never) as jest.Mocked<AgentRepository>;
orgService = new OrgService(orgRepo, agentRepo);
});
// ────────────────────────────────────────────────────────────────
// createOrg
// ────────────────────────────────────────────────────────────────
describe('createOrg()', () => {
const createData = { name: 'Acme Corp', slug: 'acme-corp', planTier: 'pro' as const };
it('should create and return a new organization when slug is unique', async () => {
orgRepo.findBySlug.mockResolvedValue(null);
orgRepo.create.mockResolvedValue(MOCK_ORG);
const result = await orgService.createOrg(createData);
expect(result).toEqual(MOCK_ORG);
expect(orgRepo.findBySlug).toHaveBeenCalledWith(createData.slug);
expect(orgRepo.create).toHaveBeenCalledWith(createData);
});
it('should throw ValidationError with SLUG_ALREADY_EXISTS when slug is taken', async () => {
orgRepo.findBySlug.mockResolvedValue(MOCK_ORG);
await expect(orgService.createOrg(createData)).rejects.toThrow(ValidationError);
await expect(orgService.createOrg(createData)).rejects.toMatchObject({
details: { code: 'SLUG_ALREADY_EXISTS', slug: createData.slug },
});
expect(orgRepo.create).not.toHaveBeenCalled();
});
});
// ────────────────────────────────────────────────────────────────
// listOrgs
// ────────────────────────────────────────────────────────────────
describe('listOrgs()', () => {
it('should return a paginated list of organizations', async () => {
orgRepo.findAll.mockResolvedValue({ orgs: [MOCK_ORG], total: 1 });
const result = await orgService.listOrgs({ page: 1, limit: 20 });
expect(result.data).toHaveLength(1);
expect(result.total).toBe(1);
expect(result.page).toBe(1);
expect(result.limit).toBe(20);
});
it('should pass filters through to the repository', async () => {
orgRepo.findAll.mockResolvedValue({ orgs: [], total: 0 });
await orgService.listOrgs({ page: 2, limit: 10, status: 'active' });
expect(orgRepo.findAll).toHaveBeenCalledWith({ page: 2, limit: 10, status: 'active' });
});
it('should return an empty list when no organizations exist', async () => {
orgRepo.findAll.mockResolvedValue({ orgs: [], total: 0 });
const result = await orgService.listOrgs({ page: 1, limit: 20 });
expect(result.data).toHaveLength(0);
expect(result.total).toBe(0);
});
});
// ────────────────────────────────────────────────────────────────
// getOrg
// ────────────────────────────────────────────────────────────────
describe('getOrg()', () => {
it('should return the organization when found', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
const result = await orgService.getOrg(MOCK_ORG.organizationId);
expect(result).toEqual(MOCK_ORG);
expect(orgRepo.findById).toHaveBeenCalledWith(MOCK_ORG.organizationId);
});
it('should throw OrgNotFoundError when organization does not exist', async () => {
orgRepo.findById.mockResolvedValue(null);
await expect(orgService.getOrg('nonexistent-org-id')).rejects.toThrow(OrgNotFoundError);
});
});
// ────────────────────────────────────────────────────────────────
// updateOrg
// ────────────────────────────────────────────────────────────────
describe('updateOrg()', () => {
it('should update and return the organization', async () => {
const updated = { ...MOCK_ORG, name: 'Acme Corp Updated' };
orgRepo.findById.mockResolvedValue(MOCK_ORG);
orgRepo.update.mockResolvedValue(updated);
const result = await orgService.updateOrg(MOCK_ORG.organizationId, { name: 'Acme Corp Updated' });
expect(result.name).toBe('Acme Corp Updated');
expect(orgRepo.update).toHaveBeenCalledWith(MOCK_ORG.organizationId, { name: 'Acme Corp Updated' });
});
it('should throw OrgNotFoundError when organization does not exist on findById', async () => {
orgRepo.findById.mockResolvedValue(null);
await expect(
orgService.updateOrg('nonexistent-id', { name: 'New Name' }),
).rejects.toThrow(OrgNotFoundError);
expect(orgRepo.update).not.toHaveBeenCalled();
});
it('should throw OrgNotFoundError when update returns null (race condition)', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
orgRepo.update.mockResolvedValue(null);
await expect(
orgService.updateOrg(MOCK_ORG.organizationId, { name: 'New Name' }),
).rejects.toThrow(OrgNotFoundError);
});
});
// ────────────────────────────────────────────────────────────────
// deleteOrg
// ────────────────────────────────────────────────────────────────
describe('deleteOrg()', () => {
it('should soft-delete the organization when it exists and has no active agents', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
orgRepo.countActiveAgents.mockResolvedValue(0);
orgRepo.softDelete.mockResolvedValue(true);
await orgService.deleteOrg(MOCK_ORG.organizationId);
expect(orgRepo.softDelete).toHaveBeenCalledWith(MOCK_ORG.organizationId);
});
it('should throw OrgNotFoundError when organization does not exist', async () => {
orgRepo.findById.mockResolvedValue(null);
await expect(orgService.deleteOrg('nonexistent-id')).rejects.toThrow(OrgNotFoundError);
expect(orgRepo.countActiveAgents).not.toHaveBeenCalled();
expect(orgRepo.softDelete).not.toHaveBeenCalled();
});
it('should throw OrgHasActiveAgentsError when organization has active agents', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
orgRepo.countActiveAgents.mockResolvedValue(3);
await expect(orgService.deleteOrg(MOCK_ORG.organizationId)).rejects.toThrow(OrgHasActiveAgentsError);
expect(orgRepo.softDelete).not.toHaveBeenCalled();
});
it('should include activeCount in OrgHasActiveAgentsError details', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
orgRepo.countActiveAgents.mockResolvedValue(5);
await expect(orgService.deleteOrg(MOCK_ORG.organizationId)).rejects.toMatchObject({
details: { activeCount: 5 },
});
});
});
// ────────────────────────────────────────────────────────────────
// addMember
// ────────────────────────────────────────────────────────────────
describe('addMember()', () => {
const addMemberData = { agentId: MOCK_AGENT.agentId, role: 'member' as const };
it('should add the agent as a member and return the membership record', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
orgRepo.findMember.mockResolvedValue(null);
orgRepo.addMember.mockResolvedValue(MOCK_MEMBER);
const result = await orgService.addMember(MOCK_ORG.organizationId, addMemberData);
expect(result).toEqual(MOCK_MEMBER);
expect(orgRepo.addMember).toHaveBeenCalledWith(
MOCK_ORG.organizationId,
MOCK_AGENT.agentId,
'member',
);
});
it('should throw OrgNotFoundError when organization does not exist', async () => {
orgRepo.findById.mockResolvedValue(null);
await expect(
orgService.addMember('nonexistent-org', addMemberData),
).rejects.toThrow(OrgNotFoundError);
expect(agentRepo.findById).not.toHaveBeenCalled();
});
it('should throw AgentNotFoundError when agent does not exist', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
agentRepo.findById.mockResolvedValue(null);
await expect(
orgService.addMember(MOCK_ORG.organizationId, addMemberData),
).rejects.toThrow(AgentNotFoundError);
expect(orgRepo.findMember).not.toHaveBeenCalled();
});
it('should throw AlreadyMemberError when agent is already a member', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
orgRepo.findMember.mockResolvedValue(MOCK_MEMBER);
await expect(
orgService.addMember(MOCK_ORG.organizationId, addMemberData),
).rejects.toThrow(AlreadyMemberError);
expect(orgRepo.addMember).not.toHaveBeenCalled();
});
it('should add member with admin role when role is admin', async () => {
orgRepo.findById.mockResolvedValue(MOCK_ORG);
agentRepo.findById.mockResolvedValue(MOCK_AGENT);
orgRepo.findMember.mockResolvedValue(null);
orgRepo.addMember.mockResolvedValue({ ...MOCK_MEMBER, role: 'admin' });
const result = await orgService.addMember(MOCK_ORG.organizationId, {
agentId: MOCK_AGENT.agentId,
role: 'admin',
});
expect(result.role).toBe('admin');
expect(orgRepo.addMember).toHaveBeenCalledWith(
MOCK_ORG.organizationId,
MOCK_AGENT.agentId,
'admin',
);
});
});
});