sentryApplicationDetails.tsx 16 KB

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