diff --git a/src/modules/integration-picker/components/IntegrationFields.tsx b/src/modules/integration-picker/components/IntegrationFields.tsx index 9bd9dcb..20f58c4 100644 --- a/src/modules/integration-picker/components/IntegrationFields.tsx +++ b/src/modules/integration-picker/components/IntegrationFields.tsx @@ -20,6 +20,7 @@ import { FieldErrors, UseFormSetValue } from 'react-hook-form'; import { useForm } from 'react-hook-form'; import useDeepCompareEffect from 'use-deep-compare-effect'; import { AuthenticationNotice, ConnectorConfigField } from '../types'; +import { shownFieldValue } from '../utils/credentialsPayload'; import { partitionNotices } from '../utils/partitionNotices'; import { formatSecretPlaceholder, isSecretPlaceholder } from '../utils/secretPlaceholder'; import { @@ -309,15 +310,7 @@ export const IntegrationForm: React.FC = ({ const schema = useMemo(() => createFormSchema(fields, rules), [fields, rules]); const defaultValues = useMemo(() => { - const initialData: Record = {}; - fields.forEach((field) => { - if (field.value !== undefined) { - initialData[field.key] = field.value.toString(); - } else { - initialData[field.key] = ''; - } - }); - return initialData; + return Object.fromEntries(fields.map((field) => [field.key, shownFieldValue(field)])); }, [fields]); const { formState, watch, reset, setValue, getValues } = useForm({ diff --git a/src/modules/integration-picker/hooks/useIntegrationPicker.ts b/src/modules/integration-picker/hooks/useIntegrationPicker.ts index 39acc7f..79bf5e0 100644 --- a/src/modules/integration-picker/hooks/useIntegrationPicker.ts +++ b/src/modules/integration-picker/hooks/useIntegrationPicker.ts @@ -18,8 +18,8 @@ import { isFalconConnectorConfig, isLegacyConnectorConfig, } from '../types'; +import { buildCredentialsPayload, withoutClearedFields } from '../utils/credentialsPayload'; import { describeConnectError, errorStatus } from '../utils/requestErrors'; -import { isSecretPlaceholder } from '../utils/secretPlaceholder'; // Shared retry configuration for queries const RETRY_CONFIG = { @@ -561,23 +561,13 @@ export const useIntegrationPicker = ({ setConnectionState({ loading: true, success: false }); try { - const cleanedFormData = { ...formData }; - if (accountData) { - fields.forEach((field) => { - if (field.secret !== false || field.type === 'password') { - const fieldValue = cleanedFormData[field.key]; - if (isSecretPlaceholder(fieldValue) && !editingSecrets.has(field.key)) { - delete cleanedFormData[field.key]; - } - } - }); - } - - Object.keys(cleanedFormData).forEach((key) => { - if (cleanedFormData[key] === '') { - delete cleanedFormData[key]; - } + const credentials = buildCredentialsPayload({ + formData, + fields, + editingSecrets, + editing: !!prefillAccount, }); + const filledCredentials = withoutClearedFields(credentials); const shouldRedirectForOAuth = authConfig?.type === 'oauth2' && @@ -624,8 +614,8 @@ export const useIntegrationPicker = ({ `${dashboardUrl}/embedded/accounts/callback`, ); let windowUrl = `${baseUrl}/connect/oauth2/${selectedIntegration.integration_id}?redirect_uri=${callbackEmbeddedAccountsUrl}&token=${token}&connection_attempt_id=${attemptId}`; - Object.keys(cleanedFormData).forEach((key) => { - windowUrl += `&${key}=${encodeURIComponent(cleanedFormData[key])}`; + Object.keys(filledCredentials).forEach((key) => { + windowUrl += `&${key}=${encodeURIComponent(filledCredentials[key])}`; }); const width = 1024; @@ -691,14 +681,14 @@ export const useIntegrationPicker = ({ accountId, token, integrationId: selectedIntegration.integration_id, - credentials: cleanedFormData, + credentials, }); successData = { id: accountId, provider: selectedIntegration.provider }; } else { const response = await connectAccount({ baseUrl, token, - credentials: cleanedFormData, + credentials: filledCredentials, integrationId: selectedIntegration.integration_id, }); if (!response) { @@ -723,7 +713,7 @@ export const useIntegrationPicker = ({ formData, editingSecrets, handleSuccess, - accountData, + prefillAccount, fields, accountId, authConfig, diff --git a/src/modules/integration-picker/utils/credentialsPayload.test.ts b/src/modules/integration-picker/utils/credentialsPayload.test.ts new file mode 100644 index 0000000..543d8e1 --- /dev/null +++ b/src/modules/integration-picker/utils/credentialsPayload.test.ts @@ -0,0 +1,173 @@ +import { describe, expect, it } from 'vitest'; +import type { ConnectorConfigField } from '../types'; +import { buildCredentialsPayload, withoutClearedFields } from './credentialsPayload'; + +const field = (overrides: Partial): ConnectorConfigField => ({ + label: overrides.key ?? 'field', + key: 'field', + required: false, + readOnly: false, + secret: false, + placeholder: '', + ...overrides, +}); + +const placeholder = '__secretvalue:**redacted**1234'; + +const shownFields = [ + field({ key: 'apiUrl', required: true, value: 'https://api.example.com' }), + field({ key: 'region', value: 'eu' }), + field({ key: 'retries', value: '3' }), + field({ key: 'subdomain' }), + field({ key: 'apiKey', secret: true, required: true, value: placeholder }), + field({ key: 'apiToken', type: 'password', value: placeholder }), +]; + +describe('buildCredentialsPayload', () => { + describe('when editing an account', () => { + it('sends a field the form showed with a value and the user emptied as null', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', region: '', retries: '' }, + fields: shownFields, + editingSecrets: new Set(), + editing: true, + }); + + expect(actual).toEqual({ + apiUrl: 'https://api.example.com', + region: null, + retries: null, + }); + }); + + it('sends a field showing a connector default the user emptied as null', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', timeout: '' }, + fields: [...shownFields, field({ key: 'timeout', type: 'number', value: 0 })], + editingSecrets: new Set(), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com', timeout: null }); + }); + + it('never clears a secret field, even one showing a real value', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', apiToken: '' }, + fields: [ + ...shownFields.filter((f) => f.key !== 'apiToken'), + field({ key: 'apiToken', type: 'password', value: 'legacy-token' }), + ], + editingSecrets: new Set(['apiToken']), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + + it('treats a field without a secret flag as a secret, as the API stores it', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', webhookKey: '' }, + fields: [ + ...shownFields, + field({ key: 'webhookKey', secret: undefined, value: placeholder }), + ], + editingSecrets: new Set(['webhookKey']), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + + it('never clears a required field, leaving the stored value to the API', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: '', region: 'eu' }, + fields: shownFields, + editingSecrets: new Set(), + editing: true, + }); + + expect(actual).toEqual({ region: 'eu' }); + }); + + it('leaves out an empty field the form showed without a value', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', subdomain: '' }, + fields: shownFields, + editingSecrets: new Set(), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + + it('leaves out a secret the user did not open, so the stored one is kept', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', apiKey: placeholder }, + fields: shownFields, + editingSecrets: new Set(), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + + it('leaves out a secret the user opened and left empty, so the stored one is kept', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', apiToken: '' }, + fields: shownFields, + editingSecrets: new Set(['apiToken']), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + + it('sends a placeholder the user opened as it stands', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', apiKey: placeholder }, + fields: shownFields, + editingSecrets: new Set(['apiKey']), + editing: true, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com', apiKey: placeholder }); + }); + + it('sends a value the user entered', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', apiKey: 'new-key', region: 'us' }, + fields: shownFields, + editingSecrets: new Set(['apiKey']), + editing: true, + }); + + expect(actual).toEqual({ + apiUrl: 'https://api.example.com', + apiKey: 'new-key', + region: 'us', + }); + }); + }); + + describe('when nothing stored is shown, as on a new account or another profile', () => { + it('leaves out an empty field', () => { + const actual = buildCredentialsPayload({ + formData: { apiUrl: 'https://api.example.com', region: '', apiToken: '' }, + fields: shownFields, + editingSecrets: new Set(), + editing: false, + }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); + }); +}); + +describe('withoutClearedFields', () => { + it('drops the cleared fields and keeps the rest', () => { + const actual = withoutClearedFields({ apiUrl: 'https://api.example.com', region: null }); + + expect(actual).toEqual({ apiUrl: 'https://api.example.com' }); + }); +}); diff --git a/src/modules/integration-picker/utils/credentialsPayload.ts b/src/modules/integration-picker/utils/credentialsPayload.ts new file mode 100644 index 0000000..07c8faa --- /dev/null +++ b/src/modules/integration-picker/utils/credentialsPayload.ts @@ -0,0 +1,69 @@ +import type { ConnectorConfigField } from '../types'; +import { isSecretPlaceholder } from './secretPlaceholder'; + +export type CredentialsPayload = Record; + +export const shownFieldValue = (field: ConnectorConfigField): string => + field.value === undefined ? '' : field.value.toString(); + +const isSecretField = (field: ConnectorConfigField) => + field.secret !== false || field.type === 'password'; + +const untouchedSecretKeys = ( + formData: Record, + fields: ConnectorConfigField[], + editingSecrets: Set, +) => + new Set( + fields + .filter( + (field) => + isSecretField(field) && + isSecretPlaceholder(formData[field.key]) && + !editingSecrets.has(field.key), + ) + .map((field) => field.key), + ); + +const emptiedKeys = (formData: Record, fields: ConnectorConfigField[]) => + new Set( + fields + .filter( + (field) => + !isSecretField(field) && + field.required !== true && + shownFieldValue(field) !== '' && + formData[field.key] === '', + ) + .map((field) => field.key), + ); + +/** + * On an edit, a field the form showed with a value and the user emptied is sent as `null`, so + * the API removes it. Secrets are never cleared this way: opening one empties it before any typing. + */ +export const buildCredentialsPayload = ({ + formData, + fields, + editingSecrets, + editing, +}: { + formData: Record; + fields: ConnectorConfigField[]; + editingSecrets: Set; + editing: boolean; +}): CredentialsPayload => { + const keptSecrets = untouchedSecretKeys(formData, fields, editingSecrets); + const cleared = editing ? emptiedKeys(formData, fields) : new Set(); + + return Object.fromEntries( + Object.entries(formData) + .filter(([key, value]) => !keptSecrets.has(key) && (value !== '' || cleared.has(key))) + .map(([key, value]) => [key, cleared.has(key) ? null : value]), + ); +}; + +export const withoutClearedFields = (credentials: CredentialsPayload): Record => + Object.fromEntries( + Object.entries(credentials).filter((entry): entry is [string, string] => entry[1] !== null), + );