Skip to content

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

feat: add support for r2 rotation

adilson6b1774d83902
diff --git a/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-r2-access-key-rotation-router.ts b/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-r2-access-key-rotation-router.ts
new file mode 100644
index 0000000000..ef8208f93c
--- /dev/null
+++ b/backend/src/ee/routes/v2/secret-rotation-v2-routers/cloudflare-r2-access-key-rotation-router.ts
@@ -0,0 +1,19 @@
+import {
+ CloudflareR2AccessKeyRotationGeneratedCredentialsSchema,
+ CloudflareR2AccessKeyRotationSchema,
+ CreateCloudflareR2AccessKeyRotationSchema,
+ UpdateCloudflareR2AccessKeyRotationSchema
+} from "@app/ee/services/secret-rotation-v2/cloudflare-r2-access-key";
+import { SecretRotation } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+
+import { registerSecretRotationEndpoints } from "./secret-rotation-v2-endpoints";
+
+export const registerCloudflareR2AccessKeyRotationRouter = async (server: FastifyZodProvider) =>
+ registerSecretRotationEndpoints({
+ type: SecretRotation.CloudflareR2AccessKey,
+ server,
+ responseSchema: CloudflareR2AccessKeyRotationSchema,
+ createSchema: CreateCloudflareR2AccessKeyRotationSchema,
+ updateSchema: UpdateCloudflareR2AccessKeyRotationSchema,
+ generatedCredentialsSchema: CloudflareR2AccessKeyRotationGeneratedCredentialsSchema
+ });
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 b740d4accb..ba0f6dd500 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
@@ -4,6 +4,7 @@ import { registerAuth0ClientSecretRotationRouter } from "./auth0-client-secret-r
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 { registerCloudflareR2AccessKeyRotationRouter } from "./cloudflare-r2-access-key-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";
@@ -60,5 +61,6 @@ export const SECRET_ROTATION_REGISTER_ROUTER_MAP: Record<
[SecretRotation.ConvexAccessKey]: registerConvexAccessKeyRotationRouter,
[SecretRotation.FireworksApiKey]: registerFireworksApiKeyRotationRouter,
[SecretRotation.SnowflakeUserKeyPair]: registerSnowflakeUserKeyPairRotationRouter,
- [SecretRotation.CloudflareApiToken]: registerCloudflareApiTokenRotationRouter
+ [SecretRotation.CloudflareApiToken]: registerCloudflareApiTokenRotationRouter,
+ [SecretRotation.CloudflareR2AccessKey]: registerCloudflareR2AccessKeyRotationRouter
};
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 3cb1aca7f5..cdeb5f6532 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
@@ -5,6 +5,7 @@ import { Auth0ClientSecretRotationListItemSchema } from "@app/ee/services/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 { CloudflareR2AccessKeyRotationListItemSchema } from "@app/ee/services/secret-rotation-v2/cloudflare-r2-access-key";
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";
@@ -61,7 +62,8 @@ const SecretRotationV2OptionsSchema = z.discriminatedUnion("type", [
ConvexAccessKeyRotationListItemSchema,
FireworksApiKeyRotationListItemSchema,
SnowflakeUserKeyPairRotationListItemSchema,
- CloudflareApiTokenRotationListItemSchema
+ CloudflareApiTokenRotationListItemSchema,
+ CloudflareR2AccessKeyRotationListItemSchema
]);
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
index b6dedee704..01a98efc5c 100644
--- 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
@@ -13,10 +13,3 @@ export const CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION: TSecretRotationV2ListIte
}
}
};
-
-/**
- * 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
index c654e4972e..c6618689cb 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
@@ -1,5 +1,3 @@
-import { AxiosError } from "axios";
-
import {
TRotationFactory,
TRotationFactoryCheckActiveCredentials,
@@ -8,23 +6,20 @@ import {
TRotationFactoryRevokeCredentials,
TRotationFactoryRotateCredentials
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
-import { BadRequestError } from "@app/lib/errors";
-import { logger } from "@app/lib/logger";
-import { safeRequest } from "@app/lib/validator";
import {
- getCloudflareAuthHeaders,
- getCloudflareErrorMessage
-} from "@app/services/app-connection/cloudflare/cloudflare-connection-fns";
-import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+ createCloudflareToken,
+ deleteCloudflareToken,
+ revokeCloudflareTokens,
+ TCloudflareTokenResources,
+ verifyCloudflareToken
+} from "@app/ee/services/secret-rotation-v2/shared/cloudflare-token";
+import { logger } from "@app/lib/logger";
-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
+ TCloudflareApiTokenRotationWithConnection
} from "./cloudflare-api-token-rotation-types";
export const cloudflareApiTokenRotationFactory: TRotationFactory<
@@ -39,13 +34,11 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
secretsMapping
} = secretRotation;
- const { accountId, apiToken } = connection.credentials;
-
- const authHeaders = getCloudflareAuthHeaders(apiToken);
+ const { accountId, apiToken: connectionApiToken } = connection.credentials;
// 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>> => {
+ const $buildResources = (policy: TCloudflareApiTokenPolicy): TCloudflareTokenResources => {
if (policy.scope === CloudflareApiTokenPolicyScope.Account) {
return { [`com.cloudflare.api.account.${accountId}`]: "*" };
}
@@ -59,81 +52,22 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
);
};
- // 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 safeRequest.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 { tokenId, tokenValue } = await createCloudflareToken({
+ accountId,
+ connectionApiToken,
+ name,
+ rotationInterval,
+ allowedIps,
+ disallowedIps,
+ policies: policies.map((policy) => ({
+ effect: policy.effect,
+ resources: $buildResources(policy),
+ permissionGroupIds: policy.permissionGroupIds
+ }))
+ });
- const $deleteToken = async (tokenId: string) => {
- try {
- await safeRequest.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)}`
- });
- }
+ return { tokenId, apiToken: tokenValue };
};
const issueCredentials: TRotationFactoryIssueCredentials<TCloudflareApiTokenRotationGeneratedCredentials> = async (
@@ -150,17 +84,11 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
) => {
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}]`
- );
- }
+ await revokeCloudflareTokens({
+ accountId,
+ connectionApiToken,
+ tokenIds: generatedCredentials.map((credential) => credential.tokenId),
+ logPrefix: `cloudflareApiTokenRotation: failed to revoke token during cleanup [rotationId=${rotationId}]`
});
return callback();
@@ -178,7 +106,7 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
if (credentialsToRevoke?.tokenId) {
try {
- await $deleteToken(credentialsToRevoke.tokenId);
+ await deleteCloudflareToken({ accountId, connectionApiToken, tokenId: credentialsToRevoke.tokenId });
} catch (error) {
logger.error(
error,
@@ -200,24 +128,7 @@ export const cloudflareApiTokenRotationFactory: TRotationFactory<
const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
TCloudflareApiTokenRotationGeneratedCredentials
> = async (activeCredentials) => {
- try {
- const { data } = await safeRequest.get<TCloudflareVerifyTokenResponse>(
- `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/verify`,
- { headers: getCloudflareAuthHeaders(activeCredentials.apiToken) }
- );
-
- 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: ${getCloudflareErrorMessage(error)}`
- });
- }
+ await verifyCloudflareToken({ accountId, tokenValue: activeCredentials.apiToken });
};
return {
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 4c0782e847..f0e9e14ff1 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
@@ -6,33 +6,24 @@ import {
BaseSecretRotationSchema,
BaseUpdateSecretRotationSchema
} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-schemas";
+import {
+ CloudflareTokenIpRestrictionSchema,
+ CloudflareTokenNameSchema,
+ CloudflareTokenPolicyEffect
+} from "@app/ee/services/secret-rotation-v2/shared/cloudflare-token";
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",
AllZones = "all-zones",
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),
+ effect: z.nativeEnum(CloudflareTokenPolicyEffect),
scope: z.nativeEnum(CloudflareApiTokenPolicyScope),
zoneIds: z.string().trim().array().optional(),
permissionGroupIds: z.string().trim().array().min(1, "At least one permission group is required")
@@ -66,22 +57,14 @@ export const CloudflareApiTokenRotationGeneratedCredentialsSchema = z
.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),
+ name: CloudflareTokenNameSchema.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()
+ allowedIps: CloudflareTokenIpRestrictionSchema.array()
.optional()
.describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.allowedIps),
- disallowedIps: IpRestrictionSchema.array()
+ disallowedIps: CloudflareTokenIpRestrictionSchema.array()
.optional()
.describe(SecretRotations.PARAMETERS.CLOUDFLARE_API_TOKEN.disallowedIps)
});
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
index 7295c783ba..bb0a07e818 100644
--- 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
@@ -25,20 +25,3 @@ export type TCloudflareApiTokenRotationGeneratedCredentials = z.infer<
>;
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-r2-access-key/cloudflare-r2-access-key-rotation-constants.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-constants.ts
new file mode 100644
index 0000000000..b422643ab6
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-constants.ts
@@ -0,0 +1,34 @@
+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";
+
+import { CloudflareR2AccessLevel } from "./cloudflare-r2-access-key-rotation-schemas";
+
+export const CLOUDFLARE_R2_ACCESS_KEY_ROTATION_LIST_OPTION: TSecretRotationV2ListItem = {
+ name: "Cloudflare R2 Access Key",
+ type: SecretRotation.CloudflareR2AccessKey,
+ connection: AppConnection.Cloudflare,
+ template: {
+ secretsMapping: {
+ apiToken: "CLOUDFLARE_R2_API_TOKEN",
+ accessKeyId: "CLOUDFLARE_R2_ACCESS_KEY_ID",
+ secretAccessKey: "CLOUDFLARE_R2_SECRET_ACCESS_KEY"
+ }
+ }
+};
+
+/** The resource scope Cloudflare reports for permission groups that attach to individual R2 buckets. */
+export const CLOUDFLARE_R2_BUCKET_PERMISSION_SCOPE = "com.cloudflare.edge.r2.bucket";
+
+/**
+ * Access levels resolve to Cloudflare's bucket-item permission groups by name — the ids are opaque and
+ * undocumented, so we look them up per account instead of hardcoding them. Read is granted alongside
+ * Write so a read-write key can always list and get objects.
+ */
+export const CLOUDFLARE_R2_ACCESS_LEVEL_PERMISSION_GROUPS: Record<CloudflareR2AccessLevel, string[]> = {
+ [CloudflareR2AccessLevel.ObjectRead]: ["Workers R2 Storage Bucket Item Read"],
+ [CloudflareR2AccessLevel.ObjectReadWrite]: [
+ "Workers R2 Storage Bucket Item Read",
+ "Workers R2 Storage Bucket Item Write"
+ ]
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-fns.ts
new file mode 100644
index 0000000000..d6dbc41cc1
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-fns.ts
@@ -0,0 +1,197 @@
+import {
+ TRotationFactory,
+ TRotationFactoryCheckActiveCredentials,
+ TRotationFactoryGetSecretsPayload,
+ TRotationFactoryIssueCredentials,
+ TRotationFactoryRevokeCredentials,
+ TRotationFactoryRotateCredentials
+} from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-types";
+import {
+ CloudflareTokenPolicyEffect,
+ createCloudflareToken,
+ deleteCloudflareToken,
+ revokeCloudflareTokens,
+ verifyCloudflareToken
+} from "@app/ee/services/secret-rotation-v2/shared/cloudflare-token";
+import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import {
+ getCloudflareErrorMessage,
+ listCloudflarePermissionGroups
+} from "@app/services/app-connection/cloudflare/cloudflare-connection-fns";
+import { TCloudflarePermissionGroup } from "@app/services/app-connection/cloudflare/cloudflare-connection-types";
+
+import {
+ CLOUDFLARE_R2_ACCESS_LEVEL_PERMISSION_GROUPS,
+ CLOUDFLARE_R2_BUCKET_PERMISSION_SCOPE
+} from "./cloudflare-r2-access-key-rotation-constants";
+import {
+ TCloudflareR2AccessKeyRotationGeneratedCredentials,
+ TCloudflareR2AccessKeyRotationWithConnection
+} from "./cloudflare-r2-access-key-rotation-types";
+
+export const cloudflareR2AccessKeyRotationFactory: TRotationFactory<
+ TCloudflareR2AccessKeyRotationWithConnection,
+ TCloudflareR2AccessKeyRotationGeneratedCredentials
+> = (secretRotation) => {
+ const {
+ id: rotationId,
+ connection,
+ rotationInterval,
+ parameters: { name, buckets, accessLevel, allowedIps, disallowedIps },
+ secretsMapping
+ } = secretRotation;
+
+ const { accountId, apiToken: connectionApiToken } = connection.credentials;
+
+ /**
+ * R2 grants object permissions per bucket, keyed by the bucket's name and jurisdiction. Cloudflare
+ * does not validate these keys when the token is created, so a bucket renamed or deleted after the
+ * rotation was configured yields a token that grants nothing rather than an error.
+ */
+ const $buildResources = (): Record<string, string> =>
+ Object.fromEntries(
+ buckets.map(({ name: bucketName, jurisdiction }) => [
+ `com.cloudflare.edge.r2.bucket.${accountId}_${jurisdiction}_${bucketName}`,
+ "*"
+ ])
+ );
+
+ /**
+ * R2's S3-compatible secret access key is the hex sha256 of the API token's value, and the access key
+ * id is the token's id. https://developers.cloudflare.com/r2/api/tokens/
+ */
+ const $toSecretAccessKey = (tokenValue: string) =>
+ crypto.nativeCrypto.createHash("sha256").update(tokenValue).digest("hex");
+
+ const $listPermissionGroups = async (): Promise<TCloudflarePermissionGroup[]> => {
+ try {
+ return await listCloudflarePermissionGroups(connection);
+ } catch (error: unknown) {
+ throw new BadRequestError({
+ message: `Failed to list Cloudflare permission groups: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+ };
+
+ const $resolvePermissionGroupIds = async () => {
+ const requiredNames = CLOUDFLARE_R2_ACCESS_LEVEL_PERMISSION_GROUPS[accessLevel];
+
+ const permissionGroups = await $listPermissionGroups();
+
+ return requiredNames.map((requiredName) => {
+ // groups reporting no scopes are accepted so an upstream response change can't break rotation
+ const permissionGroup = permissionGroups.find(
+ (group) =>
+ group.name === requiredName &&
+ (!group.scopes.length || group.scopes.includes(CLOUDFLARE_R2_BUCKET_PERMISSION_SCOPE))
+ );
+
+ if (!permissionGroup) {
+ throw new BadRequestError({
+ message: `Cloudflare permission group "${requiredName}" was not found on this account. Verify the connection's API token can read token permission groups.`
+ });
+ }
+
+ return permissionGroup.id;
+ });
+ };
+
+ const $createCredentials = async () => {
+ const permissionGroupIds = await $resolvePermissionGroupIds();
+
+ const { tokenId, tokenValue } = await createCloudflareToken({
+ accountId,
+ connectionApiToken,
+ name,
+ rotationInterval,
+ allowedIps,
+ disallowedIps,
+ policies: [
+ {
+ effect: CloudflareTokenPolicyEffect.Allow,
+ resources: $buildResources(),
+ permissionGroupIds
+ }
+ ]
+ });
+
+ return {
+ apiToken: tokenValue,
+ accessKeyId: tokenId,
+ secretAccessKey: $toSecretAccessKey(tokenValue)
+ };
+ };
+
+ const issueCredentials: TRotationFactoryIssueCredentials<TCloudflareR2AccessKeyRotationGeneratedCredentials> = async (
+ callback
+ ) => {
+ const credentials = await $createCredentials();
+
+ return callback(credentials);
+ };
+
+ const revokeCredentials: TRotationFactoryRevokeCredentials<
+ TCloudflareR2AccessKeyRotationGeneratedCredentials
+ > = async (generatedCredentials, callback) => {
+ if (!generatedCredentials?.length) return callback();
+
+ await revokeCloudflareTokens({
+ accountId,
+ connectionApiToken,
+ // the access key id *is* the underlying API token's id
+ tokenIds: generatedCredentials.map((credential) => credential.accessKeyId),
+ logPrefix: `cloudflareR2AccessKeyRotation: failed to revoke token during cleanup [rotationId=${rotationId}]`
+ });
+
+ return callback();
+ };
+
+ // We persist the new access key before revoking the old one so a revocation failure can never leave
+ // the rotation without a usable credential.
+ const rotateCredentials: TRotationFactoryRotateCredentials<
+ TCloudflareR2AccessKeyRotationGeneratedCredentials
+ > = async (credentialsToRevoke, callback) => {
+ const newCredentials = await $createCredentials();
+
+ const result = await callback(newCredentials);
+
+ if (credentialsToRevoke?.accessKeyId) {
+ try {
+ await deleteCloudflareToken({ accountId, connectionApiToken, tokenId: credentialsToRevoke.accessKeyId });
+ } catch (error) {
+ logger.error(
+ error,
+ `cloudflareR2AccessKeyRotation: failed to revoke previous token after rotation [rotationId=${rotationId}] [tokenId=${credentialsToRevoke.accessKeyId}]`
+ );
+ }
+ }
+
+ return result;
+ };
+
+ const getSecretsPayload: TRotationFactoryGetSecretsPayload<TCloudflareR2AccessKeyRotationGeneratedCredentials> = (
+ generatedCredentials
+ ) => [
+ { key: secretsMapping.apiToken, value: generatedCredentials.apiToken },
+ { key: secretsMapping.accessKeyId, value: generatedCredentials.accessKeyId },
+ { key: secretsMapping.secretAccessKey, value: generatedCredentials.secretAccessKey }
+ ];
+
+ // Introspecting the token is the only check that works for every access level — an S3 probe would
+ // fail for a write-only key, and listing buckets is an account-level permission the token lacks.
+ const checkActiveCredentials: TRotationFactoryCheckActiveCredentials<
+ TCloudflareR2AccessKeyRotationGeneratedCredentials
+ > = async (activeCredentials) => {
+ await verifyCloudflareToken({ accountId, tokenValue: activeCredentials.apiToken });
+ };
+
+ return {
+ issueCredentials,
+ revokeCredentials,
+ rotateCredentials,
+ getSecretsPayload,
+ checkActiveCredentials
+ };
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-schemas.ts
new file mode 100644
index 0000000000..24fef7e5f9
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-schemas.ts
@@ -0,0 +1,123 @@
+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 {
+ CloudflareTokenIpRestrictionSchema,
+ CloudflareTokenNameSchema
+} from "@app/ee/services/secret-rotation-v2/shared/cloudflare-token";
+import { SecretRotations } from "@app/lib/api-docs";
+import { SecretNameSchema } from "@app/server/lib/schemas";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { CloudflareR2Jurisdiction } from "@app/services/app-connection/cloudflare/cloudflare-connection-enum";
+
+export enum CloudflareR2AccessLevel {
+ ObjectRead = "object-read",
+ ObjectReadWrite = "object-read-write"
+}
+
+/** Cloudflare's own limit on R2 bucket names. */
+const CLOUDFLARE_R2_BUCKET_NAME_MAX_LENGTH = 64;
+
+/**
+ * A bucket is identified by name *and* jurisdiction: the policy resource key is
+ * `com.cloudflare.edge.r2.bucket.<accountId>_<jurisdiction>_<bucketName>`, and the same name can exist
+ * in more than one jurisdiction.
+ */
+export const CloudflareR2BucketSchema = z.object({
+ name: z
+ .string()
+ .trim()
+ .min(1, "Bucket name required")
+ .max(
+ CLOUDFLARE_R2_BUCKET_NAME_MAX_LENGTH,
+ `Bucket name must be ${CLOUDFLARE_R2_BUCKET_NAME_MAX_LENGTH} characters or fewer`
+ ),
+ jurisdiction: z.nativeEnum(CloudflareR2Jurisdiction).default(CloudflareR2Jurisdiction.Default)
+});
+
+export const CloudflareR2AccessKeyRotationGeneratedCredentialsSchema = z
+ .object({
+ // the underlying Cloudflare API token value, and the input to the secret access key hash
+ apiToken: z.string(),
+ // the API token's id — what R2's S3 API expects as the access key id, and what we delete on revoke
+ accessKeyId: z.string(),
+ // sha256 hex of `apiToken`
+ secretAccessKey: z.string()
+ })
+ .array()
+ .min(1)
+ .max(2);
+
+const CloudflareR2AccessKeyRotationParametersSchema = z.object({
+ name: CloudflareTokenNameSchema.describe(SecretRotations.PARAMETERS.CLOUDFLARE_R2_ACCESS_KEY.name),
+ buckets: CloudflareR2BucketSchema.array()
+ .min(1, "At least one bucket is required")
+ .superRefine((buckets, ctx) => {
+ const keys = buckets.map(({ name, jurisdiction }) => `${jurisdiction}:${name}`);
+
+ if (new Set(keys).size !== keys.length) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Buckets must be unique"
+ });
+ }
+ })
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_R2_ACCESS_KEY.buckets),
+ accessLevel: z
+ .nativeEnum(CloudflareR2AccessLevel)
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_R2_ACCESS_KEY.accessLevel),
+ allowedIps: CloudflareTokenIpRestrictionSchema.array()
+ .optional()
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_R2_ACCESS_KEY.allowedIps),
+ disallowedIps: CloudflareTokenIpRestrictionSchema.array()
+ .optional()
+ .describe(SecretRotations.PARAMETERS.CLOUDFLARE_R2_ACCESS_KEY.disallowedIps)
+});
+
+const CloudflareR2AccessKeyRotationSecretsMappingSchema = z.object({
+ apiToken: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.CLOUDFLARE_R2_ACCESS_KEY.apiToken),
+ accessKeyId: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.CLOUDFLARE_R2_ACCESS_KEY.accessKeyId),
+ secretAccessKey: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.CLOUDFLARE_R2_ACCESS_KEY.secretAccessKey)
+});
+
+export const CloudflareR2AccessKeyRotationTemplateSchema = z.object({
+ secretsMapping: z.object({
+ apiToken: z.string(),
+ accessKeyId: z.string(),
+ secretAccessKey: z.string()
+ })
+});
+
+export const CloudflareR2AccessKeyRotationSchema = BaseSecretRotationSchema(
+ SecretRotation.CloudflareR2AccessKey
+).extend({
+ type: z.literal(SecretRotation.CloudflareR2AccessKey),
+ parameters: CloudflareR2AccessKeyRotationParametersSchema,
+ secretsMapping: CloudflareR2AccessKeyRotationSecretsMappingSchema
+});
+
+export const CreateCloudflareR2AccessKeyRotationSchema = BaseCreateSecretRotationSchema(
+ SecretRotation.CloudflareR2AccessKey
+).extend({
+ parameters: CloudflareR2AccessKeyRotationParametersSchema,
+ secretsMapping: CloudflareR2AccessKeyRotationSecretsMappingSchema
+});
+
+export const UpdateCloudflareR2AccessKeyRotationSchema = BaseUpdateSecretRotationSchema(
+ SecretRotation.CloudflareR2AccessKey
+).extend({
+ parameters: CloudflareR2AccessKeyRotationParametersSchema.optional(),
+ secretsMapping: CloudflareR2AccessKeyRotationSecretsMappingSchema.optional()
+});
+
+export const CloudflareR2AccessKeyRotationListItemSchema = z.object({
+ name: z.literal("Cloudflare R2 Access Key"),
+ connection: z.literal(AppConnection.Cloudflare),
+ type: z.literal(SecretRotation.CloudflareR2AccessKey),
+ template: CloudflareR2AccessKeyRotationTemplateSchema
+});
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-types.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-types.ts
new file mode 100644
index 0000000000..09c30f5f60
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-rotation-types.ts
@@ -0,0 +1,28 @@
+import { z } from "zod";
+
+import { TCloudflareConnection } from "@app/services/app-connection/cloudflare/cloudflare-connection-types";
+
+import {
+ CloudflareR2AccessKeyRotationGeneratedCredentialsSchema,
+ CloudflareR2AccessKeyRotationListItemSchema,
+ CloudflareR2AccessKeyRotationSchema,
+ CloudflareR2BucketSchema,
+ CreateCloudflareR2AccessKeyRotationSchema
+} from "./cloudflare-r2-access-key-rotation-schemas";
+
+export type TCloudflareR2AccessKeyRotation = z.infer<typeof CloudflareR2AccessKeyRotationSchema>;
+
+export type TCloudflareR2AccessKeyRotationInput = z.infer<typeof CreateCloudflareR2AccessKeyRotationSchema>;
+
+export type TCloudflareR2AccessKeyRotationListItem = z.infer<typeof CloudflareR2AccessKeyRotationListItemSchema>;
+
+export type TCloudflareR2AccessKeyRotationWithConnection = TCloudflareR2AccessKeyRotation & {
+ connection: TCloudflareConnection;
+};
+
+export type TCloudflareR2AccessKeyRotationGeneratedCredentials = z.infer<
+ typeof CloudflareR2AccessKeyRotationGeneratedCredentialsSchema
+>;
+
+/** A bucket as selected on the rotation, distinct from the app connection's richer listing type. */
+export type TCloudflareR2AccessKeyBucket = z.infer<typeof CloudflareR2BucketSchema>;
diff --git a/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/index.ts b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/index.ts
new file mode 100644
index 0000000000..1f5bfbfacc
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/cloudflare-r2-access-key/index.ts
@@ -0,0 +1,3 @@
+export * from "./cloudflare-r2-access-key-rotation-constants";
+export * from "./cloudflare-r2-access-key-rotation-schemas";
+export * from "./cloudflare-r2-access-key-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 53397b2566..272a640ea0 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
@@ -25,7 +25,8 @@ export enum SecretRotation {
ConvexAccessKey = "convex-access-key",
FireworksApiKey = "fireworks-api-key",
SnowflakeUserKeyPair = "snowflake-user-key-pair",
- CloudflareApiToken = "cloudflare-api-token"
+ CloudflareApiToken = "cloudflare-api-token",
+ CloudflareR2AccessKey = "cloudflare-r2-access-key"
}
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 636042a4e8..fe47f51886 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
@@ -10,6 +10,7 @@ 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 { CLOUDFLARE_R2_ACCESS_KEY_ROTATION_LIST_OPTION } from "./cloudflare-r2-access-key";
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";
@@ -81,7 +82,8 @@ const SECRET_ROTATION_LIST_OPTIONS: Record<SecretRotation, TSecretRotationV2List
[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.CloudflareApiToken]: CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION
+ [SecretRotation.CloudflareApiToken]: CLOUDFLARE_API_TOKEN_ROTATION_LIST_OPTION,
+ [SecretRotation.CloudflareR2AccessKey]: CLOUDFLARE_R2_ACCESS_KEY_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 aaf219c0ec..3af6d642e7 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
@@ -28,7 +28,8 @@ export const SECRET_ROTATION_NAME_MAP: Record<SecretRotation, string> = {
[SecretRotation.ConvexAccessKey]: "Convex Access Key",
[SecretRotation.FireworksApiKey]: "Fireworks Secret",
[SecretRotation.SnowflakeUserKeyPair]: "Snowflake User Key Pair",
- [SecretRotation.CloudflareApiToken]: "Cloudflare API Token"
+ [SecretRotation.CloudflareApiToken]: "Cloudflare API Token",
+ [SecretRotation.CloudflareR2AccessKey]: "Cloudflare R2 Access Key"
};
export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnection> = {
@@ -58,5 +59,6 @@ export const SECRET_ROTATION_CONNECTION_MAP: Record<SecretRotation, AppConnectio
[SecretRotation.ConvexAccessKey]: AppConnection.Convex,
[SecretRotation.FireworksApiKey]: AppConnection.Fireworks,
[SecretRotation.SnowflakeUserKeyPair]: AppConnection.Snowflake,
- [SecretRotation.CloudflareApiToken]: AppConnection.Cloudflare
+ [SecretRotation.CloudflareApiToken]: AppConnection.Cloudflare,
+ [SecretRotation.CloudflareR2AccessKey]: 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 b37a29c28a..a3da0b630c 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
@@ -16,6 +16,7 @@ import {
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 { cloudflareR2AccessKeyRotationFactory } from "@app/ee/services/secret-rotation-v2/cloudflare-r2-access-key/cloudflare-r2-access-key-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";
@@ -215,7 +216,8 @@ const SECRET_ROTATION_FACTORY_MAP: Record<SecretRotation, TRotationFactoryImplem
[SecretRotation.ConvexAccessKey]: convexAccessKeyRotationFactory as TRotationFactoryImplementation,
[SecretRotation.FireworksApiKey]: fireworksApiKeyRotationFactory as TRotationFactoryImplementation,
[SecretRotation.SnowflakeUserKeyPair]: snowflakeUserKeyPairRotationFactory as TRotationFactoryImplementation,
- [SecretRotation.CloudflareApiToken]: cloudflareApiTokenRotationFactory as TRotationFactoryImplementation
+ [SecretRotation.CloudflareApiToken]: cloudflareApiTokenRotationFactory as TRotationFactoryImplementation,
+ [SecretRotation.CloudflareR2AccessKey]: cloudflareR2AccessKeyRotationFactory 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 05c6d53a25..62d824c700 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
@@ -37,6 +37,13 @@ import {
TCloudflareApiTokenRotationListItem,
TCloudflareApiTokenRotationWithConnection
} from "./cloudflare-api-token";
+import {
+ TCloudflareR2AccessKeyRotation,
+ TCloudflareR2AccessKeyRotationGeneratedCredentials,
+ TCloudflareR2AccessKeyRotationInput,
+ TCloudflareR2AccessKeyRotationListItem,
+ TCloudflareR2AccessKeyRotationWithConnection
+} from "./cloudflare-r2-access-key";
import {
TConvexAccessKeyRotation,
TConvexAccessKeyRotationGeneratedCredentials,
@@ -223,7 +230,8 @@ export type TSecretRotationV2 =
| TConvexAccessKeyRotation
| TFireworksApiKeyRotation
| TSnowflakeUserKeyPairRotation
- | TCloudflareApiTokenRotation;
+ | TCloudflareApiTokenRotation
+ | TCloudflareR2AccessKeyRotation;
export type TSecretRotationV2WithConnection =
| TPostgresCredentialsRotationWithConnection
@@ -252,7 +260,8 @@ export type TSecretRotationV2WithConnection =
| TConvexAccessKeyRotationWithConnection
| TFireworksApiKeyRotationWithConnection
| TSnowflakeUserKeyPairRotationWithConnection
- | TCloudflareApiTokenRotationWithConnection;
+ | TCloudflareApiTokenRotationWithConnection
+ | TCloudflareR2AccessKeyRotationWithConnection;
export type TSecretRotationV2GeneratedCredentials =
| TSqlCredentialsRotationGeneratedCredentials
@@ -277,7 +286,8 @@ export type TSecretRotationV2GeneratedCredentials =
| TConvexAccessKeyRotationGeneratedCredentials
| TFireworksApiKeyRotationGeneratedCredentials
| TSnowflakeUserKeyPairRotationGeneratedCredentials
- | TCloudflareApiTokenRotationGeneratedCredentials;
+ | TCloudflareApiTokenRotationGeneratedCredentials
+ | TCloudflareR2AccessKeyRotationGeneratedCredentials;
export type TSecretRotationV2Input =
| TPostgresCredentialsRotationInput
@@ -306,7 +316,8 @@ export type TSecretRotationV2Input =
| TConvexAccessKeyRotationInput
| TFireworksApiKeyRotationInput
| TSnowflakeUserKeyPairRotationInput
- | TCloudflareApiTokenRotationInput;
+ | TCloudflareApiTokenRotationInput
+ | TCloudflareR2AccessKeyRotationInput;
export type TSecretRotationV2ListItem =
| TPostgresCredentialsRotationListItem
@@ -335,7 +346,8 @@ export type TSecretRotationV2ListItem =
| TConvexAccessKeyRotationListItem
| TFireworksApiKeyRotationListItem
| TSnowflakeUserKeyPairRotationListItem
- | TCloudflareApiTokenRotationListItem;
+ | TCloudflareApiTokenRotationListItem
+ | TCloudflareR2AccessKeyRotationListItem;
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 1822d11100..25e9da1bce 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
@@ -22,6 +22,7 @@ import { UnixLinuxLocalAccountRotationSchema } from "@app/ee/services/secret-rot
import { WindowsLocalAccountRotationSchema } from "@app/ee/services/secret-rotation-v2/windows-local-account-rotation";
import { CloudflareApiTokenRotationSchema } from "./cloudflare-api-token";
+import { CloudflareR2AccessKeyRotationSchema } from "./cloudflare-r2-access-key";
import { ConvexAccessKeyRotationSchema } from "./convex-access-key";
import { DbtServiceTokenRotationSchema } from "./dbt-service-token";
import { FireworksApiKeyRotationSchema } from "./fireworks-api-key";
@@ -56,5 +57,6 @@ export const SecretRotationV2Schema = z.discriminatedUnion("type", [
ConvexAccessKeyRotationSchema,
FireworksApiKeyRotationSchema,
SnowflakeUserKeyPairRotationSchema,
- CloudflareApiTokenRotationSchema
+ CloudflareApiTokenRotationSchema,
+ CloudflareR2AccessKeyRotationSchema
]);
diff --git a/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-constants.ts b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-constants.ts
new file mode 100644
index 0000000000..0540e6cdec
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-constants.ts
@@ -0,0 +1,12 @@
+/**
+ * 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_TOKEN_MIN_TTL_DAYS = 7;
+
+/**
+ * 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_TOKEN_NAME_MAX_LENGTH = 100;
diff --git a/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-fns.ts
new file mode 100644
index 0000000000..17743bfc8a
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-fns.ts
@@ -0,0 +1,176 @@
+import { AxiosError } from "axios";
+
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator";
+import {
+ getCloudflareAuthHeaders,
+ getCloudflareErrorMessage
+} from "@app/services/app-connection/cloudflare/cloudflare-connection-fns";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+import { CLOUDFLARE_TOKEN_MIN_TTL_DAYS } from "./cloudflare-token-rotation-constants";
+import {
+ TCloudflareCreateTokenResponse,
+ TCloudflareTokenCondition,
+ TCloudflareTokenCredentials,
+ TCloudflareTokenPolicyInput,
+ TCloudflareTokenRestrictions,
+ TCloudflareVerifyTokenResponse
+} from "./cloudflare-token-rotation-types";
+
+export const getCloudflareTokenExpiresOn = (rotationInterval: number) => {
+ const days = Math.max(rotationInterval * 2 + 1, CLOUDFLARE_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");
+};
+
+// an empty `in` list would deny every request, so we omit either side rather than sending []
+export const buildCloudflareTokenCondition = ({
+ allowedIps,
+ disallowedIps
+}: TCloudflareTokenRestrictions): TCloudflareTokenCondition | undefined => {
+ if (!allowedIps?.length && !disallowedIps?.length) return undefined;
+
+ return {
+ "request.ip": {
+ ...(allowedIps?.length ? { in: allowedIps } : {}),
+ ...(disallowedIps?.length ? { not_in: disallowedIps } : {})
+ }
+ };
+};
+
+export const createCloudflareToken = async ({
+ accountId,
+ connectionApiToken,
+ name,
+ policies,
+ rotationInterval,
+ allowedIps,
+ disallowedIps
+}: {
+ accountId: string;
+ /** the app connection's token, which is what authorizes the create call */
+ connectionApiToken: string;
+ /** the user-supplied base name; a timestamp is appended so each rotated token is distinct */
+ name: string;
+ policies: TCloudflareTokenPolicyInput[];
+ rotationInterval: number;
+} & TCloudflareTokenRestrictions): Promise<TCloudflareTokenCredentials> => {
+ try {
+ const { data } = await safeRequest.post<TCloudflareCreateTokenResponse>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens`,
+ {
+ name: `${name}-${Date.now()}`,
+ policies: policies.map((policy) => ({
+ effect: policy.effect,
+ resources: policy.resources,
+ permission_groups: policy.permissionGroupIds.map((id) => ({ id }))
+ })),
+ expires_on: getCloudflareTokenExpiresOn(rotationInterval),
+ condition: buildCloudflareTokenCondition({ allowedIps, disallowedIps })
+ },
+ {
+ headers: {
+ ...getCloudflareAuthHeaders(connectionApiToken),
+ "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, tokenValue: data.result.value };
+ } catch (error: unknown) {
+ if (error instanceof BadRequestError) throw error;
+
+ throw new BadRequestError({
+ message: `Failed to create Cloudflare API token: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+};
+
+export const deleteCloudflareToken = async ({
+ accountId,
+ connectionApiToken,
+ tokenId
+}: {
+ accountId: string;
+ connectionApiToken: string;
+ tokenId: string;
+}) => {
+ try {
+ await safeRequest.delete(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/${encodeURIComponent(tokenId)}`,
+ { headers: getCloudflareAuthHeaders(connectionApiToken) }
+ );
+ } 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)}`
+ });
+ }
+};
+
+/**
+ * Best-effort revocation of every listed token. Used by the cleanup paths, where a failure must not
+ * abort the remaining deletions, so each one is logged rather than thrown.
+ */
+export const revokeCloudflareTokens = async ({
+ accountId,
+ connectionApiToken,
+ tokenIds,
+ logPrefix
+}: {
+ accountId: string;
+ connectionApiToken: string;
+ tokenIds: string[];
+ /** identifies the caller in the log line, e.g. `cloudflareApiTokenRotation: ... [rotationId=...]` */
+ logPrefix: string;
+}) => {
+ const results = await Promise.allSettled(
+ tokenIds.map((tokenId) => deleteCloudflareToken({ accountId, connectionApiToken, tokenId }))
+ );
+
+ results.forEach((result, index) => {
+ if (result.status === "rejected") {
+ logger.error(result.reason, `${logPrefix} [tokenId=${tokenIds[index]}]`);
+ }
+ });
+};
+
+/**
+ * Verifies a generated token by introspecting it with itself as the bearer — the connection's token
+ * cannot tell us whether the generated one is still active.
+ */
+export const verifyCloudflareToken = async ({ accountId, tokenValue }: { accountId: string; tokenValue: string }) => {
+ try {
+ const { data } = await safeRequest.get<TCloudflareVerifyTokenResponse>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/verify`,
+ { headers: getCloudflareAuthHeaders(tokenValue) }
+ );
+
+ 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: ${getCloudflareErrorMessage(error)}`
+ });
+ }
+};
diff --git a/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-schemas.ts
new file mode 100644
index 0000000000..a172ab91b9
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-schemas.ts
@@ -0,0 +1,22 @@
+import { z } from "zod";
+
+import { isValidIpOrCidr } from "@app/lib/ip";
+
+import { CLOUDFLARE_TOKEN_NAME_MAX_LENGTH } from "./cloudflare-token-rotation-constants";
+
+export enum CloudflareTokenPolicyEffect {
+ Allow = "allow",
+ Deny = "deny"
+}
+
+export const CloudflareTokenIpRestrictionSchema = z
+ .string()
+ .trim()
+ .refine(isValidIpOrCidr, "Must be a valid IP address or CIDR block");
+
+// Each rotation applies its own `.describe()` so the OpenAPI text stays rotation-specific.
+export const CloudflareTokenNameSchema = z
+ .string()
+ .trim()
+ .min(1, "Token name required")
+ .max(CLOUDFLARE_TOKEN_NAME_MAX_LENGTH, `Token name must be ${CLOUDFLARE_TOKEN_NAME_MAX_LENGTH} characters or fewer`);
diff --git a/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-types.ts b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-types.ts
new file mode 100644
index 0000000000..114c476c5d
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/cloudflare-token-rotation-types.ts
@@ -0,0 +1,52 @@
+import { CloudflareTokenPolicyEffect } from "./cloudflare-token-rotation-schemas";
+
+/**
+ * The `resources` map of a token policy. Most scopes map a resource id to the "*" string, but
+ * all-zones is expressed as a nested object instead.
+ * https://developers.cloudflare.com/fundamentals/api/how-to/create-via-api/
+ */
+export type TCloudflareTokenResources = Record<string, string | Record<string, string>>;
+
+export type TCloudflareTokenPolicyInput = {
+ effect: CloudflareTokenPolicyEffect;
+ resources: TCloudflareTokenResources;
+ permissionGroupIds: string[];
+};
+
+/**
+ * What Cloudflare hands back when a token is created. `tokenValue` is deliberately not named
+ * `apiToken`: each rotation decides what to call it once persisted.
+ */
+export type TCloudflareTokenCredentials = {
+ tokenId: string;
+ tokenValue: string;
+};
+
+export type TCloudflareTokenRestrictions = {
+ allowedIps?: string[];
+ disallowedIps?: string[];
+};
+
+export type TCloudflareTokenCondition = {
+ "request.ip": {
+ in?: string[];
+ not_in?: string[];
+ };
+};
+
+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/shared/cloudflare-token/index.ts b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/index.ts
new file mode 100644
index 0000000000..d54bf6162d
--- /dev/null
+++ b/backend/src/ee/services/secret-rotation-v2/shared/cloudflare-token/index.ts
@@ -0,0 +1,4 @@
+export * from "./cloudflare-token-rotation-constants";
+export * from "./cloudflare-token-rotation-fns";
+export * from "./cloudflare-token-rotation-schemas";
+export * from "./cloudflare-token-rotation-types";
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 4d367c1a37..576aff6275 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -3581,6 +3581,15 @@ export const SecretRotations = {
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."
},
+ CLOUDFLARE_R2_ACCESS_KEY: {
+ name: "The name for the generated Cloudflare API token that backs the R2 access key.",
+ buckets:
+ "The R2 buckets the generated access key is scoped to. Each entry is a bucket name plus its jurisdiction (default, eu, or fedramp).",
+ accessLevel:
+ "The level of access the generated key has over the selected buckets (object-read for read and list, object-read-write to also write).",
+ allowedIps: "The IP addresses or CIDR blocks the generated R2 access key is restricted to.",
+ disallowedIps: "The IP addresses or CIDR blocks the generated R2 access key is denied from."
+ },
CONVEX_ACCESS_KEY: {
namePrefix: "A prefix to use when naming the generated Convex access key."
},
@@ -3677,6 +3686,11 @@ export const SecretRotations = {
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."
},
+ CLOUDFLARE_R2_ACCESS_KEY: {
+ apiToken: "The name of the secret that the rotated Cloudflare API token value will be mapped to.",
+ accessKeyId: "The name of the secret that the rotated R2 access key ID will be mapped to.",
+ secretAccessKey: "The name of the secret that the rotated R2 secret access key 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 ad635a5146..2126edcf02 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
@@ -3,6 +3,7 @@ import z from "zod";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { CloudflareR2Jurisdiction } from "@app/services/app-connection/cloudflare/cloudflare-connection-enum";
import {
CreateCloudflareConnectionSchema,
SanitizedCloudflareConnectionSchema,
@@ -140,4 +141,36 @@ export const registerCloudflareConnectionRouter = async (server: FastifyZodProvi
return permissionGroups;
}
});
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/cloudflare-r2-buckets`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listCloudflareR2Buckets",
+ params: z.object({
+ connectionId: z.string().uuid()
+ }),
+ response: {
+ 200: z
+ .object({
+ name: z.string(),
+ jurisdiction: z.nativeEnum(CloudflareR2Jurisdiction),
+ location: z.string().optional(),
+ storageClass: z.string().optional(),
+ creationDate: z.string().optional()
+ })
+ .array()
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+
+ const buckets = await server.services.appConnection.cloudflare.listR2Buckets(connectionId, req.permission);
+ return buckets;
+ }
+ });
};
diff --git a/backend/src/services/app-connection/cloudflare/cloudflare-connection-enum.ts b/backend/src/services/app-connection/cloudflare/cloudflare-connection-enum.ts
index 2381524b99..2fd5d7011b 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-enum.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-enum.ts
@@ -1,3 +1,14 @@
export enum CloudflareConnectionMethod {
APIToken = "api-token"
}
+
+/**
+ * The storage jurisdiction of an R2 bucket. It is part of the bucket's identity: the bucket's token
+ * policy resource key is `com.cloudflare.edge.r2.bucket.<accountId>_<jurisdiction>_<bucketName>`, and
+ * the same bucket name can exist in more than one jurisdiction.
+ */
+export enum CloudflareR2Jurisdiction {
+ Default = "default",
+ Eu = "eu",
+ FedRamp = "fedramp"
+}
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 0c2664d4b2..bacf908e80 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-fns.ts
@@ -1,16 +1,19 @@
import { AxiosError } from "axios";
import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { safeRequest } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
-import { CloudflareConnectionMethod } from "./cloudflare-connection-enum";
+import { CloudflareConnectionMethod, CloudflareR2Jurisdiction } from "./cloudflare-connection-enum";
import {
TCloudflareConnection,
TCloudflareConnectionConfig,
TCloudflarePagesProject,
TCloudflarePermissionGroup,
+ TCloudflareR2Bucket,
+ TCloudflareR2BucketsApiResponse,
TCloudflareWorkersScript,
TCloudflareZone
} from "./cloudflare-connection-types";
@@ -19,6 +22,9 @@ import {
const CLOUDFLARE_PER_PAGE = 50;
const CLOUDFLARE_MAX_PAGES = 100;
+// R2 accepts up to 1000 per page; 100 keeps responses small while rarely needing a second request
+const CLOUDFLARE_R2_BUCKETS_PER_PAGE = 100;
+
export const getCloudflareAuthHeaders = (apiToken: string) => ({
Authorization: `Bearer ${apiToken}`,
Accept: "application/json"
@@ -130,30 +136,89 @@ export const listCloudflarePermissionGroups = async (
credentials: { apiToken, accountId }
} = appConnection;
- const permissionGroups: TCloudflarePermissionGroup[] = [];
+ const { data } = await safeRequest.get<{
+ result: { id: string; name: string; scopes?: string[] }[];
+ result_info?: { count?: number };
+ }>(`${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/permission_groups`, {
+ headers: getCloudflareAuthHeaders(apiToken)
+ });
+
+ return data.result.map((a) => ({
+ id: a.id,
+ name: a.name,
+ scopes: a.scopes ?? []
+ }));
+};
- for (let page = 1; page <= CLOUDFLARE_MAX_PAGES; page += 1) {
+/**
+ * Unlike the other list endpoints, `r2/buckets` returns its array under `result.buckets` and paginates
+ * with an opaque cursor from `result_info.cursor` rather than reporting `result_info.total_pages`, so
+ * it can't go through `$paginateCloudflare`.
+ */
+const $listCloudflareR2BucketsForJurisdiction = async ({
+ accountId,
+ apiToken,
+ jurisdiction
+}: {
+ accountId: string;
+ apiToken: string;
+ jurisdiction: CloudflareR2Jurisdiction;
+}): Promise<TCloudflareR2Bucket[]> => {
+ const buckets: TCloudflareR2Bucket[] = [];
+
+ let cursor: string | undefined;
+
+ for (let page = 0; page < CLOUDFLARE_MAX_PAGES; page += 1) {
// eslint-disable-next-line no-await-in-loop
- const { data } = await safeRequest.get<{ result: { id: string; name: string; scopes?: string[] }[] }>(
- `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/tokens/permission_groups`,
+ const { data } = await safeRequest.get<TCloudflareR2BucketsApiResponse>(
+ `${IntegrationUrls.CLOUDFLARE_API_URL}/client/v4/accounts/${accountId}/r2/buckets`,
{
- headers: getCloudflareAuthHeaders(apiToken),
- params: { page, per_page: CLOUDFLARE_PER_PAGE }
+ headers: { ...getCloudflareAuthHeaders(apiToken), "cf-r2-jurisdiction": jurisdiction },
+ params: { per_page: CLOUDFLARE_R2_BUCKETS_PER_PAGE, ...(cursor ? { cursor } : {}) }
}
);
- permissionGroups.push(
- ...data.result.map((a) => ({
- id: a.id,
- name: a.name,
- scopes: a.scopes ?? []
+ buckets.push(
+ ...(data.result?.buckets ?? []).map((bucket) => ({
+ name: bucket.name,
+ // the payload omits the jurisdiction for `default`, so fall back to the one we asked for
+ jurisdiction: (bucket.jurisdiction as CloudflareR2Jurisdiction) || jurisdiction,
+ location: bucket.location,
+ storageClass: bucket.storage_class,
+ creationDate: bucket.creation_date
}))
);
- if (data.result.length < CLOUDFLARE_PER_PAGE) break;
+ cursor = data.result_info?.cursor || undefined;
+ if (!cursor) break;
}
- return permissionGroups;
+ return buckets;
+};
+
+export const listCloudflareR2Buckets = async (appConnection: TCloudflareConnection): Promise<TCloudflareR2Bucket[]> => {
+ const {
+ credentials: { apiToken, accountId }
+ } = appConnection;
+
+ const jurisdictions = Object.values(CloudflareR2Jurisdiction);
+
+ // A bucket's jurisdiction is only reachable by asking for it, and accounts without EU/FedRAMP
+ // enabled reject those requests — a failure in one jurisdiction must not hide the others' buckets.
+ const results = await Promise.allSettled(
+ jurisdictions.map((jurisdiction) => $listCloudflareR2BucketsForJurisdiction({ accountId, apiToken, jurisdiction }))
+ );
+
+ return results.flatMap((result, index) => {
+ if (result.status === "fulfilled") return result.value;
+
+ logger.error(
+ result.reason,
+ `listCloudflareR2Buckets: skipping unavailable jurisdiction [jurisdiction=${jurisdictions[index]}]`
+ );
+
+ return [];
+ });
};
export const validateCloudflareConnectionCredentials = async (config: TCloudflareConnectionConfig) => {
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 b8cbb086ef..25e293a2ae 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-service.ts
@@ -5,6 +5,7 @@ import { AppConnection } from "../app-connection-enums";
import {
listCloudflarePagesProjects,
listCloudflarePermissionGroups,
+ listCloudflareR2Buckets,
listCloudflareWorkersScripts,
listCloudflareZones
} from "./cloudflare-connection-fns";
@@ -70,10 +71,25 @@ export const cloudflareConnectionService = (getAppConnection: TGetAppConnectionF
}
};
+ const listR2Buckets = async (connectionId: string, actor: OrgServiceActor) => {
+ const appConnection = await getAppConnection(AppConnection.Cloudflare, connectionId, actor);
+ try {
+ const buckets = await listCloudflareR2Buckets(appConnection);
+ return buckets;
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to list Cloudflare R2 buckets for Cloudflare connection [connectionId=${connectionId}]`
+ );
+ return [];
+ }
+ };
+
return {
listPagesProjects,
listWorkersScripts,
listZones,
- listPermissionGroups
+ listPermissionGroups,
+ listR2Buckets
};
};
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 36f10ee931..d039eeaebc 100644
--- a/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts
+++ b/backend/src/services/app-connection/cloudflare/cloudflare-connection-types.ts
@@ -3,6 +3,7 @@ import z from "zod";
import { DiscriminativePick } from "@app/lib/types";
import { AppConnection } from "../app-connection-enums";
+import { CloudflareR2Jurisdiction } from "./cloudflare-connection-enum";
import {
CloudflareConnectionSchema,
CreateCloudflareConnectionSchema,
@@ -44,3 +45,26 @@ export type TCloudflarePermissionGroup = {
// the resource types this permission group can be attached to, e.g. "com.cloudflare.api.account.zone"
scopes: string[];
};
+
+export type TCloudflareR2Bucket = {
+ name: string;
+ jurisdiction: CloudflareR2Jurisdiction;
+ // the physical region the bucket's data lives in, e.g. "weur" — informational only
+ location?: string;
+ storageClass?: string;
+ creationDate?: string;
+};
+
+/** Raw shape returned by Cloudflare's `GET /accounts/:id/r2/buckets` list endpoint. */
+export type TCloudflareR2BucketsApiResponse = {
+ result: {
+ buckets?: {
+ name: string;
+ creation_date?: string;
+ jurisdiction?: string;
+ location?: string;
+ storage_class?: string;
+ }[];
+ } | null;
+ result_info?: { cursor?: string };
+};