sentryApplicationDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import omit from 'lodash/omit';
  5. import {Observer} from 'mobx-react';
  6. import scrollToElement from 'scroll-to-element';
  7. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  8. import {openModal} from 'sentry/actionCreators/modal';
  9. import {
  10. addSentryAppToken,
  11. removeSentryAppToken,
  12. } from 'sentry/actionCreators/sentryAppTokens';
  13. import {Alert} from 'sentry/components/alert';
  14. import Avatar from 'sentry/components/avatar';
  15. import type {Model} from 'sentry/components/avatarChooser';
  16. import AvatarChooser from 'sentry/components/avatarChooser';
  17. import {Button} from 'sentry/components/button';
  18. import Confirm from 'sentry/components/confirm';
  19. import EmptyMessage from 'sentry/components/emptyMessage';
  20. import Form from 'sentry/components/forms/form';
  21. import FormField from 'sentry/components/forms/formField';
  22. import JsonForm from 'sentry/components/forms/jsonForm';
  23. import type {FieldValue} from 'sentry/components/forms/model';
  24. import FormModel from 'sentry/components/forms/model';
  25. import ExternalLink from 'sentry/components/links/externalLink';
  26. import Panel from 'sentry/components/panels/panel';
  27. import PanelBody from 'sentry/components/panels/panelBody';
  28. import PanelHeader from 'sentry/components/panels/panelHeader';
  29. import TextCopyInput from 'sentry/components/textCopyInput';
  30. import {Tooltip} from 'sentry/components/tooltip';
  31. import {SENTRY_APP_PERMISSIONS} from 'sentry/constants';
  32. import {
  33. internalIntegrationForms,
  34. publicIntegrationForms,
  35. } from 'sentry/data/forms/sentryApplication';
  36. import {IconAdd} from 'sentry/icons';
  37. import {t, tct} from 'sentry/locale';
  38. import {space} from 'sentry/styles/space';
  39. import type {
  40. InternalAppApiToken,
  41. NewInternalAppApiToken,
  42. Organization,
  43. Scope,
  44. SentryApp,
  45. } from 'sentry/types';
  46. import {browserHistory} from 'sentry/utils/browserHistory';
  47. import getDynamicText from 'sentry/utils/getDynamicText';
  48. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  49. import withOrganization from 'sentry/utils/withOrganization';
  50. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  51. import ApiTokenRow from 'sentry/views/settings/account/apiTokenRow';
  52. import NewTokenHandler from 'sentry/views/settings/components/newTokenHandler';
  53. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  54. import PermissionsObserver from 'sentry/views/settings/organizationDeveloperSettings/permissionsObserver';
  55. type Resource = 'Project' | 'Team' | 'Release' | 'Event' | 'Organization' | 'Member';
  56. const AVATAR_STYLES = {
  57. color: {
  58. size: 50,
  59. title: t('Default Logo'),
  60. previewText: t('The default icon for integrations'),
  61. help: t('Image must be between 256px by 256px and 1024px by 1024px.'),
  62. },
  63. simple: {
  64. size: 20,
  65. title: t('Default Icon'),
  66. previewText: tct('This is a silhouette icon used only for [uiDocs:UI Components]', {
  67. uiDocs: (
  68. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/ui-components/" />
  69. ),
  70. }),
  71. help: t(
  72. 'Image must be between 256px by 256px and 1024px by 1024px, and may only use black and transparent pixels.'
  73. ),
  74. },
  75. };
  76. /**
  77. * Finds the resource in SENTRY_APP_PERMISSIONS that contains a given scope
  78. * We should always find a match unless there is a bug
  79. * @param {Scope} scope
  80. * @return {Resource | undefined}
  81. */
  82. const getResourceFromScope = (scope: Scope): Resource | undefined => {
  83. for (const permObj of SENTRY_APP_PERMISSIONS) {
  84. const allChoices = Object.values(permObj.choices);
  85. const allScopes = allChoices.reduce(
  86. (_allScopes: string[], choice) => _allScopes.concat(choice?.scopes ?? []),
  87. []
  88. );
  89. if (allScopes.includes(scope)) {
  90. return permObj.resource as Resource;
  91. }
  92. }
  93. return undefined;
  94. };
  95. /**
  96. * We need to map the API response errors to the actual form fields.
  97. * We do this by pulling out scopes and mapping each scope error to the correct input.
  98. * @param {Object} responseJSON
  99. */
  100. const mapFormErrors = (responseJSON?: any) => {
  101. if (!responseJSON) {
  102. return responseJSON;
  103. }
  104. const formErrors = omit(responseJSON, ['scopes']);
  105. if (responseJSON.scopes) {
  106. responseJSON.scopes.forEach((message: string) => {
  107. // find the scope from the error message of a specific format
  108. const matches = message.match(/Requested permission of (\w+:\w+)/);
  109. if (matches) {
  110. const scope = matches[1];
  111. const resource = getResourceFromScope(scope as Scope);
  112. // should always match but technically resource can be undefined
  113. if (resource) {
  114. formErrors[`${resource}--permission`] = [message];
  115. }
  116. }
  117. });
  118. }
  119. return formErrors;
  120. };
  121. class SentryAppFormModel extends FormModel {
  122. /**
  123. * Filter out Permission input field values.
  124. *
  125. * Permissions (API Scopes) are presented as a list of SelectFields.
  126. * Instead of them being submitted individually, we want them rolled
  127. * up into a single list of scopes (this is done in `PermissionSelection`).
  128. *
  129. * Because they are all individual inputs, we end up with attributes
  130. * in the JSON we send to the API that we don't want.
  131. *
  132. * This function filters those attributes out of the data that is
  133. * ultimately sent to the API.
  134. */
  135. getData() {
  136. return this.fields.toJSON().reduce((data, [k, v]) => {
  137. if (!k.endsWith('--permission')) {
  138. data[k] = v;
  139. }
  140. return data;
  141. }, {});
  142. }
  143. }
  144. type Props = RouteComponentProps<{appSlug?: string}, {}> & {
  145. organization: Organization;
  146. };
  147. type State = DeprecatedAsyncView['state'] & {
  148. app: SentryApp | null;
  149. newTokens: NewInternalAppApiToken[];
  150. tokens: InternalAppApiToken[];
  151. };
  152. class SentryApplicationDetails extends DeprecatedAsyncView<Props, State> {
  153. form = new SentryAppFormModel({mapFormErrors});
  154. getDefaultState(): State {
  155. return {
  156. ...super.getDefaultState(),
  157. app: null,
  158. tokens: [],
  159. newTokens: [],
  160. };
  161. }
  162. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  163. const {appSlug} = this.props.params;
  164. if (appSlug) {
  165. const endpoints = [['app', `/sentry-apps/${appSlug}/`]];
  166. if (this.hasTokenAccess) {
  167. endpoints.push(['tokens', `/sentry-apps/${appSlug}/api-tokens/`]);
  168. }
  169. return endpoints as [string, string][];
  170. }
  171. return [];
  172. }
  173. getHeaderTitle() {
  174. const {app} = this.state;
  175. const action = app ? 'Edit' : 'Create';
  176. const type = this.isInternal ? 'Internal' : 'Public';
  177. return tct('[action] [type] Integration', {action, type});
  178. }
  179. // Events may come from the API as "issue.created" when we just want "issue" here.
  180. normalize(events) {
  181. if (events.length === 0) {
  182. return events;
  183. }
  184. return events.map(e => e.split('.').shift());
  185. }
  186. handleSubmitSuccess = (data: SentryApp) => {
  187. const {app} = this.state;
  188. const {organization} = this.props;
  189. const type = this.isInternal ? 'internal' : 'public';
  190. const baseUrl = `/settings/${organization.slug}/developer-settings/`;
  191. const url = app ? `${baseUrl}?type=${type}` : `${baseUrl}${data.slug}/`;
  192. if (app) {
  193. addSuccessMessage(t('%s successfully saved.', data.name));
  194. } else {
  195. addSuccessMessage(t('%s successfully created.', data.name));
  196. }
  197. browserHistory.push(normalizeUrl(url));
  198. };
  199. handleSubmitError = err => {
  200. let errorMessage = t('Unknown Error');
  201. if (err.status >= 400 && err.status < 500) {
  202. errorMessage = err?.responseJSON.detail ?? errorMessage;
  203. }
  204. addErrorMessage(errorMessage);
  205. if (this.form.formErrors) {
  206. const firstErrorFieldId = Object.keys(this.form.formErrors)[0];
  207. if (firstErrorFieldId) {
  208. scrollToElement(`#${firstErrorFieldId}`, {
  209. align: 'middle',
  210. offset: 0,
  211. });
  212. }
  213. }
  214. };
  215. get hasTokenAccess() {
  216. return this.props.organization.access.includes('org:write');
  217. }
  218. get isInternal() {
  219. const {app} = this.state;
  220. if (app) {
  221. // if we are editing an existing app, check the status of the app
  222. return app.status === 'internal';
  223. }
  224. return this.props.location.pathname.endsWith('new-internal/');
  225. }
  226. get showAuthInfo() {
  227. const {app} = this.state;
  228. return !(app?.clientSecret && app.clientSecret[0] === '*');
  229. }
  230. onAddToken = async (evt: React.MouseEvent): Promise<void> => {
  231. evt.preventDefault();
  232. const {app, newTokens} = this.state;
  233. if (!app) {
  234. return;
  235. }
  236. const api = this.api;
  237. const token = await addSentryAppToken(api, app);
  238. const updatedNewTokens = newTokens.concat(token);
  239. this.setState({newTokens: updatedNewTokens});
  240. };
  241. onRemoveToken = async (token: InternalAppApiToken) => {
  242. const {app, tokens} = this.state;
  243. if (!app) {
  244. return;
  245. }
  246. const api = this.api;
  247. const newTokens = tokens.filter(tok => tok.id !== token.id);
  248. await removeSentryAppToken(api, app, token.id);
  249. this.setState({tokens: newTokens});
  250. };
  251. handleFinishNewToken = (newToken: NewInternalAppApiToken) => {
  252. const {tokens, newTokens} = this.state;
  253. const updatedNewTokens = newTokens.filter(token => token.id !== newToken.id);
  254. const updatedTokens = tokens.concat(newToken as InternalAppApiToken);
  255. this.setState({tokens: updatedTokens, newTokens: updatedNewTokens});
  256. };
  257. renderTokens = () => {
  258. const {tokens, newTokens} = this.state;
  259. if (!this.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={this.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={() => this.handleFinishNewToken(newToken)}
  282. />
  283. ))
  284. );
  285. return tokensToDisplay;
  286. };
  287. rotateClientSecret = async () => {
  288. try {
  289. const rotateResponse = await this.api.requestPromise(
  290. `/sentry-apps/${this.props.params.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 type="info" showIcon>
  300. {t('This will be the only time your client secret is visible!')}
  301. </Alert>
  302. <TextCopyInput aria-label={t('new-client-secret')}>
  303. {rotateResponse.clientSecret}
  304. </TextCopyInput>
  305. </Body>
  306. </Fragment>
  307. ));
  308. } catch {
  309. addErrorMessage(t('Error rotating secret'));
  310. }
  311. };
  312. onFieldChange = (name: string, value: FieldValue): void => {
  313. if (name === 'webhookUrl' && !value && this.isInternal) {
  314. // if no webhook, then set isAlertable to false
  315. this.form.setValue('isAlertable', false);
  316. }
  317. };
  318. addAvatar = ({avatar}: Model) => {
  319. const {app} = this.state;
  320. if (app && avatar) {
  321. const avatars =
  322. app?.avatars?.filter(prevAvatar => prevAvatar.color !== avatar.color) || [];
  323. avatars.push(avatar);
  324. this.setState({app: {...app, avatars}});
  325. }
  326. };
  327. getAvatarModel = (isColor: boolean): Model => {
  328. const {app} = this.state;
  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. getAvatarPreview = (isColor: boolean) => {
  343. const {app} = this.state;
  344. if (!app) {
  345. return null;
  346. }
  347. const avatarStyle = isColor ? 'color' : 'simple';
  348. return (
  349. <AvatarPreview>
  350. <StyledPreviewAvatar
  351. size={AVATAR_STYLES[avatarStyle].size}
  352. sentryApp={app}
  353. isDefault
  354. />
  355. <AvatarPreviewTitle>{AVATAR_STYLES[avatarStyle].title}</AvatarPreviewTitle>
  356. <AvatarPreviewText>{AVATAR_STYLES[avatarStyle].previewText}</AvatarPreviewText>
  357. </AvatarPreview>
  358. );
  359. };
  360. getAvatarChooser = (isColor: boolean) => {
  361. const {app} = this.state;
  362. if (!app) {
  363. return null;
  364. }
  365. const avatarStyle = isColor ? 'color' : 'simple';
  366. return (
  367. <AvatarChooser
  368. type={isColor ? 'sentryAppColor' : 'sentryAppSimple'}
  369. allowGravatar={false}
  370. allowLetter={false}
  371. endpoint={`/sentry-apps/${app.slug}/avatar/`}
  372. model={this.getAvatarModel(isColor)}
  373. onSave={this.addAvatar}
  374. title={isColor ? t('Logo') : t('Small Icon')}
  375. help={AVATAR_STYLES[avatarStyle].help.concat(
  376. this.isInternal ? '' : t(' Required for publishing.')
  377. )}
  378. savedDataUrl={undefined}
  379. defaultChoice={{
  380. allowDefault: true,
  381. choiceText: isColor ? t('Default logo') : t('Default small icon'),
  382. preview: this.getAvatarPreview(isColor),
  383. }}
  384. />
  385. );
  386. };
  387. renderBody() {
  388. const {app} = this.state;
  389. const scopes = (app && [...app.scopes]) || [];
  390. const events = (app && this.normalize(app.events)) || [];
  391. const method = app ? 'PUT' : 'POST';
  392. const endpoint = app ? `/sentry-apps/${app.slug}/` : '/sentry-apps/';
  393. const forms = this.isInternal ? internalIntegrationForms : publicIntegrationForms;
  394. let verifyInstall: boolean;
  395. if (this.isInternal) {
  396. // force verifyInstall to false for all internal apps
  397. verifyInstall = false;
  398. } else {
  399. // use the existing value for verifyInstall if the app exists, otherwise default to true
  400. verifyInstall = app ? app.verifyInstall : true;
  401. }
  402. return (
  403. <div>
  404. <SettingsPageHeader title={this.getHeaderTitle()} />
  405. <Form
  406. apiMethod={method}
  407. apiEndpoint={endpoint}
  408. allowUndo
  409. initialData={{
  410. organization: this.props.organization.slug,
  411. isAlertable: false,
  412. isInternal: this.isInternal,
  413. schema: {},
  414. scopes: [],
  415. ...app,
  416. verifyInstall, // need to overwrite the value in app for internal if it is true
  417. }}
  418. model={this.form}
  419. onSubmitSuccess={this.handleSubmitSuccess}
  420. onSubmitError={this.handleSubmitError}
  421. onFieldChange={this.onFieldChange}
  422. >
  423. <Observer>
  424. {() => {
  425. const webhookDisabled =
  426. this.isInternal && !this.form.getValue('webhookUrl');
  427. return (
  428. <Fragment>
  429. <JsonForm additionalFieldProps={{webhookDisabled}} forms={forms} />
  430. {this.getAvatarChooser(true)}
  431. {this.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. {this.hasTokenAccess ? (
  446. <PanelHeader hasButtons>
  447. {t('Tokens')}
  448. <Button
  449. size="xs"
  450. icon={<IconAdd isCircled />}
  451. onClick={evt => this.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>{this.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}) => (
  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}) =>
  483. value ? (
  484. <Tooltip
  485. disabled={this.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. {this.hasTokenAccess ? (
  500. <Confirm
  501. onConfirm={this.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. </div>
  518. );
  519. }
  520. }
  521. export default withOrganization(SentryApplicationDetails);
  522. const AvatarPreview = styled('div')`
  523. flex: 1;
  524. display: grid;
  525. grid: 25px 25px / 50px 1fr;
  526. `;
  527. const StyledPreviewAvatar = styled(Avatar)`
  528. grid-area: 1 / 1 / 3 / 2;
  529. justify-self: end;
  530. `;
  531. const AvatarPreviewTitle = styled('span')`
  532. display: block;
  533. grid-area: 1 / 2 / 2 / 3;
  534. padding-left: ${space(2)};
  535. font-weight: ${p => p.theme.fontWeightBold};
  536. `;
  537. const AvatarPreviewText = styled('span')`
  538. display: block;
  539. grid-area: 2 / 2 / 3 / 3;
  540. padding-left: ${space(2)};
  541. `;
  542. const HiddenSecret = styled('span')`
  543. width: 100px;
  544. font-style: italic;
  545. `;
  546. const ClientSecret = styled('div')`
  547. display: flex;
  548. justify-content: right;
  549. align-items: center;
  550. margin-right: 0;
  551. `;