Skip to content

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

feat(identity-access-token): refactor revocation handling and introduce identity-wide marker

Victor Hugo dos Santos16feb50dbb4f
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 0d91d9bef2..2589019f0e 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
@@ -235,12 +235,34 @@ describe("identityAccessTokenServiceFactory", () => {
await service.revokeAllTokensForIdentity("identity-id");
- expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({
- id: "identity-id",
- identityId: "identity-id",
- revokedAt: new Date(NOW_SECONDS * 1000),
- expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)
- });
+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith(
+ {
+ id: "identity-id",
+ identityId: "identity-id",
+ revokedAt: new Date(NOW_SECONDS * 1000),
+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)
+ },
+ undefined
+ );
+ });
+
+ test("insertIdentityWideRevocationMarker writes the sentinel in the caller tx without bumping", async () => {
+ const { service, identityAccessTokenRevocationDAL, keyStore } = createService();
+ const tx = {} as unknown as Parameters<typeof service.insertIdentityWideRevocationMarker>[0]["tx"];
+
+ await service.insertIdentityWideRevocationMarker({ identityId: "identity-id", tx });
+
+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith(
+ {
+ id: "identity-id",
+ identityId: "identity-id",
+ revokedAt: new Date(NOW_SECONDS * 1000),
+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)
+ },
+ tx
+ );
+ // The bump runs post-commit in the caller, never inside the marker insert.
+ expect(keyStore.incrementSeededWithExpiry).not.toHaveBeenCalled();
});
test("writes per-token revocation to PG for exact legacy tokens", async () => {
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 907af03f46..16a46e9ccd 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
@@ -689,18 +689,25 @@ export const identityAccessTokenServiceFactory = ({
await bumpRevocationVersion(identityId);
};
- // Identity-wide revoke: any JWT with iat < this epoch is rejected on auth.
- // Uses the 90d fallback since it is one marker per deleted identity.
- const revokeAllTokensForIdentity = async (identityId: string) => {
+ // Identity-wide revoke marker: any JWT with iat < this epoch is rejected on
+ // auth. Uses the 90d fallback since it is one marker per deleted identity.
+ const insertIdentityWideRevocationMarker = async ({ identityId, tx }: { identityId: string; tx?: Knex }) => {
const appCfg = getConfig();
const revokedAt = new Date();
- await identityAccessTokenRevocationDAL.insertRevocation({
- id: identityId,
- identityId,
- revokedAt,
- expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
- });
+ await identityAccessTokenRevocationDAL.insertRevocation(
+ {
+ id: identityId,
+ identityId,
+ revokedAt,
+ expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
+ },
+ tx
+ );
+ };
+
+ const revokeAllTokensForIdentity = async (identityId: string) => {
+ await insertIdentityWideRevocationMarker({ identityId });
await bumpRevocationVersion(identityId);
};
@@ -802,6 +809,7 @@ export const identityAccessTokenServiceFactory = ({
return {
issueIdentityAccessToken,
renewAccessToken,
+ insertIdentityWideRevocationMarker,
revokeAccessToken,
revokeAllTokensForIdentity,
revokeAllTokensForClientSecret,
diff --git a/backend/src/services/identity-v2/identity-service.ts b/backend/src/services/identity-v2/identity-service.ts
index b01461595b..cc48356d98 100644
--- a/backend/src/services/identity-v2/identity-service.ts
+++ b/backend/src/services/identity-v2/identity-service.ts
@@ -66,7 +66,10 @@ type TScopedIdentityV2ServiceFactoryDep = {
membershipIdentityDAL: TMembershipIdentityDALFactory;
membershipRoleDAL: TMembershipRoleDALFactory;
identityMetadataDAL: TIdentityMetadataDALFactory;
- identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "revokeAllTokensForIdentity">;
+ identityAccessTokenService: Pick<
+ TIdentityAccessTokenServiceFactory,
+ "insertIdentityWideRevocationMarker" | "bumpIdentityRevocationVersion"
+ >;
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
projectDAL: Pick<TProjectDALFactory, "findActorAccessibleProjectIds" | "findOrgProjectIds" | "findById">;
orgDAL: Pick<TOrgDALFactory, "findById">;
@@ -377,11 +380,13 @@ export const identityV2ServiceFactory = ({
throw new BadRequestError({ message: "Cannot delete identity while delete protection is enabled" });
}
- // Set the identity-wide PG revocation epoch before removing the row so
- // any JWT issued for this identity (with iat < now) is rejected.
- await identityAccessTokenService.revokeAllTokensForIdentity(dto.selector.identityId);
-
- const deletedIdentity = await identityDAL.deleteById(dto.selector.identityId);
+ // Set the identity-wide PG revocation epoch atomically with the row delete
+ // so any JWT issued for this identity (with iat < now) is rejected.
+ const deletedIdentity = await identityDAL.transaction(async (tx) => {
+ await identityAccessTokenService.insertIdentityWideRevocationMarker({ identityId: dto.selector.identityId, tx });
+ return identityDAL.deleteById(dto.selector.identityId, tx);
+ });
+ await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId: dto.selector.identityId });
await licenseService.updateSubscriptionOrgMemberCount(scopeData.orgId);
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index 661782f68d..289526c79f 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -54,7 +54,7 @@ type TIdentityServiceFactoryDep = {
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
identityAccessTokenService: Pick<
TIdentityAccessTokenServiceFactory,
- "revokeAllTokensForIdentity" | "insertOrgMembershipRevocationMarker" | "bumpIdentityRevocationVersion"
+ "insertIdentityWideRevocationMarker" | "insertOrgMembershipRevocationMarker" | "bumpIdentityRevocationVersion"
>;
};
@@ -382,9 +382,11 @@ export const identityServiceFactory = ({
if (identityOrgMembership.identity.hasDeleteProtection)
throw new BadRequestError({ message: "Identity has delete protection" });
- await identityAccessTokenService.revokeAllTokensForIdentity(id);
-
- const deletedIdentity = await identityDAL.deleteById(id);
+ const deletedIdentity = await identityDAL.transaction(async (tx) => {
+ await identityAccessTokenService.insertIdentityWideRevocationMarker({ identityId: id, tx });
+ return identityDAL.deleteById(id, tx);
+ });
+ await identityAccessTokenService.bumpIdentityRevocationVersion({ identityId: id });
await licenseService.updateSubscriptionOrgMemberCount(identityOrgMembership.scopeOrgId);
usageMeteringService.emit(identityOrgMembership.scopeOrgId, IdentitiesMeter.key);
usageMeteringService.emit(identityOrgMembership.scopeOrgId, SecretIdentities.key);
diff --git a/backend/src/services/membership-identity/membership-identity-dal.ts b/backend/src/services/membership-identity/membership-identity-dal.ts
index f50ebffa8b..931301c0cb 100644
--- a/backend/src/services/membership-identity/membership-identity-dal.ts
+++ b/backend/src/services/membership-identity/membership-identity-dal.ts
@@ -493,5 +493,16 @@ export const membershipIdentityDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, findIdentities, getIdentityById, listAvailableIdentities };
+ // Row-locked read for transactions that must decide on the membership's
+ // current state before mutating it (e.g. the isActive revoke/restore hooks)
+ const findByIdForUpdate = async (id: string, tx: Knex) => {
+ try {
+ const doc = await tx(TableName.Membership).where({ id }).forUpdate().first();
+ return doc ? MembershipsSchema.parse(doc) : undefined;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindByIdForUpdate" });
+ }
+ };
+
+ return { ...orm, findIdentities, getIdentityById, listAvailableIdentities, findByIdForUpdate };
};
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 998bb323bb..4d60053897 100644
--- a/backend/src/services/membership-identity/membership-identity-service.test.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.test.ts
@@ -48,6 +48,7 @@ const createService = ({
const membershipIdentityDAL = {
findOne: vi.fn().mockResolvedValue(existingMembership),
+ findByIdForUpdate: 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 }),
@@ -211,4 +212,28 @@ describe("updateMembership org revocation restore", () => {
expect(removeOrgMembershipRevocationMarkers).not.toHaveBeenCalled();
expect(bumpIdentityRevocationVersion).not.toHaveBeenCalled();
});
+
+ test("decides revoke/restore from the row-locked in-transaction read, not the stale pre-read", async () => {
+ // Pre-transaction read says active; by the time the tx locks the row a
+ // concurrent update deactivated it. Reactivating must follow the locked
+ // read (restore), not the stale snapshot (no-op).
+ const {
+ service,
+ membershipIdentityDAL,
+ bumpIdentityRevocationVersion,
+ insertOrgMembershipRevocationMarker,
+ removeOrgMembershipRevocationMarkers
+ } = createService({ existingMembership: { id: MEMBERSHIP_ID, actorIdentityId: IDENTITY_ID, isActive: true } });
+ membershipIdentityDAL.findByIdForUpdate.mockResolvedValue({
+ id: MEMBERSHIP_ID,
+ actorIdentityId: IDENTITY_ID,
+ isActive: false
+ });
+
+ await service.updateMembership(buildUpdateDto(true));
+
+ expect(removeOrgMembershipRevocationMarkers).toHaveBeenCalledTimes(1);
+ expect(insertOrgMembershipRevocationMarker).not.toHaveBeenCalled();
+ expect(bumpIdentityRevocationVersion).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.ts
index e40c807b9f..93d4ecef0a 100644
--- a/backend/src/services/membership-identity/membership-identity-service.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.ts
@@ -300,15 +300,22 @@ export const membershipIdentityServiceFactory = ({
const customRolesGroupBySlug = groupBy(customRoles, ({ slug }) => slug);
- const shouldRevokeOrgTokens =
- scopeData.scope === AccessScope.Organization && data.isActive === false && existingMembership.isActive !== false;
- const shouldRestoreOrgTokens =
- scopeData.scope === AccessScope.Organization && data.isActive === true && existingMembership.isActive === false;
+ let shouldRevokeOrgTokens = false;
+ let shouldRestoreOrgTokens = false;
const membershipDoc = await membershipIdentityDAL.transaction(async (tx) => {
+ const currentMembership = await membershipIdentityDAL.findByIdForUpdate(existingMembership.id, tx);
+ if (!currentMembership) {
+ throw new BadRequestError({ message: "Identity doesn't have membership" });
+ }
+ shouldRevokeOrgTokens =
+ scopeData.scope === AccessScope.Organization && data.isActive === false && currentMembership.isActive !== false;
+ shouldRestoreOrgTokens =
+ scopeData.scope === AccessScope.Organization && data.isActive === true && currentMembership.isActive === false;
+
const doc =
typeof data.isActive === "undefined"
- ? existingMembership
+ ? currentMembership
: await membershipIdentityDAL.updateById(
existingMembership.id,
{