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
Merge branch 'main' into feature/project-permission-caching
Victor Hugo dos Santosaf34f5cf3cd0
diff --cc backend/CLAUDE.mdindex 18af7d3104,a38752b021..dac4f05cb1--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@@ -124,15 -124,43 +124,52 @@@ Uses CASL (`@casl/ability`) with MongoDBuilt-in roles: `Admin`, `Member`, `Viewer`, `NoAccess`. Custom roles use unpacked CASL rules stored in the database. Rules can include conditions with operators `$IN`, `$EQ`, `$NEQ`, `$GLOB` (for pattern matching like `prod-*`). See `PermissionConditionSchema` in `permission-types.ts`.+**Project permission caching** uses a fingerprint-based two-tier cache (`withCacheFingerprint` in `src/lib/cache/with-cache.ts`):+- **Short-lived marker** (10s TTL) in Redis — while present, cached data is served with 0 DB reads.+- **Long-lived data payload** (10m TTL) in Redis — holds the full permission blob plus a fingerprint hash.+- On marker expiry, a lightweight **fingerprint query** (`getPermissionFingerprint` in `permission-dal.ts`) runs (1 DB read). If the fingerprint matches the cached payload, the marker is reset; otherwise, a full data re-fetch occurs.+- The fingerprint covers **both project-scoped and org-scoped** memberships for the actor, so org-level changes (e.g. SSO bypass grant/revoke, org role edits) also trigger cache invalidation.+- `filterTemporary` in `flattenActiveRolesFromMemberships` runs on every request as a real-time safety net — it filters out expired temporary access regardless of cache state, so access revocation for timed roles/privileges is immediate.+- **No explicit cache invalidation calls exist.** The fingerprint self-corrects within the marker TTL (10s eventual consistency for access granting). The old `invalidateProjectPermissionCache` / DAL version counter pattern has been removed.+- Cache helpers (`cacheGet`, `cacheSet`, `applyReviver`) in `src/lib/cache/with-cache.ts` are shared between the simple `withCache` and the fingerprint-based `withCacheFingerprint`.++ ### Request-Scoped Memoization++ A per-request in-memory cache that eliminates redundant DB reads within a single HTTP request. Defined in `src/lib/request-context/request-memoizer.ts`, attached to Fastify's `@fastify/request-context` as the `memoizer` field (initialized in `src/server/app.ts`). Cache is automatically garbage-collected when the request ends — zero staleness risk, zero infrastructure.++ **How it works**: `RequestMemoizer` wraps a `Map<string, unknown>` with an async `getOrSet(key, fetcher)` method. Concurrent calls for the same key coalesce onto a single fetcher invocation (in-flight deduplication). The `requestMemoize(key, fetcher)` helper reads the memoizer from request context and falls back to direct execution when no context exists (e.g. queue workers).++ **Currently memoized**:+ - `getProjectPermission` — full-function result (keyed by projectId + actor + actorId + actorOrgId + actorAuthMethod + actionProjectType). Eliminates redundant permission checks in batch secret operations (50 secrets → 1 DB round-trip instead of 50).+ - `getOrgPermission` — full-function result (keyed by orgId + actor + actorId + actorOrgId + actorAuthMethod + scope).+ - `projectDAL.findById` — in permission-service.ts and project-bot-fns.ts. Deduplicates 4 of the 5 redundant project lookups seen per secret read request.+ - `userDAL.findById` / `identityDAL.findById` — in permission-service.ts. Eliminates the redundant actor lookup during permission resolution.++ **Usage pattern**:+ ```ts+ import { requestMemoize } from "@app/lib/request-context/request-memoizer";++ // In a service or function called during request handling:+ const project = await requestMemoize(+ `project:findById:${projectId}`,+ () => projectDAL.findById(projectId)+ );+ ```++ **When to add more items to request-scoped memoization**:+ - The data is **read-only within the request** — no mutations to the same record happen between reads.+ - The same DAL call (same table, same ID) is made **2+ times in the same request** across different services or functions. Check with Datadog traces or by searching for the DAL method across call sites in the hot path.+ - The call does **NOT use a DB transaction** (`trx` parameter). Transactional reads may see different data than read-replica results; memoizing them could return stale data.+ - The call is on a **hot path** (auth, permissions, secret CRUD). Low-frequency admin endpoints don't benefit enough to justify the added indirection.++ **When NOT to use**:+ - Inside DB transactions — pass `trx` directly, skip memoization.+ - For data mutated within the request and re-read (e.g. KMS key creation writes to the project row, then re-reads it).+ - In queue workers or background jobs — the helper falls back gracefully, but there's no request lifecycle to scope the cache.+ - For write operations — only memoize reads.++ **Key format convention**: `<entity>:<method>:<id>` for DAL calls (e.g. `project:findById:${projectId}`), `permission:<scope>:<id>:...` for permission results.+### Queue System (BullMQ)Queue infrastructure in `src/queue/queue-service.ts`. Defines 30+ named queues via `QueueName` enum (e.g., `SecretRotation`, `AuditLog`, `IntegrationSync`, `SecretReplication`, `SecretSync`, `DynamicSecretRevocation`). Each queue has typed payloads defined in `TQueueJobTypes`.diff --cc backend/src/ee/services/access-approval-request/access-approval-request-service.tsindex 9fc317d92e,9450737f10..aa067373ba--- a/backend/src/ee/services/access-approval-request/access-approval-request-service.ts+++ b/backend/src/ee/services/access-approval-request/access-approval-request-service.ts@@@ -32,8 -34,8 +34,8 @@@ import { TAccessApprovalRequestReviewerimport { ApprovalStatus, TAccessApprovalRequestServiceFactory } from "./access-approval-request-types";type TSecretApprovalRequestServiceFactoryDep = {- additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "create" | "findById">;+ additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "create" | "findById" | "deleteById">;- permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "invalidateProjectPermissionCache">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;accessApprovalPolicyApproverDAL: Pick<TAccessApprovalPolicyApproverDALFactory, "find">;projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;projectDAL: Pick<@@@ -755,9 -757,16 +757,14 @@@ export const accessApprovalRequestServi}await accessApprovalRequestDAL.updateById(accessApprovalRequest.id,- { privilegeId: privilegeIdToSet, status: ApprovalStatus.APPROVED },+ {+ privilegeId: privilegeIdToSet,+ status: ApprovalStatus.APPROVED,+ approvedAt: new Date(),+ approvedByUserId: actorId+ },tx);-- await permissionService.invalidateProjectPermissionCache(accessApprovalRequest.projectId, tx);}}@@@ -814,7 -823,75 +821,73 @@@return reviewForThisActorProcessing;});- return { ...reviewStatus, projectId: accessApprovalRequest.projectId };+ return { ...reviewStatus, projectId: accessApprovalRequest.projectId, policyId: accessApprovalRequest.policyId };+ };++ const revokeAccessRequest: TAccessApprovalRequestServiceFactory["revokeAccessRequest"] = async ({+ requestId,+ actor,+ actorId,+ actorOrgId,+ actorAuthMethod+ }) => {+ const accessApprovalRequest = await accessApprovalRequestDAL.findById(requestId);+ if (!accessApprovalRequest)+ throw new NotFoundError({ message: `Access approval request with ID '${requestId}' not found` });++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: accessApprovalRequest.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ const targetUser = await userDAL.findById(accessApprovalRequest.requestedByUserId);+ if (!targetUser) throw new NotFoundError({ message: "Target user not found" });++ const memberSubject = subject(ProjectPermissionSub.Member, {+ userEmail: targetUser.email ?? undefined+ });++ const canAssignAdditionalPrivileges = permission.can(+ ProjectPermissionMemberActions.AssignAdditionalPrivileges,+ memberSubject+ );+ const canGrantPrivilegesLegacy = permission.can(ProjectPermissionMemberActions.GrantPrivileges, memberSubject);+ const isApprover = accessApprovalRequest.policy.approvers.some((approver) => approver.userId === actorId);++ if (!canAssignAdditionalPrivileges && !canGrantPrivilegesLegacy && !isApprover) {+ throw new ForbiddenRequestError({+ message: "You do not have permission to revoke additional privileges for this user"+ });+ }++ if (accessApprovalRequest.status !== ApprovalStatus.APPROVED) {+ throw new BadRequestError({ message: "Only approved requests can be revoked" });+ }++ const updatedRequest = await accessApprovalRequestDAL.transaction(async (tx) => {+ const result = await accessApprovalRequestDAL.updateById(+ requestId,+ {+ status: ApprovalStatus.REVOKED,+ revokedAt: new Date(),+ revokedByUserId: actorId,+ privilegeId: null+ },+ tx+ );++ if (accessApprovalRequest.privilegeId) {+ await additionalPrivilegeDAL.deleteById(accessApprovalRequest.privilegeId, tx);+ }+- await permissionService.invalidateProjectPermissionCache(accessApprovalRequest.projectId, tx);-+ return result;+ });++ return { request: updatedRequest, projectId: accessApprovalRequest.projectId };};const getCount: TAccessApprovalRequestServiceFactory["getCount"] = async ({diff --cc backend/src/ee/services/permission/permission-service.tsindex 073ffd5c6f,8c3e849267..2927a30028--- a/backend/src/ee/services/permission/permission-service.ts+++ b/backend/src/ee/services/permission/permission-service.ts@@@ -420,103 -397,177 +433,136 @@@ export const permissionServiceFactoryname: "Get org permission"});}-- const projectPermissionActor: ActorType.USER | ActorType.IDENTITY =- actor === ActorType.USER ? ActorType.USER : ActorType.IDENTITY;+ const narrowedActor: ActorType.USER | ActorType.IDENTITY = actor;- // --- Permission cache: fingerprint-based with marker + data keys ---- const cached: TCachedProjectPermission = await withCacheFingerprint<TCachedProjectPermission>({- keyStore,- dataKey: KeyStorePrefixes.ProjectPermissionData(projectId, narrowedActor, actorId, actionProjectType),- markerKey: KeyStorePrefixes.ProjectPermissionMarker(projectId, narrowedActor, actorId, actionProjectType),- markerTtlSeconds: KeyStoreTtls.ProjectPermissionMarkerTtlSeconds,- dataTtlSeconds: KeyStoreTtls.ProjectPermissionDataTtlSeconds,- fingerprintFetcher: () =>- permissionDAL.getPermissionFingerprint({- projectId,- orgId: actorOrgId || "",- actorId,- actorType: narrowedActor- }),- dataFetcher: () => $fetchProjectPermissionData(projectId, actorOrgId, actionProjectType, narrowedActor, actorId),- reviver: (parsed: TCachedProjectPermission) => {- reviveCachedPermissionDates(parsed.permissionData);- }+ // Request-scoped full-function memoization: identical permission checks within the same request+ const memoKey = requestMemoKeys.projectPermission({+ projectId,+ actor,+ actorId,+ actorAuthMethod,+ actionProjectType,+ actorOrgId});+ const memoizer = requestContext.get(RequestContextKey.Memoizer);- const { permissionData, projectDetails, username, canBypassSso } = cached;+ type TProjectPermissionMemoPayload = {+ result: Awaited<ReturnType<TPermissionServiceFactory["getProjectPermission"]>>;+ projectDetailsCtx: { id: string; name: string; slug: string };+ identityPermissionMetadataCtx: Record<string, unknown>;+ };- // Re-validate org and project type on cache hit (actorOrgId is not in cache key)- if (projectDetails.orgId !== actorOrgId) {- throw new ForbiddenRequestError({ name: "This project does not belong to your selected organization." });- }- if (actionProjectType !== ActionProjectType.Any && actionProjectType !== projectDetails.type) {- throw new BadRequestError({- message: `The project is of type ${projectDetails.type}. Operations of type ${actionProjectType} are not allowed.`+ const loadProjectPermission = async (): Promise<TProjectPermissionMemoPayload> => {- // DAL-level memoization: deduplicates projectDAL.findById across services- // (permission service, getBotKey, KMS) within the same request.- const projectDetails = await requestMemoize(requestMemoKeys.projectFindById(projectId), () =>- projectDAL.findById(projectId)- );- if (!projectDetails) {- throw new NotFoundError({ message: `Project with ${projectId} not found` });- }++ // Layer 2: Redis fingerprint cache (marker 10s + data 10m)++ const cached: TCachedProjectPermission = await withCacheFingerprint<TCachedProjectPermission>({++ keyStore,++ dataKey: KeyStorePrefixes.ProjectPermissionData(projectId, narrowedActor, actorId, actionProjectType),++ markerKey: KeyStorePrefixes.ProjectPermissionMarker(projectId, narrowedActor, actorId, actionProjectType),++ markerTtlSeconds: KeyStoreTtls.ProjectPermissionMarkerTtlSeconds,++ dataTtlSeconds: KeyStoreTtls.ProjectPermissionDataTtlSeconds,++ fingerprintFetcher: () =>++ permissionDAL.getPermissionFingerprint({++ projectId,++ orgId: actorOrgId || "",++ actorId,++ actorType: narrowedActor++ }),++ dataFetcher: () =>++ $fetchProjectPermissionData(projectId, actorOrgId, actionProjectType, narrowedActor, actorId),++ reviver: (parsed: TCachedProjectPermission) => {++ reviveCachedPermissionDates(parsed.permissionData);++ }+ });- }- requestContext.set("projectDetails", {- id: projectDetails.id,- name: projectDetails.name,- slug: projectDetails.slug- });- const projectDetailsCtx = {- id: projectDetails.id,- name: projectDetails.name,- slug: projectDetails.slug- };++ const { permissionData, projectDetails, username, canBypassSso } = cached;- const permissionFromRoles = flattenActiveRolesFromMemberships(permissionData, ProjectMembershipRole.Custom);++ // Re-validate org and project type on cache hit (actorOrgId is not in cache key)+ if (projectDetails.orgId !== actorOrgId) {- throw new ForbiddenRequestError({ message: "This project does not belong to your selected organization." });++ throw new ForbiddenRequestError({ name: "This project does not belong to your selected organization." });+ }-+ if (actionProjectType !== ActionProjectType.Any && actionProjectType !== projectDetails.type) {+ throw new BadRequestError({+ message: `The project is of type ${projectDetails.type}. Operations of type ${actionProjectType} are not allowed.`+ });+ }- const hasRole = (role: string) =>- permissionData.some((memberships) => memberships.roles.some((el) => role === (el.customRoleSlug || el.role)));- const permissionData = await permissionDAL.getPermission({- scopeData: {- scope: AccessScope.Project,- orgId: projectDetails.orgId,- projectId- },- actorId,- actorType: projectPermissionActor- });- if (!permissionData?.length)- throw new ForbiddenRequestError({- message: `You are not a member of this project with ID ${projectId}. Please assign this ${projectPermissionActor} to the project with the appropriate permissions, then try again.`- });++ const projectDetailsCtx = {++ id: projectDetails.id,++ name: projectDetails.name,++ slug: projectDetails.slug++ };++ const permissionFromRoles = flattenActiveRolesFromMemberships(permissionData, ProjectMembershipRole.Custom);++ const hasRole = (role: string) =>+ permissionData.some((memberships) => memberships.roles.some((el) => role === (el.customRoleSlug || el.role)));+- // SSO enforcement applies only to users; use org-level bypass criteria (Org Admin or BypassSsoEnforcement permission)- // When project is in sub-org, use root org for bypass check (SSO enforced at root; user's bypass permission is in root org)++ // SSO enforcement runs on every request (uses per-request actorAuthMethod, not cached)+ if (actor === ActorType.USER) {- let canBypassSso = false;- 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);- }- }+ validateOrgSSO(+ actorAuthMethod,+ permissionData?.[0].orgAuthEnforced,+ Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),+ Boolean(permissionData?.[0].bypassOrgAuthEnabled),+ canBypassSso+ );+ }- // SSO enforcement runs on every request (uses per-request actorAuthMethod)- if (actor === ActorType.USER) {- validateOrgSSO(- actorAuthMethod,- permissionData?.[0].orgAuthEnforced,- Boolean(permissionData?.[0].orgGoogleSsoAuthEnforced),- Boolean(permissionData?.[0].bypassOrgAuthEnabled),- canBypassSso+ const rules = buildProjectPermissionRules(permissionFromRoles);+ const templatedRules = handlebars.compile(JSON.stringify(rules), { data: false });+ const unescapedMetadata = objectify(+ permissionData?.[0]?.metadata,+ (i) => i.key,+ (i) => i.value+ );+ const metadataKeyValuePair = escapeHandlebarsMissingDict(unescapedMetadata, "identity.metadata");+ const identityPermissionMetadataCtx = { metadata: unescapedMetadata };+- let username = "";- if (actor === ActorType.USER) {- const userDetails = await requestMemoize(requestMemoKeys.userFindById(actorId), () =>- userDAL.findById(actorId)- );- username = userDetails?.username;- } else {- const identityDetails = await requestMemoize(requestMemoKeys.identityFindById(actorId), () =>- identityDAL.findById(actorId)- );- username = identityDetails?.name;- }-+ const unescapedIdentityAuthInfo = requestContext.get(RequestContextKey.IdentityAuthInfo);+ const identityAuthInfo =+ unescapedIdentityAuthInfo?.identityId === actorId && unescapedIdentityAuthInfo+ ? escapeHandlebarsMissingDict(unescapedIdentityAuthInfo as never, "identity.auth")+ : {};++ const interpolateRules = templatedRules(+ {+ identity: {+ id: actorId,+ username,+ metadata: metadataKeyValuePair,+ auth: identityAuthInfo+ }+ },+ { data: false });- }- const rules = buildProjectPermissionRules(permissionFromRoles);- const templatedRules = handlebars.compile(JSON.stringify(rules), { data: false });- const unescapedMetadata = objectify(- permissionData?.[0]?.metadata,- (i) => i.key,- (i) => i.value- );- const metadataKeyValuePair = escapeHandlebarsMissingDict(unescapedMetadata, "identity.metadata");- requestContext.set("identityPermissionMetadata", { metadata: unescapedMetadata });-- const unescapedIdentityAuthInfo = requestContext.get("identityAuthInfo");- const identityAuthInfo =- unescapedIdentityAuthInfo?.identityId === actorId && unescapedIdentityAuthInfo- ? escapeHandlebarsMissingDict(unescapedIdentityAuthInfo as never, "identity.auth")- : {};-- const interpolateRules = templatedRules(- {- identity: {- id: actorId,- username,- metadata: metadataKeyValuePair,- auth: identityAuthInfo+ const permission = createMongoAbility<ProjectPermissionSet>(+ JSON.parse(interpolateRules) as RawRuleOf<MongoAbility<ProjectPermissionSet>>[],+ {+ conditionsMatcher}- },- { data: false }- );-- const permission = createMongoAbility<ProjectPermissionSet>(- JSON.parse(interpolateRules) as RawRuleOf<MongoAbility<ProjectPermissionSet>>[],- {- conditionsMatcher- }- );+ );- return {- permission,- memberships: permissionData,- hasRole,- hasProjectEnforcement: $checkProjectEnforcement(projectDetails)+ const result = {+ permission,+ memberships: permissionData,+ hasRole,+ hasProjectEnforcement: $checkProjectEnforcement(projectDetails)+ };++ return {+ result,+ projectDetailsCtx,+ identityPermissionMetadataCtx+ };};+++ // Layer 1: in-memory per-request memoization → Layer 2: Redis fingerprint cache → Layer 3: DB+ const payload = memoizer ? await memoizer.getOrSet(memoKey, loadProjectPermission) : await loadProjectPermission();++ requestContext.set(RequestContextKey.ProjectDetails, payload.projectDetailsCtx);+ requestContext.set(RequestContextKey.IdentityPermissionMetadata, payload.identityPermissionMetadataCtx);+ return payload.result;};const getProjectPermissions: TPermissionServiceFactory["getProjectPermissions"] = async (projectId, orgId) => {