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 re-enrollment with token version revocation
bernie-g80f626e993c8
diff --git a/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.ts b/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.tsindex 05b6f2b962..bf06cf0385 100644--- a/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.ts+++ b/backend/src/db/migrations/20260413000001_gateway-enrollment-tokens.ts@@ -4,9 +4,10 @@ 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+ // Make identityId nullable and add tokenVersion to support enrollment-token-based gatewaysawait knex.schema.alterTable(TableName.GatewayV2, (t) => {t.uuid("identityId").nullable().alter();+ t.integer("tokenVersion").notNullable().defaultTo(1);});if (!(await knex.schema.hasTable(TableName.GatewayEnrollmentTokens))) {@@ -19,6 +20,9 @@ export async function up(knex: Knex): Promise<void> {t.integer("ttl").notNullable().defaultTo(3600);t.timestamp("expiresAt").notNullable();t.timestamp("usedAt").nullable();+ // When set, enrolling with this token updates the existing gateway instead of creating a new one+ t.uuid("gatewayId").nullable();+ t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2).onDelete("CASCADE");t.timestamps(true, true, true);});@@ -30,8 +34,9 @@ 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)+ // Restore identityId to not-null and remove tokenVersion (only safe if no null rows exist)await knex.schema.alterTable(TableName.GatewayV2, (t) => {t.uuid("identityId").notNullable().alter();+ t.dropColumn("tokenVersion");});}diff --git a/backend/src/db/schemas/gateway-enrollment-tokens.ts b/backend/src/db/schemas/gateway-enrollment-tokens.tsindex 80649a9875..d88067ea2e 100644--- a/backend/src/db/schemas/gateway-enrollment-tokens.ts+++ b/backend/src/db/schemas/gateway-enrollment-tokens.ts@@ -16,7 +16,8 @@ export const GatewayEnrollmentTokensSchema = z.object({tokenHash: z.string(),ttl: z.number().int(),expiresAt: z.date(),- usedAt: z.date().nullable().optional()+ usedAt: z.date().nullable().optional(),+ gatewayId: z.string().uuid().nullable().optional()});export type TGatewayEnrollmentTokens = z.infer<typeof GatewayEnrollmentTokensSchema>;diff --git a/backend/src/db/schemas/gateways-v2.ts b/backend/src/db/schemas/gateways-v2.tsindex 1127bf3ccb..a770be68d3 100644--- a/backend/src/db/schemas/gateways-v2.ts+++ b/backend/src/db/schemas/gateways-v2.ts@@ -17,6 +17,7 @@ export const GatewaysV2Schema = z.object({identityId: z.string().uuid().nullable().optional(),relayId: z.string().uuid().nullable().optional(),name: z.string(),+ tokenVersion: z.number().default(1),heartbeat: z.date().nullable().optional(),encryptedPamSessionKey: zodBuffer.nullable().optional(),healthAlertedAt: z.date().nullable().optional(),diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex bd022d8251..09ef405f2c 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -1,6 +1,7 @@import z from "zod";import { GatewayEnrollmentTokensSchema, GatewaysV2Schema } from "@app/db/schemas";+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";import { zodBuffer } from "@app/lib/zod";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { slugSchema } from "@app/server/lib/schemas";@@ -26,6 +27,7 @@ const SanitizedEnrollmentTokenSchema = GatewayEnrollmentTokensSchema.pick({ttl: true,expiresAt: true,usedAt: true,+ gatewayId: true,createdAt: true});@@ -300,7 +302,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- return server.services.gatewayV2.createEnrollmentToken({+ const result = await server.services.gatewayV2.createEnrollmentToken({orgId: req.permission.orgId,actorId: req.permission.id,actorType: req.permission.type,@@ -308,6 +310,20 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {name: req.body.name,ttlSeconds: req.body.ttlSeconds});++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.GATEWAY_ENROLLMENT_TOKEN_CREATE,+ metadata: {+ tokenId: result.id,+ name: req.body.name+ }+ }+ });++ return result;}});@@ -336,14 +352,66 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),handler: async (req) => {- await server.services.gatewayV2.deleteEnrollmentToken({+ const { name } = await server.services.gatewayV2.deleteEnrollmentToken({orgPermission: req.permission,tokenId: req.params.tokenId});++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.GATEWAY_ENROLLMENT_TOKEN_DELETE,+ metadata: {+ tokenId: req.params.tokenId,+ name+ }+ }+ });+return { message: "Enrollment token deleted" };}});+ server.route({+ method: "POST",+ url: "/re-enroll",+ config: { rateLimit: writeLimit },+ schema: {+ operationId: "reEnrollGateway",+ body: z.object({+ gatewayId: z.string().uuid().optional(),+ tokenId: z.string().uuid().optional()+ }),+ response: {+ 200: SanitizedEnrollmentTokenSchema.extend({ token: z.string() })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req) => {+ const result = await server.services.gatewayV2.reEnrollGateway({+ orgPermission: req.permission,+ gatewayId: req.body.gatewayId,+ tokenId: req.body.tokenId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ event: {+ type: EventType.GATEWAY_RE_ENROLL,+ metadata: {+ gatewayId: req.body.gatewayId,+ tokenId: result.id,+ name: result.name+ }+ }+ });++ return result;+ }+ });+// Enrollment endpoint — no standard auth; enrollment token in body is the credentialserver.route({method: "POST",@@ -374,10 +442,30 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {}},handler: async (req) => {- return server.services.gatewayV2.enrollGateway({+ const result = await server.services.gatewayV2.enrollGateway({token: req.body.token,relayName: req.body.relayName});++ await server.services.auditLog.createAuditLog({+ orgId: result.orgId,+ actor: {+ type: ActorType.GATEWAY,+ metadata: { gatewayId: result.gatewayId }+ },+ event: {+ type: EventType.GATEWAY_ENROLL,+ metadata: {+ gatewayId: result.gatewayId,+ name: result.gatewayName+ }+ },+ ipAddress: req.ip,+ userAgent: req.headers["user-agent"] ?? "",+ userAgentType: UserAgentType.CLI+ });++ return result;}});};diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex b57443a67c..e2afd8adff 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -732,7 +732,13 @@ export enum EventType {// Secret Validation RulesSECRET_VALIDATION_RULE_CREATE = "secret-validation-rule-create",SECRET_VALIDATION_RULE_UPDATE = "secret-validation-rule-update",- SECRET_VALIDATION_RULE_DELETE = "secret-validation-rule-delete"+ SECRET_VALIDATION_RULE_DELETE = "secret-validation-rule-delete",++ // Gateway Enrollment Tokens+ GATEWAY_ENROLLMENT_TOKEN_CREATE = "gateway-enrollment-token-create",+ GATEWAY_ENROLLMENT_TOKEN_DELETE = "gateway-enrollment-token-delete",+ GATEWAY_ENROLL = "gateway-enroll",+ GATEWAY_RE_ENROLL = "gateway-re-enroll"}// Maps each actor type to the JSONB key that holds the actor's primary ID in actorMetadata.@@ -5776,6 +5782,39 @@ interface SecretValidationRuleDeleteEvent {};}+interface GatewayEnrollmentTokenCreateEvent {+ type: EventType.GATEWAY_ENROLLMENT_TOKEN_CREATE;+ metadata: {+ tokenId: string;+ name: string;+ };+}++interface GatewayEnrollmentTokenDeleteEvent {+ type: EventType.GATEWAY_ENROLLMENT_TOKEN_DELETE;+ metadata: {+ tokenId: string;+ name: string;+ };+}++interface GatewayEnrollEvent {+ type: EventType.GATEWAY_ENROLL;+ metadata: {+ gatewayId: string;+ name: string;+ };+}++interface GatewayReEnrollEvent {+ type: EventType.GATEWAY_RE_ENROLL;+ metadata: {+ gatewayId?: string;+ tokenId?: string;+ name: string;+ };+}+export type Event =| CreateSubOrganizationEvent| UpdateSubOrganizationEvent@@ -6297,4 +6336,8 @@ export type Event =| ScepRenewalEvent| SecretValidationRuleCreateEvent| SecretValidationRuleUpdateEvent- | SecretValidationRuleDeleteEvent;+ | SecretValidationRuleDeleteEvent+ | GatewayEnrollmentTokenCreateEvent+ | GatewayEnrollmentTokenDeleteEvent+ | GatewayEnrollEvent+ | GatewayReEnrollEvent;diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 7c9a354ea2..2f1ba0ff48 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -1254,6 +1254,8 @@ export const gatewayV2ServiceFactory = ({}await gatewayEnrollmentTokenDAL.deleteById(tokenId);++ return { name: token.name };};const enrollGateway = async ({ token, relayName }: { token: string; relayName?: string }) => {@@ -1295,11 +1297,23 @@ export const gatewayV2ServiceFactory = ({const orgCAs = await $getOrgCAs(orgId);try {- const gateway = await gatewayV2DAL.create({- orgId,- name,- relayId: relay.id- });+ let gateway;+ if (tokenRecord.gatewayId) {+ // Re-enrollment: reuse existing gateway record, update relay if changed+ const existing = await gatewayV2DAL.findById(tokenRecord.gatewayId);+ if (!existing) throw new NotFoundError({ message: `Gateway ${tokenRecord.gatewayId} not found` });+ if (relay.id !== existing.relayId) {+ await gatewayV2DAL.updateById(existing.id, { relayId: relay.id });+ }+ gateway = { ...existing, relayId: relay.id };+ } else {+ // Fresh enrollment: create new gateway record+ gateway = await gatewayV2DAL.create({+ orgId,+ name,+ relayId: relay.id+ });+ }const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);@@ -1367,7 +1381,8 @@ export const gatewayV2ServiceFactory = ({{gatewayId: gateway.id,orgId,- authTokenType: AuthTokenType.GATEWAY_ACCESS_TOKEN+ authTokenType: AuthTokenType.GATEWAY_ACCESS_TOKEN,+ tokenVersion: gateway.tokenVersion ?? 1},appCfg.AUTH_SECRET);@@ -1375,6 +1390,8 @@ export const gatewayV2ServiceFactory = ({return {accessToken,gatewayId: gateway.id,+ gatewayName: gateway.name,+ orgId,relayHost: relayCredentials.relayHost,pki: {serverCertificate: gatewayServerCertificate.toString("pem"),@@ -1395,6 +1412,96 @@ export const gatewayV2ServiceFactory = ({}};+ const reEnrollGateway = async ({+ orgPermission,+ gatewayId,+ tokenId,+ ttlSeconds = 3600+ }: {+ orgPermission: OrgServiceActor;+ gatewayId?: string;+ tokenId?: string;+ ttlSeconds?: number;+ }) => {+ const { permission } = await permissionService.getOrgPermission({+ actor: orgPermission.type,+ actorId: orgPermission.id,+ orgId: orgPermission.orgId,+ actorAuthMethod: orgPermission.authMethod,+ actorOrgId: orgPermission.orgId,+ scope: OrganizationActionScope.Any+ });++ ForbiddenError.from(permission).throwUnlessCan(+ OrgPermissionGatewayActions.EditGateways,+ OrgPermissionSubjects.Gateway+ );++ if (gatewayId) {+ // Re-enroll an existing (enrolled) gateway+ const gateway = await gatewayV2DAL.findById(gatewayId);+ if (!gateway || gateway.orgId !== orgPermission.orgId) {+ throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });+ }++ // Bump tokenVersion to invalidate the current JWT and clear health status+ await gatewayV2DAL.updateById(gatewayId, {+ $incr: { tokenVersion: 1 },+ heartbeat: null,+ lastHealthCheckStatus: null+ });++ // Delete any existing unused enrollment tokens for this gateway+ const existingTokens = await gatewayEnrollmentTokenDAL.find({ gatewayId });+ const unusedTokenIds = existingTokens.filter((t) => !t.usedAt).map((t) => t.id);+ if (unusedTokenIds.length > 0) {+ await gatewayEnrollmentTokenDAL.delete({ $in: { id: unusedTokenIds } });+ }++ // Create a new enrollment token linked to the existing 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: orgPermission.orgId,+ name: gateway.name,+ tokenHash,+ ttl: ttlSeconds,+ expiresAt,+ gatewayId+ });++ return { ...record, token: plainToken };+ }++ if (tokenId) {+ // Re-enroll a pending gateway (replace the enrollment token)+ const oldToken = await gatewayEnrollmentTokenDAL.findOne({ id: tokenId, orgId: orgPermission.orgId });+ if (!oldToken) {+ throw new NotFoundError({ message: `Enrollment token ${tokenId} not found` });+ }++ await gatewayEnrollmentTokenDAL.deleteById(tokenId);++ 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: orgPermission.orgId,+ name: oldToken.name,+ tokenHash,+ ttl: ttlSeconds,+ expiresAt+ });++ return { ...record, token: plainToken };+ }++ throw new BadRequestError({ message: "Either gatewayId or tokenId must be provided" });+ };+return {listGateways,registerGateway,@@ -1410,6 +1517,7 @@ export const gatewayV2ServiceFactory = ({createEnrollmentToken,listEnrollmentTokens,deleteEnrollmentToken,- enrollGateway+ enrollGateway,+ reEnrollGateway};};diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex 0b911f8d1d..41207aa932 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -7,7 +7,7 @@ import { TServiceTokens, TUsers } from "@app/db/schemas";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 { BadRequestError, UnauthorizedError } from "@app/lib/errors";import {ActorType,AuthMethod,@@ -336,8 +336,15 @@ export const injectIdentity = fp(break;}case AuthMode.GATEWAY_ACCESS_TOKEN: {- // Validate gateway exists — deletion is the revocation mechanismconst gateway = await server.services.gatewayV2.getGatewayById({ gatewayId: token.gatewayId });++ // Reject JWTs whose tokenVersion doesn't match the gateway's current version.+ // Tokens issued before the tokenVersion field existed lack the claim, so treat undefined as version 1.+ const jwtVersion = token.tokenVersion ?? 1;+ if (gateway.tokenVersion !== undefined && gateway.tokenVersion !== jwtVersion) {+ throw new UnauthorizedError({ message: "Gateway token has been revoked" });+ }+requestContext.set("orgId", token.orgId);req.auth = {diff --git a/backend/src/services/auth/auth-type.ts b/backend/src/services/auth/auth-type.tsindex a3e46f2932..5a64a53052 100644--- a/backend/src/services/auth/auth-type.ts+++ b/backend/src/services/auth/auth-type.ts@@ -55,6 +55,7 @@ export type TGatewayAccessTokenJwtPayload = {authTokenType: AuthTokenType.GATEWAY_ACCESS_TOKEN;gatewayId: string;orgId: string;+ tokenVersion: number;};// This will be null unless the token-type is JWTdiff --git a/frontend/src/hooks/api/gateways-v2/mutations.tsx b/frontend/src/hooks/api/gateways-v2/mutations.tsxindex 47674722ca..24214423fc 100644--- a/frontend/src/hooks/api/gateways-v2/mutations.tsx+++ b/frontend/src/hooks/api/gateways-v2/mutations.tsx@@ -47,6 +47,22 @@ export const useCreateGatewayEnrollmentToken = () => {});};+export const useReEnrollGateway = () => {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ gatewayId, tokenId }: { gatewayId?: string; tokenId?: string }) => {+ const { data } = await apiRequest.post<TCreateGatewayEnrollmentTokenResponse>(+ "/api/v2/gateways/re-enroll",+ { gatewayId, tokenId }+ );+ return data;+ },+ onSuccess: () => {+ queryClient.invalidateQueries(gatewaysQueryKeys.list());+ }+ });+};+export const useDeleteGatewayEnrollmentToken = () => {const queryClient = useQueryClient();return useMutation({diff --git a/frontend/src/hooks/api/gateways-v2/types.ts b/frontend/src/hooks/api/gateways-v2/types.tsindex e69ae6a462..10ce07795d 100644--- a/frontend/src/hooks/api/gateways-v2/types.ts+++ b/frontend/src/hooks/api/gateways-v2/types.ts@@ -24,6 +24,7 @@ export type TGatewayEnrollmentToken = {ttl: number;expiresAt: string;usedAt: string | null;+ gatewayId: string | null;createdAt: string;};diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsxindex 9c19ba6c75..989a7e753c 100644--- a/frontend/src/hooks/api/gateways/queries.tsx+++ b/frontend/src/hooks/api/gateways/queries.tsx@@ -18,25 +18,34 @@ export const gatewaysQueryKeys = {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 gatewayconst now = new Date();- const pendingTokens = enrollmentTokens.filter(- (t) => !t.usedAt && new Date(t.expiresAt) > now && !enrolledNames.has(t.name)+ const activeTokens = enrollmentTokens.filter(+ (t) => !t.usedAt && new Date(t.expiresAt) > now+ );++ // Gateways that have a pending re-enrollment token+ const reEnrollGatewayIds = new Set(+ activeTokens.filter((t) => t.gatewayId).map((t) => t.gatewayId)+ );++ // Fresh pending tokens (no gateway record yet)+ const enrolledNames = new Set(dataV2.map((g) => g.name));+ const pendingTokens = activeTokens.filter(+ (t) => !t.gatewayId && !enrolledNames.has(t.name));return [...data.gateways.map((g) => ({...g,isV1: true as const,- isPending: false as const+ isPending: false as const,+ isTokenOnly: false as const})),...dataV2.map((g) => ({...g,isV1: false as const,- isPending: false as const+ isPending: reEnrollGatewayIds.has(g.id) as boolean,+ isTokenOnly: false as const})),...pendingTokens.map((t) => ({id: t.id,@@ -44,7 +53,8 @@ export const gatewaysQueryKeys = {createdAt: t.createdAt,expiresAt: t.expiresAt,isV1: false as const,- isPending: true as const+ isPending: true as const,+ isTokenOnly: true as const}))];}diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsxindex f514841615..59c3e5c6fa 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 {+ faArrowsRotate,faClock,faCopy,faDoorClosed,@@ -57,6 +58,7 @@ import { GatewayHealthCheckStatus } from "@app/hooks/api/gateways-v2/types";import { EditGatewayDetailsModal } from "./components/EditGatewayDetailsModal";import { GatewayConnectedResourcesDrawer } from "./components/GatewayConnectedResourcesDrawer";import { GatewayDeployModal } from "./components/GatewayDeployModal";+import { ReEnrollGatewayModal } from "./components/ReEnrollGatewayModal";const GatewayHealthStatus = ({heartbeat,@@ -144,7 +146,8 @@ export const GatewayTab = withPermission("deployGateway","deleteGateway","editDetails",- "connectedResources"+ "connectedResources",+ "reEnrollGateway"] as const);const deleteGatewayById = useDeleteGatewayById();@@ -172,8 +175,9 @@ export const GatewayTab = withPermission(id: string;isV1: boolean;isPending: boolean;+ isTokenOnly: boolean;};- if (data.isPending) {+ if (data.isTokenOnly) {await deleteEnrollmentToken.mutateAsync(data.id);} else if (data.isV1) {await deleteGatewayById.mutateAsync(data.id);@@ -184,7 +188,7 @@ export const GatewayTab = withPermission(handlePopUpToggle("deleteGateway");createNotification({type: "success",- text: data.isPending+ text: data.isTokenOnly? "Successfully deleted enrollment token": "Successfully deleted gateway"});@@ -201,13 +205,21 @@ export const GatewayTab = withPermission(<h3 className="text-lg font-medium text-mineshaft-100">Gateways</h3><DocumentationLinkBadge href="https://infisical.com/docs/documentation/platform/gateways/overview" /><div className="flex grow" />- <Button- variant="outline_bg"- leftIcon={<FontAwesomeIcon icon={faPlus} />}- onClick={() => handlePopUpOpen("deployGateway")}+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.CreateGateways}+ a={OrgPermissionSubjects.Gateway}>- Deploy Gateway- </Button>+ {(isAllowed: boolean) => (+ <Button+ variant="outline_bg"+ leftIcon={<FontAwesomeIcon icon={faPlus} />}+ onClick={() => handlePopUpOpen("deployGateway")}+ isDisabled={!isAllowed}+ >+ Deploy Gateway+ </Button>+ )}+ </OrgPermissionCan></div></div><p className="mb-4 text-sm text-mineshaft-400">@@ -331,6 +343,24 @@ export const GatewayTab = withPermission()}</OrgPermissionCan>)}+ {!el.isV1 &&+ (el.isPending ||+ ("identityId" in el && !el.identityId)) && (+ <OrgPermissionCan+ I={OrgGatewayPermissionActions.EditGateways}+ a={OrgPermissionSubjects.Gateway}+ >+ {(isAllowed: boolean) => (+ <DropdownMenuItem+ isDisabled={!isAllowed}+ icon={<FontAwesomeIcon icon={faArrowsRotate} />}+ onClick={() => handlePopUpOpen("reEnrollGateway", el)}+ >+ Re-enroll+ </DropdownMenuItem>+ )}+ </OrgPermissionCan>+ )}<OrgPermissionCanI={OrgGatewayPermissionActions.DeleteGateways}a={OrgPermissionSubjects.Gateway}@@ -342,7 +372,7 @@ export const GatewayTab = withPermission(className="text-red"onClick={() => handlePopUpOpen("deleteGateway", el)}>- {el.isPending ? "Delete Token" : "Delete Gateway"}+ {el.isTokenOnly ? "Delete Token" : "Delete Gateway"}</DropdownMenuItem>)}</OrgPermissionCan>@@ -378,7 +408,7 @@ export const GatewayTab = withPermission(<DeleteActionModalisOpen={popUp.deleteGateway.isOpen}title={`Are you sure you want to delete ${- (popUp?.deleteGateway?.data as { isPending?: boolean })?.isPending+ (popUp?.deleteGateway?.data as { isTokenOnly?: boolean })?.isTokenOnly? "enrollment token": "gateway"} ${(popUp?.deleteGateway?.data as { name: string })?.name || ""}?`}@@ -390,6 +420,18 @@ export const GatewayTab = withPermission(isOpen={popUp.deployGateway.isOpen}onOpenChange={(isOpen) => handlePopUpToggle("deployGateway", isOpen)}/>+ <ReEnrollGatewayModal+ isOpen={popUp.reEnrollGateway.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("reEnrollGateway", isOpen)}+ gatewayData={+ popUp.reEnrollGateway.data as {+ id: string;+ name: string;+ isPending: boolean;+ isTokenOnly: boolean;+ } | null+ }+ />{selectedGateway && (<GatewayConnectedResourcesDrawerisOpen={popUp.connectedResources.isOpen}diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsxnew file mode 100644index 0000000000..85daa635ec--- /dev/null+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx@@ -0,0 +1,120 @@+import { useMemo, useState } from "react";+import { faCopy } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";++import { createNotification } from "@app/components/notifications";+import { Button, FormLabel, IconButton, Input, Modal, ModalClose, ModalContent } from "@app/components/v2";+import { useReEnrollGateway } from "@app/hooks/api/gateways-v2";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ gatewayData: { id: string; name: string; isPending: boolean; isTokenOnly: boolean } | null;+};++export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Props) => {+ const { protocol, hostname, port } = window.location;+ const portSuffix = port && port !== "80" ? `:${port}` : "";+ const siteURL = `${protocol}//${hostname}${portSuffix}`;++ const [step, setStep] = useState<"confirm" | "command">("confirm");+ const [enrollmentToken, setEnrollmentToken] = useState("");++ const { mutateAsync: reEnroll, isPending: isReEnrolling } = useReEnrollGateway();++ const handleReEnroll = async () => {+ if (!gatewayData) return;++ try {+ const result = await reEnroll(+ gatewayData.isTokenOnly ? { tokenId: gatewayData.id } : { gatewayId: gatewayData.id }+ );+ setEnrollmentToken(result.token);+ setStep("command");+ } catch {+ createNotification({ type: "error", text: "Failed to re-enroll gateway" });+ }+ };++ const command = useMemo(() => {+ return `infisical gateway start --enroll-method=static --token=${enrollmentToken} --domain=${siteURL}`;+ }, [enrollmentToken, siteURL]);++ const handleClose = (open: boolean) => {+ if (!open) {+ setStep("confirm");+ setEnrollmentToken("");+ }+ onOpenChange(open);+ };++ if (!gatewayData) return null;++ return (+ <Modal isOpen={isOpen} onOpenChange={handleClose}>+ <ModalContent+ className="max-w-2xl"+ title={`Re-enroll ${gatewayData.name}`}+ subTitle={+ step === "confirm"+ ? gatewayData.isTokenOnly+ ? "This will create a new enrollment token, replacing the expired one."+ : "This will create a new enrollment token and invalidate the current gateway credentials. The gateway will stop working until re-enrolled."+ : undefined+ }+ >+ {step === "confirm" && (+ <>+ <div className="mt-4 flex items-center">+ <Button+ className="mr-4"+ size="sm"+ colorSchema="danger"+ onClick={handleReEnroll}+ isLoading={isReEnrolling}+ >+ {gatewayData.isTokenOnly ? "Create New Token" : "Re-enroll"}+ </Button>+ <ModalClose asChild>+ <Button colorSchema="secondary" variant="plain">+ Cancel+ </Button>+ </ModalClose>+ </div>+ </>+ )}+ {step === "command" && (+ <>+ <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 />+ <IconButton+ ariaLabel="copy"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() => {+ navigator.clipboard.writeText(command);+ createNotification({ text: "Command copied to clipboard", type: "info" });+ }}+ className="w-10"+ >+ <FontAwesomeIcon icon={faCopy} />+ </IconButton>+ </div>+ <div className="mt-6 flex items-center">+ <ModalClose asChild>+ <Button className="mr-4" size="sm" colorSchema="secondary">+ Done+ </Button>+ </ModalClose>+ </div>+ </>+ )}+ </ModalContent>+ </Modal>+ );+};