Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(identity-access-token): enhance membership revocation handling and testing

Victor Hugo dos Santos9c1a783fb3a5
diff --git a/backend/src/ee/services/group/group-service.ts b/backend/src/ee/services/group/group-service.ts
index fcecefe8ce..9746b2e8db 100644
--- a/backend/src/ee/services/group/group-service.ts
+++ b/backend/src/ee/services/group/group-service.ts
@@ -2,7 +2,14 @@ import { ForbiddenError } from "@casl/ability";
import slugify from "@sindresorhus/slugify";
import { Knex } from "knex";
-import { AccessScope, OrganizationActionScope, OrgMembershipRole, TGroups, TRoles } from "@app/db/schemas";
+import {
+ AccessScope,
+ OrganizationActionScope,
+ OrgMembershipRole,
+ OrgMembershipStatus,
+ TGroups,
+ TRoles
+} from "@app/db/schemas";
import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import {
@@ -969,6 +976,28 @@ export const groupServiceFactory = ({
return { user: users[0], group: groupMembership.group };
};
+ // Joining/leaving this group changes the identity's effective org
+ // access only in orgs where the group holds a membership row and the identity
+ // has no direct access.
+ const groupMembershipAffectsIdentityOrgAccess = async (groupId: string, identityId: string) => {
+ const groupOrgMemberships = await membershipDAL.find({
+ scope: AccessScope.Organization,
+ actorGroupId: groupId
+ });
+ if (groupOrgMemberships.length === 0) return false;
+
+ const identityDirectMemberships = await membershipDAL.find({
+ scope: AccessScope.Organization,
+ actorIdentityId: identityId
+ });
+ const directOrgIds = new Set(
+ identityDirectMemberships
+ .filter((membership) => !membership.status || membership.status === OrgMembershipStatus.Accepted)
+ .map((membership) => membership.scopeOrgId)
+ );
+ return groupOrgMemberships.some((membership) => !directOrgIds.has(membership.scopeOrgId));
+ };
+
const addMachineIdentityToGroup = async ({
id,
identityId,
@@ -1047,6 +1076,13 @@ export const groupServiceFactory = ({
identityGroupMembershipDAL
});
+ // Gaining a group can restore the identity's effective org access, so cached
+ // membership denies must re-check. Skipped when the group grants no org the
+ // identity lacks directly.
+ if (await groupMembershipAffectsIdentityOrgAccess(id, identityId)) {
+ await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId });
+ }
+
// The identity may now be in a secret-manager or PAM project through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
usageMeteringService.emit(actorOrgId, PamIdentities.key);
@@ -1231,8 +1267,11 @@ export const groupServiceFactory = ({
identityIds: [identityId]
});
- // Losing a group can remove the identity's effective org access.
- await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId });
+ // Losing a group can remove the identity's effective org access. Skipped when
+ // the group granted no org the identity lacks directly
+ if (await groupMembershipAffectsIdentityOrgAccess(id, identityId)) {
+ await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId });
+ }
// The identity may have left a secret-manager or PAM project it only reached through this group.
usageMeteringService.emit(actorOrgId, SecretIdentities.key);
diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
index 041cd342a1..1efd62378a 100644
--- a/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-fns.test.ts
@@ -8,7 +8,8 @@ import {
computeTokenAuthRevokeMarkerExpiry,
evaluateRevocationMarkers,
hasLegacyTokenWithoutExpExceededMaxAge,
- IDENTITY_REVOCATION_MARKER_SKEW_SECONDS
+ IDENTITY_REVOCATION_MARKER_SKEW_SECONDS,
+ isMembershipDenyReason
} from "./identity-access-token-fns";
const MAX_AGE = 7_776_000;
@@ -353,3 +354,14 @@ describe("evaluateRevocationMarkers", () => {
).toBeNull();
});
});
+
+describe("isMembershipDenyReason", () => {
+ test("marks only the membership-derived reasons as reversible", () => {
+ expect(isMembershipDenyReason("org-membership")).toBe(true);
+ expect(isMembershipDenyReason("org-membership-inactive")).toBe(true);
+ expect(isMembershipDenyReason("token")).toBe(false);
+ expect(isMembershipDenyReason("identity")).toBe(false);
+ expect(isMembershipDenyReason("client-secret")).toBe(false);
+ expect(isMembershipDenyReason("auth-method")).toBe(false);
+ });
+});
diff --git a/backend/src/services/identity-access-token/identity-access-token-fns.ts b/backend/src/services/identity-access-token/identity-access-token-fns.ts
index 2a9b6abed8..d4a4494137 100644
--- a/backend/src/services/identity-access-token/identity-access-token-fns.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-fns.ts
@@ -303,6 +303,11 @@ export const evaluateRevocationMarkers = ({
return null;
};
+// Membership-derived denies are reversible (the identity can be re-added to the
+// org, reactivated, or regain access through a group)
+export const isMembershipDenyReason = (reason: TRevocationDenyReason): boolean =>
+ reason === "org-membership" || reason === "org-membership-inactive";
+
export const revocationDenyReasonToMessage = (
reason: TRevocationDenyReason,
messagePrefix: "Failed to authorize" | "Cannot renew"
diff --git a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
index d9e7c6e948..e9a331d0d3 100644
--- a/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-revocation-dal.ts
@@ -46,6 +46,19 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
}
};
+ // Scoped markers are the only reversible kind (org membership can be restored),
+ // so they are the only ones with a delete path.
+ const deleteRevocationsByScope = async ({ identityId, scope }: { identityId: string; scope: string }, tx?: Knex) => {
+ try {
+ await (tx ?? db)(TableName.IdentityAccessTokenRevocation)
+ .where("identityId", identityId)
+ .where("scope", scope)
+ .del();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "IdentityAccessTokenRevocationDeleteByScope" });
+ }
+ };
+
const findActiveRevocationsForToken = async ({
tokenId,
identityId,
@@ -148,6 +161,7 @@ export const identityAccessTokenRevocationDALFactory = (db: TDbClient) => {
return {
insertRevocation,
+ deleteRevocationsByScope,
findActiveRevocationsForToken,
removeExpiredRevocations
};
diff --git a/backend/src/services/identity-access-token/identity-access-token-service.test.ts b/backend/src/services/identity-access-token/identity-access-token-service.test.ts
index b56ecc663a..0d91d9bef2 100644
--- a/backend/src/services/identity-access-token/identity-access-token-service.test.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-service.test.ts
@@ -66,7 +66,8 @@ const createService = ({
);
const identityAccessTokenRevocationDAL = {
findActiveRevocationsForToken: vi.fn().mockResolvedValue(activeRevocations),
- insertRevocation: vi.fn()
+ insertRevocation: vi.fn(),
+ deleteRevocationsByScope: vi.fn()
};
const identityDAL = {
getTrustedIpsByAuthMethod: vi.fn().mockResolvedValue(trustedIps),
@@ -797,11 +798,11 @@ describe("identityAccessTokenServiceFactory", () => {
);
});
- test("denies via org-scoped membership marker without a membership re-read when cached", async () => {
+ test("denies via a version-current cached membership deny without a membership re-read", async () => {
const { service, keyStore, orgDAL } = createService();
keyStore.getItem.mockImplementation(async (key: string) => {
if (key.startsWith("identity-revocation-version:")) return "5";
- if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "org-membership" });
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "org-membership", v: 5 });
return null;
});
@@ -811,6 +812,86 @@ describe("identityAccessTokenServiceFactory", () => {
expect(orgDAL.findEffectiveOrgMembership).not.toHaveBeenCalled();
});
+ test("caches a cold-path membership deny stamped with the live version", async () => {
+ const { service, keyStore } = createService({ membership: null });
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "7";
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(
+ "not a member"
+ );
+ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
+ expect.stringContaining("identity-revocation-verdict:identity-id:"),
+ expect.any(Number),
+ JSON.stringify({ deny: "org-membership", v: 7 })
+ );
+ });
+
+ test("re-checks a stale cached membership deny and allows once membership is restored", async () => {
+ // Deny was stamped at v5; restoring the membership bumped the version to 6.
+ const { service, keyStore, orgDAL } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "6";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "org-membership", v: 5 });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).resolves.toMatchObject({
+ identityId: "identity-id"
+ });
+ expect(orgDAL.findEffectiveOrgMembership).toHaveBeenCalled();
+ // Re-stamped as an allow under the live version.
+ expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
+ expect.stringContaining("identity-revocation-verdict:identity-id:"),
+ expect.any(Number),
+ JSON.stringify({ v: 6 })
+ );
+ });
+
+ test("re-checks an unstamped legacy cached membership deny instead of trusting it", async () => {
+ const { service, keyStore, orgDAL } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "5";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "org-membership" });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).resolves.toMatchObject({
+ identityId: "identity-id"
+ });
+ expect(orgDAL.findEffectiveOrgMembership).toHaveBeenCalled();
+ });
+
+ test("serves a cached revocation deny regardless of a version mismatch", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ keyStore.getItem.mockImplementation(async (key: string) => {
+ if (key.startsWith("identity-revocation-version:")) return "9";
+ if (key.startsWith("identity-revocation-verdict:")) return JSON.stringify({ deny: "auth-method", v: 5 });
+ return null;
+ });
+
+ await expect(service.fnValidateIdentityAccessTokenFast(createTokenClaims(), "10.0.0.1")).rejects.toThrow(
+ "auth method has been revoked"
+ );
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).not.toHaveBeenCalled();
+ });
+
+ test("removeOrgMembershipRevocationMarkers deletes the org-scoped markers in the caller tx without bumping", async () => {
+ const { service, identityAccessTokenRevocationDAL, keyStore } = createService();
+ const tx = {} as unknown as Parameters<typeof service.removeOrgMembershipRevocationMarkers>[0]["tx"];
+
+ await service.removeOrgMembershipRevocationMarkers({ identityId: "identity-id", orgId: "org-id", tx });
+
+ expect(identityAccessTokenRevocationDAL.deleteRevocationsByScope).toHaveBeenCalledWith(
+ { identityId: "identity-id", scope: "org-id" },
+ tx
+ );
+ // The bump is a separate post-commit step, never triggered by the marker removal.
+ expect(keyStore.incrementSeededWithExpiry).not.toHaveBeenCalled();
+ });
+
test("insertOrgMembershipRevocationMarker writes an org-scoped marker in the caller tx without bumping", async () => {
const { service, identityAccessTokenRevocationDAL, keyStore } = createService();
const tx = {} as unknown as Parameters<typeof service.insertOrgMembershipRevocationMarker>[0]["tx"];
diff --git a/backend/src/services/identity-access-token/identity-access-token-service.ts b/backend/src/services/identity-access-token/identity-access-token-service.ts
index dd4be9f43b..907af03f46 100644
--- a/backend/src/services/identity-access-token/identity-access-token-service.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-service.ts
@@ -24,6 +24,7 @@ import {
hasFullRenewClaims,
hasLegacyTokenWithoutExpExceededMaxAge,
hasNonWildcardTrustedIps,
+ isMembershipDenyReason,
parseUsesRemaining,
resolveTtlInputs,
revocationDenyReasonToMessage,
@@ -140,12 +141,15 @@ export const identityAccessTokenServiceFactory = ({
// A cached "allowed" answer is only trusted while the identity's version
// number still matches, so a revoke instantly invalidates it without ever
- // storing the set of revocation records. A cached "denied"
- // answer needs no version check and stands for its whole lifetime, because a
- // revocation record always outlives any token it can block.
+ // storing the set of revocation records. A cached "denied" answer from a
+ // revocation needs no version check and stands for its whole lifetime,
+ // because a revocation record always outlives any token it can block.
//
// Org membership is folded into this path: on a cache miss / version change we
// re-check membership in Postgres; on a stamped allow hit we skip that query.
+ // Membership denies are reversible (re-add / reactivate), so they are
+ // version-stamped like allows and only trusted while the version matches;
+ // restoring membership bumps the version to force an immediate re-check.
const assertTokenIsNotRevoked = async ({
tokenId,
identityId,
@@ -199,7 +203,14 @@ export const identityAccessTokenServiceFactory = ({
}
if (parsed?.deny) {
- throw new UnauthorizedError({ message: revocationDenyReasonToMessage(parsed.deny, messagePrefix) });
+ // A membership deny is only honored while its stamped version matches the
+ // live one; a stale one falls through to the cold path and re-checks.
+ const denyIsCurrent =
+ !isMembershipDenyReason(parsed.deny) ||
+ (typeof parsed.v === "number" && cachedVersion !== null && parsed.v === cachedVersion);
+ if (denyIsCurrent) {
+ throw new UnauthorizedError({ message: revocationDenyReasonToMessage(parsed.deny, messagePrefix) });
+ }
}
// An allow only holds while the stamped version still matches the live one.
if (parsed && typeof parsed.v === "number" && cachedVersion !== null && parsed.v === cachedVersion) {
@@ -258,8 +269,13 @@ export const identityAccessTokenServiceFactory = ({
KeyStoreTtls.IdentityRevocationVerdictBaseInSeconds,
KeyStoreTtls.IdentityRevocationVerdictJitterInSeconds
);
- if (denyReason) {
+ if (denyReason && !isMembershipDenyReason(denyReason)) {
await keyStore.setItemWithExpiry(verdictKey, ttl, JSON.stringify({ deny: denyReason }));
+ } else if (denyReason) {
+ // Version-stamped so restoring membership (bump) invalidates it instantly.
+ if (versionForStamp !== null) {
+ await keyStore.setItemWithExpiry(verdictKey, ttl, JSON.stringify({ deny: denyReason, v: versionForStamp }));
+ }
} else if (versionForStamp !== null) {
await keyStore.setItemWithExpiry(verdictKey, ttl, JSON.stringify({ v: versionForStamp }));
}
@@ -763,6 +779,19 @@ export const identityAccessTokenServiceFactory = ({
);
};
+ // Inverse of insertOrgMembershipRevocationMarker, for restoring org access (membership re-added or reactivated)
+ const removeOrgMembershipRevocationMarkers = async ({
+ identityId,
+ orgId,
+ tx
+ }: {
+ identityId: string;
+ orgId: string;
+ tx?: Knex;
+ }) => {
+ await identityAccessTokenRevocationDAL.deleteRevocationsByScope({ identityId, scope: orgId }, tx);
+ };
+
// Best-effort cache accelerator: bumps the version so cached allow verdicts are
// rechecked once. A failed bump only defers enforcement to the verdict TTL, since the committed
// membership row (and marker) remain the durable deny that the cold path reads.
@@ -778,6 +807,7 @@ export const identityAccessTokenServiceFactory = ({
revokeAllTokensForClientSecret,
revokeTokensForIdentityAuthMethod,
insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers,
bumpIdentityRevocationVersion,
markPerTokenRevocation,
fnValidateIdentityAccessTokenFast
diff --git a/backend/src/services/membership-identity/membership-identity-service.test.ts b/backend/src/services/membership-identity/membership-identity-service.test.ts
index 5263adb816..998bb323bb 100644
--- a/backend/src/services/membership-identity/membership-identity-service.test.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.test.ts
@@ -5,7 +5,11 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { AccessScope } from "@app/db/schemas";
import { membershipIdentityServiceFactory } from "./membership-identity-service";
-import { TDeleteMembershipIdentityDTO } from "./membership-identity-types";
+import {
+ TCreateMembershipIdentityDTO,
+ TDeleteMembershipIdentityDTO,
+ TUpdateMembershipIdentityDTO
+} from "./membership-identity-types";
vi.mock("@app/lib/config/env", () => ({
getConfig: () => ({})
@@ -35,26 +39,36 @@ const buildDto = (): TDeleteMembershipIdentityDTO => ({
selector: { identityId: IDENTITY_ID }
});
-const createService = () => {
+const createService = ({
+ existingMembership = { id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID }
+}: { existingMembership?: Record<string, unknown> | null } = {}) => {
const bumpIdentityRevocationVersion = vi.fn().mockResolvedValue(undefined);
const insertOrgMembershipRevocationMarker = vi.fn().mockResolvedValue(undefined);
+ const removeOrgMembershipRevocationMarkers = vi.fn().mockResolvedValue(undefined);
const membershipIdentityDAL = {
- findOne: vi.fn().mockResolvedValue({ id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID }),
+ findOne: vi.fn().mockResolvedValue(existingMembership),
+ create: vi.fn().mockResolvedValue({ id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID }),
+ updateById: vi.fn().mockImplementation(async (id: string, data: Record<string, unknown>) => ({ id, ...data })),
deleteById: vi.fn().mockResolvedValue({ id: MEMBERSHIP_ID }),
transaction: vi.fn(async (cb: (tx: Knex) => Promise<unknown>) => cb({} as Knex))
};
const service = membershipIdentityServiceFactory({
membershipIdentityDAL: membershipIdentityDAL as never,
- roleDAL: { find: vi.fn() } as never,
- membershipRoleDAL: { delete: vi.fn().mockResolvedValue(undefined), insertMany: vi.fn() } as never,
+ roleDAL: { find: vi.fn().mockResolvedValue([]) } as never,
+ membershipRoleDAL: {
+ delete: vi.fn().mockResolvedValue(undefined),
+ insertMany: vi.fn().mockResolvedValue([])
+ } as never,
permissionService: {
getOrgPermission: vi
.fn()
- .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) })
+ .mockResolvedValue({ permission: createMongoAbility([{ action: "manage", subject: "all" }]) }),
+ // Role name "no-access" skips the privilege-boundary comparison in the guards.
+ getOrgPermissionByRoles: vi.fn().mockResolvedValue([{ role: { name: "no-access" }, permission: null }])
} as never,
- orgDAL: { findById: vi.fn(), findEffectiveOrgMembership: vi.fn() } as never,
+ orgDAL: { findById: vi.fn().mockResolvedValue({}), findEffectiveOrgMembership: vi.fn() } as never,
additionalPrivilegeDAL: { delete: vi.fn().mockResolvedValue(undefined) } as never,
identityDAL: {
findById: vi.fn().mockResolvedValue({ orgId: ROOT_ORG_ID, projectId: null })
@@ -66,11 +80,18 @@ const createService = () => {
usageMeteringService: { emit: vi.fn(), emitForProject: vi.fn() } as never,
identityAccessTokenService: {
insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers,
bumpIdentityRevocationVersion
} as never
});
- return { service, membershipIdentityDAL, bumpIdentityRevocationVersion, insertOrgMembershipRevocationMarker };
+ return {
+ service,
+ membershipIdentityDAL,
+ bumpIdentityRevocationVersion,
+ insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers
+ };
};
describe("deleteMembership org revocation bump ordering", () => {
@@ -103,3 +124,91 @@ describe("deleteMembership org revocation bump ordering", () => {
expect(result).toMatchObject({ revocationBumpPending: { identityId: IDENTITY_ID } });
});
});
+
+const buildCreateDto = (): TCreateMembershipIdentityDTO => ({
+ permission: buildDto().permission,
+ scopeData: { scope: AccessScope.Organization, orgId: SUB_ORG_ID },
+ data: { identityId: IDENTITY_ID, roles: [{ role: "member", isTemporary: false }] }
+});
+
+const buildUpdateDto = (isActive?: boolean): TUpdateMembershipIdentityDTO => ({
+ permission: buildDto().permission,
+ scopeData: { scope: AccessScope.Organization, orgId: SUB_ORG_ID },
+ selector: { identityId: IDENTITY_ID },
+ data: { isActive, roles: [{ role: "member", isTemporary: false }] }
+});
+
+describe("createMembership org revocation restore", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ test("removes org-scoped markers in the transaction and bumps after commit on re-add", async () => {
+ const { service, membershipIdentityDAL, bumpIdentityRevocationVersion, removeOrgMembershipRevocationMarkers } =
+ createService({ existingMembership: null });
+
+ await service.createMembership(buildCreateDto());
+
+ expect(membershipIdentityDAL.transaction).toHaveBeenCalledTimes(1);
+ expect(removeOrgMembershipRevocationMarkers).toHaveBeenCalledTimes(1);
+ expect(removeOrgMembershipRevocationMarkers).toHaveBeenCalledWith({
+ identityId: IDENTITY_ID,
+ orgId: SUB_ORG_ID,
+ tx: expect.anything() as Knex
+ });
+ expect(bumpIdentityRevocationVersion).toHaveBeenCalledTimes(1);
+ expect(bumpIdentityRevocationVersion).toHaveBeenCalledWith({ identityId: IDENTITY_ID });
+ });
+});
+
+describe("updateMembership org revocation restore", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ test("reactivating an inactive membership removes markers and bumps, never inserts one", async () => {
+ const {
+ service,
+ bumpIdentityRevocationVersion,
+ insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers
+ } = createService({ existingMembership: { id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID, isActive: false } });
+
+ await service.updateMembership(buildUpdateDto(true));
+
+ expect(insertOrgMembershipRevocationMarker).not.toHaveBeenCalled();
+ expect(removeOrgMembershipRevocationMarkers).toHaveBeenCalledTimes(1);
+ expect(removeOrgMembershipRevocationMarkers).toHaveBeenCalledWith({
+ identityId: IDENTITY_ID,
+ orgId: SUB_ORG_ID,
+ tx: expect.anything() as Knex
+ });
+ expect(bumpIdentityRevocationVersion).toHaveBeenCalledTimes(1);
+ });
+
+ test("deactivating an active membership inserts a marker and bumps, never removes markers", async () => {
+ const {
+ service,
+ bumpIdentityRevocationVersion,
+ insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers
+ } = createService({ existingMembership: { id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID, isActive: true } });
+
+ await service.updateMembership(buildUpdateDto(false));
+
+ expect(insertOrgMembershipRevocationMarker).toHaveBeenCalledTimes(1);
+ expect(removeOrgMembershipRevocationMarkers).not.toHaveBeenCalled();
+ expect(bumpIdentityRevocationVersion).toHaveBeenCalledTimes(1);
+ });
+
+ test("an already-active membership updated without an isActive change touches nothing", async () => {
+ const {
+ service,
+ bumpIdentityRevocationVersion,
+ insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers
+ } = createService({ existingMembership: { id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID, isActive: true } });
+
+ await service.updateMembership(buildUpdateDto(undefined));
+
+ expect(insertOrgMembershipRevocationMarker).not.toHaveBeenCalled();
+ expect(removeOrgMembershipRevocationMarkers).not.toHaveBeenCalled();
+ expect(bumpIdentityRevocationVersion).not.toHaveBeenCalled();
+ });
+});
diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.ts
index 04e2c60100..e40c807b9f 100644
--- a/backend/src/services/membership-identity/membership-identity-service.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.ts
@@ -54,7 +54,7 @@ type TMembershipIdentityServiceFactoryDep = {
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;
identityAccessTokenService: Pick<
TIdentityAccessTokenServiceFactory,
- "insertOrgMembershipRevocationMarker" | "bumpIdentityRevocationVersion"
+ "insertOrgMembershipRevocationMarker" | "removeOrgMembershipRevocationMarkers" | "bumpIdentityRevocationVersion"
>;
};
@@ -203,9 +203,25 @@ export const membershipIdentityServiceFactory = ({
}
});
await membershipRoleDAL.insertMany(roleDocs, tx);
+
+ // Re-adding an identity that was previously removed must lift the org-scoped
+ // token revocation, atomically with the membership insert.
+ if (scopeData.scope === AccessScope.Organization) {
+ await identityAccessTokenService.removeOrgMembershipRevocationMarkers({
+ identityId: dto.data.identityId,
+ orgId: scopeData.orgId,
+ tx
+ });
+ }
+
return doc;
});
+ if (scopeData.scope === AccessScope.Organization) {
+ // Post-commit, so cached membership denies re-check against the restored state.
+ await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId: dto.data.identityId });
+ }
+
// Adding an identity to a project changes the secret-manager and PAM identity meters (a direct member).
if (scopeData.scope === AccessScope.Project) {
usageMeteringService.emitForProject(scopeData.projectId, SecretIdentities.key);
@@ -286,6 +302,8 @@ export const membershipIdentityServiceFactory = ({
const shouldRevokeOrgTokens =
scopeData.scope === AccessScope.Organization && data.isActive === false && existingMembership.isActive !== false;
+ const shouldRestoreOrgTokens =
+ scopeData.scope === AccessScope.Organization && data.isActive === true && existingMembership.isActive === false;
const membershipDoc = await membershipIdentityDAL.transaction(async (tx) => {
const doc =
@@ -344,10 +362,18 @@ export const membershipIdentityServiceFactory = ({
});
}
+ if (shouldRestoreOrgTokens) {
+ await identityAccessTokenService.removeOrgMembershipRevocationMarkers({
+ identityId: dto.selector.identityId,
+ orgId: scopeData.orgId,
+ tx
+ });
+ }
+
return { ...doc, roles: insertedRoleDocs };
});
- if (shouldRevokeOrgTokens) {
+ if (shouldRevokeOrgTokens || shouldRestoreOrgTokens) {
await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId: dto.selector.identityId });
}