Skip to content

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

feat(identity-access-token): implement org-scoped revocation and membership checks

Victor Hugo dos Santos0b118066c4a2
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9699f1e89f..0591525ebf 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -908,6 +908,14 @@ export const registerRoutes = async (
usageMeteringService
});
+ const identityAccessTokenService = identityAccessTokenServiceFactory({
+ identityAccessTokenDAL,
+ identityAccessTokenRevocationDAL,
+ identityDAL,
+ orgDAL,
+ keyStore
+ });
+
const membershipIdentityService = membershipIdentityServiceFactory({
identityDAL,
membershipIdentityDAL,
@@ -920,7 +928,8 @@ export const registerRoutes = async (
applicationMembershipCleanupService,
projectDAL,
keyStore,
- usageMeteringService
+ usageMeteringService,
+ identityAccessTokenService
});
const membershipGroupService = membershipGroupServiceFactory({
@@ -2468,14 +2477,6 @@ export const registerRoutes = async (
usageMeteringService
});
- const identityAccessTokenService = identityAccessTokenServiceFactory({
- identityAccessTokenDAL,
- identityAccessTokenRevocationDAL,
- identityDAL,
- orgDAL,
- keyStore
- });
-
const identityV2Service = identityV2ServiceFactory({
membershipIdentityDAL,
membershipRoleDAL,
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 9fe7a402ff..041cd342a1 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
@@ -327,4 +327,29 @@ describe("evaluateRevocationMarkers", () => {
})
).toBe("auth-method");
});
+
+ test("denies org-scoped membership markers only for matching orgId", () => {
+ const revokedAt = new Date((NOW + 10) * 1000);
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ orgId: "org-id",
+ markers: [{ id: "uuid", identityId: "identity-id", createdAt: revokedAt, revokedAt, scope: "org-id" }]
+ })
+ ).toBe("org-membership");
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ orgId: "other-org",
+ markers: [{ id: "uuid", identityId: "identity-id", createdAt: revokedAt, revokedAt, scope: "org-id" }]
+ })
+ ).toBeNull();
+ expect(
+ evaluateRevocationMarkers({
+ ...base,
+ orgId: "org-id",
+ markers: [{ id: "uuid", identityId: "identity-id", createdAt: new Date((NOW - 10) * 1000), scope: "org-id" }]
+ })
+ ).toBeNull();
+ });
});
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 51afc1a513..2a9b6abed8 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
@@ -259,7 +259,8 @@ export const evaluateRevocationMarkers = ({
identityId,
issuedAtMs,
clientSecretId,
- authMethod
+ authMethod,
+ orgId
}: {
markers: TRevocationMarker[];
tokenId: string;
@@ -267,6 +268,7 @@ export const evaluateRevocationMarkers = ({
issuedAtMs: number;
clientSecretId?: string;
authMethod?: string;
+ orgId?: string;
}): TRevocationDenyReason | null => {
for (const revocation of markers) {
// A record with no scope either targets this exact token, or (when the whole
@@ -283,7 +285,7 @@ export const evaluateRevocationMarkers = ({
}
} else {
// A scoped record blocks every token issued before the revocation whose
- // client secret or login method matches the scope.
+ // client secret, login method, or org membership matches the scope.
const revokedAtMs = (revocation.revokedAt ?? revocation.createdAt).getTime();
if (issuedAtMs < revokedAtMs) {
if (clientSecretId && revocation.scope === clientSecretId) {
@@ -292,6 +294,9 @@ export const evaluateRevocationMarkers = ({
if (authMethod && revocation.scope === authMethod) {
return "auth-method";
}
+ if (orgId && revocation.scope === orgId) {
+ return "org-membership";
+ }
}
}
}
@@ -309,6 +314,10 @@ export const revocationDenyReasonToMessage = (
return `${messagePrefix}: identity tokens have been revoked`;
case "client-secret":
return `${messagePrefix}: client secret has been revoked`;
+ case "org-membership":
+ return `${messagePrefix}: Identity is not a member of the organization`;
+ case "org-membership-inactive":
+ return `${messagePrefix}: Identity organization membership is inactive`;
case "auth-method":
default:
return `${messagePrefix}: auth method has been revoked`;
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 41921915ca..385b5013e6 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
@@ -11,8 +11,9 @@ export type TIdentityAccessTokenRevocationDALFactory = ReturnType<typeof identit
// revoke-all sentinels, random UUID for scoped markers. `revokedAt` is populated
// for every marker except per-token revocations so runtime validation can compare
// the JWT iat against the exact revocation time. `scope` is null for legacy
-// (per-token / identity-wide) markers and holds the scope key (clientSecretId or
-// IdentityAuthMethod string) for scoped markers.
+// (per-token / identity-wide) markers and holds the scope key (clientSecretId,
+// IdentityAuthMethod string, or orgId for membership deactivate/removal) for
+// scoped markers.
type TInsertRevocationInput = {
id: string;
identityId: string;
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 b50223319d..8dd5b2955e 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
@@ -743,8 +743,8 @@ describe("identityAccessTokenServiceFactory", () => {
);
});
- test("serves a cached allow verdict without hitting the revocation DAL", async () => {
- const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ test("serves a cached allow verdict without hitting the revocation DAL or membership", async () => {
+ const { service, keyStore, identityAccessTokenRevocationDAL, 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({ v: 5 });
@@ -755,6 +755,7 @@ describe("identityAccessTokenServiceFactory", () => {
identityId: "identity-id"
});
expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).not.toHaveBeenCalled();
+ expect(orgDAL.findEffectiveOrgMembership).not.toHaveBeenCalled();
});
test("serves a cached deny verdict without hitting the revocation DAL", async () => {
@@ -772,7 +773,7 @@ describe("identityAccessTokenServiceFactory", () => {
});
test("re-queries the primary when the cached allow version is stale", async () => {
- const { service, keyStore, identityAccessTokenRevocationDAL } = createService();
+ const { service, keyStore, identityAccessTokenRevocationDAL, orgDAL } = createService();
// Live version advanced past the version the cached allow was stamped with.
keyStore.getItem.mockImplementation(async (key: string) => {
if (key.startsWith("identity-revocation-version:")) return "6";
@@ -784,6 +785,10 @@ describe("identityAccessTokenServiceFactory", () => {
identityId: "identity-id"
});
expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).toHaveBeenCalledTimes(1);
+ expect(identityAccessTokenRevocationDAL.findActiveRevocationsForToken).toHaveBeenCalledWith(
+ expect.objectContaining({ scopes: expect.arrayContaining(["org-id"]) as unknown as string[] })
+ );
+ expect(orgDAL.findEffectiveOrgMembership).toHaveBeenCalled();
// Re-stamp the allow with the current live version.
expect(keyStore.setItemWithExpiry).toHaveBeenCalledWith(
expect.stringContaining("identity-revocation-verdict:identity-id:"),
@@ -792,6 +797,39 @@ describe("identityAccessTokenServiceFactory", () => {
);
});
+ test("denies via org-scoped membership marker without a membership re-read when cached", 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")).rejects.toThrow(
+ "not a member"
+ );
+ expect(orgDAL.findEffectiveOrgMembership).not.toHaveBeenCalled();
+ });
+
+ test("revokeTokensForIdentityOrgMembership inserts an org-scoped marker and bumps version", async () => {
+ const { service, identityAccessTokenRevocationDAL, keyStore } = createService();
+
+ await service.revokeTokensForIdentityOrgMembership({ identityId: "identity-id", orgId: "org-id" });
+
+ expect(identityAccessTokenRevocationDAL.insertRevocation).toHaveBeenCalledWith({
+ id: expect.any(String) as unknown as string,
+ identityId: "identity-id",
+ scope: "org-id",
+ revokedAt: new Date(NOW_SECONDS * 1000),
+ expiresAt: new Date((NOW_SECONDS + MAX_AGE) * 1000)
+ });
+ expect(keyStore.incrementSeededWithExpiry).toHaveBeenCalledWith(
+ "identity-revocation-version:identity-id",
+ expect.any(Number),
+ expect.any(Number)
+ );
+ });
+
test("fails open to a direct primary query when the verdict cache read errors", async () => {
const { service, keyStore, identityAccessTokenRevocationDAL } = createService({
activeRevocations: [{ id: "token-id", identityId: "identity-id", createdAt: new Date(NOW_SECONDS * 1000) }]
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 0e8f4ed784..6ef34fb478 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
@@ -112,11 +112,8 @@ export const identityAccessTokenServiceFactory = ({
// old version.
const bumpRevocationVersion = async (identityId: string) => {
try {
- await keyStore.incrementSeededWithExpiry(
- KeyStorePrefixes.IdentityRevocationVersion(identityId),
- Date.now(),
- KeyStoreTtls.IdentityRevocationVersionInSeconds
- );
+ const versionKey = KeyStorePrefixes.IdentityRevocationVersion(identityId);
+ await keyStore.incrementSeededWithExpiry(versionKey, Date.now(), KeyStoreTtls.IdentityRevocationVersionInSeconds);
} catch (error) {
logger.warn(error, `identity-revocation: failed to bump version [identityId=${identityId}]`);
}
@@ -146,12 +143,16 @@ export const identityAccessTokenServiceFactory = ({
// 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.
+ //
+ // 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.
const assertTokenIsNotRevoked = async ({
tokenId,
identityId,
issuedAtMs,
clientSecretId,
authMethod,
+ orgId,
messagePrefix = "Failed to authorize"
}: {
tokenId: string;
@@ -159,11 +160,13 @@ export const identityAccessTokenServiceFactory = ({
issuedAtMs: number;
clientSecretId?: string;
authMethod?: string;
+ orgId?: string;
messagePrefix?: "Failed to authorize" | "Cannot renew";
}) => {
const scopes: string[] = [];
if (clientSecretId) scopes.push(clientSecretId);
if (authMethod) scopes.push(authMethod);
+ if (orgId) scopes.push(orgId);
const fingerprint = computeRevocationVerdictFingerprint({ tokenId, issuedAtMs, clientSecretId, authMethod });
const verdictKey = KeyStorePrefixes.IdentityRevocationVerdict(identityId, fingerprint);
@@ -222,15 +225,33 @@ export const identityAccessTokenServiceFactory = ({
scopes
});
- const denyReason = evaluateRevocationMarkers({
+ let denyReason = evaluateRevocationMarkers({
markers: activeRevocations,
tokenId,
identityId,
issuedAtMs,
clientSecretId,
- authMethod
+ authMethod,
+ orgId
});
+ // Cold-path membership check. Skipped on a stamped allow hit above; after a
+ // version bump every live token rechecks once, and only org-scoped markers
+ // deny (other orgs re-allow and re-cache).
+ if (!denyReason && orgId) {
+ const orgMembership = await orgDAL.findEffectiveOrgMembership({
+ actorType: ActorType.IDENTITY,
+ actorId: identityId,
+ orgId,
+ status: OrgMembershipStatus.Accepted
+ });
+ if (!orgMembership) {
+ denyReason = "org-membership";
+ } else if (!orgMembership.isActive) {
+ denyReason = "org-membership-inactive";
+ }
+ }
+
if (cacheAvailable) {
try {
const ttl = applyJitter(
@@ -416,7 +437,8 @@ export const identityAccessTokenServiceFactory = ({
identityId: token.identityId,
issuedAtMs,
clientSecretId: source.clientSecretId,
- authMethod: source.authMethod
+ authMethod: source.authMethod,
+ orgId: source.orgId
}),
keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(token.identityId, tokenId))
]);
@@ -455,19 +477,6 @@ export const identityAccessTokenServiceFactory = ({
}
}
- const orgMembership = await orgDAL.findEffectiveOrgMembership({
- actorType: ActorType.IDENTITY,
- actorId: token.identityId,
- orgId: source.orgId,
- status: OrgMembershipStatus.Accepted
- });
- if (!orgMembership) {
- throw new UnauthorizedError({ message: "Identity is not a member of the organization" });
- }
- if (!orgMembership.isActive) {
- throw new UnauthorizedError({ message: "Identity organization membership is inactive" });
- }
-
return {
identityId: token.identityId,
identityName: source.identityName,
@@ -522,6 +531,7 @@ export const identityAccessTokenServiceFactory = ({
issuedAtMs: decodedToken.iat * 1000,
clientSecretId: source.clientSecretId,
authMethod: source.authMethod,
+ orgId: source.orgId,
messagePrefix: "Cannot renew"
}),
keyStore.getItem(KeyStorePrefixes.IdentityTokenUsesRemaining(decodedToken.identityId, tokenId))
@@ -724,6 +734,24 @@ export const identityAccessTokenServiceFactory = ({
await bumpRevocationVersion(identityId);
};
+ // Org-scoped revoke for membership deactivate / remove-from-org: rejects every
+ // JWT for this identity whose orgId claim matches, with iat < revokedAt.
+ // Tokens scoped to other orgs (sub-org hierarchy) stay valid. Bumps the global
+ // version so cached allows are rechecked once; only this org's tokens deny.
+ const revokeTokensForIdentityOrgMembership = async ({ identityId, orgId }: { identityId: string; orgId: string }) => {
+ const appCfg = getConfig();
+ const revokedAt = new Date();
+
+ await identityAccessTokenRevocationDAL.insertRevocation({
+ id: crypto.nativeCrypto.randomUUID(),
+ identityId,
+ scope: orgId,
+ revokedAt,
+ expiresAt: new Date(revokedAt.getTime() + appCfg.MAX_MACHINE_IDENTITY_TOKEN_AGE * 1000)
+ });
+ await bumpRevocationVersion(identityId);
+ };
+
return {
issueIdentityAccessToken,
renewAccessToken,
@@ -731,6 +759,7 @@ export const identityAccessTokenServiceFactory = ({
revokeAllTokensForIdentity,
revokeAllTokensForClientSecret,
revokeTokensForIdentityAuthMethod,
+ revokeTokensForIdentityOrgMembership,
markPerTokenRevocation,
fnValidateIdentityAccessTokenFast
};
diff --git a/backend/src/services/identity-access-token/identity-access-token-types.ts b/backend/src/services/identity-access-token/identity-access-token-types.ts
index e71255187d..eb96925088 100644
--- a/backend/src/services/identity-access-token/identity-access-token-types.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-types.ts
@@ -155,4 +155,10 @@ export type TRevocationMarker = {
};
// Reason a token is denied. Cached so a hit can build the error without hitting PG.
-export type TRevocationDenyReason = "token" | "identity" | "client-secret" | "auth-method";
+export type TRevocationDenyReason =
+ | "token"
+ | "identity"
+ | "client-secret"
+ | "auth-method"
+ | "org-membership"
+ | "org-membership-inactive";
diff --git a/backend/src/services/membership-identity/membership-identity-service.ts b/backend/src/services/membership-identity/membership-identity-service.ts
index ebbfc3de17..c5d4c8541b 100644
--- a/backend/src/services/membership-identity/membership-identity-service.ts
+++ b/backend/src/services/membership-identity/membership-identity-service.ts
@@ -14,6 +14,7 @@ import { TUsageMeteringServiceFactory } from "@app/services/license-client/usage
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { TIdentityDALFactory } from "../identity/identity-dal";
+import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { TApplicationMembershipCleanupServiceFactory } from "../membership/application-membership-cleanup-service";
import { assertSecretsTemporaryAccessAllowed } from "../membership/membership-fns";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
@@ -51,6 +52,7 @@ type TMembershipIdentityServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findById">;
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit" | "emitForProject">;
+ identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "revokeTokensForIdentityOrgMembership">;
};
export type TMembershipIdentityServiceFactory = ReturnType<typeof membershipIdentityServiceFactory>;
@@ -67,7 +69,8 @@ export const membershipIdentityServiceFactory = ({
applicationMembershipCleanupService,
projectDAL,
keyStore,
- usageMeteringService
+ usageMeteringService,
+ identityAccessTokenService
}: TMembershipIdentityServiceFactoryDep) => {
const scopeFactory = {
[AccessScope.Organization]: newOrgMembershipIdentityFactory({
@@ -329,6 +332,17 @@ export const membershipIdentityServiceFactory = ({
return { ...doc, roles: insertedRoleDocs };
});
+ if (
+ scopeData.scope === AccessScope.Organization &&
+ data.isActive === false &&
+ existingMembership.isActive !== false
+ ) {
+ await identityAccessTokenService.revokeTokensForIdentityOrgMembership({
+ identityId: dto.selector.identityId,
+ orgId: scopeData.orgId
+ });
+ }
+
return { membership: membershipDoc };
};
@@ -387,6 +401,13 @@ export const membershipIdentityServiceFactory = ({
? await performDelete(externalTx)
: await membershipIdentityDAL.transaction(performDelete);
+ if (scopeData.scope === AccessScope.Organization) {
+ await identityAccessTokenService.revokeTokensForIdentityOrgMembership({
+ identityId: dto.selector.identityId,
+ orgId: scopeData.orgId
+ });
+ }
+
// Removing an identity from a project drops a direct member; removing it from the org cascades its
// project + group memberships. Either way the secret-manager and PAM identity meters change.
if (scopeData.scope === AccessScope.Project) {
diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.ts
index 092b0a4ad1..1dac1fbfba 100644
--- a/backend/src/services/org/org-dal.ts
+++ b/backend/src/services/org/org-dal.ts
@@ -837,14 +837,39 @@ export const orgDALFactory = (db: TDbClient) => {
acceptAnyStatus?: boolean;
tx?: Knex;
}): Promise<TMemberships | null> => {
- const list = await findEffectiveOrgMemberships(dto);
- const directMembership = list.find((membership) =>
- dto.actorType === ActorType.USER
- ? membership.actorUserId === dto.actorId
- : membership.actorIdentityId === dto.actorId
- );
-
- return directMembership ?? list[0] ?? null;
+ try {
+ const conn = dto.tx ?? db.replicaNode();
+ const status = dto.status ?? OrgMembershipStatus.Accepted;
+ const anyStatus = dto.acceptAnyStatus === true;
+ const actorColumn =
+ dto.actorType === ActorType.USER
+ ? (`${TableName.Membership}.actorUserId` as const)
+ : (`${TableName.Membership}.actorIdentityId` as const);
+
+ const directQuery = conn(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .where(`${TableName.Membership}.scopeOrgId`, dto.orgId)
+ .where(actorColumn, dto.actorId)
+ .select(selectAllTableCols(TableName.Membership))
+ .first();
+
+ if (!anyStatus) {
+ void directQuery.where((qb) => {
+ void qb.where(`${TableName.Membership}.status`, status).orWhereNull(`${TableName.Membership}.status`);
+ });
+ }
+
+ const direct = (await directQuery) as TMemberships | undefined;
+ if (direct) {
+ return direct;
+ }
+
+ // Direct miss: fall back to group membership.
+ const list = await findEffectiveOrgMemberships(dto);
+ return list[0] ?? null;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find effective org membership" });
+ }
};
const findMembershipWithScimFilter = async (