Skip to content

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

fix module versioning with our current approach

Thiago Araujo da Silva3568c743a4eb
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 1594f70498..bb4f40b15d 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -358,6 +358,7 @@ import { identityUaClientSecretDALFactory } from "@app/services/identity-ua/iden
import { identityUaDALFactory } from "@app/services/identity-ua/identity-ua-dal";
import { identityUaServiceFactory } from "@app/services/identity-ua/identity-ua-service";
import { identityV2DALFactory } from "@app/services/identity-v2/identity-dal";
+import { identityMembershipV2DALFactory } from "@app/services/identity-v2/identity-membership-dal";
import { identityV2ServiceFactory } from "@app/services/identity-v2/identity-service";
import { integrationDALFactory } from "@app/services/integration/integration-dal";
import { integrationServiceFactory } from "@app/services/integration/integration-service";
@@ -589,6 +590,7 @@ export const registerRoutes = async (
const identityDAL = identityDALFactory(db);
const identityV2DAL = identityV2DALFactory(db);
+ const identityMembershipV2DAL = identityMembershipV2DALFactory(db);
const identityMetadataDAL = identityMetadataDALFactory(db);
const identityAccessTokenDAL = identityAccessTokenDALFactory(db);
const identityAccessTokenRevocationDAL = identityAccessTokenRevocationDALFactory(db);
@@ -2000,8 +2002,7 @@ export const registerRoutes = async (
keyStore,
orgDAL,
membershipIdentityDAL,
- membershipRoleDAL,
- projectDAL
+ membershipRoleDAL
});
const identityAccessTokenService = identityAccessTokenServiceFactory({
@@ -2019,8 +2020,10 @@ export const registerRoutes = async (
licenseService,
permissionService,
identityDAL: identityV2DAL,
+ identityMembershipV2DAL,
identityAccessTokenService,
- keyStore
+ keyStore,
+ projectDAL
});
const identityProjectService = identityProjectServiceFactory({
diff --git a/backend/src/server/routes/v2/identity-router.ts b/backend/src/server/routes/v2/identity-router.ts
index e4b2a6f658..ba24ce88d6 100644
--- a/backend/src/server/routes/v2/identity-router.ts
+++ b/backend/src/server/routes/v2/identity-router.ts
@@ -8,7 +8,7 @@ import { CharacterType, zodValidateCharacters } from "@app/lib/validator/validat
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
-import { OrgIdentitySearchOrderBy, SearchIdentitiesScope } from "@app/services/identity/identity-types";
+import { OrgIdentitySearchOrderBy, SearchIdentitiesScope } from "@app/services/identity-v2/identity-types";
const searchResourceZodValidate = zodValidateCharacters([
CharacterType.AlphaNumeric,
@@ -137,7 +137,7 @@ export const registerIdentityRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const { identityMemberships, totalCount } = await server.services.identityV1.searchOrgIdentitiesV2({
+ const { identityMemberships, totalCount } = await server.services.identityV2.searchOrgIdentities({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -223,7 +223,7 @@ export const registerIdentityRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const counts = await server.services.identityV1.countOrgIdentitiesV2({
+ const counts = await server.services.identityV2.countOrgIdentities({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
diff --git a/backend/src/services/identity/identity-fns.test.ts b/backend/src/services/identity-v2/identity-fns.test.ts
similarity index 100%
rename from backend/src/services/identity/identity-fns.test.ts
rename to backend/src/services/identity-v2/identity-fns.test.ts
diff --git a/backend/src/services/identity-v2/identity-fns.ts b/backend/src/services/identity-v2/identity-fns.ts
index a89762ccab..5b16d5cbbd 100644
--- a/backend/src/services/identity-v2/identity-fns.ts
+++ b/backend/src/services/identity-v2/identity-fns.ts
@@ -1,24 +1,34 @@
-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { MongoAbility, subject } from "@casl/ability";
-export const getIdentityActiveLockoutAuthMethods = async (
- identityId: string,
- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">
-) => {
- const activeLockouts = await keyStore.getKeysByPattern(KeyStorePrefixes.IdentityLockoutStatePattern(identityId));
+import {
+ ProjectPermissionIdentityActions,
+ ProjectPermissionSet,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
- const activeLockoutAuthMethods = new Set<string>();
- for await (const key of activeLockouts) {
- const parts = key.split(":");
- if (parts.length > 3) {
- const lockoutRaw = await keyStore.getItem(key);
- if (lockoutRaw) {
- const lockout = JSON.parse(lockoutRaw) as { lockedOut: boolean };
- if (lockout.lockedOut) {
- activeLockoutAuthMethods.add(parts[3]);
- }
- }
- }
- }
+import { SearchIdentitiesScope } from "./identity-types";
- return Array.from(activeLockoutAuthMethods);
-};
+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 })
+ );
+ });
diff --git a/backend/src/services/identity-v2/identity-membership-dal.ts b/backend/src/services/identity-v2/identity-membership-dal.ts
new file mode 100644
index 0000000000..8bdbeac53a
--- /dev/null
+++ b/backend/src/services/identity-v2/identity-membership-dal.ts
@@ -0,0 +1,484 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { AccessScope, TableName } from "@app/db/schemas";
+import { BadRequestError, DatabaseError } from "@app/lib/errors";
+import { sqlNestRelationships } from "@app/lib/knex";
+import { buildKnexFilterForSearchResource } from "@app/lib/search-resource/db";
+import { OrderByDirection } from "@app/lib/types";
+
+import { buildAuthMethods } from "../identity/identity-fns";
+import {
+ accessScopeToSearchIdentitiesScope,
+ OrgIdentitySearchOrderBy,
+ SearchIdentitiesScope,
+ TCountIdentitiesV2DAL,
+ TSearchIdentitiesV2DAL
+} from "./identity-types";
+
+export type TIdentityMembershipV2DALFactory = ReturnType<typeof identityMembershipV2DALFactory>;
+
+export const identityMembershipV2DALFactory = (db: TDbClient) => {
+ const searchIdentitiesV2 = async (
+ {
+ limit,
+ offset = 0,
+ orderBy = OrgIdentitySearchOrderBy.Name,
+ orderDirection = OrderByDirection.ASC,
+ searchFilter,
+ orgId,
+ scope,
+ accessibleProjectIds
+ }: TSearchIdentitiesV2DAL,
+ tx?: Knex
+ ) => {
+ try {
+ const includeOrgScope = scope.includes(SearchIdentitiesScope.OrganizationScope);
+ const includeProjectScope = scope.includes(SearchIdentitiesScope.ProjectScope);
+
+ const applyScopeFilter = (qb: Knex.QueryBuilder) => {
+ void qb.whereNotNull(`${TableName.Membership}.actorIdentityId`);
+
+ // Project-owned identities (Identity.projectId IS NOT NULL) always carry a NoAccess
+ // org-level Membership row as an implementation detail of their creation flow
+ // (see identity-v2/identity-service.ts createIdentity). Excluding them here keeps
+ // the org-scope listing limited to true org-level identities, matching V1 behavior
+ // and preventing duplicate rows in the combined org+project view.
+ const orgScopeBranch = (sub: Knex.QueryBuilder) => {
+ void sub
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ .whereNull(`${TableName.Identity}.projectId`);
+ };
+
+ const projectScopeBranch = (sub: Knex.QueryBuilder) => {
+ void sub
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ .whereIn(`${TableName.Membership}.scopeProjectId`, accessibleProjectIds);
+ };
+
+ if (includeOrgScope && includeProjectScope) {
+ void qb.where((nested) => {
+ void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));
+ });
+ } else if (includeOrgScope) {
+ orgScopeBranch(qb);
+ } else if (includeProjectScope) {
+ projectScopeBranch(qb);
+ }
+ };
+
+ // Identity-auth login services update the lastLogin* columns on exactly one Membership row
+ // keyed on the identity's home org (scope=Organization, scopeOrgId=Identity.orgId, projectId
+ // omitted). The project Membership row created at `createMembershipIdentity` time therefore
+ // never receives a login timestamp. To avoid surfacing "Never" in the project / all tabs for
+ // an identity that authenticates regularly, fall back to the matching org Membership via a
+ // correlated subquery. The bound scopeOrgId must reference Identity.orgId (not the caller's
+ // orgId) so the fallback also works for a root-org identity linked into a sub-org.
+ const lastLoginFallbackRaw = (column: "lastLoginTime" | "lastLoginAuthMethod", outputAlias: string) =>
+ db.raw(
+ `COALESCE(??.??, (SELECT om.?? FROM ?? AS om WHERE om.?? = ??.?? AND om.?? = ? AND om.?? = ??.??)) as ??`,
+ [
+ TableName.Membership,
+ column,
+ column,
+ TableName.Membership,
+ "actorIdentityId",
+ TableName.Membership,
+ "actorIdentityId",
+ "scope",
+ AccessScope.Organization,
+ "scopeOrgId",
+ TableName.Identity,
+ "orgId",
+ outputAlias
+ ]
+ );
+
+ const searchedMemberships = (tx || db.replicaNode())(TableName.Membership)
+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
+ .where(applyScopeFilter)
+ .groupBy(
+ `${TableName.Membership}.id`,
+ `${TableName.Identity}.name`,
+ `${TableName.Identity}.orgId`,
+ `${TableName.Membership}.lastLoginTime`
+ )
+ .select(`${TableName.Membership}.id`)
+ .select(db.ref("name").withSchema(TableName.Identity).as("identityName"))
+ .select(lastLoginFallbackRaw("lastLoginTime", "lastLoginSort"))
+ .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(
+ db.raw(`MIN(COALESCE(??, ??)) as "roleSort"`, [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`])
+ )
+ .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(
+ db.raw(`COUNT(*) OVER() as total_count`)
+ );
+
+ if (searchFilter) {
+ buildKnexFilterForSearchResource(searchedMemberships, searchFilter, (attr) => {
+ switch (attr) {
+ case "role":
+ return [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`];
+ case "name":
+ return `${TableName.Identity}.name`;
+ default:
+ throw new BadRequestError({ message: `Invalid ${String(attr)} provided` });
+ }
+ });
+ }
+
+ if (orderBy === OrgIdentitySearchOrderBy.Role) {
+ void searchedMemberships.orderBy("roleSort", orderDirection, "last");
+ } else if (orderBy === OrgIdentitySearchOrderBy.LastLogin) {
+ // Never-used identities (lastLoginTime IS NULL) are always pushed to the bottom
+ // regardless of sort direction so the visible page is dominated by real activity.
+ void searchedMemberships.orderBy("lastLoginSort", orderDirection, "last");
+ } else {
+ void searchedMemberships.orderBy("identityName", orderDirection);
+ }
+ // Secondary sort by membership id keeps pagination deterministic when the primary
+ // sort key ties (duplicate names, identical aggregated role).
+ void searchedMemberships.orderBy(`${TableName.Membership}.id`, "asc");
+
+ if (limit) {
+ void searchedMemberships.offset(offset).limit(limit);
+ }
+
+ const searchedMembershipsSubquery = searchedMemberships.as("searchedMemberships");
+ type TSubquery = Awaited<typeof searchedMemberships>;
+
+ const query = (tx || db.replicaNode())(TableName.Membership)
+ .join<TSubquery>(searchedMembershipsSubquery, `${TableName.Membership}.id`, "searchedMemberships.id")
+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
+ .leftJoin(TableName.Project, `${TableName.Project}.id`, `${TableName.Membership}.scopeProjectId`)
+ .leftJoin(
+ TableName.IdentityUniversalAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityUniversalAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityGcpAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityGcpAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityAliCloudAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityAliCloudAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityAwsAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityAwsAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityKubernetesAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityKubernetesAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityOciAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityOciAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityOidcAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityOidcAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityAzureAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityAzureAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityTokenAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityTokenAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityJwtAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityJwtAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityLdapAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityLdapAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentityTlsCertAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentityTlsCertAuth}.identityId`
+ )
+ .leftJoin(
+ TableName.IdentitySpiffeAuth,
+ `${TableName.Membership}.actorIdentityId`,
+ `${TableName.IdentitySpiffeAuth}.identityId`
+ )
+ .select(
+ db.ref("id").withSchema(TableName.Membership),
+ db.ref("scope").withSchema(TableName.Membership).as("membershipScope"),
+ db.ref("scopeOrgId").withSchema(TableName.Membership).as("orgId"),
+ db.ref("scopeProjectId").withSchema(TableName.Membership).as("scopeProjectId"),
+ db.ref("total_count").withSchema("searchedMemberships"),
+ db.ref("createdAt").withSchema(TableName.Membership),
+ db.ref("updatedAt").withSchema(TableName.Membership),
+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),
+ db.ref("name").withSchema(TableName.Identity).as("identityName"),
+ db.ref("hasDeleteProtection").withSchema(TableName.Identity),
+ db.ref("orgId").withSchema(TableName.Identity).as("identityOrgId"),
+
+ db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),
+ db.ref("role").withSchema(TableName.MembershipRole),
+ db.ref("customRoleId").withSchema(TableName.MembershipRole).as("roleId"),
+ db.ref("isTemporary").withSchema(TableName.MembershipRole),
+ db.ref("temporaryMode").withSchema(TableName.MembershipRole),
+ db.ref("temporaryRange").withSchema(TableName.MembershipRole),
+ db.ref("temporaryAccessStartTime").withSchema(TableName.MembershipRole),
+ db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),
+
+ db.ref("id").as("projectIdRef").withSchema(TableName.Project),
+ db.ref("name").as("projectName").withSchema(TableName.Project),
+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),
+ db.ref("type").as("projectType").withSchema(TableName.Project),
+
+ db.ref("id").as("uaId").withSchema(TableName.IdentityUniversalAuth),
+ db.ref("id").as("gcpId").withSchema(TableName.IdentityGcpAuth),
+ db.ref("id").as("alicloudId").withSchema(TableName.IdentityAliCloudAuth),
+ db.ref("id").as("awsId").withSchema(TableName.IdentityAwsAuth),
+ db.ref("id").as("kubernetesId").withSchema(TableName.IdentityKubernetesAuth),
+ db.ref("id").as("ociId").withSchema(TableName.IdentityOciAuth),
+ db.ref("id").as("oidcId").withSchema(TableName.IdentityOidcAuth),
+ db.ref("id").as("azureId").withSchema(TableName.IdentityAzureAuth),
+ db.ref("id").as("tokenId").withSchema(TableName.IdentityTokenAuth),
+ db.ref("id").as("jwtId").withSchema(TableName.IdentityJwtAuth),
+ db.ref("id").as("ldapId").withSchema(TableName.IdentityLdapAuth),
+ db.ref("id").as("tlsCertId").withSchema(TableName.IdentityTlsCertAuth),
+ db.ref("id").as("spiffeId").withSchema(TableName.IdentitySpiffeAuth)
+ )
+ .select(db.ref("name").as("crName").withSchema(TableName.Role))
+ .select(db.ref("slug").as("crSlug").withSchema(TableName.Role))
+ .select(db.ref("description").as("crDescription").withSchema(TableName.Role))
+ .select(
+ lastLoginFallbackRaw("lastLoginTime", "lastLoginTime"),
+ lastLoginFallbackRaw("lastLoginAuthMethod", "lastLoginAuthMethod")
+ );
+
+ if (orderBy === OrgIdentitySearchOrderBy.Role) {
+ void query.orderBy("searchedMemberships.roleSort", orderDirection, "last");
+ } else if (orderBy === OrgIdentitySearchOrderBy.LastLogin) {
+ void query.orderBy("searchedMemberships.lastLoginSort", orderDirection, "last");
+ } else {
+ void query.orderBy("searchedMemberships.identityName", orderDirection);
+ }
+ void query.orderBy("searchedMemberships.id", "asc");
+
+ // lastLoginTime / lastLoginAuthMethod are produced by raw COALESCE expressions
+ // (see lastLoginFallbackRaw), so Knex's inferred record type doesn't include them.
+ // They are present at runtime — add them to the type explicitly so the nest-mapper
+ // destructuring below compiles.
+ const docs = (await query) as (typeof query extends PromiseLike<infer R>
+ ? R extends (infer Row)[]
+ ? Row & { lastLoginTime: Date | null; lastLoginAuthMethod: string | null }
+ : never
+ : never)[];
+
+ const formattedDocs = sqlNestRelationships({
+ data: docs,
+ key: "id",
+ parentMapper: ({
+ identityId,
+ identityOrgId,
+ identityName,
+ hasDeleteProtection,
+ total_count,
+ id,
+ membershipScope,
+ orgId: membershipOrgId,
+ scopeProjectId,
+ projectIdRef,
+ projectName,
+ projectSlug,
+ projectType,
+ uaId,
+ alicloudId,
+ awsId,
+ gcpId,
+ jwtId,
+ kubernetesId,
+ ociId,
+ oidcId,
+ azureId,
+ tokenId,
+ ldapId,
+ tlsCertId,
+ spiffeId,
+ createdAt,
+ updatedAt,
+ lastLoginTime,
+ lastLoginAuthMethod
+ }) => ({
+ id,
+ identityId: identityId as string,
+ scope: accessScopeToSearchIdentitiesScope(membershipScope),
+ orgId: membershipOrgId,
+ projectId: scopeProjectId,
+ total_count: total_count as string,
+ createdAt,
+ updatedAt,
+ lastLoginTime,
+ lastLoginAuthMethod,
+ project: projectIdRef
+ ? {
+ id: projectIdRef,
+ name: projectName,
+ slug: projectSlug,
+ type: projectType
+ }
+ : null,
+ identity: {
+ id: identityId as string,
+ name: identityName,
+ hasDeleteProtection,
+ orgId: identityOrgId,
+ authMethods: buildAuthMethods({
+ uaId,
+ alicloudId,
+ awsId,
+ gcpId,
+ kubernetesId,
+ ociId,
+ oidcId,
+ azureId,
+ tokenId,
+ jwtId,
+ ldapId,
+ tlsCertId,
+ spiffeId
+ })
+ }
+ }),
+ childrenMapper: [
+ {
+ key: "membershipRoleId",
+ label: "roles" as const,
+ mapper: ({
+ membershipRoleId,
+ role,
+ roleId,
+ crName,
+ crSlug,
+ crDescription,
+ isTemporary,
+ temporaryMode,
+ temporaryRange,
+ temporaryAccessStartTime,
+ temporaryAccessEndTime
+ }) => ({
+ id: membershipRoleId,
+ role,
+ customRoleId: roleId,
+ customRoleName: crName ?? null,
+ customRoleSlug: crSlug ?? null,
+ customRoleDescription: crDescription ?? null,
+ isTemporary,
+ temporaryMode,
+ temporaryRange,
+ temporaryAccessStartTime,
+ temporaryAccessEndTime
+ })
+ }
+ ]
+ });
+
+ return { docs: formattedDocs, totalCount: Number(formattedDocs?.[0]?.total_count ?? 0) };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "SearchIdentitiesV2" });
+ }
+ };
+
+ const countIdentitiesV2 = async (
+ { orgId, scope, accessibleProjectIds, searchFilter }: TCountIdentitiesV2DAL,
+ tx?: Knex
+ ) => {
+ try {
+ const includeOrgScope = scope.includes(SearchIdentitiesScope.OrganizationScope);
+ const includeProjectScope = scope.includes(SearchIdentitiesScope.ProjectScope);
+
+ const query = (tx || db.replicaNode())(TableName.Membership)
+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
+ .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
+ .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
+ .whereNotNull(`${TableName.Membership}.actorIdentityId`);
+
+ const orgScopeBranch = (sub: Knex.QueryBuilder) => {
+ void sub
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ .whereNull(`${TableName.Identity}.projectId`);
+ };
+
+ const projectScopeBranch = (sub: Knex.QueryBuilder) => {
+ void sub
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ .whereIn(`${TableName.Membership}.scopeProjectId`, accessibleProjectIds);
+ };
+
+ if (includeOrgScope && includeProjectScope) {
+ void query.where((nested) => {
+ void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));
+ });
+ } else if (includeOrgScope) {
+ void query.where((sub) => orgScopeBranch(sub));
+ } else if (includeProjectScope) {
+ void query.where((sub) => projectScopeBranch(sub));
+ } else {
+ return { organization: includeOrgScope ? 0 : undefined, project: includeProjectScope ? 0 : undefined };
+ }
+
+ if (searchFilter) {
+ buildKnexFilterForSearchResource(query, searchFilter, (attr) => {
+ switch (attr) {
+ case "role":
+ return [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`];
+ case "name":
+ return `${TableName.Identity}.name`;
+ default:
+ throw new BadRequestError({ message: `Invalid ${String(attr)} provided` });
+ }
+ });
+ }
+
+ const rows = await query
+ .groupBy(`${TableName.Membership}.scope`)
+ .select(db.ref("scope").withSchema(TableName.Membership).as("scope"))
+ .select<{ scope: string; count: string }[]>(
+ db.raw(`COUNT(DISTINCT ??) as count`, [`${TableName.Membership}.id`])
+ );
+
+ const counts: { organization?: number; project?: number } = {};
+ if (includeOrgScope) counts.organization = 0;
+ if (includeProjectScope) counts.project = 0;
+ for (const row of rows) {
+ if (row.scope === AccessScope.Organization && includeOrgScope) {
+ counts.organization = Number(row.count);
+ } else if (row.scope === AccessScope.Project && includeProjectScope) {
+ counts.project = Number(row.count);
+ }
+ }
+
+ return counts;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "CountIdentitiesV2" });
+ }
+ };
+
+ return { searchIdentitiesV2, countIdentitiesV2 };
+};
diff --git a/backend/src/services/identity-v2/identity-service.ts b/backend/src/services/identity-v2/identity-service.ts
index 144c634e3c..38ec20949c 100644
--- a/backend/src/services/identity-v2/identity-service.ts
+++ b/backend/src/services/identity-v2/identity-service.ts
@@ -1,20 +1,33 @@
-import { AccessScope, OrgMembershipRole } from "@app/db/schemas";
+import { AccessScope, ActionProjectType, OrganizationActionScope, OrgMembershipRole } from "@app/db/schemas";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import {
+ OrgPermissionAdminConsoleAction,
+ OrgPermissionIdentityActions,
+ OrgPermissionSubjects
+} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { getIdentityActiveLockoutAuthMethods } from "@app/services/identity-v2/identity-fns";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { ActorType } from "../auth/auth-type";
+import { getIdentityActiveLockoutAuthMethods } from "../identity/identity-fns";
import { TIdentityMetadataDALFactory } from "../identity/identity-metadata-dal";
import { TIdentityAccessTokenServiceFactory } from "../identity-access-token/identity-access-token-service";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TMembershipIdentityDALFactory } from "../membership-identity/membership-identity-dal";
import { TIdentityV2DALFactory } from "./identity-dal";
+import { filterIdentitiesByProjectPermission, TProjectPermissionAbility } from "./identity-fns";
+import { TIdentityMembershipV2DALFactory } from "./identity-membership-dal";
import {
+ SearchIdentitiesScope,
+ TCountIdentitiesV2DTO,
TCreateIdentityV2DTO,
TDeleteIdentityV2DTO,
TGetIdentityByIdV2DTO,
TListIdentityV2DTO,
+ TSearchIdentitiesV2DTO,
TUpdateIdentityV2DTO
} from "./identity-types";
import { newOrgIdentityFactory } from "./org/org-identity-factory";
@@ -22,6 +35,7 @@ import { newProjectIdentityFactory } from "./project/project-identity-factory";
type TScopedIdentityV2ServiceFactoryDep = {
identityDAL: TIdentityV2DALFactory;
+ identityMembershipV2DAL: TIdentityMembershipV2DALFactory;
permissionService: TPermissionServiceFactory;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "updateSubscriptionOrgMemberCount">;
membershipIdentityDAL: TMembershipIdentityDALFactory;
@@ -29,19 +43,22 @@ type TScopedIdentityV2ServiceFactoryDep = {
identityMetadataDAL: TIdentityMetadataDALFactory;
identityAccessTokenService: Pick<TIdentityAccessTokenServiceFactory, "revokeAllTokensForIdentity">;
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
+ projectDAL: Pick<TProjectDALFactory, "findActorAccessibleProjectIds" | "findOrgProjectIds">;
};
export type TScopedIdentityV2ServiceFactory = ReturnType<typeof identityV2ServiceFactory>;
export const identityV2ServiceFactory = ({
identityDAL,
+ identityMembershipV2DAL,
permissionService,
licenseService,
membershipIdentityDAL,
membershipRoleDAL,
identityMetadataDAL,
identityAccessTokenService,
- keyStore
+ keyStore,
+ projectDAL
}: TScopedIdentityV2ServiceFactoryDep) => {
const orgFactory = newOrgIdentityFactory({
permissionService
@@ -249,11 +266,242 @@ export const identityV2ServiceFactory = ({
return { ...identities, docs: identities.docs.filter((el) => isIdentityAccessible({ identityId: el.id })) };
};
+ const resolveIdentitySearchScope = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ scope
+ }: {
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: TSearchIdentitiesV2DTO["actorAuthMethod"];
+ actorOrgId: string;
+ scope: SearchIdentitiesScope[];
+ }): 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,
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ const canReadOrgIdentities = orgPermission.can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);
+ if (uniqueScope.has(SearchIdentitiesScope.OrganizationScope) && !canReadOrgIdentities) {
+ uniqueScope.delete(SearchIdentitiesScope.OrganizationScope);
+ }
+
+ 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 && canReadOrgIdentities) {
+ // Org admins read unconditionally across every project — skip the per-project probe,
+ // which would otherwise throw ProjectMembershipNotFound for projects the admin hasn't
+ // explicitly joined and drop them from accessibleProjectIds. The org-level identity:read
+ // gate stops access-all-projects holders without identity:read from enumerating
+ // project-scoped machine identities across the org.
+ accessibleProjectIds.push(...(await projectDAL.findOrgProjectIds(actorOrgId)));
+ } else {
+ const candidateProjectIds = 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;
+ }
+ })
+ );
+
+ 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, projectPermissions, conditionalProjectIds };
+ };
+
+ const searchOrgIdentities = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ limit,
+ offset,
+ orderBy,
+ orderDirection,
+ scope,
+ searchFilter = {}
+ }: TSearchIdentitiesV2DTO) => {
+ const { uniqueScope, accessibleProjectIds, projectPermissions, conditionalProjectIds } =
+ await resolveIdentitySearchScope({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ scope
+ });
+
+ if (!uniqueScope.size) {
+ return { identityMemberships: [], totalCount: 0 };
+ }
+
+ if (conditionalProjectIds.size === 0) {
+ const { totalCount, docs } = await identityMembershipV2DAL.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 identityMembershipV2DAL.searchIdentitiesV2({
+ orgId: actorOrgId,
+ orderBy,
+ orderDirection,
+ searchFilter,
+ scope: Array.from(uniqueScope),
+ accessibleProjectIds
+ });
+
+ 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 countOrgIdentities = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ scope,
+ searchFilter = {}
+ }: TCountIdentitiesV2DTO) => {
+ const requestedOrg = scope.includes(SearchIdentitiesScope.OrganizationScope);
+ const requestedProject = scope.includes(SearchIdentitiesScope.ProjectScope);
+
+ 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).
+ const counts: { organization?: number; project?: number } = {};
+ if (requestedOrg) counts.organization = 0;
+ if (requestedProject) counts.project = 0;
+
+ if (!uniqueScope.size) {
+ return counts;
+ }
+
+ if (conditionalProjectIds.size === 0) {
+ const dalCounts = await identityMembershipV2DAL.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 identityMembershipV2DAL.countIdentitiesV2({
+ orgId: actorOrgId,
+ scope: [SearchIdentitiesScope.OrganizationScope],
+ accessibleProjectIds: [],
+ searchFilter
+ });
+ counts.organization = orgOnly.organization ?? 0;
+ }
+
+ if (requestedProject && uniqueScope.has(SearchIdentitiesScope.ProjectScope)) {
+ const { docs } = await identityMembershipV2DAL.searchIdentitiesV2({
+ orgId: actorOrgId,
+ scope: [SearchIdentitiesScope.ProjectScope],
+ accessibleProjectIds,
+ searchFilter
+ });
+ counts.project = filterIdentitiesByProjectPermission(docs, projectPermissions, conditionalProjectIds).length;
+ }
+
+ return counts;
+ };
+
return {
createIdentity,
updateIdentity,
deleteIdentity,
getIdentityById,
- listIdentities
+ listIdentities,
+ searchOrgIdentities,
+ countOrgIdentities
};
};
diff --git a/backend/src/services/identity-v2/identity-types.ts b/backend/src/services/identity-v2/identity-types.ts
index 75e516d48f..f05fd618f1 100644
--- a/backend/src/services/identity-v2/identity-types.ts
+++ b/backend/src/services/identity-v2/identity-types.ts
@@ -1,5 +1,6 @@
-import { AccessScopeData } from "@app/db/schemas";
-import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
+import { AccessScope, AccessScopeData } from "@app/db/schemas";
+import { TSearchResourceOperator } from "@app/lib/search-resource/search";
+import { OrderByDirection, OrgServiceActor, TOrgPermission } from "@app/lib/types";
export interface TIdentityV2Factory {
onCreateIdentityGuard: (arg: TCreateIdentityV2DTO) => Promise<void>;
@@ -65,3 +66,77 @@ export type TListIdentityV2DTO = {
search: string;
}>;
};
+
+// The v2 search endpoint joins Membership and can sort by lastLoginTime; the legacy
+// v1 search / v2 identity-memberships endpoints bind orderBy straight into an
+// `identity.<col>` SQL fragment and would fail with a 500 on LastLogin since the
+// identities table has no such column. Keep this enum separate so the legacy paths
+// reject lastLogin at the Zod boundary.
+export enum OrgIdentitySearchOrderBy {
+ Name = "name",
+ Role = "role",
+ LastLogin = "lastLogin"
+}
+
+export enum SearchIdentitiesScope {
+ OrganizationScope = "organization",
+ ProjectScope = "project"
+}
+
+// Translate a raw `Membership.scope` value into a SearchIdentitiesScope. The two enums share
+// string values today but live in separate files — go through this helper so a future drift
+// (extra AccessScope variant, renamed value) surfaces here instead of silently mistyping rows.
+export const accessScopeToSearchIdentitiesScope = (scope: string): SearchIdentitiesScope => {
+ switch (scope) {
+ case AccessScope.Organization:
+ return SearchIdentitiesScope.OrganizationScope;
+ case AccessScope.Project:
+ return SearchIdentitiesScope.ProjectScope;
+ default:
+ throw new Error(`Unexpected membership scope for identity search: ${scope}`);
+ }
+};
+
+export type TSearchIdentitiesV2DAL = {
+ limit?: number;
+ offset?: number;
+ orderBy?: OrgIdentitySearchOrderBy;
+ orderDirection?: OrderByDirection;
+ orgId: string;
+ scope: SearchIdentitiesScope[];
+ accessibleProjectIds: string[];
+ searchFilter?: Partial<{
+ name: Omit<TSearchResourceOperator, "number">;
+ role: Omit<TSearchResourceOperator, "number">;
+ }>;
+};
+
+export type TSearchIdentitiesV2DTO = {
+ limit?: number;
+ offset?: number;
+ orderBy?: OrgIdentitySearchOrderBy;
+ orderDirection?: OrderByDirection;
+ scope: SearchIdentitiesScope[];
+ searchFilter?: Partial<{
+ name: Omit<TSearchResourceOperator, "number">;
+ role: Omit<TSearchResourceOperator, "number">;
+ }>;
+} & TOrgPermission;
+
+export type TCountIdentitiesV2DAL = {
+ orgId: string;
+ scope: SearchIdentitiesScope[];
+ accessibleProjectIds: string[];
+ searchFilter?: Partial<{
+ name: Omit<TSearchResourceOperator, "number">;
+ role: Omit<TSearchResourceOperator, "number">;
+ }>;
+};
+
+export type TCountIdentitiesV2DTO = {
+ scope: SearchIdentitiesScope[];
+ searchFilter?: Partial<{
+ name: Omit<TSearchResourceOperator, "number">;
+ role: Omit<TSearchResourceOperator, "number">;
+ }>;
+} & TOrgPermission;
diff --git a/backend/src/services/identity/identity-fns.ts b/backend/src/services/identity/identity-fns.ts
index 42d1527f71..efa0e63f95 100644
--- a/backend/src/services/identity/identity-fns.ts
+++ b/backend/src/services/identity/identity-fns.ts
@@ -1,38 +1,28 @@
-import { MongoAbility, subject } from "@casl/ability";
-
import { IdentityAuthMethod } from "@app/db/schemas";
-import {
- ProjectPermissionIdentityActions,
- ProjectPermissionSet,
- ProjectPermissionSub
-} from "@app/ee/services/permission/project-permission";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
-import { SearchIdentitiesScope } from "./identity-types";
+export const getIdentityActiveLockoutAuthMethods = async (
+ identityId: string,
+ keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">
+) => {
+ const activeLockouts = await keyStore.getKeysByPattern(KeyStorePrefixes.IdentityLockoutStatePattern(identityId));
-export type TProjectPermissionAbility = MongoAbility<ProjectPermissionSet>;
+ const activeLockoutAuthMethods = new Set<string>();
+ for await (const key of activeLockouts) {
+ const parts = key.split(":");
+ if (parts.length > 3) {
+ const lockoutRaw = await keyStore.getItem(key);
+ if (lockoutRaw) {
+ const lockout = JSON.parse(lockoutRaw) as { lockedOut: boolean };
+ if (lockout.lockedOut) {
+ activeLockoutAuthMethods.add(parts[3]);
+ }
+ }
+ }
+ }
-// 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 })
- );
- });
+ return Array.from(activeLockoutAuthMethods);
+};
export const buildAuthMethods = ({
uaId,
diff --git a/backend/src/services/identity/identity-org-dal.ts b/backend/src/services/identity/identity-org-dal.ts
index 133a6ebac7..cc481cf89c 100644
--- a/backend/src/services/identity/identity-org-dal.ts
+++ b/backend/src/services/identity/identity-org-dal.ts
@@ -26,13 +26,8 @@ import { selectAllTableCols, sqlNestRelationships } from "@app/lib/knex";
import { buildKnexFilterForSearchResource } from "@app/lib/search-resource/db";
import { OrderByDirection } from "@app/lib/types";
import {
- accessScopeToSearchIdentitiesScope,
OrgIdentityOrderBy,
- OrgIdentitySearchOrderBy,
- SearchIdentitiesScope,
- TCountIdentitiesV2DAL,
TListOrgIdentitiesByOrgIdDTO,
- TSearchIdentitiesV2DAL,
TSearchOrgIdentitiesByOrgIdDAL
} from "@app/services/identity/identity-types";
@@ -703,466 +698,5 @@ export const identityOrgDALFactory = (db: TDbClient) => {
}
};
- const searchIdentitiesV2 = async (
- {
- limit,
- offset = 0,
- orderBy = OrgIdentitySearchOrderBy.Name,
- orderDirection = OrderByDirection.ASC,
- searchFilter,
- orgId,
- scope,
- accessibleProjectIds
- }: TSearchIdentitiesV2DAL,
- tx?: Knex
- ) => {
- try {
- const includeOrgScope = scope.includes(SearchIdentitiesScope.OrganizationScope);
- const includeProjectScope = scope.includes(SearchIdentitiesScope.ProjectScope);
-
- const applyScopeFilter = (qb: Knex.QueryBuilder) => {
- void qb.whereNotNull(`${TableName.Membership}.actorIdentityId`);
-
- // Project-owned identities (Identity.projectId IS NOT NULL) always carry a NoAccess
- // org-level Membership row as an implementation detail of their creation flow
- // (see identity-v2/identity-service.ts createIdentity). Excluding them here keeps
- // the org-scope listing limited to true org-level identities, matching V1 behavior
- // and preventing duplicate rows in the combined org+project view.
- const orgScopeBranch = (sub: Knex.QueryBuilder) => {
- void sub
- .where(`${TableName.Membership}.scope`, AccessScope.Organization)
- .where(`${TableName.Membership}.scopeOrgId`, orgId)
- .whereNull(`${TableName.Identity}.projectId`);
- };
-
- const projectScopeBranch = (sub: Knex.QueryBuilder) => {
- void sub
- .where(`${TableName.Membership}.scope`, AccessScope.Project)
- .where(`${TableName.Membership}.scopeOrgId`, orgId)
- .whereIn(`${TableName.Membership}.scopeProjectId`, accessibleProjectIds);
- };
-
- if (includeOrgScope && includeProjectScope) {
- void qb.where((nested) => {
- void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));
- });
- } else if (includeOrgScope) {
- orgScopeBranch(qb);
- } else if (includeProjectScope) {
- projectScopeBranch(qb);
- }
- };
-
- // Identity-auth login services update the lastLogin* columns on exactly one Membership row
- // keyed on the identity's home org (scope=Organization, scopeOrgId=Identity.orgId, projectId
- // omitted). The project Membership row created at `createMembershipIdentity` time therefore
- // never receives a login timestamp. To avoid surfacing "Never" in the project / all tabs for
- // an identity that authenticates regularly, fall back to the matching org Membership via a
- // correlated subquery. The bound scopeOrgId must reference Identity.orgId (not the caller's
- // orgId) so the fallback also works for a root-org identity linked into a sub-org.
- const lastLoginFallbackRaw = (column: "lastLoginTime" | "lastLoginAuthMethod", outputAlias: string) =>
- db.raw(
- `COALESCE(??.??, (SELECT om.?? FROM ?? AS om WHERE om.?? = ??.?? AND om.?? = ? AND om.?? = ??.??)) as ??`,
- [
- TableName.Membership,
- column,
- column,
- TableName.Membership,
- "actorIdentityId",
- TableName.Membership,
- "actorIdentityId",
- "scope",
- AccessScope.Organization,
- "scopeOrgId",
- TableName.Identity,
- "orgId",
- outputAlias
- ]
- );
-
- const searchedMemberships = (tx || db.replicaNode())(TableName.Membership)
- .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
- .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
- .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
- .where(applyScopeFilter)
- .groupBy(
- `${TableName.Membership}.id`,
- `${TableName.Identity}.name`,
- `${TableName.Identity}.orgId`,
- `${TableName.Membership}.lastLoginTime`
- )
- .select(`${TableName.Membership}.id`)
- .select(db.ref("name").withSchema(TableName.Identity).as("identityName"))
- .select(lastLoginFallbackRaw("lastLoginTime", "lastLoginSort"))
- .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(
- db.raw(`MIN(COALESCE(??, ??)) as "roleSort"`, [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`])
- )
- .select<{ id: string; identityName: string; roleSort: string; total_count: string }>(
- db.raw(`COUNT(*) OVER() as total_count`)
- );
-
- if (searchFilter) {
- buildKnexFilterForSearchResource(searchedMemberships, searchFilter, (attr) => {
- switch (attr) {
- case "role":
- return [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`];
- case "name":
- return `${TableName.Identity}.name`;
- default:
- throw new BadRequestError({ message: `Invalid ${String(attr)} provided` });
- }
- });
- }
-
- if (orderBy === OrgIdentitySearchOrderBy.Role) {
- void searchedMemberships.orderBy("roleSort", orderDirection, "last");
- } else if (orderBy === OrgIdentitySearchOrderBy.LastLogin) {
- // Never-used identities (lastLoginTime IS NULL) are always pushed to the bottom
- // regardless of sort direction so the visible page is dominated by real activity.
- void searchedMemberships.orderBy("lastLoginSort", orderDirection, "last");
- } else {
- void searchedMemberships.orderBy("identityName", orderDirection);
- }
- // Secondary sort by membership id keeps pagination deterministic when the primary
- // sort key ties (duplicate names, identical aggregated role).
- void searchedMemberships.orderBy(`${TableName.Membership}.id`, "asc");
-
- if (limit) {
- void searchedMemberships.offset(offset).limit(limit);
- }
-
- const searchedMembershipsSubquery = searchedMemberships.as("searchedMemberships");
- type TSubquery = Awaited<typeof searchedMemberships>;
-
- const query = (tx || db.replicaNode())(TableName.Membership)
- .join<TSubquery>(searchedMembershipsSubquery, `${TableName.Membership}.id`, "searchedMemberships.id")
- .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
- .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
- .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
- .leftJoin(TableName.Project, `${TableName.Project}.id`, `${TableName.Membership}.scopeProjectId`)
- .leftJoin(
- TableName.IdentityUniversalAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityUniversalAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityGcpAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityGcpAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityAliCloudAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityAliCloudAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityAwsAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityAwsAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityKubernetesAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityKubernetesAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityOciAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityOciAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityOidcAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityOidcAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityAzureAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityAzureAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityTokenAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityTokenAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityJwtAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityJwtAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityLdapAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityLdapAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentityTlsCertAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentityTlsCertAuth}.identityId`
- )
- .leftJoin(
- TableName.IdentitySpiffeAuth,
- `${TableName.Membership}.actorIdentityId`,
- `${TableName.IdentitySpiffeAuth}.identityId`
- )
- .select(
- db.ref("id").withSchema(TableName.Membership),
- db.ref("scope").withSchema(TableName.Membership).as("membershipScope"),
- db.ref("scopeOrgId").withSchema(TableName.Membership).as("orgId"),
- db.ref("scopeProjectId").withSchema(TableName.Membership).as("scopeProjectId"),
- db.ref("total_count").withSchema("searchedMemberships"),
- db.ref("createdAt").withSchema(TableName.Membership),
- db.ref("updatedAt").withSchema(TableName.Membership),
- db.ref("actorIdentityId").withSchema(TableName.Membership).as("identityId"),
- db.ref("name").withSchema(TableName.Identity).as("identityName"),
- db.ref("hasDeleteProtection").withSchema(TableName.Identity),
- db.ref("orgId").withSchema(TableName.Identity).as("identityOrgId"),
-
- db.ref("id").withSchema(TableName.MembershipRole).as("membershipRoleId"),
- db.ref("role").withSchema(TableName.MembershipRole),
- db.ref("customRoleId").withSchema(TableName.MembershipRole).as("roleId"),
- db.ref("isTemporary").withSchema(TableName.MembershipRole),
- db.ref("temporaryMode").withSchema(TableName.MembershipRole),
- db.ref("temporaryRange").withSchema(TableName.MembershipRole),
- db.ref("temporaryAccessStartTime").withSchema(TableName.MembershipRole),
- db.ref("temporaryAccessEndTime").withSchema(TableName.MembershipRole),
-
- db.ref("id").as("projectIdRef").withSchema(TableName.Project),
- db.ref("name").as("projectName").withSchema(TableName.Project),
- db.ref("slug").as("projectSlug").withSchema(TableName.Project),
- db.ref("type").as("projectType").withSchema(TableName.Project),
-
- db.ref("id").as("uaId").withSchema(TableName.IdentityUniversalAuth),
- db.ref("id").as("gcpId").withSchema(TableName.IdentityGcpAuth),
- db.ref("id").as("alicloudId").withSchema(TableName.IdentityAliCloudAuth),
- db.ref("id").as("awsId").withSchema(TableName.IdentityAwsAuth),
- db.ref("id").as("kubernetesId").withSchema(TableName.IdentityKubernetesAuth),
- db.ref("id").as("ociId").withSchema(TableName.IdentityOciAuth),
- db.ref("id").as("oidcId").withSchema(TableName.IdentityOidcAuth),
- db.ref("id").as("azureId").withSchema(TableName.IdentityAzureAuth),
- db.ref("id").as("tokenId").withSchema(TableName.IdentityTokenAuth),
- db.ref("id").as("jwtId").withSchema(TableName.IdentityJwtAuth),
- db.ref("id").as("ldapId").withSchema(TableName.IdentityLdapAuth),
- db.ref("id").as("tlsCertId").withSchema(TableName.IdentityTlsCertAuth),
- db.ref("id").as("spiffeId").withSchema(TableName.IdentitySpiffeAuth)
- )
- .select(db.ref("name").as("crName").withSchema(TableName.Role))
- .select(db.ref("slug").as("crSlug").withSchema(TableName.Role))
- .select(db.ref("description").as("crDescription").withSchema(TableName.Role))
- .select(
- lastLoginFallbackRaw("lastLoginTime", "lastLoginTime"),
- lastLoginFallbackRaw("lastLoginAuthMethod", "lastLoginAuthMethod")
- );
-
- if (orderBy === OrgIdentitySearchOrderBy.Role) {
- void query.orderBy("searchedMemberships.roleSort", orderDirection, "last");
- } else if (orderBy === OrgIdentitySearchOrderBy.LastLogin) {
- void query.orderBy("searchedMemberships.lastLoginSort", orderDirection, "last");
- } else {
- void query.orderBy("searchedMemberships.identityName", orderDirection);
- }
- void query.orderBy("searchedMemberships.id", "asc");
-
- // lastLoginTime / lastLoginAuthMethod are produced by raw COALESCE expressions
- // (see lastLoginFallbackRaw), so Knex's inferred record type doesn't include them.
- // They are present at runtime — add them to the type explicitly so the nest-mapper
- // destructuring below compiles.
- const docs = (await query) as (typeof query extends PromiseLike<infer R>
- ? R extends (infer Row)[]
- ? Row & { lastLoginTime: Date | null; lastLoginAuthMethod: string | null }
- : never
- : never)[];
-
- const formattedDocs = sqlNestRelationships({
- data: docs,
- key: "id",
- parentMapper: ({
- identityId,
- identityOrgId,
- identityName,
- hasDeleteProtection,
- total_count,
- id,
- membershipScope,
- orgId: membershipOrgId,
- scopeProjectId,
- projectIdRef,
- projectName,
- projectSlug,
- projectType,
- uaId,
- alicloudId,
- awsId,
- gcpId,
- jwtId,
- kubernetesId,
- ociId,
- oidcId,
- azureId,
- tokenId,
- ldapId,
- tlsCertId,
- spiffeId,
- createdAt,
- updatedAt,
- lastLoginTime,
- lastLoginAuthMethod
- }) => ({
- id,
- identityId: identityId as string,
- scope: accessScopeToSearchIdentitiesScope(membershipScope),
- orgId: membershipOrgId,
- projectId: scopeProjectId,
- total_count: total_count as string,
- createdAt,
- updatedAt,
- lastLoginTime,
- lastLoginAuthMethod,
- project: projectIdRef
- ? {
- id: projectIdRef,
- name: projectName,
- slug: projectSlug,
- type: projectType
- }
- : null,
- identity: {
- id: identityId as string,
- name: identityName,
- hasDeleteProtection,
- orgId: identityOrgId,
- authMethods: buildAuthMethods({
- uaId,
- alicloudId,
- awsId,
- gcpId,
- kubernetesId,
- ociId,
- oidcId,
- azureId,
- tokenId,
- jwtId,
- ldapId,
- tlsCertId,
- spiffeId
- })
- }
- }),
- childrenMapper: [
- {
- key: "membershipRoleId",
- label: "roles" as const,
- mapper: ({
- membershipRoleId,
- role,
- roleId,
- crName,
- crSlug,
- crDescription,
- isTemporary,
- temporaryMode,
- temporaryRange,
- temporaryAccessStartTime,
- temporaryAccessEndTime
- }) => ({
- id: membershipRoleId,
- role,
- customRoleId: roleId,
- customRoleName: crName ?? null,
- customRoleSlug: crSlug ?? null,
- customRoleDescription: crDescription ?? null,
- isTemporary,
- temporaryMode,
- temporaryRange,
- temporaryAccessStartTime,
- temporaryAccessEndTime
- })
- }
- ]
- });
-
- return { docs: formattedDocs, totalCount: Number(formattedDocs?.[0]?.total_count ?? 0) };
- } catch (error) {
- throw new DatabaseError({ error, name: "SearchIdentitiesV2" });
- }
- };
-
- const countIdentitiesV2 = async (
- { orgId, scope, accessibleProjectIds, searchFilter }: TCountIdentitiesV2DAL,
- tx?: Knex
- ) => {
- try {
- const includeOrgScope = scope.includes(SearchIdentitiesScope.OrganizationScope);
- const includeProjectScope = scope.includes(SearchIdentitiesScope.ProjectScope);
-
- const query = (tx || db.replicaNode())(TableName.Membership)
- .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Membership}.actorIdentityId`)
- .join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
- .leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
- .whereNotNull(`${TableName.Membership}.actorIdentityId`);
-
- const orgScopeBranch = (sub: Knex.QueryBuilder) => {
- void sub
- .where(`${TableName.Membership}.scope`, AccessScope.Organization)
- .where(`${TableName.Membership}.scopeOrgId`, orgId)
- .whereNull(`${TableName.Identity}.projectId`);
- };
-
- const projectScopeBranch = (sub: Knex.QueryBuilder) => {
- void sub
- .where(`${TableName.Membership}.scope`, AccessScope.Project)
- .where(`${TableName.Membership}.scopeOrgId`, orgId)
- .whereIn(`${TableName.Membership}.scopeProjectId`, accessibleProjectIds);
- };
-
- if (includeOrgScope && includeProjectScope) {
- void query.where((nested) => {
- void nested.where((sub) => orgScopeBranch(sub)).orWhere((sub) => projectScopeBranch(sub));
- });
- } else if (includeOrgScope) {
- void query.where((sub) => orgScopeBranch(sub));
- } else if (includeProjectScope) {
- void query.where((sub) => projectScopeBranch(sub));
- } else {
- return { organization: includeOrgScope ? 0 : undefined, project: includeProjectScope ? 0 : undefined };
- }
-
- if (searchFilter) {
- buildKnexFilterForSearchResource(query, searchFilter, (attr) => {
- switch (attr) {
- case "role":
- return [`${TableName.Role}.slug`, `${TableName.MembershipRole}.role`];
- case "name":
- return `${TableName.Identity}.name`;
- default:
- throw new BadRequestError({ message: `Invalid ${String(attr)} provided` });
- }
- });
- }
-
- const rows = await query
- .groupBy(`${TableName.Membership}.scope`)
- .select(db.ref("scope").withSchema(TableName.Membership).as("scope"))
- .select<{ scope: string; count: string }[]>(
- db.raw(`COUNT(DISTINCT ??) as count`, [`${TableName.Membership}.id`])
- );
-
- const counts: { organization?: number; project?: number } = {};
- if (includeOrgScope) counts.organization = 0;
- if (includeProjectScope) counts.project = 0;
- for (const row of rows) {
- if (row.scope === AccessScope.Organization && includeOrgScope) {
- counts.organization = Number(row.count);
- } else if (row.scope === AccessScope.Project && includeProjectScope) {
- counts.project = Number(row.count);
- }
- }
-
- return counts;
- } catch (error) {
- throw new DatabaseError({ error, name: "CountIdentitiesV2" });
- }
- };
-
- return { find, findOne, countAllOrgIdentities, searchIdentities, searchIdentitiesV2, countIdentitiesV2 };
+ return { find, findOne, countAllOrgIdentities, searchIdentities };
};
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index 92bb790695..5bfd9b8f15 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -1,33 +1,19 @@
import { ForbiddenError } from "@casl/ability";
-import {
- AccessScope,
- ActionProjectType,
- OrganizationActionScope,
- OrgMembershipRole,
- TableName,
- TRoles
-} from "@app/db/schemas";
+import { AccessScope, OrganizationActionScope, OrgMembershipRole, TableName, TRoles } from "@app/db/schemas";
import { TLicenseDALFactory } from "@app/ee/services/license/license-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
-import {
- OrgPermissionAdminConsoleAction,
- OrgPermissionIdentityActions,
- OrgPermissionSubjects
-} from "@app/ee/services/permission/org-permission";
+import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import {
constructPermissionErrorMessage,
validatePrivilegeChangeOperation
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
-import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError, PermissionBoundaryError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
import { TIdentityProjectDALFactory } from "@app/services/identity-project/identity-project-dal";
-import { getIdentityActiveLockoutAuthMethods } from "@app/services/identity-v2/identity-fns";
-import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TAdditionalPrivilegeDALFactory } from "../additional-privilege/additional-privilege-dal";
import { ActorType } from "../auth/auth-type";
@@ -36,18 +22,15 @@ 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 { getIdentityActiveLockoutAuthMethods } from "./identity-fns";
import { TIdentityMetadataDALFactory } from "./identity-metadata-dal";
import { TIdentityOrgDALFactory } from "./identity-org-dal";
import {
- SearchIdentitiesScope,
- TCountIdentitiesV2DTO,
TCreateIdentityDTO,
TDeleteIdentityDTO,
TGetIdentityByIdDTO,
TListOrgIdentitiesByOrgIdDTO,
TListProjectIdentitiesByIdentityIdDTO,
- TSearchIdentitiesV2DTO,
TSearchOrgIdentitiesByOrgIdDTO,
TUpdateIdentityDTO
} from "./identity-types";
@@ -59,16 +42,12 @@ type TIdentityServiceFactoryDep = {
membershipIdentityDAL: TMembershipIdentityDALFactory;
membershipRoleDAL: TMembershipRoleDALFactory;
identityProjectDAL: Pick<TIdentityProjectDALFactory, "findByIdentityId">;
- permissionService: Pick<
- TPermissionServiceFactory,
- "getOrgPermission" | "getOrgPermissionByRoles" | "getProjectPermission"
- >;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRoles">;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "updateSubscriptionOrgMemberCount">;
licenseDAL: Pick<TLicenseDALFactory, "countOrgUsersAndIdentities">;
keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
orgDAL: Pick<TOrgDALFactory, "findById" | "findEffectiveOrgMembership">;
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
- projectDAL: Pick<TProjectDALFactory, "findActorAccessibleProjectIds" | "findOrgProjectIds">;
};
export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;
@@ -85,8 +64,7 @@ export const identityServiceFactory = ({
orgDAL,
membershipIdentityDAL,
membershipRoleDAL,
- additionalPrivilegeDAL,
- projectDAL
+ additionalPrivilegeDAL
}: TIdentityServiceFactoryDep) => {
const createIdentity = async ({
name,
@@ -504,235 +482,6 @@ export const identityServiceFactory = ({
return { identityMemberships: docs, totalCount };
};
- const resolveIdentitySearchScope = async ({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- scope
- }: {
- actor: ActorType;
- actorId: string;
- actorAuthMethod: TSearchIdentitiesV2DTO["actorAuthMethod"];
- actorOrgId: string;
- scope: SearchIdentitiesScope[];
- }): 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,
- actor,
- actorId,
- orgId: actorOrgId,
- actorAuthMethod,
- actorOrgId
- });
- const canReadOrgIdentities = orgPermission.can(OrgPermissionIdentityActions.Read, OrgPermissionSubjects.Identity);
- if (uniqueScope.has(SearchIdentitiesScope.OrganizationScope) && !canReadOrgIdentities) {
- uniqueScope.delete(SearchIdentitiesScope.OrganizationScope);
- }
-
- 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 && canReadOrgIdentities) {
- // Org admins read unconditionally across every project — skip the per-project probe,
- // which would otherwise throw ProjectMembershipNotFound for projects the admin hasn't
- // explicitly joined and drop them from accessibleProjectIds. The org-level identity:read
- // gate stops access-all-projects holders without identity:read from enumerating
- // project-scoped machine identities across the org.
- accessibleProjectIds.push(...(await projectDAL.findOrgProjectIds(actorOrgId)));
- } else {
- const candidateProjectIds = 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;
- }
- })
- );
-
- 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, projectPermissions, conditionalProjectIds };
- };
-
- const searchOrgIdentitiesV2 = async ({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- limit,
- offset,
- orderBy,
- orderDirection,
- scope,
- searchFilter = {}
- }: TSearchIdentitiesV2DTO) => {
- const { uniqueScope, accessibleProjectIds, projectPermissions, conditionalProjectIds } =
- await resolveIdentitySearchScope({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- scope
- });
-
- if (!uniqueScope.size) {
- return { identityMemberships: [], totalCount: 0 };
- }
-
- 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,
- orderBy,
- orderDirection,
- searchFilter,
- scope: Array.from(uniqueScope),
- accessibleProjectIds
- });
-
- 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 ({
- actor,
- actorId,
- actorAuthMethod,
- actorOrgId,
- scope,
- searchFilter = {}
- }: TCountIdentitiesV2DTO) => {
- const requestedOrg = scope.includes(SearchIdentitiesScope.OrganizationScope);
- const requestedProject = scope.includes(SearchIdentitiesScope.ProjectScope);
-
- 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).
- const counts: { organization?: number; project?: number } = {};
- if (requestedOrg) counts.organization = 0;
- if (requestedProject) counts.project = 0;
-
- if (!uniqueScope.size) {
- return counts;
- }
-
- 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 (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;
- };
-
const listProjectIdentitiesByIdentityId = async ({
identityId,
actor,
@@ -768,8 +517,6 @@ export const identityServiceFactory = ({
listOrgIdentities,
getIdentityById,
searchOrgIdentities,
- searchOrgIdentitiesV2,
- countOrgIdentitiesV2,
listProjectIdentitiesByIdentityId
};
};
diff --git a/backend/src/services/identity/identity-types.ts b/backend/src/services/identity/identity-types.ts
index 291645f539..4380f6f416 100644
--- a/backend/src/services/identity/identity-types.ts
+++ b/backend/src/services/identity/identity-types.ts
@@ -1,4 +1,3 @@
-import { AccessScope } from "@app/db/schemas";
import { IPType } from "@app/lib/ip";
import { TSearchResourceOperator } from "@app/lib/search-resource/search";
import { OrderByDirection, TOrgPermission } from "@app/lib/types";
@@ -51,17 +50,6 @@ export enum OrgIdentityOrderBy {
Role = "role"
}
-// The v2 search endpoint joins Membership and can sort by lastLoginTime; the legacy
-// v1 search / v2 identity-memberships endpoints bind orderBy straight into an
-// `identity.<col>` SQL fragment and would fail with a 500 on LastLogin since the
-// identities table has no such column. Keep this enum separate so the legacy paths
-// reject lastLogin at the Zod boundary.
-export enum OrgIdentitySearchOrderBy {
- Name = "name",
- Role = "role",
- LastLogin = "lastLogin"
-}
-
export type TSearchOrgIdentitiesByOrgIdDAL = {
limit?: number;
offset?: number;
@@ -75,66 +63,3 @@ export type TSearchOrgIdentitiesByOrgIdDAL = {
};
export type TSearchOrgIdentitiesByOrgIdDTO = TSearchOrgIdentitiesByOrgIdDAL & TOrgPermission;
-
-export enum SearchIdentitiesScope {
- OrganizationScope = "organization",
- ProjectScope = "project"
-}
-
-// Translate a raw `Membership.scope` value into a SearchIdentitiesScope. The two enums share
-// string values today but live in separate files — go through this helper so a future drift
-// (extra AccessScope variant, renamed value) surfaces here instead of silently mistyping rows.
-export const accessScopeToSearchIdentitiesScope = (scope: string): SearchIdentitiesScope => {
- switch (scope) {
- case AccessScope.Organization:
- return SearchIdentitiesScope.OrganizationScope;
- case AccessScope.Project:
- return SearchIdentitiesScope.ProjectScope;
- default:
- throw new Error(`Unexpected membership scope for identity search: ${scope}`);
- }
-};
-
-export type TSearchIdentitiesV2DAL = {
- limit?: number;
- offset?: number;
- orderBy?: OrgIdentitySearchOrderBy;
- orderDirection?: OrderByDirection;
- orgId: string;
- scope: SearchIdentitiesScope[];
- accessibleProjectIds: string[];
- searchFilter?: Partial<{
- name: Omit<TSearchResourceOperator, "number">;
- role: Omit<TSearchResourceOperator, "number">;
- }>;
-};
-
-export type TSearchIdentitiesV2DTO = {
- limit?: number;
- offset?: number;
- orderBy?: OrgIdentitySearchOrderBy;
- orderDirection?: OrderByDirection;
- scope: SearchIdentitiesScope[];
- searchFilter?: Partial<{
- name: Omit<TSearchResourceOperator, "number">;
- role: Omit<TSearchResourceOperator, "number">;
- }>;
-} & TOrgPermission;
-
-export type TCountIdentitiesV2DAL = {
- orgId: string;
- scope: SearchIdentitiesScope[];
- accessibleProjectIds: string[];
- searchFilter?: Partial<{
- name: Omit<TSearchResourceOperator, "number">;
- role: Omit<TSearchResourceOperator, "number">;
- }>;
-};
-
-export type TCountIdentitiesV2DTO = {
- scope: SearchIdentitiesScope[];
- searchFilter?: Partial<{
- name: Omit<TSearchResourceOperator, "number">;
- role: Omit<TSearchResourceOperator, "number">;
- }>;
-} & TOrgPermission;