Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(external-group-org-role-mapping): enhance tests and service for role mapping functionality

Victor Hugo dos Santos43f1f09665c0
diff --git a/backend/e2e-test/routes/v1/external-group-org-role-mapping.spec.ts b/backend/e2e-test/routes/v1/external-group-org-role-mapping.spec.ts
index 33f3eea988..d41ebf6b9f 100644
--- a/backend/e2e-test/routes/v1/external-group-org-role-mapping.spec.ts
+++ b/backend/e2e-test/routes/v1/external-group-org-role-mapping.spec.ts
@@ -1,11 +1,10 @@
import { randomUUID } from "node:crypto";
+import { packRules } from "@casl/ability/extra";
import jwt from "jsonwebtoken";
-import { MockInstance, vi } from "vitest";
import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
-import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig, initEnvConfig } from "@app/lib/config/env";
import { initLogger, logger } from "@app/lib/logger";
@@ -13,9 +12,10 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";
import { AuthMethod, AuthTokenType } from "@app/services/auth/auth-type";
// SCIM applies a stored mapping to newly provisioned members with no user in the loop, so saving a
-// mapping is the grant. These cases pin the route-level contract the service tests cannot see: the
-// audit log records only what the service accepted, and a save cannot land on a mapping set other
-// than the one it was authorized against.
+// mapping is the grant. These cases run against real Postgres, which the service tests cannot: a
+// save must not land on a mapping set other than the one it was authorized against. The audit
+// ordering is pinned in external-group-org-role-mapping-router.test.ts, since the e2e plan drops
+// audit entries before anything observable.
const orgId = seedData1.organization.id;
const URL = "/api/v1/scim/group-org-role-mappings";
@@ -82,12 +82,7 @@ const putMappings = (headers: Record<string, string>, mappings: [string, string]
body: { mappings: mappings.map(([groupName, roleSlug]) => ({ groupName, roleSlug })) }
});
-type TAuditSpy = MockInstance<(typeof testServer.services.auditLog)["createAuditLog"]>;
-
-const auditEventsOfType = (spy: TAuditSpy, type: EventType) =>
- spy.mock.calls.filter(([arg]) => (arg as { event?: { type?: string } })?.event?.type === type);
-
-const waitForLockWaiter = async (lockKey: number, deadline = Date.now() + 10_000): Promise<void> => {
+const waitForLockWaiter = async (lockKey: number, deadline = Date.now() + 3_000): Promise<void> => {
const { rows } = await testDb.raw(
"SELECT count(*)::int AS waiting FROM pg_locks WHERE locktype = 'advisory' AND NOT granted AND objid = ?",
[lockKey]
@@ -104,7 +99,6 @@ describe("SCIM group to org role mappings", () => {
let editor: Awaited<ReturnType<typeof createOrgUser>>;
let member: Awaited<ReturnType<typeof createOrgUser>>;
let editorRoleId: string;
- let auditSpy: TAuditSpy;
beforeAll(async () => {
initLogger();
@@ -116,7 +110,7 @@ describe("SCIM group to org role mappings", () => {
name: "e2e-scim-mapping-editor",
slug: `e2e-scim-mapping-editor-${alphaNumericNanoId(8)}`,
orgId,
- permissions: JSON.stringify([{ subject: "scim", action: ["read", "edit"] }])
+ permissions: JSON.stringify(packRules([{ subject: "scim", action: ["read", "edit"] }] as never))
})
.returning("*");
editorRoleId = role.id;
@@ -127,11 +121,6 @@ describe("SCIM group to org role mappings", () => {
beforeEach(async () => {
await testDb(TableName.ExternalGroupOrgRoleMapping).where({ orgId }).del();
- auditSpy = vi.spyOn(testServer.services.auditLog, "createAuditLog");
- });
-
- afterEach(() => {
- auditSpy.mockRestore();
});
afterAll(async () => {
@@ -158,27 +147,41 @@ describe("SCIM group to org role mappings", () => {
await testDb(TableName.Role).where({ id: editorRoleId }).del();
});
- test("a mapping the editor cannot grant is refused and not audited as an update", async () => {
+ test("a mapping the editor cannot grant is refused and nothing is stored", async () => {
const res = await putMappings(editor.headers, [["g-escalate", OrgMembershipRole.Admin]]);
- expect(res.statusCode).toBe(403);
+ expect(res.statusCode, res.payload).toBe(403);
expect(await storedMappings()).toEqual([]);
- expect(auditEventsOfType(auditSpy, EventType.UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS)).toHaveLength(0);
});
- test("an accepted update is audited exactly once", async () => {
+ test("the editor can store a mapping that grants nothing", async () => {
const res = await putMappings(editor.headers, [["g-none", OrgMembershipRole.NoAccess]]);
- expect(res.statusCode).toBe(200);
+ expect(res.statusCode, res.payload).toBe(200);
expect(await storedMappings()).toEqual([`g-none=${OrgMembershipRole.NoAccess}`]);
- expect(auditEventsOfType(auditSpy, EventType.UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS)).toHaveLength(1);
});
- test("a forbidden read is refused and not audited", async () => {
+ test("a caller without scim read is refused the list", async () => {
const res = await testServer.inject({ method: "GET", url: URL, headers: member.headers });
- expect(res.statusCode).toBe(403);
- expect(auditEventsOfType(auditSpy, EventType.GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS)).toHaveLength(0);
+ expect(res.statusCode, res.payload).toBe(403);
+ });
+
+ // Control for the race case below: without a concurrent change, the same request succeeds.
+ test("the editor can resubmit an admin mapping unchanged", async () => {
+ const seed = await putMappings(adminHeaders(), [["g-admin", OrgMembershipRole.Admin]]);
+ expect(seed.statusCode, seed.payload).toBe(200);
+
+ const res = await putMappings(editor.headers, [
+ ["g-admin", OrgMembershipRole.Admin],
+ ["g-none", OrgMembershipRole.NoAccess]
+ ]);
+
+ expect(res.statusCode, res.payload).toBe(200);
+ expect(await storedMappings()).toEqual([
+ `g-admin=${OrgMembershipRole.Admin}`,
+ `g-none=${OrgMembershipRole.NoAccess}`
+ ]);
});
test("a group named twice is a 400, not a unique-index 500", async () => {
@@ -187,7 +190,7 @@ describe("SCIM group to org role mappings", () => {
["g-twice", OrgMembershipRole.NoAccess]
]);
- expect(res.statusCode).toBe(400);
+ expect(res.statusCode, res.payload).toBe(400);
expect(await storedMappings()).toEqual([]);
});
@@ -195,7 +198,7 @@ describe("SCIM group to org role mappings", () => {
// after the editor's checks ran but before the write, the write must not put it back.
test("a save authorized against a stale snapshot is refused instead of restoring a removed mapping", async () => {
const seed = await putMappings(adminHeaders(), [["g-admin", OrgMembershipRole.Admin]]);
- expect(seed.statusCode).toBe(200);
+ expect(seed.statusCode, seed.payload).toBe(200);
const lockKey = PgSqlLock.ExternalGroupOrgRoleMappingUpdate(orgId);
let releaseLock!: () => void;
@@ -220,15 +223,17 @@ describe("SCIM group to org role mappings", () => {
["g-none", OrgMembershipRole.NoAccess]
]).then((res) => res);
- // wait until the editor's request has passed its checks and is queued on the write lock
- await waitForLockWaiter(lockKey);
-
- releaseLock();
- await concurrentAdminSave;
+ // Wait until the editor's request has passed its checks and is queued on the write lock. The
+ // lock is released either way, so a failure here fails the test instead of hanging the run.
+ try {
+ await waitForLockWaiter(lockKey);
+ } finally {
+ releaseLock();
+ await concurrentAdminSave;
+ }
const res = await editorSave;
- expect(res.statusCode).toBe(409);
+ expect(res.statusCode, res.payload).toBe(409);
expect(await storedMappings()).toEqual([]);
- expect(auditEventsOfType(auditSpy, EventType.UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS)).toHaveLength(1);
});
});
diff --git a/backend/src/server/routes/v1/external-group-org-role-mapping-router.test.ts b/backend/src/server/routes/v1/external-group-org-role-mapping-router.test.ts
new file mode 100644
index 0000000000..a927a450e2
--- /dev/null
+++ b/backend/src/server/routes/v1/external-group-org-role-mapping-router.test.ts
@@ -0,0 +1,119 @@
+import Fastify, { FastifyInstance } from "fastify";
+import { vi } from "vitest";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PermissionBoundaryError } from "@app/lib/errors";
+import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "@app/server/plugins/fastify-zod";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { registerExternalGroupOrgRoleMappingRouter } from "./external-group-org-role-mapping-router";
+
+// The audit event records what the service accepted, so the handler has to settle the service call
+// before writing it. Returning the pending promise instead still produces the right response, which
+// is why this is pinned at the route: the service tests cannot see the ordering.
+
+const ORG_ID = "org-id";
+const URL = "/api/v1/scim/group-org-role-mappings";
+const refused = () => new PermissionBoundaryError({ message: "Failed to map group 'g' to role 'admin'" });
+
+const buildServer = async ({ list, update }: { list: () => Promise<unknown>; update: () => Promise<unknown> }) => {
+ const createAuditLog = vi.fn().mockResolvedValue(undefined);
+
+ const app = Fastify({ logger: false }).withTypeProvider<ZodTypeProvider>();
+ app.setValidatorCompiler(validatorCompiler);
+ app.setSerializerCompiler(serializerCompiler);
+
+ app.decorate("services", {
+ externalGroupOrgRoleMapping: {
+ listExternalGroupOrgRoleMappings: vi.fn().mockImplementation(list),
+ updateExternalGroupOrgRoleMappings: vi.fn().mockImplementation(update)
+ },
+ auditLog: { createAuditLog }
+ } as never);
+ app.addHook("onRequest", async (req) => {
+ Object.assign(req, {
+ auth: { authMode: AuthMode.JWT },
+ permission: { orgId: ORG_ID },
+ auditLogInfo: {}
+ });
+ });
+
+ await app.register(registerExternalGroupOrgRoleMappingRouter as never, { prefix: URL });
+ await app.ready();
+
+ return { app, createAuditLog };
+};
+
+const auditedTypes = (createAuditLog: ReturnType<typeof vi.fn>) =>
+ createAuditLog.mock.calls.map(([arg]) => (arg as { event: { type: EventType } }).event.type);
+
+describe("external group org role mapping routes", () => {
+ let app: FastifyInstance | undefined;
+
+ afterEach(async () => {
+ await app?.close();
+ app = undefined;
+ });
+
+ test("a refused update is not audited", async () => {
+ const server = await buildServer({ list: async () => [], update: async () => Promise.reject(refused()) });
+ app = server.app;
+
+ const res = await app.inject({
+ method: "PUT",
+ url: URL,
+ body: { mappings: [{ groupName: "g", roleSlug: "admin" }] }
+ });
+
+ expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(server.createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("an accepted update is audited once, after the service settles", async () => {
+ const order: string[] = [];
+ const server = await buildServer({
+ list: async () => [],
+ update: async () => {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 10);
+ });
+ order.push("service");
+ return [];
+ }
+ });
+ app = server.app;
+ server.createAuditLog.mockImplementation(async () => {
+ order.push("audit");
+ });
+
+ const res = await app.inject({
+ method: "PUT",
+ url: URL,
+ body: { mappings: [{ groupName: "g", roleSlug: "no-access" }] }
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(auditedTypes(server.createAuditLog)).toEqual([EventType.UPDATE_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS]);
+ expect(order).toEqual(["service", "audit"]);
+ });
+
+ test("a refused read is not audited", async () => {
+ const server = await buildServer({ list: async () => Promise.reject(refused()), update: async () => [] });
+ app = server.app;
+
+ const res = await app.inject({ method: "GET", url: URL });
+
+ expect(res.statusCode).toBeGreaterThanOrEqual(400);
+ expect(server.createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("an accepted read is audited once", async () => {
+ const server = await buildServer({ list: async () => [], update: async () => [] });
+ app = server.app;
+
+ const res = await app.inject({ method: "GET", url: URL });
+
+ expect(res.statusCode).toBe(200);
+ expect(auditedTypes(server.createAuditLog)).toEqual([EventType.GET_EXTERNAL_GROUP_ORG_ROLE_MAPPINGS]);
+ });
+});
diff --git a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts
index 9225e72056..8f2e2e3ddf 100644
--- a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts
+++ b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-boundary.test.ts
@@ -19,6 +19,7 @@ import { externalGroupOrgRoleMappingServiceFactory } from "./external-group-org-
const ORG_ID = "org-id";
const HIGH_ROLE = { id: "high-role-id", slug: "high" };
+const PRIMARY = { node: "primary" };
const admin = createMongoAbility<MongoAbility>(orgAdminPermissions);
const member = createMongoAbility<MongoAbility>(orgMemberPermissions);
@@ -60,7 +61,8 @@ const createService = ({
const externalGroupOrgRoleMappingDAL = {
find: vi.fn().mockResolvedValue(currentMappings.map((mapping) => ({ orgId: ORG_ID, roleId: null, ...mapping }))),
- updateExternalGroupOrgRoleMappingForOrg: vi.fn().mockResolvedValue([])
+ updateExternalGroupOrgRoleMappingForOrg: vi.fn().mockResolvedValue([]),
+ primaryNode: vi.fn().mockReturnValue(PRIMARY)
};
const service = externalGroupOrgRoleMappingServiceFactory({
@@ -87,7 +89,8 @@ const createService = ({
return {
run,
getOrgPermissionByRoles,
- persist: externalGroupOrgRoleMappingDAL.updateExternalGroupOrgRoleMappingForOrg
+ persist: externalGroupOrgRoleMappingDAL.updateExternalGroupOrgRoleMappingForOrg,
+ findCurrent: externalGroupOrgRoleMappingDAL.find
};
};
@@ -258,4 +261,13 @@ describe("updateExternalGroupOrgRoleMappings privilege boundary", () => {
currentMappings.map((mapping): unknown => expect.objectContaining(mapping))
);
});
+
+ // A replica read here would lag the write's primary re-read and 409 a save nobody raced.
+ test("reads the snapshot from the primary the write re-checks against", async () => {
+ const { run, findCurrent } = createService({ actorPermission: admin, shouldUseNewPrivilegeSystem: true });
+
+ await run([{ groupName: "g", roleSlug: OrgMembershipRole.NoAccess }]);
+
+ expect(findCurrent).toHaveBeenCalledWith({ orgId: ORG_ID }, { tx: PRIMARY });
+ });
});
diff --git a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-dal.ts b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-dal.ts
index 02cf9042e1..56ca8c285f 100644
--- a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-dal.ts
+++ b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-dal.ts
@@ -62,5 +62,7 @@ export const externalGroupOrgRoleMappingDALFactory = (db: TDbClient) => {
return mappings;
};
- return { ...externalGroupOrgRoleMappingOrm, updateExternalGroupOrgRoleMappingForOrg };
+ const primaryNode = () => db.primaryNode();
+
+ return { ...externalGroupOrgRoleMappingOrm, updateExternalGroupOrgRoleMappingForOrg, primaryNode };
};
diff --git a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts
index 9d8a11cc50..dce21e43fd 100644
--- a/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts
+++ b/backend/src/services/external-group-org-role-mapping/external-group-org-role-mapping-service.ts
@@ -94,7 +94,10 @@ export const externalGroupOrgRoleMappingServiceFactory = ({
orgDAL.findById(actor.orgId)
);
- const currentMappings = await externalGroupOrgRoleMappingDAL.find({ orgId: actor.orgId });
+ const currentMappings = await externalGroupOrgRoleMappingDAL.find(
+ { orgId: actor.orgId },
+ { tx: externalGroupOrgRoleMappingDAL.primaryNode() }
+ );
const currentByGroupName = new Map(currentMappings.map((mapping) => [mapping.groupName, mapping]));
const nextByGroupName = new Map(mappings.map((mapping) => [mapping.groupName, mapping]));