Skip to content

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

Adds endpoint to list accessible orgs.

IgorHortad4f9de485ff3
diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts
index 0b1e0fcf0e..c12348fb89 100644
--- a/backend/src/server/routes/v1/organization-router.ts
+++ b/backend/src/server/routes/v1/organization-router.ts
@@ -18,7 +18,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { GenericResourceNameSchema, slugSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode, MfaMethod } from "@app/services/auth/auth-type";
-import { sanitizedOrganizationSchema } from "@app/services/org/org-schema";
+import { orgWithSubOrgsSchema, sanitizedOrganizationSchema } from "@app/services/org/org-schema";
import { integrationAuthPubSchema } from "../sanitizedSchemas";
@@ -50,6 +50,30 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
}
});
+ /**
+ * List all organizations the user can access (root orgs) with their accessible sub-orgs (id, name, slug only).
+ */
+ server.route({
+ method: "GET",
+ url: "/accessible-with-sub-orgs",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listAccessibleOrganizationsWithSubOrgs",
+ response: {
+ 200: z.object({
+ organizations: orgWithSubOrgsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT], { requireOrg: false }),
+ handler: async (req) => {
+ const organizations = await server.services.org.findAllAcessibleOrganizationsWithSubOrgs(req.permission.id);
+ return { organizations };
+ }
+ });
+
server.route({
method: "GET",
url: "/:organizationId",
diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.ts
index 6a93f85ee6..076a0824a4 100644
--- a/backend/src/services/org/org-dal.ts
+++ b/backend/src/services/org/org-dal.ts
@@ -14,7 +14,8 @@ import {
TOrganizationsInsert,
TUserEncryptionKeys
} from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
+import { BadRequestError, DatabaseError } from "@app/lib/errors";
+import { groupBy } from "@app/lib/fn";
import {
buildFindFilter,
ormify,
@@ -27,6 +28,7 @@ import {
import { generateKnexQueryFromScim } from "@app/lib/knex/scim";
import { ActorType } from "../auth/auth-type";
+import { TOrgWithSubOrgs } from "./org-schema";
import { OrgAuthMethod } from "./org-types";
export type TOrgDALFactory = ReturnType<typeof orgDALFactory>;
@@ -230,6 +232,98 @@ export const orgDALFactory = (db: TDbClient) => {
}
};
+ /**
+ * Returns all root orgs the actor can see (has membership, direct or via group),
+ * each with its sub-organizations. Basic org fields and suborg id/name/slug only.
+ */
+ const listOrganizationsWithSubOrgs = async (dto: {
+ actorId: string;
+ actorType: ActorType;
+ }): Promise<TOrgWithSubOrgs[]> => {
+ if (dto.actorType !== ActorType.USER) {
+ throw new BadRequestError({
+ message: "listOrganizationsWithSubOrgs only supports user actors; identity/machine is not supported"
+ });
+ }
+
+ try {
+ const conn = db.replicaNode();
+
+ // Group IDs the user belongs to
+ const userGroupIdsSubquery = conn(TableName.Groups)
+ .join(TableName.UserGroupMembership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Groups}.id`)
+ .where(`${TableName.UserGroupMembership}.userId`, dto.actorId)
+ .select(db.ref("id").withSchema(TableName.Groups));
+
+ // Root org IDs the user can see (membership direct or via group, scope = Organization, org is root)
+ const rootOrgIdsSubquery = conn(TableName.Membership)
+ .join(TableName.Organization, `${TableName.Membership}.scopeOrgId`, `${TableName.Organization}.id`)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .whereNull(`${TableName.Organization}.rootOrgId`)
+ .andWhere((qb) => {
+ void qb
+ .where(`${TableName.Membership}.actorUserId`, dto.actorId)
+ .orWhereIn(`${TableName.Membership}.actorGroupId`, userGroupIdsSubquery);
+ })
+ .distinct(db.ref("id").withSchema(TableName.Organization).as("rootOrgId"));
+
+ const rootOrgs = await conn(TableName.Organization)
+ .whereIn(`${TableName.Organization}.id`, rootOrgIdsSubquery)
+ .select(
+ db.ref("id").withSchema(TableName.Organization),
+ db.ref("name").withSchema(TableName.Organization),
+ db.ref("slug").withSchema(TableName.Organization),
+ db.ref("createdAt").withSchema(TableName.Organization)
+ );
+
+ const rootOrgIds = rootOrgs.map((o) => o.id);
+ if (rootOrgIds.length === 0) {
+ return rootOrgs.map((o) => ({ ...o, subOrganizations: [] }));
+ }
+
+ // Only sub-orgs the user has membership in (direct or via group)
+ const accessibleSubOrgIdsSubquery = conn(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .whereIn(
+ `${TableName.Membership}.scopeOrgId`,
+ conn(TableName.Organization)
+ .whereIn(`${TableName.Organization}.rootOrgId`, rootOrgIds)
+ .select(db.ref("id").withSchema(TableName.Organization))
+ )
+ .andWhere((qb) => {
+ void qb
+ .where(`${TableName.Membership}.actorUserId`, dto.actorId)
+ .orWhereIn(`${TableName.Membership}.actorGroupId`, userGroupIdsSubquery);
+ })
+ .select(db.ref("scopeOrgId").withSchema(TableName.Membership));
+
+ const subOrgs = await conn(TableName.Organization)
+ .whereIn(`${TableName.Organization}.rootOrgId`, rootOrgIds)
+ .whereIn(`${TableName.Organization}.id`, accessibleSubOrgIdsSubquery)
+ .select(
+ db.ref("id").withSchema(TableName.Organization),
+ db.ref("name").withSchema(TableName.Organization),
+ db.ref("slug").withSchema(TableName.Organization),
+ db.ref("rootOrgId").withSchema(TableName.Organization)
+ );
+ const subOrgsByRootId = groupBy(subOrgs, (s) => s.rootOrgId as string);
+
+ return rootOrgs.map((org) => ({
+ id: org.id,
+ name: org.name,
+ slug: org.slug,
+ createdAt: org.createdAt,
+ subOrganizations: (subOrgsByRootId[org.id] ?? []).map((s) => ({
+ id: s.id,
+ name: s.name,
+ slug: s.slug
+ }))
+ }));
+ } catch (error) {
+ throw new DatabaseError({ error, name: "List organizations with sub orgs" });
+ }
+ };
+
const findOrgById = async (orgId: string) => {
try {
const org = (await db
@@ -853,6 +947,7 @@ export const orgDALFactory = (db: TDbClient) => {
findAllOrgMembers,
countAllOrgMembers,
listSubOrganizations,
+ listOrganizationsWithSubOrgs,
findOrgById,
findOrgBySlug,
findAllOrgsByUserId,
diff --git a/backend/src/services/org/org-schema.ts b/backend/src/services/org/org-schema.ts
index 3142d2604f..49038a8470 100644
--- a/backend/src/services/org/org-schema.ts
+++ b/backend/src/services/org/org-schema.ts
@@ -1,5 +1,27 @@
+import { z } from "zod";
+
import { OrganizationsSchema } from "@app/db/schemas";
+/** Minimal org fields (id, name, slug) – e.g. for sub-org list items or summaries */
+export const orgBasicSchema = OrganizationsSchema.pick({
+ id: true,
+ name: true,
+ slug: true
+});
+export type TOrgBasic = z.infer<typeof orgBasicSchema>;
+
+/** Root org with accessible sub-orgs (basic info only) */
+export type TOrgWithSubOrgs = TOrgBasic & {
+ createdAt: Date;
+ subOrganizations: TOrgBasic[];
+};
+
+/** Zod schema for API response: org with sub-orgs */
+export const orgWithSubOrgsSchema = orgBasicSchema.extend({
+ createdAt: z.date(),
+ subOrganizations: z.array(orgBasicSchema)
+});
+
export const sanitizedOrganizationSchema = OrganizationsSchema.pick({
id: true,
name: true,
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 3232fc18b8..75d0901486 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -60,6 +60,7 @@ import { TUserDALFactory } from "../user/user-dal";
import { TIncidentContactsDALFactory } from "./incident-contacts-dal";
import { TOrgDALFactory } from "./org-dal";
import { deleteOrgMembershipsFn } from "./org-fns";
+import { TOrgWithSubOrgs } from "./org-schema";
import {
TDeleteOrgMembershipDTO,
TDeleteOrgMembershipsDTO,
@@ -202,6 +203,10 @@ export const orgServiceFactory = ({
return orgs.filter((org) => org.userStatus !== "invited");
};
+ const findAllAcessibleOrganizationsWithSubOrgs = async (userId: string): Promise<TOrgWithSubOrgs[]> => {
+ return orgDAL.listOrganizationsWithSubOrgs({ actorId: userId, actorType: ActorType.USER });
+ };
+
/*
* Get all organization an identity is part of
* */
@@ -1293,6 +1298,7 @@ export const orgServiceFactory = ({
findAllWorkspaces,
addGhostUser,
updateOrgMembership,
+ findAllAcessibleOrganizationsWithSubOrgs,
// incident contacts
findIncidentContacts,
createIncidentContact,