Skip to content

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

check for conditional permissions

Thiago Araujo da Silva4e8f5cd38c49
diff --git a/backend/src/services/identity/identity-fns.test.ts b/backend/src/services/identity/identity-fns.test.ts
new file mode 100644
index 0000000000..14ad54fb31
--- /dev/null
+++ b/backend/src/services/identity/identity-fns.test.ts
@@ -0,0 +1,126 @@
+import { createMongoAbility, MongoAbility, RawRuleOf } from "@casl/ability";
+import { describe, expect, test } from "vitest";
+
+import {
+ ProjectPermissionIdentityActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { conditionsMatcher } from "@app/lib/casl";
+
+import { filterIdentitiesByProjectPermission, TProjectPermissionAbility } from "./identity-fns";
+import { SearchIdentitiesScope } from "./identity-types";
+
+type Rule = RawRuleOf<MongoAbility<ProjectPermissionSet>>;
+
+const buildAbility = (rules: Rule[]): TProjectPermissionAbility =>
+ createMongoAbility<ProjectPermissionSet>(rules, { conditionsMatcher });
+
+const row = (overrides: {
+ identityId: string;
+ scope: SearchIdentitiesScope;
+ projectId?: string | null;
+ name?: string;
+}) => ({ name: "identity", ...overrides });
+
+describe("filterIdentitiesByProjectPermission", () => {
+ test("org-scope rows pass through unchanged", () => {
+ const rows = [
+ row({ identityId: "id-1", scope: SearchIdentitiesScope.OrganizationScope, projectId: null }),
+ row({ identityId: "id-2", scope: SearchIdentitiesScope.OrganizationScope })
+ ];
+ const result = filterIdentitiesByProjectPermission(rows, new Map(), new Set());
+ expect(result).toEqual(rows);
+ });
+
+ test("project-scope rows in unconditional projects pass through without consulting CASL", () => {
+ const unconditional = buildAbility([
+ // A throwing matcher would fail this test if the helper invoked .can() — we rely on the
+ // empty conditionalProjectIds set to short-circuit before any CASL evaluation.
+ { action: [ProjectPermissionIdentityActions.Read], subject: ProjectPermissionSub.Identity }
+ ]);
+ const rows = [
+ row({ identityId: "id-1", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-A" }),
+ row({ identityId: "id-2", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-A" })
+ ];
+ const result = filterIdentitiesByProjectPermission(rows, new Map([["proj-A", unconditional]]), new Set());
+ expect(result).toEqual(rows);
+ });
+
+ test("project-scope rows in conditional projects are filtered by identityId", () => {
+ const conditional = buildAbility([
+ {
+ action: [ProjectPermissionIdentityActions.Read],
+ subject: ProjectPermissionSub.Identity,
+ conditions: { identityId: { $in: ["id-1", "id-3"] } }
+ }
+ ]);
+ const rows = [
+ row({ identityId: "id-1", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-A" }),
+ row({ identityId: "id-2", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-A" }),
+ row({ identityId: "id-3", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-A" })
+ ];
+ const result = filterIdentitiesByProjectPermission(rows, new Map([["proj-A", conditional]]), new Set(["proj-A"]));
+ expect(result.map((r) => r.identityId)).toEqual(["id-1", "id-3"]);
+ });
+
+ test("rows from a project with no permission entry are dropped", () => {
+ const rows = [row({ identityId: "id-1", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-missing" })];
+ const result = filterIdentitiesByProjectPermission(rows, new Map(), new Set(["proj-missing"]));
+ expect(result).toEqual([]);
+ });
+
+ test("project-scope rows without a projectId are dropped", () => {
+ const rows = [row({ identityId: "id-1", scope: SearchIdentitiesScope.ProjectScope, projectId: null })];
+ const result = filterIdentitiesByProjectPermission(rows, new Map(), new Set());
+ expect(result).toEqual([]);
+ });
+
+ test("mixed scopes: org passes, unconditional project passes, conditional project filters", () => {
+ const unconditional = buildAbility([
+ { action: [ProjectPermissionIdentityActions.Read], subject: ProjectPermissionSub.Identity }
+ ]);
+ const conditional = buildAbility([
+ {
+ action: [ProjectPermissionIdentityActions.Read],
+ subject: ProjectPermissionSub.Identity,
+ conditions: { identityId: "id-3" }
+ }
+ ]);
+ const rows = [
+ row({ identityId: "id-1", scope: SearchIdentitiesScope.OrganizationScope, projectId: null }),
+ row({ identityId: "id-2", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-open" }),
+ row({ identityId: "id-3", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-locked" }),
+ row({ identityId: "id-4", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-locked" })
+ ];
+ const result = filterIdentitiesByProjectPermission(
+ rows,
+ new Map([
+ ["proj-open", unconditional],
+ ["proj-locked", conditional]
+ ]),
+ new Set(["proj-locked"])
+ );
+ expect(result.map((r) => r.identityId)).toEqual(["id-1", "id-2", "id-3"]);
+ });
+
+ test("inverted (forbid) rule with conditions denies matching rows even when project is unconditional in the set", () => {
+ // Realistic config: a base allow-all Read(Identity) plus a forbid for a specific identityId.
+ // The service flags this project as conditional, so the per-row check runs and respects the forbid.
+ const withForbid = buildAbility([
+ { action: [ProjectPermissionIdentityActions.Read], subject: ProjectPermissionSub.Identity },
+ {
+ inverted: true,
+ action: [ProjectPermissionIdentityActions.Read],
+ subject: ProjectPermissionSub.Identity,
+ conditions: { identityId: "id-blocked" }
+ }
+ ]);
+ const rows = [
+ row({ identityId: "id-allowed", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-X" }),
+ row({ identityId: "id-blocked", scope: SearchIdentitiesScope.ProjectScope, projectId: "proj-X" })
+ ];
+ const result = filterIdentitiesByProjectPermission(rows, new Map([["proj-X", withForbid]]), new Set(["proj-X"]));
+ expect(result.map((r) => r.identityId)).toEqual(["id-allowed"]);
+ });
+});
diff --git a/backend/src/services/identity/identity-fns.ts b/backend/src/services/identity/identity-fns.ts
index 189948d01c..42d1527f71 100644
--- a/backend/src/services/identity/identity-fns.ts
+++ b/backend/src/services/identity/identity-fns.ts
@@ -1,4 +1,38 @@
+import { MongoAbility, subject } from "@casl/ability";
+
import { IdentityAuthMethod } from "@app/db/schemas";
+import {
+ ProjectPermissionIdentityActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+
+import { SearchIdentitiesScope } from "./identity-types";
+
+export type TProjectPermissionAbility = MongoAbility<ProjectPermissionSet>;
+
+// Drops project-scope rows whose `identityId` fails the per-row CASL check. Org-scope rows are
+// unconditional (org-level Identity rules don't accept conditions) and pass through. Rows in
+// projects whose Read(Identity) rules carry no conditions also pass through without a CASL call:
+// the broader `can(Read, Identity)` check during scope resolution already authorized them.
+export const filterIdentitiesByProjectPermission = <
+ TRow extends { identityId: string; scope: SearchIdentitiesScope; projectId?: string | null }
+>(
+ rows: TRow[],
+ projectPermissions: Map<string, TProjectPermissionAbility>,
+ conditionalProjectIds: Set<string>
+): TRow[] =>
+ rows.filter((row) => {
+ if (row.scope !== SearchIdentitiesScope.ProjectScope) return true;
+ if (!row.projectId) return false;
+ if (!conditionalProjectIds.has(row.projectId)) return true;
+ const projectPermission = projectPermissions.get(row.projectId);
+ if (!projectPermission) return false;
+ return projectPermission.can(
+ ProjectPermissionIdentityActions.Read,
+ subject(ProjectPermissionSub.Identity, { identityId: row.identityId })
+ );
+ });
export const buildAuthMethods = ({
uaId,
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index c8020c75e0..bf7296f0ed 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -36,6 +36,7 @@ import { TMembershipIdentityDALFactory } from "../membership-identity/membership
import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityDALFactory } from "./identity-dal";
+import { filterIdentitiesByProjectPermission, TProjectPermissionAbility } from "./identity-fns";
import { TIdentityMetadataDALFactory } from "./identity-metadata-dal";
import { TIdentityOrgDALFactory } from "./identity-org-dal";
import {
@@ -515,7 +516,12 @@ export const identityServiceFactory = ({
actorAuthMethod: TSearchIdentitiesV2DTO["actorAuthMethod"];
actorOrgId: string;
scope: SearchIdentitiesScope[];
- }): Promise<{ uniqueScope: Set<SearchIdentitiesScope>; accessibleProjectIds: string[] }> => {
+ }): Promise<{
+ uniqueScope: Set<SearchIdentitiesScope>;
+ accessibleProjectIds: string[];
+ projectPermissions: Map<string, TProjectPermissionAbility>;
+ conditionalProjectIds: Set<string>;
+ }> => {
const uniqueScope = new Set(scope);
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
@@ -530,44 +536,60 @@ export const identityServiceFactory = ({
uniqueScope.delete(SearchIdentitiesScope.OrganizationScope);
}
- let accessibleProjectIds: string[] = [];
+ const accessibleProjectIds: string[] = [];
+ const projectPermissions = new Map<string, TProjectPermissionAbility>();
+ const conditionalProjectIds = new Set<string>();
if (uniqueScope.has(SearchIdentitiesScope.ProjectScope)) {
const canAccessAllProjects = orgPermission.can(
OrgPermissionAdminConsoleAction.AccessAllProjects,
OrgPermissionSubjects.AdminConsole
);
- if (canAccessAllProjects) {
- accessibleProjectIds = await projectDAL.findOrgProjectIds(actorOrgId);
- } else {
- const actorProjectIds = await projectDAL.findActorAccessibleProjectIds(actorId, actor, actorOrgId);
- const projectAccessChecks = await Promise.all(
- actorProjectIds.map(async (projectId) => {
- try {
- const { permission: projectPermission } = await permissionService.getProjectPermission({
- actor,
- actorId,
- actionProjectType: ActionProjectType.Any,
- actorAuthMethod,
- projectId,
- actorOrgId
- });
- return projectPermission.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity)
- ? projectId
- : null;
- } catch {
- return null;
- }
- })
- );
+ const candidateProjectIds = canAccessAllProjects
+ ? await projectDAL.findOrgProjectIds(actorOrgId)
+ : await projectDAL.findActorAccessibleProjectIds(actorId, actor, actorOrgId);
+
+ const projectAccessChecks = await Promise.all(
+ candidateProjectIds.map(async (projectId) => {
+ try {
+ const { permission: projectPermission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ actionProjectType: ActionProjectType.Any,
+ actorAuthMethod,
+ projectId,
+ actorOrgId
+ });
+ // Broad `can(Read, Identity)` returns true for conditional rules too. We keep the
+ // project here and use the per-row check below to honor `identityId` conditions.
+ return projectPermission.can(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity)
+ ? { projectId, permission: projectPermission }
+ : null;
+ } catch {
+ return null;
+ }
+ })
+ );
- accessibleProjectIds = projectAccessChecks.filter((id): id is string => Boolean(id));
+ for (const entry of projectAccessChecks) {
+ if (entry) {
+ accessibleProjectIds.push(entry.projectId);
+ projectPermissions.set(entry.projectId, entry.permission);
+ // Tracking which projects carry conditional Read(Identity) rules lets the row filter
+ // skip CASL.can() for projects whose access is already unconditional — the broad
+ // can(Read, Identity) check above is authoritative for them.
+ const rules = entry.permission.rulesFor(ProjectPermissionIdentityActions.Read, ProjectPermissionSub.Identity);
+ if (rules.some((rule) => rule.conditions)) {
+ conditionalProjectIds.add(entry.projectId);
+ }
+ }
}
+
if (accessibleProjectIds.length === 0) {
uniqueScope.delete(SearchIdentitiesScope.ProjectScope);
}
}
- return { uniqueScope, accessibleProjectIds };
+ return { uniqueScope, accessibleProjectIds, projectPermissions, conditionalProjectIds };
};
const searchOrgIdentitiesV2 = async ({
@@ -582,22 +604,39 @@ export const identityServiceFactory = ({
scope,
searchFilter = {}
}: TSearchIdentitiesV2DTO) => {
- const { uniqueScope, accessibleProjectIds } = await resolveIdentitySearchScope({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- scope
- });
+ const { uniqueScope, accessibleProjectIds, projectPermissions, conditionalProjectIds } =
+ await resolveIdentitySearchScope({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ scope
+ });
if (!uniqueScope.size) {
return { identityMemberships: [], totalCount: 0 };
}
- const { totalCount, docs } = await identityOrgMembershipDAL.searchIdentitiesV2({
+ if (conditionalProjectIds.size === 0) {
+ const { totalCount, docs } = await identityOrgMembershipDAL.searchIdentitiesV2({
+ orgId: actorOrgId,
+ limit,
+ offset,
+ orderBy,
+ orderDirection,
+ searchFilter,
+ scope: Array.from(uniqueScope),
+ accessibleProjectIds
+ });
+
+ return { identityMemberships: docs, totalCount };
+ }
+
+ // Conditional Read rules on Identity exist for at least one accessible project. SQL pagination
+ // would over-return rows the caller can't see, so fetch the full ordered set and filter by
+ // per-row CASL before paginating in memory. Mirrors the tier-2 pattern in pam-resource-service.
+ const { docs } = await identityOrgMembershipDAL.searchIdentitiesV2({
orgId: actorOrgId,
- limit,
- offset,
orderBy,
orderDirection,
searchFilter,
@@ -605,7 +644,13 @@ export const identityServiceFactory = ({
accessibleProjectIds
});
- return { identityMemberships: docs, totalCount };
+ const filtered = filterIdentitiesByProjectPermission(docs, projectPermissions, conditionalProjectIds);
+ const pageOffset = offset ?? 0;
+ const pageLimit = limit ?? filtered.length;
+ return {
+ identityMemberships: filtered.slice(pageOffset, pageOffset + pageLimit),
+ totalCount: filtered.length
+ };
};
const countOrgIdentitiesV2 = async ({
@@ -619,13 +664,14 @@ export const identityServiceFactory = ({
const requestedOrg = scope.includes(SearchIdentitiesScope.OrganizationScope);
const requestedProject = scope.includes(SearchIdentitiesScope.ProjectScope);
- const { uniqueScope, accessibleProjectIds } = await resolveIdentitySearchScope({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- scope
- });
+ const { uniqueScope, accessibleProjectIds, projectPermissions, conditionalProjectIds } =
+ await resolveIdentitySearchScope({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ scope
+ });
// Build the response shape from the *requested* scopes so callers always get a number
// for every scope they asked about (zero when permissions/projects filter the scope out).
@@ -637,15 +683,41 @@ export const identityServiceFactory = ({
return counts;
}
- const dalCounts = await identityOrgMembershipDAL.countIdentitiesV2({
- orgId: actorOrgId,
- scope: Array.from(uniqueScope),
- accessibleProjectIds,
- searchFilter
- });
+ if (conditionalProjectIds.size === 0) {
+ const dalCounts = await identityOrgMembershipDAL.countIdentitiesV2({
+ orgId: actorOrgId,
+ scope: Array.from(uniqueScope),
+ accessibleProjectIds,
+ searchFilter
+ });
+
+ if (requestedOrg && dalCounts.organization !== undefined) counts.organization = dalCounts.organization;
+ if (requestedProject && dalCounts.project !== undefined) counts.project = dalCounts.project;
+
+ return counts;
+ }
+
+ // Project-scope count must respect identityId conditions, so list the rows and count survivors.
+ // Org-scope rows have no per-identity conditions, so the SQL count is still correct.
+ if (requestedOrg && uniqueScope.has(SearchIdentitiesScope.OrganizationScope)) {
+ const orgOnly = await identityOrgMembershipDAL.countIdentitiesV2({
+ orgId: actorOrgId,
+ scope: [SearchIdentitiesScope.OrganizationScope],
+ accessibleProjectIds: [],
+ searchFilter
+ });
+ counts.organization = orgOnly.organization ?? 0;
+ }
- if (requestedOrg && dalCounts.organization !== undefined) counts.organization = dalCounts.organization;
- if (requestedProject && dalCounts.project !== undefined) counts.project = dalCounts.project;
+ if (requestedProject && uniqueScope.has(SearchIdentitiesScope.ProjectScope)) {
+ const { docs } = await identityOrgMembershipDAL.searchIdentitiesV2({
+ orgId: actorOrgId,
+ scope: [SearchIdentitiesScope.ProjectScope],
+ accessibleProjectIds,
+ searchFilter
+ });
+ counts.project = filterIdentitiesByProjectPermission(docs, projectPermissions, conditionalProjectIds).length;
+ }
return counts;
};