Skip to content

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

feat: V3 gateway API with auth-method-scoped endpoints

bernie-gedacd82cfcdd
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 1b8b620577..cfef612459 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -1,16 +1,12 @@
import z from "zod";
-import { GatewayEnrollmentTokensSchema, GatewaysV2Schema } from "@app/db/schemas";
-import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+import { 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 { 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,
identityId: true,
@@ -21,16 +17,6 @@ const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
lastHealthCheckStatus: true
});
-const SanitizedEnrollmentTokenSchema = GatewayEnrollmentTokensSchema.pick({
- id: true,
- name: true,
- ttl: true,
- expiresAt: true,
- usedAt: true,
- gatewayId: true,
- createdAt: true
-});
-
export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
@@ -286,168 +272,6 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
}
});
- // 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" })
- }),
- response: {
- 200: SanitizedEnrollmentTokenSchema.extend({ token: z.string() })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const result = await server.services.gatewayV2.createEnrollmentToken({
- orgId: req.permission.orgId,
- actorId: req.permission.id,
- actorType: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- name: req.body.name
- });
-
- 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;
- }
- });
-
- 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) => {
- 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()
- }),
- 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
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- event: {
- type: EventType.GATEWAY_RE_ENROLL,
- metadata: {
- gatewayId: req.body.gatewayId,
- name: result.name
- }
- }
- });
-
- return result;
- }
- });
-
- // 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) => {
- 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;
- }
- });
+ // Enrollment endpoints have moved to V3: /api/v3/gateways
};
+
diff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.ts
new file mode 100644
index 0000000000..28fb887843
--- /dev/null
+++ b/backend/src/ee/routes/v3/gateway-router.ts
@@ -0,0 +1,197 @@
+import z from "zod";
+
+import { GatewaysV2Schema } from "@app/db/schemas";
+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+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 { ActorType, AuthMode } from "@app/services/auth/auth-type";
+
+const enrollRateLimit = { windowMs: 60 * 1000, max: 10 };
+
+const SanitizedGatewayV2Schema = GatewaysV2Schema.pick({
+ id: true,
+ identityId: true,
+ name: true,
+ createdAt: true,
+ updatedAt: true,
+ heartbeat: true,
+ lastHealthCheckStatus: true
+});
+
+export const registerGatewayV3Router = async (server: FastifyZodProvider) => {
+ // Create a gateway
+ server.route({
+ method: "POST",
+ url: "/",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "createGateway",
+ body: z.object({
+ name: slugSchema({ min: 1, max: 64, field: "name" })
+ }),
+ response: {
+ 200: SanitizedGatewayV2Schema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const gateway = await server.services.gatewayV2.createGateway({
+ orgId: req.permission.orgId,
+ actorId: req.permission.id,
+ actorType: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ name: req.body.name
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.GATEWAY_ENROLLMENT_TOKEN_CREATE,
+ metadata: {
+ tokenId: gateway.id,
+ name: req.body.name
+ }
+ }
+ });
+
+ return gateway;
+ }
+ });
+
+ // Generate enrollment token for a gateway
+ server.route({
+ method: "POST",
+ url: "/:gatewayId/token-auth/configure",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "configureGatewayTokenAuth",
+ params: z.object({
+ gatewayId: z.string().uuid()
+ }),
+ response: {
+ 200: z.object({
+ token: z.string(),
+ expiresAt: z.date()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const result = await server.services.gatewayV2.configureTokenAuth({
+ orgPermission: req.permission,
+ gatewayId: req.params.gatewayId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.GATEWAY_RE_ENROLL,
+ metadata: {
+ gatewayId: req.params.gatewayId,
+ name: result.name
+ }
+ }
+ });
+
+ return { token: result.token, expiresAt: result.expiresAt };
+ }
+ });
+
+ // Enroll a gateway using a token (unauthenticated)
+ server.route({
+ method: "POST",
+ url: "/token-auth/enroll",
+ config: { rateLimit: enrollRateLimit },
+ schema: {
+ operationId: "enrollGatewayWithToken",
+ 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) => {
+ 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;
+ }
+ });
+
+ // Connect (refresh certs) for an enrolled gateway
+ server.route({
+ method: "POST",
+ url: "/connect",
+ config: { rateLimit: writeLimit },
+ schema: {
+ operationId: "connectGateway",
+ body: z.object({
+ relayName: slugSchema({ min: 1, max: 32, field: "relayName" }).optional()
+ }),
+ response: {
+ 200: z.object({
+ 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()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.GATEWAY_ACCESS_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.gatewayV2.connectGateway({
+ orgId: req.permission.orgId,
+ actorId: req.permission.id,
+ actorType: req.permission.type,
+ relayName: req.body.relayName
+ });
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v3/index.ts b/backend/src/ee/routes/v3/index.ts
new file mode 100644
index 0000000000..84514752a0
--- /dev/null
+++ b/backend/src/ee/routes/v3/index.ts
@@ -0,0 +1,5 @@
+import { registerGatewayV3Router } from "./gateway-router";
+
+export const registerV3EERoutes = async (server: FastifyZodProvider) => {
+ await server.register(registerGatewayV3Router, { prefix: "/gateways" });
+};
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index ae651ec647..019ac1ffb7 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -1190,7 +1190,9 @@ export const gatewayV2ServiceFactory = ({
return gateway;
};
- const createEnrollmentToken = async ({
+ // --- V3 service methods ---
+
+ const createGateway = async ({
orgId,
actorId,
actorType,
@@ -1222,38 +1224,23 @@ export const gatewayV2ServiceFactory = ({
throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
}
- const { plainToken, tokenHash, expiresAt } = $generateEnrollmentToken();
-
- // Create both the gateway record and the enrollment token in a single transaction.
- // The gateway exists immediately so other features (K8s auth, dynamic secrets, etc.)
- // can reference it by ID before the CLI enrolls.
- const { gateway, token: tokenRecord } = await gatewayEnrollmentTokenDAL.transaction(async (tx) => {
- const gw = await gatewayV2DAL.create({ orgId, name }, tx);
-
- const tkn = await gatewayEnrollmentTokenDAL.create(
- {
- orgId,
- name,
- tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt,
- gatewayId: gw.id
- },
- tx
- );
-
- return { gateway: gw, token: tkn };
- });
-
- return { ...tokenRecord, token: plainToken, gatewayId: gateway.id };
+ try {
+ const gateway = await gatewayV2DAL.create({ orgId, name });
+ return gateway;
+ } catch (err) {
+ if (err instanceof DatabaseError && (err.error as { code: string })?.code === DatabaseErrorCode.UniqueViolation) {
+ throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
+ }
+ throw err;
+ }
};
- const deleteEnrollmentToken = async ({
+ const configureTokenAuth = async ({
orgPermission,
- tokenId
+ gatewayId
}: {
orgPermission: OrgServiceActor;
- tokenId: string;
+ gatewayId: string;
}) => {
const { permission } = await permissionService.getOrgPermission({
actor: orgPermission.type,
@@ -1265,18 +1252,76 @@ export const gatewayV2ServiceFactory = ({
});
ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionGatewayActions.DeleteGateways,
+ OrgPermissionGatewayActions.EditGateways,
OrgPermissionSubjects.Gateway
);
- const token = await gatewayEnrollmentTokenDAL.findOne({ id: tokenId, orgId: orgPermission.orgId });
- if (!token) {
- throw new NotFoundError({ message: `Enrollment token ${tokenId} not found` });
+ const gateway = await gatewayV2DAL.findById(gatewayId);
+ if (!gateway || gateway.orgId !== orgPermission.orgId) {
+ throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
}
- await gatewayEnrollmentTokenDAL.deleteById(tokenId);
+ const gatewayToken = $generateEnrollmentToken();
+
+ const record = await gatewayEnrollmentTokenDAL.transaction(async (tx) => {
+ // Delete any existing unused enrollment tokens for this gateway
+ const existingTokens = await gatewayEnrollmentTokenDAL.find({ gatewayId }, { tx });
+ const unusedTokenIds = existingTokens.filter((t) => !t.usedAt).map((t) => t.id);
+ if (unusedTokenIds.length > 0) {
+ await gatewayEnrollmentTokenDAL.delete({ $in: { id: unusedTokenIds } }, tx);
+ }
+
+ return gatewayEnrollmentTokenDAL.create(
+ {
+ orgId: orgPermission.orgId,
+ name: gateway.name,
+ tokenHash: gatewayToken.tokenHash,
+ ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
+ expiresAt: gatewayToken.expiresAt,
+ gatewayId
+ },
+ tx
+ );
+ });
+
+ return { ...record, token: gatewayToken.plainToken };
+ };
+
+ const connectGateway = async ({
+ orgId,
+ actorId,
+ actorType,
+ relayName
+ }: {
+ orgId: string;
+ actorId: string;
+ actorType: ActorType;
+ relayName?: string;
+ }) => {
+ const orgCAs = await $getOrgCAs(orgId);
+
+ 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 });
+ }
- return { name: token.name };
+ // Identity-based flow: delegate to registerGateway
+ throw new BadRequestError({ message: "Use POST /api/v2/gateways for identity-based registration" });
};
const enrollGateway = async ({ token, relayName }: { token: string; relayName?: string }) => {
@@ -1373,60 +1418,6 @@ export const gatewayV2ServiceFactory = ({
}
};
- const reEnrollGateway = async ({
- orgPermission,
- gatewayId
- }: {
- orgPermission: OrgServiceActor;
- gatewayId: 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.EditGateways,
- OrgPermissionSubjects.Gateway
- );
-
- // Re-enroll a gateway (pending or enrolled).
- // The old gateway keeps running until the new machine enrolls with this token.
- // tokenVersion is bumped in enrollGateway when the token is consumed, not here.
- const gateway = await gatewayV2DAL.findById(gatewayId);
- if (!gateway || gateway.orgId !== orgPermission.orgId) {
- throw new NotFoundError({ message: `Gateway ${gatewayId} not found` });
- }
-
- const gatewayToken = $generateEnrollmentToken();
-
- const record = await gatewayEnrollmentTokenDAL.transaction(async (tx) => {
- const existingTokens = await gatewayEnrollmentTokenDAL.find({ gatewayId }, { tx });
- const unusedTokenIds = existingTokens.filter((t) => !t.usedAt).map((t) => t.id);
- if (unusedTokenIds.length > 0) {
- await gatewayEnrollmentTokenDAL.delete({ $in: { id: unusedTokenIds } }, tx);
- }
-
- return gatewayEnrollmentTokenDAL.create(
- {
- orgId: orgPermission.orgId,
- name: gateway.name,
- tokenHash: gatewayToken.tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt: gatewayToken.expiresAt,
- gatewayId
- },
- tx
- );
- });
-
- return { ...record, token: gatewayToken.plainToken };
- };
-
return {
listGateways,
registerGateway,
@@ -1439,9 +1430,10 @@ export const gatewayV2ServiceFactory = ({
healthcheckNotify,
getConnectedResources,
getGatewayById,
- createEnrollmentToken,
- deleteEnrollmentToken,
enrollGateway,
- reEnrollGateway
+ // V3
+ createGateway,
+ configureTokenAuth,
+ connectGateway
};
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index adb1abfe00..a91519d3a7 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -14,6 +14,7 @@ import { registerCertificateEstRouter } from "@app/ee/routes/est/certificate-est
import { registerPkiScepRouter } from "@app/ee/routes/scep/pki-scep-router";
import { registerV1EERoutes } from "@app/ee/routes/v1";
import { registerV2EERoutes } from "@app/ee/routes/v2";
+import { registerV3EERoutes } from "@app/ee/routes/v3";
import {
accessApprovalPolicyApproverDALFactory,
accessApprovalPolicyBypasserDALFactory
@@ -3322,7 +3323,13 @@ export const registerRoutes = async (
},
{ prefix: "/api/v2" }
);
- await server.register(registerV3Routes, { prefix: "/api/v3" });
+ await server.register(
+ async (v3Server) => {
+ await v3Server.register(registerV3EERoutes);
+ await v3Server.register(registerV3Routes);
+ },
+ { prefix: "/api/v3" }
+ );
await server.register(registerV4Routes, { prefix: "/api/v4" });
// Note: This is a special route for BDD tests. It's only available in development mode and only for BDD tests.
diff --git a/frontend/src/hooks/api/gateways-v2/mutations.tsx b/frontend/src/hooks/api/gateways-v2/mutations.tsx
index 9dc805cd7d..eeffc4f66e 100644
--- a/frontend/src/hooks/api/gateways-v2/mutations.tsx
+++ b/frontend/src/hooks/api/gateways-v2/mutations.tsx
@@ -3,9 +3,7 @@ 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"];
+import { TGatewayV2 } from "./types";
const invalidateGatewayQueries = (queryClient: ReturnType<typeof useQueryClient>) => {
queryClient.invalidateQueries(gatewaysQueryKeys.list());
@@ -36,14 +34,11 @@ export const useTriggerGatewayV2Heartbeat = () => {
});
};
-export const useCreateGatewayEnrollmentToken = () => {
+export const useCreateGateway = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ name }: { name: string }) => {
- const { data } = await apiRequest.post<TCreateGatewayEnrollmentTokenResponse>(
- "/api/v2/gateways/enrollment-tokens",
- { name }
- );
+ const { data } = await apiRequest.post<TGatewayV2>("/api/v3/gateways", { name });
return data;
},
onSuccess: () => {
@@ -52,13 +47,12 @@ export const useCreateGatewayEnrollmentToken = () => {
});
};
-export const useReEnrollGateway = () => {
+export const useConfigureGatewayTokenAuth = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ gatewayId }: { gatewayId: string }) => {
- const { data } = await apiRequest.post<TCreateGatewayEnrollmentTokenResponse>(
- "/api/v2/gateways/re-enroll",
- { gatewayId }
+ const { data } = await apiRequest.post<{ token: string; expiresAt: string }>(
+ `/api/v3/gateways/${gatewayId}/token-auth/configure`
);
return data;
},
@@ -67,15 +61,3 @@ export const useReEnrollGateway = () => {
}
});
};
-
-export const useDeleteGatewayEnrollmentToken = () => {
- const queryClient = useQueryClient();
- return useMutation({
- mutationFn: async (tokenId: string) => {
- await apiRequest.delete(`/api/v2/gateways/enrollment-tokens/${tokenId}`);
- },
- onSuccess: () => {
- invalidateGatewayQueries(queryClient);
- }
- });
-};
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx
index 63d58aed5c..227fb8f3b3 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx
@@ -17,7 +17,7 @@ import {
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways";
-import { useCreateGatewayEnrollmentToken } from "@app/hooks/api/gateways-v2";
+import { useConfigureGatewayTokenAuth, useCreateGateway } from "@app/hooks/api/gateways-v2";
import { useGetRelays } from "@app/hooks/api/relays/queries";
import { slugSchema } from "@app/lib/schemas";
@@ -58,8 +58,9 @@ export const GatewayCliDeploymentMethod = () => {
const { data: gateways } = useQuery(gatewaysQueryKeys.listWithTokens());
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
- const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =
- useCreateGatewayEnrollmentToken();
+ const { mutateAsync: createGateway, isPending: isCreatingGateway } = useCreateGateway();
+ const { mutateAsync: configureTokenAuth, isPending: isConfiguringToken } =
+ useConfigureGatewayTokenAuth();
const handleContinue = async () => {
setFormErrors([]);
@@ -73,20 +74,21 @@ export const GatewayCliDeploymentMethod = () => {
if (existingNames.includes(name.trim())) {
createNotification({
type: "error",
- text: "A gateway or enrollment token with this name already exists."
+ text: "A gateway with this name already exists."
});
return;
}
try {
- const result = await createEnrollmentToken({ name });
- setEnrollmentToken(result.token);
+ const gateway = await createGateway({ name });
+ const tokenResult = await configureTokenAuth({ gatewayId: gateway.id });
+ setEnrollmentToken(tokenResult.token);
const relayName = relay?.id === "_auto" ? "" : (relay?.name ?? "");
setResolvedRelayName(relayName);
setStep("command");
} catch {
- createNotification({ type: "error", text: "Failed to create enrollment token" });
+ createNotification({ type: "error", text: "Failed to create gateway" });
}
};
@@ -180,7 +182,7 @@ export const GatewayCliDeploymentMethod = () => {
size="sm"
colorSchema="secondary"
onClick={handleContinue}
- isLoading={isCreatingToken}
+ isLoading={isCreatingGateway || isConfiguringToken}
>
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.tsx
index 7b4843f5e0..db03b1b704 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx
@@ -17,7 +17,7 @@ import {
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import { gatewaysQueryKeys } from "@app/hooks/api/gateways";
-import { useCreateGatewayEnrollmentToken } from "@app/hooks/api/gateways-v2";
+import { useConfigureGatewayTokenAuth, useCreateGateway } from "@app/hooks/api/gateways-v2";
import { useGetRelays } from "@app/hooks/api/relays/queries";
import { slugSchema } from "@app/lib/schemas";
@@ -58,8 +58,9 @@ export const GatewayCliSystemdDeploymentMethod = () => {
const { data: gateways } = useQuery(gatewaysQueryKeys.listWithTokens());
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
- const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =
- useCreateGatewayEnrollmentToken();
+ const { mutateAsync: createGateway, isPending: isCreatingGateway } = useCreateGateway();
+ const { mutateAsync: configureTokenAuth, isPending: isConfiguringToken } =
+ useConfigureGatewayTokenAuth();
const handleContinue = async () => {
setFormErrors([]);
@@ -73,20 +74,21 @@ export const GatewayCliSystemdDeploymentMethod = () => {
if (existingNames.includes(name.trim())) {
createNotification({
type: "error",
- text: "A gateway or enrollment token with this name already exists."
+ text: "A gateway with this name already exists."
});
return;
}
try {
- const result = await createEnrollmentToken({ name });
- setEnrollmentToken(result.token);
+ const gateway = await createGateway({ name });
+ const tokenResult = await configureTokenAuth({ gatewayId: gateway.id });
+ setEnrollmentToken(tokenResult.token);
const relayName = relay?.id === "_auto" ? "" : (relay?.name ?? "");
setResolvedRelayName(relayName);
setStep("command");
} catch {
- createNotification({ type: "error", text: "Failed to create enrollment token" });
+ createNotification({ type: "error", text: "Failed to create gateway" });
}
};
@@ -205,7 +207,7 @@ export const GatewayCliSystemdDeploymentMethod = () => {
size="sm"
colorSchema="secondary"
onClick={handleContinue}
- isLoading={isCreatingToken}
+ isLoading={isCreatingGateway || isConfiguringToken}
>
Continue
</Button>
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx
index 3704906671..a37f98f0c8 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx
@@ -13,7 +13,7 @@ import {
ModalClose,
ModalContent
} from "@app/components/v2";
-import { useReEnrollGateway } from "@app/hooks/api/gateways-v2";
+import { useConfigureGatewayTokenAuth } from "@app/hooks/api/gateways-v2";
type Props = {
isOpen: boolean;
@@ -30,13 +30,14 @@ export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Prop
const [enrollmentToken, setEnrollmentToken] = useState("");
const [confirmText, setConfirmText] = useState("");
- const { mutateAsync: reEnroll, isPending: isReEnrolling } = useReEnrollGateway();
+ const { mutateAsync: configureTokenAuth, isPending: isReEnrolling } =
+ useConfigureGatewayTokenAuth();
const handleReEnroll = async () => {
if (!gatewayData || confirmText !== "confirm") return;
try {
- const result = await reEnroll({ gatewayId: gatewayData.id });
+ const result = await configureTokenAuth({ gatewayId: gatewayData.id });
setEnrollmentToken(result.token);
setStep("command");
} catch {