Skip to content

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

fix(org): return 409 for the organization-limit refusal

Vlad Ligai85533349f8ce
diff --git a/backend/e2e-test/routes/v2/org-create-limit.spec.ts b/backend/e2e-test/routes/v2/org-create-limit.spec.ts
index f86a331b21..1665c325ec 100644
--- a/backend/e2e-test/routes/v2/org-create-limit.spec.ts
+++ b/backend/e2e-test/routes/v2/org-create-limit.spec.ts
@@ -1,55 +1,59 @@
import { AccessScope, OrgMembershipStatus, TableName, TOrganizationsInsert } from "@app/db/schemas";
import { seedData1 } from "@app/db/seed-data";
+import { getConfig, overrideEnvConfig } from "@app/lib/config/env";
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[] = [];
+// 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 track = (orgId: string) => {
+ createdOrgIds.push(orgId);
+ return orgId;
+};
+
+const createOrgRequest = (name: string) =>
+ testServer.inject({
+ method: "POST",
+ url: "/api/v2/organizations",
+ headers: { authorization: `Bearer ${jwtAuthToken}` },
+ body: { name }
+ });
+const createOrgOverHttp = async (name: string) => {
+ const res = await createOrgRequest(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);
+};
+
+const cleanupTrackedOrgs = async () => {
+ const ids = createdOrgIds.splice(0);
+ if (ids.length) await testDb(TableName.Organization).whereIn("id", ids).delete();
+};
+
+describe("Organizations counted against a user's create limit", () => {
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();
- });
+ afterEach(cleanupTrackedOrgs);
// 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 () => {
@@ -110,7 +114,6 @@ describe("Organizations counted against a user's create limit", () => {
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");
@@ -119,3 +122,49 @@ describe("Organizations counted against a user's create limit", () => {
await deleteOrgOverHttp(first);
});
});
+
+// The limit only engages on cloud, and this environment is not cloud. Re-parsing the env with the
+// license server key set is the only way to reach the refusal, so the suite would otherwise cover
+// everything around it and nothing that does the refusing. The flip reaches only code calling
+// getConfig() per request: instanceType and the license service's envConfig were both captured at
+// boot, so no license-server call becomes live.
+describe("The create-organization route on cloud", () => {
+ beforeAll(() => {
+ process.env.LICENSE_SERVER_V2_SERVICE_KEY = "e2e-cloud";
+ overrideEnvConfig({});
+ expect(getConfig().isCloud).toBe(true);
+ });
+
+ afterAll(async () => {
+ delete process.env.LICENSE_SERVER_V2_SERVICE_KEY;
+ overrideEnvConfig({});
+ expect(getConfig().isCloud).toBe(false);
+ await cleanupTrackedOrgs();
+ });
+
+ // Deleted straight from the database rather than over HTTP, since the delete route's cloud branch
+ // would reach a license server this environment does not run.
+ afterEach(cleanupTrackedOrgs);
+
+ test("a second org is refused with 409", async () => {
+ await createOrgOverHttp("org-limit-cloud-first");
+
+ const res = await createOrgRequest("org-limit-cloud-second");
+
+ expect(res.statusCode).toBe(409);
+ expect(res.json().message).toMatch(/already created an organization/);
+ });
+
+ test("concurrent creates land exactly one org", async () => {
+ const results = await Promise.all([
+ createOrgRequest("org-limit-cloud-race-a"),
+ createOrgRequest("org-limit-cloud-race-b")
+ ]);
+
+ const statuses = results.map((res) => res.statusCode).sort();
+ expect(statuses).toEqual([200, 409]);
+
+ results.filter((res) => res.statusCode === 200).forEach((res) => track(res.json().organization.id as string));
+ await expect(countCreatedOrgs()).resolves.toBe(1);
+ });
+});
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 9568eb9da9..d667e6abf3 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -36,7 +36,13 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
import { applyJitter } from "@app/lib/dates";
import { delay as delayMs } from "@app/lib/delay";
-import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
+import {
+ BadRequestError,
+ ConflictError,
+ ForbiddenRequestError,
+ NotFoundError,
+ UnauthorizedError
+} from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
@@ -701,8 +707,9 @@ export const orgServiceFactory = ({
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."
+ throw new ConflictError({
+ message:
+ "You have already created an organization. Ask an administrator of an existing organization to invite you."
});
}
}