Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix: UI and permissions
varonix6690c50dd297
diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.test.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.test.tsnew file mode 100644index 0000000000..d2b3028d2b--- /dev/null+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.test.ts@@ -0,0 +1,24 @@+import { STRIPE_API_KEY_PERMISSION_GROUPS, STRIPE_API_KEY_PERMISSIONS } from "./stripe-api-key-rotation-constants";++describe("STRIPE_API_KEY_PERMISSION_GROUPS", () => {+ const cataloged = STRIPE_API_KEY_PERMISSION_GROUPS.flatMap(({ resources }) =>+ resources.flatMap(({ read, write }) => [read, write].filter(Boolean))+ );++ test("lists every accepted permission exactly once", () => {+ expect([...cataloged].sort()).toEqual([...STRIPE_API_KEY_PERMISSIONS].sort());+ });++ test("gives every resource at least one permission", () => {+ STRIPE_API_KEY_PERMISSION_GROUPS.forEach(({ resources }) =>+ resources.forEach((resource) => expect(resource.read ?? resource.write).toBeDefined())+ );+ });++ test("keeps resource names unique within a group", () => {+ STRIPE_API_KEY_PERMISSION_GROUPS.forEach(({ resources }) => {+ const names = resources.map(({ name }) => name);+ expect(new Set(names).size).toBe(names.length);+ });+ });+});diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.tsindex 8471d5863e..63a5125432 100644--- a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.ts+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-constants.ts@@ -168,6 +168,225 @@ export const STRIPE_API_KEY_PERMISSIONS = ["webhook_write"] as const;+export type TStripeApiKeyPermission = (typeof STRIPE_API_KEY_PERMISSIONS)[number];++export type TStripeApiKeyPermissionResource = {+ name: string;+ read?: TStripeApiKeyPermission;+ write?: TStripeApiKeyPermission;+};++export type TStripeApiKeyPermissionGroup = {+ name: string;+ resources: TStripeApiKeyPermissionResource[];+};++/**+ * The permissions above as the Stripe dashboard presents them: one resource per row, with the read+ * and write permission it supports. Clients render this rather than parsing permission names, so a+ * permission added above needs a row here too (the constants test enforces it).+ */+export const STRIPE_API_KEY_PERMISSION_GROUPS: TStripeApiKeyPermissionGroup[] = [+ {+ name: "Core",+ resources: [+ { name: "Apple Pay domains", read: "apple_pay_domain_read", write: "apple_pay_domain_write" },+ { name: "Balance", read: "balance_read" },+ { name: "Balance transaction sources", read: "balance_transaction_source_read" },+ { name: "Charges and refunds", read: "charge_read", write: "charge_write" },+ { name: "Confirmation tokens", read: "confirmation_token_read" },+ {+ name: "Confirmation tokens (client)",+ read: "confirmation_token_client_read",+ write: "confirmation_token_client_write"+ },+ { name: "Customers", read: "customer_read", write: "customer_write" },+ { name: "Customer sessions", read: "customer_session_read", write: "customer_session_write" },+ { name: "Disputes", read: "dispute_read", write: "dispute_write" },+ { name: "Events", read: "event_read" },+ { name: "Files", read: "file_read", write: "file_write" },+ { name: "Mandates", read: "mandate_read", write: "mandate_write" },+ { name: "Payment intents", read: "payment_intent_read", write: "payment_intent_write" },+ { name: "Payment methods", read: "payment_method_read", write: "payment_method_write" },+ {+ name: "Payment method configurations",+ read: "payment_method_configurations_read",+ write: "payment_method_configurations_write"+ },+ {+ name: "Payment method domains",+ read: "payment_method_domain_read",+ write: "payment_method_domain_write"+ },+ { name: "Payment records", read: "payment_records_read", write: "payment_records_write" },+ { name: "Payouts", read: "payout_read", write: "payout_write" },+ { name: "Payout intents", read: "payout_intent_read" },+ { name: "Products", read: "product_read", write: "product_write" },+ { name: "Reviews", read: "review_read", write: "review_write" },+ { name: "Setup intents", read: "setup_intent_read", write: "setup_intent_write" },+ { name: "Sources", read: "source_read", write: "source_write" },+ { name: "Tokens", read: "token_read", write: "token_write" },+ { name: "Transactions", read: "transaction_read" }+ ]+ },+ {+ name: "Checkout",+ resources: [+ { name: "Checkout sessions", read: "checkout_session_read", write: "checkout_session_write" },+ { name: "Payment links", read: "payment_links_read", write: "payment_links_write" },+ { name: "Shipping rates", read: "shipping_rate_read", write: "shipping_rate_write" }+ ]+ },+ {+ name: "Billing",+ resources: [+ { name: "Billing profiles", read: "billing_profile_read", write: "billing_profile_write" },+ { name: "Billing settings", read: "billing_settings_read", write: "billing_settings_write" },+ { name: "Billing intents", read: "billing_intent_read" },+ { name: "Coupons", read: "coupon_read", write: "coupon_write" },+ { name: "Credit notes", read: "credit_note_read", write: "credit_note_write" },+ { name: "Customer portal", read: "customer_portal_read", write: "customer_portal_write" },+ { name: "Entitlements", read: "entitlement_read" },+ { name: "Invoices", read: "invoice_read", write: "invoice_write" },+ { name: "Meters", read: "billing_meter_read", write: "billing_meter_write" },+ { name: "Meter events", read: "billing_meter_event_read", write: "billing_meter_event_write" },+ { name: "Meter usage analytics", read: "billing_analytics_meter_usage_read" },+ { name: "Plans and prices", read: "plan_read", write: "plan_write" },+ {+ name: "Product catalog imports",+ read: "product_catalog_import_read",+ write: "product_catalog_import_write"+ },+ { name: "Promotion codes", read: "promotion_code_read", write: "promotion_code_write" },+ { name: "Quotes", read: "quote_read", write: "quote_write" },+ { name: "Rate cards", write: "rate_card_write" },+ { name: "Rate card subscriptions", write: "rate_card_subscription_write" },+ { name: "Subscriptions", read: "subscription_read", write: "subscription_write" },+ { name: "Test clocks", read: "billing_clock_read", write: "billing_clock_write" },+ { name: "Usage records", read: "usage_record_read", write: "usage_record_write" }+ ]+ },+ {+ name: "Tax",+ resources: [+ {+ name: "Tax calculations and transactions",+ read: "tax_calculations_and_transactions_read",+ write: "tax_calculations_and_transactions_write"+ },+ { name: "Tax locations", read: "tax_locations_read", write: "tax_locations_write" },+ { name: "Tax rates", read: "tax_rate_read", write: "tax_rate_write" },+ { name: "Tax settings", read: "tax_settings_read", write: "tax_settings_write" }+ ]+ },+ {+ name: "Connect",+ resources: [+ { name: "Account links", write: "account_link_write" },+ { name: "Application fees", read: "application_fee_read", write: "application_fee_write" },+ { name: "Connected accounts", read: "connected_account_read" },+ { name: "Edit links", write: "edit_link_write" },+ { name: "Fee domain resources", read: "fee_domain_resources_read" },+ { name: "Top-ups", read: "top_up_read", write: "top_up_write" },+ { name: "Transfers", read: "transfer_read", write: "transfer_write" }+ ]+ },+ {+ name: "Capital",+ resources: [+ {+ name: "Financing offers",+ read: "capital_for_platforms_financing_offer_read",+ write: "capital_for_platforms_financing_offer_write"+ },+ { name: "Financing summary", read: "capital_for_platforms_financing_summary_read" },+ { name: "Financing transactions", read: "capital_for_platforms_financing_transaction_read" }+ ]+ },+ {+ name: "Orders",+ resources: [+ { name: "Orders", read: "order_read", write: "order_write" },+ { name: "SKUs", read: "sku_read", write: "sku_write" }+ ]+ },+ {+ name: "Issuing",+ resources: [+ { name: "All Issuing resources", read: "issuing_read", write: "issuing_write" },+ { name: "Authorizations", read: "issuing_authorization_read", write: "issuing_authorization_write" },+ { name: "Cards", read: "issuing_card_read", write: "issuing_card_write" },+ { name: "Cardholders", read: "issuing_cardholder_read", write: "issuing_cardholder_write" },+ { name: "Credit ledger", read: "issuing_credit_ledger_read", write: "issuing_credit_ledger_write" },+ { name: "Disputes", read: "issuing_dispute_read", write: "issuing_dispute_write" },+ { name: "Tokens", read: "issuing_token_read", write: "issuing_token_write" },+ { name: "Token network data", read: "issuing_token_network_data_read" },+ { name: "Transactions", read: "issuing_transaction_read", write: "issuing_transaction_write" },+ { name: "Verifications", write: "issuing_verification_write" }+ ]+ },+ {+ name: "Treasury",+ resources: [+ { name: "Financial accounts", read: "financial_account_read" },+ { name: "Inbound transfers", read: "inbound_transfer_read" },+ { name: "Outbound payments", read: "outbound_payment_read" },+ { name: "Outbound transfers", read: "outbound_transfer_read" },+ { name: "Received credits", read: "received_credit_read" },+ { name: "Received debits", read: "received_debit_read" },+ { name: "Recipient verifications", read: "recipient_verification_read" },+ { name: "Transactions", read: "treasury_transaction_read" }+ ]+ },+ {+ name: "Terminal",+ resources: [+ {+ name: "Configurations",+ read: "terminal_configuration_read",+ write: "terminal_configuration_write"+ },+ { name: "Connection tokens", write: "terminal_connection_token_write" },+ { name: "Locations", read: "terminal_location_read", write: "terminal_location_write" },+ { name: "Readers", read: "terminal_reader_read", write: "terminal_reader_write" }+ ]+ },+ {+ name: "Reporting",+ resources: [+ { name: "Adjustments", read: "adjustment_read" },+ {+ name: "Report runs and report types",+ read: "report_runs_and_report_types_read",+ write: "report_runs_and_report_types_write"+ }+ ]+ },+ {+ name: "Developers",+ resources: [+ { name: "API keys", write: "api_key_write" },+ {+ name: "Provisioning account requests",+ read: "provisioning_account_request_read",+ write: "provisioning_account_request_write"+ },+ {+ name: "Provisioning projects",+ read: "provisioning_project_read",+ write: "provisioning_project_write"+ },+ {+ name: "Provisioning resources",+ read: "provisioning_resource_read",+ write: "provisioning_resource_write"+ },+ { name: "Secrets", read: "secret_read", write: "secret_write" },+ { name: "Webhook endpoints", read: "webhook_read", write: "webhook_write" }+ ]+ }+];+export const STRIPE_API_KEY_ROTATION_LIST_OPTION: TSecretRotationV2ListItem = {name: "Stripe API Key",type: SecretRotation.StripeApiKey,@@ -176,6 +395,6 @@ export const STRIPE_API_KEY_ROTATION_LIST_OPTION: TSecretRotationV2ListItem = {secretsMapping: {apiKey: "STRIPE_API_KEY"},- permissions: [...STRIPE_API_KEY_PERMISSIONS]+ permissionGroups: STRIPE_API_KEY_PERMISSION_GROUPS}};diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.tsindex 50387b20ad..3644f11792 100644--- a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.test.ts@@ -50,19 +50,16 @@ const UNUSED_DEPENDENCIES = [{}, {}, {}, {}] as unknown as [// The factory reads these four fields of the rotation row and nothing else, so the rest of the row// is left off rather than filled with placeholders that would read as though they mattered.-const rotation = (activeIndex: number, connectPermissions: string[]) =>+const rotation = (activeIndex: number) =>({connection: { id: "connection-id", credentials: { accountId: "acct_123" } },- parameters: { permissions: ["customer_read"], connectPermissions },+ parameters: { permissions: ["customer_read"] },secretsMapping: { apiKey: "STRIPE_API_KEY" },activeIndex}) as unknown as TStripeApiKeyRotationWithConnection;-const makeFactory = ({- activeIndex = 0,- connectPermissions = []-}: { activeIndex?: number; connectPermissions?: string[] } = {}) =>- stripeApiKeyRotationFactory(rotation(activeIndex, connectPermissions), ...UNUSED_DEPENDENCIES);+const makeFactory = ({ activeIndex = 0 }: { activeIndex?: number } = {}) =>+ stripeApiKeyRotationFactory(rotation(activeIndex), ...UNUSED_DEPENDENCIES);const isCreate = (url: string) => url.endsWith("/v2/iam/api_keys");const isExpire = (url: string) => url.endsWith("/expire");@@ -280,34 +277,6 @@ describe("stripeApiKeyRotationFactory", () => {});});- describe("connect permissions", () => {- // Nothing readable on the account says whether it is a Connect platform, so a rejected create- // is the only place a user learns that Connect permissions were the problem.- it("names Connect permissions as the likely cause when Stripe rejects the create", async () => {- postMock.mockRejectedValue(httpError(400, "Invalid permissions"));-- await expect(makeFactory({ connectPermissions: ["customer_read"] }).issueCredentials(commit)).rejects.toThrow(- /not a Connect platform, remove the Connect permissions/- );- });-- it("leaves a rejection alone when no Connect permissions were sent", async () => {- postMock.mockRejectedValue(httpError(400, "Invalid permissions"));-- await expect(makeFactory().issueCredentials(commit)).rejects.toThrow(- /Infisical cannot manage API keys on Stripe account/- );- });-- it("keeps the reinstall remedy when the failure is an authorization one", async () => {- postMock.mockRejectedValue(httpError(403, "app removed"));-- await expect(makeFactory({ connectPermissions: ["customer_read"] }).issueCredentials(commit)).rejects.toThrow(- /reinstall it and reconnect/- );- });- });-describe("checkActiveCredentials", () => {it("treats 403 as a live key and 401 as a dead one", async () => {getMock.mockRejectedValueOnce(httpError(403, "Insufficient permissions"));diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.tsindex 61fd77eef4..96f7d590cd 100644--- a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-fns.ts@@ -34,7 +34,7 @@ export const stripeApiKeyRotationFactory: TRotationFactory<> = (secretRotation) => {const {connection,- parameters: { permissions, connectPermissions },+ parameters: { permissions, keyName },secretsMapping} = secretRotation;@@ -42,7 +42,8 @@ export const stripeApiKeyRotationFactory: TRotationFactory<// The factory is built without an id at create time, so the name comes from the mapped secret.// It is what makes a key stranded by a timed-out create identifiable in the Stripe dashboard.- const $keyName = () => `infisical-${secretsMapping.apiKey}-${Date.now()}`.slice(0, STRIPE_KEY_NAME_MAX_LENGTH);+ const $keyName = () =>+ `${keyName ?? `infisical-${secretsMapping.apiKey}-${Date.now()}`}`.slice(0, STRIPE_KEY_NAME_MAX_LENGTH);/** No 404 on a double expire has ever been observed, so a non-404 failure on retiring a key that* was already expired can't be told apart from a real failure by status code alone. This is only@@ -129,23 +130,12 @@ export const stripeApiKeyRotationFactory: TRotationFactory<{type: "secret_key",name: $keyName(),- ...(permissions?.length ? { permissions } : {}),- ...(connectPermissions?.length ? { connect_permissions: connectPermissions } : {}),+ permissions,public_key: { pem_key: { data: publicKey, algorithm: "RSA" } }},withIdempotencyKey(getStripeAppRequestConfig(accountId))));} catch (error) {- // Stripe rejects connect_permissions on an account that is not a Connect platform, without- // naming the parameter at fault, and nothing we can read off the account says whether it is- // one. So the rejection carries the likely cause. Only a 400 qualifies: the auth and- // availability failures have their own remedy and keep it.- if (connectPermissions?.length && getStripeErrorStatus(error) === 400) {- throw new BadRequestError({- message: `Stripe rejected the API key for account '${accountId}': ${getStripeErrorMessage(error)}. If this Stripe account is not a Connect platform, remove the Connect permissions from this rotation and try again.`- });- }-return throwStripeApiKeyManagementError(accountId, error);}diff --git a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-schemas.ts b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-schemas.tsindex f77c660cc4..c750c9b60a 100644--- a/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-schemas.ts+++ b/backend/src/ee/services/secret-rotation-v2/stripe-api-key/stripe-api-key-rotation-schemas.ts@@ -23,28 +23,16 @@ export const StripeApiKeyRotationGeneratedCredentialsSchema = z.min(1).max(2);-const StripeApiKeyPermissionListSchema = StripeApiKeyPermissionSchema.array()+const StripeApiKeyPermissionListSchema = z+ .array(StripeApiKeyPermissionSchema)+ .min(1, "At least one permission is required").max(STRIPE_API_KEY_PERMISSIONS.length).transform((permissions) => [...new Set(permissions)]);-const StripeApiKeyRotationParametersSchema = z- .object({- permissions: StripeApiKeyPermissionListSchema.optional().describe(- SecretRotations.PARAMETERS.STRIPE_API_KEY.permissions- ),- connectPermissions: StripeApiKeyPermissionListSchema.optional().describe(- SecretRotations.PARAMETERS.STRIPE_API_KEY.connectPermissions- )- })- .superRefine((parameters, ctx) => {- if (parameters.permissions?.length || parameters.connectPermissions?.length) return;-- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["permissions"],- message: "At least one permission or Connect permission is required"- });- });+const StripeApiKeyRotationParametersSchema = z.object({+ keyName: z.string().optional().describe(SecretRotations.PARAMETERS.STRIPE_API_KEY.keyName),+ permissions: StripeApiKeyPermissionListSchema.describe(SecretRotations.PARAMETERS.STRIPE_API_KEY.permissions)+});const StripeApiKeyRotationSecretsMappingSchema = z.object({apiKey: SecretNameSchema.describe(SecretRotations.SECRETS_MAPPING.STRIPE_API_KEY.apiKey)@@ -54,7 +42,18 @@ export const StripeApiKeyRotationTemplateSchema = z.object({secretsMapping: z.object({apiKey: z.string()}),- permissions: z.string().array()+ permissionGroups: z+ .object({+ name: z.string(),+ resources: z+ .object({+ name: z.string(),+ read: z.string().optional(),+ write: z.string().optional()+ })+ .array()+ })+ .array()});export const StripeApiKeyRotationSchema = BaseSecretRotationSchema(SecretRotation.StripeApiKey).extend({diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex c2be2a427e..661975be59 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -3650,10 +3650,9 @@ export const SecretRotations = {modulusLength: "The modulus length in bits of the generated RSA key pairs. Defaults to 2048."},STRIPE_API_KEY: {+ keyName: "The name of the Stripe API key that will be created and rotated by Infisical.",permissions:- "The permissions granted to the generated Stripe API key. Stripe has no wildcard permission, so this is the full list of what the key may do.",- connectPermissions:- "The permissions that the generated Stripe API key has over connected accounts. If your Stripe account is not a Connect platform account, you cannot configure Connect permissions for the key."+ "The permissions granted to the generated Stripe API key. Stripe has no wildcard permission, so this is the full list of what the key may do."}},SECRETS_MAPPING: {diff --git a/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.tsindex 8df2bf4849..56c520c355 100644--- a/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts+++ b/backend/src/server/routes/v1/app-connection-routers/stripe-connection-router.ts@@ -1,14 +1,9 @@-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 {CreateStripeConnectionSchema,SanitizedStripeConnectionSchema,UpdateStripeConnectionSchema} from "@app/services/app-connection/stripe";-import { AuthMode } from "@app/services/auth/auth-type";import { registerAppConnectionEndpoints } from "./app-connection-endpoints";@@ -20,40 +15,4 @@ export const registerStripeConnectionRouter = async (server: FastifyZodProvider)createSchema: CreateStripeConnectionSchema,updateSchema: UpdateStripeConnectionSchema});-- // The below endpoints are not exposed and for Infisical App use- server.route({- method: "GET",- url: `/:connectionId/api-keys`,- config: {- rateLimit: readLimit- },- schema: {- operationId: "listStripeApiKeys",- params: z.object({- connectionId: z.string().uuid()- }),- response: {- 200: z.object({- apiKeys: z- .object({- id: z.string(),- name: z.string(),- status: z.string(),- permissions: z.string().array(),- connectPermissions: z.string().array()- })- .array()- })- }- },- onRequest: verifyAuth([AuthMode.JWT, AuthMode.OAUTH]),- handler: async (req) => {- const { connectionId } = req.params;-- const apiKeys = await server.services.appConnection.stripe.listApiKeys(connectionId, req.permission);-- return { apiKeys };- }- });};diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.tsindex 5c49e4f0a5..ba29b1185b 100644--- a/backend/src/services/app-connection/app-connection-service.ts+++ b/backend/src/services/app-connection/app-connection-service.ts@@ -181,7 +181,7 @@ import { snowflakeConnectionService } from "./snowflake/snowflake-connection-serimport { ValidateSpaceliftConnectionCredentialsSchema } from "./spacelift";import { spaceliftConnectionService } from "./spacelift/spacelift-connection-service";import { ValidateSshConnectionCredentialsSchema } from "./ssh";-import { stripeConnectionService, ValidateStripeConnectionCredentialsSchema } from "./stripe";+import { ValidateStripeConnectionCredentialsSchema } from "./stripe";import { ValidateSupabaseConnectionCredentialsSchema } from "./supabase";import { supabaseConnectionService } from "./supabase/supabase-connection-service";import { ValidateTeamCityConnectionCredentialsSchema } from "./teamcity";@@ -1422,7 +1422,6 @@ export const appConnectionServiceFactory = ({bitbucket: bitbucketConnectionService(connectAppConnectionById),checkly: checklyConnectionService(connectAppConnectionById),supabase: supabaseConnectionService(connectAppConnectionById),- stripe: stripeConnectionService(connectAppConnectionById),rundeck: rundeckConnectionService(connectAppConnectionById),digitalOcean: digitalOceanAppPlatformConnectionService(connectAppConnectionById),netlify: netlifyConnectionService(connectAppConnectionById),diff --git a/backend/src/services/app-connection/stripe/index.ts b/backend/src/services/app-connection/stripe/index.tsindex b0533624cb..9f9f9e6a8f 100644--- a/backend/src/services/app-connection/stripe/index.ts+++ b/backend/src/services/app-connection/stripe/index.ts@@ -1,5 +1,4 @@export * from "./stripe-connection-enums";export * from "./stripe-connection-public-client";export * from "./stripe-connection-schemas";-export * from "./stripe-connection-service";export * from "./stripe-connection-types";diff --git a/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts b/backend/src/services/app-connection/stripe/stripe-connection-public-client.tsindex d4f541dc63..5c12d1d96b 100644--- a/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts+++ b/backend/src/services/app-connection/stripe/stripe-connection-public-client.ts@@ -1,12 +1,10 @@/* eslint-disable no-await-in-loop */import crypto from "node:crypto";-import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";+import { AxiosError, AxiosRequestConfig } from "axios";import { getConfig } from "@app/lib/config/env";-import { request } from "@app/lib/config/request";import { BadRequestError, InternalServerError } from "@app/lib/errors";-import { logger } from "@app/lib/logger";import { IntegrationUrls } from "@app/services/integration-auth/integration-list";// The Managed API Keys API is in private preview and is only served under a preview API version.@@ -76,77 +74,3 @@ export const throwStripeApiKeyManagementError = (accountId: string, error: unkno`If the Infisical app was removed from this Stripe account, reinstall it and reconnect.`});};--export type TStripeApiKeyListItem = {- id: string;- name?: string | null;- status?: string | null;- permissions?: string[] | null;- connect_permissions?: string[] | null;-};--type TStripeApiKeyListResponse = {- data?: TStripeApiKeyListItem[];- next_page_url?: string | null;-};--const STRIPE_LIST_PAGE_SIZE = 100;--// Stripe rejects limit=200 with "The maximum page limit is 100", so this is the largest page it-// serves. The page cap is a runaway guard, not an expected bound.-const STRIPE_LIST_MAX_PAGES = 50;--// Stripe's list response carries secret_key.token, in full plaintext, for every key in the account.-// TStripeApiKeyListItem omits it only at the type level, so rebuilding each item as a fresh object-// literal is what actually keeps the raw response object, and the secret it carries, from leaving-// this function. Downstream callers strip it again on their own responses; this is defense in depth.-const sanitizeApiKeyListItem = (item: TStripeApiKeyListItem): TStripeApiKeyListItem => ({- id: item.id,- name: item.name,- status: item.status,- permissions: item.permissions,- connect_permissions: item.connect_permissions-});--export const listStripeApiKeys = async (accountId: string): Promise<TStripeApiKeyListItem[]> => {- const config = getStripeAppRequestConfig(accountId);- const keys: TStripeApiKeyListItem[] = [];-- let url: string | undefined = `${STRIPE_API_KEYS_URL}?limit=${STRIPE_LIST_PAGE_SIZE}`;- let pages = 0;-- while (url && pages < STRIPE_LIST_MAX_PAGES) {- // The explicit AxiosResponse annotation breaks a circular type-inference error TS raises when a- // loop variable (url) is both an argument to this generic call and reassigned from its result.- const response: AxiosResponse<TStripeApiKeyListResponse> = await request.get<TStripeApiKeyListResponse>(- url,- config- );-- keys.push(...(response.data?.data ?? []).map(sanitizeApiKeyListItem));-- const nextPageUrl = response.data?.next_page_url ?? undefined;-- // config carries the app's own key, which can act on every account the app is installed on, not- // a per-connection token. This must be checked before that credential goes out on the next- // request, never after, since next_page_url comes from the response body Stripe controls.- if (nextPageUrl && !nextPageUrl.startsWith(STRIPE_API_KEYS_URL)) {- logger.error(- `listStripeApiKeys: next_page_url for account ${accountId} did not point at the Stripe API keys endpoint, stopped paginating`- );- url = undefined;- } else {- url = nextPageUrl;- }-- pages += 1;- }-- if (url) {- logger.warn(- `listStripeApiKeys: stopped after ${STRIPE_LIST_MAX_PAGES} pages for account ${accountId}, the list is truncated`- );- }-- return keys;-};diff --git a/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts b/backend/src/services/app-connection/stripe/stripe-connection-service.test.tsdeleted file mode 100644index aa7543cc90..0000000000--- a/backend/src/services/app-connection/stripe/stripe-connection-service.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const { getMock } = vi.hoisted(() => ({ getMock: vi.fn() }));--vi.mock("@app/lib/config/env", () => ({- getConfig: () => ({ INF_APP_CONNECTION_STRIPE_SECRET_KEY: "sk_test_app" })-}));-vi.mock("@app/lib/config/request", () => ({- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-call- request: { get: (...args: unknown[]) => (getMock as any)(...args) }-}));-vi.mock("@app/lib/logger", () => ({- logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }-}));--// eslint-disable-next-line import/first-import { stripeConnectionService } from "./stripe-connection-service";--const keyPage = (id: string, next?: string) => ({- data: {- data: [- {- id,- name: `key-${id}`,- status: "active",- permissions: ["charge_read"],- connect_permissions: [],- // Stripe really does return this, in full, for every key.- secret_key: { token: `rk_test_${id}_full_plaintext_secret`, secret_token_redacted: "rk_test_...ab12" }- }- ],- next_page_url: next ?? null- }-});--const makeService = () =>- stripeConnectionService(- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument- vi.fn(async () => ({ credentials: { accountId: "acct_123" } })) as any- );--describe("stripeConnectionService.listApiKeys", () => {- beforeEach(() => getMock.mockReset());-- it("never returns the plaintext secret Stripe includes in every list item", async () => {- getMock.mockResolvedValueOnce(keyPage("mk_1"));-- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument- const keys = await makeService().listApiKeys("connection-id", {} as any);-- expect(keys).toEqual([- {- id: "mk_1",- name: "key-mk_1",- status: "active",- permissions: ["charge_read"],- connectPermissions: []- }- ]);- expect(JSON.stringify(keys)).not.toContain("plaintext_secret");- expect(JSON.stringify(keys)).not.toContain("secret_key");- });-- it("follows next_page_url instead of returning only the first page", async () => {- getMock- .mockResolvedValueOnce(keyPage("mk_1", "https://api.stripe.com/v2/iam/api_keys?page=2"))- .mockResolvedValueOnce(keyPage("mk_2"));-- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument- const keys = await makeService().listApiKeys("connection-id", {} as any);-- expect(keys.map((key) => key.id)).toEqual(["mk_1", "mk_2"]);- expect(getMock).toHaveBeenCalledTimes(2);- expect(getMock.mock.calls[0][0]).toContain("limit=100");- expect(getMock.mock.calls[1][0]).toBe("https://api.stripe.com/v2/iam/api_keys?page=2");- });-- it("never sends the app credential to a next_page_url outside the Stripe API keys endpoint", async () => {- getMock.mockResolvedValueOnce(keyPage("mk_1", "https://evil.example.com/v2/iam/api_keys?page=2"));-- // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument- const keys = await makeService().listApiKeys("connection-id", {} as any);-- expect(keys.map((key) => key.id)).toEqual(["mk_1"]);- expect(getMock).toHaveBeenCalledTimes(1);- });-});diff --git a/backend/src/services/app-connection/stripe/stripe-connection-service.ts b/backend/src/services/app-connection/stripe/stripe-connection-service.tsdeleted file mode 100644index 504c4cfb73..0000000000--- a/backend/src/services/app-connection/stripe/stripe-connection-service.ts+++ /dev/null@@ -1,44 +0,0 @@-import { OrgServiceActor } from "@app/lib/types";--import { AppConnection } from "../app-connection-enums";-import { listStripeApiKeys, throwStripeApiKeyManagementError } from "./stripe-connection-public-client";-import { TStripeConnection } from "./stripe-connection-types";--type TGetAppConnectionFunc = (- app: AppConnection,- connectionId: string,- actor: OrgServiceActor-) => Promise<TStripeConnection>;--export type TStripeApiKeySummary = {- id: string;- name: string;- status: string;- permissions: string[];- connectPermissions: string[];-};--export const stripeConnectionService = (getAppConnection: TGetAppConnectionFunc) => {- const listApiKeys = async (connectionId: string, actor: OrgServiceActor): Promise<TStripeApiKeySummary[]> => {- const appConnection = await getAppConnection(AppConnection.Stripe, connectionId, actor);- const { accountId } = appConnection.credentials;-- try {- const keys = await listStripeApiKeys(accountId);-- // Stripe returns secret_key.token, in full plaintext, for every key in the account. Mapping to- // an explicit shape here is what keeps it out of the HTTP response.- return keys.map((key) => ({- id: key.id,- name: key.name ?? "",- status: key.status ?? "",- permissions: key.permissions ?? [],- connectPermissions: key.connect_permissions ?? []- }));- } catch (error) {- return throwStripeApiKeyManagementError(accountId, error);- }- };-- return { listApiKeys };-};diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyPermissionSelector.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyPermissionSelector.tsxnew file mode 100644index 0000000000..45054aa8de--- /dev/null+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyPermissionSelector.tsx@@ -0,0 +1,315 @@+import { useMemo, useState } from "react";+import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";+import { ChevronDownIcon, SearchIcon } from "lucide-react";++import {+ Button,+ FieldLabel,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Skeleton+} from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import {+ TStripeApiKeyPermissionGroup,+ TStripeApiKeyPermissionResource+} from "@app/hooks/api/secretRotationsV2/types/stripe-api-key-rotation";++enum AccessLevel {+ None = "none",+ Read = "read",+ Write = "write"+}++const LEVEL_LABELS: Record<AccessLevel, string> = {+ [AccessLevel.None]: "None",+ [AccessLevel.Read]: "Read",+ [AccessLevel.Write]: "Write"+};++const ACTIVE_SEGMENT_CLASSES: Record<AccessLevel, string> = {+ [AccessLevel.None]: "data-[state=checked]:bg-foreground/10 data-[state=checked]:text-foreground",+ [AccessLevel.Read]: "data-[state=checked]:bg-info/15 data-[state=checked]:text-info",+ [AccessLevel.Write]: "data-[state=checked]:bg-warning/15 data-[state=checked]:text-warning"+};++const getLevels = (resource: TStripeApiKeyPermissionResource) => [+ AccessLevel.None,+ ...(resource.read ? [AccessLevel.Read] : []),+ ...(resource.write ? [AccessLevel.Write] : [])+];++const getLevel = (resource: TStripeApiKeyPermissionResource, granted: Set<string>) => {+ if (resource.write && granted.has(resource.write)) return AccessLevel.Write;+ if (resource.read && granted.has(resource.read)) return AccessLevel.Read;+ return AccessLevel.None;+};++// Write sends the resource's read permission too, the same way the Stripe dashboard treats write as+// including read.+const toPermissions = (resource: TStripeApiKeyPermissionResource, level: AccessLevel) => {+ if (level === AccessLevel.None) return [];+ if (level === AccessLevel.Read) return resource.read ? [resource.read] : [];+ return [resource.read, resource.write].filter((permission): permission is string =>+ Boolean(permission)+ );+};++// A bulk level a resource cannot take: Write falls back to Read, so "Set all Write" still grants+// every read-only resource, and Read leaves write-only resources as they are.+const resolveBulkLevel = (resource: TStripeApiKeyPermissionResource, level: AccessLevel) => {+ if (getLevels(resource).includes(level)) return level;+ if (level === AccessLevel.Write) return AccessLevel.Read;+ return null;+};++const matchesQuery = (+ group: TStripeApiKeyPermissionGroup,+ resource: TStripeApiKeyPermissionResource,+ query: string+) =>+ [group.name, resource.name, resource.read, resource.write].some((text) =>+ text?.toLowerCase().includes(query)+ );++type SegmentedControlProps<T extends string> = {+ value: T;+ options: { value: T; label: string; className?: string }[];+ onValueChange: (value: T) => void;+ "aria-label": string;+ segmentClassName?: string;+};++const SegmentedControl = <T extends string>({+ value,+ options,+ onValueChange,+ segmentClassName,+ ...props+}: SegmentedControlProps<T>) => (+ <RadioGroupPrimitive.Root+ value={value}+ onValueChange={(next) => onValueChange(next as T)}+ orientation="horizontal"+ className="flex shrink-0 gap-0.5 rounded-md border border-border bg-popover p-0.5"+ aria-label={props["aria-label"]}+ >+ {options.map((option) => (+ <RadioGroupPrimitive.Item+ key={option.value}+ value={option.value}+ className={cn(+ "cursor-pointer rounded-sm text-xs text-accent outline-none",+ "focus-visible:ring-[3px] focus-visible:ring-ring/50",+ "data-[state=checked]:bg-foreground/10 data-[state=checked]:text-foreground",+ segmentClassName,+ option.className+ )}+ >+ {option.label}+ </RadioGroupPrimitive.Item>+ ))}+ </RadioGroupPrimitive.Root>+);++type Props = {+ groups: TStripeApiKeyPermissionGroup[];+ value: string[];+ onChange: (value: string[]) => void;+ isLoading?: boolean;+};++export const StripeApiKeyPermissionSelector = ({ groups, value, onChange, isLoading }: Props) => {+ const [query, setQuery] = useState("");+ const [isGrantedOnly, setIsGrantedOnly] = useState(false);+ const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});++ const granted = useMemo(() => new Set(value), [value]);++ const setLevels = (patch: Map<TStripeApiKeyPermissionResource, AccessLevel>) => {+ // Only the resources in the patch are rewritten, so an existing rotation keeps the exact+ // permissions it was saved with for everything the user did not touch.+ const touched = new Set(+ [...patch.keys()].flatMap((resource) => [resource.read, resource.write])+ );+ const next = value.filter((permission) => !touched.has(permission));+ patch.forEach((level, resource) => next.push(...toPermissions(resource, level)));+ onChange(next);+ };++ const normalizedQuery = query.trim().toLowerCase();++ const visibleGroups = useMemo(+ () =>+ groups+ .map((group) => ({+ ...group,+ rows: group.resources.filter(+ (resource) =>+ matchesQuery(group, resource, normalizedQuery) &&+ (!isGrantedOnly || getLevel(resource, granted) !== AccessLevel.None)+ ),+ grantedCount: group.resources.filter(+ (resource) => getLevel(resource, granted) !== AccessLevel.None+ ).length+ }))+ .filter((group) => group.rows.length),+ [groups, normalizedQuery, isGrantedOnly, granted]+ );++ const summary = useMemo(() => {+ const levels = groups.flatMap(({ resources }) =>+ resources.map((resource) => getLevel(resource, granted))+ );+ const read = levels.filter((level) => level === AccessLevel.Read).length;+ const write = levels.filter((level) => level === AccessLevel.Write).length;+ return `${read + write} resources · ${read} read · ${write} write`;+ }, [groups, granted]);++ const applyToVisible = (level: AccessLevel) => {+ const patch = new Map<TStripeApiKeyPermissionResource, AccessLevel>();+ visibleGroups.forEach(({ rows }) =>+ rows.forEach((resource) => {+ const resolved = resolveBulkLevel(resource, level);+ if (resolved) patch.set(resource, resolved);+ })+ );+ setLevels(patch);+ };++ return (+ <>+ <div className="flex items-baseline justify-between gap-3">+ <FieldLabel id="stripe-permissions-label" size="sm">+ Permissions+ </FieldLabel>+ {!isLoading && (+ <span className="shrink-0 text-xs whitespace-nowrap text-accent">{summary}</span>+ )}+ </div>+ <p className="text-xs text-muted">+ Grant the minimum access Infisical needs to create and revoke this key.+ </p>+ <div+ role="group"+ aria-labelledby="stripe-permissions-label"+ className="mt-1.5 overflow-hidden rounded-md border border-border bg-container"+ >+ <div className="flex items-center gap-2 border-b border-border p-2">+ <InputGroup className="h-8 flex-1 bg-popover">+ <InputGroupAddon align="inline-start">+ <SearchIcon className="size-3.5" strokeWidth={1.75} />+ </InputGroupAddon>+ <InputGroupInput+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search resources"+ aria-label="Search Stripe resources"+ className="text-[13px]"+ />+ </InputGroup>+ <SegmentedControl+ aria-label="Show resources"+ value={isGrantedOnly ? "granted" : "all"}+ onValueChange={(next) => setIsGrantedOnly(next === "granted")}+ options={[+ { value: "all", label: "All" },+ { value: "granted", label: "Granted" }+ ]}+ segmentClassName="h-[26px] px-2.5"+ />+ <div className="flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap text-accent">+ Set all+ {[AccessLevel.None, AccessLevel.Read, AccessLevel.Write].map((level) => (+ <Button+ key={level}+ type="button"+ variant="outline"+ size="xs"+ className="rounded-md text-label hover:text-foreground"+ isDisabled={isLoading || !visibleGroups.length}+ onClick={() => applyToVisible(level)}+ >+ {LEVEL_LABELS[level]}+ </Button>+ ))}+ </div>+ </div>+ <div className="max-h-[400px] overflow-auto">+ {isLoading &&+ Array.from({ length: 6 }, (_, i) => (+ <div key={i} className="flex h-10 items-center border-b border-border-faint px-3">+ <Skeleton className="h-4 w-full" />+ </div>+ ))}+ {!isLoading &&+ visibleGroups.map(({ name: groupName, resources, rows, grantedCount }) => {+ const isExpanded = !collapsed[groupName] || Boolean(normalizedQuery);++ return (+ <div key={groupName}>+ <button+ type="button"+ aria-expanded={isExpanded}+ onClick={() =>+ setCollapsed((prev) => ({ ...prev, [groupName]: !prev[groupName] }))+ }+ className="sticky top-0 z-[1] flex h-8 w-full cursor-pointer items-center gap-2 border-b border-border bg-card px-3 text-left text-xs font-medium text-label outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:ring-inset"+ >+ <ChevronDownIcon+ className={cn(+ "size-3 transition-transform duration-200 ease-in-out",+ !isExpanded && "-rotate-90"+ )}+ strokeWidth={2}+ />+ <span className="flex-1">{groupName}</span>+ <span className="shrink-0 font-normal whitespace-nowrap text-muted">+ {grantedCount} of {resources.length} granted+ </span>+ </button>+ {isExpanded &&+ rows.map((resource) => {+ const level = getLevel(resource, granted);++ return (+ <div+ key={resource.name}+ className="flex h-10 items-center justify-between gap-3 border-b border-border-faint pr-3 pl-8 hover:bg-container-hover"+ >+ <span+ className={cn(+ "truncate text-[13px]",+ level === AccessLevel.None ? "text-label" : "text-foreground"+ )}+ >+ {resource.name}+ </span>+ <SegmentedControl+ aria-label={`${groupName} ${resource.name} access`}+ value={level}+ onValueChange={(next) => setLevels(new Map([[resource, next]]))}+ options={getLevels(resource).map((option) => ({+ value: option,+ label: LEVEL_LABELS[option],+ className: ACTIVE_SEGMENT_CLASSES[option]+ }))}+ segmentClassName="h-6 w-13"+ />+ </div>+ );+ })}+ </div>+ );+ })}+ {!isLoading && !visibleGroups.length && (+ <div className="p-6 text-center text-[13px] text-accent">+ {normalizedQuery ? "No resources match this search." : "No resources granted yet."}+ </div>+ )}+ </div>+ </div>+ </>+ );+};diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyRotationParametersFields.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyRotationParametersFields.tsxindex c8d7355419..ff169727d4 100644--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyRotationParametersFields.tsx+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ParametersFields/StripeApiKeyRotationParametersFields.tsx@@ -1,133 +1,62 @@-import { useEffect, useMemo, useState } from "react";-import { Controller, useFormContext, useWatch } from "react-hook-form";+import { useMemo } from "react";+import { Controller, useFormContext } from "react-hook-form";-import { createNotification } from "@app/components/notifications";import { TSecretRotationV2Form } from "@app/components/secret-rotations-v2/forms/schemas";-import { Combobox, Field, FieldDescription, FieldError, FieldLabel } from "@app/components/v3";-import {- TStripeApiKey,- useStripeConnectionListApiKeys-} from "@app/hooks/api/appConnections/stripe";+import { Field, FieldError, Input } from "@app/components/v3";import { SecretRotation, useSecretRotationV2Option } from "@app/hooks/api/secretRotationsV2";+import { StripeApiKeyPermissionSelector } from "./StripeApiKeyPermissionSelector";+import { FieldLabelWithTooltip } from "../shared";+export const StripeApiKeyRotationParametersFields = () => {- const { control, setValue } = useFormContext<+ const { control } = useFormContext<TSecretRotationV2Form & { type: SecretRotation.StripeApiKey }>();- const [copiedFromKey, setCopiedFromKey] = useState<TStripeApiKey | null>(null);-- const connectionId = useWatch({ control, name: "connection.id" });const { rotationOption, isLoading: isRotationOptionLoading } = useSecretRotationV2Option(SecretRotation.StripeApiKey);- const { data: apiKeys = [], isPending: isApiKeysPending } = useStripeConnectionListApiKeys(- connectionId,- { enabled: Boolean(connectionId) }- );- // A disabled query (no connection picked yet) reports isPending forever, so it must not be- // read on its own as "loading".- const isApiKeysLoading = isApiKeysPending && Boolean(connectionId);-- // A stale selection from a previous connection is not just visually wrong: the Combobox- // would keep offering a key that belongs to a different Stripe account.- useEffect(() => {- setCopiedFromKey(null);- }, [connectionId]);-- const permissions = useMemo(() => rotationOption?.template.permissions ?? [], [rotationOption]);-- // Only keys still usable as a source: an expired or revoked key's permissions are not a- // meaningful default for a new one.- const activeApiKeys = useMemo(- () => apiKeys.filter((apiKey) => apiKey.status === "active"),- [apiKeys]- );-- const applyKeyPermissions = (apiKey: TStripeApiKey) => {- setCopiedFromKey(apiKey);-- const allowedPermissions = new Set(permissions);- const filteredPermissions = apiKey.permissions.filter((permission) =>- allowedPermissions.has(permission)- );- const filteredConnectPermissions = apiKey.connectPermissions.filter((permission) =>- allowedPermissions.has(permission)- );-- setValue("parameters.permissions", filteredPermissions, { shouldDirty: true });- setValue("parameters.connectPermissions", filteredConnectPermissions, { shouldDirty: true });- const droppedCount =- apiKey.permissions.length -- filteredPermissions.length +- (apiKey.connectPermissions.length - filteredConnectPermissions.length);-- if (droppedCount > 0) {- createNotification({- type: "warning",- text: `${droppedCount} permission${droppedCount === 1 ? "" : "s"} on ${apiKey.name || apiKey.id} ${droppedCount === 1 ? "isn't" : "aren't"} recognized by Infisical and ${droppedCount === 1 ? "was" : "were"} not copied.`- });- }- };+ const groups = useMemo(() => rotationOption?.template.permissionGroups ?? [], [rotationOption]);return (<><Controllerrender={({ field: { value, onChange }, fieldState: { error } }) => (<Field data-invalid={Boolean(error)}>- <FieldLabel htmlFor="stripe-permissions">Permissions</FieldLabel>- <Combobox- id="stripe-permissions"- multiple- isSelectAll- options={permissions}+ <FieldLabelWithTooltip+ htmlFor="secret-rotation-key-name"+ tooltip="The name of the key to use for the secret rotation. This is used to identify the key in the Stripe API. This is optional and will default to a random key name in Stripe."+ >+ Key Name+ </FieldLabelWithTooltip>+ <Input+ id="secret-rotation-key-name"+ placeholder="Infisical Managed Stripe Key"+ value={value}+ onChange={onChange}+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ control={control}+ name="parameters.keyName"+ />+ <Controller+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <StripeApiKeyPermissionSelector+ groups={groups}value={value ?? []}- onValueChange={onChange}- getOptionValue={(permission) => permission}- getOptionLabel={(permission) => permission}- placeholder="Select permissions..."- searchPlaceholder="Search permissions..."- searchAriaLabel="Search Stripe permissions"- clearAriaLabel="Clear all permissions"+ onChange={onChange}isLoading={isRotationOptionLoading}/>- {!error && (- <FieldDescription>- Select All only selects the permissions your search currently matches, not the full- list.- </FieldDescription>- )}<FieldError>{error?.message}</FieldError></Field>)}control={control}name="parameters.permissions"/>- {(activeApiKeys.length > 0 || isApiKeysLoading) && (- <Field>- <FieldLabel htmlFor="stripe-copy-from-key">- Copy permissions from an existing key- </FieldLabel>- <Combobox- id="stripe-copy-from-key"- options={activeApiKeys}- value={copiedFromKey}- onValueChange={applyKeyPermissions}- getOptionValue={(apiKey) => apiKey.id}- getOptionLabel={(apiKey) => apiKey.name || apiKey.id}- placeholder="Select a key..."- searchPlaceholder="Search keys..."- searchAriaLabel="Search Stripe API keys"- isLoading={isApiKeysLoading}- isDisabled={isRotationOptionLoading}- />- <FieldDescription>- Applies that key's permissions to the fields above. It does not link the rotation- to the key.- </FieldDescription>- </Field>- )}</>);};diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ReviewFields/StripeApiKeyRotationReviewFields.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ReviewFields/StripeApiKeyRotationReviewFields.tsxindex f43bec0d54..268e2a3c54 100644--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ReviewFields/StripeApiKeyRotationReviewFields.tsx+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ReviewFields/StripeApiKeyRotationReviewFields.tsx@@ -31,16 +31,14 @@ export const StripeApiKeyRotationReviewFields = () => {return (<><SecretRotationReviewSection label="Parameters">+ {Boolean(parameters.keyName) && (+ <ReviewField label="Key Name">{parameters.keyName}</ReviewField>+ )}{Boolean(parameters.permissions?.length) && (<ReviewField label="Permissions">{summarizePermissions(parameters.permissions ?? [])}</ReviewField>)}- {Boolean(parameters.connectPermissions?.length) && (- <ReviewField label="Connect Permissions">- {summarizePermissions(parameters.connectPermissions ?? [])}- </ReviewField>- )}</SecretRotationReviewSection><SecretRotationReviewSection label="Secrets Mapping"><ReviewField label="API Key">{apiKey}</ReviewField>diff --git a/frontend/src/components/secret-rotations-v2/forms/schemas/stripe-api-key-rotation-schema.ts b/frontend/src/components/secret-rotations-v2/forms/schemas/stripe-api-key-rotation-schema.tsindex af4d703c4d..d95cd3bbc6 100644--- a/frontend/src/components/secret-rotations-v2/forms/schemas/stripe-api-key-rotation-schema.ts+++ b/frontend/src/components/secret-rotations-v2/forms/schemas/stripe-api-key-rotation-schema.ts@@ -6,20 +6,10 @@ import { SecretRotation } from "@app/hooks/api/secretRotationsV2";export const StripeApiKeyRotationSchema = z.object({type: z.literal(SecretRotation.StripeApiKey),- parameters: z- .object({- permissions: z.string().trim().array().optional(),- connectPermissions: z.string().trim().array().optional()- })- .superRefine((parameters, ctx) => {- if (parameters.permissions?.length || parameters.connectPermissions?.length) return;-- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ["permissions"],- message: "At least one permission or Connect permission is required"- });- }),+ parameters: z.object({+ permissions: z.string().trim().array().min(1, "Grant at least one permission"),+ keyName: z.string().max(100, "Key name must be less than 100 characters").trim().optional()+ }),secretsMapping: z.object({apiKey: z.string().trim().min(1, "API Key secret name required")})diff --git a/frontend/src/hooks/api/appConnections/stripe/index.ts b/frontend/src/hooks/api/appConnections/stripe/index.tsdeleted file mode 100644index 2c1906d369..0000000000--- a/frontend/src/hooks/api/appConnections/stripe/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from "./queries";-export * from "./types";diff --git a/frontend/src/hooks/api/appConnections/stripe/queries.tsx b/frontend/src/hooks/api/appConnections/stripe/queries.tsxdeleted file mode 100644index 751057be9a..0000000000--- a/frontend/src/hooks/api/appConnections/stripe/queries.tsx+++ /dev/null@@ -1,37 +0,0 @@-import { useQuery, UseQueryOptions } from "@tanstack/react-query";--import { apiRequest } from "@app/config/request";-import { appConnectionKeys } from "@app/hooks/api/appConnections";--import { TStripeApiKey } from "./types";--const stripeConnectionKeys = {- all: [...appConnectionKeys.all, "stripe"] as const,- listApiKeys: (connectionId: string) =>- [...stripeConnectionKeys.all, "api-keys", connectionId] as const-};--export const useStripeConnectionListApiKeys = (- connectionId: string,- options?: Omit<- UseQueryOptions<- TStripeApiKey[],- unknown,- TStripeApiKey[],- ReturnType<typeof stripeConnectionKeys.listApiKeys>- >,- "queryKey" | "queryFn"- >-) => {- return useQuery({- queryKey: stripeConnectionKeys.listApiKeys(connectionId),- queryFn: async () => {- const { data } = await apiRequest.get<{ apiKeys: TStripeApiKey[] }>(- `/api/v1/app-connections/stripe/${connectionId}/api-keys`- );-- return data.apiKeys;- },- ...options- });-};diff --git a/frontend/src/hooks/api/appConnections/stripe/types.ts b/frontend/src/hooks/api/appConnections/stripe/types.tsdeleted file mode 100644index 66c7401e2f..0000000000--- a/frontend/src/hooks/api/appConnections/stripe/types.ts+++ /dev/null@@ -1,7 +0,0 @@-export type TStripeApiKey = {- id: string;- name: string;- status: string;- permissions: string[];- connectPermissions: string[];-};diff --git a/frontend/src/hooks/api/secretRotationsV2/types/stripe-api-key-rotation.ts b/frontend/src/hooks/api/secretRotationsV2/types/stripe-api-key-rotation.tsindex a7d6d1a190..a69b766f5b 100644--- a/frontend/src/hooks/api/secretRotationsV2/types/stripe-api-key-rotation.ts+++ b/frontend/src/hooks/api/secretRotationsV2/types/stripe-api-key-rotation.ts@@ -8,8 +8,7 @@ import {export type TStripeApiKeyRotation = TSecretRotationV2Base & {type: SecretRotation.StripeApiKey;parameters: {- permissions?: string[];- connectPermissions?: string[];+ permissions: string[];};secretsMapping: {apiKey: string;@@ -27,12 +26,23 @@ export type TStripeApiKeyRotationGeneratedCredentialsResponse =TStripeApiKeyRotationGeneratedCredentials>;+export type TStripeApiKeyPermissionResource = {+ name: string;+ read?: string;+ write?: string;+};++export type TStripeApiKeyPermissionGroup = {+ name: string;+ resources: TStripeApiKeyPermissionResource[];+};+export type TStripeApiKeyRotationOption = {name: string;type: SecretRotation.StripeApiKey;connection: AppConnection.Stripe;template: {secretsMapping: TStripeApiKeyRotation["secretsMapping"];- permissions: string[];+ permissionGroups: TStripeApiKeyPermissionGroup[];};};diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/StripeConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/StripeConnectionForm.tsxindex 2c5ffc72f0..26fe299d08 100644--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/StripeConnectionForm.tsx+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/StripeConnectionForm.tsx@@ -1,12 +1,30 @@import crypto from "crypto";import { useState } from "react";-import { FormProvider, useForm } from "react-hook-form";+import { Controller, FormProvider, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { z } from "zod";-import { Button, SheetFooter } from "@app/components/v3";-import { useGetAppConnectionOauthReturnUrl } from "@app/helpers/appConnections";+import {+ Button,+ Field,+ FieldError,+ FieldLabel,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ SheetFooter,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ APP_CONNECTION_MAP,+ getAppConnectionMethodDetails,+ useGetAppConnectionOauthReturnUrl+} from "@app/helpers/appConnections";import { isInfisicalCloud } from "@app/helpers/platform";import { useScopeVariant } from "@app/hooks";import { useGetAppConnectionOption } from "@app/hooks/api/appConnections";@@ -21,6 +39,7 @@ import {genericAppConnectionFieldsSchema,GenericAppConnectionsFields} from "./GenericAppConnectionFields";+import { Info } from "lucide-react";type Props = {appConnection?: TStripeConnection;@@ -66,6 +85,7 @@ export const StripeConnectionForm = ({ appConnection, projectId }: Props) => {const {handleSubmit,+ control,formState: { isSubmitting, isDirty }} = form;@@ -113,10 +133,42 @@ export const StripeConnectionForm = ({ appConnection, projectId }: Props) => {<form onSubmit={handleSubmit(onSubmit)}>{!isUpdate && <GenericAppConnectionsFields />}- <p className="mb-4 text-sm text-mineshaft-400">- You will be redirected to Stripe to install the Infisical app and choose the account- Infisical should manage API keys for.- </p>+ <Controller+ name="method"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Method+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent className="max-w-sm">+ {`The method you would like to use to connect with ${+ APP_CONNECTION_MAP[AppConnection.Stripe].name+ }. This field cannot be changed after creation.`}+ </TooltipContent>+ </Tooltip>+ </FieldLabel>+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>+ <SelectTrigger className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select a method..." />+ </SelectTrigger>+ <SelectContent position="popper">+ {Object.values(StripeConnectionMethod).map((method) => {+ return (+ <SelectItem value={method} key={method}>+ {getAppConnectionMethodDetails(method).name}{" "}+ </SelectItem>+ );+ })}+ </SelectContent>+ </Select>+ <FieldError errors={[error]} />+ </Field>+ )}+ />{!isLoading && isMissingConfig && (<p className="mb-4 text-sm text-red">