sentryApplicationDetails.tsx 19 KB

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