Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions ee/apps/den-api/src/organization-role-credential-revocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { and, eq, isNull } from "@openwork-ee/den-db/drizzle"
import { MemberTable } from "@openwork-ee/den-db/schema"
import { revokeOrganizationApiKeysForMember } from "./api-keys.js"
import { revokeMembershipSessionCredentials } from "./credential-revocation.js"
import { db } from "./db.js"

type OrganizationId = typeof MemberTable.$inferSelect.organizationId

export type OrganizationRoleCredentialRevocationCounts = {
members: number
apiKeys: number
sessions: number
oauthAccessTokens: number
oauthRefreshTokens: number
}

function splitRoleValue(value: string) {
return value
.split(",")
.map((entry) => entry.trim())
.filter(Boolean)
}

export async function revokeCredentialsForOrganizationRoleMembers(input: {
organizationId: OrganizationId
role: string
}): Promise<OrganizationRoleCredentialRevocationCounts> {
const members = await db
.select({
id: MemberTable.id,
role: MemberTable.role,
userId: MemberTable.userId,
})
.from(MemberTable)
.where(and(eq(MemberTable.organizationId, input.organizationId), isNull(MemberTable.removedAt)))

const counts: OrganizationRoleCredentialRevocationCounts = {
members: 0,
apiKeys: 0,
sessions: 0,
oauthAccessTokens: 0,
oauthRefreshTokens: 0,
}

for (const member of members) {
if (!splitRoleValue(member.role).includes(input.role)) {
continue
}

counts.members += 1
counts.apiKeys += await revokeOrganizationApiKeysForMember({
organizationId: input.organizationId,
orgMembershipId: member.id,
userId: member.userId,
})

const credentials = await revokeMembershipSessionCredentials({
organizationId: input.organizationId,
userId: member.userId,
})
counts.sessions += credentials.sessions
counts.oauthAccessTokens += credentials.oauthAccessTokens
counts.oauthRefreshTokens += credentials.oauthRefreshTokens
}

return counts
}
11 changes: 10 additions & 1 deletion ee/apps/den-api/src/routes/org/roles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { db } from "../../db.js"
import { jsonValidator, paramValidator, requireUserMiddleware, resolveOrganizationContextMiddleware } from "../../middleware/index.js"
import { emptyResponse, forbiddenSchema, invalidRequestSchema, jsonResponse, notFoundSchema, successSchema, unauthorizedSchema } from "../../openapi.js"
import { validateAssignableOrganizationPermissionRecord } from "../../organization-access.js"
import { revokeCredentialsForOrganizationRoleMembers } from "../../organization-role-credential-revocation.js"
import { serializePermissionRecord } from "../../orgs.js"
import type { OrgRouteVariables } from "./shared.js"
import { createRoleId, ensureOwner, idParamSchema, normalizeRoleName, replaceRoleValue, splitRoles } from "./shared.js"
Expand Down Expand Up @@ -175,6 +176,7 @@ export function registerOrgRoleRoutes<T extends { Variables: OrgRouteVariables }
}
nextPermission = serializePermissionRecord(input.permission)
}
const permissionChanged = nextPermission !== roleRow.permission

await db
.update(OrganizationRoleTable)
Expand Down Expand Up @@ -215,6 +217,13 @@ export function registerOrgRoleRoutes<T extends { Variables: OrgRouteVariables }
}
}

if (permissionChanged) {
await revokeCredentialsForOrganizationRoleMembers({

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Credential revocation is non-atomic with the role permission update, so revocation failures can leave stale credentials after a successful permission change. This is a fail-open security gap in the new hardening path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At ee/apps/den-api/src/routes/org/roles.ts, line 221:

<comment>Credential revocation is non-atomic with the role permission update, so revocation failures can leave stale credentials after a successful permission change. This is a fail-open security gap in the new hardening path.</comment>

<file context>
@@ -215,6 +217,13 @@ export function registerOrgRoleRoutes<T extends { Variables: OrgRouteVariables }
     }
 
+    if (permissionChanged) {
+      await revokeCredentialsForOrganizationRoleMembers({
+        organizationId: payload.organization.id,
+        role: nextRoleName,
</file context>

organizationId: payload.organization.id,
role: nextRoleName,
})
}

await recordOrganizationAuditEvent({
organizationId: payload.organization.id,
actorUserId: payload.currentMember.userId,
Expand All @@ -224,7 +233,7 @@ export function registerOrgRoleRoutes<T extends { Variables: OrgRouteVariables }
previousRole: roleRow.role,
nextRole: nextRoleName,
roleRenamed: nextRoleName !== roleRow.role,
permissionChanged: nextPermission !== roleRow.permission,
permissionChanged,
},
})

Expand Down
101 changes: 101 additions & 0 deletions ee/apps/den-api/test/organization-role-credential-revocation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { beforeAll, expect, mock, test } from "bun:test"
import { MemberTable } from "@openwork-ee/den-db/schema"

const members = [
{ id: "member_one", role: "member,security-admin", userId: "user_one" },
{ id: "member_two", role: "security-admin", userId: null },
{ id: "member_three", role: "admin", userId: "user_three" },
]

const apiKeyRevocations: unknown[] = []
const credentialRevocations: unknown[] = []
let selectCalls = 0

function resetCalls() {
apiKeyRevocations.length = 0
credentialRevocations.length = 0
selectCalls = 0
}

let roleCredentialRevocationModule: typeof import("../src/organization-role-credential-revocation.js")

beforeAll(async () => {
mock.module("../src/db.js", () => ({
db: {
select: () => ({
from: (table: unknown) => ({
where: () => {
selectCalls += 1
return Promise.resolve(table === MemberTable ? members : [])
},
}),
}),
},
}))

mock.module("../src/api-keys.js", () => ({
revokeOrganizationApiKeysForMember: (input: unknown) => {
apiKeyRevocations.push(input)
return Promise.resolve(1)
},
}))

mock.module("../src/credential-revocation.js", () => ({
revokeMembershipSessionCredentials: (input: unknown) => {
credentialRevocations.push(input)
return Promise.resolve({
sessions: input && typeof input === "object" && "userId" in input && input.userId ? 2 : 0,
oauthAccessTokens: input && typeof input === "object" && "userId" in input && input.userId ? 1 : 0,
oauthRefreshTokens: input && typeof input === "object" && "userId" in input && input.userId ? 1 : 0,
})
},
}))

roleCredentialRevocationModule = await import("../src/organization-role-credential-revocation.js")
})

test("role credential revocation touches active members using the changed role", async () => {
resetCalls()

const counts = await roleCredentialRevocationModule.revokeCredentialsForOrganizationRoleMembers({
organizationId: "org_123",
role: "security-admin",
})

expect(counts).toEqual({
members: 2,
apiKeys: 2,
sessions: 2,
oauthAccessTokens: 1,
oauthRefreshTokens: 1,
})
expect(selectCalls).toBe(1)
expect(apiKeyRevocations).toEqual([
{ organizationId: "org_123", orgMembershipId: "member_one", userId: "user_one" },
{ organizationId: "org_123", orgMembershipId: "member_two", userId: null },
])
expect(credentialRevocations).toEqual([
{ organizationId: "org_123", userId: "user_one" },
{ organizationId: "org_123", userId: null },
])
})

test("role credential revocation skips members without the changed role", async () => {
resetCalls()

const counts = await roleCredentialRevocationModule.revokeCredentialsForOrganizationRoleMembers({
organizationId: "org_123",
role: "billing-admin",
})

expect(counts).toEqual({
members: 0,
apiKeys: 0,
sessions: 0,
oauthAccessTokens: 0,
oauthRefreshTokens: 0,
})
expect(selectCalls).toBe(1)
expect(apiKeyRevocations).toEqual([])
expect(credentialRevocations).toEqual([])
})
Loading