sentryApplicationDetails.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 {
  10. addSentryAppToken,
  11. removeSentryAppToken,
  12. } from 'sentry/actionCreators/sentryAppTokens';
  13. import Avatar from 'sentry/components/avatar';
  14. import type {Model} from 'sentry/components/avatarChooser';
  15. import AvatarChooser from 'sentry/components/avatarChooser';
  16. import {Button} from 'sentry/components/button';
  17. import EmptyMessage from 'sentry/components/emptyMessage';
  18. import Form from 'sentry/components/forms/form';
  19. import FormField from 'sentry/components/forms/formField';
  20. import JsonForm from 'sentry/components/forms/jsonForm';
  21. import type {FieldValue} from 'sentry/components/forms/model';
  22. import FormModel from 'sentry/components/forms/model';
  23. import ExternalLink from 'sentry/components/links/externalLink';
  24. import Panel from 'sentry/components/panels/panel';
  25. import PanelBody from 'sentry/components/panels/panelBody';
  26. import PanelHeader from 'sentry/components/panels/panelHeader';
  27. import TextCopyInput from 'sentry/components/textCopyInput';
  28. import {Tooltip} from 'sentry/components/tooltip';
  29. import {SENTRY_APP_PERMISSIONS} from 'sentry/constants';
  30. import {
  31. internalIntegrationForms,
  32. publicIntegrationForms,
  33. } from 'sentry/data/forms/sentryApplication';
  34. import {IconAdd} from 'sentry/icons';
  35. import {t, tct} from 'sentry/locale';
  36. import {space} from 'sentry/styles/space';
  37. import type {
  38. InternalAppApiToken,
  39. NewInternalAppApiToken,
  40. Organization,
  41. Scope,
  42. SentryApp,
  43. } from 'sentry/types';
  44. import getDynamicText from 'sentry/utils/getDynamicText';
  45. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  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.route.path === '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. onFieldChange = (name: string, value: FieldValue): void => {
  285. if (name === 'webhookUrl' && !value && this.isInternal) {
  286. // if no webhook, then set isAlertable to false
  287. this.form.setValue('isAlertable', false);
  288. }
  289. };
  290. addAvatar = ({avatar}: Model) => {
  291. const {app} = this.state;
  292. if (app && avatar) {
  293. const avatars =
  294. app?.avatars?.filter(prevAvatar => prevAvatar.color !== avatar.color) || [];
  295. avatars.push(avatar);
  296. this.setState({app: {...app, avatars}});
  297. }
  298. };
  299. getAvatarModel = (isColor: boolean): Model => {
  300. const {app} = this.state;
  301. const defaultModel: Model = {
  302. avatar: {
  303. avatarType: 'default',
  304. avatarUuid: null,
  305. },
  306. };
  307. if (!app) {
  308. return defaultModel;
  309. }
  310. return {
  311. avatar: app?.avatars?.find(({color}) => color === isColor) || defaultModel.avatar,
  312. };
  313. };
  314. getAvatarPreview = (isColor: boolean) => {
  315. const {app} = this.state;
  316. if (!app) {
  317. return null;
  318. }
  319. const avatarStyle = isColor ? 'color' : 'simple';
  320. return (
  321. <AvatarPreview>
  322. <StyledPreviewAvatar
  323. size={AVATAR_STYLES[avatarStyle].size}
  324. sentryApp={app}
  325. isDefault
  326. />
  327. <AvatarPreviewTitle>{AVATAR_STYLES[avatarStyle].title}</AvatarPreviewTitle>
  328. <AvatarPreviewText>{AVATAR_STYLES[avatarStyle].previewText}</AvatarPreviewText>
  329. </AvatarPreview>
  330. );
  331. };
  332. getAvatarChooser = (isColor: boolean) => {
  333. const {app} = this.state;
  334. if (!app) {
  335. return null;
  336. }
  337. const avatarStyle = isColor ? 'color' : 'simple';
  338. return (
  339. <AvatarChooser
  340. type={isColor ? 'sentryAppColor' : 'sentryAppSimple'}
  341. allowGravatar={false}
  342. allowLetter={false}
  343. endpoint={`/sentry-apps/${app.slug}/avatar/`}
  344. model={this.getAvatarModel(isColor)}
  345. onSave={this.addAvatar}
  346. title={isColor ? t('Logo') : t('Small Icon')}
  347. help={AVATAR_STYLES[avatarStyle].help.concat(
  348. this.isInternal ? '' : t(' Required for publishing.')
  349. )}
  350. savedDataUrl={undefined}
  351. defaultChoice={{
  352. allowDefault: true,
  353. choiceText: isColor ? t('Default logo') : t('Default small icon'),
  354. preview: this.getAvatarPreview(isColor),
  355. }}
  356. />
  357. );
  358. };
  359. renderBody() {
  360. const {app} = this.state;
  361. const scopes = (app && [...app.scopes]) || [];
  362. const events = (app && this.normalize(app.events)) || [];
  363. const method = app ? 'PUT' : 'POST';
  364. const endpoint = app ? `/sentry-apps/${app.slug}/` : '/sentry-apps/';
  365. const forms = this.isInternal ? internalIntegrationForms : publicIntegrationForms;
  366. let verifyInstall: boolean;
  367. if (this.isInternal) {
  368. // force verifyInstall to false for all internal apps
  369. verifyInstall = false;
  370. } else {
  371. // use the existing value for verifyInstall if the app exists, otherwise default to true
  372. verifyInstall = app ? app.verifyInstall : true;
  373. }
  374. return (
  375. <div>
  376. <SettingsPageHeader title={this.getHeaderTitle()} />
  377. <Form
  378. apiMethod={method}
  379. apiEndpoint={endpoint}
  380. allowUndo
  381. initialData={{
  382. organization: this.props.organization.slug,
  383. isAlertable: false,
  384. isInternal: this.isInternal,
  385. schema: {},
  386. scopes: [],
  387. ...app,
  388. verifyInstall, // need to overwrite the value in app for internal if it is true
  389. }}
  390. model={this.form}
  391. onSubmitSuccess={this.handleSubmitSuccess}
  392. onSubmitError={this.handleSubmitError}
  393. onFieldChange={this.onFieldChange}
  394. >
  395. <Observer>
  396. {() => {
  397. const webhookDisabled =
  398. this.isInternal && !this.form.getValue('webhookUrl');
  399. return (
  400. <Fragment>
  401. <JsonForm additionalFieldProps={{webhookDisabled}} forms={forms} />
  402. {this.getAvatarChooser(true)}
  403. {this.getAvatarChooser(false)}
  404. <PermissionsObserver
  405. webhookDisabled={webhookDisabled}
  406. appPublished={app ? app.status === 'published' : false}
  407. scopes={scopes}
  408. events={events}
  409. newApp={!app}
  410. />
  411. </Fragment>
  412. );
  413. }}
  414. </Observer>
  415. {app && app.status === 'internal' && (
  416. <Panel>
  417. {this.hasTokenAccess ? (
  418. <PanelHeader hasButtons>
  419. {t('Tokens')}
  420. <Button
  421. size="xs"
  422. icon={<IconAdd isCircled />}
  423. onClick={evt => this.onAddToken(evt)}
  424. data-test-id="token-add"
  425. >
  426. {t('New Token')}
  427. </Button>
  428. </PanelHeader>
  429. ) : (
  430. <PanelHeader>{t('Tokens')}</PanelHeader>
  431. )}
  432. <PanelBody>{this.renderTokens()}</PanelBody>
  433. </Panel>
  434. )}
  435. {app && (
  436. <Panel>
  437. <PanelHeader>{t('Credentials')}</PanelHeader>
  438. <PanelBody>
  439. {app.status !== 'internal' && (
  440. <FormField name="clientId" label="Client ID">
  441. {({value, id}) => (
  442. <TextCopyInput id={id}>
  443. {getDynamicText({value, fixed: 'CI_CLIENT_ID'})}
  444. </TextCopyInput>
  445. )}
  446. </FormField>
  447. )}
  448. <FormField name="clientSecret" label="Client Secret">
  449. {({value, id}) =>
  450. value ? (
  451. <Tooltip
  452. disabled={this.showAuthInfo}
  453. position="right"
  454. containerDisplayMode="inline"
  455. title={t(
  456. 'You do not have access to view these credentials because the permissions for this integration exceed those of your role.'
  457. )}
  458. >
  459. <TextCopyInput id={id}>
  460. {getDynamicText({value, fixed: 'CI_CLIENT_SECRET'})}
  461. </TextCopyInput>
  462. </Tooltip>
  463. ) : (
  464. <em>hidden</em>
  465. )
  466. }
  467. </FormField>
  468. </PanelBody>
  469. </Panel>
  470. )}
  471. </Form>
  472. </div>
  473. );
  474. }
  475. }
  476. export default withOrganization(SentryApplicationDetails);
  477. const AvatarPreview = styled('div')`
  478. flex: 1;
  479. display: grid;
  480. grid: 25px 25px / 50px 1fr;
  481. `;
  482. const StyledPreviewAvatar = styled(Avatar)`
  483. grid-area: 1 / 1 / 3 / 2;
  484. justify-self: end;
  485. `;
  486. const AvatarPreviewTitle = styled('span')`
  487. display: block;
  488. grid-area: 1 / 2 / 2 / 3;
  489. padding-left: ${space(2)};
  490. font-weight: bold;
  491. `;
  492. const AvatarPreviewText = styled('span')`
  493. display: block;
  494. grid-area: 2 / 2 / 3 / 3;
  495. padding-left: ${space(2)};
  496. `;