Skip to content

Commit 3660309

Browse files
pcncTrigger.dev RepoOps
authored andcommitted
fix(plugins,webapp): record the exact previous role on a role change
Mono-RevId: 2b4428f4b48f4d110f800bdb64a94f4100df5230
1 parent 1c1891a commit 3660309

7 files changed

Lines changed: 50 additions & 103 deletions

File tree

‎apps/webapp/app/models/member.server.ts‎

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import type {
44
PrismaClientOrTransaction,
55
Project,
66
} from "@trigger.dev/database";
7-
import { tryCatch } from "@trigger.dev/core/utils";
87
import { z } from "zod";
98
import { Prisma as PrismaNamespace, type Prisma, prisma } from "~/db.server";
109
import {
@@ -463,33 +462,20 @@ async function assignInviteRbacRole({
463462
recordRoleChange?: { memberId: string; email: string };
464463
}): Promise<boolean> {
465464
try {
466-
let roleBefore: { id: string; name: string } | null = null;
467465
if (onlyWhenUnassigned) {
468466
const currentRole = await rbac.getUserRole({ userId, organizationId });
469467
if (currentRole !== null) {
470468
return false;
471469
}
472-
} else if (recordRoleChange && auditLogs.isRecordingEnabled()) {
473-
// Best-effort, like setOrgMemberRole: a failed read records an unknown "before".
474-
const [roleBeforeError, currentRole] = await tryCatch(
475-
rbac.getUserRole({ userId, organizationId })
476-
);
477-
if (roleBeforeError) {
478-
logger.warn("acceptInvite: failed to read the role before assigning the invite's role", {
479-
organizationId,
480-
userId,
481-
error: roleBeforeError,
482-
});
483-
}
484-
roleBefore = currentRole ?? null;
485470
}
486471

487472
const roleResult = await rbac.setUserRole({
488473
userId,
489474
organizationId,
490475
roleId: rbacRoleId,
491476
});
492-
if (roleResult.ok && recordRoleChange && roleBefore?.id !== rbacRoleId) {
477+
// The plugin reports the role it replaced, read in its own transaction.
478+
if (roleResult.ok && roleResult.changed && recordRoleChange) {
493479
recordMemberAuditEventInBackground(
494480
async () => ({
495481
category: "members",
@@ -501,7 +487,7 @@ async function assignInviteRbacRole({
501487
}),
502488
changes: {
503489
role: {
504-
before: roleBefore?.name ?? null,
490+
before: roleResult.previousRole?.name ?? null,
505491
after: await auditRoleName(organizationId, rbacRoleId),
506492
},
507493
},

‎apps/webapp/app/models/orgMember.server.ts‎

Lines changed: 16 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { tryCatch } from "@trigger.dev/core/utils";
2-
import type { RoleAssignmentResult } from "@trigger.dev/plugins";
2+
import type { UserRoleAssignmentResult } from "@trigger.dev/plugins";
33
import { $transaction, Prisma, prisma } from "~/db.server";
44
import { deleteOrgMember, prepareMemberRemovalKeys } from "./deleteOrgMember.server";
55
import { findOrCreateDirectoryUser } from "./directoryUser.server";
@@ -81,21 +81,19 @@ async function wasMemberAtWrite(userId: string, organizationId: string): Promise
8181
* that failed. Setting the role a member already has, or a role for a user who isn't a member,
8282
* records nothing. While recording is off, it reads nothing for the event.
8383
*
84-
* "after" is the role this call wrote. "before" is read before the write, outside the plugin's
85-
* transaction, so it is best-effort: a concurrent change between the read and the write can make it
86-
* stale, or skip the event when the stale role equals the new one. The proper fix (the plugin
87-
* returning the previous role from its transaction) is
88-
* https://linear.app/triggerdotdev/issue/TRI-16184. The member is read before the write too, so the
89-
* event can name them after a later removal. Whether they were still a member at the write is
90-
* checked right after it, before this returns (see `wasMemberAtWrite`). Auditing never blocks the
91-
* role change: a failed read is logged and the change goes ahead.
84+
* "before" and whether the role changed come from the plugin, read in the write's transaction, so
85+
* they are exact. "after" is the role this call wrote, but its name is looked up after the write,
86+
* so a custom role renamed or deleted since then shows its new name or null. The member is read
87+
* before the write, so the event can name them after a later removal. Whether they were still a
88+
* member at the write is checked right after it, before this returns (see `wasMemberAtWrite`).
89+
* Auditing never blocks the role change: a failed read is logged and the change goes ahead.
9290
*
9391
* `attribution` is for callers with no user behind them, such as the directory sync worker.
9492
*/
9593
export async function setOrgMemberRole(
9694
params: { userId: string; organizationId: string; roleId: string },
9795
attribution?: MemberAuditAttribution
98-
): Promise<RoleAssignmentResult> {
96+
): Promise<UserRoleAssignmentResult> {
9997
const result = await writeOrgMemberRole(params, attribution);
10098
if (result.ok) {
10199
await enqueueAttioMemberSync({ organizationId: params.organizationId, userId: params.userId });
@@ -106,22 +104,18 @@ export async function setOrgMemberRole(
106104
async function writeOrgMemberRole(
107105
params: { userId: string; organizationId: string; roleId: string },
108106
attribution?: MemberAuditAttribution
109-
): Promise<RoleAssignmentResult> {
107+
): Promise<UserRoleAssignmentResult> {
110108
const { userId, organizationId, roleId } = params;
111109

112110
if (!auditLogs.isRecordingEnabled()) {
113111
return rbac.setUserRole({ userId, organizationId, roleId });
114112
}
115113

116-
// Both reads run together, so the change waits for one round trip, not two. The role is read even
117-
// for a user who turns out not to be a member, where it goes unused.
118-
const [[memberReadError, memberBeforeWrite], [roleBeforeError, roleBefore]] = await Promise.all([
119-
// Read before the write, so a later removal can't leave the event with nobody to name. If this
120-
// read fails, the member is looked up after the write instead.
121-
tryCatch(findAuditMember(userId, organizationId)),
122-
// If this read fails, the change is recorded with an unknown "before".
123-
tryCatch(rbac.getUserRole({ userId, organizationId })),
124-
]);
114+
// Read before the write, so a later removal can't leave the event with nobody to name. If this
115+
// read fails, the member is looked up after the write instead.
116+
const [memberReadError, memberBeforeWrite] = await tryCatch(
117+
findAuditMember(userId, organizationId)
118+
);
125119
if (memberReadError) {
126120
logger.warn("setOrgMemberRole: failed to read the member before the change", {
127121
userId,
@@ -133,16 +127,8 @@ async function writeOrgMemberRole(
133127
return rbac.setUserRole({ userId, organizationId, roleId });
134128
}
135129

136-
if (roleBeforeError) {
137-
logger.warn("setOrgMemberRole: failed to read the role before the change", {
138-
userId,
139-
organizationId,
140-
error: roleBeforeError,
141-
});
142-
}
143-
144130
const result = await rbac.setUserRole({ userId, organizationId, roleId });
145-
if (!result.ok || (!roleBeforeError && roleBefore?.id === roleId)) {
131+
if (!result.ok || !result.changed) {
146132
return result;
147133
}
148134

@@ -168,7 +154,7 @@ async function writeOrgMemberRole(
168154
target: memberAuditTarget(member),
169155
changes: {
170156
role: {
171-
before: roleBefore?.name ?? null,
157+
before: result.previousRole?.name ?? null,
172158
after: await auditRoleName(organizationId, roleId),
173159
},
174160
},

‎apps/webapp/test/memberAuditEvents.test.ts‎

Lines changed: 18 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ vi.mock("~/db.server", async () => {
4646
// or read roles call `useRoleStandIn()`. The stand-in replaces only the role methods, with the
4747
// contract of enterprise/packages/plugins/src/rbac/controller.ts: a role read is null for a user who
4848
// isn't a member, else their assigned role, else the legacy OrgMember.role mapping (ADMIN -> Owner,
49-
// MEMBER -> Admin). `setUserRole` writes the assignment whether or not the user is a member, and
50-
// refuses to demote the org's last Owner. Session authentication stays the real fallback's.
49+
// MEMBER -> Admin). `setUserRole` writes the assignment whether or not the user is a member, refuses
50+
// to demote the org's last Owner, and returns the role it replaced and whether the role changed. Session authentication stays the real fallback's.
5151
type FakeRole = { id: string; name: string; isSystem: boolean };
5252
const rbacHolder = vi.hoisted(() => ({
5353
/** Whether the role methods come from the stand-in instead of the fallback. */
@@ -58,8 +58,6 @@ const rbacHolder = vi.hoisted(() => ({
5858
developer: { id: "role_developer", name: "Developer", isSystem: true },
5959
} as Record<string, { id: string; name: string; isSystem: boolean }>,
6060
assignments: new Map<string, { id: string; name: string; isSystem: boolean }>(),
61-
/** Makes the next `getUserRole` throw, like a failed database read. */
62-
failNextGetUserRole: false,
6361
/** How many times each read ran, to tell which reads a change made. */
6462
reads: { getUserRole: 0, allRoles: 0 },
6563
/** While set, `allRoles` waits for it, like a slow database read. */
@@ -88,10 +86,6 @@ vi.mock("~/services/rbac.server", async () => {
8886
const roleStandIn: Record<string, unknown> = {
8987
async getUserRole({ userId, organizationId }: { userId: string; organizationId: string }) {
9088
rbacHolder.reads.getUserRole++;
91-
if (rbacHolder.failNextGetUserRole) {
92-
rbacHolder.failNextGetUserRole = false;
93-
throw new Error("role read failed");
94-
}
9589
return effectiveRole(userId, organizationId);
9690
},
9791
async getUserRoles(userIds: string[], organizationId: string) {
@@ -111,6 +105,7 @@ vi.mock("~/services/rbac.server", async () => {
111105
async setUserRole(params: { userId: string; organizationId: string; roleId: string }) {
112106
const role = Object.values(rbacHolder.roles).find((r) => r.id === params.roleId);
113107
if (!role) return { ok: false, error: "Role not found" };
108+
const previousRole = await effectiveRole(params.userId, params.organizationId);
114109
const members = await prismaHolder.client!.orgMember.findMany({
115110
where: { organizationId: params.organizationId },
116111
select: { userId: true },
@@ -127,7 +122,7 @@ vi.mock("~/services/rbac.server", async () => {
127122
};
128123
}
129124
rbacHolder.assignments.set(key(params.userId, params.organizationId), role);
130-
return { ok: true };
125+
return { ok: true, previousRole, changed: previousRole?.id !== role.id };
131126
},
132127
async removeUserRole({ userId, organizationId }: { userId: string; organizationId: string }) {
133128
rbacHolder.assignments.delete(key(userId, organizationId));
@@ -211,7 +206,6 @@ let disableRecording: (() => void) | undefined;
211206
beforeEach(() => {
212207
rbacHolder.roleStandIn = false;
213208
rbacHolder.assignments.clear();
214-
rbacHolder.failNextGetUserRole = false;
215209
rbacHolder.reads = { getUserRole: 0, allRoles: 0 };
216210
rbacHolder.allRolesGate = null;
217211
ssoHolder.overrides = {};
@@ -816,7 +810,7 @@ describe("reads made only for audit events", () => {
816810
});
817811
await flushAuditEvents();
818812

819-
expect(roleChange).toEqual({ ok: true });
813+
expect(roleChange).toMatchObject({ ok: true, changed: true });
820814
expect(added.created).toBe(true);
821815
expect(rbacHolder.assignments.get(`${organization.id}:${member.id}`)).toEqual(
822816
rbacHolder.roles.admin
@@ -834,7 +828,8 @@ describe("reads made only for audit events", () => {
834828
roleId: rbacHolder.roles.developer.id,
835829
});
836830
await flushAuditEvents();
837-
expect(rbacHolder.reads).toEqual({ getUserRole: 1, allRoles: 1 });
831+
// The role it replaced comes from the plugin's write, so only the role names are read.
832+
expect(rbacHolder.reads).toEqual({ getUserRole: 0, allRoles: 1 });
838833
expect(recorded).toHaveLength(1);
839834
})
840835
);
@@ -861,7 +856,7 @@ describe("reads made only for audit events", () => {
861856
const recordedBeforeRelease = recorded.length;
862857
releaseRoleNames();
863858

864-
expect(outcome).toEqual({ ok: true });
859+
expect(outcome).toMatchObject({ ok: true, changed: true });
865860
expect(recordedBeforeRelease).toBe(0);
866861
expect(await recordedEvents(recorded)).toEqual([
867862
{
@@ -926,7 +921,11 @@ describe("role change audit events", () => {
926921
roleId: rbacHolder.roles.admin.id,
927922
});
928923

929-
expect(result).toEqual({ ok: true });
924+
expect(result).toMatchObject({
925+
ok: true,
926+
changed: true,
927+
previousRole: { name: "Developer" },
928+
});
930929
expect(await recordedEvents(recorded)).toEqual([
931930
{
932931
category: "members",
@@ -987,7 +986,7 @@ describe("role change audit events", () => {
987986
);
988987
releaseMemberReads();
989988

990-
expect(result).toEqual({ ok: true });
989+
expect(result).toMatchObject({ ok: true, changed: true });
991990
expect(await recordedEvents(recorded)).toEqual([
992991
{
993992
category: "members",
@@ -1045,46 +1044,12 @@ describe("role change audit events", () => {
10451044
code: "last_owner",
10461045
});
10471046
expect(unknownRole).toEqual({ ok: false, error: "Role not found" });
1048-
expect(sameRole).toEqual({ ok: true });
1049-
expect(nonMember).toEqual({ ok: true });
1047+
expect(sameRole).toMatchObject({ ok: true, changed: false });
1048+
expect(nonMember).toMatchObject({ ok: true });
10501049
expect(await recordedEvents(recorded)).toEqual([]);
10511050
}
10521051
);
10531052

1054-
// Catches: a failed "before" read blocking the role change, or dropping its event.
1055-
postgresTest(
1056-
"changes the role and records it without a before when the pre-read fails",
1057-
async ({ prisma }) =>
1058-
inAuditedRequest(async () => {
1059-
prismaHolder.client = prisma;
1060-
useRoleStandIn();
1061-
const { setOrgMemberRole } = await import("~/models/orgMember.server");
1062-
const { organization, member, regularMember } = await seedOrg(prisma);
1063-
rbacHolder.failNextGetUserRole = true;
1064-
1065-
const recorded = await startRecording();
1066-
const result = await setOrgMemberRole({
1067-
userId: member.id,
1068-
organizationId: organization.id,
1069-
roleId: rbacHolder.roles.admin.id,
1070-
});
1071-
1072-
expect(result).toEqual({ ok: true });
1073-
expect(rbacHolder.assignments.get(`${organization.id}:${member.id}`)).toEqual(
1074-
rbacHolder.roles.admin
1075-
);
1076-
expect(await recordedEvents(recorded)).toEqual([
1077-
{
1078-
category: "members",
1079-
action: "member.role_changed",
1080-
organizationId: organization.id,
1081-
target: { type: "member", id: regularMember.id, name: member.email },
1082-
changes: { role: { before: null, after: "Admin" } },
1083-
},
1084-
]);
1085-
})
1086-
);
1087-
10881053
// Catches: a failed member read before the write blocking the role change, or dropping its event.
10891054
// The client below fails that one read, so the event has to find the member after the write.
10901055
postgresTest(
@@ -1119,7 +1084,7 @@ describe("role change audit events", () => {
11191084
});
11201085

11211086
expect(failNextMemberRead).toBe(false);
1122-
expect(result).toEqual({ ok: true });
1087+
expect(result).toMatchObject({ ok: true, changed: true });
11231088
expect(rbacHolder.assignments.get(`${organization.id}:${member.id}`)).toEqual(
11241089
rbacHolder.roles.admin
11251090
);
@@ -1180,7 +1145,7 @@ describe("role change audit events", () => {
11801145
});
11811146

11821147
expect(removeAfterNextMemberRead).toBe(false);
1183-
expect(result).toEqual({ ok: true });
1148+
expect(result).toMatchObject({ ok: true, changed: true });
11841149
expect(
11851150
await prisma.orgMember.count({
11861151
where: { userId: member.id, organizationId: organization.id },

‎internal-packages/rbac/src/fallback.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type {
1212
RoleBaseAccessController,
1313
RoleMutationResult,
1414
UserActorAuthResult,
15+
UserRoleAssignmentResult,
1516
} from "@trigger.dev/plugins";
1617
import {
1718
FULL_ACCESS_PRESET_ID,
@@ -417,7 +418,7 @@ class RoleBaseAccessFallbackController implements RoleBaseAccessController {
417418
return new Map(userIds.map((id) => [id, null]));
418419
}
419420

420-
async setUserRole(): Promise<RoleAssignmentResult> {
421+
async setUserRole(): Promise<UserRoleAssignmentResult> {
421422
return { ok: false, error: "RBAC plugin not installed" };
422423
}
423424

‎internal-packages/rbac/src/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type {
1818
RoleBaseAccessController,
1919
RoleBasedAccessControlPlugin,
2020
RoleMutationResult,
21+
UserRoleAssignmentResult,
2122
} from "@trigger.dev/plugins";
2223
import type { PrismaClient } from "@trigger.dev/database";
2324
import { isAdditionalApiKey } from "@trigger.dev/core/v3/apiKeys";
@@ -545,7 +546,7 @@ class LazyController implements RoleBaseAccessController {
545546

546547
async setUserRole(
547548
...args: Parameters<RoleBaseAccessController["setUserRole"]>
548-
): Promise<RoleAssignmentResult> {
549+
): Promise<UserRoleAssignmentResult> {
549550
return (await this.c()).setUserRole(...args);
550551
}
551552

‎packages/plugins/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export type {
22
RoleBasedAccessControlPlugin,
33
RoleBaseAccessController,
44
RoleAssignmentResult,
5+
UserRoleAssignmentResult,
56
RoleMutationResult,
67
Permission,
78
Role,

‎packages/plugins/src/rbac.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,7 @@ export interface RoleBaseAccessController {
841841
organizationId: string;
842842
roleId: string;
843843
projectId?: string;
844-
}): Promise<RoleAssignmentResult>;
844+
}): Promise<UserRoleAssignmentResult>;
845845

846846
removeUserRole(params: {
847847
userId: string;
@@ -900,6 +900,13 @@ export type RoleAssignmentResult =
900900
| { ok: true }
901901
| { ok: false; error: string; code?: RoleAssignmentErrorCode };
902902

903+
// `setUserRole`'s result. On success, `previousRole` is the user's effective role in that scope
904+
// before the write (null if they had none) and `changed` is whether the write changed it, both read
905+
// in the write's transaction.
906+
export type UserRoleAssignmentResult =
907+
| { ok: true; previousRole: Role | null; changed: boolean }
908+
| Extract<RoleAssignmentResult, { ok: false }>;
909+
903910
import type { PluginDatabaseConfig } from "./databaseConfig.js";
904911
import type { ApiKeyCapabilityCatalogue, ApiKeyCapabilityMap } from "./apiKeyCapabilities.js";
905912

0 commit comments

Comments
 (0)