sentryApplicationDetails.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  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. return [
  163. ['app', `/sentry-apps/${appSlug}/`],
  164. ['tokens', `/sentry-apps/${appSlug}/api-tokens/`],
  165. ];
  166. }
  167. return [];
  168. }
  169. getHeaderTitle() {
  170. const {app} = this.state;
  171. const action = app ? 'Edit' : 'Create';
  172. const type = this.isInternal ? 'Internal' : 'Public';
  173. return tct('[action] [type] Integration', {action, type});
  174. }
  175. // Events may come from the API as "issue.created" when we just want "issue" here.
  176. normalize(events) {
  177. if (events.length === 0) {
  178. return events;
  179. }
  180. return events.map(e => e.split('.').shift());
  181. }
  182. handleSubmitSuccess = (data: SentryApp) => {
  183. const {app} = this.state;
  184. const {organization} = this.props;
  185. const type = this.isInternal ? 'internal' : 'public';
  186. const baseUrl = `/settings/${organization.slug}/developer-settings/`;
  187. const url = app ? `${baseUrl}?type=${type}` : `${baseUrl}${data.slug}/`;
  188. if (app) {
  189. addSuccessMessage(t('%s successfully saved.', data.name));
  190. } else {
  191. addSuccessMessage(t('%s successfully created.', data.name));
  192. }
  193. browserHistory.push(normalizeUrl(url));
  194. };
  195. handleSubmitError = err => {
  196. let errorMessage = t('Unknown Error');
  197. if (err.status >= 400 && err.status < 500) {
  198. errorMessage = err?.responseJSON.detail ?? errorMessage;
  199. }
  200. addErrorMessage(errorMessage);
  201. if (this.form.formErrors) {
  202. const firstErrorFieldId = Object.keys(this.form.formErrors)[0];
  203. if (firstErrorFieldId) {
  204. scrollToElement(`#${firstErrorFieldId}`, {
  205. align: 'middle',
  206. offset: 0,
  207. });
  208. }
  209. }
  210. };
  211. get isInternal() {
  212. const {app} = this.state;
  213. if (app) {
  214. // if we are editing an existing app, check the status of the app
  215. return app.status === 'internal';
  216. }
  217. return this.props.route.path === 'new-internal/';
  218. }
  219. get showAuthInfo() {
  220. const {app} = this.state;
  221. return !(app?.clientSecret && app.clientSecret[0] === '*');
  222. }
  223. onAddToken = async (evt: React.MouseEvent): Promise<void> => {
  224. evt.preventDefault();
  225. const {app, newTokens} = this.state;
  226. if (!app) {
  227. return;
  228. }
  229. const api = this.api;
  230. const token = await addSentryAppToken(api, app);
  231. const updatedNewTokens = newTokens.concat(token);
  232. this.setState({newTokens: updatedNewTokens});
  233. };
  234. onRemoveToken = async (token: InternalAppApiToken) => {
  235. const {app, tokens} = this.state;
  236. if (!app) {
  237. return;
  238. }
  239. const api = this.api;
  240. const newTokens = tokens.filter(tok => tok.id !== token.id);
  241. await removeSentryAppToken(api, app, token.id);
  242. this.setState({tokens: newTokens});
  243. };
  244. handleFinishNewToken = (newToken: NewInternalAppApiToken) => {
  245. const {tokens, newTokens} = this.state;
  246. const updatedNewTokens = newTokens.filter(token => token.id !== newToken.id);
  247. const updatedTokens = tokens.concat(newToken as InternalAppApiToken);
  248. this.setState({tokens: updatedTokens, newTokens: updatedNewTokens});
  249. };
  250. renderTokens = () => {
  251. const {tokens, newTokens} = this.state;
  252. if (tokens.length < 1 && newTokens.length < 1) {
  253. return <EmptyMessage description={t('No tokens created yet.')} />;
  254. }
  255. const tokensToDisplay = tokens.map(token => (
  256. <ApiTokenRow
  257. data-test-id="api-token"
  258. key={token.id}
  259. token={token}
  260. onRemove={this.onRemoveToken}
  261. />
  262. ));
  263. tokensToDisplay.push(
  264. ...newTokens.map(newToken => (
  265. <NewTokenHandler
  266. data-test-id="new-api-token"
  267. key={newToken.id}
  268. token={getDynamicText({value: newToken.token, fixed: 'ORG_AUTH_TOKEN'})}
  269. handleGoBack={() => this.handleFinishNewToken(newToken)}
  270. />
  271. ))
  272. );
  273. return tokensToDisplay;
  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. newApp={!app}
  401. />
  402. </Fragment>
  403. );
  404. }}
  405. </Observer>
  406. {app && app.status === 'internal' && (
  407. <Panel>
  408. <PanelHeader hasButtons>
  409. {t('Tokens')}
  410. <Button
  411. size="xs"
  412. icon={<IconAdd isCircled />}
  413. onClick={evt => this.onAddToken(evt)}
  414. data-test-id="token-add"
  415. >
  416. {t('New Token')}
  417. </Button>
  418. </PanelHeader>
  419. <PanelBody>{this.renderTokens()}</PanelBody>
  420. </Panel>
  421. )}
  422. {app && (
  423. <Panel>
  424. <PanelHeader>{t('Credentials')}</PanelHeader>
  425. <PanelBody>
  426. {app.status !== 'internal' && (
  427. <FormField name="clientId" label="Client ID">
  428. {({value, id}) => (
  429. <TextCopyInput id={id}>
  430. {getDynamicText({value, fixed: 'CI_CLIENT_ID'})}
  431. </TextCopyInput>
  432. )}
  433. </FormField>
  434. )}
  435. <FormField name="clientSecret" label="Client Secret">
  436. {({value, id}) =>
  437. value ? (
  438. <Tooltip
  439. disabled={this.showAuthInfo}
  440. position="right"
  441. containerDisplayMode="inline"
  442. title={t(
  443. 'You do not have access to view these credentials because the permissions for this integration exceed those of your role.'
  444. )}
  445. >
  446. <TextCopyInput id={id}>
  447. {getDynamicText({value, fixed: 'CI_CLIENT_SECRET'})}
  448. </TextCopyInput>
  449. </Tooltip>
  450. ) : (
  451. <em>hidden</em>
  452. )
  453. }
  454. </FormField>
  455. </PanelBody>
  456. </Panel>
  457. )}
  458. </Form>
  459. </div>
  460. );
  461. }
  462. }
  463. export default withOrganization(SentryApplicationDetails);
  464. const AvatarPreview = styled('div')`
  465. flex: 1;
  466. display: grid;
  467. grid: 25px 25px / 50px 1fr;
  468. `;
  469. const StyledPreviewAvatar = styled(Avatar)`
  470. grid-area: 1 / 1 / 3 / 2;
  471. justify-self: end;
  472. `;
  473. const AvatarPreviewTitle = styled('span')`
  474. display: block;
  475. grid-area: 1 / 2 / 2 / 3;
  476. padding-left: ${space(2)};
  477. font-weight: bold;
  478. `;
  479. const AvatarPreviewText = styled('span')`
  480. display: block;
  481. grid-area: 2 / 2 / 3 / 3;
  482. padding-left: ${space(2)};
  483. `;