Skip to content

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

fix(org): limit users to one self-created organization

Vlad Ligai741abca412d9
diff --git a/backend/e2e-test/routes/v2/org-create-limit.spec.ts b/backend/e2e-test/routes/v2/org-create-limit.spec.ts
new file mode 100644
index 0000000000..f86a331b21
--- /dev/null
+++ b/backend/e2e-test/routes/v2/org-create-limit.spec.ts
@@ -0,0 +1,121 @@
+import { AccessScope, OrgMembershipStatus, TableName, TOrganizationsInsert } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { orgDALFactory } from "@app/services/org/org-dal";
+
+import { loginUser, selectOrg } from "../../testUtils/auth";
+
+// The route opts in only on cloud and this environment is not cloud, so the refusal itself cannot be
+// driven over HTTP here. What decides it is the count, which is tested directly.
+const orgDAL = orgDALFactory(testDb);
+
+const countCreatedOrgs = () => orgDAL.countJoinedRootOrgsCreatedByUserId(seedData1.id, testDb);
+
+describe("Organizations counted against a user's create limit", () => {
+ // Anything left behind would carry into the next test's count and blame the wrong one.
+ const createdOrgIds: string[] = [];
+
+ const track = (orgId: string) => {
+ createdOrgIds.push(orgId);
+ return orgId;
+ };
+
+ const insertOrg = async (fields: TOrganizationsInsert) => {
+ const [org] = await testDb(TableName.Organization).insert(fields).returning("*");
+ return track(org.id);
+ };
+
+ const createOrgOverHttp = async (name: string) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: "/api/v2/organizations",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: { name }
+ });
+ expect(res.statusCode).toBe(200);
+ return track(res.json().organization.id as string);
+ };
+
+ const deleteOrgOverHttp = async (orgId: string) => {
+ const { accessToken } = await loginUser(seedData1.email, seedData1.password);
+ const { payload } = await selectOrg(accessToken, orgId);
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/organizations/${orgId}`,
+ headers: { authorization: `Bearer ${payload.token}` }
+ });
+ expect(res.statusCode).toBe(200);
+ };
+
+ afterEach(async () => {
+ const ids = createdOrgIds.splice(0);
+ if (ids.length) await testDb(TableName.Organization).whereIn("id", ids).delete();
+ });
+
+ // The seeded org carries no createdByUserId, the shape every org predating the column has.
+ test("an org the user only belongs to does not count", async () => {
+ await expect(countCreatedOrgs()).resolves.toBe(0);
+ });
+
+ test("an org the user created counts until it is deleted", async () => {
+ const orgId = await createOrgOverHttp("org-limit-created");
+
+ await expect(countCreatedOrgs()).resolves.toBe(1);
+
+ await deleteOrgOverHttp(orgId);
+ await expect(countCreatedOrgs()).resolves.toBe(0);
+ });
+
+ test("an org the user created but does not belong to does not count", async () => {
+ await insertOrg({ name: "org-limit-orphan", slug: "org-limit-orphan", createdByUserId: seedData1.id });
+
+ await expect(countCreatedOrgs()).resolves.toBe(0);
+ });
+
+ // SCIM sets isActive from the IdP's active flag without touching status, so a deactivated creator
+ // would otherwise hold a slot in an org they cannot use.
+ test("an org the user is deactivated in does not count", async () => {
+ const orgId = await insertOrg({
+ name: "org-limit-deactivated",
+ slug: "org-limit-deactivated",
+ createdByUserId: seedData1.id
+ });
+ await testDb(TableName.Membership).insert({
+ scope: AccessScope.Organization,
+ scopeOrgId: orgId,
+ actorUserId: seedData1.id,
+ isActive: false,
+ status: OrgMembershipStatus.Accepted
+ });
+
+ await expect(countCreatedOrgs()).resolves.toBe(0);
+ });
+
+ test("a sub-org does not count", async () => {
+ const rootId = await insertOrg({ name: "org-limit-root", slug: "org-limit-root" });
+ const subId = await insertOrg({
+ name: "org-limit-sub",
+ slug: "org-limit-sub",
+ rootOrgId: rootId,
+ parentOrgId: rootId,
+ createdByUserId: seedData1.id
+ });
+ await testDb(TableName.Membership).insert({
+ scope: AccessScope.Organization,
+ scopeOrgId: subId,
+ actorUserId: seedData1.id,
+ isActive: true,
+ status: OrgMembershipStatus.Accepted
+ });
+
+ await expect(countCreatedOrgs()).resolves.toBe(0);
+ });
+
+ // Regression guard for the cloud gate: self-hosted keeps unlimited creates.
+ test("the route does not refuse a second org off cloud", async () => {
+ const first = await createOrgOverHttp("org-limit-off-cloud-first");
+ const second = await createOrgOverHttp("org-limit-off-cloud-second");
+
+ await deleteOrgOverHttp(second);
+ await deleteOrgOverHttp(first);
+ });
+});
diff --git a/backend/e2e-test/testUtils/fixtures.ts b/backend/e2e-test/testUtils/fixtures.ts
index 8ed20c9281..fe5b561601 100644
--- a/backend/e2e-test/testUtils/fixtures.ts
+++ b/backend/e2e-test/testUtils/fixtures.ts
@@ -37,12 +37,15 @@ export const createIsolatedOrgAndProject = async (namePrefix: string) => {
// Hard-deletes the org row; every project/environment/secret/webhook underneath it is reaped by
// FK cascade (org-service.ts:deleteOrganizationById), so there's nothing else to tear down.
+ // Asserted so a silent cleanup failure surfaces here rather than as leaked org-scoped state in a
+ // later suite.
const cleanup = async () => {
- await testServer.inject({
+ const deleteRes = await testServer.inject({
method: "DELETE",
url: `/api/v2/organizations/${orgId}`,
headers: { authorization: `Bearer ${authToken}` }
});
+ expect(deleteRes.statusCode).toBe(200);
};
return { orgId, projectId, authToken, cleanup };
diff --git a/backend/src/db/migrations/20260918230000_add-org-created-by-user-id.ts b/backend/src/db/migrations/20260918230000_add-org-created-by-user-id.ts
new file mode 100644
index 0000000000..803c3b3751
--- /dev/null
+++ b/backend/src/db/migrations/20260918230000_add-org-created-by-user-id.ts
@@ -0,0 +1,28 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasColumn = await knex.schema.hasColumn(TableName.Organization, "createdByUserId");
+ if (!hasColumn) {
+ await knex.schema.alterTable(TableName.Organization, (t) => {
+ // Null for organizations that predate this column, and for orgs created from the admin panel
+ // (super-admin-service createOrganization passes no user), so neither counts against anyone's
+ // create limit. Instance bootstrap does pass the admin's id, so that org is attributed to them.
+ // Not backfilled: the nearest proxy for an existing org's creator is its oldest admin, which
+ // mis-attributes any org whose creator has left and would lock that admin out of creating one.
+ t.uuid("createdByUserId").nullable();
+ t.foreign("createdByUserId").references("id").inTable(TableName.Users).onDelete("SET NULL");
+ t.index("createdByUserId");
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasColumn = await knex.schema.hasColumn(TableName.Organization, "createdByUserId");
+ if (hasColumn) {
+ await knex.schema.alterTable(TableName.Organization, (t) => {
+ t.dropColumn("createdByUserId");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/organizations.ts b/backend/src/db/schemas/organizations.ts
index 54afbf3beb..d516635f42 100644
--- a/backend/src/db/schemas/organizations.ts
+++ b/backend/src/db/schemas/organizations.ts
@@ -43,7 +43,8 @@ export const OrganizationsSchema = z.object({
blockDuplicateSecretSyncDestinations: z.boolean().default(false),
secretShareBrandConfig: z.unknown().nullable().optional(),
defaultCertManagerProjectId: z.string().nullable().optional(),
- allowCrossProjectSecretSharing: z.boolean().default(false)
+ allowCrossProjectSecretSharing: z.boolean().default(false),
+ createdByUserId: z.string().uuid().nullable().optional()
});
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index 5b295b7bfe..75b2f4647f 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -19,6 +19,7 @@ export const PgSqlLock = {
EmailDomainCreationLock: () => pgAdvisoryLockHashText(`org-email-domain-creation`),
SecretRotationV2Creation: (folderId: string) => pgAdvisoryLockHashText(`secret-rotation-v2-creation:${folderId}`),
CreateProject: (orgId: string) => pgAdvisoryLockHashText(`create-project:${orgId}`),
+ CreateOrganization: (userId: string) => pgAdvisoryLockHashText(`create-organization:${userId}`),
CreateFolder: (envId: string, projectId: string) => pgAdvisoryLockHashText(`create-folder:${envId}-${projectId}`),
InstanceRelayConfigInit: () => pgAdvisoryLockHashText("instance-relay-config-init"),
OrgGatewayV2Init: (orgId: string) => pgAdvisoryLockHashText(`org-gateway-v2-init:${orgId}`),
diff --git a/backend/src/server/routes/v2/organization-router.ts b/backend/src/server/routes/v2/organization-router.ts
index 3d5fe647f9..2791c2bdef 100644
--- a/backend/src/server/routes/v2/organization-router.ts
+++ b/backend/src/server/routes/v2/organization-router.ts
@@ -473,9 +473,13 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
if (req.auth.actor !== ActorType.USER) return;
+ // Cloud only: the limit targets signup spam, and self-hosted keeps the old behavior.
+ const appCfg = getConfig();
+
const organization = await server.services.org.createOrganization({
userId: req.permission.id,
- orgName: req.body.name
+ orgName: req.body.name,
+ blockIfUserHasCreatedOrg: appCfg.isCloud
});
void server.services.telemetry.sendPostHogEvents({
diff --git a/backend/src/services/org/org-dal.ts b/backend/src/services/org/org-dal.ts
index 94e7df66ce..a198994449 100644
--- a/backend/src/services/org/org-dal.ts
+++ b/backend/src/services/org/org-dal.ts
@@ -465,6 +465,36 @@ export const orgDALFactory = (db: TDbClient) => {
}
};
+ // Root orgs this user created and still belongs to. Orgs they were only invited into never count,
+ // so joining any number of organizations stays unrestricted. An org they created but were since
+ // removed from, or deactivated in, does not count either: it is no longer theirs to use, and
+ // counting it would leave them unable to create one anywhere. Sub-orgs are excluded, they are the
+ // supported way to add more. Takes the transaction rather than an optional one so the read cannot land on a replica,
+ // where lag would let a second create pass the check the advisory lock exists to serialize.
+ const countJoinedRootOrgsCreatedByUserId = async (userId: string, tx: Knex) => {
+ try {
+ const count = await tx(TableName.Organization)
+ .where(`${TableName.Organization}.createdByUserId`, userId)
+ .whereNull(`${TableName.Organization}.rootOrgId`)
+ .whereExists((qb) => {
+ void qb
+ .select(tx.raw("1"))
+ .from(TableName.Membership)
+ .where(`${TableName.Membership}.actorUserId`, userId)
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .where(`${TableName.Membership}.status`, OrgMembershipStatus.Accepted)
+ .where(`${TableName.Membership}.isActive`, true)
+ .whereRaw(`"${TableName.Membership}"."scopeOrgId" = "${TableName.Organization}"."id"`);
+ })
+ .count("*", { as: "count" })
+ .first();
+
+ return Number((count as unknown as CountResult)?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count joined root orgs created by user id" });
+ }
+ };
+
const findOrgByProjectId = async (projectId: string): Promise<TOrganizations> => {
try {
const [org] = await db
@@ -1141,6 +1171,7 @@ export const orgDALFactory = (db: TDbClient) => {
findOrgById,
findOrgBySlug,
findAllOrgsByUserId,
+ countJoinedRootOrgsCreatedByUserId,
findOrganizationsByFilter,
findOrgMembersByUsername,
findOrgMembersByRole,
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 7bf1c1d059..9568eb9da9 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -30,6 +30,7 @@ import {
import { assertRoleSetBoundary } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { TSamlConfigDALFactory } from "@app/ee/services/saml-config/saml-config-dal";
+import { PgSqlLock } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
@@ -681,16 +682,36 @@ export const orgServiceFactory = ({
const createOrganization = async (
{
userId,
- orgName
+ orgName,
+ blockIfUserHasCreatedOrg
}: {
userId?: string;
orgName: string;
+ // Set by the user-facing create-org endpoint, and only on cloud. Signup and instance-admin
+ // creation call this without it and keep their existing behavior.
+ blockIfUserHasCreatedOrg?: boolean;
},
trx?: Knex
) => {
const createOrg = async (tx: Knex) => {
+ // The advisory lock serializes concurrent creates for the same user so two requests cannot both
+ // read a count of zero and each land an org.
+ if (blockIfUserHasCreatedOrg && userId) {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateOrganization(userId)]);
+
+ const createdOrgs = await orgDAL.countJoinedRootOrgsCreatedByUserId(userId, tx);
+ if (createdOrgs > 0) {
+ throw new BadRequestError({
+ message: "You have already created an organization. Contact your administrator to be added to another one."
+ });
+ }
+ }
+
// akhilmhdh: for now this is auto created. in future we can input from user and for previous users just modifiy
- const org = await orgDAL.create({ name: orgName, slug: slugify(`${orgName}-${alphaNumericNanoId(4)}`) }, tx);
+ const org = await orgDAL.create(
+ { name: orgName, slug: slugify(`${orgName}-${alphaNumericNanoId(4)}`), createdByUserId: userId },
+ tx
+ );
if (userId) {
const membership = await orgDAL.createMembership(
{