Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,10 @@
"@types/passport": "^1.0.17",
"@types/passport-google-oauth20": "^2.0.17",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^7.2.0",
"eslint": "^9.39.1",
"jest": "^30.4.2",
"supertest": "^7.2.2",
"ts-jest": "^29.4.11",
"typescript": "5.9.2"
}
Expand Down
4 changes: 4 additions & 0 deletions apps/api/src/__mocks__/db-client.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,17 @@ export const mockPrismaClient = {
findUnique: jest.fn(),
findFirst: jest.fn(),
},
userDepartment: {
findFirst: jest.fn(),
},
};

export class PrismaClient {
$connect = mockPrismaClient.$connect;
$disconnect = mockPrismaClient.$disconnect;
user = mockPrismaClient.user;
organization = mockPrismaClient.organization;
userDepartment = mockPrismaClient.userDepartment;
}

export const Prisma = {};
26 changes: 19 additions & 7 deletions apps/api/src/app.module.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { AppModule } from "./app.module";
import { MCPController } from "./mcp/mcp.controller";
import { GoogleStrategy } from "./auth/strategies/google.strategy";
import { PrismaService } from "./prisma/prisma.service";
import type { AuthenticatedUser } from "./auth/auth.types";

/** Stub that replaces GoogleStrategy so tests don't need real OAuth credentials. */
class MockGoogleStrategy {
Expand All @@ -15,6 +16,19 @@ class MockPrismaService {
$disconnect = jest.fn().mockResolvedValue(undefined);
user = { findUnique: jest.fn(), create: jest.fn() };
organization = { findFirst: jest.fn() };
userDepartment = { findFirst: jest.fn().mockResolvedValue(null) };
}

const mockJwtUser: AuthenticatedUser = {
id: "test_user",
email: "test@example.com",
organizationId: "test_org",
role: "member",
};

function makeMockReq(user: AuthenticatedUser = mockJwtUser) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { user } as any;
}

describe("AppModule", () => {
Expand Down Expand Up @@ -50,7 +64,7 @@ describe("AppModule", () => {
.overrideProvider(PrismaService)
.useClass(MockPrismaService)
.compile(),
).resolves.not.toThrow();
).resolves.toBeDefined();
});

it("should provide MCPController via imported MCPModule", async () => {
Expand Down Expand Up @@ -79,12 +93,10 @@ describe("AppModule", () => {
.compile();

const controller = module.get(MCPController);
const response = await controller.handleMCP({
userId: "test_user",
organizationId: "test_org",
departmentId: "test_dept",
query: "integration check",
});
const response = await controller.handleMCP(
{ query: "integration check" },
makeMockReq(),
);

expect(response.answer).toBe(
"Based on company standards: integration check",
Expand Down
209 changes: 209 additions & 0 deletions apps/api/src/mcp/identity.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { IdentityService } from "./identity.service";
import type { PrismaService } from "../prisma/prisma.service";

/** Minimal mock shape for PrismaService covering only what IdentityService uses. */
function makeMockPrisma() {
return {
userDepartment: {
findFirst: jest.fn(),
},
};
}

describe("IdentityService", () => {
let service: IdentityService;
let prisma: ReturnType<typeof makeMockPrisma>;

beforeEach(() => {
prisma = makeMockPrisma();
service = new IdentityService(prisma as unknown as PrismaService);
});

afterEach(() => {
jest.clearAllMocks();
});

describe("resolveScope", () => {
it("returns organizationId and departmentId when a primary department exists", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce({
id: "ud_1",
userId: "user_123",
departmentId: "dept_789",
isPrimary: true,
});

const result = await service.resolveScope("user_123", "org_456");

expect(result).toEqual({
organizationId: "org_456",
departmentId: "dept_789",
});
});

it("returns null departmentId when no primary department row exists", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

const result = await service.resolveScope("user_no_dept", "org_456");

expect(result).toEqual({
organizationId: "org_456",
departmentId: null,
});
});

it("queries userDepartment with userId, isPrimary: true, and organization constraint", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

await service.resolveScope("user_abc", "org_xyz");

expect(prisma.userDepartment.findFirst).toHaveBeenCalledWith({
where: {
userId: "user_abc",
isPrimary: true,
department: { organizationId: "org_xyz" },
},
});
});

it("passes organizationId through from the parameter, not from the database", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce({
id: "ud_2",
userId: "user_123",
departmentId: "dept_from_db",
isPrimary: true,
});

const result = await service.resolveScope("user_123", "org_from_jwt");

expect(result.organizationId).toBe("org_from_jwt");
});

it("uses departmentId from the matched UserDepartment row, not the row's own id", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce({
id: "join_table_row_id",
userId: "user_123",
departmentId: "the_real_dept_id",
isPrimary: true,
});

const result = await service.resolveScope("user_123", "org_456");

expect(result.departmentId).toBe("the_real_dept_id");
expect(result.departmentId).not.toBe("join_table_row_id");
});

it("forwards the exact userId to the prisma query", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

await service.resolveScope("user_exact_id_check", "org_456");

expect(prisma.userDepartment.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ userId: "user_exact_id_check" }),
}),
);
});

it("always queries with isPrimary: true regardless of what the db returns", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce({
id: "ud_3",
userId: "user_123",
departmentId: "dept_456",
isPrimary: true,
});

await service.resolveScope("user_123", "org_456");

expect(prisma.userDepartment.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ isPrimary: true }),
}),
);
});

it("calls userDepartment.findFirst exactly once per resolveScope call", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

await service.resolveScope("user_123", "org_456");

expect(prisma.userDepartment.findFirst).toHaveBeenCalledTimes(1);
});

it("issues separate db queries for separate resolveScope calls", async () => {
prisma.userDepartment.findFirst
.mockResolvedValueOnce({ id: "ud_a", userId: "user_a", departmentId: "dept_a", isPrimary: true })
.mockResolvedValueOnce(null);

const [resultA, resultB] = await Promise.all([
service.resolveScope("user_a", "org_a"),
service.resolveScope("user_b", "org_b"),
]);

expect(prisma.userDepartment.findFirst).toHaveBeenCalledTimes(2);
expect(resultA.departmentId).toBe("dept_a");
expect(resultB.departmentId).toBeNull();
});

it("returns a Promise", () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

const returnValue = service.resolveScope("user_123", "org_456");

expect(returnValue).toBeInstanceOf(Promise);
});

it("different users with the same organizationId get independent dept lookups", async () => {
prisma.userDepartment.findFirst
.mockResolvedValueOnce({ id: "ud_1", userId: "user_1", departmentId: "dept_for_user1", isPrimary: true })
.mockResolvedValueOnce({ id: "ud_2", userId: "user_2", departmentId: "dept_for_user2", isPrimary: true });

const result1 = await service.resolveScope("user_1", "shared_org");
const result2 = await service.resolveScope("user_2", "shared_org");

expect(result1.departmentId).toBe("dept_for_user1");
expect(result2.departmentId).toBe("dept_for_user2");
expect(result1.organizationId).toBe("shared_org");
expect(result2.organizationId).toBe("shared_org");
});

it("handles an empty string userId without throwing", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce(null);

const result = await service.resolveScope("", "org_456");

expect(result.departmentId).toBeNull();
expect(result.organizationId).toBe("org_456");
expect(prisma.userDepartment.findFirst).toHaveBeenCalledWith({
where: {
userId: "",
isPrimary: true,
department: { organizationId: "org_456" },
},
});
});

it("propagates errors thrown by the prisma query", async () => {
const dbError = new Error("Database connection lost");
prisma.userDepartment.findFirst.mockRejectedValueOnce(dbError);

await expect(service.resolveScope("user_123", "org_456")).rejects.toThrow(
"Database connection lost",
);
});

it("scope object has exactly the organizationId and departmentId keys", async () => {
prisma.userDepartment.findFirst.mockResolvedValueOnce({
id: "ud_1",
userId: "user_123",
departmentId: "dept_789",
isPrimary: true,
});

const result = await service.resolveScope("user_123", "org_456");

expect(Object.keys(result).sort()).toEqual(
["departmentId", "organizationId"].sort(),
);
});
});
});
37 changes: 37 additions & 0 deletions apps/api/src/mcp/identity.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Injectable } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";

export interface ResolvedScope {
organizationId: string;
departmentId: string | null;
}

@Injectable()
export class IdentityService {
constructor(private readonly prisma: PrismaService) {}

/**
* Resolves the identity scope for a request.
*
* The organizationId comes directly from the validated JWT claim.
* The departmentId is looked up from the UserDepartment join table,
* selecting the row flagged as the user's Primary Department.
* The department relation filter on organizationId ensures cross-org
* isolation: a user cannot accidentally resolve a department that belongs
* to a different organization.
* Returns null for departmentId when no primary department is configured.
*/
async resolveScope(
userId: string,
organizationId: string,
): Promise<ResolvedScope> {
const primaryDept = await this.prisma.userDepartment.findFirst({
where: { userId, isPrimary: true, department: { organizationId } },
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.

return {
organizationId,
departmentId: primaryDept?.departmentId ?? null,
};
}
}
Loading
Loading