sentryApplicationDetails.tsx 17 KB

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