|
| 1 | +import { Prisma, prisma } from "~/db.server"; |
| 2 | +import { logger } from "~/services/logger.server"; |
| 3 | +import { rbac } from "~/services/rbac.server"; |
| 4 | + |
| 5 | +export type EnsureOrgMemberParams = { |
| 6 | + userId: string; |
| 7 | + organizationId: string; |
| 8 | + // null = use the seeded MEMBER role from the existing enum. A non-null |
| 9 | + // value is an RBAC role id; when an RBAC plugin is installed it gets |
| 10 | + // attached after the OrgMember row is created. |
| 11 | + roleId: string | null; |
| 12 | + source: "sso_jit" | "invite" | "manual"; |
| 13 | +}; |
| 14 | + |
| 15 | +export type EnsureOrgMemberResult = { created: boolean; orgMemberId: string }; |
| 16 | + |
| 17 | +// Completes a JIT role assignment for an ALREADY-existing membership whose |
| 18 | +// RBAC role never got applied. This is a no-op when a role is already |
| 19 | +// assigned, so it can never demote a deliberately-set role — it only fills |
| 20 | +// in the gap left by an interrupted provision (see `ensureOrgMember`). Always |
| 21 | +// best-effort: a valid membership already exists, so a failure here is logged |
| 22 | +// and swallowed rather than thrown. |
| 23 | +async function healMissingRoleAssignment(params: { |
| 24 | + userId: string; |
| 25 | + organizationId: string; |
| 26 | + roleId: string; |
| 27 | + source: EnsureOrgMemberParams["source"]; |
| 28 | +}): Promise<void> { |
| 29 | + const { userId, organizationId, roleId, source } = params; |
| 30 | + |
| 31 | + const currentRole = await rbac.getUserRole({ userId, organizationId }); |
| 32 | + if (currentRole !== null) return; |
| 33 | + |
| 34 | + const result = await rbac.setUserRole({ userId, organizationId, roleId }); |
| 35 | + if (!result.ok) { |
| 36 | + logger.warn("ensureOrgMember.setUserRole failed while healing unassigned membership", { |
| 37 | + source, |
| 38 | + userId, |
| 39 | + organizationId, |
| 40 | + roleId, |
| 41 | + error: result.error, |
| 42 | + }); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// Idempotent OrgMember upsert. If the (userId, organizationId) row |
| 47 | +// already exists this is a no-op (returns `{ created: false }`); we do |
| 48 | +// NOT touch the existing role to avoid demoting a user that JIT happens |
| 49 | +// to fire for again. |
| 50 | +// |
| 51 | +// Seat-limit enforcement lives at the call sites — every existing |
| 52 | +// OrgMember insert in the codebase does its own seat check before |
| 53 | +// calling in. This helper deliberately does none (SSO JIT and |
| 54 | +// invite-accept are exempt by policy). |
| 55 | +export async function ensureOrgMember( |
| 56 | + params: EnsureOrgMemberParams |
| 57 | +): Promise<EnsureOrgMemberResult> { |
| 58 | + const { userId, organizationId, roleId, source } = params; |
| 59 | + |
| 60 | + const existing = await prisma.orgMember.findFirst({ |
| 61 | + where: { userId, organizationId }, |
| 62 | + select: { id: true }, |
| 63 | + }); |
| 64 | + if (existing) { |
| 65 | + // Existing membership is normally a pure no-op: we don't re-touch the |
| 66 | + // role, since a user JIT fires for again may have been deliberately |
| 67 | + // promoted and must not be demoted back to the JIT default. |
| 68 | + // |
| 69 | + // The one exception is self-healing a half-provisioned row. The create + |
| 70 | + // setUserRole + compensating delete below are not transactional (the RBAC |
| 71 | + // plugin writes on its own connection, so a single DB transaction isn't |
| 72 | + // possible). If setUserRole failed AND that compensating delete also |
| 73 | + // failed, the placeholder MEMBER row is orphaned — and this findFirst |
| 74 | + // would short-circuit every future login, stranding the user on the |
| 75 | + // placeholder role forever. So when a JIT role is requested but the RBAC |
| 76 | + // layer shows no role assigned, complete the assignment now. It's gated on |
| 77 | + // "no role assigned", so it can never demote a real one. |
| 78 | + if (roleId !== null) { |
| 79 | + await healMissingRoleAssignment({ userId, organizationId, roleId, source }); |
| 80 | + } |
| 81 | + return { created: false, orgMemberId: existing.id }; |
| 82 | + } |
| 83 | + |
| 84 | + // Two concurrent JIT/invite flows can both miss the findFirst above and |
| 85 | + // race to create the same (userId, organizationId) row; the unique |
| 86 | + // constraint makes one lose with P2002. Treat that as the idempotent |
| 87 | + // "already a member" case rather than letting it break sign-in. |
| 88 | + let member: { id: string }; |
| 89 | + try { |
| 90 | + member = await prisma.orgMember.create({ |
| 91 | + data: { |
| 92 | + userId, |
| 93 | + organizationId, |
| 94 | + role: "MEMBER", |
| 95 | + }, |
| 96 | + select: { id: true }, |
| 97 | + }); |
| 98 | + } catch (error) { |
| 99 | + if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2002") { |
| 100 | + const existingAfterConflict = await prisma.orgMember.findFirst({ |
| 101 | + where: { userId, organizationId }, |
| 102 | + select: { id: true }, |
| 103 | + }); |
| 104 | + if (existingAfterConflict) { |
| 105 | + return { created: false, orgMemberId: existingAfterConflict.id }; |
| 106 | + } |
| 107 | + } |
| 108 | + throw error; |
| 109 | + } |
| 110 | + |
| 111 | + if (roleId !== null) { |
| 112 | + const result = await rbac.setUserRole({ userId, organizationId, roleId }); |
| 113 | + if (!result.ok) { |
| 114 | + // The membership was just created with the legacy `MEMBER` enum role as |
| 115 | + // a placeholder; the intended RBAC role failed to apply. Leaving the row |
| 116 | + // in place would grant the user `MEMBER` access — potentially broader |
| 117 | + // than the configured (e.g. restrictive) JIT default role they were |
| 118 | + // supposed to get. Roll back so we never half-provision into an |
| 119 | + // unintended privilege level, then throw so the caller can decide |
| 120 | + // whether to skip provisioning or fail the flow. |
| 121 | + logger.warn("ensureOrgMember.setUserRole failed; rolling back membership", { |
| 122 | + source, |
| 123 | + userId, |
| 124 | + organizationId, |
| 125 | + roleId, |
| 126 | + error: result.error, |
| 127 | + }); |
| 128 | + await prisma.orgMember.delete({ where: { id: member.id } }); |
| 129 | + throw new Error(`ensureOrgMember: failed to apply role ${roleId}: ${result.error}`); |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + return { created: true, orgMemberId: member.id }; |
| 134 | +} |
0 commit comments