From f8d3fe4fff9e848d103b0e3994c39ecb916f9015 Mon Sep 17 00:00:00 2001 From: Colin Barber Date: Wed, 18 Nov 2026 19:50:14 +0000 Subject: [PATCH] feat(authorization): support PATCH for membership role assignments Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- docs/behavior.md | 25 ++- .../routes/authorization-checks.spec.ts | 171 ++++++++++++++++++ src/workos/routes/authorization-checks.ts | 109 +++++++++++ 3 files changed, 302 insertions(+), 3 deletions(-) diff --git a/docs/behavior.md b/docs/behavior.md index f20df42..9dbb3ba 100644 --- a/docs/behavior.md +++ b/docs/behavior.md @@ -323,14 +323,33 @@ Every organization owns an implicit `organization` resource whose `external_id` organization's `external_id`, falling back to the organization id. Resources created without parent fields attach to it, and it cannot be created, updated, or deleted directly. +### Membership role assignments + +Direct role assignments support criteria removal through +`DELETE /authorization/organization_memberships/{id}/role_assignments`. + +`PATCH /authorization/organization_memberships/{id}/role_assignments` accepts `add` and `remove` +lists, each defaulting to empty, with 1–100 entries combined. Each entry names a `role_slug` and +selects a resource by `resource_id` or by `resource_type_slug` and `resource_external_id`. +All entries are validated before any assignments change. Matching uses the resolved role and +resource IDs, so an organization role shadows an environment role with the same slug. + +| Code | Condition | Status | +| --------------------------------- | ------------------------------------------------------------------------------------------------------ | ------ | +| — | Update succeeds with no response body; existing adds and unmatched removals are skipped. | 204 | +| `role_assignment_update_overlap` | Both lists resolve to the same role and resource pair. | 400 | +| `entity_not_found` | The membership, role, or resource is unknown, or the role or resource belongs to another organization. | 404 | +| — or `unprocessable_entity` | The request fails body validation, including the combined entry count. | 422 | +| `NoResourceIdentifierProvided` | An entry has no resource selector. | 422 | +| `BothResourceIdentifiersProvided` | An entry provides both complete resource selectors. | 422 | + ### Native group authorization Native AuthKit groups can receive scoped roles through `/authorization/groups/{groupId}/role_assignments`: create and list assignments, then get or delete one by ID or remove by role and resource criteria. Omitting the resource targets the -organization's own resource. Direct role assignments also support criteria removal through -`DELETE /authorization/organization_memberships/{id}/role_assignments`. Duplicate group -assignments return `409` with code `duplicate_group_role_assignment`; an unknown role slug is a +organization's own resource. Duplicate group assignments return `409` with code +`duplicate_group_role_assignment`; an unknown role slug is a `404`, as is group criteria removal that matches nothing; roles and resources from another organization are rejected. Permission checks, effective-permission lists, and accessible-resource discovery resolve current group membership and include grants on resource ancestors. Removing a member or group diff --git a/src/workos/routes/authorization-checks.spec.ts b/src/workos/routes/authorization-checks.spec.ts index 06b00ea..48873f8 100644 --- a/src/workos/routes/authorization-checks.spec.ts +++ b/src/workos/routes/authorization-checks.spec.ts @@ -346,6 +346,177 @@ describe('Authorization check + role assignment routes', () => { expect(body.data.length).toBe(0); }); + describe('PATCH membership role assignments', () => { + const roleSlug = 'admin-role'; + const editor = { role_slug: 'editor', resource_type_slug: 'doc', resource_external_id: 'patch-doc' }; + let path: string; + let orgId: string; + let resourceId: string; + let assignmentId: string; + let adminRoleId: string; + const admin = () => ({ role_slug: roleSlug, resource_id: resourceId }); + const patch = (body: unknown, target = path) => req(target, { method: 'PATCH', body: JSON.stringify(body) }); + + async function assignments() { + const body: { + data: Array<{ id: string; role_id: string; role: { slug: string }; resource: { id: string } }>; + } = await json(await req(path)); + return body.data; + } + + async function assignmentIds() { + return (await assignments()).map(({ id }) => id); + } + + beforeEach(async () => { + const { membership, org, adminRole } = await setup(); + path = `/authorization/organization_memberships/${membership.id}/role_assignments`; + orgId = org.id; + adminRoleId = adminRole.id; + const resource = await json( + await req('/authorization/resources', { + method: 'POST', + body: JSON.stringify({ + resource_type_slug: 'doc', + external_id: 'patch-doc', + organization_id: orgId, + name: 'Doc', + }), + }), + ); + resourceId = resource.id; + const original = await json(await req(path, { method: 'POST', body: JSON.stringify(admin()) })); + assignmentId = original.id; + }); + + it('adds and removes grants in one request and returns no body', async () => { + const response = await patch({ add: [editor], remove: [admin()] }); + const grants = (await assignments()).map(({ role, resource }) => [role.slug, resource.id]); + expect([response.status, await response.text(), grants]).toEqual([204, '', [['editor', resourceId]]]); + }); + + it('skips adding a grant that is already held', async () => { + const response = await patch({ add: [admin()] }); + expect([response.status, await assignmentIds()]).toEqual([204, [assignmentId]]); + }); + + it('skips removing a grant that is not held', async () => { + const response = await patch({ remove: [editor] }); + expect([response.status, await assignmentIds()]).toEqual([204, [assignmentId]]); + }); + + it('rejects zero entries', async () => { + const response = await patch({}); + expect([response.status, await assignmentIds()]).toEqual([422, [assignmentId]]); + }); + + it('rejects 101 entries across both lists', async () => { + const response = await patch({ add: Array.from({ length: 100 }, () => editor), remove: [admin()] }); + expect([response.status, await assignmentIds()]).toEqual([422, [assignmentId]]); + }); + + it.each(['resource id', 'external id'])( + 'rejects overlap addressed by %s without changing grants', + async (selector) => { + const overlap = selector === 'resource id' ? { role_slug: 'editor', resource_id: resourceId } : editor; + const response = await patch({ + add: [{ role_slug: 'editor', resource_id: resourceId }], + remove: [admin(), overlap], + }); + expect([response.status, (await json(response)).code, await assignmentIds()]).toEqual([ + 400, + 'role_assignment_update_overlap', + [assignmentId], + ]); + }, + ); + + it('rejects an unknown role without changing grants', async () => { + const response = await patch({ add: [editor], remove: [admin(), { ...admin(), role_slug: 'unknown-role' }] }); + expect([response.status, await json(response), await assignmentIds()]).toEqual([ + 404, + { code: 'entity_not_found', message: "Role not found: 'unknown-role'.", entity_id: 'unknown-role' }, + [assignmentId], + ]); + }); + + it('rejects an unknown membership without changing grants', async () => { + const response = await patch( + { add: [editor], remove: [admin()] }, + '/authorization/organization_memberships/om_missing/role_assignments', + ); + expect([response.status, await json(response), await assignmentIds()]).toEqual([ + 404, + { + code: 'entity_not_found', + message: "UserOrganizationMembership not found: 'om_missing'.", + entity_id: 'om_missing', + }, + [assignmentId], + ]); + }); + + it('rejects a resource from another organization without changing grants', async () => { + const otherOrg = await json( + await req('/organizations', { method: 'POST', body: JSON.stringify({ name: 'Other Org' }) }), + ); + const resource = await json( + await req('/authorization/resources', { + method: 'POST', + body: JSON.stringify({ + resource_type_slug: 'doc', + external_id: 'other-patch-doc', + organization_id: otherOrg.id, + name: 'Other Doc', + }), + }), + ); + const response = await patch({ add: [editor], remove: [admin(), { ...admin(), resource_id: resource.id }] }); + expect([response.status, await json(response), await assignmentIds()]).toEqual([ + 404, + { + code: 'entity_not_found', + message: `AuthorizationResource not found: '${resource.id}'.`, + entity_id: resource.id, + }, + [assignmentId], + ]); + }); + + it('rejects an entry without a resource selector without changing grants', async () => { + const response = await patch({ add: [editor], remove: [admin(), { role_slug: roleSlug }] }); + expect([response.status, (await json(response)).code, await assignmentIds()]).toEqual([ + 422, + 'NoResourceIdentifierProvided', + [assignmentId], + ]); + }); + + it('removes only the organization role when its slug shadows an environment role', async () => { + const orgRole = getWorkOSStore(store).roles.insert({ + object: 'role', + slug: roleSlug, + name: 'Org Admin', + description: null, + type: 'OrganizationRole', + organization_id: orgId, + is_default_role: false, + priority: 0, + resource_type_slug: 'organization', + }); + await req(path, { method: 'POST', body: JSON.stringify(admin()) }); + const roleIds = async () => (await assignments()).map(({ role_id }) => role_id).sort(); + const before = await roleIds(); + + const response = await patch({ remove: [admin()] }); + expect([before, response.status, await roleIds()]).toEqual([ + [adminRoleId, orgRole.id].sort(), + 204, + [adminRoleId], + ]); + }); + }); + it('lists resources accessible to membership', async () => { const { membership, org } = await setup(); diff --git a/src/workos/routes/authorization-checks.ts b/src/workos/routes/authorization-checks.ts index 44c2e2a..b83c27a 100644 --- a/src/workos/routes/authorization-checks.ts +++ b/src/workos/routes/authorization-checks.ts @@ -6,6 +6,7 @@ import { cursorPaginate, notFound, validationError, + validationFailed, parseJsonBody, parseListParams, ID_PREFIXES, @@ -22,6 +23,7 @@ import { import { resolvePrimaryRole } from '../role-helpers.js'; import { membershipRoleSlugs } from '../membership-roles.js'; import { findOrCreateOrganizationResource } from '../organization-resource.js'; +import { optionalNonEmpty, required, validateBody } from '../authorization-validation.js'; // An unknown role slug on a group role assignment is production's // GroupRoleAssignmentRoleNotFoundException (api authorization/exceptions): the entity_not_found @@ -149,6 +151,84 @@ function resolveResourceTarget( return null; } +function roleAssignmentUpdateLists(body: Record): { add: unknown[]; remove: unknown[] } { + const { add = [], remove = [] } = body; + for (const field of Object.keys(body)) { + if (field !== 'add' && field !== 'remove') { + throw validationFailed([{ field, code: `property ${field} should not exist` }]); + } + } + if (!Array.isArray(add) || !Array.isArray(remove)) { + const field = Array.isArray(add) ? 'remove' : 'add'; + throw validationFailed([{ field, code: `${field} must be an array` }]); + } + const count = add.length + remove.length; + if (count < 1 || count > 100) { + throw validationFailed([{ field: 'add', code: 'add and remove must contain between 1 and 100 entries combined.' }]); + } + return { add, remove }; +} + +function resolveRoleAssignmentUpdateEntry(ws: WorkOSStore, organizationId: string, entry: unknown) { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { + throw validationError('A role assignment must be an object'); + } + const body = entry as Record; + validateBody(body, { + forbidUnknown: true, + fields: { + role_slug: required(), + resource_id: optionalNonEmpty(), + resource_external_id: optionalNonEmpty(), + resource_type_slug: optionalNonEmpty(), + }, + }); + + const roleSlug = body.role_slug as string; + const role = resolvePrimaryRole(ws, organizationId, roleSlug); + if (!role) throw notFound('Role', roleSlug); + if (body.resource_id && body.resource_external_id && body.resource_type_slug) { + throw new WorkOSApiError( + 422, + 'Provide either resource_id OR (resource_external_id and resource_type_slug), not both.', + 'BothResourceIdentifiersProvided', + ); + } + const resource = resolveResourceTarget(ws, body, organizationId); + if (!resource) { + throw new WorkOSApiError( + 422, + 'Either resource_id OR (resource_external_id and resource_type_slug) must be provided.', + 'NoResourceIdentifierProvided', + ); + } + return { + role_id: role.id, + role_slug: role.slug, + resource_id: resource.id, + resource_external_id: resource.external_id, + resource_type_slug: resource.resource_type_slug, + }; +} + +type RoleAssignmentUpdateEntry = ReturnType; + +function roleAssignmentKey({ role_id, resource_id }: Pick): string { + return JSON.stringify([role_id, resource_id]); +} + +function assertNoRoleAssignmentUpdateOverlap(add: RoleAssignmentUpdateEntry[], removed: ReadonlySet): void { + for (const entry of add) { + if (removed.has(roleAssignmentKey(entry))) { + throw new WorkOSApiError( + 400, + `Role '${entry.role_slug}' on resource '${entry.resource_id}' cannot be added and removed in the same update.`, + 'role_assignment_update_overlap', + ); + } + } +} + // A group grant always names a resource: production's resolveResource maps an // omitted selector to the organization's own resource, so the spec requires // `resource.id`, `resource.external_id` and `resource.resource_type_slug`. @@ -468,6 +548,35 @@ export function authorizationCheckRoutes(ctx: RouteContext): void { return c.json(formatRoleAssignment(assignment), 201); }); + app.patch('/authorization/organization_memberships/:id/role_assignments', async (c) => { + const membershipId = c.req.param('id'); + const membership = ws.organizationMemberships.get(membershipId); + if (!membership) throw notFound('UserOrganizationMembership', membershipId); + + const { add, remove } = roleAssignmentUpdateLists(await parseJsonBody(c)); + const resolve = (entry: unknown) => resolveRoleAssignmentUpdateEntry(ws, membership.organization_id, entry); + const additions = add.map(resolve); + const toRemove = new Set(remove.map(resolve).map(roleAssignmentKey)); + assertNoRoleAssignmentUpdateOverlap(additions, toRemove); + + const assignments = ws.roleAssignments.findBy('organization_membership_id', membershipId); + const held = new Set(assignments.map(roleAssignmentKey)); + for (const entry of additions) { + const key = roleAssignmentKey(entry); + if (held.has(key)) continue; + ws.roleAssignments.insert({ + ...entry, + object: 'role_assignment', + organization_membership_id: membershipId, + }); + held.add(key); + } + for (const assignment of assignments) { + if (toRemove.has(roleAssignmentKey(assignment))) ws.roleAssignments.delete(assignment.id); + } + return c.body(null, 204); + }); + // Delete role assignment app.delete('/authorization/organization_memberships/:id/role_assignments/:assignmentId', (c) => { const membershipId = c.req.param('id');