Skip to content

Commit acad5ed

Browse files
committed
fix(auth): harden organization membership mutations
1 parent 969ccf2 commit acad5ed

55 files changed

Lines changed: 4816 additions & 5739 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎server/src/addie/mcp/admin-tools.ts‎

Lines changed: 5 additions & 135 deletions
Original file line numberDiff line numberDiff line change
@@ -11259,21 +11259,6 @@ Use add_committee_leader to assign a leader.`;
1125911259
// MEMBERSHIP INVITE HANDLERS
1126011260
// ============================================
1126111261

11262-
function actionToHeader(action: string): string {
11263-
switch (action) {
11264-
case "invited":
11265-
return "Invitation sent";
11266-
case "member_added":
11267-
return "Added to org";
11268-
case "role_updated":
11269-
return "Role updated";
11270-
case "no_change":
11271-
return "No change";
11272-
default:
11273-
return "Done";
11274-
}
11275-
}
11276-
1127711262
function formatRelativeDays(d: Date): string {
1127811263
const diffMs = d.getTime() - Date.now();
1127911264
const days = Math.round(diffMs / 86400000);
@@ -11537,126 +11522,11 @@ Use add_committee_leader to assign a leader.`;
1153711522
}
1153811523
});
1153911524

11540-
handlers.set("add_member_to_org", async (input) => {
11541-
const email = ((input.email as string) || "").trim().toLowerCase();
11542-
const orgId = input.org_id as string;
11543-
const role = (input.role as string) ?? "member";
11544-
const seatType = (input.seat_type as string) ?? "community_only";
11545-
11546-
if (!email || !email.includes("@")) {
11547-
return "❌ email is required (a valid email address).";
11548-
}
11549-
if (!orgId || !orgId.startsWith("org_")) {
11550-
return "❌ org_id is required (org_…).";
11551-
}
11552-
if (!["member", "admin", "owner"].includes(role)) {
11553-
return `❌ role must be one of: member, admin, owner (got: ${role}).`;
11554-
}
11555-
if (!["contributor", "community_only"].includes(seatType)) {
11556-
return `❌ seat_type must be one of: contributor, community_only (got: ${seatType}).`;
11557-
}
11558-
11559-
const adminUser = memberContext?.workos_user;
11560-
if (!adminUser) {
11561-
return "❌ Cannot add member — no signed-in admin context.";
11562-
}
11563-
11564-
const apiKey = process.env.ADMIN_API_KEY;
11565-
if (!apiKey) {
11566-
return "❌ ADMIN_API_KEY is not configured on the server.";
11567-
}
11568-
// Match the base-URL precedence used by member-tools.ts:getBaseUrl —
11569-
// BASE_URL (production) wins; otherwise PORT/CONDUCTOR_PORT for local.
11570-
const baseUrl =
11571-
process.env.BASE_URL ||
11572-
`http://localhost:${
11573-
process.env.PORT || process.env.CONDUCTOR_PORT || "3000"
11574-
}`;
11575-
const endpoint = `${baseUrl}/api/organizations/${encodeURIComponent(
11576-
orgId,
11577-
)}/members/by-email`;
11578-
11579-
try {
11580-
const response = await fetch(endpoint, {
11581-
method: "POST",
11582-
headers: {
11583-
"Content-Type": "application/json",
11584-
Authorization: `Bearer ${apiKey}`,
11585-
},
11586-
body: JSON.stringify({ email, role, seat_type: seatType }),
11587-
signal: AbortSignal.timeout(10000),
11588-
});
11589-
const data = (await response.json().catch(() => ({}))) as Record<
11590-
string,
11591-
unknown
11592-
>;
11593-
if (!response.ok) {
11594-
const errorMsg =
11595-
(data.message as string) ||
11596-
(data.error as string) ||
11597-
`HTTP ${response.status}`;
11598-
logger.warn(
11599-
{ status: response.status, orgId, email, error: errorMsg },
11600-
"add_member_to_org route returned non-OK",
11601-
);
11602-
return `❌ Failed to add ${email} to ${orgId}: ${errorMsg}`;
11603-
}
11604-
11605-
const action = data.action as string;
11606-
logger.info(
11607-
{
11608-
orgId,
11609-
email,
11610-
action,
11611-
role,
11612-
seatType,
11613-
adminUserId: adminUser.workos_user_id,
11614-
},
11615-
"Addie called add_member_to_org",
11616-
);
11617-
11618-
// Mirror the route's response shape rather than reflecting the input —
11619-
// e.g. the route may keep an existing seat_type when adding to an org
11620-
// the user already has a seat in.
11621-
const responseSeatType =
11622-
(data.seat_type as string | undefined) ?? seatType;
11623-
11624-
let md = `## ${actionToHeader(action)}\n\n`;
11625-
md += `**Email:** ${email}\n`;
11626-
md += `**Org:** ${orgId}\n`;
11627-
11628-
if (action === "invited") {
11629-
const invitation = data.invitation as
11630-
| Record<string, unknown>
11631-
| undefined;
11632-
const expiresAt = invitation?.expires_at as string | undefined;
11633-
md += `**Invited as:** member (must be promoted after acceptance for higher roles)\n`;
11634-
md += `**Requested role:** ${role}\n`;
11635-
md += `**Seat type:** ${responseSeatType}\n`;
11636-
if (expiresAt) md += `**Invite expires:** ${expiresAt.slice(0, 10)}\n`;
11637-
if (invitation?.accept_invitation_url) {
11638-
md += `\nThey'll receive an email with a sign-up link.\n`;
11639-
}
11640-
} else if (action === "member_added") {
11641-
md += `**Role:** ${role}\n`;
11642-
md += `**Seat type:** ${responseSeatType}\n`;
11643-
md += `\nThey already had a WorkOS account; added directly to the org.\n`;
11644-
} else if (action === "role_updated") {
11645-
const previousRole = data.previous_role as string | null | undefined;
11646-
md += `**New role:** ${role}\n`;
11647-
md += `**Previous role:** ${previousRole ?? "(none)"}\n`;
11648-
} else if (action === "no_change") {
11649-
md += `\nNo change — they already have role ${role}.\n`;
11650-
} else {
11651-
md += `**Action:** ${action ?? "unknown"}\n`;
11652-
}
11653-
return md;
11654-
} catch (error) {
11655-
logger.error({ error, orgId, email }, "Error calling members/by-email");
11656-
return `❌ Failed to add member: ${
11657-
error instanceof Error ? error.message : "Unknown error"
11658-
}`;
11659-
}
11525+
// The old HTTP adapter replaced its human caller with ADMIN_API_KEY.
11526+
// MemberContext supplies canonical person metadata, not an immutable exact
11527+
// credential/organization/epoch proof. Do not launder that into admin writes.
11528+
handlers.set("add_member_to_org", async () => {
11529+
return "❌ Organization membership changes require the signed-in organization management page. Addie cannot forward an exact authenticated actor for this operation.";
1166011530
});
1166111531

1166211532
handlers.set("diagnose_signin_block", async (input) => {

‎server/src/auth/workos-jwt.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,14 @@
77
* token issued by the MCP OAuth flow works across both surfaces.
88
*/
99

10-
import { createRemoteJWKSet, errors, jwtVerify, type JWTPayload, type JWTVerifyGetKey } from 'jose';
10+
import {
11+
createRemoteJWKSet,
12+
decodeProtectedHeader,
13+
errors,
14+
jwtVerify,
15+
type JWTPayload,
16+
type JWTVerifyGetKey,
17+
} from 'jose';
1118
import { createLogger } from '../logger.js';
1219

1320
const logger = createLogger('workos-jwt');
@@ -21,6 +28,7 @@ export function isInvalidWorkOSJWTError(error: unknown): boolean {
2128
'ERR_JWS_INVALID', 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED',
2229
'ERR_JWKS_NO_MATCHING_KEY',
2330
'ERR_JOSE_ALG_NOT_ALLOWED', 'ERR_JOSE_NOT_SUPPORTED',
31+
'ERR_WORKOS_TOKEN_INVALID_HEADER', 'ERR_WORKOS_TOKEN_INVALID_KID',
2432
].includes(code);
2533
}
2634

@@ -125,6 +133,18 @@ export function looksLikeJWT(token: string): boolean {
125133
* signature verification against our shared JWKS.
126134
*/
127135
export async function verifyWorkOSJWT(token: string): Promise<VerifiedWorkOSToken> {
136+
let protectedHeader: ReturnType<typeof decodeProtectedHeader>;
137+
try {
138+
protectedHeader = decodeProtectedHeader(token);
139+
} catch (cause) {
140+
throw Object.assign(new Error('Token protected header is malformed'), {
141+
code: 'ERR_WORKOS_TOKEN_INVALID_HEADER',
142+
cause,
143+
});
144+
}
145+
if (protectedHeader.kid !== undefined && typeof protectedHeader.kid !== 'string') {
146+
throw Object.assign(new Error('Token key id must be a string'), { code: 'ERR_WORKOS_TOKEN_INVALID_KID' });
147+
}
128148
const jwksInstance = getJWKS();
129149

130150
const { payload } = await jwtVerify(token,

‎server/src/db/api-key-management-db.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const SNAPSHOT_SQL = `
1919
SELECT pg_catalog.pg_is_in_recovery() AS in_recovery,
2020
credential.workos_user_id AS authenticated_user_id,
2121
primary_binding.workos_user_id AS canonical_user_id, binding.identity_id,
22+
binding.xmin::text AS binding_version,
2223
COALESCE(primary_binding.primary_count, 0)::text AS primary_count,
2324
EXISTS (
2425
SELECT 1 FROM registry_audit_log audit
@@ -46,6 +47,7 @@ interface SnapshotRow {
4647
authenticated_user_id: string | null;
4748
canonical_user_id: string | null;
4849
identity_id: string | null;
50+
binding_version: string | null;
4951
authorization_epoch: string;
5052
email: string | null;
5153
email_verified: boolean;
@@ -57,12 +59,13 @@ function snapshotFromRow(row: SnapshotRow | undefined, organizationId: string |
5759
if (!row || row.in_recovery) throw new AuthorizationSnapshotUnavailableError();
5860
// Grant-free management must retain the primary snapshot's terminal
5961
// lifecycle boundary, including stale provider recreation and bad routing.
60-
if (row.terminal_marker || !row.authenticated_user_id || !row.identity_id
62+
if (row.terminal_marker || !row.authenticated_user_id || !row.identity_id || !row.binding_version
6163
|| row.primary_count !== '1' || !row.canonical_user_id) return null;
6264
return Object.freeze({
6365
authenticatedUserId: row.authenticated_user_id,
6466
canonicalUserId: row.canonical_user_id,
6567
identityId: row.identity_id,
68+
bindingVersion: row.binding_version,
6669
selectedOrganizationId: organizationId,
6770
authorizationEpoch: row.authorization_epoch,
6871
credential: Object.freeze({

‎server/src/db/identity-db.ts‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,8 +216,9 @@ export const CREDENTIAL_MUTATION_ADMISSION_TIMEOUT_MS = 1_000;
216216

217217
/**
218218
* Keep one connection free for confirmed deletion and bound admission wait.
219-
* Guard callbacks must use their supplied client and must not perform provider
220-
* I/O, so each admitted mutation consumes exactly one pool connection.
219+
* Guard mutation callbacks must use their supplied client and must not perform
220+
* provider I/O. A serialized prefetch may use the admitted connection before
221+
* the credential lock is acquired, so confirmed deletion can still progress.
221222
*/
222223
const credentialMutationAdmission = {
223224
active: 0,
@@ -427,6 +428,7 @@ async function withCredentialEventMutation<T>(
427428
workosUserId: string,
428429
mode: CredentialMutationMode,
429430
mutation: (client: PoolClient) => Promise<T>,
431+
serializedPrefetch?: () => Promise<void>,
430432
): Promise<CredentialEventMutationResult<T>> {
431433
const releaseCapacity = await acquireCredentialMutationPoolCapacity();
432434
try {
@@ -436,6 +438,45 @@ async function withCredentialEventMutation<T>(
436438
try {
437439
await client.query('BEGIN');
438440
await client.query(`SET LOCAL lock_timeout = '${CREDENTIAL_MUTATION_LOCK_TIMEOUT_MS}ms'`);
441+
if (serializedPrefetch) {
442+
// Membership provider reads can be slow, so serialize them on a
443+
// distinct lock before taking the credential-revocation lock. This
444+
// preserves webhook ordering without delaying a confirmed deletion.
445+
await client.query(`SELECT pg_advisory_xact_lock(hashtextextended($1, 6828))`, [workosUserId]);
446+
447+
// Avoid provider reads for a credential that is already inactive.
448+
// This is only an optimization: deletion can race this read, and the
449+
// locked lifecycle check below remains the authority before effects.
450+
const preflight = await client.query<{
451+
user_exists: boolean;
452+
binding_exists: boolean;
453+
primary_count: string;
454+
}>(
455+
`SELECT EXISTS (
456+
SELECT 1 FROM users WHERE workos_user_id = $1
457+
) AS user_exists,
458+
EXISTS (
459+
SELECT 1 FROM identity_workos_users WHERE workos_user_id = $1
460+
) AS binding_exists,
461+
COALESCE((
462+
SELECT COUNT(*)
463+
FROM identity_workos_users actor_iwu
464+
JOIN identity_workos_users primary_iwu
465+
ON primary_iwu.identity_id = actor_iwu.identity_id
466+
AND primary_iwu.is_primary = TRUE
467+
WHERE actor_iwu.workos_user_id = $1
468+
), 0)::text AS primary_count`,
469+
[workosUserId],
470+
);
471+
const state = preflight.rows[0];
472+
if (state?.user_exists !== true
473+
|| state.binding_exists !== true
474+
|| Number(state.primary_count) !== 1) {
475+
await client.query('COMMIT');
476+
return { applied: false };
477+
}
478+
await serializedPrefetch();
479+
}
439480
const { identityId } = await lockCredentialThenIdentityMutation(client, workosUserId);
440481
if (await hasConfirmedDeletionTombstone(client, workosUserId)) {
441482
await client.query('COMMIT');
@@ -505,6 +546,19 @@ export async function withActiveCredentialEventMutation<T>(
505546
return withCredentialEventMutation(workosUserId, 'active', mutation);
506547
}
507548

549+
/**
550+
* Serialize read-only provider state for one credential before taking the
551+
* credential lifecycle lock, then recheck the locked lifecycle before local
552+
* effects. The prefetch must be bounded and must not perform provider writes.
553+
*/
554+
export async function withActiveCredentialEventMutationAfterSerializedPrefetch<T>(
555+
workosUserId: string,
556+
prefetch: () => Promise<void>,
557+
mutation: (client: PoolClient) => Promise<T>,
558+
): Promise<CredentialEventMutationResult<T>> {
559+
return withCredentialEventMutation(workosUserId, 'active', mutation, prefetch);
560+
}
561+
508562
/** Apply one atomic authority mutation to a sorted set of live credentials. */
509563
export async function withActiveCredentialSetMutation<T>(
510564
workosUserIds: string[],

0 commit comments

Comments
 (0)