Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: gateway enrollment token flow
bernie-gcf6a55282a3d
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex 27f5c05471..0db144ddbe 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -164,6 +164,9 @@ import {TGatewaysV2,TGatewaysV2Insert,TGatewaysV2Update,+ TGatewayEnrollmentTokens,+ TGatewayEnrollmentTokensInsert,+ TGatewayEnrollmentTokensUpdate,TGitAppInstallSessions,TGitAppInstallSessionsInsert,TGitAppInstallSessionsUpdate,@@ -1578,6 +1581,11 @@ declare module "knex/types/tables" {TOrgGatewayConfigV2Update>;[TableName.GatewayV2]: KnexOriginal.CompositeTableType<TGatewaysV2, TGatewaysV2Insert, TGatewaysV2Update>;+ [TableName.GatewayEnrollmentTokens]: KnexOriginal.CompositeTableType<+ TGatewayEnrollmentTokens,+ TGatewayEnrollmentTokensInsert,+ TGatewayEnrollmentTokensUpdate+ >;[TableName.UserNotifications]: KnexOriginal.CompositeTableType<TUserNotifications,TUserNotificationsInsert,diff --git a/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.ts b/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.tsnew file mode 100644index 0000000000..05b6f2b962--- /dev/null+++ b/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.ts@@ -0,0 +1,37 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ // Make identityId nullable on gateways_v2 to support enrollment-token-based gateways+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {+ t.uuid("identityId").nullable().alter();+ });++ if (!(await knex.schema.hasTable(TableName.GatewayEnrollmentTokens))) {+ await knex.schema.createTable(TableName.GatewayEnrollmentTokens, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());+ t.uuid("orgId").notNullable();+ t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");+ t.string("name", 64).notNullable();+ t.string("tokenHash", 128).notNullable().unique();+ t.integer("ttl").notNullable().defaultTo(3600);+ t.timestamp("expiresAt").notNullable();+ t.timestamp("usedAt").nullable();+ t.timestamps(true, true, true);+ });++ await createOnUpdateTrigger(knex, TableName.GatewayEnrollmentTokens);+ }+}++export async function down(knex: Knex): Promise<void> {+ await dropOnUpdateTrigger(knex, TableName.GatewayEnrollmentTokens);+ await knex.schema.dropTableIfExists(TableName.GatewayEnrollmentTokens);++ // Restore identityId to not-null (only safe if no null rows exist)+ await knex.schema.alterTable(TableName.GatewayV2, (t) => {+ t.uuid("identityId").notNullable().alter();+ });+}diff --git a/backend/src/db/schemas/gateway-enrollment-tokens.ts b/backend/src/db/schemas/gateway-enrollment-tokens.tsnew file mode 100644index 0000000000..80649a9875--- /dev/null+++ b/backend/src/db/schemas/gateway-enrollment-tokens.ts@@ -0,0 +1,26 @@+// 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 { TImmutableDBKeys } from "./models";++export const GatewayEnrollmentTokensSchema = z.object({+ id: z.string().uuid(),+ createdAt: z.date(),+ updatedAt: z.date(),+ orgId: z.string().uuid(),+ name: z.string(),+ tokenHash: z.string(),+ ttl: z.number().int(),+ expiresAt: z.date(),+ usedAt: z.date().nullable().optional()+});++export type TGatewayEnrollmentTokens = z.infer<typeof GatewayEnrollmentTokensSchema>;+export type TGatewayEnrollmentTokensInsert = Omit<z.input<typeof GatewayEnrollmentTokensSchema>, TImmutableDBKeys>;+export type TGatewayEnrollmentTokensUpdate = Partial<+ Omit<z.input<typeof GatewayEnrollmentTokensSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/gateways-v2.ts b/backend/src/db/schemas/gateways-v2.tsindex a133fa2ace..1127bf3ccb 100644--- a/backend/src/db/schemas/gateways-v2.ts+++ b/backend/src/db/schemas/gateways-v2.ts@@ -14,7 +14,7 @@ export const GatewaysV2Schema = z.object({createdAt: z.date(),updatedAt: z.date(),orgId: z.string().uuid(),- identityId: z.string().uuid(),+ identityId: z.string().uuid().nullable().optional(),relayId: z.string().uuid().nullable().optional(),name: z.string(),heartbeat: z.date().nullable().optional(),diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 1ee9a97033..15af09ffd0 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -53,6 +53,7 @@ export * from "./folder-tree-checkpoint-resources";export * from "./folder-tree-checkpoints";export * from "./gateways";export * from "./gateways-v2";+export * from "./gateway-enrollment-tokens";export * from "./git-app-install-sessions";export * from "./git-app-org";export * from "./github-org-sync-configs";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex 33752dd9ef..db1d12d508 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -219,6 +219,7 @@ export enum TableName {OrgGatewayConfigV2 = "org_gateway_config_v2",Relay = "relays",GatewayV2 = "gateways_v2",+ GatewayEnrollmentTokens = "gateway_enrollment_tokens",KeyValueStore = "key_value_store",diff --git a/backend/src/ee/routes/v1/pam-session-router.ts b/backend/src/ee/routes/v1/pam-session-router.tsindex e88d20c967..58201043d5 100644--- a/backend/src/ee/routes/v1/pam-session-router.ts+++ b/backend/src/ee/routes/v1/pam-session-router.ts@@ -54,7 +54,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {const { credentials, projectId, account, sessionStarted } =await server.services.pamAccount.getSessionCredentials(req.params.sessionId, req.permission);@@ -125,7 +125,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {const { session, projectId } = await server.services.pamSession.updateLogsById({@@ -172,7 +172,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {const { session, projectId, alreadyEnded } = await server.services.pamSession.endSessionById(req.params.sessionId,@@ -379,7 +379,7 @@ export const registerPamSessionRouter = async (server: FastifyZodProvider) => {200: z.object({ ok: z.literal(true) })}},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {const EventBatchSchema = z.array(z.union([PamSessionCommandLogSchema, TerminalEventSchema, HttpEventSchema]));try {diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex f72ec9b3f4..bd022d8251 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -1,11 +1,14 @@import z from "zod";-import { GatewaysV2Schema } from "@app/db/schemas";+import { GatewayEnrollmentTokensSchema, GatewaysV2Schema } from "@app/db/schemas";import { zodBuffer } from "@app/lib/zod";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";+import { ActorType, AuthMode } from "@app/services/auth/auth-type";++// Stricter rate limit for the unauthenticated enroll endpoint+const enrollRateLimit = { windowMs: 60 * 1000, max: 10 };const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({id: true,@@ -17,6 +20,15 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({lastHealthCheckStatus: true});+const SanitizedEnrollmentTokenSchema = GatewayEnrollmentTokensSchema.pick({+ id: true,+ name: true,+ ttl: true,+ expiresAt: true,+ usedAt: true,+ createdAt: true+});+export const registerGatewayV2Router = async (server: FastifyZodProvider) => {server.route({method: "POST",@@ -24,8 +36,8 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {schema: {operationId: "registerGateway",body: z.object({- relayName: slugSchema({ min: 1, max: 32, field: "relayName" }),- name: slugSchema({ min: 1, max: 32, field: "name" })+ relayName: slugSchema({ min: 1, max: 32, field: "relayName" }).optional(),+ name: slugSchema({ min: 1, max: 32, field: "name" }).optional()}),response: {200: z.object({@@ -47,17 +59,16 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {config: {rateLimit: writeLimit},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {- const gateway = await server.services.gatewayV2.registerGateway({+ return server.services.gatewayV2.registerGateway({orgId: req.permission.orgId,relayName: req.body.relayName,actorId: req.permission.id,+ actorType: req.permission.type,actorAuthMethod: req.permission.authMethod,name: req.body.name});-- return gateway;}});@@ -75,7 +86,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {})}},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {await server.services.gatewayV2.heartbeat({orgPermission: req.permission@@ -92,10 +103,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {operationId: "listGateways",response: {200: SanitizedGatewayV2Schema.extend({- identity: z.object({- name: z.string(),- id: z.string()- }),+ identity: z.object({ name: z.string(), id: z.string() }).nullable(),connectedResourcesCount: z.number()}).array()}@@ -178,7 +186,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {200: zodBuffer}},- onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),+ onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.GATEWAY_ACCESS_TOKEN]),handler: async (req) => {const pamSessionKey = await server.services.gatewayV2.getPamSessionKey({orgPermission: req.permission@@ -274,4 +282,102 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {return resources;}});++ // Enrollment token management+ server.route({+ method: "POST",+ url: "/enrollment-tokens",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "createGatewayEnrollmentToken",+ body: z.object({+ name: slugSchema({ min: 1, max: 64, field: "name" }),+ ttlSeconds: z.number().int().min(60).max(86400).default(3600).optional()+ }),+ response: {+ 200: SanitizedEnrollmentTokenSchema.extend({ token: z.string() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.gatewayV2.createEnrollmentToken({+ orgId: req.permission.orgId,+ actorId: req.permission.id,+ actorType: req.permission.type,+ actorAuthMethod: req.permission.authMethod,+ name: req.body.name,+ ttlSeconds: req.body.ttlSeconds+ });+ }+ });++ server.route({+ method: "GET",+ url: "/enrollment-tokens",+ config: { rateLimit: readLimit },+ schema: {+ operationId: "listGatewayEnrollmentTokens",+ response: { 200: SanitizedEnrollmentTokenSchema.array() }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ return server.services.gatewayV2.listEnrollmentTokens({ orgPermission: req.permission });+ }+ });++ server.route({+ method: "DELETE",+ url: "/enrollment-tokens/:tokenId",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "deleteGatewayEnrollmentToken",+ params: z.object({ tokenId: z.string().uuid() }),+ response: { 200: z.object({ message: z.string() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ await server.services.gatewayV2.deleteEnrollmentToken({+ orgPermission: req.permission,+ tokenId: req.params.tokenId+ });+ return { message: "Enrollment token deleted" };+ }+ });++ // Enrollment endpoint — no standard auth; enrollment token in body is the credential+ server.route({+ method: "POST",+ url: "/enroll",+ config: { rateLimit: enrollRateLimit },+ schema: {+ operationId: "enrollGateway",+ body: z.object({+ token: z.string().min(1),+ relayName: slugSchema({ min: 1, max: 32, field: "relayName" }).optional()+ }),+ response: {+ 200: z.object({+ accessToken: z.string(),+ gatewayId: z.string(),+ relayHost: z.string(),+ pki: z.object({+ serverCertificate: z.string(),+ serverPrivateKey: z.string(),+ clientCertificateChain: z.string()+ }),+ ssh: z.object({+ clientCertificate: z.string(),+ clientPrivateKey: z.string(),+ serverCAPublicKey: z.string()+ })+ })+ }+ },+ handler: async (req) => {+ return server.services.gatewayV2.enrollGateway({+ token: req.body.token,+ relayName: req.body.relayName+ });+ }+ });};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 3fd4913399..b57443a67c 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -88,7 +88,8 @@ export type TCreateAuditLogDTO = {| AcmeProfileActor| AcmeAccountActor| EstAccountActor- | ScepAccountActor;+ | ScepAccountActor+ | GatewayActor;orgId?: string;projectId?: string;} & BaseAuthData;@@ -810,6 +811,10 @@ interface ScepAccountActorMetadata {interface UnknownUserActorMetadata {}+interface GatewayActorMetadata {+ gatewayId: string;+}+export interface UserActor {type: ActorType.USER;metadata: UserActorMetadata;@@ -863,6 +868,12 @@ export interface ScepAccountActor {type: ActorType.SCEP_ACCOUNT;metadata: ScepAccountActorMetadata;}++export interface GatewayActor {+ type: ActorType.GATEWAY;+ metadata: GatewayActorMetadata;+}+export type Actor =| UserActor| ServiceActor@@ -873,7 +884,8 @@ export type Actor =| AcmeProfileActor| AcmeAccountActor| EstAccountActor- | ScepAccountActor;+ | ScepAccountActor+ | GatewayActor;interface GetSecretsEvent {type: EventType.GET_SECRETS;diff --git a/backend/src/ee/services/gateway-v2/gateway-enrollment-token-dal.ts b/backend/src/ee/services/gateway-v2/gateway-enrollment-token-dal.tsnew file mode 100644index 0000000000..18bbecc451--- /dev/null+++ b/backend/src/ee/services/gateway-v2/gateway-enrollment-token-dal.ts@@ -0,0 +1,9 @@+import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { ormify } from "@app/lib/knex";++export type TGatewayEnrollmentTokenDALFactory = ReturnType<typeof gatewayEnrollmentTokenDALFactory>;++export const gatewayEnrollmentTokenDALFactory = (db: TDbClient) => {+ return ormify(db, TableName.GatewayEnrollmentTokens);+};diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts b/backend/src/ee/services/gateway-v2/gateway-v2-dal.tsindex a5534e0e3f..3a7b4862ee 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-dal.ts@@ -22,7 +22,7 @@ export const gatewayV2DalFactory = (db: TDbClient) => {const query = (tx || db.replicaNode())(TableName.GatewayV2)// eslint-disable-next-line @typescript-eslint/no-misused-promises.where(buildFindFilter(regularFilter, TableName.GatewayV2))- .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.GatewayV2}.identityId`)+ .leftJoin(TableName.Identity, `${TableName.Identity}.id`, `${TableName.GatewayV2}.identityId`).select(selectAllTableCols(TableName.GatewayV2)).select(db.ref("name").withSchema(TableName.Identity).as("identityName"));@@ -54,7 +54,7 @@ export const gatewayV2DalFactory = (db: TDbClient) => {return docs.map((el) => ({...GatewaysV2Schema.parse(el),- identity: { id: el.identityId, name: el.identityName }+ identity: el.identityId ? { id: el.identityId, name: el.identityName as string } : null}));} catch (error) {throw new DatabaseError({ error, name: `${TableName.GatewayV2}: Find` });diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex c1f8d81c74..7c9a354ea2 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -5,6 +5,7 @@ import * as x509 from "@peculiar/x509";import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, TRelays } from "@app/db/schemas";import { PgSqlLock } from "@app/keystore/keystore";+import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";@@ -14,7 +15,7 @@ import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";import { OrgServiceActor } from "@app/lib/types";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import { ActorAuthMethod, ActorType, AuthTokenType } from "@app/services/auth/auth-type";import { constructPemChainFromCerts } from "@app/services/certificate/certificate-fns";import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types";import {@@ -30,6 +31,7 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";import { TSmtpService } from "@app/services/smtp/smtp-service";import { TAiMcpServerDALFactory } from "../ai-mcp-server/ai-mcp-server-dal";+import { TGatewayEnrollmentTokenDALFactory } from "./gateway-enrollment-token-dal";import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";import { TPamDiscoverySourceDALFactory } from "../pam-discovery/pam-discovery-source-dal";import { TPamResourceDALFactory } from "../pam-resource/pam-resource-dal";@@ -49,6 +51,7 @@ type TGatewayV2ServiceFactoryDep = {kmsService: TKmsServiceFactory;relayService: TRelayServiceFactory;gatewayV2DAL: TGatewayV2DALFactory;+ gatewayEnrollmentTokenDAL: TGatewayEnrollmentTokenDALFactory;relayDAL: TRelayDALFactory;permissionService: TPermissionServiceFactory;orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;@@ -70,6 +73,7 @@ export const gatewayV2ServiceFactory = ({kmsService,relayService,gatewayV2DAL,+ gatewayEnrollmentTokenDAL,relayDAL,permissionService,orgDAL,@@ -648,31 +652,148 @@ export const gatewayV2ServiceFactory = ({};};+ const $issueGatewayCerts = async ({+ orgId,+ orgCAs,+ relayName,+ gateway+ }: {+ orgId: string;+ orgCAs: Awaited<ReturnType<typeof $getOrgCAs>>;+ relayName: string;+ gateway: { id: string; name: string };+ }) => {+ const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);+ const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);+ const rootGatewayCaCert = new x509.X509Certificate(orgCAs.rootGatewayCaCertificate);+ const gatewayClientCaCert = new x509.X509Certificate(orgCAs.gatewayClientCaCertificate);++ const gatewayServerCaSkObj = crypto.nativeCrypto.createPrivateKey({+ key: orgCAs.gatewayServerCaPrivateKey,+ format: "der",+ type: "pkcs8"+ });+ const gatewayServerCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(+ "pkcs8",+ gatewayServerCaSkObj.export({ format: "der", type: "pkcs8" }),+ alg,+ true,+ ["sign"]+ );++ const gatewayServerKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const gatewayServerCertIssuedAt = new Date();+ const gatewayServerCertExpireAt = new Date(new Date().setDate(new Date().getDate() + 1));+ const gatewayServerCertPrivateKey = crypto.nativeCrypto.KeyObject.from(gatewayServerKeys.privateKey);++ const gatewayServerCertExtensions: x509.Extension[] = [+ new x509.BasicConstraintsExtension(false),+ await x509.AuthorityKeyIdentifierExtension.create(gatewayServerCaCert, false),+ await x509.SubjectKeyIdentifierExtension.create(gatewayServerKeys.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),+ new x509.SubjectAlternativeNameExtension([+ { type: "dns", value: "localhost" },+ { type: "ip", value: "127.0.0.1" },+ { type: "ip", value: "::1" }+ ])+ ];++ const gatewayServerSerialNumber = createSerialNumber();+ const gatewayServerCertificate = await x509.X509CertificateGenerator.create({+ serialNumber: gatewayServerSerialNumber,+ subject: `O=${orgId},CN=Gateway`,+ issuer: gatewayServerCaCert.subject,+ notBefore: gatewayServerCertIssuedAt,+ notAfter: gatewayServerCertExpireAt,+ signingKey: gatewayServerCaPrivateKey,+ publicKey: gatewayServerKeys.publicKey,+ signingAlgorithm: alg,+ extensions: gatewayServerCertExtensions+ });++ const relayCredentials = await relayService.getCredentialsForGateway({+ relayName,+ orgId,+ gatewayId: gateway.id,+ gatewayName: gateway.name+ });++ return {+ gatewayId: gateway.id,+ relayHost: relayCredentials.relayHost,+ pki: {+ serverCertificate: gatewayServerCertificate.toString("pem"),+ serverPrivateKey: gatewayServerCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),+ clientCertificateChain: constructPemChainFromCerts([gatewayClientCaCert, rootGatewayCaCert])+ },+ ssh: {+ clientCertificate: relayCredentials.clientSshCert,+ clientPrivateKey: relayCredentials.clientSshPrivateKey,+ serverCAPublicKey: relayCredentials.serverCAPublicKey+ }+ };+ };+const registerGateway = async ({orgId,actorId,+ actorType,actorAuthMethod,relayName,name}: {orgId: string;actorId: string;+ actorType: ActorType;actorAuthMethod: ActorAuthMethod;- relayName: string;- name: string;+ relayName?: string;+ name?: string;}) => {- await $validateIdentityAccessToGateway(orgId, actorId, actorAuthMethod);const orgCAs = await $getOrgCAs(orgId);- let relay: TRelays = await relayDAL.findOne({ orgId, name: relayName });- if (!relay) {- relay = await relayDAL.findOne({ name: relayName, orgId: null });+ // Enrollment-flow gateways authenticate with GATEWAY_ACCESS_TOKEN — the gateway row+ // already exists, so we just look it up and issue fresh certs using its stored relay.+ if (actorType === ActorType.GATEWAY) {+ const gateway = await gatewayV2DAL.findById(actorId);+ if (!gateway || gateway.orgId !== orgId) {+ throw new NotFoundError({ message: `Gateway ${actorId} not found` });+ }++ let resolvedRelay: TRelays | undefined;+ if (relayName) {+ resolvedRelay = await relayDAL.findOne({ orgId, name: relayName });+ if (!resolvedRelay) resolvedRelay = await relayDAL.findOne({ name: relayName, orgId: null });+ if (!resolvedRelay) throw new NotFoundError({ message: `Relay ${relayName} not found` });+ } else {+ if (!gateway.relayId) throw new NotFoundError({ message: "No relay associated with this gateway" });+ resolvedRelay = await relayDAL.findById(gateway.relayId);+ if (!resolvedRelay) throw new NotFoundError({ message: "No relay associated with this gateway" });+ }++ return $issueGatewayCerts({ orgId, orgCAs, relayName: resolvedRelay.name, gateway });}- if (!relay) {- throw new NotFoundError({ message: `Relay ${relayName} not found` });+ // Identity-based flow: upsert the gateway row then issue certs.+ await $validateIdentityAccessToGateway(orgId, actorId, actorAuthMethod);++ if (!name) {+ throw new BadRequestError({ message: "Gateway name is required" });}+ if (!relayName) {+ throw new BadRequestError({ message: "Relay name is required" });+ }++ let relay: TRelays = await relayDAL.findOne({ orgId, name: relayName });+ if (!relay) relay = await relayDAL.findOne({ name: relayName, orgId: null });+ if (!relay) throw new NotFoundError({ message: `Relay ${relayName} not found` });+try {const [gateway] = await gatewayV2DAL.upsert([@@ -686,81 +807,7 @@ export const gatewayV2ServiceFactory = ({["identityId"]);- const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);- const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);- const rootGatewayCaCert = new x509.X509Certificate(orgCAs.rootGatewayCaCertificate);- const gatewayClientCaCert = new x509.X509Certificate(orgCAs.gatewayClientCaCertificate);-- const gatewayServerCaSkObj = crypto.nativeCrypto.createPrivateKey({- key: orgCAs.gatewayServerCaPrivateKey,- format: "der",- type: "pkcs8"- });- const gatewayServerCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(- "pkcs8",- gatewayServerCaSkObj.export({ format: "der", type: "pkcs8" }),- alg,- true,- ["sign"]- );-- const gatewayServerKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);- const gatewayServerCertIssuedAt = new Date();- const gatewayServerCertExpireAt = new Date(new Date().setDate(new Date().getDate() + 1));- const gatewayServerCertPrivateKey = crypto.nativeCrypto.KeyObject.from(gatewayServerKeys.privateKey);-- const gatewayServerCertExtensions: x509.Extension[] = [- new x509.BasicConstraintsExtension(false),- await x509.AuthorityKeyIdentifierExtension.create(gatewayServerCaCert, false),- await x509.SubjectKeyIdentifierExtension.create(gatewayServerKeys.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),- new x509.SubjectAlternativeNameExtension([- { type: "dns", value: "localhost" },- { type: "ip", value: "127.0.0.1" },- { type: "ip", value: "::1" }- ])- ];-- const gatewayServerSerialNumber = createSerialNumber();- const gatewayServerCertificate = await x509.X509CertificateGenerator.create({- serialNumber: gatewayServerSerialNumber,- subject: `O=${orgId},CN=Gateway`,- issuer: gatewayServerCaCert.subject,- notBefore: gatewayServerCertIssuedAt,- notAfter: gatewayServerCertExpireAt,- signingKey: gatewayServerCaPrivateKey,- publicKey: gatewayServerKeys.publicKey,- signingAlgorithm: alg,- extensions: gatewayServerCertExtensions- });-- const relayCredentials = await relayService.getCredentialsForGateway({- relayName,- orgId,- gatewayId: gateway.id,- gatewayName: gateway.name- });-- return {- gatewayId: gateway.id,- relayHost: relayCredentials.relayHost,- pki: {- serverCertificate: gatewayServerCertificate.toString("pem"),- serverPrivateKey: gatewayServerCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),- clientCertificateChain: constructPemChainFromCerts([gatewayClientCaCert, rootGatewayCaCert])- },- ssh: {- clientCertificate: relayCredentials.clientSshCert,- clientPrivateKey: relayCredentials.clientSshPrivateKey,- serverCAPublicKey: relayCredentials.serverCAPublicKey- }- };+ return $issueGatewayCerts({ orgId, orgCAs, relayName, gateway });} catch (err) {if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {throw new BadRequestError({ message: `Gateway with name "${name}" already exists` });@@ -888,6 +935,15 @@ export const gatewayV2ServiceFactory = ({};const heartbeat = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {+ if (orgPermission.type === ActorType.GATEWAY) {+ const gateway = await gatewayV2DAL.findById(orgPermission.id);+ if (!gateway || gateway.orgId !== orgPermission.orgId) {+ throw new NotFoundError({ message: `Gateway ${orgPermission.id} not found.` });+ }+ await $checkGatewayHealth(gateway.id);+ return;+ }+await $validateIdentityAccessToGateway(orgPermission.orgId, orgPermission.id, orgPermission.authMethod);const gateway = await gatewayV2DAL.findOne({@@ -939,25 +995,26 @@ export const gatewayV2ServiceFactory = ({};const getPamSessionKey = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {- const { permission } = await permissionService.getOrgPermission({- actor: orgPermission.type,- actorId: orgPermission.id,- orgId: orgPermission.orgId,- actorAuthMethod: orgPermission.authMethod,- actorOrgId: orgPermission.orgId,- scope: OrganizationActionScope.Any- });+ // Gateway actors are already authenticated via GATEWAY_ACCESS_TOKEN JWT — skip org permission check.+ if (orgPermission.type !== ActorType.GATEWAY) {+ const { permission } = await permissionService.getOrgPermission({+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId,+ scope: OrganizationActionScope.Any+ });- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionGatewayActions.CreateGateways,- OrgPermissionSubjects.Gateway- );+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.CreateGateways,+ OrgPermissionSubjects.Gateway+ );+ }return gatewayV2DAL.transaction(async (tx) => {const gateway = await gatewayV2DAL.findOne(- {- identityId: orgPermission.id- },+ orgPermission.type === ActorType.GATEWAY ? { id: orgPermission.id } : { identityId: orgPermission.id },tx);@@ -1098,6 +1155,246 @@ export const gatewayV2ServiceFactory = ({};};+ const getGatewayById = async ({ gatewayId }: { gatewayId: string }) => {+ const gateway = await gatewayV2DAL.findById(gatewayId);+ if (!gateway) {+ throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });+ }+ return gateway;+ };++ const createEnrollmentToken = async ({+ orgId,+ actorId,+ actorType,+ actorAuthMethod,+ name,+ ttlSeconds = 3600+ }: {+ orgId: string;+ actorId: string;+ actorType: ActorType;+ actorAuthMethod: ActorAuthMethod;+ name: string;+ ttlSeconds?: number;+ }) => {+ const { permission } = await permissionService.getOrgPermission({+ actor: actorType,+ actorId,+ orgId,+ actorAuthMethod,+ actorOrgId: orgId,+ scope: OrganizationActionScope.Any+ });++ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.CreateGateways,+ OrgPermissionSubjects.Gateway+ );++ const plainToken = `gwe_${crypto.randomBytes(32).toString("base64url")}`;+ const tokenHash = crypto.nativeCrypto.createHash("sha256").update(plainToken).digest("hex");+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000);++ const record = await gatewayEnrollmentTokenDAL.create({+ orgId,+ name,+ tokenHash,+ ttl: ttlSeconds,+ expiresAt+ });++ return { ...record, token: plainToken };+ };++ const listEnrollmentTokens = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {+ const { permission } = await permissionService.getOrgPermission({+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId,+ scope: OrganizationActionScope.Any+ });++ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.ListGateways,+ OrgPermissionSubjects.Gateway+ );++ const now = new Date();+ const tokens = await gatewayEnrollmentTokenDAL.find({ orgId: orgPermission.orgId });+ return tokens.filter((t) => t.expiresAt > now && !t.usedAt).map(({ tokenHash: _, ...rest }) => rest);+ };++ const deleteEnrollmentToken = async ({+ orgPermission,+ tokenId+ }: {+ orgPermission: OrgServiceActor;+ tokenId: string;+ }) => {+ const { permission } = await permissionService.getOrgPermission({+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId,+ scope: OrganizationActionScope.Any+ });++ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.DeleteGateways,+ OrgPermissionSubjects.Gateway+ );++ const token = await gatewayEnrollmentTokenDAL.findOne({ id: tokenId, orgId: orgPermission.orgId });+ if (!token) {+ throw new NotFoundError({ message: `Enrollment token ${tokenId} not found` });+ }++ await gatewayEnrollmentTokenDAL.deleteById(tokenId);+ };++ const enrollGateway = async ({ token, relayName }: { token: string; relayName?: string }) => {+ const tokenHash = crypto.nativeCrypto.createHash("sha256").update(token).digest("hex");++ const tokenRecord = await gatewayEnrollmentTokenDAL.findOne({ tokenHash });+ if (!tokenRecord) {+ throw new BadRequestError({ message: "Invalid enrollment token" });+ }++ if (tokenRecord.expiresAt < new Date()) {+ throw new BadRequestError({ message: "Enrollment token has expired" });+ }++ const { orgId, name } = tokenRecord;++ // Resolve the relay before consuming the token so a missing relay doesn't burn it.+ let relay: TRelays | undefined;+ if (relayName) {+ relay = await relayDAL.findOne({ orgId, name: relayName });+ if (!relay) relay = await relayDAL.findOne({ name: relayName, orgId: null });+ if (!relay) throw new NotFoundError({ message: `Relay ${relayName} not found` });+ } else {+ // Auto-select: prefer an org-specific relay, fall back to a global one+ const orgRelays = await relayDAL.find({ orgId });+ relay = orgRelays[0] ?? (await relayDAL.find({ orgId: null }))[0];+ if (!relay) throw new NotFoundError({ message: "No relay available for auto-selection" });+ }++ // Single-use check inside a transaction — re-read to guard against races+ await gatewayEnrollmentTokenDAL.transaction(async (tx) => {+ const locked = await gatewayEnrollmentTokenDAL.findOne({ id: tokenRecord.id }, tx);+ if (!locked || locked.usedAt) {+ throw new BadRequestError({ message: "Enrollment token has already been used" });+ }+ await gatewayEnrollmentTokenDAL.updateById(tokenRecord.id, { usedAt: new Date() }, tx);+ });++ const orgCAs = await $getOrgCAs(orgId);++ try {+ const gateway = await gatewayV2DAL.create({+ orgId,+ name,+ relayId: relay.id+ });++ const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);+ const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);+ const rootGatewayCaCert = new x509.X509Certificate(orgCAs.rootGatewayCaCertificate);+ const gatewayClientCaCert = new x509.X509Certificate(orgCAs.gatewayClientCaCertificate);++ const gatewayServerCaSkObj = crypto.nativeCrypto.createPrivateKey({+ key: orgCAs.gatewayServerCaPrivateKey,+ format: "der",+ type: "pkcs8"+ });+ const gatewayServerCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(+ "pkcs8",+ gatewayServerCaSkObj.export({ format: "der", type: "pkcs8" }),+ alg,+ true,+ ["sign"]+ );++ const gatewayServerKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);+ const gatewayServerCertIssuedAt = new Date();+ const gatewayServerCertExpireAt = new Date(new Date().setDate(new Date().getDate() + 1));+ const gatewayServerCertPrivateKey = crypto.nativeCrypto.KeyObject.from(gatewayServerKeys.privateKey);++ const gatewayServerCertExtensions: x509.Extension[] = [+ new x509.BasicConstraintsExtension(false),+ await x509.AuthorityKeyIdentifierExtension.create(gatewayServerCaCert, false),+ await x509.SubjectKeyIdentifierExtension.create(gatewayServerKeys.publicKey),+ new x509.CertificatePolicyExtension(["2.5.29.32.0"]),+ 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),+ new x509.SubjectAlternativeNameExtension([+ { type: "dns", value: "localhost" },+ { type: "ip", value: "127.0.0.1" },+ { type: "ip", value: "::1" }+ ])+ ];++ const gatewayServerSerialNumber = createSerialNumber();+ const gatewayServerCertificate = await x509.X509CertificateGenerator.create({+ serialNumber: gatewayServerSerialNumber,+ subject: `O=${orgId},CN=Gateway`,+ issuer: gatewayServerCaCert.subject,+ notBefore: gatewayServerCertIssuedAt,+ notAfter: gatewayServerCertExpireAt,+ signingKey: gatewayServerCaPrivateKey,+ publicKey: gatewayServerKeys.publicKey,+ signingAlgorithm: alg,+ extensions: gatewayServerCertExtensions+ });++ const relayCredentials = await relayService.getCredentialsForGateway({+ relayName: relay.name,+ orgId,+ gatewayId: gateway.id,+ gatewayName: gateway.name+ });++ const appCfg = getConfig();+ const accessToken = crypto.jwt().sign(+ {+ gatewayId: gateway.id,+ orgId,+ authTokenType: AuthTokenType.GATEWAY_ACCESS_TOKEN+ },+ appCfg.AUTH_SECRET+ );++ return {+ accessToken,+ gatewayId: gateway.id,+ relayHost: relayCredentials.relayHost,+ pki: {+ serverCertificate: gatewayServerCertificate.toString("pem"),+ serverPrivateKey: gatewayServerCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),+ clientCertificateChain: constructPemChainFromCerts([gatewayClientCaCert, rootGatewayCaCert])+ },+ ssh: {+ clientCertificate: relayCredentials.clientSshCert,+ clientPrivateKey: relayCredentials.clientSshPrivateKey,+ serverCAPublicKey: relayCredentials.serverCAPublicKey+ }+ };+ } catch (err) {+ if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {+ throw new BadRequestError({ message: `Gateway with name "${name}" already exists` });+ }+ throw err;+ }+ };+return {listGateways,registerGateway,@@ -1108,6 +1405,11 @@ export const gatewayV2ServiceFactory = ({triggerHeartbeat,getPamSessionKey,healthcheckNotify,- getConnectedResources+ getConnectedResources,+ getGatewayById,+ createEnrollmentToken,+ listEnrollmentTokens,+ deleteEnrollmentToken,+ enrollGateway};};diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 28b8bdcc54..74adcfe6b2 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -945,8 +945,8 @@ export const pamAccountServiceFactory = ({};const getSessionCredentials = async (sessionId: string, actor: OrgServiceActor) => {- // To be hit by gateways only- if (actor.type !== ActorType.IDENTITY) {+ // To be hit by gateways only (identity-based or enrollment-flow)+ if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });}@@ -956,19 +956,21 @@ export const pamAccountServiceFactory = ({const project = await projectDAL.findById(session.projectId);if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });- const { permission } = await permissionService.getOrgPermission({- actor: actor.type,- actorId: actor.id,- orgId: project.orgId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- scope: OrganizationActionScope.Any- });+ if (actor.type === ActorType.IDENTITY) {+ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: project.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionGatewayActions.CreateGateways,- OrgPermissionSubjects.Gateway- );+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.CreateGateways,+ OrgPermissionSubjects.Gateway+ );+ }if (!session.accountId) throw new NotFoundError({ message: "Session is missing accountId column" });@@ -983,10 +985,16 @@ export const pamAccountServiceFactory = ({const resource = await pamResourceDAL.findById(account.resourceId);if (!resource) throw new NotFoundError({ message: `Resource with ID '${account.resourceId}' not found` });- if (resource.gatewayId && resource.gatewayIdentityId !== actor.id) {- throw new ForbiddenRequestError({- message: "Identity does not have access to fetch the PAM session credentials"- });+ if (resource.gatewayId) {+ const authorized =+ actor.type === ActorType.GATEWAY+ ? resource.gatewayId === actor.id+ : resource.gatewayIdentityId === actor.id;+ if (!authorized) {+ throw new ForbiddenRequestError({+ message: "Gateway does not have access to fetch the PAM session credentials"+ });+ }}const decryptedAccount = await decryptAccount(account, session.projectId, kmsService);diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex ec5f681b7e..a9f3a79a39 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -122,8 +122,8 @@ export const pamSessionServiceFactory = ({};const updateLogsById = async ({ sessionId, logs }: TUpdateSessionLogsDTO, actor: OrgServiceActor) => {- // To be hit by gateways only- if (actor.type !== ActorType.IDENTITY) {+ // To be hit by gateways only (identity-based or enrollment-flow)+ if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });}@@ -137,19 +137,21 @@ export const pamSessionServiceFactory = ({const project = await projectDAL.findById(session.projectId);if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });- const { permission } = await permissionService.getOrgPermission({- actor: actor.type,- actorId: actor.id,- orgId: project.orgId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- scope: OrganizationActionScope.Any- });+ if (actor.type === ActorType.IDENTITY) {+ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: project.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionGatewayActions.CreateGateways,- OrgPermissionSubjects.Gateway- );+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.CreateGateways,+ OrgPermissionSubjects.Gateway+ );+ }if (session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {throw new ForbiddenRequestError({ message: "Identity does not have access to update logs for this session" });@@ -178,16 +180,16 @@ export const pamSessionServiceFactory = ({const project = await projectDAL.findById(session.projectId);if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });- const { permission } = await permissionService.getOrgPermission({- actor: actor.type,- actorId: actor.id,- orgId: project.orgId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- scope: OrganizationActionScope.Any- });-if (actor.type === ActorType.IDENTITY) {+ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: project.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });+ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGatewayActions.CreateGateways,OrgPermissionSubjects.Gateway@@ -196,12 +198,17 @@ export const pamSessionServiceFactory = ({if (session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {throw new ForbiddenRequestError({ message: "Identity does not have access to end this session" });}+ } else if (actor.type === ActorType.GATEWAY) {+ // Enrollment-flow gateways authenticate directly; JWT proves org membership.+ if (session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Gateway does not have access to end this session" });+ }} else if (actor.type === ActorType.USER) {if (session.userId !== actor.id) {throw new ForbiddenRequestError({ message: "You are not authorized to end this session" });}} else {- throw new ForbiddenRequestError({ message: "Only identities and users can perform this action" });+ throw new ForbiddenRequestError({ message: "Only gateways and users can perform this action" });}const updatedSession = await pamSessionDAL.endSessionById(sessionId);@@ -337,7 +344,8 @@ export const pamSessionServiceFactory = ({};const uploadEventBatch = async ({ sessionId, startOffset, events }: TUploadEventBatchDTO, actor: OrgServiceActor) => {- if (actor.type !== ActorType.IDENTITY) {+ // To be hit by gateways only (identity-based or enrollment-flow)+ if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {throw new ForbiddenRequestError({ message: "Only gateways can perform this action" });}@@ -347,19 +355,21 @@ export const pamSessionServiceFactory = ({const project = await projectDAL.findById(session.projectId);if (!project) throw new NotFoundError({ message: `Project with ID '${session.projectId}' not found` });- const { permission } = await permissionService.getOrgPermission({- actor: actor.type,- actorId: actor.id,- orgId: project.orgId,- actorAuthMethod: actor.authMethod,- actorOrgId: actor.orgId,- scope: OrganizationActionScope.Any- });+ if (actor.type === ActorType.IDENTITY) {+ const { permission } = await permissionService.getOrgPermission({+ actor: actor.type,+ actorId: actor.id,+ orgId: project.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId,+ scope: OrganizationActionScope.Any+ });- ForbiddenError.from(permission).throwUnlessCan(- OrgPermissionGatewayActions.CreateGateways,- OrgPermissionSubjects.Gateway- );+ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.CreateGateways,+ OrgPermissionSubjects.Gateway+ );+ }if (session.gatewayIdentityId && session.gatewayIdentityId !== actor.id) {throw new ForbiddenRequestError({ message: "Identity does not have access to upload events for this session" });diff --git a/backend/src/server/plugins/audit-log.ts b/backend/src/server/plugins/audit-log.tsindex 9fb14e97cb..839d83d175 100644--- a/backend/src/server/plugins/audit-log.ts+++ b/backend/src/server/plugins/audit-log.ts@@ -84,6 +84,13 @@ export const injectAuditLogInfo = fp(async (server: FastifyZodProvider) => {type: ActorType.SCIM_CLIENT,metadata: {}};+ } else if (req.auth.actor === ActorType.GATEWAY) {+ payload.actor = {+ type: ActorType.GATEWAY,+ metadata: {+ gatewayId: req.permission.id+ }+ };} else {throw new BadRequestError({ message: "Invalid actor type provided" });}diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex b155a12dfb..0b911f8d1d 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -8,7 +8,14 @@ import { TScimTokenJwtPayload } from "@app/ee/services/scim/scim-types";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";import { BadRequestError } from "@app/lib/errors";-import { ActorType, AuthMethod, AuthMode, AuthModeJwtTokenPayload, AuthTokenType } from "@app/services/auth/auth-type";+import {+ ActorType,+ AuthMethod,+ AuthMode,+ AuthModeJwtTokenPayload,+ AuthTokenType,+ TGatewayAccessTokenJwtPayload+} from "@app/services/auth/auth-type";import { TIdentityAccessTokenJwtPayload } from "@app/services/identity-access-token/identity-access-token-types";import { getServerCfg } from "@app/services/super-admin/super-admin-service";@@ -68,6 +75,16 @@ export type TAuthMode =rootOrgId: string;parentOrgId: string;authMethod: null;+ }+ | {+ authMode: AuthMode.GATEWAY_ACCESS_TOKEN;+ actor: ActorType.GATEWAY;+ gatewayId: string;+ orgId: string;+ rootOrgId: string;+ parentOrgId: string;+ authMethod: null;+ token: TGatewayAccessTokenJwtPayload;};export const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {@@ -120,6 +137,12 @@ export const extractAuth = async (req: FastifyRequest, jwtSecret: string) => {token: decodedToken as TScimTokenJwtPayload,actor: ActorType.SCIM_CLIENT} as const;+ case AuthTokenType.GATEWAY_ACCESS_TOKEN:+ return {+ authMode: AuthMode.GATEWAY_ACCESS_TOKEN,+ token: decodedToken as TGatewayAccessTokenJwtPayload,+ actor: ActorType.GATEWAY+ } as const;default:return { authMode: null, token: null } as const;}@@ -163,6 +186,11 @@ export const injectIdentity = fp(return;}+ // Authentication is handled on a route-level (enrollment token in body)+ if (req.url === "/api/v2/gateways/enroll") {+ return;+ }+// Authentication is handled on a route-levelif (req.url === "/api/v1/relays/heartbeat-instance-relay") {return;@@ -307,6 +335,23 @@ export const injectIdentity = fp(};break;}+ case AuthMode.GATEWAY_ACCESS_TOKEN: {+ // Validate gateway exists — deletion is the revocation mechanism+ const gateway = await server.services.gatewayV2.getGatewayById({ gatewayId: token.gatewayId });+ requestContext.set("orgId", token.orgId);++ req.auth = {+ authMode: AuthMode.GATEWAY_ACCESS_TOKEN,+ actor,+ gatewayId: token.gatewayId,+ orgId: token.orgId,+ rootOrgId: token.orgId,+ parentOrgId: token.orgId,+ authMethod: null,+ token+ };+ break;+ }default:throw new BadRequestError({ message: "Invalid token strategy provided" });}diff --git a/backend/src/server/plugins/auth/inject-permission.ts b/backend/src/server/plugins/auth/inject-permission.tsindex 827a055d3c..b19f7cd97a 100644--- a/backend/src/server/plugins/auth/inject-permission.ts+++ b/backend/src/server/plugins/auth/inject-permission.ts@@ -61,6 +61,19 @@ export const injectPermission = fp(async (server) => {logger.info(`injectPermission: Injecting permissions for [permissionsForIdentity=${req.auth.scimTokenId}] [type=${ActorType.SCIM_CLIENT}]`);+ } else if (req.auth.actor === ActorType.GATEWAY) {+ req.permission = {+ type: ActorType.GATEWAY,+ id: req.auth.gatewayId,+ orgId: req.auth.orgId,+ rootOrgId: req.auth.rootOrgId,+ parentOrgId: req.auth.parentOrgId,+ authMethod: null+ };++ logger.info(+ `injectPermission: Injecting permissions for [permissionsForGateway=${req.auth.gatewayId}] [type=${ActorType.GATEWAY}]`+ );}});});diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 7d51408344..2dc1558307 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -56,6 +56,7 @@ import { externalKmsServiceFactory } from "@app/ee/services/external-kms/externaimport { gatewayDALFactory } from "@app/ee/services/gateway/gateway-dal";import { gatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";import { orgGatewayConfigDALFactory } from "@app/ee/services/gateway/org-gateway-config-dal";+import { gatewayEnrollmentTokenDALFactory } from "@app/ee/services/gateway-v2/gateway-enrollment-token-dal";import { gatewayV2DalFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";import { gatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";import { orgGatewayConfigV2DalFactory } from "@app/ee/services/gateway-v2/org-gateway-config-v2-dal";@@ -1271,6 +1272,7 @@ export const registerRoutes = async (const orgRelayConfigDAL = orgRelayConfigDalFactory(db);const relayDAL = relayDalFactory(db);const gatewayV2DAL = gatewayV2DalFactory(db);+ const gatewayEnrollmentTokenDAL = gatewayEnrollmentTokenDALFactory(db);const approvalPolicyDAL = approvalPolicyDALFactory(db);@@ -1429,6 +1431,7 @@ export const registerRoutes = async (relayService,orgGatewayConfigV2DAL,gatewayV2DAL,+ gatewayEnrollmentTokenDAL,relayDAL,permissionService,orgDAL,diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex 280433ffa4..a3e46f2932 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -22,7 +22,8 @@ export enum AuthTokenType {SERVICE_ACCESS_TOKEN = "serviceAccessToken",SERVICE_REFRESH_TOKEN = "serviceRefreshToken",IDENTITY_ACCESS_TOKEN = "identityAccessToken",- SCIM_TOKEN = "scimToken"+ SCIM_TOKEN = "scimToken",+ GATEWAY_ACCESS_TOKEN = "gatewayAccessToken"}export enum AuthMode {@@ -31,7 +32,8 @@ export enum AuthMode {API_KEY = "apiKey",IDENTITY_ACCESS_TOKEN = "identityAccessToken",SCIM_TOKEN = "scimToken",- MCP_JWT = "mcpJwt"+ MCP_JWT = "mcpJwt",+ GATEWAY_ACCESS_TOKEN = "gatewayAccessToken"}export enum ActorType { // would extend to AWS, Azure, ...@@ -45,9 +47,16 @@ export enum ActorType { // would extend to AWS, Azure, ...ACME_ACCOUNT = "acmeAccount",EST_ACCOUNT = "estAccount",SCEP_ACCOUNT = "scepAccount",- UNKNOWN_USER = "unknownUser"+ UNKNOWN_USER = "unknownUser",+ GATEWAY = "gateway"}+export type TGatewayAccessTokenJwtPayload = {+ authTokenType: AuthTokenType.GATEWAY_ACCESS_TOKEN;+ gatewayId: string;+ orgId: string;+};+// This will be null unless the token-type is JWTexport type ActorAuthMethod = AuthMethod | null;diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex 9a72395185..5e0b3547a9 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -3,6 +3,7 @@ import {AcmeAccountActor,AcmeProfileActor,EstAccountActor,+ GatewayActor,IdentityActor,KmipClientActor,PlatformActor,@@ -132,7 +133,8 @@ export type TSecretModifiedEvent = {| AcmeProfileActor| KmipClientActor| EstAccountActor- | ScepAccountActor;+ | ScepAccountActor+ | GatewayActor;};};diff --git a/frontend/src/hooks/api/gateways-v2/mutations.tsx b/frontend/src/hooks/api/gateways-v2/mutations.tsxindex 574f15c737..47674722ca 100644--- a/frontend/src/hooks/api/gateways-v2/mutations.tsx+++ b/frontend/src/hooks/api/gateways-v2/mutations.tsx@@ -3,6 +3,9 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { gatewaysQueryKeys } from "../gateways/queries";+import { TCreateGatewayEnrollmentTokenResponse } from "./types";++export const gatewayEnrollmentTokenQueryKey = () => ["gateway-enrollment-tokens"];export const useDeleteGatewayV2ById = () => {const queryClient = useQueryClient();@@ -27,3 +30,31 @@ export const useTriggerGatewayV2Heartbeat = () => {}});};++export const useCreateGatewayEnrollmentToken = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ name, ttlSeconds }: { name: string; ttlSeconds?: number }) => {+ const { data } = await apiRequest.post<TCreateGatewayEnrollmentTokenResponse>(+ "/api/v2/gateways/enrollment-tokens",+ { name, ttlSeconds }+ );+ return data;+ },+ onSuccess: () => {+ queryClient.invalidateQueries(gatewaysQueryKeys.list());+ }+ });+};++export const useDeleteGatewayEnrollmentToken = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (tokenId: string) => {+ await apiRequest.delete(`/api/v2/gateways/enrollment-tokens/${tokenId}`);+ },+ onSuccess: () => {+ queryClient.invalidateQueries(gatewaysQueryKeys.list());+ }+ });+};diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.tsindex 33d13345aa..e69ae6a462 100644--- a/frontend/src/hooks/api/gateways-v2/types.ts+++ b/frontend/src/hooks/api/gateways-v2/types.ts@@ -5,17 +5,30 @@ export enum GatewayHealthCheckStatus {export type TGatewayV2 = {id: string;- identityId: string;+ identityId: string | null;name: string;createdAt: string;updatedAt: string;- heartbeat: string;+ heartbeat: string | null;lastHealthCheckStatus: GatewayHealthCheckStatus | null;connectedResourcesCount: number;identity: {name: string;id: string;- };+ } | null;+};++export type TGatewayEnrollmentToken = {+ id: string;+ name: string;+ ttl: number;+ expiresAt: string;+ usedAt: string | null;+ createdAt: string;+};++export type TCreateGatewayEnrollmentTokenResponse = TGatewayEnrollmentToken & {+ token: string;};export type TGatewayConnectedAppConnection = {diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsxindex ef4dafb75b..9c19ba6c75 100644--- a/frontend/src/hooks/api/gateways/queries.tsx+++ b/frontend/src/hooks/api/gateways/queries.tsx@@ -2,7 +2,7 @@ import { queryOptions } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { TGatewayV2 } from "../gateways-v2/types";+import { TGatewayEnrollmentToken, TGatewayV2 } from "../gateways-v2/types";import { TGateway } from "./types";export const gatewaysQueryKeys = {@@ -12,19 +12,39 @@ export const gatewaysQueryKeys = {queryOptions({queryKey: gatewaysQueryKeys.listKey(),queryFn: async () => {- const [{ data }, { data: dataV2 }] = await Promise.all([+ const [{ data }, { data: dataV2 }, { data: enrollmentTokens }] = await Promise.all([apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"),- apiRequest.get<TGatewayV2[]>("/api/v2/gateways")+ apiRequest.get<TGatewayV2[]>("/api/v2/gateways"),+ apiRequest.get<TGatewayEnrollmentToken[]>("/api/v2/gateways/enrollment-tokens")]);+ // Build a set of names that already have a real gateway (enrolled + registered)+ const enrolledNames = new Set(dataV2.map((g) => g.name));++ // Pending tokens: unused, not expired, and not already enrolled as a gateway+ const now = new Date();+ const pendingTokens = enrollmentTokens.filter(+ (t) => !t.usedAt && new Date(t.expiresAt) > now && !enrolledNames.has(t.name)+ );+return [...data.gateways.map((g) => ({...g,- isV1: true+ isV1: true as const,+ isPending: false as const})),...dataV2.map((g) => ({...g,- isV1: false+ isV1: false as const,+ isPending: false as const+ })),+ ...pendingTokens.map((t) => ({+ id: t.id,+ name: t.name,+ createdAt: t.createdAt,+ expiresAt: t.expiresAt,+ isV1: false as const,+ isPending: true as const}))];}diff --git a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsxindex e63dc7e328..44acddee8b 100644--- a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx@@ -64,13 +64,14 @@ export const NetworkHealthBanner = () => {const unreachableGateways = useMemo(() =>gateways?.filter((g) => {+ if (g.isPending) return false;if ("lastHealthCheckStatus" in g &&g.lastHealthCheckStatus === GatewayHealthCheckStatus.Failed) {return true;}- return isHeartbeatStale(g.heartbeat);+ return "heartbeat" in g && isHeartbeatStale(g.heartbeat);}).length ?? 0,[gateways]);diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsxindex 7c1a5e5d59..f514841615 100644--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx@@ -1,5 +1,6 @@import { useState } from "react";import {+ faClock,faCopy,faDoorClosed,faEdit,@@ -46,7 +47,11 @@ import {import { withPermission } from "@app/hoc";import { usePopUp } from "@app/hooks";import { gatewaysQueryKeys, useDeleteGatewayById } from "@app/hooks/api/gateways";-import { useDeleteGatewayV2ById, useTriggerGatewayV2Heartbeat } from "@app/hooks/api/gateways-v2";+import {+ useDeleteGatewayEnrollmentToken,+ useDeleteGatewayV2ById,+ useTriggerGatewayV2Heartbeat+} from "@app/hooks/api/gateways-v2";import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";import { EditGatewayDetailsModal } from "./components/EditGatewayDetailsModal";@@ -55,11 +60,32 @@ import { GatewayDeployModal } from "./components/GatewayDeployModal";const GatewayHealthStatus = ({heartbeat,- lastHealthCheckStatus+ lastHealthCheckStatus,+ isPending}: {- heartbeat?: string;+ heartbeat?: string | null;lastHealthCheckStatus?: GatewayHealthCheckStatus | null;+ isPending?: boolean;}) => {+ if (isPending) {+ return (+ <Tooltip content="Waiting for gateway to enroll using the CLI command">+ <span className="inline-flex cursor-default items-center gap-1.5 text-yellow-500">+ <FontAwesomeIcon icon={faClock} className="size-3" />+ Pending+ </span>+ </Tooltip>+ );+ }++ if (!heartbeat && !lastHealthCheckStatus) {+ return (+ <Tooltip content="Gateway has not connected yet">+ <span className="cursor-default text-yellow-500">Unregistered</span>+ </Tooltip>+ );+ }+const heartbeatDate = heartbeat ? new Date(heartbeat) : null;const isHealthy = lastHealthCheckStatus === GatewayHealthCheckStatus.Healthy;@@ -123,6 +149,7 @@ export const GatewayTab = withPermission(const deleteGatewayById = useDeleteGatewayById();const deleteGatewayV2ById = useDeleteGatewayV2ById();+ const deleteEnrollmentToken = useDeleteGatewayEnrollmentToken();const triggerGatewayV2Heartbeat = useTriggerGatewayV2Heartbeat();const handleTriggerHealthCheck = async (id: string) => {@@ -141,8 +168,14 @@ export const GatewayTab = withPermission(};const handleDeleteGateway = async () => {- const data = popUp.deleteGateway.data as { id: string; isV1: boolean };- if (data.isV1) {+ const data = popUp.deleteGateway.data as {+ id: string;+ isV1: boolean;+ isPending: boolean;+ };+ if (data.isPending) {+ await deleteEnrollmentToken.mutateAsync(data.id);+ } else if (data.isV1) {await deleteGatewayById.mutateAsync(data.id);} else {await deleteGatewayV2ById.mutateAsync(data.id);@@ -151,7 +184,9 @@ export const GatewayTab = withPermission(handlePopUpToggle("deleteGateway");createNotification({type: "success",- text: "Successfully deleted gateway"+ text: data.isPending+ ? "Successfully deleted enrollment token"+ : "Successfully deleted gateway"});};@@ -216,29 +251,40 @@ export const GatewayTab = withPermission(<Td><div className="flex items-center gap-2"><span>{el.name}</span>- <span className="rounded-sm bg-mineshaft-700 px-1.5 py-0.5 text-xs text-mineshaft-400">- Gateway v{el.isV1 ? "1" : "2"}- </span>+ {el.isPending ? (+ <span className="rounded-sm bg-yellow-900/30 px-1.5 py-0.5 text-xs text-yellow-500">+ Pending+ </span>+ ) : (+ <span className="rounded-sm bg-mineshaft-700 px-1.5 py-0.5 text-xs text-mineshaft-400">+ Gateway v{el.isV1 ? "1" : "2"}+ </span>+ )}</div></Td><Td>- <GatewayConnectedCell- isV1={el.isV1}- connectedResourcesCount={- "connectedResourcesCount" in el ? el.connectedResourcesCount : 0- }- onClick={() => {- setSelectedGateway({ id: el.id, name: el.name });- handlePopUpOpen("connectedResources");- }}- />+ {el.isPending ? (+ <span className="text-mineshaft-400">—</span>+ ) : (+ <GatewayConnectedCell+ isV1={el.isV1}+ connectedResourcesCount={+ "connectedResourcesCount" in el ? el.connectedResourcesCount : 0+ }+ onClick={() => {+ setSelectedGateway({ id: el.id, name: el.name });+ handlePopUpOpen("connectedResources");+ }}+ />+ )}</Td><Td><GatewayHealthStatus- heartbeat={el.heartbeat}+ heartbeat={"heartbeat" in el ? el.heartbeat : null}lastHealthCheckStatus={"lastHealthCheckStatus" in el ? el.lastHealthCheckStatus : null}+ isPending={el.isPending}/></Td><Td className="w-5">@@ -261,7 +307,7 @@ export const GatewayTab = withPermission(>Copy ID</DropdownMenuItem>- {!el.isV1 && (+ {!el.isV1 && !el.isPending && (<DropdownMenuItemicon={<FontAwesomeIcon icon={faHeartPulse} />}onClick={() => handleTriggerHealthCheck(el.id)}@@ -296,7 +342,7 @@ export const GatewayTab = withPermission(className="text-red"onClick={() => handlePopUpOpen("deleteGateway", el)}>- Delete Gateway+ {el.isPending ? "Delete Token" : "Delete Gateway"}</DropdownMenuItem>)}</OrgPermissionCan>@@ -331,9 +377,11 @@ export const GatewayTab = withPermission()}<DeleteActionModalisOpen={popUp.deleteGateway.isOpen}- title={`Are you sure you want to delete gateway ${- (popUp?.deleteGateway?.data as { name: string })?.name || ""- }?`}+ title={`Are you sure you want to delete ${+ (popUp?.deleteGateway?.data as { isPending?: boolean })?.isPending+ ? "enrollment token"+ : "gateway"+ } ${(popUp?.deleteGateway?.data as { name: string })?.name || ""}?`}onChange={(isOpen) => handlePopUpToggle("deleteGateway", isOpen)}deleteKey="confirm"onDeleteApproved={() => handleDeleteGateway()}diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsxindex 4a654dc9d3..016a46da90 100644--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx@@ -1,6 +1,6 @@import { useMemo, useState } from "react";import { SingleValue } from "react-select";-import { faCopy, faQuestionCircle, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";+import { faCopy, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNavigate } from "@tanstack/react-router";import { z } from "zod";@@ -8,188 +8,88 @@ import { z } from "zod";import { createNotification } from "@app/components/notifications";import {Button,- Checkbox,FilterableSelect,FormLabel,IconButton,Input,- ModalClose,- Tooltip+ ModalClose} from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";-import {- OrgPermissionIdentityActions,- OrgPermissionSubjects,- useOrganization,- useOrgPermission-} from "@app/context";-import {- useAddIdentityTokenAuth,- useCreateTokenIdentityTokenAuth,- useGetIdentityMembershipOrgs,- useGetIdentityTokenAuth,- useGetRelays-} from "@app/hooks/api";-import { safeJWTSchema, slugSchema } from "@app/lib/schemas";+import { useCreateGatewayEnrollmentToken } from "@app/hooks/api/gateways-v2";+import { useGetRelays } from "@app/hooks/api/relays/queries";+import { slugSchema } from "@app/lib/schemas";import { RelayOption } from "./RelayOption";-const baseFormSchema = z.object({+const formSchema = z.object({name: slugSchema({ field: "name" }),relay: z- .object(- {- id: z.string(),- name: z.string()- },- { required_error: "Relay is required" }- )+ .object({ id: z.string(), name: z.string() }, { required_error: "Relay is required" }).nullable().refine((val) => val !== null, { message: "Relay is required" })});-const formSchemaWithIdentity = baseFormSchema.extend({- identity: z- .object(- {- id: z.string(),- name: z.string()- },- { required_error: "Machine identity is required" }- )- .nullable()- .refine((val) => val !== null, { message: "Machine identity is required" })-});--const formSchemaWithToken = baseFormSchema.extend({- identityToken: safeJWTSchema-});-export const GatewayCliDeploymentMethod = () => {const { protocol, hostname, port } = window.location;const portSuffix = port && port !== "80" ? `:${port}` : "";const siteURL = `${protocol}//${hostname}${portSuffix}`;- const navigate = useNavigate({- from: ROUTE_PATHS.Organization.NetworkingPage.path- });+ const navigate = useNavigate({ from: ROUTE_PATHS.Organization.NetworkingPage.path });- const [autogenerateToken, setAutogenerateToken] = useState(true);const [step, setStep] = useState<"form" | "command">("form");const [name, setName] = useState("");- const [relay, setRelay] = useState<null | {- id: string;- name: string;- }>({ id: "_auto", name: "Auto Select Relay" });- const [identity, setIdentity] = useState<null | {- id: string;- name: string;- }>(null);- const [identityToken, setIdentityToken] = useState("");+ const [relay, setRelay] = useState<null | { id: string; name: string }>({+ id: "_auto",+ name: "Auto Select Relay"+ });+ const [enrollmentToken, setEnrollmentToken] = useState("");+ const [resolvedRelayName, setResolvedRelayName] = useState("");const [formErrors, setFormErrors] = useState<z.ZodIssue[]>([]);const errors = useMemo(() => {const errorMap: Record<string, string | undefined> = {};formErrors.forEach((issue) => {- if (issue.path.length > 0) {- errorMap[String(issue.path[0])] = issue.message;- }+ if (issue.path.length > 0) errorMap[String(issue.path[0])] = issue.message;});return errorMap;}, [formErrors]);const { data: relays, isPending: isRelaysLoading } = useGetRelays();+ const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =+ useCreateGatewayEnrollmentToken();- const { currentOrg } = useOrganization();- const organizationId = currentOrg?.id || "";-- const { permission } = useOrgPermission();- const canCreateToken = permission.can(- OrgPermissionIdentityActions.CreateToken,- OrgPermissionSubjects.Identity- );-- const { data: identityMembershipOrgsData, isPending: isIdentitiesLoading } =- useGetIdentityMembershipOrgs({- organizationId,- limit: 20000- });- const identityMembershipOrgs = identityMembershipOrgsData?.identityMemberships || [];-- const { mutateAsync: createToken, isPending: isCreatingToken } =- useCreateTokenIdentityTokenAuth();- const { mutateAsync: addIdentityTokenAuth, isPending: isAddingTokenAuth } =- useAddIdentityTokenAuth();- const { refetch } = useGetIdentityTokenAuth(identity?.id ?? "");-- const handleGenerateCommand = async () => {+ const handleContinue = async () => {setFormErrors([]);+ const validation = formSchema.safeParse({ name, relay });+ if (!validation.success) {+ setFormErrors(validation.error.issues);+ return;+ }- if (canCreateToken && autogenerateToken) {- const validation = formSchemaWithIdentity.safeParse({- name,- relay,- identity- });- if (!validation.success) {- setFormErrors(validation.error.issues);- return;- }-- const validatedIdentity = validation.data.identity;-- try {- const { data: identityTokenAuth } = await refetch();- if (!identityTokenAuth) {- await addIdentityTokenAuth({- identityId: validatedIdentity.id,- organizationId,- accessTokenTTL: 2592000,- accessTokenMaxTTL: 2592000,- accessTokenNumUsesLimit: 0,- accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]- });- createNotification({- text: "Token authentication has been automatically enabled for the selected identity. By default, it is configured to allow all IP addresses with a default token TTL of 30 days. You can manage these settings in Access Control.",- type: "warning"- });- }+ try {+ const result = await createEnrollmentToken({ name });+ setEnrollmentToken(result.token);- const token = await createToken({- identityId: validatedIdentity.id,- name: `gateway token for ${name} (autogenerated)`- });- setIdentityToken(token.accessToken);- createNotification({- text: "Automatically generated a token for the selected identity.",- type: "info"- });- setStep("command");- } catch {- setIdentityToken("");- }- } else {- const validation = formSchemaWithToken.safeParse({- name,- relay,- identityToken- });- if (!validation.success) {- setFormErrors(validation.error.issues);- return;- }+ const relayName = relay?.id === "_auto" ? "" : relay?.name ?? "";+ setResolvedRelayName(relayName);setStep("command");+ } catch {+ createNotification({ type: "error", text: "Failed to create enrollment token" });}};const command = useMemo(() => {- const relayPart = relay?.id !== "_auto" ? ` --target-relay-name=${relay?.name || ""}` : "";- return `sudo infisical gateway start --name=${name}${relayPart} --domain=${siteURL} --token=${identityToken}`;- }, [name, relay, identityToken, siteURL]);+ const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";+ return `infisical gateway start --enroll-method=static --token=${enrollmentToken}${relayPart} --domain=${siteURL}`;+ }, [enrollmentToken, resolvedRelayName, siteURL]);if (step === "command") {return (<>+ <p className="mb-3 text-sm text-mineshaft-300">+ Run the following command on the machine where you want to deploy the gateway. The token+ expires in 1 hour and can only be used once.+ </p><FormLabel label="CLI Command" /><div className="flex gap-2"><Input value={command} isDisabled />@@ -199,10 +99,7 @@ export const GatewayCliDeploymentMethod = () => {colorSchema="secondary"onClick={() => {navigator.clipboard.writeText(command);- createNotification({- text: "Command copied to clipboard",- type: "info"- });+ createNotification({ text: "Command copied to clipboard", type: "info" });}}className="w-10">@@ -250,19 +147,12 @@ export const GatewayCliDeploymentMethod = () => {});return;}-setRelay(newValue as SingleValue<{ id: string; name: string }>);}}isLoading={isRelaysLoading}options={[- {- id: "_auto",- name: "Auto Select Relay"- },- {- id: "_create",- name: "Deploy New Relay"- },+ { id: "_auto", name: "Auto Select Relay" },+ { id: "_create", name: "Deploy New Relay" },...(relays || [])]}placeholder="Select relay..."@@ -272,87 +162,13 @@ export const GatewayCliDeploymentMethod = () => {/>{errors.relay && <p className="mt-1 text-sm text-red">{errors.relay}</p>}- {canCreateToken && autogenerateToken ? (- <>- <FormLabel- label="Machine Identity"- tooltipText="The machine identity that your gateway will use for authentication."- className="mt-4"- />- <FilterableSelect- value={identity}- onChange={(e) =>- setIdentity(- e as SingleValue<{- id: string;- name: string;- }>- )- }- isLoading={isIdentitiesLoading}- placeholder="Select machine identity..."- options={identityMembershipOrgs.map((membership) => membership.identity)}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- />- {errors.identity && <p className="mt-1 text-sm text-red">{errors.identity}</p>}- </>- ) : (- <>- <FormLabel- label="Machine Identity Token"- tooltipText="The machine identity token that your gateway will use for authentication."- className="mt-4"- />- <Input- value={identityToken}- onChange={(e) => setIdentityToken(e.target.value)}- placeholder="Enter machine identity token..."- isError={Boolean(errors.identityToken)}- />- {errors.identityToken && <p className="mt-1 text-sm text-red">{errors.identityToken}</p>}- </>- )}-- {canCreateToken && (- <div className="mt-2">- <Checkbox- isChecked={autogenerateToken}- onCheckedChange={(e) => {- setAutogenerateToken(Boolean(e));- }}- id="autogenerate-token"- className="mr-2"- >- <div className="flex items-center">- <span>Automatically enable token auth and generate a token for machine identity</span>- <Tooltip- className="max-w-md"- content={- <>- Token authentication will be automatically enabled for the selected machine- identity if it isn't already configured. By default, it will be configured- to allow all IP addresses with a token TTL of 30 days. You can manage these- settings in Access Control.- <br />- <br />A token will automatically be generated to be used with the CLI command.- </>- }- >- <FontAwesomeIcon icon={faQuestionCircle} size="sm" className="mt-0.5 ml-1" />- </Tooltip>- </div>- </Checkbox>- </div>- )}-<div className="mt-6 flex items-center"><ButtonclassName="mr-4"size="sm"colorSchema="secondary"- onClick={handleGenerateCommand}- isLoading={isCreatingToken || isAddingTokenAuth}+ onClick={handleContinue}+ isLoading={isCreatingToken}>Continue</Button>diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsxindex 3b0c458f96..0125bde58f 100644--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx@@ -1,6 +1,6 @@import { useMemo, useState } from "react";import { SingleValue } from "react-select";-import { faCopy, faQuestionCircle, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";+import { faCopy, faUpRightFromSquare } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { useNavigate } from "@tanstack/react-router";import { z } from "zod";@@ -8,190 +8,90 @@ import { z } from "zod";import { createNotification } from "@app/components/notifications";import {Button,- Checkbox,FilterableSelect,FormLabel,IconButton,Input,- ModalClose,- Tooltip+ ModalClose} from "@app/components/v2";import { ROUTE_PATHS } from "@app/const/routes";-import {- OrgPermissionIdentityActions,- OrgPermissionSubjects,- useOrganization,- useOrgPermission-} from "@app/context";-import {- useAddIdentityTokenAuth,- useCreateTokenIdentityTokenAuth,- useGetIdentityMembershipOrgs,- useGetIdentityTokenAuth,- useGetRelays-} from "@app/hooks/api";-import { safeJWTSchema, slugSchema } from "@app/lib/schemas";+import { useCreateGatewayEnrollmentToken } from "@app/hooks/api/gateways-v2";+import { useGetRelays } from "@app/hooks/api/relays/queries";+import { slugSchema } from "@app/lib/schemas";import { RelayOption } from "./RelayOption";-const baseFormSchema = z.object({+const formSchema = z.object({name: slugSchema({ field: "name" }),relay: z- .object(- {- id: z.string(),- name: z.string()- },- { required_error: "Relay is required" }- )+ .object({ id: z.string(), name: z.string() }, { required_error: "Relay is required" }).nullable().refine((val) => val !== null, { message: "Relay is required" })});-const formSchemaWithIdentity = baseFormSchema.extend({- identity: z- .object(- {- id: z.string(),- name: z.string()- },- { required_error: "Machine identity is required" }- )- .nullable()- .refine((val) => val !== null, { message: "Machine identity is required" })-});--const formSchemaWithToken = baseFormSchema.extend({- identityToken: safeJWTSchema-});-export const GatewayCliSystemdDeploymentMethod = () => {const { protocol, hostname, port } = window.location;const portSuffix = port && port !== "80" ? `:${port}` : "";const siteURL = `${protocol}//${hostname}${portSuffix}`;- const navigate = useNavigate({- from: ROUTE_PATHS.Organization.NetworkingPage.path- });+ const navigate = useNavigate({ from: ROUTE_PATHS.Organization.NetworkingPage.path });- const [autogenerateToken, setAutogenerateToken] = useState(true);const [step, setStep] = useState<"form" | "command">("form");const [name, setName] = useState("");- const [relay, setRelay] = useState<null | {- id: string;- name: string;- }>({ id: "_auto", name: "Auto Select Relay" });- const [identity, setIdentity] = useState<null | {- id: string;- name: string;- }>(null);- const [identityToken, setIdentityToken] = useState("");+ const [relay, setRelay] = useState<null | { id: string; name: string }>({+ id: "_auto",+ name: "Auto Select Relay"+ });+ const [enrollmentToken, setEnrollmentToken] = useState("");+ const [resolvedRelayName, setResolvedRelayName] = useState("");const [formErrors, setFormErrors] = useState<z.ZodIssue[]>([]);const errors = useMemo(() => {const errorMap: Record<string, string | undefined> = {};formErrors.forEach((issue) => {- if (issue.path.length > 0) {- errorMap[String(issue.path[0])] = issue.message;- }+ if (issue.path.length > 0) errorMap[String(issue.path[0])] = issue.message;});return errorMap;}, [formErrors]);const { data: relays, isPending: isRelaysLoading } = useGetRelays();+ const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =+ useCreateGatewayEnrollmentToken();- const { currentOrg } = useOrganization();- const organizationId = currentOrg?.id || "";-- const { permission } = useOrgPermission();- const canCreateToken = permission.can(- OrgPermissionIdentityActions.CreateToken,- OrgPermissionSubjects.Identity- );-- const { data: identityMembershipOrgsData, isPending: isIdentitiesLoading } =- useGetIdentityMembershipOrgs({- organizationId,- limit: 20000- });- const identityMembershipOrgs = identityMembershipOrgsData?.identityMemberships || [];-- const { mutateAsync: createToken, isPending: isCreatingToken } =- useCreateTokenIdentityTokenAuth();- const { mutateAsync: addIdentityTokenAuth, isPending: isAddingTokenAuth } =- useAddIdentityTokenAuth();- const { refetch } = useGetIdentityTokenAuth(identity?.id ?? "");-- const handleGenerateCommand = async () => {+ const handleContinue = async () => {setFormErrors([]);+ const validation = formSchema.safeParse({ name, relay });+ if (!validation.success) {+ setFormErrors(validation.error.issues);+ return;+ }- if (canCreateToken && autogenerateToken) {- const validation = formSchemaWithIdentity.safeParse({- name,- relay,- identity- });- if (!validation.success) {- setFormErrors(validation.error.issues);- return;- }-- const validatedIdentity = validation.data.identity;-- try {- const { data: identityTokenAuth } = await refetch();- if (!identityTokenAuth) {- await addIdentityTokenAuth({- identityId: validatedIdentity.id,- organizationId,- accessTokenTTL: 2592000,- accessTokenMaxTTL: 2592000,- accessTokenNumUsesLimit: 0,- accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]- });- createNotification({- text: "Token authentication has been automatically enabled for the selected identity. By default, it is configured to allow all IP addresses with a default token TTL of 30 days. You can manage these settings in Access Control.",- type: "warning"- });- }+ try {+ const result = await createEnrollmentToken({ name });+ setEnrollmentToken(result.token);- const token = await createToken({- identityId: validatedIdentity.id,- name: `gateway token for ${name} (autogenerated)`- });- setIdentityToken(token.accessToken);- createNotification({- text: "Automatically generated a token for the selected identity.",- type: "info"- });- setStep("command");- } catch {- setIdentityToken("");- }- } else {- const validation = formSchemaWithToken.safeParse({- name,- relay,- identityToken- });- if (!validation.success) {- setFormErrors(validation.error.issues);- return;- }+ const relayName = relay?.id === "_auto" ? "" : relay?.name ?? "";+ setResolvedRelayName(relayName);setStep("command");+ } catch {+ createNotification({ type: "error", text: "Failed to create enrollment token" });}};const installCommand = useMemo(() => {- const relayPart = relay?.id !== "_auto" ? ` --target-relay-name=${relay?.name || ""}` : "";- return `sudo infisical gateway systemd install --name=${name}${relayPart} --domain=${siteURL} --token=${identityToken}`;- }, [name, relay, identityToken, siteURL]);+ const relayPart = resolvedRelayName ? ` --target-relay-name=${resolvedRelayName}` : "";+ return `sudo infisical gateway systemd install --enroll-method=static --token=${enrollmentToken} --name=${name}${relayPart} --domain=${siteURL}`;+ }, [enrollmentToken, name, resolvedRelayName, siteURL]);const startServiceCommand = "sudo systemctl start infisical-gateway";if (step === "command") {return (<>+ <p className="mb-3 text-sm text-mineshaft-300">+ Run the following commands on the machine where you want to deploy the gateway. The token+ expires in 1 hour and can only be used once.+ </p><FormLabel label="Installation Command" /><div className="flex gap-2"><Input value={installCommand} isDisabled />@@ -201,10 +101,7 @@ export const GatewayCliSystemdDeploymentMethod = () => {colorSchema="secondary"onClick={() => {navigator.clipboard.writeText(installCommand);- createNotification({- text: "Installation command copied to clipboard",- type: "info"- });+ createNotification({ text: "Installation command copied to clipboard", type: "info" });}}className="w-10">@@ -272,19 +169,12 @@ export const GatewayCliSystemdDeploymentMethod = () => {});return;}-setRelay(newValue as SingleValue<{ id: string; name: string }>);}}isLoading={isRelaysLoading}options={[- {- id: "_auto",- name: "Auto Select Relay"- },- {- id: "_create",- name: "Deploy New Relay"- },+ { id: "_auto", name: "Auto Select Relay" },+ { id: "_create", name: "Deploy New Relay" },...(relays || [])]}placeholder="Select relay..."@@ -294,87 +184,13 @@ export const GatewayCliSystemdDeploymentMethod = () => {/>{errors.relay && <p className="mt-1 text-sm text-red">{errors.relay}</p>}- {canCreateToken && autogenerateToken ? (- <>- <FormLabel- label="Machine Identity"- tooltipText="The machine identity that your gateway will use for authentication."- className="mt-4"- />- <FilterableSelect- value={identity}- onChange={(e) =>- setIdentity(- e as SingleValue<{- id: string;- name: string;- }>- )- }- isLoading={isIdentitiesLoading}- placeholder="Select machine identity..."- options={identityMembershipOrgs.map((membership) => membership.identity)}- getOptionValue={(option) => option.id}- getOptionLabel={(option) => option.name}- />- {errors.identity && <p className="mt-1 text-sm text-red">{errors.identity}</p>}- </>- ) : (- <>- <FormLabel- label="Machine Identity Token"- tooltipText="The machine identity token that your gateway will use for authentication."- className="mt-4"- />- <Input- value={identityToken}- onChange={(e) => setIdentityToken(e.target.value)}- placeholder="Enter machine identity token..."- isError={Boolean(errors.identityToken)}- />- {errors.identityToken && <p className="mt-1 text-sm text-red">{errors.identityToken}</p>}- </>- )}-- {canCreateToken && (- <div className="mt-2">- <Checkbox- isChecked={autogenerateToken}- onCheckedChange={(e) => {- setAutogenerateToken(Boolean(e));- }}- id="autogenerate-token"- className="mr-2"- >- <div className="flex items-center">- <span>Automatically enable token auth and generate a token for machine identity</span>- <Tooltip- className="max-w-md"- content={- <>- Token authentication will be automatically enabled for the selected machine- identity if it isn't already configured. By default, it will be configured- to allow all IP addresses with a token TTL of 30 days. You can manage these- settings in Access Control.- <br />- <br />A token will automatically be generated to be used with the CLI command.- </>- }- >- <FontAwesomeIcon icon={faQuestionCircle} size="sm" className="mt-0.5 ml-1" />- </Tooltip>- </div>- </Checkbox>- </div>- )}-<div className="mt-6 flex items-center"><ButtonclassName="mr-4"size="sm"colorSchema="secondary"- onClick={handleGenerateCommand}- isLoading={isCreatingToken || isAddingTokenAuth}+ onClick={handleContinue}+ isLoading={isCreatingToken}>Continue</Button>