Skip to content

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

fix: separate shared gateway query from token-aware query, transactional re-enroll

bernie-g0ddcd1674b8a
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 d4dc44baa1..a9d78b9f55 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -1464,58 +1464,68 @@ export const gatewayV2ServiceFactory = ({
);
if (gatewayId) {
- // Re-enroll an existing (enrolled) gateway
+ // Re-enroll an existing (enrolled) gateway.
+ // Wrapped in a transaction so tokenVersion bump, old token cleanup, and new token
+ // creation are atomic. If any step fails, the gateway's JWT is not revoked.
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
- });
+ const gatewayToken = $generateEnrollmentToken();
- // 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 } });
- }
+ const record = await gatewayEnrollmentTokenDAL.transaction(async (tx) => {
+ await gatewayV2DAL.updateById(
+ gatewayId,
+ { $incr: { tokenVersion: 1 }, heartbeat: null, lastHealthCheckStatus: null },
+ tx
+ );
- // Create a new enrollment token linked to the existing gateway
- const gatewayToken = $generateEnrollmentToken();
+ 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);
+ }
- const record = await gatewayEnrollmentTokenDAL.create({
- orgId: orgPermission.orgId,
- name: gateway.name,
- tokenHash: gatewayToken.tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt: gatewayToken.expiresAt,
- gatewayId
+ 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 };
}
if (tokenId) {
- // Re-enroll a pending gateway (replace the enrollment token)
+ // 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` });
}
- await gatewayEnrollmentTokenDAL.deleteById(tokenId);
-
const pendingToken = $generateEnrollmentToken();
- const record = await gatewayEnrollmentTokenDAL.create({
- orgId: orgPermission.orgId,
- name: oldToken.name,
- tokenHash: pendingToken.tokenHash,
- ttl: ENROLLMENT_TOKEN_TTL_SECONDS,
- expiresAt: pendingToken.expiresAt
+ 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
+ );
});
return { ...record, token: pendingToken.plainToken };
diff --git a/frontend/src/hooks/api/gateways-v2/mutations.tsx b/frontend/src/hooks/api/gateways-v2/mutations.tsx
index e2a1160deb..841c423741 100644
--- a/frontend/src/hooks/api/gateways-v2/mutations.tsx
+++ b/frontend/src/hooks/api/gateways-v2/mutations.tsx
@@ -7,6 +7,11 @@ import { TCreateGatewayEnrollmentTokenResponse } from "./types";
export const gatewayEnrollmentTokenQueryKey = () => ["gateway-enrollment-tokens"];
+const invalidateGatewayQueries = (queryClient: ReturnType<typeof useQueryClient>) => {
+ queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ queryClient.invalidateQueries(gatewaysQueryKeys.listWithTokens());
+};
+
export const useDeleteGatewayV2ById = () => {
const queryClient = useQueryClient();
return useMutation({
@@ -14,7 +19,7 @@ export const useDeleteGatewayV2ById = () => {
return apiRequest.delete(`/api/v2/gateways/${id}`);
},
onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ invalidateGatewayQueries(queryClient);
}
});
};
@@ -26,7 +31,7 @@ export const useTriggerGatewayV2Heartbeat = () => {
return apiRequest.post(`/api/v2/gateways/${id}/heartbeat`);
},
onSettled: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ invalidateGatewayQueries(queryClient);
}
});
};
@@ -42,7 +47,7 @@ export const useCreateGatewayEnrollmentToken = () => {
return data;
},
onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ invalidateGatewayQueries(queryClient);
}
});
};
@@ -58,7 +63,7 @@ export const useReEnrollGateway = () => {
return data;
},
onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ invalidateGatewayQueries(queryClient);
}
});
};
@@ -70,7 +75,7 @@ export const useDeleteGatewayEnrollmentToken = () => {
await apiRequest.delete(`/api/v2/gateways/enrollment-tokens/${tokenId}`);
},
onSuccess: () => {
- queryClient.invalidateQueries(gatewaysQueryKeys.list());
+ invalidateGatewayQueries(queryClient);
}
});
};
diff --git a/frontend/src/hooks/api/gateways/queries.tsx b/frontend/src/hooks/api/gateways/queries.tsx
index eb116f4801..79db1a2808 100644
--- a/frontend/src/hooks/api/gateways/queries.tsx
+++ b/frontend/src/hooks/api/gateways/queries.tsx
@@ -11,6 +11,28 @@ export const gatewaysQueryKeys = {
list: () =>
queryOptions({
queryKey: gatewaysQueryKeys.listKey(),
+ queryFn: async () => {
+ const [{ data }, { data: dataV2 }] = await Promise.all([
+ apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"),
+ apiRequest.get<TGatewayV2[]>("/api/v2/gateways")
+ ]);
+
+ return [
+ ...data.gateways.map((g) => ({
+ ...g,
+ isV1: true as const
+ })),
+ ...dataV2.map((g) => ({
+ ...g,
+ isV1: false as const
+ }))
+ ];
+ }
+ }),
+ listWithTokensKey: () => [...gatewaysQueryKeys.allKey(), "list-with-tokens"],
+ listWithTokens: () =>
+ queryOptions({
+ queryKey: gatewaysQueryKeys.listWithTokensKey(),
queryFn: async () => {
const [{ data }, { data: dataV2 }, { data: enrollmentTokens }] = await Promise.all([
apiRequest.get<{ gateways: TGateway[] }>("/api/v1/gateways"),
diff --git a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
index 44acddee8b..7b571beff9 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NetworkHealthBanner/NetworkHealthBanner.tsx
@@ -64,7 +64,6 @@ export const NetworkHealthBanner = () => {
const unreachableGateways = useMemo(
() =>
gateways?.filter((g) => {
- if (g.isPending) return false;
if (
"lastHealthCheckStatus" in g &&
g.lastHealthCheckStatus === GatewayHealthCheckStatus.Failed
diff --git a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
index 3d2ebb198e..81fc9bf01a 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/GatewayTab.tsx
@@ -152,7 +152,9 @@ export const GatewayTab = withPermission(
id: string;
name: string;
} | null>(null);
- const { data: gateways, isPending: isGatewaysLoading } = useQuery(gatewaysQueryKeys.list());
+ const { data: gateways, isPending: isGatewaysLoading } = useQuery(
+ gatewaysQueryKeys.listWithTokens()
+ );
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
"deployGateway",
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 0eab7100d9..d6caf1fca6 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliDeploymentMethod.tsx
@@ -56,7 +56,7 @@ export const GatewayCliDeploymentMethod = () => {
return errorMap;
}, [formErrors]);
- const { data: gateways } = useQuery(gatewaysQueryKeys.list());
+ const { data: gateways } = useQuery(gatewaysQueryKeys.listWithTokens());
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =
useCreateGatewayEnrollmentToken();
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 63fc170c56..c9bbfa9eb6 100644
--- a/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx
+++ b/frontend/src/pages/organization/NetworkingPage/components/GatewayTab/components/GatewayCliSystemdDeploymentMethod.tsx
@@ -56,7 +56,7 @@ export const GatewayCliSystemdDeploymentMethod = () => {
return errorMap;
}, [formErrors]);
- const { data: gateways } = useQuery(gatewaysQueryKeys.list());
+ const { data: gateways } = useQuery(gatewaysQueryKeys.listWithTokens());
const { data: relays, isPending: isRelaysLoading } = useGetRelays();
const { mutateAsync: createEnrollmentToken, isPending: isCreatingToken } =
useCreateGatewayEnrollmentToken();