sentryApplicationDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import {Fragment, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import omit from 'lodash/omit';
  4. import {Observer} from 'mobx-react';
  5. import scrollToElement from 'scroll-to-element';
  6. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  7. import {openModal} from 'sentry/actionCreators/modal';
  8. import {
  9. addSentryAppToken,
  10. removeSentryAppToken,
  11. } from 'sentry/actionCreators/sentryAppTokens';
  12. import Avatar from 'sentry/components/avatar';
  13. import type {Model} from 'sentry/components/avatarChooser';
  14. import AvatarChooser from 'sentry/components/avatarChooser';
  15. import {Button} from 'sentry/components/button';
  16. import Confirm from 'sentry/components/confirm';
  17. import {Alert} from 'sentry/components/core/alert';
  18. import EmptyMessage from 'sentry/components/emptyMessage';
  19. import Form from 'sentry/components/forms/form';
  20. import FormField from 'sentry/components/forms/formField';
  21. import JsonForm from 'sentry/components/forms/jsonForm';
  22. import type {FieldValue} from 'sentry/components/forms/model';
  23. import FormModel from 'sentry/components/forms/model';
  24. import ExternalLink from 'sentry/components/links/externalLink';
  25. import LoadingError from 'sentry/components/loadingError';
  26. import LoadingIndicator from 'sentry/components/loadingIndicator';
  27. import Panel from 'sentry/components/panels/panel';
  28. import PanelBody from 'sentry/components/panels/panelBody';
  29. import PanelHeader from 'sentry/components/panels/panelHeader';
  30. import TextCopyInput from 'sentry/components/textCopyInput';
  31. import {Tooltip} from 'sentry/components/tooltip';
  32. import {SENTRY_APP_PERMISSIONS} from 'sentry/constants';
  33. import {
  34. internalIntegrationForms,
  35. publicIntegrationForms,
  36. } from 'sentry/data/forms/sentryApplication';
  37. import {IconAdd} from 'sentry/icons';
  38. import {t, tct} from 'sentry/locale';
  39. import {space} from 'sentry/styles/space';
  40. import type {Scope} from 'sentry/types/core';
  41. import type {SentryApp, SentryAppAvatar} from 'sentry/types/integrations';
  42. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  43. import type {InternalAppApiToken, NewInternalAppApiToken} from 'sentry/types/user';
  44. import getDynamicText from 'sentry/utils/getDynamicText';
  45. import {
  46. type ApiQueryKey,
  47. setApiQueryData,
  48. useApiQuery,
  49. useQueryClient,
  50. } from 'sentry/utils/queryClient';
  51. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  52. import useApi from 'sentry/utils/useApi';
  53. import useOrganization from 'sentry/utils/useOrganization';
  54. import ApiTokenRow from 'sentry/views/settings/account/apiTokenRow';
  55. import NewTokenHandler from 'sentry/views/settings/components/newTokenHandler';
  56. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  57. import PermissionsObserver from 'sentry/views/settings/organizationDeveloperSettings/permissionsObserver';
  58. type Resource = 'Project' | 'Team' | 'Release' | 'Event' | 'Organization' | 'Member';
  59. const AVATAR_STYLES = {
  60. color: {
  61. size: 50,
  62. title: t('Default Logo'),
  63. previewText: t('The default icon for integrations'),
  64. help: t('Image must be between 256px by 256px and 1024px by 1024px.'),
  65. },
  66. simple: {
  67. size: 20,
  68. title: t('Default Icon'),
  69. previewText: tct('This is a silhouette icon used only for [uiDocs:UI Components]', {
  70. uiDocs: (
  71. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/ui-components/" />
  72. ),
  73. }),
  74. help: t(
  75. 'Image must be between 256px by 256px and 1024px by 1024px, and may only use black and transparent pixels.'
  76. ),
  77. },
  78. };
  79. /**
  80. * Finds the resource in SENTRY_APP_PERMISSIONS that contains a given scope
  81. * We should always find a match unless there is a bug
  82. * @param {Scope} scope
  83. * @return {Resource | undefined}
  84. */
  85. const getResourceFromScope = (scope: Scope): Resource | undefined => {
  86. for (const permObj of SENTRY_APP_PERMISSIONS) {
  87. const allChoices = Object.values(permObj.choices);
  88. const allScopes = allChoices.reduce(
  89. (_allScopes: string[], choice) => _allScopes.concat(choice?.scopes ?? []),
  90. []
  91. );
  92. if (allScopes.includes(scope)) {
  93. return permObj.resource as Resource;
  94. }
  95. }
  96. return undefined;
  97. };
  98. /**
  99. * We need to map the API response errors to the actual form fields.
  100. * We do this by pulling out scopes and mapping each scope error to the correct input.
  101. * @param {Object} responseJSON
  102. */
  103. const mapFormErrors = (responseJSON?: any) => {
  104. if (!responseJSON) {
  105. return responseJSON;
  106. }
  107. const formErrors = omit(responseJSON, ['scopes']);
  108. if (responseJSON.scopes) {
  109. responseJSON.scopes.forEach((message: string) => {
  110. // find the scope from the error message of a specific format
  111. const matches = message.match(/Requested permission of (\w+:\w+)/);
  112. if (matches) {
  113. const scope = matches[1];
  114. const resource = getResourceFromScope(scope as Scope);
  115. // should always match but technically resource can be undefined
  116. if (resource) {
  117. formErrors[`${resource}--permission`] = [message];
  118. }
  119. }
  120. });
  121. }
  122. return formErrors;
  123. };
  124. class SentryAppFormModel extends FormModel {
  125. /**
  126. * Filter out Permission input field values.
  127. *
  128. * Permissions (API Scopes) are presented as a list of SelectFields.
  129. * Instead of them being submitted individually, we want them rolled
  130. * up into a single list of scopes (this is done in `PermissionSelection`).
  131. *
  132. * Because they are all individual inputs, we end up with attributes
  133. * in the JSON we send to the API that we don't want.
  134. *
  135. * This function filters those attributes out of the data that is
  136. * ultimately sent to the API.
  137. */
  138. getData() {
  139. return this.fields.toJSON().reduce((data, [k, v]) => {
  140. if (!k.endsWith('--permission')) {
  141. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  142. data[k] = v;
  143. }
  144. return data;
  145. }, {});
  146. }
  147. }
  148. type Props = RouteComponentProps<{appSlug?: string}>;
  149. const makeSentryAppQueryKey = (appSlug?: string): ApiQueryKey => {
  150. return [`/sentry-apps/${appSlug}/`];
  151. };
  152. const makeSentryAppApiTokensQueryKey = (appSlug?: string): ApiQueryKey => {
  153. return [`/sentry-apps/${appSlug}/api-tokens/`];
  154. };
  155. export default function SentryApplicationDetails(props: Props) {
  156. const {appSlug} = props.params;
  157. const {router, location} = props;
  158. const organization = useOrganization();
  159. const [form] = useState<SentryAppFormModel>(
  160. () => new SentryAppFormModel({mapFormErrors})
  161. );
  162. const isEditingApp = !!appSlug;
  163. const api = useApi();
  164. const queryClient = useQueryClient();
  165. const SENTRY_APP_QUERY_KEY = makeSentryAppQueryKey(appSlug);
  166. const SENTRY_APP_API_TOKENS_QUERY_KEY = makeSentryAppApiTokensQueryKey(appSlug);
  167. const {
  168. data: app = undefined,
  169. isPending,
  170. isError,
  171. refetch,
  172. } = useApiQuery<SentryApp>(SENTRY_APP_QUERY_KEY, {
  173. staleTime: 30000,
  174. enabled: isEditingApp,
  175. });
  176. const {data: tokens = []} = useApiQuery<InternalAppApiToken[]>(
  177. SENTRY_APP_API_TOKENS_QUERY_KEY,
  178. {
  179. staleTime: 30000,
  180. enabled: isEditingApp,
  181. }
  182. );
  183. const [newTokens, setNewTokens] = useState<NewInternalAppApiToken[]>([]);
  184. // Events may come from the API as "issue.created" when we just want "issue" here.
  185. const normalize = (events: any) => {
  186. if (events.length === 0) {
  187. return events;
  188. }
  189. return events.map((e: any) => e.split('.').shift());
  190. };
  191. const hasTokenAccess = () => {
  192. return organization.access.includes('org:write');
  193. };
  194. const isInternal = () => {
  195. if (app) {
  196. // if we are editing an existing app, check the status of the app
  197. return app.status === 'internal';
  198. }
  199. return location.pathname.endsWith('new-internal/');
  200. };
  201. const showAuthInfo = () => !(app?.clientSecret && app.clientSecret[0] === '*');
  202. const headerTitle = () => {
  203. const action = app ? 'Edit' : 'Create';
  204. const type = isInternal() ? 'Internal' : 'Public';
  205. return tct('[action] [type] Integration', {action, type});
  206. };
  207. const handleSubmitSuccess = (data: SentryApp) => {
  208. const type = isInternal() ? 'internal' : 'public';
  209. const baseUrl = `/settings/${organization.slug}/developer-settings/`;
  210. const url = app ? `${baseUrl}?type=${type}` : `${baseUrl}${data.slug}/`;
  211. if (app) {
  212. addSuccessMessage(t('%s successfully saved.', data.name));
  213. refetch();
  214. } else {
  215. addSuccessMessage(t('%s successfully created.', data.name));
  216. }
  217. router.push(normalizeUrl(url));
  218. };
  219. const handleSubmitError = (err: any) => {
  220. let errorMessage = t('Unknown Error');
  221. if (err.status >= 400 && err.status < 500) {
  222. errorMessage = err?.responseJSON.detail ?? errorMessage;
  223. }
  224. addErrorMessage(errorMessage);
  225. if (form.formErrors) {
  226. const firstErrorFieldId = Object.keys(form.formErrors)[0];
  227. if (firstErrorFieldId) {
  228. scrollToElement(`#${firstErrorFieldId}`, {
  229. align: 'middle',
  230. offset: 0,
  231. });
  232. }
  233. }
  234. };
  235. const onAddToken = async (evt: React.MouseEvent): Promise<void> => {
  236. evt.preventDefault();
  237. if (!app) {
  238. return;
  239. }
  240. const token = await addSentryAppToken(api, app);
  241. const updatedNewTokens = newTokens.concat(token);
  242. setNewTokens(updatedNewTokens);
  243. };
  244. const onRemoveToken = async (token: InternalAppApiToken) => {
  245. if (!app) {
  246. return;
  247. }
  248. const updatedTokens = tokens.filter(tok => tok.id !== token.id);
  249. await removeSentryAppToken(api, app, token.id);
  250. setApiQueryData(queryClient, SENTRY_APP_API_TOKENS_QUERY_KEY, updatedTokens);
  251. };
  252. const handleFinishNewToken = (newToken: NewInternalAppApiToken) => {
  253. const updatedNewTokens = newTokens.filter(token => token.id !== newToken.id);
  254. const updatedTokens = tokens.concat(newToken as InternalAppApiToken);
  255. setApiQueryData(queryClient, SENTRY_APP_API_TOKENS_QUERY_KEY, updatedTokens);
  256. setNewTokens(updatedNewTokens);
  257. };
  258. const renderTokens = () => {
  259. if (!hasTokenAccess) {
  260. return (
  261. <EmptyMessage description={t('You do not have access to view these tokens.')} />
  262. );
  263. }
  264. if (tokens.length < 1 && newTokens.length < 1) {
  265. return <EmptyMessage description={t('No tokens created yet.')} />;
  266. }
  267. const tokensToDisplay = tokens.map(token => (
  268. <ApiTokenRow
  269. data-test-id="api-token"
  270. key={token.id}
  271. token={token}
  272. onRemove={onRemoveToken}
  273. />
  274. ));
  275. tokensToDisplay.push(
  276. ...newTokens.map(newToken => (
  277. <NewTokenHandler
  278. data-test-id="new-api-token"
  279. key={newToken.id}
  280. token={getDynamicText({value: newToken.token, fixed: 'ORG_AUTH_TOKEN'})}
  281. handleGoBack={() => handleFinishNewToken(newToken)}
  282. />
  283. ))
  284. );
  285. return tokensToDisplay;
  286. };
  287. const rotateClientSecret = async () => {
  288. try {
  289. const rotateResponse = await api.requestPromise(
  290. `/sentry-apps/${appSlug}/rotate-secret/`,
  291. {
  292. method: 'POST',
  293. }
  294. );
  295. openModal(({Body, Header}) => (
  296. <Fragment>
  297. <Header>{t('Your new Client Secret')}</Header>
  298. <Body>
  299. <Alert.Container>
  300. <Alert type="info" showIcon>
  301. {t('This will be the only time your client secret is visible!')}
  302. </Alert>
  303. </Alert.Container>
  304. <TextCopyInput aria-label={t('new-client-secret')}>
  305. {rotateResponse.clientSecret}
  306. </TextCopyInput>
  307. </Body>
  308. </Fragment>
  309. ));
  310. } catch {
  311. addErrorMessage(t('Error rotating secret'));
  312. }
  313. };
  314. const onFieldChange = (name: string, value: FieldValue): void => {
  315. if (name === 'webhookUrl' && !value && isInternal()) {
  316. // if no webhook, then set isAlertable to false
  317. form.setValue('isAlertable', false);
  318. }
  319. };
  320. const addAvatar = ({avatar}: Model) => {
  321. if (app && avatar) {
  322. const avatars =
  323. app?.avatars?.filter(prevAvatar => prevAvatar.color !== avatar.color) || [];
  324. avatars.push(avatar as SentryAppAvatar);
  325. setApiQueryData(queryClient, SENTRY_APP_QUERY_KEY, {...app, avatars});
  326. }
  327. };
  328. const getAvatarModel = (isColor: boolean): Model => {
  329. const defaultModel: Model = {
  330. avatar: {
  331. avatarType: 'default',
  332. avatarUuid: null,
  333. },
  334. };
  335. if (!app) {
  336. return defaultModel;
  337. }
  338. return {
  339. avatar: app?.avatars?.find(({color}) => color === isColor) || defaultModel.avatar,
  340. };
  341. };
  342. const getAvatarPreview = (isColor: boolean) => {
  343. if (!app) {
  344. return null;
  345. }
  346. const avatarStyle = isColor ? 'color' : 'simple';
  347. return (
  348. <AvatarPreview>
  349. <StyledPreviewAvatar
  350. size={AVATAR_STYLES[avatarStyle].size}
  351. sentryApp={app}
  352. isDefault
  353. />
  354. <AvatarPreviewTitle>{AVATAR_STYLES[avatarStyle].title}</AvatarPreviewTitle>
  355. <AvatarPreviewText>{AVATAR_STYLES[avatarStyle].previewText}</AvatarPreviewText>
  356. </AvatarPreview>
  357. );
  358. };
  359. const getAvatarChooser = (isColor: boolean) => {
  360. if (!app) {
  361. return null;
  362. }
  363. const avatarStyle = isColor ? 'color' : 'simple';
  364. return (
  365. <AvatarChooser
  366. type={isColor ? 'sentryAppColor' : 'sentryAppSimple'}
  367. allowGravatar={false}
  368. allowLetter={false}
  369. endpoint={`/sentry-apps/${app.slug}/avatar/`}
  370. model={getAvatarModel(isColor)}
  371. onSave={addAvatar}
  372. title={isColor ? t('Logo') : t('Small Icon')}
  373. help={AVATAR_STYLES[avatarStyle].help.concat(
  374. isInternal() ? '' : t(' Required for publishing.')
  375. )}
  376. savedDataUrl={undefined}
  377. defaultChoice={{
  378. allowDefault: true,
  379. choiceText: isColor ? t('Default logo') : t('Default small icon'),
  380. preview: getAvatarPreview(isColor),
  381. }}
  382. />
  383. );
  384. };
  385. const scopes = (app && [...app.scopes]) || [];
  386. const events = (app && normalize(app.events)) || [];
  387. const method = app ? 'PUT' : 'POST';
  388. const endpoint = app ? `/sentry-apps/${app.slug}/` : '/sentry-apps/';
  389. const forms = isInternal() ? internalIntegrationForms : publicIntegrationForms;
  390. let verifyInstall: boolean;
  391. if (isInternal()) {
  392. // force verifyInstall to false for all internal apps
  393. verifyInstall = false;
  394. } else {
  395. // use the existing value for verifyInstall if the app exists, otherwise default to true
  396. verifyInstall = app ? app.verifyInstall : true;
  397. }
  398. return (
  399. <div>
  400. <SettingsPageHeader title={headerTitle()} />
  401. {isEditingApp && isPending ? (
  402. <LoadingIndicator />
  403. ) : isEditingApp && isError ? (
  404. <LoadingError onRetry={refetch} />
  405. ) : (
  406. <Form
  407. apiMethod={method}
  408. apiEndpoint={endpoint}
  409. allowUndo
  410. initialData={{
  411. organization: organization.slug,
  412. isAlertable: false,
  413. isInternal: isInternal(),
  414. schema: {},
  415. scopes: [],
  416. ...app,
  417. verifyInstall, // need to overwrite the value in app for internal if it is true
  418. }}
  419. model={form}
  420. onSubmitSuccess={handleSubmitSuccess}
  421. onSubmitError={handleSubmitError}
  422. onFieldChange={onFieldChange}
  423. >
  424. <Observer>
  425. {() => {
  426. const webhookDisabled = isInternal() && !form.getValue('webhookUrl');
  427. return (
  428. <Fragment>
  429. <JsonForm additionalFieldProps={{webhookDisabled}} forms={forms} />
  430. {getAvatarChooser(true)}
  431. {getAvatarChooser(false)}
  432. <PermissionsObserver
  433. webhookDisabled={webhookDisabled}
  434. appPublished={app ? app.status === 'published' : false}
  435. scopes={scopes}
  436. events={events}
  437. newApp={!app}
  438. />
  439. </Fragment>
  440. );
  441. }}
  442. </Observer>
  443. {app && app.status === 'internal' && (
  444. <Panel>
  445. {hasTokenAccess() ? (
  446. <PanelHeader hasButtons>
  447. {t('Tokens')}
  448. <Button
  449. size="xs"
  450. icon={<IconAdd isCircled />}
  451. onClick={evt => onAddToken(evt)}
  452. data-test-id="token-add"
  453. >
  454. {t('New Token')}
  455. </Button>
  456. </PanelHeader>
  457. ) : (
  458. <PanelHeader>{t('Tokens')}</PanelHeader>
  459. )}
  460. <PanelBody>{renderTokens()}</PanelBody>
  461. </Panel>
  462. )}
  463. {app && (
  464. <Panel>
  465. <PanelHeader>{t('Credentials')}</PanelHeader>
  466. <PanelBody>
  467. {app.status !== 'internal' && (
  468. <FormField name="clientId" label="Client ID">
  469. {({value, id}: any) => (
  470. <TextCopyInput id={id}>
  471. {getDynamicText({value, fixed: 'CI_CLIENT_ID'})}
  472. </TextCopyInput>
  473. )}
  474. </FormField>
  475. )}
  476. <FormField
  477. name="clientSecret"
  478. label="Client Secret"
  479. help={t(`Your secret is only available briefly after integration creation. Make
  480. sure to save this value!`)}
  481. >
  482. {({value, id}: any) =>
  483. value ? (
  484. <Tooltip
  485. disabled={showAuthInfo()}
  486. position="right"
  487. containerDisplayMode="inline"
  488. title={t(
  489. 'Only Manager or Owner can view these credentials, or the permissions for this integration exceed those of your role.'
  490. )}
  491. >
  492. <TextCopyInput id={id}>
  493. {getDynamicText({value, fixed: 'CI_CLIENT_SECRET'})}
  494. </TextCopyInput>
  495. </Tooltip>
  496. ) : (
  497. <ClientSecret>
  498. <HiddenSecret>{t('hidden')}</HiddenSecret>
  499. {hasTokenAccess() ? (
  500. <Confirm
  501. onConfirm={rotateClientSecret}
  502. message={t(
  503. 'Are you sure you want to rotate the client secret? The current one will not be usable anymore, and this cannot be undone.'
  504. )}
  505. >
  506. <Button priority="danger">Rotate client secret</Button>
  507. </Confirm>
  508. ) : undefined}
  509. </ClientSecret>
  510. )
  511. }
  512. </FormField>
  513. </PanelBody>
  514. </Panel>
  515. )}
  516. </Form>
  517. )}
  518. </div>
  519. );
  520. }
  521. const AvatarPreview = styled('div')`
  522. flex: 1;
  523. display: grid;
  524. grid: 25px 25px / 50px 1fr;
  525. `;
  526. const StyledPreviewAvatar = styled(Avatar)`
  527. grid-area: 1 / 1 / 3 / 2;
  528. justify-self: end;
  529. `;
  530. const AvatarPreviewTitle = styled('span')`
  531. display: block;
  532. grid-area: 1 / 2 / 2 / 3;
  533. padding-left: ${space(2)};
  534. font-weight: ${p => p.theme.fontWeightBold};
  535. `;
  536. const AvatarPreviewText = styled('span')`
  537. display: block;
  538. grid-area: 2 / 2 / 3 / 3;
  539. padding-left: ${space(2)};
  540. `;
  541. const HiddenSecret = styled('span')`
  542. width: 100px;
  543. font-style: italic;
  544. `;
  545. const ClientSecret = styled('div')`
  546. display: flex;
  547. justify-content: right;
  548. align-items: center;
  549. margin-right: 0;
  550. `;