From 84c534ef703ba70536c219b9cbdeb9cabe37983d Mon Sep 17 00:00:00 2001 From: = Date: Fri, 14 Feb 2025 13:11:50 +0530 Subject: [PATCH 01/30] feat: added api for admin and org gateway management --- backend/src/@types/fastify.d.ts | 2 + backend/src/@types/knex.d.ts | 20 ++ .../20250212191958_create-gateway.ts | 84 ++++++ .../src/db/schemas/gateway-instance-config.ts | 33 ++ backend/src/db/schemas/gateways.ts | 28 ++ backend/src/db/schemas/index.ts | 3 + backend/src/db/schemas/models.ts | 4 + backend/src/db/schemas/org-gateway-root-ca.ts | 27 ++ backend/src/ee/routes/v1/gateway-router.ts | 158 ++++++++++ backend/src/ee/routes/v1/index.ts | 3 + .../src/ee/services/gateway/gateway-dal.ts | 33 ++ .../gateway/gateway-instance-config-dal.ts | 11 + .../ee/services/gateway/gateway-service.ts | 284 ++++++++++++++++++ .../src/ee/services/gateway/gateway-types.ts | 21 ++ .../gateway/org-gateway-root-ca-dal.ts | 10 + .../src/ee/services/license/license-fns.ts | 3 +- .../src/ee/services/license/license-types.ts | 1 + .../ee/services/permission/org-permission.ts | 12 +- backend/src/keystore/keystore.ts | 12 +- backend/src/lib/config/env.ts | 7 + backend/src/lib/crypto/hashtext.ts | 29 ++ backend/src/lib/turn/credentials.ts | 16 + backend/src/server/routes/index.ts | 20 +- backend/src/server/routes/v1/admin-router.ts | 85 +++++- .../super-admin/super-admin-service.ts | 158 +++++++++- 25 files changed, 1053 insertions(+), 11 deletions(-) create mode 100644 backend/src/db/migrations/20250212191958_create-gateway.ts create mode 100644 backend/src/db/schemas/gateway-instance-config.ts create mode 100644 backend/src/db/schemas/gateways.ts create mode 100644 backend/src/db/schemas/org-gateway-root-ca.ts create mode 100644 backend/src/ee/routes/v1/gateway-router.ts create mode 100644 backend/src/ee/services/gateway/gateway-dal.ts create mode 100644 backend/src/ee/services/gateway/gateway-instance-config-dal.ts create mode 100644 backend/src/ee/services/gateway/gateway-service.ts create mode 100644 backend/src/ee/services/gateway/gateway-types.ts create mode 100644 backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts create mode 100644 backend/src/lib/crypto/hashtext.ts create mode 100644 backend/src/lib/turn/credentials.ts diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts index 1cb11545c..6cc850847 100644 --- a/backend/src/@types/fastify.d.ts +++ b/backend/src/@types/fastify.d.ts @@ -95,6 +95,7 @@ import { TUserServiceFactory } from "@app/services/user/user-service"; import { TUserEngagementServiceFactory } from "@app/services/user-engagement/user-engagement-service"; import { TWebhookServiceFactory } from "@app/services/webhook/webhook-service"; import { TWorkflowIntegrationServiceFactory } from "@app/services/workflow-integration/workflow-integration-service"; +import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service"; declare module "@fastify/request-context" { interface RequestContextData { @@ -228,6 +229,7 @@ declare module "fastify" { secretSync: TSecretSyncServiceFactory; kmip: TKmipServiceFactory; kmipOperation: TKmipOperationServiceFactory; + gateway: TGatewayServiceFactory; }; // this is exclusive use for middlewares in which we need to inject data // everywhere else access using service layer diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts index 27f6b894c..b09b02046 100644 --- a/backend/src/@types/knex.d.ts +++ b/backend/src/@types/knex.d.ts @@ -68,6 +68,12 @@ import { TExternalKms, TExternalKmsInsert, TExternalKmsUpdate, + TGatewayInstanceConfig, + TGatewayInstanceConfigInsert, + TGatewayInstanceConfigUpdate, + TGateways, + TGatewaysInsert, + TGatewaysUpdate, TGitAppInstallSessions, TGitAppInstallSessionsInsert, TGitAppInstallSessionsUpdate, @@ -179,6 +185,9 @@ import { TOrgBots, TOrgBotsInsert, TOrgBotsUpdate, + TOrgGatewayRootCa, + TOrgGatewayRootCaInsert, + TOrgGatewayRootCaUpdate, TOrgMemberships, TOrgMembershipsInsert, TOrgMembershipsUpdate, @@ -930,5 +939,16 @@ declare module "knex/types/tables" { TKmipClientCertificatesInsert, TKmipClientCertificatesUpdate >; + [TableName.Gateway]: KnexOriginal.CompositeTableType; + [TableName.GatewayInstanceConfig]: KnexOriginal.CompositeTableType< + TGatewayInstanceConfig, + TGatewayInstanceConfigInsert, + TGatewayInstanceConfigUpdate + >; + [TableName.OrgGatewayRootCa]: KnexOriginal.CompositeTableType< + TOrgGatewayRootCa, + TOrgGatewayRootCaInsert, + TOrgGatewayRootCaUpdate + >; } } diff --git a/backend/src/db/migrations/20250212191958_create-gateway.ts b/backend/src/db/migrations/20250212191958_create-gateway.ts new file mode 100644 index 000000000..635cd7427 --- /dev/null +++ b/backend/src/db/migrations/20250212191958_create-gateway.ts @@ -0,0 +1,84 @@ +import { Knex } from "knex"; + +import { TableName } from "../schemas"; +import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils"; + +export async function up(knex: Knex): Promise { + if (!(await knex.schema.hasTable(TableName.GatewayInstanceConfig))) { + await knex.schema.createTable(TableName.GatewayInstanceConfig, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.string("caKeyAlgorithm").notNullable(); + t.boolean("isDisabled").defaultTo(false); + + t.string("infisicalClientCaSerialNumber").notNullable(); + t.datetime("infisicalClientCaIssuedAt").notNullable(); + t.datetime("infisicalClientCaExpiration").notNullable(); + t.binary("encryptedInfisicalClientCaCertificate").notNullable(); + t.binary("encryptedInfisicalClientCaPrivateKey").notNullable(); + + t.string("infisicalClientCertSerialNumber").notNullable(); + t.string("infisicalClientCertKeyAlgorithm").notNullable(); + t.datetime("infisicalClientCertIssuedAt").notNullable(); + t.datetime("infisicalClientCertExpiration").notNullable(); + t.binary("encryptedInfisicalClientCertificate").notNullable(); + t.binary("encryptedInfisicalClientPrivateKey").notNullable(); + t.timestamps(true, true, true); + }); + + await createOnUpdateTrigger(knex, TableName.GatewayInstanceConfig); + } + + if (!(await knex.schema.hasTable(TableName.OrgGatewayRootCa))) { + await knex.schema.createTable(TableName.OrgGatewayRootCa, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + t.string("caKeyAlgorithm").notNullable(); + t.string("caSerialNumber").notNullable(); + t.datetime("caIssuedAt").notNullable(); + t.datetime("caExpiration").notNullable(); + t.binary("encryptedCaCertificate").notNullable(); + t.binary("encryptedCaPrivateKey").notNullable(); + + t.uuid("orgId").notNullable(); + t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE"); + + t.timestamps(true, true, true); + }); + + await createOnUpdateTrigger(knex, TableName.OrgGatewayRootCa); + } + + if (!(await knex.schema.hasTable(TableName.Gateway))) { + await knex.schema.createTable(TableName.Gateway, (t) => { + t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); + + t.string("name").notNullable(); + t.string("serialNumber").notNullable(); + t.string("keyAlgorithm").notNullable(); + t.datetime("issuedAt").notNullable(); + t.datetime("expiration").notNullable(); + + t.binary("relayAddress").notNullable(); + + t.uuid("orgGatewayRootCaId").notNullable(); + t.foreign("orgGatewayRootCaId").references("id").inTable(TableName.OrgGatewayRootCa).onDelete("CASCADE"); + + t.uuid("identityId").notNullable(); + t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE"); + + t.timestamps(true, true, true); + }); + + await createOnUpdateTrigger(knex, TableName.Gateway); + } +} + +export async function down(knex: Knex): Promise { + await knex.schema.dropTableIfExists(TableName.GatewayInstanceConfig); + await dropOnUpdateTrigger(knex, TableName.GatewayInstanceConfig); + + await knex.schema.dropTableIfExists(TableName.Gateway); + await dropOnUpdateTrigger(knex, TableName.Gateway); + + await knex.schema.dropTableIfExists(TableName.OrgGatewayRootCa); + await dropOnUpdateTrigger(knex, TableName.OrgGatewayRootCa); +} diff --git a/backend/src/db/schemas/gateway-instance-config.ts b/backend/src/db/schemas/gateway-instance-config.ts new file mode 100644 index 000000000..f59b4b781 --- /dev/null +++ b/backend/src/db/schemas/gateway-instance-config.ts @@ -0,0 +1,33 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { zodBuffer } from "@app/lib/zod"; + +import { TImmutableDBKeys } from "./models"; + +export const GatewayInstanceConfigSchema = z.object({ + id: z.string().uuid(), + caKeyAlgorithm: z.string(), + isDisabled: z.boolean().default(false).nullable().optional(), + infisicalClientCaSerialNumber: z.string(), + infisicalClientCaIssuedAt: z.date(), + infisicalClientCaExpiration: z.date(), + encryptedInfisicalClientCaCertificate: zodBuffer, + encryptedInfisicalClientCaPrivateKey: zodBuffer, + infisicalClientCertSerialNumber: z.string(), + infisicalClientCertKeyAlgorithm: z.string(), + infisicalClientCertIssuedAt: z.date(), + infisicalClientCertExpiration: z.date(), + encryptedInfisicalClientCertificate: zodBuffer, + encryptedInfisicalClientPrivateKey: zodBuffer, + createdAt: z.date(), + updatedAt: z.date() +}); + +export type TGatewayInstanceConfig = z.infer; +export type TGatewayInstanceConfigInsert = Omit, TImmutableDBKeys>; +export type TGatewayInstanceConfigUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/gateways.ts b/backend/src/db/schemas/gateways.ts new file mode 100644 index 000000000..7dc29fdb5 --- /dev/null +++ b/backend/src/db/schemas/gateways.ts @@ -0,0 +1,28 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { zodBuffer } from "@app/lib/zod"; + +import { TImmutableDBKeys } from "./models"; + +export const GatewaysSchema = z.object({ + id: z.string().uuid(), + name: z.string(), + serialNumber: z.string(), + keyAlgorithm: z.string(), + issuedAt: z.date(), + expiration: z.date(), + relayAddress: zodBuffer, + orgGatewayRootCaId: z.string().uuid(), + identityId: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date() +}); + +export type TGateways = z.infer; +export type TGatewaysInsert = Omit, TImmutableDBKeys>; +export type TGatewaysUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts index 737193836..9e03cb246 100644 --- a/backend/src/db/schemas/index.ts +++ b/backend/src/db/schemas/index.ts @@ -20,6 +20,8 @@ export * from "./certificates"; export * from "./dynamic-secret-leases"; export * from "./dynamic-secrets"; export * from "./external-kms"; +export * from "./gateway-instance-config"; +export * from "./gateways"; export * from "./git-app-install-sessions"; export * from "./git-app-org"; export * from "./group-project-membership-roles"; @@ -57,6 +59,7 @@ export * from "./ldap-group-maps"; export * from "./models"; export * from "./oidc-configs"; export * from "./org-bots"; +export * from "./org-gateway-root-ca"; export * from "./org-memberships"; export * from "./org-roles"; export * from "./organizations"; diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts index 3c5d1cad8..069a9ea51 100644 --- a/backend/src/db/schemas/models.ts +++ b/backend/src/db/schemas/models.ts @@ -113,6 +113,10 @@ export enum TableName { SecretApprovalRequestSecretTagV2 = "secret_approval_request_secret_tags_v2", SnapshotSecretV2 = "secret_snapshot_secrets_v2", ProjectSplitBackfillIds = "project_split_backfill_ids", + // Gateway + GatewayInstanceConfig = "gateway_instance_config", + OrgGatewayRootCa = "org_gateway_root_ca", + Gateway = "gateways", // junction tables with tags SecretV2JnTag = "secret_v2_tag_junction", JnSecretTag = "secret_tag_junction", diff --git a/backend/src/db/schemas/org-gateway-root-ca.ts b/backend/src/db/schemas/org-gateway-root-ca.ts new file mode 100644 index 000000000..96c36fb37 --- /dev/null +++ b/backend/src/db/schemas/org-gateway-root-ca.ts @@ -0,0 +1,27 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { zodBuffer } from "@app/lib/zod"; + +import { TImmutableDBKeys } from "./models"; + +export const OrgGatewayRootCaSchema = z.object({ + id: z.string().uuid(), + caKeyAlgorithm: z.string(), + caSerialNumber: z.string(), + caIssuedAt: z.date(), + caExpiration: z.date(), + encryptedCaCertificate: zodBuffer, + encryptedCaPrivateKey: zodBuffer, + orgId: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date() +}); + +export type TOrgGatewayRootCa = z.infer; +export type TOrgGatewayRootCaInsert = Omit, TImmutableDBKeys>; +export type TOrgGatewayRootCaUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts new file mode 100644 index 000000000..27dbd850b --- /dev/null +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -0,0 +1,158 @@ +import { z } from "zod"; + +import { GatewaysSchema } from "@app/db/schemas"; +import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; +import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; +import { AuthMode } from "@app/services/auth/auth-type"; + +const SanitizedGatewaySchema = GatewaysSchema.pick({ + id: true, + identityId: true, + name: true, + createdAt: true, + updatedAt: true, + issuedAt: true, + serialNumber: true +}); + +export const registerGatewayRouter = async (server: FastifyZodProvider) => { + server.route({ + method: "POST", + url: "/register-identity", + config: { + rateLimit: writeLimit + }, + schema: { + response: { + 200: z.object({ + turnServerUsername: z.string(), + turnServerPassword: z.string(), + turnServerAddress: z.string(), + infisicalStaticIp: z.string() + }) + } + }, + onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const relayDetails = await server.services.gateway.getGatewayRelayDetails( + req.permission.id, + req.permission.orgId + ); + return relayDetails; + } + }); + + server.route({ + method: "POST", + url: "/exchange-cert", + config: { + rateLimit: writeLimit + }, + schema: { + body: z.object({ + relayAddress: z.string() + }), + response: { + 200: z.object({ + serialNumber: z.string(), + privateKey: z.string(), + certificate: z.string(), + certificateChain: z.string() + }) + } + }, + onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]), + handler: async (req) => { + const gatewayCertificates = await server.services.gateway.exchangeAllocatedRelayAddress({ + identityOrg: req.permission.orgId, + identityId: req.permission.id, + relayAddress: req.body.relayAddress + }); + return gatewayCertificates; + } + }); + + server.route({ + method: "GET", + url: "/", + config: { + rateLimit: readLimit + }, + schema: { + 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]), + 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]), + handler: async (req) => { + const gateway = await server.services.gateway.getGatewayById({ + orgPermission: req.permission, + id: req.params.id + }); + return { gateway }; + } + }); + + server.route({ + method: "DELETE", + url: "/:id", + config: { + rateLimit: readLimit + }, + 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 + }); + return { gateway }; + } + }); +}; diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts index 0567c76ef..e793c687d 100644 --- a/backend/src/ee/routes/v1/index.ts +++ b/backend/src/ee/routes/v1/index.ts @@ -7,6 +7,7 @@ import { registerCaCrlRouter } from "./certificate-authority-crl-router"; import { registerDynamicSecretLeaseRouter } from "./dynamic-secret-lease-router"; import { registerDynamicSecretRouter } from "./dynamic-secret-router"; import { registerExternalKmsRouter } from "./external-kms-router"; +import { registerGatewayRouter } from "./gateway-router"; import { registerGroupRouter } from "./group-router"; import { registerIdentityProjectAdditionalPrivilegeRouter } from "./identity-project-additional-privilege-router"; import { registerKmipRouter } from "./kmip-router"; @@ -67,6 +68,8 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => { { prefix: "/dynamic-secrets" } ); + await server.register(registerGatewayRouter, { prefix: "/gateways" }); + await server.register( async (pkiRouter) => { await pkiRouter.register(registerCaCrlRouter, { prefix: "/crl" }); diff --git a/backend/src/ee/services/gateway/gateway-dal.ts b/backend/src/ee/services/gateway/gateway-dal.ts new file mode 100644 index 000000000..86a40a3fe --- /dev/null +++ b/backend/src/ee/services/gateway/gateway-dal.ts @@ -0,0 +1,33 @@ +import { TDbClient } from "@app/db"; +import { 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; + +export const gatewayDALFactory = (db: TDbClient) => { + const orm = ormify(db, TableName.Gateway); + + const find = async (filter: TFindFilter, { offset, limit, sort, tx }: TFindOpt = {}) => { + try { + const query = (tx || db)(TableName.Gateway) + // eslint-disable-next-line @typescript-eslint/no-misused-promises + .where(buildFindFilter(filter)) + .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Gateway}.identityId`) + .select(selectAllTableCols(TableName.Gateway)) + .select(db.ref("name").withSchema(TableName.Identity).as("identityName")); + 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) => ({ ...el, 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-instance-config-dal.ts b/backend/src/ee/services/gateway/gateway-instance-config-dal.ts new file mode 100644 index 000000000..14dcb7b9f --- /dev/null +++ b/backend/src/ee/services/gateway/gateway-instance-config-dal.ts @@ -0,0 +1,11 @@ +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { ormify } from "@app/lib/knex"; + +export type TGatewayInstanceConfigDALFactory = ReturnType; + +export const gatewayInstanceConfigDALFactory = (db: TDbClient) => { + const orm = ormify(db, TableName.GatewayInstanceConfig); + + return orm; +}; diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts new file mode 100644 index 000000000..8f3ab3f9f --- /dev/null +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -0,0 +1,284 @@ +import crypto from "node:crypto"; + +import { ForbiddenError } from "@casl/ability"; +import * as x509 from "@peculiar/x509"; + +import { PgSqlLock } from "@app/keystore/keystore"; +import { getConfig } from "@app/lib/config/env"; +import { BadRequestError, NotFoundError } from "@app/lib/errors"; +import { alphaNumericNanoId } from "@app/lib/nanoid"; +import { getTurnCredentials } from "@app/lib/turn/credentials"; +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 { OrgGatewayPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; +import { TPermissionServiceFactory } from "../permission/permission-service"; +import { TGatewayDALFactory } from "./gateway-dal"; +import { TExchangeAllocatedRelayAddressDTO, TGetGatewayByIdDTO, TListGatewaysDTO } from "./gateway-types"; +import { TOrgGatewayRootCaDALFactory } from "./org-gateway-root-ca-dal"; + +type TGatewayServiceFactoryDep = { + gatewayDAL: TGatewayDALFactory; + orgGatewayRootCaDAL: Pick; + licenseService: Pick; + kmsService: Pick; + permissionService: Pick; +}; + +export type TGatewayServiceFactory = ReturnType; + +// TODO(gateway): missing permission check +export const gatewayServiceFactory = ({ + gatewayDAL, + licenseService, + orgGatewayRootCaDAL, + kmsService, + permissionService +}: TGatewayServiceFactoryDep) => { + const $validateOrgAccessToGateway = async (orgId: string) => { + 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 getGatewayRelayDetails = async (actorId: string, actorOrgId: string) => { + const envCfg = getConfig(); + await $validateOrgAccessToGateway(actorOrgId); + + if ( + !envCfg.GATEWAY_RELAY_AUTH_SECRET || + !envCfg.GATEWAY_RELAY_ADDRESS || + !envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS + ) { + throw new BadRequestError({ + message: "Gateway handshake failed due to missing instance config." + }); + } + // TODO(gateway): keep it in 30mins redis after encryption to avoid multiple credentials spinning up + const { username: turnServerUsername, password: turnServerPassword } = getTurnCredentials( + actorId, + envCfg.GATEWAY_RELAY_AUTH_SECRET + ); + + return { + turnServerUsername, + turnServerPassword, + turnServerAddress: envCfg.GATEWAY_RELAY_ADDRESS, + infisicalStaticIp: envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS + }; + }; + + const exchangeAllocatedRelayAddress = async ({ + identityId, + identityOrg, + relayAddress + }: TExchangeAllocatedRelayAddressDTO) => { + const { encryptor: orgKmsEncryptor, decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({ + type: KmsDataKey.Organization, + orgId: identityOrg + }); + + const orgGatewayRootCa = await orgGatewayRootCaDAL.transaction(async (tx) => { + await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayRootCaInit(identityOrg)]); + const existingGateway = await orgGatewayRootCaDAL.findOne({ orgId: identityOrg }); + if (existingGateway) return existingGateway; + const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048); + // generate root CA + const orgGatewayRootCaSerialNumber = createSerialNumber(); + const orgGatewayRootCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const orgGatewayCaSkObj = crypto.KeyObject.from(orgGatewayRootCaKeys.privateKey); + const orgGatewayCaIssuedAt = new Date(); + const orgGatewayCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 25)); + + const orgGatewayCaCert = await x509.X509CertificateGenerator.createSelfSigned({ + name: `CN=Org Gateway Root CA,O=${identityOrg}`, + serialNumber: orgGatewayRootCaSerialNumber, + notBefore: orgGatewayCaIssuedAt, + notAfter: orgGatewayCaExpiration, + signingAlgorithm: alg, + keys: orgGatewayRootCaKeys, + extensions: [ + // eslint-disable-next-line no-bitwise + new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), + await x509.SubjectKeyIdentifierExtension.create(orgGatewayRootCaKeys.publicKey) + ] + }); + + return orgGatewayRootCaDAL.create({ + orgId: identityOrg, + caIssuedAt: orgGatewayCaIssuedAt, + caExpiration: orgGatewayCaExpiration, + caSerialNumber: orgGatewayRootCaSerialNumber, + encryptedCaCertificate: orgKmsEncryptor({ plainText: Buffer.from(orgGatewayCaCert.rawData) }).cipherTextBlob, + encryptedCaPrivateKey: orgKmsEncryptor({ + plainText: orgGatewayCaSkObj.export({ + type: "pkcs8", + format: "der" + }) + }).cipherTextBlob, + caKeyAlgorithm: CertKeyAlgorithm.RSA_2048 + }); + }); + + const caCertObj = new x509.X509Certificate( + orgKmsDecryptor({ + cipherTextBlob: orgGatewayRootCa.encryptedCaCertificate + }) + ); + const caAlg = keyAlgorithmToAlgCfg(orgGatewayRootCa.caKeyAlgorithm as CertKeyAlgorithm); + const caSkObj = crypto.createPrivateKey({ + key: orgKmsDecryptor({ cipherTextBlob: orgGatewayRootCa.encryptedCaPrivateKey }), + format: "der", + type: "pkcs8" + }); + const caPrivateKey = await crypto.subtle.importKey( + "pkcs8", + caSkObj.export({ format: "der", type: "pkcs8" }), + caAlg, + true, + ["sign"] + ); + + const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048); + const gatewayKeys = await crypto.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(caCertObj, 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 }], false) + ]; + + const serialNumber = createSerialNumber(); + const privateKey = crypto.KeyObject.from(gatewayKeys.privateKey); + const gatewayCertificate = await x509.X509CertificateGenerator.create({ + serialNumber, + subject: `CN=${identityId},O=${identityOrg}`, + issuer: caCertObj.subject, + notBefore: certIssuedAt, + notAfter: certExpireAt, + signingKey: caPrivateKey, + publicKey: gatewayKeys.publicKey, + signingAlgorithm: alg, + extensions + }); + + await gatewayDAL.transaction(async (tx) => { + await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayCertExchange(identityOrg)]); + const existingGateway = await gatewayDAL.findOne({ identityId, orgGatewayRootCaId: orgGatewayRootCa.id }); + if (existingGateway) { + return gatewayDAL.updateById(existingGateway.id, { + keyAlgorithm: CertKeyAlgorithm.RSA_2048, + issuedAt: certIssuedAt, + expiration: certExpireAt, + serialNumber, + relayAddress: orgKmsEncryptor({ plainText: Buffer.from(relayAddress) }).cipherTextBlob + }); + } + + return gatewayDAL.create({ + keyAlgorithm: CertKeyAlgorithm.RSA_2048, + issuedAt: certIssuedAt, + expiration: certExpireAt, + serialNumber, + relayAddress: orgKmsEncryptor({ plainText: Buffer.from(relayAddress) }).cipherTextBlob, + identityId, + orgGatewayRootCaId: orgGatewayRootCa.id, + name: alphaNumericNanoId(8) + }); + }); + + return { + serialNumber, + privateKey: privateKey.export({ format: "pem", type: "pkcs8" }) as string, + certificate: gatewayCertificate.toString("pem"), + certificateChain: caCertObj.toString("pem") + }; + }; + + const listGateways = async ({ orgPermission }: TListGatewaysDTO) => { + const { permission } = await permissionService.getOrgPermission( + orgPermission.type, + orgPermission.id, + orgPermission.orgId, + orgPermission.authMethod, + orgPermission.orgId + ); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); + if (!rootCa) return []; + + const gateways = await gatewayDAL.find({ + orgGatewayRootCaId: rootCa.id + }); + return gateways; + }; + + const getGatewayById = async ({ orgPermission, id }: TGetGatewayByIdDTO) => { + const { permission } = await permissionService.getOrgPermission( + orgPermission.type, + orgPermission.id, + orgPermission.orgId, + orgPermission.authMethod, + orgPermission.orgId + ); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); + if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); + + const [gateway] = await gatewayDAL.find({ id, orgGatewayRootCaId: rootCa.id }); + 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( + orgPermission.type, + orgPermission.id, + orgPermission.orgId, + orgPermission.authMethod, + orgPermission.orgId + ); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); + if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); + + const [gateway] = await gatewayDAL.delete({ id, orgGatewayRootCaId: rootCa.id }); + if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); + return gateway; + }; + + return { + getGatewayRelayDetails, + exchangeAllocatedRelayAddress, + listGateways, + getGatewayById, + deleteGatewayById + }; +}; diff --git a/backend/src/ee/services/gateway/gateway-types.ts b/backend/src/ee/services/gateway/gateway-types.ts new file mode 100644 index 000000000..40328d041 --- /dev/null +++ b/backend/src/ee/services/gateway/gateway-types.ts @@ -0,0 +1,21 @@ +import { OrgServiceActor } from "@app/lib/types"; + +export type TExchangeAllocatedRelayAddressDTO = { + identityId: string; + identityOrg: string; + relayAddress: string; +}; + +export type TListGatewaysDTO = { + orgPermission: OrgServiceActor; +}; + +export type TGetGatewayByIdDTO = { + id: string; + orgPermission: OrgServiceActor; +}; + +export type TDeleteGatewayByIdDTO = { + id: string; + orgPermission: OrgServiceActor; +}; diff --git a/backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts b/backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts new file mode 100644 index 000000000..4730f20f8 --- /dev/null +++ b/backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts @@ -0,0 +1,10 @@ +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { ormify } from "@app/lib/knex"; + +export type TOrgGatewayRootCaDALFactory = ReturnType; + +export const orgGatewayRootCaDALFactory = (db: TDbClient) => { + const orm = ormify(db, TableName.OrgGatewayRootCa); + return orm; +}; diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts index cab19a530..3f9e1b42c 100644 --- a/backend/src/ee/services/license/license-fns.ts +++ b/backend/src/ee/services/license/license-fns.ts @@ -51,7 +51,8 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ pkiEst: false, enforceMfa: false, projectTemplates: false, - kmip: false + kmip: false, + gateway: true }); export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => { diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts index 2b4dbe49e..626a0c999 100644 --- a/backend/src/ee/services/license/license-types.ts +++ b/backend/src/ee/services/license/license-types.ts @@ -69,6 +69,7 @@ export type TFeatureSet = { enforceMfa: boolean; projectTemplates: false; kmip: false; + gateway: true; }; export type TOrgPlansTableDTO = { diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts index 03d1747d4..c83a30f25 100644 --- a/backend/src/ee/services/permission/org-permission.ts +++ b/backend/src/ee/services/permission/org-permission.ts @@ -32,6 +32,14 @@ export enum OrgPermissionAdminConsoleAction { AccessAllProjects = "access-all-projects" } +export enum OrgGatewayPermissionActions { + // is there a better word for this. This mean can an identity be a gateway + Create = "create", + Read = "read", + Edit = "edit", + Delete = "delete" +} + export enum OrgPermissionSubjects { Workspace = "workspace", Role = "role", @@ -50,7 +58,8 @@ export enum OrgPermissionSubjects { AuditLogs = "audit-logs", ProjectTemplates = "project-templates", AppConnections = "app-connections", - Kmip = "kmip" + Kmip = "kmip", + Gateway = "gateway" } export type AppConnectionSubjectFields = { @@ -73,6 +82,7 @@ export type OrgPermissionSet = | [OrgPermissionActions, OrgPermissionSubjects.Kms] | [OrgPermissionActions, OrgPermissionSubjects.AuditLogs] | [OrgPermissionActions, OrgPermissionSubjects.ProjectTemplates] + | [OrgGatewayPermissionActions, OrgPermissionSubjects.Gateway] | [ OrgPermissionAppConnectionActions, ( diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts index a5f3c24c0..982dc21f9 100644 --- a/backend/src/keystore/keystore.ts +++ b/backend/src/keystore/keystore.ts @@ -2,11 +2,13 @@ import { Redis } from "ioredis"; import { Redlock, Settings } from "@app/lib/red-lock"; -export enum PgSqlLock { - BootUpMigration = 2023, - SuperAdminInit = 2024, - KmsRootKeyInit = 2025 -} +export const PgSqlLock = { + BootUpMigration: 2023, + SuperAdminInit: 2024, + KmsRootKeyInit: 2025, + OrgGatewayRootCaInit: (orgId: string) => `org-gateway-root-ca:${orgId}`, + OrgGatewayCertExchange: (orgId: string) => `org-gateway-cert-exchange:${orgId}` +} as const; export type TKeyStoreFactory = ReturnType; diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts index 801e937a2..a286b4203 100644 --- a/backend/src/lib/config/env.ts +++ b/backend/src/lib/config/env.ts @@ -184,6 +184,13 @@ const envSchema = z USE_PG_QUEUE: zodStrBool.default("false"), SHOULD_INIT_PG_QUEUE: zodStrBool.default("false"), + /* Gateway----------------------------------------------------------------------------- */ + GATEWAY_INFISICAL_STATIC_IP_ADDRESS: zpStr(z.string().optional()), + GATEWAY_RELAY_ADDRESS: zpStr(z.string().optional()), + GATEWAY_RELAY_AUTH_SECRET: zpStr(z.string().optional()), + + /* ----------------------------------------------------------------------------- */ + /* App Connections ----------------------------------------------------------------------------- */ // aws diff --git a/backend/src/lib/crypto/hashtext.ts b/backend/src/lib/crypto/hashtext.ts new file mode 100644 index 000000000..221608382 --- /dev/null +++ b/backend/src/lib/crypto/hashtext.ts @@ -0,0 +1,29 @@ +// used for postgres lock +// this is something postgres does under the hood +// convert any string to a unique number +export const hashtext = (text: string) => { + // Convert text to UTF8 bytes array for consistent behavior with PostgreSQL + const encoder = new TextEncoder(); + const bytes = encoder.encode(text); + + // Implementation of hash_any + let result = 0; + + for (let i = 0; i < bytes.length; i += 1) { + // eslint-disable-next-line no-bitwise + result = ((result << 5) + result) ^ bytes[i]; + // Keep within 32-bit integer range + // eslint-disable-next-line no-bitwise + result >>>= 0; + } + + // Convert to signed 32-bit integer like PostgreSQL + // eslint-disable-next-line no-bitwise + return result | 0; +}; + +export const pgAdvisoryLockHashText = (text: string) => { + const hash = hashtext(text); + // Ensure positive value within PostgreSQL integer range + return Math.abs(hash) % 2 ** 31; +}; diff --git a/backend/src/lib/turn/credentials.ts b/backend/src/lib/turn/credentials.ts new file mode 100644 index 000000000..817148c30 --- /dev/null +++ b/backend/src/lib/turn/credentials.ts @@ -0,0 +1,16 @@ +import crypto from "node:crypto"; + +const TURN_TOKEN_TTL = 60 * 60 * 1000; // 24 hours in milliseconds +export const getTurnCredentials = (id: string, authSecret: string, ttl = TURN_TOKEN_TTL) => { + const timestamp = Math.floor((Date.now() + ttl) / 1000); + const username = `${timestamp}:${id}`; + + const hmac = crypto.createHmac("sha1", authSecret); + hmac.update(username); + const password = hmac.digest("base64"); + + return { + username, + password + }; +}; diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index 155b52cfb..fb8552744 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -27,6 +27,10 @@ import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic- import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-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 { gatewayInstanceConfigDALFactory } from "@app/ee/services/gateway/gateway-instance-config-dal"; +import { gatewayServiceFactory } from "@app/ee/services/gateway/gateway-service"; +import { orgGatewayRootCaDALFactory } from "@app/ee/services/gateway/org-gateway-root-ca-dal"; import { groupDALFactory } from "@app/ee/services/group/group-dal"; import { groupServiceFactory } from "@app/ee/services/group/group-service"; import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; @@ -393,6 +397,10 @@ export const registerRoutes = async ( const kmipOrgConfigDAL = kmipOrgConfigDALFactory(db); const kmipOrgServerCertificateDAL = kmipOrgServerCertificateDALFactory(db); + const gatewayInstanceConfigDAL = gatewayInstanceConfigDALFactory(db); + const orgGatewayRootCaDAL = orgGatewayRootCaDALFactory(db); + const gatewayDAL = gatewayDALFactory(db); + const permissionService = permissionServiceFactory({ permissionDAL, orgRoleDAL, @@ -631,6 +639,7 @@ export const registerRoutes = async ( authService: loginService, serverCfgDAL: superAdminDAL, kmsRootConfigDAL, + gatewayInstanceConfigDAL, orgService, keyStore, licenseService, @@ -1457,6 +1466,14 @@ export const registerRoutes = async ( permissionService }); + const gatewayService = gatewayServiceFactory({ + orgGatewayRootCaDAL, + permissionService, + gatewayDAL, + kmsService, + licenseService + }); + await superAdminService.initServerCfg(); // setup the communication with license key server @@ -1557,7 +1574,8 @@ export const registerRoutes = async ( appConnection: appConnectionService, secretSync: secretSyncService, kmip: kmipService, - kmipOperation: kmipOperationService + kmipOperation: kmipOperationService, + gateway: gatewayService }); const cronJobs: CronJob[] = []; diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts index 6ecebb274..4359ef3fe 100644 --- a/backend/src/server/routes/v1/admin-router.ts +++ b/backend/src/server/routes/v1/admin-router.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import { OrganizationsSchema, SuperAdminSchema, UsersSchema } from "@app/db/schemas"; +import { GatewayInstanceConfigSchema, OrganizationsSchema, SuperAdminSchema, UsersSchema } from "@app/db/schemas"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError } from "@app/lib/errors"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; @@ -12,6 +12,13 @@ import { getServerCfg } from "@app/services/super-admin/super-admin-service"; import { LoginMethod } from "@app/services/super-admin/super-admin-types"; import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types"; +const SanitizedInstanceGatewaySchema = GatewayInstanceConfigSchema.pick({ + isDisabled: true, + infisicalClientCaIssuedAt: true, + infisicalClientCaSerialNumber: true, + caKeyAlgorithm: true +}); + export const registerAdminRouter = async (server: FastifyZodProvider) => { server.route({ method: "GET", @@ -247,6 +254,82 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => { } }); + server.route({ + method: "POST", + url: "/gateway", + config: { + rateLimit: writeLimit + }, + schema: { + response: { + 200: z.object({ + message: z.string() + }) + } + }, + onRequest: (req, res, done) => { + verifyAuth([AuthMode.JWT])(req, res, () => { + verifySuperAdmin(req, res, done); + }); + }, + handler: async () => { + await server.services.superAdmin.setupInstanceGateway(); + return { message: "Gateway setup completed" }; + } + }); + + server.route({ + method: "PATCH", + url: "/gateway", + config: { + rateLimit: writeLimit + }, + schema: { + body: z.object({ + isDisabled: z.boolean().optional() + }), + response: { + 200: z.object({ + message: z.string(), + gateway: SanitizedInstanceGatewaySchema + }) + } + }, + onRequest: (req, res, done) => { + verifyAuth([AuthMode.JWT])(req, res, () => { + verifySuperAdmin(req, res, done); + }); + }, + handler: async (req) => { + const gateway = await server.services.superAdmin.updateInstanceGateway(req.body); + return { message: "Gateway updated Successfully.", gateway }; + } + }); + + server.route({ + method: "GET", + url: "/gateway", + config: { + rateLimit: readLimit + }, + schema: { + response: { + 200: z.object({ + gateway: SanitizedInstanceGatewaySchema + }) + } + }, + onRequest: (req, res, done) => { + verifyAuth([AuthMode.JWT])(req, res, () => { + verifySuperAdmin(req, res, done); + }); + }, + handler: async () => { + const gateway = await server.services.superAdmin.getInstanceGateway(); + return { gateway }; + } + }); + server.route({ method: "POST", url: "/signup", diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts index 9a6075423..cf9c35425 100644 --- a/backend/src/services/super-admin/super-admin-service.ts +++ b/backend/src/services/super-admin/super-admin-service.ts @@ -1,6 +1,9 @@ +import * as x509 from "@peculiar/x509"; import bcrypt from "bcrypt"; +import crypto, { KeyObject } from "crypto"; import { TSuperAdmin, TSuperAdminUpdate } from "@app/db/schemas"; +import { TGatewayInstanceConfigDALFactory } from "@app/ee/services/gateway/gateway-instance-config-dal"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; @@ -10,6 +13,8 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors"; import { TAuthLoginFactory } from "../auth/auth-login-service"; import { AuthMethod } from "../auth/auth-type"; +import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificate/certificate-types"; +import { createSerialNumber, keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns"; import { KMS_ROOT_CONFIG_UUID } from "../kms/kms-fns"; import { TKmsRootConfigDALFactory } from "../kms/kms-root-config-dal"; import { TKmsServiceFactory } from "../kms/kms-service"; @@ -31,6 +36,7 @@ type TSuperAdminServiceFactoryDep = { orgService: Pick; keyStore: Pick; licenseService: Pick; + gatewayInstanceConfigDAL: Pick; }; export type TSuperAdminServiceFactory = ReturnType; @@ -47,6 +53,7 @@ export let getServerCfg: () => Promise< const ADMIN_CONFIG_KEY = "infisical-admin-cfg"; const ADMIN_CONFIG_KEY_EXP = 60; // 60s const ADMIN_CONFIG_DB_UUID = "00000000-0000-0000-0000-000000000000"; +const GATEWAY_INSTANCE_CONFIG_UUID = "00000000-0000-0000-0000-000000000000"; export const superAdminServiceFactory = ({ serverCfgDAL, @@ -57,7 +64,8 @@ export const superAdminServiceFactory = ({ keyStore, kmsRootConfigDAL, kmsService, - licenseService + licenseService, + gatewayInstanceConfigDAL }: TSuperAdminServiceFactoryDep) => { const initServerCfg = async () => { // TODO(akhilmhdh): bad pattern time less change this later to me itself @@ -373,6 +381,149 @@ export const superAdminServiceFactory = ({ await kmsService.updateEncryptionStrategy(strategy); }; + const setupInstanceGateway = async () => { + if (!licenseService.onPremFeatures.gateway) { + throw new BadRequestError({ + message: "Failed to setup gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." + }); + } + + const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); + if (existingConfig) { + throw new BadRequestError({ + message: "Gateway has already been configured for the instance" + }); + } + + const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048); + // generate root CA + const infisicalClientRootCaSerialNumber = createSerialNumber(); + const infisicalClientRootCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const infisicalClientCaSkObj = KeyObject.from(infisicalClientRootCaKeys.privateKey); + const infisicalClientCaIssuedAt = new Date(); + const infisicalClientCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 25)); + + const infisicalClientCaCert = await x509.X509CertificateGenerator.createSelfSigned({ + name: "CN=Infisical Gateway Client Root CA", + serialNumber: infisicalClientRootCaSerialNumber, + notBefore: infisicalClientCaIssuedAt, + notAfter: infisicalClientCaExpiration, + signingAlgorithm: alg, + keys: infisicalClientRootCaKeys, + extensions: [ + // eslint-disable-next-line no-bitwise + new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), + await x509.SubjectKeyIdentifierExtension.create(infisicalClientRootCaKeys.publicKey) + ] + }); + + const infisicalClientLeafCertserialNumber = createSerialNumber(); + const infisicalClientLeafKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const extensions: x509.Extension[] = [ + new x509.BasicConstraintsExtension(false), + await x509.AuthorityKeyIdentifierExtension.create(infisicalClientCaCert, false), + await x509.SubjectKeyIdentifierExtension.create(infisicalClientLeafKeys.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 infisicalClientLeafCert = await x509.X509CertificateGenerator.create({ + serialNumber: infisicalClientLeafCertserialNumber, + subject: `OU=infisical,CN=infisical`, + issuer: infisicalClientCaCert.issuer, + notBefore: infisicalClientCaIssuedAt, + notAfter: infisicalClientCaExpiration, + signingKey: infisicalClientRootCaKeys.privateKey, + publicKey: infisicalClientLeafKeys.publicKey, + signingAlgorithm: alg, + extensions + }); + + const infisicalClientLeafCertSkObj = KeyObject.from(infisicalClientLeafKeys.privateKey); + const encryptWithRootKey = kmsService.encryptWithRootKey(); + await gatewayInstanceConfigDAL.create({ + // @ts-expect-error id is kept as fixed for idempotence and to avoid race condition + id: GATEWAY_INSTANCE_CONFIG_UUID, + isDisabled: false, + caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, + infisicalClientCaIssuedAt, + infisicalClientCaExpiration, + infisicalClientCaSerialNumber: infisicalClientRootCaSerialNumber, + encryptedInfisicalClientCaCertificate: encryptWithRootKey(Buffer.from(infisicalClientCaCert.rawData)), + encryptedInfisicalClientCaPrivateKey: encryptWithRootKey( + infisicalClientCaSkObj.export({ + type: "pkcs8", + format: "der" + }) + ), + infisicalClientCertIssuedAt: infisicalClientCaIssuedAt, + infisicalClientCertExpiration: infisicalClientCaExpiration, + infisicalClientCertSerialNumber: infisicalClientLeafCertserialNumber, + infisicalClientCertKeyAlgorithm: CertKeyAlgorithm.RSA_2048, + encryptedInfisicalClientCertificate: encryptWithRootKey(Buffer.from(infisicalClientLeafCert.rawData)), + encryptedInfisicalClientPrivateKey: encryptWithRootKey( + infisicalClientLeafCertSkObj.export({ + type: "pkcs8", + format: "der" + }) + ) + }); + }; + + const updateInstanceGateway = async ({ isDisabled }: { isDisabled?: boolean }) => { + if (!licenseService.onPremFeatures.gateway) { + throw new BadRequestError({ + message: "Failed to update gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." + }); + } + + const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); + if (!existingConfig) { + throw new NotFoundError({ + message: "Gateway instance config not found" + }); + } + + const updatedGatewayInstanceConfig = await gatewayInstanceConfigDAL.updateById(GATEWAY_INSTANCE_CONFIG_UUID, { + isDisabled + }); + return { + infisicalClientCaSerialNumber: updatedGatewayInstanceConfig.infisicalClientCaSerialNumber, + isDisabled: updatedGatewayInstanceConfig?.isDisabled, + caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, + infisicalClientCaIssuedAt: updatedGatewayInstanceConfig.infisicalClientCaIssuedAt + }; + }; + + const getInstanceGateway = async () => { + if (!licenseService.onPremFeatures.gateway) { + throw new BadRequestError({ + message: "Failed to update gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." + }); + } + + const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); + if (!existingConfig) { + throw new NotFoundError({ + message: "Gateway instance config not found" + }); + } + + return { + infisicalClientCaSerialNumber: existingConfig.infisicalClientCaSerialNumber, + isDisabled: existingConfig?.isDisabled, + caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, + infisicalClientCaIssuedAt: existingConfig.infisicalClientCaIssuedAt + }; + }; + return { initServerCfg, updateServerCfg, @@ -381,6 +532,9 @@ export const superAdminServiceFactory = ({ deleteUser, getAdminSlackConfig, updateRootEncryptionStrategy, - getConfiguredEncryptionStrategies + getConfiguredEncryptionStrategies, + setupInstanceGateway, + updateInstanceGateway, + getInstanceGateway }; }; From d65ae2c61b710639d7617fafae40b8047b192b6d Mon Sep 17 00:00:00 2001 From: = Date: Fri, 14 Feb 2025 13:12:05 +0530 Subject: [PATCH 02/30] feat: added instance gateway setup ui --- frontend/src/hooks/api/admin/index.ts | 2 + frontend/src/hooks/api/admin/mutation.ts | 25 ++++ frontend/src/hooks/api/admin/queries.ts | 20 ++- frontend/src/hooks/api/admin/types.ts | 11 ++ frontend/src/hooks/api/subscriptions/types.ts | 1 + .../pages/admin/OverviewPage/GatewayPanel.tsx | 114 ++++++++++++++++++ .../pages/admin/OverviewPage/OverviewPage.tsx | 8 +- 7 files changed, 178 insertions(+), 3 deletions(-) create mode 100644 frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx diff --git a/frontend/src/hooks/api/admin/index.ts b/frontend/src/hooks/api/admin/index.ts index 5405878c7..69f673187 100644 --- a/frontend/src/hooks/api/admin/index.ts +++ b/frontend/src/hooks/api/admin/index.ts @@ -1,7 +1,9 @@ export { useAdminDeleteUser, useCreateAdminUser, + useSetupInstanceGatewayConfig, useUpdateAdminSlackConfig, + useUpdateInstanceGatewayConfig, useUpdateServerConfig, useUpdateServerEncryptionStrategy } from "./mutation"; diff --git a/frontend/src/hooks/api/admin/mutation.ts b/frontend/src/hooks/api/admin/mutation.ts index c68760fa4..3bb1bfb2a 100644 --- a/frontend/src/hooks/api/admin/mutation.ts +++ b/frontend/src/hooks/api/admin/mutation.ts @@ -9,6 +9,7 @@ import { AdminSlackConfig, RootKeyEncryptionStrategy, TCreateAdminUserDTO, + TDisableInstanceGatewayConfigDTO, TServerConfig, TUpdateAdminSlackConfigDTO } from "./types"; @@ -98,3 +99,27 @@ export const useUpdateServerEncryptionStrategy = () => { } }); }; + +export const useSetupInstanceGatewayConfig = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async () => { + await apiRequest.post("/api/v1/admin/gateway"); + }, + onSuccess: () => { + queryClient.invalidateQueries(adminQueryKeys.getInstanceGatewayConfig()); + } + }); +}; + +export const useUpdateInstanceGatewayConfig = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (dto: TDisableInstanceGatewayConfigDTO) => { + await apiRequest.patch("/api/v1/admin/gateway", dto); + }, + onSuccess: () => { + queryClient.invalidateQueries(adminQueryKeys.getInstanceGatewayConfig()); + } + }); +}; diff --git a/frontend/src/hooks/api/admin/queries.ts b/frontend/src/hooks/api/admin/queries.ts index 12ae1cf64..afcbd31fb 100644 --- a/frontend/src/hooks/api/admin/queries.ts +++ b/frontend/src/hooks/api/admin/queries.ts @@ -1,4 +1,5 @@ -import { useInfiniteQuery, useQuery, UseQueryOptions } from "@tanstack/react-query"; +import { queryOptions, useInfiniteQuery, useQuery, UseQueryOptions } from "@tanstack/react-query"; +import { AxiosError } from "axios"; import { apiRequest } from "@app/config/request"; @@ -7,6 +8,7 @@ import { AdminGetUsersFilters, AdminSlackConfig, TGetServerRootKmsEncryptionDetails, + TInstanceGatewayConfig, TServerConfig } from "./types"; @@ -18,7 +20,21 @@ export const adminQueryKeys = { serverConfig: () => ["server-config"] as const, getUsers: (filters: AdminGetUsersFilters) => [adminStandaloneKeys.getUsers, { filters }] as const, getAdminSlackConfig: () => ["admin-slack-config"] as const, - getServerEncryptionStrategies: () => ["server-encryption-strategies"] as const + getServerEncryptionStrategies: () => ["server-encryption-strategies"] as const, + + getInstanceGatewayConfig: () => + queryOptions({ + queryKey: ["instance-gateway-config"], + queryFn: async () => { + const { data } = await apiRequest + .get<{ gateway: TInstanceGatewayConfig }>("/api/v1/admin/gateway") + .catch((err: AxiosError) => { + if (err.response?.status === 404) return { data: { gateway: false as const } }; + throw err; + }); + return data.gateway; + } + }) }; export const fetchServerConfig = async () => { diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts index 60fa3ab98..282af07a2 100644 --- a/frontend/src/hooks/api/admin/types.ts +++ b/frontend/src/hooks/api/admin/types.ts @@ -66,3 +66,14 @@ export enum RootKeyEncryptionStrategy { Software = "SOFTWARE", HSM = "HSM" } + +export type TInstanceGatewayConfig = { + isDisabled: boolean; + infisicalClientCaIssuedAt: string; + infisicalClientCaSerialNumber: string; + caKeyAlgorithm: string; +}; + +export type TDisableInstanceGatewayConfigDTO = { + isDisabled?: boolean; +}; diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.ts index 3129dd508..b6b653ece 100644 --- a/frontend/src/hooks/api/subscriptions/types.ts +++ b/frontend/src/hooks/api/subscriptions/types.ts @@ -42,6 +42,7 @@ export type SubscriptionPlan = { has_used_trial: boolean; caCrl: boolean; instanceUserManagement: boolean; + gateway: boolean; externalKms: boolean; pkiEst: boolean; enforceMfa: boolean; diff --git a/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx b/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx new file mode 100644 index 000000000..8590bee47 --- /dev/null +++ b/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx @@ -0,0 +1,114 @@ +import { useQuery } from "@tanstack/react-query"; +import { format } from "date-fns"; + +import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; +import { createNotification } from "@app/components/notifications"; +import { Button, EmptyState, Tooltip } from "@app/components/v2"; +import { useSubscription } from "@app/context"; +import { usePopUp } from "@app/hooks"; +import { useSetupInstanceGatewayConfig, useUpdateInstanceGatewayConfig } from "@app/hooks/api"; +import { adminQueryKeys } from "@app/hooks/api/admin/queries"; + +export const GatewayPanel = () => { + const { subscription } = useSubscription(); + const { data } = useQuery(adminQueryKeys.getInstanceGatewayConfig()); + const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["upgradePlan"] as const); + + const setupInstanceConfig = useSetupInstanceGatewayConfig(); + const updateInstanceConfig = useUpdateInstanceGatewayConfig(); + + const handleSetupInstance = () => { + if (!subscription.gateway) { + handlePopUpOpen("upgradePlan"); + return; + } + + if (!setupInstanceConfig.isPending) { + setupInstanceConfig.mutate(undefined, { + onSuccess: () => { + createNotification({ + type: "success", + text: "Instance gateway setup completed" + }); + } + }); + } + }; + + const handleUpdateGatewayStatus = ({ isDisabled }: { isDisabled?: boolean }) => { + if (!updateInstanceConfig.isPending) { + updateInstanceConfig.mutate( + { isDisabled }, + { + onSuccess: () => { + createNotification({ + type: "success", + text: "Instance gateway updated" + }); + } + } + ); + } + }; + + if (!data) { + return ( +
+ + + +
+ ); + } + + return ( +
+
+
Gateway
+ {data?.isDisabled && ( + +
+ + )} +
+
+
+ Infisical Client Root CA Issued At +
+
{format(new Date(data.infisicalClientCaIssuedAt), "yyyy-MM-dd")}
+
+
+
+ Infisical Client Root CA Seriial Number +
+
{data.infisicalClientCaSerialNumber}
+
+ + handlePopUpToggle("upgradePlan", isOpen)} + text="You can use Gateway if you switch to Infisical's Enterprise plan." + /> +
+ ); +}; diff --git a/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx b/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx index 45c2fa3ec..3b771fab4 100644 --- a/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx +++ b/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx @@ -33,6 +33,7 @@ import { EncryptionPanel } from "./components/EncryptionPanel"; import { IntegrationPanel } from "./components/IntegrationPanel"; import { RateLimitPanel } from "./components/RateLimitPanel"; import { UserPanel } from "./components/UserPanel"; +import { GatewayPanel } from "./GatewayPanel"; enum TabSections { Settings = "settings", @@ -41,7 +42,8 @@ enum TabSections { RateLimit = "rate-limit", Integrations = "integrations", Users = "users", - Kmip = "kmip" + Kmip = "kmip", + Gateway = "gateway" } enum SignUpModes { @@ -150,6 +152,7 @@ export const OverviewPage = () => { Rate Limit Integrations Users + Gateway
@@ -348,6 +351,9 @@ export const OverviewPage = () => { + + + )} From 4bbe80c083e21ff40433667f243acbb538fbca0d Mon Sep 17 00:00:00 2001 From: = Date: Fri, 14 Feb 2025 15:10:26 +0530 Subject: [PATCH 03/30] feat: resolved permission in backend --- backend/src/ee/services/gateway/gateway-service.ts | 6 +++--- backend/src/ee/services/permission/org-permission.ts | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index 8f3ab3f9f..1d3b87e15 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -230,7 +230,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); if (!rootCa) return []; @@ -248,7 +248,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); @@ -265,7 +265,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts index c83a30f25..272dc6de4 100644 --- a/backend/src/ee/services/permission/org-permission.ts +++ b/backend/src/ee/services/permission/org-permission.ts @@ -274,6 +274,10 @@ const buildAdminPermission = () => { can(OrgPermissionAppConnectionActions.Delete, OrgPermissionSubjects.AppConnections); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); + can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); + can(OrgGatewayPermissionActions.Edit, OrgPermissionSubjects.Gateway); + can(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); + can(OrgPermissionAdminConsoleAction.AccessAllProjects, OrgPermissionSubjects.AdminConsole); can(OrgPermissionKmipActions.Setup, OrgPermissionSubjects.Kmip); @@ -310,6 +314,7 @@ const buildMemberPermission = () => { can(OrgPermissionActions.Read, OrgPermissionSubjects.AuditLogs); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); + can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); return rules; }; From 7905017121f4c6294295f5b861d41f74726f4a6c Mon Sep 17 00:00:00 2001 From: = Date: Fri, 14 Feb 2025 15:11:23 +0530 Subject: [PATCH 04/30] feat: added gateway page in ui for org --- .../src/context/OrgPermissionContext/types.ts | 14 +- frontend/src/hooks/api/gateways/index.tsx | 2 + frontend/src/hooks/api/gateways/mutation.tsx | 15 ++ frontend/src/hooks/api/gateways/queries.tsx | 16 ++ frontend/src/hooks/api/gateways/types.ts | 17 ++ frontend/src/hooks/api/index.tsx | 1 + .../OrganizationLayout/OrganizationLayout.tsx | 7 + .../MinimizedOrgSidebar.tsx | 8 + .../GatewayListPage/GatewayListPage.tsx | 132 +++++++++++++ .../Gateways/GatewayListPage/route.tsx | 23 +++ .../components/OrgRoleModifySection.utils.ts | 13 +- .../OrgPermissionGatewayRow.tsx | 182 ++++++++++++++++++ frontend/src/routeTree.gen.ts | 75 ++++++++ frontend/src/routes.ts | 3 +- 14 files changed, 504 insertions(+), 4 deletions(-) create mode 100644 frontend/src/hooks/api/gateways/index.tsx create mode 100644 frontend/src/hooks/api/gateways/mutation.tsx create mode 100644 frontend/src/hooks/api/gateways/queries.tsx create mode 100644 frontend/src/hooks/api/gateways/types.ts create mode 100644 frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx create mode 100644 frontend/src/pages/organization/Gateways/GatewayListPage/route.tsx create mode 100644 frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts index 46329abc6..2eb5c19b3 100644 --- a/frontend/src/context/OrgPermissionContext/types.ts +++ b/frontend/src/context/OrgPermissionContext/types.ts @@ -7,6 +7,14 @@ export enum OrgPermissionActions { Delete = "delete" } +export enum OrgGatewayPermissionActions { + // is there a better word for this. This mean can an identity be a gateway + Create = "create", + Read = "read", + Edit = "edit", + Delete = "delete" +} + export enum OrgPermissionSubjects { Workspace = "workspace", Role = "role", @@ -25,7 +33,8 @@ export enum OrgPermissionSubjects { AuditLogs = "audit-logs", ProjectTemplates = "project-templates", AppConnections = "app-connections", - Kmip = "kmip" + Kmip = "kmip", + Gateway = "gateway" } export enum OrgPermissionAdminConsoleAction { @@ -68,7 +77,8 @@ export type OrgPermissionSet = | [OrgPermissionActions, OrgPermissionSubjects.AuditLogs] | [OrgPermissionActions, OrgPermissionSubjects.ProjectTemplates] | [OrgPermissionAppConnectionActions, OrgPermissionSubjects.AppConnections] - | [OrgPermissionKmipActions, OrgPermissionSubjects.Kmip]; + | [OrgPermissionKmipActions, OrgPermissionSubjects.Kmip] + | [OrgGatewayPermissionActions, OrgPermissionSubjects.Gateway]; // TODO(scott): add back once org UI refactored // | [ // OrgPermissionAppConnectionActions, diff --git a/frontend/src/hooks/api/gateways/index.tsx b/frontend/src/hooks/api/gateways/index.tsx new file mode 100644 index 000000000..c42152dc0 --- /dev/null +++ b/frontend/src/hooks/api/gateways/index.tsx @@ -0,0 +1,2 @@ +export { useDeleteGateway } from "./mutation"; +export { gatewaysQueryKeys } from "./queries"; diff --git a/frontend/src/hooks/api/gateways/mutation.tsx b/frontend/src/hooks/api/gateways/mutation.tsx new file mode 100644 index 000000000..858d8fa8a --- /dev/null +++ b/frontend/src/hooks/api/gateways/mutation.tsx @@ -0,0 +1,15 @@ +import { apiRequest } from "@app/config/request"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { gatewaysQueryKeys } from "./queries"; + +export const useDeleteGateway = () => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (id: string) => { + return apiRequest.delete(`/api/v1/gateways/${id}`); + }, + onSuccess: () => { + queryClient.invalidateQueries(gatewaysQueryKeys.list()); + } + }); +}; diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx new file mode 100644 index 000000000..e41e5d871 --- /dev/null +++ b/frontend/src/hooks/api/gateways/queries.tsx @@ -0,0 +1,16 @@ +import { apiRequest } from "@app/config/request"; +import { queryOptions } from "@tanstack/react-query"; +import { TGateway } from "./types"; + +export const gatewaysQueryKeys = { + allKey: () => ["gateways"], + listKey: () => [...gatewaysQueryKeys.allKey(), "list"], + list: () => + queryOptions({ + queryKey: gatewaysQueryKeys.listKey(), + queryFn: async () => { + const { data } = await apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"); + return data.gateways; + } + }) +}; diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts new file mode 100644 index 000000000..0af9d04b8 --- /dev/null +++ b/frontend/src/hooks/api/gateways/types.ts @@ -0,0 +1,17 @@ +export type TGateway = { + id: string; + identityId: string; + name: string; + createdAt: string; + updatedAt: string; + issuedAt: string; + serialNumber: string; + identity: { + name: string; + id: string; + }; +}; + +export type TDeleteGatewayDTO = { + id: string; +}; diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx index 441b5ba86..8311dbf2d 100644 --- a/frontend/src/hooks/api/index.tsx +++ b/frontend/src/hooks/api/index.tsx @@ -10,6 +10,7 @@ export * from "./certificates"; export * from "./certificateTemplates"; export * from "./dynamicSecret"; export * from "./dynamicSecretLease"; +export * from "./gateways"; export * from "./groups"; export * from "./identities"; export * from "./identityProjectAdditionalPrivilege"; diff --git a/frontend/src/layouts/OrganizationLayout/OrganizationLayout.tsx b/frontend/src/layouts/OrganizationLayout/OrganizationLayout.tsx index 589e82895..efd2335e5 100644 --- a/frontend/src/layouts/OrganizationLayout/OrganizationLayout.tsx +++ b/frontend/src/layouts/OrganizationLayout/OrganizationLayout.tsx @@ -101,6 +101,13 @@ export const OrganizationLayout = () => { )} + + {({ isActive }) => ( + + Gateways + + )} + {({ isActive }) => ( diff --git a/frontend/src/layouts/OrganizationLayout/components/MinimizedOrgSidebar/MinimizedOrgSidebar.tsx b/frontend/src/layouts/OrganizationLayout/components/MinimizedOrgSidebar/MinimizedOrgSidebar.tsx index 02c352bcc..4a255acad 100644 --- a/frontend/src/layouts/OrganizationLayout/components/MinimizedOrgSidebar/MinimizedOrgSidebar.tsx +++ b/frontend/src/layouts/OrganizationLayout/components/MinimizedOrgSidebar/MinimizedOrgSidebar.tsx @@ -5,6 +5,7 @@ import { faBook, faCheck, faCog, + faDoorClosed, faEnvelope, faInfinity, faInfo, @@ -352,6 +353,13 @@ export const MinimizedOrgSidebar = () => { App Connections + + } + > + Gateways + + {(window.location.origin.includes("https://app.infisical.com") || window.location.origin.includes("https://eu.infisical.com") || window.location.origin.includes("https://gamma.infisical.com")) && ( diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx new file mode 100644 index 000000000..0ced1319f --- /dev/null +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx @@ -0,0 +1,132 @@ +import { useState } from "react"; +import { Helmet } from "react-helmet"; +import { + faArrowUpRightFromSquare, + faBookOpen, + faMagnifyingGlass, + faPlug, + faSearch +} from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { useQuery } from "@tanstack/react-query"; +import { format } from "date-fns"; + +import { + EmptyState, + Input, + PageHeader, + Table, + TableContainer, + TableSkeleton, + TBody, + Td, + Th, + THead, + Tr +} from "@app/components/v2"; +import { + OrgPermissionAppConnectionActions, + OrgPermissionSubjects +} from "@app/context/OrgPermissionContext/types"; +import { withPermission } from "@app/hoc"; +import { gatewaysQueryKeys } from "@app/hooks/api/gateways"; + +export const GatewayListPage = withPermission( + () => { + const [search, setSearch] = useState(""); + const { data: gateways, isPending: isGatewayLoading } = useQuery(gatewaysQueryKeys.list()); + + const filteredGateway = gateways?.filter((el) => + el.name.toLowerCase().includes(search.toLowerCase()) + ); + + return ( +
+ + Infisical | Gateways + + +
+
+ + Gateways + +
+ + Docs + +
+
+
+ } + description="Create and configure connections with third-party apps for re-use across Infisical projects" + /> +
+
+
+ setSearch(e.target.value)} + leftIcon={} + placeholder="Search connections..." + className="flex-1" + /> +
+ + + + + + + + + + + {isGatewayLoading && ( + + )} + {filteredGateway?.map((el) => ( + + + + + + ))} + +
NameIssued AtIdentity +
{el.name}{format(new Date(el.issuedAt), "yyyy-MM-dd")}{el.identity.name} +
+ {!isGatewayLoading && !filteredGateway?.length && ( + + )} +
+
+
+
+
+ + ); + }, + { + action: OrgPermissionAppConnectionActions.Read, + subject: OrgPermissionSubjects.AppConnections + } +); diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/route.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/route.tsx new file mode 100644 index 000000000..ab03869a3 --- /dev/null +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/route.tsx @@ -0,0 +1,23 @@ +import { faHome } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { createFileRoute, linkOptions } from "@tanstack/react-router"; + +import { GatewayListPage } from "./GatewayListPage"; + +export const Route = createFileRoute( + "/_authenticate/_inject-org-details/_org-layout/organization/gateways/" +)({ + component: GatewayListPage, + context: () => ({ + breadcrumbs: [ + { + label: "Home", + icon: () => , + link: linkOptions({ to: "/organization/secret-manager/overview" }) + }, + { + label: "Gateways" + } + ] + }) +}); diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts index 209373285..985bbbddd 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts +++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts @@ -3,6 +3,7 @@ import { z } from "zod"; import { OrgPermissionSubjects } from "@app/context"; import { + OrgGatewayPermissionActions, OrgPermissionAppConnectionActions, OrgPermissionKmipActions } from "@app/context/OrgPermissionContext/types"; @@ -34,6 +35,15 @@ const kmipPermissionSchema = z }) .optional(); +const orgGatewayPermissionSchema = z + .object({ + [OrgGatewayPermissionActions.Read]: z.boolean().optional(), + [OrgGatewayPermissionActions.Edit]: z.boolean().optional(), + [OrgGatewayPermissionActions.Delete]: z.boolean().optional(), + [OrgGatewayPermissionActions.Create]: z.boolean().optional() + }) + .optional(); + const adminConsolePermissionSchmea = z .object({ "access-all-projects": z.boolean().optional() @@ -72,7 +82,8 @@ export const formSchema = z.object({ [OrgPermissionSubjects.Kms]: generalPermissionSchema, [OrgPermissionSubjects.ProjectTemplates]: generalPermissionSchema, "app-connections": appConnectionsPermissionSchema, - kmip: kmipPermissionSchema + kmip: kmipPermissionSchema, + [OrgPermissionSubjects.Gateway]: orgGatewayPermissionSchema }) .optional() }); diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx new file mode 100644 index 000000000..efafa6a42 --- /dev/null +++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx @@ -0,0 +1,182 @@ +import { useEffect, useMemo } from "react"; +import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form"; +import { faChevronDown, faChevronRight } from "@fortawesome/free-solid-svg-icons"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; + +import { createNotification } from "@app/components/notifications"; +import { Checkbox, Select, SelectItem, Td, Tr } from "@app/components/v2"; +import { OrgGatewayPermissionActions } from "@app/context/OrgPermissionContext/types"; +import { useToggle } from "@app/hooks"; + +import { TFormSchema } from "../OrgRoleModifySection.utils"; + +type Props = { + isEditable: boolean; + setValue: UseFormSetValue; + control: Control; +}; + +enum Permission { + NoAccess = "no-access", + ReadOnly = "read-only", + FullAccess = "full-access", + Custom = "custom" +} + +const PERMISSION_ACTIONS = [ + { action: OrgGatewayPermissionActions.Read, label: "Read" }, + { action: OrgGatewayPermissionActions.Create, label: "Create" }, + { action: OrgGatewayPermissionActions.Edit, label: "Modify" }, + { action: OrgGatewayPermissionActions.Delete, label: "Remove" } +] as const; + +export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props) => { + const [isRowExpanded, setIsRowExpanded] = useToggle(); + const [isCustom, setIsCustom] = useToggle(); + + const rule = useWatch({ + control, + name: "permissions.gateway" + }); + + const selectedPermissionCategory = useMemo(() => { + const actions = Object.keys(rule || {}) as Array; + const totalActions = PERMISSION_ACTIONS.length; + const score = actions.map((key) => (rule?.[key] ? 1 : 0)).reduce((a, b) => a + b, 0 as number); + + if (isCustom) return Permission.Custom; + if (score === 0) return Permission.NoAccess; + if (score === totalActions) return Permission.FullAccess; + if (score === 1 && rule?.[OrgGatewayPermissionActions.Read]) return Permission.ReadOnly; + + return Permission.Custom; + }, [rule, isCustom]); + + useEffect(() => { + if (selectedPermissionCategory === Permission.Custom) setIsCustom.on(); + else setIsCustom.off(); + }, [selectedPermissionCategory]); + + useEffect(() => { + const isRowCustom = selectedPermissionCategory === Permission.Custom; + if (isRowCustom) { + setIsRowExpanded.on(); + } + }, []); + + const handlePermissionChange = (val: Permission) => { + if (!val) return; + if (val === Permission.Custom) { + setIsRowExpanded.on(); + setIsCustom.on(); + return; + } + setIsCustom.off(); + + switch (val) { + case Permission.FullAccess: + setValue( + "permissions.app-connections", + { + [OrgGatewayPermissionActions.Read]: true, + [OrgGatewayPermissionActions.Edit]: true, + [OrgGatewayPermissionActions.Create]: true, + [OrgGatewayPermissionActions.Delete]: true + }, + { shouldDirty: true } + ); + break; + case Permission.ReadOnly: + setValue( + "permissions.app-connections", + { + [OrgGatewayPermissionActions.Read]: true, + [OrgGatewayPermissionActions.Edit]: false, + [OrgGatewayPermissionActions.Create]: false, + [OrgGatewayPermissionActions.Delete]: false + }, + { shouldDirty: true } + ); + break; + + case Permission.NoAccess: + default: + setValue( + "permissions.app-connections", + { + [OrgGatewayPermissionActions.Read]: false, + [OrgGatewayPermissionActions.Edit]: false, + [OrgGatewayPermissionActions.Create]: false, + [OrgGatewayPermissionActions.Delete]: false + }, + { shouldDirty: true } + ); + } + }; + + return ( + <> + setIsRowExpanded.toggle()} + > + + + + Gateways + + + + + {isRowExpanded && ( + + +
+ {PERMISSION_ACTIONS.map(({ action, label }) => { + return ( + ( + { + if (!isEditable) { + createNotification({ + type: "error", + text: "Failed to update default role" + }); + return; + } + field.onChange(e); + }} + id={`permissions.gateways.${action}`} + > + {label} + + )} + /> + ); + })} +
+ + + )} + + ); +}; diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts index 3b7f260ad..aa74e98ad 100644 --- a/frontend/src/routeTree.gen.ts +++ b/frontend/src/routeTree.gen.ts @@ -60,6 +60,7 @@ import { Route as organizationKmsOverviewPageRouteImport } from './pages/organiz import { Route as organizationIdentityDetailsByIDPageRouteImport } from './pages/organization/IdentityDetailsByIDPage/route' import { Route as organizationGroupDetailsByIDPageRouteImport } from './pages/organization/GroupDetailsByIDPage/route' import { Route as organizationCertManagerOverviewPageRouteImport } from './pages/organization/CertManagerOverviewPage/route' +import { Route as organizationGatewaysGatewayListPageRouteImport } from './pages/organization/Gateways/GatewayListPage/route' import { Route as organizationAppConnectionsAppConnectionsPageRouteImport } from './pages/organization/AppConnections/AppConnectionsPage/route' import { Route as projectAccessControlPageRouteSshImport } from './pages/project/AccessControlPage/route-ssh' import { Route as projectAccessControlPageRouteSecretManagerImport } from './pages/project/AccessControlPage/route-secret-manager' @@ -209,6 +210,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdImport = createFileRoute( '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId', )() +const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport = + createFileRoute( + '/_authenticate/_inject-org-details/_org-layout/organization/gateways', + )() const AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsImport = createFileRoute( '/_authenticate/_inject-org-details/_org-layout/organization/app-connections', @@ -454,6 +459,14 @@ const AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdRoute = getParentRoute: () => organizationLayoutRoute, } as any) +const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute = + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport.update({ + id: '/gateways', + path: '/gateways', + getParentRoute: () => + AuthenticateInjectOrgDetailsOrgLayoutOrganizationRoute, + } as any) + const AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRoute = AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsImport.update({ id: '/app-connections', @@ -625,6 +638,14 @@ const organizationCertManagerOverviewPageRouteRoute = AuthenticateInjectOrgDetailsOrgLayoutOrganizationRoute, } as any) +const organizationGatewaysGatewayListPageRouteRoute = + organizationGatewaysGatewayListPageRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute, + } as any) + const organizationAppConnectionsAppConnectionsPageRouteRoute = organizationAppConnectionsAppConnectionsPageRouteImport.update({ id: '/', @@ -1886,6 +1907,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsImport parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationImport } + '/_authenticate/_inject-org-details/_org-layout/organization/gateways': { + id: '/_authenticate/_inject-org-details/_org-layout/organization/gateways' + path: '/gateways' + fullPath: '/organization/gateways' + preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport + parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationImport + } '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId': { id: '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId' path: '/secret-manager/$projectId' @@ -1907,6 +1935,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof organizationAppConnectionsAppConnectionsPageRouteImport parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsImport } + '/_authenticate/_inject-org-details/_org-layout/organization/gateways/': { + id: '/_authenticate/_inject-org-details/_org-layout/organization/gateways/' + path: '/' + fullPath: '/organization/gateways/' + preLoaderRoute: typeof organizationGatewaysGatewayListPageRouteImport + parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport + } '/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview': { id: '/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview' path: '/cert-manager/overview' @@ -2900,6 +2935,21 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithCh AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteChildren, ) +interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteChildren { + organizationGatewaysGatewayListPageRouteRoute: typeof organizationGatewaysGatewayListPageRouteRoute +} + +const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteChildren = + { + organizationGatewaysGatewayListPageRouteRoute: + organizationGatewaysGatewayListPageRouteRoute, + } + +const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren = + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute._addFileChildren( + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteChildren, + ) + interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationRouteChildren { organizationAccessManagementPageRouteRoute: typeof organizationAccessManagementPageRouteRoute organizationAdminPageRouteRoute: typeof organizationAdminPageRouteRoute @@ -2909,6 +2959,7 @@ interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationRouteChildren { organizationSecretSharingPageRouteRoute: typeof organizationSecretSharingPageRouteRoute organizationSettingsPageRouteRoute: typeof organizationSettingsPageRouteRoute AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren organizationCertManagerOverviewPageRouteRoute: typeof organizationCertManagerOverviewPageRouteRoute organizationGroupDetailsByIDPageRouteRoute: typeof organizationGroupDetailsByIDPageRouteRoute organizationIdentityDetailsByIDPageRouteRoute: typeof organizationIdentityDetailsByIDPageRouteRoute @@ -2933,6 +2984,8 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRouteChildren: Authentica organizationSettingsPageRouteRoute: organizationSettingsPageRouteRoute, AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRoute: AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren, + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute: + AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren, organizationCertManagerOverviewPageRouteRoute: organizationCertManagerOverviewPageRouteRoute, organizationGroupDetailsByIDPageRouteRoute: @@ -3608,9 +3661,11 @@ export interface FileRoutesByFullPath { '/cert-manager/$projectId': typeof certManagerLayoutRouteWithChildren '/kms/$projectId': typeof kmsLayoutRouteWithChildren '/organization/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren + '/organization/gateways': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren '/secret-manager/$projectId': typeof secretManagerLayoutRouteWithChildren '/ssh/$projectId': typeof sshLayoutRouteWithChildren '/organization/app-connections/': typeof organizationAppConnectionsAppConnectionsPageRouteRoute + '/organization/gateways/': typeof organizationGatewaysGatewayListPageRouteRoute '/organization/cert-manager/overview': typeof organizationCertManagerOverviewPageRouteRoute '/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute '/organization/identities/$identityId': typeof organizationIdentityDetailsByIDPageRouteRoute @@ -3780,6 +3835,7 @@ export interface FileRoutesByTo { '/secret-manager/$projectId': typeof secretManagerLayoutRouteWithChildren '/ssh/$projectId': typeof sshLayoutRouteWithChildren '/organization/app-connections': typeof organizationAppConnectionsAppConnectionsPageRouteRoute + '/organization/gateways': typeof organizationGatewaysGatewayListPageRouteRoute '/organization/cert-manager/overview': typeof organizationCertManagerOverviewPageRouteRoute '/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute '/organization/identities/$identityId': typeof organizationIdentityDetailsByIDPageRouteRoute @@ -3956,9 +4012,11 @@ export interface FileRoutesById { '/_authenticate/_inject-org-details/_org-layout/cert-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutCertManagerProjectIdRouteWithChildren '/_authenticate/_inject-org-details/_org-layout/kms/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutKmsProjectIdRouteWithChildren '/_authenticate/_inject-org-details/_org-layout/organization/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren + '/_authenticate/_inject-org-details/_org-layout/organization/gateways': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdRouteWithChildren '/_authenticate/_inject-org-details/_org-layout/ssh/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutSshProjectIdRouteWithChildren '/_authenticate/_inject-org-details/_org-layout/organization/app-connections/': typeof organizationAppConnectionsAppConnectionsPageRouteRoute + '/_authenticate/_inject-org-details/_org-layout/organization/gateways/': typeof organizationGatewaysGatewayListPageRouteRoute '/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview': typeof organizationCertManagerOverviewPageRouteRoute '/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute '/_authenticate/_inject-org-details/_org-layout/organization/identities/$identityId': typeof organizationIdentityDetailsByIDPageRouteRoute @@ -4136,9 +4194,11 @@ export interface FileRouteTypes { | '/cert-manager/$projectId' | '/kms/$projectId' | '/organization/app-connections' + | '/organization/gateways' | '/secret-manager/$projectId' | '/ssh/$projectId' | '/organization/app-connections/' + | '/organization/gateways/' | '/organization/cert-manager/overview' | '/organization/groups/$groupId' | '/organization/identities/$identityId' @@ -4307,6 +4367,7 @@ export interface FileRouteTypes { | '/secret-manager/$projectId' | '/ssh/$projectId' | '/organization/app-connections' + | '/organization/gateways' | '/organization/cert-manager/overview' | '/organization/groups/$groupId' | '/organization/identities/$identityId' @@ -4481,9 +4542,11 @@ export interface FileRouteTypes { | '/_authenticate/_inject-org-details/_org-layout/cert-manager/$projectId' | '/_authenticate/_inject-org-details/_org-layout/kms/$projectId' | '/_authenticate/_inject-org-details/_org-layout/organization/app-connections' + | '/_authenticate/_inject-org-details/_org-layout/organization/gateways' | '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId' | '/_authenticate/_inject-org-details/_org-layout/ssh/$projectId' | '/_authenticate/_inject-org-details/_org-layout/organization/app-connections/' + | '/_authenticate/_inject-org-details/_org-layout/organization/gateways/' | '/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview' | '/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId' | '/_authenticate/_inject-org-details/_org-layout/organization/identities/$identityId' @@ -4848,6 +4911,7 @@ export const routeTree = rootRoute "/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing", "/_authenticate/_inject-org-details/_org-layout/organization/settings", "/_authenticate/_inject-org-details/_org-layout/organization/app-connections", + "/_authenticate/_inject-org-details/_org-layout/organization/gateways", "/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview", "/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId", "/_authenticate/_inject-org-details/_org-layout/organization/identities/$identityId", @@ -4919,6 +4983,13 @@ export const routeTree = rootRoute "/_authenticate/_inject-org-details/_org-layout/organization/app-connections/$appConnection/oauth/callback" ] }, + "/_authenticate/_inject-org-details/_org-layout/organization/gateways": { + "filePath": "", + "parent": "/_authenticate/_inject-org-details/_org-layout/organization", + "children": [ + "/_authenticate/_inject-org-details/_org-layout/organization/gateways/" + ] + }, "/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId": { "filePath": "", "parent": "/_authenticate/_inject-org-details/_org-layout", @@ -4937,6 +5008,10 @@ export const routeTree = rootRoute "filePath": "organization/AppConnections/AppConnectionsPage/route.tsx", "parent": "/_authenticate/_inject-org-details/_org-layout/organization/app-connections" }, + "/_authenticate/_inject-org-details/_org-layout/organization/gateways/": { + "filePath": "organization/Gateways/GatewayListPage/route.tsx", + "parent": "/_authenticate/_inject-org-details/_org-layout/organization/gateways" + }, "/_authenticate/_inject-org-details/_org-layout/organization/cert-manager/overview": { "filePath": "organization/CertManagerOverviewPage/route.tsx", "parent": "/_authenticate/_inject-org-details/_org-layout/organization" diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts index d1c64d47e..bc04e9631 100644 --- a/frontend/src/routes.ts +++ b/frontend/src/routes.ts @@ -29,7 +29,8 @@ const organizationRoutes = route("/organization", [ "/$appConnection/oauth/callback", "organization/AppConnections/OauthCallbackPage/route.tsx" ) - ]) + ]), + route("/gateways", [index("organization/Gateways/GatewayListPage/route.tsx")]) ]); const secretManagerRoutes = route("/secret-manager/$projectId", [ From 852002995813b76bf88461b175e18f62f1c64cf8 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 17 Feb 2025 13:40:11 +0530 Subject: [PATCH 05/30] feat: updated backend to new data structure for org --- backend/src/@types/knex.d.ts | 22 +- .../20250212191958_create-gateway.ts | 65 ++--- .../src/db/schemas/gateway-instance-config.ts | 33 --- backend/src/db/schemas/index.ts | 3 +- backend/src/db/schemas/models.ts | 3 +- backend/src/db/schemas/org-gateway-config.ts | 43 +++ backend/src/db/schemas/org-gateway-root-ca.ts | 27 -- backend/src/ee/routes/v1/gateway-router.ts | 1 + .../gateway/gateway-instance-config-dal.ts | 11 - .../ee/services/gateway/gateway-service.ts | 261 ++++++++++++++---- .../gateway/org-gateway-config-dal.ts | 10 + .../gateway/org-gateway-root-ca-dal.ts | 10 - backend/src/keystore/keystore.ts | 5 +- backend/src/lib/config/env.ts | 1 + backend/src/server/routes/index.ts | 11 +- backend/src/server/routes/v1/admin-router.ts | 85 +----- .../super-admin/super-admin-service.ts | 158 +---------- 17 files changed, 310 insertions(+), 439 deletions(-) delete mode 100644 backend/src/db/schemas/gateway-instance-config.ts create mode 100644 backend/src/db/schemas/org-gateway-config.ts delete mode 100644 backend/src/db/schemas/org-gateway-root-ca.ts delete mode 100644 backend/src/ee/services/gateway/gateway-instance-config-dal.ts create mode 100644 backend/src/ee/services/gateway/org-gateway-config-dal.ts delete mode 100644 backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts index b09b02046..416a0013b 100644 --- a/backend/src/@types/knex.d.ts +++ b/backend/src/@types/knex.d.ts @@ -68,9 +68,6 @@ import { TExternalKms, TExternalKmsInsert, TExternalKmsUpdate, - TGatewayInstanceConfig, - TGatewayInstanceConfigInsert, - TGatewayInstanceConfigUpdate, TGateways, TGatewaysInsert, TGatewaysUpdate, @@ -185,9 +182,9 @@ import { TOrgBots, TOrgBotsInsert, TOrgBotsUpdate, - TOrgGatewayRootCa, - TOrgGatewayRootCaInsert, - TOrgGatewayRootCaUpdate, + TOrgGatewayConfig, + TOrgGatewayConfigInsert, + TOrgGatewayConfigUpdate, TOrgMemberships, TOrgMembershipsInsert, TOrgMembershipsUpdate, @@ -940,15 +937,10 @@ declare module "knex/types/tables" { TKmipClientCertificatesUpdate >; [TableName.Gateway]: KnexOriginal.CompositeTableType; - [TableName.GatewayInstanceConfig]: KnexOriginal.CompositeTableType< - TGatewayInstanceConfig, - TGatewayInstanceConfigInsert, - TGatewayInstanceConfigUpdate - >; - [TableName.OrgGatewayRootCa]: KnexOriginal.CompositeTableType< - TOrgGatewayRootCa, - TOrgGatewayRootCaInsert, - TOrgGatewayRootCaUpdate + [TableName.OrgGatewayConfig]: KnexOriginal.CompositeTableType< + TOrgGatewayConfig, + TOrgGatewayConfigInsert, + TOrgGatewayConfigUpdate >; } } diff --git a/backend/src/db/migrations/20250212191958_create-gateway.ts b/backend/src/db/migrations/20250212191958_create-gateway.ts index 635cd7427..ee9ef0ef7 100644 --- a/backend/src/db/migrations/20250212191958_create-gateway.ts +++ b/backend/src/db/migrations/20250212191958_create-gateway.ts @@ -4,47 +4,43 @@ import { TableName } from "../schemas"; import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils"; export async function up(knex: Knex): Promise { - if (!(await knex.schema.hasTable(TableName.GatewayInstanceConfig))) { - await knex.schema.createTable(TableName.GatewayInstanceConfig, (t) => { + if (!(await knex.schema.hasTable(TableName.OrgGatewayConfig))) { + await knex.schema.createTable(TableName.OrgGatewayConfig, (t) => { t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); - t.string("caKeyAlgorithm").notNullable(); - t.boolean("isDisabled").defaultTo(false); + t.string("rootCaKeyAlgorithm").notNullable(); - t.string("infisicalClientCaSerialNumber").notNullable(); - t.datetime("infisicalClientCaIssuedAt").notNullable(); - t.datetime("infisicalClientCaExpiration").notNullable(); - t.binary("encryptedInfisicalClientCaCertificate").notNullable(); - t.binary("encryptedInfisicalClientCaPrivateKey").notNullable(); + t.datetime("rootCaIssuedAt").notNullable(); + t.datetime("rootCaExpiration").notNullable(); + t.string("rootCaSerialNumber").notNullable(); + t.binary("encryptedRootCaCertificate").notNullable(); + t.binary("encryptedRootCaPrivateKey").notNullable(); - t.string("infisicalClientCertSerialNumber").notNullable(); - t.string("infisicalClientCertKeyAlgorithm").notNullable(); - t.datetime("infisicalClientCertIssuedAt").notNullable(); - t.datetime("infisicalClientCertExpiration").notNullable(); - t.binary("encryptedInfisicalClientCertificate").notNullable(); - t.binary("encryptedInfisicalClientPrivateKey").notNullable(); - t.timestamps(true, true, true); - }); + t.datetime("clientCaIssuedAt").notNullable(); + t.datetime("clientCaExpiration").notNullable(); + t.string("clientCaSerialNumber"); + t.binary("encryptedClientCaCertificate").notNullable(); + t.binary("encryptedClientCaPrivateKey").notNullable(); - await createOnUpdateTrigger(knex, TableName.GatewayInstanceConfig); - } + t.string("clientCertSerialNumber").notNullable(); + t.string("clientCertKeyAlgorithm").notNullable(); + t.datetime("clientCertIssuedAt").notNullable(); + t.datetime("clientCertExpiration").notNullable(); + t.binary("encryptedClientCertificate").notNullable(); + t.binary("encryptedClientPrivateKey").notNullable(); - if (!(await knex.schema.hasTable(TableName.OrgGatewayRootCa))) { - await knex.schema.createTable(TableName.OrgGatewayRootCa, (t) => { - t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid()); - t.string("caKeyAlgorithm").notNullable(); - t.string("caSerialNumber").notNullable(); - t.datetime("caIssuedAt").notNullable(); - t.datetime("caExpiration").notNullable(); - t.binary("encryptedCaCertificate").notNullable(); - t.binary("encryptedCaPrivateKey").notNullable(); + t.datetime("gatewayCaIssuedAt").notNullable(); + t.datetime("gatewayCaExpiration").notNullable(); + t.string("gatewayCaSerialNumber").notNullable(); + t.binary("encryptedGatewayCaCertificate").notNullable(); + t.binary("encryptedGatewayCaPrivateKey").notNullable(); t.uuid("orgId").notNullable(); t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE"); - + t.unique("orgId"); t.timestamps(true, true, true); }); - await createOnUpdateTrigger(knex, TableName.OrgGatewayRootCa); + await createOnUpdateTrigger(knex, TableName.OrgGatewayConfig); } if (!(await knex.schema.hasTable(TableName.Gateway))) { @@ -60,7 +56,7 @@ export async function up(knex: Knex): Promise { t.binary("relayAddress").notNullable(); t.uuid("orgGatewayRootCaId").notNullable(); - t.foreign("orgGatewayRootCaId").references("id").inTable(TableName.OrgGatewayRootCa).onDelete("CASCADE"); + t.foreign("orgGatewayRootCaId").references("id").inTable(TableName.OrgGatewayConfig).onDelete("CASCADE"); t.uuid("identityId").notNullable(); t.foreign("identityId").references("id").inTable(TableName.Identity).onDelete("CASCADE"); @@ -73,12 +69,9 @@ export async function up(knex: Knex): Promise { } export async function down(knex: Knex): Promise { - await knex.schema.dropTableIfExists(TableName.GatewayInstanceConfig); - await dropOnUpdateTrigger(knex, TableName.GatewayInstanceConfig); - await knex.schema.dropTableIfExists(TableName.Gateway); await dropOnUpdateTrigger(knex, TableName.Gateway); - await knex.schema.dropTableIfExists(TableName.OrgGatewayRootCa); - await dropOnUpdateTrigger(knex, TableName.OrgGatewayRootCa); + await knex.schema.dropTableIfExists(TableName.OrgGatewayConfig); + await dropOnUpdateTrigger(knex, TableName.OrgGatewayConfig); } diff --git a/backend/src/db/schemas/gateway-instance-config.ts b/backend/src/db/schemas/gateway-instance-config.ts deleted file mode 100644 index f59b4b781..000000000 --- a/backend/src/db/schemas/gateway-instance-config.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Code generated by automation script, DO NOT EDIT. -// Automated by pulling database and generating zod schema -// To update. Just run npm run generate:schema -// Written by akhilmhdh. - -import { z } from "zod"; - -import { zodBuffer } from "@app/lib/zod"; - -import { TImmutableDBKeys } from "./models"; - -export const GatewayInstanceConfigSchema = z.object({ - id: z.string().uuid(), - caKeyAlgorithm: z.string(), - isDisabled: z.boolean().default(false).nullable().optional(), - infisicalClientCaSerialNumber: z.string(), - infisicalClientCaIssuedAt: z.date(), - infisicalClientCaExpiration: z.date(), - encryptedInfisicalClientCaCertificate: zodBuffer, - encryptedInfisicalClientCaPrivateKey: zodBuffer, - infisicalClientCertSerialNumber: z.string(), - infisicalClientCertKeyAlgorithm: z.string(), - infisicalClientCertIssuedAt: z.date(), - infisicalClientCertExpiration: z.date(), - encryptedInfisicalClientCertificate: zodBuffer, - encryptedInfisicalClientPrivateKey: zodBuffer, - createdAt: z.date(), - updatedAt: z.date() -}); - -export type TGatewayInstanceConfig = z.infer; -export type TGatewayInstanceConfigInsert = Omit, TImmutableDBKeys>; -export type TGatewayInstanceConfigUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts index 9e03cb246..b4d4138f8 100644 --- a/backend/src/db/schemas/index.ts +++ b/backend/src/db/schemas/index.ts @@ -20,7 +20,6 @@ export * from "./certificates"; export * from "./dynamic-secret-leases"; export * from "./dynamic-secrets"; export * from "./external-kms"; -export * from "./gateway-instance-config"; export * from "./gateways"; export * from "./git-app-install-sessions"; export * from "./git-app-org"; @@ -59,7 +58,7 @@ export * from "./ldap-group-maps"; export * from "./models"; export * from "./oidc-configs"; export * from "./org-bots"; -export * from "./org-gateway-root-ca"; +export * from "./org-gateway-config"; export * from "./org-memberships"; export * from "./org-roles"; export * from "./organizations"; diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts index 069a9ea51..7d7f2fe4e 100644 --- a/backend/src/db/schemas/models.ts +++ b/backend/src/db/schemas/models.ts @@ -114,8 +114,7 @@ export enum TableName { SnapshotSecretV2 = "secret_snapshot_secrets_v2", ProjectSplitBackfillIds = "project_split_backfill_ids", // Gateway - GatewayInstanceConfig = "gateway_instance_config", - OrgGatewayRootCa = "org_gateway_root_ca", + OrgGatewayConfig = "org_gateway_config", Gateway = "gateways", // junction tables with tags SecretV2JnTag = "secret_v2_tag_junction", diff --git a/backend/src/db/schemas/org-gateway-config.ts b/backend/src/db/schemas/org-gateway-config.ts new file mode 100644 index 000000000..ddf18c3fc --- /dev/null +++ b/backend/src/db/schemas/org-gateway-config.ts @@ -0,0 +1,43 @@ +// Code generated by automation script, DO NOT EDIT. +// Automated by pulling database and generating zod schema +// To update. Just run npm run generate:schema +// Written by akhilmhdh. + +import { z } from "zod"; + +import { zodBuffer } from "@app/lib/zod"; + +import { TImmutableDBKeys } from "./models"; + +export const OrgGatewayConfigSchema = z.object({ + id: z.string().uuid(), + rootCaKeyAlgorithm: z.string(), + rootCaIssuedAt: z.date(), + rootCaExpiration: z.date(), + rootCaSerialNumber: z.string(), + encryptedRootCaCertificate: zodBuffer, + encryptedRootCaPrivateKey: zodBuffer, + clientCaIssuedAt: z.date(), + clientCaExpiration: z.date(), + clientCaSerialNumber: z.string().nullable().optional(), + encryptedClientCaCertificate: zodBuffer, + encryptedClientCaPrivateKey: zodBuffer, + clientCertSerialNumber: z.string(), + clientCertKeyAlgorithm: z.string(), + clientCertIssuedAt: z.date(), + clientCertExpiration: z.date(), + encryptedClientCertificate: zodBuffer, + encryptedClientPrivateKey: zodBuffer, + gatewayCaIssuedAt: z.date(), + gatewayCaExpiration: z.date(), + gatewayCaSerialNumber: z.string(), + encryptedGatewayCaCertificate: zodBuffer, + encryptedGatewayCaPrivateKey: zodBuffer, + orgId: z.string().uuid(), + createdAt: z.date(), + updatedAt: z.date() +}); + +export type TOrgGatewayConfig = z.infer; +export type TOrgGatewayConfigInsert = Omit, TImmutableDBKeys>; +export type TOrgGatewayConfigUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/db/schemas/org-gateway-root-ca.ts b/backend/src/db/schemas/org-gateway-root-ca.ts deleted file mode 100644 index 96c36fb37..000000000 --- a/backend/src/db/schemas/org-gateway-root-ca.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Code generated by automation script, DO NOT EDIT. -// Automated by pulling database and generating zod schema -// To update. Just run npm run generate:schema -// Written by akhilmhdh. - -import { z } from "zod"; - -import { zodBuffer } from "@app/lib/zod"; - -import { TImmutableDBKeys } from "./models"; - -export const OrgGatewayRootCaSchema = z.object({ - id: z.string().uuid(), - caKeyAlgorithm: z.string(), - caSerialNumber: z.string(), - caIssuedAt: z.date(), - caExpiration: z.date(), - encryptedCaCertificate: zodBuffer, - encryptedCaPrivateKey: zodBuffer, - orgId: z.string().uuid(), - createdAt: z.date(), - updatedAt: z.date() -}); - -export type TOrgGatewayRootCa = z.infer; -export type TOrgGatewayRootCaInsert = Omit, TImmutableDBKeys>; -export type TOrgGatewayRootCaUpdate = Partial, TImmutableDBKeys>>; diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts index 27dbd850b..4282d41e0 100644 --- a/backend/src/ee/routes/v1/gateway-router.ts +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -27,6 +27,7 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { 200: z.object({ turnServerUsername: z.string(), turnServerPassword: z.string(), + turnServerRealm: z.string(), turnServerAddress: z.string(), infisicalStaticIp: z.string() }) diff --git a/backend/src/ee/services/gateway/gateway-instance-config-dal.ts b/backend/src/ee/services/gateway/gateway-instance-config-dal.ts deleted file mode 100644 index 14dcb7b9f..000000000 --- a/backend/src/ee/services/gateway/gateway-instance-config-dal.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { TDbClient } from "@app/db"; -import { TableName } from "@app/db/schemas"; -import { ormify } from "@app/lib/knex"; - -export type TGatewayInstanceConfigDALFactory = ReturnType; - -export const gatewayInstanceConfigDALFactory = (db: TDbClient) => { - const orm = ormify(db, TableName.GatewayInstanceConfig); - - return orm; -}; diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index 1d3b87e15..330d48d0e 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -2,6 +2,8 @@ import crypto from "node:crypto"; import { ForbiddenError } from "@casl/ability"; import * as x509 from "@peculiar/x509"; +import fs from "fs/promises"; +import path from "path/posix"; import { PgSqlLock } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; @@ -21,13 +23,13 @@ import { OrgGatewayPermissionActions, OrgPermissionSubjects } from "../permissio import { TPermissionServiceFactory } from "../permission/permission-service"; import { TGatewayDALFactory } from "./gateway-dal"; import { TExchangeAllocatedRelayAddressDTO, TGetGatewayByIdDTO, TListGatewaysDTO } from "./gateway-types"; -import { TOrgGatewayRootCaDALFactory } from "./org-gateway-root-ca-dal"; +import { TOrgGatewayConfigDALFactory } from "./org-gateway-config-dal"; type TGatewayServiceFactoryDep = { gatewayDAL: TGatewayDALFactory; - orgGatewayRootCaDAL: Pick; + orgGatewayConfigDAL: Pick; licenseService: Pick; - kmsService: Pick; + kmsService: Pick; permissionService: Pick; }; @@ -37,9 +39,9 @@ export type TGatewayServiceFactory = ReturnType; export const gatewayServiceFactory = ({ gatewayDAL, licenseService, - orgGatewayRootCaDAL, kmsService, - permissionService + permissionService, + orgGatewayConfigDAL }: TGatewayServiceFactoryDep) => { const $validateOrgAccessToGateway = async (orgId: string) => { if (!licenseService.onPremFeatures.gateway) { @@ -64,7 +66,8 @@ export const gatewayServiceFactory = ({ if ( !envCfg.GATEWAY_RELAY_AUTH_SECRET || !envCfg.GATEWAY_RELAY_ADDRESS || - !envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS + !envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS || + !envCfg.GATEWAY_RELAY_REALM ) { throw new BadRequestError({ message: "Gateway handshake failed due to missing instance config." @@ -79,6 +82,7 @@ export const gatewayServiceFactory = ({ return { turnServerUsername, turnServerPassword, + turnServerRealm: envCfg.GATEWAY_RELAY_REALM, turnServerAddress: envCfg.GATEWAY_RELAY_ADDRESS, infisicalStaticIp: envCfg.GATEWAY_INFISICAL_STATIC_IP_ADDRESS }; @@ -94,63 +98,208 @@ export const gatewayServiceFactory = ({ orgId: identityOrg }); - const orgGatewayRootCa = await orgGatewayRootCaDAL.transaction(async (tx) => { + const orgGatewayConfig = await orgGatewayConfigDAL.transaction(async (tx) => { await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayRootCaInit(identityOrg)]); - const existingGateway = await orgGatewayRootCaDAL.findOne({ orgId: identityOrg }); - if (existingGateway) return existingGateway; + const existingGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: identityOrg }); + if (existingGatewayConfig) return existingGatewayConfig; + const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048); // generate root CA - const orgGatewayRootCaSerialNumber = createSerialNumber(); - const orgGatewayRootCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); - const orgGatewayCaSkObj = crypto.KeyObject.from(orgGatewayRootCaKeys.privateKey); - const orgGatewayCaIssuedAt = new Date(); - const orgGatewayCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 25)); - - const orgGatewayCaCert = await x509.X509CertificateGenerator.createSelfSigned({ - name: `CN=Org Gateway Root CA,O=${identityOrg}`, - serialNumber: orgGatewayRootCaSerialNumber, - notBefore: orgGatewayCaIssuedAt, - notAfter: orgGatewayCaExpiration, + const rootCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const rootCaSerialNumber = createSerialNumber(); + const rootCaSkObj = crypto.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: "CN=Infisical Gateway Root CA", + serialNumber: rootCaSerialNumber, + notBefore: rootCaIssuedAt, + notAfter: rootCaExpiration, signingAlgorithm: alg, - keys: orgGatewayRootCaKeys, + keys: rootCaKeys, extensions: [ // eslint-disable-next-line no-bitwise new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), - await x509.SubjectKeyIdentifierExtension.create(orgGatewayRootCaKeys.publicKey) + await x509.SubjectKeyIdentifierExtension.create(rootCaKeys.publicKey) ] }); - return orgGatewayRootCaDAL.create({ + // generate client ca + const clientCaSerialNumber = createSerialNumber(); + const clientCaIssuedAt = new Date(); + const clientCaExpiration = new Date(new Date().setFullYear(2045)); + const clientCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const clientCaSkObj = crypto.KeyObject.from(clientCaKeys.privateKey); + + const clientCaCert = await x509.X509CertificateGenerator.create({ + serialNumber: clientCaSerialNumber, + subject: "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.subtle.generateKey(alg, true, ["sign", "verify"]); + const clientCertSerialNumber = createSerialNumber(); + const clientCert = await x509.X509CertificateGenerator.create({ + serialNumber: clientCertSerialNumber, + subject: "O=infisical,OU=gateway,CN=cloud-client", + 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.KeyObject.from(clientKeys.privateKey); + + // generate gateway ca + const gatewayCaSerialNumber = createSerialNumber(); + const gatewayCaIssuedAt = new Date(); + const gatewayCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10)); + const gatewayCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); + const gatewayCaSkObj = crypto.KeyObject.from(gatewayCaKeys.privateKey); + const gatewayCaCert = await x509.X509CertificateGenerator.create({ + serialNumber: gatewayCaSerialNumber, + subject: "CN=KMIP Server Intermediate 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) + ] + }); + + await fs.writeFile(path.join(__dirname, "./root-ca-cert"), rootCaCert.toString("pem")); + await fs.writeFile(path.join(__dirname, "./client-ca-cert"), clientCaCert.toString("pem")); + await fs.writeFile(path.join(__dirname, "./gateway-ca-cert"), gatewayCaCert.toString("pem")); + await fs.writeFile(path.join(__dirname, "./client-cert"), clientCert.toString("pem")); + await fs.writeFile( + path.join(__dirname, "./client-key"), + clientSkObj.export({ type: "pkcs8", format: "pem" }) as string + ); + + return orgGatewayConfigDAL.create({ orgId: identityOrg, - caIssuedAt: orgGatewayCaIssuedAt, - caExpiration: orgGatewayCaExpiration, - caSerialNumber: orgGatewayRootCaSerialNumber, - encryptedCaCertificate: orgKmsEncryptor({ plainText: Buffer.from(orgGatewayCaCert.rawData) }).cipherTextBlob, - encryptedCaPrivateKey: orgKmsEncryptor({ - plainText: orgGatewayCaSkObj.export({ + rootCaIssuedAt, + rootCaExpiration, + rootCaSerialNumber, + rootCaKeyAlgorithm, + encryptedRootCaPrivateKey: orgKmsEncryptor({ + plainText: rootCaSkObj.export({ type: "pkcs8", format: "der" }) }).cipherTextBlob, - caKeyAlgorithm: CertKeyAlgorithm.RSA_2048 + 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 caCertObj = new x509.X509Certificate( + const rootCaCert = new x509.X509Certificate( orgKmsDecryptor({ - cipherTextBlob: orgGatewayRootCa.encryptedCaCertificate + cipherTextBlob: orgGatewayConfig.encryptedRootCaCertificate }) ); - const caAlg = keyAlgorithmToAlgCfg(orgGatewayRootCa.caKeyAlgorithm as CertKeyAlgorithm); - const caSkObj = crypto.createPrivateKey({ - key: orgKmsDecryptor({ cipherTextBlob: orgGatewayRootCa.encryptedCaPrivateKey }), + const clientCaCert = new x509.X509Certificate( + orgKmsDecryptor({ + cipherTextBlob: orgGatewayConfig.encryptedClientCaCertificate + }) + ); + + const gatewayCaAlg = keyAlgorithmToAlgCfg(orgGatewayConfig.rootCaKeyAlgorithm as CertKeyAlgorithm); + const gatewayCaSkObj = crypto.createPrivateKey({ + key: orgKmsDecryptor({ cipherTextBlob: orgGatewayConfig.encryptedGatewayCaPrivateKey }), format: "der", type: "pkcs8" }); - const caPrivateKey = await crypto.subtle.importKey( + const gatewayCaPrivateKey = await crypto.subtle.importKey( "pkcs8", - caSkObj.export({ format: "der", type: "pkcs8" }), - caAlg, + gatewayCaSkObj.export({ format: "der", type: "pkcs8" }), + gatewayCaAlg, true, ["sign"] ); @@ -160,9 +309,10 @@ export const gatewayServiceFactory = ({ 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(caCertObj, false), + await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, false), await x509.SubjectKeyIdentifierExtension.create(gatewayKeys.publicKey), new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy new x509.KeyUsagesExtension( @@ -172,7 +322,8 @@ export const gatewayServiceFactory = ({ ), new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true), // san - new x509.SubjectAlternativeNameExtension([{ type: "ip", value: relayAddress }], false) + // TODO(gateway): change this later + new x509.SubjectAlternativeNameExtension([{ type: "ip", value: "127.0.0.1" }], false) ]; const serialNumber = createSerialNumber(); @@ -180,10 +331,10 @@ export const gatewayServiceFactory = ({ const gatewayCertificate = await x509.X509CertificateGenerator.create({ serialNumber, subject: `CN=${identityId},O=${identityOrg}`, - issuer: caCertObj.subject, + issuer: rootCaCert.subject, notBefore: certIssuedAt, notAfter: certExpireAt, - signingKey: caPrivateKey, + signingKey: gatewayCaPrivateKey, publicKey: gatewayKeys.publicKey, signingAlgorithm: alg, extensions @@ -191,7 +342,7 @@ export const gatewayServiceFactory = ({ await gatewayDAL.transaction(async (tx) => { await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.OrgGatewayCertExchange(identityOrg)]); - const existingGateway = await gatewayDAL.findOne({ identityId, orgGatewayRootCaId: orgGatewayRootCa.id }); + const existingGateway = await gatewayDAL.findOne({ identityId, orgGatewayRootCaId: orgGatewayConfig.id }); if (existingGateway) { return gatewayDAL.updateById(existingGateway.id, { keyAlgorithm: CertKeyAlgorithm.RSA_2048, @@ -209,16 +360,18 @@ export const gatewayServiceFactory = ({ serialNumber, relayAddress: orgKmsEncryptor({ plainText: Buffer.from(relayAddress) }).cipherTextBlob, identityId, - orgGatewayRootCaId: orgGatewayRootCa.id, + orgGatewayRootCaId: orgGatewayConfig.id, name: alphaNumericNanoId(8) }); }); + 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: caCertObj.toString("pem") + certificateChain: gatewayCertificateChain }; }; @@ -231,11 +384,11 @@ export const gatewayServiceFactory = ({ orgPermission.orgId ); ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); - const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); - if (!rootCa) return []; + const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); + if (!orgGatewayConfig) return []; const gateways = await gatewayDAL.find({ - orgGatewayRootCaId: rootCa.id + orgGatewayRootCaId: orgGatewayConfig.id }); return gateways; }; @@ -249,10 +402,10 @@ export const gatewayServiceFactory = ({ orgPermission.orgId ); ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); - const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); - if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); + 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: rootCa.id }); + const [gateway] = await gatewayDAL.find({ id, orgGatewayRootCaId: orgGatewayConfig.id }); if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); return gateway; }; @@ -266,10 +419,10 @@ export const gatewayServiceFactory = ({ orgPermission.orgId ); ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); - const rootCa = await orgGatewayRootCaDAL.findOne({ orgId: orgPermission.orgId }); - if (!rootCa) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); + 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: rootCa.id }); + const [gateway] = await gatewayDAL.delete({ id, orgGatewayRootCaId: orgGatewayConfig.id }); if (!gateway) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); return gateway; }; diff --git a/backend/src/ee/services/gateway/org-gateway-config-dal.ts b/backend/src/ee/services/gateway/org-gateway-config-dal.ts new file mode 100644 index 000000000..9d4f9384a --- /dev/null +++ b/backend/src/ee/services/gateway/org-gateway-config-dal.ts @@ -0,0 +1,10 @@ +import { TDbClient } from "@app/db"; +import { TableName } from "@app/db/schemas"; +import { ormify } from "@app/lib/knex"; + +export type TOrgGatewayConfigDALFactory = ReturnType; + +export const orgGatewayConfigDALFactory = (db: TDbClient) => { + const orm = ormify(db, TableName.OrgGatewayConfig); + return orm; +}; diff --git a/backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts b/backend/src/ee/services/gateway/org-gateway-root-ca-dal.ts deleted file mode 100644 index 4730f20f8..000000000 --- a/backend/src/ee/services/gateway/org-gateway-root-ca-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 TOrgGatewayRootCaDALFactory = ReturnType; - -export const orgGatewayRootCaDALFactory = (db: TDbClient) => { - const orm = ormify(db, TableName.OrgGatewayRootCa); - return orm; -}; diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts index 982dc21f9..76e93ce9f 100644 --- a/backend/src/keystore/keystore.ts +++ b/backend/src/keystore/keystore.ts @@ -1,13 +1,14 @@ import { Redis } from "ioredis"; import { Redlock, Settings } from "@app/lib/red-lock"; +import { pgAdvisoryLockHashText } from "@app/lib/crypto/hashtext"; export const PgSqlLock = { BootUpMigration: 2023, SuperAdminInit: 2024, KmsRootKeyInit: 2025, - OrgGatewayRootCaInit: (orgId: string) => `org-gateway-root-ca:${orgId}`, - OrgGatewayCertExchange: (orgId: string) => `org-gateway-cert-exchange:${orgId}` + OrgGatewayRootCaInit: (orgId: string) => pgAdvisoryLockHashText(`org-gateway-root-ca:${orgId}`), + OrgGatewayCertExchange: (orgId: string) => pgAdvisoryLockHashText(`org-gateway-cert-exchange:${orgId}`) } as const; export type TKeyStoreFactory = ReturnType; diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts index a286b4203..c51809849 100644 --- a/backend/src/lib/config/env.ts +++ b/backend/src/lib/config/env.ts @@ -187,6 +187,7 @@ const envSchema = z /* Gateway----------------------------------------------------------------------------- */ GATEWAY_INFISICAL_STATIC_IP_ADDRESS: zpStr(z.string().optional()), GATEWAY_RELAY_ADDRESS: zpStr(z.string().optional()), + GATEWAY_RELAY_REALM: zpStr(z.string().optional()), GATEWAY_RELAY_AUTH_SECRET: zpStr(z.string().optional()), /* ----------------------------------------------------------------------------- */ diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index fb8552744..ca6a16a6e 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -28,9 +28,8 @@ import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secre 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 { gatewayInstanceConfigDALFactory } from "@app/ee/services/gateway/gateway-instance-config-dal"; import { gatewayServiceFactory } from "@app/ee/services/gateway/gateway-service"; -import { orgGatewayRootCaDALFactory } from "@app/ee/services/gateway/org-gateway-root-ca-dal"; +import { orgGatewayConfigDALFactory } from "@app/ee/services/gateway/org-gateway-config-dal"; import { groupDALFactory } from "@app/ee/services/group/group-dal"; import { groupServiceFactory } from "@app/ee/services/group/group-service"; import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal"; @@ -397,8 +396,7 @@ export const registerRoutes = async ( const kmipOrgConfigDAL = kmipOrgConfigDALFactory(db); const kmipOrgServerCertificateDAL = kmipOrgServerCertificateDALFactory(db); - const gatewayInstanceConfigDAL = gatewayInstanceConfigDALFactory(db); - const orgGatewayRootCaDAL = orgGatewayRootCaDALFactory(db); + const orgGatewayConfigDAL = orgGatewayConfigDALFactory(db); const gatewayDAL = gatewayDALFactory(db); const permissionService = permissionServiceFactory({ @@ -639,7 +637,6 @@ export const registerRoutes = async ( authService: loginService, serverCfgDAL: superAdminDAL, kmsRootConfigDAL, - gatewayInstanceConfigDAL, orgService, keyStore, licenseService, @@ -1467,11 +1464,11 @@ export const registerRoutes = async ( }); const gatewayService = gatewayServiceFactory({ - orgGatewayRootCaDAL, permissionService, gatewayDAL, kmsService, - licenseService + licenseService, + orgGatewayConfigDAL }); await superAdminService.initServerCfg(); diff --git a/backend/src/server/routes/v1/admin-router.ts b/backend/src/server/routes/v1/admin-router.ts index 4359ef3fe..6ecebb274 100644 --- a/backend/src/server/routes/v1/admin-router.ts +++ b/backend/src/server/routes/v1/admin-router.ts @@ -1,6 +1,6 @@ import { z } from "zod"; -import { GatewayInstanceConfigSchema, OrganizationsSchema, SuperAdminSchema, UsersSchema } from "@app/db/schemas"; +import { OrganizationsSchema, SuperAdminSchema, UsersSchema } from "@app/db/schemas"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError } from "@app/lib/errors"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; @@ -12,13 +12,6 @@ import { getServerCfg } from "@app/services/super-admin/super-admin-service"; import { LoginMethod } from "@app/services/super-admin/super-admin-types"; import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types"; -const SanitizedInstanceGatewaySchema = GatewayInstanceConfigSchema.pick({ - isDisabled: true, - infisicalClientCaIssuedAt: true, - infisicalClientCaSerialNumber: true, - caKeyAlgorithm: true -}); - export const registerAdminRouter = async (server: FastifyZodProvider) => { server.route({ method: "GET", @@ -254,82 +247,6 @@ export const registerAdminRouter = async (server: FastifyZodProvider) => { } }); - server.route({ - method: "POST", - url: "/gateway", - config: { - rateLimit: writeLimit - }, - schema: { - response: { - 200: z.object({ - message: z.string() - }) - } - }, - onRequest: (req, res, done) => { - verifyAuth([AuthMode.JWT])(req, res, () => { - verifySuperAdmin(req, res, done); - }); - }, - handler: async () => { - await server.services.superAdmin.setupInstanceGateway(); - return { message: "Gateway setup completed" }; - } - }); - - server.route({ - method: "PATCH", - url: "/gateway", - config: { - rateLimit: writeLimit - }, - schema: { - body: z.object({ - isDisabled: z.boolean().optional() - }), - response: { - 200: z.object({ - message: z.string(), - gateway: SanitizedInstanceGatewaySchema - }) - } - }, - onRequest: (req, res, done) => { - verifyAuth([AuthMode.JWT])(req, res, () => { - verifySuperAdmin(req, res, done); - }); - }, - handler: async (req) => { - const gateway = await server.services.superAdmin.updateInstanceGateway(req.body); - return { message: "Gateway updated Successfully.", gateway }; - } - }); - - server.route({ - method: "GET", - url: "/gateway", - config: { - rateLimit: readLimit - }, - schema: { - response: { - 200: z.object({ - gateway: SanitizedInstanceGatewaySchema - }) - } - }, - onRequest: (req, res, done) => { - verifyAuth([AuthMode.JWT])(req, res, () => { - verifySuperAdmin(req, res, done); - }); - }, - handler: async () => { - const gateway = await server.services.superAdmin.getInstanceGateway(); - return { gateway }; - } - }); - server.route({ method: "POST", url: "/signup", diff --git a/backend/src/services/super-admin/super-admin-service.ts b/backend/src/services/super-admin/super-admin-service.ts index cf9c35425..9a6075423 100644 --- a/backend/src/services/super-admin/super-admin-service.ts +++ b/backend/src/services/super-admin/super-admin-service.ts @@ -1,9 +1,6 @@ -import * as x509 from "@peculiar/x509"; import bcrypt from "bcrypt"; -import crypto, { KeyObject } from "crypto"; import { TSuperAdmin, TSuperAdminUpdate } from "@app/db/schemas"; -import { TGatewayInstanceConfigDALFactory } from "@app/ee/services/gateway/gateway-instance-config-dal"; import { TLicenseServiceFactory } from "@app/ee/services/license/license-service"; import { PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; @@ -13,8 +10,6 @@ import { BadRequestError, NotFoundError } from "@app/lib/errors"; import { TAuthLoginFactory } from "../auth/auth-login-service"; import { AuthMethod } from "../auth/auth-type"; -import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "../certificate/certificate-types"; -import { createSerialNumber, keyAlgorithmToAlgCfg } from "../certificate-authority/certificate-authority-fns"; import { KMS_ROOT_CONFIG_UUID } from "../kms/kms-fns"; import { TKmsRootConfigDALFactory } from "../kms/kms-root-config-dal"; import { TKmsServiceFactory } from "../kms/kms-service"; @@ -36,7 +31,6 @@ type TSuperAdminServiceFactoryDep = { orgService: Pick; keyStore: Pick; licenseService: Pick; - gatewayInstanceConfigDAL: Pick; }; export type TSuperAdminServiceFactory = ReturnType; @@ -53,7 +47,6 @@ export let getServerCfg: () => Promise< const ADMIN_CONFIG_KEY = "infisical-admin-cfg"; const ADMIN_CONFIG_KEY_EXP = 60; // 60s const ADMIN_CONFIG_DB_UUID = "00000000-0000-0000-0000-000000000000"; -const GATEWAY_INSTANCE_CONFIG_UUID = "00000000-0000-0000-0000-000000000000"; export const superAdminServiceFactory = ({ serverCfgDAL, @@ -64,8 +57,7 @@ export const superAdminServiceFactory = ({ keyStore, kmsRootConfigDAL, kmsService, - licenseService, - gatewayInstanceConfigDAL + licenseService }: TSuperAdminServiceFactoryDep) => { const initServerCfg = async () => { // TODO(akhilmhdh): bad pattern time less change this later to me itself @@ -381,149 +373,6 @@ export const superAdminServiceFactory = ({ await kmsService.updateEncryptionStrategy(strategy); }; - const setupInstanceGateway = async () => { - if (!licenseService.onPremFeatures.gateway) { - throw new BadRequestError({ - message: "Failed to setup gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." - }); - } - - const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); - if (existingConfig) { - throw new BadRequestError({ - message: "Gateway has already been configured for the instance" - }); - } - - const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048); - // generate root CA - const infisicalClientRootCaSerialNumber = createSerialNumber(); - const infisicalClientRootCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); - const infisicalClientCaSkObj = KeyObject.from(infisicalClientRootCaKeys.privateKey); - const infisicalClientCaIssuedAt = new Date(); - const infisicalClientCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 25)); - - const infisicalClientCaCert = await x509.X509CertificateGenerator.createSelfSigned({ - name: "CN=Infisical Gateway Client Root CA", - serialNumber: infisicalClientRootCaSerialNumber, - notBefore: infisicalClientCaIssuedAt, - notAfter: infisicalClientCaExpiration, - signingAlgorithm: alg, - keys: infisicalClientRootCaKeys, - extensions: [ - // eslint-disable-next-line no-bitwise - new x509.KeyUsagesExtension(x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign, true), - await x509.SubjectKeyIdentifierExtension.create(infisicalClientRootCaKeys.publicKey) - ] - }); - - const infisicalClientLeafCertserialNumber = createSerialNumber(); - const infisicalClientLeafKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); - const extensions: x509.Extension[] = [ - new x509.BasicConstraintsExtension(false), - await x509.AuthorityKeyIdentifierExtension.create(infisicalClientCaCert, false), - await x509.SubjectKeyIdentifierExtension.create(infisicalClientLeafKeys.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 infisicalClientLeafCert = await x509.X509CertificateGenerator.create({ - serialNumber: infisicalClientLeafCertserialNumber, - subject: `OU=infisical,CN=infisical`, - issuer: infisicalClientCaCert.issuer, - notBefore: infisicalClientCaIssuedAt, - notAfter: infisicalClientCaExpiration, - signingKey: infisicalClientRootCaKeys.privateKey, - publicKey: infisicalClientLeafKeys.publicKey, - signingAlgorithm: alg, - extensions - }); - - const infisicalClientLeafCertSkObj = KeyObject.from(infisicalClientLeafKeys.privateKey); - const encryptWithRootKey = kmsService.encryptWithRootKey(); - await gatewayInstanceConfigDAL.create({ - // @ts-expect-error id is kept as fixed for idempotence and to avoid race condition - id: GATEWAY_INSTANCE_CONFIG_UUID, - isDisabled: false, - caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, - infisicalClientCaIssuedAt, - infisicalClientCaExpiration, - infisicalClientCaSerialNumber: infisicalClientRootCaSerialNumber, - encryptedInfisicalClientCaCertificate: encryptWithRootKey(Buffer.from(infisicalClientCaCert.rawData)), - encryptedInfisicalClientCaPrivateKey: encryptWithRootKey( - infisicalClientCaSkObj.export({ - type: "pkcs8", - format: "der" - }) - ), - infisicalClientCertIssuedAt: infisicalClientCaIssuedAt, - infisicalClientCertExpiration: infisicalClientCaExpiration, - infisicalClientCertSerialNumber: infisicalClientLeafCertserialNumber, - infisicalClientCertKeyAlgorithm: CertKeyAlgorithm.RSA_2048, - encryptedInfisicalClientCertificate: encryptWithRootKey(Buffer.from(infisicalClientLeafCert.rawData)), - encryptedInfisicalClientPrivateKey: encryptWithRootKey( - infisicalClientLeafCertSkObj.export({ - type: "pkcs8", - format: "der" - }) - ) - }); - }; - - const updateInstanceGateway = async ({ isDisabled }: { isDisabled?: boolean }) => { - if (!licenseService.onPremFeatures.gateway) { - throw new BadRequestError({ - message: "Failed to update gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." - }); - } - - const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); - if (!existingConfig) { - throw new NotFoundError({ - message: "Gateway instance config not found" - }); - } - - const updatedGatewayInstanceConfig = await gatewayInstanceConfigDAL.updateById(GATEWAY_INSTANCE_CONFIG_UUID, { - isDisabled - }); - return { - infisicalClientCaSerialNumber: updatedGatewayInstanceConfig.infisicalClientCaSerialNumber, - isDisabled: updatedGatewayInstanceConfig?.isDisabled, - caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, - infisicalClientCaIssuedAt: updatedGatewayInstanceConfig.infisicalClientCaIssuedAt - }; - }; - - const getInstanceGateway = async () => { - if (!licenseService.onPremFeatures.gateway) { - throw new BadRequestError({ - message: "Failed to update gateway ca due to plan restriction. Upgrade to Infisical's Enterprise plan." - }); - } - - const existingConfig = await gatewayInstanceConfigDAL.findById(GATEWAY_INSTANCE_CONFIG_UUID); - if (!existingConfig) { - throw new NotFoundError({ - message: "Gateway instance config not found" - }); - } - - return { - infisicalClientCaSerialNumber: existingConfig.infisicalClientCaSerialNumber, - isDisabled: existingConfig?.isDisabled, - caKeyAlgorithm: CertKeyAlgorithm.RSA_2048, - infisicalClientCaIssuedAt: existingConfig.infisicalClientCaIssuedAt - }; - }; - return { initServerCfg, updateServerCfg, @@ -532,9 +381,6 @@ export const superAdminServiceFactory = ({ deleteUser, getAdminSlackConfig, updateRootEncryptionStrategy, - getConfiguredEncryptionStrategies, - setupInstanceGateway, - updateInstanceGateway, - getInstanceGateway + getConfiguredEncryptionStrategies }; }; From c6b3b2431232c38bd569d4ab7f1aaa4152ae2df6 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 17 Feb 2025 13:53:07 +0530 Subject: [PATCH 06/30] feat: gateway in cli first version\ --- cli/go.mod | 17 ++- cli/go.sum | 34 ++++-- cli/packages/api/api.go | 39 +++++++ cli/packages/api/model.go | 19 ++++ cli/packages/cmd/gateway.go | 61 ++++++++++ cli/packages/gateway/connection.go | 109 ++++++++++++++++++ cli/packages/gateway/gateway.go | 174 +++++++++++++++++++++++++++++ 7 files changed, 438 insertions(+), 15 deletions(-) create mode 100644 cli/packages/cmd/gateway.go create mode 100644 cli/packages/gateway/connection.go create mode 100644 cli/packages/gateway/gateway.go diff --git a/cli/go.mod b/cli/go.mod index b96772c91..7339ec68f 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -18,14 +18,16 @@ require ( github.com/muesli/reflow v0.3.0 github.com/muesli/roff v0.1.0 github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9 + github.com/pion/logging v0.2.3 + github.com/pion/turn/v4 v4.0.0 github.com/posthog/posthog-go v0.0.0-20221221115252-24dfed35d71a github.com/rs/cors v1.11.0 github.com/rs/zerolog v1.26.1 github.com/spf13/cobra v1.6.1 github.com/spf13/viper v1.8.1 github.com/stretchr/testify v1.9.0 - golang.org/x/crypto v0.31.0 - golang.org/x/term v0.27.0 + golang.org/x/crypto v0.33.0 + golang.org/x/term v0.29.0 gopkg.in/yaml.v2 v2.4.0 ) @@ -81,6 +83,10 @@ require ( github.com/muesli/termenv v0.15.2 // indirect github.com/oklog/ulid v1.3.1 // indirect github.com/pelletier/go-toml v1.9.3 // indirect + github.com/pion/dtls/v3 v3.0.4 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/stun/v3 v3.0.0 // indirect + github.com/pion/transport/v3 v3.0.7 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/rivo/uniseg v0.2.0 // indirect @@ -88,6 +94,7 @@ require ( github.com/spf13/cast v1.3.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/subosito/gotenv v1.2.0 // indirect + github.com/wlynxg/anet v0.0.5 // indirect github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c // indirect go.mongodb.org/mongo-driver v1.10.0 // indirect go.opencensus.io v0.24.0 // indirect @@ -98,9 +105,9 @@ require ( go.opentelemetry.io/otel/trace v1.24.0 // indirect golang.org/x/net v0.33.0 // indirect golang.org/x/oauth2 v0.21.0 // indirect - golang.org/x/sync v0.10.0 // indirect - golang.org/x/sys v0.28.0 // indirect - golang.org/x/text v0.21.0 // indirect + golang.org/x/sync v0.11.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect golang.org/x/time v0.6.0 // indirect google.golang.org/api v0.188.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20240701130421-f6361c86f094 // indirect diff --git a/cli/go.sum b/cli/go.sum index 67a3d3275..20215d776 100644 --- a/cli/go.sum +++ b/cli/go.sum @@ -347,6 +347,18 @@ github.com/pelletier/go-toml v1.9.3 h1:zeC5b1GviRUyKYd6OJPvBU/mcVDVoL1OhT17FCt5d github.com/pelletier/go-toml v1.9.3/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9 h1:lL+y4Xv20pVlCGyLzNHRC0I0rIHhIL1lTvHizoS/dU8= github.com/petar-dambovaliev/aho-corasick v0.0.0-20211021192214-5ab2d9280aa9/go.mod h1:EHPiTAKtiFmrMldLUNswFwfZ2eJIYBHktdaUTZxYWRw= +github.com/pion/dtls/v3 v3.0.4 h1:44CZekewMzfrn9pmGrj5BNnTMDCFwr+6sLH+cCuLM7U= +github.com/pion/dtls/v3 v3.0.4/go.mod h1:R373CsjxWqNPf6MEkfdy3aSe9niZvL/JaKlGeFphtMg= +github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI= +github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw= +github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU= +github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0= +github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo= +github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM= +github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -410,6 +422,8 @@ github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69 github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= github.com/urfave/cli v1.22.5/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= +github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= @@ -458,8 +472,8 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -560,8 +574,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -610,11 +624,11 @@ golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.27.0 h1:WP60Sv1nlK1T6SupCHbXzSaN0b9wUmsPoRS9b61A23Q= -golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM= +golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU= +golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -624,8 +638,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/cli/packages/api/api.go b/cli/packages/api/api.go index 3d050cd97..7b13c6e02 100644 --- a/cli/packages/api/api.go +++ b/cli/packages/api/api.go @@ -544,3 +544,42 @@ func CallUpdateRawSecretsV3(httpClient *resty.Client, request UpdateRawSecretByN return nil } + +func CallRegisterGatewayIdentityV1(httpClient *resty.Client) (*GetRelayCredentialsResponseV1, error) { + var resBody GetRelayCredentialsResponseV1 + response, err := httpClient. + R(). + SetResult(&resBody). + SetHeader("User-Agent", USER_AGENT). + Post(fmt.Sprintf("%v/v1/gateways/register-identity", config.INFISICAL_URL)) + + if err != nil { + return nil, fmt.Errorf("CallRegisterGatewayIdentityV1: Unable to complete api request [err=%w]", err) + } + + if response.IsError() { + return nil, fmt.Errorf("CallRegisterGatewayIdentityV1: Unsuccessful response [%v %v] [status-code=%v] [response=%v]", response.Request.Method, response.Request.URL, response.StatusCode(), response.String()) + } + + return &resBody, nil +} + +func CallExchangeRelayCertV1(httpClient *resty.Client, request ExchangeRelayCertRequestV1) (*ExchangeRelayCertResponseV1, error) { + var resBody ExchangeRelayCertResponseV1 + response, err := httpClient. + R(). + SetResult(&resBody). + SetBody(request). + SetHeader("User-Agent", USER_AGENT). + Post(fmt.Sprintf("%v/v1/gateways/exchange-cert", config.INFISICAL_URL)) + + if err != nil { + return nil, fmt.Errorf("CallExchangeRelayCertV1: Unable to complete api request [err=%w]", err) + } + + if response.IsError() { + return nil, fmt.Errorf("CallExchangeRelayCertV1: Unsuccessful response [%v %v] [status-code=%v] [response=%v]", response.Request.Method, response.Request.URL, response.StatusCode(), response.String()) + } + + return &resBody, nil +} diff --git a/cli/packages/api/model.go b/cli/packages/api/model.go index 73a04200d..72dbbc97b 100644 --- a/cli/packages/api/model.go +++ b/cli/packages/api/model.go @@ -629,3 +629,22 @@ type GetRawSecretV3ByNameResponse struct { } `json:"secret"` ETag string } + +type GetRelayCredentialsResponseV1 struct { + TurnServerUsername string `json:"turnServerUsername"` + TurnServerPassword string `json:"turnServerPassword"` + TurnServerRealm string `json:"turnServerRealm"` + TurnServerAddress string `json:"turnServerAddress"` + InfisicalStaticIp string `json:"infisicalStaticIp"` +} + +type ExchangeRelayCertRequestV1 struct { + RelayAddress string `json:"relayAddress"` +} + +type ExchangeRelayCertResponseV1 struct { + SerialNumber string `json:"serialNumber"` + PrivateKey string `json:"privateKey"` + Certificate string `json:"certificate"` + CertificateChain string `json:"certificateChain"` +} diff --git a/cli/packages/cmd/gateway.go b/cli/packages/cmd/gateway.go new file mode 100644 index 000000000..945340b22 --- /dev/null +++ b/cli/packages/cmd/gateway.go @@ -0,0 +1,61 @@ +package cmd + +import ( + // "fmt" + + // "github.com/Infisical/infisical-merge/packages/api" + // "github.com/Infisical/infisical-merge/packages/models" + "fmt" + + "github.com/Infisical/infisical-merge/packages/gateway" + "github.com/Infisical/infisical-merge/packages/util" + // "github.com/Infisical/infisical-merge/packages/visualize" + // "github.com/rs/zerolog/log" + + // "github.com/go-resty/resty/v2" + "github.com/posthog/posthog-go" + "github.com/spf13/cobra" +) + +var gatewayCmd = &cobra.Command{ + Example: `infisical gateway`, + Short: "Used to infisical gateway", + Use: "gateway", + DisableFlagsInUseLine: true, + Args: cobra.NoArgs, + Run: func(cmd *cobra.Command, args []string) { + token, err := util.GetInfisicalToken(cmd) + if err != nil { + util.HandleError(err, "Unable to parse flag") + } + + if token == nil { + util.HandleError(fmt.Errorf("Token not found")) + } + + gatewayInstance, err := gateway.NewGateway(token.Token) + if err != nil { + util.HandleError(err) + } + + if err = gatewayInstance.ConnectWithRelay(); err != nil { + util.HandleError(err) + } + + if err := gatewayInstance.Listen(); err != nil { + util.HandleError(err) + } + + Telemetry.CaptureEvent("cli-command:gateway", posthog.NewProperties().Set("version", util.CLI_VERSION)) + }, +} + +func init() { + gatewayCmd.SetHelpFunc(func(command *cobra.Command, strings []string) { + command.Flags().MarkHidden("domain") + command.Parent().HelpFunc()(command, strings) + }) + gatewayCmd.Flags().String("token", "", "Connect with Infisical using machine identity access token") + + rootCmd.AddCommand(gatewayCmd) +} diff --git a/cli/packages/gateway/connection.go b/cli/packages/gateway/connection.go new file mode 100644 index 000000000..dfde595cb --- /dev/null +++ b/cli/packages/gateway/connection.go @@ -0,0 +1,109 @@ +package gateway + +import ( + "bufio" + "bytes" + "fmt" + "io" + "net" + "sync" + + "github.com/rs/zerolog/log" +) + +func handleConnection(conn net.Conn) { + defer conn.Close() + log.Info().Msgf("New connection from: %s", conn.RemoteAddr().String()) + + // Use buffered reader for better handling of fragmented data + reader := bufio.NewReader(conn) + for { + msg, err := reader.ReadBytes('\n') + if err != nil { + log.Error().Msgf("Error reading command: %s", err) + return + } + + cmd := bytes.ToUpper(bytes.TrimSpace(bytes.Split(msg, []byte(" "))[0])) + args := bytes.TrimSpace(bytes.TrimPrefix(msg, cmd)) + + switch string(cmd) { + case "FORWARD-TCP": + proxyAddress := string(bytes.Split(args, []byte(" "))[0]) + fmt.Println(proxyAddress) + destTarget, err := net.Dial("tcp", proxyAddress) + fmt.Println(err) + if err != nil { + log.Error().Msgf("Failed to connect to target: %v", err) + return + } + defer destTarget.Close() + + // Handle buffered data + buffered := reader.Buffered() + if buffered > 0 { + bufferedData := make([]byte, buffered) + _, err := reader.Read(bufferedData) + if err != nil { + log.Error().Msgf("Error reading buffered data: %v", err) + return + } + + if _, err = destTarget.Write(bufferedData); err != nil { + log.Error().Msgf("Error writing buffered data: %v", err) + return + } + } + + CopyData(conn, destTarget) + break + case "PING": + conn.Write([]byte("PONG\n")) + default: + log.Error().Msgf("Unknown command: %s", string(cmd)) + break + } + } +} + +type CloseWrite interface { + CloseWrite() error +} + +func CopyData(src, dst net.Conn) { + // Create a WaitGroup to wait for both copy operations + var wg sync.WaitGroup + wg.Add(2) + + // Start copying in both directions + go func() { + defer wg.Done() + if _, err := io.Copy(dst, src); err != nil { + log.Error().Msgf("Error copying postgres->client: %v", err) + } + + if e, ok := dst.(CloseWrite); ok { + log.Print("Closing dst") + e.CloseWrite() + } else { + + log.Print("Not closed") + } + }() + + go func() { + defer wg.Done() + if _, err := io.Copy(src, dst); err != nil { + log.Error().Msgf("Error copying client->postgres: %v", err) + } + if e, ok := src.(CloseWrite); ok { + log.Print("Closing src") + e.CloseWrite() + } else { + log.Print("Not closed") + } + }() + + // Wait for both copies to complete + wg.Wait() +} diff --git a/cli/packages/gateway/gateway.go b/cli/packages/gateway/gateway.go new file mode 100644 index 000000000..484737b79 --- /dev/null +++ b/cli/packages/gateway/gateway.go @@ -0,0 +1,174 @@ +package gateway + +import ( + "crypto/tls" + "crypto/x509" + "fmt" + "net" + "strings" + "time" + + "github.com/Infisical/infisical-merge/packages/api" + "github.com/go-resty/resty/v2" + "github.com/pion/logging" + "github.com/pion/turn/v4" + "github.com/rs/zerolog/log" +) + +type GatewayConfig struct { + TurnServerUsername string + TurnServerPassword string + TurnServerAddress string + InfisicalStaticIp string + SerialNumber string + PrivateKey string + Certificate string + CertificateChain string +} + +type Gateway struct { + httpClient *resty.Client + config *GatewayConfig + client *turn.Client +} + +func NewGateway(identityToken string) (Gateway, error) { + httpClient := resty.New() + httpClient.SetAuthToken(identityToken) + + return Gateway{ + httpClient: httpClient, + config: &GatewayConfig{}, + }, nil +} + +func (g *Gateway) ConnectWithRelay() error { + relayDetails, err := api.CallRegisterGatewayIdentityV1(g.httpClient) + if err != nil { + return err + } + + // Dial TURN Server + conn, err := net.Dial("tcp", relayDetails.TurnServerAddress) + if err != nil { + return fmt.Errorf("Failed to connect with relay server: %w", err) + } + + if tcpConn, ok := conn.(*net.TCPConn); ok { + tcpConn.SetKeepAlive(true) + tcpConn.SetKeepAlivePeriod(10 * time.Second) + tcpConn.SetNoDelay(true) + } + + // Start a new TURN Client and wrap our net.Conn in a STUNConn + // This allows us to simulate datagram based communication over a net.Conn + cfg := &turn.ClientConfig{ + STUNServerAddr: relayDetails.TurnServerAddress, + TURNServerAddr: relayDetails.TurnServerAddress, + Conn: turn.NewSTUNConn(conn), + Username: relayDetails.TurnServerUsername, + Password: relayDetails.TurnServerPassword, + Realm: relayDetails.TurnServerRealm, + LoggerFactory: logging.NewDefaultLoggerFactory(), + } + + client, err := turn.NewClient(cfg) + if err != nil { + return fmt.Errorf("Failed to create relay client: %w", err) + } + + err = client.Listen() + if err != nil { + return fmt.Errorf("Failed to listen to relay server: %w", err) + } + + g.config = &GatewayConfig{ + TurnServerUsername: relayDetails.TurnServerUsername, + TurnServerPassword: relayDetails.TurnServerPassword, + TurnServerAddress: relayDetails.TurnServerAddress, + InfisicalStaticIp: relayDetails.InfisicalStaticIp, + } + // if port not specific allow all port + if !strings.Contains(relayDetails.InfisicalStaticIp, ":") { + g.config.InfisicalStaticIp = g.config.InfisicalStaticIp + ":0" + } + + g.client = client + return nil +} + +func (g *Gateway) Listen() error { + defer g.client.Close() + // Allocate a relay socket on the TURN server. On success, it + // will return a net.PacketConn which represents the remote + // socket. + relayNonTlsConn, err := g.client.AllocateTCP() + if err != nil { + return fmt.Errorf("Failed to allocate relay connection: %w", err) + } + defer func() { + if closeErr := relayNonTlsConn.Close(); closeErr != nil { + log.Error().Msgf("Failed to close connection: %s", closeErr) + } + }() + + peerAddr, err := net.ResolveTCPAddr("tcp", g.config.InfisicalStaticIp) + if err != nil { + return fmt.Errorf("Failed to parse infisical static ip: %w", err) + } + gatewayCert, err := api.CallExchangeRelayCertV1(g.httpClient, api.ExchangeRelayCertRequestV1{ + RelayAddress: relayNonTlsConn.Addr().String(), + }) + if err != nil { + return err + } + + g.config.SerialNumber = gatewayCert.SerialNumber + g.config.PrivateKey = gatewayCert.PrivateKey + g.config.Certificate = gatewayCert.Certificate + g.config.CertificateChain = gatewayCert.CertificateChain + + go func() { + err := relayNonTlsConn.CreatePermissions(peerAddr) + if err != nil { + log.Error().Msgf("Failed to refresh permission: %s", err) + } + log.Printf("Created permission for incoming connections") + ticker := time.NewTicker(2 * time.Minute) // Refresh before 5-min expiry + for range ticker.C { + err := relayNonTlsConn.CreatePermissions(peerAddr) + if err != nil { + log.Error().Msgf("Failed to refresh permission: %s", err) + } + } + }() + + cert, err := tls.X509KeyPair([]byte(gatewayCert.Certificate), []byte(gatewayCert.PrivateKey)) + if err != nil { + return fmt.Errorf("failed to parse cert: %s", err) + } + + fmt.Println(relayNonTlsConn.Addr().String()) + caCertPool := x509.NewCertPool() + caCertPool.AppendCertsFromPEM([]byte(gatewayCert.CertificateChain)) + + relayConn := tls.NewListener(relayNonTlsConn, &tls.Config{ + Certificates: []tls.Certificate{cert}, + MinVersion: tls.VersionTLS12, + ClientCAs: caCertPool, + ClientAuth: tls.RequireAndVerifyClientCert, + }) + + for { + log.Info().Msg("Connector started successfully") + // Accept new relay connection + conn, err := relayConn.Accept() + if err != nil { + log.Error().Msgf("Failed to accept connection: %v", err) + continue + } + + // Handle the connection in a goroutine + go handleConnection(conn) + } +} From a7ca242f5d4a4b0a791456c91b725878a5644404 Mon Sep 17 00:00:00 2001 From: = Date: Mon, 17 Feb 2025 13:53:39 +0530 Subject: [PATCH 07/30] feat: frontend changes for connector management --- docker-compose.prod.yml | 1 - frontend/src/hooks/api/admin/index.ts | 2 - frontend/src/hooks/api/admin/mutation.ts | 25 ---- frontend/src/hooks/api/admin/queries.ts | 20 +-- frontend/src/hooks/api/admin/types.ts | 11 -- frontend/src/hooks/api/gateways/mutation.tsx | 4 +- frontend/src/hooks/api/gateways/queries.tsx | 4 +- .../pages/admin/OverviewPage/GatewayPanel.tsx | 114 ------------------ .../pages/admin/OverviewPage/OverviewPage.tsx | 8 +- sink/docker-compose.coturn.yml | 0 10 files changed, 9 insertions(+), 180 deletions(-) delete mode 100644 frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx create mode 100644 sink/docker-compose.coturn.yml diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index d3526d841..f12d446ef 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -56,4 +56,3 @@ volumes: networks: infisical: - diff --git a/frontend/src/hooks/api/admin/index.ts b/frontend/src/hooks/api/admin/index.ts index 69f673187..5405878c7 100644 --- a/frontend/src/hooks/api/admin/index.ts +++ b/frontend/src/hooks/api/admin/index.ts @@ -1,9 +1,7 @@ export { useAdminDeleteUser, useCreateAdminUser, - useSetupInstanceGatewayConfig, useUpdateAdminSlackConfig, - useUpdateInstanceGatewayConfig, useUpdateServerConfig, useUpdateServerEncryptionStrategy } from "./mutation"; diff --git a/frontend/src/hooks/api/admin/mutation.ts b/frontend/src/hooks/api/admin/mutation.ts index 3bb1bfb2a..c68760fa4 100644 --- a/frontend/src/hooks/api/admin/mutation.ts +++ b/frontend/src/hooks/api/admin/mutation.ts @@ -9,7 +9,6 @@ import { AdminSlackConfig, RootKeyEncryptionStrategy, TCreateAdminUserDTO, - TDisableInstanceGatewayConfigDTO, TServerConfig, TUpdateAdminSlackConfigDTO } from "./types"; @@ -99,27 +98,3 @@ export const useUpdateServerEncryptionStrategy = () => { } }); }; - -export const useSetupInstanceGatewayConfig = () => { - const queryClient = useQueryClient(); - return useMutation({ - mutationFn: async () => { - await apiRequest.post("/api/v1/admin/gateway"); - }, - onSuccess: () => { - queryClient.invalidateQueries(adminQueryKeys.getInstanceGatewayConfig()); - } - }); -}; - -export const useUpdateInstanceGatewayConfig = () => { - const queryClient = useQueryClient(); - return useMutation({ - mutationFn: async (dto: TDisableInstanceGatewayConfigDTO) => { - await apiRequest.patch("/api/v1/admin/gateway", dto); - }, - onSuccess: () => { - queryClient.invalidateQueries(adminQueryKeys.getInstanceGatewayConfig()); - } - }); -}; diff --git a/frontend/src/hooks/api/admin/queries.ts b/frontend/src/hooks/api/admin/queries.ts index afcbd31fb..12ae1cf64 100644 --- a/frontend/src/hooks/api/admin/queries.ts +++ b/frontend/src/hooks/api/admin/queries.ts @@ -1,5 +1,4 @@ -import { queryOptions, useInfiniteQuery, useQuery, UseQueryOptions } from "@tanstack/react-query"; -import { AxiosError } from "axios"; +import { useInfiniteQuery, useQuery, UseQueryOptions } from "@tanstack/react-query"; import { apiRequest } from "@app/config/request"; @@ -8,7 +7,6 @@ import { AdminGetUsersFilters, AdminSlackConfig, TGetServerRootKmsEncryptionDetails, - TInstanceGatewayConfig, TServerConfig } from "./types"; @@ -20,21 +18,7 @@ export const adminQueryKeys = { serverConfig: () => ["server-config"] as const, getUsers: (filters: AdminGetUsersFilters) => [adminStandaloneKeys.getUsers, { filters }] as const, getAdminSlackConfig: () => ["admin-slack-config"] as const, - getServerEncryptionStrategies: () => ["server-encryption-strategies"] as const, - - getInstanceGatewayConfig: () => - queryOptions({ - queryKey: ["instance-gateway-config"], - queryFn: async () => { - const { data } = await apiRequest - .get<{ gateway: TInstanceGatewayConfig }>("/api/v1/admin/gateway") - .catch((err: AxiosError) => { - if (err.response?.status === 404) return { data: { gateway: false as const } }; - throw err; - }); - return data.gateway; - } - }) + getServerEncryptionStrategies: () => ["server-encryption-strategies"] as const }; export const fetchServerConfig = async () => { diff --git a/frontend/src/hooks/api/admin/types.ts b/frontend/src/hooks/api/admin/types.ts index 282af07a2..60fa3ab98 100644 --- a/frontend/src/hooks/api/admin/types.ts +++ b/frontend/src/hooks/api/admin/types.ts @@ -66,14 +66,3 @@ export enum RootKeyEncryptionStrategy { Software = "SOFTWARE", HSM = "HSM" } - -export type TInstanceGatewayConfig = { - isDisabled: boolean; - infisicalClientCaIssuedAt: string; - infisicalClientCaSerialNumber: string; - caKeyAlgorithm: string; -}; - -export type TDisableInstanceGatewayConfigDTO = { - isDisabled?: boolean; -}; diff --git a/frontend/src/hooks/api/gateways/mutation.tsx b/frontend/src/hooks/api/gateways/mutation.tsx index 858d8fa8a..1d1fa63d9 100644 --- a/frontend/src/hooks/api/gateways/mutation.tsx +++ b/frontend/src/hooks/api/gateways/mutation.tsx @@ -1,5 +1,7 @@ -import { apiRequest } from "@app/config/request"; import { useMutation, useQueryClient } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + import { gatewaysQueryKeys } from "./queries"; export const useDeleteGateway = () => { diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx index e41e5d871..bb05b17a4 100644 --- a/frontend/src/hooks/api/gateways/queries.tsx +++ b/frontend/src/hooks/api/gateways/queries.tsx @@ -1,5 +1,7 @@ -import { apiRequest } from "@app/config/request"; import { queryOptions } from "@tanstack/react-query"; + +import { apiRequest } from "@app/config/request"; + import { TGateway } from "./types"; export const gatewaysQueryKeys = { diff --git a/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx b/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx deleted file mode 100644 index 8590bee47..000000000 --- a/frontend/src/pages/admin/OverviewPage/GatewayPanel.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import { useQuery } from "@tanstack/react-query"; -import { format } from "date-fns"; - -import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal"; -import { createNotification } from "@app/components/notifications"; -import { Button, EmptyState, Tooltip } from "@app/components/v2"; -import { useSubscription } from "@app/context"; -import { usePopUp } from "@app/hooks"; -import { useSetupInstanceGatewayConfig, useUpdateInstanceGatewayConfig } from "@app/hooks/api"; -import { adminQueryKeys } from "@app/hooks/api/admin/queries"; - -export const GatewayPanel = () => { - const { subscription } = useSubscription(); - const { data } = useQuery(adminQueryKeys.getInstanceGatewayConfig()); - const { handlePopUpToggle, popUp, handlePopUpOpen } = usePopUp(["upgradePlan"] as const); - - const setupInstanceConfig = useSetupInstanceGatewayConfig(); - const updateInstanceConfig = useUpdateInstanceGatewayConfig(); - - const handleSetupInstance = () => { - if (!subscription.gateway) { - handlePopUpOpen("upgradePlan"); - return; - } - - if (!setupInstanceConfig.isPending) { - setupInstanceConfig.mutate(undefined, { - onSuccess: () => { - createNotification({ - type: "success", - text: "Instance gateway setup completed" - }); - } - }); - } - }; - - const handleUpdateGatewayStatus = ({ isDisabled }: { isDisabled?: boolean }) => { - if (!updateInstanceConfig.isPending) { - updateInstanceConfig.mutate( - { isDisabled }, - { - onSuccess: () => { - createNotification({ - type: "success", - text: "Instance gateway updated" - }); - } - } - ); - } - }; - - if (!data) { - return ( -
- - - -
- ); - } - - return ( -
-
-
Gateway
- {data?.isDisabled && ( - -
- - )} -
-
-
- Infisical Client Root CA Issued At -
-
{format(new Date(data.infisicalClientCaIssuedAt), "yyyy-MM-dd")}
-
-
-
- Infisical Client Root CA Seriial Number -
-
{data.infisicalClientCaSerialNumber}
-
- - handlePopUpToggle("upgradePlan", isOpen)} - text="You can use Gateway if you switch to Infisical's Enterprise plan." - /> -
- ); -}; diff --git a/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx b/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx index 3b771fab4..45c2fa3ec 100644 --- a/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx +++ b/frontend/src/pages/admin/OverviewPage/OverviewPage.tsx @@ -33,7 +33,6 @@ import { EncryptionPanel } from "./components/EncryptionPanel"; import { IntegrationPanel } from "./components/IntegrationPanel"; import { RateLimitPanel } from "./components/RateLimitPanel"; import { UserPanel } from "./components/UserPanel"; -import { GatewayPanel } from "./GatewayPanel"; enum TabSections { Settings = "settings", @@ -42,8 +41,7 @@ enum TabSections { RateLimit = "rate-limit", Integrations = "integrations", Users = "users", - Kmip = "kmip", - Gateway = "gateway" + Kmip = "kmip" } enum SignUpModes { @@ -152,7 +150,6 @@ export const OverviewPage = () => { Rate Limit Integrations Users - Gateway
@@ -351,9 +348,6 @@ export const OverviewPage = () => { - - - )} diff --git a/sink/docker-compose.coturn.yml b/sink/docker-compose.coturn.yml new file mode 100644 index 000000000..e69de29bb From 1307fa49d41f2d2927100d890474e6b6d47210ee Mon Sep 17 00:00:00 2001 From: = Date: Tue, 18 Feb 2025 23:36:25 +0530 Subject: [PATCH 08/30] feat: completed backend for gateway --- backend/src/@types/fastify.d.ts | 2 +- .../20250212191958_create-gateway.ts | 15 + backend/src/db/schemas/dynamic-secrets.ts | 3 +- backend/src/ee/routes/v1/gateway-router.ts | 50 +++- .../dynamic-secret/dynamic-secret-fns.ts | 17 +- .../dynamic-secret/dynamic-secret-service.ts | 48 +++- .../dynamic-secret/providers/index.ts | 11 +- .../dynamic-secret/providers/models.ts | 3 +- .../dynamic-secret/providers/sql-database.ts | 170 ++++++++---- .../src/ee/services/gateway/gateway-dal.ts | 23 +- .../ee/services/gateway/gateway-service.ts | 185 ++++++++++--- .../src/ee/services/gateway/gateway-types.ts | 13 + .../src/ee/services/license/license-fns.ts | 2 +- .../src/ee/services/license/license-types.ts | 2 +- .../ee/services/permission/org-permission.ts | 2 + backend/src/keystore/keystore.ts | 5 +- backend/src/lib/gateway/index.ts | 258 ++++++++++++++++++ backend/src/server/routes/index.ts | 18 +- 18 files changed, 718 insertions(+), 109 deletions(-) create mode 100644 backend/src/lib/gateway/index.ts diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts index 6cc850847..85a19b676 100644 --- a/backend/src/@types/fastify.d.ts +++ b/backend/src/@types/fastify.d.ts @@ -13,6 +13,7 @@ import { TCertificateEstServiceFactory } from "@app/ee/services/certificate-est/ import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-service"; import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service"; import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service"; +import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service"; import { TGroupServiceFactory } from "@app/ee/services/group/group-service"; import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service"; import { TIdentityProjectAdditionalPrivilegeV2ServiceFactory } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-service"; @@ -95,7 +96,6 @@ import { TUserServiceFactory } from "@app/services/user/user-service"; import { TUserEngagementServiceFactory } from "@app/services/user-engagement/user-engagement-service"; import { TWebhookServiceFactory } from "@app/services/webhook/webhook-service"; import { TWorkflowIntegrationServiceFactory } from "@app/services/workflow-integration/workflow-integration-service"; -import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service"; declare module "@fastify/request-context" { interface RequestContextData { diff --git a/backend/src/db/migrations/20250212191958_create-gateway.ts b/backend/src/db/migrations/20250212191958_create-gateway.ts index ee9ef0ef7..87f58bc78 100644 --- a/backend/src/db/migrations/20250212191958_create-gateway.ts +++ b/backend/src/db/migrations/20250212191958_create-gateway.ts @@ -66,6 +66,14 @@ export async function up(knex: Knex): Promise { await createOnUpdateTrigger(knex, TableName.Gateway); } + + if (await knex.schema.hasTable(TableName.DynamicSecret)) { + const doesGatewayColExist = await knex.schema.hasColumn(TableName.DynamicSecret, "gatewayId"); + await knex.schema.alterTable(TableName.DynamicSecret, (t) => { + // not setting a foreign constraint so that cascade effects are not triggered + if (!doesGatewayColExist) t.uuid("gatewayId"); + }); + } } export async function down(knex: Knex): Promise { @@ -74,4 +82,11 @@ export async function down(knex: Knex): Promise { await knex.schema.dropTableIfExists(TableName.OrgGatewayConfig); await dropOnUpdateTrigger(knex, TableName.OrgGatewayConfig); + + if (await knex.schema.hasTable(TableName.DynamicSecret)) { + const doesGatewayColExist = await knex.schema.hasColumn(TableName.DynamicSecret, "gatewayId"); + await knex.schema.alterTable(TableName.DynamicSecret, (t) => { + if (doesGatewayColExist) t.dropColumn("gatewayId"); + }); + } } diff --git a/backend/src/db/schemas/dynamic-secrets.ts b/backend/src/db/schemas/dynamic-secrets.ts index eaddea8fe..b60683e85 100644 --- a/backend/src/db/schemas/dynamic-secrets.ts +++ b/backend/src/db/schemas/dynamic-secrets.ts @@ -26,7 +26,8 @@ export const DynamicSecretsSchema = z.object({ statusDetails: z.string().nullable().optional(), createdAt: z.date(), updatedAt: z.date(), - encryptedInput: zodBuffer + encryptedInput: zodBuffer, + gatewayId: z.string().uuid().nullable().optional() }); export type TDynamicSecrets = z.infer; diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts index 4282d41e0..332997619 100644 --- a/backend/src/ee/routes/v1/gateway-router.ts +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -2,6 +2,7 @@ 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 { verifyAuth } from "@app/server/plugins/auth/verify-auth"; import { AuthMode } from "@app/services/auth/auth-type"; @@ -37,7 +38,8 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { handler: async (req) => { const relayDetails = await server.services.gateway.getGatewayRelayDetails( req.permission.id, - req.permission.orgId + req.permission.orgId, + req.permission.authMethod ); return relayDetails; } @@ -67,7 +69,8 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { const gatewayCertificates = await server.services.gateway.exchangeAllocatedRelayAddress({ identityOrg: req.permission.orgId, identityId: req.permission.id, - relayAddress: req.body.relayAddress + relayAddress: req.body.relayAddress, + identityOrgAuthMethod: req.permission.authMethod }); return gatewayCertificates; } @@ -80,6 +83,9 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { rateLimit: readLimit }, schema: { + querystring: z.object({ + projectId: z.string().optional() + }), response: { 200: z.object({ gateways: SanitizedGatewaySchema.extend({ @@ -93,6 +99,14 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { }, onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.JWT]), handler: async (req) => { + if (req.query.projectId) { + const gateways = await server.services.gateway.getProjectGateways({ + projectId: req.query.projectId, + projectPermission: req.permission + }); + return { gateways }; + } + const gateways = await server.services.gateway.listGateways({ orgPermission: req.permission }); @@ -131,11 +145,41 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { } }); + 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 + }); + return { gateway }; + } + }); + server.route({ method: "DELETE", url: "/:id", config: { - rateLimit: readLimit + rateLimit: writeLimit }, schema: { params: z.object({ diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts index 04aeb3950..ac6a66d3b 100644 --- a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts +++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts @@ -1,20 +1,31 @@ +import crypto from "node:crypto"; + import { getConfig } from "@app/lib/config/env"; import { BadRequestError } from "@app/lib/errors"; import { getDbConnectionHost } from "@app/lib/knex"; -export const verifyHostInputValidity = (host: string) => { +export const verifyHostInputValidity = (host: string, isGateway = false) => { const appCfg = getConfig(); const dbHost = appCfg.DB_HOST || getDbConnectionHost(appCfg.DB_CONNECTION_URI); + // no need for validation when it's dev + if (appCfg.NODE_ENV === "development") return; + + if (host === "host.docker.internal") throw new BadRequestError({ message: "Invalid db host" }); if ( appCfg.isCloud && + !isGateway && // localhost // internal ips - (host === "host.docker.internal" || host.match(/^10\.\d+\.\d+\.\d+/) || host.match(/^192\.168\.\d+\.\d+/)) + (host.match(/^10\.\d+\.\d+\.\d+/) || host.match(/^192\.168\.\d+\.\d+/)) ) throw new BadRequestError({ message: "Invalid db host" }); - if (host === "localhost" || host === "127.0.0.1" || dbHost === host) { + if ( + host === "localhost" || + host === "127.0.0.1" || + crypto.timingSafeEqual(Buffer.from(dbHost || ""), Buffer.from(host)) + ) { throw new BadRequestError({ message: "Invalid db host" }); } }; 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 eac5e2ecf..5579bc9af 100644 --- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts +++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts @@ -16,6 +16,8 @@ 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 { TOrgGatewayConfigDALFactory } from "../gateway/org-gateway-config-dal"; import { TDynamicSecretDALFactory } from "./dynamic-secret-dal"; import { DynamicSecretStatus, @@ -44,6 +46,8 @@ type TDynamicSecretServiceFactoryDep = { projectDAL: Pick; permissionService: Pick; kmsService: Pick; + gatewayDAL: Pick; + orgGatewayConfigDAL: Pick; }; export type TDynamicSecretServiceFactory = ReturnType; @@ -57,7 +61,9 @@ export const dynamicSecretServiceFactory = ({ permissionService, dynamicSecretQueueService, projectDAL, - kmsService + kmsService, + gatewayDAL, + orgGatewayConfigDAL }: TDynamicSecretServiceFactoryDep) => { const create = async ({ path, @@ -108,6 +114,23 @@ export const dynamicSecretServiceFactory = ({ const selectedProvider = dynamicSecretProviders[provider.type]; const inputs = await selectedProvider.validateProviderInputs(provider.inputs); + let selectedGatewayId: string | null = null; + if (inputs && typeof inputs === "object" && "gatewayId" in inputs && inputs.gatewayId) { + const gatewayId = inputs.gatewayId as string; + + const orgGateway = await orgGatewayConfigDAL.findOne({ orgId: actorOrgId }); + if (!orgGateway) + throw new NotFoundError({ + message: `Gateway with ${gatewayId} not found` + }); + const gateway = await gatewayDAL.findOne({ id: gatewayId, orgGatewayRootCaId: orgGateway.id }); + if (!gateway) + throw new NotFoundError({ + message: `Gateway with ${gatewayId} not found` + }); + selectedGatewayId = gateway.id; + } + const isConnected = await selectedProvider.validateConnection(provider.inputs); if (!isConnected) throw new BadRequestError({ message: "Provider connection failed" }); @@ -123,7 +146,8 @@ export const dynamicSecretServiceFactory = ({ maxTTL, defaultTTL, folderId: folder.id, - name + name, + gatewayId: selectedGatewayId }); return dynamicSecretCfg; }; @@ -195,6 +219,23 @@ export const dynamicSecretServiceFactory = ({ const newInput = { ...decryptedStoredInput, ...(inputs || {}) }; const updatedInput = await selectedProvider.validateProviderInputs(newInput); + let selectedGatewayId: string | null = null; + if (updatedInput && typeof updatedInput === "object" && "gatewayId" in updatedInput && updatedInput?.gatewayId) { + const gatewayId = updatedInput.gatewayId as string; + + const orgGateway = await orgGatewayConfigDAL.findOne({ orgId: actorOrgId }); + if (!orgGateway) + throw new NotFoundError({ + message: `Gateway with ${gatewayId} not found` + }); + const gateway = await gatewayDAL.findOne({ id: gatewayId, orgGatewayRootCaId: orgGateway.id }); + if (!gateway) + throw new NotFoundError({ + message: `Gateway with ${gatewayId} not found` + }); + selectedGatewayId = gateway.id; + } + const isConnected = await selectedProvider.validateConnection(newInput); if (!isConnected) throw new BadRequestError({ message: "Provider connection failed" }); @@ -204,7 +245,8 @@ export const dynamicSecretServiceFactory = ({ defaultTTL, name: newName ?? name, status: null, - statusDetails: null + statusDetails: null, + gatewayId: selectedGatewayId }); return updatedDynamicCfg; diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.ts index 9ed757a37..faa671980 100644 --- a/backend/src/ee/services/dynamic-secret/providers/index.ts +++ b/backend/src/ee/services/dynamic-secret/providers/index.ts @@ -1,5 +1,6 @@ import { SnowflakeProvider } from "@app/ee/services/dynamic-secret/providers/snowflake"; +import { TGatewayServiceFactory } from "../../gateway/gateway-service"; import { AwsElastiCacheDatabaseProvider } from "./aws-elasticache"; import { AwsIamProvider } from "./aws-iam"; import { AzureEntraIDProvider } from "./azure-entra-id"; @@ -16,8 +17,14 @@ import { SapHanaProvider } from "./sap-hana"; import { SqlDatabaseProvider } from "./sql-database"; import { TotpProvider } from "./totp"; -export const buildDynamicSecretProviders = (): Record => ({ - [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider(), +type TBuildDynamicSecretProviderDTO = { + gatewayService: Pick; +}; + +export const buildDynamicSecretProviders = ({ + gatewayService +}: TBuildDynamicSecretProviderDTO): Record => ({ + [DynamicSecretProviders.SqlDatabase]: SqlDatabaseProvider({ gatewayService }), [DynamicSecretProviders.Cassandra]: CassandraProvider(), [DynamicSecretProviders.AwsIam]: AwsIamProvider(), [DynamicSecretProviders.Redis]: RedisDatabaseProvider(), diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.ts index e8b9e6548..8b742dc54 100644 --- a/backend/src/ee/services/dynamic-secret/providers/models.ts +++ b/backend/src/ee/services/dynamic-secret/providers/models.ts @@ -103,7 +103,8 @@ export const DynamicSecretSqlDBSchema = z.object({ creationStatement: z.string().trim(), revocationStatement: z.string().trim(), renewStatement: z.string().trim().optional(), - ca: z.string().optional() + ca: z.string().optional(), + gatewayId: z.string().nullable().optional() }); export const DynamicSecretCassandraSchema = z.object({ 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 a9bfad525..53b16e026 100644 --- a/backend/src/ee/services/dynamic-secret/providers/sql-database.ts +++ b/backend/src/ee/services/dynamic-secret/providers/sql-database.ts @@ -3,8 +3,10 @@ import knex from "knex"; import { customAlphabet } from "nanoid"; import { z } from "zod"; +import { withGatewayProxy } from "@app/lib/gateway"; import { alphaNumericNanoId } from "@app/lib/nanoid"; +import { TGatewayServiceFactory } from "../../gateway/gateway-service"; import { verifyHostInputValidity } from "../dynamic-secret-fns"; import { DynamicSecretSqlDBSchema, SqlProviders, TDynamicProviderFns } from "./models"; @@ -25,10 +27,14 @@ const generateUsername = (provider: SqlProviders) => { return alphaNumericNanoId(32); }; -export const SqlDatabaseProvider = (): TDynamicProviderFns => { +type TSqlDatabaseProviderDTO = { + gatewayService: Pick; +}; + +export const SqlDatabaseProvider = ({ gatewayService }: TSqlDatabaseProviderDTO): TDynamicProviderFns => { const validateProviderInputs = async (inputs: unknown) => { const providerInputs = await DynamicSecretSqlDBSchema.parseAsync(inputs); - verifyHostInputValidity(providerInputs.host); + verifyHostInputValidity(providerInputs.host, Boolean(providerInputs.gatewayId)); return providerInputs; }; @@ -61,61 +67,107 @@ export const SqlDatabaseProvider = (): TDynamicProviderFns => { return db; }; + const gatewayProxyWrapper = async ( + providerInputs: z.infer, + gatewayCallback: (port: number) => Promise + ) => { + const relayDetails = await gatewayService.fnGetGatewayClientTls(providerInputs.gatewayId as string); + const [relayHost, relayPort] = relayDetails.relayAddress.split(":"); + await withGatewayProxy( + async (port) => { + await gatewayCallback(port); + }, + { + targetHost: providerInputs.host, + targetPort: providerInputs.port, + relayHost, + relayPort: Number(relayPort), + identityId: relayDetails.identityId, + orgId: relayDetails.orgId, + tlsOptions: { + ca: relayDetails.certChain, + cert: relayDetails.certificate, + key: relayDetails.privateKey + } + } + ); + }; + const validateConnection = async (inputs: unknown) => { const providerInputs = await validateProviderInputs(inputs); - const db = await $getClient(providerInputs); - // oracle needs from keyword - const testStatement = providerInputs.client === SqlProviders.Oracle ? "SELECT 1 FROM DUAL" : "SELECT 1"; + let isConnected = false; + const gatewayCallback = async (port = providerInputs.port) => { + const db = await $getClient({ ...providerInputs, port }); + // oracle needs from keyword + const testStatement = providerInputs.client === SqlProviders.Oracle ? "SELECT 1 FROM DUAL" : "SELECT 1"; - const isConnected = await db.raw(testStatement).then(() => true); - await db.destroy(); + isConnected = await db.raw(testStatement).then(() => true); + await db.destroy(); + }; + + if (providerInputs.gatewayId) { + await gatewayProxyWrapper(providerInputs, gatewayCallback); + } else { + await gatewayCallback(); + } return isConnected; }; const create = async (inputs: unknown, expireAt: number) => { const providerInputs = await validateProviderInputs(inputs); - const db = await $getClient(providerInputs); - const username = generateUsername(providerInputs.client); const password = generatePassword(providerInputs.client); - const { database } = providerInputs; - const expiration = new Date(expireAt).toISOString(); + const gatewayCallback = async (port = providerInputs.port) => { + const db = await $getClient({ ...providerInputs, port }); + const { database } = providerInputs; + const expiration = new Date(expireAt).toISOString(); - const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({ - username, - password, - expiration, - database - }); + const creationStatement = handlebars.compile(providerInputs.creationStatement, { noEscape: true })({ + username, + password, + expiration, + database + }); - const queries = creationStatement.toString().split(";").filter(Boolean); - await db.transaction(async (tx) => { - for (const query of queries) { - // eslint-disable-next-line - await tx.raw(query); - } - }); - await db.destroy(); + const queries = creationStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); + await db.destroy(); + }; + if (providerInputs.gatewayId) { + await gatewayProxyWrapper(providerInputs, gatewayCallback); + } else { + await gatewayCallback(); + } return { entityId: username, data: { DB_USERNAME: username, DB_PASSWORD: password } }; }; const revoke = async (inputs: unknown, entityId: string) => { const providerInputs = await validateProviderInputs(inputs); - const db = await $getClient(providerInputs); - const username = entityId; const { database } = providerInputs; + const gatewayCallback = async (port = providerInputs.port) => { + const db = await $getClient({ ...providerInputs, port }); + const revokeStatement = handlebars.compile(providerInputs.revocationStatement)({ username, database }); + const queries = revokeStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); - const revokeStatement = handlebars.compile(providerInputs.revocationStatement)({ username, database }); - const queries = revokeStatement.toString().split(";").filter(Boolean); - await db.transaction(async (tx) => { - for (const query of queries) { - // eslint-disable-next-line - await tx.raw(query); - } - }); - - await db.destroy(); + await db.destroy(); + }; + if (providerInputs.gatewayId) { + await gatewayProxyWrapper(providerInputs, gatewayCallback); + } else { + await gatewayCallback(); + } return { entityId: username }; }; @@ -123,28 +175,34 @@ export const SqlDatabaseProvider = (): TDynamicProviderFns => { const providerInputs = await validateProviderInputs(inputs); if (!providerInputs.renewStatement) return { entityId }; - const db = await $getClient(providerInputs); + const gatewayCallback = async (port = providerInputs.port) => { + const db = await $getClient({ ...providerInputs, port }); + const expiration = new Date(expireAt).toISOString(); + const { database } = providerInputs; - const expiration = new Date(expireAt).toISOString(); - const { database } = providerInputs; - - const renewStatement = handlebars.compile(providerInputs.renewStatement)({ - username: entityId, - expiration, - database - }); - - if (renewStatement) { - const queries = renewStatement.toString().split(";").filter(Boolean); - await db.transaction(async (tx) => { - for (const query of queries) { - // eslint-disable-next-line - await tx.raw(query); - } + const renewStatement = handlebars.compile(providerInputs.renewStatement)({ + username: entityId, + expiration, + database }); - } - await db.destroy(); + if (renewStatement) { + const queries = renewStatement.toString().split(";").filter(Boolean); + await db.transaction(async (tx) => { + for (const query of queries) { + // eslint-disable-next-line + await tx.raw(query); + } + }); + } + + await db.destroy(); + }; + if (providerInputs.gatewayId) { + await gatewayProxyWrapper(providerInputs, gatewayCallback); + } else { + await gatewayCallback(); + } return { entityId }; }; diff --git a/backend/src/ee/services/gateway/gateway-dal.ts b/backend/src/ee/services/gateway/gateway-dal.ts index 86a40a3fe..5d0be06bf 100644 --- a/backend/src/ee/services/gateway/gateway-dal.ts +++ b/backend/src/ee/services/gateway/gateway-dal.ts @@ -1,3 +1,5 @@ +import { Knex } from "knex"; + import { TDbClient } from "@app/db"; import { TableName, TGateways } from "@app/db/schemas"; import { DatabaseError } from "@app/lib/errors"; @@ -29,5 +31,24 @@ export const gatewayDALFactory = (db: TDbClient) => { } }; - return { ...orm, find }; + const findByProjectId = async (projectId: string, tx?: Knex) => { + try { + const query = (tx || db)(TableName.Gateway) + .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Gateway}.identityId`) + .join( + TableName.IdentityProjectMembership, + `${TableName.Identity}.id`, + `${TableName.IdentityProjectMembership}.identityId` + ) + .select(selectAllTableCols(TableName.Gateway)) + .select(db.ref("name").withSchema(TableName.Identity).as("identityName")) + .where({ [`${TableName.IdentityProjectMembership}.projectId` as "projectId"]: projectId }); + const docs = await query; + return docs.map((el) => ({ ...el, identity: { id: el.identityId, name: el.identityName } })); + } catch (error) { + throw new DatabaseError({ error, name: `${TableName.Gateway}: Find by project id` }); + } + }; + + return { ...orm, find, findByProjectId }; }; diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index 330d48d0e..e3d07041e 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -1,15 +1,16 @@ import crypto from "node:crypto"; -import { ForbiddenError } from "@casl/ability"; +import { ForbiddenError, subject } from "@casl/ability"; import * as x509 from "@peculiar/x509"; -import fs from "fs/promises"; -import path from "path/posix"; +import { z } from "zod"; -import { PgSqlLock } from "@app/keystore/keystore"; +import { ActionProjectType } from "@app/db/schemas"; +import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError, NotFoundError } from "@app/lib/errors"; 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, @@ -21,29 +22,41 @@ import { KmsDataKey } from "@app/services/kms/kms-types"; import { TLicenseServiceFactory } from "../license/license-service"; import { OrgGatewayPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; import { TPermissionServiceFactory } from "../permission/permission-service"; +import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { TGatewayDALFactory } from "./gateway-dal"; -import { TExchangeAllocatedRelayAddressDTO, TGetGatewayByIdDTO, TListGatewaysDTO } from "./gateway-types"; +import { + TExchangeAllocatedRelayAddressDTO, + TGetGatewayByIdDTO, + TGetProjectGatewayByIdDTO, + TListGatewaysDTO, + TUpdateGatewayByIdDTO +} from "./gateway-types"; import { TOrgGatewayConfigDALFactory } from "./org-gateway-config-dal"; type TGatewayServiceFactoryDep = { gatewayDAL: TGatewayDALFactory; - orgGatewayConfigDAL: Pick; + orgGatewayConfigDAL: Pick; licenseService: Pick; kmsService: Pick; - permissionService: Pick; + permissionService: Pick; + keyStore: Pick; }; export type TGatewayServiceFactory = ReturnType; +const TURN_SERVER_CREDENTIALS_SCHEMA = z.object({ + username: z.string(), + password: z.string() +}); -// TODO(gateway): missing permission check export const gatewayServiceFactory = ({ gatewayDAL, licenseService, kmsService, permissionService, - orgGatewayConfigDAL + orgGatewayConfigDAL, + keyStore }: TGatewayServiceFactoryDep) => { - const $validateOrgAccessToGateway = async (orgId: string) => { + const $validateOrgAccessToGateway = async (orgId: string, actorId: string, actorAuthMethod: ActorAuthMethod) => { if (!licenseService.onPremFeatures.gateway) { throw new BadRequestError({ message: @@ -57,11 +70,20 @@ export const gatewayServiceFactory = ({ "Gateway handshake failed due to organization plan restrictions. Please upgrade your instance to Infisical's Enterprise plan." }); } + const { permission } = await permissionService.getOrgPermission( + ActorType.IDENTITY, + actorId, + orgId, + actorAuthMethod, + orgId + ); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); }; - const getGatewayRelayDetails = async (actorId: string, actorOrgId: string) => { + const getGatewayRelayDetails = async (actorId: string, actorOrgId: string, actorAuthMethod: ActorAuthMethod) => { + const TURN_CRED_EXPIRY = 5 * 60; const envCfg = getConfig(); - await $validateOrgAccessToGateway(actorOrgId); + await $validateOrgAccessToGateway(actorOrgId, actorId, actorAuthMethod); if ( !envCfg.GATEWAY_RELAY_AUTH_SECRET || @@ -73,11 +95,25 @@ export const gatewayServiceFactory = ({ message: "Gateway handshake failed due to missing instance config." }); } - // TODO(gateway): keep it in 30mins redis after encryption to avoid multiple credentials spinning up - const { username: turnServerUsername, password: turnServerPassword } = getTurnCredentials( - actorId, - envCfg.GATEWAY_RELAY_AUTH_SECRET - ); + + 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(previousCredential)); + turnServerUsername = el.username; + turnServerPassword = el.password; + } else { + const el = getTurnCredentials(actorId, envCfg.GATEWAY_RELAY_AUTH_SECRET); + await keyStore.setItemWithExpiry( + KeyStorePrefixes.GatewayIdentityCredential(actorId), + TURN_CRED_EXPIRY, + JSON.stringify({ username: el.username, password: el.password }) + ); + turnServerUsername = el.username; + turnServerPassword = el.password; + } return { turnServerUsername, @@ -91,8 +127,10 @@ export const gatewayServiceFactory = ({ const exchangeAllocatedRelayAddress = async ({ identityId, identityOrg, - relayAddress + relayAddress, + identityOrgAuthMethod }: TExchangeAllocatedRelayAddressDTO) => { + await $validateOrgAccessToGateway(identityOrg, identityId, identityOrgAuthMethod); const { encryptor: orgKmsEncryptor, decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.Organization, orgId: identityOrg @@ -160,7 +198,7 @@ export const gatewayServiceFactory = ({ const clientCertSerialNumber = createSerialNumber(); const clientCert = await x509.X509CertificateGenerator.create({ serialNumber: clientCertSerialNumber, - subject: "O=infisical,OU=gateway,CN=cloud-client", + subject: `O=${identityOrg},OU=gateway-client,CN=cloud`, issuer: clientCaCert.subject, notAfter: clientCaExpiration, notBefore: clientCaIssuedAt, @@ -214,15 +252,6 @@ export const gatewayServiceFactory = ({ ] }); - await fs.writeFile(path.join(__dirname, "./root-ca-cert"), rootCaCert.toString("pem")); - await fs.writeFile(path.join(__dirname, "./client-ca-cert"), clientCaCert.toString("pem")); - await fs.writeFile(path.join(__dirname, "./gateway-ca-cert"), gatewayCaCert.toString("pem")); - await fs.writeFile(path.join(__dirname, "./client-cert"), clientCert.toString("pem")); - await fs.writeFile( - path.join(__dirname, "./client-key"), - clientSkObj.export({ type: "pkcs8", format: "pem" }) as string - ); - return orgGatewayConfigDAL.create({ orgId: identityOrg, rootCaIssuedAt, @@ -322,7 +351,6 @@ export const gatewayServiceFactory = ({ ), new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true), // san - // TODO(gateway): change this later new x509.SubjectAlternativeNameExtension([{ type: "ip", value: "127.0.0.1" }], false) ]; @@ -340,16 +368,23 @@ export const gatewayServiceFactory = ({ 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(relayAddress) }).cipherTextBlob + relayAddress: orgKmsEncryptor({ + plainText: Buffer.from(formatedRelayAddress) + }).cipherTextBlob }); } @@ -358,7 +393,9 @@ export const gatewayServiceFactory = ({ issuedAt: certIssuedAt, expiration: certExpireAt, serialNumber, - relayAddress: orgKmsEncryptor({ plainText: Buffer.from(relayAddress) }).cipherTextBlob, + relayAddress: orgKmsEncryptor({ + plainText: Buffer.from(formatedRelayAddress) + }).cipherTextBlob, identityId, orgGatewayRootCaId: orgGatewayConfig.id, name: alphaNumericNanoId(8) @@ -410,6 +447,23 @@ export const gatewayServiceFactory = ({ return gateway; }; + const updateGatewayById = async ({ orgPermission, id, name }: TUpdateGatewayByIdDTO) => { + const { permission } = await permissionService.getOrgPermission( + orgPermission.type, + orgPermission.id, + orgPermission.orgId, + orgPermission.authMethod, + orgPermission.orgId + ); + ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Delete, 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( orgPermission.type, @@ -427,11 +481,78 @@ export const gatewayServiceFactory = ({ return gateway; }; + const getProjectGateways = async ({ projectId, projectPermission }: TGetProjectGatewayByIdDTO) => { + const { permission } = await permissionService.getProjectPermission({ + projectId, + actor: projectPermission.type, + actorId: projectPermission.id, + actorOrgId: projectPermission.orgId, + actorAuthMethod: projectPermission.authMethod, + actionProjectType: ActionProjectType.Any + }); + + const gateways = await gatewayDAL.findByProjectId(projectId); + const allowedGateways = gateways.filter((el) => + permission.can( + ProjectPermissionActions.Read, + subject(ProjectPermissionSub.Identity, { identityId: el.identityId }) + ) + ); + return allowedGateways; + }; + + // this has no permission check and used for dynamic secrets directly + // assumes permission check is already done + const fnGetGatewayClientTls = async (gatewayId: string) => { + 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 { 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.createPrivateKey({ + key: orgKmsDecryptor({ cipherTextBlob: orgGatewayConfig.encryptedClientPrivateKey }), + format: "der", + type: "pkcs8" + }); + + return { + relayAddress: orgKmsDecryptor({ cipherTextBlob: gateway.relayAddress }).toString(), + privateKey: clientSkObj.export({ type: "pkcs8", format: "pem" }), + certificate: clientCert.toString("pem"), + certChain: `${gatewayCaCert.toString("pem")}\n${rootCaCert.toString("pem")}`.trim(), + identityId: gateway.identityId, + orgId: orgGatewayConfig.orgId + }; + }; + return { getGatewayRelayDetails, exchangeAllocatedRelayAddress, listGateways, getGatewayById, - deleteGatewayById + updateGatewayById, + deleteGatewayById, + getProjectGateways, + fnGetGatewayClientTls }; }; diff --git a/backend/src/ee/services/gateway/gateway-types.ts b/backend/src/ee/services/gateway/gateway-types.ts index 40328d041..666f65e6b 100644 --- a/backend/src/ee/services/gateway/gateway-types.ts +++ b/backend/src/ee/services/gateway/gateway-types.ts @@ -1,8 +1,10 @@ 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; }; @@ -15,7 +17,18 @@ export type TGetGatewayByIdDTO = { 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; +}; diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts index 3f9e1b42c..21d378802 100644 --- a/backend/src/ee/services/license/license-fns.ts +++ b/backend/src/ee/services/license/license-fns.ts @@ -52,7 +52,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ enforceMfa: false, projectTemplates: false, kmip: false, - gateway: true + gateway: false }); export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => { diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts index 626a0c999..34e350cf6 100644 --- a/backend/src/ee/services/license/license-types.ts +++ b/backend/src/ee/services/license/license-types.ts @@ -69,7 +69,7 @@ export type TFeatureSet = { enforceMfa: boolean; projectTemplates: false; kmip: false; - gateway: true; + gateway: false; }; export type TOrgPlansTableDTO = { diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts index 272dc6de4..efed6a1b2 100644 --- a/backend/src/ee/services/permission/org-permission.ts +++ b/backend/src/ee/services/permission/org-permission.ts @@ -275,6 +275,7 @@ const buildAdminPermission = () => { can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); + can(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); can(OrgGatewayPermissionActions.Edit, OrgPermissionSubjects.Gateway); can(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); @@ -315,6 +316,7 @@ const buildMemberPermission = () => { can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); + can(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); return rules; }; diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts index 76e93ce9f..04d31fc1a 100644 --- a/backend/src/keystore/keystore.ts +++ b/backend/src/keystore/keystore.ts @@ -1,7 +1,7 @@ import { Redis } from "ioredis"; -import { Redlock, Settings } from "@app/lib/red-lock"; import { pgAdvisoryLockHashText } from "@app/lib/crypto/hashtext"; +import { Redlock, Settings } from "@app/lib/red-lock"; export const PgSqlLock = { BootUpMigration: 2023, @@ -36,7 +36,8 @@ export const KeyStorePrefixes = { SecretSyncLastRunTimestamp: (syncId: string) => `secret-sync-last-run-${syncId}` as const, IdentityAccessTokenStatusUpdate: (identityAccessTokenId: string) => `identity-access-token-status:${identityAccessTokenId}`, - ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}` + ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`, + GatewayIdentityCredential: (identityId: string) => `gateway-credentails:${identityId}` }; export const KeyStoreTtls = { diff --git a/backend/src/lib/gateway/index.ts b/backend/src/lib/gateway/index.ts new file mode 100644 index 000000000..b4963cdff --- /dev/null +++ b/backend/src/lib/gateway/index.ts @@ -0,0 +1,258 @@ +/* eslint-disable no-await-in-loop */ +import net from "node:net"; +import tls from "node:tls"; + +import { BadRequestError } from "../errors"; +import { logger } from "../logger"; + +const DEFAULT_MAX_RETRIES = 3; +const DEFAULT_RETRY_DELAY = 1000; // 1 second + +const createTLSConnection = (relayHost: string, relayPort: number, tlsOptions: tls.TlsOptions = {}) => { + return new Promise((resolve, reject) => { + // @ts-expect-error this is resolved in next connect + const socket = new tls.TLSSocket(null, { + rejectUnauthorized: true, + ...tlsOptions + }); + + const cleanup = () => { + socket.removeAllListeners(); + socket.end(); + }; + + socket.once("error", (err) => { + cleanup(); + reject(err); + }); + + socket.connect(relayPort, relayHost, () => { + resolve(socket); + }); + }); +}; + +type TPingGatewayAndVerifyDTO = { + relayHost: string; + relayPort: number; + tlsOptions: tls.TlsOptions; + maxRetries: number; + identityId: string; + orgId: string; +}; + +const pingGatewayAndVerifyIdentity = async ({ + relayHost, + relayPort, + tlsOptions = {}, + maxRetries = DEFAULT_MAX_RETRIES, + identityId, + orgId +}: TPingGatewayAndVerifyDTO) => { + let lastError: Error | null = null; + + for (let attempt = 1; attempt <= maxRetries; attempt += 1) { + try { + const socket = await createTLSConnection(relayHost, relayPort, tlsOptions); + socket.setTimeout(2000); + + const pingResult = await new Promise((resolve, reject) => { + socket.once("timeout", () => { + socket.destroy(); + reject(new Error("Timeout")); + }); + socket.once("close", () => { + socket.destroy(); + }); + + socket.once("end", () => { + socket.destroy(); + }); + socket.once("error", (err) => { + reject(err); + }); + + socket.write(Buffer.from("PING\n"), () => { + socket.once("data", (data) => { + const response = (data as string).toString(); + const certificate = socket.getPeerCertificate(); + + if (certificate.subject.CN !== identityId || certificate.subject.O !== orgId) { + throw new BadRequestError({ + message: `Invalid gateway. Certificate not found for ${identityId} in organisation ${orgId}` + }); + } + + if (response === "PONG") { + resolve(true); + } else { + reject(new Error(`Unexpected response: ${response}`)); + } + }); + }); + }); + + socket.end(); + return pingResult; + } catch (err) { + lastError = err as Error; + + if (attempt < maxRetries) { + await new Promise((resolve) => { + setTimeout(resolve, DEFAULT_RETRY_DELAY); + }); + } + } + } + + throw new Error(`Failed to ping gateway after ${maxRetries} attempts. Last error: ${lastError?.message}`); +}; + +interface TProxyServer { + server: net.Server; + port: number; + cleanup: () => void; +} + +const setupProxyServer = ({ + targetPort, + targetHost, + tlsOptions = {}, + relayHost, + relayPort +}: { + targetHost: string; + targetPort: number; + relayPort: number; + relayHost: string; + tlsOptions: tls.TlsOptions; +}): Promise => { + return new Promise((resolve, reject) => { + const server = net.createServer(); + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + server.on("connection", async (clientSocket) => { + try { + const targetSocket = await createTLSConnection(relayHost, relayPort, tlsOptions); + + targetSocket.write(Buffer.from(`FORWARD-TCP ${targetHost}:${targetPort}\n`), () => { + clientSocket.on("data", (data) => { + const flushed = targetSocket.write(data); + if (!flushed) { + clientSocket.pause(); + targetSocket.once("drain", () => { + clientSocket.resume(); + }); + } + }); + + targetSocket.on("data", (data) => { + const flushed = clientSocket.write(data as string); + if (!flushed) { + targetSocket.pause(); + clientSocket.once("drain", () => { + targetSocket.resume(); + }); + } + }); + }); + + const cleanup = () => { + clientSocket?.unpipe(); + clientSocket?.end(); + targetSocket?.unpipe(); + targetSocket?.end(); + }; + + clientSocket.on("error", (err) => { + logger.error(err, "Client socket error"); + cleanup(); + reject(err); + }); + + targetSocket.on("error", (err) => { + logger.error(err, "Target socket error"); + cleanup(); + reject(err); + }); + + clientSocket.on("end", cleanup); + targetSocket.on("end", cleanup); + } catch (err) { + logger.error(err, "Failed to establish target connection:"); + clientSocket.end(); + reject(err); + } + }); + + server.on("error", (err) => { + reject(err); + }); + + 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"); + resolve({ + server, + port: address.port, + cleanup: () => { + server.close(); + } + }); + }); + }); +}; + +interface ProxyOptions { + targetHost: string; + targetPort: number; + relayHost: string; + relayPort: number; + tlsOptions?: tls.TlsOptions; + maxRetries?: number; + identityId: string; + orgId: string; +} + +export const withGatewayProxy = async ( + callback: (port: number) => Promise, + options: ProxyOptions +): Promise => { + const { + relayHost, + relayPort, + targetHost, + targetPort, + tlsOptions = {}, + maxRetries = DEFAULT_MAX_RETRIES, + identityId, + orgId + } = options; + + // First, try to ping the gateway + await pingGatewayAndVerifyIdentity({ + relayHost, + relayPort, + tlsOptions, + maxRetries, + identityId, + orgId + }); + + // Setup the proxy server + const { port, cleanup } = await setupProxyServer({ targetHost, targetPort, relayPort, relayHost, tlsOptions }); + + try { + // Execute the callback with the allocated port + await callback(port); + } finally { + // Ensure cleanup happens regardless of success or failure + cleanup(); + } +}; diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index ca6a16a6e..11fa5220e 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -1306,7 +1306,18 @@ export const registerRoutes = async ( kmsService }); - const dynamicSecretProviders = buildDynamicSecretProviders(); + const gatewayService = gatewayServiceFactory({ + permissionService, + gatewayDAL, + kmsService, + licenseService, + orgGatewayConfigDAL, + keyStore + }); + + const dynamicSecretProviders = buildDynamicSecretProviders({ + gatewayService + }); const dynamicSecretQueueService = dynamicSecretLeaseQueueServiceFactory({ queueService, dynamicSecretLeaseDAL, @@ -1324,8 +1335,11 @@ export const registerRoutes = async ( folderDAL, permissionService, licenseService, - kmsService + kmsService, + gatewayDAL, + orgGatewayConfigDAL }); + const dynamicSecretLeaseService = dynamicSecretLeaseServiceFactory({ projectDAL, permissionService, From 78718cd299e77a8e9e4d5c4485c7d1e01376603c Mon Sep 17 00:00:00 2001 From: = Date: Tue, 18 Feb 2025 23:36:39 +0530 Subject: [PATCH 09/30] feat: completed cli for gateway --- cli/packages/gateway/connection.go | 54 ++++++++++++++---------------- cli/packages/gateway/gateway.go | 52 ++++++++++++++++++++-------- 2 files changed, 63 insertions(+), 43 deletions(-) diff --git a/cli/packages/gateway/connection.go b/cli/packages/gateway/connection.go index dfde595cb..bd91f1f61 100644 --- a/cli/packages/gateway/connection.go +++ b/cli/packages/gateway/connection.go @@ -3,7 +3,7 @@ package gateway import ( "bufio" "bytes" - "fmt" + "errors" "io" "net" "sync" @@ -20,6 +20,9 @@ func handleConnection(conn net.Conn) { for { msg, err := reader.ReadBytes('\n') if err != nil { + if errors.Is(err, io.EOF) { + return + } log.Error().Msgf("Error reading command: %s", err) return } @@ -30,9 +33,7 @@ func handleConnection(conn net.Conn) { switch string(cmd) { case "FORWARD-TCP": proxyAddress := string(bytes.Split(args, []byte(" "))[0]) - fmt.Println(proxyAddress) destTarget, err := net.Dial("tcp", proxyAddress) - fmt.Println(err) if err != nil { log.Error().Msgf("Failed to connect to target: %v", err) return @@ -56,12 +57,13 @@ func handleConnection(conn net.Conn) { } CopyData(conn, destTarget) - break + return case "PING": - conn.Write([]byte("PONG\n")) + conn.Write([]byte("PONG")) + return default: log.Error().Msgf("Unknown command: %s", string(cmd)) - break + return } } } @@ -71,39 +73,33 @@ type CloseWrite interface { } func CopyData(src, dst net.Conn) { - // Create a WaitGroup to wait for both copy operations var wg sync.WaitGroup wg.Add(2) - // Start copying in both directions - go func() { + copyAndClose := func(dst, src net.Conn, done chan<- bool) { defer wg.Done() - if _, err := io.Copy(dst, src); err != nil { - log.Error().Msgf("Error copying postgres->client: %v", err) + _, err := io.Copy(dst, src) + if err != nil && !errors.Is(err, io.EOF) { + log.Error().Msgf("Copy error: %v", err) } - if e, ok := dst.(CloseWrite); ok { - log.Print("Closing dst") - e.CloseWrite() - } else { + // Signal we're done writing + done <- true - log.Print("Not closed") + // Half close the connection if possible + if c, ok := dst.(CloseWrite); ok { + c.CloseWrite() } - }() + } - go func() { - defer wg.Done() - if _, err := io.Copy(src, dst); err != nil { - log.Error().Msgf("Error copying client->postgres: %v", err) - } - if e, ok := src.(CloseWrite); ok { - log.Print("Closing src") - e.CloseWrite() - } else { - log.Print("Not closed") - } - }() + done1 := make(chan bool, 1) + done2 := make(chan bool, 1) + + go copyAndClose(dst, src, done1) + go copyAndClose(src, dst, done2) // Wait for both copies to complete + <-done1 + <-done2 wg.Wait() } diff --git a/cli/packages/gateway/gateway.go b/cli/packages/gateway/gateway.go index 484737b79..766af9795 100644 --- a/cli/packages/gateway/gateway.go +++ b/cli/packages/gateway/gateway.go @@ -48,16 +48,15 @@ func (g *Gateway) ConnectWithRelay() error { return err } - // Dial TURN Server - conn, err := net.Dial("tcp", relayDetails.TurnServerAddress) + turnServerAddr, err := net.ResolveTCPAddr("tcp", relayDetails.TurnServerAddress) if err != nil { - return fmt.Errorf("Failed to connect with relay server: %w", err) + return fmt.Errorf("Failed to resolve TURN server address: %w", err) } - if tcpConn, ok := conn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(10 * time.Second) - tcpConn.SetNoDelay(true) + // Dial TURN Server + conn, err := net.DialTCP("tcp", nil, turnServerAddr) + if err != nil { + return fmt.Errorf("Failed to connect with relay server: %w", err) } // Start a new TURN Client and wrap our net.Conn in a STUNConn @@ -77,11 +76,6 @@ func (g *Gateway) ConnectWithRelay() error { return fmt.Errorf("Failed to create relay client: %w", err) } - err = client.Listen() - if err != nil { - return fmt.Errorf("Failed to listen to relay server: %w", err) - } - g.config = &GatewayConfig{ TurnServerUsername: relayDetails.TurnServerUsername, TurnServerPassword: relayDetails.TurnServerPassword, @@ -99,6 +93,11 @@ func (g *Gateway) ConnectWithRelay() error { func (g *Gateway) Listen() error { defer g.client.Close() + err := g.client.Listen() + if err != nil { + return fmt.Errorf("Failed to listen to relay server: %w", err) + } + log.Info().Msg("Connected with relay") // Allocate a relay socket on the TURN server. On success, it // will return a net.PacketConn which represents the remote // socket. @@ -106,6 +105,7 @@ func (g *Gateway) Listen() error { if err != nil { return fmt.Errorf("Failed to allocate relay connection: %w", err) } + defer func() { if closeErr := relayNonTlsConn.Close(); closeErr != nil { log.Error().Msgf("Failed to close connection: %s", closeErr) @@ -148,7 +148,6 @@ func (g *Gateway) Listen() error { return fmt.Errorf("failed to parse cert: %s", err) } - fmt.Println(relayNonTlsConn.Addr().String()) caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM([]byte(gatewayCert.CertificateChain)) @@ -159,8 +158,8 @@ func (g *Gateway) Listen() error { ClientAuth: tls.RequireAndVerifyClientCert, }) + log.Info().Msg("Connector started successfully") for { - log.Info().Msg("Connector started successfully") // Accept new relay connection conn, err := relayConn.Accept() if err != nil { @@ -168,6 +167,31 @@ func (g *Gateway) Listen() error { continue } + tlsConn, ok := conn.(*tls.Conn) + if !ok { + log.Error().Msg("Failed to convert to TLS connection") + conn.Close() + continue + } + + err = tlsConn.Handshake() + if err != nil { + log.Error().Msgf("TLS handshake failed: %v", err) + conn.Close() + continue + } + + // Get connection state which contains certificate information + state := tlsConn.ConnectionState() + if len(state.PeerCertificates) > 0 { + organizationUnit := state.PeerCertificates[0].Subject.OrganizationalUnit + commonName := state.PeerCertificates[0].Subject.CommonName + if organizationUnit[0] != "gateway-client" && commonName != "cloud" { + log.Error().Msgf("Client certificate verification failed. Received %s, %s", organizationUnit, commonName) + continue + } + } + // Handle the connection in a goroutine go handleConnection(conn) } From f34370cb9df96b7462daac81f5300856cac61b60 Mon Sep 17 00:00:00 2001 From: = Date: Tue, 18 Feb 2025 23:39:31 +0530 Subject: [PATCH 10/30] feat: completed frontend --- frontend/src/components/v2/Modal/Modal.tsx | 6 +- frontend/src/hooks/api/dynamicSecret/types.ts | 1 + frontend/src/hooks/api/gateways/index.tsx | 2 +- frontend/src/hooks/api/gateways/mutation.tsx | 17 ++- frontend/src/hooks/api/gateways/queries.tsx | 16 ++- frontend/src/hooks/api/gateways/types.ts | 9 ++ .../GatewayListPage/GatewayListPage.tsx | 111 +++++++++++++++++- .../components/EditGatewayDetailsModal.tsx | 75 ++++++++++++ .../RolePermissionsSection.tsx | 6 + .../SqlDatabaseInputForm.tsx | 42 ++++++- .../EditDynamicSecretSqlProviderForm.tsx | 49 +++++++- 11 files changed, 316 insertions(+), 18 deletions(-) create mode 100644 frontend/src/pages/organization/Gateways/GatewayListPage/components/EditGatewayDetailsModal.tsx diff --git a/frontend/src/components/v2/Modal/Modal.tsx b/frontend/src/components/v2/Modal/Modal.tsx index 9b7baa921..f3b63eae4 100644 --- a/frontend/src/components/v2/Modal/Modal.tsx +++ b/frontend/src/components/v2/Modal/Modal.tsx @@ -45,7 +45,11 @@ export const ModalContent = forwardRef( )} style={{ maxHeight: "90%" }} > - {title && {title}} + {title && ( + + {title} + + )} { +export const useDeleteGatewayById = () => { const queryClient = useQueryClient(); return useMutation({ mutationFn: (id: string) => { return apiRequest.delete(`/api/v1/gateways/${id}`); }, onSuccess: () => { - queryClient.invalidateQueries(gatewaysQueryKeys.list()); + 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 bb05b17a4..a38fe39bd 100644 --- a/frontend/src/hooks/api/gateways/queries.tsx +++ b/frontend/src/hooks/api/gateways/queries.tsx @@ -2,16 +2,22 @@ import { queryOptions } from "@tanstack/react-query"; import { apiRequest } from "@app/config/request"; -import { TGateway } from "./types"; +import { TGateway, TListGatewayDTO } from "./types"; export const gatewaysQueryKeys = { allKey: () => ["gateways"], - listKey: () => [...gatewaysQueryKeys.allKey(), "list"], - list: () => + listKey: ({ projectId }: TListGatewayDTO) => [ + ...gatewaysQueryKeys.allKey(), + "list", + { projectId } + ], + list: ({ projectId }: TListGatewayDTO = {}) => queryOptions({ - queryKey: gatewaysQueryKeys.listKey(), + queryKey: gatewaysQueryKeys.listKey({ projectId }), queryFn: async () => { - const { data } = await apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"); + const { data } = await apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways", { + params: { projectId } + }); return data.gateways; } }) diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts index 0af9d04b8..9d7917ef4 100644 --- a/frontend/src/hooks/api/gateways/types.ts +++ b/frontend/src/hooks/api/gateways/types.ts @@ -12,6 +12,15 @@ export type TGateway = { }; }; +export type TUpdateGatewayDTO = { + id: string; + name?: string; +}; + export type TDeleteGatewayDTO = { id: string; }; + +export type TListGatewayDTO = { + projectId?: string; +}; diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx index 0ced1319f..d252f259a 100644 --- a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx @@ -3,17 +3,30 @@ import { Helmet } from "react-helmet"; import { faArrowUpRightFromSquare, faBookOpen, + faEdit, + faEllipsisV, faMagnifyingGlass, faPlug, - faSearch + faSearch, + faTrash } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useQuery } from "@tanstack/react-query"; import { format } from "date-fns"; +import { createNotification } from "@app/components/notifications"; +import { OrgPermissionCan } from "@app/components/permissions"; import { + DeleteActionModal, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, EmptyState, + IconButton, Input, + Modal, + ModalContent, PageHeader, Table, TableContainer, @@ -22,20 +35,44 @@ import { Td, Th, THead, + Tooltip, Tr } from "@app/components/v2"; import { + OrgGatewayPermissionActions, OrgPermissionAppConnectionActions, OrgPermissionSubjects } from "@app/context/OrgPermissionContext/types"; import { withPermission } from "@app/hoc"; -import { gatewaysQueryKeys } from "@app/hooks/api/gateways"; +import { usePopUp } from "@app/hooks"; +import { gatewaysQueryKeys, useDeleteGatewayById } from "@app/hooks/api/gateways"; + +import { EditGatewayDetailsModal } from "./components/EditGatewayDetailsModal"; export const GatewayListPage = withPermission( () => { const [search, setSearch] = useState(""); const { data: gateways, isPending: isGatewayLoading } = useQuery(gatewaysQueryKeys.list()); + const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([ + "deleteGateway", + "editDetails" + ] as const); + + const deleteGatewayById = useDeleteGatewayById(); + + const handleDeleteGateway = async () => { + await deleteGatewayById.mutateAsync((popUp.deleteGateway.data as { id: string }).id, { + onSuccess: () => { + handlePopUpToggle("deleteGateway"); + createNotification({ + type: "success", + text: "Successfully delete gateway" + }); + } + }); + }; + const filteredGateway = gateways?.filter((el) => el.name.toLowerCase().includes(search.toLowerCase()) ); @@ -100,13 +137,70 @@ export const GatewayListPage = withPermission( {filteredGateway?.map((el) => ( {el.name} - {format(new Date(el.issuedAt), "yyyy-MM-dd")} + {format(new Date(el.issuedAt), "yyyy-MM-dd hh:mm:ss aaa")} {el.identity.name} - + + + + + + + + + + + {(isAllowed: boolean) => ( + } + onClick={() => handlePopUpOpen("editDetails", el)} + > + Edit Details + + )} + + + {(isAllowed: boolean) => ( + } + className="text-red" + onClick={() => handlePopUpOpen("deleteGateway", el)} + > + Delete Gateway + + )} + + + + + ))} + handlePopUpToggle("editDetails", isOpen)} + > + + handlePopUpToggle("editDetails")} + /> + + {!isGatewayLoading && !filteredGateway?.length && ( )} + handlePopUpToggle("deleteGateway", isOpen)} + deleteKey="confirm" + onDeleteApproved={() => handleDeleteGateway()} + /> diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/components/EditGatewayDetailsModal.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/components/EditGatewayDetailsModal.tsx new file mode 100644 index 000000000..1e07036ba --- /dev/null +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/components/EditGatewayDetailsModal.tsx @@ -0,0 +1,75 @@ +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 { 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; + +export const EditGatewayDetailsModal = ({ gatewayDetails, onClose }: Props) => { + const { + control, + handleSubmit, + formState: { isSubmitting } + } = useForm({ + 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 ( +
+ ( + + + + )} + /> +
+ + +
+ + ); +}; diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx index 9f66e358a..de9fbde80 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx @@ -14,6 +14,7 @@ import { TFormSchema } from "../OrgRoleModifySection.utils"; import { OrgPermissionAdminConsoleRow } from "./OrgPermissionAdminConsoleRow"; +import { OrgGatewayPermissionRow } from "./OrgPermissionGatewayRow"; import { OrgPermissionKmipRow } from "./OrgPermissionKmipRow"; import { OrgRoleWorkspaceRow } from "./OrgRoleWorkspaceRow"; import { RolePermissionRow } from "./RolePermissionRow"; @@ -171,6 +172,11 @@ export const RolePermissionsSection = ({ roleId }: Props) => { setValue={setValue} isEditable={isCustomRole} /> + { const valMs = ms(val); @@ -124,6 +127,8 @@ export const SqlDatabaseInputForm = ({ secretPath, projectSlug }: Props) => { + const { currentWorkspace } = useWorkspace(); + const { control, setValue, @@ -137,6 +142,9 @@ export const SqlDatabaseInputForm = ({ }); const createDynamicSecret = useCreateDynamicSecret(); + const { data: projectGateways, isPending: isProjectGatewaysLoading } = useQuery( + gatewaysQueryKeys.list({ projectId: currentWorkspace.id }) + ); const handleCreateDynamicSecret = async ({ name, maxTTL, provider, defaultTTL }: TForm) => { // wait till previous request is finished @@ -222,6 +230,36 @@ export const SqlDatabaseInputForm = ({ /> +
+ ( + + + + )} + /> +
Configuration diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx index 18543502f..165b94314 100644 --- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx +++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx @@ -1,5 +1,6 @@ import { Controller, useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; +import { useQuery } from "@tanstack/react-query"; import ms from "ms"; import { z } from "zod"; @@ -18,7 +19,8 @@ import { SelectItem, TextArea } from "@app/components/v2"; -import { useUpdateDynamicSecret } from "@app/hooks/api"; +import { useWorkspace } from "@app/context"; +import { gatewaysQueryKeys, useUpdateDynamicSecret } from "@app/hooks/api"; import { SqlProviders, TDynamicSecret } from "@app/hooks/api/dynamicSecret/types"; const formSchema = z.object({ @@ -33,7 +35,8 @@ const formSchema = z.object({ creationStatement: z.string().min(1), revocationStatement: z.string().min(1), renewStatement: z.string().optional(), - ca: z.string().optional() + ca: z.string().optional(), + gatewayId: z.string().optional() }) .partial(), defaultTTL: z.string().superRefine((val, ctx) => { @@ -81,6 +84,7 @@ export const EditDynamicSecretSqlProviderForm = ({ }: Props) => { const { control, + watch, formState: { isSubmitting }, handleSubmit } = useForm({ @@ -94,8 +98,14 @@ export const EditDynamicSecretSqlProviderForm = ({ } } }); + const { currentWorkspace } = useWorkspace(); + const { data: projectGateways, isPending: isProjectGatewaysLoading } = useQuery( + gatewaysQueryKeys.list({ projectId: currentWorkspace.id }) + ); const updateDynamicSecret = useUpdateDynamicSecret(); + const selectedGatewayId = watch("inputs.gatewayId"); + const isGatewayInActive = projectGateways?.findIndex((el) => el.id === selectedGatewayId) === -1; const handleUpdateDynamicSecret = async ({ inputs, maxTTL, defaultTTL, newName }: TForm) => { // wait till previous request is finished @@ -109,7 +119,7 @@ export const EditDynamicSecretSqlProviderForm = ({ data: { maxTTL: maxTTL || undefined, defaultTTL, - inputs, + inputs: { ...inputs, gatewayId: isGatewayInActive ? null : inputs.gatewayId }, newName: newName === dynamicSecret.name ? undefined : newName } }); @@ -176,6 +186,39 @@ export const EditDynamicSecretSqlProviderForm = ({ />
+
+ ( + + + + )} + /> +
Configuration
From f7406ea8f89156c8963ba3318fa54c81f48e86b9 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 20 Feb 2025 23:37:19 +0530 Subject: [PATCH 11/30] feat: review feedback, and more changes in cli --- .../20250212191958_create-gateway.ts | 1 + backend/src/db/schemas/gateways.ts | 1 + backend/src/ee/routes/v1/gateway-router.ts | 25 ++- .../ee/services/gateway/gateway-service.ts | 72 ++++++- .../src/ee/services/gateway/gateway-types.ts | 4 + .../ee/services/permission/org-permission.ts | 22 ++- backend/src/keystore/keystore.ts | 2 +- backend/src/lib/gateway/index.ts | 6 +- cli/packages/api/api.go | 17 ++ cli/packages/cmd/gateway.go | 61 ++++-- cli/packages/gateway/connection.go | 4 +- cli/packages/gateway/gateway.go | 187 ++++++++++++++---- frontend/src/hooks/api/gateways/types.ts | 1 + .../GatewayListPage/GatewayListPage.tsx | 7 +- .../components/OrgRoleModifySection.utils.ts | 2 +- .../OrgPermissionGatewayRow.tsx | 6 +- 16 files changed, 336 insertions(+), 82 deletions(-) diff --git a/backend/src/db/migrations/20250212191958_create-gateway.ts b/backend/src/db/migrations/20250212191958_create-gateway.ts index 87f58bc78..b91fc116c 100644 --- a/backend/src/db/migrations/20250212191958_create-gateway.ts +++ b/backend/src/db/migrations/20250212191958_create-gateway.ts @@ -52,6 +52,7 @@ export async function up(knex: Knex): Promise { t.string("keyAlgorithm").notNullable(); t.datetime("issuedAt").notNullable(); t.datetime("expiration").notNullable(); + t.datetime("heartbeat"); t.binary("relayAddress").notNullable(); diff --git a/backend/src/db/schemas/gateways.ts b/backend/src/db/schemas/gateways.ts index 7dc29fdb5..30f5f25e0 100644 --- a/backend/src/db/schemas/gateways.ts +++ b/backend/src/db/schemas/gateways.ts @@ -16,6 +16,7 @@ export const GatewaysSchema = z.object({ keyAlgorithm: z.string(), issuedAt: z.date(), expiration: z.date(), + heartbeat: z.date().nullable().optional(), relayAddress: zodBuffer, orgGatewayRootCaId: z.string().uuid(), identityId: z.string().uuid(), diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts index 332997619..bd2ac2739 100644 --- a/backend/src/ee/routes/v1/gateway-router.ts +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -13,7 +13,8 @@ const SanitizedGatewaySchema = GatewaysSchema.pick({ createdAt: true, updatedAt: true, issuedAt: true, - serialNumber: true + serialNumber: true, + heartbeat: true }); export const registerGatewayRouter = async (server: FastifyZodProvider) => { @@ -76,6 +77,28 @@ 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: "/", diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index e3d07041e..560adc444 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -8,6 +8,7 @@ import { ActionProjectType } from "@app/db/schemas"; import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore"; import { getConfig } from "@app/lib/config/env"; import { BadRequestError, NotFoundError } from "@app/lib/errors"; +import { pingGatewayAndVerify } from "@app/lib/gateway"; import { alphaNumericNanoId } from "@app/lib/nanoid"; import { getTurnCredentials } from "@app/lib/turn/credentials"; import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type"; @@ -20,7 +21,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service"; import { KmsDataKey } from "@app/services/kms/kms-types"; import { TLicenseServiceFactory } from "../license/license-service"; -import { OrgGatewayPermissionActions, OrgPermissionSubjects } from "../permission/org-permission"; +import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission"; import { TPermissionServiceFactory } from "../permission/permission-service"; import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission"; import { TGatewayDALFactory } from "./gateway-dal"; @@ -28,6 +29,7 @@ import { TExchangeAllocatedRelayAddressDTO, TGetGatewayByIdDTO, TGetProjectGatewayByIdDTO, + THeartBeatDTO, TListGatewaysDTO, TUpdateGatewayByIdDTO } from "./gateway-types"; @@ -77,7 +79,7 @@ export const gatewayServiceFactory = ({ actorAuthMethod, orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); }; const getGatewayRelayDetails = async (actorId: string, actorOrgId: string, actorAuthMethod: ActorAuthMethod) => { @@ -412,6 +414,61 @@ export const gatewayServiceFactory = ({ }; }; + 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 + .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, + 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( orgPermission.type, @@ -420,7 +477,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); if (!orgGatewayConfig) return []; @@ -438,7 +495,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); @@ -455,7 +512,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Edit, OrgPermissionSubjects.Gateway); const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); @@ -472,7 +529,7 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Delete, OrgPermissionSubjects.Gateway); const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); if (!orgGatewayConfig) throw new NotFoundError({ message: `Gateway with ID ${id} not found.` }); @@ -553,6 +610,7 @@ export const gatewayServiceFactory = ({ updateGatewayById, deleteGatewayById, getProjectGateways, - fnGetGatewayClientTls + fnGetGatewayClientTls, + heartbeat }; }; diff --git a/backend/src/ee/services/gateway/gateway-types.ts b/backend/src/ee/services/gateway/gateway-types.ts index 666f65e6b..823028154 100644 --- a/backend/src/ee/services/gateway/gateway-types.ts +++ b/backend/src/ee/services/gateway/gateway-types.ts @@ -32,3 +32,7 @@ export type TGetProjectGatewayByIdDTO = { projectId: string; projectPermission: OrgServiceActor; }; + +export type THeartBeatDTO = { + orgPermission: OrgServiceActor; +}; diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts index efed6a1b2..696df74ff 100644 --- a/backend/src/ee/services/permission/org-permission.ts +++ b/backend/src/ee/services/permission/org-permission.ts @@ -32,7 +32,7 @@ export enum OrgPermissionAdminConsoleAction { AccessAllProjects = "access-all-projects" } -export enum OrgGatewayPermissionActions { +export enum OrgPermissionGatewayActions { // is there a better word for this. This mean can an identity be a gateway Create = "create", Read = "read", @@ -82,7 +82,7 @@ export type OrgPermissionSet = | [OrgPermissionActions, OrgPermissionSubjects.Kms] | [OrgPermissionActions, OrgPermissionSubjects.AuditLogs] | [OrgPermissionActions, OrgPermissionSubjects.ProjectTemplates] - | [OrgGatewayPermissionActions, OrgPermissionSubjects.Gateway] + | [OrgPermissionGatewayActions, OrgPermissionSubjects.Gateway] | [ OrgPermissionAppConnectionActions, ( @@ -190,6 +190,12 @@ export const OrgPermissionSchema = z.discriminatedUnion("subject", [ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionKmipActions).describe( "Describe what action an entity can take." ) + }), + z.object({ + subject: z.literal(OrgPermissionSubjects.Gateway).describe("The entity this permission pertains to."), + action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionGatewayActions).describe( + "Describe what action an entity can take." + ) }) ]); @@ -274,10 +280,10 @@ const buildAdminPermission = () => { can(OrgPermissionAppConnectionActions.Delete, OrgPermissionSubjects.AppConnections); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); - can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); - can(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); - can(OrgGatewayPermissionActions.Edit, OrgPermissionSubjects.Gateway); - can(OrgGatewayPermissionActions.Delete, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Edit, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Delete, OrgPermissionSubjects.Gateway); can(OrgPermissionAdminConsoleAction.AccessAllProjects, OrgPermissionSubjects.AdminConsole); @@ -315,8 +321,8 @@ const buildMemberPermission = () => { can(OrgPermissionActions.Read, OrgPermissionSubjects.AuditLogs); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); - can(OrgGatewayPermissionActions.Read, OrgPermissionSubjects.Gateway); - can(OrgGatewayPermissionActions.Create, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); return rules; }; diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts index 04d31fc1a..8ff07db26 100644 --- a/backend/src/keystore/keystore.ts +++ b/backend/src/keystore/keystore.ts @@ -37,7 +37,7 @@ export const KeyStorePrefixes = { IdentityAccessTokenStatusUpdate: (identityAccessTokenId: string) => `identity-access-token-status:${identityAccessTokenId}`, ServiceTokenStatusUpdate: (serviceTokenId: string) => `service-token-status:${serviceTokenId}`, - GatewayIdentityCredential: (identityId: string) => `gateway-credentails:${identityId}` + GatewayIdentityCredential: (identityId: string) => `gateway-credentials:${identityId}` }; export const KeyStoreTtls = { diff --git a/backend/src/lib/gateway/index.ts b/backend/src/lib/gateway/index.ts index b4963cdff..d483b963e 100644 --- a/backend/src/lib/gateway/index.ts +++ b/backend/src/lib/gateway/index.ts @@ -36,12 +36,12 @@ type TPingGatewayAndVerifyDTO = { relayHost: string; relayPort: number; tlsOptions: tls.TlsOptions; - maxRetries: number; + maxRetries?: number; identityId: string; orgId: string; }; -const pingGatewayAndVerifyIdentity = async ({ +export const pingGatewayAndVerify = async ({ relayHost, relayPort, tlsOptions = {}, @@ -236,7 +236,7 @@ export const withGatewayProxy = async ( } = options; // First, try to ping the gateway - await pingGatewayAndVerifyIdentity({ + await pingGatewayAndVerify({ relayHost, relayPort, tlsOptions, diff --git a/cli/packages/api/api.go b/cli/packages/api/api.go index 7b13c6e02..454257405 100644 --- a/cli/packages/api/api.go +++ b/cli/packages/api/api.go @@ -583,3 +583,20 @@ func CallExchangeRelayCertV1(httpClient *resty.Client, request ExchangeRelayCert return &resBody, nil } + +func CallGatewayHeartBeatV1(httpClient *resty.Client) error { + response, err := httpClient. + R(). + SetHeader("User-Agent", USER_AGENT). + Post(fmt.Sprintf("%v/v1/gateways/heartbeat", config.INFISICAL_URL)) + + if err != nil { + return fmt.Errorf("CallGatewayHeartBeatV1: Unable to complete api request [err=%w]", err) + } + + if response.IsError() { + return fmt.Errorf("CallGatewayHeartBeatV1: Unsuccessful response [%v %v] [status-code=%v] [response=%v]", response.Request.Method, response.Request.URL, response.StatusCode(), response.String()) + } + + return nil +} diff --git a/cli/packages/cmd/gateway.go b/cli/packages/cmd/gateway.go index 945340b22..497200647 100644 --- a/cli/packages/cmd/gateway.go +++ b/cli/packages/cmd/gateway.go @@ -5,10 +5,17 @@ import ( // "github.com/Infisical/infisical-merge/packages/api" // "github.com/Infisical/infisical-merge/packages/models" + "context" "fmt" + "os" + "os/signal" + "syscall" + "time" "github.com/Infisical/infisical-merge/packages/gateway" "github.com/Infisical/infisical-merge/packages/util" + "github.com/rs/zerolog/log" + // "github.com/Infisical/infisical-merge/packages/visualize" // "github.com/rs/zerolog/log" @@ -33,20 +40,48 @@ var gatewayCmd = &cobra.Command{ util.HandleError(fmt.Errorf("Token not found")) } - gatewayInstance, err := gateway.NewGateway(token.Token) - if err != nil { - util.HandleError(err) - } - - if err = gatewayInstance.ConnectWithRelay(); err != nil { - util.HandleError(err) - } - - if err := gatewayInstance.Listen(); err != nil { - util.HandleError(err) - } - Telemetry.CaptureEvent("cli-command:gateway", posthog.NewProperties().Set("version", util.CLI_VERSION)) + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) + sigStopCh := make(chan bool, 1) + + go func() { + <-sigCh + close(sigStopCh) + }() + + ctx, cancel := context.WithCancel(cmd.Context()) + defer cancel() + + for { + select { + case <-sigStopCh: + log.Info().Msg("Shutting down gateway") + return + default: + gatewayInstance, err := gateway.NewGateway(token.Token) + if err != nil { + util.HandleError(err) + } + + if err = gatewayInstance.ConnectWithRelay(); err != nil { + log.Error().Msgf("Gateway connection error with relay: %s", err) + log.Info().Msg("Restarting gateway...") + time.Sleep(5 * time.Second) + continue + } + + if err := gatewayInstance.Listen(ctx); err == nil { + // meaning everything went smooth and we are exiting + return + } + + log.Error().Msgf("Gateway listen error: %s", err) + log.Info().Msg("Restarting gateway...") + time.Sleep(5 * time.Second) + } + } }, } diff --git a/cli/packages/gateway/connection.go b/cli/packages/gateway/connection.go index bd91f1f61..c29804506 100644 --- a/cli/packages/gateway/connection.go +++ b/cli/packages/gateway/connection.go @@ -59,7 +59,9 @@ func handleConnection(conn net.Conn) { CopyData(conn, destTarget) return case "PING": - conn.Write([]byte("PONG")) + if _, err := conn.Write([]byte("PONG")); err != nil { + log.Error().Msgf("Error writing PONG response: %v", err) + } return default: log.Error().Msgf("Unknown command: %s", string(cmd)) diff --git a/cli/packages/gateway/gateway.go b/cli/packages/gateway/gateway.go index 766af9795..cfa4fe24a 100644 --- a/cli/packages/gateway/gateway.go +++ b/cli/packages/gateway/gateway.go @@ -1,11 +1,13 @@ package gateway import ( + "context" "crypto/tls" "crypto/x509" "fmt" "net" "strings" + "sync" "time" "github.com/Infisical/infisical-merge/packages/api" @@ -91,12 +93,13 @@ func (g *Gateway) ConnectWithRelay() error { return nil } -func (g *Gateway) Listen() error { +func (g *Gateway) Listen(ctx context.Context) error { defer g.client.Close() err := g.client.Listen() if err != nil { return fmt.Errorf("Failed to listen to relay server: %w", err) } + log.Info().Msg("Connected with relay") // Allocate a relay socket on the TURN server. On success, it // will return a net.PacketConn which represents the remote @@ -106,6 +109,7 @@ func (g *Gateway) Listen() error { return fmt.Errorf("Failed to allocate relay connection: %w", err) } + log.Info().Msg(relayNonTlsConn.Addr().String()) defer func() { if closeErr := relayNonTlsConn.Close(); closeErr != nil { log.Error().Msgf("Failed to close connection: %s", closeErr) @@ -128,20 +132,12 @@ func (g *Gateway) Listen() error { g.config.Certificate = gatewayCert.Certificate g.config.CertificateChain = gatewayCert.CertificateChain - go func() { + done := make(chan bool, 1) + + g.registerPermissionLifecycle(func() error { err := relayNonTlsConn.CreatePermissions(peerAddr) - if err != nil { - log.Error().Msgf("Failed to refresh permission: %s", err) - } - log.Printf("Created permission for incoming connections") - ticker := time.NewTicker(2 * time.Minute) // Refresh before 5-min expiry - for range ticker.C { - err := relayNonTlsConn.CreatePermissions(peerAddr) - if err != nil { - log.Error().Msgf("Failed to refresh permission: %s", err) - } - } - }() + return err + }, done) cert, err := tls.X509KeyPair([]byte(gatewayCert.Certificate), []byte(gatewayCert.PrivateKey)) if err != nil { @@ -158,41 +154,146 @@ func (g *Gateway) Listen() error { ClientAuth: tls.RequireAndVerifyClientCert, }) + errCh := make(chan error, 1) log.Info().Msg("Connector started successfully") - for { - // Accept new relay connection - conn, err := relayConn.Accept() - if err != nil { - log.Error().Msgf("Failed to accept connection: %v", err) - continue - } + g.registerHeartBeat(errCh, done) + g.registerRelayIsActive(relayNonTlsConn.Addr().String(), errCh, done) - tlsConn, ok := conn.(*tls.Conn) - if !ok { - log.Error().Msg("Failed to convert to TLS connection") - conn.Close() - continue - } + // Create a WaitGroup to track active connections + var wg sync.WaitGroup - err = tlsConn.Handshake() - if err != nil { - log.Error().Msgf("TLS handshake failed: %v", err) - conn.Close() - continue - } + go func() { + for { + select { + case <-done: + return + default: + // Accept new relay connection + conn, err := relayConn.Accept() + if err != nil { + if !strings.Contains(err.Error(), "data contains incomplete STUN or TURN frame") { + log.Error().Msgf("Failed to accept connection: %v", err) + } + continue + } - // Get connection state which contains certificate information - state := tlsConn.ConnectionState() - if len(state.PeerCertificates) > 0 { - organizationUnit := state.PeerCertificates[0].Subject.OrganizationalUnit - commonName := state.PeerCertificates[0].Subject.CommonName - if organizationUnit[0] != "gateway-client" && commonName != "cloud" { - log.Error().Msgf("Client certificate verification failed. Received %s, %s", organizationUnit, commonName) - continue + tlsConn, ok := conn.(*tls.Conn) + if !ok { + log.Error().Msg("Failed to convert to TLS connection") + conn.Close() + continue + } + + err = tlsConn.Handshake() + if err != nil { + log.Error().Msgf("TLS handshake failed: %v", err) + conn.Close() + continue + } + + // Get connection state which contains certificate information + state := tlsConn.ConnectionState() + if len(state.PeerCertificates) > 0 { + organizationUnit := state.PeerCertificates[0].Subject.OrganizationalUnit + commonName := state.PeerCertificates[0].Subject.CommonName + if organizationUnit[0] != "gateway-client" && commonName != "cloud" { + log.Error().Msgf("Client certificate verification failed. Received %s, %s", organizationUnit, commonName) + continue + } + } + + // Handle the connection in a goroutine + wg.Add(1) + go func() { + defer wg.Done() + handleConnection(conn) + }() } } + }() - // Handle the connection in a goroutine - go handleConnection(conn) + var isShutdown bool + select { + case <-ctx.Done(): + log.Info().Msg("Shutting down gateway...") + isShutdown = true + case err = <-errCh: } + + // Signal the accept loop to stop + close(done) + wg.Wait() + + if isShutdown { + log.Info().Msg("Gateway shutdown complete") + } + + return err +} + +func (g *Gateway) registerHeartBeat(errCh chan error, done chan bool) { + ticker := time.NewTicker(1 * time.Hour) + + go func() { + // wait for 5 mins + time.Sleep(5 * time.Second) + err := api.CallGatewayHeartBeatV1(g.httpClient) + if err != nil { + log.Error().Msgf("Failed to register heartbeat: %s", err) + } + + for { + select { + case <-done: + ticker.Stop() + return + case <-ticker.C: + err := api.CallGatewayHeartBeatV1(g.httpClient) + errCh <- err + } + } + }() +} + +func (g *Gateway) registerPermissionLifecycle(permissionFn func() error, done chan bool) { + ticker := time.NewTicker(3 * time.Minute) + + go func() { + // wait for 5 mins + permissionFn() + log.Printf("Ceated permission for incoming connections") + for { + select { + case <-done: + ticker.Stop() + return + case <-ticker.C: + permissionFn() + } + } + }() +} + +func (g *Gateway) registerRelayIsActive(serverAddr string, errCh chan error, done chan bool) { + ticker := time.NewTicker(10 * time.Second) + + go func() { + time.Sleep(5 * time.Second) + for { + select { + case <-done: + ticker.Stop() + return + case <-ticker.C: + conn, err := net.Dial("tcp", serverAddr) + if err != nil { + errCh <- err + return + } + if conn != nil { + conn.Close() + } + } + } + }() } diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts index 9d7917ef4..3c0971079 100644 --- a/frontend/src/hooks/api/gateways/types.ts +++ b/frontend/src/hooks/api/gateways/types.ts @@ -6,6 +6,7 @@ export type TGateway = { updatedAt: string; issuedAt: string; serialNumber: string; + heartbeart: string; identity: { name: string; id: string; diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx index d252f259a..9c9302b49 100644 --- a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx @@ -12,7 +12,7 @@ import { } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { useQuery } from "@tanstack/react-query"; -import { format } from "date-fns"; +import { format, formatRelative } from "date-fns"; import { createNotification } from "@app/components/notifications"; import { OrgPermissionCan } from "@app/components/permissions"; @@ -139,6 +139,11 @@ export const GatewayListPage = withPermission( {el.name} {format(new Date(el.issuedAt), "yyyy-MM-dd hh:mm:ss aaa")} {el.identity.name} + + {el.heartbeart + ? formatRelative(new Date(), new Date(el.heartbeart)) + : "-"} + diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts index 985bbbddd..4b3393fa8 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts +++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts @@ -83,7 +83,7 @@ export const formSchema = z.object({ [OrgPermissionSubjects.ProjectTemplates]: generalPermissionSchema, "app-connections": appConnectionsPermissionSchema, kmip: kmipPermissionSchema, - [OrgPermissionSubjects.Gateway]: orgGatewayPermissionSchema + gateway: orgGatewayPermissionSchema }) .optional() }); diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx index efafa6a42..fe160bb31 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx @@ -76,7 +76,7 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props switch (val) { case Permission.FullAccess: setValue( - "permissions.app-connections", + "permissions.gateway", { [OrgGatewayPermissionActions.Read]: true, [OrgGatewayPermissionActions.Edit]: true, @@ -88,7 +88,7 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props break; case Permission.ReadOnly: setValue( - "permissions.app-connections", + "permissions.gateway", { [OrgGatewayPermissionActions.Read]: true, [OrgGatewayPermissionActions.Edit]: false, @@ -102,7 +102,7 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props case Permission.NoAccess: default: setValue( - "permissions.app-connections", + "permissions.gateway", { [OrgGatewayPermissionActions.Read]: false, [OrgGatewayPermissionActions.Edit]: false, From 46ca5c8efa1e2926e8d36c1a479cf5e5639d3580 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 20 Feb 2025 23:54:46 +0530 Subject: [PATCH 12/30] feat: resolved type error from rebase --- backend/src/server/routes/index.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts index 11fa5220e..9b8d1a36a 100644 --- a/backend/src/server/routes/index.ts +++ b/backend/src/server/routes/index.ts @@ -1477,14 +1477,6 @@ export const registerRoutes = async ( permissionService }); - const gatewayService = gatewayServiceFactory({ - permissionService, - gatewayDAL, - kmsService, - licenseService, - orgGatewayConfigDAL - }); - await superAdminService.initServerCfg(); // setup the communication with license key server From 55b1fbdf5287d1ab07d29f5c55d35dcb96a4fc1d Mon Sep 17 00:00:00 2001 From: = Date: Fri, 21 Feb 2025 00:20:52 +0530 Subject: [PATCH 13/30] feat: added validation for relay ip --- backend/src/ee/routes/v1/gateway-router.ts | 7 ++++++- backend/src/ee/services/gateway/gateway-service.ts | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts index bd2ac2739..860e5b66b 100644 --- a/backend/src/ee/routes/v1/gateway-router.ts +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { GatewaysSchema } from "@app/db/schemas"; +import { isValidIp } from "@app/lib/ip"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { slugSchema } from "@app/server/lib/schemas"; import { verifyAuth } from "@app/server/plugins/auth/verify-auth"; @@ -16,6 +17,10 @@ const SanitizedGatewaySchema = GatewaysSchema.pick({ serialNumber: true, heartbeat: true }); +const isValidRelayAddress = (relayAddress: string) => { + const [ip, port] = relayAddress.split(":"); + return isValidIp(ip) && Number(port) <= 65535 && Number(port) >= 49152; +}; export const registerGatewayRouter = async (server: FastifyZodProvider) => { server.route({ @@ -54,7 +59,7 @@ export const registerGatewayRouter = async (server: FastifyZodProvider) => { }, schema: { body: z.object({ - relayAddress: z.string() + relayAddress: z.string().refine(isValidRelayAddress, { message: "Invalid relay address" }) }), response: { 200: z.object({ diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index 560adc444..44f48b574 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -353,7 +353,7 @@ export const gatewayServiceFactory = ({ ), new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true), // san - new x509.SubjectAlternativeNameExtension([{ type: "ip", value: "127.0.0.1" }], false) + new x509.SubjectAlternativeNameExtension([{ type: "ip", value: relayAddress.split(":")[0] }], false) ]; const serialNumber = createSerialNumber(); @@ -374,6 +374,7 @@ export const gatewayServiceFactory = ({ // 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 }); From afd444cad684e20b4c406fc4ed0f2c0e1c3843fe Mon Sep 17 00:00:00 2001 From: = Date: Fri, 21 Feb 2025 14:29:01 +0530 Subject: [PATCH 14/30] feat: permission changes --- .../20250212191958_create-gateway.ts | 5 +- .../ee/services/gateway/gateway-service.ts | 47 ++++++++++++++----- .../src/ee/services/license/license-fns.ts | 4 +- .../ee/services/permission/org-permission.ts | 20 ++++---- .../src/context/OrgPermissionContext/types.ts | 8 ++-- frontend/src/hooks/api/gateways/types.ts | 2 +- .../GatewayListPage/GatewayListPage.tsx | 19 ++++++-- .../components/OrgRoleModifySection.utils.ts | 8 ++-- .../OrgPermissionGatewayRow.tsx | 34 +++++++------- .../SqlDatabaseInputForm.tsx | 8 +++- .../EditDynamicSecretSqlProviderForm.tsx | 9 +++- 11 files changed, 105 insertions(+), 59 deletions(-) diff --git a/backend/src/db/migrations/20250212191958_create-gateway.ts b/backend/src/db/migrations/20250212191958_create-gateway.ts index b91fc116c..3d9f37101 100644 --- a/backend/src/db/migrations/20250212191958_create-gateway.ts +++ b/backend/src/db/migrations/20250212191958_create-gateway.ts @@ -72,7 +72,10 @@ export async function up(knex: Knex): Promise { const doesGatewayColExist = await knex.schema.hasColumn(TableName.DynamicSecret, "gatewayId"); await knex.schema.alterTable(TableName.DynamicSecret, (t) => { // not setting a foreign constraint so that cascade effects are not triggered - if (!doesGatewayColExist) t.uuid("gatewayId"); + if (!doesGatewayColExist) { + t.uuid("gatewayId"); + t.foreign("gatewayId").references("id").inTable(TableName.Identity); + } }); } } diff --git a/backend/src/ee/services/gateway/gateway-service.ts b/backend/src/ee/services/gateway/gateway-service.ts index 44f48b574..d370035e4 100644 --- a/backend/src/ee/services/gateway/gateway-service.ts +++ b/backend/src/ee/services/gateway/gateway-service.ts @@ -79,7 +79,10 @@ export const gatewayServiceFactory = ({ actorAuthMethod, orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan( + OrgPermissionGatewayActions.CreateGateways, + OrgPermissionSubjects.Gateway + ); }; const getGatewayRelayDetails = async (actorId: string, actorOrgId: string, actorAuthMethod: ActorAuthMethod) => { @@ -152,7 +155,7 @@ export const gatewayServiceFactory = ({ const rootCaKeyAlgorithm = CertKeyAlgorithm.RSA_2048; const rootCaExpiration = new Date(new Date().setFullYear(2045)); const rootCaCert = await x509.X509CertificateGenerator.createSelfSigned({ - name: "CN=Infisical Gateway Root CA", + name: `O=${identityOrg},CN=Infisical Gateway Root CA`, serialNumber: rootCaSerialNumber, notBefore: rootCaIssuedAt, notAfter: rootCaExpiration, @@ -174,7 +177,7 @@ export const gatewayServiceFactory = ({ const clientCaCert = await x509.X509CertificateGenerator.create({ serialNumber: clientCaSerialNumber, - subject: "CN=Client Intermediate CA", + subject: `O=${identityOrg},CN=Client Intermediate CA`, issuer: rootCaCert.subject, notBefore: clientCaIssuedAt, notAfter: clientCaExpiration, @@ -227,12 +230,12 @@ export const gatewayServiceFactory = ({ // generate gateway ca const gatewayCaSerialNumber = createSerialNumber(); const gatewayCaIssuedAt = new Date(); - const gatewayCaExpiration = new Date(new Date().setFullYear(new Date().getFullYear() + 10)); + const gatewayCaExpiration = new Date(new Date().setFullYear(2045)); const gatewayCaKeys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]); const gatewayCaSkObj = crypto.KeyObject.from(gatewayCaKeys.privateKey); const gatewayCaCert = await x509.X509CertificateGenerator.create({ serialNumber: gatewayCaSerialNumber, - subject: "CN=KMIP Server Intermediate CA", + subject: `O=${identityOrg},CN=Gateway CA`, issuer: rootCaCert.subject, notBefore: gatewayCaIssuedAt, notAfter: gatewayCaExpiration, @@ -327,6 +330,12 @@ export const gatewayServiceFactory = ({ format: "der", type: "pkcs8" }); + const gatewayCaCert = new x509.X509Certificate( + orgKmsDecryptor({ + cipherTextBlob: orgGatewayConfig.encryptedGatewayCaCertificate + }) + ); + const gatewayCaPrivateKey = await crypto.subtle.importKey( "pkcs8", gatewayCaSkObj.export({ format: "der", type: "pkcs8" }), @@ -343,7 +352,7 @@ export const gatewayServiceFactory = ({ const extensions: x509.Extension[] = [ new x509.BasicConstraintsExtension(false), - await x509.AuthorityKeyIdentifierExtension.create(rootCaCert, 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( @@ -360,8 +369,8 @@ export const gatewayServiceFactory = ({ const privateKey = crypto.KeyObject.from(gatewayKeys.privateKey); const gatewayCertificate = await x509.X509CertificateGenerator.create({ serialNumber, - subject: `CN=${identityId},O=${identityOrg}`, - issuer: rootCaCert.subject, + subject: `CN=${identityId},O=${identityOrg},OU=Gateway`, + issuer: gatewayCaCert.subject, notBefore: certIssuedAt, notAfter: certExpireAt, signingKey: gatewayCaPrivateKey, @@ -401,7 +410,7 @@ export const gatewayServiceFactory = ({ }).cipherTextBlob, identityId, orgGatewayRootCaId: orgGatewayConfig.id, - name: alphaNumericNanoId(8) + name: `gateway-${alphaNumericNanoId(6)}` }); }); @@ -478,7 +487,10 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); + ForbiddenError.from(permission).throwUnlessCan( + OrgPermissionGatewayActions.ListGateways, + OrgPermissionSubjects.Gateway + ); const orgGatewayConfig = await orgGatewayConfigDAL.findOne({ orgId: orgPermission.orgId }); if (!orgGatewayConfig) return []; @@ -496,7 +508,10 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); + 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.` }); @@ -513,7 +528,10 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Edit, OrgPermissionSubjects.Gateway); + 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.` }); @@ -530,7 +548,10 @@ export const gatewayServiceFactory = ({ orgPermission.authMethod, orgPermission.orgId ); - ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.Delete, OrgPermissionSubjects.Gateway); + 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.` }); diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts index 21d378802..85f5cf921 100644 --- a/backend/src/ee/services/license/license-fns.ts +++ b/backend/src/ee/services/license/license-fns.ts @@ -17,7 +17,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ environmentsUsed: 0, identityLimit: null, identitiesUsed: 0, - dynamicSecret: false, + dynamicSecret: true, secretVersioning: true, pitRecovery: false, ipAllowlisting: false, @@ -52,7 +52,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ enforceMfa: false, projectTemplates: false, kmip: false, - gateway: false + gateway: true }); export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => { diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts index 696df74ff..dbabcc2c1 100644 --- a/backend/src/ee/services/permission/org-permission.ts +++ b/backend/src/ee/services/permission/org-permission.ts @@ -34,10 +34,10 @@ export enum OrgPermissionAdminConsoleAction { export enum OrgPermissionGatewayActions { // is there a better word for this. This mean can an identity be a gateway - Create = "create", - Read = "read", - Edit = "edit", - Delete = "delete" + CreateGateways = "create-gateways", + ListGateways = "list-gateways", + EditGateways = "edit-gateways", + DeleteGateways = "delete-gateways" } export enum OrgPermissionSubjects { @@ -280,10 +280,10 @@ const buildAdminPermission = () => { can(OrgPermissionAppConnectionActions.Delete, OrgPermissionSubjects.AppConnections); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); - can(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); - can(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); - can(OrgPermissionGatewayActions.Edit, OrgPermissionSubjects.Gateway); - can(OrgPermissionGatewayActions.Delete, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.ListGateways, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.CreateGateways, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.EditGateways, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.DeleteGateways, OrgPermissionSubjects.Gateway); can(OrgPermissionAdminConsoleAction.AccessAllProjects, OrgPermissionSubjects.AdminConsole); @@ -321,8 +321,8 @@ const buildMemberPermission = () => { can(OrgPermissionActions.Read, OrgPermissionSubjects.AuditLogs); can(OrgPermissionAppConnectionActions.Connect, OrgPermissionSubjects.AppConnections); - can(OrgPermissionGatewayActions.Read, OrgPermissionSubjects.Gateway); - can(OrgPermissionGatewayActions.Create, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.ListGateways, OrgPermissionSubjects.Gateway); + can(OrgPermissionGatewayActions.CreateGateways, OrgPermissionSubjects.Gateway); return rules; }; diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts index 2eb5c19b3..2a31ed6a8 100644 --- a/frontend/src/context/OrgPermissionContext/types.ts +++ b/frontend/src/context/OrgPermissionContext/types.ts @@ -9,10 +9,10 @@ export enum OrgPermissionActions { export enum OrgGatewayPermissionActions { // is there a better word for this. This mean can an identity be a gateway - Create = "create", - Read = "read", - Edit = "edit", - Delete = "delete" + CreateGateways = "create-gateways", + ListGateways = "list-gateways", + EditGateways = "edit-gateways", + DeleteGateways = "delete-gateways" } export enum OrgPermissionSubjects { diff --git a/frontend/src/hooks/api/gateways/types.ts b/frontend/src/hooks/api/gateways/types.ts index 3c0971079..42ce1ebc2 100644 --- a/frontend/src/hooks/api/gateways/types.ts +++ b/frontend/src/hooks/api/gateways/types.ts @@ -6,7 +6,7 @@ export type TGateway = { updatedAt: string; issuedAt: string; serialNumber: string; - heartbeart: string; + heartbeat: string; identity: { name: string; id: string; diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx index 9c9302b49..4a06534b6 100644 --- a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx +++ b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx @@ -5,6 +5,7 @@ import { faBookOpen, faEdit, faEllipsisV, + faInfoCircle, faMagnifyingGlass, faPlug, faSearch, @@ -125,8 +126,18 @@ export const GatewayListPage = withPermission( Name - Issued At + Cert Issued At Identity + + Health Check + + + + @@ -140,8 +151,8 @@ export const GatewayListPage = withPermission( {format(new Date(el.issuedAt), "yyyy-MM-dd hh:mm:ss aaa")} {el.identity.name} - {el.heartbeart - ? formatRelative(new Date(), new Date(el.heartbeart)) + {el.heartbeat + ? formatRelative(new Date(el.heartbeat), new Date()) : "-"} @@ -159,7 +170,7 @@ export const GatewayListPage = withPermission( {(isAllowed: boolean) => ( diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts index 4b3393fa8..42dd31417 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts +++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts @@ -37,10 +37,10 @@ const kmipPermissionSchema = z const orgGatewayPermissionSchema = z .object({ - [OrgGatewayPermissionActions.Read]: z.boolean().optional(), - [OrgGatewayPermissionActions.Edit]: z.boolean().optional(), - [OrgGatewayPermissionActions.Delete]: z.boolean().optional(), - [OrgGatewayPermissionActions.Create]: z.boolean().optional() + [OrgGatewayPermissionActions.ListGateways]: z.boolean().optional(), + [OrgGatewayPermissionActions.EditGateways]: z.boolean().optional(), + [OrgGatewayPermissionActions.DeleteGateways]: z.boolean().optional(), + [OrgGatewayPermissionActions.CreateGateways]: z.boolean().optional() }) .optional(); diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx index fe160bb31..46e88653a 100644 --- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx +++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionGatewayRow.tsx @@ -24,10 +24,10 @@ enum Permission { } const PERMISSION_ACTIONS = [ - { action: OrgGatewayPermissionActions.Read, label: "Read" }, - { action: OrgGatewayPermissionActions.Create, label: "Create" }, - { action: OrgGatewayPermissionActions.Edit, label: "Modify" }, - { action: OrgGatewayPermissionActions.Delete, label: "Remove" } + { action: OrgGatewayPermissionActions.ListGateways, label: "List Gateways" }, + { action: OrgGatewayPermissionActions.CreateGateways, label: "Create Gateways" }, + { action: OrgGatewayPermissionActions.EditGateways, label: "Edit Gateways" }, + { action: OrgGatewayPermissionActions.DeleteGateways, label: "Delete Gateways" } ] as const; export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props) => { @@ -47,7 +47,7 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props if (isCustom) return Permission.Custom; if (score === 0) return Permission.NoAccess; if (score === totalActions) return Permission.FullAccess; - if (score === 1 && rule?.[OrgGatewayPermissionActions.Read]) return Permission.ReadOnly; + if (score === 1 && rule?.[OrgGatewayPermissionActions.ListGateways]) return Permission.ReadOnly; return Permission.Custom; }, [rule, isCustom]); @@ -78,10 +78,10 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props setValue( "permissions.gateway", { - [OrgGatewayPermissionActions.Read]: true, - [OrgGatewayPermissionActions.Edit]: true, - [OrgGatewayPermissionActions.Create]: true, - [OrgGatewayPermissionActions.Delete]: true + [OrgGatewayPermissionActions.ListGateways]: true, + [OrgGatewayPermissionActions.EditGateways]: true, + [OrgGatewayPermissionActions.CreateGateways]: true, + [OrgGatewayPermissionActions.DeleteGateways]: true }, { shouldDirty: true } ); @@ -90,10 +90,10 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props setValue( "permissions.gateway", { - [OrgGatewayPermissionActions.Read]: true, - [OrgGatewayPermissionActions.Edit]: false, - [OrgGatewayPermissionActions.Create]: false, - [OrgGatewayPermissionActions.Delete]: false + [OrgGatewayPermissionActions.ListGateways]: true, + [OrgGatewayPermissionActions.EditGateways]: false, + [OrgGatewayPermissionActions.CreateGateways]: false, + [OrgGatewayPermissionActions.DeleteGateways]: false }, { shouldDirty: true } ); @@ -104,10 +104,10 @@ export const OrgGatewayPermissionRow = ({ isEditable, control, setValue }: Props setValue( "permissions.gateway", { - [OrgGatewayPermissionActions.Read]: false, - [OrgGatewayPermissionActions.Edit]: false, - [OrgGatewayPermissionActions.Create]: false, - [OrgGatewayPermissionActions.Delete]: false + [OrgGatewayPermissionActions.ListGateways]: false, + [OrgGatewayPermissionActions.EditGateways]: false, + [OrgGatewayPermissionActions.CreateGateways]: false, + [OrgGatewayPermissionActions.DeleteGateways]: false }, { shouldDirty: true } ); diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx index 7c877e150..68c16eee6 100644 --- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx +++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx @@ -247,9 +247,15 @@ export const SqlDatabaseInputForm = ({ className="w-full border border-mineshaft-500" dropdownContainerClassName="max-w-none" isLoading={isProjectGatewaysLoading} - placeholder="Select gateway" + placeholder="Internet gateway" position="popper" > + onChange(undefined)} + > + Internet Gateway + {projectGateways?.map((el) => ( {el.name} diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx index 165b94314..572f7832e 100644 --- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx +++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSqlProviderForm.tsx @@ -195,7 +195,9 @@ export const EditDynamicSecretSqlProviderForm = ({ + onChange(undefined)}> + Internet Gateway + {projectGateways?.map((el) => ( {el.name} From 17e576511b163c48a08c3d1ad5b3f7965a47723f Mon Sep 17 00:00:00 2001 From: = Date: Fri, 21 Feb 2025 16:45:18 +0530 Subject: [PATCH 15/30] feat: updated backend --- backend/src/ee/routes/v1/gateway-router.ts | 2 +- backend/src/ee/services/license/license-fns.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/src/ee/routes/v1/gateway-router.ts b/backend/src/ee/routes/v1/gateway-router.ts index 860e5b66b..edb887e2d 100644 --- a/backend/src/ee/routes/v1/gateway-router.ts +++ b/backend/src/ee/routes/v1/gateway-router.ts @@ -19,7 +19,7 @@ const SanitizedGatewaySchema = GatewaysSchema.pick({ }); const isValidRelayAddress = (relayAddress: string) => { const [ip, port] = relayAddress.split(":"); - return isValidIp(ip) && Number(port) <= 65535 && Number(port) >= 49152; + return isValidIp(ip) && Number(port) <= 65535 && Number(port) >= 40000; }; export const registerGatewayRouter = async (server: FastifyZodProvider) => { diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts index 85f5cf921..21d378802 100644 --- a/backend/src/ee/services/license/license-fns.ts +++ b/backend/src/ee/services/license/license-fns.ts @@ -17,7 +17,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ environmentsUsed: 0, identityLimit: null, identitiesUsed: 0, - dynamicSecret: true, + dynamicSecret: false, secretVersioning: true, pitRecovery: false, ipAllowlisting: false, @@ -52,7 +52,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({ enforceMfa: false, projectTemplates: false, kmip: false, - gateway: true + gateway: false }); export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => { From 9b44972e7794b6416b1a0521165ef5680ce73ef3 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 21 Feb 2025 16:45:35 +0530 Subject: [PATCH 16/30] feat: added better message on heartbeat --- cli/packages/cmd/gateway.go | 7 ++++--- cli/packages/gateway/gateway.go | 7 ++++--- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/cli/packages/cmd/gateway.go b/cli/packages/cmd/gateway.go index 497200647..fc45080ac 100644 --- a/cli/packages/cmd/gateway.go +++ b/cli/packages/cmd/gateway.go @@ -46,14 +46,15 @@ var gatewayCmd = &cobra.Command{ signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) sigStopCh := make(chan bool, 1) + ctx, cancel := context.WithCancel(cmd.Context()) + defer cancel() + go func() { <-sigCh close(sigStopCh) + cancel() }() - ctx, cancel := context.WithCancel(cmd.Context()) - defer cancel() - for { select { case <-sigStopCh: diff --git a/cli/packages/gateway/gateway.go b/cli/packages/gateway/gateway.go index cfa4fe24a..a8de875be 100644 --- a/cli/packages/gateway/gateway.go +++ b/cli/packages/gateway/gateway.go @@ -155,7 +155,7 @@ func (g *Gateway) Listen(ctx context.Context) error { }) errCh := make(chan error, 1) - log.Info().Msg("Connector started successfully") + log.Info().Msg("Gateway started successfully") g.registerHeartBeat(errCh, done) g.registerRelayIsActive(relayNonTlsConn.Addr().String(), errCh, done) @@ -235,8 +235,8 @@ func (g *Gateway) registerHeartBeat(errCh chan error, done chan bool) { ticker := time.NewTicker(1 * time.Hour) go func() { - // wait for 5 mins - time.Sleep(5 * time.Second) + time.Sleep(10 * time.Second) + log.Info().Msg("Registering first heart beat") err := api.CallGatewayHeartBeatV1(g.httpClient) if err != nil { log.Error().Msgf("Failed to register heartbeat: %s", err) @@ -248,6 +248,7 @@ func (g *Gateway) registerHeartBeat(errCh chan error, done chan bool) { ticker.Stop() return case <-ticker.C: + log.Info().Msg("Registering heart beat") err := api.CallGatewayHeartBeatV1(g.httpClient) errCh <- err } From 929a41065c44da8980fd1819097abe3544d064c9 Mon Sep 17 00:00:00 2001 From: = Date: Fri, 21 Feb 2025 16:45:43 +0530 Subject: [PATCH 17/30] feat: first doc for gateway --- .../platform/gateways/overview.mdx | 79 ++++++++++++++++++ .../gateways/create-identity-for-gateway.png | Bin 0 -> 383861 bytes .../platform/gateways/dynamic-secret.png | Bin 0 -> 393478 bytes .../images/platform/gateways/gateway-list.png | Bin 0 -> 443518 bytes docs/mint.json | 4 + 5 files changed, 83 insertions(+) create mode 100644 docs/documentation/platform/gateways/overview.mdx create mode 100644 docs/images/platform/gateways/create-identity-for-gateway.png create mode 100644 docs/images/platform/gateways/dynamic-secret.png create mode 100644 docs/images/platform/gateways/gateway-list.png diff --git a/docs/documentation/platform/gateways/overview.mdx b/docs/documentation/platform/gateways/overview.mdx new file mode 100644 index 000000000..304fb87db --- /dev/null +++ b/docs/documentation/platform/gateways/overview.mdx @@ -0,0 +1,79 @@ +--- +title: "Gateway" +sidebarTitle: "Overview" +description: "Learn how to provide access on private resources to Infisical." +--- + + + Note that Gateway is a paid feature. + + If you're using Infisical Cloud, then it is available under the **Enterprise Tier** + If you're self-hosting Infisical, then you should contact sales@infisical.com to purchase an enterprise license to use it. + + + +## Introduction + +Gateway is Infisical's solution for providing secure access to your private resources without exposing them to the internet. + +By "without exposing," we mean that your resources remain completely closed to inbound connections - no SSH ports, no TCP ports are open. +This level of security ensures that even port scanning cannot detect your resources. + +## How It Works + +A gateway is a simple server that acts as a bridge for direct communication between the Infisical server and your private, closed resources (such as databases). + +When deployed, the gateway establishes a connection with the relay server. Infisical then communicates with your gateway through these relays. +All communication between Infisical and the gateway is end-to-end encrypted, ensuring that only the platform and your gateway can decrypt the transmitted information. + +## Deployment + +You can easily deploy a gateway using the Infisical CLI by following these steps: + + + + 1. Navigate to your **Organization Access Control**. + 2. Create a dedicated identity for the gateway. + 3. Best practice: Use one unique identity per gateway. + ![create-gateway](../../../images/platform/gateways/create-identity-for-gateway.png) + + + + Set up authentication by following the [Identity Auth Method Configuration](../identities/universal-auth) guide. + + + + 1. Deploy the gateway using Infisical CLI with this command: + ```bash + INFISICAL_TOKEN=$(infisical login ...) infisical gateway + ``` + + Verify that the deployed gateway has access to your private resources + + + + + 1. Check the gateway log to have **Gateway started successfully** + + 2. Navigate to **Gateways** list page in Org Access Control + ![list-gateway](../../../images/platform/gateways/gateway-list.png) + + + +## Using Your Gateway + +### Configuring Dynamic Secrets + +To use your gateway with dynamic secrets: + +1. Navigate to your dynamic secret provider settings +2. Under **Gateway** options, switch from **Internet Gateway** to your deployed gateway + ![dynamic-secret-gateway](../../../images/platform/gateways/dynamic-secret.png) + +### Supported Providers + +Currently, gateways are supported for the following dynamic secret providers: + +- SQL Database Providers (MySQL, PostgreSQL, etc.) + +Additional provider support will be added in future updates. diff --git a/docs/images/platform/gateways/create-identity-for-gateway.png b/docs/images/platform/gateways/create-identity-for-gateway.png new file mode 100644 index 0000000000000000000000000000000000000000..d7ef6b02aee9177ccabaf38a099bfc866df82539 GIT binary patch literal 383861 zcmbTec|26_`#(NJge;Y0Czb57??kAq#TfgNeV1+QLy^i>*^)IS%rLf)eJf;5jBOZX zANw+vVP<}(_wxCCzW@9luj28TIdkTobKmE>uKQY_*Lh*6uYI0|jRph)oxgYY&O_iW z5(J`3q&^FrIi&KF0N%*_9%`$DkOLg6zz0J|(|b;OdLTjIm>NV*b^&ze_YmM86zdA2 z_}4KAbOU$?fzITS{qMJVn%r(cg|I$kW5iPa#P8>c2)P0LQ;ii(TdU*ARbq<*TN8hCCYH zzK%RHqT-_BS5;_uczBe29h?*%-qHHc&w)?MS6%%5eH6sRpirnNR8rL2*IDeAyu7@a zxP+L5ga|M~#4p&(-!4eR%a8Bh7y0jX?l}6{`?~u0yLx-^{JyT;Bkurz<*QeJPxL>3 z|6ZrRtJD9^nw1qDl|%B|3fwv8dmE$DiBBwbnnh>;~=v2X{sP&FurRieV^tW zh5A<0%lt3*sTv+ZA>W!0YOs@vwl<+>dg}!bUKYXBE|t^Xw0ecH;Nd;Dx&a$Ff9P~0 z<9pvV$?w@2TfsTvwK<^!%ldETf;YvylM}P+O`eOD=I{E<=#z za*_y;mQP*Bs45b6YTKI30%&n+vHMc6R5(k{zFf(Dgmw+JBE*0aND`-A^3=#L1k)l|YvwUDw;;>AbAiCL|Cih{*uJXTFJhcHCxo!0nG>PH)n6GHV?<+LW zZc7eqLZ9#O{;4GV=e~H9W(Ex97|7XtRL%c`6^ z;sVV_g&np6q_s2HrrB<$$Aorudx|h_Zwt&c)HIXm=>J&4e)DhJr1cQ=wpQ8C(vX@$ zDU$IL4PE6eN_C?0UFyPHGuD>uWVPg6u!HTUwb4Y*zhT{va&n4Rw$V()Z-Ulb*uL_l z0_DO=_qUXo<7YG`6MsT8cX$?uj#oDJooiZ@byZMrZ6W7sh7v+=g=qYbSpM05YmFek z%?zsI=H^r9(WRiCi~gSA^zQtB2z)+Vr;h8d);tR(JE3e1GMy&qb#^wL4}D_JGt2un zZ`5v^nuqZwS(0k#Q4{;k5d2?g2oM=J#X1XU&u;sDP*GRxkjCSmednSKS;~W-N9QWO zC!TeP_#2J^d}GxpQ<(X}9|INbC?=gR&E`i0sXc<9!wKoa8k!snL zC

=@bn5~WE3e))^{ZE(J5$b;I&=dIR_mroNl(|& z)T~QMOS}L0K?PpWc#WA?(dNdpzmb{qVvPP|;+&+p3hXo32dM?-OsN;IzI-u#k@$j{ zll;TK?UpSh>N&NQuC)49z7N-AWb|WN-V~JQsnP82-HGjR`5P)ms)bXovx0`-bHklS z4l!pJkB8us5cNm-(g(kOJpzLZ?)2R69kEb{nKfW*XW#R|tUg6N{k${5b&6HoeRarC zZgckpJvDG}z`M!f1A|0hC3PI`I5>XmdF#S#o0xtSP4OZwDSc|4kPk~5`YYj#!c&h+ zf=qH*WAJsn9Eou+5>k(jDCX(YQc{Yr0>^^e%z0P=E{=t!D?!^d zMTVwkX2m-N_hI*LW6195dfm8n>()=H>tOnYr7O&BPoPiYIsRrNvRUxtS5UR$+-X*} zAAG4UT5%CN1)Cc39AnAwkufdp=Vcl9P`n&~Pjh6&Gdp7zwuL9;fVav^N-TX3oQr4d zgFBI5KRUcHu@eWz{Dtpl2mus9Kt;={w=HO`d#Di0ooI=e` z(8&`Qr}HsCe~Ng3?E@D!Rc}oqCu7LnZCdMUSgb=-R!RscnNCY+QRcY*1;K#` zp$zb|8X0MiI*zR4d5sx{P%ZvKA|muC0f{mNn(c6iwwylT8llgnT!Ii2;}WlfoEkDa zBL8BiQIi8Qb=xOdJ@~mEy-B_RnE9a#b#!WEKSG?Tl@CDTqAk()M-} zd$-Q8EO|3c3g;;&3+wkTQJW1puD{{k9W3#h1j9@Nj70HX&z>^7kH&Th5o&xe{*Z@y zX068G!I0YcBK6UrLo*cdf-0ywzx|8aojVSZVs{SzhI5QB$paW7WAe}Xse{NY&H)?J z9x)+t<*zotzbKsd2?UtC8y>fTPi$JPOW?QEv(kO&NW{27>wM_U(oDm_MaMgTvs6Rw zs64vJ;4tw9m8)6o5#(H43(JJd5#HyVIIjJ6zn?l>rn?A`ygZ@x8;jLVSgAR$R+clr*Yii>)^5eqQv<@c5ns~OcDPTLyol#w;nPlve;vq~f34Ip`r3^NMR+na zPyN6trT3t;V7FuHYKCm#UEj*-!J&->XC=`JjSaR$%a~nu-okIq4Lep zrrKY3DcaR+e}1J}*jmo=?E4HU%h~;|&E4&oZX>WZT1xwLLQ?b3mdmKtiXqoi2*jEn zF84B={fxy#QE{-4m7A_38M9_X~#`=xA@+h(@akN1Bx=6A*eGUJNIV3s0k4jCS|;EzJX zwoY7}iI}MdXK47d>rSefvffCDYF2!t03$oQ(4g{ON<5cx&y+(Gm)t9Uh?QTduxa^^ z$xiY=Ha}_|v=m^F$I;4_x~;iufN^&TDh63sl;>IAz@+l+fvLMIQ26b-B!(QtgEg;- z`W%+bLT!h zT9|;mDVS+>c@h5^S}o=sxz7=TOL${67@sP_-s`Z}`Hp$6aW&SSkyM5c97;br*k#lSkY$qQvi>?U(6+Zz|@d$(7q7J044ry{oIM`@=`VkU}>~ zjT8ZHG40pcc?lx7yC&{43p!p%W+<>~sIeZzFJ%(1GpI`4vd!(%j=#d&LfCzZlXmE~ zvrh1AD^oRFp7J47TW5FNZl>K|pU?<7Sa;1D|DX*GcAm_9lY{9wOq4tGhYAXNjS*Z} z#kT!%Q<-lu=li`2OiXx&;x&1UWL>ex^cw+pNV;^MZ?(>l4YmF}RX-C;HI?MEh6ct)f2Y+R1XvhPddJK7LnH=}eeb-0=MHsBIGHO|Tu9D(K0xe-X z{X2X)WFVTtFBL)+wW(};#pmIp@o2KGoVVAMLo^krDV%nG#fha{k7N1XPTA6(q}rDr z?6-Whp{`);R8v$0cl5L1u^ImPvt&EHSznd8-mN6<)hiycrlUrhkkU8HxiAxCGxomx z=D5AXe$i{+p%|9#h3^*~k9P|MDGrKP;A~QWNsEo_GT>Ga*VEv6P9fT`|0n~$OB+A~ z%NXX6_l<5OVbEBpho9fYGCQ7Exw&QS)+{|W8|c!B8t*ZEO!%^=V3gTaVIIaSWCYj? zU~|5Ri=*wMT=@gv@`-xuC|P+R=T*n`#}&89RtInA$f;QGPq_||FWX$^4zz2n8e}-t zh+xruJ4-QL<7weK)0{nAV{19l04;NHax&MjX%362o_a-_tr+lzvW0N9u&Bod2y?u| zN`)#o1IOP>I1hNto7Pgvw9})tEve_E+8dteT#Zx{KesY-EBS^BPwh+~!UkS+uraKy za(ooN`m?}K{FeA=2+caCNqa!qTRnmCEs`QF2LsP(@>3u`VETcg$PL>)7mO_?b$iy% zxaCIOy713!Dz$smO~t{8kz1P`7XrCzRXYRsyRRJEnn$VD)4Wib40!&kqU+hr$y~J2 zuZ4aHt;5OaZsb%Kpx0J0O%@5w-i>o1b+{TuHxGuI^L$!~Y3|5ob6&Aw0Ea^b55EFX)C?m7(;JE!{Guh6c5tTnF; z<`(lssu3t2+1oFEW64Qo>WD>^eQX5k&xS3r7V7LR^`mMuB~CKs zA6i;^1iVM!;@M@j=sClR78V!3mzY&KPV6p@5+^Uy%R9W{z}4~<*motq$;{+KK*~~C zZ6a1jV4llVA-SyN!|%m5iZUZmYYH5n4u=`3Dai;`Mzx>5>uK02^pX8@EvK%Q7eOX& z6;N>1C#is2MM{C<`I=13d+m!LzZ7<9(bIODrPCxfCO+;aBNrqdhkJ)8^PQO4>EhlB z1qrvRGGH$}`93i4TAM4pZ;^xj(Y)d?#+L?`nwHiBhFA$zISmHZhb3`MFFrk-Nlg>6 zFh}RYh-R#EKIKdlRWg;4YCII=r%mk7d58JQse}0Qo_3ctDS*%JZ!J%sQ{h5M$(vy! z_Rixn=JYe<-P4ksWvAwriSryE@EP<@VDF3EjW*4hiU!EK13b22;j@uJ>d9skdNQK> zeQd96RdXOdJRDO8gYcGx)#2Z{FOJPz2E0FOVcD5|u@{L*Jgje#)Hp)zlPx=^ZdTJ5 zz^FU(K|ri!Wu!KE?%u_%^g~Rj%?;)K=XJ#oY|ceV3#zhc|A~i7Z4`y4Y$cCR8x@pj zg_L_AdQQrmmKN)@etJ(4%kcom=&4~fEIP&-V(i~aZtGlxWp=Wt_b;YXFkQ?ytNJ7X zST>Ua+Py1~vQqQvOPp8MP*t(OKJO80ITchToyH+FvTLfnXRPZ3Hy(MQn?h?(abs-u z$FDT#Usnw%bQE>&5DrxVWl3D{&q1aItlyexrpEswwdr2m?x~d;lf_LxK;YQJ=DsSGr zS@@wr#l9936H{s1rfy%SlP>BzAn$yy%Beq|>T9}~ja~K!mVIS~x#){`sQM4K2GeX{ z1eEW_c*Rry&8Z2wh~{!z22jOvS*sg~Sy$8&Mm+(vvygnfSU`Ff3pZHCC^zzjb5^R`R2B z&!pnNapTJEhOV5TpVaR%(402*j~*>FK{07Nh1tb|Nu|)K>!lWjy$x=;W{^v$)l3*H#b?CRQu6v5O;A%(n zckAc|0~wF0n+knfp6=71sy}jfFNxCv%pnAc2AKh7Bn3D?xp zy07T?ItO!KaAa#LUYWHs%dLTBXJ_Za`vD;lfePZ=Cpk8QIm*|~zz693&O8$7LDQ=J zFI4FDhfVK9BqY=?pqzcCdwP3D!i(TPJ-x&p=JxjQd@MeUBlcx~XtseMEnNfcn?@Z~ zM!yUHbIY%0N-GuC(@nK`Sp;W4HaF28youZl>fMLOZd-0JEP9rr&)%S(D7Ap_U2&My zGXY<>j##B+etBO~X4;1k;5(<8{Y4PpqKR=a+7z zmjTjVM8_WZxxzasM06O=2~SHfJ&`&9lpU#t*9*_anPe9rXt3l?Vmr4 z+pOOU#DSK%SfxWsIOKd;~fK#U2MHBPO5f!Ksw?FURrd-}ZIjX0ck z9X(A{CCU|o-qLsKy^|Wk{wnXFPY>Q}mgJ(BkxeV2vf?~r>)nKV7SAT#gEiuY&L@oN zn3$wl1}{qcE@#(%pKVKhUnycy(=(*aAlu*@f`ZEV;JC6y!L`ilashtx!a&OUUR2Z> zs_r!`)W7OeYRfXY@;!q5>;c*fY*!U1;kw&l9ivCCd}EsQS|jOIVQxtK>cfV>jWpHE zB;M)zz>5U4yRis=cIA*1-LP%4x-BAAd;o+5L>zkiTN9~5q?G($k66RHdDi^mh^M{) zk=P0smzR4h7kjS@O56wUaoBQxKs>Pu__pY~wgEMrUbFqlk_*FLB2HEYAcQTy82XzM z8JP!UpW2OCg;slj+cE}KPNo!EZn3O$kh24RRy;TCrK7V#YB6XKf1Z8B86(iyBvq@} zjQxT7mTvix_~o`iSAVCkmlrZ@ch$MlWiFrXr0;wOY8jo}l`H(>+>50f^I)oI|L5ze z#btNj<2BA8&1G?1nLe1hpOs()TLYxjT%@dpSdaF@aVvkpze8Lr)m-G3^I5muOA~>& zPZ1EQs@KN`rMOq%LtO6++bm2qh$>Cpa)Ubge0nU=tBzGa;*lHx40$t zpYz>`{lt;koD|0*mR5^-ccZ=xyHU}_bxUPozk}9t(VNHwAWi=?PnR}~=)O>od zM()11&D625UNulTihB~Fs&uf@F)Fi1lA8v1ui0Qp%Jr)%fHDGprQp5$ymUFGF!ybSkio*=4hg&m)ayPDD z*Hq5Jlxh_)Ry`GKKAI9Zb@Y<8u`xmEY9(=bA{ClGefk71pFqQ(sDr^$g=b7FQX@Cc z1l9a}Bu>q<-R?IiV|vv4zykKnwE0ni4f%aBrNel1UfjI2yG6uK%yM=_?M%e7m7B+K zsnJ8D%-+MjB~#w_uv3CZaOk8|ElNBfZ~o|_!7Vt$s=oiM=hB#D$sVpIKAw&>wC|kT zdMfydLcsb>8yGHTWjozVfpKX(Cwxg@sAa4FlTcXG_OIS0_-8}A9PgG4SL5=Z?EJ;$ z^;YDzAxeRCQLA~ONnFbN+ip^v*RaJ0)6kiw-4**J9qVdUF2+)o!|8|UWbvoW~_1$9nbKS7r}2y#f3R(R*F!0&O)JQtE#Pr%IgkX zBZUUu$A>K>5e8*rNeB6$ZC>B+*I5(^yl3{52=JNM^w$j)x&&X0##~r$UYqVie8%(%gD`51=9PPioI%3piv6e{d zoE`iuD-^lcQCgqh`h=1;o+=7gfo~ho&sI>#Sqe0R{QAjT-q@&gOg!OshzSX5%+H5o zjK`2xrQ7L9ii3^X8P?kZUH0bHZUTH-Uy#;|2klhQ6(Y`Nad2ROiL?Eu{g3w|T?bQD zgL25xdJYzr!ljG$oK=3YhrEaaopkf%)tJdALHIVm>HRaS?8efxgz6BSO=ry-vcW`O z<@lQY#Hn)`{IfWWcvz_iW*7>@w?VwOUQbY!@e1Z)NI)#A*2+!p=vY8p>7>@I_R97$ z-YDKcO@BLEG<(W+?-|h+ zB0h82uJ-gqM(DHvy3(TqBOVt9=(02KKK7`;pD~dpYzFA%pXkF4G>`=hFAaXql*TRV z6<_TYOUX$-3^u71V5q8wX^}ovgW1p+mrB@2=F^|3X6sXknj+za@+S=!K3n{^7pW}M}Rbg2YB3V z3|U$|IILdlWtB~DR_#_jT#shPg%f(kT6&JD5ap}$3jQmz2R=>qy9==n*b#_3hu^TC ztb%8QzVhs5keFiNI?tXlN~-GWi{Ul^0SAEL61%{f53>Wo$Zf?5N}5bIquI$dWO|%f z^W7M4^I}1;=g07d12WD5Z!FX$I5;Cr7Meq27RLO;Js5p_t1I45VZX)ubkKF$@|YOQ z4YoxX`UhFmYS6Q~Y{GZ&1vCrB-U=QcI@Ib{eQ;&)d^cQ;(}p>#l*_9Mv)K5)PY8)s zP~$|Jn2nb)v*cL+SSes!z#-@dFva^zea8b+o^fMV4T0>u<KNjF*!!HaQfMdqDN_D)a${(1NSPC3YS;=!*J?O1SfWVGg>BiO~hdv}J zeQGxfP0&aawfdxj9(YqVs9>a($mZ&ys1Hs;Me$DizgoQ?Yde}h14}10?R=^*AXNqJ zT;N;Se}$(jeQK(}gKE--n$-qoKkh?8tax{JQnzk%vW5NHA(<{?TZf^3%RST3X;+G` zXX#eNnnG|XEktvBj^vyiuW;*r!?p?*PWAh$gwrY}mC)I?lWVtlAMA50|FB1?1Sk)( znTpVkS^A~oFatf4Vuv%N$j5r&FNqoq^&yi@hZxWJ+un-AFZK(`1}ejG&*J8}1A;cH z#}a;|R~QkheA=$gli0?rpa~VL&-v(O1)rB1AC7{DZzOYve5FZn^&@BtaluX>@EI19 zRx}F-vKwy3)tbi8;OjH);{Txqk-jiLL>o zxRoG#*r~dzVaCfvSSE~&6?0n!>atSkR@0#spp^os3F3$em7`gWLg4zyGtkMsjamek zzDyGI(CsAm9{zpElZs6*ZZwk`Pdr5$A~FVfrvQx;y!N1J@|CIpkVv5wZ5+?FVheA2 z50@!bx#Ck?y4N+b41$z;X4dFu27tP(hMC{={di~uzSV6toQj0k?(V{aitHU9cFn(x zvw~=@O%=q=+jTCB?Mc2JPIMFUM1YwPH4Q^1xKqwEULib-%#P<3xVpBJ5wu&Abvpj2 z$%O@ndpd~Ir&LRiwc$LkCoo}qo4E|@8W=DsdS zU@7cw8Q~Uw{@mqJG`OG85qn;eWsx6TU`jO$mnFc?TRrgTdwZ)B$;9`p7~6_GV`~Ja zl&yO7cEZ5bwfMpG#>$5z37Kl6+?@bW2~uxH7BVL`o!hc(Gwk5U? zM3zgj|FkZaTji_5au+wOG7Z<>3wShS;^FH+wn|W}$rAj+eSAn;k(0D8IjC5gDKtEC z2Faij)B<7tsP)VnfNIa;U^dqr$|_5P##()zj&eoX>o5 zKMvY82ii&#;cV%$WaU_fIxPibrfn%vE9Ul!I=1vW8}-l$4_EB%4ZN=p8y8JgOiqn@S}Yb9=F+yJ zu$Tg37BiEX+4T2{o@7i;nD}X-Y8L^>HHwPmtES7FEK4w8(Ph{qMq#tcuZzp~!`Icp zw{&6hH7amlRZ>{vj4jEC}0+)@)H!{R+RYY6^aPuz@b*y5s4| zg+0KvMk&>v^l^sh)`J<^Qc~-XaJ!u4{xu+Sw&beu>(Wn0D|=3Td7M1Vt6@C5$qWu} z&6IH)xm(x)IEb5{H^2OXUwwk{Hj(_%i|1X!txZFu#%nwq_E(0ixbM?K$pDO^PoXW5 znrF62Esxw5lhlfPeR8l-9e77un;rFzhL*O(Gm&<6b#)X@uO(}Y;PT4d+kkq(oMk;H zb$xv+6W#}3jCU`RUs+q(9s|lqMssC>qmH%3gJR3su=frQ4yI@}-#H)&k_zN3?gN6G zkQeIjp8|g0i<0YmSruZVua87%xJ{?Mc?gzA;+I>^4U82nJ{Q4fQN{M!!3PtC%Gp;v z(Gat>*0;o`^c~N@#Mfu1yQIe~J;TmU0SQrIt9o7k6&pxxfCpgBDi|QW{h1JxE!0Vk z*Ypzhm3b|Ymoq!5g{%IYMaoC$C&iU2bnP5XSuV>fZX!14z6_2n5;Bk)UiI9tfv&N~ zkCpy_&uNh}y4JZ?pqD9w;qc;2UNHoVC^ksAIB)Df;^lo07ewbMH}@;9+AiMO zlX(65^-?~1?8{SFQJc~%kcu|knkGm%tzWtKJV{n&jmCNMHjEQ?`gnKD#(kk6-TJZ> zbMJ39Db1h|A2hX|d0(zqTZxH?;MM+BdFJZ^1 zG3mriRakS_;f61gKv@ciSThj%Ks`IK zV$?u>(Lo4w&_u&x1tSEEHowMe&e7@)n z=xC46&wKp$ffRnJy@aHsBLEv3t*@o6a)$94DDAurIO><3xdyQguCDeH%?iN=G0(1!}8$QOfW~g$DlFMBc}qoHb(1nIuK=~F>~+dF~Nc>;lIvxv8Vrb6&p`~(fZ=5 z!MRoYiQ3#5!p>O{_0m~DUbuUzZm$&AX+#4HZy0-&vujHX9rFPv$yi&s6KM9B+(Kj@B2(^p(K<4iTVn169)cYKr+GKsS^9bT2({ zKt-~?!tF#AyoV{O+l))B!khZzTz54nA@ZE#C{MS7(F=EyzkAfj2J zm84VH>gUakm-LCumrcOWz7jQ-qjsl7;)sDL*etj!Eg=6C2K+id`#-5Z~Bbwoh9 z`479YCVJQQ586pGfu+_>lL{ZL&^7QU9$D4a;qL=7NAnSG1s|oV0$0UhziV>k>D4>4 z>WOgC157A)w-Ym)ltmdP6%`3M))Pq$V_*bHLJ1eaDdUbF2)J$;E_Opd?8o-e@?yH# zbjF-?lihfE&+NPEVLQ9=ZFo4ljEB$o{EVj6#ut@-uf5_yOF5Q*UZ-Y*M1tPZl3cwV zx-sz&-3M!{DoY(Nx9jkvv`2C(d`=%NwXl%&!89I^Rw8233v~k~!{*PAv9ICD%s9m* zEP%wsVhm8vfBW`|Uvd_ZKJr~HNH<-Z`?CEzMX}XFnv=pg=LFv$P-zg1cHUGv-R6~; z?_JeL-SqYITWmhz5@*;s#^r==1}JD#?T#V|I?X3ui6y2Lx=wv>H}`)u{5x%-6Lmwh zR>9+%+Hz#uBe`?q(x93Ew2b^=Bkjk}pRs;T^h-b;)9g)ha+cRnN^x2DXDB9Ma+FaB zC>0(V8Ke_V5Q2uQgT_tZyUsuIZohf^*7p27;N!{T_TT05m7HO-ZA(mT>2n3btX|8M zl#xsB6P7=s3f+-)J(i_A_z!Sj_ZrDTIV%Mqs6v{TE$2dW{IMfL)RxSb7A#V?OiD~$ zW6oc^cwy0vW$d1wUg|j(UGV`ulhisO{JVYoy@$N%4j6KyL65S}|3^v4Fmv!$-HB-3 z8d7mFKTh;>piR&mrPgz-9kXD=(VMuEjYQfPFJ6qoS?~VN9BX@BzW*}Lu>;?umX_1i zLJar-9_m%nB=vnEK65V!-ZSp7uceWB=Se(;lRj|#2BYkE^YvMcuGunIDq@R1l;DCR zkk6M*33@Hw@5VmBD>#?zZ&&<5x6o}7M)20qT5PtEAa**zO2PC55>;aQZc8dFX$CD+ zm^C!zYEgt-iA8HHdySGr>uAoLT?=ia^T`l2`qbLP67Zm zMBF1>8e8j8z*uL(I&;1-4y3 zp3g@uI)eTD91EUW6&5j$`wc3I)Tg;o0<>DYT1 zMX3@dw5V2o!^Tdw8niEq;-|+kzm5H)mAU*5v(3pY`5E}2e)vZKU#kULOM}e_yN{MI zTTSawMdA@O_8XJcRr