Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: add gateway pool support across remaining platform areas (#6285)
Saif Ur Rahmanad566aa280cd
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex bdfcfe4f01..51e37eefdf 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -2491,6 +2491,7 @@"integrity": "sha512-vMqyb7XCDMPvJFFOaT9kxtiRh42GwlZEg1/uIgtZshS5a/8OaduUfCi7kynKgc3Tw/6Uo2D+db9qBttghhmxwQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@ampproject/remapping": "^2.2.0","@babel/code-frame": "^7.26.2",@@ -4549,6 +4550,7 @@"url": "https://opencollective.com/csstools"}],+ "peer": true,"engines": {"node": ">=18"},@@ -4570,6 +4572,7 @@"url": "https://opencollective.com/csstools"}],+ "peer": true,"engines": {"node": ">=18"}@@ -7154,6 +7157,7 @@"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz","integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}@@ -8072,6 +8076,7 @@"resolved": "https://registry.npmjs.org/@octokit/core/-/core-5.2.1.tgz","integrity": "sha512-dKYCMuPO1bmrpuogcjQ8z7ICCH3FP6WmxpwC03yjzGfZhj9fTJg6+bS1+UAplekbN2C+M61UNllGOOoAfGCrdQ==","license": "MIT",+ "peer": true,"dependencies": {"@octokit/auth-token": "^4.0.0","@octokit/graphql": "^7.1.0",@@ -8627,6 +8632,7 @@"version": "1.9.0","resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz","integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",+ "peer": true,"engines": {"node": ">=8.0.0"}@@ -9299,6 +9305,7 @@"resolved": "https://registry.npmjs.org/@react-email/body/-/body-0.2.0.tgz","integrity": "sha512-9GCWmVmKUAoRfloboCd+RKm6X17xn7eGL7HnpAZUnjBXBilWCxsKnLMTC/ixSHDKS/A/057M1Tx6ZUXd89sVBw==","license": "MIT",+ "peer": true,"peerDependencies": {"react": "^18.0 || ^19.0 || ^19.0.0-rc"}@@ -9308,6 +9315,7 @@"resolved": "https://registry.npmjs.org/@react-email/button/-/button-0.2.0.tgz","integrity": "sha512-8i+v6cMxr2emz4ihCrRiYJPp2/sdYsNNsBzXStlcA+/B9Umpm5Jj3WJKYpgTPM+aeyiqlG/MMI1AucnBm4f1oQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9320,6 +9328,7 @@"resolved": "https://registry.npmjs.org/@react-email/code-block/-/code-block-0.2.0.tgz","integrity": "sha512-eIrPW9PIFgDopQU0e/OPpwCW2QWQDtNZDSsiN4sJO8KdMnWWnXJicnRfzrit5rHwFo+Y98i+w/Y5ScnBAFr1dQ==","license": "MIT",+ "peer": true,"dependencies": {"prismjs": "^1.30.0"},@@ -9335,6 +9344,7 @@"resolved": "https://registry.npmjs.org/@react-email/code-inline/-/code-inline-0.0.5.tgz","integrity": "sha512-MmAsOzdJpzsnY2cZoPHFPk6uDO/Ncpb4Kh1hAt9UZc1xOW3fIzpe1Pi9y9p6wwUmpaeeDalJxAxH6/fnTquinA==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9410,6 +9420,7 @@"resolved": "https://registry.npmjs.org/@react-email/container/-/container-0.0.15.tgz","integrity": "sha512-Qo2IQo0ru2kZq47REmHW3iXjAQaKu4tpeq/M8m1zHIVwKduL2vYOBQWbC2oDnMtWPmkBjej6XxgtZByxM6cCFg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9443,6 +9454,7 @@"resolved": "https://registry.npmjs.org/@react-email/heading/-/heading-0.0.15.tgz","integrity": "sha512-xF2GqsvBrp/HbRHWEfOgSfRFX+Q8I5KBEIG5+Lv3Vb2R/NYr0s8A5JhHHGf2pWBMJdbP4B2WHgj/VUrhy8dkIg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9455,6 +9467,7 @@"resolved": "https://registry.npmjs.org/@react-email/hr/-/hr-0.0.11.tgz","integrity": "sha512-S1gZHVhwOsd1Iad5IFhpfICwNPMGPJidG/Uysy1AwmspyoAP5a4Iw3OWEpINFdgh9MHladbxcLKO2AJO+cA9Lw==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9479,6 +9492,7 @@"resolved": "https://registry.npmjs.org/@react-email/img/-/img-0.0.11.tgz","integrity": "sha512-aGc8Y6U5C3igoMaqAJKsCpkbm1XjguQ09Acd+YcTKwjnC2+0w3yGUJkjWB2vTx4tN8dCqQCXO8FmdJpMfOA9EQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9491,6 +9505,7 @@"resolved": "https://registry.npmjs.org/@react-email/link/-/link-0.0.12.tgz","integrity": "sha512-vF+xxQk2fGS1CN7UPQDbzvcBGfffr+GjTPNiWM38fhBfsLv6A/YUfaqxWlmL7zLzVmo0K2cvvV9wxlSyNba1aQ==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -9518,6 +9533,7 @@"resolved": "https://registry.npmjs.org/@react-email/preview/-/preview-0.0.13.tgz","integrity": "sha512-F7j9FJ0JN/A4d7yr+aw28p4uX7VLWs7hTHtLo7WRyw4G+Lit6Zucq4UWKRxJC8lpsUdzVmG7aBJnKOT+urqs/w==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -10090,6 +10106,7 @@"resolved": "https://registry.npmjs.org/@react-email/text/-/text-0.1.5.tgz","integrity": "sha512-o5PNHFSE085VMXayxH+SJ1LSOtGsTv+RpNKnTiJDrJUwoBu77G3PlKOsZZQHCNyD28WsQpl9v2WcJLbQudqwPg==","license": "MIT",+ "peer": true,"engines": {"node": ">=18.0.0"},@@ -11710,6 +11727,7 @@"resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.17.tgz","integrity": "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q==","license": "MIT",+ "peer": true,"dependencies": {"undici-types": "~6.21.0"}@@ -12168,6 +12186,7 @@"integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==","dev": true,"license": "BSD-2-Clause",+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "6.21.0","@typescript-eslint/types": "6.21.0",@@ -12614,6 +12633,7 @@"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz","integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -13127,6 +13147,7 @@"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz","integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==","license": "MIT",+ "peer": true,"dependencies": {"bn.js": "^4.0.0","inherits": "^2.0.1",@@ -13247,6 +13268,7 @@"resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz","integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==","license": "MIT",+ "peer": true,"dependencies": {"follow-redirects": "^1.15.11","form-data": "^4.0.5",@@ -13853,6 +13875,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.8.9","caniuse-lite": "^1.0.30001746",@@ -15334,6 +15357,7 @@"version": "16.4.1","resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.1.tgz","integrity": "sha512-CjA3y+Dr3FyFDOAMnxZEGtnW9KBR2M0JvvUtXNW+dYJL5ROWxP9DUHCwgFqpMk0OXCc0ljhaNTr2w/kutYIcHQ==",+ "peer": true,"engines": {"node": ">=12"},@@ -15704,6 +15728,7 @@"dev": true,"hasInstallScript": true,"license": "MIT",+ "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -15786,6 +15811,7 @@"resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz","integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==","dev": true,+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.2.0","@eslint-community/regexpp": "^4.6.1",@@ -15884,6 +15910,7 @@"resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz","integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==","dev": true,+ "peer": true,"bin": {"eslint-config-prettier": "bin/cli.js"},@@ -15972,6 +15999,7 @@"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.29.1.tgz","integrity": "sha512-BbPC0cuExzhiMo4Ff1BTVwHpjjv28C5R+btTOGaCRC7UEz801up0JadwkeSk5Ued6TG34uaczuVuH6qyy5YUxw==","dev": true,+ "peer": true,"dependencies": {"array-includes": "^3.1.7","array.prototype.findlastindex": "^1.2.3",@@ -16384,6 +16412,7 @@"resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz","integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==","license": "MIT",+ "peer": true,"dependencies": {"accepts": "~1.3.8","array-flatten": "1.1.1",@@ -16457,7 +16486,6 @@"resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz","integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==","license": "MIT",- "peer": true,"dependencies": {"cookie": "~0.7.2","cookie-signature": "~1.0.7",@@ -16479,14 +16507,12 @@"node_modules/express-session/node_modules/cookie-signature": {"version": "1.0.7","resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz",- "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==",- "peer": true+ "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA=="},"node_modules/express-session/node_modules/debug": {"version": "2.6.9","resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz","integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==",- "peer": true,"dependencies": {"ms": "2.0.0"}@@ -16494,8 +16520,7 @@"node_modules/express-session/node_modules/ms": {"version": "2.0.0","resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",- "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",- "peer": true+ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="},"node_modules/express/node_modules/cookie-signature": {"version": "1.0.6",@@ -17983,6 +18008,7 @@"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.12.tgz","integrity": "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q==","license": "MIT",+ "peer": true,"engines": {"node": ">=16.9.0"}@@ -21306,7 +21332,6 @@"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz","integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==","license": "MIT",- "peer": true,"engines": {"node": ">= 0.8"}@@ -21945,6 +21970,7 @@"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-3.0.2.tgz","integrity": "sha512-cfDHL6LStTEKlNilboNtobT/kEa30PtAf2Q1OgszfrG/rpVl1xaFWT9ktfkS306GmHgmnad1Sw4wabhlvFtsTw==","license": "MIT",+ "peer": true,"engines": {"node": ">=10"},@@ -22287,6 +22313,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -22384,6 +22411,7 @@"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.5.3.tgz","integrity": "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==","license": "MIT",+ "peer": true,"bin": {"prettier": "bin/prettier.cjs"},@@ -22821,7 +22849,6 @@"version": "1.0.0","resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz","integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==",- "peer": true,"engines": {"node": ">= 0.8"}@@ -22925,6 +22952,7 @@"resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz","integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==","license": "MIT",+ "peer": true,"engines": {"node": ">=0.10.0"}@@ -22934,6 +22962,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz","integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==","license": "MIT",+ "peer": true,"dependencies": {"scheduler": "^0.26.0"},@@ -24650,6 +24679,7 @@"resolved": "https://registry.npmjs.org/socks/-/socks-2.8.4.tgz","integrity": "sha512-D3YaD0aRxR3mEcqnidIs7ReYJFVzWdd6fXJYUM8ixcQcJRGTka/b3saV0KflYhyVJXKhb947GndU35SxYNResQ==","license": "MIT",+ "peer": true,"dependencies": {"ip-address": "^9.0.5","smart-buffer": "^4.2.0"@@ -25974,6 +26004,7 @@"integrity": "sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "~0.25.0","get-tsconfig": "^4.7.5"@@ -26142,6 +26173,7 @@"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.2.tgz","integrity": "sha512-6l+RyNy7oAHDfxC4FzSJcz9vnjTKxrLpDG5M2Vu4SHRVNg6xzqZp6LYSR9zjqQTu8DU/f5xwxUdADOkbrIX2gQ==","dev": true,+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -26182,7 +26214,6 @@"version": "2.1.5","resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz","integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==",- "peer": true,"dependencies": {"random-bytes": "~1.0.0"},@@ -26451,6 +26482,7 @@"integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"esbuild": "^0.27.0","fdir": "^6.5.0",@@ -27863,6 +27895,7 @@"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz","integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==","license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/backend/src/db/migrations/20260501091201_add-gateway-pool-to-pki-discovery-configs.ts b/backend/src/db/migrations/20260501091201_add-gateway-pool-to-pki-discovery-configs.tsnew file mode 100644index 0000000000..64c35f51b9--- /dev/null+++ b/backend/src/db/migrations/20260501091201_add-gateway-pool-to-pki-discovery-configs.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PkiDiscoveryConfig, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PkiDiscoveryConfig, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PkiDiscoveryConfig, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PkiDiscoveryConfig, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501091732_add-gateway-pool-to-pam-domains.ts b/backend/src/db/migrations/20260501091732_add-gateway-pool-to-pam-domains.tsnew file mode 100644index 0000000000..603cb8c381--- /dev/null+++ b/backend/src/db/migrations/20260501091732_add-gateway-pool-to-pam-domains.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamDomain, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PamDomain, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamDomain, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PamDomain, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501092415_add-gateway-pool-to-pam-resources.ts b/backend/src/db/migrations/20260501092415_add-gateway-pool-to-pam-resources.tsnew file mode 100644index 0000000000..eb8b3094c9--- /dev/null+++ b/backend/src/db/migrations/20260501092415_add-gateway-pool-to-pam-resources.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamResource, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamResource, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PamResource, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501093048_add-gateway-pool-to-pam-discovery-sources.ts b/backend/src/db/migrations/20260501093048_add-gateway-pool-to-pam-discovery-sources.tsnew file mode 100644index 0000000000..2a63a2488b--- /dev/null+++ b/backend/src/db/migrations/20260501093048_add-gateway-pool-to-pam-discovery-sources.ts@@ -0,0 +1,27 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ // Loosen gatewayId to nullable so a row can reference a gateway pool instead.+ await knex.schema.alterTable(TableName.PamDiscoverySource, (t) => {+ t.uuid("gatewayId").nullable().alter();+ });++ const hasColumn = await knex.schema.hasColumn(TableName.PamDiscoverySource, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PamDiscoverySource, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamDiscoverySource, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PamDiscoverySource, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501093623_add-gateway-pool-to-app-connections.ts b/backend/src/db/migrations/20260501093623_add-gateway-pool-to-app-connections.tsnew file mode 100644index 0000000000..7eaaa66caf--- /dev/null+++ b/backend/src/db/migrations/20260501093623_add-gateway-pool-to-app-connections.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.AppConnection, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.AppConnection, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.AppConnection, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.AppConnection, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501094157_add-gateway-pool-to-dynamic-secrets.ts b/backend/src/db/migrations/20260501094157_add-gateway-pool-to-dynamic-secrets.tsnew file mode 100644index 0000000000..17ba6d7009--- /dev/null+++ b/backend/src/db/migrations/20260501094157_add-gateway-pool-to-dynamic-secrets.ts@@ -0,0 +1,22 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.DynamicSecret, "gatewayPoolId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.DynamicSecret, (t) => {+ t.uuid("gatewayPoolId").nullable();+ t.foreign("gatewayPoolId").references("id").inTable(TableName.GatewayPool).onDelete("RESTRICT");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.DynamicSecret, "gatewayPoolId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.DynamicSecret, (t) => {+ t.dropColumn("gatewayPoolId");+ });+ }+}diff --git a/backend/src/db/migrations/20260501094734_pin-gateway-to-pam-session.ts b/backend/src/db/migrations/20260501094734_pin-gateway-to-pam-session.tsnew file mode 100644index 0000000000..4faccc7d5e--- /dev/null+++ b/backend/src/db/migrations/20260501094734_pin-gateway-to-pam-session.ts@@ -0,0 +1,23 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++// Pin the resolved gateway to the session so pool-backed sessions use a stable gateway throughout their lifetime.+export async function up(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamSession, "gatewayId");+ if (!hasColumn) {+ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.uuid("gatewayId").nullable();+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("SET NULL");+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ const hasColumn = await knex.schema.hasColumn(TableName.PamSession, "gatewayId");+ if (hasColumn) {+ await knex.schema.alterTable(TableName.PamSession, (t) => {+ t.dropColumn("gatewayId");+ });+ }+}diff --git a/backend/src/db/schemas/app-connections.ts b/backend/src/db/schemas/app-connections.tsindex b379cfa2e0..221836a58d 100644--- a/backend/src/db/schemas/app-connections.ts+++ b/backend/src/db/schemas/app-connections.ts@@ -23,7 +23,8 @@ export const AppConnectionsSchema = z.object({isPlatformManagedCredentials: z.boolean().default(false).nullable().optional(),gatewayId: z.string().uuid().nullable().optional(),projectId: z.string().nullable().optional(),- isAutoRotationEnabled: z.boolean().default(false)+ isAutoRotationEnabled: z.boolean().default(false),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TAppConnections = z.infer<typeof AppConnectionsSchema>;diff --git a/backend/src/db/schemas/dynamic-secrets.ts b/backend/src/db/schemas/dynamic-secrets.tsindex 526239f1c0..73a8eea7d8 100644--- a/backend/src/db/schemas/dynamic-secrets.ts+++ b/backend/src/db/schemas/dynamic-secrets.ts@@ -30,7 +30,8 @@ export const DynamicSecretsSchema = z.object({projectGatewayId: z.string().uuid().nullable().optional(),gatewayId: z.string().uuid().nullable().optional(),usernameTemplate: z.string().nullable().optional(),- gatewayV2Id: z.string().uuid().nullable().optional()+ gatewayV2Id: z.string().uuid().nullable().optional(),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TDynamicSecrets = z.infer<typeof DynamicSecretsSchema>;diff --git a/backend/src/db/schemas/pam-discovery-sources.ts b/backend/src/db/schemas/pam-discovery-sources.tsindex d4d6e3bcf4..722b2a98d7 100644--- a/backend/src/db/schemas/pam-discovery-sources.ts+++ b/backend/src/db/schemas/pam-discovery-sources.ts@@ -14,14 +14,15 @@ export const PamDiscoverySourcesSchema = z.object({projectId: z.string(),name: z.string(),discoveryType: z.string(),- gatewayId: z.string().uuid(),+ gatewayId: z.string().uuid().nullable().optional(),encryptedDiscoveryCredentials: zodBuffer,discoveryConfiguration: z.unknown(),schedule: z.string().default("manual"),lastRunAt: z.date().nullable().optional(),status: z.string().default("active"),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TPamDiscoverySources = z.infer<typeof PamDiscoverySourcesSchema>;diff --git a/backend/src/db/schemas/pam-domains.ts b/backend/src/db/schemas/pam-domains.tsindex da1a63a99e..b4474119b5 100644--- a/backend/src/db/schemas/pam-domains.ts+++ b/backend/src/db/schemas/pam-domains.ts@@ -18,7 +18,8 @@ export const PamDomainsSchema = z.object({encryptedConnectionDetails: zodBuffer,discoveryFingerprint: z.string().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TPamDomains = z.infer<typeof PamDomainsSchema>;diff --git a/backend/src/db/schemas/pam-resources.ts b/backend/src/db/schemas/pam-resources.tsindex 0e03fcc83f..caedb1de73 100644--- a/backend/src/db/schemas/pam-resources.ts+++ b/backend/src/db/schemas/pam-resources.ts@@ -22,7 +22,8 @@ export const PamResourcesSchema = z.object({encryptedResourceMetadata: zodBuffer.nullable().optional(),discoveryFingerprint: z.string().nullable().optional(),domainId: z.string().uuid().nullable().optional(),- encryptedSessionSummaryConfig: zodBuffer.nullable().optional()+ encryptedSessionSummaryConfig: zodBuffer.nullable().optional(),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TPamResources = z.infer<typeof PamResourcesSchema>;diff --git a/backend/src/db/schemas/pam-sessions.ts b/backend/src/db/schemas/pam-sessions.tsindex 467da53393..230328fc54 100644--- a/backend/src/db/schemas/pam-sessions.ts+++ b/backend/src/db/schemas/pam-sessions.ts@@ -36,7 +36,8 @@ export const PamSessionsSchema = z.object({reason: z.string().nullable().optional(),selectedResourceId: z.string().uuid().nullable().optional(),encryptedSessionKey: zodBuffer.nullable().optional(),- gatewayUploadTokenHash: zodBuffer.nullable().optional()+ gatewayUploadTokenHash: zodBuffer.nullable().optional(),+ gatewayId: z.string().uuid().nullable().optional()});export type TPamSessions = z.infer<typeof PamSessionsSchema>;diff --git a/backend/src/db/schemas/pki-discovery-configs.ts b/backend/src/db/schemas/pki-discovery-configs.tsindex 9c48882aad..1f8a93b7c1 100644--- a/backend/src/db/schemas/pki-discovery-configs.ts+++ b/backend/src/db/schemas/pki-discovery-configs.ts@@ -23,7 +23,8 @@ export const PkiDiscoveryConfigsSchema = z.object({lastScanMessage: z.string().nullable().optional(),lastScannedAt: z.date().nullable().optional(),createdAt: z.date(),- updatedAt: z.date()+ updatedAt: z.date(),+ gatewayPoolId: z.string().uuid().nullable().optional()});export type TPkiDiscoveryConfigs = z.infer<typeof PkiDiscoveryConfigsSchema>;diff --git a/backend/src/ee/routes/v1/gateway-pool-router.ts b/backend/src/ee/routes/v1/gateway-pool-router.tsindex 2995f29fc3..bf1deeda48 100644--- a/backend/src/ee/routes/v1/gateway-pool-router.ts+++ b/backend/src/ee/routes/v1/gateway-pool-router.ts@@ -298,6 +298,60 @@ export const registerGatewayPoolRouter = async (server: FastifyZodProvider) => {identityId: z.string(),identityName: z.string().nullable()})+ ),+ pkiDiscoveryConfigs: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ projectId: z.string(),+ projectName: z.string().nullable()+ })+ ),+ pamDomains: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ projectId: z.string(),+ projectName: z.string().nullable()+ })+ ),+ pamResources: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ projectId: z.string(),+ resourceType: z.string(),+ projectName: z.string().nullable()+ })+ ),+ pamDiscoverySources: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ projectId: z.string(),+ discoveryType: z.string(),+ projectName: z.string().nullable()+ })+ ),+ appConnections: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ app: z.string(),+ projectId: z.string().nullish(),+ projectName: z.string().nullable()+ })+ ),+ dynamicSecrets: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ type: z.string(),+ folderId: z.string(),+ projectId: z.string(),+ projectName: z.string(),+ environmentSlug: z.string()+ }))})}diff --git a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.tsindex 50531c2521..363ca23788 100644--- a/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts+++ b/backend/src/ee/routes/v1/pam-discovery-routers/pam-discovery-endpoints.ts@@ -29,14 +29,16 @@ export const registerPamDiscoveryEndpoints = <T extends TPamDiscoverySource>({discoveryConfiguration: T["discoveryConfiguration"];discoveryCredentials: T["discoveryCredentials"];schedule: T["schedule"];- gatewayId: T["gatewayId"];+ gatewayId?: string;+ gatewayPoolId?: string;}>;updateDiscoverySourceSchema: z.ZodType<{name?: T["name"];discoveryConfiguration?: T["discoveryConfiguration"];discoveryCredentials?: T["discoveryCredentials"];schedule?: T["schedule"];- gatewayId?: T["gatewayId"];+ gatewayId?: string;+ gatewayPoolId?: string;}>;discoveryResponseSchema: z.ZodTypeAny;discoveryRunResponseSchema: z.ZodTypeAny;diff --git a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts b/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.tsindex 54b6fbb61c..f2f2681b18 100644--- a/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts+++ b/backend/src/ee/routes/v1/pam-domain-routers/pam-domain-endpoints.ts@@ -22,12 +22,14 @@ export const registerPamDomainEndpoints = <T extends TPamDomain>({projectId: T["projectId"];connectionDetails: T["connectionDetails"];gatewayId?: string;+ gatewayPoolId?: string;name: T["name"];metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;}>;updateDomainSchema: z.ZodType<{connectionDetails?: T["connectionDetails"];gatewayId?: string;+ gatewayPoolId?: string;name?: T["name"];metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;}>;diff --git a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.tsindex 486a6a13ee..5cf77cae9f 100644--- a/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts+++ b/backend/src/ee/routes/v1/pam-resource-routers/pam-resource-endpoints.ts@@ -23,6 +23,7 @@ export const registerPamResourceEndpoints = <T extends TPamResource>({projectId: T["projectId"];connectionDetails: T["connectionDetails"];gatewayId?: T["gatewayId"];+ gatewayPoolId?: string;name: T["name"];rotationAccountCredentials?: T["rotationAccountCredentials"];metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;@@ -30,6 +31,7 @@ export const registerPamResourceEndpoints = <T extends TPamResource>({updateResourceSchema: z.ZodType<{connectionDetails?: T["connectionDetails"];gatewayId?: T["gatewayId"];+ gatewayPoolId?: string;name?: T["name"];rotationAccountCredentials?: T["rotationAccountCredentials"];metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.tsindex 3aed8c7536..91d2c28049 100644--- a/backend/src/ee/routes/v1/pki-discovery-router.ts+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts@@ -74,20 +74,31 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>tags: [ApiDocsTags.PkiDiscovery],operationId: "createPkiDiscovery",description: "Create a new PKI discovery configuration",- body: z.object({- projectId: z.string().describe("The ID of the project"),- name: slugSchema({ field: "Name", max: 100 }).describe("Name of the discovery configuration"),- description: z.string().max(500).optional().describe("Description of the discovery configuration"),- discoveryType: z- .nativeEnum(PkiDiscoveryType)- .optional()- .default(PkiDiscoveryType.Network)- .describe("Type of discovery scan"),- targetConfig: NetworkTargetConfigSchema.describe("Target configuration for discovery scans"),- isAutoScanEnabled: z.boolean().optional().default(false).describe("Enable automatic scheduled scans"),- scanIntervalDays: z.number().min(1).max(365).optional().describe("Interval in days between automatic scans"),- gatewayId: z.string().uuid().optional().describe("Gateway ID for scanning private networks")- }),+ body: z+ .object({+ projectId: z.string().describe("The ID of the project"),+ name: slugSchema({ field: "Name", max: 100 }).describe("Name of the discovery configuration"),+ description: z.string().max(500).optional().describe("Description of the discovery configuration"),+ discoveryType: z+ .nativeEnum(PkiDiscoveryType)+ .optional()+ .default(PkiDiscoveryType.Network)+ .describe("Type of discovery scan"),+ targetConfig: NetworkTargetConfigSchema.describe("Target configuration for discovery scans"),+ isAutoScanEnabled: z.boolean().optional().default(false).describe("Enable automatic scheduled scans"),+ scanIntervalDays: z.number().min(1).max(365).optional().describe("Interval in days between automatic scans"),+ gatewayId: z.string().uuid().optional().describe("Gateway ID for scanning private networks"),+ gatewayPoolId: z.string().uuid().optional().describe("Gateway pool ID for scanning private networks")+ })+ .superRefine((data, ctx) => {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayPoolId"],+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool"+ });+ }+ }),response: {200: PkiDiscoveryConfigsSchema}@@ -97,7 +108,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>req.body.targetConfig.ipRanges,req.body.targetConfig.ports,req.body.targetConfig.domains,- !!req.body.gatewayId+ !!req.body.gatewayId || !!req.body.gatewayPoolId);if (!validation.valid) {throw new BadRequestError({ message: validation.error || "Invalid target configuration" });@@ -112,6 +123,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>isAutoScanEnabled: req.body.isAutoScanEnabled,scanIntervalDays: req.body.scanIntervalDays,gatewayId: req.body.gatewayId,+ gatewayPoolId: req.body.gatewayPoolId,actor: req.permission.type,actorId: req.permission.id,actorAuthMethod: req.permission.authMethod,@@ -209,7 +221,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>response: {200: PkiDiscoveryConfigsSchema.extend({linkedInstallationsCount: z.number().optional(),- gatewayName: z.string().nullable().optional()+ gatewayName: z.string().nullable().optional(),+ gatewayPoolName: z.string().nullable().optional()})}},@@ -253,29 +266,47 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>params: z.object({discoveryId: z.string().uuid().describe("The ID of the discovery configuration")}),- body: z.object({- name: slugSchema({ field: "Name", max: 100 }).optional().describe("Name of the discovery configuration"),- description: z.string().max(500).optional().nullable().describe("Description of the discovery configuration"),- targetConfig: NetworkTargetConfigSchema.optional().describe("Target configuration for discovery scans"),- isAutoScanEnabled: z.boolean().optional().describe("Enable automatic scheduled scans"),- scanIntervalDays: z- .number()- .min(1)- .max(365)- .optional()- .nullable()- .describe("Interval in days between automatic scans"),- gatewayId: z.string().uuid().optional().nullable().describe("Gateway ID for scanning private networks"),- isActive: z.boolean().optional().describe("Whether the discovery configuration is active")- }),+ body: z+ .object({+ name: slugSchema({ field: "Name", max: 100 }).optional().describe("Name of the discovery configuration"),+ description: z.string().max(500).optional().nullable().describe("Description of the discovery configuration"),+ targetConfig: NetworkTargetConfigSchema.optional().describe("Target configuration for discovery scans"),+ isAutoScanEnabled: z.boolean().optional().describe("Enable automatic scheduled scans"),+ scanIntervalDays: z+ .number()+ .min(1)+ .max(365)+ .optional()+ .nullable()+ .describe("Interval in days between automatic scans"),+ gatewayId: z.string().uuid().optional().nullable().describe("Gateway ID for scanning private networks"),+ gatewayPoolId: z+ .string()+ .uuid()+ .optional()+ .nullable()+ .describe("Gateway pool ID for scanning private networks"),+ isActive: z.boolean().optional().describe("Whether the discovery configuration is active")+ })+ .superRefine((data, ctx) => {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayPoolId"],+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool"+ });+ }+ }),response: {200: PkiDiscoveryConfigsSchema}},handler: async (req) => {if (req.body.targetConfig) {- let hasGateway = req.body.gatewayId !== null && req.body.gatewayId !== undefined;- if (!hasGateway && req.body.gatewayId === undefined) {+ let hasGateway =+ (req.body.gatewayId !== null && req.body.gatewayId !== undefined) ||+ (req.body.gatewayPoolId !== null && req.body.gatewayPoolId !== undefined);+ if (!hasGateway && req.body.gatewayId === undefined && req.body.gatewayPoolId === undefined) {const existing = await server.services.pkiDiscovery.getDiscovery({discoveryId: req.params.discoveryId,actor: req.permission.type,@@ -283,7 +314,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>actorAuthMethod: req.permission.authMethod,actorOrgId: req.permission.orgId});- hasGateway = !!existing.gatewayId;+ hasGateway = !!existing.gatewayId || !!existing.gatewayPoolId;}const validation = validateTargetConfig(req.body.targetConfig.ipRanges,@@ -304,6 +335,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>isAutoScanEnabled: req.body.isAutoScanEnabled,scanIntervalDays: req.body.scanIntervalDays ?? undefined,gatewayId: req.body.gatewayId,+ gatewayPoolId: req.body.gatewayPoolId,isActive: req.body.isActive,actor: req.permission.type,actorId: req.permission.id,diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.tsindex 482bb85194..2e61577ed2 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-dal.ts@@ -48,6 +48,21 @@ export interface TDynamicSecretDALFactory extends Omit<TOrmify<TableName.Dynamic}>>;countByGatewayId: (gatewayId: string, tx?: Knex) => Promise<number>;+ findByGatewayPoolId: (+ gatewayPoolId: string,+ tx?: Knex+ ) => Promise<+ Array<{+ id: string;+ name: string;+ type: string;+ folderId: string;+ projectId: string;+ projectName: string;+ environmentSlug: string;+ }>+ >;+ countByGatewayPoolId: (gatewayPoolId: string, tx?: Knex) => Promise<number>;}export const dynamicSecretDALFactory = (db: TDbClient): TDynamicSecretDALFactory => {@@ -224,5 +239,42 @@ export const dynamicSecretDALFactory = (db: TDbClient): TDynamicSecretDALFactoryreturn parseInt(String(result?.count || "0"), 10);};- return { ...orm, listDynamicSecretsByFolderIds, findOne, findWithMetadata, findByGatewayId, countByGatewayId };+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.DynamicSecret)+ .join(TableName.SecretFolder, `${TableName.DynamicSecret}.folderId`, `${TableName.SecretFolder}.id`)+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.DynamicSecret}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.DynamicSecret),+ db.ref("name").withSchema(TableName.DynamicSecret),+ db.ref("type").withSchema(TableName.DynamicSecret),+ db.ref("folderId").withSchema(TableName.DynamicSecret),+ db.ref("projectId").withSchema(TableName.Environment),+ db.ref("name").withSchema(TableName.Project).as("projectName"),+ db.ref("slug").withSchema(TableName.Environment).as("environmentSlug")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.DynamicSecret)+ .where(`${TableName.DynamicSecret}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };++ return {+ ...orm,+ listDynamicSecretsByFolderIds,+ findOne,+ findWithMetadata,+ findByGatewayId,+ countByGatewayId,+ findByGatewayPoolId,+ countByGatewayPoolId+ };};diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.tsindex b0165ae7cb..d2a82429c6 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts@@ -20,6 +20,7 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-foldimport { TDynamicSecretLeaseDALFactory } from "../dynamic-secret-lease/dynamic-secret-lease-dal";import { TDynamicSecretLeaseQueueServiceFactory } from "../dynamic-secret-lease/dynamic-secret-lease-queue";import { TGatewayDALFactory } from "../gateway/gateway-dal";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";import { TDynamicSecretDALFactory } from "./dynamic-secret-dal";@@ -45,6 +46,7 @@ type TDynamicSecretServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;gatewayDAL: Pick<TGatewayDALFactory, "findOne" | "find">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne" | "find">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveAttachableGatewayFromPool">;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;};@@ -88,6 +90,7 @@ export const dynamicSecretServiceFactory = ({kmsService,gatewayDAL,gatewayV2DAL,+ gatewayPoolService,resourceMetadataDAL}: TDynamicSecretServiceFactoryDep): TDynamicSecretServiceFactory => {const create: TDynamicSecretServiceFactory["create"] = async ({@@ -149,8 +152,28 @@ export const dynamicSecretServiceFactory = ({const selectedProvider = dynamicSecretProviders[provider.type];const inputs = await selectedProvider.validateProviderInputs(provider.inputs, { projectId });+ if (+ inputs &&+ typeof inputs === "object" &&+ "gatewayId" in inputs &&+ inputs.gatewayId &&+ "gatewayPoolId" in inputs &&+ inputs.gatewayPoolId+ ) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+let selectedGatewayId: string | null = null;- if (inputs && typeof inputs === "object" && "gatewayId" in inputs && inputs.gatewayId) {+ let selectedGatewayPoolId: string | null = null;+ if (inputs && typeof inputs === "object" && "gatewayPoolId" in inputs && inputs.gatewayPoolId) {+ const gatewayPoolId = inputs.gatewayPoolId as string;+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actorOrgId,+ actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }+ });+ selectedGatewayPoolId = gatewayPoolId;+ } else if (inputs && typeof inputs === "object" && "gatewayId" in inputs && inputs.gatewayId) {const gatewayId = inputs.gatewayId as string;const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: actorOrgId });@@ -201,8 +224,9 @@ export const dynamicSecretServiceFactory = ({defaultTTL,folderId: folder.id,name,- gatewayId: isGatewayV1 ? selectedGatewayId : undefined,- gatewayV2Id: isGatewayV1 ? undefined : selectedGatewayId,+ gatewayId: !selectedGatewayPoolId && isGatewayV1 ? selectedGatewayId : undefined,+ gatewayV2Id: !selectedGatewayPoolId && !isGatewayV1 ? selectedGatewayId : undefined,+ gatewayPoolId: selectedGatewayPoolId ?? undefined,usernameTemplate},tx@@ -316,6 +340,23 @@ export const dynamicSecretServiceFactory = ({secretManagerDecryptor({ cipherTextBlob: dynamicSecretCfg.encryptedInput }).toString()) as object;const newInput = { ...decryptedStoredInput, ...(inputs || {}) };+ // Mutual exclusion: reject if both gateway fields are set+ if (+ inputs &&+ typeof inputs === "object" &&+ "gatewayId" in inputs &&+ inputs.gatewayId &&+ "gatewayPoolId" in inputs &&+ inputs.gatewayPoolId+ ) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+ if (inputs && typeof inputs === "object") {+ if ((inputs as Record<string, unknown>).gatewayId)+ (newInput as Record<string, unknown>).gatewayPoolId = undefined;+ else if ((inputs as Record<string, unknown>).gatewayPoolId)+ (newInput as Record<string, unknown>).gatewayId = undefined;+ }const oldInput = await selectedProvider.validateProviderInputs(decryptedStoredInput, { projectId });const updatedInput = await selectedProvider.validateProviderInputs(newInput, { projectId });@@ -336,9 +377,32 @@ export const dynamicSecretServiceFactory = ({});- let selectedGatewayId: string | null = null;- let isGatewayV1 = true;- if (updatedInput && typeof updatedInput === "object" && "gatewayId" in updatedInput && updatedInput?.gatewayId) {+ let selectedGatewayId: string | null = (newInput as Record<string, unknown>).gatewayId as string | null;+ let selectedGatewayPoolId: string | null = (newInput as Record<string, unknown>).gatewayPoolId as string | null;+ let isGatewayV1 = Boolean(dynamicSecretCfg.gatewayId);+ const hasGatewayFieldInInput =+ inputs && typeof inputs === "object" && ("gatewayId" in inputs || "gatewayPoolId" in inputs);+ if (+ inputs &&+ typeof inputs === "object" &&+ "gatewayPoolId" in inputs &&+ inputs.gatewayPoolId &&+ inputs.gatewayPoolId !== (decryptedStoredInput as Record<string, unknown>).gatewayPoolId+ ) {+ const { gatewayPoolId } = inputs;+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actorOrgId,+ actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }+ });+ selectedGatewayPoolId = gatewayPoolId;+ } else if (+ updatedInput &&+ typeof updatedInput === "object" &&+ "gatewayId" in updatedInput &&+ updatedInput?.gatewayId+ ) {+ selectedGatewayPoolId = null;const gatewayId = updatedInput.gatewayId as string;const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: actorOrgId });@@ -350,9 +414,7 @@ export const dynamicSecretServiceFactory = ({});}- if (!gateway) {- isGatewayV1 = false;- }+ isGatewayV1 = Boolean(gateway);const { permission: orgPermission } = await permissionService.getOrgPermission({scope: OrganizationActionScope.Any,@@ -384,8 +446,13 @@ export const dynamicSecretServiceFactory = ({defaultTTL,name: newName ?? name,status: null,- gatewayId: isGatewayV1 ? selectedGatewayId : null,- gatewayV2Id: isGatewayV1 ? null : selectedGatewayId,+ ...(hasGatewayFieldInInput+ ? {+ gatewayId: !selectedGatewayPoolId && isGatewayV1 ? selectedGatewayId : null,+ gatewayV2Id: !selectedGatewayPoolId && !isGatewayV1 ? selectedGatewayId : null,+ gatewayPoolId: selectedGatewayPoolId+ }+ : {}),usernameTemplate},txdiff --git a/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.tsindex 00c77013bf..4a50ebe13c 100644--- a/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts+++ b/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts@@ -13,6 +13,7 @@ import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebarsimport { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";import { DynamicSecretAzureSqlDBSchema, PasswordRequirements, SqlProviders, TDynamicProviderFns } from "./models";@@ -108,18 +109,20 @@ const generatePassword = (requirements?: PasswordRequirements) => {type TAzureSqlDatabaseProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const AzureSqlDatabaseProvider = ({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TAzureSqlDatabaseProviderDTO): TDynamicProviderFns => {const validateProviderInputs = async (inputs: unknown) => {const providerInputs = await DynamicSecretAzureSqlDBSchema.parseAsync(inputs);const [hostIp] = await verifyHostInputValidity({host: providerInputs.host,- isGateway: Boolean(providerInputs.gatewayId),+ isGateway: Boolean(providerInputs.gatewayId || providerInputs.gatewayPoolId),isDynamicSecret: true});validateHandlebarTemplate("Azure SQL master creation", providerInputs.masterCreationStatement, {@@ -161,7 +164,9 @@ export const AzureSqlDatabaseProvider = ({*/const isAzureSql = new RE2(/\.database\.windows\.net$/i).test(providerInputs.originalHost);const azureServerLabel =- isAzureSql && providerInputs.gatewayId ? providerInputs.originalHost?.split(".")[0] : undefined;+ isAzureSql && (providerInputs.gatewayId || providerInputs.gatewayPoolId)+ ? providerInputs.originalHost?.split(".")[0]+ : undefined;const effectiveUser =isAzureSql && !providerInputs.username.includes("@") && azureServerLabel? `${providerInputs.username}@${azureServerLabel}`@@ -195,8 +200,9 @@ export const AzureSqlDatabaseProvider = ({providerInputs: z.infer<typeof DynamicSecretAzureSqlDBSchema>,gatewayCallback: (host: string, port: number) => Promise<void>) => {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: providerInputs.gatewayId as string,+ gatewayId: effectiveGatewayId as string,targetHost: providerInputs.host,targetPort: providerInputs.port});@@ -215,7 +221,7 @@ export const AzureSqlDatabaseProvider = ({);}- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(providerInputs.gatewayId as string);+ const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);await withGatewayProxy(async (port) => {await gatewayCallback("localhost", port);@@ -256,7 +262,7 @@ export const AzureSqlDatabaseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -357,7 +363,7 @@ export const AzureSqlDatabaseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -472,7 +478,7 @@ export const AzureSqlDatabaseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -521,7 +527,7 @@ export const AzureSqlDatabaseProvider = ({await db.destroy();}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();diff --git a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts b/backend/src/ee/services/dynamic-secret/providers/clickhouse.tsindex c8313ceb14..42e38690d0 100644--- a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts+++ b/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts@@ -12,6 +12,7 @@ import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebarsimport { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";import { DynamicSecretClickhouseSchema, PasswordRequirements, TDynamicProviderFns } from "./models";@@ -100,11 +101,13 @@ const generatePassword = (requirements?: PasswordRequirements) => {type TClickhouseProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const ClickhouseProvider = ({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TClickhouseProviderDTO): TDynamicProviderFns => {const validateProviderInputs = async (inputs: unknown) => {const providerInputs = await DynamicSecretClickhouseSchema.parseAsync(inputs);@@ -113,7 +116,7 @@ export const ClickhouseProvider = ({const [hostIp] = await verifyHostInputValidity({host: sanitizedHost,- isGateway: Boolean(providerInputs.gatewayId),+ isGateway: Boolean(providerInputs.gatewayId || providerInputs.gatewayPoolId),isDynamicSecret: true});@@ -171,8 +174,9 @@ export const ClickhouseProvider = ({providerInputs: z.infer<typeof DynamicSecretClickhouseSchema>,gatewayCallback: (host: string, port: number) => Promise<void>) => {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: providerInputs.gatewayId as string,+ gatewayId: effectiveGatewayId as string,targetHost: providerInputs.host,targetPort: providerInputs.port});@@ -191,7 +195,7 @@ export const ClickhouseProvider = ({);}- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(providerInputs.gatewayId as string);+ const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);await withGatewayProxy(async (port) => {await gatewayCallback("localhost", port);@@ -234,7 +238,7 @@ export const ClickhouseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -296,7 +300,7 @@ export const ClickhouseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -339,7 +343,7 @@ export const ClickhouseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -385,7 +389,7 @@ export const ClickhouseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.tsindex aa0b77cf65..10348a9c1a 100644--- a/backend/src/ee/services/dynamic-secret/providers/index.ts+++ b/backend/src/ee/services/dynamic-secret/providers/index.ts@@ -1,6 +1,7 @@import { SnowflakeProvider } from "@app/ee/services/dynamic-secret/providers/snowflake";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { AwsElastiCacheDatabaseProvider } from "./aws-elasticache";import { AwsIamProvider } from "./aws-iam";@@ -30,14 +31,16 @@ import { VerticaProvider } from "./vertica";type TBuildDynamicSecretProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const buildDynamicSecretProviders = ({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TBuildDynamicSecretProviderDTO): Record<DynamicSecretProviders, TDynamicProviderFns> => ({- [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider({ gatewayService, gatewayV2Service }),- [DynamicSecretProviders.Clickhouse]: ClickhouseProvider({ gatewayService, gatewayV2Service }),+ [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),+ [DynamicSecretProviders.Clickhouse]: ClickhouseProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),[DynamicSecretProviders.Cassandra]: CassandraProvider(),[DynamicSecretProviders.AwsIam]: AwsIamProvider(),[DynamicSecretProviders.Redis]: RedisDatabaseProvider(),@@ -48,14 +51,18 @@ export const buildDynamicSecretProviders = ({[DynamicSecretProviders.ElasticSearch]: ElasticSearchProvider(),[DynamicSecretProviders.RabbitMq]: RabbitMqProvider(),[DynamicSecretProviders.AzureEntraID]: AzureEntraIDProvider(),- [DynamicSecretProviders.AzureSqlDatabase]: AzureSqlDatabaseProvider({ gatewayService, gatewayV2Service }),+ [DynamicSecretProviders.AzureSqlDatabase]: AzureSqlDatabaseProvider({+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ }),[DynamicSecretProviders.Ldap]: LdapProvider(),[DynamicSecretProviders.SapHana]: SapHanaProvider(),[DynamicSecretProviders.Snowflake]: SnowflakeProvider(),[DynamicSecretProviders.Totp]: TotpProvider(),[DynamicSecretProviders.SapAse]: SapAseProvider(),- [DynamicSecretProviders.Kubernetes]: KubernetesProvider({ gatewayService, gatewayV2Service }),- [DynamicSecretProviders.Vertica]: VerticaProvider({ gatewayService }),+ [DynamicSecretProviders.Kubernetes]: KubernetesProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),+ [DynamicSecretProviders.Vertica]: VerticaProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),[DynamicSecretProviders.GcpIam]: GcpIamProvider(),[DynamicSecretProviders.Github]: GithubProvider(),[DynamicSecretProviders.Couchbase]: CouchbaseProvider(),diff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.tsindex 5dac4914fc..e2395ac518 100644--- a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts+++ b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts@@ -15,6 +15,7 @@ import {TDynamicSecretKubernetesLeaseConfig} from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import {DynamicSecretKubernetesSchema,@@ -33,15 +34,17 @@ const GATEWAY_AUTH_DEFAULT_URL = "https://kubernetes.default.svc.cluster.local";type TKubernetesProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const KubernetesProvider = ({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TKubernetesProviderDTO): TDynamicProviderFns => {const validateProviderInputs = async (inputs: unknown) => {const providerInputs = await DynamicSecretKubernetesSchema.parseAsync(inputs);- if (!providerInputs.gatewayId && providerInputs.url) {+ if (!providerInputs.gatewayId && !providerInputs.gatewayPoolId && providerInputs.url) {await blockLocalAndPrivateIpAddresses(providerInputs.url);}@@ -345,11 +348,12 @@ export const KubernetesProvider = ({}): undefined;- if (providerInputs.gatewayId) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);+ if (effectiveGatewayId) {if (providerInputs.authMethod === KubernetesAuthMethod.Gateway) {await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sHost,targetPort: k8sPort,httpsAgent,@@ -362,7 +366,7 @@ export const KubernetesProvider = ({} else {await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sGatewayHost,targetPort: k8sPort,httpsAgent,@@ -614,11 +618,12 @@ export const KubernetesProvider = ({}): undefined;- if (providerInputs.gatewayId) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);+ if (effectiveGatewayId) {if (providerInputs.authMethod === KubernetesAuthMethod.Gateway) {tokenData = await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sHost,targetPort: k8sPort,httpsAgent,@@ -631,7 +636,7 @@ export const KubernetesProvider = ({} else {tokenData = await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sGatewayHost,targetPort: k8sPort,httpsAgent,@@ -773,11 +778,12 @@ export const KubernetesProvider = ({}): undefined;- if (providerInputs.gatewayId) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);+ if (effectiveGatewayId) {if (providerInputs.authMethod === KubernetesAuthMethod.Gateway) {await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sHost,targetPort: k8sPort,httpsAgent,@@ -788,7 +794,7 @@ export const KubernetesProvider = ({} else {await $gatewayProxyWrapper({- gatewayId: providerInputs.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: k8sGatewayHost,targetPort: k8sPort,httpsAgent,diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.tsindex 2e0e3c5fd2..58b1de9249 100644--- a/backend/src/ee/services/dynamic-secret/providers/models.ts+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts@@ -197,7 +197,8 @@ export const DynamicSecretSqlDBSchema = z.object({ca: z.string().optional(),sslEnabled: z.boolean().optional(),sslRejectUnauthorized: z.boolean().default(true),- gatewayId: z.string().nullable().optional()+ gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional()});export const DynamicSecretClickhouseSchema = z.object({@@ -232,7 +233,8 @@ export const DynamicSecretClickhouseSchema = z.object({revocationStatement: z.string().trim(),renewStatement: z.string().trim().optional(),ca: z.string().optional(),- gatewayId: z.string().nullable().optional()+ gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional()});export const DynamicSecretCassandraSchema = z.object({@@ -427,7 +429,8 @@ export const DynamicSecretAzureSqlDBSchema = z.object({ca: z.string().optional(),sslEnabled: z.boolean().optional(),sslRejectUnauthorized: z.boolean().default(true),- gatewayId: z.string().nullable().optional()+ gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional()});export const LdapSchema = z.union([@@ -477,7 +480,8 @@ export const DynamicSecretKubernetesSchema = z(val) => characterValidator([CharacterType.AlphaNumeric, CharacterType.Hyphen])(val),"Invalid namespace format"),- gatewayId: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),audiences: z.array(z.string().trim().min(1)),authMethod: z.nativeEnum(KubernetesAuthMethod).default(KubernetesAuthMethod.Api)}),@@ -506,7 +510,8 @@ export const DynamicSecretKubernetesSchema = znamespaces.every((ns) => characterValidator([CharacterType.AlphaNumeric, CharacterType.Hyphen])(ns)));}, "Must be a valid comma-separated list of namespace values"),- gatewayId: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),audiences: z.array(z.string().trim().min(1)),roleType: z.nativeEnum(KubernetesRoleType),role: z.string().trim().min(1),@@ -514,11 +519,18 @@ export const DynamicSecretKubernetesSchema = z})]).superRefine((data, ctx) => {- if (data.authMethod === KubernetesAuthMethod.Gateway && !data.gatewayId) {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayPoolId"],+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool"+ });+ }+ if (data.authMethod === KubernetesAuthMethod.Gateway && !data.gatewayId && !data.gatewayPoolId) {ctx.addIssue({path: ["gatewayId"],code: z.ZodIssueCode.custom,- message: "When auth method is set to Gateway, a gateway must be selected"+ message: "When auth method is set to Gateway, a gateway or gateway pool must be selected"});}if (data.authMethod === KubernetesAuthMethod.Api || !data.authMethod) {@@ -546,6 +558,7 @@ export const DynamicSecretVerticaSchema = z.object({password: z.string().trim(),database: z.string().trim(),gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional(),creationStatement: z.string().trim(),revocationStatement: z.string().trim(),passwordRequirements: zdiff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.tsindex 230dd73b52..559f3d96fe 100644--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts@@ -13,6 +13,7 @@ import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebarsimport { ActorIdentityAttributes } from "../../dynamic-secret-lease/dynamic-secret-lease-types";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";import { DynamicSecretSqlDBSchema, PasswordRequirements, SqlProviders, TDynamicProviderFns } from "./models";@@ -114,18 +115,20 @@ const generatePassword = (provider: SqlProviders, requirements?: PasswordRequiretype TSqlDatabaseProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const SqlDatabaseProvider = ({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TSqlDatabaseProviderDTO): TDynamicProviderFns => {const validateProviderInputs = async (inputs: unknown) => {const providerInputs = await DynamicSecretSqlDBSchema.parseAsync(inputs);const [hostIp] = await verifyHostInputValidity({host: providerInputs.host,- isGateway: Boolean(providerInputs.gatewayId),+ isGateway: Boolean(providerInputs.gatewayId || providerInputs.gatewayPoolId),isDynamicSecret: true});validateHandlebarTemplate("SQL creation", providerInputs.creationStatement, {@@ -165,7 +168,9 @@ export const SqlDatabaseProvider = ({*/const isAzureSql = isMsSQLClient && new RE2(/\.database\.windows\.net$/i).test(providerInputs.originalHost);const azureServerLabel =- isAzureSql && providerInputs.gatewayId ? providerInputs.originalHost?.split(".")[0] : undefined;+ isAzureSql && (providerInputs.gatewayId || providerInputs.gatewayPoolId)+ ? providerInputs.originalHost?.split(".")[0]+ : undefined;const effectiveUser =isAzureSql && !providerInputs.username.includes("@") && azureServerLabel? `${providerInputs.username}@${azureServerLabel}`@@ -177,7 +182,7 @@ export const SqlDatabaseProvider = ({database: providerInputs.database,port: providerInputs.port,host:- providerInputs.client === SqlProviders.Postgres && !providerInputs.gatewayId+ providerInputs.client === SqlProviders.Postgres && !providerInputs.gatewayId && !providerInputs.gatewayPoolId? providerInputs.hostIp: providerInputs.host,user: effectiveUser,@@ -204,8 +209,9 @@ export const SqlDatabaseProvider = ({providerInputs: z.infer<typeof DynamicSecretSqlDBSchema>,gatewayCallback: (host: string, port: number) => Promise<void>) => {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: providerInputs.gatewayId as string,+ gatewayId: effectiveGatewayId as string,targetHost: providerInputs.host,targetPort: providerInputs.port});@@ -224,7 +230,7 @@ export const SqlDatabaseProvider = ({);}- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(providerInputs.gatewayId as string);+ const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);await withGatewayProxy(async (port) => {await gatewayCallback("localhost", port);@@ -267,7 +273,7 @@ export const SqlDatabaseProvider = ({}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -329,7 +335,7 @@ export const SqlDatabaseProvider = ({await db.destroy();}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -372,7 +378,7 @@ export const SqlDatabaseProvider = ({await db.destroy();}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -421,7 +427,7 @@ export const SqlDatabaseProvider = ({await db.destroy();}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();diff --git a/backend/src/ee/services/dynamic-secret/providers/vertica.ts b/backend/src/ee/services/dynamic-secret/providers/vertica.tsindex fe152a9b7f..759417285c 100644--- a/backend/src/ee/services/dynamic-secret/providers/vertica.ts+++ b/backend/src/ee/services/dynamic-secret/providers/vertica.ts@@ -6,11 +6,14 @@ import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError } from "@app/lib/errors";import { sanitizeString } from "@app/lib/fn";import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";import { alphaNumericNanoId } from "@app/lib/nanoid";import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";import { TGatewayServiceFactory } from "../../gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "../../gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";import { verifyHostInputValidity } from "../dynamic-secret-fns";import { DynamicSecretVerticaSchema, PasswordRequirements, TDynamicProviderFns } from "./models";@@ -132,15 +135,21 @@ const generateUsername = (usernameTemplate?: string | null) => {type TVerticaProviderDTO = {gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};-export const VerticaProvider = ({ gatewayService }: TVerticaProviderDTO): TDynamicProviderFns => {+export const VerticaProvider = ({+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+}: TVerticaProviderDTO): TDynamicProviderFns => {const validateProviderInputs = async (inputs: unknown) => {const providerInputs = await DynamicSecretVerticaSchema.parseAsync(inputs);const [hostIp] = await verifyHostInputValidity({host: providerInputs.host,- isGateway: Boolean(providerInputs.gatewayId),+ isGateway: Boolean(providerInputs.gatewayId || providerInputs.gatewayPoolId),isDynamicSecret: true});validateHandlebarTemplate("Vertica creation", providerInputs.creationStatement, {@@ -194,7 +203,28 @@ export const VerticaProvider = ({ gatewayService }: TVerticaProviderDTO): TDynamproviderInputs: z.infer<typeof DynamicSecretVerticaSchema>,gatewayCallback: (host: string, port: number) => Promise<void>) => {- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(providerInputs.gatewayId as string);+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(providerInputs);+ const gatewayV2ConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({+ gatewayId: effectiveGatewayId as string,+ targetHost: providerInputs.host,+ targetPort: providerInputs.port+ });++ if (gatewayV2ConnectionDetails) {+ return withGatewayV2Proxy(+ async (port: number) => {+ await gatewayCallback("localhost", port);+ },+ {+ relayHost: gatewayV2ConnectionDetails.relayHost,+ gateway: gatewayV2ConnectionDetails.gateway,+ relay: gatewayV2ConnectionDetails.relay,+ protocol: GatewayProxyProtocol.Tcp+ }+ );+ }++ const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);await withGatewayProxy(async (port) => {await gatewayCallback("localhost", port);@@ -234,7 +264,7 @@ export const VerticaProvider = ({ gatewayService }: TVerticaProviderDTO): TDynam}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -284,7 +314,7 @@ export const VerticaProvider = ({ gatewayService }: TVerticaProviderDTO): TDynam}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();@@ -356,7 +386,7 @@ export const VerticaProvider = ({ gatewayService }: TVerticaProviderDTO): TDynam}};- if (providerInputs.gatewayId) {+ if (providerInputs.gatewayId || providerInputs.gatewayPoolId) {await gatewayProxyWrapper(providerInputs, gatewayCallback);} else {await gatewayCallback();diff --git a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts b/backend/src/ee/services/gateway-pool/gateway-pool-service.tsindex 60b057e1da..072f643cc5 100644--- a/backend/src/ee/services/gateway-pool/gateway-pool-service.ts+++ b/backend/src/ee/services/gateway-pool/gateway-pool-service.ts@@ -5,14 +5,20 @@ 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";+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { TIdentityKubernetesAuthDALFactory } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-dal";+import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";import { TLicenseServiceFactory } from "../license/license-service";+import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";+import { TPamDomainDALFactory } from "../pam-domain/pam-domain-dal";+import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";import { OrgPermissionGatewayPoolActions, OrgPermissionSubjects } from "../permission/org-permission";import { TPermissionServiceFactory } from "../permission/permission-service-types";+import { TPkiDiscoveryConfigDALFactory } from "../pki-discovery/pki-discovery-config-dal";import { TGatewayPoolDALFactory } from "./gateway-pool-dal";import { TGatewayPoolMembershipDALFactory } from "./gateway-pool-membership-dal";import {@@ -34,6 +40,12 @@ type TGatewayPoolServiceFactoryDep = {permissionService: TPermissionServiceFactory;licenseService: Pick<TLicenseServiceFactory, "getPlan">;identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ pamDomainDAL: Pick<TPamDomainDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ pamResourceDAL: Pick<TPamResourceDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ pamDiscoverySourceDAL: Pick<TPamDiscoverySourceDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;+ dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findByGatewayPoolId" | "countByGatewayPoolId">;};export type TGatewayPoolServiceFactory = ReturnType<typeof gatewayPoolServiceFactory>;@@ -45,7 +57,13 @@ export const gatewayPoolServiceFactory = ({gatewayV2Service,permissionService,licenseService,- identityKubernetesAuthDAL+ identityKubernetesAuthDAL,+ pkiDiscoveryConfigDAL,+ pamDomainDAL,+ pamResourceDAL,+ pamDiscoverySourceDAL,+ appConnectionDAL,+ dynamicSecretDAL}: TGatewayPoolServiceFactoryDep) => {const $checkPermission = async (actor: OrgServiceActor, action: OrgPermissionGatewayPoolActions) => {const { permission } = await permissionService.getOrgPermission({@@ -100,16 +118,54 @@ export const gatewayPoolServiceFactory = ({if (pools.length === 0) return [];// Add more DAL counts here as pool support expands to other consumers- const [k8sAuthCounts] = await Promise.all([+ const [+ k8sAuthCounts,+ pkiDiscoveryCounts,+ pamDomainCounts,+ pamResourceCounts,+ pamDiscoverySourceCounts,+ appConnectionCounts,+ dynamicSecretCounts+ ] = await Promise.all([Promise.all(pools.map((pool) =>identityKubernetesAuthDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))+ ),+ Promise.all(+ pools.map((pool) =>+ pkiDiscoveryConfigDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))+ )+ ),+ Promise.all(+ pools.map((pool) => pamDomainDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))+ ),+ Promise.all(+ pools.map((pool) => pamResourceDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))+ ),+ Promise.all(+ pools.map((pool) =>+ pamDiscoverySourceDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))+ )+ ),+ Promise.all(+ pools.map((pool) => appConnectionDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count })))+ ),+ Promise.all(+ pools.map((pool) => dynamicSecretDAL.countByGatewayPoolId(pool.id).then((count) => ({ id: pool.id, count }))))]);const countMap = new Map<string, number>();- for (const { id, count } of k8sAuthCounts) {+ for (const { id, count } of [+ ...k8sAuthCounts,+ ...pkiDiscoveryCounts,+ ...pamDomainCounts,+ ...pamResourceCounts,+ ...pamDiscoverySourceCounts,+ ...appConnectionCounts,+ ...dynamicSecretCounts+ ]) {countMap.set(id, (countMap.get(id) ?? 0) + count);}@@ -266,6 +322,53 @@ export const gatewayPoolServiceFactory = ({});};+ // Enforce license + RBAC + pool-belongs-to-org before a consumer attaches a pool. Does NOT require a healthy member.+ const resolveAttachableGatewayFromPool = async ({+ poolId,+ orgId,+ actor+ }: {+ poolId: string;+ orgId: string;+ actor: Pick<OrgServiceActor, "type" | "id" | "authMethod" | "orgId">;+ }) => {+ await $checkLicense(orgId);++ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayPoolActions.AttachGatewayPools,+ OrgPermissionSubjects.GatewayPool+ );++ const pool = await gatewayPoolDAL.findById(poolId);+ if (!pool || pool.orgId !== orgId) {+ throw new NotFoundError({ message: `Gateway pool with ID ${poolId} not found` });+ }+ };++ // Return gatewayId directly, or pick a random healthy pool member. Null when neither is set.+ const resolveEffectiveGatewayId = async ({+ gatewayId,+ gatewayPoolId+ }: {+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ }): Promise<string | null> => {+ if (gatewayId) return gatewayId;+ if (gatewayPoolId) {+ const picked = await pickRandomHealthyGateway(gatewayPoolId);+ return picked.id;+ }+ return null;+ };+const getConnectedResources = async ({ poolId, ...actor }: TGetGatewayPoolByIdDTO) => {await $checkPermission(actor, OrgPermissionGatewayPoolActions.ListGatewayPools);await $checkLicense(actor.orgId);@@ -276,15 +379,63 @@ export const gatewayPoolServiceFactory = ({}// Add more DAL calls here as pool support expands to other consumers- const kubernetesAuths = await identityKubernetesAuthDAL.findByGatewayPoolId(poolId);+ const [+ kubernetesAuths,+ pkiDiscoveryConfigs,+ pamDomains,+ pamResources,+ pamDiscoverySources,+ appConnections,+ dynamicSecrets+ ] = await Promise.all([+ identityKubernetesAuthDAL.findByGatewayPoolId(poolId),+ pkiDiscoveryConfigDAL.findByGatewayPoolId(poolId),+ pamDomainDAL.findByGatewayPoolId(poolId),+ pamResourceDAL.findByGatewayPoolId(poolId),+ pamDiscoverySourceDAL.findByGatewayPoolId(poolId),+ appConnectionDAL.findByGatewayPoolId(poolId),+ dynamicSecretDAL.findByGatewayPoolId(poolId)+ ]);- return { kubernetesAuths };+ return {+ kubernetesAuths,+ pkiDiscoveryConfigs,+ pamDomains,+ pamResources,+ pamDiscoverySources,+ appConnections,+ dynamicSecrets+ };};const getConnectedResourcesCount = async (poolId: string): Promise<number> => {// Add more DAL counts here as pool support expands to other consumers- const k8sAuthCount = await identityKubernetesAuthDAL.countByGatewayPoolId(poolId);- return k8sAuthCount;+ const [+ k8sAuthCount,+ pkiDiscoveryCount,+ pamDomainCount,+ pamResourceCount,+ pamDiscoverySourceCount,+ appConnectionCount,+ dynamicSecretCount+ ] = await Promise.all([+ identityKubernetesAuthDAL.countByGatewayPoolId(poolId),+ pkiDiscoveryConfigDAL.countByGatewayPoolId(poolId),+ pamDomainDAL.countByGatewayPoolId(poolId),+ pamResourceDAL.countByGatewayPoolId(poolId),+ pamDiscoverySourceDAL.countByGatewayPoolId(poolId),+ appConnectionDAL.countByGatewayPoolId(poolId),+ dynamicSecretDAL.countByGatewayPoolId(poolId)+ ]);+ return (+ k8sAuthCount ++ pkiDiscoveryCount ++ pamDomainCount ++ pamResourceCount ++ pamDiscoverySourceCount ++ appConnectionCount ++ dynamicSecretCount+ );};return {@@ -298,6 +449,8 @@ export const gatewayPoolServiceFactory = ({pickRandomHealthyGateway,getPlatformConnectionDetailsByPoolId,getConnectedResources,- getConnectedResourcesCount+ getConnectedResourcesCount,+ resolveAttachableGatewayFromPool,+ resolveEffectiveGatewayId};};diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 7705289519..a632e106f0 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -56,6 +56,7 @@ import { TSmtpService } from "@app/services/smtp/smtp-service";import { TUserDALFactory } from "@app/services/user/user-dal";import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { PAM_ACCOUNT_POLICY_RULE_SUPPORTED_RESOURCES } from "../pam-account-policy/pam-account-policy-constants";import { TPamAccountPolicyDALFactory } from "../pam-account-policy/pam-account-policy-dal";@@ -114,6 +115,7 @@ type TPamAccountServiceFactoryDep = {TGatewayV2ServiceFactory,"getPAMConnectionDetails" | "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;userDAL: TUserDALFactory;auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;tokenService: Pick<TAuthTokenServiceFactory, "createTokenForUser" | "validateTokenForUser">;@@ -149,6 +151,7 @@ export const pamAccountServiceFactory = ({permissionService,kmsService,gatewayV2Service,+ gatewayPoolService,auditLogService,approvalPolicyDAL,approvalRequestGrantsDAL,@@ -176,6 +179,7 @@ export const pamAccountServiceFactory = ({resourceType: resource.resourceType,domainType: null as string | null,gatewayId: resource.gatewayId,+ gatewayPoolId: resource.gatewayPoolId ?? null,encryptedConnectionDetails: resource.encryptedConnectionDetails,encryptedResourceMetadata: resource.encryptedResourceMetadata,encryptedRotationAccountCredentials: resource.encryptedRotationAccountCredentials,@@ -192,6 +196,7 @@ export const pamAccountServiceFactory = ({resourceType: null as string | null,domainType: domain.domainType,gatewayId: domain.gatewayId,+ gatewayPoolId: domain.gatewayPoolId ?? null,encryptedConnectionDetails: domain.encryptedConnectionDetails,encryptedResourceMetadata: null as Buffer | null,encryptedRotationAccountCredentials: null as Buffer | null,@@ -246,6 +251,7 @@ export const pamAccountServiceFactory = ({}));+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(parent);let factory;if (parent.isResource) {const connectionDetails = await decryptResourceConnectionDetails({@@ -263,7 +269,7 @@ export const pamAccountServiceFactory = ({factory = PAM_RESOURCE_FACTORY_MAP[parent.resourceType as PamResource](parent.resourceType as PamResource,connectionDetails,- parent.gatewayId,+ effectiveGatewayId,gatewayV2Service,parent.projectId,resourceInternalMetadata@@ -277,7 +283,7 @@ export const pamAccountServiceFactory = ({factory = PAM_DOMAIN_FACTORY_MAP[parent.domainType as PamDomainType](parent.domainType as PamDomainType,connectionDetails,- parent.gatewayId,+ effectiveGatewayId,gatewayV2Service,parent.projectId);@@ -426,6 +432,7 @@ export const pamAccountServiceFactory = ({}if (credentials !== undefined) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId(parent);let factory;if (parent.isResource) {const connectionDetails = await decryptResourceConnectionDetails({@@ -443,7 +450,7 @@ export const pamAccountServiceFactory = ({factory = PAM_RESOURCE_FACTORY_MAP[parent.resourceType as PamResource](parent.resourceType as PamResource,connectionDetails,- parent.gatewayId,+ effectiveGatewayId,gatewayV2Service,account.projectId,resourceInternalMetadata@@ -457,7 +464,7 @@ export const pamAccountServiceFactory = ({factory = PAM_DOMAIN_FACTORY_MAP[parent.domainType as PamDomainType](parent.domainType as PamDomainType,connectionDetails,- parent.gatewayId,+ effectiveGatewayId,gatewayV2Service,account.projectId);@@ -939,11 +946,12 @@ export const pamAccountServiceFactory = ({await mfaSessionService.deleteMfaSession(mfaSessionId);}- const { connectionDetails, gatewayId, resourceType } = await decryptResource(- resource,- account.projectId,- kmsService- );+ const decryptedResource = await decryptResource(resource, account.projectId, kmsService);+ const { connectionDetails, resourceType } = decryptedResource;+ const gatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: decryptedResource.gatewayId,+ gatewayPoolId: decryptedResource.gatewayPoolId+ });if (resourceType === PamResource.Windows) {const recordingConfig = await pamProjectRecordingConfigDAL.findByProjectId(account.projectId);@@ -1019,10 +1027,10 @@ export const pamAccountServiceFactory = ({};}- // For gateway-based resources (Postgres, MySQL, SSH), create session first- //- // Recording secrets are generated lazily at credential fetch time so the raw- // upload token can be returned exactly once to the gateway without persisting it+ if (!gatewayId) {+ throw new BadRequestError({ message: "Gateway ID is required for this resource type" });+ }+const session = await pamSessionDAL.create({accountName: account.name,actorEmail,@@ -1037,14 +1045,11 @@ export const pamAccountServiceFactory = ({resourceId: isDomainAccount ? null : resource.id,selectedResourceId: isDomainAccount ? resource.id : null,userId: actor.id,+ gatewayId,expiresAt: new Date(Date.now() + duration),reason: trimmedReason});- if (!gatewayId) {- throw new BadRequestError({ message: "Gateway ID is required for this resource type" });- }-const { host, port } = (() => {if (resourceType === PamResource.Kubernetes) {const url = new URL(connectionDetails.url);@@ -1293,14 +1298,15 @@ export const pamAccountServiceFactory = ({const resource = await pamResourceDAL.findById(resourceId);if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });- if (resource.gatewayId) {- const authorized =- actor.type === ActorType.GATEWAY ? resource.gatewayId === actor.id : resource.gatewayIdentityId === actor.id;- if (!authorized) {- throw new ForbiddenRequestError({- message: "Gateway does not have access to fetch the PAM session credentials"- });- }+ if (!session.gatewayId) {+ throw new BadRequestError({ message: "Session has no associated gateway" });+ }+ const authorized =+ actor.type === ActorType.GATEWAY ? session.gatewayId === actor.id : session.gatewayIdentityId === actor.id;+ if (!authorized) {+ throw new ForbiddenRequestError({+ message: "Gateway does not have access to fetch the PAM session credentials"+ });}const decryptedAccount = await decryptAccount(account, session.projectId, kmsService);@@ -1566,11 +1572,14 @@ export const pamAccountServiceFactory = ({}logResourceType = resource.resourceType;- const { connectionDetails, rotationAccountCredentials, gatewayId, resourceType } = await decryptResource(- resource,- account.projectId,- kmsService- );+ const decrypted = await decryptResource(resource, account.projectId, kmsService);+ const {+ connectionDetails,+ rotationAccountCredentials,+ gatewayId,+ gatewayPoolId: rotationGatewayPoolId,+ resourceType+ } = decrypted;if (!rotationAccountCredentials) {logger.warn(`[Rotation] Decrypted rotation credentials missing for account [accountId=${account.id}], releasing lock`@@ -1612,10 +1621,14 @@ export const pamAccountServiceFactory = ({return;}+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId,+ gatewayPoolId: rotationGatewayPoolId+ });const factory = PAM_RESOURCE_FACTORY_MAP[resourceType as PamResource](resourceType as PamResource,connectionDetails,- gatewayId,+ effectiveGatewayId,gatewayV2Service,account.projectId);diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.tsindex cfe5231eed..1c10fb4725 100644--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts@@ -461,7 +461,8 @@ const upsertDomain = async (gatewayId: string,kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,pamDomainDAL: Pick<TPamDomainDALFactory, "create" | "find">,- tx: Knex+ tx: Knex,+ gatewayPoolId?: string | null) => {const fingerprint = configuration.domainFQDN.toLowerCase();@@ -499,7 +500,8 @@ const upsertDomain = async (projectId,name: domainResourceName,domainType: PamDomainType.ActiveDirectory,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,encryptedConnectionDetails,discoveryFingerprint: fingerprint},@@ -515,6 +517,7 @@ const upsertWindowsServerResource = async (domainId: string,domainFQDN: string,gatewayId: string,+ gatewayPoolId: string | null | undefined,winrmConfig: {winrmPort: number;useWinrmHttps: boolean;@@ -576,7 +579,8 @@ const upsertWindowsServerResource = async (projectId,name: resourceName,resourceType: PamResource.Windows,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,encryptedConnectionDetails,encryptedResourceMetadata,domainId,@@ -882,7 +886,7 @@ const upsertDiscoveredDependency = async (export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory<TAdDiscoveryConfiguration,TAdDiscoveryCredentials-> = (_discoveryType, configuration, credentials, gatewayId, projectId, gatewayV2Service) => {+> = (_discoveryType, configuration, credentials, gatewayId, projectId, gatewayV2Service, gatewayPoolId) => {const validateConnection = async () => {try {const ldapProtocol = configuration.useLdaps ? "ldaps" : "ldap";@@ -1000,7 +1004,15 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory<// Auto-import AD domainconst { domain } = await pamDomainDAL.transaction(async (tx) => {- const result = await upsertDomain(projectId, configuration, gatewayId, kmsService, pamDomainDAL, tx);+ const result = await upsertDomain(+ projectId,+ configuration,+ gatewayId,+ kmsService,+ pamDomainDAL,+ tx,+ gatewayPoolId+ );return result;});@@ -1016,6 +1028,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory<domain.id,configuration.domainFQDN,gatewayId,+ gatewayPoolId,{winrmPort: configuration.winrmPort,useWinrmHttps: configuration.useWinrmHttps,diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts b/backend/src/ee/services/pam-discovery/pam-discovery-queue.tsindex fe6979c2d6..ea9600b447 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-queue.ts@@ -1,3 +1,4 @@+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";import { logger } from "@app/lib/logger";@@ -35,6 +36,7 @@ type TPamDiscoveryQueueFactoryDep = {queueService: TQueueServiceFactory;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export type TPamDiscoveryQueueFactory = ReturnType<typeof pamDiscoveryQueueFactory>;@@ -52,7 +54,8 @@ export const pamDiscoveryQueueFactory = ({kmsService,queueService,gatewayV2Service,- gatewayV2DAL+ gatewayV2DAL,+ gatewayPoolService}: TPamDiscoveryQueueFactoryDep) => {const startPamDiscoveryQueue = () => {queueService.start(QueueName.PamDiscoveryScan, async (job) => {@@ -79,13 +82,26 @@ export const pamDiscoveryQueueFactory = ({const configuration = discoverySource.discoveryConfiguration as TPamDiscoveryConfiguration;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: discoverySource.gatewayId,+ gatewayPoolId: discoverySource.gatewayPoolId+ });+ if (!effectiveGatewayId) {+ logger.error(+ { discoverySourceId, triggeredBy },+ "PAM Discovery Source has no gateway or gateway pool, skipping scan"+ );+ return;+ }+const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](discoveryType,configuration,credentials,- discoverySource.gatewayId,+ effectiveGatewayId,discoverySource.projectId,- gatewayV2Service+ gatewayV2Service,+ discoverySource.gatewayPoolId);const scanDeps = {diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.tsindex 541b6609a3..dc4aa5fe7c 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-schemas.ts@@ -33,16 +33,19 @@ export const BasePamDiscoverySourceSchema = PamDiscoverySourcesSchema.omit({status: z.nativeEnum(PamDiscoverySourceStatus)});+// No .superRefine — would turn into ZodEffects and break .extend() in per-type schemas.export const BaseCreatePamDiscoverySourceSchema = z.object({projectId: z.string().uuid(),name: slugSchema({ field: "name" }),- gatewayId: z.string().uuid(),+ gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional(),schedule: z.nativeEnum(PamDiscoverySchedule)});export const BaseUpdatePamDiscoverySourceSchema = z.object({name: slugSchema({ field: "name" }).optional(),gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional(),schedule: z.nativeEnum(PamDiscoverySchedule).optional()});diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.tsindex 351aa07133..32c3990b09 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-dal.ts@@ -137,11 +137,37 @@ export const pamDiscoverySourceDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.PamDiscoverySource)+ .leftJoin(TableName.Project, `${TableName.PamDiscoverySource}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.PamDiscoverySource}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.PamDiscoverySource),+ db.ref("name").withSchema(TableName.PamDiscoverySource),+ db.ref("projectId").withSchema(TableName.PamDiscoverySource),+ db.ref("discoveryType").withSchema(TableName.PamDiscoverySource),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.PamDiscoverySource)+ .where(`${TableName.PamDiscoverySource}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };+return {...orm,findByProjectId,findDueForScan,findByGatewayId,- countByGatewayId+ countByGatewayId,+ findByGatewayPoolId,+ countByGatewayPoolId};};diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.tsindex fae4bc71e1..5d30f98002 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-source-service.ts@@ -17,6 +17,7 @@ import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";@@ -82,6 +83,10 @@ type TPamDiscoverySourceServiceFactoryDep = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"+ >;pamDiscoveryQueue: Pick<TPamDiscoveryQueueFactory, "queuePamDiscoveryScan">;};@@ -100,6 +105,7 @@ export const pamDiscoverySourceServiceFactory = ({kmsService,gatewayV2DAL,gatewayV2Service,+ gatewayPoolService,pamDiscoveryQueue}: TPamDiscoverySourceServiceFactoryDep) => {const create = async (@@ -108,12 +114,20 @@ export const pamDiscoverySourceServiceFactory = ({name,discoveryType,gatewayId,+ gatewayPoolId,discoveryCredentials,discoveryConfiguration,schedule}: TCreatePamDiscoverySourceDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+ if (!gatewayId && !gatewayPoolId) {+ throw new BadRequestError({ message: "A gateway or gateway pool is required" });+ }+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -137,21 +151,32 @@ export const pamDiscoverySourceServiceFactory = ({actorOrgId: actor.orgId});- ForbiddenError.from(orgPermission).throwUnlessCan(- OrgPermissionGatewayActions.AttachGateways,- OrgPermissionSubjects.Gateway- );+ if (gatewayId) {+ ForbiddenError.from(orgPermission).throwUnlessCan(+ OrgPermissionGatewayActions.AttachGateways,+ OrgPermissionSubjects.Gateway+ );- const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });- if (!gateway) {- throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });+ const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actor.orgId });+ if (!gateway) {+ throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });+ }+ } else if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });}+ const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });+ if (!validationGatewayId) throw new BadRequestError({ message: "A gateway or gateway pool is required" });+const factory = PAM_DISCOVERY_FACTORY_MAP[discoveryType](discoveryType,discoveryConfiguration,discoveryCredentials,- gatewayId,+ validationGatewayId,projectId,gatewayV2Service);@@ -168,7 +193,8 @@ export const pamDiscoverySourceServiceFactory = ({projectId,name,discoveryType,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,encryptedDiscoveryCredentials,discoveryConfiguration,schedule,@@ -191,12 +217,17 @@ export const pamDiscoverySourceServiceFactory = ({discoverySourceId,name,gatewayId,+ gatewayPoolId,discoveryCredentials,discoveryConfiguration,schedule}: TUpdatePamDiscoverySourceDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const discoverySource = await pamDiscoverySourceDAL.findById(discoverySourceId);if (!discoverySource) {throw new NotFoundError({ message: `Discovery Source with ID '${discoverySourceId}' not found` });@@ -238,6 +269,16 @@ export const pamDiscoverySourceServiceFactory = ({throw new BadRequestError({ message: "Gateway not found or does not belong to this organization" });}updateDoc.gatewayId = gatewayId;+ updateDoc.gatewayPoolId = null;+ } else if (gatewayPoolId && gatewayPoolId !== discoverySource.gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });++ updateDoc.gatewayPoolId = gatewayPoolId;+ updateDoc.gatewayId = null;}if (name !== undefined) updateDoc.name = name;@@ -275,9 +316,11 @@ export const pamDiscoverySourceServiceFactory = ({});}- // Validate if connection details changed- if (gatewayId || discoveryConfiguration || discoveryCredentials) {- const effectiveGatewayId = gatewayId ?? discoverySource.gatewayId;+ if (gatewayId || gatewayPoolId || discoveryConfiguration || discoveryCredentials) {+ const effectiveAttachedGatewayId =+ updateDoc.gatewayId !== undefined ? updateDoc.gatewayId : discoverySource.gatewayId;+ const effectiveAttachedPoolId =+ updateDoc.gatewayPoolId !== undefined ? updateDoc.gatewayPoolId : discoverySource.gatewayPoolId;const effectiveConfiguration = (discoveryConfiguration ??discoverySource.discoveryConfiguration) as TPamDiscoveryConfiguration;@@ -290,12 +333,17 @@ export const pamDiscoverySourceServiceFactory = ({});}- if (effectiveGatewayId && effectiveCredentials) {+ const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: effectiveAttachedGatewayId,+ gatewayPoolId: effectiveAttachedPoolId+ });++ if (validationGatewayId && effectiveCredentials) {const factory = PAM_DISCOVERY_FACTORY_MAP[discoverySource.discoveryType as PamDiscoveryType](discoverySource.discoveryType as PamDiscoveryType,effectiveConfiguration,effectiveCredentials,- effectiveGatewayId,+ validationGatewayId,discoverySource.projectId,gatewayV2Service);diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts b/backend/src/ee/services/pam-discovery/pam-discovery-types.tsindex e49271be43..0e81bccc9a 100644--- a/backend/src/ee/services/pam-discovery/pam-discovery-types.ts+++ b/backend/src/ee/services/pam-discovery/pam-discovery-types.ts@@ -16,8 +16,10 @@ export type TPamDiscoveryConfiguration = TActiveDirectoryDiscoverySourceConfigur// Discovery Source DTOsexport type TCreatePamDiscoverySourceDTO = Pick<TPamDiscoverySource,- "name" | "projectId" | "discoveryType" | "discoveryConfiguration" | "schedule" | "gatewayId"+ "name" | "projectId" | "discoveryType" | "discoveryConfiguration" | "schedule"> & {+ gatewayId?: string | null;+ gatewayPoolId?: string | null;discoveryCredentials: TPamDiscoveryCredentials;};@@ -69,7 +71,8 @@ export type TPamDiscoveryFactory<T extends TPamDiscoveryConfiguration, C extendscredentials: C,gatewayId: string,projectId: string,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolId?: string | null) => {validateConnection: () => Promise<void>;scan: (diff --git a/backend/src/ee/services/pam-domain/pam-domain-dal.ts b/backend/src/ee/services/pam-domain/pam-domain-dal.tsindex c773cad156..e65042c87f 100644--- a/backend/src/ee/services/pam-domain/pam-domain-dal.ts+++ b/backend/src/ee/services/pam-domain/pam-domain-dal.ts@@ -110,10 +110,35 @@ export const pamDomainDALFactory = (db: TDbClient) => {return byDomainId;};+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.PamDomain)+ .leftJoin(TableName.Project, `${TableName.PamDomain}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.PamDomain}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.PamDomain),+ db.ref("name").withSchema(TableName.PamDomain),+ db.ref("projectId").withSchema(TableName.PamDomain),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.PamDomain)+ .where(`${TableName.PamDomain}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };+return {...orm,findById,findByProjectId,- findMetadataByDomainIds+ findMetadataByDomainIds,+ findByGatewayPoolId,+ countByGatewayPoolId};};diff --git a/backend/src/ee/services/pam-domain/pam-domain-schemas.ts b/backend/src/ee/services/pam-domain/pam-domain-schemas.tsindex 40d9378337..8b1580822e 100644--- a/backend/src/ee/services/pam-domain/pam-domain-schemas.ts+++ b/backend/src/ee/services/pam-domain/pam-domain-schemas.ts@@ -38,8 +38,24 @@ const CoreCreatePamDomainSchema = z.object({});export const CreateActiveDirectoryDomainSchema = CoreCreatePamDomainSchema.extend({- gatewayId: z.string().uuid(),+ gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional(),connectionDetails: ActiveDirectoryConnectionDetailsSchema+}).superRefine((data, ctx) => {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayPoolId"],+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool"+ });+ }+ if (!data.gatewayId && !data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayId"],+ code: z.ZodIssueCode.custom,+ message: "A gateway or gateway pool is required"+ });+ }});const CoreUpdatePamDomainSchema = z.object({@@ -49,7 +65,16 @@ const CoreUpdatePamDomainSchema = z.object({export const UpdateActiveDirectoryDomainSchema = CoreUpdatePamDomainSchema.extend({gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional(),connectionDetails: ActiveDirectoryConnectionDetailsSchema.optional()+}).superRefine((data, ctx) => {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ path: ["gatewayPoolId"],+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool"+ });+ }});export const SanitizedDomainSchema = z.discriminatedUnion("domainType", [SanitizedActiveDirectoryDomainSchema]);diff --git a/backend/src/ee/services/pam-domain/pam-domain-service.ts b/backend/src/ee/services/pam-domain/pam-domain-service.tsindex bdeeda3a19..4e2ca88913 100644--- a/backend/src/ee/services/pam-domain/pam-domain-service.ts+++ b/backend/src/ee/services/pam-domain/pam-domain-service.ts@@ -46,6 +46,7 @@ export const pamDomainServiceFactory = ({permissionService,kmsService,gatewayV2Service,+ gatewayPoolService,resourceMetadataDAL}: TPamDomainServiceFactoryDep) => {const getById = async (id: string, domainType: PamDomainType, actor: OrgServiceActor) => {@@ -86,9 +87,16 @@ export const pamDomainServiceFactory = ({};const create = async (- { domainType, connectionDetails, gatewayId, name, projectId, metadata }: TCreateDomainDTO,+ { domainType, connectionDetails, gatewayId, gatewayPoolId, name, projectId, metadata }: TCreateDomainDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+ if (!gatewayId && !gatewayPoolId) {+ throw new BadRequestError({ message: "A gateway or gateway pool is required" });+ }+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -107,6 +115,14 @@ export const pamDomainServiceFactory = ({}));+ if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });+ }+const existingDomain = await pamDomainDAL.findOne({ name, projectId });if (existingDomain) {throw new BadRequestError({@@ -114,10 +130,12 @@ export const pamDomainServiceFactory = ({});}+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });+const factory = PAM_DOMAIN_FACTORY_MAP[domainType](domainType,connectionDetails,- gatewayId,+ effectiveGatewayId,gatewayV2Service,projectId);@@ -135,7 +153,8 @@ export const pamDomainServiceFactory = ({{domainType,encryptedConnectionDetails,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,name,projectId},@@ -171,9 +190,13 @@ export const pamDomainServiceFactory = ({};const updateById = async (- { domainId, connectionDetails, name, gatewayId, metadata }: TUpdateDomainDTO,+ { domainId, connectionDetails, name, gatewayId, gatewayPoolId, metadata }: TUpdateDomainDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const domain = await pamDomainDAL.findById(domainId);if (!domain) throw new NotFoundError({ message: `Domain with ID '${domainId}' not found` });@@ -209,11 +232,32 @@ export const pamDomainServiceFactory = ({);}+ if (gatewayPoolId && gatewayPoolId !== domain.gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });+ }+const updateDoc: Partial<TPamDomains> = {};- const effectiveGatewayId = gatewayId !== undefined ? gatewayId : domain.gatewayId;+ // Mutual exclusion: setting one clears the other.+ let effectiveGatewayId: string | null | undefined = domain.gatewayId;+ let effectiveGatewayPoolId: string | null | undefined = domain.gatewayPoolId;+ if (gatewayId !== undefined && gatewayPoolId !== undefined) {+ effectiveGatewayId = gatewayId;+ effectiveGatewayPoolId = gatewayPoolId;+ } else if (gatewayId !== undefined) {+ effectiveGatewayId = gatewayId;+ effectiveGatewayPoolId = gatewayId !== null ? null : undefined;+ } else if (gatewayPoolId !== undefined) {+ effectiveGatewayPoolId = gatewayPoolId;+ effectiveGatewayId = gatewayPoolId !== null ? null : undefined;+ }- if (gatewayId !== undefined) {- updateDoc.gatewayId = gatewayId;+ if (gatewayId !== undefined || gatewayPoolId !== undefined) {+ updateDoc.gatewayId = effectiveGatewayId;+ updateDoc.gatewayPoolId = effectiveGatewayPoolId;}if (name !== undefined) {@@ -221,10 +265,14 @@ export const pamDomainServiceFactory = ({}if (connectionDetails !== undefined) {+ const validationGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: effectiveGatewayId,+ gatewayPoolId: effectiveGatewayPoolId+ });const factory = PAM_DOMAIN_FACTORY_MAP[domain.domainType as PamDomainType](domain.domainType as PamDomainType,connectionDetails,- effectiveGatewayId,+ validationGatewayId,gatewayV2Service,domain.projectId);diff --git a/backend/src/ee/services/pam-domain/pam-domain-types.ts b/backend/src/ee/services/pam-domain/pam-domain-types.tsindex 827467d9c2..e320bc5978 100644--- a/backend/src/ee/services/pam-domain/pam-domain-types.ts+++ b/backend/src/ee/services/pam-domain/pam-domain-types.ts@@ -5,6 +5,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";import { TPostRotateContext } from "../pam-resource/pam-resource-types";@@ -21,6 +22,7 @@ export type TPamDomain = {name: string;domainType: PamDomainType;gatewayId?: string | null;+ gatewayPoolId?: string | null;discoveryFingerprint?: string | null;createdAt: Date;updatedAt: Date;@@ -33,6 +35,7 @@ export type TCreateDomainDTO = {name: string;domainType: PamDomainType;gatewayId?: string | null;+ gatewayPoolId?: string | null;connectionDetails: TPamDomainConnectionDetails;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;};@@ -41,6 +44,7 @@ export type TUpdateDomainDTO = {domainId: string;name?: string;gatewayId?: string | null;+ gatewayPoolId?: string | null;connectionDetails?: TPamDomainConnectionDetails;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;};@@ -65,6 +69,10 @@ export type TPamDomainServiceFactoryDep = {permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"+ >;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;};diff --git a/backend/src/ee/services/pam-resource/pam-resource-dal.ts b/backend/src/ee/services/pam-resource/pam-resource-dal.tsindex 615908d387..c9709b5835 100644--- a/backend/src/ee/services/pam-resource/pam-resource-dal.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-dal.ts@@ -172,6 +172,30 @@ export const pamResourceDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.PamResource)+ .leftJoin(TableName.Project, `${TableName.PamResource}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.PamResource}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.PamResource),+ db.ref("name").withSchema(TableName.PamResource),+ db.ref("projectId").withSchema(TableName.PamResource),+ db.ref("resourceType").withSchema(TableName.PamResource),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.PamResource)+ .where(`${TableName.PamResource}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };+const countByProject = async (projectId: string, tx?: Knex): Promise<number> => {const result = await (tx || db.replicaNode())(TableName.PamResource).where("projectId", projectId)@@ -210,6 +234,8 @@ export const pamResourceDALFactory = (db: TDbClient) => {findByDomainId,findByGatewayId,countByGatewayId,+ findByGatewayPoolId,+ countByGatewayPoolId,countByProject,countWithRotationByProject,countByProjectGroupedByTypediff --git a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts b/backend/src/ee/services/pam-resource/pam-resource-schemas.tsindex 0af9b9ef2c..63a1b9ee9c 100644--- a/backend/src/ee/services/pam-resource/pam-resource-schemas.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-schemas.ts@@ -52,8 +52,10 @@ const CoreCreatePamResourceSchema = z.object({metadata: ResourceMetadataNonEncryptionSchema.optional()});+// No .superRefine — would turn into ZodEffects and break .extend() in per-type schemas.export const BaseCreateGatewayPamResourceSchema = CoreCreatePamResourceSchema.extend({- gatewayId: z.string().uuid()+ gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional()});export const BaseCreatePamResourceSchema = CoreCreatePamResourceSchema;@@ -65,7 +67,8 @@ const CoreUpdatePamResourceSchema = z.object({});export const BaseUpdateGatewayPamResourceSchema = CoreUpdatePamResourceSchema.extend({- gatewayId: z.string().uuid().optional()+ gatewayId: z.string().uuid().optional(),+ gatewayPoolId: z.string().uuid().optional()});export const BaseUpdatePamResourceSchema = CoreUpdatePamResourceSchema;diff --git a/backend/src/ee/services/pam-resource/pam-resource-service.ts b/backend/src/ee/services/pam-resource/pam-resource-service.tsindex 4110bc511c..a101cd9f8d 100644--- a/backend/src/ee/services/pam-resource/pam-resource-service.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-service.ts@@ -21,6 +21,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TResourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";import { PamAccountView } from "../pam-account/pam-account-enums";@@ -58,6 +59,10 @@ type TPamResourceServiceFactoryDep = {TGatewayV2ServiceFactory,"getPAMConnectionDetails" | "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool"+ >;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;pamProjectRecordingConfigDAL: {@@ -75,6 +80,7 @@ export const pamResourceServiceFactory = ({permissionService,kmsService,gatewayV2Service,+ gatewayPoolService,resourceMetadataDAL,appConnectionDAL,pamProjectRecordingConfigDAL@@ -165,6 +171,7 @@ export const pamResourceServiceFactory = ({resourceType,connectionDetails,gatewayId,+ gatewayPoolId,name,projectId,rotationAccountCredentials,@@ -173,6 +180,13 @@ export const pamResourceServiceFactory = ({}: TCreateResourceDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+ if (resourceType !== PamResource.AwsIam && !gatewayId && !gatewayPoolId) {+ throw new BadRequestError({ message: "A gateway or gateway pool is required for this resource type" });+ }+const { permission } = await permissionService.getProjectPermission({actor: actor.type,actorAuthMethod: actor.authMethod,@@ -191,6 +205,14 @@ export const pamResourceServiceFactory = ({}));+ if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });+ }+if (domainId) {await assertDomainInProject(domainId, projectId);}@@ -206,10 +228,12 @@ export const pamResourceServiceFactory = ({}}+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId, gatewayPoolId });+const factory = PAM_RESOURCE_FACTORY_MAP[resourceType](resourceType,connectionDetails,- gatewayId,+ effectiveGatewayId,gatewayV2Service,projectId);@@ -239,7 +263,8 @@ export const pamResourceServiceFactory = ({{resourceType,encryptedConnectionDetails,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,name,projectId,encryptedRotationAccountCredentials,@@ -283,12 +308,17 @@ export const pamResourceServiceFactory = ({name,rotationAccountCredentials,gatewayId,+ gatewayPoolId,domainId,metadata,sessionSummaryConfig}: TUpdateResourceDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const resource = await pamResourceDAL.findById(resourceId);if (!resource) throw new NotFoundError({ message: `Resource with ID '${resourceId}' not found` });@@ -327,12 +357,33 @@ export const pamResourceServiceFactory = ({);}+ if (gatewayPoolId && gatewayPoolId !== resource.gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });+ }+const updateDoc: Partial<TPamResources> = {};- const effectiveGatewayId = gatewayId !== undefined ? gatewayId : resource.gatewayId;+ // Mutual exclusion: setting one clears the other.+ let effectiveGatewayIdAttr: string | null | undefined = resource.gatewayId;+ let effectiveGatewayPoolIdAttr: string | null | undefined = resource.gatewayPoolId ?? null;+ if (gatewayId !== undefined && gatewayPoolId !== undefined) {+ effectiveGatewayIdAttr = gatewayId;+ effectiveGatewayPoolIdAttr = gatewayPoolId;+ } else if (gatewayId !== undefined) {+ effectiveGatewayIdAttr = gatewayId;+ effectiveGatewayPoolIdAttr = gatewayId !== null ? null : undefined;+ } else if (gatewayPoolId !== undefined) {+ effectiveGatewayPoolIdAttr = gatewayPoolId;+ effectiveGatewayIdAttr = gatewayPoolId !== null ? null : undefined;+ }- if (gatewayId !== undefined) {- updateDoc.gatewayId = gatewayId;+ if (gatewayId !== undefined || gatewayPoolId !== undefined) {+ updateDoc.gatewayId = effectiveGatewayIdAttr;+ updateDoc.gatewayPoolId = effectiveGatewayPoolIdAttr;}if (name !== undefined) {@@ -346,6 +397,14 @@ export const pamResourceServiceFactory = ({updateDoc.domainId = domainId;}+ let effectiveGatewayId: string | null | undefined;+ if (connectionDetails !== undefined || rotationAccountCredentials !== undefined) {+ effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: effectiveGatewayIdAttr,+ gatewayPoolId: effectiveGatewayPoolIdAttr+ });+ }+if (connectionDetails !== undefined) {const factory = PAM_RESOURCE_FACTORY_MAP[resource.resourceType as PamResource](resource.resourceType as PamResource,diff --git a/backend/src/ee/services/pam-resource/pam-resource-types.ts b/backend/src/ee/services/pam-resource/pam-resource-types.tsindex 0cae6204c5..9e29643ac7 100644--- a/backend/src/ee/services/pam-resource/pam-resource-types.ts+++ b/backend/src/ee/services/pam-resource/pam-resource-types.ts@@ -127,6 +127,7 @@ export type TPamAccountCredentials =// Resource DTOsexport type TCreateResourceDTO = Pick<TPamResource, "name" | "connectionDetails" | "resourceType" | "projectId"> & {gatewayId?: string | null;+ gatewayPoolId?: string | null;rotationAccountCredentials?: TPamAccountCredentials | null;domainId?: string | null;metadata?: z.input<typeof ResourceMetadataNonEncryptionSchema>;diff --git a/backend/src/ee/services/pam-session/pam-session-dal.ts b/backend/src/ee/services/pam-session/pam-session-dal.tsindex 3a679c3095..6606a15f51 100644--- a/backend/src/ee/services/pam-session/pam-session-dal.ts+++ b/backend/src/ee/services/pam-session/pam-session-dal.ts@@ -26,7 +26,13 @@ export const pamSessionDALFactory = (db: TDbClient) => {.leftJoin(TableName.PamResource, function joinResource() {this.on(sessionResourceOn);})- .leftJoin(TableName.GatewayV2, `${TableName.PamResource}.gatewayId`, `${TableName.GatewayV2}.id`)+ .leftJoin(TableName.GatewayV2, function joinSessionGateway() {+ this.on(+ `${TableName.GatewayV2}.id`,+ "=",+ db.raw("COALESCE(??, ??)", [`${TableName.PamSession}.gatewayId`, `${TableName.PamResource}.gatewayId`])+ );+ }).select(selectAllTableCols(TableName.PamSession)).select(db.ref("name").withSchema(TableName.GatewayV2).as("gatewayName")).select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId"))@@ -79,7 +85,13 @@ export const pamSessionDALFactory = (db: TDbClient) => {.leftJoin(TableName.PamResource, function joinResource() {this.on(sessionResourceOn);})- .leftJoin(TableName.GatewayV2, `${TableName.PamResource}.gatewayId`, `${TableName.GatewayV2}.id`)+ .leftJoin(TableName.GatewayV2, function joinSessionGateway() {+ this.on(+ `${TableName.GatewayV2}.id`,+ "=",+ db.raw("COALESCE(??, ??)", [`${TableName.PamSession}.gatewayId`, `${TableName.PamResource}.gatewayId`])+ );+ }).select(selectAllTableCols(TableName.PamSession)).select(db.ref("identityId").withSchema(TableName.GatewayV2).as("gatewayIdentityId")).select(db.ref("id").withSchema(TableName.GatewayV2).as("gatewayId"))diff --git a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts b/backend/src/ee/services/pam-web-access/pam-web-access-service.tsindex b560a54e83..97c4cc294c 100644--- a/backend/src/ee/services/pam-web-access/pam-web-access-service.ts+++ b/backend/src/ee/services/pam-web-access/pam-web-access-service.ts@@ -5,6 +5,7 @@ import type WebSocket from "ws";import { ActionProjectType } from "@app/db/schemas";import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";@@ -77,6 +78,7 @@ type TPamWebAccessServiceFactoryDep = {pamSessionDAL: Pick<TPamSessionDALFactory, "create" | "updateById" | "countActiveWebSessions">;pamSessionExpirationService: Pick<TPamSessionExpirationServiceFactory, "scheduleSessionExpiration">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPAMConnectionDetails">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;userDAL: Pick<TUserDALFactory, "findById">;mfaSessionService: Pick<@@ -116,6 +118,7 @@ export const pamWebAccessServiceFactory = ({pamSessionDAL,pamSessionExpirationService,gatewayV2Service,+ gatewayPoolService,kmsService,userDAL,mfaSessionService,@@ -467,7 +470,11 @@ export const pamWebAccessServiceFactory = ({throw new BadRequestError({ message: "Web access is not supported for this resource type" });}- if (!resource.gatewayId) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: resource.gatewayId,+ gatewayPoolId: resource.gatewayPoolId+ });+ if (!effectiveGatewayId) {throw new BadRequestError({ message: "Gateway not configured for this resource" });}@@ -515,6 +522,7 @@ export const pamWebAccessServiceFactory = ({accountId: account.id,resourceId: resource.id,userId,+ gatewayId: effectiveGatewayId,reason: accessReason?.trim() || null});@@ -522,7 +530,7 @@ export const pamWebAccessServiceFactory = ({// 4. GET CERTIFICATESconst certs = await gatewayV2Service.getPAMConnectionDetails({- gatewayId: resource.gatewayId,+ gatewayId: effectiveGatewayId,sessionId: session.id,resourceType: resource.resourceType as PamResource,host,diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-config-dal.ts b/backend/src/ee/services/pki-discovery/pki-discovery-config-dal.tsindex a80c3546ef..74523c28c4 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-config-dal.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-config-dal.ts@@ -175,6 +175,29 @@ export const pkiDiscoveryConfigDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.PkiDiscoveryConfig)+ .leftJoin(TableName.Project, `${TableName.PkiDiscoveryConfig}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.PkiDiscoveryConfig}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.PkiDiscoveryConfig),+ db.ref("name").withSchema(TableName.PkiDiscoveryConfig),+ db.ref("projectId").withSchema(TableName.PkiDiscoveryConfig),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.PkiDiscoveryConfig)+ .where(`${TableName.PkiDiscoveryConfig}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };+return {...pkiDiscoveryConfigOrm,findByProjectId,@@ -184,6 +207,8 @@ export const pkiDiscoveryConfigDALFactory = (db: TDbClient) => {findByName,claimScanSlot,findByGatewayId,- countByGatewayId+ countByGatewayId,+ findByGatewayPoolId,+ countByGatewayPoolId};};diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts b/backend/src/ee/services/pki-discovery/pki-discovery-queue.tsindex c83dc00cf7..7bcbb0e573 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts@@ -1,3 +1,4 @@+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";import { logger } from "@app/lib/logger";@@ -28,6 +29,7 @@ type TPkiDiscoveryQueueFactoryDep = {queueService: TQueueServiceFactory;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export type TPkiDiscoveryQueueFactory = ReturnType<typeof pkiDiscoveryQueueFactory>;@@ -44,7 +46,8 @@ export const pkiDiscoveryQueueFactory = ({kmsService,queueService,gatewayV2Service,- gatewayV2DAL+ gatewayV2DAL,+ gatewayPoolService}: TPkiDiscoveryQueueFactoryDep) => {const startPkiDiscoveryScanQueue = () => {queueService.start(QueueName.PkiDiscoveryScan, async (job) => {@@ -71,7 +74,8 @@ export const pkiDiscoveryQueueFactory = ({projectDAL,kmsService,gatewayV2Service,- gatewayV2DAL+ gatewayV2DAL,+ gatewayPoolService};switch (discoveryType) {diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.tsindex 4f7d1b1672..21348482d3 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts@@ -3,6 +3,7 @@ import net from "net";import pLimit from "p-limit";import { TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db/schemas";+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";import { GatewayProxyProtocol } from "@app/lib/gateway/types";@@ -62,10 +63,18 @@ type TExecuteScanDeps = {kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayV2DAL?: Pick<TGatewayV2DALFactory, "findById">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps): Promise<void> => {- const { pkiDiscoveryConfigDAL, pkiDiscoveryScanHistoryDAL, projectDAL, kmsService, gatewayV2Service } = deps;+ const {+ pkiDiscoveryConfigDAL,+ pkiDiscoveryScanHistoryDAL,+ projectDAL,+ kmsService,+ gatewayV2Service,+ gatewayPoolService+ } = deps;const startedAt = new Date();let scanHistoryId: string | undefined;@@ -118,14 +127,21 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):});scanHistoryId = scanHistory.id;+ const effectiveGatewayId = gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: discoveryConfig.gatewayId,+ gatewayPoolId: discoveryConfig.gatewayPoolId+ })+ : (discoveryConfig.gatewayId ?? null);+let gatewayName: string | undefined;- if (discoveryConfig.gatewayId && deps.gatewayV2DAL) {- const gw = await deps.gatewayV2DAL.findById(discoveryConfig.gatewayId);+ if (effectiveGatewayId && deps.gatewayV2DAL) {+ const gw = await deps.gatewayV2DAL.findById(effectiveGatewayId);gatewayName = gw?.name;}const targetConfig = discoveryConfig.targetConfig as TPkiDiscoveryTargetConfig;- const hasGateway = !!discoveryConfig.gatewayId;+ const hasGateway = !!effectiveGatewayId;const targets = await resolveTargets(targetConfig, hasGateway);const uniqueHosts = new Set(targets.map((t) => t.host)).size;@@ -147,8 +163,11 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):const limit = pLimit(SCAN_CONCURRENCY);let results: TScanEndpointResult[];- if (discoveryConfig.gatewayId && gatewayV2Service) {- logger.info({ discoveryId, gatewayId: discoveryConfig.gatewayId }, "Scanning via gateway proxy");+ if (effectiveGatewayId && gatewayV2Service) {+ logger.info(+ { discoveryId, gatewayId: effectiveGatewayId, gatewayPoolId: discoveryConfig.gatewayPoolId ?? undefined },+ "Scanning via gateway proxy"+ );results = [];let consecutiveGwFailures = 0;@@ -160,7 +179,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):try {const targetGatewayDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: discoveryConfig.gatewayId,+ gatewayId: effectiveGatewayId,targetHost: target.host,targetPort: target.port});@@ -307,8 +326,9 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):now,deps,kmsEncryptor,- discoveryConfig.gatewayId ?? undefined,- gatewayName+ effectiveGatewayId ?? undefined,+ gatewayName,+ discoveryConfig.gatewayPoolId ?? effectiveGatewayId ?? undefined);if (processedCertIds.installationId) {@@ -353,7 +373,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):const domainFingerprint = computeLocationFingerprint(PkiInstallationLocationType.Network,domainLocationDetails,- discoveryConfig.gatewayId ?? undefined+ discoveryConfig.gatewayPoolId ?? effectiveGatewayId ?? undefined);const domainInstallationId = await deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {@@ -523,7 +543,8 @@ const processEndpointResult = async (deps: TExecuteScanDeps,kmsEncryptor: TKmsEncryptor,gatewayId?: string,- gatewayName?: string+ gatewayName?: string,+ fingerprintGatewayKey?: string): Promise<{ installationId?: string; certificateIds: string[]; sniHostname?: string }> => {const {pkiCertificateInstallationDAL,@@ -561,7 +582,7 @@ const processEndpointResult = async (const locationFingerprint = computeLocationFingerprint(PkiInstallationLocationType.Network,locationDetails,- gatewayId+ fingerprintGatewayKey ?? gatewayId);const displayName = ipAddress || result.host;diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts b/backend/src/ee/services/pki-discovery/pki-discovery-service.tsindex 561f5777b7..d7e2f54ed1 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts@@ -1,6 +1,8 @@import { ForbiddenError } from "@casl/ability";import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";+import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {@@ -47,6 +49,8 @@ type TPkiDiscoveryServiceFactoryDep = {>;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;+ gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveAttachableGatewayFromPool">;queuePkiDiscoveryScan: (discoveryId: string) => Promise<void>;};@@ -71,6 +75,8 @@ export const pkiDiscoveryServiceFactory = ({pkiDiscoveryScanHistoryDAL,permissionService,gatewayV2DAL,+ gatewayPoolDAL,+ gatewayPoolService,queuePkiDiscoveryScan}: TPkiDiscoveryServiceFactoryDep) => {const createDiscovery = async ({@@ -82,11 +88,16 @@ export const pkiDiscoveryServiceFactory = ({isAutoScanEnabled,scanIntervalDays,gatewayId,+ gatewayPoolId,actor,actorId,actorAuthMethod,actorOrgId}: TCreatePkiDiscoveryDTO) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const { permission } = await permissionService.getProjectPermission({actor,actorId,@@ -129,6 +140,12 @@ export const pkiDiscoveryServiceFactory = ({OrgPermissionGatewayActions.AttachGateways,OrgPermissionSubjects.Gateway);+ } else if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actorOrgId,+ actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }+ });}try {@@ -140,7 +157,8 @@ export const pkiDiscoveryServiceFactory = ({targetConfig,isAutoScanEnabled: isAutoScanEnabled ?? false,scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,isActive: true});@@ -164,12 +182,17 @@ export const pkiDiscoveryServiceFactory = ({isAutoScanEnabled,scanIntervalDays,gatewayId,+ gatewayPoolId,isActive,actor,actorId,actorAuthMethod,actorOrgId}: TUpdatePkiDiscoveryDTO) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const discovery = await pkiDiscoveryConfigDAL.findById(discoveryId);if (!discovery) {throw new NotFoundError({ message: `Discovery configuration with ID '${discoveryId}' not found` });@@ -215,8 +238,17 @@ export const pkiDiscoveryServiceFactory = ({OrgPermissionGatewayActions.AttachGateways,OrgPermissionSubjects.Gateway);+ } else if (gatewayPoolId && gatewayPoolId !== discovery.gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actorOrgId,+ actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }+ });}+ const gatewayIdValue = gatewayPoolId ? null : gatewayId;+ const gatewayPoolIdValue = gatewayId ? null : gatewayPoolId;+try {const updatedDiscovery = await pkiDiscoveryConfigDAL.updateById(discoveryId, {name,@@ -224,7 +256,8 @@ export const pkiDiscoveryServiceFactory = ({targetConfig,isAutoScanEnabled,scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,- gatewayId,+ gatewayId: gatewayIdValue,+ gatewayPoolId: gatewayPoolIdValue,isActive});@@ -292,14 +325,20 @@ export const pkiDiscoveryServiceFactory = ({);let gatewayName: string | null = null;+ let gatewayPoolName: string | null = null;if (discovery.gatewayId) {const gateway = await gatewayV2DAL.findOne({ id: discovery.gatewayId });if (gateway) {gatewayName = gateway.name;}+ } else if (discovery.gatewayPoolId) {+ const pool = await gatewayPoolDAL.findById(discovery.gatewayPoolId);+ if (pool) {+ gatewayPoolName = pool.name;+ }}- return { ...discovery, gatewayName };+ return { ...discovery, gatewayName, gatewayPoolName };};const listDiscoveries = async ({diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts b/backend/src/ee/services/pki-discovery/pki-discovery-types.tsindex 1b7b56844a..029ef8f3f2 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts@@ -61,7 +61,8 @@ export type TCreatePkiDiscoveryDTO = {targetConfig: TPkiDiscoveryTargetConfig;isAutoScanEnabled?: boolean;scanIntervalDays?: number;- gatewayId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;} & Omit<TProjectPermission, "projectId">;export type TUpdatePkiDiscoveryDTO = {@@ -72,6 +73,7 @@ export type TUpdatePkiDiscoveryDTO = {isAutoScanEnabled?: boolean;scanIntervalDays?: number;gatewayId?: string | null;+ gatewayPoolId?: string | null;isActive?: boolean;} & Omit<TProjectPermission, "projectId">;diff --git a/backend/src/ee/services/secret-rotation-v2/hp-ilo-rotation/hp-ilo-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/hp-ilo-rotation/hp-ilo-rotation-fns.tsindex 39bcdf413a..7a31540378 100644--- a/backend/src/ee/services/secret-rotation-v2/hp-ilo-rotation/hp-ilo-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/hp-ilo-rotation/hp-ilo-rotation-fns.ts@@ -202,7 +202,7 @@ export const hpIloRotationFactory: TRotationFactory<THpIloRotationWithConnection,THpIloRotationGeneratedCredentials,THpIloRotationInput["temporaryParameters"]-> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service) => {+> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service, gatewayPoolService) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const { username, passwordRequirements, rotationMethod = HpIloRotationMethod.LoginAsRoot } = parameters;@@ -213,11 +213,16 @@ export const hpIloRotationFactory: TRotationFactory<if (username === connection.credentials.username)throw new BadRequestError({ message: "Provided username is used in Infisical app connections." });+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+const sshConfig: TSshConnectionConfig = {method: connection.method,app: connection.app,orgId: connection.orgId,- gatewayId: connection.gatewayId,+ gatewayId: effectiveGatewayId,credentials: connection.credentials} as TSshConnectionConfig;diff --git a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.tsindex aa45e9a069..ae2b743c63 100644--- a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts@@ -109,17 +109,30 @@ export const ldapPasswordRotationFactory: TRotationFactory<TLdapPasswordRotationWithConnection,TLdapPasswordRotationGeneratedCredentials,TLdapPasswordRotationInput["temporaryParameters"]-> = (secretRotation, appConnectionDAL, kmsService, gatewayService, gatewayV2Service) => {+> = (secretRotation, appConnectionDAL, kmsService, gatewayService, gatewayV2Service, gatewayPoolService) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const { dn, passwordRequirements } = parameters;+ let resolvedConnection: typeof connection | undefined;+ const getResolvedConnection = async () => {+ if (!resolvedConnection) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ resolvedConnection = { ...connection, gatewayId: effectiveGatewayId, gatewayPoolId: null };+ }+ return resolvedConnection;+ };+const $verifyCredentials = async (verifyOpts: Pick<TLdapConnection["credentials"], "dn" | "password"> & { url?: string }) => {try {+ const conn = await getResolvedConnection();await executeWithPotentialGateway(- { ...connection, credentials: { ...connection.credentials, ...verifyOpts } },+ { ...conn, credentials: { ...conn.credentials, ...verifyOpts } },gatewayV2Service,async () => {});@@ -210,9 +223,10 @@ export const ldapPasswordRotationFactory: TRotationFactory<// referral error here so we can re-throw it after the proxy's catch block.let capturedReferralError: LdapReferralError | undefined;+ const conn = await getResolvedConnection();try {await executeWithPotentialGateway(- { ...connection, credentials: targetCredentials },+ { ...conn, credentials: targetCredentials },gatewayV2Service,async (client) => {let userDn: string;diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.tsindex 77bd7e69ac..d4f60347fd 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts@@ -54,6 +54,7 @@ const baseSecretRotationV2Query = ({db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("connectionGatewayPoolId"),db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),@@ -109,6 +110,7 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRotaconnectionUpdatedAt,connectionVersion,connectionGatewayId,+ connectionGatewayPoolId,connectionProjectId,connectionIsPlatformManagedCredentials,connectionIsAutoRotationEnabled,@@ -131,6 +133,7 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRotaupdatedAt: connectionUpdatedAt,version: connectionVersion,gatewayId: connectionGatewayId,+ gatewayPoolId: connectionGatewayPoolId,projectId: connectionProjectId,isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,isAutoRotationEnabled: connectionIsAutoRotationEnableddiff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.tsindex bbd4ab5dba..cee9b3ae62 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts@@ -89,6 +89,7 @@ import { TSecretVersionV2DALFactory } from "@app/services/secret-v2-bridge/secreimport { TSecretVersionV2TagDALFactory } from "@app/services/secret-v2-bridge/secret-version-tag-dal";import { WebhookEvents } from "@app/services/webhook/webhook-types";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import { awsIamUserSecretRotationFactory } from "./aws-iam-user-secret/aws-iam-user-secret-rotation-fns";import { dbtServiceTokenRotationFactory } from "./dbt-service-token/dbt-service-token-rotation-fns";@@ -157,6 +158,7 @@ export type TSecretRotationV2ServiceFactoryDep = {folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export type TSecretRotationV2ServiceFactory = ReturnType<typeof secretRotationV2ServiceFactory>;@@ -213,7 +215,8 @@ export const secretRotationV2ServiceFactory = ({folderCommitService,appConnectionDAL,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TSecretRotationV2ServiceFactoryDep) => {const $queueSendSecretRotationStatusNotification = async (secretRotation: TSecretRotationV2Raw) => {const appCfg = getConfig();@@ -558,7 +561,8 @@ export const secretRotationV2ServiceFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService);// Perform ALL validation checks BEFORE rotating credentials on the external system.@@ -927,7 +931,8 @@ export const secretRotationV2ServiceFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService);const generatedCredentials = await decryptSecretRotationCredentials({@@ -1244,7 +1249,8 @@ export const secretRotationV2ServiceFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService);const updatedRotation = await rotationFactory.rotateCredentials(@@ -1816,7 +1822,8 @@ export const secretRotationV2ServiceFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService);// Issue new credentials using login-as-root mode (app connection credentials)diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.tsindex 6e6ed6e2d1..41b8356929 100644--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts@@ -6,6 +6,7 @@ import { TAppConnectionDALFactory } from "@app/services/app-connection/app-conneimport { TKmsServiceFactory } from "@app/services/kms/kms-service";import { SecretsOrderBy } from "@app/services/secret/secret-types";+import { TGatewayPoolServiceFactory } from "../gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "../gateway-v2/gateway-v2-service";import {TAuth0ClientSecretRotation,@@ -400,7 +401,8 @@ export type TRotationFactory<appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">,kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {issueCredentials: TRotationFactoryIssueCredentials<C, P>;revokeCredentials: TRotationFactoryRevokeCredentials<C>;diff --git a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.tsindex 5becb191f0..365ab11d78 100644--- a/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-fns.ts@@ -43,7 +43,7 @@ const ORACLE_PASSWORD_REQUIREMENTS = {export const sqlCredentialsRotationFactory: TRotationFactory<TSqlCredentialsRotationWithConnection,TSqlCredentialsRotationGeneratedCredentials-> = (secretRotation, _appConnectionDAL, _kmsService, gatewayService, gatewayV2Service) => {+> = (secretRotation, _appConnectionDAL, _kmsService, gatewayService, gatewayV2Service, gatewayPoolService) => {const {connection,parameters: {@@ -67,18 +67,31 @@ export const sqlCredentialsRotationFactory: TRotationFactory<connection.app === AppConnection.OracleDB ? ORACLE_PASSWORD_REQUIREMENTS : DEFAULT_PASSWORD_REQUIREMENTS;const passwordRequirement = userProvidedPasswordRequirements || defaultPasswordRequirement;- const executeOperation = <T>(+ let resolvedConnection: typeof connection | undefined;+ const getResolvedConnection = async () => {+ if (!resolvedConnection) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ resolvedConnection = { ...connection, gatewayId: effectiveGatewayId, gatewayPoolId: null };+ }+ return resolvedConnection;+ };++ const executeOperation = async <T>(operation: (client: Knex) => Promise<T>,credentialsOverride?: TSqlCredentialsRotationGeneratedCredentials[number]) => {+ const conn = await getResolvedConnection();const finalCredentials = {- ...connection.credentials,+ ...conn.credentials,...credentialsOverride};return executeWithPotentialGateway({- ...connection,+ ...conn,credentials: finalCredentials},gatewayService,diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.tsindex 84fc1d3f46..fec28bec31 100644--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns.ts@@ -306,7 +306,7 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<TUnixLinuxLocalAccountRotationWithConnection,TUnixLinuxLocalAccountRotationGeneratedCredentials,TUnixLinuxLocalAccountRotationInput["temporaryParameters"]-> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service) => {+> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service, gatewayPoolService) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const {username,@@ -316,17 +316,28 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<} = parameters;const shouldUseSudo = Boolean(useSudo);- // Helper to verify SSH credentials work- // Tries direct SSH first, then falls back to su via app connection+ let resolvedConnection: typeof connection | undefined;+ const getResolvedConnection = async () => {+ if (!resolvedConnection) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ resolvedConnection = { ...connection, gatewayId: effectiveGatewayId, gatewayPoolId: null };+ }+ return resolvedConnection;+ };+const $verifyCredentials = async (targetUsername: string, targetPassword: string): Promise<void> => {+ const conn = await getResolvedConnection();const verifyConfig: TSshConnectionConfig = {method: SshConnectionMethod.Password,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,credentials: {- host: connection.credentials.host,- port: connection.credentials.port,+ host: conn.credentials.host,+ port: conn.credentials.port,username: targetUsername,password: targetPassword}@@ -351,22 +362,27 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<// Attempt 2: SSH with app connection, then su to target userconst appConnConfig: TSshConnectionConfig = {- method: connection.method,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,- credentials: connection.credentials+ method: conn.method,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,+ credentials: conn.credentials} as TSshConnectionConfig;try {- await executeWithPotentialGateway(appConnConfig, gatewayV2Service, async (targetHost, targetPort) => {- const client = await getSshConnectionClient(appConnConfig, targetHost, targetPort);- try {- await verifySuLogin(client, targetUsername, targetPassword);- } finally {- client.destroy();- }- });+ await executeWithPotentialGateway(+ appConnConfig,+ gatewayV2Service,+ async (targetHost, targetPort) => {+ const client = await getSshConnectionClient(appConnConfig, targetHost, targetPort);+ try {+ await verifySuLogin(client, targetUsername, targetPassword);+ } finally {+ client.destroy();+ }+ },+ gatewayPoolService+ );} catch (suError) {throw new Error(`Failed to verify credentials. Direct SSH login failed: ${directSshError}. Fallback su verification also failed: ${(suError as Error).message}`@@ -376,23 +392,22 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<// Main password rotation logicconst $rotatePassword = async (currentPassword?: string): Promise<{ username: string; password: string }> => {- const { credentials } = connection;+ const conn = await getResolvedConnection();+ const { credentials } = conn;const newPassword = generatePassword(passwordRequirements);const isSelfRotation = rotationMethod === UnixLinuxLocalAccountRotationMethod.LoginAsTarget;if (username === credentials.username)throw new BadRequestError({ message: "Provided username is used in Infisical app connections." });- // Determine which credentials to use for the SSH connectionlet connectConfig: TSshConnectionConfig;if (isSelfRotation && currentPassword) {- // For self-rotation with current password, connect as the target userconnectConfig = {method: SshConnectionMethod.Password,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,credentials: {host: credentials.host,port: credentials.port,@@ -401,13 +416,12 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<}};} else {- // For managed rotation, connect with the app connection credentials (admin)connectConfig = {- method: connection.method,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,- credentials: connection.credentials+ method: conn.method,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,+ credentials: conn.credentials} as TSshConnectionConfig;}@@ -416,13 +430,11 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<try {if (isSelfRotation && currentPassword) {- // Self rotation: user changes their own password using passwd commandawait changeSelfPassword(client, currentPassword, newPassword);} else {- // Managed rotation: admin changes user's password using passwd (with sudo if specified)const appConnectionPassword =- connection.method === SshConnectionMethod.Password- ? (connection.credentials as { password: string }).password+ conn.method === SshConnectionMethod.Password+ ? (conn.credentials as { password: string }).password: undefined;await changeManagedPassword(client, username, newPassword, shouldUseSudo, appConnectionPassword);}diff --git a/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-fns.tsindex f431e82bde..a10e787d3c 100644--- a/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/windows-local-account-rotation/windows-local-account-rotation-fns.ts@@ -25,24 +25,33 @@ export const windowsLocalAccountRotationFactory: TRotationFactory<TWindowsLocalAccountRotationWithConnection,TWindowsLocalAccountRotationGeneratedCredentials,TWindowsLocalAccountRotationInput["temporaryParameters"]-> = (secretRotation, _appConnectionDAL, _kmsService, _gatewayService, gatewayV2Service) => {+> = (secretRotation, _appConnectionDAL, _kmsService, _gatewayService, gatewayV2Service, gatewayPoolService) => {const { connection, parameters, secretsMapping, activeIndex } = secretRotation;const { username, passwordRequirements, rotationMethod = WindowsLocalAccountRotationMethod.LoginAsRoot } = parameters;- // Helper to verify Windows credentials work via SMB- // Note: We don't pass the domain when verifying the rotated account because it's a local account,- // not a domain account. The domain is only used for the app connection (admin) credentials.+ let resolvedConnection: typeof connection | undefined;+ const getResolvedConnection = async () => {+ if (!resolvedConnection) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ resolvedConnection = { ...connection, gatewayId: effectiveGatewayId, gatewayPoolId: null };+ }+ return resolvedConnection;+ };+const $verifyCredentials = async (targetUsername: string, targetPassword: string): Promise<void> => {- const { credentials } = connection;+ const conn = await getResolvedConnection();const verifyConfig: TSmbConnectionConfig = {method: SmbConnectionMethod.Credentials,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,credentials: {- host: credentials.host,- port: credentials.port,+ host: conn.credentials.host,+ port: conn.credentials.port,domain: undefined,username: targetUsername,password: targetPassword@@ -50,14 +59,13 @@ export const windowsLocalAccountRotationFactory: TRotationFactory<};await executeSmbWithPotentialGateway(verifyConfig, gatewayV2Service, async (targetHost, targetPort) => {- // Verify without domain - local accounts don't belong to a domainawait verifyWindowsCredentials(targetHost, targetPort, targetUsername, targetPassword, undefined);});};- // Main password rotation logicconst $rotatePassword = async (currentPassword?: string): Promise<{ username: string; password: string }> => {- const { credentials } = connection;+ const conn = await getResolvedConnection();+ const { credentials } = conn;const credentialsDomain: string | undefined = credentials.domain;const credentialsPassword: string = credentials.password;const newPassword = generatePassword(passwordRequirements);@@ -77,16 +85,14 @@ export const windowsLocalAccountRotationFactory: TRotationFactory<if (isSelfRotation && currentPassword) {smbConfig.adminUser = username;smbConfig.adminPassword = currentPassword;- // Clear domain for self-rotation - local accounts don't belong to a domainsmbConfig.domain = undefined;}- // Determine which credentials to use for the SMB connectionconst connectConfig: TSmbConnectionConfig = {- method: connection.method,- app: connection.app,- orgId: connection.orgId,- gatewayId: connection.gatewayId,+ method: conn.method,+ app: conn.app,+ orgId: conn.orgId,+ gatewayId: conn.gatewayId,credentials: {host: credentials.host,port: credentials.port,@@ -99,7 +105,6 @@ export const windowsLocalAccountRotationFactory: TRotationFactory<if (isSelfRotation && currentPassword) {connectConfig.credentials.username = username;connectConfig.credentials.password = currentPassword;- // Clear domain for self-rotation - local accounts don't belong to a domainconnectConfig.credentials.domain = undefined;}diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.tsindex cd6097703b..83bbc37b51 100644--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts@@ -50,6 +50,7 @@ const baseSecretScanningDataSourceQuery = ({db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("connectionGatewayPoolId"),db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),@@ -87,6 +88,7 @@ const expandSecretScanningDataSource = <connectionVersion,connectionIsPlatformManagedCredentials,connectionGatewayId,+ connectionGatewayPoolId,connectionProjectId,...el} = dataSource;@@ -109,6 +111,7 @@ const expandSecretScanningDataSource = <isAutoRotationEnabled: connectionIsAutoRotationEnabled,isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,gatewayId: connectionGatewayId,+ gatewayPoolId: connectionGatewayPoolId,projectId: connectionProjectId}: undefineddiff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 65a8ad4b11..79abd383d1 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -1328,6 +1328,7 @@ export const registerRoutes = async (const pamResourceDAL = pamResourceDALFactory(db);const pamDiscoverySourceDAL = pamDiscoverySourceDALFactory(db);+ const pamDomainDAL = pamDomainDALFactory(db);const aiMcpServerDAL = aiMcpServerDALFactory(db);const sshCertificateAuthorityService = sshCertificateAuthorityServiceFactory({@@ -1511,7 +1512,13 @@ export const registerRoutes = async (gatewayV2Service,permissionService,licenseService,- identityKubernetesAuthDAL+ identityKubernetesAuthDAL,+ pkiDiscoveryConfigDAL,+ pamDomainDAL,+ pamResourceDAL,+ pamDiscoverySourceDAL,+ appConnectionDAL,+ dynamicSecretDAL});const secretSyncQueue = secretSyncQueueFactory({@@ -1540,6 +1547,7 @@ export const registerRoutes = async (licenseService,gatewayService,gatewayV2Service,+ gatewayPoolService,notificationService,projectSlackConfigDAL,projectMicrosoftTeamsConfigDAL,@@ -2156,7 +2164,8 @@ export const registerRoutes = async (const dynamicSecretProviders = buildDynamicSecretProviders({gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const dynamicSecretQueueService = dynamicSecretLeaseQueueServiceFactory({@@ -2184,6 +2193,7 @@ export const registerRoutes = async (kmsService,gatewayDAL,gatewayV2DAL,+ gatewayPoolService,resourceMetadataDAL});@@ -2342,6 +2352,7 @@ export const registerRoutes = async (licenseService,gatewayService,gatewayV2Service,+ gatewayPoolService,gatewayDAL,gatewayV2DAL,projectDAL,@@ -2445,7 +2456,8 @@ export const registerRoutes = async (queueService,appConnectionDAL,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const insightsService = insightsServiceFactory({@@ -2476,7 +2488,8 @@ export const registerRoutes = async (certificateAuthorityDAL,certificateAuthorityCertDAL,certificateSyncDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const pkiSyncCleanup = pkiSyncCleanupQueueServiceFactory({@@ -2573,7 +2586,8 @@ export const registerRoutes = async (pkiSyncQueue,certificateRequestDAL,resourceMetadataDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const certificateEstService = certificateEstServiceFactory({@@ -2657,7 +2671,8 @@ export const registerRoutes = async (certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const certificateApprovalService = certificateApprovalServiceFactory({@@ -2853,7 +2868,8 @@ export const registerRoutes = async (kmsService,queueService,gatewayV2Service,- gatewayV2DAL+ gatewayV2DAL,+ gatewayPoolService});const pkiDiscoveryService = pkiDiscoveryServiceFactory({@@ -2861,6 +2877,8 @@ export const registerRoutes = async (pkiDiscoveryScanHistoryDAL,permissionService,gatewayV2DAL,+ gatewayPoolDAL,+ gatewayPoolService,queuePkiDiscoveryScan: pkiDiscoveryQueue.queuePkiDiscoveryScan});@@ -2941,7 +2959,6 @@ export const registerRoutes = async (});const pamFolderDAL = pamFolderDALFactory(db);- const pamDomainDAL = pamDomainDALFactory(db);const pamResourceFavoriteDAL = pamResourceFavoriteDALFactory(db);const pamAccountDAL = pamAccountDALFactory(db);const pamAccountPolicyDAL = pamAccountPolicyDALFactory(db);@@ -2993,6 +3010,7 @@ export const registerRoutes = async (permissionService,kmsService,gatewayV2Service,+ gatewayPoolService,resourceMetadataDAL,appConnectionDAL,pamProjectRecordingConfigDAL@@ -3004,6 +3022,7 @@ export const registerRoutes = async (permissionService,kmsService,gatewayV2Service,+ gatewayPoolService,resourceMetadataDAL});@@ -3046,6 +3065,7 @@ export const registerRoutes = async (pamAccountPolicyDAL,pamResourceRotationRulesDAL,gatewayV2Service,+ gatewayPoolService,kmsService,pamResourceDAL,pamSessionDAL,@@ -3102,6 +3122,7 @@ export const registerRoutes = async (pamSessionDAL,pamSessionExpirationService,gatewayV2Service,+ gatewayPoolService,kmsService,userDAL,mfaSessionService,@@ -3124,7 +3145,8 @@ export const registerRoutes = async (kmsService,queueService,gatewayV2Service,- gatewayV2DAL+ gatewayV2DAL,+ gatewayPoolService});const pamDiscoverySourceService = pamDiscoverySourceServiceFactory({@@ -3140,6 +3162,7 @@ export const registerRoutes = async (kmsService,gatewayV2DAL,gatewayV2Service,+ gatewayPoolService,pamDiscoveryQueue});@@ -3186,7 +3209,8 @@ export const registerRoutes = async (externalMigrationConfigDAL,secretService,auditLogService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});// setup the communication with license key serverdiff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.tsindex 912a887686..15a9ef82f1 100644--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts@@ -31,6 +31,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extenisPlatformManagedCredentials?: boolean;isAutoRotationEnabled?: boolean | null;gatewayId?: string | null;+ gatewayPoolId?: string | null;projectId?: string;rotation?: TCreateAppConnectionCredentialRotationSchema | null;}>;@@ -40,6 +41,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extendescription?: string | null;isPlatformManagedCredentials?: boolean;gatewayId?: string | null;+ gatewayPoolId?: string | null;isAutoRotationEnabled?: boolean | null;rotation?: Partial<TCreateAppConnectionCredentialRotationSchema> | null;}>;@@ -288,6 +290,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extendescription,isPlatformManagedCredentials,gatewayId,+ gatewayPoolId,projectId,isAutoRotationEnabled,rotation@@ -302,6 +305,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extendescription,isPlatformManagedCredentials,gatewayId,+ gatewayPoolId,projectId,rotation,isAutoRotationEnabled: isAutoRotationEnabled ?? false@@ -369,6 +373,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extendescription,isPlatformManagedCredentials,gatewayId,+ gatewayPoolId,rotation,isAutoRotationEnabled} = req.body;@@ -382,6 +387,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I extendescription,isPlatformManagedCredentials,gatewayId,+ gatewayPoolId,isAutoRotationEnabled: isAutoRotationEnabled ?? undefined,rotation: rotation ?? undefined},diff --git a/backend/src/server/routes/v3/external-migration-router.ts b/backend/src/server/routes/v3/external-migration-router.tsindex 59592bcfad..f91d74ff48 100644--- a/backend/src/server/routes/v3/external-migration-router.ts+++ b/backend/src/server/routes/v3/external-migration-router.ts@@ -79,7 +79,8 @@ export const registerExternalMigrationRouter = async (server: FastifyZodProvidervaultNamespace: z.string().trim().optional(),vaultUrl: z.string(),mappingType: z.nativeEnum(VaultMappingType),- gatewayId: z.string().optional()+ gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional()})},onRequest: verifyAuth([AuthMode.JWT]),diff --git a/backend/src/services/app-connection/app-connection-dal.ts b/backend/src/services/app-connection/app-connection-dal.tsindex 67f3955a71..afecaa4598 100644--- a/backend/src/services/app-connection/app-connection-dal.ts+++ b/backend/src/services/app-connection/app-connection-dal.ts@@ -178,5 +178,37 @@ export const appConnectionDALFactory = (db: TDbClient) => {return parseInt(String(result?.count || "0"), 10);};- return { ...appConnectionOrm, findAppConnectionUsageById, findWithProjectDetails, findByGatewayId, countByGatewayId };+ const findByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const docs = await (tx || db.replicaNode())(TableName.AppConnection)+ .leftJoin(TableName.Project, `${TableName.AppConnection}.projectId`, `${TableName.Project}.id`)+ .where(`${TableName.AppConnection}.gatewayPoolId`, gatewayPoolId)+ .select(+ db.ref("id").withSchema(TableName.AppConnection),+ db.ref("name").withSchema(TableName.AppConnection),+ db.ref("app").withSchema(TableName.AppConnection),+ db.ref("projectId").withSchema(TableName.AppConnection),+ db.ref("name").withSchema(TableName.Project).as("projectName")+ );++ return docs;+ };++ const countByGatewayPoolId = async (gatewayPoolId: string, tx?: Knex) => {+ const result = await (tx || db.replicaNode())(TableName.AppConnection)+ .where(`${TableName.AppConnection}.gatewayPoolId`, gatewayPoolId)+ .count("id")+ .first();++ return parseInt(String(result?.count || "0"), 10);+ };++ return {+ ...appConnectionOrm,+ findAppConnectionUsageById,+ findWithProjectDetails,+ findByGatewayId,+ countByGatewayId,+ findByGatewayPoolId,+ countByGatewayPoolId+ };};diff --git a/backend/src/services/app-connection/app-connection-schemas.ts b/backend/src/services/app-connection/app-connection-schemas.tsindex 3687b5a372..1ac7fe167f 100644--- a/backend/src/services/app-connection/app-connection-schemas.ts+++ b/backend/src/services/app-connection/app-connection-schemas.ts@@ -79,6 +79,12 @@ export const GenericCreateAppConnectionFieldsSchema = (.undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }).or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })).describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),+ gatewayPoolId: supportsGateways+ ? z.string().uuid().nullish().describe("The Gateway Pool ID to use for this connection.")+ : z+ .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),isAutoRotationEnabled: supportsCredentialRotation? z.boolean().optional().describe(AppConnections.CREATE(app).isAutoRotationEnabled)@@ -104,6 +110,13 @@ export const GenericCreateAppConnectionFieldsSchema = (path: ["rotation"]});}+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool",+ path: ["gatewayPoolId"]+ });+ }});export const GenericUpdateAppConnectionFieldsSchema = (@@ -114,42 +127,58 @@ export const GenericUpdateAppConnectionFieldsSchema = (supportsCredentialRotation = false}: TAppConnectionBaseConfig = {}) =>- z.object({- name: slugSchema({ field: "name" }).describe(AppConnections.UPDATE(app).name).optional(),- description: z- .string()- .trim()- .max(256, "Description cannot exceed 256 characters")- .nullish()- .describe(AppConnections.UPDATE(app).description),- isPlatformManagedCredentials: supportsPlatformManagedCredentials- ? z.boolean().optional().describe(AppConnections.UPDATE(app).isPlatformManagedCredentials)- : z- .literal(false, {- errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })- })- .optional()- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),- gatewayId: supportsGateways- ? z.string().uuid().nullish().describe("The Gateway ID to use for this connection.")- : z- .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })- .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),+ z+ .object({+ name: slugSchema({ field: "name" }).describe(AppConnections.UPDATE(app).name).optional(),+ description: z+ .string()+ .trim()+ .max(256, "Description cannot exceed 256 characters")+ .nullish()+ .describe(AppConnections.UPDATE(app).description),+ isPlatformManagedCredentials: supportsPlatformManagedCredentials+ ? z.boolean().optional().describe(AppConnections.UPDATE(app).isPlatformManagedCredentials)+ : z+ .literal(false, {+ errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ })+ .optional()+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),+ gatewayId: supportsGateways+ ? z.string().uuid().nullish().describe("The Gateway ID to use for this connection.")+ : z+ .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),+ gatewayPoolId: supportsGateways+ ? z.string().uuid().nullish().describe("The Gateway Pool ID to use for this connection.")+ : z+ .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),- isAutoRotationEnabled: supportsCredentialRotation- ? z.boolean().optional().describe(AppConnections.UPDATE(app).isAutoRotationEnabled)- : z- .literal(false, {- errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })- })- .optional()- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),+ isAutoRotationEnabled: supportsCredentialRotation+ ? z.boolean().optional().describe(AppConnections.UPDATE(app).isAutoRotationEnabled)+ : z+ .literal(false, {+ errorMap: () => ({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ })+ .optional()+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`),- rotation: supportsCredentialRotation- ? UpdateAppConnectionCredentialRotationSchema.optional().describe(AppConnections.UPDATE(app).rotation)- : z- .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })- .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))- .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`)- });+ rotation: supportsCredentialRotation+ ? UpdateAppConnectionCredentialRotationSchema.optional().describe(AppConnections.UPDATE(app).rotation)+ : z+ .undefined({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` })+ .or(z.null({ message: `Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections` }))+ .describe(`Not supported for ${APP_CONNECTION_NAME_MAP[app]} Connections.`)+ })+ .superRefine((data, ctx) => {+ if (data.gatewayId && data.gatewayPoolId) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Cannot specify both a gateway and a gateway pool",+ path: ["gatewayPoolId"]+ });+ }+ });diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex db20b4fcf5..4c59572e6c 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -9,6 +9,7 @@ import { ociConnectionService } from "@app/ee/services/app-connections/oci/oci-cimport { ValidateOracleDBConnectionCredentialsSchema } from "@app/ee/services/app-connections/oracledb";import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+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";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";@@ -169,6 +170,10 @@ export type TAppConnectionServiceFactoryDep = {licenseService: Pick<TLicenseServiceFactory, "getPlan">;gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "pickRandomHealthyGateway" | "resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId"+ >;gatewayDAL: Pick<TGatewayDALFactory, "find">;gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;projectDAL: Pick<TProjectDALFactory, "findProjectById">;@@ -253,6 +258,7 @@ export const appConnectionServiceFactory = ({licenseService,gatewayService,gatewayV2Service,+ gatewayPoolService,gatewayDAL,gatewayV2DAL,projectDAL,@@ -421,6 +427,7 @@ export const appConnectionServiceFactory = ({app,credentials,gatewayId,+ gatewayPoolId,projectId,rotation,isAutoRotationEnabled,@@ -428,6 +435,10 @@ export const appConnectionServiceFactory = ({}: TCreateAppConnectionDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const { permission: orgPermission } = await permissionService.getOrgPermission({actorId: actor.id,actor: actor.type,@@ -485,6 +496,20 @@ export const appConnectionServiceFactory = ({}}+ if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actor.orgId,+ actor+ });+ }++ let validationGatewayId: string | null | undefined = gatewayId;+ if (gatewayPoolId) {+ const picked = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);+ validationGatewayId = picked.id;+ }+await enterpriseAppCheck(licenseService,app,@@ -498,7 +523,7 @@ export const appConnectionServiceFactory = ({credentials,method,orgId: actor.orgId,- gatewayId+ gatewayId: validationGatewayId} as TAppConnectionConfig,gatewayService,gatewayV2Service,@@ -521,7 +546,8 @@ export const appConnectionServiceFactory = ({encryptedCredentials,method,app,- gatewayId,+ gatewayId: gatewayPoolId ? null : gatewayId,+ gatewayPoolId: gatewayPoolId ?? null,projectId,isAutoRotationEnabled,...params@@ -552,7 +578,7 @@ export const appConnectionServiceFactory = ({orgId: actor.orgId,credentials: validatedCredentials,method,- gatewayId+ gatewayId: validationGatewayId} as TAppConnectionConfig,(platformCredentials) => createConnection(platformCredentials),gatewayService,@@ -577,9 +603,21 @@ export const appConnectionServiceFactory = ({};const updateAppConnection = async (- { connectionId, credentials, gatewayId, isAutoRotationEnabled, rotation, ...params }: TUpdateAppConnectionDTO,+ {+ connectionId,+ credentials,+ gatewayId,+ gatewayPoolId,+ isAutoRotationEnabled,+ rotation,+ ...params+ }: TUpdateAppConnectionDTO,actor: OrgServiceActor) => {+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }+const appConnection = await appConnectionDAL.findById(connectionId);if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });@@ -638,6 +676,36 @@ export const appConnectionServiceFactory = ({}}+ // Mutual exclusion: setting one clears the other.+ let gatewayIdValue: string | null | undefined;+ let gatewayPoolIdValue: string | null | undefined;+ if (gatewayId !== undefined && gatewayPoolId !== undefined) {+ gatewayIdValue = gatewayId;+ gatewayPoolIdValue = gatewayPoolId;+ } else if (gatewayId !== undefined) {+ gatewayIdValue = gatewayId;+ gatewayPoolIdValue = gatewayId !== null ? null : undefined;+ } else if (gatewayPoolId !== undefined) {+ gatewayPoolIdValue = gatewayPoolId;+ gatewayIdValue = gatewayPoolId !== null ? null : undefined;+ }++ const effectiveGatewayIdForUpdate = gatewayIdValue !== undefined ? gatewayIdValue : appConnection.gatewayId;+ const effectiveGatewayPoolIdForUpdate =+ gatewayPoolIdValue !== undefined ? gatewayPoolIdValue : appConnection.gatewayPoolId;++ if (effectiveGatewayPoolIdForUpdate) {+ const isNewPoolAttachment =+ gatewayPoolId !== undefined && gatewayPoolId !== appConnection.gatewayPoolId && gatewayPoolId !== null;+ if (isNewPoolAttachment) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: effectiveGatewayPoolIdForUpdate,+ orgId: actor.orgId,+ actor+ });+ }+ }+// prevent updating credentials or management status if platform managedif (appConnection.isPlatformManagedCredentials && (params.isPlatformManagedCredentials === false || credentials)) {throw new BadRequestError({@@ -646,10 +714,16 @@ export const appConnectionServiceFactory = ({}let updatedCredentials: undefined | TAppConnection["credentials"];+ let validationGatewayId: string | null | undefined;const { app, method } = appConnection as DiscriminativePick<TAppConnectionConfig, "app" | "method">;if (credentials) {+ validationGatewayId = effectiveGatewayIdForUpdate;+ if (effectiveGatewayPoolIdForUpdate) {+ const picked = await gatewayPoolService.pickRandomHealthyGateway(effectiveGatewayPoolIdForUpdate);+ validationGatewayId = picked.id;+ }if (!VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[app].safeParse({method,@@ -668,7 +742,7 @@ export const appConnectionServiceFactory = ({orgId: actor.orgId,credentials,method,- gatewayId+ gatewayId: validationGatewayId} as TAppConnectionConfig,gatewayService,gatewayV2Service,@@ -695,7 +769,8 @@ export const appConnectionServiceFactory = ({{orgId: actor.orgId,encryptedCredentials,- gatewayId,+ ...(gatewayIdValue !== undefined && { gatewayId: gatewayIdValue }),+ ...(gatewayPoolIdValue !== undefined && { gatewayPoolId: gatewayPoolIdValue }),...params},tx@@ -728,7 +803,7 @@ export const appConnectionServiceFactory = ({orgId: actor.orgId,credentials: updatedCredentials,method,- gatewayId+ gatewayId: validationGatewayId} as TAppConnectionConfig,(platformCredentials) => updateConnection(platformCredentials, tx),gatewayService,@@ -1080,7 +1155,7 @@ export const appConnectionServiceFactory = ({listAvailableAppConnectionsForUser,findAppConnectionUsageById,triggerCredentialRotation,- github: githubConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service),+ github: githubConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service, gatewayPoolService),githubRadar: githubRadarConnectionService(connectAppConnectionById),gcp: gcpConnectionService(connectAppConnectionById),databricks: databricksConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),@@ -1093,7 +1168,7 @@ export const appConnectionServiceFactory = ({azureClientSecrets: azureClientSecretsConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),azureDevOps: azureDevOpsConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),auth0: auth0ConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),- hcvault: hcVaultConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service),+ hcvault: hcVaultConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service, gatewayPoolService),windmill: windmillConnectionService(connectAppConnectionById),teamcity: teamcityConnectionService(connectAppConnectionById),oci: ociConnectionService(connectAppConnectionById, licenseService),diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.tsindex 06271e6115..cfda59d106 100644--- a/backend/src/services/app-connection/app-connection-types.ts+++ b/backend/src/services/app-connection/app-connection-types.ts@@ -543,6 +543,7 @@ export type TCreateAppConnectionDTO = Pick<| "description"| "isPlatformManagedCredentials"| "gatewayId"+ | "gatewayPoolId"| "projectId"| "rotation"| "isAutoRotationEnabled"diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.tsindex d375637828..e104177575 100644--- a/backend/src/services/app-connection/github/github-connection-fns.ts+++ b/backend/src/services/app-connection/github/github-connection-fns.ts@@ -4,6 +4,7 @@ import RE2 from "re2";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { getConfig } from "@app/lib/config/env";import { request as httpRequest } from "@app/lib/config/request";@@ -175,7 +176,8 @@ export const requestWithGitHubGateway = async <T>(export const getGitHubAppAuthToken = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const appCfg = getConfig();const appId = appCfg.INF_APP_CONNECTION_GITHUB_APP_ID;@@ -208,12 +210,17 @@ export const getGitHubAppAuthToken = async (const apiBaseUrl = await getGitHubInstanceApiUrl(appConnection);const { installationId } = appConnection.credentials;- const gatewayConnectionDetails = appConnection.gatewayId- ? await getGitHubGatewayConnectionDetails(appConnection.gatewayId, apiBaseUrl, gatewayV2Service)+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: appConnection.gatewayId,+ gatewayPoolId: appConnection.gatewayPoolId+ });++ const gatewayConnectionDetails = effectiveGatewayId+ ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service): undefined;const response = await requestWithGitHubGateway<{ token: string; expires_at: string }>(- appConnection,+ { gatewayId: effectiveGatewayId },gatewayService,gatewayV2Service,{@@ -258,6 +265,7 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,path: string,dataMapper?: (data: R) => T[]): Promise<T[]> => {@@ -273,7 +281,7 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(token = credentials.personalAccessToken;break;default:- token = await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service);+ token = await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service, gatewayPoolService);}const baseUrl = `https://${await getGitHubInstanceApiUrl(appConnection)}${path}`;@@ -281,16 +289,21 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(initialUrlObj.searchParams.set("per_page", "100");const apiBaseUrl = await getGitHubInstanceApiUrl(appConnection);- const gatewayConnectionDetails = appConnection.gatewayId- ? await getGitHubGatewayConnectionDetails(appConnection.gatewayId, apiBaseUrl, gatewayV2Service)+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: appConnection.gatewayId,+ gatewayPoolId: appConnection.gatewayPoolId+ });+ const gatewayConnectionDetails = effectiveGatewayId+ ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service): undefined;+ const resolvedConn = { gatewayId: effectiveGatewayId };let results: T[] = [];const maxIterations = 1000;// Make initial request to get link headerconst firstResponse: AxiosResponse<R> = await requestWithGitHubGateway<R>(- appConnection,+ resolvedConn,gatewayService,gatewayV2Service,{@@ -324,7 +337,7 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(pageRequests.push(requestWithGitHubGateway<R>(- appConnection,+ resolvedConn,gatewayService,gatewayV2Service,{@@ -354,7 +367,7 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(while (url && i < maxIterations) {// eslint-disable-next-line no-await-in-loopconst response: AxiosResponse<R> = await requestWithGitHubGateway<R>(- appConnection,+ resolvedConn,gatewayService,gatewayV2Service,{@@ -407,13 +420,15 @@ type GitHubEnvironment = {export const getGitHubRepositories = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {if (appConnection.method === GitHubConnectionMethod.App) {return makePaginatedGitHubRequest<GitHubRepository, { repositories: GitHubRepository[] }>(appConnection,gatewayService,gatewayV2Service,+ gatewayPoolService,"/installation/repositories",(data) => data.repositories);@@ -423,6 +438,7 @@ export const getGitHubRepositories = async (appConnection,gatewayService,gatewayV2Service,+ gatewayPoolService,"/user/repos");@@ -432,13 +448,21 @@ export const getGitHubRepositories = async (export const getGitHubOrganizations = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {if (appConnection.method === GitHubConnectionMethod.App) {const installationRepositories = await makePaginatedGitHubRequest<GitHubRepository,{ repositories: GitHubRepository[] }- >(appConnection, gatewayService, gatewayV2Service, "/installation/repositories", (data) => data.repositories);+ >(+ appConnection,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ "/installation/repositories",+ (data) => data.repositories+ );const organizationMap: Record<string, GitHubOrganization> = {};installationRepositories.forEach((repo) => {@@ -450,13 +474,20 @@ export const getGitHubOrganizations = async (return Object.values(organizationMap);}- return makePaginatedGitHubRequest<GitHubOrganization>(appConnection, gatewayService, gatewayV2Service, "/user/orgs");+ return makePaginatedGitHubRequest<GitHubOrganization>(+ appConnection,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ "/user/orgs"+ );};export const getGitHubEnvironments = async (appConnection: TGitHubConnection,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,owner: string,repo: string) => {@@ -465,6 +496,7 @@ export const getGitHubEnvironments = async (appConnection,gatewayService,gatewayV2Service,+ gatewayPoolService,`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/environments`,(data) => data.environments);@@ -501,13 +533,14 @@ export const validateGitHubConnectionCredentials = async (const gatewayConnectionDetails = config.gatewayId? await getGitHubGatewayConnectionDetails(config.gatewayId, apiBaseUrl, gatewayV2Service): undefined;+ const resolvedConfig = { gatewayId: config.gatewayId };// PAT validationif (method === GitHubConnectionMethod.Pat) {try {const apiUrl = await getGitHubInstanceApiUrl(config);await requestWithGitHubGateway(- config,+ resolvedConfig,gatewayService,gatewayV2Service,{@@ -574,7 +607,7 @@ export const validateGitHubConnectionCredentials = async (try {tokenResp = await requestWithGitHubGateway<GithubTokenRespData>(- config,+ resolvedConfig,gatewayService,gatewayV2Service,{@@ -632,7 +665,7 @@ export const validateGitHubConnectionCredentials = async (};}[];}>(- config,+ resolvedConfig,gatewayService,gatewayV2Service,{diff --git a/backend/src/services/app-connection/github/github-connection-service.ts b/backend/src/services/app-connection/github/github-connection-service.tsindex 8292d94e0c..dd590a7d5f 100644--- a/backend/src/services/app-connection/github/github-connection-service.ts+++ b/backend/src/services/app-connection/github/github-connection-service.ts@@ -1,4 +1,5 @@import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { OrgServiceActor } from "@app/lib/types";import { AppConnection } from "@app/services/app-connection/app-connection-enums";@@ -24,12 +25,18 @@ type TListGitHubEnvironmentsDTO = {export const githubConnectionService = (getAppConnection: TGetAppConnectionFunc,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const listRepositories = async (connectionId: string, actor: OrgServiceActor) => {const appConnection = await getAppConnection(AppConnection.GitHub, connectionId, actor);- const repositories = await getGitHubRepositories(appConnection, gatewayService, gatewayV2Service);+ const repositories = await getGitHubRepositories(+ appConnection,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );return repositories;};@@ -37,7 +44,12 @@ export const githubConnectionService = (const listOrganizations = async (connectionId: string, actor: OrgServiceActor) => {const appConnection = await getAppConnection(AppConnection.GitHub, connectionId, actor);- const organizations = await getGitHubOrganizations(appConnection, gatewayService, gatewayV2Service);+ const organizations = await getGitHubOrganizations(+ appConnection,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );return organizations;};@@ -48,7 +60,14 @@ export const githubConnectionService = () => {const appConnection = await getAppConnection(AppConnection.GitHub, connectionId, actor);- const environments = await getGitHubEnvironments(appConnection, gatewayService, gatewayV2Service, owner, repo);+ const environments = await getGitHubEnvironments(+ appConnection,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService,+ owner,+ repo+ );return environments;};diff --git a/backend/src/services/app-connection/github/github-connection-types.ts b/backend/src/services/app-connection/github/github-connection-types.tsindex c4aed54b5f..dd454fc823 100644--- a/backend/src/services/app-connection/github/github-connection-types.ts+++ b/backend/src/services/app-connection/github/github-connection-types.ts@@ -19,5 +19,5 @@ export type TValidateGitHubConnectionCredentialsSchema = typeof ValidateGitHubCoexport type TGitHubConnectionConfig = DiscriminativePick<TGitHubConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId">;diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.tsindex d50e4e9bfa..e6eabc6156 100644--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts@@ -3,6 +3,7 @@ import https from "https";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";import { request } from "@app/lib/config/request";@@ -129,13 +130,24 @@ type TokenRespData = {};export const requestWithHCVaultGateway = async <T>(- appConnection: { gatewayId?: string | null },+ appConnection: { gatewayId?: string | null; gatewayPoolId?: string | null },gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,requestConfig: AxiosRequestConfig,- gatewayDetails?: TGatewayDetails+ gatewayDetails?: TGatewayDetails,+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<AxiosResponse<T>> => {- const { gatewayId } = appConnection;+ const { gatewayId: directGatewayId, gatewayPoolId } = appConnection;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }+ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;const url = new URL(requestConfig.url as string);await blockLocalAndPrivateIpAddresses(url.toString(), Boolean(gatewayId));diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-service.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-service.tsindex 614a0ad7a6..0115e66508 100644--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-service.ts+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-service.ts@@ -1,4 +1,5 @@import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";@@ -17,13 +18,19 @@ type TGetAppConnectionFunc = (export const hcVaultConnectionService = (getAppConnection: TGetAppConnectionFunc,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const listMounts = async (connectionId: string, actor: OrgServiceActor) => {const appConnection = await getAppConnection(AppConnection.HCVault, connectionId, actor);+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: appConnection.gatewayId,+ gatewayPoolId: appConnection.gatewayPoolId+ });+ const resolvedConnection = { ...appConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };try {- const mounts = await listHCVaultMounts(appConnection, gatewayService, gatewayV2Service);+ const mounts = await listHCVaultMounts(resolvedConnection, gatewayService, gatewayV2Service);// Filter for KV mounts (v1 and v2) and extract just the pathsreturn mounts.filter((mount) => mount.type === "kv" && (mount.version === KvVersion.V2 || mount.version === KvVersion.V1))diff --git a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts b/backend/src/services/app-connection/ldap/ldap-connection-fns.tsindex 68de9c8fca..0f131a6514 100644--- a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts+++ b/backend/src/services/app-connection/ldap/ldap-connection-fns.ts@@ -3,6 +3,7 @@ import { isIP } from "node:net";import ldap from "@infisical/ldapjs";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { getConfig } from "@app/lib/config/env";import { BadRequestError } from "@app/lib/errors";@@ -222,12 +223,23 @@ export const getLdapConnectionClient = async ({export const executeWithPotentialGateway = async <T>(config: TLdapConnectionConfig,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- operation: (client: ldap.Client) => Promise<T>+ operation: (client: ldap.Client) => Promise<T>,+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<T> => {- const { gatewayId, credentials } = config;+ const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;const { protocol, host, port } = parseLdapUrl(credentials.url);const appCfg = getConfig();+ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }+ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;+if (gatewayId && gatewayV2Service) {await blockLocalAndPrivateIpAddresses(credentials.url, true);const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({diff --git a/backend/src/services/app-connection/ldap/ldap-connection-types.ts b/backend/src/services/app-connection/ldap/ldap-connection-types.tsindex 581fca5604..9d8307d201 100644--- a/backend/src/services/app-connection/ldap/ldap-connection-types.ts+++ b/backend/src/services/app-connection/ldap/ldap-connection-types.ts@@ -19,7 +19,7 @@ export type TValidateLdapConnectionCredentialsSchema = typeof ValidateLdapConnecexport type TLdapConnectionConfig = DiscriminativePick<TLdapConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/app-connection/netscaler/netscaler-connection-types.ts b/backend/src/services/app-connection/netscaler/netscaler-connection-types.tsindex a9a899ec3f..14f16b1e7d 100644--- a/backend/src/services/app-connection/netscaler/netscaler-connection-types.ts+++ b/backend/src/services/app-connection/netscaler/netscaler-connection-types.ts@@ -19,7 +19,7 @@ export type TValidateNetScalerConnectionCredentialsSchema = typeof ValidateNetScexport type TNetScalerConnectionConfig = DiscriminativePick<TNetScalerConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts b/backend/src/services/app-connection/shared/sql/sql-connection-fns.tsindex 766b95a65c..70fd33fa71 100644--- a/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts+++ b/backend/src/services/app-connection/shared/sql/sql-connection-fns.ts@@ -4,6 +4,7 @@ import oracledb from "oracledb";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import {TSqlCredentialsRotationGeneratedCredentials,@@ -144,9 +145,20 @@ export const executeWithPotentialGateway = async <T>(config: TSqlConnectionConfig,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- operation: (client: Knex) => Promise<T>+ operation: (client: Knex) => Promise<T>,+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<T> => {- const { credentials, app, gatewayId } = config;+ const { credentials, app, gatewayId: directGatewayId, gatewayPoolId } = config;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }+ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;if (gatewayId && gatewayService && gatewayV2Service) {const [targetHost] = await verifyHostInputValidity({diff --git a/backend/src/services/app-connection/shared/sql/sql-connection-types.ts b/backend/src/services/app-connection/shared/sql/sql-connection-types.tsindex 104aacfb97..1e851c4300 100644--- a/backend/src/services/app-connection/shared/sql/sql-connection-types.ts+++ b/backend/src/services/app-connection/shared/sql/sql-connection-types.ts@@ -3,7 +3,7 @@ import { TSqlConnectionInput } from "@app/services/app-connection/app-connectionexport type TSqlConnectionConfig = DiscriminativePick<TSqlConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/app-connection/smb/smb-connection-fns.ts b/backend/src/services/app-connection/smb/smb-connection-fns.tsindex de39f3cbb0..885c88bc4f 100644--- a/backend/src/services/app-connection/smb/smb-connection-fns.ts+++ b/backend/src/services/app-connection/smb/smb-connection-fns.ts@@ -1,4 +1,5 @@import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { BadRequestError } from "@app/lib/errors";import { GatewayProxyProtocol } from "@app/lib/gateway";@@ -21,9 +22,20 @@ export const getSmbConnectionListItem = () => {export const executeSmbWithPotentialGateway = async <T>(config: TSmbConnectionConfig,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- operation: (targetHost: string, targetPort: number) => Promise<T>+ operation: (targetHost: string, targetPort: number) => Promise<T>,+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<T> => {- const { gatewayId, credentials } = config;+ const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }+ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;if (gatewayId) {await blockLocalAndPrivateIpAddresses(`smb://${credentials.host}:${credentials.port}`, true);diff --git a/backend/src/services/app-connection/smb/smb-connection-types.ts b/backend/src/services/app-connection/smb/smb-connection-types.tsindex 3e44c5632f..e395ed7bf6 100644--- a/backend/src/services/app-connection/smb/smb-connection-types.ts+++ b/backend/src/services/app-connection/smb/smb-connection-types.ts@@ -19,7 +19,7 @@ export type TValidateSmbConnectionCredentialsSchema = typeof ValidateSmbConnectiexport type TSmbConnectionConfig = DiscriminativePick<TSmbConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.tsindex 2afed4776f..1dcc2b6c1a 100644--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts@@ -1,6 +1,7 @@import { Client, ConnectConfig } from "ssh2";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { BadRequestError, InternalServerError } from "@app/lib/errors";import { GatewayProxyProtocol } from "@app/lib/gateway";@@ -161,9 +162,20 @@ export const getSshConnectionClient = async (export const executeWithPotentialGateway = async <T>(config: TSshConnectionConfig,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,- operation: (targetHost: string, targetPort: number) => Promise<T>+ operation: (targetHost: string, targetPort: number) => Promise<T>,+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">): Promise<T> => {- const { gatewayId, credentials } = config;+ const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;++ if (gatewayPoolId && !gatewayPoolService) {+ throw new BadRequestError({+ message: "Pool-backed connections require gatewayPoolService at the call site"+ });+ }+ const gatewayId =+ gatewayPoolId && gatewayPoolService+ ? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })+ : directGatewayId;if (gatewayId) {await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, true);diff --git a/backend/src/services/app-connection/ssh/ssh-connection-types.ts b/backend/src/services/app-connection/ssh/ssh-connection-types.tsindex ef06d7a310..3b9bdc0b5d 100644--- a/backend/src/services/app-connection/ssh/ssh-connection-types.ts+++ b/backend/src/services/app-connection/ssh/ssh-connection-types.ts@@ -19,7 +19,7 @@ export type TValidateSshConnectionCredentialsSchema = typeof ValidateSshConnectiexport type TSshConnectionConfig = DiscriminativePick<TSshConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-types.ts b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-types.tsindex 5a4e665a40..a17d71a28d 100644--- a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-types.ts+++ b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-types.ts@@ -19,7 +19,7 @@ export type TValidateVenafiTppConnectionCredentialsSchema = typeof ValidateVenafexport type TVenafiTppConnectionConfig = DiscriminativePick<TVenafiTppConnectionInput,- "method" | "app" | "credentials" | "gatewayId"+ "method" | "app" | "credentials" | "gatewayId" | "gatewayPoolId"> & {orgId: string;};diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.tsindex ebfdc6dd22..6a0460804e 100644--- a/backend/src/services/certificate-authority/certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts@@ -1,6 +1,7 @@import { ForbiddenError, subject } from "@casl/ability";import { ActionProjectType, TableName } from "@app/db/schemas";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {@@ -124,6 +125,7 @@ type TCertificateAuthorityServiceFactoryDep = {>;resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export type TCertificateAuthorityServiceFactory = ReturnType<typeof certificateAuthorityServiceFactory>;@@ -146,7 +148,8 @@ export const certificateAuthorityServiceFactory = ({certificateProfileDAL,certificateRequestDAL,resourceMetadataDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TCertificateAuthorityServiceFactoryDep) => {const acmeFns = AcmeCertificateAuthorityFns({appConnectionDAL,@@ -191,7 +194,8 @@ export const certificateAuthorityServiceFactory = ({kmsService,projectDAL,certificateProfileDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});const awsPcaFns = AwsPcaCertificateAuthorityFns({diff --git a/backend/src/services/certificate-authority/certificate-issuance-queue.ts b/backend/src/services/certificate-authority/certificate-issuance-queue.tsindex 0ea573d2be..83f9911e5b 100644--- a/backend/src/services/certificate-authority/certificate-issuance-queue.ts+++ b/backend/src/services/certificate-authority/certificate-issuance-queue.ts@@ -1,6 +1,7 @@import acme from "acme-client";import { UnrecoverableError } from "bullmq";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";@@ -130,6 +131,7 @@ type TCertificateIssuanceQueueFactoryDep = {resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "find" | "insertMany">;pkiAlertV2Queue?: Pick<TPkiAlertV2QueueServiceFactory, "queueCertificateEvent">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export type TCertificateIssuanceQueueFactory = ReturnType<typeof certificateIssuanceQueueFactory>;@@ -153,7 +155,8 @@ export const certificateIssuanceQueueFactory = ({certificateRequestDAL,resourceMetadataDAL,pkiAlertV2Queue,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TCertificateIssuanceQueueFactoryDep) => {const acmeFns = AcmeCertificateAuthorityFns({appConnectionDAL,@@ -236,7 +239,8 @@ export const certificateIssuanceQueueFactory = ({kmsService,projectDAL,certificateProfileDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});/**diff --git a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.tsindex b8fabb7283..dda9c43112 100644--- a/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/venafi-tpp/venafi-tpp-certificate-authority-fns.ts@@ -4,6 +4,7 @@ import { AxiosError } from "axios";import RE2 from "re2";import { TableName } from "@app/db/schemas";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { crypto } from "@app/lib/crypto/cryptography";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -114,7 +115,8 @@ const sanToVenafiFormat = (san: {const getVenafiTppConnection = async (appConnectionId: string,appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">,- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const appConnection = await appConnectionDAL.findById(appConnectionId);if (!appConnection) {@@ -149,7 +151,12 @@ const getVenafiTppConnection = async (password: string;};- return { credentials, gatewayId: appConnection.gatewayId ?? null };+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: appConnection.gatewayId,+ gatewayPoolId: appConnection.gatewayPoolId+ });++ return { credentials, gatewayId: effectiveGatewayId ?? null };};const submitCertificateToTpp = async ({@@ -342,6 +349,7 @@ type TVenafiTppCertificateAuthorityFnsDeps = {projectDAL: Pick<TProjectDALFactory, "findById" | "findOne" | "updateById" | "transaction">;certificateProfileDAL?: Pick<TCertificateProfileDALFactory, "findById">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const VenafiTppCertificateAuthorityFns = ({@@ -355,7 +363,8 @@ export const VenafiTppCertificateAuthorityFns = ({kmsService,projectDAL,certificateProfileDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TVenafiTppCertificateAuthorityFnsDeps) => {const createCertificateAuthority = async ({name,@@ -605,7 +614,8 @@ export const VenafiTppCertificateAuthorityFns = ({const { credentials, gatewayId } = await getVenafiTppConnection(venafiCa.configuration.appConnectionId,appConnectionDAL,- kmsService+ kmsService,+ gatewayPoolService);const baseUrl = normalizeTppUrl(credentials.tppUrl);diff --git a/backend/src/services/external-migration/external-migration-config-dal.ts b/backend/src/services/external-migration/external-migration-config-dal.tsindex 1f0d11361d..f4c05b49f2 100644--- a/backend/src/services/external-migration/external-migration-config-dal.ts+++ b/backend/src/services/external-migration/external-migration-config-dal.ts@@ -26,6 +26,7 @@ const buildConnectionJoin = (qb: Knex.QueryBuilder, db: TDbClient) =>db.ref("description").withSchema(TableName.AppConnection).as("appConnectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("appConnectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("appConnectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("appConnectionGatewayPoolId"),db.ref("projectId").withSchema(TableName.AppConnection).as("appConnectionProjectId"),db.ref("createdAt").withSchema(TableName.AppConnection).as("appConnectionCreatedAt"),db.ref("updatedAt").withSchema(TableName.AppConnection).as("appConnectionUpdatedAt")@@ -46,6 +47,7 @@ const mapResultToConnection = (raw: Record<string, unknown>) => {description: raw.appConnectionDescription,version: raw.appConnectionVersion,gatewayId: raw.appConnectionGatewayId,+ gatewayPoolId: raw.appConnectionGatewayPoolId,projectId: raw.appConnectionProjectId,createdAt: raw.appConnectionCreatedAt as Date,updatedAt: raw.appConnectionUpdatedAt as Date,diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.tsindex 11084e992b..426a91befe 100644--- a/backend/src/services/external-migration/external-migration-service.ts+++ b/backend/src/services/external-migration/external-migration-service.ts@@ -7,6 +7,7 @@ import {} from "@app/ee/services/audit-log/audit-log-types";import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { crypto } from "@app/lib/crypto/cryptography";@@ -79,6 +80,10 @@ type TExternalMigrationServiceFactoryDep = {userDAL: Pick<TUserDALFactory, "findById">;gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<+ TGatewayPoolServiceFactory,+ "resolveEffectiveGatewayId" | "resolveAttachableGatewayFromPool" | "pickRandomHealthyGateway"+ >;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;};@@ -90,6 +95,7 @@ export const externalMigrationServiceFactory = ({userDAL,gatewayService,gatewayV2Service,+ gatewayPoolService,secretService,auditLogService,appConnectionService,@@ -99,7 +105,12 @@ export const externalMigrationServiceFactory = ({const getGatewayDetails = async (connection: THCVaultConnection) => {let gatewayDetails: TGatewayDetails | undefined;- if (connection.gatewayId) {+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });++ if (effectiveGatewayId) {const instanceUrl = await getHCVaultInstanceUrl(connection);const url = new URL(instanceUrl);@@ -113,7 +124,7 @@ export const externalMigrationServiceFactory = ({const targetPort = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;const gatewayV2Details = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({- gatewayId: connection.gatewayId,+ gatewayId: effectiveGatewayId,targetHost,targetPort});@@ -128,7 +139,7 @@ export const externalMigrationServiceFactory = ({}};} else {- const gatewayV1Details = await gatewayService.fnGetGatewayClientTlsByGatewayId(connection.gatewayId);+ const gatewayV1Details = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId);if (gatewayV1Details) {gatewayDetails = {gatewayVersion: GatewayVersion.V1,@@ -196,9 +207,19 @@ export const externalMigrationServiceFactory = ({projectId: null});+ const connectionGatewayId = migrationConfig.connection.gatewayId as string | null | undefined;+ const connectionGatewayPoolId = migrationConfig.connection.gatewayPoolId as string | null | undefined;++ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connectionGatewayId,+ gatewayPoolId: connectionGatewayPoolId+ });+return {...migrationConfig.connection,- credentials+ credentials,+ gatewayId: effectiveGatewayId,+ gatewayPoolId: null} as THCVaultConnection;};@@ -257,6 +278,7 @@ export const externalMigrationServiceFactory = ({mappingType,vaultUrl,gatewayId,+ gatewayPoolId,actor,actorId,actorOrgId,@@ -277,13 +299,28 @@ export const externalMigrationServiceFactory = ({const user = await userDAL.findById(actorId);+ if (gatewayId && gatewayPoolId) {+ throw new BadRequestError({ message: "Cannot specify both a gateway and a gateway pool" });+ }++ let effectiveGatewayId: string | null = gatewayId ?? null;+ if (gatewayPoolId) {+ await gatewayPoolService.resolveAttachableGatewayFromPool({+ poolId: gatewayPoolId,+ orgId: actorOrgId,+ actor: { type: actor, id: actorId, orgId: actorOrgId, authMethod: actorAuthMethod }+ });+ const picked = await gatewayPoolService.pickRandomHealthyGateway(gatewayPoolId);+ effectiveGatewayId = picked.id;+ }+const vaultData = await importVaultDataFn({vaultAccessToken,vaultNamespace,vaultUrl,mappingType,- gatewayId,+ gatewayId: effectiveGatewayId ?? undefined,orgId: actorOrgId},{@@ -367,19 +404,28 @@ export const externalMigrationServiceFactory = ({}const gatewayDetails = await getGatewayDetails(connection);+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ const sanitizedConnection = {+ ...connection,+ gatewayId: effectiveGatewayId,+ gatewayPoolId: null+ } as typeof connection;try {- await getHCVaultPolicyNames(namespace, connection, gatewayService, gatewayV2Service, gatewayDetails);+ await getHCVaultPolicyNames(namespace, sanitizedConnection, gatewayService, gatewayV2Service, gatewayDetails);await getHCVaultAuthMounts(namespace,HCVaultAuthType.Kubernetes,- connection,+ sanitizedConnection,gatewayService,gatewayV2Service,gatewayDetails);- await listHCVaultMounts(connection, gatewayService, gatewayV2Service);+ await listHCVaultMounts(sanitizedConnection, gatewayService, gatewayV2Service);} catch (error) {throw new BadRequestError({message: `Failed to establish namespace configuration. ${error instanceof Error ? error.message : "Unknown error"}`diff --git a/backend/src/services/external-migration/external-migration-types.ts b/backend/src/services/external-migration/external-migration-types.tsindex fd3dbfcf45..13c2dcc529 100644--- a/backend/src/services/external-migration/external-migration-types.ts+++ b/backend/src/services/external-migration/external-migration-types.ts@@ -44,6 +44,7 @@ export type TImportVaultDataDTO = {mappingType: VaultMappingType;vaultUrl: string;gatewayId?: string;+ gatewayPoolId?: string;} & Omit<TOrgPermission, "orgId">;export type TImportInfisicalDataCreate = {diff --git a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.tsindex 9d2aaa8bd8..fa3a38c5df 100644--- a/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/netscaler/netscaler-pki-sync-fns.ts@@ -4,6 +4,7 @@ import handlebars from "handlebars";import RE2 from "re2";import { TCertificateSyncs } from "@app/db/schemas";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { logger } from "@app/lib/logger";import { executeNetScalerOperationWithGateway } from "@app/services/app-connection/netscaler/netscaler-connection-fns";@@ -40,6 +41,7 @@ type TNetScalerPkiSyncFactoryDeps = {>;certificateDAL: Pick<TCertificateDALFactory, "findById">;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};const getNetScalerCredentials = (pkiSync: TPkiSyncWithCredentials): TNetScalerCredentials => {@@ -299,8 +301,18 @@ const removeNetScalerCertificate = async (export const netScalerPkiSyncFactory = ({certificateSyncDAL,certificateDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TNetScalerPkiSyncFactoryDeps) => {+ const resolveGateway = async (pkiSync: TPkiSyncWithCredentials) => {+ return gatewayPoolService+ ? gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: pkiSync.connection.gatewayId,+ gatewayPoolId: pkiSync.connection.gatewayPoolId+ })+ : (pkiSync.connection.gatewayId ?? null);+ };+const syncCertificates = async (pkiSync: TPkiSyncWithCredentials,certificateMap: TCertificateMap@@ -324,8 +336,10 @@ export const netScalerPkiSyncFactory = ({const preserveItemOnRenewal = syncOptions?.preserveItemOnRenewal ?? true;const certificateNameSchema = syncOptions?.certificateNameSchema;+ const effectiveGatewayId = await resolveGateway(pkiSync);+return executeNetScalerOperationWithGateway(- { gatewayId: pkiSync.connection.gatewayId, credentials },+ { gatewayId: effectiveGatewayId, credentials },gatewayV2Service,async (makeRequest) => {let uploaded = 0;@@ -638,8 +652,10 @@ export const netScalerPkiSyncFactory = ({return;}+ const effectiveGatewayId = await resolveGateway(pkiSync);+await executeNetScalerOperationWithGateway(- { gatewayId: pkiSync.connection.gatewayId, credentials },+ { gatewayId: effectiveGatewayId, credentials },gatewayV2Service,async (makeRequest) => {const session = await createNetScalerSession(credentials, makeRequest);diff --git a/backend/src/services/pki-sync/pki-sync-dal.ts b/backend/src/services/pki-sync/pki-sync-dal.tsindex d04344b1e8..ce4e50ec18 100644--- a/backend/src/services/pki-sync/pki-sync-dal.ts+++ b/backend/src/services/pki-sync/pki-sync-dal.ts@@ -30,6 +30,7 @@ const basePkiSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: PkiSyncFdb.ref("description").withSchema(TableName.AppConnection).as("appConnectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("appConnectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("appConnectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("appConnectionGatewayPoolId"),db.ref("createdAt").withSchema(TableName.AppConnection).as("appConnectionCreatedAt"),db.ref("updatedAt").withSchema(TableName.AppConnection).as("appConnectionUpdatedAt"),db@@ -72,6 +73,7 @@ const basePkiSyncWithSubscriberQuery = ({db.ref("description").withSchema(TableName.AppConnection).as("appConnectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("appConnectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("appConnectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("appConnectionGatewayPoolId"),db.ref("createdAt").withSchema(TableName.AppConnection).as("appConnectionCreatedAt"),db.ref("updatedAt").withSchema(TableName.AppConnection).as("appConnectionUpdatedAt"),db@@ -106,6 +108,7 @@ const expandPkiSync = (pkiSync: Awaited<ReturnType<typeof basePkiSyncQuery>>[numappConnectionDescription,appConnectionVersion,appConnectionGatewayId,+ appConnectionGatewayPoolId,appConnectionCreatedAt,appConnectionUpdatedAt,appConnectionIsPlatformManagedCredentials,@@ -130,6 +133,7 @@ const expandPkiSync = (pkiSync: Awaited<ReturnType<typeof basePkiSyncQuery>>[numdescription: appConnectionDescription,version: appConnectionVersion,gatewayId: appConnectionGatewayId,+ gatewayPoolId: appConnectionGatewayPoolId,createdAt: appConnectionCreatedAt,updatedAt: appConnectionUpdatedAt,isPlatformManagedCredentials: appConnectionIsPlatformManagedCredentials@@ -148,6 +152,7 @@ const expandPkiSyncWithSubscriber = (pkiSync: Awaited<ReturnType<typeof basePkiSappConnectionDescription,appConnectionVersion,appConnectionGatewayId,+ appConnectionGatewayPoolId,appConnectionCreatedAt,appConnectionUpdatedAt,appConnectionIsPlatformManagedCredentials,@@ -174,6 +179,7 @@ const expandPkiSyncWithSubscriber = (pkiSync: Awaited<ReturnType<typeof basePkiSdescription: appConnectionDescription,version: appConnectionVersion,gatewayId: appConnectionGatewayId,+ gatewayPoolId: appConnectionGatewayPoolId,createdAt: appConnectionCreatedAt,updatedAt: appConnectionUpdatedAt,isPlatformManagedCredentials: appConnectionIsPlatformManagedCredentialsdiff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.tsindex 0b86cc9002..e527197227 100644--- a/backend/src/services/pki-sync/pki-sync-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-fns.ts@@ -1,6 +1,7 @@import handlebars from "handlebars";import { z, ZodSchema } from "zod";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { BadRequestError } from "@app/lib/errors";@@ -230,6 +231,7 @@ export const PkiSyncFns = {certificateDAL: TCertificateDALFactory;certificateSyncDAL: TCertificateSyncDALFactory;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;}): Promise<{uploaded: number;@@ -303,7 +305,8 @@ export const PkiSyncFns = {const netScalerPkiSync = netScalerPkiSyncFactory({certificateDAL: dependencies.certificateDAL,certificateSyncDAL: dependencies.certificateSyncDAL,- gatewayV2Service: dependencies.gatewayV2Service+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService});return netScalerPkiSync.syncCertificates(pkiSync, certificateMap);}@@ -322,6 +325,7 @@ export const PkiSyncFns = {certificateDAL: TCertificateDALFactory;certificateMap: TCertificateMap;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;}): Promise<void> => {switch (pkiSync.destination) {@@ -405,7 +409,8 @@ export const PkiSyncFns = {const netScalerPkiSync = netScalerPkiSyncFactory({certificateDAL: dependencies.certificateDAL,certificateSyncDAL: dependencies.certificateSyncDAL,- gatewayV2Service: dependencies.gatewayV2Service+ gatewayV2Service: dependencies.gatewayV2Service,+ gatewayPoolService: dependencies.gatewayPoolService});await netScalerPkiSync.removeCertificates(pkiSync, certificateNames, {certificateSyncDAL: dependencies.certificateSyncDAL,diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.tsindex 3861809ae5..ab7623ad86 100644--- a/backend/src/services/pki-sync/pki-sync-queue.ts+++ b/backend/src/services/pki-sync/pki-sync-queue.ts@@ -8,6 +8,7 @@ import handlebars from "handlebars";import { TCertificates } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";@@ -68,6 +69,7 @@ type TPkiSyncQueueFactoryDep = {certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findById">;certificateSyncDAL: TCertificateSyncDALFactory;gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};type PkiSyncActionJob = Job<@@ -100,7 +102,8 @@ export const pkiSyncQueueFactory = ({certificateAuthorityDAL,certificateAuthorityCertDAL,certificateSyncDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService}: TPkiSyncQueueFactoryDep) => {const appCfg = getConfig();@@ -461,7 +464,8 @@ export const pkiSyncQueueFactory = ({kmsService,certificateDAL,certificateSyncDAL,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});logger.info(@@ -727,7 +731,8 @@ export const pkiSyncQueueFactory = ({certificateSyncDAL,certificateDAL,certificateMap,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});diff --git a/backend/src/services/pki-sync/pki-sync-types.ts b/backend/src/services/pki-sync/pki-sync-types.tsindex 72818091e0..cef5ae064c 100644--- a/backend/src/services/pki-sync/pki-sync-types.ts+++ b/backend/src/services/pki-sync/pki-sync-types.ts@@ -47,6 +47,7 @@ export type TPkiSync = {description?: string;version: number;gatewayId?: string;+ gatewayPoolId?: string | null;createdAt: Date;updatedAt: Date;isPlatformManagedCredentials?: boolean;@@ -65,6 +66,7 @@ export type TPkiSyncWithCredentials = TPkiSync & {credentials: Record<string, unknown>;orgId: string;gatewayId?: string;+ gatewayPoolId?: string | null;};};diff --git a/backend/src/services/secret-sync/github/github-sync-fns.ts b/backend/src/services/secret-sync/github/github-sync-fns.tsindex 4057f38b1a..8586ca73f5 100644--- a/backend/src/services/secret-sync/github/github-sync-fns.ts+++ b/backend/src/services/secret-sync/github/github-sync-fns.ts@@ -1,6 +1,7 @@import sodium from "libsodium-wrappers";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import {getGitHubAppAuthToken,@@ -23,7 +24,8 @@ import { TGitHubPublicKey, TGitHubSecret, TGitHubSecretPayload, TGitHubSyncWithCconst getEncryptedSecrets = async (secretSync: TGitHubSyncWithCredentials,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const { destinationConfig, connection } = secretSync;@@ -48,6 +50,7 @@ const getEncryptedSecrets = async (connection,gatewayService,gatewayV2Service,+ gatewayPoolService,path,(data) => data.secrets);@@ -57,6 +60,7 @@ const getPublicKey = async (secretSync: TGitHubSyncWithCredentials,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,token: string) => {const { destinationConfig, connection } = secretSync;@@ -79,12 +83,16 @@ const getPublicKey = async (}const apiBaseUrl = await getGitHubInstanceApiUrl(connection);- const gatewayConnectionDetails = connection.gatewayId- ? await getGitHubGatewayConnectionDetails(connection.gatewayId, apiBaseUrl, gatewayV2Service)+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ const gatewayConnectionDetails = effectiveGatewayId+ ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service): undefined;const response = await requestWithGitHubGateway<TGitHubPublicKey>(- connection,+ { gatewayId: effectiveGatewayId },gatewayService,gatewayV2Service,{@@ -106,6 +114,7 @@ const deleteSecret = async (secretSync: TGitHubSyncWithCredentials,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,token: string,encryptedSecret: TGitHubSecret) => {@@ -129,12 +138,16 @@ const deleteSecret = async (}const apiBaseUrl = await getGitHubInstanceApiUrl(connection);- const gatewayConnectionDetails = connection.gatewayId- ? await getGitHubGatewayConnectionDetails(connection.gatewayId, apiBaseUrl, gatewayV2Service)+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ const gatewayConnectionDetails = effectiveGatewayId+ ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service): undefined;await requestWithGitHubGateway(- connection,+ { gatewayId: effectiveGatewayId },gatewayService,gatewayV2Service,{@@ -154,6 +167,7 @@ const putSecret = async (secretSync: TGitHubSyncWithCredentials,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,token: string,payload: TGitHubSecretPayload) => {@@ -187,12 +201,16 @@ const putSecret = async (}const apiBaseUrl = await getGitHubInstanceApiUrl(connection);- const gatewayConnectionDetails = connection.gatewayId- ? await getGitHubGatewayConnectionDetails(connection.gatewayId, apiBaseUrl, gatewayV2Service)+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: connection.gatewayId,+ gatewayPoolId: connection.gatewayPoolId+ });+ const gatewayConnectionDetails = effectiveGatewayId+ ? await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service): undefined;await requestWithGitHubGateway(- connection,+ { gatewayId: effectiveGatewayId },gatewayService,gatewayV2Service,{@@ -214,7 +232,8 @@ export const GithubSyncFns = {secretSync: TGitHubSyncWithCredentials,ogSecretMap: TSecretMap,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const secretMap = Object.fromEntries(Object.entries(ogSecretMap).map(([i, v]) => [i.toUpperCase(), v]));@@ -244,7 +263,12 @@ export const GithubSyncFns = {);}- const { connection } = secretSync;+ const { connection: rawConnection } = secretSync;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: rawConnection.gatewayId,+ gatewayPoolId: rawConnection.gatewayPoolId+ });+ const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };let token: string;switch (connection.method) {@@ -255,26 +279,29 @@ export const GithubSyncFns = {token = connection.credentials.personalAccessToken;break;default:- token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service);+ token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service, gatewayPoolService);}- const encryptedSecrets = await getEncryptedSecrets(secretSync, gatewayService, gatewayV2Service);- const publicKey = await getPublicKey(secretSync, gatewayService, gatewayV2Service, token);+ const resolvedSync = { ...secretSync, connection };+ const encryptedSecrets = await getEncryptedSecrets(+ resolvedSync,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );+ const publicKey = await getPublicKey(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token);await sodium.ready;for await (const key of Object.keys(secretMap)) {- // convert secret & base64 key to Uint8Array.const binaryKey = sodium.from_base64(publicKey.key, sodium.base64_variants.ORIGINAL);const binarySecretValue = sodium.from_string(secretMap[key].value);- // encrypt secret using libsodiumconst encryptedBytes = sodium.crypto_box_seal(binarySecretValue, binaryKey);- // convert encrypted Uint8Array to base64const encryptedSecretValue = sodium.to_base64(encryptedBytes, sodium.base64_variants.ORIGINAL);try {- await putSecret(secretSync, gatewayService, gatewayV2Service, token, {+ await putSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, {secret_name: key,encrypted_value: encryptedSecretValue,key_id: publicKey.key_id@@ -295,7 +322,7 @@ export const GithubSyncFns = {continue;if (!(encryptedSecret.name in secretMap)) {- await deleteSecret(secretSync, gatewayService, gatewayV2Service, token, encryptedSecret);+ await deleteSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, encryptedSecret);}}},@@ -306,11 +333,18 @@ export const GithubSyncFns = {secretSync: TGitHubSyncWithCredentials,ogSecretMap: TSecretMap,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const secretMap = Object.fromEntries(Object.entries(ogSecretMap).map(([i, v]) => [i.toUpperCase(), v]));- const { connection } = secretSync;+ const { connection: rawConnection } = secretSync;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: rawConnection.gatewayId,+ gatewayPoolId: rawConnection.gatewayPoolId+ });+ const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };+ const resolvedSync = { ...secretSync, connection };let token: string;switch (connection.method) {@@ -321,14 +355,19 @@ export const GithubSyncFns = {token = connection.credentials.personalAccessToken;break;default:- token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service);+ token = await getGitHubAppAuthToken(connection, gatewayService, gatewayV2Service, gatewayPoolService);}- const encryptedSecrets = await getEncryptedSecrets(secretSync, gatewayService, gatewayV2Service);+ const encryptedSecrets = await getEncryptedSecrets(+ resolvedSync,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );for await (const encryptedSecret of encryptedSecrets) {if (encryptedSecret.name in secretMap) {- await deleteSecret(secretSync, gatewayService, gatewayV2Service, token, encryptedSecret);+ await deleteSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, encryptedSecret);}}}diff --git a/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts b/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.tsindex d636290f7f..83bfb8d857 100644--- a/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts+++ b/backend/src/services/secret-sync/hc-vault/hc-vault-sync-fns.ts@@ -1,6 +1,7 @@import { isAxiosError } from "axios";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { BadRequestError } from "@app/lib/errors";import { removeTrailingSlash } from "@app/lib/fn";@@ -162,14 +163,20 @@ export const HCVaultSyncFns = {secretSync: THCVaultSyncWithCredentials,secretMap: TSecretMap,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const {- connection,+ connection: rawConnection,environment,destinationConfig: { mount, path },syncOptions: { disableSecretDeletion, keySchema }} = secretSync;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: rawConnection.gatewayId,+ gatewayPoolId: rawConnection.gatewayPoolId+ });+ const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };const { namespace } = connection.credentials;const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);@@ -259,12 +266,18 @@ export const HCVaultSyncFns = {secretSync: THCVaultSyncWithCredentials,secretMap: TSecretMap,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const {- connection,+ connection: rawConnection,destinationConfig: { mount, path }} = secretSync;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: rawConnection.gatewayId,+ gatewayPoolId: rawConnection.gatewayPoolId+ });+ const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };const { namespace } = connection.credentials;const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);@@ -328,12 +341,18 @@ export const HCVaultSyncFns = {getSecrets: async (secretSync: THCVaultSyncWithCredentials,gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">) => {const {- connection,+ connection: rawConnection,destinationConfig: { mount, path }} = secretSync;+ const effectiveGatewayId = await gatewayPoolService.resolveEffectiveGatewayId({+ gatewayId: rawConnection.gatewayId,+ gatewayPoolId: rawConnection.gatewayPoolId+ });+ const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };const { namespace } = connection.credentials;const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);diff --git a/backend/src/services/secret-sync/secret-sync-dal.ts b/backend/src/services/secret-sync/secret-sync-dal.tsindex e71adeb643..4102bf32f9 100644--- a/backend/src/services/secret-sync/secret-sync-dal.ts+++ b/backend/src/services/secret-sync/secret-sync-dal.ts@@ -31,6 +31,7 @@ const baseSecretSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: Secredb.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),+ db.ref("gatewayPoolId").withSchema(TableName.AppConnection).as("connectionGatewayPoolId"),db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),db.ref("isAutoRotationEnabled").withSchema(TableName.AppConnection).as("connectionIsAutoRotationEnabled"),db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),@@ -69,6 +70,7 @@ const expandSecretSync = (connectionVersion,connectionIsPlatformManagedCredentials,connectionGatewayId,+ connectionGatewayPoolId,connectionProjectId,connectionIsAutoRotationEnabled,...el@@ -91,6 +93,7 @@ const expandSecretSync = (version: connectionVersion,isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,gatewayId: connectionGatewayId,+ gatewayPoolId: connectionGatewayPoolId,projectId: connectionProjectId,isAutoRotationEnabled: connectionIsAutoRotationEnabled},diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.tsindex e2f110910d..a297089bf3 100644--- a/backend/src/services/secret-sync/secret-sync-fns.ts+++ b/backend/src/services/secret-sync/secret-sync-fns.ts@@ -2,6 +2,7 @@ import { AxiosError } from "axios";import handlebars from "handlebars";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { CHEF_SYNC_LIST_OPTION, ChefSyncFns } from "@app/ee/services/secret-sync/chef";@@ -167,6 +168,7 @@ type TSyncSecretDeps = {kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};export const getKeyWithSchema = ({@@ -292,7 +294,7 @@ export const SecretSyncFns = {syncSecrets: (secretSync: TSecretSyncWithCredentials,secretMap: TSecretMap,- { kmsService, appConnectionDAL, gatewayService, gatewayV2Service }: TSyncSecretDeps+ { kmsService, appConnectionDAL, gatewayService, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps): Promise<TSyncSecretsResult | void> => {const schemaSecretMap = addSchema(secretMap, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema);@@ -302,7 +304,13 @@ export const SecretSyncFns = {case SecretSync.AWSSecretsManager:return AwsSecretsManagerSyncFns.syncSecrets(secretSync, schemaSecretMap, secretMap);case SecretSync.GitHub:- return GithubSyncFns.syncSecrets(secretSync, schemaSecretMap, gatewayService, gatewayV2Service);+ return GithubSyncFns.syncSecrets(+ secretSync,+ schemaSecretMap,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );case SecretSync.GCPSecretManager:return GcpSyncFns.syncSecrets(secretSync, schemaSecretMap);case SecretSync.AzureKeyVault:@@ -341,7 +349,13 @@ export const SecretSyncFns = {case SecretSync.Windmill:return WindmillSyncFns.syncSecrets(secretSync, schemaSecretMap);case SecretSync.HCVault:- return HCVaultSyncFns.syncSecrets(secretSync, schemaSecretMap, gatewayService, gatewayV2Service);+ return HCVaultSyncFns.syncSecrets(+ secretSync,+ schemaSecretMap,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );case SecretSync.TeamCity:return TeamCitySyncFns.syncSecrets(secretSync, schemaSecretMap);case SecretSync.OCIVault:@@ -406,7 +420,7 @@ export const SecretSyncFns = {},getSecrets: async (secretSync: TSecretSyncWithCredentials,- { kmsService, appConnectionDAL, gatewayService, gatewayV2Service }: TSyncSecretDeps+ { kmsService, appConnectionDAL, gatewayService, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps): Promise<TSecretMap> => {let secretMap: TSecretMap;switch (secretSync.destination) {@@ -467,7 +481,7 @@ export const SecretSyncFns = {secretMap = await WindmillSyncFns.getSecrets(secretSync);break;case SecretSync.HCVault:- secretMap = await HCVaultSyncFns.getSecrets(secretSync, gatewayService, gatewayV2Service);+ secretMap = await HCVaultSyncFns.getSecrets(secretSync, gatewayService, gatewayV2Service, gatewayPoolService);break;case SecretSync.TeamCity:secretMap = await TeamCitySyncFns.getSecrets(secretSync);@@ -566,7 +580,7 @@ export const SecretSyncFns = {removeSecrets: (secretSync: TSecretSyncWithCredentials,secretMap: TSecretMap,- { kmsService, appConnectionDAL, gatewayService, gatewayV2Service }: TSyncSecretDeps+ { kmsService, appConnectionDAL, gatewayService, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps): Promise<void> => {const schemaSecretMap = addSchema(secretMap, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema);@@ -576,7 +590,13 @@ export const SecretSyncFns = {case SecretSync.AWSSecretsManager:return AwsSecretsManagerSyncFns.removeSecrets(secretSync, schemaSecretMap);case SecretSync.GitHub:- return GithubSyncFns.removeSecrets(secretSync, schemaSecretMap, gatewayService, gatewayV2Service);+ return GithubSyncFns.removeSecrets(+ secretSync,+ schemaSecretMap,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );case SecretSync.GCPSecretManager:return GcpSyncFns.removeSecrets(secretSync, schemaSecretMap);case SecretSync.AzureKeyVault:@@ -613,7 +633,13 @@ export const SecretSyncFns = {case SecretSync.Windmill:return WindmillSyncFns.removeSecrets(secretSync, schemaSecretMap);case SecretSync.HCVault:- return HCVaultSyncFns.removeSecrets(secretSync, schemaSecretMap, gatewayService, gatewayV2Service);+ return HCVaultSyncFns.removeSecrets(+ secretSync,+ schemaSecretMap,+ gatewayService,+ gatewayV2Service,+ gatewayPoolService+ );case SecretSync.TeamCity:return TeamCitySyncFns.removeSecrets(secretSync, schemaSecretMap);case SecretSync.OCIVault:diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex c3b9c81e0b..b9b1637439 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -6,6 +6,7 @@ import { randomUUID } from "crypto";import { ProjectMembershipRole, SecretType } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";@@ -119,6 +120,7 @@ type TSecretSyncQueueFactoryDep = {licenseService: Pick<TLicenseServiceFactory, "getPlan">;gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;projectSlackConfigDAL: Pick<TProjectSlackConfigDALFactory, "getIntegrationDetailsByProject">;projectMicrosoftTeamsConfigDAL: Pick<TProjectMicrosoftTeamsConfigDALFactory, "getIntegrationDetailsByProject">;@@ -166,6 +168,7 @@ export const secretSyncQueueFactory = ({licenseService,gatewayService,gatewayV2Service,+ gatewayPoolService,notificationService,projectSlackConfigDAL,projectMicrosoftTeamsConfigDAL,@@ -434,7 +437,8 @@ export const secretSyncQueueFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});if (!Object.keys(importedSecrets).length) return {};@@ -580,7 +584,8 @@ export const secretSyncQueueFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});syncResult = result ?? undefined;@@ -830,7 +835,8 @@ export const secretSyncQueueFactory = ({appConnectionDAL,kmsService,gatewayService,- gatewayV2Service+ gatewayV2Service,+ gatewayPoolService});diff --git a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsxindex b54ee7c4ec..4a092e452a 100644--- a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx+++ b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx@@ -1,6 +1,7 @@import { faGlobe, faLayerGroup, faServer } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useQuery } from "@tanstack/react-query";+import { twMerge } from "tailwind-merge";import { Select, SelectItem, Tooltip } from "@app/components/v2";import { useSubscription } from "@app/context";@@ -19,6 +20,9 @@ type Props = {onChange: (value: GatewayPickerValue) => void;isDisabled?: boolean;className?: string;+ isRequired?: boolean;+ placeholder?: string;+ variant?: "v2" | "v3";};const SectionLabel = ({ children }: { children: React.ReactNode }) => (@@ -27,7 +31,15 @@ const SectionLabel = ({ children }: { children: React.ReactNode }) => (const SectionDivider = () => <div className="my-1 h-px bg-mineshaft-600" />;-export const GatewayPicker = ({ value, onChange, isDisabled, className }: Props) => {+export const GatewayPicker = ({+ value,+ onChange,+ isDisabled,+ className,+ isRequired,+ placeholder,+ variant = "v2"+}: Props) => {const { subscription } = useSubscription();const showPools = subscription?.gatewayPool;@@ -39,7 +51,7 @@ export const GatewayPicker = ({ value, onChange, isDisabled, className }: Props)const isLoading = isGatewaysLoading || (showPools && isPoolsLoading);- let selectValue = "internet";+ let selectValue = isRequired ? "" : "internet";if (value.gatewayPoolId) {selectValue = `pool:${value.gatewayPoolId}`;} else if (value.gatewayId) {@@ -65,27 +77,41 @@ export const GatewayPicker = ({ value, onChange, isDisabled, className }: Props)(!("lastHealthCheckStatus" in gw) ||gw.lastHealthCheckStatus !== GatewayHealthCheckStatus.Failed);+ const itemHoverV3 =+ "[&_[data-radix-collection-item]:hover]:bg-foreground/5 [&_[data-radix-collection-item][data-highlighted]]:bg-foreground/5";+return (<Selectvalue={selectValue}onValueChange={handleChange}isDisabled={isDisabled}isLoading={Boolean(isLoading)}- className={className}- dropdownContainerClassName="max-w-none"+ containerClassName="contents"+ className={twMerge(+ "w-full",+ variant === "v3" && "h-9 border-border bg-transparent text-foreground",+ className+ )}+ dropdownContainerClassName={twMerge(+ "max-w-none",+ variant === "v3" && `border-border bg-popover text-foreground ${itemHoverV3}`+ )}position="popper"side="bottom"+ placeholder={placeholder}>- <SelectItem value="internet">- <div className="flex items-center gap-2">- <FontAwesomeIcon icon={faGlobe} className="size-3.5 text-mineshaft-400" />- Internet Gateway- </div>- </SelectItem>+ {!isRequired && (+ <SelectItem value="internet">+ <div className="flex items-center gap-2">+ <FontAwesomeIcon icon={faGlobe} className="size-3.5 text-mineshaft-400" />+ Internet Gateway+ </div>+ </SelectItem>+ )}{showPools && pools && pools.length > 0 && (<>- <SectionDivider />+ {!isRequired && <SectionDivider />}<SectionLabel><div className="flex items-center justify-between"><div className="flex items-center gap-2">@@ -118,7 +144,7 @@ export const GatewayPicker = ({ value, onChange, isDisabled, className }: Props){v2Gateways.length > 0 && (<>- <SectionDivider />+ {(!isRequired || (showPools && pools && pools.length > 0)) && <SectionDivider />}<SectionLabel><div className="flex items-center gap-2"><FontAwesomeIcon icon={faServer} className="size-3" />diff --git a/frontend/src/hooks/api/appConnections/mutations.tsx b/frontend/src/hooks/api/appConnections/mutations.tsxindex 1e60bc609f..d9a17807f5 100644--- a/frontend/src/hooks/api/appConnections/mutations.tsx+++ b/frontend/src/hooks/api/appConnections/mutations.tsx@@ -9,6 +9,7 @@ import {TRotateAppConnectionCredentialsDTO,TUpdateAppConnectionDTO} from "@app/hooks/api/appConnections/types";+import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";export const useCreateAppConnection = () => {const queryClient = useQueryClient();@@ -24,6 +25,7 @@ export const useCreateAppConnection = () => {onSuccess: ({ projectId, app }) => {queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -42,6 +44,7 @@ export const useUpdateAppConnection = () => {onSuccess: ({ projectId, app }) => {queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });// queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });}});@@ -75,6 +78,7 @@ export const useDeleteAppConnection = () => {onSuccess: ({ projectId, app }) => {queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });// queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });}});diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.tsindex 420d3792ca..44dcfeb032 100644--- a/frontend/src/hooks/api/appConnections/types/index.ts+++ b/frontend/src/hooks/api/appConnections/types/index.ts@@ -215,13 +215,19 @@ export type TCreateAppConnectionDTO = Pick<| "description"| "isPlatformManagedCredentials"| "gatewayId"+ | "gatewayPoolId"| "projectId">;export type TUpdateAppConnectionDTO = Partial<Pick<TAppConnection,- "name" | "credentials" | "description" | "isPlatformManagedCredentials" | "gatewayId"+ | "name"+ | "credentials"+ | "description"+ | "isPlatformManagedCredentials"+ | "gatewayId"+ | "gatewayPoolId">> & {connectionId: string;diff --git a/frontend/src/hooks/api/appConnections/types/root-connection.ts b/frontend/src/hooks/api/appConnections/types/root-connection.tsindex 40e204be51..2c98ee83e3 100644--- a/frontend/src/hooks/api/appConnections/types/root-connection.ts+++ b/frontend/src/hooks/api/appConnections/types/root-connection.ts@@ -23,6 +23,7 @@ export type TRootAppConnection = {};};gatewayId?: string | null;+ gatewayPoolId?: string | null;projectId?: string | null;project?: {name: string;diff --git a/frontend/src/hooks/api/dynamicSecret/mutation.ts b/frontend/src/hooks/api/dynamicSecret/mutation.tsindex 2d04334e6d..8b5b4b66d9 100644--- a/frontend/src/hooks/api/dynamicSecret/mutation.ts+++ b/frontend/src/hooks/api/dynamicSecret/mutation.ts@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { dashboardKeys } from "@app/hooks/api/dashboard/queries";+import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";import { dynamicSecretKeys } from "./queries";import {@@ -28,6 +29,7 @@ export const useCreateDynamicSecret = () => {queryClient.invalidateQueries({queryKey: dynamicSecretKeys.list({ path, projectSlug, environmentSlug })});+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -52,6 +54,7 @@ export const useUpdateDynamicSecret = () => {queryClient.invalidateQueries({queryKey: dynamicSecretKeys.details({ path, projectSlug, environmentSlug, name })});+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -73,6 +76,7 @@ export const useDeleteDynamicSecret = () => {queryClient.invalidateQueries({queryKey: dynamicSecretKeys.list({ path, projectSlug, environmentSlug })});+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};diff --git a/frontend/src/hooks/api/gateway-pools/types.ts b/frontend/src/hooks/api/gateway-pools/types.tsindex 1a6675e9aa..9154b84c72 100644--- a/frontend/src/hooks/api/gateway-pools/types.ts+++ b/frontend/src/hooks/api/gateway-pools/types.ts@@ -10,12 +10,39 @@ export type TGatewayPool = {connectedResourcesCount: number;};+type ConnectedProjectResource = {+ id: string;+ name: string;+ projectId: string;+ projectName: string | null;+};+export type TGatewayPoolConnectedResources = {kubernetesAuths: {id: string;identityId: string;identityName: string | null;}[];+ pkiDiscoveryConfigs: ConnectedProjectResource[];+ pamDomains: ConnectedProjectResource[];+ pamResources: (ConnectedProjectResource & { resourceType: string })[];+ pamDiscoverySources: (ConnectedProjectResource & { discoveryType: string })[];+ appConnections: {+ id: string;+ name: string;+ app: string;+ projectId: string | null;+ projectName: string | null;+ }[];+ dynamicSecrets: {+ id: string;+ name: string;+ type: string;+ folderId: string;+ projectId: string;+ projectName: string;+ environmentSlug: string;+ }[];};export type TGatewayPoolMember = {diff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 3cf95e4326..80663b9d0d 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { gatewayPoolsQueryKeys } from "../gateway-pools/queries";import { pamKeys } from "./queries";import {TCreatePamAccountDTO,@@ -42,6 +43,7 @@ export const useCreatePamResource = () => {},onSuccess: ({ projectId }) => {queryClient.invalidateQueries({ queryKey: pamKeys.listResources({ projectId }) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -62,6 +64,7 @@ export const useUpdatePamResource = () => {queryClient.invalidateQueries({queryKey: pamKeys.getResource(resourceType, resourceId)});+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -78,6 +81,7 @@ export const useDeletePamResource = () => {},onSuccess: ({ projectId }) => {queryClient.invalidateQueries({ queryKey: pamKeys.listResources({ projectId }) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};diff --git a/frontend/src/hooks/api/pam/types/base-resource.ts b/frontend/src/hooks/api/pam/types/base-resource.tsindex 95fac67553..e208cd81ae 100644--- a/frontend/src/hooks/api/pam/types/base-resource.ts+++ b/frontend/src/hooks/api/pam/types/base-resource.ts@@ -9,6 +9,7 @@ export interface TBasePamResource {projectId: string;name: string;gatewayId: string;+ gatewayPoolId?: string | null;domainId?: string | null;metadata?: { key: string; value: string }[];isFavorite?: boolean;diff --git a/frontend/src/hooks/api/pam/types/index.ts b/frontend/src/hooks/api/pam/types/index.tsindex ac0b7a3557..41730a4dde 100644--- a/frontend/src/hooks/api/pam/types/index.ts+++ b/frontend/src/hooks/api/pam/types/index.ts@@ -148,19 +148,21 @@ export type TListPamResourcesDTO = {export type TCreatePamResourceDTO = Pick<TPamResource,- "name" | "connectionDetails" | "resourceType" | "gatewayId" | "projectId"+ "name" | "connectionDetails" | "resourceType" | "projectId"> & {+ gatewayId?: string;+ gatewayPoolId?: string;domainId?: string | null;metadata?: { key: string; value: string }[];};export type { TSessionSummaryConfig };-export type TUpdatePamResourceDTO = Partial<- Pick<TPamResource, "name" | "connectionDetails" | "gatewayId">-> & {+export type TUpdatePamResourceDTO = Partial<Pick<TPamResource, "name" | "connectionDetails">> & {resourceId: string;resourceType: PamResourceType;+ gatewayId?: string;+ gatewayPoolId?: string;domainId?: string | null;metadata?: { key: string; value: string }[];rotationAccountCredentials?: { username: string; password: string } | null;diff --git a/frontend/src/hooks/api/pamDiscovery/mutations.tsx b/frontend/src/hooks/api/pamDiscovery/mutations.tsxindex ce131ddb14..296fd41c63 100644--- a/frontend/src/hooks/api/pamDiscovery/mutations.tsx+++ b/frontend/src/hooks/api/pamDiscovery/mutations.tsx@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { gatewayPoolsQueryKeys } from "../gateway-pools/queries";import { pamDiscoveryKeys } from "./queries";import {TCreatePamDiscoverySourceDTO,@@ -23,6 +24,7 @@ export const useCreatePamDiscoverySource = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.sources() });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -43,6 +45,7 @@ export const useUpdatePamDiscoverySource = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.all });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -58,6 +61,7 @@ export const useDeletePamDiscoverySource = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDiscoveryKeys.sources() });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};diff --git a/frontend/src/hooks/api/pamDiscovery/types.ts b/frontend/src/hooks/api/pamDiscovery/types.tsindex c6f95ef523..7aa4ee5ae2 100644--- a/frontend/src/hooks/api/pamDiscovery/types.ts+++ b/frontend/src/hooks/api/pamDiscovery/types.ts@@ -17,6 +17,7 @@ export type TPamDiscoverySource = {name: string;discoveryType: PamDiscoveryType;gatewayId?: string | null;+ gatewayPoolId?: string | null;discoveryConfiguration?: Record<string, unknown>;discoveryCredentials?: Record<string, unknown>;schedule?: string | null;@@ -115,7 +116,8 @@ export type TCreatePamDiscoverySourceDTO = {projectId: string;name: string;discoveryType: PamDiscoveryType;- gatewayId: string;+ gatewayId?: string;+ gatewayPoolId?: string;discoveryCredentials: Record<string, unknown>;discoveryConfiguration: Record<string, unknown>;schedule?: string;@@ -126,6 +128,7 @@ export type TUpdatePamDiscoverySourceDTO = {discoveryType: PamDiscoveryType;name?: string;gatewayId?: string;+ gatewayPoolId?: string;discoveryCredentials?: Record<string, unknown>;discoveryConfiguration?: Record<string, unknown>;schedule?: string;diff --git a/frontend/src/hooks/api/pamDomain/mutations.tsx b/frontend/src/hooks/api/pamDomain/mutations.tsxindex ad55891fb2..da29c6ce91 100644--- a/frontend/src/hooks/api/pamDomain/mutations.tsx+++ b/frontend/src/hooks/api/pamDomain/mutations.tsx@@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";+import { gatewayPoolsQueryKeys } from "../gateway-pools/queries";import { pamDomainKeys } from "./queries";import { TCreatePamDomainDTO, TDeletePamDomainDTO, TPamDomain, TUpdatePamDomainDTO } from "./types";@@ -17,6 +18,7 @@ export const useCreatePamDomain = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDomainKeys.domain() });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -33,6 +35,7 @@ export const useUpdatePamDomain = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDomainKeys.domain() });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};@@ -48,6 +51,7 @@ export const useDeletePamDomain = () => {},onSuccess: () => {queryClient.invalidateQueries({ queryKey: pamDomainKeys.domain() });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });}});};diff --git a/frontend/src/hooks/api/pamDomain/types.ts b/frontend/src/hooks/api/pamDomain/types.tsindex ac71807187..fd9342cc09 100644--- a/frontend/src/hooks/api/pamDomain/types.ts+++ b/frontend/src/hooks/api/pamDomain/types.ts@@ -7,6 +7,7 @@ export type TBasePamDomain = {name: string;domainType: PamDomainType;gatewayId?: string | null;+ gatewayPoolId?: string | null;createdAt: string;updatedAt: string;metadata?: Array<{ id: string; key: string; value: string }>;@@ -34,7 +35,8 @@ export type TCreatePamDomainDTO = {domainType: PamDomainType;projectId: string;name: string;- gatewayId: string;+ gatewayId?: string;+ gatewayPoolId?: string;connectionDetails: TActiveDirectoryConnectionDetails;metadata?: Array<{ key: string; value?: string }>;};@@ -44,6 +46,7 @@ export type TUpdatePamDomainDTO = {domainId: string;name?: string;gatewayId?: string;+ gatewayPoolId?: string;connectionDetails?: TActiveDirectoryConnectionDetails;metadata?: Array<{ key: string; value?: string }>;};diff --git a/frontend/src/hooks/api/pkiDiscovery/mutations.tsx b/frontend/src/hooks/api/pkiDiscovery/mutations.tsxindex 5aa1d59db7..648b876917 100644--- a/frontend/src/hooks/api/pkiDiscovery/mutations.tsx+++ b/frontend/src/hooks/api/pkiDiscovery/mutations.tsx@@ -3,6 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { createNotification } from "@app/components/notifications";import { apiRequest } from "@app/config/request";+import { gatewayPoolsQueryKeys } from "../gateway-pools/queries";import { pkiDiscoveryKeys, pkiInstallationKeys } from "./queries";import {TCreatePkiDiscoveryDTO,@@ -28,6 +29,7 @@ export const useCreatePkiDiscovery = () => {},onSuccess: (_, { projectId }) => {queryClient.invalidateQueries({ queryKey: pkiDiscoveryKeys.list(projectId) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });createNotification({text: "Successfully created discovery job",type: "success"@@ -49,6 +51,7 @@ export const useUpdatePkiDiscovery = () => {onSuccess: (discovery) => {queryClient.invalidateQueries({ queryKey: pkiDiscoveryKeys.list(discovery.projectId) });queryClient.invalidateQueries({ queryKey: pkiDiscoveryKeys.discovery(discovery.id) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });createNotification({text: "Successfully updated discovery job",type: "success"@@ -69,6 +72,7 @@ export const useDeletePkiDiscovery = () => {onSuccess: (discovery) => {queryClient.invalidateQueries({ queryKey: pkiDiscoveryKeys.list(discovery.projectId) });queryClient.invalidateQueries({ queryKey: pkiDiscoveryKeys.discovery(discovery.id) });+ queryClient.invalidateQueries({ queryKey: gatewayPoolsQueryKeys.allKey() });createNotification({text: "Successfully deleted discovery job",type: "success"diff --git a/frontend/src/hooks/api/pkiDiscovery/types.ts b/frontend/src/hooks/api/pkiDiscovery/types.tsindex 9b676043cf..d80701c96c 100644--- a/frontend/src/hooks/api/pkiDiscovery/types.ts+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts@@ -46,7 +46,9 @@ export type TPkiDiscovery = {isAutoScanEnabled: boolean;scanIntervalDays: number | null;gatewayId: string | null;+ gatewayPoolId: string | null;gatewayName: string | null;+ gatewayPoolName: string | null;isActive: boolean;lastScanStatus: PkiDiscoveryScanStatus | null;lastScanJobId: string | null;@@ -144,6 +146,7 @@ export type TCreatePkiDiscoveryDTO = {isAutoScanEnabled?: boolean;scanIntervalDays?: number;gatewayId?: string;+ gatewayPoolId?: string;};export type TUpdatePkiDiscoveryDTO = {@@ -154,6 +157,7 @@ export type TUpdatePkiDiscoveryDTO = {isAutoScanEnabled?: boolean;scanIntervalDays?: number | null;gatewayId?: string | null;+ gatewayPoolId?: string | null;isActive?: boolean;};diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsxindex c117595a4b..7043cc359c 100644--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx@@ -64,6 +64,12 @@ export const DiscoveryDetailsSection = ({ discovery }: Props) => {<DetailValue>{discovery.gatewayName}</DetailValue></Detail>)}+ {discovery.gatewayPoolName && (+ <Detail>+ <DetailLabel>Gateway Pool</DetailLabel>+ <DetailValue>{discovery.gatewayPoolName}</DetailValue>+ </Detail>+ )}<Detail><DetailLabel>Last Scanned</DetailLabel><DetailValue>diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsxindex 6e9abe6b1f..9523005580 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx@@ -1,7 +1,6 @@import { useEffect } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import {@@ -15,9 +14,9 @@ import {Switch,TextArea} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3";import { isInfisicalCloud } from "@app/helpers/platform";import {- gatewaysQueryKeys,PkiDiscoveryType,TPkiDiscovery,useCreatePkiDiscovery,@@ -177,7 +176,8 @@ const formSchema = z.object({ctx.addIssue({ code: z.ZodIssueCode.custom, message: result.error });}}),- gatewayId: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),isAutoScanEnabled: z.boolean(),scanIntervalDays: z.number().min(1).max(365).optional()});@@ -229,6 +229,7 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: ProhandleSubmit,reset,watch,+ setValue,formState: { isSubmitting }} = useForm<FormData>({resolver: zodResolver(formSchema),@@ -237,15 +238,13 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: Prodescription: "",targets: "",ports: DEFAULT_TLS_PORTS,- gatewayId: "none",+ gatewayId: null,+ gatewayPoolId: null,isAutoScanEnabled: false,scanIntervalDays: 7}});- const { data: gatewaysData } = useQuery(gatewaysQueryKeys.list());- const gateways = (gatewaysData || []).filter((g) => !g.isV1);-const createDiscovery = useCreatePkiDiscovery();const updateDiscovery = useUpdatePkiDiscovery();@@ -259,7 +258,8 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: Prodescription: discovery.description || "",targets: formatTargets(discovery),ports: formatPorts(discovery),- gatewayId: discovery.gatewayId || "none",+ gatewayId: discovery.gatewayId,+ gatewayPoolId: discovery.gatewayPoolId,isAutoScanEnabled: discovery.isAutoScanEnabled,scanIntervalDays: discovery.scanIntervalDays || 7});@@ -269,7 +269,8 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: Prodescription: "",targets: "",ports: DEFAULT_TLS_PORTS,- gatewayId: "none",+ gatewayId: null,+ gatewayPoolId: null,isAutoScanEnabled: false,scanIntervalDays: 7});@@ -300,7 +301,8 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: ProipRanges: ipRanges.length > 0 ? ipRanges : undefined,ports},- gatewayId: data.gatewayId && data.gatewayId !== "none" ? data.gatewayId : null,+ gatewayId: data.gatewayPoolId ? null : (data.gatewayId ?? null),+ gatewayPoolId: data.gatewayPoolId ?? null,isAutoScanEnabled: data.isAutoScanEnabled,scanIntervalDays: data.isAutoScanEnabled ? data.scanIntervalDays : null});@@ -315,7 +317,8 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: ProipRanges: ipRanges.length > 0 ? ipRanges : undefined,ports},- gatewayId: data.gatewayId && data.gatewayId !== "none" ? data.gatewayId : undefined,+ gatewayId: data.gatewayPoolId ? undefined : (data.gatewayId ?? undefined),+ gatewayPoolId: data.gatewayPoolId ?? undefined,isAutoScanEnabled: data.isAutoScanEnabled,scanIntervalDays: data.isAutoScanEnabled ? data.scanIntervalDays : undefined});@@ -405,53 +408,47 @@ export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: Pro<Controllername="gatewayId"control={control}- render={({ field }) => (- <FormControl- label="Gateway"- tooltipClassName="max-w-lg py-3"- tooltipText={- <div className="flex flex-col gap-3">- <p>- Use a gateway to discover certificates on private networks that are not- directly accessible from the internet. The gateway acts as a proxy, routing- scan traffic through your infrastructure.- </p>- {!isInfisicalCloud() && (+ render={() => {+ const gatewayIdVal = watch("gatewayId");+ const gatewayPoolIdVal = watch("gatewayPoolId");+ return (+ <FormControl+ label="Gateway"+ tooltipClassName="max-w-lg py-3"+ tooltipText={+ <div className="flex flex-col gap-3"><p>- Alternatively, you can set the{" "}- <span className="font-medium text-bunker-200">- ALLOW_INTERNAL_IP_CONNECTIONS- </span>{" "}- environment variable to <span className="font-medium">true</span> on your- instance to scan private networks directly without a gateway.+ Use a gateway to discover certificates on private networks that are not+ directly accessible from the internet. The gateway acts as a proxy, routing+ scan traffic through your infrastructure.</p>- )}- </div>- }- >- <Select- value={field.value}- onValueChange={field.onChange}- placeholder="Select a gateway (optional)"- className="w-full"+ {!isInfisicalCloud() && (+ <p>+ Alternatively, you can set the{" "}+ <span className="font-medium text-bunker-200">+ ALLOW_INTERNAL_IP_CONNECTIONS+ </span>{" "}+ environment variable to <span className="font-medium">true</span> on your+ instance to scan private networks directly without a gateway.+ </p>+ )}+ </div>+ }>- <SelectItem value="none" key="none">- None (Direct scan)- </SelectItem>- {gateways.length === 0 ? (- <SelectItem value="no-gateways" isDisabled>- No gateways available- </SelectItem>- ) : (- gateways.map((gateway) => (- <SelectItem value={gateway.id} key={gateway.id}>- {gateway.name}- </SelectItem>- ))- )}- </Select>- </FormControl>- )}+ <GatewayPicker+ value={{+ gatewayId: gatewayIdVal ?? null,+ gatewayPoolId: gatewayPoolIdVal ?? null+ }}+ onChange={({ gatewayId, gatewayPoolId }) => {+ setValue("gatewayId", gatewayId, { shouldDirty: true });+ setValue("gatewayPoolId", gatewayPoolId, { shouldDirty: true });+ }}+ className="w-full"+ />+ </FormControl>+ );+ }}/><Controllerdiff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GenericAppConnectionFields.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GenericAppConnectionFields.tsxindex 91304c257e..05311260b1 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GenericAppConnectionFields.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GenericAppConnectionFields.tsx@@ -22,6 +22,10 @@ export const genericAppConnectionFieldsSchema = z.object({.string().nullish().transform((v) => (v === "" ? null : v)),+ gatewayPoolId: z+ .string()+ .nullish()+ .transform((v) => (v === "" ? null : v)),isAutoRotationEnabled: z.boolean().optional(),rotation: rotationSchema.optional()});diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsxindex ead21dda65..9e2b3f43db 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx@@ -3,7 +3,6 @@ import crypto from "crypto";import { useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -21,6 +20,7 @@ import {SelectItem,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,@@ -32,7 +32,6 @@ import {useGetAppConnectionOauthReturnUrl} from "@app/helpers/appConnections";import { isInfisicalCloud } from "@app/helpers/platform";-import { gatewaysQueryKeys } from "@app/hooks/api";import {GitHubConnectionMethod,TGitHubConnection,@@ -115,6 +114,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proapp: AppConnection.GitHub,method: GitHubConnectionMethod.App,gatewayId: null,+ gatewayPoolId: null,credentials: {instanceType: "cloud"}@@ -130,10 +130,11 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Pro} = form;const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const selectedMethod = watch("method");const instanceType = watch("credentials.instanceType");+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const returnUrl = useGetAppConnectionOauthReturnUrl();@@ -285,6 +286,7 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Profield.onChange(e);if (e === "cloud") {setValue("gatewayId", null);+ setValue("gatewayPoolId", null);}}}className="w-full border border-mineshaft-500"@@ -321,47 +323,26 @@ export const GitHubConnectionForm = ({ appConnection, projectId, onSubmit }: Proa={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value || (null as unknown as string)}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(null)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: gatewayId ?? null,+ gatewayPoolId: gatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/HCVaultConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/HCVaultConnectionForm.tsxindex dce53fddad..dd9cb0348b 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/HCVaultConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/HCVaultConnectionForm.tsx@@ -1,6 +1,5 @@import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -14,13 +13,13 @@ import {SelectItem,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { HCVaultConnectionMethod, THCVaultConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";@@ -76,21 +75,24 @@ export const HCVaultConnectionForm = ({ appConnection, onSubmit }: Props) => {defaultValues: appConnection ?? {app: AppConnection.HCVault,method: HCVaultConnectionMethod.AppRole,- gatewayId: null+ gatewayId: null,+ gatewayPoolId: null}});const {handleSubmit,control,+ setValue,watch,formState: { isSubmitting, isDirty }} = form;const selectedMethod = watch("method");+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());return (<FormProvider {...form}>@@ -134,45 +136,23 @@ export const HCVaultConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/LdapConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/LdapConnectionForm.tsxindex d786a7d758..3b6434de81 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/LdapConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/LdapConnectionForm.tsx@@ -4,7 +4,6 @@ import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Tab } from "@headlessui/react";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -20,11 +19,11 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects, useSubscription } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";import { DistinguishedNameRegex, UserPrincipalNameRegex } from "@app/helpers/string";-import { gatewaysQueryKeys } from "@app/hooks/api";import {LdapConnectionMethod,LdapConnectionProvider,@@ -90,6 +89,7 @@ export const LdapConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.LDAP,method: LdapConnectionMethod.SimpleBind,gatewayId: null,+ gatewayPoolId: null,credentials: {provider: LdapConnectionProvider.ActiveDirectory,url: "",@@ -104,14 +104,16 @@ export const LdapConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,formState: { isSubmitting, isDirty },watch} = form;const selectedProvider = watch("credentials.provider");const sslEnabled = watch("credentials.url")?.startsWith("ldaps://") ?? false;+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());return (<FormProvider {...form}>@@ -128,48 +130,23 @@ export const LdapConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MsSqlConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MsSqlConnectionForm.tsxindex 082cdad3b5..a61ea046e6 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MsSqlConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MsSqlConnectionForm.tsx@@ -1,18 +1,17 @@import { useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";import { Button, FormControl, ModalClose, Select, SelectItem, Tooltip } from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { AppConnection } from "@app/hooks/api/appConnections/enums";import {MsSqlConnectionMethod,@@ -60,6 +59,7 @@ export const MsSqlConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.MsSql,method: MsSqlConnectionMethod.UsernameAndPassword,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 1433,@@ -76,12 +76,15 @@ export const MsSqlConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;const { subscription } = useSubscription();const isPlatformManagedCredentials = appConnection?.isPlatformManagedCredentials ?? false;- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const confirmSubmit = async (formData: FormData) => {if (formData.isPlatformManagedCredentials) {@@ -107,48 +110,23 @@ export const MsSqlConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MySqlConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MySqlConnectionForm.tsxindex a3108226ae..eb532c8f3b 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MySqlConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MySqlConnectionForm.tsx@@ -1,18 +1,17 @@import { useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";import { Button, FormControl, ModalClose, Select, SelectItem, Tooltip } from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { MySqlConnectionMethod, TMySqlConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { PlatformManagedConfirmationModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/PlatformManagedConfirmationModal";@@ -57,6 +56,7 @@ export const MySqlConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.MySql,method: MySqlConnectionMethod.UsernameAndPassword,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 3306,@@ -73,12 +73,15 @@ export const MySqlConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;const { subscription } = useSubscription();const isPlatformManagedCredentials = appConnection?.isPlatformManagedCredentials ?? false;- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const confirmSubmit = async (formData: FormData) => {if (formData.isPlatformManagedCredentials) {@@ -104,48 +107,23 @@ export const MySqlConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/NetScalerConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/NetScalerConnectionForm.tsxindex 038200e97f..47f16f527f 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/NetScalerConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/NetScalerConnectionForm.tsx@@ -4,7 +4,6 @@ import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Tab } from "@headlessui/react";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -20,10 +19,10 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { NetScalerConnectionMethod, TNetScalerConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";@@ -86,6 +85,7 @@ export const NetScalerConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.NetScaler,method: NetScalerConnectionMethod.BasicAuth,gatewayId: null,+ gatewayPoolId: null,credentials: {sslRejectUnauthorized: false,sslCertificate: undefined@@ -96,10 +96,13 @@ export const NetScalerConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");return (<FormProvider {...form}>@@ -110,48 +113,23 @@ export const NetScalerConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan><Controllerdiff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/OracleDBConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/OracleDBConnectionForm.tsxindex d16763132e..bb4b66ccc0 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/OracleDBConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/OracleDBConnectionForm.tsx@@ -1,18 +1,17 @@import { useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";import { Button, FormControl, ModalClose, Select, SelectItem, Tooltip } from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { OracleDBConnectionMethod, TOracleDBConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { PlatformManagedConfirmationModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/PlatformManagedConfirmationModal";@@ -57,6 +56,7 @@ export const OracleDBConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.OracleDB,method: OracleDBConnectionMethod.UsernameAndPassword,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 1521,@@ -73,12 +73,15 @@ export const OracleDBConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;const { subscription } = useSubscription();const isPlatformManagedCredentials = appConnection?.isPlatformManagedCredentials ?? false;- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const confirmSubmit = async (formData: FormData) => {if (formData.isPlatformManagedCredentials) {@@ -104,48 +107,23 @@ export const OracleDBConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/PostgresConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/PostgresConnectionForm.tsxindex ae00d7b574..0e6cdefc27 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/PostgresConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/PostgresConnectionForm.tsx@@ -1,18 +1,17 @@import { useState } from "react";import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";import { Button, FormControl, ModalClose, Select, SelectItem, Tooltip } from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { PostgresConnectionMethod, TPostgresConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";import { PlatformManagedConfirmationModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/shared/PlatformManagedConfirmationModal";@@ -57,6 +56,7 @@ export const PostgresConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.Postgres,method: PostgresConnectionMethod.UsernameAndPassword,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 5432,@@ -73,12 +73,15 @@ export const PostgresConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;const { subscription } = useSubscription();const isPlatformManagedCredentials = appConnection?.isPlatformManagedCredentials ?? false;- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const confirmSubmit = async (formData: FormData) => {if (formData.isPlatformManagedCredentials) {@@ -104,48 +107,23 @@ export const PostgresConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SmbConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SmbConnectionForm.tsxindex 21fd5e0d74..3eaa946426 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SmbConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SmbConnectionForm.tsx@@ -1,19 +1,10 @@import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";-import {- Button,- FormControl,- Input,- ModalClose,- SecretInput,- Select,- SelectItem,- Tooltip-} from "@app/components/v2";+import { Button, FormControl, Input, ModalClose, SecretInput, Tooltip } from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects, useSubscription } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";@@ -24,7 +15,6 @@ import {SMB_VALIDATION_LIMITS,validateSmbPassword} from "@app/helpers/smb";-import { gatewaysQueryKeys } from "@app/hooks/api";import { SmbConnectionMethod, TSmbConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";@@ -105,6 +95,7 @@ export const SmbConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.SMB,method: SmbConnectionMethod.Credentials,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 445,@@ -118,11 +109,14 @@ export const SmbConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());return (<FormProvider {...form}>@@ -134,48 +128,23 @@ export const SmbConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SshConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SshConnectionForm.tsxindex e458079756..b34a32d2ab 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SshConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/SshConnectionForm.tsx@@ -1,6 +1,5 @@import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -14,10 +13,10 @@ import {SelectItem,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects, useSubscription } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { SshConnectionMethod, TSshConnection } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";@@ -78,6 +77,7 @@ export const SshConnectionForm = ({ appConnection, onSubmit }: Props) => {app: AppConnection.SSH,method: SshConnectionMethod.SshKey,gatewayId: null,+ gatewayPoolId: null,credentials: {host: "",port: 22,@@ -96,8 +96,9 @@ export const SshConnectionForm = ({ appConnection, onSubmit }: Props) => {} = form;const selectedMethod = watch("method");+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const handleMethodChange = (newMethod: SshConnectionMethod) => {const currentCredentials = form.getValues("credentials");@@ -132,48 +133,23 @@ export const SshConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiTppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiTppConnectionForm.tsxindex 1dc0556290..019ddaa254 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiTppConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/VenafiTppConnectionForm.tsx@@ -1,6 +1,5 @@import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import { OrgPermissionCan } from "@app/components/permissions";@@ -14,13 +13,13 @@ import {SelectItem,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { useSubscription } from "@app/context";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";-import { gatewaysQueryKeys } from "@app/hooks/api";import { TVenafiTppConnection, VenafiTppConnectionMethod } from "@app/hooks/api/appConnections";import { AppConnection } from "@app/hooks/api/appConnections/enums";@@ -67,6 +66,7 @@ export const VenafiTppConnectionForm = ({ appConnection, onSubmit }: Props) => {name: "",description: "",gatewayId: null,+ gatewayPoolId: null,credentials: {tppUrl: "",clientId: "",@@ -79,11 +79,14 @@ export const VenafiTppConnectionForm = ({ appConnection, onSubmit }: Props) => {const {handleSubmit,control,+ setValue,+ watch,formState: { isSubmitting, isDirty }} = form;+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");const { subscription } = useSubscription();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());return (<FormProvider {...form}>@@ -126,45 +129,23 @@ export const VenafiTppConnectionForm = ({ appConnection, onSubmit }: Props) => {a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="gatewayId"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <Select- isDisabled={!isAllowed}- value={value as string}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true });+ setValue("gatewayPoolId", newPoolId, { shouldDirty: true });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan>)}diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolConnectedResourcesDrawer.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolConnectedResourcesDrawer.tsxindex 8200f37210..b6a67e9217 100644--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolConnectedResourcesDrawer.tsx+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolConnectedResourcesDrawer.tsx@@ -29,33 +29,47 @@ type Props = {const getTotalResourceCount = (resources: TGatewayPoolConnectedResources | undefined): number => {if (!resources) return 0;- return resources.kubernetesAuths.length;+ return (+ resources.kubernetesAuths.length ++ resources.pkiDiscoveryConfigs.length ++ resources.pamDomains.length ++ resources.pamResources.length ++ resources.pamDiscoverySources.length ++ resources.appConnections.length ++ resources.dynamicSecrets.length+ );};type ResourceRowProps = {name: string;subtitle: string;- to: string;- params: Record<string, string>;+ to?: string;+ params?: Record<string, string>;isLast?: boolean;};const ResourceRow = ({ name, subtitle, to, params, isLast }: ResourceRowProps) => {- return (- <Link- to={to as "/"}- params={params}- className={`flex items-center justify-between px-4 py-2.5 transition-colors hover:bg-mineshaft-700/30 ${- !isLast ? "border-b border-mineshaft-600" : ""- }`}- >+ const className = `flex items-center justify-between px-4 py-2.5 ${+ to ? "transition-colors hover:bg-mineshaft-700/30" : ""+ } ${!isLast ? "border-b border-mineshaft-600" : ""}`;+ const inner = (+ <><div className="flex flex-col gap-0.5"><span className="text-sm text-mineshaft-100">{name}</span><span className="text-xs text-mineshaft-400">{subtitle}</span></div>- <ExternalLinkIcon className="size-3.5 text-mineshaft-400" />- </Link>+ {to ? <ExternalLinkIcon className="size-3.5 text-mineshaft-400" /> : null}+ </>);++ if (to && params) {+ return (+ <Link to={to as "/"} params={params} className={className}>+ {inner}+ </Link>+ );+ }+ return <div className={className}>{inner}</div>;};export const PoolConnectedResourcesDrawer = ({ isOpen, onOpenChange, poolId, poolName }: Props) => {@@ -64,9 +78,17 @@ export const PoolConnectedResourcesDrawer = ({ isOpen, onOpenChange, poolId, pooconst totalCount = getTotalResourceCount(resources);- const defaultOpenSections = [resources?.kubernetesAuths.length ? "kubernetes-auth" : null].filter(- Boolean- ) as string[];+ const defaultOpenSections = (+ [+ resources?.kubernetesAuths.length ? "kubernetes-auth" : null,+ resources?.pkiDiscoveryConfigs.length ? "pki-discovery" : null,+ resources?.pamDomains.length ? "pam-domains" : null,+ resources?.pamResources.length ? "pam-resources" : null,+ resources?.pamDiscoverySources.length ? "pam-discovery" : null,+ resources?.appConnections.length ? "app-connections" : null,+ resources?.dynamicSecrets.length ? "dynamic-secrets" : null+ ] as (string | null)[]+ ).filter(Boolean) as string[];return (<Sheet open={isOpen} onOpenChange={onOpenChange}>@@ -118,6 +140,120 @@ export const PoolConnectedResourcesDrawer = ({ isOpen, onOpenChange, poolId, poo</AccordionContent></AccordionItem>)}++ {(resources?.pkiDiscoveryConfigs.length ?? 0) > 0 && (+ <AccordionItem value="pki-discovery">+ <AccordionTrigger>+ <span className="flex-1">PKI Discovery</span>+ <Badge variant="neutral">{resources?.pkiDiscoveryConfigs.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.pkiDiscoveryConfigs.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={r.projectName ? `Project: ${r.projectName}` : "PKI Discovery"}+ isLast={idx === (resources?.pkiDiscoveryConfigs.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}++ {(resources?.pamDomains.length ?? 0) > 0 && (+ <AccordionItem value="pam-domains">+ <AccordionTrigger>+ <span className="flex-1">PAM Domains</span>+ <Badge variant="neutral">{resources?.pamDomains.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.pamDomains.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={r.projectName ? `Project: ${r.projectName}` : "PAM Domain"}+ isLast={idx === (resources?.pamDomains.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}++ {(resources?.pamResources.length ?? 0) > 0 && (+ <AccordionItem value="pam-resources">+ <AccordionTrigger>+ <span className="flex-1">PAM Resources</span>+ <Badge variant="neutral">{resources?.pamResources.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.pamResources.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={`${r.resourceType}${r.projectName ? ` · ${r.projectName}` : ""}`}+ isLast={idx === (resources?.pamResources.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}++ {(resources?.pamDiscoverySources.length ?? 0) > 0 && (+ <AccordionItem value="pam-discovery">+ <AccordionTrigger>+ <span className="flex-1">PAM Discovery Sources</span>+ <Badge variant="neutral">{resources?.pamDiscoverySources.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.pamDiscoverySources.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={`${r.discoveryType}${r.projectName ? ` · ${r.projectName}` : ""}`}+ isLast={idx === (resources?.pamDiscoverySources.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}++ {(resources?.appConnections.length ?? 0) > 0 && (+ <AccordionItem value="app-connections">+ <AccordionTrigger>+ <span className="flex-1">App Connections</span>+ <Badge variant="neutral">{resources?.appConnections.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.appConnections.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={`${r.app}${r.projectName ? ` · ${r.projectName}` : ""}`}+ isLast={idx === (resources?.appConnections.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}++ {(resources?.dynamicSecrets.length ?? 0) > 0 && (+ <AccordionItem value="dynamic-secrets">+ <AccordionTrigger>+ <span className="flex-1">Dynamic Secrets</span>+ <Badge variant="neutral">{resources?.dynamicSecrets.length}</Badge>+ </AccordionTrigger>+ <AccordionContent className="p-0">+ {resources?.dynamicSecrets.map((r, idx) => (+ <ResourceRow+ key={r.id}+ name={r.name}+ subtitle={`${r.type} · ${r.environmentSlug}${r.projectName ? ` · ${r.projectName}` : ""}`}+ isLast={idx === (resources?.dynamicSecrets.length ?? 0) - 1}+ />+ ))}+ </AccordionContent>+ </AccordionItem>+ )}</Accordion>)}</div>diff --git a/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx b/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsxindex 1464ce117d..648395ae05 100644--- a/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx+++ b/frontend/src/pages/pam/PamDiscoveryDetailPage/PamDiscoveryDetailPage.tsx@@ -55,6 +55,7 @@ import { ProjectPermissionSub, useOrganization } from "@app/context";import { ProjectPermissionPamDiscoveryActions } from "@app/context/ProjectPermissionContext/types";import { usePagination } from "@app/hooks";import { gatewaysQueryKeys } from "@app/hooks/api";+import { useListGatewayPools } from "@app/hooks/api/gateway-pools/queries";import type {TPamDiscoverySource,TPamDiscoverySourceRunProgress@@ -143,7 +144,9 @@ const DiscoveryConfigurationSection = ({onEdit: VoidFunction;}) => {const { data: gateways } = useQuery(gatewaysQueryKeys.list());+ const { data: pools } = useListGatewayPools();const gateway = gateways?.find((g) => g.id === source.gatewayId);+ const pool = pools?.find((p) => p.id === source.gatewayPoolId);return (<div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">@@ -167,6 +170,12 @@ const DiscoveryConfigurationSection = ({<DetailValue>{gateway?.name ?? "Unknown"}</DetailValue></Detail>)}+ {source.gatewayPoolId && (+ <Detail>+ <DetailLabel>Gateway Pool</DetailLabel>+ <DetailValue>{pool?.name ?? "Unknown"}</DetailValue>+ </Detail>+ )}<Detail><DetailLabel>Domain FQDN</DetailLabel><DetailValue>{(source.discoveryConfiguration?.domainFQDN as string) || "-"}</DetailValue>diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsxindex 6b2ff268d9..8b90f26efe 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/ActiveDirectoryDiscoveryForm.tsx@@ -81,7 +81,8 @@ export const ActiveDirectoryDiscoveryForm = ({ source, onSubmit, closeSheet }: P? {discoveryType: PamDiscoveryType.ActiveDirectory,name: source.name,- gateway: source.gatewayId ? { id: source.gatewayId, name: "" } : undefined,+ gatewayId: source.gatewayId ?? null,+ gatewayPoolId: source.gatewayPoolId ?? null,schedule: source.schedule || "manual",discoveryConfiguration: {domainFQDN: (source.discoveryConfiguration?.domainFQDN as string) || "",@@ -115,7 +116,8 @@ export const ActiveDirectoryDiscoveryForm = ({ source, onSubmit, closeSheet }: P: {discoveryType: PamDiscoveryType.ActiveDirectory,schedule: "manual",- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,discoveryConfiguration: {domainFQDN: "",dcAddress: "",diff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsxindex f4ec88802d..9ecd4aa7c9 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/GenericDiscoveryFields.tsx@@ -1,5 +1,4 @@import { Controller, useFormContext } from "react-hook-form";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";import {@@ -7,7 +6,6 @@ import {FieldContent,FieldError,FieldLabel,- FilterableSelect,Input,Select,SelectContent,@@ -15,31 +13,27 @@ import {SelectTrigger,SelectValue} from "@app/components/v3";-import { gatewaysQueryKeys } from "@app/hooks/api";--export const gatewayOptionSchema = z.object({- id: z.string().min(1, "Gateway is required"),- name: z.string()-});+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";+// No .refine() — would turn into ZodEffects and break .extend() in per-type discovery forms.export const genericDiscoveryFieldsSchema = z.object({name: z.string().trim().min(1, "Name is required").max(255),- gateway: gatewayOptionSchema.nullable().refine((val) => val !== null, {- message: "Gateway is required"- }),+ gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional(),schedule: z.string().default("manual")});type GenericFormValues = {name: string;- gateway: { id: string; name: string } | null;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;schedule: string;};export const GenericDiscoveryFields = () => {- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());-- const { control } = useFormContext<GenericFormValues>();+ const { control, watch, setValue } = useFormContext<GenericFormValues>();+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");return (<div className="flex flex-col gap-3">@@ -66,31 +60,28 @@ export const GenericDiscoveryFields = () => {<Controllercontrol={control}- name="gateway"- render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => {- const selectedOption =- value && gateways ? (gateways.find((g) => g.id === value.id) ?? value) : value;-- return (- <Field>- <FieldLabel>Gateway</FieldLabel>- <FieldContent>- <FilterableSelect- value={selectedOption}- onChange={onChange}- onBlur={onBlur}- options={gateways}- isError={Boolean(error)}- isLoading={isGatewaysLoading}- placeholder="Select a Gateway..."- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- );- }}+ name="gatewayId"+ render={({ fieldState: { error } }) => (+ <Field>+ <FieldLabel>Gateway</FieldLabel>+ <FieldContent>+ <GatewayPicker+ isRequired+ variant="v3"+ placeholder="Select a Gateway..."+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true, shouldValidate: true });+ setValue("gatewayPoolId", newPoolId, {+ shouldDirty: true,+ shouldValidate: true+ });+ }}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/><Controllerdiff --git a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsxindex e6fe81122f..10cb0753f8 100644--- a/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx+++ b/frontend/src/pages/pam/PamDiscoveryPage/components/PamDiscoverySourceForm/PamDiscoverySourceForm.tsx@@ -29,7 +29,8 @@ const CreateForm = ({ discoveryType, closeSheet, projectId }: CreateFormProps) =const onSubmit = async (formData: {name: string;- gateway: { id: string; name: string } | null;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;schedule: string;discoveryType: PamDiscoveryType;discoveryConfiguration: Record<string, unknown>;@@ -39,7 +40,8 @@ const CreateForm = ({ discoveryType, closeSheet, projectId }: CreateFormProps) =projectId,name: formData.name,discoveryType: formData.discoveryType,- gatewayId: formData.gateway!.id,+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined,discoveryConfiguration: formData.discoveryConfiguration,discoveryCredentials: formData.discoveryCredentials,schedule: formData.schedule@@ -65,7 +67,8 @@ const UpdateForm = ({ source, closeSheet }: UpdateFormProps) => {const onSubmit = async (formData: {name: string;- gateway: { id: string; name: string } | null;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;schedule: string;discoveryType: PamDiscoveryType;discoveryConfiguration: Record<string, unknown>;@@ -75,7 +78,8 @@ const UpdateForm = ({ source, closeSheet }: UpdateFormProps) => {discoverySourceId: source.id,discoveryType: formData.discoveryType,name: formData.name,- gatewayId: formData.gateway!.id,+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined,discoveryConfiguration: formData.discoveryConfiguration,discoveryCredentials: formData.discoveryCredentials,schedule: formData.schedulediff --git a/frontend/src/pages/pam/PamDomainByIDPage/components/PamDomainConnectionSection.tsx b/frontend/src/pages/pam/PamDomainByIDPage/components/PamDomainConnectionSection.tsxindex 02c7fc460b..0fe38222e3 100644--- a/frontend/src/pages/pam/PamDomainByIDPage/components/PamDomainConnectionSection.tsx+++ b/frontend/src/pages/pam/PamDomainByIDPage/components/PamDomainConnectionSection.tsx@@ -5,6 +5,7 @@ import { ProjectPermissionCan } from "@app/components/permissions";import { Detail, DetailGroup, DetailLabel, DetailValue, IconButton } from "@app/components/v3";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";import { gatewaysQueryKeys } from "@app/hooks/api";+import { useListGatewayPools } from "@app/hooks/api/gateway-pools/queries";import { PamDomainType, TPamDomain } from "@app/hooks/api/pamDomain";type Props = {@@ -35,7 +36,9 @@ const ActiveDirectoryConnectionDetails = ({export const PamDomainConnectionSection = ({ domain, onEdit }: Props) => {const { data: gateways } = useQuery(gatewaysQueryKeys.list());+ const { data: pools } = useListGatewayPools();const gateway = gateways?.find((g) => g.id === domain.gatewayId);+ const pool = pools?.find((p) => p.id === domain.gatewayPoolId);return (<div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">@@ -56,6 +59,12 @@ export const PamDomainConnectionSection = ({ domain, onEdit }: Props) => {<DetailValue>{gateway?.name ?? "Unknown"}</DetailValue></Detail>)}+ {domain.gatewayPoolId && (+ <Detail>+ <DetailLabel>Gateway Pool</DetailLabel>+ <DetailValue>{pool?.name ?? "Unknown"}</DetailValue>+ </Detail>+ )}{domain.domainType === PamDomainType.ActiveDirectory && (<ActiveDirectoryConnectionDetails connectionDetails={domain.connectionDetails} />)}diff --git a/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/ActiveDirectoryDomainForm.tsx b/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/ActiveDirectoryDomainForm.tsxindex 9cc3a30a53..fdab5b8c7c 100644--- a/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/ActiveDirectoryDomainForm.tsx+++ b/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/ActiveDirectoryDomainForm.tsx@@ -62,7 +62,8 @@ export const ActiveDirectoryDomainForm = ({ domain, onSubmit, closeSheet }: PropdefaultValues: domain? {name: domain.name,- gateway: domain.gatewayId ? { id: domain.gatewayId, name: "" } : undefined,+ gatewayId: domain.gatewayId ?? null,+ gatewayPoolId: domain.gatewayPoolId ?? null,connectionDetails: {...domain.connectionDetails,useLdaps: domain.connectionDetails.useLdaps ?? false,@@ -72,7 +73,8 @@ export const ActiveDirectoryDomainForm = ({ domain, onSubmit, closeSheet }: Prop}}: {- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {domain: "",dcAddress: "",diff --git a/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/PamDomainForm.tsx b/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/PamDomainForm.tsxindex 1adfcc0884..0c85bf35bc 100644--- a/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/PamDomainForm.tsx+++ b/frontend/src/pages/pam/PamDomainsPage/components/PamDomainForm/PamDomainForm.tsx@@ -30,20 +30,20 @@ const CreateForm = ({ domainType, closeSheet, projectId }: CreateFormProps) => {const onSubmit = async (formData: Record<string, unknown> & {name: string;- gateway?: { id: string; name: string } | null;- gatewayId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;connectionDetails: unknown;metadata?: { key: string; value: string }[];}) => {- const { gateway, ...rest } = formData;const domain = await createPamDomain.mutateAsync({- ...rest,+ ...formData,domainType,projectId,- gatewayId: gateway?.id ?? rest.gatewayId!,- connectionDetails: rest.connectionDetails as TPamDomain["connectionDetails"],- metadata: rest.metadata+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined,+ connectionDetails: formData.connectionDetails as TPamDomain["connectionDetails"],+ metadata: formData.metadata});createNotification({text: `Successfully created ${domainName} domain`,@@ -69,20 +69,20 @@ const UpdateForm = ({ domain, closeSheet }: UpdateFormProps) => {const onSubmit = async (formData: Record<string, unknown> & {name?: string;- gateway?: { id: string; name: string } | null;- gatewayId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;connectionDetails?: unknown;metadata?: { key: string; value: string }[];}) => {- const { gateway, ...rest } = formData;const updatedDomain = await updatePamDomain.mutateAsync({domainId: domain.id,domainType: domain.domainType,- ...rest,- gatewayId: gateway?.id ?? rest.gatewayId,- connectionDetails: rest.connectionDetails as TPamDomain["connectionDetails"],- metadata: rest.metadata+ ...formData,+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined,+ connectionDetails: formData.connectionDetails as TPamDomain["connectionDetails"],+ metadata: formData.metadata});createNotification({text: `Successfully updated ${domainName} domain`,diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceConnectionSection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceConnectionSection.tsxindex 7813b0bc0c..cf758931e5 100644--- a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceConnectionSection.tsx+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceConnectionSection.tsx@@ -5,6 +5,7 @@ import { ProjectPermissionCan } from "@app/components/permissions";import { Detail, DetailLabel, DetailValue, IconButton } from "@app/components/v3";import { ProjectPermissionActions, ProjectPermissionSub } from "@app/context";import { gatewaysQueryKeys } from "@app/hooks/api";+import { useListGatewayPools } from "@app/hooks/api/gateway-pools/queries";import { PamResourceType, TPamResource } from "@app/hooks/api/pam";type Props = {@@ -203,8 +204,10 @@ export const PamResourceConnectionSection = ({onEdit}: Props & { onEdit: VoidFunction }) => {const { data: gateways } = useQuery(gatewaysQueryKeys.list());+ const { data: pools } = useListGatewayPools();const gateway = gateways?.find((g) => g.id === resource.gatewayId);+ const pool = pools?.find((p) => p.id === resource.gatewayPoolId);return (<div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">@@ -228,6 +231,12 @@ export const PamResourceConnectionSection = ({<DetailValue>{gateway?.name ?? "Unknown"}</DetailValue></Detail>)}+ {resource.gatewayPoolId && (+ <Detail>+ <DetailLabel>Gateway Pool</DetailLabel>+ <DetailValue>{pool?.name ?? "Unknown"}</DetailValue>+ </Detail>+ )}<ConnectionDetailsContent resource={resource} /></div></div>diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/GenericResourceFields.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/GenericResourceFields.tsxindex 5895b820d0..42aa807837 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/GenericResourceFields.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/GenericResourceFields.tsx@@ -1,28 +1,15 @@import { Controller, useFormContext } from "react-hook-form";-import { useQuery } from "@tanstack/react-query";import { z } from "zod";-import {- Field,- FieldContent,- FieldError,- FieldLabel,- FilterableSelect,- Input-} from "@app/components/v3";-import { gatewaysQueryKeys } from "@app/hooks/api";+import { Field, FieldContent, FieldError, FieldLabel, Input } from "@app/components/v3";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { slugSchema } from "@app/lib/schemas";-export const gatewayOptionSchema = z.object({- id: z.string().min(1, "Gateway is required"),- name: z.string()-});-+// No .refine() — would turn into ZodEffects and break .extend() in per-resource forms.export const genericResourceFieldsSchema = z.object({name: slugSchema({ min: 1, max: 64, field: "Name" }),- gateway: gatewayOptionSchema.nullable().refine((val) => val !== null, {- message: "Gateway is required"- }),+ gatewayId: z.string().nullable().optional(),+ gatewayPoolId: z.string().nullable().optional(),metadata: z.object({key: z.string().trim().min(1),@@ -34,13 +21,14 @@ export const genericResourceFieldsSchema = z.object({type GenericFormValues = {name: string;- gateway: { id: string; name: string } | null;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;};export const GenericResourceFields = () => {- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());-- const { control } = useFormContext<GenericFormValues>();+ const { control, watch, setValue } = useFormContext<GenericFormValues>();+ const gatewayId = watch("gatewayId");+ const gatewayPoolId = watch("gatewayPoolId");return (<div className="flex flex-col gap-3">@@ -60,31 +48,28 @@ export const GenericResourceFields = () => {<Controllercontrol={control}- name="gateway"- render={({ field: { value, onChange, onBlur }, fieldState: { error } }) => {- const selectedOption =- value && gateways ? (gateways.find((g) => g.id === value.id) ?? value) : value;-- return (- <Field>- <FieldLabel>Gateway</FieldLabel>- <FieldContent>- <FilterableSelect- value={selectedOption}- onChange={onChange}- onBlur={onBlur}- options={gateways}- isError={Boolean(error)}- isLoading={isGatewaysLoading}- placeholder="Select a Gateway..."- getOptionLabel={(option) => option.name}- getOptionValue={(option) => option.id}- />- <FieldError errors={[error]} />- </FieldContent>- </Field>- );- }}+ name="gatewayId"+ render={({ fieldState: { error } }) => (+ <Field>+ <FieldLabel>Gateway</FieldLabel>+ <FieldContent>+ <GatewayPicker+ isRequired+ variant="v3"+ placeholder="Select a Gateway..."+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("gatewayId", newGwId, { shouldDirty: true, shouldValidate: true });+ setValue("gatewayPoolId", newPoolId, {+ shouldDirty: true,+ shouldValidate: true+ });+ }}+ />+ <FieldError errors={[error]} />+ </FieldContent>+ </Field>+ )}/></div>);diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsxindex 934dcaf680..773c106f79 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/KubernetesResourceForm.tsx@@ -54,11 +54,13 @@ export const KubernetesResourceForm = ({ resource, onSubmit, closeSheet }: PropsdefaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.Kubernetes,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {url: "",sslRejectUnauthorized: true,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MongoDBResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MongoDBResourceForm.tsxindex 78d6960b46..a11f32efd3 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MongoDBResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MongoDBResourceForm.tsx@@ -100,12 +100,14 @@ export const MongoDBResourceForm = ({ resource, onSubmit, closeSheet }: Props) =defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined,+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null,connectionDetails: resource.connectionDetails}: {resourceType: PamResourceType.MongoDB,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {connectionString: "",database: "admin",diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MsSQLResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MsSQLResourceForm.tsxindex 14f4e9a11f..b4c20229f9 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MsSQLResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MsSQLResourceForm.tsx@@ -31,11 +31,13 @@ export const MsSQLResourceForm = ({ resource, onSubmit, closeSheet }: Props) =>defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.MsSQL,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 1433,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MySQLResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MySQLResourceForm.tsxindex 57951df92c..3210d0fffd 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MySQLResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/MySQLResourceForm.tsx@@ -33,11 +33,13 @@ export const MySQLResourceForm = ({ resource, onSubmit, closeSheet }: Props) =>defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.MySQL,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 3306,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/OracleDBResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/OracleDBResourceForm.tsxindex a8056068c4..0742f33ec9 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/OracleDBResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/OracleDBResourceForm.tsx@@ -43,11 +43,13 @@ export const OracleDBResourceForm = ({ resource, onSubmit, closeSheet }: Props)defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.OracleDB,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 1521,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsxindex b48cab935b..70695fbaad 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PamResourceForm.tsx@@ -42,15 +42,15 @@ const CreateForm = ({ resourceType, closeSheet, projectId }: CreateFormProps) =>TPamResource,"name" | "resourceType" | "connectionDetails" | "domainId"> & {- gateway?: { id: string; name: string } | null;- gatewayId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;metadata?: { key: string; value: string }[];}) => {- const { gateway, ...rest } = formData;const resource = await createPamResource.mutateAsync({- ...rest,- gatewayId: gateway?.id ?? rest.gatewayId,+ ...formData,+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined,projectId});createNotification({@@ -95,16 +95,16 @@ const UpdateForm = ({ resource, closeSheet }: UpdateFormProps) => {TPamResource,"name" | "resourceType" | "connectionDetails" | "domainId"> & {- gateway?: { id: string; name: string } | null;- gatewayId?: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;metadata?: { key: string; value: string }[];}) => {- const { gateway, ...rest } = formData;const updatedResource = await updatePamResource.mutateAsync({resourceId: resource.id,- ...rest,- gatewayId: gateway?.id ?? rest.gatewayId+ ...formData,+ gatewayId: formData.gatewayId ?? undefined,+ gatewayPoolId: formData.gatewayPoolId ?? undefined});createNotification({text: `Successfully updated ${resourceName} resource`,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsxindex 56b65eaaf4..e23fed7b7b 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/PostgresResourceForm.tsx@@ -31,11 +31,13 @@ export const PostgresResourceForm = ({ resource, onSubmit, closeSheet }: Props)defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.Postgres,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 5432,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/RedisResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/RedisResourceForm.tsxindex 4146eb8578..7ccdfef1ae 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/RedisResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/RedisResourceForm.tsx@@ -50,11 +50,13 @@ export const RedisResourceForm = ({ resource, onSubmit, closeSheet }: Props) =>defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.Redis,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 6379,diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsxindex f1da2e4d85..397639409a 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/SSHResourceForm.tsx@@ -43,11 +43,13 @@ export const SSHResourceForm = ({ resource, onSubmit, closeSheet }: Props) => {defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null}: {resourceType: PamResourceType.SSH,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {host: "",port: 22diff --git a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/WindowsResourceForm.tsx b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/WindowsResourceForm.tsxindex 44627b1209..38bf8994c4 100644--- a/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/WindowsResourceForm.tsx+++ b/frontend/src/pages/pam/PamResourcesPage/components/PamResourceForm/WindowsResourceForm.tsx@@ -63,7 +63,8 @@ export const WindowsResourceForm = ({ resource, onSubmit, closeSheet }: Props) =defaultValues: resource? {...resource,- gateway: resource.gatewayId ? { id: resource.gatewayId, name: "" } : undefined,+ gatewayId: resource.gatewayId ?? null,+ gatewayPoolId: resource.gatewayPoolId ?? null,domainId: resource.domainId ?? null,connectionDetails: {...(resource.connectionDetails as FormData["connectionDetails"]),@@ -77,7 +78,8 @@ export const WindowsResourceForm = ({ resource, onSubmit, closeSheet }: Props) =}: {resourceType: PamResourceType.Windows,- gateway: undefined,+ gatewayId: null,+ gatewayPoolId: null,connectionDetails: {protocol: WindowsProtocol.RDP,hostname: "",diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureSqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureSqlDatabaseInputForm.tsxindex edad7d9735..c79742898d 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureSqlDatabaseInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureSqlDatabaseInputForm.tsx@@ -2,7 +2,6 @@ import { Controller, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -18,17 +17,16 @@ import {FormControl,Input,SecretInput,- Select,- SelectItem,Switch,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";+import { useCreateDynamicSecret } from "@app/hooks/api";import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";import { ProjectEnv } from "@app/hooks/api/types";import { slugSchema } from "@app/lib/schemas";@@ -71,7 +69,8 @@ const formSchema = z.object({sslEnabled: z.boolean().optional(),ca: z.string().optional(),sslRejectUnauthorized: z.boolean().default(true),- gatewayId: z.string().optional()+ gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional()}),defaultTTL: z.string().superRefine((val, ctx) => {const valMs = ms(val);@@ -134,6 +133,7 @@ export const AzureSqlDatabaseInputForm = ({control,formState: { isSubmitting },handleSubmit,+ setValue,watch} = useForm<TForm>({resolver: zodResolver(formSchema),@@ -159,8 +159,9 @@ export const AzureSqlDatabaseInputForm = ({});const createDynamicSecret = useCreateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const sslEnabled = watch("provider.sslEnabled");+ const providerGatewayId = watch("provider.gatewayId");+ const providerGatewayPoolId = watch("provider.gatewayPoolId");const handleCreateDynamicSecret = async ({name,@@ -258,48 +259,30 @@ export const AzureSqlDatabaseInputForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="provider.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: providerGatewayId ?? null,+ gatewayPoolId: providerGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("provider.gatewayId", newGwId ?? undefined, {+ shouldDirty: true+ });+ setValue("provider.gatewayPoolId", newPoolId ?? undefined, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ClickHouseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ClickHouseInputForm.tsxindex 6b992f951e..3220eaf676 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ClickHouseInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ClickHouseInputForm.tsx@@ -1,6 +1,5 @@import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -16,16 +15,15 @@ import {FormControl,Input,SecretInput,- Select,- SelectItem,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";+import { useCreateDynamicSecret } from "@app/hooks/api";import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";import { ProjectEnv } from "@app/hooks/api/types";import { slugSchema } from "@app/lib/schemas";@@ -65,7 +63,8 @@ const formSchema = z.object({revocationStatement: z.string().min(1),renewStatement: z.string().optional(),ca: z.string().optional(),- gatewayId: z.string().optional()+ gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional()}),defaultTTL: z.string().superRefine((val, ctx) => {const valMs = ms(val);@@ -131,6 +130,7 @@ export const ClickHouseInputForm = ({control,formState: { isSubmitting },handleSubmit,+ setValue,watch} = useForm<TForm>({resolver: zodResolver(formSchema),@@ -153,7 +153,8 @@ export const ClickHouseInputForm = ({});const createDynamicSecret = useCreateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const providerGatewayId = watch("provider.gatewayId");+ const providerGatewayPoolId = watch("provider.gatewayPoolId");const handleCreateDynamicSecret = async ({name,@@ -248,48 +249,30 @@ export const ClickHouseInputForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="provider.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: providerGatewayId ?? null,+ gatewayPoolId: providerGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("provider.gatewayId", newGwId ?? undefined, {+ shouldDirty: true+ });+ setValue("provider.gatewayPoolId", newPoolId ?? undefined, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsxindex 0f335a06b8..11440d4a79 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx@@ -3,7 +3,6 @@ import { Controller, FieldValues, useFieldArray, useForm } from "react-hook-formimport { faQuestionCircle, faTrash } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -22,9 +21,10 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context/OrgPermissionContext";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";+import { useCreateDynamicSecret } from "@app/hooks/api";import {DynamicSecretProviders,KubernetesDynamicSecretCredentialType@@ -77,6 +77,7 @@ const formSchema = z"Namespace must be a single value, not a comma-separated list"),gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional(),audiences: z.array(z.string().trim().min(1)),authMethod: z.nativeEnum(AuthMethod).default(AuthMethod.Api)}),@@ -96,6 +97,7 @@ const formSchema = zreturn namespaces.length > 0 && namespaces.every((ns) => ns.length > 0);}, "Must be a valid comma-separated list of namespace values"),gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional(),audiences: z.array(z.string().trim().min(1)),roleType: z.nativeEnum(RoleType),role: z.string().trim().min(1),@@ -125,11 +127,15 @@ const formSchema = zusernameTemplate: z.string().trim().optional()}).superRefine((data, ctx) => {- if (data.provider.authMethod === AuthMethod.Gateway && !data.provider.gatewayId) {+ if (+ data.provider.authMethod === AuthMethod.Gateway &&+ !data.provider.gatewayId &&+ !data.provider.gatewayPoolId+ ) {ctx.addIssue({path: ["provider.gatewayId"],code: z.ZodIssueCode.custom,- message: "When auth method is set to Gateway, a gateway must be selected"+ message: "When auth method is set to Gateway, a gateway or gateway pool must be selected"});}if (data.provider.authMethod === AuthMethod.Api) {@@ -203,7 +209,8 @@ export const KubernetesInputForm = ({});const createDynamicSecret = useCreateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const providerGatewayId = watch("provider.gatewayId");+ const providerGatewayPoolId = watch("provider.gatewayPoolId");const sslEnabled = watch("provider.sslEnabled");const credentialType = watch("provider.credentialType");@@ -370,48 +377,30 @@ export const KubernetesInputForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="provider.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: providerGatewayId ?? null,+ gatewayPoolId: providerGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("provider.gatewayId", newGwId ?? undefined, {+ shouldDirty: true+ });+ setValue("provider.gatewayPoolId", newPoolId ?? undefined, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsxindex 1696049853..e407c4d79c 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx@@ -3,7 +3,6 @@ import { Controller, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -26,11 +25,12 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";+import { useCreateDynamicSecret } from "@app/hooks/api";import { DynamicSecretProviders, SqlProviders } from "@app/hooks/api/dynamicSecret/types";import { VaultDatabaseRole } from "@app/hooks/api/migration/types";import { ProjectEnv } from "@app/hooks/api/types";@@ -76,7 +76,8 @@ const formSchema = z.object({sslEnabled: z.boolean().optional(),ca: z.string().optional(),sslRejectUnauthorized: z.boolean().default(true),- gatewayId: z.string().optional()+ gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional()}),defaultTTL: z.string().superRefine((val, ctx) => {const valMs = ms(val);@@ -209,8 +210,9 @@ export const SqlDatabaseInputForm = ({});const createDynamicSecret = useCreateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const selectedClient = watch("provider.client");+ const providerGatewayId = watch("provider.gatewayId");+ const providerGatewayPoolId = watch("provider.gatewayPoolId");const handleCreateDynamicSecret = async ({name,@@ -449,48 +451,30 @@ export const SqlDatabaseInputForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="provider.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: providerGatewayId ?? null,+ gatewayPoolId: providerGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("provider.gatewayId", newGwId ?? undefined, {+ shouldDirty: true+ });+ setValue("provider.gatewayPoolId", newPoolId ?? undefined, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsxindex 7bd66a4668..441a28d7fa 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx@@ -1,6 +1,5 @@import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -15,16 +14,15 @@ import {FilterableSelect,FormControl,Input,- Select,- SelectItem,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import {OrgGatewayPermissionActions,OrgPermissionSubjects} from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";+import { useCreateDynamicSecret } from "@app/hooks/api";import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";import { ProjectEnv } from "@app/hooks/api/types";@@ -59,7 +57,8 @@ const formSchema = z.object({passwordRequirements: passwordRequirementsSchema.optional(),creationStatement: z.string().min(1),revocationStatement: z.string().min(1),- gatewayId: z.string().optional()+ gatewayId: z.string().optional(),+ gatewayPoolId: z.string().optional()}),defaultTTL: z.string().superRefine((val, ctx) => {const valMs = ms(val);@@ -105,6 +104,7 @@ export const VerticaInputForm = ({const {control,watch,+ setValue,formState: { isSubmitting },handleSubmit} = useForm<TForm>({@@ -133,7 +133,8 @@ GRANT CREATE ON SCHEMA public TO {{username}};`,});const createDynamicSecret = useCreateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());+ const providerGatewayId = watch("provider.gatewayId");+ const providerGatewayPoolId = watch("provider.gatewayPoolId");const handleCreateDynamicSecret = async ({name,@@ -223,48 +224,30 @@ GRANT CREATE ON SCHEMA public TO {{username}};`,a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="provider.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: providerGatewayId ?? null,+ gatewayPoolId: providerGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("provider.gatewayId", newGwId ?? undefined, {+ shouldDirty: true+ });+ setValue("provider.gatewayPoolId", newPoolId ?? undefined, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAzureSqlDatabaseForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAzureSqlDatabaseForm.tsxindex d1a896a74f..4505ca8a4b 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAzureSqlDatabaseForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAzureSqlDatabaseForm.tsx@@ -2,7 +2,6 @@ import { Controller, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -18,15 +17,14 @@ import {FormControl,Input,SecretInput,- Select,- SelectItem,Switch,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api";+import { useUpdateDynamicSecret } from "@app/hooks/api";import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";import { slugSchema } from "@app/lib/schemas";@@ -69,7 +67,8 @@ const formSchema = z.object({ca: z.string().optional(),sslEnabled: z.boolean().optional(),sslRejectUnauthorized: z.boolean().optional(),- gatewayId: z.string().optional()+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable()}).partial(),defaultTTL: z.string().superRefine((val, ctx) => {@@ -133,6 +132,7 @@ export const EditDynamicSecretAzureSqlDatabaseForm = ({control,formState: { isSubmitting },handleSubmit,+ setValue,watch} = useForm<TForm>({resolver: zodResolver(formSchema),@@ -152,8 +152,9 @@ export const EditDynamicSecretAzureSqlDatabaseForm = ({});const updateDynamicSecret = useUpdateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const sslEnabled = watch("inputs.sslEnabled");+ const inputsGatewayId = watch("inputs.gatewayId");+ const inputsGatewayPoolId = watch("inputs.gatewayPoolId");const handleUpdateDynamicSecret = async ({inputs,@@ -250,47 +251,30 @@ export const EditDynamicSecretAzureSqlDatabaseForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="inputs.gatewayId"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: inputsGatewayId ?? null,+ gatewayPoolId: inputsGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("inputs.gatewayId", newGwId ?? null, {+ shouldDirty: true+ });+ setValue("inputs.gatewayPoolId", newPoolId ?? null, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretClickHouseForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretClickHouseForm.tsxindex bb1f3b8fbe..0eec6e8afa 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretClickHouseForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretClickHouseForm.tsx@@ -1,6 +1,5 @@import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -16,14 +15,13 @@ import {FormControl,Input,SecretInput,- Select,- SelectItem,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api";+import { useUpdateDynamicSecret } from "@app/hooks/api";import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";import { slugSchema } from "@app/lib/schemas";@@ -63,7 +61,8 @@ const formSchema = z.object({revocationStatement: z.string().min(1),renewStatement: z.string().optional(),ca: z.string().optional(),- gatewayId: z.string().optional().nullable()+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable()}).partial(),defaultTTL: z.string().superRefine((val, ctx) => {@@ -127,6 +126,7 @@ export const EditDynamicSecretClickHouseForm = ({const {control,watch,+ setValue,formState: { isSubmitting },handleSubmit} = useForm<TForm>({@@ -146,10 +146,9 @@ export const EditDynamicSecretClickHouseForm = ({}});- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const updateDynamicSecret = useUpdateDynamicSecret();const selectedGatewayId = watch("inputs.gatewayId");- const isGatewayInActive = gateways?.findIndex((el) => el.id === selectedGatewayId) === -1;+ const selectedGatewayPoolId = watch("inputs.gatewayPoolId");const handleUpdateDynamicSecret = async ({inputs,@@ -171,7 +170,8 @@ export const EditDynamicSecretClickHouseForm = ({defaultTTL,inputs: {...inputs,- gatewayId: isGatewayInActive ? null : inputs.gatewayId+ gatewayId: inputs.gatewayId ?? null,+ gatewayPoolId: inputs.gatewayPoolId ?? null},newName: newName === dynamicSecret.name ? undefined : newName,metadata,@@ -244,53 +244,28 @@ export const EditDynamicSecretClickHouseForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="inputs.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message) || isGatewayInActive}- errorText={- isGatewayInActive && selectedGatewayId- ? `Project Gateway ${selectedGatewayId} is removed`- : error?.message- }- label="Gateway"- helperText=""- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value || undefined}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: selectedGatewayId ?? null,+ gatewayPoolId: selectedGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("inputs.gatewayId", newGwId ?? null, { shouldDirty: true });+ setValue("inputs.gatewayPoolId", newPoolId ?? null, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretKubernetesForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretKubernetesForm.tsxindex ec44e12734..1139122542 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretKubernetesForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretKubernetesForm.tsx@@ -2,7 +2,6 @@ import { Controller, FieldValues, useFieldArray, useForm } from "react-hook-formimport { faQuestionCircle, faTrash } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -20,9 +19,10 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context/OrgPermissionContext";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api";+import { useUpdateDynamicSecret } from "@app/hooks/api";import {KubernetesDynamicSecretCredentialType,TDynamicSecret@@ -69,7 +69,8 @@ const formSchema = z(val) => !val.includes(","),"Namespace must be a single value, not a comma-separated list"),- gatewayId: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),audiences: z.array(z.string().trim().min(1)),authMethod: z.nativeEnum(AuthMethod).default(AuthMethod.Api)}),@@ -88,7 +89,8 @@ const formSchema = zconst namespaces = val.split(",").map((ns) => ns.trim());return namespaces.length > 0 && namespaces.every((ns) => ns.length > 0);}, "Must be a valid comma-separated list of namespace values"),- gatewayId: z.string().optional(),+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable(),audiences: z.array(z.string().trim().min(1)),roleType: z.nativeEnum(RoleType),role: z.string().trim().min(1),@@ -117,11 +119,15 @@ const formSchema = zusernameTemplate: z.string().trim().optional()}).superRefine((data, ctx) => {- if (data.inputs.authMethod === AuthMethod.Gateway && !data.inputs.gatewayId) {+ if (+ data.inputs.authMethod === AuthMethod.Gateway &&+ !data.inputs.gatewayId &&+ !data.inputs.gatewayPoolId+ ) {ctx.addIssue({path: ["inputs.gatewayId"],code: z.ZodIssueCode.custom,- message: "When auth method is set to Gateway, a gateway must be selected"+ message: "When auth method is set to Gateway, a gateway or gateway pool must be selected"});}if (data.inputs.authMethod === AuthMethod.Api) {@@ -163,6 +169,7 @@ export const EditDynamicSecretKubernetesForm = ({control,formState: { isSubmitting },handleSubmit,+ setValue,watch} = useForm<TForm>({resolver: zodResolver(formSchema),@@ -181,11 +188,12 @@ export const EditDynamicSecretKubernetesForm = ({});const updateDynamicSecret = useUpdateDynamicSecret();- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const sslEnabled = watch("inputs.sslEnabled");const credentialType = watch("inputs.credentialType");const authMethod = watch("inputs.authMethod");+ const inputsGatewayId = watch("inputs.gatewayId");+ const inputsGatewayPoolId = watch("inputs.gatewayPoolId");const handleUpdateDynamicSecret = async (formData: TForm) => {// wait till previous request is finished@@ -283,48 +291,30 @@ export const EditDynamicSecretKubernetesForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="inputs.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message)}- errorText={error?.message}- label="Gateway"- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: inputsGatewayId ?? null,+ gatewayPoolId: inputsGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("inputs.gatewayId", newGwId ?? null, {+ shouldDirty: true+ });+ setValue("inputs.gatewayPoolId", newPoolId ?? null, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsxindex 0219ac9ee4..28ce7a9f0a 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx@@ -2,7 +2,6 @@ import { Controller, useForm } from "react-hook-form";import { faQuestionCircle } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -24,9 +23,10 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api";+import { useUpdateDynamicSecret } from "@app/hooks/api";import { SqlProviders, TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";import { slugSchema } from "@app/lib/schemas";@@ -69,7 +69,8 @@ const formSchema = z.object({sslEnabled: z.boolean().optional(),ca: z.string().optional(),sslRejectUnauthorized: z.boolean().optional(),- gatewayId: z.string().optional().nullable()+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable()}).partial(),defaultTTL: z.string().superRefine((val, ctx) => {@@ -132,6 +133,7 @@ export const EditDynamicSecretSqlProviderForm = ({const {control,watch,+ setValue,formState: { isSubmitting },handleSubmit} = useForm<TForm>({@@ -153,12 +155,11 @@ export const EditDynamicSecretSqlProviderForm = ({}});- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const selectedClient = watch("inputs.client");const updateDynamicSecret = useUpdateDynamicSecret();const selectedGatewayId = watch("inputs.gatewayId");- const isGatewayInActive = gateways?.findIndex((el) => el.id === selectedGatewayId) === -1;+ const selectedGatewayPoolId = watch("inputs.gatewayPoolId");const handleUpdateDynamicSecret = async ({inputs,@@ -181,7 +182,8 @@ export const EditDynamicSecretSqlProviderForm = ({defaultTTL,inputs: {...inputs,- gatewayId: isGatewayInActive ? null : inputs.gatewayId+ gatewayId: inputs.gatewayId ?? null,+ gatewayPoolId: inputs.gatewayPoolId ?? null},newName: newName === dynamicSecret.name ? undefined : newName,metadata,@@ -254,53 +256,28 @@ export const EditDynamicSecretSqlProviderForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="inputs.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message) || isGatewayInActive}- errorText={- isGatewayInActive && selectedGatewayId- ? `Project Gateway ${selectedGatewayId} is removed`- : error?.message- }- label="Gateway"- helperText=""- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value || undefined}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: selectedGatewayId ?? null,+ gatewayPoolId: selectedGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("inputs.gatewayId", newGwId ?? null, { shouldDirty: true });+ setValue("inputs.gatewayPoolId", newPoolId ?? null, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretVertica.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretVertica.tsxindex 0579ba3b9d..702d2906b9 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretVertica.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretVertica.tsx@@ -1,6 +1,5 @@import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";-import { useQuery } from "@tanstack/react-query";import ms from "ms";import { z } from "zod";@@ -15,14 +14,13 @@ import {Button,FormControl,Input,- Select,- SelectItem,TextArea,Tooltip} from "@app/components/v2";+import { GatewayPicker } from "@app/components/v3/platform/GatewayPicker";import { OrgPermissionSubjects } from "@app/context";import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types";-import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api";+import { useUpdateDynamicSecret } from "@app/hooks/api";import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";const passwordRequirementsSchema = z@@ -57,7 +55,8 @@ const formSchema = z.object({passwordRequirements: passwordRequirementsSchema.optional(),creationStatement: z.string().min(1),revocationStatement: z.string().min(1),- gatewayId: z.string().optional().nullable()+ gatewayId: z.string().optional().nullable(),+ gatewayPoolId: z.string().optional().nullable()}).partial(),defaultTTL: z.string().superRefine((val, ctx) => {@@ -112,6 +111,7 @@ export const EditDynamicSecretVerticaForm = ({const {control,watch,+ setValue,formState: { isSubmitting },handleSubmit} = useForm<TForm>({@@ -130,11 +130,10 @@ export const EditDynamicSecretVerticaForm = ({}});- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());const updateDynamicSecret = useUpdateDynamicSecret();const selectedGatewayId = watch("inputs.gatewayId");- const isGatewayInActive = gateways?.findIndex((el) => el.id === selectedGatewayId) === -1;+ const selectedGatewayPoolId = watch("inputs.gatewayPoolId");const handleUpdateDynamicSecret = async ({inputs,@@ -157,7 +156,8 @@ export const EditDynamicSecretVerticaForm = ({defaultTTL,inputs: {...inputs,- gatewayId: isGatewayInActive ? null : inputs.gatewayId+ gatewayId: inputs.gatewayId ?? null,+ gatewayPoolId: inputs.gatewayPoolId ?? null},newName: newName === dynamicSecret.name ? undefined : newName,usernameTemplate: !usernameTemplate || isDefaultUsernameTemplate ? null : usernameTemplate@@ -234,53 +234,28 @@ export const EditDynamicSecretVerticaForm = ({a={OrgPermissionSubjects.Gateway}>{(isAllowed) => (- <Controller- control={control}- name="inputs.gatewayId"- defaultValue=""- render={({ field: { value, onChange }, fieldState: { error } }) => (- <FormControl- isError={Boolean(error?.message) || isGatewayInActive}- errorText={- isGatewayInActive && selectedGatewayId- ? `Project Gateway ${selectedGatewayId} is removed`- : error?.message- }- label="Gateway"- helperText=""- >- <Tooltip- isDisabled={isAllowed}- content="Restricted access. You don't have permission to attach gateways to resources."- >- <div>- <Select- isDisabled={!isAllowed}- value={value || undefined}- onValueChange={onChange}- className="w-full border border-mineshaft-500"- dropdownContainerClassName="max-w-none"- isLoading={isGatewaysLoading}- placeholder="Default: Internet Gateway"- position="popper"- >- <SelectItem- value={null as unknown as string}- onClick={() => onChange(undefined)}- >- Internet Gateway- </SelectItem>- {gateways?.map((el) => (- <SelectItem value={el.id} key={el.id}>- {el.name}- </SelectItem>- ))}- </Select>- </div>- </Tooltip>- </FormControl>- )}- />+ <FormControl label="Gateway">+ <Tooltip+ isDisabled={isAllowed}+ content="Restricted access. You don't have permission to attach gateways to resources."+ >+ <div>+ <GatewayPicker+ isDisabled={!isAllowed}+ value={{+ gatewayId: selectedGatewayId ?? null,+ gatewayPoolId: selectedGatewayPoolId ?? null+ }}+ onChange={({ gatewayId: newGwId, gatewayPoolId: newPoolId }) => {+ setValue("inputs.gatewayId", newGwId ?? null, { shouldDirty: true });+ setValue("inputs.gatewayPoolId", newPoolId ?? null, {+ shouldDirty: true+ });+ }}+ />+ </div>+ </Tooltip>+ </FormControl>)}</OrgPermissionCan></div>