Skip to content

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

fix: org-scoping, race conditions, pool limit, query invalidation

bernie-gedc64da7e71e
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
index 397d3e0dda..118b294293 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-dal.ts
@@ -1,3 +1,5 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
@@ -52,9 +54,13 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
}
};
- const findByIdWithMembers = async (poolId: string) => {
+ const findByIdWithMembers = async (poolId: string, orgId: string) => {
try {
- const pool = await db.replicaNode()(TableName.GatewayPool).where(`${TableName.GatewayPool}.id`, poolId).first();
+ const pool = await db
+ .replicaNode()(TableName.GatewayPool)
+ .where(`${TableName.GatewayPool}.id`, poolId)
+ .where(`${TableName.GatewayPool}.orgId`, orgId)
+ .first();
if (!pool) return null;
@@ -75,5 +81,14 @@ export const gatewayPoolDalFactory = (db: TDbClient) => {
}
};
- return { ...orm, findByOrgIdWithDetails, findByIdWithMembers };
+ const countByOrgId = async (orgId: string, tx?: Knex) => {
+ try {
+ const result = await (tx || db.replicaNode())(TableName.GatewayPool).where({ orgId }).count("id").first();
+ return parseInt(String(result?.count || "0"), 10);
+ } catch (error) {
+ throw new DatabaseError({ error, name: `${TableName.GatewayPool}: CountByOrgId` });
+ }
+ };
+
+ return { ...orm, findByOrgIdWithDetails, findByIdWithMembers, countByOrgId };
};
diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
index a6660dc1b7..23fdfbfd47 100644
--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts
@@ -1,10 +1,14 @@
import { ForbiddenError } from "@casl/ability";
import { OrganizationActionScope } from "@app/db/schemas";
+import { PgSqlLock } from "@app/keystore/keystore";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
+
+// Temporary limit until pool limiting is implemented at the plan level
+const MAX_GATEWAY_POOLS_PER_ORG = 50;
import { TIdentityKubernetesAuthDALFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-dal";
import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";
@@ -72,21 +76,32 @@ export const gatewayPoolServiceFactory = ({
await $checkPermission(actor, OrgPermissionGatewayPoolActions.CreateGatewayPools);
await $checkLicense(actor.orgId);
- try {
- const pool = await gatewayPoolDAL.create({
- orgId: actor.orgId,
- name
- });
- return pool;
- } catch (error) {
- if (
- error instanceof DatabaseError &&
- (error as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
- ) {
- throw new BadRequestError({ message: `A gateway pool named "${name}" already exists in this organization.` });
+ const pool = await gatewayPoolDAL.transaction(async (tx) => {
+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateGatewayPool(actor.orgId)]);
+
+ const existingCount = await gatewayPoolDAL.countByOrgId(actor.orgId, tx);
+ if (existingCount >= MAX_GATEWAY_POOLS_PER_ORG) {
+ throw new BadRequestError({
+ message: `Organization has reached the maximum limit of ${MAX_GATEWAY_POOLS_PER_ORG} gateway pools`
+ });
}
- throw error;
- }
+
+ try {
+ return await gatewayPoolDAL.create({ orgId: actor.orgId, name }, tx);
+ } catch (error) {
+ if (
+ error instanceof DatabaseError &&
+ (error as DatabaseError & { code?: string }).code === DatabaseErrorCode.UniqueViolation
+ ) {
+ throw new BadRequestError({
+ message: `A gateway pool named "${name}" already exists in this organization.`
+ });
+ }
+ throw error;
+ }
+ });
+
+ return pool;
};
const listGatewayPools = async (actor: TListGatewayPoolsDTO) => {
@@ -110,8 +125,8 @@ export const gatewayPoolServiceFactory = ({
await $checkPermission(actor, OrgPermissionGatewayPoolActions.ListGatewayPools);
await $checkLicense(actor.orgId);
- const pool = await gatewayPoolDAL.findByIdWithMembers(poolId);
- if (!pool || pool.orgId !== actor.orgId) {
+ const pool = await gatewayPoolDAL.findByIdWithMembers(poolId, actor.orgId);
+ if (!pool) {
throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });
}
@@ -152,16 +167,20 @@ export const gatewayPoolServiceFactory = ({
throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });
}
- // Check for referencing consumer configs (add more DAL counts here as pool support expands)
- const k8sAuthCount = await identityKubernetesAuthDAL.countByGatewayPoolId(poolId);
- const totalReferences = k8sAuthCount;
- if (totalReferences > 0) {
- throw new BadRequestError({
- message: `Cannot delete pool "${existingPool.name}" because it is referenced by ${totalReferences} consumer configuration(s). Remove the pool reference from those configs first.`
- });
- }
+ await gatewayPoolDAL.transaction(async (tx) => {
+ // Check for referencing consumer configs inside transaction to prevent race conditions
+ // Add more DAL counts here as pool support expands
+ const k8sAuthCount = await identityKubernetesAuthDAL.countByGatewayPoolId(poolId, tx);
+ const totalReferences = k8sAuthCount;
+ if (totalReferences > 0) {
+ throw new BadRequestError({
+ message: `Cannot delete pool "${existingPool.name}" because it is referenced by ${totalReferences} consumer configuration(s). Remove the pool reference from those configs first.`
+ });
+ }
+
+ await gatewayPoolDAL.deleteById(poolId, tx);
+ });
- await gatewayPoolDAL.deleteById(poolId);
return existingPool;
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index a640b1ddde..de08aecbc2 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -32,6 +32,7 @@ export const PgSqlLock = {
PamResourceSshCaInit: (resourceId: string) => pgAdvisoryLockHashText(`pam-resource-ssh-ca-init:${resourceId}`),
CreateIdentity: (orgId: string) => pgAdvisoryLockHashText(`create-identity:${orgId}`),
CreateGateway: (orgId: string) => pgAdvisoryLockHashText(`create-gateway:${orgId}`),
+ CreateGatewayPool: (orgId: string) => pgAdvisoryLockHashText(`create-gateway-pool:${orgId}`),
AccessSharedSecret: (sharedSecretId: string) => pgAdvisoryLockHashText(`access-shared-secret:${sharedSecretId}`),
KmsOrgKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-key:${orgId}`),
KmsOrgDataKeyCreation: (orgId: string) => pgAdvisoryLockHashText(`kms-org-data-key:${orgId}`),
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 072310fcaa..99eb708046 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1973,7 +1973,8 @@ export const registerRoutes = async (
gatewayDAL,
kmsService,
membershipIdentityDAL,
- gatewayPoolService
+ gatewayPoolService,
+ gatewayPoolDAL
});
const identityGcpAuthService = identityGcpAuthServiceFactory({
identityDAL,
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 877caffba1..73e902cfa5 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -14,6 +14,7 @@ import {
} from "@app/db/schemas";
import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
+import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -89,7 +90,11 @@ type TIdentityKubernetesAuthServiceFactoryDep = {
gatewayV2Service: TGatewayV2ServiceFactory;
gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "getPlatformConnectionDetailsByPoolId" | "pickRandomHealthyGateway">;
+ gatewayPoolService: Pick<
+ TGatewayPoolServiceFactory,
+ "getPlatformConnectionDetailsByPoolId" | "pickRandomHealthyGateway"
+ >;
+ gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
orgDAL: Pick<TOrgDALFactory, "findById" | "findOne" | "findEffectiveOrgMembership">;
};
@@ -110,6 +115,7 @@ export const identityKubernetesAuthServiceFactory = ({
gatewayV2DAL,
kmsService,
gatewayPoolService,
+ gatewayPoolDAL,
orgDAL
}: TIdentityKubernetesAuthServiceFactoryDep) => {
const $gatewayProxyWrapper = async <T>(
@@ -889,6 +895,11 @@ export const identityKubernetesAuthServiceFactory = ({
OrgPermissionSubjects.GatewayPool
);
+ const pool = await gatewayPoolDAL.findById(gatewayPoolId);
+ if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
+ throw new NotFoundError({ message: `Gateway pool with ID ${gatewayPoolId} not found` });
+ }
+
// Validate connectivity through a random healthy pool member
const validationGateway = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);
if (tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
@@ -1112,6 +1123,11 @@ export const identityKubernetesAuthServiceFactory = ({
OrgPermissionGatewayPoolActions.AttachGatewayPools,
OrgPermissionSubjects.GatewayPool
);
+
+ const pool = await gatewayPoolDAL.findById(gatewayPoolId);
+ if (!pool || pool.orgId !== identityMembershipOrg.scopeOrgId) {
+ throw new NotFoundError({ message: `Gateway pool with ID ${gatewayPoolId} not found` });
+ }
}
// Strict check to see if gateway ID is undefined. It should update the gateway ID to null if its strictly set to null.
diff --git a/frontend/src/hooks/api/identities/mutations.tsx b/frontend/src/hooks/api/identities/mutations.tsx
index 8e475e61f7..f815823da2 100644
--- a/frontend/src/hooks/api/identities/mutations.tsx
+++ b/frontend/src/hooks/api/identities/mutations.tsx
@@ -1456,7 +1456,10 @@ export const useAddIdentityKubernetesAuth = () => {
});
}
queryClient.invalidateQueries({ queryKey: identitiesKeys.getIdentityById(identityId) });
- queryClient.invalidateQueries({ queryKey: identitiesKeys.getIdentityAzureAuth(identityId) });
+ queryClient.invalidateQueries({
+ queryKey: identitiesKeys.getIdentityKubernetesAuth(identityId)
+ });
+ queryClient.invalidateQueries({ queryKey: gatewayPoolsKeys.allKey() });
}
});
};