Skip to content

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

refacor the app connection to simplify implementation

adilsondf779060c8f2
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns.ts
index 9f1e2676ce..960dd4693e 100644
--- a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns.ts
@@ -11,6 +11,10 @@ import {
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
+import {
+ getCloudflareAuthHeaders,
+ getCloudflareErrorMessage
+} from "@app/services/app-connection/cloudflare/cloudflare-connection-fns";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
import { CLOUDFLARE_API_TOKEN_MIN_TTL_DAYS } from "./cloudflare-api-token-rotation-constants";
@@ -23,15 +27,6 @@ import {
TCloudflareVerifyTokenResponse
} from "./cloudflare-api-token-rotation-types";
-const getCloudflareErrorMessage = (error: unknown) => {
- if (error instanceof AxiosError) {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- return (error.response?.data?.errors?.[0]?.message as string) || error.message || "Unknown error";
- }
-
- return "Unknown error";
-};
-
export const cloudflareApiTokenRotationFactory: TRotationFactory<
TCloudflareApiTokenRotationWithConnection,
TCloudflareApiTokenRotationGeneratedCredentials
@@ -46,16 +41,19 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
const { accountId, apiToken } = connection.credentials;
- const authHeaders = {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- };
+ const authHeaders = getCloudflareAuthHeaders(apiToken);
- const $buildResources = (policy: TCloudflareApiTokenPolicy) => {
+ // https://developers.cloudflare.com/fundamentals/api/how-to/create-via-api/ — note that all-zones is
+ // expressed as a nested object rather than the "*" string the other scopes use
+ const $buildResources = (policy: TCloudflareApiTokenPolicy): Record<string, string | Record<string, string>> => {
if (policy.scope === CloudflareApiTokenPolicyScope.Account) {
return { [`com.cloudflare.api.account.${accountId}`]: "*" };
}
+ if (policy.scope === CloudflareApiTokenPolicyScope.AllZones) {
+ return { [`com.cloudflare.api.account.${accountId}`]: { "com.cloudflare.api.account.zone.*": "*" } };
+ }
+
return Object.fromEntries(
(policy.zoneIds ?? []).map((zoneId) => [`com.cloudflare.api.account.zone.${zoneId}`, "*"])
);
@@ -202,31 +200,22 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
TCloudflareApiTokenRotationGeneratedCredentials
> = async (activeCredentials) => {
- let data: TCloudflareVerifyTokenResponse;
-
try {
- ({ data } = await request.get<TCloudflareVerifyTokenResponse>(
+ const { data } = await request.get<TCloudflareVerifyTokenResponse>(
`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/verify`,
- {
- headers: {
- Authorization: `Bearer ${activeCredentials.apiToken}`,
- Accept: "application/json"
- }
- }
- ));
- } catch (error: unknown) {
- logger.error(
- error,
- `cloudflareApiTokenRotation: failed to verify token during check active credentials [rotationId=${rotationId}] [tokenId=${activeCredentials.tokenId}]`
+ { headers: getCloudflareAuthHeaders(activeCredentials.apiToken) }
);
- throw new BadRequestError({
- message: `Cloudflare API token verification failed: ${getCloudflareErrorMessage(error)}`
- });
- }
- if (!data.success || data.result?.status !== "active") {
+ if (!data.success || data.result?.status !== "active") {
+ throw new BadRequestError({
+ message: `Cloudflare API token verification failed: token status is ${data.result?.status ?? "unknown"}`
+ });
+ }
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+
throw new BadRequestError({
- message: `Cloudflare API token verification failed: token status is ${data.result?.status ?? "unknown"}`
+ message: `Cloudflare API token verification failed: ${getCloudflareErrorMessage(error)}`
});
}
};
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-schemas.ts
index 56c132a325..4c0782e847 100644
--- a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-schemas.ts
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-schemas.ts
@@ -18,6 +18,7 @@ export enum CloudflareApiTokenPolicyEffect {
export enum CloudflareApiTokenPolicyScope {
Account = "account",
+ AllZones = "all-zones",
Zones = "zones"
}
@@ -41,15 +42,16 @@ export const CloudflareApiTokenPolicySchema = z
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["zoneIds"],
- message: "At least one zone is required when the policy is scoped to zones"
+ message: "At least one zone is required when the policy is scoped to specific zones"
});
}
- if (policy.scope === CloudflareApiTokenPolicyScope.Account && policy.zoneIds?.length) {
+ // reject zones on the other scopes rather than silently ignoring them
+ if (policy.scope !== CloudflareApiTokenPolicyScope.Zones && policy.zoneIds?.length) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["zoneIds"],
- message: "Zones cannot be specified when the policy is scoped to the entire account"
+ message: "Zones can only be specified when the policy is scoped to specific zones"
});
}
});
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 115b709273..4d367c1a37 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3577,7 +3577,7 @@ export const SecretRotations = {
CLOUDFLARE_API_TOKEN: {
name: "The name for the generated Cloudflare API token.",
policies:
- "The access policies to attach to the generated Cloudflare API token. Each policy scopes a set of permission groups to either the entire account or a set of zones.",
+ "The access policies to attach to the generated Cloudflare API token. Each policy scopes a set of permission groups to the entire account, to all zones in the account, or to a specific set of zones.",
allowedIps: "The IP addresses or CIDR blocks the generated Cloudflare API token is restricted to.",
disallowedIps: "The IP addresses or CIDR blocks the generated Cloudflare API token is denied from."
},
diff --git a/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts b/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
index a4c720b77e..0098fa695b 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
@@ -2,7 +2,6 @@ import { AxiosError } from "axios";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
@@ -16,10 +15,50 @@ import {
TCloudflareZone
} from "./cloudflare-connection-types";
-const CLOUDFLARE_ZONES_PER_PAGE = 50;
-const CLOUDFLARE_PERMISSION_GROUPS_PER_PAGE = 50;
+// Cloudflare caps per_page at 50 on the list endpoints we use
+const CLOUDFLARE_PER_PAGE = 50;
const CLOUDFLARE_MAX_PAGES = 100;
+export const getCloudflareAuthHeaders = (apiToken: string) => ({
+ Authorization: `Bearer ${apiToken}`,
+ Accept: "application/json"
+});
+
+export const getCloudflareErrorMessage = (error: unknown) => {
+ if (error instanceof AxiosError) {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
+ return (error.response?.data?.errors?.[0]?.message as string) || error.message || "Unknown error";
+ }
+
+ return "Unknown error";
+};
+
+/** Walks a paginated Cloudflare list endpoint using the `result_info.total_pages` it reports. */
+const $paginateCloudflare = async <T>(
+ url: string,
+ { apiToken, params }: { apiToken: string; params?: Record<string, unknown> }
+): Promise<T[]> => {
+ const results: T[] = [];
+
+ let page = 1;
+ let totalPages = 1;
+
+ while (page <= totalPages && page <= CLOUDFLARE_MAX_PAGES) {
+ // eslint-disable-next-line no-await-in-loop
+ const { data } = await request.get<{ result: T[]; result_info?: { total_pages?: number } }>(url, {
+ headers: getCloudflareAuthHeaders(apiToken),
+ params: { ...params, page, per_page: CLOUDFLARE_PER_PAGE }
+ });
+
+ results.push(...data.result);
+
+ totalPages = data.result_info?.total_pages ?? 1;
+ page += 1;
+ }
+
+ return results;
+};
+
export const getCloudflareConnectionListItem = () => {
return {
name: "Cloudflare" as const,
@@ -37,12 +76,7 @@ export const listCloudflarePagesProjects = async (
const { data } = await request.get<{ result: { name: string; id: string }[] }>(
`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/pages/projects`,
- {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- }
- }
+ { headers: getCloudflareAuthHeaders(apiToken) }
);
return data.result.map((a) => ({
@@ -60,12 +94,7 @@ export const listCloudflareWorkersScripts = async (
const { data } = await request.get<{ result: { id: string }[] }>(
`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/workers/scripts`,
- {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- }
- }
+ { headers: getCloudflareAuthHeaders(apiToken) }
);
return data.result.map((a) => ({
@@ -78,42 +107,22 @@ export const listCloudflareZones = async (appConnection: TCloudflareConnection):
credentials: { apiToken }
} = appConnection;
- const zones: TCloudflareZone[] = [];
-
- let page = 1;
- let totalPages = 1;
-
- // Cloudflare defaults to 20 results per page and caps per_page at 50 for the zones endpoint
- while (page <= totalPages && page <= CLOUDFLARE_MAX_PAGES) {
- // eslint-disable-next-line no-await-in-loop
- const { data } = await request.get<{
- result: { name: string; id: string }[];
- result_info?: { total_pages?: number };
- }>(`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/zones`, {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- },
- params: {
- page,
- per_page: CLOUDFLARE_ZONES_PER_PAGE
- }
- });
-
- zones.push(
- ...data.result.map((a) => ({
- name: a.name,
- id: a.id
- }))
- );
-
- totalPages = data.result_info?.total_pages ?? 1;
- page += 1;
- }
+ const zones = await $paginateCloudflare<{ id: string; name: string }>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/zones`,
+ { apiToken }
+ );
- return zones;
+ return zones.map((a) => ({
+ name: a.name,
+ id: a.id
+ }));
};
+/**
+ * Unlike the other list endpoints, token permission groups don't reliably report
+ * `result_info.total_pages`, so this paginates on its own: keep requesting while a page comes back
+ * full and stop on the first partial page.
+ */
export const listCloudflarePermissionGroups = async (
appConnection: TCloudflareConnection
): Promise<TCloudflarePermissionGroup[]> => {
@@ -123,24 +132,15 @@ export const listCloudflarePermissionGroups = async (
const permissionGroups: TCloudflarePermissionGroup[] = [];
- let page = 1;
- let totalPages = 1;
-
- while (page <= totalPages && page <= CLOUDFLARE_MAX_PAGES) {
+ for (let page = 1; page <= CLOUDFLARE_MAX_PAGES; page += 1) {
// eslint-disable-next-line no-await-in-loop
- const { data } = await request.get<{
- result: { id: string; name: string; scopes?: string[] }[];
- result_info?: { total_pages?: number };
- }>(`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/permission_groups`, {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- },
- params: {
- page,
- per_page: CLOUDFLARE_PERMISSION_GROUPS_PER_PAGE
+ const { data } = await request.get<{ result: { id: string; name: string; scopes?: string[] }[] }>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/permission_groups`,
+ {
+ headers: getCloudflareAuthHeaders(apiToken),
+ params: { page, per_page: CLOUDFLARE_PER_PAGE }
}
- });
+ );
permissionGroups.push(
...data.result.map((a) => ({
@@ -150,11 +150,7 @@ export const listCloudflarePermissionGroups = async (
}))
);
- // this endpoint doesn't always return result_info, so when it's missing we keep paging as long as
- // the page came back full and stop on the first partial page
- totalPages =
- data.result_info?.total_pages ?? (data.result.length === CLOUDFLARE_PERMISSION_GROUPS_PER_PAGE ? page + 1 : page);
- page += 1;
+ if (data.result.length < CLOUDFLARE_PER_PAGE) break;
}
return permissionGroups;
@@ -165,10 +161,7 @@ export const validateCloudflareConnectionCredentials = async (config: TCloudflar
try {
const resp = await request.get(`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}`, {
- headers: {
- Authorization: `Bearer ${apiToken}`,
- Accept: "application/json"
- }
+ headers: getCloudflareAuthHeaders(apiToken)
});
if (resp.data === null) {
@@ -177,11 +170,9 @@ export const validateCloudflareConnectionCredentials = async (config: TCloudflar
});
}
} catch (error: unknown) {
- logger.error(error, `Failed to validate Cloudflare connection credentials [accountId=${accountId}]`);
if (error instanceof AxiosError) {
throw new BadRequestError({
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
- message: `Failed to validate credentials: ${error.response?.data?.errors?.[0]?.message || error.message || "Unknown error"}`
+ message: `Failed to validate credentials: ${getCloudflareErrorMessage(error)}`
});
}
throw new BadRequestError({