Skip to content

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

chore: deprecate gateway v1

Sheen Capadngan14221baac4ee
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index cdf3592400..65b9d80c02 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -739,6 +739,22 @@ EE routes register before community routes so they can override/extend endpoints
**Agent Vault**: the same applies to the `agent-vault-*` services and routers; the concept map is [`src/ee/services/agent-vault/CLAUDE.md`](src/ee/services/agent-vault/CLAUDE.md). PAM and Agent Vault are the two **org-scoped products**: one implicit project per org, resolved lazily, whose roles collapse to admin or member. Anything that branches on `ProjectType.PAM` (metering emits, predefined roles, the billable-project count, invite grants) almost always needs an Agent Vault arm too.
+**Gateways: there is only one generation.** Gateway v1 (`ee/services/gateway`, `lib/gateway`, the QUIC
+transport over `@infisical/quic`, and `/api/v1/gateways`) is gone; `gateway-v2` and `gateway-pool` are the
+whole story, and `lib/gateway-v2/types.ts` owns `GatewayProxyProtocol` / `GatewayHttpProxyActions`. What
+survives is DB-only, and deliberately: the `gateways`, `org_gateway_config` and `project_gateways` tables
+and the `gatewayId` columns on `dynamic_secrets`, `identity_kubernetes_auths` and
+`identity_auth_templates` are still populated but never read or written, so the removal stays revertible.
+Those three tables' `TableName` members exist for that reason alone.
+
+Two consequences when touching a gateway dial path. Resolve the gateway with
+`gatewayV2Service.getPlatformConnectionDetailsByGatewayId`, and when it returns nothing **throw**
+(`getMissingGatewayMessage` in `lib/gateway-v2/gateway-errors.ts`) rather than continuing: every one of
+these call sites sits in front of an `if (gatewayId)` guard whose else-branch dials the target host
+directly, so falling through turns a dangling gateway reference into a silent bypass of the network
+boundary the gateway exists to enforce. And `app_connections.gatewayId` is **not** a v1 column — unlike the
+three above it never grew a `gatewayV2Id`, so that one column carries v2 ids and must stay.
+
### Server Plugins
Key plugins in `src/server/plugins/`:
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 22c1d13f59..999ff94bbe 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -47,7 +47,6 @@
"@google-cloud/kms": "^5.4.0",
"@infisical/ldapjs": "3.0.11",
"@infisical/pg-view-generator": "^1.1.0",
- "@infisical/quic": "^1.0.8",
"@node-saml/passport-saml": "^5.1.0",
"@octokit/auth-app": "^7.1.1",
"@octokit/core": "^5.2.1",
@@ -6598,112 +6597,6 @@
"node": ">=18.0.0"
}
},
- "node_modules/@infisical/quic": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic/-/quic-1.0.8.tgz",
- "integrity": "sha512-ozgGkVdLP+ST41rPYmtaUBnBzisEzoI1l9yIds2l3hbd6OX6I836G0djTWLZbisn2ZO8CEbr8buLUclxqiY/IA==",
- "license": "Apache-2.0",
- "dependencies": {
- "@matrixai/async-cancellable": "^1.1.1",
- "@matrixai/async-init": "^1.10.0",
- "@matrixai/async-locks": "^4.0.0",
- "@matrixai/contexts": "^1.2.0",
- "@matrixai/errors": "^1.2.0",
- "@matrixai/events": "^3.2.3",
- "@matrixai/logger": "^3.1.2",
- "@matrixai/resources": "^1.1.5",
- "@matrixai/timer": "^1.1.3",
- "ip-num": "^1.5.0"
- },
- "optionalDependencies": {
- "@infisical/quic-darwin-arm64": "1.0.8",
- "@infisical/quic-darwin-universal": "1.0.8",
- "@infisical/quic-darwin-x64": "1.0.8",
- "@infisical/quic-linux-arm": "1.0.8",
- "@infisical/quic-linux-arm64": "1.0.8",
- "@infisical/quic-linux-x64": "1.0.8",
- "@infisical/quic-win32-x64": "1.0.8"
- }
- },
- "node_modules/@infisical/quic-darwin-arm64": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-darwin-arm64/-/quic-darwin-arm64-1.0.8.tgz",
- "integrity": "sha512-gJ1g2magCRQ+v02q6Jx50t85xIWnXgihYz/vak0YDYUIIOZFrcc7BaxNdfAo6lcxxDuGnK9RDTcLOpfMWt9EtQ==",
- "cpu": [
- "arm64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@infisical/quic-darwin-universal": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-darwin-universal/-/quic-darwin-universal-1.0.8.tgz",
- "integrity": "sha512-BsOVIKexP+FysAyddnHHNKADUKz12ZzX7Eyl3fx4ZBGYdjzk3QTkG989HhSvYYQ+p3GyxB7p+Qn1cX3W5q3SHw==",
- "cpu": [
- "x64",
- "arm64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@infisical/quic-darwin-x64": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-darwin-x64/-/quic-darwin-x64-1.0.8.tgz",
- "integrity": "sha512-xvWuAB8plgGFxK9trO1MYq5xhRFgKRySpWxOuPDkNrGQZJNBZTiQfCM91dWfpMip1GhmhO7K0fcp5GYTphMXCA==",
- "cpu": [
- "x64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@infisical/quic-linux-arm64": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-linux-arm64/-/quic-linux-arm64-1.0.8.tgz",
- "integrity": "sha512-vOEr/gIskr+eXN0rofpX1+hCJeKjUnHpt97LVsob9Jh7cXVGa9ywM0NbbYurz7FOdWH8+fBtppxkto4UdLSrZg==",
- "cpu": [
- "arm64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@infisical/quic-linux-x64": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-linux-x64/-/quic-linux-x64-1.0.8.tgz",
- "integrity": "sha512-YE4xk5xv2oAiqZwVqNhC9AUnuFj1Q0cUiZmxih0RqfO51sr1BCgqmSBRWRykrdL8oyPmQduSNWKN7FcckPhYVQ==",
- "cpu": [
- "x64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@infisical/quic-win32-x64": {
- "version": "1.0.8",
- "resolved": "https://registry.npmjs.org/@infisical/quic-win32-x64/-/quic-win32-x64-1.0.8.tgz",
- "integrity": "sha512-Ihh+NxKI6ujJTvOoRwQ8PUmoxU05iiAzkq0r0tP2xtTdXfg57R7sOGUyJCjg1AwpS40T+xgGTIjIGGQS50qYvg==",
- "cpu": [
- "x64"
- ],
- "license": "Apache-2.0",
- "optional": true,
- "os": [
- "win32"
- ]
- },
"node_modules/@inquirer/external-editor": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-1.0.3.tgz",
@@ -7019,85 +6912,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
- "node_modules/@matrixai/async-cancellable": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/@matrixai/async-cancellable/-/async-cancellable-1.1.1.tgz",
- "integrity": "sha512-f0yxu7dHwvffZ++7aCm2WIcCJn18uLcOTdCCwEA3R3KVHYE3TG/JNoTWD9/mqBkAV1AI5vBfJzg27WnF9rOUXQ==",
- "license": "Apache-2.0"
- },
- "node_modules/@matrixai/async-init": {
- "version": "1.10.0",
- "resolved": "https://registry.npmjs.org/@matrixai/async-init/-/async-init-1.10.0.tgz",
- "integrity": "sha512-JjUFu6rqd+dtTHFJ6z8bjbceuFGBj/APWfJByVsfbEH1DJsOgWERFcW3DBUrS0mgTph4Vl518tsNcsSwKT5Y+g==",
- "license": "Apache-2.0",
- "dependencies": {
- "@matrixai/async-locks": "^4.0.0",
- "@matrixai/errors": "^1.2.0",
- "@matrixai/events": "^3.2.0"
- }
- },
- "node_modules/@matrixai/async-locks": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/@matrixai/async-locks/-/async-locks-4.0.0.tgz",
- "integrity": "sha512-u/3fOdtjOKcDYF8dDoPR1/+7nmOkhxo42eBpXTEgfI0hLPGI37PoW7tjLvwy+O51Quy1HGOwhsR/Dgr4x+euug==",
- "license": "Apache-2.0",
- "dependencies": {
- "@matrixai/async-cancellable": "^1.1.1",
- "@matrixai/errors": "^1.1.7",
- "@matrixai/resources": "^1.1.5",
- "@matrixai/timer": "^1.1.1"
- }
- },
- "node_modules/@matrixai/contexts": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/@matrixai/contexts/-/contexts-1.2.0.tgz",
- "integrity": "sha512-MR/B02Kf4UoliP9b/gMMKsvWV6QM4JSPKTIqrhQP2tbOl3FwLI+AIhL3vgYEj1Xw+PP8bY5cr8ontJ8x6AJyMg==",
- "license": "Apache-2.0",
- "dependencies": {
- "@matrixai/async-cancellable": "^1.1.1",
- "@matrixai/async-locks": "^4.0.0",
- "@matrixai/errors": "^1.1.7",
- "@matrixai/resources": "^1.1.5",
- "@matrixai/timer": "^1.1.1"
- }
- },
- "node_modules/@matrixai/errors": {
- "version": "1.2.0",
- "resolved": "https://registry.npmjs.org/@matrixai/errors/-/errors-1.2.0.tgz",
- "integrity": "sha512-eZHPHFla5GFmi0O0yGgbtkca+ZjwpDbMz+60NC3y+DzQq6BMoe4gHmPjDalAHTxyxv0+Q+AWJTuV8Ows+IqBfQ==",
- "license": "Apache-2.0",
- "dependencies": {
- "ts-custom-error": "3.2.2"
- }
- },
- "node_modules/@matrixai/events": {
- "version": "3.2.3",
- "resolved": "https://registry.npmjs.org/@matrixai/events/-/events-3.2.3.tgz",
- "integrity": "sha512-bZrNCwzYeFalGQpn8qa/jgD10mUAwLRbv6xGMI7gGz1f+vE65d3GPoJ6JoFOJSg9iCmRSayQJ+IipH3LMATvDA==",
- "license": "Apache-2.0"
- },
- "node_modules/@matrixai/logger": {
- "version": "3.1.3",
- "resolved": "https://registry.npmjs.org/@matrixai/logger/-/logger-3.1.3.tgz",
- "integrity": "sha512-wIHyiAzkrlZ/qlss4HLtXFzdlk1hxmAb0FNCQMd7ZwiHJABiKbvQtFSpBUvUakZYwYomiFmHwTYkHloiIVjrsg==",
- "license": "Apache-2.0"
- },
- "node_modules/@matrixai/resources": {
- "version": "1.1.5",
- "resolved": "https://registry.npmjs.org/@matrixai/resources/-/resources-1.1.5.tgz",
- "integrity": "sha512-m/DEZEe3wHqWEPTyoBtzFF6U9vWYhEnQtGgwvqiAlTxTM0rk96UBpWjDZCTF/vYG11ZlmlQFtg5H+zGgbjaB3Q==",
- "license": "Apache-2.0"
- },
- "node_modules/@matrixai/timer": {
- "version": "1.1.3",
- "resolved": "https://registry.npmjs.org/@matrixai/timer/-/timer-1.1.3.tgz",
- "integrity": "sha512-BG5bAZMIt7qxc9iqAOCk2zm7V0+yNQLwp+WhsWVkP25Nvd1klqKpScE1lGwoLA27ygxEi+8IRU3wa8PLrhs0DQ==",
- "license": "Apache-2.0",
- "dependencies": {
- "@matrixai/async-cancellable": "^1.1.1",
- "@matrixai/errors": "^1.1.7"
- }
- },
"node_modules/@mongodb-js/saslprep": {
"version": "1.1.9",
"resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.9.tgz",
@@ -18883,12 +18697,6 @@
"node": ">= 12"
}
},
- "node_modules/ip-num": {
- "version": "1.5.1",
- "resolved": "https://registry.npmjs.org/ip-num/-/ip-num-1.5.1.tgz",
- "integrity": "sha512-QziFxgxq3mjIf5CuwlzXFYscHxgLqdEdJKRo2UJ5GurL5zrSRMzT/O+nK0ABimoFH8MWF8YwIiwECYsHc1LpUQ==",
- "license": "MIT"
- },
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@@ -26622,15 +26430,6 @@
"typescript": ">=4.2.0"
}
},
- "node_modules/ts-custom-error": {
- "version": "3.2.2",
- "resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.2.2.tgz",
- "integrity": "sha512-u0YCNf2lf6T/vHm+POKZK1yFKWpSpJitcUN3HxqyEcFuNnHIDbyuIQC7QDy/PsBX3giFyk9rt6BFqBAh2lsDZQ==",
- "license": "MIT",
- "engines": {
- "node": ">=14.0.0"
- }
- },
"node_modules/ts-interface-checker": {
"version": "0.1.13",
"resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz",
diff --git a/backend/package.json b/backend/package.json
index 1e426c37c3..5664cd9562 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -201,7 +201,6 @@
"@google-cloud/kms": "^5.4.0",
"@infisical/ldapjs": "3.0.11",
"@infisical/pg-view-generator": "^1.1.0",
- "@infisical/quic": "^1.0.8",
"@node-saml/passport-saml": "^5.1.0",
"@octokit/auth-app": "^7.1.1",
"@octokit/core": "^5.2.1",
diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 288ff7f853..c5ffb1aec0 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -22,7 +22,6 @@ import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secr
import { TEmailDomainServiceFactory } from "@app/ee/services/email-domain/email-domain-service";
import { TEventBusService as TInternalEventBusService } from "@app/ee/services/event-bus";
import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
-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 { TGithubOrgSyncServiceFactory } from "@app/ee/services/github-org-sync/github-org-sync-service";
@@ -419,7 +418,6 @@ declare module "fastify" {
kmip: TKmipServiceFactory;
kmipOperation: TKmipOperationServiceFactory;
kmipServer: TKmipServerServiceFactory;
- gateway: TGatewayServiceFactory;
secretRotationV2: TSecretRotationV2ServiceFactory;
microsoftTeams: TMicrosoftTeamsServiceFactory;
assumePrivileges: TAssumePrivilegeServiceFactory;
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 14a451ec95..c3883e5a85 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -167,7 +167,9 @@ export enum TableName {
ProjectSplitBackfillIds = "project_split_backfill_ids",
UserNotifications = "user_notifications",
ScimEvents = "scim_events",
- // Gateway
+ // Gateway v1. Retired: nothing reads or writes these tables, or the gatewayId columns on
+ // dynamic_secrets / identity_kubernetes_auths / identity_auth_templates that point at them.
+ // They are kept populated so the removal can be reverted without data loss.
OrgGatewayConfig = "org_gateway_config",
Gateway = "gateways",
ProjectGateway = "project_gateways",
diff --git a/backend/src/ee/routes/v1/dynamic-secret-router.ts b/backend/src/ee/routes/v1/dynamic-secret-router.ts
index 117d9cbb95..2f619c3dbb 100644
--- a/backend/src/ee/routes/v1/dynamic-secret-router.ts
+++ b/backend/src/ee/routes/v1/dynamic-secret-router.ts
@@ -118,7 +118,7 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) =>
secretPath: dynamicSecretCfg.secretPath,
defaultTTL: `${ms(dynamicSecretCfg.defaultTTL) / 1000}s`,
maxTTL: dynamicSecretCfg.maxTTL ? `${ms(dynamicSecretCfg.maxTTL) / 1000}s` : null,
- hasGateway: Boolean(dynamicSecretCfg.gatewayId || dynamicSecretCfg.gatewayV2Id)
+ hasGateway: Boolean(dynamicSecretCfg.gatewayV2Id)
}
})
.catch(() => {});
diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts
deleted file mode 100644
index ebd130ea78..0000000000
--- a/backend/src/ee/routes/v1/gateway-router.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { z } from "zod";
-
-import { GatewaysSchema } from "@app/db/schemas";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { slugSchema } from "@app/server/lib/schemas";
-import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-
-const SanitizedGatewaySchema = GatewaysSchema.pick({
- id: true,
- identityId: true,
- name: true,
- createdAt: true,
- updatedAt: true,
- issuedAt: true,
- serialNumber: true,
- heartbeat: true
-});
-
-export const registerGatewayRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "POST",
- url: "/heartbeat",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- response: {
- 200: z.object({
- message: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- await server.services.gateway.heartbeat({
- orgPermission: req.permission
- });
- return { message: "Successfully registered heartbeat" };
- }
- });
-
- server.route({
- method: "GET",
- url: "/",
- config: {
- rateLimit: readLimit
- },
- schema: {
- querystring: z.object({
- projectId: z.string().optional()
- }),
- response: {
- 200: z.object({
- gateways: SanitizedGatewaySchema.extend({
- identity: z.object({
- name: z.string(),
- id: z.string()
- })
- }).array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT, AuthMode.OAUTH]),
- handler: async (req) => {
- const gateways = await server.services.gateway.listGateways({
- orgPermission: req.permission
- });
- return { gateways };
- }
- });
-
- server.route({
- method: "GET",
- url: "/projects/:projectId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- projectId: z.string()
- }),
- response: {
- 200: z.object({
- gateways: SanitizedGatewaySchema.extend({
- identity: z.object({
- name: z.string(),
- id: z.string()
- })
- }).array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT, AuthMode.OAUTH]),
- handler: async (req) => {
- const gateways = await server.services.gateway.listGateways({
- orgPermission: req.permission
- });
- return { gateways };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:id",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- id: z.string()
- }),
- response: {
- 200: z.object({
- gateway: SanitizedGatewaySchema.extend({
- identity: z.object({
- name: z.string(),
- id: z.string()
- })
- })
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT, AuthMode.OAUTH]),
- handler: async (req) => {
- const gateway = await server.services.gateway.getGatewayById({
- orgPermission: req.permission,
- id: req.params.id
- });
- return { gateway };
- }
- });
-
- server.route({
- method: "PATCH",
- url: "/:id",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- id: z.string()
- }),
- body: z.object({
- name: slugSchema({ field: "name" }).optional()
- }),
- response: {
- 200: z.object({
- gateway: SanitizedGatewaySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT]),
- handler: async (req) => {
- const gateway = await server.services.gateway.updateGatewayById({
- orgPermission: req.permission,
- id: req.params.id,
- name: req.body.name
- });
-
- void server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.GatewayUpdated,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- gatewayId: gateway.id
- }
- })
- .catch(() => {});
-
- return { gateway };
- }
- });
-
- server.route({
- method: "DELETE",
- url: "/:id",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- id: z.string()
- }),
- response: {
- 200: z.object({
- gateway: SanitizedGatewaySchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT]),
- handler: async (req) => {
- const gateway = await server.services.gateway.deleteGatewayById({
- orgPermission: req.permission,
- id: req.params.id
- });
-
- void server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.GatewayDeleted,
- distinctId: getTelemetryDistinctId(req),
- organizationId: req.permission.orgId,
- properties: {
- gatewayId: gateway.id
- }
- })
- .catch(() => {});
-
- return { gateway };
- }
- });
-};
diff --git a/backend/src/ee/routes/v1/identity-template-router.ts b/backend/src/ee/routes/v1/identity-template-router.ts
index 606de581ff..8b19ba1545 100644
--- a/backend/src/ee/routes/v1/identity-template-router.ts
+++ b/backend/src/ee/routes/v1/identity-template-router.ts
@@ -31,7 +31,8 @@ const templateNameSchema = z
// exact shape here documents each method's fields and makes the response serializer a
// second barrier that drops anything undeclared
// the gateway reference is stored in columns so it can carry a foreign key, but it stays
-// inside templateFields in the API, so the v1/v2 column split is not part of the contract
+// inside templateFields in the API, so the column names are not part of the contract.
+// gatewayId is the retired v1 column, kept on the table but never read or written any more
const templateRowSchema = IdentityAuthTemplatesSchema.omit({
gatewayId: true,
gatewayV2Id: true,
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 7c816365ca..0776e0d729 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -19,7 +19,6 @@ import { registerEmailDomainRouter } from "./email-domain-router";
import { registerExternalKmsRouter } from "./external-kms-router";
import { EXTERNAL_KMS_REGISTER_ROUTER_MAP } from "./external-kms-routers";
import { registerGatewayPoolRouter } from "./gateway-pool-router";
-import { registerGatewayRouter } from "./gateway-router";
import { registerGithubOrgSyncRouter } from "./github-org-sync-router";
import { registerGroupRouter } from "./group-router";
import { registerHoneyTokenRouter } from "./honey-token-router";
@@ -101,7 +100,6 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
{ prefix: "/dynamic-secrets" }
);
- await server.register(registerGatewayRouter, { prefix: "/gateways" });
await server.register(registerGatewayPoolRouter, { prefix: "/gateway-pools" });
await server.register(registerRelayRouter, { prefix: "/relays" });
await server.register(registerGithubOrgSyncRouter, { prefix: "/github-org-sync-config" });
diff --git a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
index f8417814f6..a26c15bfbe 100644
--- a/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
+++ b/backend/src/ee/services/app-connections/chef/chef-connection-fns.ts
@@ -2,14 +2,13 @@ import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import crypto from "crypto";
import https from "https";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
@@ -214,7 +213,6 @@ export const getChefConnectionListItem = () => {
export const validateChefConnectionCredentials = async (
config: TChefConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined
) => {
const { credentials: inputCredentials, gatewayId } = config;
diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
index f9c5195e69..a7a3aae20c 100644
--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
@@ -19,7 +19,6 @@ import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-fold
import { 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";
@@ -46,7 +45,6 @@ type TDynamicSecretServiceFactoryDep = {
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayDAL: Pick<TGatewayDALFactory, "findOne" | "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne" | "find">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveAttachableGatewayFromPool">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
@@ -90,7 +88,6 @@ export const dynamicSecretServiceFactory = ({
dynamicSecretQueueService,
projectDAL,
kmsService,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolService,
resourceMetadataDAL
@@ -110,7 +107,6 @@ export const dynamicSecretServiceFactory = ({
metadata,
usernameTemplate
}) => {
- let isGatewayV1 = true;
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
@@ -178,24 +174,19 @@ export const dynamicSecretServiceFactory = ({
} 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 });
const [gatewayv2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId });
- if (!gateway && !gatewayv2) {
+ if (!gatewayv2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found`
});
}
- if (!gateway) {
- isGatewayV1 = false;
- }
-
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
- orgId: gateway?.orgId || gatewayv2?.orgId,
+ orgId: gatewayv2.orgId,
actorAuthMethod,
actorOrgId
});
@@ -205,7 +196,7 @@ export const dynamicSecretServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- selectedGatewayId = gateway?.id ?? gatewayv2?.id;
+ selectedGatewayId = gatewayv2.id;
}
const isConnected = await selectedProvider.validateConnection(provider.inputs, { projectId });
@@ -226,8 +217,7 @@ export const dynamicSecretServiceFactory = ({
defaultTTL,
folderId: folder.id,
name,
- gatewayId: !selectedGatewayPoolId && isGatewayV1 ? selectedGatewayId : undefined,
- gatewayV2Id: !selectedGatewayPoolId && !isGatewayV1 ? selectedGatewayId : undefined,
+ gatewayV2Id: !selectedGatewayPoolId ? selectedGatewayId : undefined,
gatewayPoolId: selectedGatewayPoolId ?? undefined,
usernameTemplate
},
@@ -390,7 +380,6 @@ export const dynamicSecretServiceFactory = ({
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 (
@@ -416,22 +405,19 @@ export const dynamicSecretServiceFactory = ({
selectedGatewayPoolId = null;
const gatewayId = updatedInput.gatewayId as string;
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: actorOrgId });
const [gatewayv2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId });
- if (!gateway && !gatewayv2) {
+ if (!gatewayv2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found`
});
}
- isGatewayV1 = Boolean(gateway);
-
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
actor,
actorId,
- orgId: gateway?.orgId || gatewayv2?.orgId,
+ orgId: gatewayv2.orgId,
actorAuthMethod,
actorOrgId
});
@@ -441,7 +427,7 @@ export const dynamicSecretServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- selectedGatewayId = gateway?.id ?? gatewayv2?.id;
+ selectedGatewayId = gatewayv2.id;
}
const isConnected = await selectedProvider.validateConnection(newInput, { projectId });
@@ -459,8 +445,7 @@ export const dynamicSecretServiceFactory = ({
status: null,
...(hasGatewayFieldInInput
? {
- gatewayId: !selectedGatewayPoolId && isGatewayV1 ? selectedGatewayId : null,
- gatewayV2Id: !selectedGatewayPoolId && !isGatewayV1 ? selectedGatewayId : null,
+ gatewayV2Id: !selectedGatewayPoolId ? selectedGatewayId : null,
gatewayPoolId: selectedGatewayPoolId
}
: {}),
diff --git a/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/azure-sql-database.ts
index b75047e121..863dfbd6c7 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
@@ -5,14 +5,14 @@ import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";
import { 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";
@@ -107,13 +107,11 @@ const generatePassword = (requirements?: PasswordRequirements) => {
};
type TAzureSqlDatabaseProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export const AzureSqlDatabaseProvider = ({
- gatewayService,
gatewayV2Service,
gatewayPoolService
}: TAzureSqlDatabaseProviderDTO): TDynamicProviderFns => {
@@ -207,28 +205,19 @@ export const AzureSqlDatabaseProvider = ({
targetPort: providerInputs.port
});
- if (gatewayV2ConnectionDetails) {
- return withGatewayV2Proxy(
- async (port) => {
- await gatewayCallback("localhost", port);
- },
- {
- ...gatewayV2ConnectionDetails,
- protocol: GatewayProxyProtocol.Tcp
- }
- );
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the target host from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(effectiveGatewayId as string) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);
- await withGatewayProxy(
+ return withGatewayV2Proxy(
async (port) => {
await gatewayCallback("localhost", port);
},
{
- relayDetails,
- protocol: GatewayProxyProtocol.Tcp,
- targetHost: providerInputs.host,
- targetPort: providerInputs.port
+ ...gatewayV2ConnectionDetails,
+ protocol: GatewayProxyProtocol.Tcp
}
);
};
diff --git a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts b/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
index 05440eeb4e..287b8f96ba 100644
--- a/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/clickhouse.ts
@@ -4,14 +4,14 @@ import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";
import { 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";
@@ -99,13 +99,11 @@ const generatePassword = (requirements?: PasswordRequirements) => {
};
type TClickhouseProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export const ClickhouseProvider = ({
- gatewayService,
gatewayV2Service,
gatewayPoolService
}: TClickhouseProviderDTO): TDynamicProviderFns => {
@@ -181,28 +179,19 @@ export const ClickhouseProvider = ({
targetPort: providerInputs.port
});
- if (gatewayV2ConnectionDetails) {
- return withGatewayV2Proxy(
- async (port) => {
- await gatewayCallback("localhost", port);
- },
- {
- ...gatewayV2ConnectionDetails,
- protocol: GatewayProxyProtocol.Tcp
- }
- );
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the target host from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(effectiveGatewayId as string) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);
- await withGatewayProxy(
+ return withGatewayV2Proxy(
async (port) => {
await gatewayCallback("localhost", port);
},
{
- relayDetails,
- protocol: GatewayProxyProtocol.Tcp,
- targetHost: providerInputs.host,
- targetPort: providerInputs.port
+ ...gatewayV2ConnectionDetails,
+ protocol: GatewayProxyProtocol.Tcp
}
);
};
diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.ts
index 5f2c57f628..04b777ff90 100644
--- a/backend/src/ee/services/dynamic-secret/providers/index.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/index.ts
@@ -1,7 +1,6 @@
import { SnowflakeProvider } from "@app/ee/services/dynamic-secret/providers/snowflake";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-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";
@@ -33,20 +32,18 @@ import { TotpProvider } from "./totp";
import { VerticaProvider } from "./vertica";
type TBuildDynamicSecretProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
projectDAL: Pick<TProjectDALFactory, "findById">;
};
export const buildDynamicSecretProviders = ({
- gatewayService,
gatewayV2Service,
gatewayPoolService,
projectDAL
}: TBuildDynamicSecretProviderDTO): Record<DynamicSecretProviders, TDynamicProviderFns> => ({
- [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),
- [DynamicSecretProviders.Clickhouse]: ClickhouseProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),
+ [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider({ gatewayV2Service, gatewayPoolService }),
+ [DynamicSecretProviders.Clickhouse]: ClickhouseProvider({ gatewayV2Service, gatewayPoolService }),
[DynamicSecretProviders.Cassandra]: CassandraProvider(),
[DynamicSecretProviders.AwsIam]: AwsIamProvider(),
[DynamicSecretProviders.Redis]: RedisDatabaseProvider(),
@@ -57,22 +54,18 @@ export const buildDynamicSecretProviders = ({
[DynamicSecretProviders.ElasticSearch]: ElasticSearchProvider(),
[DynamicSecretProviders.RabbitMq]: RabbitMqProvider(),
[DynamicSecretProviders.AzureEntraID]: AzureEntraIDProvider(),
- [DynamicSecretProviders.AzureSqlDatabase]: AzureSqlDatabaseProvider({
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
- }),
+ [DynamicSecretProviders.AzureSqlDatabase]: AzureSqlDatabaseProvider({ gatewayV2Service, gatewayPoolService }),
[DynamicSecretProviders.Ldap]: LdapProvider(),
[DynamicSecretProviders.SapHana]: SapHanaProvider(),
[DynamicSecretProviders.Snowflake]: SnowflakeProvider(),
[DynamicSecretProviders.Totp]: TotpProvider(),
[DynamicSecretProviders.SapAse]: SapAseProvider(),
- [DynamicSecretProviders.Kubernetes]: KubernetesProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),
- [DynamicSecretProviders.Vertica]: VerticaProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),
+ [DynamicSecretProviders.Kubernetes]: KubernetesProvider({ gatewayV2Service, gatewayPoolService }),
+ [DynamicSecretProviders.Vertica]: VerticaProvider({ gatewayV2Service, gatewayPoolService }),
[DynamicSecretProviders.GcpIam]: GcpIamProvider({ projectDAL }),
[DynamicSecretProviders.Github]: GithubProvider(),
[DynamicSecretProviders.Couchbase]: CouchbaseProvider(),
- [DynamicSecretProviders.Milvus]: MilvusProvider({ gatewayService, gatewayV2Service, gatewayPoolService }),
+ [DynamicSecretProviders.Milvus]: MilvusProvider({ gatewayV2Service, gatewayPoolService }),
[DynamicSecretProviders.Ssh]: SshProvider(),
[DynamicSecretProviders.IbmApiConnect]: IbmApiConnectProvider(),
[DynamicSecretProviders.Tailscale]: TailscaleProvider()
diff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
index 92e040c2c7..8bb19ea277 100644
--- a/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/kubernetes.ts
@@ -3,10 +3,11 @@ import https from "https";
import { TDynamicSecrets } from "@app/db/schemas";
import { request } from "@app/lib/config/request";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayHttpProxyActions, GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { TKubernetesTokenRequest } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";
@@ -14,7 +15,6 @@ import {
ActorIdentityAttributes,
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 {
@@ -32,13 +32,11 @@ const EXTERNAL_REQUEST_TIMEOUT = 10 * 1000;
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,
gatewayPoolService
}: TKubernetesProviderDTO): TDynamicProviderFns => {
@@ -66,42 +64,24 @@ export const KubernetesProvider = ({
targetHost: inputs.targetHost,
targetPort: inputs.targetPort
});
- if (gatewayV2ConnectionDetails) {
- const callbackResult = await withGatewayV2Proxy(
- async (port) => {
- return gatewayCallback(
- inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
- port,
- inputs.httpsAgent
- );
- },
- {
- ...gatewayV2ConnectionDetails,
- protocol: inputs.reviewTokenThroughGateway ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,
- httpsAgent: inputs.httpsAgent
- }
- );
-
- return callbackResult;
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the Kubernetes API server from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(inputs.gatewayId) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(inputs.gatewayId);
-
- const callbackResult = await withGatewayProxy(
- async (port, httpsAgent) => {
+ const callbackResult = await withGatewayV2Proxy(
+ async (port) => {
// Needs to be https protocol or the kubernetes API server will fail with "Client sent an HTTP request to an HTTPS server"
- const res = await gatewayCallback(
+ return gatewayCallback(
inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
port,
- httpsAgent
+ inputs.httpsAgent
);
- return res;
},
{
- relayDetails,
+ ...gatewayV2ConnectionDetails,
protocol: inputs.reviewTokenThroughGateway ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,
- targetHost: inputs.targetHost,
- // we always pass this, because its needed for both tcp and http protocol
httpsAgent: inputs.httpsAgent
}
);
diff --git a/backend/src/ee/services/dynamic-secret/providers/milvus.ts b/backend/src/ee/services/dynamic-secret/providers/milvus.ts
index 95614f0d22..2e1f7e2f07 100644
--- a/backend/src/ee/services/dynamic-secret/providers/milvus.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/milvus.ts
@@ -5,16 +5,16 @@ import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
import { request } from "@app/lib/config/request";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator";
import { 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";
@@ -24,7 +24,6 @@ import { generateUsername } from "./templateUtils";
type TMilvusProviderInputs = z.infer<typeof DynamicSecretMilvusSchema>;
type TMilvusProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
@@ -85,11 +84,7 @@ export const sanitizeMilvusUsername = (username: string) => username.substring(0
export const deriveRoleName = (username: string) =>
`${MILVUS_ROLE_PREFIX}${username}`.substring(0, MILVUS_MAX_USERNAME_LENGTH);
-export const MilvusProvider = ({
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
-}: TMilvusProviderDTO): TDynamicProviderFns => {
+export const MilvusProvider = ({ gatewayV2Service, gatewayPoolService }: TMilvusProviderDTO): TDynamicProviderFns => {
const validateProviderInputs = async (inputs: object) => {
const providerInputs = await DynamicSecretMilvusSchema.parseAsync(inputs);
const { hostname, origin } = parseMilvusHost(providerInputs, providerInputs.host, providerInputs.port);
@@ -140,20 +135,15 @@ export const MilvusProvider = ({
targetPort: inputs.targetPort
});
- if (gatewayV2ConnectionDetails) {
- return withGatewayV2Proxy(async (port) => gatewayCallback("localhost", port), {
- ...gatewayV2ConnectionDetails,
- protocol: GatewayProxyProtocol.Tcp,
- httpsAgent: inputs.httpsAgent
- });
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the target host from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(inputs.gatewayId) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(inputs.gatewayId);
- return withGatewayProxy(async (port) => gatewayCallback("localhost", port), {
- relayDetails,
+ return withGatewayV2Proxy(async (port) => gatewayCallback("localhost", port), {
+ ...gatewayV2ConnectionDetails,
protocol: GatewayProxyProtocol.Tcp,
- targetHost: bareHostname,
- targetPort: inputs.targetPort,
httpsAgent: inputs.httpsAgent
});
};
diff --git a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
index bc244e07be..19f3fe9226 100644
--- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts
@@ -5,15 +5,15 @@ import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";
import { generatePasswordWithConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-password-generator";
import { 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";
@@ -120,13 +120,11 @@ const generatePassword = (provider: SqlProviders, requirements?: PasswordRequire
};
type TSqlDatabaseProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export const SqlDatabaseProvider = ({
- gatewayService,
gatewayV2Service,
gatewayPoolService
}: TSqlDatabaseProviderDTO): TDynamicProviderFns => {
@@ -223,28 +221,19 @@ export const SqlDatabaseProvider = ({
targetPort: providerInputs.port
});
- if (gatewayV2ConnectionDetails) {
- return withGatewayV2Proxy(
- async (port) => {
- await gatewayCallback("localhost", port);
- },
- {
- ...gatewayV2ConnectionDetails,
- protocol: GatewayProxyProtocol.Tcp
- }
- );
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the target host from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(effectiveGatewayId as string) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);
- await withGatewayProxy(
+ return withGatewayV2Proxy(
async (port) => {
await gatewayCallback("localhost", port);
},
{
- relayDetails,
- protocol: GatewayProxyProtocol.Tcp,
- targetHost: providerInputs.host,
- targetPort: providerInputs.port
+ ...gatewayV2ConnectionDetails,
+ protocol: GatewayProxyProtocol.Tcp
}
);
};
diff --git a/backend/src/ee/services/dynamic-secret/providers/vertica.ts b/backend/src/ee/services/dynamic-secret/providers/vertica.ts
index c478ec9250..3dd4c416b3 100644
--- a/backend/src/ee/services/dynamic-secret/providers/vertica.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/vertica.ts
@@ -3,15 +3,15 @@ import knex, { Knex } from "knex";
import { z } from "zod";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
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";
@@ -134,16 +134,11 @@ const generateUsername = (usernameTemplate?: string | null) => {
};
type TVerticaProviderDTO = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
-export const VerticaProvider = ({
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
-}: TVerticaProviderDTO): TDynamicProviderFns => {
+export const VerticaProvider = ({ gatewayV2Service, gatewayPoolService }: TVerticaProviderDTO): TDynamicProviderFns => {
const validateProviderInputs = async (inputs: unknown) => {
const providerInputs = await DynamicSecretVerticaSchema.parseAsync(inputs);
@@ -210,28 +205,19 @@ export const VerticaProvider = ({
targetPort: providerInputs.port
});
- if (gatewayV2ConnectionDetails) {
- return withGatewayV2Proxy(
- async (port: number) => {
- await gatewayCallback("localhost", port);
- },
- {
- ...gatewayV2ConnectionDetails,
- protocol: GatewayProxyProtocol.Tcp
- }
- );
+ // Falling through here would silently bypass the gateway this dynamic secret is pinned to
+ // and dial the target host from the platform instead.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(effectiveGatewayId as string) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId as string);
- await withGatewayProxy(
- async (port) => {
+ return withGatewayV2Proxy(
+ async (port: number) => {
await gatewayCallback("localhost", port);
},
{
- relayDetails,
- protocol: GatewayProxyProtocol.Tcp,
- targetHost: providerInputs.host,
- targetPort: providerInputs.port
+ ...gatewayV2ConnectionDetails,
+ protocol: GatewayProxyProtocol.Tcp
}
);
};
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts b/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts
index b7f1e3431a..4fb88ecb46 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-fns.ts
@@ -1,6 +1,6 @@
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callTestConnection, TestConnectionResponse } from "@app/lib/gateway-v2/test-connection-rpc";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
import { TGatewayV2ServiceFactory } from "./gateway-v2-service";
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 227cb3664a..f24581d48a 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -11,9 +11,9 @@ import { crypto } from "@app/lib/crypto";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
import { groupBy } from "@app/lib/fn";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
import { getGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { OrgServiceActor } from "@app/lib/types";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
diff --git a/backend/src/ee/services/gateway/gateway-dal.ts b/backend/src/ee/services/gateway/gateway-dal.ts
deleted file mode 100644
index 58f59d3139..0000000000
--- a/backend/src/ee/services/gateway/gateway-dal.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { TDbClient } from "@app/db";
-import { AccessScope, GatewaysSchema, TableName, TGateways } from "@app/db/schemas";
-import { DatabaseError } from "@app/lib/errors";
-import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";
-
-export type TGatewayDALFactory = ReturnType<typeof gatewayDALFactory>;
-
-export const gatewayDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.Gateway);
-
- const find = async (
- filter: TFindFilter<TGateways> & { orgId?: string },
- { offset, limit, sort, tx }: TFindOpt<TGateways> = {}
- ) => {
- try {
- const query = (tx || db.replicaNode())(TableName.Gateway)
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- .where(buildFindFilter(filter, TableName.Gateway, ["orgId"]))
- .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Gateway}.identityId`)
- .join(TableName.Membership, `${TableName.Membership}.actorIdentityId`, `${TableName.Gateway}.identityId`)
- .select(selectAllTableCols(TableName.Gateway))
- .select(db.ref("scopeOrgId").withSchema(TableName.Membership).as("identityOrgId"))
- .select(db.ref("name").withSchema(TableName.Identity).as("identityName"))
- .where(`${TableName.Membership}.scope`, AccessScope.Organization);
-
- if (filter.orgId) {
- void query.where(`${TableName.Membership}.scopeOrgId`, filter.orgId);
- }
- if (limit) void query.limit(limit);
- if (offset) void query.offset(offset);
- if (sort) {
- void query.orderBy(sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls })));
- }
-
- const docs = await query;
-
- return docs.map((el) => ({
- ...GatewaysSchema.parse(el),
- orgId: el.identityOrgId,
- identity: { id: el.identityId, name: el.identityName }
- }));
- } catch (error) {
- throw new DatabaseError({ error, name: `${TableName.Gateway}: Find` });
- }
- };
-
- return { ...orm, find };
-};
diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts
deleted file mode 100644
index 069d3bfb4f..0000000000
--- a/backend/src/ee/services/gateway/gateway-service.ts
+++ /dev/null
@@ -1,637 +0,0 @@
-import { ForbiddenError } from "@casl/ability";
-import * as x509 from "@peculiar/x509";
-import { z } from "zod";
-
-import { OrganizationActionScope } from "@app/db/schemas";
-import { KeyStorePrefixes, KeyStoreTtls, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";
-import { getConfig } from "@app/lib/config/env";
-import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { pingGatewayAndVerify } from "@app/lib/gateway";
-import { TGatewayV1RelayDetails } from "@app/lib/gateway/types";
-import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { getTurnCredentials } from "@app/lib/turn/credentials";
-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
-import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types";
-import {
- createSerialNumber,
- keyAlgorithmToAlgCfg
-} from "@app/services/certificate-authority/certificate-authority-fns";
-import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { KmsDataKey } from "@app/services/kms/kms-types";
-
-import { TLicenseServiceFactory } from "../license/license-service";
-import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
-import { TPermissionServiceFactory } from "../permission/permission-service-types";
-import { TGatewayDALFactory } from "./gateway-dal";
-import {
- TExchangeAllocatedRelayAddressDTO,
- TGetGatewayByIdDTO,
- THeartBeatDTO,
- TListGatewaysDTO,
- TUpdateGatewayByIdDTO
-} from "./gateway-types";
-import { TOrgGatewayConfigDALFactory } from "./org-gateway-config-dal";
-
-type TGatewayServiceFactoryDep = {
- gatewayDAL: TGatewayDALFactory;
- orgGatewayConfigDAL: Pick<TOrgGatewayConfigDALFactory, "findOne" | "create" | "transaction" | "findById">;
- licenseService: Pick<TLicenseServiceFactory, "onPremFeatures" | "getPlan">;
- kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey" | "decryptWithRootKey">;
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
- keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
-};
-
-export type TGatewayServiceFactory = ReturnType<typeof gatewayServiceFactory>;
-const TURN_SERVER_CREDENTIALS_SCHEMA = z.object({
- username: z.string(),
- password: z.string()
-});
-
-export const gatewayServiceFactory = ({
- gatewayDAL,
- licenseService,
- kmsService,
- permissionService,
- orgGatewayConfigDAL,
- keyStore
-}: TGatewayServiceFactoryDep) => {
- const $validateOrgAccessToGateway = async (orgId: string, actorId: string, actorAuthMethod: ActorAuthMethod) => {
- // if (!licenseService.onPremFeatures.gateway) {
- // throw new BadRequestError({
- // message:
- // "Gateway handshake failed due to instance plan restrictions. Please upgrade your instance to Infisical's Enterprise plan."
- // });
- // }
- const orgLicensePlan = await licenseService.getPlan(orgId);
- if (!orgLicensePlan.gateway) {
- throw new BadRequestError({
- message:
- "Gateway handshake failed due to organization plan restrictions. Please upgrade your instance to Infisical's Enterprise plan."
- });
- }
- const { permission } = await permissionService.getOrgPermission({
- actor: ActorType.IDENTITY,
- actorId,
- orgId,
- actorAuthMethod,
- actorOrgId: orgId,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.CreateGateways,
- OrgPermissionSubjects.Gateway
- );
- };
-
- const getGatewayRelayDetails = async (actorId: string, actorOrgId: string, actorAuthMethod: ActorAuthMethod) => {
- const envCfg = getConfig();
- await $validateOrgAccessToGateway(actorOrgId, actorId, actorAuthMethod);
- const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: actorOrgId
- });
-
- if (!envCfg.GATEWAY_RELAY_AUTH_SECRET || !envCfg.GATEWAY_RELAY_ADDRESS || !envCfg.GATEWAY_RELAY_REALM) {
- throw new BadRequestError({
- message: "Gateway handshake failed due to missing instance configuration."
- });
- }
-
- let turnServerUsername = "";
- let turnServerPassword = "";
- // keep it in redis for 5mins to avoid generating so many credentials
- const previousCredential = await keyStore.getItem(KeyStorePrefixes.GatewayIdentityCredential(actorId));
- if (previousCredential) {
- const el = await TURN_SERVER_CREDENTIALS_SCHEMA.parseAsync(
- JSON.parse(decryptor({ cipherTextBlob: Buffer.from(previousCredential, "hex") }).toString())
- );
- turnServerUsername = el.username;
- turnServerPassword = el.password;
- } else {
- const el = getTurnCredentials(actorId, envCfg.GATEWAY_RELAY_AUTH_SECRET);
- await keyStore.setItemWithExpiry(
- KeyStorePrefixes.GatewayIdentityCredential(actorId),
- KeyStoreTtls.GatewayRelayCredentialInSeconds,
- encryptor({
- plainText: Buffer.from(JSON.stringify({ username: el.username, password: el.password }))
- }).cipherTextBlob.toString("hex")
- );
- turnServerUsername = el.username;
- turnServerPassword = el.password;
- }
-
- return {
- turnServerUsername,
- turnServerPassword,
- turnServerRealm: envCfg.GATEWAY_RELAY_REALM,
- turnServerAddress: envCfg.GATEWAY_RELAY_ADDRESS,
- infisicalStaticIp: envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS
- };
- };
-
- const exchangeAllocatedRelayAddress = async ({
- identityId,
- identityOrg,
- relayAddress,
- identityOrgAuthMethod
- }: TExchangeAllocatedRelayAddressDTO) => {
- await $validateOrgAccessToGateway(identityOrg, identityId, identityOrgAuthMethod);
- const { encryptor: orgKmsEncryptor, decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: identityOrg
- });
-
- const orgGatewayConfig = await orgGatewayConfigDAL.transaction(async (tx) => {
- await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayRootCaInit(identityOrg)]);
- const existingGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: identityOrg });
- if (existingGatewayConfig) return existingGatewayConfig;
-
- const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
- // generate root CA
- const rootCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
- const rootCaSerialNumber = createSerialNumber();
- const rootCaSkObj = crypto.nativeCrypto.KeyObject.from(rootCaKeys.privateKey);
- const rootCaIssuedAt = new Date();
- const rootCaKeyAlgorithm = CertKeyAlgorithm.RSA_2048;
- const rootCaExpiration = new Date(new Date().setFullYear(2045));
- const rootCaCert = await x509.X509CertificateGenerator.createSelfSigned({
- name: `O=${identityOrg},CN=Infisical Gateway Root CA`,
- serialNumber: rootCaSerialNumber,
- notBefore: rootCaIssuedAt,
- notAfter: rootCaExpiration,
- signingAlgorithm: alg,
- keys: rootCaKeys,
- extensions: [
- // eslint-disable-next-line no-bitwise
- new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true),
- await x509.SubjectKeyIdentifierExtension.create(rootCaKeys.publicKey)
- ]
- });
-
- // generate client ca
- const clientCaSerialNumber = createSerialNumber();
- const clientCaIssuedAt = new Date();
- const clientCaExpiration = new Date(new Date().setFullYear(2045));
- const clientCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
- const clientCaSkObj = crypto.nativeCrypto.KeyObject.from(clientCaKeys.privateKey);
-
- const clientCaCert = await x509.X509CertificateGenerator.create({
- serialNumber: clientCaSerialNumber,
- subject: `O=${identityOrg},CN=Client Intermediate CA`,
- issuer: rootCaCert.subject,
- notBefore: clientCaIssuedAt,
- notAfter: clientCaExpiration,
- signingKey: rootCaKeys.privateKey,
- publicKey: clientCaKeys.publicKey,
- signingAlgorithm: alg,
- extensions: [
- new x509.KeyUsagesExtension(
- // eslint-disable-next-line no-bitwise
- x509.KeyUsageFlags.keyCertSign |
- x509.KeyUsageFlags.cRLSign |
- x509.KeyUsageFlags.digitalSignature |
- x509.KeyUsageFlags.keyEncipherment,
- true
- ),
- new x509.BasicConstraintsExtension(true, 0, true),
- await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),
- await x509.SubjectKeyIdentifierExtension.create(clientCaKeys.publicKey)
- ]
- });
-
- const clientKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
- const clientCertSerialNumber = createSerialNumber();
- const clientCert = await x509.X509CertificateGenerator.create({
- serialNumber: clientCertSerialNumber,
- subject: `O=${identityOrg},OU=gateway-client,CN=cloud`,
- issuer: clientCaCert.subject,
- notAfter: clientCaExpiration,
- notBefore: clientCaIssuedAt,
- signingKey: clientCaKeys.privateKey,
- publicKey: clientKeys.publicKey,
- signingAlgorithm: alg,
- extensions: [
- new x509.BasicConstraintsExtension(false),
- await x509.AuthorityKeyIdentifierExtension.create(clientCaCert, false),
- await x509.SubjectKeyIdentifierExtension.create(clientKeys.publicKey),
- new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy
- new x509.KeyUsagesExtension(
- // eslint-disable-next-line no-bitwise
- x509.KeyUsageFlags[CertKeyUsage.DIGITAL_SIGNATURE] |
- x509.KeyUsageFlags[CertKeyUsage.KEY_ENCIPHERMENT] |
- x509.KeyUsageFlags[CertKeyUsage.KEY_AGREEMENT],
- true
- ),
- new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true)
- ]
- });
- const clientSkObj = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);
-
- // generate gateway ca
- const gatewayCaSerialNumber = createSerialNumber();
- const gatewayCaIssuedAt = new Date();
- const gatewayCaExpiration = new Date(new Date().setFullYear(2045));
- const gatewayCaKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
- const gatewayCaSkObj = crypto.nativeCrypto.KeyObject.from(gatewayCaKeys.privateKey);
- const gatewayCaCert = await x509.X509CertificateGenerator.create({
- serialNumber: gatewayCaSerialNumber,
- subject: `O=${identityOrg},CN=Gateway CA`,
- issuer: rootCaCert.subject,
- notBefore: gatewayCaIssuedAt,
- notAfter: gatewayCaExpiration,
- signingKey: rootCaKeys.privateKey,
- publicKey: gatewayCaKeys.publicKey,
- signingAlgorithm: alg,
- extensions: [
- new x509.KeyUsagesExtension(
- // eslint-disable-next-line no-bitwise
- x509.KeyUsageFlags.keyCertSign |
- x509.KeyUsageFlags.cRLSign |
- x509.KeyUsageFlags.digitalSignature |
- x509.KeyUsageFlags.keyEncipherment,
- true
- ),
- new x509.BasicConstraintsExtension(true, 0, true),
- await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false),
- await x509.SubjectKeyIdentifierExtension.create(gatewayCaKeys.publicKey)
- ]
- });
-
- return orgGatewayConfigDAL.create({
- orgId: identityOrg,
- rootCaIssuedAt,
- rootCaExpiration,
- rootCaSerialNumber,
- rootCaKeyAlgorithm,
- encryptedRootCaPrivateKey: orgKmsEncryptor({
- plainText: rootCaSkObj.export({
- type: "pkcs8",
- format: "der"
- })
- }).cipherTextBlob,
- encryptedRootCaCertificate: orgKmsEncryptor({ plainText: Buffer.from(rootCaCert.rawData) }).cipherTextBlob,
-
- clientCaIssuedAt,
- clientCaExpiration,
- clientCaSerialNumber,
- encryptedClientCaPrivateKey: orgKmsEncryptor({
- plainText: clientCaSkObj.export({
- type: "pkcs8",
- format: "der"
- })
- }).cipherTextBlob,
- encryptedClientCaCertificate: orgKmsEncryptor({
- plainText: Buffer.from(clientCaCert.rawData)
- }).cipherTextBlob,
-
- clientCertIssuedAt: clientCaIssuedAt,
- clientCertExpiration: clientCaExpiration,
- clientCertKeyAlgorithm: CertKeyAlgorithm.RSA_2048,
- clientCertSerialNumber,
- encryptedClientPrivateKey: orgKmsEncryptor({
- plainText: clientSkObj.export({
- type: "pkcs8",
- format: "der"
- })
- }).cipherTextBlob,
- encryptedClientCertificate: orgKmsEncryptor({
- plainText: Buffer.from(clientCert.rawData)
- }).cipherTextBlob,
-
- gatewayCaIssuedAt,
- gatewayCaExpiration,
- gatewayCaSerialNumber,
- encryptedGatewayCaPrivateKey: orgKmsEncryptor({
- plainText: gatewayCaSkObj.export({
- type: "pkcs8",
- format: "der"
- })
- }).cipherTextBlob,
- encryptedGatewayCaCertificate: orgKmsEncryptor({
- plainText: Buffer.from(gatewayCaCert.rawData)
- }).cipherTextBlob
- });
- });
-
- const rootCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedRootCaCertificate
- })
- );
- const clientCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedClientCaCertificate
- })
- );
-
- const gatewayCaAlg = keyAlgorithmToAlgCfg(orgGatewayConfig.rootCaKeyAlgorithm as CertKeyAlgorithm);
- const gatewayCaSkObj = crypto.nativeCrypto.createPrivateKey({
- key: orgKmsDecryptor({ cipherTextBlob: orgGatewayConfig.encryptedGatewayCaPrivateKey }),
- format: "der",
- type: "pkcs8"
- });
- const gatewayCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedGatewayCaCertificate
- })
- );
-
- const gatewayCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(
- "pkcs8",
- gatewayCaSkObj.export({ format: "der", type: "pkcs8" }),
- gatewayCaAlg,
- true,
- ["sign"]
- );
-
- const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
- const gatewayKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
- const certIssuedAt = new Date();
- // then need to periodically init
- const certExpireAt = new Date(new Date().setMonth(new Date().getMonth() + 1));
-
- const extensions: x509.Extension[] = [
- new x509.BasicConstraintsExtension(false),
- await x509.AuthorityKeyIdentifierExtension.create(gatewayCaCert, false),
- await x509.SubjectKeyIdentifierExtension.create(gatewayKeys.publicKey),
- new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy
- new x509.KeyUsagesExtension(
- // eslint-disable-next-line no-bitwise
- x509.KeyUsageFlags[CertKeyUsage.DIGITAL_SIGNATURE] | x509.KeyUsageFlags[CertKeyUsage.KEY_ENCIPHERMENT],
- true
- ),
- new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true),
- // san
- new x509.SubjectAlternativeNameExtension([{ type: "ip", value: relayAddress.split(":")[0] }], false)
- ];
-
- const serialNumber = createSerialNumber();
- const privateKey = crypto.nativeCrypto.KeyObject.from(gatewayKeys.privateKey);
- const gatewayCertificate = await x509.X509CertificateGenerator.create({
- serialNumber,
- subject: `CN=${identityId},O=${identityOrg},OU=Gateway`,
- issuer: gatewayCaCert.subject,
- notBefore: certIssuedAt,
- notAfter: certExpireAt,
- signingKey: gatewayCaPrivateKey,
- publicKey: gatewayKeys.publicKey,
- signingAlgorithm: alg,
- extensions
- });
-
- const appCfg = getConfig();
- // just for local development
- const formatedRelayAddress =
- appCfg.NODE_ENV === "development" ? relayAddress.replace("127.0.0.1", "host.docker.internal") : relayAddress;
-
- await gatewayDAL.transaction(async (tx) => {
- await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayCertExchange(identityOrg)]);
- const existingGateway = await gatewayDAL.findOne({ identityId, orgGatewayRootCaId: orgGatewayConfig.id });
-
- if (existingGateway) {
- return gatewayDAL.updateById(existingGateway.id, {
- keyAlgorithm: CertKeyAlgorithm.RSA_2048,
- issuedAt: certIssuedAt,
- expiration: certExpireAt,
- serialNumber,
- relayAddress: orgKmsEncryptor({
- plainText: Buffer.from(formatedRelayAddress)
- }).cipherTextBlob
- });
- }
-
- return gatewayDAL.create({
- keyAlgorithm: CertKeyAlgorithm.RSA_2048,
- issuedAt: certIssuedAt,
- expiration: certExpireAt,
- serialNumber,
- relayAddress: orgKmsEncryptor({
- plainText: Buffer.from(formatedRelayAddress)
- }).cipherTextBlob,
- identityId,
- orgGatewayRootCaId: orgGatewayConfig.id,
- name: `gateway-${alphaNumericNanoId(6).toLowerCase()}`
- });
- });
-
- const gatewayCertificateChain = `${clientCaCert.toString("pem")}\n${rootCaCert.toString("pem")}`.trim();
-
- return {
- serialNumber,
- privateKey: privateKey.export({ format: "pem", type: "pkcs8" }) as string,
- certificate: gatewayCertificate.toString("pem"),
- certificateChain: gatewayCertificateChain
- };
- };
-
- const heartbeat = async ({ orgPermission }: THeartBeatDTO) => {
- await $validateOrgAccessToGateway(orgPermission.orgId, orgPermission.id, orgPermission.authMethod);
- const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId });
- if (!orgGatewayConfig) throw new NotFoundError({ message: `Identity with ID ${orgPermission.id} not found.` });
-
- const [gateway] = await gatewayDAL.find({ identityId: orgPermission.id, orgGatewayRootCaId: orgGatewayConfig.id });
- if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${orgPermission.id} not found.` });
-
- const { decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: orgGatewayConfig.orgId
- });
-
- const rootCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedRootCaCertificate
- })
- );
- const gatewayCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedGatewayCaCertificate
- })
- );
- const clientCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedClientCertificate
- })
- );
-
- const privateKey = crypto.nativeCrypto
- .createPrivateKey({
- key: orgKmsDecryptor({ cipherTextBlob: orgGatewayConfig.encryptedClientPrivateKey }),
- format: "der",
- type: "pkcs8"
- })
- .export({ type: "pkcs8", format: "pem" });
-
- const relayAddress = orgKmsDecryptor({ cipherTextBlob: gateway.relayAddress }).toString();
- const [relayHost, relayPort] = relayAddress.split(":");
-
- await pingGatewayAndVerify({
- relayHost,
- relayPort: Number(relayPort),
- tlsOptions: {
- key: privateKey.toString(),
- ca: `${gatewayCaCert.toString("pem")}\n${rootCaCert.toString("pem")}`.trim(),
- cert: clientCert.toString("pem")
- },
- identityId: orgPermission.id,
- orgId: orgPermission.orgId
- });
-
- await gatewayDAL.updateById(gateway.id, { heartbeat: new Date() });
- };
-
- const listGateways = async ({ orgPermission }: TListGatewaysDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actor: orgPermission.type,
- actorId: orgPermission.id,
- orgId: orgPermission.orgId,
- actorAuthMethod: orgPermission.authMethod,
- actorOrgId: orgPermission.orgId,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.ListGateways,
- OrgPermissionSubjects.Gateway
- );
- const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId });
- if (!orgGatewayConfig) return [];
-
- const gateways = await gatewayDAL.find({
- orgGatewayRootCaId: orgGatewayConfig.id
- });
- return gateways;
- };
-
- const getGatewayById = async ({ orgPermission, id }: TGetGatewayByIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actor: orgPermission.type,
- actorId: orgPermission.id,
- orgId: orgPermission.orgId,
- actorAuthMethod: orgPermission.authMethod,
- actorOrgId: orgPermission.orgId,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.ListGateways,
- OrgPermissionSubjects.Gateway
- );
- const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId });
- if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
-
- const [gateway] = await gatewayDAL.find({ id, orgGatewayRootCaId: orgGatewayConfig.id });
- if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
- return gateway;
- };
-
- const updateGatewayById = async ({ orgPermission, id, name }: TUpdateGatewayByIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actor: orgPermission.type,
- actorId: orgPermission.id,
- orgId: orgPermission.orgId,
- actorAuthMethod: orgPermission.authMethod,
- actorOrgId: orgPermission.orgId,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.EditGateways,
- OrgPermissionSubjects.Gateway
- );
- const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId });
- if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
-
- const [gateway] = await gatewayDAL.update({ id, orgGatewayRootCaId: orgGatewayConfig.id }, { name });
- if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
-
- return gateway;
- };
-
- const deleteGatewayById = async ({ orgPermission, id }: TGetGatewayByIdDTO) => {
- const { permission } = await permissionService.getOrgPermission({
- actor: orgPermission.type,
- actorId: orgPermission.id,
- orgId: orgPermission.orgId,
- actorAuthMethod: orgPermission.authMethod,
- actorOrgId: orgPermission.orgId,
- scope: OrganizationActionScope.Any
- });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.DeleteGateways,
- OrgPermissionSubjects.Gateway
- );
- const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId });
- if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
-
- const [gateway] = await gatewayDAL.delete({ id, orgGatewayRootCaId: orgGatewayConfig.id });
- if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` });
- return gateway;
- };
-
- const fnGetGatewayClientTlsByGatewayId = async (gatewayId: string): Promise<TGatewayV1RelayDetails> => {
- const gateway = await gatewayDAL.findById(gatewayId);
- if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${gatewayId} not found.` });
-
- const orgGatewayConfig = await orgGatewayConfigDAL.findById(gateway.orgGatewayRootCaId);
-
- const orgLicensePlan = await licenseService.getPlan(orgGatewayConfig.orgId);
- if (!orgLicensePlan.gateway) {
- throw new BadRequestError({
- message: "Please upgrade your instance to Infisical's Enterprise plan to use gateways."
- });
- }
-
- const { decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId: orgGatewayConfig.orgId
- });
-
- const rootCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedRootCaCertificate
- })
- );
- const gatewayCaCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedGatewayCaCertificate
- })
- );
- const clientCert = new x509.X509Certificate(
- orgKmsDecryptor({
- cipherTextBlob: orgGatewayConfig.encryptedClientCertificate
- })
- );
-
- const clientSkObj = crypto.nativeCrypto.createPrivateKey({
- key: orgKmsDecryptor({ cipherTextBlob: orgGatewayConfig.encryptedClientPrivateKey }),
- format: "der",
- type: "pkcs8"
- });
-
- const relayAddress = orgKmsDecryptor({ cipherTextBlob: gateway.relayAddress }).toString();
-
- const [relayHost, relayPort] = relayAddress.split(":");
-
- return {
- relayAddress,
- relayHost,
- relayPort: Number(relayPort),
- tlsOptions: {
- key: clientSkObj.export({ type: "pkcs8", format: "pem" }).toString(),
- cert: clientCert.toString("pem"),
- ca: `${gatewayCaCert.toString("pem")}\n${rootCaCert.toString("pem")}`.trim()
- },
- identityId: gateway.identityId,
- orgId: orgGatewayConfig.orgId
- };
- };
-
- return {
- getGatewayRelayDetails,
- exchangeAllocatedRelayAddress,
- listGateways,
- getGatewayById,
- updateGatewayById,
- deleteGatewayById,
- fnGetGatewayClientTlsByGatewayId,
- heartbeat
- };
-};
diff --git a/backend/src/ee/services/gateway/gateway-types.ts b/backend/src/ee/services/gateway/gateway-types.ts
deleted file mode 100644
index 823028154f..0000000000
--- a/backend/src/ee/services/gateway/gateway-types.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { OrgServiceActor } from "@app/lib/types";
-import { ActorAuthMethod } from "@app/services/auth/auth-type";
-
-export type TExchangeAllocatedRelayAddressDTO = {
- identityId: string;
- identityOrg: string;
- identityOrgAuthMethod: ActorAuthMethod;
- relayAddress: string;
-};
-
-export type TListGatewaysDTO = {
- orgPermission: OrgServiceActor;
-};
-
-export type TGetGatewayByIdDTO = {
- id: string;
- orgPermission: OrgServiceActor;
-};
-
-export type TUpdateGatewayByIdDTO = {
- id: string;
- name?: string;
- orgPermission: OrgServiceActor;
-};
-
-export type TDeleteGatewayByIdDTO = {
- id: string;
- orgPermission: OrgServiceActor;
-};
-
-export type TGetProjectGatewayByIdDTO = {
- projectId: string;
- projectPermission: OrgServiceActor;
-};
-
-export type THeartBeatDTO = {
- orgPermission: OrgServiceActor;
-};
diff --git a/backend/src/ee/services/gateway/org-gateway-config-dal.ts b/backend/src/ee/services/gateway/org-gateway-config-dal.ts
deleted file mode 100644
index 9d4f9384ad..0000000000
--- a/backend/src/ee/services/gateway/org-gateway-config-dal.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TOrgGatewayConfigDALFactory = ReturnType<typeof orgGatewayConfigDALFactory>;
-
-export const orgGatewayConfigDALFactory = (db: TDbClient) => {
- const orm = ormify(db, TableName.OrgGatewayConfig);
- return orm;
-};
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
index 08a860eb10..d374031c2b 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.test.ts
@@ -23,7 +23,6 @@ vi.mock("node:dns/promises", () => ({
const ORG_ID = "org-id";
const TEMPLATE_ID = "template-id";
-const GATEWAY_ID = "gateway-id";
const GATEWAY_V2_ID = "gateway-v2-id";
const PRIVATE_HOST = "https://10.0.0.1";
// a literal IP keeps the suite hermetic: blockLocalAndPrivateIpAddresses skips the DNS lookup
@@ -36,19 +35,17 @@ const baseBlobFields = {
allowedAudience: ""
};
-const NO_GATEWAY = { gatewayId: null, gatewayV2Id: null, gatewayPoolId: null };
+const NO_GATEWAY = { gatewayV2Id: null, gatewayPoolId: null };
const createService = ({
authMethod = IdentityAuthTemplateMethod.KUBERNETES,
blobFields = baseBlobFields,
- gatewayColumns = { gatewayId: GATEWAY_ID, gatewayV2Id: null, gatewayPoolId: null },
- liveGatewayIds = [GATEWAY_ID],
+ gatewayColumns = { gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null },
liveGatewayV2Ids = [GATEWAY_V2_ID]
}: {
authMethod?: IdentityAuthTemplateMethod;
blobFields?: Record<string, unknown>;
- gatewayColumns?: { gatewayId: string | null; gatewayV2Id: string | null; gatewayPoolId: string | null };
- liveGatewayIds?: string[];
+ gatewayColumns?: { gatewayV2Id: string | null; gatewayPoolId: string | null };
liveGatewayV2Ids?: string[];
} = {}) => {
const identityKubernetesAuthDAL = {
@@ -80,9 +77,6 @@ const createService = ({
transaction: vi.fn().mockImplementation(async (cb: (tx: unknown) => Promise<unknown>) => cb({}))
};
- const gatewayDAL = {
- find: vi.fn().mockImplementation(({ id }: { id: string }) => (liveGatewayIds.includes(id) ? [{ id }] : []))
- };
const gatewayV2DAL = {
find: vi.fn().mockImplementation(({ id }: { id: string }) => (liveGatewayV2Ids.includes(id) ? [{ id }] : []))
};
@@ -94,7 +88,6 @@ const createService = ({
identityLdapAuthDAL: { updateByTemplateId: vi.fn().mockResolvedValue([]) },
identityKubernetesAuthDAL,
identityOidcAuthDAL,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolDAL,
permissionService: {
@@ -206,15 +199,14 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {
await patchTemplate(service, { gatewayId: GATEWAY_V2_ID });
const [, update] = identityAuthTemplateDAL.updateById.mock.calls[0] as [string, Record<string, unknown>];
- // a v2 gateway resolves onto its own column, mirroring identity_kubernetes_auths
+ // the gateway resolves onto its own column, mirroring identity_kubernetes_auths
expect(update.gatewayV2Id).toBe(GATEWAY_V2_ID);
- expect(update.gatewayId).toBeNull();
expect(JSON.parse((update.templateFields as Buffer).toString())).not.toHaveProperty("gatewayId");
});
- it("reports the logical gatewayId from whichever column holds it", async () => {
+ it("reports the gatewayV2Id column as the logical gatewayId", async () => {
const { service } = createService({
- gatewayColumns: { gatewayId: null, gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null }
+ gatewayColumns: { gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null }
});
const updated = await patchTemplate(service, { allowedAudience: "aud" });
@@ -225,11 +217,11 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {
it("propagates the template's gateway columns onto linked identities", async () => {
const { service, identityKubernetesAuthDAL } = createService({ gatewayColumns: NO_GATEWAY });
- await patchTemplate(service, { gatewayId: GATEWAY_ID });
+ await patchTemplate(service, { gatewayId: GATEWAY_V2_ID });
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
{ templateId: TEMPLATE_ID },
- expect.objectContaining({ gatewayId: GATEWAY_ID, gatewayV2Id: null, gatewayPoolId: null }),
+ expect.objectContaining({ gatewayV2Id: GATEWAY_V2_ID, gatewayPoolId: null }),
expect.anything()
);
});
@@ -259,7 +251,7 @@ describe("identityAuthTemplateServiceFactory gateway column storage", () => {
// linked rows still get the row's existing gateway, so they cannot drift from the template
expect(identityKubernetesAuthDAL.updateByTemplateId).toHaveBeenCalledWith(
{ templateId: TEMPLATE_ID },
- expect.objectContaining({ gatewayId: GATEWAY_ID }),
+ expect.objectContaining({ gatewayV2Id: GATEWAY_V2_ID }),
expect.anything()
);
});
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
index 64a97139ee..610c43d9f7 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-service.ts
@@ -3,7 +3,6 @@ import { ForbiddenError } from "@casl/ability";
import { OrganizationActionScope, TIdentityKubernetesAuthsUpdate, TIdentityOidcAuthsUpdate } from "@app/db/schemas";
import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
-import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
@@ -49,7 +48,6 @@ type TIdentityAuthTemplateServiceFactoryDep = {
identityLdapAuthDAL: Pick<TIdentityLdapAuthDALFactory, "updateByTemplateId">;
identityKubernetesAuthDAL: Pick<TIdentityKubernetesAuthDALFactory, "updateByTemplateId">;
identityOidcAuthDAL: Pick<TIdentityOidcAuthDALFactory, "updateByTemplateId">;
- gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
@@ -67,7 +65,6 @@ export const identityAuthTemplateServiceFactory = ({
identityLdapAuthDAL,
identityKubernetesAuthDAL,
identityOidcAuthDAL,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolDAL,
permissionService,
@@ -222,22 +219,15 @@ export const identityAuthTemplateServiceFactory = ({
gatewayPoolId?: string | null;
orgId: string;
}) => {
- let resolvedGatewayId: string | null = null;
let resolvedGatewayV2Id: string | null = null;
if (gatewayId && !gatewayPoolId) {
- const [[gateway], [gatewayV2]] = await Promise.all([
- gatewayDAL.find({ id: gatewayId, orgId }),
- gatewayV2DAL.find({ id: gatewayId, orgId })
- ]);
- if (gateway) {
- resolvedGatewayId = gatewayId;
- } else if (gatewayV2) {
- resolvedGatewayV2Id = gatewayId;
- } else {
+ const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId });
+ if (!gatewayV2) {
throw new BadRequestError({
message: `Gateway with ID '${gatewayId}' was not found in this organization. Select an existing gateway for the template.`
});
}
+ resolvedGatewayV2Id = gatewayId;
}
if (gatewayPoolId) {
const pool = await gatewayPoolDAL.findById(gatewayPoolId);
@@ -247,7 +237,7 @@ export const identityAuthTemplateServiceFactory = ({
});
}
}
- return { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId: gatewayPoolId ?? null };
+ return { resolvedGatewayV2Id, resolvedGatewayPoolId: gatewayPoolId ?? null };
};
// the gateway reference lives in columns rather than the encrypted blob so it can carry a
@@ -267,16 +257,16 @@ export const identityAuthTemplateServiceFactory = ({
const $methodHasGatewayFields = (authMethod: string) =>
(templateFieldPatchKeysByMethod[authMethod as IdentityAuthTemplateMethod] ?? []).includes("gatewayId");
- // the API keeps one logical gatewayId covering both gateway generations, so the v1/v2
- // column split stays an implementation detail
+ // the API exposes the gateway as a plain gatewayId, so the gatewayV2Id column name stays an
+ // implementation detail
const $withGatewayFields = (
- template: Pick<TIdentityAuthTemplates, "authMethod" | "gatewayId" | "gatewayV2Id" | "gatewayPoolId">,
+ template: Pick<TIdentityAuthTemplates, "authMethod" | "gatewayV2Id" | "gatewayPoolId">,
fields: Record<string, unknown>
) => {
if (!$methodHasGatewayFields(template.authMethod)) return fields;
return {
...fields,
- gatewayId: template.gatewayV2Id ?? template.gatewayId ?? null,
+ gatewayId: template.gatewayV2Id ?? null,
gatewayPoolId: template.gatewayPoolId ?? null
};
};
@@ -341,14 +331,13 @@ export const identityAuthTemplateServiceFactory = ({
plan,
permission
});
- const { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId } =
- await $resolveKubernetesTemplateGateway({
- gatewayId: normalizedFields.gatewayId,
- gatewayPoolId: normalizedFields.gatewayPoolId,
- orgId: actorOrgId
- });
+ const { resolvedGatewayV2Id, resolvedGatewayPoolId } = await $resolveKubernetesTemplateGateway({
+ gatewayId: normalizedFields.gatewayId,
+ gatewayPoolId: normalizedFields.gatewayPoolId,
+ orgId: actorOrgId
+ });
gatewayColumns = {
- gatewayId: resolvedGatewayId,
+ gatewayId: null,
gatewayV2Id: resolvedGatewayV2Id,
gatewayPoolId: resolvedGatewayPoolId
};
@@ -467,14 +456,17 @@ export const identityAuthTemplateServiceFactory = ({
plan,
permission
});
- const { resolvedGatewayId, resolvedGatewayV2Id, resolvedGatewayPoolId } =
- await $resolveKubernetesTemplateGateway({
- gatewayId: merged.gatewayId,
- gatewayPoolId: merged.gatewayPoolId,
- orgId: template.orgId
- });
+ const { resolvedGatewayV2Id, resolvedGatewayPoolId } = await $resolveKubernetesTemplateGateway({
+ gatewayId: merged.gatewayId,
+ gatewayPoolId: merged.gatewayPoolId,
+ orgId: template.orgId
+ });
gatewayColumnUpdate = {
- gatewayId: resolvedGatewayId,
+ // a deliberate gateway edit clears the retired v1 pin as well, otherwise the template
+ // stays permanently unusable: identities cannot attach to a v1-pinned template and
+ // patching gatewayId to null would only clear gatewayV2Id. Templates nobody edits keep
+ // their v1 value, so the retirement stays revertible.
+ gatewayId: null,
gatewayV2Id: resolvedGatewayV2Id,
gatewayPoolId: resolvedGatewayPoolId
};
diff --git a/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts b/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts
index b79d53e24c..c330a5c266 100644
--- a/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts
+++ b/backend/src/ee/services/identity-auth-template/identity-auth-template-types.ts
@@ -15,7 +15,7 @@ import {
// Derived from the response schemas so the service and the route contract cannot drift
export type TSanitizedIdentityAuthTemplate = Omit<
TIdentityAuthTemplates,
- "templateFields" | "authMethod" | "gatewayId" | "gatewayV2Id" | "gatewayPoolId"
+ "templateFields" | "authMethod" | "gatewayV2Id" | "gatewayPoolId"
> &
(
| {
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
index a20c8993e8..7bfbe319d9 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.test.ts
@@ -69,7 +69,6 @@ const buildService = (
),
updateById
},
- gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },
gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() },
gatewayPoolService: { resolveEffectiveGatewayId: vi.fn(async () => "gw-1") },
kmsService: { createCipherPairWithDataKey: vi.fn(async () => identityCipher) },
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
index 2d7eb2510c..35982b5e80 100644
--- a/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
+++ b/backend/src/ee/services/pam-account-heartbeat/pam-account-heartbeat-service.ts
@@ -1,4 +1,3 @@
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { testConnectionWithGateway } from "@app/ee/services/gateway-v2/gateway-v2-fns";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
@@ -42,7 +41,6 @@ import {
type TPamAccountHeartbeatServiceFactoryDep = {
pamAccountDAL: TPamAccountDALFactory;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -55,7 +53,6 @@ export type TPamAccountHeartbeatServiceFactory = ReturnType<typeof pamAccountHea
export const pamAccountHeartbeatServiceFactory = ({
pamAccountDAL,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
kmsService,
@@ -187,7 +184,7 @@ export const pamAccountHeartbeatServiceFactory = ({
gatewayId: account.gatewayId ?? account.templateGatewayId,
gatewayPoolId: account.gatewayPoolId ?? account.templateGatewayPoolId
},
- { gatewayService, gatewayV2Service, gatewayPoolService }
+ { gatewayV2Service, gatewayPoolService }
);
} catch (err) {
const kind = (err as { gatewayFailureKind?: GatewayFailureKind | null }).gatewayFailureKind ?? null;
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts
index 0533ad216a..8b581a53d0 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.test.ts
@@ -83,7 +83,6 @@ const buildService = (
membershipRoleDAL: { find: vi.fn() },
kmsService: { createCipherPairWithDataKey: vi.fn(async () => identityCipher) },
keyStore: { acquireLock: vi.fn(async () => ({ release: vi.fn(async () => undefined) })) },
- gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() },
gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() },
gatewayPoolService: { resolveEffectiveGatewayId: vi.fn() },
pamAccountDependencyDAL: { findByAccountId: vi.fn(async () => []), updateById: vi.fn(async () => undefined) },
diff --git a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
index e85141bcb2..ce9dfbf47e 100644
--- a/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
+++ b/backend/src/ee/services/pam-account-rotation/pam-account-rotation-service.ts
@@ -1,6 +1,5 @@
import pLimit from "p-limit";
-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";
@@ -87,7 +86,6 @@ type TPamAccountRotationServiceFactoryDep = {
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "acquireLock">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
pamAccountDependencyDAL: Pick<TPamAccountDependencyDALFactory, "findByAccountId" | "updateById">;
@@ -104,7 +102,6 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
membershipRoleDAL,
kmsService,
keyStore,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
pamAccountDependencyDAL,
@@ -113,7 +110,7 @@ export const pamAccountRotationServiceFactory = (deps: TPamAccountRotationServic
rotationHandlers = PAM_ROTATION_FACTORY_MAP
} = deps;
- const gatewayDeps = { gatewayService, gatewayV2Service, gatewayPoolService };
+ const gatewayDeps = { gatewayV2Service, gatewayPoolService };
const getProjectCipher = (projectId: string) =>
kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
diff --git a/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts b/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
index 57be0e3d0b..b408c50c60 100644
--- a/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
+++ b/backend/src/ee/services/pam-account-rotation/shared/pam-rotation-sql-connection.ts
@@ -1,6 +1,5 @@
import { Knex } from "knex";
-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 { executeWithPotentialGateway } from "@app/services/app-connection/shared/sql";
@@ -21,7 +20,6 @@ export type TPamSqlConnectionDetails = {
};
export type TPamRotationGatewayDeps = {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
@@ -35,7 +33,7 @@ export const withPamSqlClient = async <T>(
gatewayId?: string | null;
gatewayPoolId?: string | null;
},
- { gatewayService, gatewayV2Service, gatewayPoolService }: TPamRotationGatewayDeps,
+ { gatewayV2Service, gatewayPoolService }: TPamRotationGatewayDeps,
operation: (client: Knex) => Promise<T>
): Promise<T> => {
const { accountType, connectionDetails, auth, gatewayId, gatewayPoolId } = input;
@@ -56,5 +54,5 @@ export const withPamSqlClient = async <T>(
gatewayPoolId
} as TSqlConnectionConfig;
- return executeWithPotentialGateway(config, gatewayService, gatewayV2Service, operation, gatewayPoolService);
+ return executeWithPotentialGateway(config, gatewayV2Service, operation, gatewayPoolService);
};
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
index 353fb968b7..63f0356651 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-fns.ts
@@ -1,10 +1,10 @@
import ldapjs from "@infisical/ldapjs";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callPortSweep, callSshExec, SshExecCredentials } from "@app/lib/gateway-v2/ssh-rpc";
import { GatewayFailureKind } from "@app/lib/gateway-v2/test-connection-rpc";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
diff --git a/backend/src/ee/services/pam-session/pam-session-fns.ts b/backend/src/ee/services/pam-session/pam-session-fns.ts
index 28702db1cc..91d29aa4b4 100644
--- a/backend/src/ee/services/pam-session/pam-session-fns.ts
+++ b/backend/src/ee/services/pam-session/pam-session-fns.ts
@@ -2,8 +2,8 @@ import { Knex } from "knex";
import net from "net";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
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.ts
index 4b4e1b914c..f882c2f1ba 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
@@ -12,8 +12,8 @@ import { resolveAccessControls } from "@app/ee/services/pam/pam-policies";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
import { setupGatewayProxy, withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { ActorType } from "@app/services/auth/auth-type";
import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";
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.ts
index 0295f65eb2..eb876de1dd 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
@@ -6,8 +6,8 @@ import { TCertificatesInsert, TPkiCertificateInstallationsInsert } from "@app/db
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";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
index 2f968664ba..c8fcd46ea0 100644
--- a/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
@@ -1,6 +1,6 @@
import { request as httpRequest } from "@app/lib/config/request";
-import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { getSharedHttpsAgent } from "@app/lib/validator/safe-request";
import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";
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.ts
index 9efe98125d..8a633bd8cf 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
@@ -207,7 +207,7 @@ export const hpIloRotationFactory: TRotationFactory<
THpIloRotationWithConnection,
THpIloRotationGeneratedCredentials,
THpIloRotationInput["temporaryParameters"]
-> = (secretRotation, appConnectionDAL, kmsService, _gatewayService, gatewayV2Service, gatewayPoolService) => {
+> = (secretRotation, appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService) => {
const { connection, parameters, secretsMapping, activeIndex } = secretRotation;
const { username, passwordRequirements, rotationMethod = HpIloRotationMethod.LoginAsRoot } = parameters;
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.ts
index 51484e742c..bd0a49e31e 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
@@ -111,15 +111,7 @@ export const ldapPasswordRotationFactory: TRotationFactory<
TLdapPasswordRotationWithConnection,
TLdapPasswordRotationGeneratedCredentials,
TLdapPasswordRotationInput["temporaryParameters"]
-> = (
- secretRotation,
- appConnectionDAL,
- kmsService,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- passwordValidationContext
-) => {
+> = (secretRotation, appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService, passwordValidationContext) => {
const { connection, parameters, secretsMapping, activeIndex } = secretRotation;
const { dn, passwordRequirements } = parameters;
diff --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.ts
index 87f745ae37..ef55ff3b09 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
@@ -4,7 +4,6 @@ import isEqual from "lodash.isequal";
import { ActionProjectType, SecretType, TableName } 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 { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { hasSecretReadValueOrDescribePermission } from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
@@ -171,7 +170,6 @@ export type TSecretRotationV2ServiceFactoryDep = {
queueService: Pick<TQueueServiceFactory, "queue">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
@@ -240,7 +238,6 @@ export const secretRotationV2ServiceFactory = ({
queueService,
folderCommitService,
appConnectionDAL,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
telemetryService,
@@ -620,7 +617,6 @@ export const secretRotationV2ServiceFactory = ({
} as TSecretRotationV2WithConnection,
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
passwordValidationContext
@@ -996,7 +992,6 @@ export const secretRotationV2ServiceFactory = ({
} as TSecretRotationV2WithConnection,
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
passwordValidationContext
@@ -1340,7 +1335,6 @@ export const secretRotationV2ServiceFactory = ({
} as TSecretRotationV2WithConnection,
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
passwordValidationContext
@@ -1666,7 +1660,6 @@ export const secretRotationV2ServiceFactory = ({
} as TSecretRotationV2WithConnection,
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
);
@@ -2066,7 +2059,6 @@ export const secretRotationV2ServiceFactory = ({
} as TSecretRotationV2WithConnection,
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
passwordValidationContext
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.ts
index 7c83c696d4..18fa688801 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
@@ -1,5 +1,4 @@
import { AuditLogInfo } from "@app/ee/services/audit-log/audit-log-types";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TSqlCredentialsRotationGeneratedCredentials } from "@app/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-types";
import { OrderByDirection } from "@app/lib/types";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
@@ -524,7 +523,6 @@ export type TRotationFactory<
secretRotation: T,
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
passwordValidationContext?: TRotationPasswordValidationContext
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.ts
index 1a01d8be8d..205897acc8 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
@@ -68,7 +68,6 @@ export const sqlCredentialsRotationFactory: TRotationFactory<
secretRotation,
_appConnectionDAL,
_kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
passwordValidationContext
@@ -125,7 +124,6 @@ export const sqlCredentialsRotationFactory: TRotationFactory<
...conn,
credentials: finalCredentials
},
- gatewayService,
gatewayV2Service,
(client) => operation(client)
);
diff --git a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
index fbff8e0944..9c8a0aaa87 100644
--- a/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
+++ b/backend/src/ee/services/secret-rotation-v2/unix-linux-local-account-rotation/pty-expect-engine.ts
@@ -89,7 +89,8 @@ export type TExpectSessionConfig = {
};
// An SSH channel over a PTY re-segments output wherever the network splits the bytes, and a
-// gateway-backed connection copies between TCP and QUIC with no framing at all. The same
+// gateway-backed connection copies between TCP and the gateway's TLS tunnel with no framing at
+// all. The same
// `passwd` exchange can arrive as one chunk or twenty, so matching against only the latest
// chunk is unreliable: 11 of the 49 split points inside AIX's "root's New password:\r\n"
// break a per-chunk match. This engine accumulates everything into a pending buffer and
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.ts
index 1b2b30111e..78c5d02eef 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
@@ -362,15 +362,7 @@ export const unixLinuxLocalAccountRotationFactory: TRotationFactory<
TUnixLinuxLocalAccountRotationWithConnection,
TUnixLinuxLocalAccountRotationGeneratedCredentials,
TUnixLinuxLocalAccountRotationInput["temporaryParameters"]
-> = (
- secretRotation,
- appConnectionDAL,
- kmsService,
- _gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- passwordValidationContext
-) => {
+> = (secretRotation, appConnectionDAL, kmsService, gatewayV2Service, gatewayPoolService, passwordValidationContext) => {
const { connection, parameters, secretsMapping, activeIndex } = secretRotation;
const {
username,
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.ts
index b470dda0cc..3237662262 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
@@ -26,7 +26,7 @@ export const windowsLocalAccountRotationFactory: TRotationFactory<
TWindowsLocalAccountRotationWithConnection,
TWindowsLocalAccountRotationGeneratedCredentials,
TWindowsLocalAccountRotationInput["temporaryParameters"]
-> = (secretRotation, _appConnectionDAL, _kmsService, _gatewayService, gatewayV2Service, gatewayPoolService) => {
+> = (secretRotation, _appConnectionDAL, _kmsService, gatewayV2Service, gatewayPoolService) => {
const { connection, parameters, secretsMapping, activeIndex } = secretRotation;
const { username, passwordRequirements, rotationMethod = WindowsLocalAccountRotationMethod.LoginAsRoot } = parameters;
diff --git a/backend/src/lib/gateway-v2/gateway-errors.ts b/backend/src/lib/gateway-v2/gateway-errors.ts
new file mode 100644
index 0000000000..a418ba0ef5
--- /dev/null
+++ b/backend/src/lib/gateway-v2/gateway-errors.ts
@@ -0,0 +1,19 @@
+/**
+ * A gateway id that resolves to no gateway is never safe to treat as "no gateway configured": the
+ * resource is pinned to it, so dialling the target directly would bypass the network boundary the
+ * gateway exists to enforce. Every caller turns this into a 404 instead.
+ *
+ * The most likely reason a caller lands here is a resource still pointing at a legacy gateway.
+ * Those rows are retained but no longer read, and there is no in-place upgrade for one, so the
+ * message names that outcome and asks for a new gateway rather than implying the old id can be
+ * recovered.
+ */
+export const getMissingGatewayMessage = (gatewayId: string) =>
+ `Gateway with ID '${gatewayId}' was not found. It was either deleted, or created on the legacy gateway system, which is no longer supported. Deploy a new gateway under Organization Settings > Networking and select it on this resource, or remove the gateway to connect directly.`;
+
+/**
+ * Used where the resource is known to point at a legacy gateway, so the message can state the
+ * cause outright instead of offering it as one possibility.
+ */
+export const getRetiredGatewayMessage = (resourceDescription: string) =>
+ `${resourceDescription} is attached to a gateway created on the legacy gateway system, which is no longer supported. Deploy a new gateway under Organization Settings > Networking and select it, or remove the gateway to connect directly.`;
diff --git a/backend/src/lib/gateway-v2/gateway-v2.test.ts b/backend/src/lib/gateway-v2/gateway-v2.test.ts
index 601c7eb183..b48341f5b2 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.test.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.test.ts
@@ -3,7 +3,7 @@ import tls from "node:tls";
import forge from "node-forge";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { setupGatewayProxy } from "./gateway-v2";
diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.ts
index 185f9abb7d..7982be026b 100644
--- a/backend/src/lib/gateway-v2/gateway-v2.ts
+++ b/backend/src/lib/gateway-v2/gateway-v2.ts
@@ -14,11 +14,11 @@ import { splitPemChain } from "@app/services/certificate/certificate-fns";
import { getConfig } from "../config/env";
import { BadRequestError, GatewayTransportError } from "../errors";
-import { GatewayProxyProtocol } from "../gateway/types";
import { logger } from "../logger";
import { markAttemptTransportFailure, markAttemptTunnelEstablished } from "./gateway-attempt-context";
import { getGatewayLoadTracker } from "./gateway-load-tracker";
import { isGatewayTransportFailure } from "./gateway-retry";
+import { GatewayProxyProtocol } from "./types";
interface IGatewayProxyServer {
server: net.Server;
diff --git a/backend/src/lib/gateway-v2/types.ts b/backend/src/lib/gateway-v2/types.ts
new file mode 100644
index 0000000000..ab0aac9cb6
--- /dev/null
+++ b/backend/src/lib/gateway-v2/types.ts
@@ -0,0 +1,19 @@
+export enum GatewayProxyProtocol {
+ Http = "http",
+ Tcp = "tcp",
+ Ping = "ping",
+ Health = "health",
+ Pam = "pam",
+ PamRdpBrowser = "pam-rdp-browser",
+ PamSessionCancellation = "pam-session-cancellation",
+ Pkcs11 = "pkcs11",
+ Adcs = "adcs",
+ Discovery = "discovery",
+ ConnectionTest = "connection-test",
+ WinRm = "winrm"
+}
+
+export enum GatewayHttpProxyActions {
+ InjectGatewayK8sServiceAccountToken = "inject-k8s-sa-auth-token",
+ UseGatewayK8sServiceAccount = "use-k8s-sa"
+}
diff --git a/backend/src/lib/gateway/gateway.ts b/backend/src/lib/gateway/gateway.ts
deleted file mode 100644
index f5d551fa23..0000000000
--- a/backend/src/lib/gateway/gateway.ts
+++ /dev/null
@@ -1,429 +0,0 @@
-/* eslint-disable no-await-in-loop */
-import net from "node:net";
-
-import quicDefault, * as quicModule from "@infisical/quic";
-import { isAxiosError } from "axios";
-import https from "https";
-
-import { crypto } from "@app/lib/crypto/cryptography";
-
-import { BadRequestError } from "../errors";
-import { logger } from "../logger";
-import {
- GatewayProxyProtocol,
- IGatewayProxyOptions,
- IGatewayProxyServer,
- TGatewayTlsOptions,
- TPingGatewayAndVerifyDTO
-} from "./types";
-
-const DEFAULT_MAX_RETRIES = 3;
-const DEFAULT_RETRY_DELAY = 1000; // 1 second
-
-const quic = quicDefault || quicModule;
-
-const parseSubjectDetails = (data: string) => {
- const values: Record<string, string> = {};
- data.split("\n").forEach((el) => {
- const [key, value] = el.split("=");
- values[key.trim()] = value.trim();
- });
- return values;
-};
-
-const createQuicConnection = async (
- relayHost: string,
- relayPort: number,
- tlsOptions: TGatewayTlsOptions,
- identityId: string,
- orgId: string
-) => {
- const client = await quic.QUICClient.createQUICClient({
- host: relayHost,
- port: relayPort,
- config: {
- ca: tlsOptions.ca,
- cert: tlsOptions.cert,
- key: tlsOptions.key,
- applicationProtos: ["infisical-gateway"],
- verifyPeer: true,
- verifyCallback: async (certs) => {
- if (!certs || certs.length === 0) return quic.native.CryptoError.CertificateRequired;
- const serverCertificate = new crypto.nativeCrypto.X509Certificate(Buffer.from(certs[0]));
- const caCertificate = new crypto.nativeCrypto.X509Certificate(tlsOptions.ca);
- const isValidServerCertificate = serverCertificate.verify(caCertificate.publicKey);
- if (!isValidServerCertificate) return quic.native.CryptoError.BadCertificate;
-
- const subjectDetails = parseSubjectDetails(serverCertificate.subject);
- if (subjectDetails.OU !== "Gateway" || subjectDetails.CN !== identityId || subjectDetails.O !== orgId) {
- return quic.native.CryptoError.CertificateUnknown;
- }
-
- if (new Date() > new Date(serverCertificate.validTo) || new Date() < new Date(serverCertificate.validFrom)) {
- return quic.native.CryptoError.CertificateExpired;
- }
-
- const formatedRelayHost =
- process.env.NODE_ENV === "development" ? relayHost.replace("host.docker.internal", "127.0.0.1") : relayHost;
- if (!serverCertificate.checkIP(formatedRelayHost)) return quic.native.CryptoError.BadCertificate;
- },
- maxIdleTimeout: 90000,
- keepAliveIntervalTime: 30000
- },
- crypto: {
- ops: {
- randomBytes: async (data) => {
- crypto.nativeCrypto.getRandomValues(new Uint8Array(data));
- }
- }
- }
- });
- return client;
-};
-
-export const pingGatewayAndVerify = async ({
- relayHost,
- relayPort,
- tlsOptions,
- maxRetries = DEFAULT_MAX_RETRIES,
- identityId,
- orgId
-}: TPingGatewayAndVerifyDTO) => {
- let lastError: Error | null = null;
- const quicClient = await createQuicConnection(relayHost, relayPort, tlsOptions, identityId, orgId).catch((err) => {
- throw new BadRequestError({
- message: (err as Error)?.message,
- error: err as Error
- });
- });
-
- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
- try {
- const stream = quicClient.connection.newStream("bidi");
- const pingWriter = stream.writable.getWriter();
- await pingWriter.write(Buffer.from("PING\n"));
- pingWriter.releaseLock();
-
- // Read PONG response
- const reader = stream.readable.getReader();
- const { value, done } = await reader.read();
-
- if (done) {
- throw new Error("Gateway closed before receiving PONG");
- }
-
- const response = Buffer.from(value).toString();
-
- if (response !== "PONG\n" && response !== "PONG") {
- throw new Error(`Failed to Ping. Unexpected response: ${response}`);
- }
-
- reader.releaseLock();
- return;
- } catch (err) {
- lastError = err as Error;
-
- if (attempt < maxRetries) {
- await new Promise((resolve) => {
- setTimeout(resolve, DEFAULT_RETRY_DELAY);
- });
- }
- } finally {
- await quicClient.destroy();
- }
- }
-
- logger.error(lastError);
- throw new BadRequestError({
- message: `Failed to ping gateway after ${maxRetries} attempts. Last error: ${lastError?.message}`
- });
-};
-
-const setupProxyServer = async ({
- targetPort,
- targetHost,
- tlsOptions,
- relayHost,
- relayPort,
- identityId,
- orgId,
- protocol = GatewayProxyProtocol.Tcp,
- httpsAgent
-}: {
- targetHost?: string;
- targetPort?: number;
- relayPort: number;
- relayHost: string;
- tlsOptions: TGatewayTlsOptions;
- identityId: string;
- orgId: string;
- protocol?: GatewayProxyProtocol;
- httpsAgent?: https.Agent;
-}): Promise<IGatewayProxyServer> => {
- const quicClient = await createQuicConnection(relayHost, relayPort, tlsOptions, identityId, orgId).catch((err) => {
- throw new BadRequestError({
- error: err as Error
- });
- });
- const proxyErrorMsg = [""];
-
- return new Promise((resolve, reject) => {
- const server = net.createServer();
-
- let streamClosed = false;
-
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- server.on("connection", async (clientConn) => {
- try {
- clientConn.setKeepAlive(true, 30000); // 30 seconds
- clientConn.setNoDelay(true);
-
- const stream = quicClient.connection.newStream("bidi");
-
- const forwardWriter = stream.writable.getWriter();
- let command: string;
-
- if (protocol === GatewayProxyProtocol.Http) {
- if (!targetHost && !targetPort) {
- command = `FORWARD-HTTP`;
- logger.debug(`Using HTTP proxy mode, no target URL provided [command=${command.trim()}]`);
- } else {
- if (!targetHost || targetPort === undefined) {
- throw new BadRequestError({
- message: `Target host and port are required for HTTP proxy mode with custom target`
- });
- }
-
- const targetUrl = `${targetHost}:${targetPort}`; // note(daniel): targetHost MUST include the scheme (https|http)
- command = `FORWARD-HTTP ${targetUrl}`;
- logger.debug(`Using HTTP proxy mode, custom target URL provided [command=${command.trim()}]`);
-
- // extract ca certificate from httpsAgent if present
- if (httpsAgent && targetHost.startsWith("https://")) {
- const agentOptions = httpsAgent.options;
- if (agentOptions && agentOptions.ca) {
- const caCert = Array.isArray(agentOptions.ca) ? agentOptions.ca.join("\n") : agentOptions.ca;
- const caB64 = Buffer.from(caCert as string).toString("base64");
- command += ` ca=${caB64}`;
-
- const rejectUnauthorized = agentOptions.rejectUnauthorized !== false;
- command += ` verify=${rejectUnauthorized}`;
-
- logger.debug(`Using HTTP proxy mode, custom target URL provided [command=${command.trim()}]`);
- }
- }
- }
-
- command += "\n";
- } else if (protocol === GatewayProxyProtocol.Tcp) {
- if (!targetHost || !targetPort) {
- throw new BadRequestError({
- message: `Target host and port are required for TCP proxy mode`
- });
- }
-
- // For TCP mode, send FORWARD-TCP with host:port
- command = `FORWARD-TCP ${targetHost}:${targetPort}\n`;
- logger.debug(`Using TCP proxy mode: ${command.trim()}`);
- } else {
- throw new BadRequestError({
- message: `Invalid protocol: ${protocol as string}`
- });
- }
-
- await forwardWriter.write(Buffer.from(command));
- forwardWriter.releaseLock();
-
- // Set up bidirectional copy
- const setupCopy = () => {
- // Client to QUIC
- // eslint-disable-next-line
- (async () => {
- const writer = stream.writable.getWriter();
-
- // Create a handler for client data
- clientConn.on("data", (chunk) => {
- writer.write(chunk).catch((err) => {
- proxyErrorMsg.push((err as Error)?.message);
- });
- });
-
- // Handle client connection close
- clientConn.on("end", () => {
- if (!streamClosed) {
- try {
- writer.close().catch((err) => {
- logger.debug(err, "Error closing writer (already closed)");
- });
- } catch (error) {
- logger.debug(error, "Error in writer close");
- }
- }
- });
-
- clientConn.on("error", (clientConnErr) => {
- writer.abort(clientConnErr?.message).catch((err) => {
- proxyErrorMsg.push((err as Error)?.message);
- });
- });
- })();
-
- // QUIC to Client
- void (async () => {
- try {
- const reader = stream.readable.getReader();
-
- let reading = true;
- while (reading) {
- const { value, done } = await reader.read();
-
- if (done) {
- reading = false;
- clientConn.end(); // Close client connection when QUIC stream ends
- break;
- }
-
- // Write data to TCP client
- const canContinue = clientConn.write(Buffer.from(value));
-
- // Handle backpressure
- if (!canContinue) {
- await new Promise((res) => {
- clientConn.once("drain", res);
- });
- }
- }
- } catch (err) {
- proxyErrorMsg.push((err as Error)?.message);
- clientConn.destroy();
- }
- })();
- };
-
- setupCopy();
- // Handle connection closure
- clientConn.on("close", () => {
- if (!streamClosed) {
- streamClosed = true;
- stream.destroy().catch((err) => {
- logger.debug(err, "Stream already destroyed during close event");
- });
- }
- });
-
- const cleanup = async () => {
- try {
- clientConn?.destroy();
- } catch (err) {
- logger.debug(err, "Error destroying client connection");
- }
-
- if (!streamClosed) {
- streamClosed = true;
- try {
- await stream.destroy();
- } catch (err) {
- logger.debug(err, "Error destroying stream (might be already closed)");
- }
- }
- };
-
- clientConn.on("error", (clientConnErr) => {
- logger.error(clientConnErr, "Client socket error");
- cleanup().catch((err) => {
- logger.error(err, "Client conn cleanup");
- });
- });
-
- clientConn.on("end", () => {
- cleanup().catch((err) => {
- logger.error(err, "Client conn end");
- });
- });
- } catch (err) {
- logger.error(err, "Failed to establish target connection:");
- clientConn.end();
- reject(err);
- }
- });
-
- server.on("error", (err) => {
- reject(err);
- });
-
- server.on("close", () => {
- quicClient?.destroy().catch((err) => {
- logger.error(err, "Failed to destroy quic client");
- });
- });
-
- server.listen(0, () => {
- const address = server.address();
- if (!address || typeof address === "string") {
- server.close();
- reject(new Error("Failed to get server port"));
- return;
- }
-
- logger.info(`Gateway proxy started on port ${address.port} (${protocol} mode)`);
- resolve({
- server,
- port: address.port,
- cleanup: async () => {
- try {
- server.close();
- } catch (err) {
- logger.debug(err, "Error closing server");
- }
-
- try {
- await quicClient?.destroy();
- } catch (err) {
- logger.debug(err, "Error destroying QUIC client");
- }
- },
- getProxyError: () => proxyErrorMsg.join(",")
- });
- });
- });
-};
-
-export const withGatewayProxy = async <T>(
- callback: (port: number, httpsAgent?: https.Agent) => Promise<T>,
- options: IGatewayProxyOptions
-): Promise<T> => {
- const { targetHost, targetPort, relayDetails, protocol, httpsAgent } = options;
-
- // Setup the proxy server
- const { port, cleanup, getProxyError } = await setupProxyServer({
- targetHost,
- targetPort,
- relayPort: relayDetails.relayPort,
- relayHost: relayDetails.relayHost,
- tlsOptions: relayDetails.tlsOptions,
- identityId: relayDetails.identityId,
- orgId: relayDetails.orgId,
- protocol,
- httpsAgent
- });
-
- try {
- // Execute the callback with the allocated port
- return await callback(port, httpsAgent);
- } catch (err) {
- const proxyErrorMessage = getProxyError();
- if (proxyErrorMessage) {
- logger.error(new Error(proxyErrorMessage), "Failed to proxy");
- }
- logger.error(err, "Failed to do gateway");
- let errorMessage = proxyErrorMessage || (err as Error)?.message;
- if (isAxiosError(err) && (err.response?.data as { message?: string })?.message) {
- errorMessage = (err.response?.data as { message: string }).message;
- }
-
- throw new BadRequestError({ message: errorMessage });
- } finally {
- // Ensure cleanup happens regardless of success or failure
- await cleanup();
- }
-};
diff --git a/backend/src/lib/gateway/index.ts b/backend/src/lib/gateway/index.ts
deleted file mode 100644
index 9292473e50..0000000000
--- a/backend/src/lib/gateway/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export { pingGatewayAndVerify, withGatewayProxy } from "./gateway";
-export { GatewayHttpProxyActions, GatewayProxyProtocol } from "./types";
diff --git a/backend/src/lib/gateway/types.ts b/backend/src/lib/gateway/types.ts
deleted file mode 100644
index 45d12f2ea9..0000000000
--- a/backend/src/lib/gateway/types.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import net from "node:net";
-
-import https from "https";
-
-export type TGatewayTlsOptions = { ca: string; cert: string; key: string };
-
-export enum GatewayProxyProtocol {
- Http = "http",
- Tcp = "tcp",
- Ping = "ping",
- Health = "health",
- Pam = "pam",
- PamRdpBrowser = "pam-rdp-browser",
- PamSessionCancellation = "pam-session-cancellation",
- Pkcs11 = "pkcs11",
- Adcs = "adcs",
- Discovery = "discovery",
- ConnectionTest = "connection-test",
- WinRm = "winrm"
-}
-
-export enum GatewayHttpProxyActions {
- InjectGatewayK8sServiceAccountToken = "inject-k8s-sa-auth-token",
- UseGatewayK8sServiceAccount = "use-k8s-sa"
-}
-
-export interface IGatewayProxyOptions {
- targetHost?: string;
- targetPort?: number;
- protocol: GatewayProxyProtocol;
- httpsAgent?: https.Agent;
- relayDetails: TGatewayV1RelayDetails;
-}
-
-export type TPingGatewayAndVerifyDTO = {
- relayHost: string;
- relayPort: number;
- tlsOptions: TGatewayTlsOptions;
- maxRetries?: number;
- identityId: string;
- orgId: string;
-};
-
-export interface IGatewayProxyServer {
- server: net.Server;
- port: number;
- cleanup: () => Promise<void>;
- getProxyError: () => string;
-}
-
-export type TGatewayV1RelayDetails = {
- relayAddress: string;
- tlsOptions: TGatewayTlsOptions;
- identityId: string;
- orgId: string;
- relayHost: string;
- relayPort: number;
-};
-
-export enum GatewayVersion {
- V1 = "v1",
- V2 = "v2"
-}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index bfdc88c906..01c6be9a82 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -63,9 +63,6 @@ import { emailDomainServiceFactory } from "@app/ee/services/email-domain/email-d
import { eventBusServiceFactory } from "@app/ee/services/event-bus/event-bus-service";
import { externalKmsDALFactory } from "@app/ee/services/external-kms/external-kms-dal";
import { externalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
-import { gatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
-import { gatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
-import { orgGatewayConfigDALFactory } from "@app/ee/services/gateway/org-gateway-config-dal";
import { gatewayPoolDalFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { gatewayPoolMembershipDalFactory } from "@app/ee/services/gateway-pool/gateway-pool-membership-dal";
import { gatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
@@ -770,8 +767,6 @@ export const registerRoutes = async (
const kmipOrgConfigDAL = kmipOrgConfigDALFactory(db);
const kmipOrgServerCertificateDAL = kmipOrgServerCertificateDALFactory(db);
- const orgGatewayConfigDAL = orgGatewayConfigDALFactory(db);
- const gatewayDAL = gatewayDALFactory(db);
const secretReminderRecipientsDAL = secretReminderRecipientsDALFactory(db);
const githubOrgSyncDAL = githubOrgSyncDALFactory(db);
const gitHubAppDAL = gitHubAppDALFactory(db);
@@ -1908,15 +1903,6 @@ export const registerRoutes = async (
kmsService
});
- const gatewayService = gatewayServiceFactory({
- permissionService,
- gatewayDAL,
- kmsService,
- licenseService,
- orgGatewayConfigDAL,
- keyStore
- });
-
// Populated after gatewayV2Service and gatewayPoolService exist; both depend on
// resourceAuthMethodService, so the proxy resolver cannot be a constructor dependency.
const gatewayProxyRegistry = gatewayProxyRegistryFactory();
@@ -2142,7 +2128,6 @@ export const registerRoutes = async (
membershipRoleDAL,
kmsService,
keyStore,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
pamAccountDependencyDAL,
@@ -2152,7 +2137,6 @@ export const registerRoutes = async (
const pamAccountHeartbeatService = pamAccountHeartbeatServiceFactory({
pamAccountDAL,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
kmsService,
@@ -2209,10 +2193,8 @@ export const registerRoutes = async (
kmsService,
keyStore,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
- gatewayDAL,
gatewayV2DAL,
auditLogService,
userDAL
@@ -2244,7 +2226,6 @@ export const registerRoutes = async (
appConnectionDAL,
gitHubAppDAL,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
notificationService,
@@ -2671,7 +2652,6 @@ export const registerRoutes = async (
identityLdapAuthDAL,
identityKubernetesAuthDAL,
identityOidcAuthDAL,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolDAL,
permissionService,
@@ -2710,11 +2690,9 @@ export const registerRoutes = async (
identityAccessTokenDAL,
permissionService,
licenseService,
- gatewayService,
orgDAL,
gatewayV2Service,
gatewayV2DAL,
- gatewayDAL,
kmsService,
keyStore,
membershipIdentityDAL,
@@ -2914,7 +2892,6 @@ export const registerRoutes = async (
});
const dynamicSecretProviders = buildDynamicSecretProviders({
- gatewayService,
gatewayV2Service,
gatewayPoolService,
projectDAL
@@ -2943,7 +2920,6 @@ export const registerRoutes = async (
permissionService,
licenseService,
kmsService,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolService,
resourceMetadataDAL
@@ -3121,10 +3097,8 @@ export const registerRoutes = async (
permissionService,
kmsService,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
- gatewayDAL,
gatewayV2DAL,
projectDAL,
appConnectionCredentialRotationService,
@@ -3302,7 +3276,6 @@ export const registerRoutes = async (
secretQueueService,
queueService,
appConnectionDAL,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
telemetryService,
@@ -4063,8 +4036,6 @@ export const registerRoutes = async (
externalMigrationQueue,
userDAL,
permissionService,
- gatewayDAL,
- gatewayService,
gatewayV2DAL,
appConnectionService,
secretService,
@@ -4293,7 +4264,6 @@ export const registerRoutes = async (
kmip: kmipService,
kmipOperation: kmipOperationService,
kmipServer: kmipServerService,
- gateway: gatewayService,
relay: relayService,
gatewayV2: gatewayV2Service,
gatewayPool: gatewayPoolService,
diff --git a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
index 88325b3476..64f4fdd1a2 100644
--- a/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-kubernetes-auth-router.ts
@@ -34,7 +34,6 @@ const IdentityKubernetesAuthResponseSchema = IdentityKubernetesAuthsSchema.pick(
allowedNamespaces: true,
allowedNames: true,
allowedAudience: true,
- gatewayId: true,
gatewayPoolId: true,
verifyTlsCertificate: true,
templateId: true,
@@ -44,7 +43,10 @@ const IdentityKubernetesAuthResponseSchema = IdentityKubernetesAuthsSchema.pick(
isTokenReviewerJwtTemplateSourced: true
}).extend({
caCert: z.string(),
- tokenReviewerJwt: z.string().optional().nullable()
+ tokenReviewerJwt: z.string().optional().nullable(),
+ // declared rather than picked: the row's own gatewayId is the retired v1 column, and the
+ // service fills this field from gatewayV2Id so the API name stays unchanged
+ gatewayId: z.string().uuid().optional().nullable()
});
export const registerIdentityKubernetesRouter = async (server: FastifyZodProvider) => {
diff --git a/backend/src/services/app-connection/adcs/adcs-connection-fns.ts b/backend/src/services/app-connection/adcs/adcs-connection-fns.ts
index 2e1e8744b2..771c533fb6 100644
--- a/backend/src/services/app-connection/adcs/adcs-connection-fns.ts
+++ b/backend/src/services/app-connection/adcs/adcs-connection-fns.ts
@@ -1,10 +1,9 @@
-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/types";
import { AdcsRpcEndpoint, AdcsTemplatesResult, callAdcsEndpoint } from "@app/lib/gateway-v2/adcs-rpc";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { ADCSConnectionMethod } from "./adcs-connection-enums";
@@ -177,7 +176,6 @@ export const resolveAdcsCaName = async (
export const validateADCSConnectionCredentials = async (
config: TADCSConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
try {
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index f406d616cd..a8035fe8ff 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -10,7 +10,6 @@ import {
validateOCIConnectionCredentials
} from "@app/ee/services/app-connections/oci";
import { getOracleDBConnectionListItem, OracleDBConnectionMethod } from "@app/ee/services/app-connections/oracledb";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { SECRET_ROTATION_CONNECTION_MAP } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-maps";
@@ -574,7 +573,6 @@ export const decryptAppConnectionConfiguration = async ({
export const validateAppConnectionCredentials = async (
appConnection: TAppConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
deps: {
identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;
@@ -587,8 +585,8 @@ export const validateAppConnectionCredentials = async (
const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TAppConnectionCredentialsValidator> = {
[AppConnection.AWS]: validateAwsConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Databricks]: validateDatabricksConnectionCredentials as TAppConnectionCredentialsValidator,
- [AppConnection.GitHub]: ((config: TAppConnectionConfig, gw, gw2) =>
- validateGitHubConnectionCredentials(config as TGitHubConnectionConfig, gw, gw2, {
+ [AppConnection.GitHub]: ((config: TAppConnectionConfig, gw) =>
+ validateGitHubConnectionCredentials(config as TGitHubConnectionConfig, gw, {
gitHubAppDAL: deps.gitHubAppDAL,
kmsService: deps.kmsService
})) as TAppConnectionCredentialsValidator,
@@ -686,7 +684,7 @@ export const validateAppConnectionCredentials = async (
[AppConnection.Daytona]: validateDaytonaConnectionCredentials as TAppConnectionCredentialsValidator
};
- return VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[appConnection.app](appConnection, gatewayService, gatewayV2Service);
+ return VALIDATE_APP_CONNECTION_CREDENTIALS_MAP[appConnection.app](appConnection, gatewayV2Service);
};
export const getAppConnectionMethodName = (method: TAppConnection["method"]) => {
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index a01140feb2..5778c80061 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -7,8 +7,6 @@ import { chefConnectionService } from "@app/ee/services/app-connections/chef/che
import { ValidateOCIConnectionCredentialsSchema } from "@app/ee/services/app-connections/oci";
import { ociConnectionService } from "@app/ee/services/app-connections/oci/oci-connection-service";
import { 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";
@@ -207,13 +205,11 @@ export type TAppConnectionServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<
TGatewayPoolServiceFactory,
"resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId" | "runWithPoolFailover"
>;
- gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
projectDAL: Pick<TProjectDALFactory, "findProjectById">;
appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;
@@ -316,10 +312,8 @@ export const appConnectionServiceFactory = ({
permissionService,
kmsService,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
- gatewayDAL,
gatewayV2DAL,
projectDAL,
appConnectionCredentialRotationService,
@@ -567,9 +561,8 @@ export const appConnectionServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: actor.orgId });
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actor.orgId });
- if (!gateway && !gatewayV2) {
+ if (!gatewayV2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found for org`
});
@@ -610,7 +603,6 @@ export const appConnectionServiceFactory = ({
gatewayId: validationGatewayId,
projectType: project?.type
} as TAppConnectionConfig,
- gatewayService,
gatewayV2Service,
{ identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }
);
@@ -699,7 +691,6 @@ export const appConnectionServiceFactory = ({
gatewayId: validationGatewayId
} as TAppConnectionConfig,
(platformCredentials) => createConnection(platformCredentials),
- gatewayService,
gatewayV2Service
);
} else {
@@ -794,9 +785,8 @@ export const appConnectionServiceFactory = ({
);
if (gatewayId) {
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: actor.orgId });
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: actor.orgId });
- if (!gateway && !gatewayV2) {
+ if (!gatewayV2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found for org`
});
@@ -901,7 +891,6 @@ export const appConnectionServiceFactory = ({
gatewayId: validationGatewayId,
projectType: updateProject?.type
} as TAppConnectionConfig,
- gatewayService,
gatewayV2Service,
{ identityUaDAL, gitHubAppDAL, kmsService, keyStore, actorId: actor.id }
);
@@ -986,7 +975,6 @@ export const appConnectionServiceFactory = ({
gatewayId: validationGatewayIdForUpdate
} as TAppConnectionConfig,
(platformCredentials) => updateConnection(platformCredentials, tx),
- gatewayService,
gatewayV2Service
);
} else {
@@ -1368,7 +1356,7 @@ export const appConnectionServiceFactory = ({
listAvailableAppConnectionsForUser,
findAppConnectionUsageById,
triggerCredentialRotation,
- github: githubConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service, gatewayPoolService, {
+ github: githubConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService, {
gitHubAppDAL,
kmsService
}),
@@ -1387,7 +1375,7 @@ export const appConnectionServiceFactory = ({
azureDevOps: azureDevOpsConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
auth0: auth0ConnectionService(connectAppConnectionById, appConnectionDAL, kmsService),
salesforce: salesforceConnectionService(connectAppConnectionById),
- hcvault: hcVaultConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service, gatewayPoolService),
+ hcvault: hcVaultConnectionService(connectAppConnectionById, 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.ts
index 27a67e730c..6b452f508b 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -15,7 +15,6 @@ import {
TOracleDBConnectionInput,
TValidateOracleDBConnectionCredentialsSchema
} from "@app/ee/services/app-connections/oracledb";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { TSqlConnectionConfig } from "@app/services/app-connection/shared/sql/sql-connection-types";
@@ -917,14 +916,12 @@ export type TListAwsConnectionListeners = {
export type TAppConnectionCredentialsValidator = (
appConnection: TAppConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => Promise<TAppConnection["credentials"]>;
export type TAppConnectionTransitionCredentialsToPlatform = (
appConnection: TAppConnectionConfig,
callback: (credentials: TAppConnection["credentials"]) => Promise<TAppConnectionRaw>,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => Promise<TAppConnectionRaw>;
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
index 833cde9403..8270541235 100644
--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
@@ -3,14 +3,14 @@ import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
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 { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import {
@@ -43,7 +43,6 @@ import {
*/
export const requestWithAzureKeyVaultGateway = async <T>(
connection: { gatewayId?: string | null; gatewayPoolId?: string | null },
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
requestConfig: AxiosRequestConfig,
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
@@ -74,61 +73,18 @@ export const requestWithAzureKeyVaultGateway = async <T>(
// eslint-disable-next-line no-nested-ternary
const targetPort = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
- // try gateway v2 first, then fall back to gateway v1
const gatewayConnectionDetailsV2 = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost,
targetPort
});
- if (gatewayConnectionDetailsV2) {
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const isHttps = url.protocol === "https:";
-
- url.host = `localhost:${proxyPort}`;
-
- const finalRequestConfig: AxiosRequestConfig = {
- ...requestConfig,
- url: url.toString(),
- headers: {
- ...requestConfig.headers,
- Host: targetHost
- },
- ...(isHttps && {
- httpsAgent: new https.Agent({
- servername: targetHost
- })
- })
- };
-
- try {
- return await request.request(finalRequestConfig);
- } catch (error) {
- if (error instanceof AxiosError) {
- logger.error(
- {
- error,
- message: error.message,
- data: (error.response as undefined | { data: unknown })?.data,
- url: url.toString()
- },
- "Error during Azure Key Vault gateway v2 request:"
- );
- }
- throw error;
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- ...gatewayConnectionDetailsV2
- }
- );
+ // Falling through here would silently bypass the gateway this connection is pinned to.
+ if (!gatewayConnectionDetailsV2) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
- const gatewayConnectionDetailsV1 = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
-
- return withGatewayProxy(
+ return withGatewayV2Proxy(
async (proxyPort) => {
const isHttps = url.protocol === "https:";
@@ -159,17 +115,15 @@ export const requestWithAzureKeyVaultGateway = async <T>(
data: (error.response as undefined | { data: unknown })?.data,
url: url.toString()
},
- "Error during Azure Key Vault gateway v1 request:"
+ "Error during Azure Key Vault gateway request:"
);
}
throw error;
}
},
{
- relayDetails: gatewayConnectionDetailsV1,
protocol: GatewayProxyProtocol.Tcp,
- targetHost,
- targetPort
+ ...gatewayConnectionDetailsV2
}
);
};
diff --git a/backend/src/services/app-connection/f5-big-ip/f5-big-ip-connection-fns.ts b/backend/src/services/app-connection/f5-big-ip/f5-big-ip-connection-fns.ts
index b8750a0bf3..50739aef82 100644
--- a/backend/src/services/app-connection/f5-big-ip/f5-big-ip-connection-fns.ts
+++ b/backend/src/services/app-connection/f5-big-ip/f5-big-ip-connection-fns.ts
@@ -1,12 +1,11 @@
import { AxiosRequestConfig } from "axios";
import https from "https";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -98,7 +97,6 @@ type TF5BigIpLoginResponse = {
export const validateF5BigIpConnectionCredentials = async (
config: TF5BigIpConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { hostname, port, username, password } = config.credentials;
diff --git a/backend/src/services/app-connection/github/github-connection-fns.test.ts b/backend/src/services/app-connection/github/github-connection-fns.test.ts
index b54646265a..be99dcb8b4 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.test.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.test.ts
@@ -24,8 +24,7 @@ vi.mock("@app/lib/logger", () => ({
logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
}));
vi.mock("@app/lib/crypto", () => ({ crypto: {} }));
-vi.mock("@app/lib/gateway", () => ({
- withGatewayProxy: vi.fn(),
+vi.mock("@app/lib/gateway-v2/types", () => ({
GatewayProxyProtocol: { Tcp: "tcp", Http: "http" }
}));
vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({ withGatewayV2Proxy: vi.fn() }));
@@ -46,7 +45,7 @@ describe("requestWithGitHubGateway — non-gateway request handling", () => {
});
it("routes the non-gateway request through safeRequest (host-validated + IP-pinned + no redirects)", async () => {
- await requestWithGitHubGateway({ gatewayId: null }, {} as any, {} as any, {
+ await requestWithGitHubGateway({ gatewayId: null }, {} as any, {
url: "https://api.github.com/user/repos",
method: "GET"
});
@@ -58,9 +57,9 @@ describe("requestWithGitHubGateway — non-gateway request handling", () => {
});
it("rejects a request with no URL instead of throwing a raw TypeError", async () => {
- await expect(
- requestWithGitHubGateway({ gatewayId: null }, {} as any, {} as any, { method: "GET" })
- ).rejects.toThrow(/missing a target URL/);
+ await expect(requestWithGitHubGateway({ gatewayId: null }, {} as any, { method: "GET" })).rejects.toThrow(
+ /missing a target URL/
+ );
expect(safeRequestMock).not.toHaveBeenCalled();
});
diff --git a/backend/src/services/app-connection/github/github-connection-fns.ts b/backend/src/services/app-connection/github/github-connection-fns.ts
index 82c2712822..dbd0490153 100644
--- a/backend/src/services/app-connection/github/github-connection-fns.ts
+++ b/backend/src/services/app-connection/github/github-connection-fns.ts
@@ -3,15 +3,15 @@ import https from "https";
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";
import { crypto } from "@app/lib/crypto";
-import { BadRequestError, ForbiddenRequestError, InternalServerError } from "@app/lib/errors";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { BadRequestError, ForbiddenRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses, safeRequest } from "@app/lib/validator";
import { getAppConnectionMethodName } from "@app/services/app-connection/app-connection-fns";
@@ -173,25 +173,27 @@ export const getGitHubGatewayConnectionDetails = async (
targetHost: string,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<Awaited<ReturnType<TGatewayV2ServiceFactory["getPlatformConnectionDetailsByGatewayId"]>> | undefined> => {
+ const urlString = targetHost.includes("://") ? targetHost : `https://${targetHost}`;
+ let hostname: string;
try {
- const urlString = targetHost.includes("://") ? targetHost : `https://${targetHost}`;
- const url = new URL(urlString);
- const { hostname } = url;
-
- return await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
- gatewayId,
- targetHost: hostname,
- targetPort: 443
- });
+ ({ hostname } = new URL(urlString));
} catch {
- // Return undefined to allow fallback to V1 gateway
- return undefined;
+ throw new BadRequestError({ message: `GitHub connection host '${targetHost}' is not a valid URL` });
}
+
+ // Deliberately unguarded: only a genuinely missing gateway may come back as undefined, because
+ // the caller renders that as "gateway not found". Swallowing the resolver's own failures here
+ // (unreachable transport, missing org gateway config) would report a healthy but offline gateway
+ // as deleted, and tell the user to remove a configuration that is fine.
+ return gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId,
+ targetHost: hostname,
+ targetPort: 443
+ });
};
export const requestWithGitHubGateway = async <T>(
appConnection: { gatewayId?: string | null },
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
requestConfig: AxiosRequestConfig,
gatewayConnectionDetails?: Awaited<ReturnType<TGatewayV2ServiceFactory["getPlatformConnectionDetailsByGatewayId"]>>
@@ -215,49 +217,17 @@ export const requestWithGitHubGateway = async <T>(
const [targetHost] = await verifyHostInputValidity({ host: url.host, isGateway: true, isDynamicSecret: false });
- const connectionDetails = gatewayConnectionDetails;
+ // Callers that already resolved the gateway pass the details in; the rest are resolved here, so
+ // omitting that argument cannot turn a healthy gateway into the "not found" throw below.
+ const connectionDetails =
+ gatewayConnectionDetails ?? (await getGitHubGatewayConnectionDetails(gatewayId, targetHost, gatewayV2Service));
- if (connectionDetails) {
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const httpsAgent = new https.Agent({
- servername: targetHost
- });
-
- url.protocol = "https:";
- url.host = `localhost:${proxyPort}`;
-
- const finalRequestConfig: AxiosRequestConfig = {
- ...requestConfig,
- url: url.toString(),
- httpsAgent,
- headers: {
- ...requestConfig.headers,
- Host: targetHost
- }
- };
-
- try {
- return await httpRequest.request(finalRequestConfig);
- } catch (error) {
- const axiosError = error as AxiosError;
- logger.error(
- { message: axiosError.message, data: axiosError.response?.data },
- "Error during GitHub gateway request:"
- );
- throw error;
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- ...connectionDetails
- }
- );
+ // Falling through here would silently bypass the gateway this connection is pinned to.
+ if (!connectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
-
- return withGatewayProxy(
+ return withGatewayV2Proxy(
async (proxyPort) => {
const httpsAgent = new https.Agent({
servername: targetHost
@@ -288,10 +258,8 @@ export const requestWithGitHubGateway = async <T>(
}
},
{
- relayDetails,
protocol: GatewayProxyProtocol.Tcp,
- targetHost,
- targetPort: 443
+ ...connectionDetails
}
);
};
@@ -316,7 +284,6 @@ export const buildGitHubAppJwtHeaders = (appJwt: string) => ({
export const getGitHubAppAuthToken = async (
appConnection: TGitHubConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
deps: TGitHubAppCredentialResolverDeps
@@ -368,7 +335,6 @@ export const getGitHubAppAuthToken = async (
const response = await requestWithGitHubGateway<{ token: string; expires_at: string }>(
{ gatewayId: effectiveGatewayId },
- gatewayService,
gatewayV2Service,
{
url: `https://${apiBaseUrl}/app/installations/${installationId}/access_tokens`,
@@ -406,7 +372,6 @@ function extractNextPageUrl(linkHeader: string | undefined): string | null {
export const makePaginatedGitHubRequest = async <T, R = T[]>(
appConnection: TGitHubConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
path: string,
@@ -425,7 +390,7 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(
token = credentials.personalAccessToken;
break;
default:
- token = await getGitHubAppAuthToken(appConnection, gatewayService, gatewayV2Service, gatewayPoolService, deps);
+ token = await getGitHubAppAuthToken(appConnection, gatewayV2Service, gatewayPoolService, deps);
}
const apiBaseUrl = await getGitHubInstanceApiUrl(appConnection);
@@ -447,7 +412,6 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(
// Make initial request to get link header
const firstResponse: AxiosResponse<R> = await requestWithGitHubGateway<R>(
resolvedConn,
- gatewayService,
gatewayV2Service,
{
url: initialUrlObj.toString(),
@@ -481,7 +445,6 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(
pageRequests.push(
requestWithGitHubGateway<R>(
resolvedConn,
- gatewayService,
gatewayV2Service,
{
url: pageUrlObj.toString(),
@@ -511,7 +474,6 @@ export const makePaginatedGitHubRequest = async <T, R = T[]>(
// eslint-disable-next-line no-await-in-loop
const response: AxiosResponse<R> = await requestWithGitHubGateway<R>(
resolvedConn,
- gatewayService,
gatewayV2Service,
{
url,
@@ -562,7 +524,6 @@ type GitHubEnvironment = {
export const getGitHubRepositories = async (
appConnection: TGitHubConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
deps: TGitHubAppCredentialResolverDeps
@@ -570,7 +531,6 @@ export const getGitHubRepositories = async (
if (appConnection.method === GitHubConnectionMethod.App) {
return makePaginatedGitHubRequest<GitHubRepository, { repositories: GitHubRepository[] }>(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
"/installation/repositories",
@@ -581,7 +541,6 @@ export const getGitHubRepositories = async (
const repos = await makePaginatedGitHubRequest<GitHubRepository>(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
"/user/repos",
@@ -593,7 +552,6 @@ export const getGitHubRepositories = async (
export const getGitHubOrganizations = async (
appConnection: TGitHubConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
deps: TGitHubAppCredentialResolverDeps
@@ -604,7 +562,6 @@ export const getGitHubOrganizations = async (
{ repositories: GitHubRepository[] }
>(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
"/installation/repositories",
@@ -624,7 +581,6 @@ export const getGitHubOrganizations = async (
return makePaginatedGitHubRequest<GitHubOrganization>(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
"/user/orgs",
@@ -634,7 +590,6 @@ export const getGitHubOrganizations = async (
export const getGitHubEnvironments = async (
appConnection: TGitHubConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
owner: string,
@@ -644,7 +599,6 @@ export const getGitHubEnvironments = async (
try {
return await makePaginatedGitHubRequest<GitHubEnvironment, { environments: GitHubEnvironment[] }>(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/environments`,
@@ -765,7 +719,6 @@ export const exchangeGitHubOAuthCode = async ({
export const validateGitHubConnectionCredentials = async (
config: TGitHubConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
deps: TGitHubAppCredentialResolverDeps
) => {
@@ -807,7 +760,6 @@ export const validateGitHubConnectionCredentials = async (
const apiUrl = await getGitHubInstanceApiUrl(config);
await requestWithGitHubGateway(
resolvedConfig,
- gatewayService,
gatewayV2Service,
{
url: `https://${apiUrl}/user`,
@@ -881,7 +833,6 @@ export const validateGitHubConnectionCredentials = async (
requestFn: (requestConfig) =>
requestWithGitHubGateway<GithubTokenRespData>(
resolvedConfig,
- gatewayService,
gatewayV2Service,
requestConfig,
oauthGatewayConnectionDetails
@@ -922,7 +873,6 @@ export const validateGitHubConnectionCredentials = async (
const installations = await listGitHubUserInstallations(apiBaseUrl, tokenResp.data.access_token, (requestConfig) =>
requestWithGitHubGateway<{ installations: TGitHubUserInstallation[] }>(
resolvedConfig,
- gatewayService,
gatewayV2Service,
requestConfig,
gatewayConnectionDetails
diff --git a/backend/src/services/app-connection/github/github-connection-service.ts b/backend/src/services/app-connection/github/github-connection-service.ts
index 6d5426b350..5f12c0b303 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,3 @@
-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";
@@ -25,7 +24,6 @@ type TListGitHubEnvironmentsDTO = {
export const githubConnectionService = (
getAppConnection: TGetAppConnectionFunc,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
gitHubAppDeps: TGitHubAppCredentialResolverDeps
@@ -35,7 +33,6 @@ export const githubConnectionService = (
const repositories = await getGitHubRepositories(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
gitHubAppDeps
@@ -49,7 +46,6 @@ export const githubConnectionService = (
const organizations = await getGitHubOrganizations(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
gitHubAppDeps
@@ -66,7 +62,6 @@ export const githubConnectionService = (
const environments = await getGitHubEnvironments(
appConnection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
owner,
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.ts
index 87bb444da3..844ab0df9a 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
@@ -2,16 +2,15 @@ import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
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";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
-import { GatewayVersion, TGatewayV1RelayDetails } from "@app/lib/gateway/types";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -145,7 +144,6 @@ type TokenRespData = {
export const requestWithHCVaultGateway = async <T>(
appConnection: { gatewayId?: string | null; gatewayPoolId?: string | null },
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
requestConfig: AxiosRequestConfig,
gatewayDetails?: TGatewayDetails,
@@ -171,11 +169,7 @@ export const requestWithHCVaultGateway = async <T>(
return request.request(requestConfig);
}
- let gatewayConnectionDetailsV2: TGatewayV2ConnectionDetails | undefined;
-
- if (gatewayDetails && gatewayDetails.gatewayVersion === GatewayVersion.V2) {
- gatewayConnectionDetailsV2 = gatewayDetails.details;
- }
+ let gatewayConnectionDetails: TGatewayV2ConnectionDetails | undefined = gatewayDetails?.details;
let targetHost: string;
let targetPort: number;
@@ -190,84 +184,37 @@ export const requestWithHCVaultGateway = async <T>(
targetPort = url.port ? Number(url.port) : url.protocol === "https:" ? 443 : 80;
}
- // if no gateway details are provided, we first try gateway v2, then gateway v1 as a fallback.
if (!gatewayDetails) {
- gatewayConnectionDetailsV2 = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost,
targetPort
});
}
- if (gatewayConnectionDetailsV2) {
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const isHttps = url.protocol === "https:";
-
- url.host = `localhost:${proxyPort}`;
-
- const finalRequestConfig: AxiosRequestConfig = {
- ...requestConfig,
- url: url.toString(),
- headers: {
- ...requestConfig.headers,
- Host: targetHost
- },
- ...(isHttps && {
- httpsAgent: new https.Agent({
- servername: targetHost
- })
- })
- };
-
- try {
- return await request.request(finalRequestConfig);
- } catch (error) {
- if (error instanceof AxiosError) {
- logger.error(
- {
- error,
- message: error.message,
- data: (error.response as undefined | { data: unknown })?.data,
- url: url.toString()
- },
- "Error during HashiCorp Vault gateway request:"
- );
- }
- throw error;
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- ...gatewayConnectionDetailsV2
- }
- );
- }
-
- let gatewayConnectionDetailsV1: TGatewayV1RelayDetails | undefined;
- if (gatewayDetails && gatewayDetails.gatewayVersion === GatewayVersion.V1) {
- gatewayConnectionDetailsV1 = gatewayDetails.details;
- } else {
- gatewayConnectionDetailsV1 = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
+ // Falling through here would silently bypass the gateway this connection is pinned to.
+ if (!gatewayConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
- return withGatewayProxy(
+ return withGatewayV2Proxy(
async (proxyPort) => {
- const httpsAgent = new https.Agent({
- servername: targetHost
- });
+ const isHttps = url.protocol === "https:";
- url.protocol = "https:";
url.host = `localhost:${proxyPort}`;
const finalRequestConfig: AxiosRequestConfig = {
...requestConfig,
url: url.toString(),
- httpsAgent,
headers: {
...requestConfig.headers,
Host: targetHost
- }
+ },
+ ...(isHttps && {
+ httpsAgent: new https.Agent({
+ servername: targetHost
+ })
+ })
};
try {
@@ -288,17 +235,14 @@ export const requestWithHCVaultGateway = async <T>(
}
},
{
- relayDetails: gatewayConnectionDetailsV1,
protocol: GatewayProxyProtocol.Tcp,
- targetHost,
- targetPort
+ ...gatewayConnectionDetails
}
);
};
export const getHCVaultAccessToken = async (
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
// Return access token directly if not using AppRole method
@@ -310,7 +254,7 @@ export const getHCVaultAccessToken = async (
try {
const { instanceUrl, roleId, secretId } = connection.credentials;
- const tokenResp = await requestWithHCVaultGateway<TokenRespData>(connection, gatewayService, gatewayV2Service, {
+ const tokenResp = await requestWithHCVaultGateway<TokenRespData>(connection, gatewayV2Service, {
url: `${removeTrailingSlash(instanceUrl)}/v1/auth/approle/login`,
method: "POST",
headers: {
@@ -337,16 +281,15 @@ export const getHCVaultAccessToken = async (
export const validateHCVaultConnectionCredentials = async (
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
try {
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
// Verify token
- await requestWithHCVaultGateway(connection, gatewayService, gatewayV2Service, {
+ await requestWithHCVaultGateway(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/auth/token/lookup-self`,
method: "GET",
headers: { "X-Vault-Token": accessToken }
@@ -375,12 +318,11 @@ export const validateHCVaultConnectionCredentials = async (
export const getHCVaultPolicyNames = async (
namespace: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
try {
const { data: listData } = await requestWithHCVaultGateway<{
@@ -389,7 +331,6 @@ export const getHCVaultPolicyNames = async (
};
}>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/sys/policy`,
@@ -423,21 +364,14 @@ export const getHCVaultPolicyNames = async (
export const listHCVaultPolicies = async (
namespace: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
try {
- const policyNames = await getHCVaultPolicyNames(
- namespace,
- connection,
- gatewayService,
- gatewayV2Service,
- gatewayDetails
- );
+ const policyNames = await getHCVaultPolicyNames(namespace, connection, gatewayV2Service, gatewayDetails);
const limiter = createConcurrencyLimiter(HC_VAULT_CONCURRENCY_LIMIT);
@@ -452,7 +386,6 @@ export const listHCVaultPolicies = async (
};
}>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/sys/policy/${policyName}`,
@@ -498,13 +431,11 @@ export const listHCVaultPolicies = async (
const fetchHCVaultNamespacesWithoutNamespaceHeader = async ({
connection,
- gatewayService,
gatewayV2Service,
instanceUrl,
accessToken
}: {
connection: THCVaultConnection;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
instanceUrl: string;
accessToken: string;
@@ -512,7 +443,7 @@ const fetchHCVaultNamespacesWithoutNamespaceHeader = async ({
try {
const { data } = await requestWithHCVaultGateway<{
data: { keys: string[] };
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/sys/namespaces?list=true`,
method: "GET",
headers: {
@@ -533,11 +464,10 @@ const fetchHCVaultNamespacesWithoutNamespaceHeader = async ({
export const listHCVaultNamespaces = async (
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const currentNamespace = connection.credentials.namespace || "/";
@@ -555,7 +485,7 @@ export const listHCVaultNamespaces = async (
};
};
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/sys/namespaces?list=true`,
method: "GET",
headers: {
@@ -579,7 +509,6 @@ export const listHCVaultNamespaces = async (
) {
return fetchHCVaultNamespacesWithoutNamespaceHeader({
connection,
- gatewayService,
gatewayV2Service,
instanceUrl,
accessToken
@@ -666,20 +595,18 @@ export const listHCVaultNamespaces = async (
export const listHCVaultMounts = async (
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
namespace?: string,
gatewayDetails?: TGatewayDetails
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const targetNamespace = namespace || connection.credentials.namespace;
const fetchMounts = (namespaceHeader?: string) =>
requestWithHCVaultGateway<THCVaultMountResponse>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/sys/mounts`,
@@ -748,7 +675,6 @@ const listHCVaultAccessiblePathsFromAcl = async (
instanceUrl: string,
accessToken: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
): Promise<string[]> => {
@@ -760,7 +686,6 @@ const listHCVaultAccessiblePathsFromAcl = async (
};
}>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/sys/internal/ui/resultant-acl`,
@@ -828,13 +753,12 @@ const listHCVaultAccessiblePathsFromAcl = async (
export const listHCVaultSecretPaths = async (
namespace: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
filterMountPath?: string,
gatewayDetails?: TGatewayDetails
) => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const getPaths = async (
mountPath: string,
@@ -858,7 +782,6 @@ export const listHCVaultSecretPaths = async (
};
}>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${path}?list=true`,
@@ -947,7 +870,7 @@ export const listHCVaultSecretPaths = async (
};
// Get all mounts
- const mounts = await listHCVaultMounts(connection, gatewayService, gatewayV2Service, namespace);
+ const mounts = await listHCVaultMounts(connection, gatewayV2Service, namespace);
// Filter for KV mounts (kv, kv-v1, kv-v2)
let kvMounts = mounts.filter(isKvMount);
@@ -992,7 +915,6 @@ export const listHCVaultSecretPaths = async (
instanceUrl,
accessToken,
connection,
- gatewayService,
gatewayV2Service,
gatewayDetails
);
@@ -1085,7 +1007,6 @@ const fetchVaultSecretAtPath = async ({
instanceUrl,
accessToken,
connection,
- gatewayService,
gatewayV2Service,
skipNamespaceHeader = false
}: {
@@ -1095,7 +1016,6 @@ const fetchVaultSecretAtPath = async ({
instanceUrl: string;
accessToken: string;
connection: THCVaultConnection;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
skipNamespaceHeader: boolean;
}): Promise<Record<string, JsonValue>> => {
@@ -1116,7 +1036,7 @@ const fetchVaultSecretAtPath = async ({
version: number;
};
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${mountUrlPath}/data/${actualPath}`,
method: "GET",
headers: {
@@ -1134,7 +1054,7 @@ const fetchVaultSecretAtPath = async ({
lease_duration: number;
lease_id: string;
renewable: boolean;
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${mountUrlPath}/${actualPath}`,
method: "GET",
headers: {
@@ -1178,12 +1098,11 @@ export const getHCVaultSecretsForPaths = async (
mountPath: string,
secretPaths: string[],
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<Array<{ vaultSecretPath: string; secrets: Record<string, JsonValue> }>> => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
- const mounts = await listHCVaultMounts(connection, gatewayService, gatewayV2Service, namespace);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
+ const mounts = await listHCVaultMounts(connection, gatewayV2Service, namespace);
const limiter = createConcurrencyLimiter(HC_VAULT_CONCURRENCY_LIMIT);
if (secretPaths.length === 0) {
@@ -1198,7 +1117,6 @@ export const getHCVaultSecretsForPaths = async (
instanceUrl,
accessToken,
connection,
- gatewayService,
gatewayV2Service
};
@@ -1243,17 +1161,15 @@ export const getHCVaultAuthMounts = async (
namespace: string,
authType: HCVaultAuthType | undefined,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayDetails?: TGatewayDetails
): Promise<THCVaultAuthMount[]> => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
try {
const { data } = await requestWithHCVaultGateway<THCVaultAuthMountResponse>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/sys/auth`,
@@ -1301,11 +1217,10 @@ export const getHCVaultKubernetesAuthRoles = async (
namespace: string,
mountPath: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<THCVaultKubernetesAuthRoleWithConfig[]> => {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
// Remove trailing slash from mount path
const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath;
@@ -1314,7 +1229,6 @@ export const getHCVaultKubernetesAuthRoles = async (
// 1. Get the Kubernetes auth configuration for this mount
const { data: configResponse } = await requestWithHCVaultGateway<{ data: THCVaultKubernetesAuthConfig }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/auth/${encodeURIComponent(cleanMountPath)}/config`,
@@ -1331,7 +1245,6 @@ export const getHCVaultKubernetesAuthRoles = async (
// 2. List all roles in this mount
const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/auth/${cleanMountPath}/role`,
@@ -1356,7 +1269,6 @@ export const getHCVaultKubernetesAuthRoles = async (
limiter(async () => {
const { data: roleResponse } = await requestWithHCVaultGateway<{ data: THCVaultKubernetesAuthRole }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/auth/${encodeURIComponent(cleanMountPath)}/role/${encodeURIComponent(roleName)}`,
@@ -1402,7 +1314,6 @@ export const getHCVaultKubernetesRoles = async (
namespace: string,
mountPath: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<THCVaultKubernetesRole[]> => {
// Remove trailing slash from mount path
@@ -1410,11 +1321,10 @@ export const getHCVaultKubernetesRoles = async (
try {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
// 1. Get the Kubernetes secrets engine configuration for this mount
const { data: configResponse } = await requestWithHCVaultGateway<{ data: THCVaultKubernetesSecretsConfig }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/config`,
@@ -1433,7 +1343,6 @@ export const getHCVaultKubernetesRoles = async (
try {
const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/roles?list=true`,
@@ -1474,7 +1383,7 @@ export const getHCVaultKubernetesRoles = async (
extra_annotations?: Record<string, string>;
extra_labels?: Record<string, string>;
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/roles/${encodeURIComponent(roleName)}`,
method: "GET",
headers: {
@@ -1505,7 +1414,6 @@ export const getHCVaultDatabaseRoles = async (
namespace: string,
mountPath: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<THCVaultDatabaseRole[]> => {
// Remove trailing slash from mount path
@@ -1513,14 +1421,13 @@ export const getHCVaultDatabaseRoles = async (
try {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
// 1. List all database connections in this mount to get their configs
let connectionNames: string[] = [];
try {
const { data: connectionListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/config?list=true`,
@@ -1547,7 +1454,7 @@ export const getHCVaultDatabaseRoles = async (
try {
const { data: configResponse } = await requestWithHCVaultGateway<{
data: THCVaultDatabaseConfig;
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/config/${encodeURIComponent(connName)}`,
method: "GET",
headers: {
@@ -1568,7 +1475,6 @@ export const getHCVaultDatabaseRoles = async (
try {
const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/roles?list=true`,
@@ -1601,7 +1507,7 @@ export const getHCVaultDatabaseRoles = async (
revocation_statements?: string[];
renew_statements?: string[];
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/roles/${encodeURIComponent(roleName)}`,
method: "GET",
headers: {
@@ -1642,7 +1548,6 @@ export const getHCVaultLdapRoles = async (
namespace: string,
mountPath: string,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<THCVaultLdapRole[]> => {
// Remove trailing slash from mount path
@@ -1650,12 +1555,11 @@ export const getHCVaultLdapRoles = async (
try {
const instanceUrl = await getHCVaultInstanceUrl(connection);
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
// 1. Get the LDAP secrets engine configuration for this mount
const { data: configResponse } = await requestWithHCVaultGateway<{ data: THCVaultLdapConfig }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/config`,
@@ -1674,7 +1578,6 @@ export const getHCVaultLdapRoles = async (
try {
const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(
connection,
- gatewayService,
gatewayV2Service,
{
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/role?list=true`,
@@ -1709,7 +1612,7 @@ export const getHCVaultLdapRoles = async (
rollback_ldif?: string;
username_template?: string;
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${encodeURIComponent(cleanMountPath)}/role/${encodeURIComponent(roleName)}`,
method: "GET",
headers: {
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.ts
index 0115e66508..b400e11241 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,3 @@
-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";
@@ -17,7 +16,6 @@ type TGetAppConnectionFunc = (
export const hcVaultConnectionService = (
getAppConnection: TGetAppConnectionFunc,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
) => {
@@ -30,7 +28,7 @@ export const hcVaultConnectionService = (
const resolvedConnection = { ...appConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };
try {
- const mounts = await listHCVaultMounts(resolvedConnection, gatewayService, gatewayV2Service);
+ const mounts = await listHCVaultMounts(resolvedConnection, gatewayV2Service);
// Filter for KV mounts (v1 and v2) and extract just the paths
return mounts
.filter((mount) => mount.type === "kv" && (mount.version === KvVersion.V2 || mount.version === KvVersion.V1))
diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts
index 8444bf2db0..2d6f7e0896 100644
--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts
+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts
@@ -1,7 +1,6 @@
import z from "zod";
import { TGatewayV2ConnectionDetails } from "@app/ee/services/gateway-v2/gateway-v2-types";
-import { GatewayVersion, TGatewayV1RelayDetails } from "@app/lib/gateway/types";
import { DiscriminativePick } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
@@ -167,20 +166,10 @@ export type THCVaultLdapRole = {
mountPath: string;
};
-export type TGatewayDetails =
- | {
- gatewayVersion: GatewayVersion.V1;
- details: TGatewayV1RelayDetails;
- target: {
- host: string;
- port: number;
- };
- }
- | {
- gatewayVersion: GatewayVersion.V2;
- details: TGatewayV2ConnectionDetails;
- target: {
- host: string;
- port: number;
- };
- };
+export type TGatewayDetails = {
+ details: TGatewayV2ConnectionDetails;
+ target: {
+ host: string;
+ port: number;
+ };
+};
diff --git a/backend/src/services/app-connection/kemp-loadmaster/kemp-loadmaster-connection-fns.ts b/backend/src/services/app-connection/kemp-loadmaster/kemp-loadmaster-connection-fns.ts
index db8878f679..c9db00349a 100644
--- a/backend/src/services/app-connection/kemp-loadmaster/kemp-loadmaster-connection-fns.ts
+++ b/backend/src/services/app-connection/kemp-loadmaster/kemp-loadmaster-connection-fns.ts
@@ -2,13 +2,12 @@ import { AxiosError, AxiosRequestConfig } from "axios";
import { XMLParser } from "fast-xml-parser";
import https from "https";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { safeRequest } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -193,7 +192,6 @@ export const listKempVirtualServices = async (
export const validateKempLoadMasterConnectionCredentials = async (
config: TKempLoadMasterConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { credentials } = config;
diff --git a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts b/backend/src/services/app-connection/ldap/ldap-connection-fns.ts
index 552548b8f4..b6180469ef 100644
--- a/backend/src/services/app-connection/ldap/ldap-connection-fns.ts
+++ b/backend/src/services/app-connection/ldap/ldap-connection-fns.ts
@@ -2,13 +2,12 @@ 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";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -298,7 +297,6 @@ export const executeWithPotentialGateway = async <T>(
export const validateLdapConnectionCredentials = async (
config: TLdapConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
try {
diff --git a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
index 05388c6a2c..eae7912db4 100644
--- a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
+++ b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.ts
@@ -1,12 +1,11 @@
import { AxiosRequestConfig } from "axios";
import https from "https";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -94,7 +93,6 @@ const requestWithNetScalerGateway = async <T>(
export const validateNetScalerConnectionCredentials = async (
config: TNetScalerConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { hostname, port, username, password } = config.credentials;
diff --git a/backend/src/services/app-connection/nutanix-prism-central/nutanix-prism-central-connection-fns.ts b/backend/src/services/app-connection/nutanix-prism-central/nutanix-prism-central-connection-fns.ts
index 2948698ffe..7abf9e7153 100644
--- a/backend/src/services/app-connection/nutanix-prism-central/nutanix-prism-central-connection-fns.ts
+++ b/backend/src/services/app-connection/nutanix-prism-central/nutanix-prism-central-connection-fns.ts
@@ -2,12 +2,11 @@ import { AxiosRequestConfig } from "axios";
import crypto from "crypto";
import https from "https";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { blockLocalAndPrivateIpAddresses, buildSsrfSafeAgent } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -140,7 +139,6 @@ export const executeNutanixOperationWithGateway = async <T>(
export const validateNutanixPrismCentralConnectionCredentials = async (
config: TNutanixPrismCentralConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { credentials } = config;
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.ts
index 7835b165d3..e3a7c66c46 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
@@ -3,7 +3,6 @@ import knex, { Knex } from "knex";
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 {
@@ -11,9 +10,10 @@ import {
TSqlCredentialsRotationWithConnection
} from "@app/ee/services/secret-rotation-v2/shared/sql-credentials/sql-credentials-rotation-types";
import { getConfig } from "@app/lib/config/env";
-import { BadRequestError, DatabaseError } from "@app/lib/errors";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TAppConnectionRaw, TSqlConnection } from "@app/services/app-connection/app-connection-types";
@@ -150,7 +150,6 @@ export const getSqlConnectionClient = async (appConnection: Pick<TSqlConnection,
export const executeWithPotentialGateway = async <T>(
config: TSqlConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
operation: (client: Knex) => Promise<T>,
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
@@ -167,7 +166,7 @@ export const executeWithPotentialGateway = async <T>(
? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })
: directGatewayId;
- if (gatewayId && gatewayService && gatewayV2Service) {
+ if (gatewayId && gatewayV2Service) {
const [targetHost] = await verifyHostInputValidity({
host: credentials.host,
isGateway: true,
@@ -179,6 +178,12 @@ export const executeWithPotentialGateway = async <T>(
targetPort: credentials.port
});
+ // Falling through to the direct path here would silently bypass the gateway the connection is
+ // pinned to and dial the target host from the platform instead.
+ if (!platformConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
+ }
+
const createClient = (proxyPort: number): Knex => {
const { database, username, password } = credentials;
if (isOracleWalletConnection(app)) {
@@ -199,26 +204,7 @@ export const executeWithPotentialGateway = async <T>(
});
};
- if (platformConnectionDetails) {
- return withGatewayV2Proxy(
- async (proxyPort) => {
- const client = createClient(proxyPort);
- try {
- return await operation(client);
- } finally {
- await client.destroy();
- }
- },
- {
- protocol: GatewayProxyProtocol.Tcp,
- ...platformConnectionDetails
- }
- );
- }
-
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
-
- return withGatewayProxy(
+ return withGatewayV2Proxy(
async (proxyPort) => {
const client = createClient(proxyPort);
try {
@@ -228,10 +214,8 @@ export const executeWithPotentialGateway = async <T>(
}
},
{
- relayDetails,
protocol: GatewayProxyProtocol.Tcp,
- targetHost: app === AppConnection.Postgres ? targetHost : credentials.host,
- targetPort: credentials.port
+ ...platformConnectionDetails
}
);
}
@@ -247,11 +231,10 @@ export const executeWithPotentialGateway = async <T>(
export const validateSqlConnectionCredentials = async (
config: TSqlConnectionConfig,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
try {
- await executeWithPotentialGateway(config, gatewayService, gatewayV2Service, async (client) => {
+ await executeWithPotentialGateway(config, gatewayV2Service, async (client) => {
await client.raw(getSqlConnectionVerifyQuery(config.app));
});
return config.credentials;
@@ -292,7 +275,6 @@ export const SQL_CONNECTION_ALTER_LOGIN_STATEMENT: Record<
export const transferSqlConnectionCredentialsToPlatform = async (
config: TSqlConnectionConfig,
callback: (credentials: TSqlConnectionConfig["credentials"]) => Promise<TAppConnectionRaw>,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { credentials, app } = config;
@@ -300,7 +282,7 @@ export const transferSqlConnectionCredentialsToPlatform = async (
const newPassword = alphaNumericNanoId(32);
try {
- return await executeWithPotentialGateway(config, gatewayService, gatewayV2Service, (client) => {
+ return await executeWithPotentialGateway(config, gatewayV2Service, (client) => {
return client.transaction(async (tx) => {
const filteredUsername = getRoleUsernameForHost(credentials.username, credentials.host);
diff --git a/backend/src/services/app-connection/smb/smb-connection-fns.ts b/backend/src/services/app-connection/smb/smb-connection-fns.ts
index 09618e59f8..1d3d63c54d 100644
--- a/backend/src/services/app-connection/smb/smb-connection-fns.ts
+++ b/backend/src/services/app-connection/smb/smb-connection-fns.ts
@@ -1,9 +1,8 @@
-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";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { verifyWindowsCredentials } from "@app/lib/smb-rpc";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -68,7 +67,6 @@ export const executeSmbWithPotentialGateway = async <T>(
export const validateSmbConnectionCredentials = async (
config: TSmbConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
try {
diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
index 45fce9bdbe..f53c7222ae 100644
--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
@@ -1,12 +1,11 @@
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";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callSshExec, SshExecAuthMethod, SshExecCredentials, SshExecResult } from "@app/lib/gateway-v2/ssh-rpc";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -416,7 +415,6 @@ export const executeSshCommand = async (
export const validateSshConnectionCredentials = async (
config: TSshConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { credentials } = config;
diff --git a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
index e56b9d1916..f33ee73907 100644
--- a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
+++ b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.ts
@@ -6,8 +6,8 @@ import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator/validate-url";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
diff --git a/backend/src/services/app-connection/winrm/winrm-connection-fns.ts b/backend/src/services/app-connection/winrm/winrm-connection-fns.ts
index 4cd5046c78..62e7520e6e 100644
--- a/backend/src/services/app-connection/winrm/winrm-connection-fns.ts
+++ b/backend/src/services/app-connection/winrm/winrm-connection-fns.ts
@@ -1,9 +1,8 @@
-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/types";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { callWinRmEndpoint, WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -112,7 +111,6 @@ export const executeWinRMGatewayOperation = async <T>(
export const validateWinRMConnectionCredentials = async (
config: TWinRMConnectionConfig,
- _gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
try {
diff --git a/backend/src/services/external-migration/external-migration-fns/vault.ts b/backend/src/services/external-migration/external-migration-fns/vault.ts
index 8f516c6994..1f425c1163 100644
--- a/backend/src/services/external-migration/external-migration-fns/vault.ts
+++ b/backend/src/services/external-migration/external-migration-fns/vault.ts
@@ -3,11 +3,11 @@ import https from "node:https";
import axios, { AxiosInstance, isAxiosError } from "axios";
import { v4 as uuidv4 } from "uuid";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
-import { BadRequestError } from "@app/lib/errors";
-import { GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses, isValidFolderName } from "@app/lib/validator";
@@ -21,10 +21,7 @@ type VaultData = {
secretData: Record<string, string>;
};
-const vaultFactory = (
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
- gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
-) => {
+const vaultFactory = (gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">) => {
const $gatewayProxyWrapper = async <T>(
inputs: {
gatewayId: string;
@@ -42,27 +39,21 @@ const vaultFactory = (
targetPort
});
- if (gatewayV2Details) {
- const isHttps = targetProtocol === "https";
- const httpsAgent = isHttps ? new https.Agent({ servername: targetHostname }) : undefined;
-
- return withGatewayV2Proxy(
- async (port) => gatewayCallback(`${targetProtocol}://localhost`, port, httpsAgent, targetHostname),
- {
- protocol: GatewayProxyProtocol.Tcp,
- ...gatewayV2Details
- }
- );
+ // Falling through here would silently bypass the gateway this migration is pinned to.
+ if (!gatewayV2Details) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(gatewayId) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(gatewayId);
+ const isHttps = targetProtocol === "https";
+ const httpsAgent = isHttps ? new https.Agent({ servername: targetHostname }) : undefined;
- return withGatewayProxy(async (port, httpsAgent) => gatewayCallback("http://localhost", port, httpsAgent), {
- protocol: GatewayProxyProtocol.Http,
- targetHost: `${targetProtocol}://${targetHostname}`,
- targetPort,
- relayDetails
- });
+ return withGatewayV2Proxy(
+ async (port) => gatewayCallback(`${targetProtocol}://localhost`, port, httpsAgent, targetHostname),
+ {
+ protocol: GatewayProxyProtocol.Tcp,
+ ...gatewayV2Details
+ }
+ );
};
const getMounts = async (request: AxiosInstance) => {
@@ -558,10 +549,8 @@ export const importVaultDataFn = async (
orgId: string;
},
{
- gatewayService,
gatewayV2Service
}: {
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
}
) => {
@@ -592,7 +581,7 @@ export const importVaultDataFn = async (
`[importVaultDataFn]: Running ${orgId in vaultMigrationTransformMappings ? "custom" : "default"} transform`
);
- const vaultApi = vaultFactory(gatewayService, gatewayV2Service);
+ const vaultApi = vaultFactory(gatewayV2Service);
const vaultData = await vaultApi.collectVaultData({
accessToken: vaultAccessToken,
diff --git a/backend/src/services/external-migration/external-migration-service.test.ts b/backend/src/services/external-migration/external-migration-service.test.ts
index 6ce3a918a6..aba3d95cb0 100644
--- a/backend/src/services/external-migration/external-migration-service.test.ts
+++ b/backend/src/services/external-migration/external-migration-service.test.ts
@@ -90,9 +90,7 @@ const buildService = ({ approvalPaths = [] as string[] } = {}) => {
secretService: { createManySecretsRaw },
auditLogService: { createAuditLog: vi.fn().mockResolvedValue(undefined) },
externalMigrationQueue: { enqueueVaultImportSideEffects: vi.fn().mockResolvedValue(undefined) },
- gatewayService: {},
gatewayV2Service: {},
- gatewayDAL: {},
gatewayV2DAL: {},
gatewayPoolService: {},
userDAL: {}
diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.ts
index b3bc7fb7c0..4519f02007 100644
--- a/backend/src/services/external-migration/external-migration-service.ts
+++ b/backend/src/services/external-migration/external-migration-service.ts
@@ -8,8 +8,6 @@ import {
TAuditLogServiceFactory
} from "@app/ee/services/audit-log/audit-log-types";
import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
-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";
@@ -22,7 +20,6 @@ import {
} from "@app/ee/services/permission/project-permission";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { GatewayVersion } from "@app/lib/gateway/types";
import { logger } from "@app/lib/logger";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
import { OrgServiceActor } from "@app/lib/types";
@@ -161,9 +158,7 @@ type TExternalMigrationServiceFactoryDep = {
"connectAppConnectionById" | "validateAppConnectionUsageById"
>;
userDAL: Pick<TUserDALFactory, "findById">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
- gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
gatewayPoolService: Pick<
TGatewayPoolServiceFactory,
@@ -180,9 +175,7 @@ export const externalMigrationServiceFactory = ({
permissionService,
externalMigrationQueue,
userDAL,
- gatewayService,
gatewayV2Service,
- gatewayDAL,
gatewayV2DAL,
gatewayPoolService,
secretService,
@@ -221,25 +214,12 @@ export const externalMigrationServiceFactory = ({
if (gatewayV2Details) {
gatewayDetails = {
- gatewayVersion: GatewayVersion.V2,
details: gatewayV2Details,
target: {
host: targetHost,
port: targetPort
}
};
- } else {
- const gatewayV1Details = await gatewayService.fnGetGatewayClientTlsByGatewayId(effectiveGatewayId);
- if (gatewayV1Details) {
- gatewayDetails = {
- gatewayVersion: GatewayVersion.V1,
- details: gatewayV1Details,
- target: {
- host: targetHost,
- port: targetPort
- }
- };
- }
}
}
@@ -329,13 +309,10 @@ export const externalMigrationServiceFactory = ({
let effectiveGatewayId: string | null = gatewayId ?? null;
if (gatewayId) {
- const [gateway, gatewayV2] = await Promise.all([
- gatewayDAL.find({ id: gatewayId, orgId: actorOrgId }, { limit: 1 }),
- gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId }, { limit: 1 })
- ]);
+ const gatewayV2 = await gatewayV2DAL.find({ id: gatewayId, orgId: actorOrgId }, { limit: 1 });
// Ensure gatewayId is part of the actor's org
- if (!gateway.length && !gatewayV2.length) {
+ if (!gatewayV2.length) {
throw new NotFoundError({ message: `Gateway with ID ${gatewayId} not found` });
}
}
@@ -360,7 +337,6 @@ export const externalMigrationServiceFactory = ({
orgId: actorOrgId
},
{
- gatewayService,
gatewayV2Service
}
);
@@ -422,7 +398,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return listHCVaultNamespaces(connection, gatewayService, gatewayV2Service);
+ return listHCVaultNamespaces(connection, gatewayV2Service);
};
const getVaultPolicies = async ({
@@ -442,7 +418,7 @@ export const externalMigrationServiceFactory = ({
const gatewayDetails = await getGatewayDetails(connection);
- return listHCVaultPolicies(namespace, connection, gatewayService, gatewayV2Service, gatewayDetails);
+ return listHCVaultPolicies(namespace, connection, gatewayV2Service, gatewayDetails);
};
const getVaultMounts = async ({
@@ -462,7 +438,7 @@ export const externalMigrationServiceFactory = ({
const gatewayDetails = await getGatewayDetails(connection);
- return listHCVaultMounts(connection, gatewayService, gatewayV2Service, namespace, gatewayDetails);
+ return listHCVaultMounts(connection, gatewayV2Service, namespace, gatewayDetails);
};
const getVaultSecretPaths = async ({
@@ -484,7 +460,7 @@ export const externalMigrationServiceFactory = ({
const gatewayDetails = await getGatewayDetails(connection);
- return listHCVaultSecretPaths(namespace, connection, gatewayService, gatewayV2Service, mountPath, gatewayDetails);
+ return listHCVaultSecretPaths(namespace, connection, gatewayV2Service, mountPath, gatewayDetails);
};
const $importVaultSecretsPreservingStructure = async ({
@@ -727,7 +703,6 @@ export const externalMigrationServiceFactory = ({
mountPath,
uniqueVaultSecretPaths,
connection,
- gatewayService,
gatewayV2Service
);
@@ -846,7 +821,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return getHCVaultAuthMounts(namespace, authType as HCVaultAuthType, connection, gatewayService, gatewayV2Service);
+ return getHCVaultAuthMounts(namespace, authType as HCVaultAuthType, connection, gatewayV2Service);
};
const getVaultKubernetesAuthRoles = async ({
@@ -865,7 +840,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return getHCVaultKubernetesAuthRoles(namespace, mountPath, connection, gatewayService, gatewayV2Service);
+ return getHCVaultKubernetesAuthRoles(namespace, mountPath, connection, gatewayV2Service);
};
const getVaultKubernetesRoles = async ({
@@ -884,7 +859,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return getHCVaultKubernetesRoles(namespace, mountPath, connection, gatewayService, gatewayV2Service);
+ return getHCVaultKubernetesRoles(namespace, mountPath, connection, gatewayV2Service);
};
const getVaultDatabaseRoles = async ({
@@ -903,7 +878,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return getHCVaultDatabaseRoles(namespace, mountPath, connection, gatewayService, gatewayV2Service);
+ return getHCVaultDatabaseRoles(namespace, mountPath, connection, gatewayV2Service);
};
const getVaultLdapRoles = async ({
@@ -922,7 +897,7 @@ export const externalMigrationServiceFactory = ({
connectionId,
actor
);
- return getHCVaultLdapRoles(namespace, mountPath, connection, gatewayService, gatewayV2Service);
+ return getHCVaultLdapRoles(namespace, mountPath, connection, gatewayV2Service);
};
// ─── Doppler In-Platform Migration ──────────────────────────────────────────
diff --git a/backend/src/services/github-app/github-app-service.ts b/backend/src/services/github-app/github-app-service.ts
index 3b13526b2a..9b028ac06f 100644
--- a/backend/src/services/github-app/github-app-service.ts
+++ b/backend/src/services/github-app/github-app-service.ts
@@ -3,8 +3,6 @@ import { AxiosError, AxiosRequestConfig } from "axios";
import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
-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";
@@ -59,13 +57,11 @@ type TGitHubAppServiceFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<
TGatewayPoolServiceFactory,
"resolveAttachableGatewayFromPool" | "resolveEffectiveGatewayId"
>;
- gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
userDAL: Pick<TUserDALFactory, "findById">;
@@ -79,10 +75,8 @@ export const gitHubAppServiceFactory = ({
kmsService,
keyStore,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
- gatewayDAL,
gatewayV2DAL,
auditLogService,
userDAL
@@ -151,9 +145,8 @@ export const gitHubAppServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: orgPermission.orgId });
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: orgPermission.orgId });
- if (!gateway && !gatewayV2) {
+ if (!gatewayV2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found for org`
});
@@ -585,7 +578,6 @@ export const gitHubAppServiceFactory = ({
const { data } = effectiveGatewayId
? await requestWithGitHubGateway<TGitHubAppManifestResponse>(
{ gatewayId: effectiveGatewayId },
- gatewayService,
gatewayV2Service,
requestConfig,
await getGitHubGatewayConnectionDetails(effectiveGatewayId, apiBaseUrl, gatewayV2Service)
diff --git a/backend/src/services/hsm-connector/hsm-connector-routing.ts b/backend/src/services/hsm-connector/hsm-connector-routing.ts
index ff6fb59878..83fad50c3e 100644
--- a/backend/src/services/hsm-connector/hsm-connector-routing.ts
+++ b/backend/src/services/hsm-connector/hsm-connector-routing.ts
@@ -1,9 +1,9 @@
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
-import { GatewayProxyProtocol } from "@app/lib/gateway/types";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callPkcs11Endpoint, isRetryablePkcs11RpcError, Pkcs11RpcEndpoint } from "@app/lib/gateway-v2/pkcs11-rpc";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import {
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
index 70e2c99fe7..1acaf1012d 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts
@@ -129,9 +129,7 @@ const createService = ({
decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
})
},
- gatewayService: {},
gatewayV2Service: {},
- gatewayDAL: { find: vi.fn().mockResolvedValue([]) },
gatewayV2DAL: { find: vi.fn().mockResolvedValue([]) },
gatewayPoolService: { pickHealthyGateway: vi.fn(), runWithPoolFailover: vi.fn() },
gatewayPoolDAL: { findById: vi.fn().mockResolvedValue(null) },
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 604edf3e93..898c94085d 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -13,8 +13,6 @@ import {
TIdentityKubernetesAuthsUpdate
} from "@app/db/schemas";
import { TIdentityAuthTemplates } from "@app/db/schemas/identity-auth-templates";
-import { TGatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";
-import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
@@ -47,8 +45,9 @@ import {
PermissionBoundaryError,
UnauthorizedError
} from "@app/lib/errors";
-import { GatewayHttpProxyActions, GatewayProxyProtocol, withGatewayProxy } from "@app/lib/gateway";
+import { getMissingGatewayMessage, getRetiredGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
@@ -116,9 +115,7 @@ type TIdentityKubernetesAuthServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayService: TGatewayServiceFactory;
gatewayV2Service: TGatewayV2ServiceFactory;
- gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "pickHealthyGateway" | "runWithPoolFailover">;
gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
@@ -133,6 +130,17 @@ export type TIdentityKubernetesAuthServiceFactory = ReturnType<typeof identityKu
const GATEWAY_AUTH_DEFAULT_HOST = "https://kubernetes.default.svc.cluster.local";
+// The retired gateway v1 `gatewayId` column is still populated on rows that were pinned to a v1
+// gateway. Nothing can resolve it any more, but it still means "this must not be dialed directly",
+// so every gateway-or-direct decision has to treat it as a configured gateway and fail closed.
+// Reading only gatewayV2Id/gatewayPoolId would send the token reviewer JWT straight to the
+// customer's Kubernetes API server from the platform.
+const isPinnedToRetiredGateway = (row: {
+ gatewayId?: string | null;
+ gatewayV2Id?: string | null;
+ gatewayPoolId?: string | null;
+}) => Boolean(row.gatewayId) && !row.gatewayV2Id && !row.gatewayPoolId;
+
export const identityKubernetesAuthServiceFactory = ({
identityDAL,
identityKubernetesAuthDAL,
@@ -142,9 +150,7 @@ export const identityKubernetesAuthServiceFactory = ({
identityAccessTokenDAL,
permissionService,
licenseService,
- gatewayService,
gatewayV2Service,
- gatewayDAL,
gatewayV2DAL,
kmsService,
gatewayPoolService,
@@ -190,7 +196,6 @@ export const identityKubernetesAuthServiceFactory = ({
}
);
- // Pools are gateway-v2 only, so there is no v1 fallback to preserve on this branch.
if (inputs.gatewayPoolId) {
const { result } = await gatewayPoolService.runWithPoolFailover(
{ poolId: inputs.gatewayPoolId },
@@ -215,32 +220,12 @@ export const identityKubernetesAuthServiceFactory = ({
targetPort: inputs.targetPort ?? 443
});
- if (gatewayV2ConnectionDetails) {
- return $proxyThroughGatewayV2(gatewayV2ConnectionDetails);
+ // Falling through here would silently bypass the gateway this auth method is pinned to.
+ if (!gatewayV2ConnectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(inputs.gatewayId!) });
}
- const relayDetails = await gatewayService.fnGetGatewayClientTlsByGatewayId(inputs.gatewayId!);
-
- const callbackResult = await withGatewayProxy(
- async (port, httpsAgent) => {
- const res = await gatewayCallback(
- inputs.reviewTokenThroughGateway ? "http://localhost" : "https://localhost",
- port,
- httpsAgent
- );
- return res;
- },
- {
- protocol: inputs.reviewTokenThroughGateway ? GatewayProxyProtocol.Http : GatewayProxyProtocol.Tcp,
- targetHost: inputs.targetHost,
- targetPort: inputs.targetPort,
- relayDetails,
- // only needed for TCP protocol, because the gateway as reviewer will use the pod's CA cert for auth directly
- ...(gatewayHttpsAgent ? { httpsAgent: gatewayHttpsAgent } : {})
- }
- );
-
- return callbackResult;
+ return $proxyThroughGatewayV2(gatewayV2ConnectionDetails);
};
/**
@@ -336,6 +321,10 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
+ if (isPinnedToRetiredGateway(identityKubernetesAuth)) {
+ throw new BadRequestError({ message: getRetiredGatewayMessage("This Kubernetes auth method") });
+ }
+
const identity = await requestMemoize(requestMemoKeys.identityFindById(identityKubernetesAuth.identityId), () =>
identityDAL.findById(identityKubernetesAuth.identityId)
);
@@ -472,10 +461,7 @@ export const identityKubernetesAuthServiceFactory = ({
const tokenReviewCallbackThroughGateway = async (host: string, port?: number) => {
// localPort is the correlation key into the gatewayTunnel:* lines, which carry the tunnel id
// and outlive this request: the tunnel is torn down after the response is already logged.
- const gatewayIdForLog =
- identityKubernetesAuth.gatewayV2Id ??
- identityKubernetesAuth.gatewayId ??
- identityKubernetesAuth.gatewayPoolId;
+ const gatewayIdForLog = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayPoolId;
logger.info(
{ host, port },
`tokenReviewCallbackThroughGateway: Processing kubernetes token review using gateway [identityId=${identityKubernetesAuth.identityId}] [gatewayId=${gatewayIdForLog}] [localPort=${port}]`
@@ -537,11 +523,7 @@ export const identityKubernetesAuthServiceFactory = ({
let data: TCreateTokenReviewResponse | undefined;
if (identityKubernetesAuth.tokenReviewMode === IdentityKubernetesAuthTokenReviewMode.Gateway) {
- if (
- !identityKubernetesAuth.gatewayId &&
- !identityKubernetesAuth.gatewayV2Id &&
- !identityKubernetesAuth.gatewayPoolId
- ) {
+ if (!identityKubernetesAuth.gatewayV2Id && !identityKubernetesAuth.gatewayPoolId) {
throw new BadRequestError({
message: "Gateway or Gateway Pool is required when token review mode is set to Gateway"
});
@@ -551,7 +533,7 @@ export const identityKubernetesAuthServiceFactory = ({
{
gatewayId: identityKubernetesAuth.gatewayPoolId
? undefined
- : ((identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string),
+ : (identityKubernetesAuth.gatewayV2Id as string),
gatewayPoolId: identityKubernetesAuth.gatewayPoolId ?? undefined,
caCert: caCert || undefined,
verifyTlsCertificate: identityKubernetesAuth.verifyTlsCertificate,
@@ -573,17 +555,14 @@ export const identityKubernetesAuthServiceFactory = ({
const [k8sHost, k8sPort] = kubernetesHost.split(":");
- const hasGateway =
- identityKubernetesAuth.gatewayId ||
- identityKubernetesAuth.gatewayV2Id ||
- identityKubernetesAuth.gatewayPoolId;
+ const hasGateway = identityKubernetesAuth.gatewayV2Id || identityKubernetesAuth.gatewayPoolId;
data = hasGateway
? await $gatewayProxyWrapper(
{
gatewayId: identityKubernetesAuth.gatewayPoolId
? undefined
- : ((identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string),
+ : (identityKubernetesAuth.gatewayV2Id as string),
gatewayPoolId: identityKubernetesAuth.gatewayPoolId ?? undefined,
targetHost: k8sHost,
targetPort: k8sPort ? Number(k8sPort) : 443,
@@ -928,7 +907,12 @@ export const identityKubernetesAuthServiceFactory = ({
caCert = templateFields.caCert || undefined;
tokenReviewerJwt = templateFields.tokenReviewerJwt || undefined;
tokenReviewMode = templateFields.tokenReviewMode;
- gatewayId = template.gatewayV2Id ?? template.gatewayId ?? null;
+ if (isPinnedToRetiredGateway(template)) {
+ throw new BadRequestError({
+ message: getRetiredGatewayMessage(`Auth template '${template.name}'`)
+ });
+ }
+ gatewayId = template.gatewayV2Id ?? null;
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
@@ -978,7 +962,6 @@ export const identityKubernetesAuthServiceFactory = ({
const resolvedVerifyTlsCertificate = verifyTlsCertificate ?? Boolean(caCert);
- let isGatewayV1 = true;
if (gatewayId) {
if (!plan.gateway) {
throw new BadRequestError({
@@ -987,18 +970,13 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
- if (!gateway && !gatewayV2) {
+ if (!gatewayV2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found`
});
}
- if (!gateway) {
- isGatewayV1 = false;
- }
-
// when the gateway comes from a template, attaching the gateway was authorized at
// template authoring time, so the actor only needs the attach-template permission
if (!template) {
@@ -1099,14 +1077,9 @@ export const identityKubernetesAuthServiceFactory = ({
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
- let resolvedGatewayId: string | null | undefined = null;
let resolvedGatewayV2Id: string | null | undefined = null;
if (!gatewayPoolId && gatewayId) {
- if (isGatewayV1) {
- resolvedGatewayId = gatewayId;
- } else {
- resolvedGatewayV2Id = gatewayId;
- }
+ resolvedGatewayV2Id = gatewayId;
}
const identityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
@@ -1122,7 +1095,6 @@ export const identityKubernetesAuthServiceFactory = ({
accessTokenMaxTTL,
accessTokenTTL,
accessTokenNumUsesLimit,
- gatewayId: resolvedGatewayId,
gatewayV2Id: resolvedGatewayV2Id,
gatewayPoolId: gatewayPoolId ?? null,
templateId: template?.id ?? null,
@@ -1146,7 +1118,8 @@ export const identityKubernetesAuthServiceFactory = ({
// a template's reviewer JWT is an org-scoped write-only credential; identity-level
// readers must not be able to recover it through the identity endpoints
tokenReviewerJwt: template ? "" : tokenReviewerJwt,
- orgId: identityMembershipOrg.scopeOrgId
+ orgId: identityMembershipOrg.scopeOrgId,
+ gatewayId: identityKubernetesAuth.gatewayV2Id
};
};
@@ -1276,7 +1249,12 @@ export const identityKubernetesAuthServiceFactory = ({
tokenReviewMode = templateFields.tokenReviewMode;
// the template's gateway lives in columns, not the encrypted fields, so it can carry a
// foreign key and clear itself in step with the columns copied onto this row
- gatewayId = template.gatewayV2Id ?? template.gatewayId ?? null;
+ if (isPinnedToRetiredGateway(template)) {
+ throw new BadRequestError({
+ message: getRetiredGatewayMessage(`Auth template '${template.name}'`)
+ });
+ }
+ gatewayId = template.gatewayV2Id ?? null;
gatewayPoolId = template.gatewayPoolId ?? null;
verifyTlsCertificate = templateFields.verifyTlsCertificate ?? Boolean(templateFields.caCert?.length);
allowedAudience = templateFields.allowedAudience ?? "";
@@ -1317,6 +1295,8 @@ export const identityKubernetesAuthServiceFactory = ({
// too. every field below decides where or how the JWT is sent; the host alone is not enough
// (a gateway tunnels it in API mode, and CA/verify settings guard it on the wire)
if (!template && identityKubernetesAuth.isTokenReviewerJwtTemplateSourced && tokenReviewerJwt === undefined) {
+ // includes the retired v1 column: unlinking a v1-pinned gateway still repoints where
+ // the template-sourced reviewer JWT would be sent
const storedGatewayId = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId ?? null;
const repointsConnection =
(kubernetesHost !== undefined && kubernetesHost !== identityKubernetesAuth.kubernetesHost) ||
@@ -1353,7 +1333,6 @@ export const identityKubernetesAuthServiceFactory = ({
return extractIPDetails(accessTokenTrustedIp.ipAddress);
});
- let isGatewayV1 = true;
if (gatewayId) {
if (!plan.gateway) {
throw new BadRequestError({
@@ -1362,19 +1341,14 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
- const [gateway] = await gatewayDAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
const [gatewayV2] = await gatewayV2DAL.find({ id: gatewayId, orgId: identityMembershipOrg.scopeOrgId });
- if (!gateway && !gatewayV2) {
+ if (!gatewayV2) {
throw new NotFoundError({
message: `Gateway with ID ${gatewayId} not found`
});
}
- if (!gateway) {
- isGatewayV1 = false;
- }
-
if (!template) {
const { permission: orgPermission } = await permissionService.getOrgPermission({
scope: OrganizationActionScope.Any,
@@ -1423,14 +1397,9 @@ export const identityKubernetesAuthServiceFactory = ({
// Strict check to see if gateway ID is undefined. It should update the gateway ID to null if its strictly set to null.
const shouldUpdateGatewayId = Boolean(gatewayId !== undefined || gatewayPoolId !== undefined);
- let gatewayIdValue: string | null | undefined = null;
let gatewayV2IdValue: string | null | undefined = null;
if (!gatewayPoolId && gatewayId) {
- if (isGatewayV1) {
- gatewayIdValue = gatewayId;
- } else {
- gatewayV2IdValue = gatewayId;
- }
+ gatewayV2IdValue = gatewayId;
}
let gatewayPoolIdValue: string | null | undefined;
if (gatewayPoolId !== undefined) {
@@ -1451,7 +1420,7 @@ export const identityKubernetesAuthServiceFactory = ({
} else if (gatewayId !== undefined) {
effectiveGatewayId = gatewayId;
} else {
- effectiveGatewayId = identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId;
+ effectiveGatewayId = identityKubernetesAuth.gatewayV2Id;
}
let effectiveCaCert: string | undefined;
@@ -1568,8 +1537,12 @@ export const identityKubernetesAuthServiceFactory = ({
// tri-state passthrough: undefined keeps the current link, null unlinks, a uuid links
// (a re-assert of the current id skips the template load above, so template is unset)
templateId,
- gatewayId: shouldUpdateGatewayId ? gatewayIdValue : undefined,
gatewayV2Id: shouldUpdateGatewayId ? gatewayV2IdValue : undefined,
+ // A deliberate gateway change clears the retired v1 pin too, otherwise `isPinnedToRetiredGateway`
+ // would reject this row's logins forever with no way to detach: setting gatewayId to null only
+ // clears gatewayV2Id, leaving the retired column set. Rows nobody edits keep their v1 value, so
+ // the retirement stays revertible for everything that has not already been repointed.
+ gatewayId: shouldUpdateGatewayId ? null : undefined,
gatewayPoolId: gatewayPoolIdValue,
verifyTlsCertificate: resolvedVerifyTlsCertificate,
accessTokenMaxTTL,
@@ -1618,7 +1591,8 @@ export const identityKubernetesAuthServiceFactory = ({
...updatedKubernetesAuth,
orgId: identityMembershipOrg.scopeOrgId,
caCert: updatedCACert,
- tokenReviewerJwt: updatedTokenReviewerJwt
+ tokenReviewerJwt: updatedTokenReviewerJwt,
+ gatewayId: updatedKubernetesAuth.gatewayV2Id
};
};
@@ -1707,7 +1681,7 @@ export const identityKubernetesAuthServiceFactory = ({
caCert,
tokenReviewerJwt,
orgId: identityMembershipOrg.scopeOrgId,
- gatewayId: identityKubernetesAuth.gatewayId ?? identityKubernetesAuth.gatewayV2Id
+ gatewayId: identityKubernetesAuth.gatewayV2Id
};
};
@@ -1796,7 +1770,12 @@ export const identityKubernetesAuthServiceFactory = ({
const revokedIdentityKubernetesAuth = await identityKubernetesAuthDAL.transaction(async (tx) => {
const deletedKubernetesAuth = await identityKubernetesAuthDAL.delete({ identityId }, tx);
await identityAccessTokenDAL.delete({ identityId, authMethod: IdentityAuthMethod.KUBERNETES_AUTH }, tx);
- return { ...deletedKubernetesAuth?.[0], orgId: identityMembershipOrg.scopeOrgId };
+ return {
+ ...deletedKubernetesAuth?.[0],
+ orgId: identityMembershipOrg.scopeOrgId,
+ // the row's own gatewayId is the retired v1 column; the API field reports gatewayV2Id
+ gatewayId: deletedKubernetesAuth?.[0]?.gatewayV2Id
+ };
});
// Detaching the auth method must invalidate any tokens already issued
diff --git a/backend/src/services/secret-sync/azure-key-vault/azure-key-vault-sync-fns.ts b/backend/src/services/secret-sync/azure-key-vault/azure-key-vault-sync-fns.ts
index aee8326090..658f6ef2ba 100644
--- a/backend/src/services/secret-sync/azure-key-vault/azure-key-vault-sync-fns.ts
+++ b/backend/src/services/secret-sync/azure-key-vault/azure-key-vault-sync-fns.ts
@@ -1,7 +1,6 @@
/* eslint-disable no-await-in-loop */
import { AxiosError } 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 { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
@@ -19,7 +18,6 @@ import { GetAzureKeyVaultSecret, TAzureKeyVaultSyncWithCredentials } from "./azu
type TAzureKeyVaultSyncFactoryDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
@@ -32,7 +30,6 @@ const AZURE_KEY_VAULT_CERTIFICATE_CONTENT_TYPES = ["application/x-pkcs12", "appl
export const azureKeyVaultSyncFactory = ({
kmsService,
appConnectionDAL,
- gatewayService,
gatewayV2Service,
gatewayPoolService
}: TAzureKeyVaultSyncFactoryDeps) => {
@@ -50,7 +47,6 @@ export const azureKeyVaultSyncFactory = ({
while (currentUrl) {
const res = await requestWithAzureKeyVaultGateway<{ value: GetAzureKeyVaultSecret; nextLink: string }>(
gatewayConnection,
- gatewayService,
gatewayV2Service,
{
method: "GET",
@@ -97,7 +93,6 @@ export const azureKeyVaultSyncFactory = ({
const azureKeyVaultSecret = await requestWithAzureKeyVaultGateway<GetAzureKeyVaultSecret>(
gatewayConnection,
- gatewayService,
gatewayV2Service,
{
method: "GET",
@@ -186,7 +181,7 @@ export const azureKeyVaultSyncFactory = ({
while (!isSecretSet && maxTries > 0) {
// try to set secret
try {
- await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayService, gatewayV2Service, {
+ await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayV2Service, {
method: "PUT",
url: `${secretSync.destinationConfig.vaultBaseUrl}/secrets/${key}?api-version=7.3`,
data: {
@@ -203,7 +198,7 @@ export const azureKeyVaultSyncFactory = ({
if (err instanceof AxiosError) {
// eslint-disable-next-line
if (err.response?.data?.error?.innererror?.code === "ObjectIsDeletedButRecoverable") {
- await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayService, gatewayV2Service, {
+ await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayV2Service, {
method: "POST",
url: `${secretSync.destinationConfig.vaultBaseUrl}/deletedsecrets/${key}/recover?api-version=7.3`,
data: {},
@@ -248,7 +243,7 @@ export const azureKeyVaultSyncFactory = ({
matchesSchema(secret, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
!setSecrets.find((setSecret) => setSecret.key === secret)
)) {
- await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayService, gatewayV2Service, {
+ await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayV2Service, {
method: "DELETE",
url: `${secretSync.destinationConfig.vaultBaseUrl}/secrets/${deleteSecretKey}?api-version=7.3`,
headers: {
@@ -281,7 +276,7 @@ export const azureKeyVaultSyncFactory = ({
if (underscoredKey in secretMap) {
if (!disabledAzureKeyVaultSecretKeys.includes(underscoredKey)) {
- await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayService, gatewayV2Service, {
+ await requestWithAzureKeyVaultGateway(gatewayConnection, gatewayV2Service, {
method: "DELETE",
url: `${secretSync.destinationConfig.vaultBaseUrl}/secrets/${key}?api-version=7.3`,
headers: {
diff --git a/backend/src/services/secret-sync/github/github-sync-fns.ts b/backend/src/services/secret-sync/github/github-sync-fns.ts
index 6aee7b669a..4a39ae56e8 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,5 @@
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 {
@@ -24,7 +23,6 @@ import { TGitHubPublicKey, TGitHubSecret, TGitHubSecretPayload, TGitHubSyncWithC
const getEncryptedSecrets = async (
secretSync: TGitHubSyncWithCredentials,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
gitHubAppDeps: TGitHubAppCredentialResolverDeps
@@ -50,7 +48,6 @@ const getEncryptedSecrets = async (
return makePaginatedGitHubRequest<TGitHubSecret, { secrets: TGitHubSecret[] }>(
connection,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
path,
@@ -61,7 +58,6 @@ const getEncryptedSecrets = async (
const getPublicKey = async (
secretSync: TGitHubSyncWithCredentials,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
token: string
@@ -96,7 +92,6 @@ const getPublicKey = async (
const response = await requestWithGitHubGateway<TGitHubPublicKey>(
{ gatewayId: effectiveGatewayId },
- gatewayService,
gatewayV2Service,
{
url: `https://${apiBaseUrl}${path}`,
@@ -115,7 +110,6 @@ const getPublicKey = async (
const deleteSecret = async (
secretSync: TGitHubSyncWithCredentials,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
token: string,
@@ -151,7 +145,6 @@ const deleteSecret = async (
await requestWithGitHubGateway(
{ gatewayId: effectiveGatewayId },
- gatewayService,
gatewayV2Service,
{
url: `https://${apiBaseUrl}${path}`,
@@ -168,7 +161,6 @@ const deleteSecret = async (
const putSecret = async (
secretSync: TGitHubSyncWithCredentials,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
token: string,
@@ -214,7 +206,6 @@ const putSecret = async (
await requestWithGitHubGateway(
{ gatewayId: effectiveGatewayId },
- gatewayService,
gatewayV2Service,
{
url: `https://${apiBaseUrl}${path}`,
@@ -234,7 +225,6 @@ export const GithubSyncFns = {
syncSecrets: async (
secretSync: TGitHubSyncWithCredentials,
ogSecretMap: TSecretMap,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
gitHubAppDeps: TGitHubAppCredentialResolverDeps
@@ -283,24 +273,17 @@ export const GithubSyncFns = {
token = connection.credentials.personalAccessToken;
break;
default:
- token = await getGitHubAppAuthToken(
- connection,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- gitHubAppDeps
- );
+ token = await getGitHubAppAuthToken(connection, gatewayV2Service, gatewayPoolService, gitHubAppDeps);
}
const resolvedSync = { ...secretSync, connection };
const encryptedSecrets = await getEncryptedSecrets(
resolvedSync,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
gitHubAppDeps
);
- const publicKey = await getPublicKey(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token);
+ const publicKey = await getPublicKey(resolvedSync, gatewayV2Service, gatewayPoolService, token);
await sodium.ready;
for await (const key of Object.keys(secretMap)) {
@@ -312,7 +295,7 @@ export const GithubSyncFns = {
const encryptedSecretValue = sodium.to_base64(encryptedBytes, sodium.base64_variants.ORIGINAL);
try {
- await putSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, {
+ await putSecret(resolvedSync, gatewayV2Service, gatewayPoolService, token, {
secret_name: key,
encrypted_value: encryptedSecretValue,
key_id: publicKey.key_id
@@ -333,7 +316,7 @@ export const GithubSyncFns = {
continue;
if (!(encryptedSecret.name in secretMap)) {
- await deleteSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, encryptedSecret);
+ await deleteSecret(resolvedSync, gatewayV2Service, gatewayPoolService, token, encryptedSecret);
}
}
},
@@ -343,7 +326,6 @@ export const GithubSyncFns = {
removeSecrets: async (
secretSync: TGitHubSyncWithCredentials,
ogSecretMap: TSecretMap,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
gitHubAppDeps: TGitHubAppCredentialResolverDeps
@@ -367,18 +349,11 @@ export const GithubSyncFns = {
token = connection.credentials.personalAccessToken;
break;
default:
- token = await getGitHubAppAuthToken(
- connection,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- gitHubAppDeps
- );
+ token = await getGitHubAppAuthToken(connection, gatewayV2Service, gatewayPoolService, gitHubAppDeps);
}
const encryptedSecrets = await getEncryptedSecrets(
resolvedSync,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
gitHubAppDeps
@@ -386,7 +361,7 @@ export const GithubSyncFns = {
for await (const encryptedSecret of encryptedSecrets) {
if (encryptedSecret.name in secretMap) {
- await deleteSecret(resolvedSync, gatewayService, gatewayV2Service, gatewayPoolService, token, encryptedSecret);
+ await deleteSecret(resolvedSync, 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.ts
index 83bfb8d857..65ee0547c3 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,5 @@
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";
@@ -28,7 +27,6 @@ const getKvMountVersion = async ({
mount,
accessToken,
connection,
- gatewayService,
gatewayV2Service
}: {
instanceUrl: string;
@@ -36,7 +34,6 @@ const getKvMountVersion = async ({
mount: string;
accessToken: string;
connection: THCVaultConnection;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
}) => {
const { data } = await requestWithHCVaultGateway<{
@@ -47,7 +44,7 @@ const getKvMountVersion = async ({
} | null;
};
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/sys/mounts`,
method: "GET",
headers: {
@@ -75,7 +72,6 @@ const getKvMountVersion = async ({
const listHCVaultVariables = async (
{ instanceUrl, namespace, mount, mountVersion, accessToken, path }: THCVaultListVariables,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
): Promise<{ [key: string]: string }> => {
try {
@@ -87,19 +83,14 @@ const listHCVaultVariables = async (
if (mountVersion === KvVersion.V2) {
// KV v2 response structure
- const { data } = await requestWithHCVaultGateway<THCVaultListVariablesResponse>(
- connection,
- gatewayService,
- gatewayV2Service,
- {
- url: `${instanceUrl}/v1/${urlPath}`,
- method: "GET",
- headers: {
- "X-Vault-Token": accessToken,
- ...(namespace ? { "X-Vault-Namespace": namespace } : {})
- }
+ const { data } = await requestWithHCVaultGateway<THCVaultListVariablesResponse>(connection, gatewayV2Service, {
+ url: `${instanceUrl}/v1/${urlPath}`,
+ method: "GET",
+ headers: {
+ "X-Vault-Token": accessToken,
+ ...(namespace ? { "X-Vault-Namespace": namespace } : {})
}
- );
+ });
return data.data.data;
}
@@ -108,7 +99,7 @@ const listHCVaultVariables = async (
data: {
[key: string]: string;
};
- }>(connection, gatewayService, gatewayV2Service, {
+ }>(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${urlPath}`,
method: "GET",
headers: {
@@ -134,7 +125,6 @@ const listHCVaultVariables = async (
const updateHCVaultVariables = async (
{ path, instanceUrl, namespace, accessToken, mount, mountVersion, data }: TPostHCVaultVariable,
connection: THCVaultConnection,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
// KV v2 uses /data/ in the path, KV v1 does not
@@ -146,7 +136,7 @@ const updateHCVaultVariables = async (
// KV v2 wraps data in { data: { ... } }, KV v1 sends data directly
const payload = mountVersion === KvVersion.V2 ? { data } : data;
- return requestWithHCVaultGateway(connection, gatewayService, gatewayV2Service, {
+ return requestWithHCVaultGateway(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${urlPath}`,
method: "POST",
headers: {
@@ -162,7 +152,6 @@ export const HCVaultSyncFns = {
syncSecrets: async (
secretSync: THCVaultSyncWithCredentials,
secretMap: TSecretMap,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
) => {
@@ -179,7 +168,7 @@ export const HCVaultSyncFns = {
const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };
const { namespace } = connection.credentials;
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
@@ -189,7 +178,6 @@ export const HCVaultSyncFns = {
mount,
accessToken,
connection,
- gatewayService,
gatewayV2Service
});
@@ -203,7 +191,6 @@ export const HCVaultSyncFns = {
path
},
connection,
- gatewayService,
gatewayV2Service
);
let tainted = false;
@@ -234,7 +221,7 @@ export const HCVaultSyncFns = {
// for kv v2: can write empty data to keep the path with metadata
if (mountVersion === KvVersion.V1) {
const urlPath = `${removeTrailingSlash(mount)}/${path}`;
- await requestWithHCVaultGateway(connection, gatewayService, gatewayV2Service, {
+ await requestWithHCVaultGateway(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${urlPath}`,
method: "DELETE",
headers: {
@@ -253,7 +240,6 @@ export const HCVaultSyncFns = {
await updateHCVaultVariables(
{ accessToken, instanceUrl, namespace, mount, mountVersion, path, data: variables },
connection,
- gatewayService,
gatewayV2Service
);
} catch (error) {
@@ -265,7 +251,6 @@ export const HCVaultSyncFns = {
removeSecrets: async (
secretSync: THCVaultSyncWithCredentials,
secretMap: TSecretMap,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
) => {
@@ -280,7 +265,7 @@ export const HCVaultSyncFns = {
const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };
const { namespace } = connection.credentials;
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
@@ -290,14 +275,12 @@ export const HCVaultSyncFns = {
mount,
accessToken,
connection,
- gatewayService,
gatewayV2Service
});
const variables = await listHCVaultVariables(
{ instanceUrl, namespace, accessToken, mount, mountVersion, path },
connection,
- gatewayService,
gatewayV2Service
);
@@ -314,7 +297,7 @@ export const HCVaultSyncFns = {
// for kv v2: can write empty data to keep the path with metadata
if (mountVersion === KvVersion.V1) {
const urlPath = `${removeTrailingSlash(mount)}/${path}`;
- await requestWithHCVaultGateway(connection, gatewayService, gatewayV2Service, {
+ await requestWithHCVaultGateway(connection, gatewayV2Service, {
url: `${instanceUrl}/v1/${urlPath}`,
method: "DELETE",
headers: {
@@ -329,7 +312,6 @@ export const HCVaultSyncFns = {
await updateHCVaultVariables(
{ accessToken, instanceUrl, namespace, mount, mountVersion, path, data: variables },
connection,
- gatewayService,
gatewayV2Service
);
} catch (error) {
@@ -340,7 +322,6 @@ export const HCVaultSyncFns = {
},
getSecrets: async (
secretSync: THCVaultSyncWithCredentials,
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
) => {
@@ -355,7 +336,7 @@ export const HCVaultSyncFns = {
const connection = { ...rawConnection, gatewayId: effectiveGatewayId, gatewayPoolId: null };
const { namespace } = connection.credentials;
- const accessToken = await getHCVaultAccessToken(connection, gatewayService, gatewayV2Service);
+ const accessToken = await getHCVaultAccessToken(connection, gatewayV2Service);
const instanceUrl = await getHCVaultInstanceUrl(connection);
// Get mount details to determine KV version
@@ -365,7 +346,6 @@ export const HCVaultSyncFns = {
mount,
accessToken,
connection,
- gatewayService,
gatewayV2Service
});
@@ -379,7 +359,6 @@ export const HCVaultSyncFns = {
path
},
connection,
- gatewayService,
gatewayV2Service
);
diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.ts
index a2dc587741..05dff8fc2b 100644
--- a/backend/src/services/secret-sync/secret-sync-fns.ts
+++ b/backend/src/services/secret-sync/secret-sync-fns.ts
@@ -1,7 +1,6 @@
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";
@@ -184,7 +183,6 @@ type TSyncSecretDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
@@ -312,14 +310,7 @@ export const SecretSyncFns = {
syncSecrets: (
secretSync: TSecretSyncWithCredentials,
secretMap: TSecretMap,
- {
- kmsService,
- appConnectionDAL,
- gitHubAppDAL,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
- }: TSyncSecretDeps
+ { kmsService, appConnectionDAL, gitHubAppDAL, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps
): Promise<TSyncSecretsResult | void> => {
const schemaSecretMap = addSchema(secretMap, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema);
@@ -329,21 +320,16 @@ export const SecretSyncFns = {
case SecretSync.AWSSecretsManager:
return AwsSecretsManagerSyncFns.syncSecrets(secretSync, schemaSecretMap, secretMap);
case SecretSync.GitHub:
- return GithubSyncFns.syncSecrets(
- secretSync,
- schemaSecretMap,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- { gitHubAppDAL, kmsService }
- );
+ return GithubSyncFns.syncSecrets(secretSync, schemaSecretMap, gatewayV2Service, gatewayPoolService, {
+ gitHubAppDAL,
+ kmsService
+ });
case SecretSync.GCPSecretManager:
return GcpSyncFns.syncSecrets(secretSync, schemaSecretMap);
case SecretSync.AzureKeyVault:
return azureKeyVaultSyncFactory({
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
}).syncSecrets(secretSync, schemaSecretMap);
@@ -378,13 +364,7 @@ export const SecretSyncFns = {
case SecretSync.Windmill:
return WindmillSyncFns.syncSecrets(secretSync, schemaSecretMap);
case SecretSync.HCVault:
- return HCVaultSyncFns.syncSecrets(
- secretSync,
- schemaSecretMap,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
- );
+ return HCVaultSyncFns.syncSecrets(secretSync, schemaSecretMap, gatewayV2Service, gatewayPoolService);
case SecretSync.TeamCity:
return TeamCitySyncFns.syncSecrets(secretSync, schemaSecretMap);
case SecretSync.OCIVault:
@@ -463,7 +443,7 @@ export const SecretSyncFns = {
},
getSecrets: async (
secretSync: TSecretSyncWithCredentials,
- { kmsService, appConnectionDAL, gatewayService, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps
+ { kmsService, appConnectionDAL, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps
): Promise<TSecretMap> => {
let secretMap: TSecretMap;
switch (secretSync.destination) {
@@ -486,7 +466,6 @@ export const SecretSyncFns = {
secretMap = await azureKeyVaultSyncFactory({
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
}).getSecrets(secretSync);
@@ -527,7 +506,7 @@ export const SecretSyncFns = {
secretMap = await WindmillSyncFns.getSecrets(secretSync);
break;
case SecretSync.HCVault:
- secretMap = await HCVaultSyncFns.getSecrets(secretSync, gatewayService, gatewayV2Service, gatewayPoolService);
+ secretMap = await HCVaultSyncFns.getSecrets(secretSync, gatewayV2Service, gatewayPoolService);
break;
case SecretSync.TeamCity:
secretMap = await TeamCitySyncFns.getSecrets(secretSync);
@@ -647,14 +626,7 @@ export const SecretSyncFns = {
removeSecrets: (
secretSync: TSecretSyncWithCredentials,
secretMap: TSecretMap,
- {
- kmsService,
- appConnectionDAL,
- gitHubAppDAL,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
- }: TSyncSecretDeps
+ { kmsService, appConnectionDAL, gitHubAppDAL, gatewayV2Service, gatewayPoolService }: TSyncSecretDeps
): Promise<void> => {
const schemaSecretMap = addSchema(secretMap, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema);
@@ -664,21 +636,16 @@ export const SecretSyncFns = {
case SecretSync.AWSSecretsManager:
return AwsSecretsManagerSyncFns.removeSecrets(secretSync, schemaSecretMap);
case SecretSync.GitHub:
- return GithubSyncFns.removeSecrets(
- secretSync,
- schemaSecretMap,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService,
- { gitHubAppDAL, kmsService }
- );
+ return GithubSyncFns.removeSecrets(secretSync, schemaSecretMap, gatewayV2Service, gatewayPoolService, {
+ gitHubAppDAL,
+ kmsService
+ });
case SecretSync.GCPSecretManager:
return GcpSyncFns.removeSecrets(secretSync, schemaSecretMap);
case SecretSync.AzureKeyVault:
return azureKeyVaultSyncFactory({
appConnectionDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
}).removeSecrets(secretSync, schemaSecretMap);
@@ -711,13 +678,7 @@ export const SecretSyncFns = {
case SecretSync.Windmill:
return WindmillSyncFns.removeSecrets(secretSync, schemaSecretMap);
case SecretSync.HCVault:
- return HCVaultSyncFns.removeSecrets(
- secretSync,
- schemaSecretMap,
- gatewayService,
- gatewayV2Service,
- gatewayPoolService
- );
+ return HCVaultSyncFns.removeSecrets(secretSync, schemaSecretMap, 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.ts
index bf2e5ec17d..44076eb573 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.ts
@@ -4,7 +4,6 @@ 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";
@@ -126,7 +125,6 @@ type TSecretSyncQueueFactoryDep = {
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
- gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
@@ -180,7 +178,6 @@ export const secretSyncQueueFactory = ({
resourceMetadataDAL,
folderCommitService,
licenseService,
- gatewayService,
gatewayV2Service,
gatewayPoolService,
notificationService,
@@ -446,7 +443,6 @@ export const secretSyncQueueFactory = ({
appConnectionDAL,
gitHubAppDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
});
@@ -594,7 +590,6 @@ export const secretSyncQueueFactory = ({
appConnectionDAL,
gitHubAppDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
});
@@ -875,7 +870,6 @@ export const secretSyncQueueFactory = ({
appConnectionDAL,
gitHubAppDAL,
kmsService,
- gatewayService,
gatewayV2Service,
gatewayPoolService
}
diff --git a/backend/src/services/telemetry/telemetry-dal.ts b/backend/src/services/telemetry/telemetry-dal.ts
index 16138905db..bf497a4281 100644
--- a/backend/src/services/telemetry/telemetry-dal.ts
+++ b/backend/src/services/telemetry/telemetry-dal.ts
@@ -175,20 +175,10 @@ export const telemetryDALFactory = (db: TDbClient) => {
}
});
- // Count active gateways from both legacy (Gateway) and V2 (GatewayV2) tables.
- // Legacy gateways heartbeat every ~3 minutes; use a 5-minute window to avoid undercounting.
- const legacyActiveResult = (
- await db(TableName.Gateway)
- .whereNotNull("heartbeat")
- .whereRaw(`"heartbeat" > NOW() - INTERVAL '5 minutes'`)
- .count()
- .first()
- )?.count as string;
-
- const v2ActiveResult = (await db(TableName.GatewayV2).whereRaw(buildGatewayReachableSql()).count().first())
+ const activeGatewaysResult = (await db(TableName.GatewayV2).whereRaw(buildGatewayReachableSql()).count().first())
?.count as string;
- const activeGateways = parseInt(legacyActiveResult || "0", 10) + parseInt(v2ActiveResult || "0", 10);
+ const activeGateways = parseInt(activeGatewaysResult || "0", 10);
// Merge legacy `secrets` and `secrets_v2` counts. secrets_v2 is the active table;
// legacy `secrets` only retains rows for projects that haven't been migrated.
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 56b1372977..6fe4c7fb08 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -102,8 +102,6 @@ export enum PostHogEventTypes {
SecretRotationV2Deleted = "Secret Rotation V2 Deleted",
SecretRotationV2Executed = "Secret Rotation V2 Executed",
GatewayCertExchanged = "Gateway Cert Exchanged",
- GatewayUpdated = "Gateway Updated",
- GatewayDeleted = "Gateway Deleted",
PamAccountTemplateCreated = "PAM Account Template Created",
PamAccountTemplateUpdated = "PAM Account Template Updated",
PamAccountTemplateDeleted = "PAM Account Template Deleted",
@@ -1091,20 +1089,6 @@ export type TGatewayCertExchangedEvent = {
};
};
-export type TGatewayUpdatedEvent = {
- event: PostHogEventTypes.GatewayUpdated;
- properties: {
- gatewayId: string;
- };
-};
-
-export type TGatewayDeletedEvent = {
- event: PostHogEventTypes.GatewayDeleted;
- properties: {
- gatewayId: string;
- };
-};
-
export type TPamAccountTemplateEvent = {
event:
| PostHogEventTypes.PamAccountTemplateCreated
@@ -2605,8 +2589,6 @@ export type TPostHogEvent = {
| TSecretRotationV2DeletedEvent
| TSecretRotationV2ExecutedEvent
| TGatewayCertExchangedEvent
- | TGatewayUpdatedEvent
- | TGatewayDeletedEvent
| TPamAccountTemplateEvent
| TPamFolderEvent
| TPamAccountEvent
diff --git a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
index bba9e824ec..c0eadb5a75 100644
--- a/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
+++ b/frontend/src/components/v3/platform/GatewayPicker/GatewayPicker.tsx
@@ -8,7 +8,7 @@ import {
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import { gatewayPoolsQueryKeys } from "@app/hooks/api/gateway-pools/queries";
-import { gatewaysQueryKeys, isListedGatewayV2 } from "@app/hooks/api/gateways/queries";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
import { PoolHealthBadge } from "@app/pages/organization/NetworkingPage/components/GatewayTab/components/PoolHealthBadge";
@@ -88,8 +88,7 @@ export const GatewayPicker = ({
}
};
- const v2Gateways =
- gateways?.filter(isListedGatewayV2).filter((g) => g.id !== excludeGatewayId) ?? [];
+ const v2Gateways = gateways?.filter((g) => g.id !== excludeGatewayId) ?? [];
const isOnline = (gw: (typeof v2Gateways)[number]) => isGatewayHealthy(gw);
diff --git a/frontend/src/hooks/api/gateways/index.tsx b/frontend/src/hooks/api/gateways/index.tsx
index af5a77e292..05e674e807 100644
--- a/frontend/src/hooks/api/gateways/index.tsx
+++ b/frontend/src/hooks/api/gateways/index.tsx
@@ -1,2 +1 @@
-export { useDeleteGatewayById, useUpdateGatewayById } from "./mutation";
export { gatewaysQueryKeys } from "./queries";
diff --git a/frontend/src/hooks/api/gateways/mutation.tsx b/frontend/src/hooks/api/gateways/mutation.tsx
deleted file mode 100644
index ef292cb39b..0000000000
--- a/frontend/src/hooks/api/gateways/mutation.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-
-import { apiRequest } from "@app/config/request";
-
-import { gatewaysQueryKeys } from "./queries";
-import { TUpdateGatewayDTO } from "./types";
-
-export const useDeleteGatewayById = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: (id: string) => {
- return apiRequest.delete(`/api/v1/gateways/${id}`);
- },
- onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
- }
- });
-};
-
-export const useUpdateGatewayById = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: ({ id, name }: TUpdateGatewayDTO) => {
- return apiRequest.patch(`/api/v1/gateways/${id}`, { name });
- },
- onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
- }
- });
-};
diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx
index 42c3abeb68..1368bedc2c 100644
--- a/frontend/src/hooks/api/gateways/queries.tsx
+++ b/frontend/src/hooks/api/gateways/queries.tsx
@@ -3,15 +3,8 @@ import { queryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TGatewayV2 } from "../gateways-v2/types";
-import { TGateway } from "./types";
-export type TListedGatewayV1 = TGateway & { isV1: true };
-export type TListedGatewayV2 = TGatewayV2 & { isV1: false };
-export type TListedGateway = TListedGatewayV1 | TListedGatewayV2;
-
-// A predicate, so the narrowing survives a .filter(). A plain boolean callback does not narrow.
-export const isListedGatewayV2 = (gateway: TListedGateway): gateway is TListedGatewayV2 =>
- !gateway.isV1;
+export type TListedGateway = TGatewayV2;
export const gatewaysQueryKeys = {
allKey: () => ["gateways"],
@@ -20,25 +13,11 @@ export const gatewaysQueryKeys = {
queryOptions({
queryKey: gatewaysQueryKeys.listKey(),
queryFn: async () => {
- const [{ data }, { data: dataV2 }] = await Promise.all([
- apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"),
- apiRequest.get<TGatewayV2[]>("/api/v2/gateways")
- ]);
+ const { data } = await apiRequest.get<TGatewayV2[]>("/api/v2/gateways");
// Filter out enrollment-flow gateways that haven't connected yet
// so gateway pickers don't show them as selectable options.
- const connectedV2 = dataV2.filter((g) => g.identityId || g.heartbeat || g.directHeartbeat);
-
- return [
- ...data.gateways.map((g) => ({
- ...g,
- isV1: true as const
- })),
- ...connectedV2.map((g) => ({
- ...g,
- isV1: false as const
- }))
- ];
+ return data.filter((g) => g.identityId || g.heartbeat || g.directHeartbeat);
}
}),
listWithTokensKey: () => [...gatewaysQueryKeys.allKey(), "list-with-tokens"],
@@ -46,15 +25,8 @@ export const gatewaysQueryKeys = {
queryOptions({
queryKey: gatewaysQueryKeys.listWithTokensKey(),
queryFn: async () => {
- const [{ data }, { data: dataV2 }] = await Promise.all([
- apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"),
- apiRequest.get<TGatewayV2[]>("/api/v2/gateways")
- ]);
-
- return [
- ...data.gateways.map((g) => ({ ...g, isV1: true as const })),
- ...dataV2.map((g) => ({ ...g, isV1: false as const }))
- ];
+ const { data } = await apiRequest.get<TGatewayV2[]>("/api/v2/gateways");
+ return data;
}
})
};
diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts
deleted file mode 100644
index 29f6441528..0000000000
--- a/frontend/src/hooks/api/gateways/types.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export type TGateway = {
- id: string;
- identityId: string;
- name: string;
- createdAt: string;
- updatedAt: string;
- issuedAt: string;
- serialNumber: string;
- heartbeat: string;
- identity: {
- name: string;
- id: string;
- };
- isV1?: boolean;
- capabilities?: Record<string, unknown>;
-};
-
-export type TUpdateGatewayDTO = {
- id: string;
- name?: string;
-};
-
-export type TDeleteGatewayDTO = {
- id: string;
-};
diff --git a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
index 403aa872fc..b89d3eb477 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
@@ -103,7 +103,6 @@ export const NetworkHealthBanner = () => {
const unreachableGatewayCount = useMemo(
() =>
gateways?.filter((g) => {
- if (g.isV1) return false;
return !isGatewayHealthy(g);
}).length ?? 0,
[gateways]
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
index 8c9f601e1e..96ea0e9d3a 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/CreateHsmConnectorWizard/CreateHsmConnectorWizard.tsx
@@ -48,7 +48,6 @@ export const CreateHsmConnectorWizard = ({ isOpen, onOpenChange }: Props) => {
const reachedFromOptions: ReachedFromOption[] = useMemo(() => {
const gatewayOptions: ReachedFromOption[] = gateways
- .filter((g) => !g.isV1)
.filter((g) => g.capabilities?.pkcs11 === true)
.map((g) => ({ value: `gateway:${g.id}`, label: g.name, group: "gateway" as const }));
const poolOptions: ReachedFromOption[] = pools.map((p) => ({
diff --git a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx
index 9d40142f80..b82b2348d8 100644
--- a/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx
+++ b/frontend/src/pages/cert-manager/SettingsPage/components/HsmConnectorsTab/EditHsmConnectorSheet.tsx
@@ -58,7 +58,6 @@ export const EditHsmConnectorSheet = ({ connector, onClose }: Props) => {
return "";
})();
const gatewayOptions: ReachedFromOption[] = gateways
- .filter((g) => !g.isV1)
.filter((g) => g.capabilities?.pkcs11 === true)
.map((g) => ({ value: `gateway:${g.id}`, label: g.name, group: "gateway" as const }));
const poolOptions: ReachedFromOption[] = pools.map((p) => ({
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
index ccfee02586..5c6c3d4cfc 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
@@ -7,7 +7,6 @@ import {
HeartPulseIcon,
InfoIcon,
MoreHorizontalIcon,
- PencilIcon,
PlusIcon,
SearchIcon,
TrashIcon
@@ -28,7 +27,6 @@ import {
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
- Badge,
Button,
Card,
CardAction,
@@ -36,10 +34,6 @@ import {
CardDescription,
CardHeader,
CardTitle,
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
DocumentationLinkBadge,
DropdownMenu,
DropdownMenuContent,
@@ -80,11 +74,10 @@ import { withPermission } from "@app/hoc";
import { usePopUp } from "@app/hooks";
import { useListGatewayPools } from "@app/hooks/api/gateway-pools";
import { TGatewayPool } from "@app/hooks/api/gateway-pools/types";
-import { gatewaysQueryKeys, useDeleteGatewayById } from "@app/hooks/api/gateways";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways";
import { useDeleteGatewayV2ById, useTriggerGatewayV2Heartbeat } from "@app/hooks/api/gateways-v2";
import { CreateGatewayPoolModal } from "./components/CreateGatewayPoolModal";
-import { EditGatewayDetailsModal } from "./components/EditGatewayDetailsModal";
import { GatewayDeployModal } from "./components/GatewayDeployModal";
import { GatewayHealthStatus } from "./components/GatewayHealthStatus";
import { GatewayPoolsContent } from "./components/GatewayPoolsContent";
@@ -125,12 +118,10 @@ export const GatewayTab = withPermission(
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"deployGateway",
"deleteGateway",
- "editDetails",
"createPool",
"upgradePlan"
] as const);
- const deleteGatewayById = useDeleteGatewayById();
const deleteGatewayV2ById = useDeleteGatewayV2ById();
const triggerGatewayV2Heartbeat = useTriggerGatewayV2Heartbeat();
@@ -147,13 +138,9 @@ export const GatewayTab = withPermission(
};
const handleDeleteGateway = async () => {
- const data = popUp.deleteGateway.data as { id: string; isV1: boolean };
+ const data = popUp.deleteGateway.data as { id: string };
try {
- if (data.isV1) {
- await deleteGatewayById.mutateAsync(data.id);
- } else {
- await deleteGatewayV2ById.mutateAsync(data.id);
- }
+ await deleteGatewayV2ById.mutateAsync(data.id);
handlePopUpToggle("deleteGateway", false);
createNotification({ type: "success", text: "Successfully deleted gateway" });
} catch {
@@ -325,19 +312,15 @@ export const GatewayTab = withPermission(
</TableRow>
))}
{filteredGateway?.map((el) => {
- const canNavigate = !el.isV1;
return (
<TableRow
key={el.id}
- className={canNavigate ? "cursor-pointer" : undefined}
- onClick={
- canNavigate
- ? () =>
- navigate({
- to: "/organizations/$orgId/networking/gateways/$gatewayId",
- params: { orgId, gatewayId: el.id }
- })
- : undefined
+ className="cursor-pointer"
+ onClick={() =>
+ navigate({
+ to: "/organizations/$orgId/networking/gateways/$gatewayId",
+ params: { orgId, gatewayId: el.id }
+ })
}
>
<TableCell>
@@ -348,16 +331,6 @@ export const GatewayTab = withPermission(
</TooltipTrigger>
<TooltipContent>{el.name}</TooltipContent>
</Tooltip>
- {el.isV1 && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="neutral" className="shrink-0">
- V1
- </Badge>
- </TooltipTrigger>
- <TooltipContent>Legacy</TooltipContent>
- </Tooltip>
- )}
</div>
</TableCell>
{showPoolsTab && (
@@ -377,7 +350,7 @@ export const GatewayTab = withPermission(
</TableCell>
)}
<TableCell className="whitespace-nowrap">
- {!el.isV1 && el.connectedResourcesCount > 0 ? (
+ {el.connectedResourcesCount > 0 ? (
<span>
{el.connectedResourcesCount} resource
{el.connectedResourcesCount !== 1 ? "s" : ""}
@@ -409,33 +382,14 @@ export const GatewayTab = withPermission(
<CopyIcon />
Copy ID
</DropdownMenuItem>
- {!el.isV1 &&
- (!!el.directAddress ||
- !!el.relayId ||
- !!el.heartbeat ||
- el.heartbeatTTL !== null) && (
- <DropdownMenuItem
- onClick={() => handleTriggerHealthCheck(el.id)}
- >
- <HeartPulseIcon />
- Trigger Health Check
- </DropdownMenuItem>
- )}
- {el.isV1 && (
- <OrgPermissionCan
- I={OrgGatewayPermissionActions.EditGateways}
- a={OrgPermissionSubjects.Gateway}
- >
- {(isAllowed: boolean) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- onClick={() => handlePopUpOpen("editDetails", el)}
- >
- <PencilIcon />
- Edit Details
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
+ {(!!el.directAddress ||
+ !!el.relayId ||
+ !!el.heartbeat ||
+ el.heartbeatTTL !== null) && (
+ <DropdownMenuItem onClick={() => handleTriggerHealthCheck(el.id)}>
+ <HeartPulseIcon />
+ Trigger Health Check
+ </DropdownMenuItem>
)}
<OrgPermissionCan
I={OrgGatewayPermissionActions.DeleteGateways}
@@ -461,20 +415,6 @@ export const GatewayTab = withPermission(
</TableBody>
</Table>
)}
- <Dialog
- open={popUp.editDetails.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("editDetails", isOpen)}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Edit Gateway</DialogTitle>
- </DialogHeader>
- <EditGatewayDetailsModal
- gatewayDetails={popUp.editDetails.data}
- onClose={() => handlePopUpToggle("editDetails")}
- />
- </DialogContent>
- </Dialog>
<AlertDialog
open={popUp.deleteGateway.isOpen}
confirmationValue={
@@ -499,14 +439,12 @@ export const GatewayTab = withPermission(
<AlertDescription>Deleting this gateway cannot be undone.</AlertDescription>
</Alert>
<AlertDialogFooter>
- <AlertDialogCancel
- isDisabled={deleteGatewayById.isPending || deleteGatewayV2ById.isPending}
- >
+ <AlertDialogCancel isDisabled={deleteGatewayV2ById.isPending}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
variant="danger"
- isPending={deleteGatewayById.isPending || deleteGatewayV2ById.isPending}
+ isPending={deleteGatewayV2ById.isPending}
onClick={(event) => {
event.preventDefault();
handleDeleteGateway();
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/EditGatewayDetailsModal.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/EditGatewayDetailsModal.tsx
deleted file mode 100644
index 328897180c..0000000000
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/EditGatewayDetailsModal.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { Controller, useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import { createNotification } from "@app/components/notifications";
-import { Button, FormControl, Input } from "@app/components/v2";
-import { NoticeBannerV2 } from "@app/components/v2/NoticeBannerV2/NoticeBannerV2";
-import { useUpdateGatewayById } from "@app/hooks/api";
-import { TGateway } from "@app/hooks/api/gateways/types";
-
-type Props = {
- gatewayDetails: TGateway;
- onClose: () => void;
-};
-
-const schema = z.object({
- name: z.string()
-});
-
-export type FormData = z.infer<typeof schema>;
-
-export const EditGatewayDetailsModal = ({ gatewayDetails, onClose }: Props) => {
- const {
- control,
- handleSubmit,
- formState: { isSubmitting }
- } = useForm<FormData>({
- resolver: zodResolver(schema),
- defaultValues: {
- name: gatewayDetails?.name
- }
- });
-
- const updateGatewayById = useUpdateGatewayById();
-
- const onFormSubmit = ({ name }: FormData) => {
- if (isSubmitting) return;
- updateGatewayById.mutate(
- {
- id: gatewayDetails.id,
- name
- },
- {
- onSuccess: () => {
- createNotification({
- type: "success",
- text: "Successfully updated gateway"
- });
- onClose();
- }
- }
- );
- };
-
- return (
- <form onSubmit={handleSubmit(onFormSubmit)}>
- <NoticeBannerV2 className="mx-auto mb-4" title="Project Linking">
- <p className="mt-1 text-xs text-mineshaft-300">
- Since the 15th May 2025, all gateways are automatically available for use in all projects
- and you no longer need to link them.
- <br />
- Organization members with the &quot;Attach Gateways&quot; permission can use gateways
- anywhere within the organization.
- </p>
- </NoticeBannerV2>
-
- <Controller
- control={control}
- name="name"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Name" isError={Boolean(error)} errorText={error?.message} isRequired>
- <Input {...field} placeholder="db-subnet-1" autoComplete="off" name="gateway-name" />
- </FormControl>
- )}
- />
- <div className="mt-4 flex items-center">
- <Button className="mr-4" size="sm" type="submit" isLoading={isSubmitting}>
- Update
- </Button>
- <Button colorSchema="secondary" variant="plain" onClick={() => onClose()}>
- Cancel
- </Button>
- </div>
- </form>
- );
-};
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
index c0b77ae98f..d2b738176d 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/PoolDetailSheet.tsx
@@ -35,10 +35,7 @@ import {
TableHead,
TableHeader,
TableHeadLabel,
- TableRow,
- Tooltip,
- TooltipContent,
- TooltipTrigger
+ TableRow
} from "@app/components/v3";
import {
OrgGatewayPoolPermissionActions,
@@ -47,7 +44,7 @@ import {
import { usePopUp } from "@app/hooks";
import { useAddGatewayToPool, useRemoveGatewayFromPool } from "@app/hooks/api/gateway-pools";
import { TGatewayPool } from "@app/hooks/api/gateway-pools/types";
-import { gatewaysQueryKeys, isListedGatewayV2 } from "@app/hooks/api/gateways/queries";
+import { gatewaysQueryKeys } from "@app/hooks/api/gateways/queries";
import { useTriggerGatewayV2Heartbeat } from "@app/hooks/api/gateways-v2";
import { isGatewayHealthy } from "@app/hooks/api/gateways-v2/utils";
@@ -82,7 +79,7 @@ export const PoolDetailSheet = ({ isOpen, onOpenChange, pool }: Props) => {
);
const availableGateways = useMemo(
- () => allGateways?.filter((g) => !g.isV1 && !pool?.memberGatewayIds.includes(g.id)) ?? [],
+ () => allGateways?.filter((g) => !pool?.memberGatewayIds.includes(g.id)) ?? [],
[allGateways, pool?.memberGatewayIds]
);
@@ -228,23 +225,13 @@ export const PoolDetailSheet = ({ isOpen, onOpenChange, pool }: Props) => {
</TableRow>
)}
{memberGateways.map((gw) => {
- const isOnline = isListedGatewayV2(gw) && isGatewayHealthy(gw);
+ const isOnline = isGatewayHealthy(gw);
return (
<TableRow key={gw.id}>
<TableCell>
<div className="flex min-w-0 items-center gap-2">
<span className="min-w-0 flex-1 truncate">{gw.name}</span>
- {gw.isV1 && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Badge variant="neutral" className="shrink-0">
- V1
- </Badge>
- </TooltipTrigger>
- <TooltipContent>Legacy</TooltipContent>
- </Tooltip>
- )}
</div>
</TableCell>
<TableCell>
@@ -265,12 +252,10 @@ export const PoolDetailSheet = ({ isOpen, onOpenChange, pool }: Props) => {
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="z-[60] min-w-[180px]">
- {!gw.isV1 && (
- <DropdownMenuItem onSelect={() => handleHealthCheck(gw.id)}>
- <FontAwesomeIcon icon={faHeartPulse} />
- Trigger health check
- </DropdownMenuItem>
- )}
+ <DropdownMenuItem onSelect={() => handleHealthCheck(gw.id)}>
+ <FontAwesomeIcon icon={faHeartPulse} />
+ Trigger health check
+ </DropdownMenuItem>
<DropdownMenuItem
variant="danger"
onSelect={() =>