Skip to content

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

refactor: create gateway record at token creation time

bernie-gf6205670593c
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index b701049b23..795e4375f1 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -378,8 +378,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
schema: {
operationId: "reEnrollGateway",
body: z.object({
- gatewayId: z.string().uuid().optional(),
- tokenId: z.string().uuid().optional()
+ gatewayId: z.string().uuid()
}),
response: {
200: SanitizedEnrollmentTokenSchema.extend({ token: z.string() })
@@ -389,8 +388,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
handler: async (req) => {
const result = await server.services.gatewayV2.reEnrollGateway({
orgPermission: req.permission,
- gatewayId: req.body.gatewayId,
- tokenId: req.body.tokenId
+ gatewayId: req.body.gatewayId
});
await server.services.auditLog.createAuditLog({
@@ -400,7 +398,6 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
type: EventType.GATEWAY_RE_ENROLL,
metadata: {
gatewayId: req.body.gatewayId,
- tokenId: result.id,
name: result.name
}
}
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index e2afd8adff..fa50ab0393 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -5809,8 +5809,7 @@ interface GatewayEnrollEvent {
interface GatewayReEnrollEvent {
type: EventType.GATEWAY_RE_ENROLL;
metadata: {
- gatewayId?: string;
- tokenId?: string;
+ gatewayId: string;
name: string;
};
}
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 3b1cd668a2..a6fe1edbbd 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -1204,22 +1204,30 @@ export const gatewayV2ServiceFactory = ({
throw new BadRequestError({ message: `A gateway named "${name}" already exists` });
}
- const existingTokens = await gatewayEnrollmentTokenDAL.find({ orgId, name });
- if (existingTokens.length > 0) {
- throw new BadRequestError({ message: `An enrollment token named "${name}" already exists` });
- }
-
const { plainToken, tokenHash, expiresAt } = $generateEnrollmentToken();
- const record = await gatewayEnrollmentTokenDAL.create({
- orgId,
- name,
- tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt
+ // 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 { ...record, token: plainToken };
+ return { ...tokenRecord, token: plainToken, gatewayId: gateway.id };
};
const listEnrollmentTokens = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
@@ -1325,27 +1333,19 @@ export const gatewayV2ServiceFactory = ({
const orgCAs = await $getOrgCAs(orgId);
try {
- let gateway;
- if (tokenRecord.gatewayId) {
- // Re-enrollment: reuse existing gateway record.
- // Bump tokenVersion to invalidate the old machine's JWT and clear health status.
- const existing = await gatewayV2DAL.findById(tokenRecord.gatewayId);
- if (!existing) throw new NotFoundError({ message: `Gateway ${tokenRecord.gatewayId} not found` });
- const updated = await gatewayV2DAL.updateById(existing.id, {
- $incr: { tokenVersion: 1 },
- relayId: relay.id,
- heartbeat: null,
- lastHealthCheckStatus: null
- });
- gateway = updated;
- } else {
- // Fresh enrollment: create new gateway record
- gateway = await gatewayV2DAL.create({
- orgId,
- name,
- relayId: relay.id
- });
+ // The gateway record was created at token creation time.
+ // Bump tokenVersion to invalidate any previous JWT and set the relay.
+ if (!tokenRecord.gatewayId) {
+ throw new BadRequestError({ message: "Enrollment token is not linked to a gateway" });
}
+ const existing = await gatewayV2DAL.findById(tokenRecord.gatewayId);
+ if (!existing) throw new NotFoundError({ message: `Gateway ${tokenRecord.gatewayId} not found` });
+ const gateway = await gatewayV2DAL.updateById(existing.id, {
+ $incr: { tokenVersion: 1 },
+ relayId: relay.id,
+ heartbeat: null,
+ lastHealthCheckStatus: null
+ });
const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
const gatewayServerCaCert = new x509.X509Certificate(orgCAs.gatewayServerCaCertificate);
@@ -1446,12 +1446,10 @@ export const gatewayV2ServiceFactory = ({
const reEnrollGateway = async ({
orgPermission,
- gatewayId,
- tokenId
+ gatewayId
}: {
orgPermission: OrgServiceActor;
- gatewayId?: string;
- tokenId?: string;
+ gatewayId: string;
}) => {
const { permission } = await permissionService.getOrgPermission({
actor: orgPermission.type,
@@ -1467,69 +1465,37 @@ export const gatewayV2ServiceFactory = ({
OrgPermissionSubjects.Gateway
);
- if (gatewayId) {
- // Re-enroll an existing (enrolled) gateway.
- // 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 };
+ // 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` });
}
- if (tokenId) {
- // Re-enroll a pending gateway (replace the enrollment token).
- // Wrapped in a transaction so delete + create are atomic.
- const oldToken = await gatewayEnrollmentTokenDAL.findOne({ id: tokenId, orgId: orgPermission.orgId });
- if (!oldToken) {
- throw new NotFoundError({ message: `Enrollment token ${tokenId} not found` });
- }
-
- const pendingToken = $generateEnrollmentToken();
+ const gatewayToken = $generateEnrollmentToken();
- const record = await gatewayEnrollmentTokenDAL.transaction(async (tx) => {
- await gatewayEnrollmentTokenDAL.deleteById(tokenId, tx);
-
- return gatewayEnrollmentTokenDAL.create(
- {
- orgId: orgPermission.orgId,
- name: oldToken.name,
- tokenHash: pendingToken.tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt: pendingToken.expiresAt
- },
- tx
- );
- });
+ 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 { ...record, token: pendingToken.plainToken };
- }
+ return gatewayEnrollmentTokenDAL.create(
+ {
+ orgId: orgPermission.orgId,
+ name: gateway.name,
+ tokenHash: gatewayToken.tokenHash,
+ ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
+ expiresAt: gatewayToken.expiresAt,
+ gatewayId
+ },
+ tx
+ );
+ });
- throw new BadRequestError({ message: "Either gatewayId or tokenId must be provided" });
+ return { ...record, token: gatewayToken.plainToken };
};
return {
diff --git a/frontend/src/hooks/api/gateways-v2/mutations.tsx b/frontend/src/hooks/api/gateways-v2/mutations.tsx
index 841c423741..9dc805cd7d 100644
--- a/frontend/src/hooks/api/gateways-v2/mutations.tsx
+++ b/frontend/src/hooks/api/gateways-v2/mutations.tsx
@@ -55,10 +55,10 @@ export const useCreateGatewayEnrollmentToken = () => {
export const useReEnrollGateway = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ gatewayId, tokenId }: { gatewayId?: string; tokenId?: string }) => {
+ mutationFn: async ({ gatewayId }: { gatewayId: string }) => {
const { data } = await apiRequest.post<TCreateGatewayEnrollmentTokenResponse>(
"/api/v2/gateways/re-enroll",
- { gatewayId, tokenId }
+ { gatewayId }
);
return data;
},
diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx
index eed9541344..8bfb52fe22 100644
--- a/frontend/src/hooks/api/gateways/queries.tsx
+++ b/frontend/src/hooks/api/gateways/queries.tsx
@@ -43,17 +43,18 @@ export const gatewaysQueryKeys = {
const now = new Date();
const unusedTokens = enrollmentTokens.filter((t) => !t.usedAt);
- // Gateways that have a pending (non-expired) re-enrollment token
- const reEnrollGatewayIds = new Set(
+ // Gateways with a non-expired unused enrollment token (pending initial enrollment or re-enrollment)
+ const pendingGatewayIds = new Set(
unusedTokens
.filter((t) => t.gatewayId && new Date(t.expiresAt) > now)
.map((t) => t.gatewayId)
);
- // Standalone tokens (no gateway record yet), both active and expired
- const enrolledNames = new Set(dataV2.map((g) => g.name));
- const standaloneTokens = unusedTokens.filter(
- (t) => !t.gatewayId && !enrolledNames.has(t.name)
+ // Gateways whose only unused token is expired
+ const expiredGatewayIds = new Set(
+ unusedTokens
+ .filter((t) => t.gatewayId && new Date(t.expiresAt) <= now && !pendingGatewayIds.has(t.gatewayId))
+ .map((t) => t.gatewayId)
);
return [
@@ -62,26 +63,22 @@ export const gatewaysQueryKeys = {
isV1: true as const,
isPending: false as const,
isExpired: false as const,
- isTokenOnly: false as const
+ hasReEnrollToken: false as const
})),
- ...dataV2.map((g) => ({
- ...g,
- isV1: false as const,
- isPending: false as const,
- isExpired: false as const,
- isTokenOnly: false as const,
- hasReEnrollToken: reEnrollGatewayIds.has(g.id) as boolean
- })),
- ...standaloneTokens.map((t) => ({
- id: t.id,
- name: t.name,
- createdAt: t.createdAt,
- expiresAt: t.expiresAt,
- isV1: false as const,
- isPending: new Date(t.expiresAt) > now,
- isExpired: new Date(t.expiresAt) <= now,
- isTokenOnly: true as const
- }))
+ ...dataV2.map((g) => {
+ const hasHeartbeat = !!g.heartbeat;
+ const isPending = pendingGatewayIds.has(g.id) && !hasHeartbeat;
+ const hasReEnrollToken = pendingGatewayIds.has(g.id) && hasHeartbeat;
+ const isExpired = expiredGatewayIds.has(g.id) && !hasHeartbeat;
+
+ return {
+ ...g,
+ isV1: false as const,
+ isPending,
+ isExpired,
+ hasReEnrollToken
+ };
+ })
];
}
})
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
index bb7f4cf185..7eb7f01458 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
@@ -49,7 +49,6 @@ import { withPermission } from "@app/hoc";
import { usePopUp } from "@app/hooks";
import { gatewaysQueryKeys, useDeleteGatewayById } from "@app/hooks/api/gateways";
import {
- useDeleteGatewayEnrollmentToken,
useDeleteGatewayV2ById,
useTriggerGatewayV2Heartbeat
} from "@app/hooks/api/gateways-v2";
@@ -166,7 +165,6 @@ export const GatewayTab = withPermission(
const deleteGatewayById = useDeleteGatewayById();
const deleteGatewayV2ById = useDeleteGatewayV2ById();
- const deleteEnrollmentToken = useDeleteGatewayEnrollmentToken();
const triggerGatewayV2Heartbeat = useTriggerGatewayV2Heartbeat();
const handleTriggerHealthCheck = async (id: string) => {
@@ -188,12 +186,8 @@ export const GatewayTab = withPermission(
const data = popUp.deleteGateway.data as {
id: string;
isV1: boolean;
- isPending: boolean;
- isTokenOnly: boolean;
};
- if (data.isTokenOnly) {
- await deleteEnrollmentToken.mutateAsync(data.id);
- } else if (data.isV1) {
+ if (data.isV1) {
await deleteGatewayById.mutateAsync(data.id);
} else {
await deleteGatewayV2ById.mutateAsync(data.id);
@@ -202,9 +196,7 @@ export const GatewayTab = withPermission(
handlePopUpToggle("deleteGateway");
createNotification({
type: "success",
- text: data.isTokenOnly
- ? "Successfully deleted enrollment token"
- : "Successfully deleted gateway"
+ text: "Successfully deleted gateway"
});
};
@@ -403,7 +395,7 @@ export const GatewayTab = withPermission(
className="text-red"
onClick={() => handlePopUpOpen("deleteGateway", el)}
>
- {el.isTokenOnly ? "Delete Token" : "Delete Gateway"}
+ Delete Gateway
</DropdownMenuItem>
)}
</OrgPermissionCan>
@@ -438,11 +430,7 @@ export const GatewayTab = withPermission(
)}
<DeleteActionModal
isOpen={popUp.deleteGateway.isOpen}
- title={`Are you sure you want to delete ${
- (popUp?.deleteGateway?.data as { isTokenOnly?: boolean })?.isTokenOnly
- ? "enrollment token"
- : "gateway"
- } ${(popUp?.deleteGateway?.data as { name: string })?.name || ""}?`}
+ title={`Are you sure you want to delete gateway ${(popUp?.deleteGateway?.data as { name: string })?.name || ""}?`}
onChange={(isOpen) => handlePopUpToggle("deleteGateway", isOpen)}
deleteKey="confirm"
onDeleteApproved={() => handleDeleteGateway()}
@@ -459,7 +447,6 @@ export const GatewayTab = withPermission(
id: string;
name: string;
isPending: boolean;
- isTokenOnly: boolean;
} | null
}
/>
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 103d75847d..02a214951d 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/ReEnrollGatewayModal.tsx
@@ -17,7 +17,7 @@ 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;
+ gatewayData: { id: string; name: string; isPending: boolean } | null;
};
export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Props) => {
@@ -34,9 +34,7 @@ export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Prop
if (!gatewayData) return;
try {
- const result = await reEnroll(
- gatewayData.isTokenOnly ? { tokenId: gatewayData.id } : { gatewayId: gatewayData.id }
- );
+ const result = await reEnroll({ gatewayId: gatewayData.id });
setEnrollmentToken(result.token);
setStep("command");
} catch {
@@ -64,12 +62,11 @@ export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Prop
<ModalContent
className="max-w-2xl"
title={`Re-enroll ${gatewayData.name}`}
- subTitle={(() => {
- if (step !== "confirm") return undefined;
- if (gatewayData.isTokenOnly)
- return "This will create a new enrollment token, replacing the expired one.";
- return "This will create a new enrollment token. The existing gateway will keep running until the new machine enrolls.";
- })()}
+ subTitle={
+ step === "confirm"
+ ? "This will create a new enrollment token. The existing gateway will keep running until the new machine enrolls."
+ : undefined
+ }
>
{step === "confirm" && (
<div className="mt-4 flex items-center">
@@ -80,7 +77,7 @@ export const ReEnrollGatewayModal = ({ isOpen, onOpenChange, gatewayData }: Prop
onClick={handleReEnroll}
isLoading={isReEnrolling}
>
- {gatewayData.isTokenOnly ? "Create New Token" : "Re-enroll"}
+ Re-enroll
</Button>
<ModalClose asChild>
<Button colorSchema="secondary" variant="plain">