Skip to content

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

fix(insights): check each person with one permission merged across their memberships

Dimitris Staratzis2dc4b8d5f7c8
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 116029c373..84a912f776 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -1153,7 +1153,8 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
everything by design. Their reads are still recorded, so the access sheet's Last Read stays true for them. A
pair is listed once the secret (`trackedSince`) and the actor's access to that secret both predate `judgedFrom`.
Access is dated per secret (`createAccessDating`): each actor's sources (every role assignment and project-wide
- privilege, from `getProjectPermissions`' `accessSources`; each group they are in; each folder grant) carry the date
+ privilege, from `getProjectPermissions`' `accessSources`; each group they are in, from `permissionForActor` with
+ `groupsOnly` so placeholders hold the member's details; each folder grant) carry the date
`findAccessSourceDates` gives them, and a secret's access dates from the oldest source that grants it on its own,
so a change only restarts the window for the secrets it opened. An edit to a custom role's rules dates that role
for every secret it gives, since which secrets an edit opened is not recorded. Expired access is not a source,
@@ -1180,8 +1181,11 @@ owns the two read endpoints and hands `recordRead` / `recordBulkRead` through to
(`id`/`folderId`/`environment`/`secretPath`/`role`). A folder grant is stored as an additional privilege with a
`folderId`, which the member listings filter out, so `getProjectPermissions` returns them as
`folderAccessByActorId` from the grants it already loads. The UI decides how to label all of them. Custom role ids and names come from
- `getProjectPermissions`, so the scan makes no role lookup of its own. Group members are checked with the group's
- permission (`getProjectPermissions` lists only direct members) and count once however many ways they qualify. It
+ `getProjectPermissions`, so the scan makes no role lookup of its own. Each person is checked with one permission merged across their direct membership and every group
+ they are in (`getProjectPermissions().permissionForActor`, built from getProjectPermission's own steps by
+ `buildMergedProjectPermissionRules`), so a deny in one role holds against an allow in another, and placeholders
+ such as `{{identity.username}}` are filled from that person's details (looked up for group-only members only
+ when a group role holds one). It
is cached per project for a day (`insights-cache:<projectId>:unused-access`, under a per-project lock on a cold
cache): every actor's row, plus the unread secret ids for the 200 actors with the most, capped at 200 each; an
actor past that is scanned for alone when opened and cached per actor. Served by
diff --git a/backend/src/ee/services/permission/merged-project-permission.test.ts b/backend/src/ee/services/permission/merged-project-permission.test.ts
new file mode 100644
index 0000000000..929478eccd
--- /dev/null
+++ b/backend/src/ee/services/permission/merged-project-permission.test.ts
@@ -0,0 +1,84 @@
+import { createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";
+import { packRules } from "@casl/ability/extra";
+import { describe, expect, test } from "vitest";
+
+import { ProjectMembershipRole } from "@app/db/schemas";
+import { conditionsMatcher } from "@app/lib/casl";
+
+import { hasSecretReadValueOrDescribePermission } from "./permission-fns";
+import { buildMergedProjectPermissionRules } from "./permission-service";
+import { ProjectPermissionSecretActions, ProjectPermissionSet, ProjectPermissionSub } from "./project-permission";
+
+const customRole = (rules: RawRuleOf<MongoAbility<ProjectPermissionSet>>[]) => ({
+ roles: [{ role: ProjectMembershipRole.Custom, permissions: packRules(rules) }]
+});
+const canRead = (rules: ReturnType<typeof buildMergedProjectPermissionRules>, secretPath: string) =>
+ hasSecretReadValueOrDescribePermission(
+ createMongoAbility<ProjectPermissionSet>(rules, { conditionsMatcher }),
+ ProjectPermissionSecretActions.ReadValue,
+ { environment: "prod", secretPath, secretName: "KEY", secretTags: [] }
+ );
+const identity = (username: string) => ({ id: "actor", username, metadata: [] });
+
+describe("buildMergedProjectPermissionRules", () => {
+ test("lets a group's deny hold against an allow from the direct membership", () => {
+ const rules = buildMergedProjectPermissionRules({
+ memberships: [
+ customRole([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "prod" }
+ }
+ ]),
+ customRole([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "prod", secretPath: "/payments" },
+ inverted: true
+ }
+ ])
+ ],
+ identity: identity("alice")
+ });
+ expect(canRead(rules, "/payments")).toBe(false);
+ expect(canRead(rules, "/api")).toBe(true);
+ });
+
+ test("fills a group role's placeholder with the person's own username", () => {
+ const rules = buildMergedProjectPermissionRules({
+ memberships: [
+ customRole([
+ {
+ action: ProjectPermissionSecretActions.ReadValue,
+ subject: ProjectPermissionSub.Secrets,
+ conditions: { environment: "prod", secretPath: "/users/{{identity.username}}" }
+ }
+ ])
+ ],
+ identity: identity("bob")
+ });
+ expect(canRead(rules, "/users/bob")).toBe(true);
+ expect(canRead(rules, "/users/alice")).toBe(false);
+ });
+
+ test("leaves out folder grants when any membership holds the Admin role", () => {
+ const listOnly = [{ id: "grant", folderId: "folder", role: "list", environmentSlug: "prod", secretPath: "/api" }];
+ const asMember = buildMergedProjectPermissionRules({
+ memberships: [{ roles: [{ role: ProjectMembershipRole.Member }] }],
+ folderGrants: listOnly,
+ identity: identity("carol")
+ });
+ const asAdminThroughGroup = buildMergedProjectPermissionRules({
+ memberships: [
+ { roles: [{ role: ProjectMembershipRole.Member }] },
+ { roles: [{ role: ProjectMembershipRole.Admin }] }
+ ],
+ folderGrants: listOnly,
+ identity: identity("carol")
+ });
+ expect(canRead(asMember, "/api")).toBe(false);
+ expect(canRead(asAdminThroughGroup, "/api")).toBe(true);
+ });
+});
diff --git a/backend/src/ee/services/permission/permission-service-types.ts b/backend/src/ee/services/permission/permission-service-types.ts
index 6fc98ac9d7..6687a83bbd 100644
--- a/backend/src/ee/services/permission/permission-service-types.ts
+++ b/backend/src/ee/services/permission/permission-service-types.ts
@@ -195,8 +195,6 @@ export type TPermissionServiceFactory = {
}[];
groupPermissions: {
permission: MongoAbility<ProjectPermissionSet, MongoQuery>;
- // The group's roles with the given member's own folder grants applied on top.
- permissionForMember: (actorId: string) => MongoAbility<ProjectPermissionSet, MongoQuery>;
id: string;
name: string;
membershipId: string;
@@ -210,6 +208,21 @@ export type TPermissionServiceFactory = {
// Each user's and identity's active folder grants, keyed by actor id, whether they are a direct member or
// reach the project through a group. Admins are listed too, though their grants are never applied.
folderAccessByActorId: Map<string, TProjectFolderScopedPrivilege[]>;
+ // One person's permission merged across their direct membership and the given groups, the way
+ // getProjectPermission builds it. Pass the username and metadata of someone who is only in the project through a
+ // group, since only direct members' details are loaded here.
+ permissionForActor: (actor: {
+ actorId: string;
+ groupIds: string[];
+ username?: string;
+ metadata?: { key: string; value: string }[];
+ // Only what the given groups give the person, without their direct membership or folder grants, still with
+ // the person's own details filled in.
+ groupsOnly?: boolean;
+ }) => MongoAbility<ProjectPermissionSet, MongoQuery>;
+ // Whether any group role holds a placeholder such as {{identity.username}}, so that a caller only looks up group
+ // members' details when they change the result.
+ groupRulesHavePlaceholders: boolean;
}>;
getOrgPermissionByRoles: (
roles: string[],
diff --git a/backend/src/ee/services/permission/permission-service.ts b/backend/src/ee/services/permission/permission-service.ts
index 2d5b2c1798..33587ef9e4 100644
--- a/backend/src/ee/services/permission/permission-service.ts
+++ b/backend/src/ee/services/permission/permission-service.ts
@@ -321,6 +321,44 @@ const hasActiveProjectAdminRole = (
memberships: Array<{ roles: Array<{ role: string; isTemporary?: boolean; temporaryAccessEndTime?: Date | null }> }>
): boolean => memberships.some((m) => m.roles.some((r) => r.role === ProjectMembershipRole.Admin && isActiveRole(r)));
+type TGetProjectPermissionsResult = Awaited<ReturnType<TPermissionServiceFactory["getProjectPermissions"]>>;
+
+// One person's project permission from all of their memberships, built with the steps getProjectPermission takes:
+// the active roles and privileges of every membership, their folder grants unless one of those roles is Admin, and
+// placeholders filled from their own details. For a caller that holds the project's memberships in bulk.
+export const buildMergedProjectPermissionRules = ({
+ memberships,
+ folderGrants,
+ projectType,
+ identity
+}: {
+ memberships: MembershipWithRoles[];
+ folderGrants?: TProjectFolderScopedPrivilege[];
+ projectType?: string;
+ identity: { id: string; username: string; metadata: { key: string; value: string }[] };
+}) =>
+ interpolatePermissionRules(
+ buildProjectPermissionRules(
+ flattenActiveRolesFromMemberships(memberships, ProjectMembershipRole.Custom),
+ projectType,
+ hasActiveProjectAdminRole(memberships.map(({ roles }) => ({ roles: roles ?? [] }))) ? undefined : folderGrants
+ ),
+ {
+ identity: {
+ id: identity.id,
+ username: identity.username,
+ metadata: escapeHandlebarsMissingDict(
+ objectify(
+ identity.metadata,
+ (item) => item.key,
+ (item) => item.value
+ ),
+ "identity.metadata"
+ )
+ }
+ }
+ );
+
type TPermissionServiceFactoryDep = {
serviceTokenDAL: Pick<TServiceTokenDALFactory, "findById">;
projectDAL: Pick<TProjectDALFactory, "findById">;
@@ -1121,26 +1159,8 @@ export const permissionServiceFactory = ({
conditionsMatcher
});
- // What a member gets through the group: the group's roles with that member's own folder grants on top, the
- // same way their own permission is built, so a grant that narrows a folder narrows the group access too.
- const memberPermissions = new Map<string, MongoAbility<ProjectPermissionSet>>();
- const permissionForMember = (actorId: string) => {
- const folderPrivileges = folderScopedPrivilegesOf(actorId, groupProjectPermission.roles);
- if (!folderPrivileges?.length) return permission;
- let memberPermission = memberPermissions.get(actorId);
- if (!memberPermission) {
- memberPermission = createMongoAbility<ProjectPermissionSet>(
- buildProjectPermissionRules(rolePermissions, undefined, folderPrivileges),
- { conditionsMatcher }
- );
- memberPermissions.set(actorId, memberPermission);
- }
- return memberPermission;
- };
-
return {
permission,
- permissionForMember,
id: groupProjectPermission.groupId,
membershipId: groupProjectPermission.id,
name: groupProjectPermission.username,
@@ -1166,11 +1186,56 @@ export const permissionServiceFactory = ({
])
);
+ const directMembershipByActorId = new Map<
+ string,
+ (typeof rawUserProjectPermissions)[number] | (typeof rawIdentityProjectPermissions)[number]
+ >([
+ ...rawUserProjectPermissions.map((membership) => [membership.userId, membership] as const),
+ ...rawIdentityProjectPermissions.map((membership) => [membership.identityId, membership] as const)
+ ]);
+ const groupMembershipById = new Map(
+ rawGroupProjectPermissions.map((membership) => [membership.groupId, membership])
+ );
+ const mergedAbilities = new Map<string, MongoAbility<ProjectPermissionSet>>();
+ const permissionForActor: TGetProjectPermissionsResult["permissionForActor"] = ({
+ actorId,
+ groupIds,
+ username,
+ metadata,
+ groupsOnly = false
+ }) => {
+ const direct = directMembershipByActorId.get(actorId);
+ const rules = buildMergedProjectPermissionRules({
+ memberships: [
+ ...(direct && !groupsOnly ? [direct] : []),
+ ...groupIds.flatMap((groupId) => groupMembershipById.get(groupId) ?? [])
+ ],
+ folderGrants: groupsOnly ? undefined : folderScopedPrivilegesByActorId.get(actorId)?.filter(isActiveRole),
+ projectType: project?.type,
+ identity: {
+ id: actorId,
+ username: direct?.username ?? username ?? "",
+ metadata: direct?.metadata ?? metadata ?? []
+ }
+ });
+ const rulesKey = JSON.stringify(rules);
+ let permission = mergedAbilities.get(rulesKey);
+ if (!permission) {
+ permission = createMongoAbility<ProjectPermissionSet>(rules, { conditionsMatcher });
+ mergedAbilities.set(rulesKey, permission);
+ }
+ return permission;
+ };
+
return {
userPermissions,
identityPermissions,
groupPermissions,
- folderAccessByActorId
+ folderAccessByActorId,
+ permissionForActor,
+ groupRulesHavePlaceholders: rawGroupProjectPermissions.some((membership) =>
+ JSON.stringify(membership.roles ?? []).includes("{{")
+ )
};
};
diff --git a/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts b/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts
index 5b5b3242ce..05c5cde43f 100644
--- a/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts
+++ b/backend/src/ee/services/secret-read-activity/secret-read-activity-service.ts
@@ -22,6 +22,7 @@ import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
+import { TIdentityMetadataDALFactory } from "@app/services/identity/identity-metadata-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -90,6 +91,7 @@ type TSecretReadActivityServiceFactoryDep = {
secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "find" | "findSecretReferencesByProjectId">;
userDAL: Pick<TUserDALFactory, "find">;
identityDAL: Pick<TIdentityDALFactory, "find">;
+ identityMetadataDAL: Pick<TIdentityMetadataDALFactory, "find">;
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;
identityGroupMembershipDAL: Pick<TIdentityGroupMembershipDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -109,6 +111,7 @@ export const secretReadActivityServiceFactory = ({
secretV2BridgeDAL,
userDAL,
identityDAL,
+ identityMetadataDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
kmsService,
@@ -279,13 +282,48 @@ export const secretReadActivityServiceFactory = ({
};
};
- // Everyone who can hold secrets in the project, and what each secret's readers are judged against. The user and
- // identity lists carry only direct members, so every group member is also listed with what the group gives them,
- // their own folder grants included. Until a project has a full window of reads, it is judged on the reads since
- // tracking began.
+ // The username and metadata of people the project permissions did not load, to fill placeholders in group roles.
+ const $findActorDetails = async (
+ orgId: string,
+ actors: { actorType: TSecretReaderType; actorId: string }[]
+ ): Promise<Map<string, { username: string; metadata: { key: string; value: string }[] }>> => {
+ const idsOf = (actorType: TSecretReaderType) =>
+ actors.filter((actor) => actor.actorType === actorType).map((actor) => actor.actorId);
+ const [userIds, identityIds] = [idsOf(ActorType.USER), idsOf(ActorType.IDENTITY)];
+ const [users, identities, userMetadata, identityMetadata] = await Promise.all([
+ userIds.length ? userDAL.find({ $in: { id: userIds } }) : [],
+ identityIds.length ? identityDAL.find({ $in: { id: identityIds } }) : [],
+ userIds.length ? identityMetadataDAL.find({ orgId, $in: { userId: userIds } }) : [],
+ identityIds.length ? identityMetadataDAL.find({ orgId, $in: { identityId: identityIds } }) : []
+ ]);
+ const metadataByUserId = groupBy(userMetadata, (row) => row.userId ?? "");
+ const metadataByIdentityId = groupBy(identityMetadata, (row) => row.identityId ?? "");
+ const toPairs = (rows: { key: string; value: string }[] = []) => rows.map(({ key, value }) => ({ key, value }));
+ return new Map([
+ ...users.map(
+ (user) => [user.id, { username: user.username, metadata: toPairs(metadataByUserId[user.id]) }] as const
+ ),
+ ...identities.map(
+ (identity) =>
+ [identity.id, { username: identity.name, metadata: toPairs(metadataByIdentityId[identity.id]) }] as const
+ )
+ ]);
+ };
+
+ // Everyone who can hold secrets in the project, and what each secret's readers are judged against. Each person is
+ // checked with one permission merged across their direct membership and every group they are in, the way
+ // getProjectPermission builds it, so a deny in one role holds against an allow in another. Until a project has a
+ // full window of reads, it is judged on the reads since tracking began.
const $loadProjectAccess = async (projectId: string, orgId: string, windowStart: Date) => {
const [
- { userPermissions, identityPermissions, groupPermissions, folderAccessByActorId },
+ {
+ userPermissions,
+ identityPermissions,
+ groupPermissions,
+ folderAccessByActorId,
+ permissionForActor,
+ groupRulesHavePlaceholders
+ },
sourceDates,
adminActorIds,
{ trackingStartedAt }
@@ -319,19 +357,30 @@ export const secretReadActivityServiceFactory = ({
const group = groupById.get(groupId);
return group ? [{ group, actorType: actorType as TSecretReaderType, actorId, joinedAt }] : [];
});
- const readers: TProjectReader[] = [
- ...userPermissions.map(({ id, permission }) => ({ actorType: ActorType.USER as const, actorId: id, permission })),
- ...identityPermissions.map(({ id, permission }) => ({
- actorType: ActorType.IDENTITY as const,
- actorId: id,
- permission
- })),
- ...groupMembers.map(({ group, actorType, actorId }) => ({
- actorType,
- actorId,
- permission: group.permissionForMember(actorId)
- }))
- ];
+ const people = new Map<string, { actorType: TSecretReaderType; actorId: string; groupIds: string[] }>();
+ const personOf = (actorType: TSecretReaderType, actorId: string) => {
+ const key = toActorKey(actorType, actorId);
+ const person = people.get(key) ?? { actorType, actorId, groupIds: [] };
+ people.set(key, person);
+ return person;
+ };
+ userPermissions.forEach(({ id }) => personOf(ActorType.USER, id));
+ identityPermissions.forEach(({ id }) => personOf(ActorType.IDENTITY, id));
+ groupMembers.forEach(({ group, actorType, actorId }) => personOf(actorType, actorId).groupIds.push(group.id));
+
+ // A placeholder such as {{identity.username}} is filled from the person's own details. Direct members' details
+ // come with the permissions; those of people only in through a group are looked up, and only when a group role
+ // holds a placeholder.
+ const directMemberIds = new Set([...userPermissions, ...identityPermissions].map(({ id }) => id));
+ const groupOnly = [...people.values()].filter((person) => !directMemberIds.has(person.actorId));
+ const detailsByActorId = groupRulesHavePlaceholders
+ ? await $findActorDetails(orgId, groupOnly)
+ : new Map<string, { username: string; metadata: { key: string; value: string }[] }>();
+ const readers: TProjectReader[] = [...people.values()].map(({ actorType, actorId, groupIds: memberOf }) => ({
+ actorType,
+ actorId,
+ permission: permissionForActor({ actorId, groupIds: memberOf, ...detailsByActorId.get(actorId) })
+ }));
// Every source of each actor's access with its date: their own roles and project-wide privileges, each group
// they are in (dated from joining it or from the group's own role change, whichever is later), and their folder
@@ -353,12 +402,14 @@ export const secretReadActivityServiceFactory = ({
}))
]);
});
+ // A group on its own, with the member's details filled into its placeholders.
groupMembers.forEach(({ group, actorId, joinedAt }) => {
const groupChangedAt = sourceDates.groupDates.get(group.id);
addSources(actorId, [
{
date: groupChangedAt && groupChangedAt > joinedAt ? groupChangedAt : joinedAt,
- permission: () => group.permission
+ permission: () =>
+ permissionForActor({ actorId, groupIds: [group.id], groupsOnly: true, ...detailsByActorId.get(actorId) })
}
]);
});
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index a23a689914..93c504d8d7 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3536,6 +3536,7 @@ export const registerRoutes = async (
secretV2BridgeDAL,
userDAL,
identityDAL,
+ identityMetadataDAL,
userGroupMembershipDAL,
identityGroupMembershipDAL,
kmsService,