sentryApplicationDetails.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import {browserHistory} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import omit from 'lodash/omit';
  6. import {Observer} from 'mobx-react';
  7. import scrollToElement from 'scroll-to-element';
  8. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  9. import {openModal} from 'sentry/actionCreators/modal';
  10. import {
  11. addSentryAppToken,
  12. removeSentryAppToken,
  13. } from 'sentry/actionCreators/sentryAppTokens';
  14. import {Alert} from 'sentry/components/alert';
  15. import Avatar from 'sentry/components/avatar';
  16. import type {Model} from 'sentry/components/avatarChooser';
  17. import AvatarChooser from 'sentry/components/avatarChooser';
  18. import {Button} from 'sentry/components/button';
  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 getDynamicText from 'sentry/utils/getDynamicText';
  47. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  48. import withOrganization from 'sentry/utils/withOrganization';
  49. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  50. import ApiTokenRow from 'sentry/views/settings/account/apiTokenRow';
  51. import NewTokenHandler from 'sentry/views/settings/components/newTokenHandler';
  52. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  53. import PermissionsObserver from 'sentry/views/settings/organizationDeveloperSettings/permissionsObserver';
  54. type Resource = 'Project' | 'Team' | 'Release' | 'Event' | 'Organization' | 'Member';
  55. const AVATAR_STYLES = {
  56. color: {
  57. size: 50,
  58. title: t('Default Logo'),
  59. previewText: t('The default icon for integrations'),
  60. help: t('Image must be between 256px by 256px and 1024px by 1024px.'),
  61. },
  62. simple: {
  63. size: 20,
  64. title: t('Default Icon'),
  65. previewText: tct('This is a silhouette icon used only for [uiDocs:UI Components]', {
  66. uiDocs: (
  67. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/ui-components/" />
  68. ),
  69. }),
  70. help: t(
  71. 'Image must be between 256px by 256px and 1024px by 1024px, and may only use black and transparent pixels.'
  72. ),
  73. },
  74. };
  75. /**
  76. * Finds the resource in SENTRY_APP_PERMISSIONS that contains a given scope
  77. * We should always find a match unless there is a bug
  78. * @param {Scope} scope
  79. * @return {Resource | undefined}
  80. */
  81. const getResourceFromScope = (scope: Scope): Resource | undefined => {
  82. for (const permObj of SENTRY_APP_PERMISSIONS) {
  83. const allChoices = Object.values(permObj.choices);
  84. const allScopes = allChoices.reduce(
  85. (_allScopes: string[], choice) => _allScopes.concat(choice?.scopes ?? []),
  86. []
  87. );
  88. if (allScopes.includes(scope)) {
  89. return permObj.resource as Resource;
  90. }
  91. }
  92. return undefined;
  93. };
  94. /**
  95. * We need to map the API response errors to the actual form fields.
  96. * We do this by pulling out scopes and mapping each scope error to the correct input.
  97. * @param {Object} responseJSON
  98. */
  99. const mapFormErrors = (responseJSON?: any) => {
  100. if (!responseJSON) {
  101. return responseJSON;
  102. }
  103. const formErrors = omit(responseJSON, ['scopes']);
  104. if (responseJSON.scopes) {
  105. responseJSON.scopes.forEach((message: string) => {
  106. // find the scope from the error message of a specific format
  107. const matches = message.match(/Requested permission of (\w+:\w+)/);
  108. if (matches) {
  109. const scope = matches[1];
  110. const resource = getResourceFromScope(scope as Scope);
  111. // should always match but technically resource can be undefined
  112. if (resource) {
  113. formErrors[`${resource}--permission`] = [message];
  114. }
  115. }
  116. });
  117. }
  118. return formErrors;
  119. };
  120. class SentryAppFormModel extends FormModel {
  121. /**
  122. * Filter out Permission input field values.
  123. *
  124. * Permissions (API Scopes) are presented as a list of SelectFields.
  125. * Instead of them being submitted individually, we want them rolled
  126. * up into a single list of scopes (this is done in `PermissionSelection`).
  127. *
  128. * Because they are all individual inputs, we end up with attributes
  129. * in the JSON we send to the API that we don't want.
  130. *
  131. * This function filters those attributes out of the data that is
  132. * ultimately sent to the API.
  133. */
  134. getData() {
  135. return this.fields.toJSON().reduce((data, [k, v]) => {
  136. if (!k.endsWith('--permission')) {
  137. data[k] = v;
  138. }
  139. return data;
  140. }, {});
  141. }
  142. }
  143. type Props = RouteComponentProps<{appSlug?: string}, {}> & {
  144. organization: Organization;
  145. };
  146. type State = DeprecatedAsyncView['state'] & {
  147. app: SentryApp | null;
  148. newTokens: NewInternalAppApiToken[];
  149. tokens: InternalAppApiToken[];
  150. };
  151. class SentryApplicationDetails extends DeprecatedAsyncView<Props, State> {
  152. form = new SentryAppFormModel({mapFormErrors});
  153. getDefaultState(): State {
  154. return {
  155. ...super.getDefaultState(),
  156. app: null,
  157. tokens: [],
  158. newTokens: [],
  159. };
  160. }
  161. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  162. const {appSlug} = this.props.params;
  163. if (appSlug) {
  164. const endpoints = [['app', `/sentry-apps/${appSlug}/`]];
  165. if (this.hasTokenAccess) {
  166. endpoints.push(['tokens', `/sentry-apps/${appSlug}/api-tokens/`]);
  167. }
  168. return endpoints as [string, string][];
  169. }
  170. return [];
  171. }
  172. getHeaderTitle() {
  173. const {app} = this.state;
  174. const action = app ? 'Edit' : 'Create';
  175. const type = this.isInternal ? 'Internal' : 'Public';
  176. return tct('[action] [type] Integration', {action, type});
  177. }
  178. // Events may come from the API as "issue.created" when we just want "issue" here.
  179. normalize(events) {
  180. if (events.length === 0) {
  181. return events;
  182. }
  183. return events.map(e => e.split('.').shift());
  184. }
  185. handleSubmitSuccess = (data: SentryApp) => {
  186. const {app} = this.state;
  187. const {organization} = this.props;
  188. const type = this.isInternal ? 'internal' : 'public';
  189. const baseUrl = `/settings/${organization.slug}/developer-settings/`;
  190. const url = app ? `${baseUrl}?type=${type}` : `${baseUrl}${data.slug}/`;
  191. if (app) {
  192. addSuccessMessage(t('%s successfully saved.', data.name));
  193. } else {
  194. addSuccessMessage(t('%s successfully created.', data.name));
  195. }
  196. browserHistory.push(normalizeUrl(url));
  197. };
  198. handleSubmitError = err => {
  199. let errorMessage = t('Unknown Error');
  200. if (err.status >= 400 && err.status < 500) {
  201. errorMessage = err?.responseJSON.detail ?? errorMessage;
  202. }
  203. addErrorMessage(errorMessage);
  204. if (this.form.formErrors) {
  205. const firstErrorFieldId = Object.keys(this.form.formErrors)[0];
  206. if (firstErrorFieldId) {
  207. scrollToElement(`#${firstErrorFieldId}`, {
  208. align: 'middle',
  209. offset: 0,
  210. });
  211. }
  212. }
  213. };
  214. get hasTokenAccess() {
  215. return this.props.organization.access.includes('org:write');
  216. }
  217. get isInternal() {
  218. const {app} = this.state;
  219. if (app) {
  220. // if we are editing an existing app, check the status of the app
  221. return app.status === 'internal';
  222. }
  223. return this.props.route.path === 'new-internal/';
  224. }
  225. get showAuthInfo() {
  226. const {app} = this.state;
  227. return !(app?.clientSecret && app.clientSecret[0] === '*');
  228. }
  229. onAddToken = async (evt: React.MouseEvent): Promise<void> => {
  230. evt.preventDefault();
  231. const {app, newTokens} = this.state;
  232. if (!app) {
  233. return;
  234. }
  235. const api = this.api;
  236. const token = await addSentryAppToken(api, app);
  237. const updatedNewTokens = newTokens.concat(token);
  238. this.setState({newTokens: updatedNewTokens});
  239. };
  240. onRemoveToken = async (token: InternalAppApiToken) => {
  241. const {app, tokens} = this.state;
  242. if (!app) {
  243. return;
  244. }
  245. const api = this.api;
  246. const newTokens = tokens.filter(tok => tok.id !== token.id);
  247. await removeSentryAppToken(api, app, token.id);
  248. this.setState({tokens: newTokens});
  249. };
  250. handleFinishNewToken = (newToken: NewInternalAppApiToken) => {
  251. const {tokens, newTokens} = this.state;
  252. const updatedNewTokens = newTokens.filter(token => token.id !== newToken.id);
  253. const updatedTokens = tokens.concat(newToken as InternalAppApiToken);
  254. this.setState({tokens: updatedTokens, newTokens: updatedNewTokens});
  255. };
  256. renderTokens = () => {
  257. const {tokens, newTokens} = this.state;
  258. if (!this.hasTokenAccess) {
  259. return (
  260. <EmptyMessage description={t('You do not have access to view these tokens.')} />
  261. );
  262. }
  263. if (tokens.length < 1 && newTokens.length < 1) {
  264. return <EmptyMessage description={t('No tokens created yet.')} />;
  265. }
  266. const tokensToDisplay = tokens.map(token => (
  267. <ApiTokenRow
  268. data-test-id="api-token"
  269. key={token.id}
  270. token={token}
  271. onRemove={this.onRemoveToken}
  272. />
  273. ));
  274. tokensToDisplay.push(
  275. ...newTokens.map(newToken => (
  276. <NewTokenHandler
  277. data-test-id="new-api-token"
  278. key={newToken.id}
  279. token={getDynamicText({value: newToken.token, fixed: 'ORG_AUTH_TOKEN'})}
  280. handleGoBack={() => this.handleFinishNewToken(newToken)}
  281. />
  282. ))
  283. );
  284. return tokensToDisplay;
  285. };
  286. rotateClientSecret = async () => {
  287. try {
  288. const rotateResponse = await this.api.requestPromise(
  289. `/sentry-apps/${this.props.params.appSlug}/rotate-secret/`,
  290. {
  291. method: 'POST',
  292. }
  293. );
  294. openModal(({Body, Header}) => (
  295. <Fragment>
  296. <Header>{t('Rotated Client Secret')}</Header>
  297. <Body>
  298. <Alert type="info" showIcon>
  299. {t('This will be the only time your client secret is visible!')}
  300. </Alert>
  301. <p>
  302. {t('Your client secret is:')}
  303. <code>{rotateResponse.clientSecret}</code>
  304. </p>
  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. 'You do not have access to view these credentials because 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. <Button onClick={this.rotateClientSecret} priority="danger">
  501. Rotate client secret
  502. </Button>
  503. ) : undefined}
  504. </ClientSecret>
  505. )
  506. }
  507. </FormField>
  508. </PanelBody>
  509. </Panel>
  510. )}
  511. </Form>
  512. </div>
  513. );
  514. }
  515. }
  516. export default withOrganization(SentryApplicationDetails);
  517. const AvatarPreview = styled('div')`
  518. flex: 1;
  519. display: grid;
  520. grid: 25px 25px / 50px 1fr;
  521. `;
  522. const StyledPreviewAvatar = styled(Avatar)`
  523. grid-area: 1 / 1 / 3 / 2;
  524. justify-self: end;
  525. `;
  526. const AvatarPreviewTitle = styled('span')`
  527. display: block;
  528. grid-area: 1 / 2 / 2 / 3;
  529. padding-left: ${space(2)};
  530. font-weight: bold;
  531. `;
  532. const AvatarPreviewText = styled('span')`
  533. display: block;
  534. grid-area: 2 / 2 / 3 / 3;
  535. padding-left: ${space(2)};
  536. `;
  537. const HiddenSecret = styled('span')`
  538. width: 100px;
  539. font-style: italic;
  540. `;
  541. const ClientSecret = styled('div')`
  542. display: flex;
  543. justify-content: right;
  544. align-items: center;
  545. margin-right: 0;
  546. `;