Skip to content

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

feat: add support on the server to rotate API keys on cloudflare

adilsone919bab5bb2b
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-api-token-rotation-router.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-api-token-rotation-router.ts
new file mode 100644
index 0000000000..509adf138d
--- /dev/null
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-api-token-rotation-router.ts
@@ -0,0 +1,19 @@
+import {
+ CloudflareApiTokenRotationGeneratedCredentialsSchema,
+ CloudflareApiTokenRotationSchema,
+ CreateCloudflareApiTokenRotationSchema,
+ UpdateCloudflareApiTokenRotationSchema
+} from "@app/ee/services/secret-rotation-v2/cloudflare-api-token";
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+
+import { registerSecretRotationEndpoints } from "./secret-rotation-v2-endpoints";
+
+export const registerCloudflareApiTokenRotationRouter = async (server: FastifyZodProvider) =>
+ registerSecretRotationEndpoints({
+ type: SecretRotation.CloudflareApiToken,
+ server,
+ responseSchema: CloudflareApiTokenRotationSchema,
+ createSchema: CreateCloudflareApiTokenRotationSchema,
+ updateSchema: UpdateCloudflareApiTokenRotationSchema,
+ generatedCredentialsSchema: CloudflareApiTokenRotationGeneratedCredentialsSchema
+ });
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
index 96c1f43540..b740d4accb 100644
--- a/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/index.ts
@@ -3,6 +3,7 @@ import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotat
import { registerAuth0ClientSecretRotationRouter } from "./auth0-client-secret-rotation-router";
import { registerAwsIamUserSecretRotationRouter } from "./aws-iam-user-secret-rotation-router";
import { registerAzureClientSecretRotationRouter } from "./azure-client-secret-rotation-router";
+import { registerCloudflareApiTokenRotationRouter } from "./cloudflare-api-token-rotation-router";
import { registerConvexAccessKeyRotationRouter } from "./convex-access-key-rotation-router";
import { registerDatabricksServicePrincipalSecretRotationRouter } from "./databricks-service-principal-secret-rotation-router";
import { registerDatadogApiKeyRotationRouter } from "./datadog-api-key-rotation-router";
@@ -58,5 +59,6 @@ export const SECRET_ROTATION_REGISTER_ROUTER_MAP: Record<
[SecretRotation.DatadogApiKey]: registerDatadogApiKeyRotationRouter,
[SecretRotation.ConvexAccessKey]: registerConvexAccessKeyRotationRouter,
[SecretRotation.FireworksApiKey]: registerFireworksApiKeyRotationRouter,
- [SecretRotation.SnowflakeUserKeyPair]: registerSnowflakeUserKeyPairRotationRouter
+ [SecretRotation.SnowflakeUserKeyPair]: registerSnowflakeUserKeyPairRotationRouter,
+ [SecretRotation.CloudflareApiToken]: registerCloudflareApiTokenRotationRouter
};
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
index b31f328505..3cb1aca7f5 100644
--- a/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/secret-rotation-v2-router.ts
@@ -4,6 +4,7 @@ import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { Auth0ClientSecretRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/auth0-client-secret";
import { AwsIamUserSecretRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/aws-iam-user-secret";
import { AzureClientSecretRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/azure-client-secret";
+import { CloudflareApiTokenRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/cloudflare-api-token";
import { ConvexAccessKeyRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/convex-access-key";
import { DatabricksServicePrincipalSecretRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/databricks-service-principal-secret";
import { DatadogApiKeyRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/datadog-api-key";
@@ -59,7 +60,8 @@ const SecretRotationV2OptionsSchema = z.discriminatedUnion("type", [
DatadogApiKeyRotationListItemSchema,
ConvexAccessKeyRotationListItemSchema,
FireworksApiKeyRotationListItemSchema,
- SnowflakeUserKeyPairRotationListItemSchema
+ SnowflakeUserKeyPairRotationListItemSchema,
+ CloudflareApiTokenRotationListItemSchema
]);
export const registerSecretRotationV2Router = async (server: FastifyZodProvider) => {
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-constants.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-constants.ts
new file mode 100644
index 0000000000..b6dedee704
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-constants.ts
@@ -0,0 +1,22 @@
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import { TSecretRotationV2ListItem } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+export const CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION: TSecretRotationV2ListItem = {
+ name: "Cloudflare API Token",
+ type: SecretRotation.CloudflareApiToken,
+ connection: AppConnection.Cloudflare,
+ template: {
+ secretsMapping: {
+ tokenId: "CLOUDFLARE_API_TOKEN_ID",
+ apiToken: "CLOUDFLARE_API_TOKEN"
+ }
+ }
+};
+
+/**
+ * A generated token stays active across at most two rotation cycles, so `2 * interval + 1` days can
+ * never expire a token that is still in use. The floor keeps rotation development mode (where the
+ * interval is treated as minutes) from producing a near-immediate expiry.
+ */
+export const CLOUDFLARE_API_TOKEN_MIN_TTL_DAYS = 7;
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
new file mode 100644
index 0000000000..9f1e2676ce
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns.ts
@@ -0,0 +1,241 @@
+import { AxiosError } from "axios";
+
+import {
+ TRotationFactory,
+ TRotationFactoryCheckActiveCredentials,
+ TRotationFactoryGetSecretsPayload,
+ TRotationFactoryIssueCredentials,
+ TRotationFactoryRevokeCredentials,
+ TRotationFactoryRotateCredentials
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+import { CLOUDFLARE_API_TOKEN_MIN_TTL_DAYS } from "./cloudflare-api-token-rotation-constants";
+import { CloudflareApiTokenPolicyScope } from "./cloudflare-api-token-rotation-schemas";
+import {
+ TCloudflareApiTokenPolicy,
+ TCloudflareApiTokenRotationGeneratedCredentials,
+ TCloudflareApiTokenRotationWithConnection,
+ TCloudflareCreateTokenResponse,
+ 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
+> = (secretRotation) => {
+ const {
+ id: rotationId,
+ connection,
+ rotationInterval,
+ parameters: { name, policies, allowedIps, disallowedIps },
+ secretsMapping
+ } = secretRotation;
+
+ const { accountId, apiToken } = connection.credentials;
+
+ const authHeaders = {
+ Authorization: `Bearer ${apiToken}`,
+ Accept: "application/json"
+ };
+
+ const $buildResources = (policy: TCloudflareApiTokenPolicy) => {
+ if (policy.scope === CloudflareApiTokenPolicyScope.Account) {
+ return { [`com.cloudflare.api.account.${accountId}`]: "*" };
+ }
+
+ return Object.fromEntries(
+ (policy.zoneIds ?? []).map((zoneId) => [`com.cloudflare.api.account.zone.${zoneId}`, "*"])
+ );
+ };
+
+ // an empty `in` list would deny every request, so we omit either side rather than sending []
+ const $buildCondition = () => {
+ if (!allowedIps?.length && !disallowedIps?.length) return undefined;
+
+ return {
+ "request.ip": {
+ ...(allowedIps?.length ? { in: allowedIps } : {}),
+ ...(disallowedIps?.length ? { not_in: disallowedIps } : {})
+ }
+ };
+ };
+
+ const $getExpiresOn = () => {
+ const days = Math.max(rotationInterval * 2 + 1, CLOUDFLARE_API_TOKEN_MIN_TTL_DAYS);
+
+ const expiresOn = new Date();
+ expiresOn.setUTCDate(expiresOn.getUTCDate() + days);
+ expiresOn.setUTCMilliseconds(0);
+
+ // Cloudflare expects RFC 3339 without fractional seconds
+ return expiresOn.toISOString().replace(/\.\d{3}Z$/, "Z");
+ };
+
+ const $createToken = async () => {
+ try {
+ const { data } = await request.post<TCloudflareCreateTokenResponse>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens`,
+ {
+ name: `${name}-${Date.now()}`,
+ policies: policies.map((policy) => ({
+ effect: policy.effect,
+ resources: $buildResources(policy),
+ permission_groups: policy.permissionGroupIds.map((id) => ({ id }))
+ })),
+ expires_on: $getExpiresOn(),
+ condition: $buildCondition()
+ },
+ {
+ headers: {
+ ...authHeaders,
+ "Content-Type": "application/json"
+ }
+ }
+ );
+
+ if (!data?.result?.id || !data?.result?.value) {
+ throw new BadRequestError({
+ message: "Cloudflare API token response missing 'result.id' or 'result.value'"
+ });
+ }
+
+ return { tokenId: data.result.id, apiToken: data.result.value };
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+
+ throw new BadRequestError({
+ message: `Failed to create Cloudflare API token: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+ };
+
+ const $deleteToken = async (tokenId: string) => {
+ try {
+ await request.delete(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/${encodeURIComponent(tokenId)}`,
+ { headers: authHeaders }
+ );
+ } catch (error: unknown) {
+ // 404 means the token is already gone, which is the desired end state of revocation
+ if (error instanceof AxiosError && error.response?.status === 404) return;
+
+ throw new BadRequestError({
+ message: `Failed to delete Cloudflare API token ${tokenId}: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+ };
+
+ const issueCredentials: TRotationFactoryIssueCredentials<TCloudflareApiTokenRotationGeneratedCredentials> = async (
+ callback
+ ) => {
+ const credentials = await $createToken();
+
+ return callback(credentials);
+ };
+
+ const revokeCredentials: TRotationFactoryRevokeCredentials<TCloudflareApiTokenRotationGeneratedCredentials> = async (
+ generatedCredentials,
+ callback
+ ) => {
+ if (!generatedCredentials?.length) return callback();
+
+ const results = await Promise.allSettled(
+ generatedCredentials.map((credential) => $deleteToken(credential.tokenId))
+ );
+
+ results.forEach((result, index) => {
+ if (result.status === "rejected") {
+ logger.error(
+ result.reason,
+ `cloudflareApiTokenRotation: failed to revoke token during cleanup [rotationId=${rotationId}] [tokenId=${generatedCredentials[index].tokenId}]`
+ );
+ }
+ });
+
+ return callback();
+ };
+
+ // We persist the new token before revoking the old one so a revocation failure can never leave the
+ // rotation without a usable credential.
+ const rotateCredentials: TRotationFactoryRotateCredentials<TCloudflareApiTokenRotationGeneratedCredentials> = async (
+ credentialsToRevoke,
+ callback
+ ) => {
+ const newCredentials = await $createToken();
+
+ const result = await callback(newCredentials);
+
+ if (credentialsToRevoke?.tokenId) {
+ try {
+ await $deleteToken(credentialsToRevoke.tokenId);
+ } catch (error) {
+ logger.error(
+ error,
+ `cloudflareApiTokenRotation: failed to revoke previous token after rotation [rotationId=${rotationId}] [tokenId=${credentialsToRevoke.tokenId}]`
+ );
+ }
+ }
+
+ return result;
+ };
+
+ const getSecretsPayload: TRotationFactoryGetSecretsPayload<TCloudflareApiTokenRotationGeneratedCredentials> = (
+ generatedCredentials
+ ) => [
+ { key: secretsMapping.tokenId, value: generatedCredentials.tokenId },
+ { key: secretsMapping.apiToken, value: generatedCredentials.apiToken }
+ ];
+
+ const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
+ TCloudflareApiTokenRotationGeneratedCredentials
+ > = async (activeCredentials) => {
+ let data: TCloudflareVerifyTokenResponse;
+
+ try {
+ ({ 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}]`
+ );
+ throw new BadRequestError({
+ message: `Cloudflare API token verification failed: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+
+ if (!data.success || data.result?.status !== "active") {
+ throw new BadRequestError({
+ message: `Cloudflare API token verification failed: token status is ${data.result?.status ?? "unknown"}`
+ });
+ }
+ };
+
+ return {
+ issueCredentials,
+ revokeCredentials,
+ rotateCredentials,
+ getSecretsPayload,
+ checkActiveCredentials
+ };
+};
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
new file mode 100644
index 0000000000..56c132a325
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-schemas.ts
@@ -0,0 +1,124 @@
+import { z } from "zod";
+
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import {
+ BaseCreateSecretRotationSchema,
+ BaseSecretRotationSchema,
+ BaseUpdateSecretRotationSchema
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-schemas";
+import { SecretRotations } from "@app/lib/api-docs";
+import { isValidIpOrCidr } from "@app/lib/ip";
+import { SecretNameSchema } from "@app/server/lib/schemas";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+export enum CloudflareApiTokenPolicyEffect {
+ Allow = "allow",
+ Deny = "deny"
+}
+
+export enum CloudflareApiTokenPolicyScope {
+ Account = "account",
+ Zones = "zones"
+}
+
+/**
+ * Cloudflare caps token names at 120 characters. We generate names as `<name>-<timestamp>`, so the
+ * user-supplied portion is capped lower to leave room for the suffix.
+ */
+export const CLOUDFLARE_API_TOKEN_NAME_MAX_LENGTH = 100;
+
+const IpRestrictionSchema = z.string().trim().refine(isValidIpOrCidr, "Must be a valid IP address or CIDR block");
+
+export const CloudflareApiTokenPolicySchema = z
+ .object({
+ effect: z.nativeEnum(CloudflareApiTokenPolicyEffect),
+ scope: z.nativeEnum(CloudflareApiTokenPolicyScope),
+ zoneIds: z.string().trim().array().optional(),
+ permissionGroupIds: z.string().trim().array().min(1, "At least one permission group is required")
+ })
+ .superRefine((policy, ctx) => {
+ if (policy.scope === CloudflareApiTokenPolicyScope.Zones && !policy.zoneIds?.length) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["zoneIds"],
+ message: "At least one zone is required when the policy is scoped to zones"
+ });
+ }
+
+ if (policy.scope === CloudflareApiTokenPolicyScope.Account && 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"
+ });
+ }
+ });
+
+export const CloudflareApiTokenRotationGeneratedCredentialsSchema = z
+ .object({
+ tokenId: z.string(),
+ apiToken: z.string()
+ })
+ .array()
+ .min(1)
+ .max(2);
+
+const CloudflareApiTokenRotationParametersSchema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1, "Token name required")
+ .max(
+ CLOUDFLARE_API_TOKEN_NAME_MAX_LENGTH,
+ `Token name must be ${CLOUDFLARE_API_TOKEN_NAME_MAX_LENGTH} characters or fewer`
+ )
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.name),
+ policies: CloudflareApiTokenPolicySchema.array()
+ .min(1, "At least one access policy is required")
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.policies),
+ allowedIps: IpRestrictionSchema.array()
+ .optional()
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.allowedIps),
+ disallowedIps: IpRestrictionSchema.array()
+ .optional()
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.disallowedIps)
+});
+
+const CloudflareApiTokenRotationSecretsMappingSchema = z.object({
+ tokenId: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.CLOUDFLARE_API_TOKEN.tokenId),
+ apiToken: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.CLOUDFLARE_API_TOKEN.apiToken)
+});
+
+export const CloudflareApiTokenRotationTemplateSchema = z.object({
+ secretsMapping: z.object({
+ tokenId: z.string(),
+ apiToken: z.string()
+ })
+});
+
+export const CloudflareApiTokenRotationSchema = BaseSecretRotationSchema(SecretRotation.CloudflareApiToken).extend({
+ type: z.literal(SecretRotation.CloudflareApiToken),
+ parameters: CloudflareApiTokenRotationParametersSchema,
+ secretsMapping: CloudflareApiTokenRotationSecretsMappingSchema
+});
+
+export const CreateCloudflareApiTokenRotationSchema = BaseCreateSecretRotationSchema(
+ SecretRotation.CloudflareApiToken
+).extend({
+ parameters: CloudflareApiTokenRotationParametersSchema,
+ secretsMapping: CloudflareApiTokenRotationSecretsMappingSchema
+});
+
+export const UpdateCloudflareApiTokenRotationSchema = BaseUpdateSecretRotationSchema(
+ SecretRotation.CloudflareApiToken
+).extend({
+ parameters: CloudflareApiTokenRotationParametersSchema.optional(),
+ secretsMapping: CloudflareApiTokenRotationSecretsMappingSchema.optional()
+});
+
+export const CloudflareApiTokenRotationListItemSchema = z.object({
+ name: z.literal("Cloudflare API Token"),
+ connection: z.literal(AppConnection.Cloudflare),
+ type: z.literal(SecretRotation.CloudflareApiToken),
+ template: CloudflareApiTokenRotationTemplateSchema
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-types.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-types.ts
new file mode 100644
index 0000000000..7295c783ba
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-types.ts
@@ -0,0 +1,44 @@
+import { z } from "zod";
+
+import { TCloudflareConnection } from "@app/services/app-connection/cloudflare/cloudflare-connection-types";
+
+import {
+ CloudflareApiTokenPolicySchema,
+ CloudflareApiTokenRotationGeneratedCredentialsSchema,
+ CloudflareApiTokenRotationListItemSchema,
+ CloudflareApiTokenRotationSchema,
+ CreateCloudflareApiTokenRotationSchema
+} from "./cloudflare-api-token-rotation-schemas";
+
+export type TCloudflareApiTokenRotation = z.infer<typeof CloudflareApiTokenRotationSchema>;
+
+export type TCloudflareApiTokenRotationInput = z.infer<typeof CreateCloudflareApiTokenRotationSchema>;
+
+export type TCloudflareApiTokenRotationListItem = z.infer<typeof CloudflareApiTokenRotationListItemSchema>;
+
+export type TCloudflareApiTokenRotationWithConnection = TCloudflareApiTokenRotation & {
+ connection: TCloudflareConnection;
+};
+
+export type TCloudflareApiTokenRotationGeneratedCredentials = z.infer<
+ typeof CloudflareApiTokenRotationGeneratedCredentialsSchema
+>;
+
+export type TCloudflareApiTokenPolicy = z.infer<typeof CloudflareApiTokenPolicySchema>;
+
+export type TCloudflareCreateTokenResponse = {
+ result: {
+ id: string;
+ name: string;
+ value: string;
+ status: string;
+ } | null;
+};
+
+export type TCloudflareVerifyTokenResponse = {
+ success: boolean;
+ result: {
+ id: string;
+ status: string;
+ } | null;
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/index.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/index.ts
new file mode 100644
index 0000000000..2e89ec6665
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-api-token/index.ts
@@ -0,0 +1,3 @@
+export * from "./cloudflare-api-token-rotation-constants";
+export * from "./cloudflare-api-token-rotation-schemas";
+export * from "./cloudflare-api-token-rotation-types";
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
index fca62825f6..53397b2566 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-enums.ts
@@ -24,7 +24,8 @@ export enum SecretRotation {
DatadogApiKey = "datadog-api-key",
ConvexAccessKey = "convex-access-key",
FireworksApiKey = "fireworks-api-key",
- SnowflakeUserKeyPair = "snowflake-user-key-pair"
+ SnowflakeUserKeyPair = "snowflake-user-key-pair",
+ CloudflareApiToken = "cloudflare-api-token"
}
export enum SecretRotationStatus {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
index f9270e156b..636042a4e8 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-fns.ts
@@ -9,6 +9,7 @@ import { KmsDataKey } from "@app/services/kms/kms-types";
import { AUTH0_CLIENT_SECRET_ROTATION_LIST_OPTION } from "./auth0-client-secret";
import { AWS_IAM_USER_SECRET_ROTATION_LIST_OPTION } from "./aws-iam-user-secret";
import { AZURE_CLIENT_SECRET_ROTATION_LIST_OPTION } from "./azure-client-secret";
+import { CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION } from "./cloudflare-api-token";
import { CONVEX_ACCESS_KEY_ROTATION_LIST_OPTION } from "./convex-access-key";
import { DATABRICKS_SERVICE_PRINCIPAL_SECRET_ROTATION_LIST_OPTION } from "./databricks-service-principal-secret";
import { DATADOG_API_KEY_ROTATION_LIST_OPTION } from "./datadog-api-key";
@@ -79,7 +80,8 @@ const SECRET_ROTATION_LIST_OPTIONS: Record<SecretRotation, TSecretRotationV2List
[SecretRotation.DatadogApiKey]: DATADOG_API_KEY_ROTATION_LIST_OPTION,
[SecretRotation.ConvexAccessKey]: CONVEX_ACCESS_KEY_ROTATION_LIST_OPTION,
[SecretRotation.FireworksApiKey]: FIREWORKS_API_KEY_ROTATION_LIST_OPTION,
- [SecretRotation.SnowflakeUserKeyPair]: SNOWFLAKE_USER_KEY_PAIR_ROTATION_LIST_OPTION
+ [SecretRotation.SnowflakeUserKeyPair]: SNOWFLAKE_USER_KEY_PAIR_ROTATION_LIST_OPTION,
+ [SecretRotation.CloudflareApiToken]: CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION
};
export const listSecretRotationOptions = () => {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
index df36948a2a..aaf219c0ec 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-maps.ts
@@ -27,7 +27,8 @@ export const SECRET_ROTATION_NAME_MAP: Record<SecretRotation, string> = {
[SecretRotation.DatadogApiKey]: "Datadog API Key",
[SecretRotation.ConvexAccessKey]: "Convex Access Key",
[SecretRotation.FireworksApiKey]: "Fireworks Secret",
- [SecretRotation.SnowflakeUserKeyPair]: "Snowflake User Key Pair"
+ [SecretRotation.SnowflakeUserKeyPair]: "Snowflake User Key Pair",
+ [SecretRotation.CloudflareApiToken]: "Cloudflare API Token"
};
export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnection> = {
@@ -56,5 +57,6 @@ export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnectio
[SecretRotation.DatadogApiKey]: AppConnection.Datadog,
[SecretRotation.ConvexAccessKey]: AppConnection.Convex,
[SecretRotation.FireworksApiKey]: AppConnection.Fireworks,
- [SecretRotation.SnowflakeUserKeyPair]: AppConnection.Snowflake
+ [SecretRotation.SnowflakeUserKeyPair]: AppConnection.Snowflake,
+ [SecretRotation.CloudflareApiToken]: AppConnection.Cloudflare
};
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
index 5b6d2948c9..b37a29c28a 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
@@ -15,6 +15,7 @@ import {
} from "@app/ee/services/permission/project-permission";
import { auth0ClientSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/auth0-client-secret/auth0-client-secret-rotation-fns";
import { azureClientSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/azure-client-secret/azure-client-secret-rotation-fns";
+import { cloudflareApiTokenRotationFactory } from "@app/ee/services/secret-rotation-v2/cloudflare-api-token/cloudflare-api-token-rotation-fns";
import { convexAccessKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/convex-access-key/convex-access-key-rotation-fns";
import { databricksServicePrincipalSecretRotationFactory } from "@app/ee/services/secret-rotation-v2/databricks-service-principal-secret/databricks-service-principal-secret-rotation-fns";
import { datadogApiKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/datadog-api-key/datadog-api-key-rotation-fns";
@@ -213,7 +214,8 @@ const SECRET_ROTATION_FACTORY_MAP: Record<SecretRotation, TRotationFactoryImplem
[SecretRotation.DatadogApiKey]: datadogApiKeyRotationFactory as TRotationFactoryImplementation,
[SecretRotation.ConvexAccessKey]: convexAccessKeyRotationFactory as TRotationFactoryImplementation,
[SecretRotation.FireworksApiKey]: fireworksApiKeyRotationFactory as TRotationFactoryImplementation,
- [SecretRotation.SnowflakeUserKeyPair]: snowflakeUserKeyPairRotationFactory as TRotationFactoryImplementation
+ [SecretRotation.SnowflakeUserKeyPair]: snowflakeUserKeyPairRotationFactory as TRotationFactoryImplementation,
+ [SecretRotation.CloudflareApiToken]: cloudflareApiTokenRotationFactory as TRotationFactoryImplementation
};
export const secretRotationV2ServiceFactory = ({
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
index 4f1431a5c7..05c6d53a25 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-types.ts
@@ -30,6 +30,13 @@ import {
TAzureClientSecretRotationListItem,
TAzureClientSecretRotationWithConnection
} from "./azure-client-secret";
+import {
+ TCloudflareApiTokenRotation,
+ TCloudflareApiTokenRotationGeneratedCredentials,
+ TCloudflareApiTokenRotationInput,
+ TCloudflareApiTokenRotationListItem,
+ TCloudflareApiTokenRotationWithConnection
+} from "./cloudflare-api-token";
import {
TConvexAccessKeyRotation,
TConvexAccessKeyRotationGeneratedCredentials,
@@ -215,7 +222,8 @@ export type TSecretRotationV2 =
| TDatadogApiKeyRotation
| TConvexAccessKeyRotation
| TFireworksApiKeyRotation
- | TSnowflakeUserKeyPairRotation;
+ | TSnowflakeUserKeyPairRotation
+ | TCloudflareApiTokenRotation;
export type TSecretRotationV2WithConnection =
| TPostgresCredentialsRotationWithConnection
@@ -243,7 +251,8 @@ export type TSecretRotationV2WithConnection =
| TDatadogApiKeyRotationWithConnection
| TConvexAccessKeyRotationWithConnection
| TFireworksApiKeyRotationWithConnection
- | TSnowflakeUserKeyPairRotationWithConnection;
+ | TSnowflakeUserKeyPairRotationWithConnection
+ | TCloudflareApiTokenRotationWithConnection;
export type TSecretRotationV2GeneratedCredentials =
| TSqlCredentialsRotationGeneratedCredentials
@@ -267,7 +276,8 @@ export type TSecretRotationV2GeneratedCredentials =
| TDatadogApiKeyRotationGeneratedCredentials
| TConvexAccessKeyRotationGeneratedCredentials
| TFireworksApiKeyRotationGeneratedCredentials
- | TSnowflakeUserKeyPairRotationGeneratedCredentials;
+ | TSnowflakeUserKeyPairRotationGeneratedCredentials
+ | TCloudflareApiTokenRotationGeneratedCredentials;
export type TSecretRotationV2Input =
| TPostgresCredentialsRotationInput
@@ -295,7 +305,8 @@ export type TSecretRotationV2Input =
| TDatadogApiKeyRotationInput
| TConvexAccessKeyRotationInput
| TFireworksApiKeyRotationInput
- | TSnowflakeUserKeyPairRotationInput;
+ | TSnowflakeUserKeyPairRotationInput
+ | TCloudflareApiTokenRotationInput;
export type TSecretRotationV2ListItem =
| TPostgresCredentialsRotationListItem
@@ -323,7 +334,8 @@ export type TSecretRotationV2ListItem =
| TDatadogApiKeyRotationListItem
| TConvexAccessKeyRotationListItem
| TFireworksApiKeyRotationListItem
- | TSnowflakeUserKeyPairRotationListItem;
+ | TSnowflakeUserKeyPairRotationListItem
+ | TCloudflareApiTokenRotationListItem;
export type TSecretRotationV2TemporaryParameters =
| TLdapPasswordRotationInput["temporaryParameters"]
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
index 6e88c7a3ef..1822d11100 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema.ts
@@ -21,6 +21,7 @@ import { SalesforceOauthCredentialsRotationSchema } from "@app/ee/services/secre
import { UnixLinuxLocalAccountRotationSchema } from "@app/ee/services/secret-rotation-v2/unix-linux-local-account-rotation";
import { WindowsLocalAccountRotationSchema } from "@app/ee/services/secret-rotation-v2/windows-local-account-rotation";
+import { CloudflareApiTokenRotationSchema } from "./cloudflare-api-token";
import { ConvexAccessKeyRotationSchema } from "./convex-access-key";
import { DbtServiceTokenRotationSchema } from "./dbt-service-token";
import { FireworksApiKeyRotationSchema } from "./fireworks-api-key";
@@ -54,5 +55,6 @@ export const SecretRotationV2Schema = z.discriminatedUnion("type", [
DatadogApiKeyRotationSchema,
ConvexAccessKeyRotationSchema,
FireworksApiKeyRotationSchema,
- SnowflakeUserKeyPairRotationSchema
+ SnowflakeUserKeyPairRotationSchema,
+ CloudflareApiTokenRotationSchema
]);
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 6be121ce42..115b709273 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3574,6 +3574,13 @@ export const SecretRotations = {
DATADOG_API_KEY: {
name: "The name for the generated Datadog API key."
},
+ 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.",
+ 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."
+ },
CONVEX_ACCESS_KEY: {
namePrefix: "A prefix to use when naming the generated Convex access key."
},
@@ -3666,6 +3673,10 @@ export const SecretRotations = {
apiKeyId: "The name of the secret that the rotated Datadog API key ID will be mapped to.",
apiKey: "The name of the secret that the rotated Datadog API key value will be mapped to."
},
+ CLOUDFLARE_API_TOKEN: {
+ tokenId: "The name of the secret that the rotated Cloudflare API token ID will be mapped to.",
+ apiToken: "The name of the secret that the rotated Cloudflare API token value will be mapped to."
+ },
CONVEX_ACCESS_KEY: {
accessKey: "The name of the secret that the rotated Convex access key will be mapped to."
},
diff --git a/backend/src/server/routes/v1/app-connection-routers/cloudflare-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/cloudflare-connection-router.ts
index 768b3786b3..ad635a5146 100644
--- a/backend/src/server/routes/v1/app-connection-routers/cloudflare-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/cloudflare-connection-router.ts
@@ -107,4 +107,37 @@ export const registerCloudflareConnectionRouter = async (server: FastifyZodProvi
return zones;
}
});
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/cloudflare-permission-groups`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listCloudflarePermissionGroups",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ response: {
+ 200: z
+ .object({
+ id: z.string(),
+ name: z.string(),
+ scopes: z.string().array()
+ })
+ .array()
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+
+ const permissionGroups = await server.services.appConnection.cloudflare.listPermissionGroups(
+ connectionId,
+ req.permission
+ );
+ return permissionGroups;
+ }
+ });
};
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 f43e031005..a4c720b77e 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
@@ -2,6 +2,7 @@ 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";
@@ -10,11 +11,13 @@ import {
TCloudflareConnection,
TCloudflareConnectionConfig,
TCloudflarePagesProject,
+ TCloudflarePermissionGroup,
TCloudflareWorkersScript,
TCloudflareZone
} from "./cloudflare-connection-types";
const CLOUDFLARE_ZONES_PER_PAGE = 50;
+const CLOUDFLARE_PERMISSION_GROUPS_PER_PAGE = 50;
const CLOUDFLARE_MAX_PAGES = 100;
export const getCloudflareConnectionListItem = () => {
@@ -111,6 +114,52 @@ export const listCloudflareZones = async (appConnection: TCloudflareConnection):
return zones;
};
+export const listCloudflarePermissionGroups = async (
+ appConnection: TCloudflareConnection
+): Promise<TCloudflarePermissionGroup[]> => {
+ const {
+ credentials: { apiToken, accountId }
+ } = appConnection;
+
+ const permissionGroups: TCloudflarePermissionGroup[] = [];
+
+ 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: { 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
+ }
+ });
+
+ permissionGroups.push(
+ ...data.result.map((a) => ({
+ id: a.id,
+ name: a.name,
+ scopes: a.scopes ?? []
+ }))
+ );
+
+ // 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;
+ }
+
+ return permissionGroups;
+};
+
export const validateCloudflareConnectionCredentials = async (config: TCloudflareConnectionConfig) => {
const { apiToken, accountId } = config.credentials;
@@ -128,6 +177,7 @@ 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
diff --git a/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts b/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts
index c832ddb902..b8cbb086ef 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts
@@ -4,6 +4,7 @@ import { OrgServiceActor } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
import {
listCloudflarePagesProjects,
+ listCloudflarePermissionGroups,
listCloudflareWorkersScripts,
listCloudflareZones
} from "./cloudflare-connection-fns";
@@ -55,9 +56,24 @@ export const cloudflareConnectionService = (getAppConnection: TGetAppConnectionF
}
};
+ const listPermissionGroups = async (connectionId: string, actor: OrgServiceActor) => {
+ const appConnection = await getAppConnection(AppConnection.Cloudflare, connectionId, actor);
+ try {
+ const permissionGroups = await listCloudflarePermissionGroups(appConnection);
+ return permissionGroups;
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to list Cloudflare permission groups for Cloudflare connection [connectionId=${connectionId}]`
+ );
+ return [];
+ }
+ };
+
return {
listPagesProjects,
listWorkersScripts,
- listZones
+ listZones,
+ listPermissionGroups
};
};
diff --git a/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts b/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts
index 163bf64955..36f10ee931 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts
@@ -37,3 +37,10 @@ export type TCloudflareZone = {
id: string;
name: string;
};
+
+export type TCloudflarePermissionGroup = {
+ id: string;
+ name: string;
+ // the resource types this permission group can be attached to, e.g. "com.cloudflare.api.account.zone"
+ scopes: string[];
+};