Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix enforcement cache stale value
Thiago Araujo da Silvadba75adf8131
diff --git a/backend/AGENTS.md b/backend/AGENTS.mdindex b0cbc602b8..444e1bd111 100644--- a/backend/AGENTS.md+++ b/backend/AGENTS.md@@ -306,10 +306,13 @@ enforces SSO admits only sessions its own IdP issued: `validateOrgSSO` comparesorg's root org on every user permission check, reading it from `userAuthInfo` in the request context(only when the check is for the requester), so it covers `selectOrganization`, OAuth consent, and asession that was already open when enforcement was turned on. Members who can bypass SSO are let-through, and a token with no claim (issued before it existed) is taken at its auth method. A sub-org-has no enforcement of its own: `permissionDAL.getPermission` reads `authEnforced`,-`googleSsoAuthEnforced` and `bypassOrgAuthEnabled` from its root org, and only a root org role can-bypass them, so a sub-org admin role exempts no one.+through, and a token with no claim (issued before it existed) is taken at its auth method. Enforcement+is org policy, not a permission: the permission service reads `authEnforced`, `googleSsoAuthEnforced`+and `bypassOrgAuthEnabled` per request from the root org (`getOrgSsoPolicy`, through the same+`orgFindById` request memo the auth layer fills), never from `permissionDAL.getPermission` or the+cached project permission, so a change applies on the next request. A sub-org has no enforcement of its+own and follows its root, and only a root org role can bypass it, so a sub-org admin role exempts no+one. The project permission cache holds only that role-derived bypass answer.**Every path that issues or re-issues a user token must carry the claim forward** (MFA, refresh,signup, org deletion, delegated OAuth codes and tokens). A dropped claim reads as a pre-claim tokendiff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 4571bf3382..20c74e2723 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -90,7 +90,8 @@ const buildPermissionService = () =>identityDAL: identityDALFactory(testDb),additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb),groupDAL: groupDALFactory(testDb),- secretFolderDAL: secretFolderDALFactory(testDb)+ secretFolderDAL: secretFolderDALFactory(testDb),+ orgDAL: orgDALFactory(testDb)});const grantRows = (diff --git a/backend/e2e-test/routes/v2/secret-folder-rbac.spec.ts b/backend/e2e-test/routes/v2/secret-folder-rbac.spec.tsindex b244b382ba..9bbd3f2f4e 100644--- a/backend/e2e-test/routes/v2/secret-folder-rbac.spec.ts+++ b/backend/e2e-test/routes/v2/secret-folder-rbac.spec.ts@@ -23,6 +23,7 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";import { additionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";import { identityDALFactory } from "@app/services/identity/identity-dal";+import { orgDALFactory } from "@app/services/org/org-dal";import { projectDALFactory } from "@app/services/project/project-dal";import { roleDALFactory } from "@app/services/role/role-dal";import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";@@ -69,7 +70,8 @@ beforeAll(async () => {roleDAL: roleDALFactory(testDb),additionalPrivilegeDAL: additionalPrivilegeDALFactory(testDb),groupDAL: groupDALFactory(testDb),- secretFolderDAL: secretFolderDALFactory(testDb)+ secretFolderDAL: secretFolderDALFactory(testDb),+ orgDAL: orgDALFactory(testDb)});const username = `folder-rbac-${alphaNumericNanoId(8)}@example.com`.toLowerCase();diff --git a/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts b/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.tsindex 58506c0fa1..3651482db4 100644--- a/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts+++ b/backend/e2e-test/routes/v3/auth-sso-session-binding.spec.ts@@ -157,6 +157,55 @@ describe("Auth SSO session binding", () => {expect(refused.json().message).toMatch(/another organization's identity provider/);});+ test("A project read another org's IdP session already cached is refused once the org starts enforcing SSO", async () => {+ const created = await testServer.inject({+ method: "POST",+ url: "/api/v1/projects",+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { projectName: `binding-cache-${crypto.randomUUID().slice(0, 8)}` }+ });+ expect(created.statusCode).toBe(200);+ const projectId = created.json().project.id as string;++ try {+ const { userId, tokens } = await loginThroughOrgBIdp();+ await addMemberToOrgA(userId);+ const user = await getDb()(TableName.Users).where({ id: userId }).first();+ const added = await testServer.inject({+ method: "POST",+ url: `/api/v2/workspace/${projectId}/memberships`,+ headers: { authorization: `Bearer ${jwtAuthToken}` },+ body: { usernames: [user?.username], roleSlugs: ["member"] }+ });+ expect(added.statusCode).toBe(200);++ const { payload: selected } = await selectOrg(tokens.access, ORG_A_ID);+ const readProject = () =>+ testServer.inject({+ method: "GET",+ url: `/api/v1/projects/${projectId}`,+ headers: { authorization: `Bearer ${selected.token}` }+ });+ expect((await readProject()).statusCode).toBe(200);++ await setAuthEnforced(ORG_A_ID, true);+ // The project permission is still cached; enforcement must apply on the very next request.+ const markerKeys = await testRedis.keys(`*project-permission-marker:${projectId}:*`);+ expect(markerKeys.length).toBeGreaterThan(0);+ const refused = await readProject();++ expect(refused.statusCode).toBe(403);+ expect(refused.json().message).toMatch(/another organization's identity provider/);+ } finally {+ await setAuthEnforced(ORG_A_ID, false);+ await testServer.inject({+ method: "DELETE",+ url: `/api/v1/projects/${projectId}`,+ headers: { authorization: `Bearer ${jwtAuthToken}` }+ });+ }+ });+describe("Sub-organizations", () => {let subOrgId: string;diff --git a/backend/src/db/migrations/utils/services.ts b/backend/src/db/migrations/utils/services.tsindex 4059159785..d68672fc3b 100644--- a/backend/src/db/migrations/utils/services.ts+++ b/backend/src/db/migrations/utils/services.ts@@ -89,7 +89,8 @@ export const getMigrationEncryptionServices = async ({identityDAL,additionalPrivilegeDAL,groupDAL,- secretFolderDAL+ secretFolderDAL,+ orgDAL});const licenseService = licenseServiceFactory({diff --git a/backend/src/ee/services/permission/permission-by-roles.test.ts b/backend/src/ee/services/permission/permission-by-roles.test.tsindex 7a10934cac..7b7cc3793e 100644--- a/backend/src/ee/services/permission/permission-by-roles.test.ts+++ b/backend/src/ee/services/permission/permission-by-roles.test.ts@@ -42,7 +42,8 @@ const createService = () => {identityDAL: {} as never,additionalPrivilegeDAL: {} as never,groupDAL: {} as never,- secretFolderDAL: {} as never+ secretFolderDAL: {} as never,+ orgDAL: {} as never} as never);return { service, roleDAL };diff --git a/backend/src/ee/services/permission/permission-dal.ts b/backend/src/ee/services/permission/permission-dal.tsindex 3919385b80..17354aea9b 100644--- a/backend/src/ee/services/permission/permission-dal.ts+++ b/backend/src/ee/services/permission/permission-dal.ts@@ -414,21 +414,7 @@ export const permissionDALFactory = (db: TDbClient): TPermissionDALFactory => {]});- // SSO enforcement is set on the root org only (sub-orgs cannot change it), so a sub-org takes its- // root's settings; otherwise a sub-org session would never be checked against them.- const rootOrgId = data[0]?.rootOrgId;- if (!rootOrgId) return data;- const rootOrg = await (tx || db)- .replicaNode()(TableName.Organization)- .where({ id: rootOrgId })- .select("authEnforced", "googleSsoAuthEnforced", "bypassOrgAuthEnabled")- .first();- return data.map((membership) => ({- ...membership,- orgAuthEnforced: rootOrg?.authEnforced,- orgGoogleSsoAuthEnforced: Boolean(rootOrg?.googleSsoAuthEnforced),- bypassOrgAuthEnabled: Boolean(rootOrg?.bypassOrgAuthEnabled)- }));+ return data;} catch (error) {throw new DatabaseError({ error, name: "Get Permission" });}diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.tsindex a600627dde..23f06f91e3 100644--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@ -60,6 +60,7 @@ import {isValidOauthScope,OauthScope} from "@app/services/oauth-client/oauth-scope";+import { TOrgDALFactory } from "@app/services/org/org-dal";import { TProjectDALFactory } from "@app/services/project/project-dal";import { TRoleDALFactory } from "@app/services/role/role-dal";import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";@@ -377,6 +378,7 @@ type TPermissionServiceFactoryDep = {additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "find" | "findFolderScopedPrivileges">;groupDAL: Pick<TGroupDALFactory, "find">;secretFolderDAL: Pick<TSecretFolderDALFactory, "findSecretPathByFolderIds">;+ orgDAL: Pick<TOrgDALFactory, "findById">;};export const permissionServiceFactory = ({@@ -389,8 +391,31 @@ export const permissionServiceFactory = ({roleDAL,additionalPrivilegeDAL,groupDAL,- secretFolderDAL+ secretFolderDAL,+ orgDAL}: TPermissionServiceFactoryDep): TPermissionServiceFactory => {+ const getOrgSsoPolicy = async (rootOrgId: string) => {+ const rootOrg = await requestMemoize(requestMemoKeys.orgFindById(rootOrgId), () => orgDAL.findById(rootOrgId));+ return {+ isOrgSsoEnforced: Boolean(rootOrg?.authEnforced),+ isOrgGoogleSsoEnforced: Boolean(rootOrg?.googleSsoAuthEnforced),+ isOrgSsoBypassEnabled: Boolean(rootOrg?.bypassOrgAuthEnabled)+ };+ };++ const canBypassRootOrgSso = async (actorId: string, rootOrgId: string) => {+ const rootPermissionData = await permissionDAL.getPermission({+ scopeData: { scope: AccessScope.Organization, orgId: rootOrgId },+ actorId,+ actorType: ActorType.USER+ });+ if (!rootPermissionData?.length) return false;+ return createMongoAbility<OrgPermissionSet>(+ buildOrgPermissionRules(flattenActiveRolesFromMemberships(rootPermissionData, OrgMembershipRole.Custom)),+ { conditionsMatcher }+ ).can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);+ };+const getOrgPermission: TPermissionServiceFactory["getOrgPermission"] = async ({actor,actorId,@@ -450,33 +475,20 @@ export const permissionServiceFactory = ({conditionsMatcher});- let canBypassSso = fullPermission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);-- // A sub-org inherits its root's enforcement, so only a root org role may bypass it, the same as- // selectOrganization and project permissions decide it; a sub-org role must not exempt anyone.- const isSsoEnforced = permissionData[0].orgAuthEnforced || permissionData[0].orgGoogleSsoAuthEnforced;- if (actor === ActorType.USER && rootOrgId && isSsoEnforced) {- const rootPermissionData = await permissionDAL.getPermission({- scopeData: { scope: AccessScope.Organization, orgId: rootOrgId },- actorId,- actorType: ActorType.USER- });- canBypassSso =- rootPermissionData.length > 0 &&- createMongoAbility<OrgPermissionSet>(- buildOrgPermissionRules(flattenActiveRolesFromMemberships(rootPermissionData, OrgMembershipRole.Custom)),- { conditionsMatcher }- ).can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);- }-// SSO enforcement applies only to users. Evaluate it against the full ability — SSO bypass is a// property of the user's roles, not of what an OAuth client was delegated.if (actor === ActorType.USER) {+ const ssoPolicy = await getOrgSsoPolicy(rootOrgId ?? orgId);+ const isSsoEnforced = ssoPolicy.isOrgSsoEnforced || ssoPolicy.isOrgGoogleSsoEnforced;+ let canBypassSso = false;+ if (isSsoEnforced) {+ canBypassSso = rootOrgId+ ? await canBypassRootOrgSso(actorId, rootOrgId)+ : fullPermission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);+ }validateOrgSSO({actorAuthMethod,- isOrgSsoEnforced: permissionData?.[0].orgAuthEnforced,- isOrgGoogleSsoEnforced: Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),- isOrgSsoBypassEnabled: Boolean(permissionData?.[0].bypassOrgAuthEnabled),+ ...ssoPolicy,isAdmin: canBypassSso,issuingRootOrgId: getSessionIssuingRootOrgId(actorId),rootOrgId: rootOrgId ?? orgId@@ -659,29 +671,10 @@ export const permissionServiceFactory = ({username = identityDetails?.name ?? "";}- // SSO bypass check (for USER actors) — pre-compute and cache the boolean- let canBypassSso = false;- if (actor === ActorType.USER) {- const enforceSsoAndBypassEnabled =- permissionData?.[0].orgAuthEnforced ||- (permissionData?.[0].orgGoogleSsoAuthEnforced && permissionData?.[0].bypassOrgAuthEnabled);-- if (enforceSsoAndBypassEnabled) {- const orgIdForBypass = permissionData?.[0].rootOrgId ?? projectDetails.orgId;- const orgPermissionData = await permissionDAL.getPermission({- scopeData: { scope: AccessScope.Organization, orgId: orgIdForBypass },- actorId,- actorType: ActorType.USER- });- if (orgPermissionData?.length) {- const orgPermissionFromRoles = flattenActiveRolesFromMemberships(orgPermissionData, OrgMembershipRole.Custom);- const orgPermission = createMongoAbility<OrgPermissionSet>(buildOrgPermissionRules(orgPermissionFromRoles), {- conditionsMatcher- });- canBypassSso = orgPermission.can(OrgPermissionSsoActions.BypassSsoEnforcement, OrgPermissionSubjects.Sso);- }- }- }+ const canBypassSso =+ actor === ActorType.USER+ ? await canBypassRootOrgSso(actorId, permissionData?.[0].rootOrgId ?? projectDetails.orgId)+ : false;// Folder-scoped grants ride in the same cached blob, behind the same fingerprint. Admins cannot// receive folder grants, but a grant can predate a promotion to admin; skip the fetch so such a@@ -813,14 +806,13 @@ export const permissionServiceFactory = ({// SSO enforcement runs on every request (uses per-request actorAuthMethod, not cached)if (actor === ActorType.USER) {+ const rootOrgId = permissionData?.[0].rootOrgId ?? projectDetails.orgId;validateOrgSSO({actorAuthMethod,- isOrgSsoEnforced: permissionData?.[0].orgAuthEnforced,- isOrgGoogleSsoEnforced: Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),- isOrgSsoBypassEnabled: Boolean(permissionData?.[0].bypassOrgAuthEnabled),+ ...(await getOrgSsoPolicy(rootOrgId)),isAdmin: canBypassSso,issuingRootOrgId: getSessionIssuingRootOrgId(actorId),- rootOrgId: permissionData?.[0].rootOrgId ?? projectDetails.orgId+ rootOrgId});}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a4ff1ab80b..72b18feaba 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -924,7 +924,8 @@ export const registerRoutes = async (identityDAL,additionalPrivilegeDAL,groupDAL,- secretFolderDAL: folderDAL+ secretFolderDAL: folderDAL,+ orgDAL});const assumePrivilegeService = assumePrivilegeServiceFactory({diff --git a/backend/src/services/auth-token/auth-token-service.test.ts b/backend/src/services/auth-token/auth-token-service.test.tsindex db7e237b66..076158c915 100644--- a/backend/src/services/auth-token/auth-token-service.test.ts+++ b/backend/src/services/auth-token/auth-token-service.test.ts@@ -267,6 +267,7 @@ describe("tokenServiceFactory — org scope of user tokens", () => {} = {}) => {const orgDAL = {findOne: vi.fn(async ({ id }: { id: string }) => orgs[id]),+ findById: vi.fn(async (id: string) => orgs[id]),// Mirrors the DAL: a status filter hides rows in any other status unless acceptAnyStatus is set.findEffectiveOrgMembership: vi.fn(async ({ orgId, status, acceptAnyStatus }: { orgId: string; status?: string; acceptAnyStatus?: boolean }) => {@@ -374,7 +375,7 @@ describe("tokenServiceFactory — org scope of user tokens", () => {const { service, orgDAL } = build();const identity = await service.fnValidateJwtIdentity(accessToken({}));expect(identity).toMatchObject({ orgId: "", rootOrgId: "" });- expect(orgDAL.findOne).not.toHaveBeenCalled();+ expect(orgDAL.findById).not.toHaveBeenCalled();});test("a token for an org that no longer exists is refused with 401, not a 500", async () => {diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.tsindex 2cb2e999e5..4971494303 100644--- a/backend/src/services/auth-token/auth-token-service.ts+++ b/backend/src/services/auth-token/auth-token-service.ts@@ -26,7 +26,7 @@ import {type TAuthTokenServiceFactoryDep = {tokenDAL: TTokenDALFactory;userDAL: Pick<TUserDALFactory, "findById" | "transaction">;- orgDAL: Pick<TOrgDALFactory, "findOne" | "findEffectiveOrgMembership">;+ orgDAL: Pick<TOrgDALFactory, "findOne" | "findById" | "findEffectiveOrgMembership">;membershipUserDAL: Pick<TMembershipUserDALFactory, "findOne">;keyStore: Pick<TKeyStoreFactory,@@ -426,7 +426,9 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu}if (!subOrganizationId) {- const organization = await orgDAL.findOne({ id: organizationId });+ const organization = await requestMemoize(requestMemoKeys.orgFindById(organizationId), () =>+ orgDAL.findById(organizationId)+ );if (!organization) {throw new UnauthorizedError({@@ -443,7 +445,9 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu};}- const subOrganization = await orgDAL.findOne({ id: subOrganizationId });+ const subOrganization = await requestMemoize(requestMemoKeys.orgFindById(subOrganizationId), () =>+ orgDAL.findById(subOrganizationId)+ );if (!subOrganization) {throw new UnauthorizedError({message: `The sub-organization with ID '${subOrganizationId}' no longer exists. Log in again.`