api.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. import {browserHistory} from 'react-router';
  2. import * as Sentry from '@sentry/react';
  3. import Cookies from 'js-cookie';
  4. import * as qs from 'query-string';
  5. import {openSudo, redirectToProject} from 'sentry/actionCreators/modal';
  6. import {EXPERIMENTAL_SPA} from 'sentry/constants';
  7. import {
  8. PROJECT_MOVED,
  9. SUDO_REQUIRED,
  10. SUPERUSER_REQUIRED,
  11. } from 'sentry/constants/apiErrorCodes';
  12. import controlsilopatterns from 'sentry/data/controlsiloUrlPatterns';
  13. import {metric} from 'sentry/utils/analytics';
  14. import getCsrfToken from 'sentry/utils/getCsrfToken';
  15. import {uniqueId} from 'sentry/utils/guid';
  16. import RequestError from 'sentry/utils/requestError/requestError';
  17. import {sanitizePath} from 'sentry/utils/requestError/sanitizePath';
  18. import ConfigStore from './stores/configStore';
  19. import OrganizationStore from './stores/organizationStore';
  20. export class Request {
  21. /**
  22. * Is the request still in flight
  23. */
  24. alive: boolean;
  25. /**
  26. * Promise which will be resolved when the request has completed
  27. */
  28. requestPromise: Promise<Response>;
  29. /**
  30. * AbortController to cancel the in-flight request. This will not be set in
  31. * unsupported browsers.
  32. */
  33. aborter?: AbortController;
  34. constructor(requestPromise: Promise<Response>, aborter?: AbortController) {
  35. this.requestPromise = requestPromise;
  36. this.aborter = aborter;
  37. this.alive = true;
  38. }
  39. cancel() {
  40. this.alive = false;
  41. this.aborter?.abort();
  42. metric('app.api.request-abort', 1);
  43. }
  44. }
  45. export type ApiResult<Data = any> = [
  46. data: Data,
  47. statusText: string | undefined,
  48. resp: ResponseMeta | undefined,
  49. ];
  50. export type ResponseMeta<R = any> = {
  51. /**
  52. * Get a header value from the response
  53. */
  54. getResponseHeader: (header: string) => string | null;
  55. /**
  56. * The response body decoded from json
  57. */
  58. responseJSON: R;
  59. /**
  60. * The string value of the response
  61. */
  62. responseText: string;
  63. /**
  64. * The response status code
  65. */
  66. status: Response['status'];
  67. /**
  68. * The response status code text
  69. */
  70. statusText: Response['statusText'];
  71. };
  72. /**
  73. * Check if the requested method does not require CSRF tokens
  74. */
  75. function csrfSafeMethod(method?: string): boolean {
  76. // these HTTP methods do not require CSRF protection
  77. return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method ?? '');
  78. }
  79. /**
  80. * Check if we a request is going to the same or similar origin.
  81. * similar origins are those that share an ancestor. Example `sentry.sentry.io` and `us.sentry.io`
  82. * are similar origins, but sentry.sentry.io and sentry.example.io are not.
  83. */
  84. export function isSimilarOrigin(target: string, origin: string): boolean {
  85. const targetUrl = new URL(target, origin);
  86. const originUrl = new URL(origin);
  87. if (originUrl.hostname.endsWith(targetUrl.hostname)) {
  88. return true;
  89. }
  90. // Check if the target and origin are on sibiling subdomains.
  91. const targetHost = targetUrl.hostname.split('.');
  92. const originHost = originUrl.hostname.split('.');
  93. // Remove the subdomains. If don't have at least 2 segments we aren't subdomains.
  94. targetHost.shift();
  95. originHost.shift();
  96. if (targetHost.length < 2 || originHost.length < 2) {
  97. return false;
  98. }
  99. return targetHost.join('.') === originHost.join('.');
  100. }
  101. // TODO: Need better way of identifying anonymous pages that don't trigger redirect
  102. const ALLOWED_ANON_PAGES = [
  103. /^\/accept\//,
  104. /^\/share\//,
  105. /^\/auth\/login\//,
  106. /^\/join-request\//,
  107. ];
  108. /**
  109. * Return true if we should skip calling the normal error handler
  110. */
  111. const globalErrorHandlers: ((resp: ResponseMeta) => boolean)[] = [];
  112. export const initApiClientErrorHandling = () =>
  113. globalErrorHandlers.push((resp: ResponseMeta) => {
  114. const pageAllowsAnon = ALLOWED_ANON_PAGES.find(regex =>
  115. regex.test(window.location.pathname)
  116. );
  117. // Ignore error unless it is a 401
  118. if (!resp || resp.status !== 401 || pageAllowsAnon) {
  119. return false;
  120. }
  121. const code = resp?.responseJSON?.detail?.code;
  122. const extra = resp?.responseJSON?.detail?.extra;
  123. // 401s can also mean sudo is required or it's a request that is allowed to fail
  124. // Ignore if these are the cases
  125. if (
  126. [
  127. 'sudo-required',
  128. 'ignore',
  129. '2fa-required',
  130. 'app-connect-authentication-error',
  131. ].includes(code)
  132. ) {
  133. return false;
  134. }
  135. // If user must login via SSO, redirect to org login page
  136. if (code === 'sso-required') {
  137. window.location.assign(extra.loginUrl);
  138. return true;
  139. }
  140. if (code === 'member-disabled-over-limit') {
  141. browserHistory.replace(extra.next);
  142. return true;
  143. }
  144. // Otherwise, the user has become unauthenticated. Send them to auth
  145. Cookies.set('session_expired', '1');
  146. if (EXPERIMENTAL_SPA) {
  147. browserHistory.replace('/auth/login/');
  148. } else {
  149. window.location.reload();
  150. }
  151. return true;
  152. });
  153. /**
  154. * Construct a full request URL
  155. */
  156. function buildRequestUrl(baseUrl: string, path: string, options: RequestOptions) {
  157. let params: string;
  158. try {
  159. params = qs.stringify(options.query ?? []);
  160. } catch (err) {
  161. Sentry.withScope(scope => {
  162. scope.setExtra('path', path);
  163. scope.setExtra('query', options.query);
  164. Sentry.captureException(err);
  165. });
  166. throw err;
  167. }
  168. // Append the baseUrl if required
  169. let fullUrl = path.includes(baseUrl) ? path : baseUrl + path;
  170. // Apply path and domain transforms for hybrid-cloud
  171. fullUrl = resolveHostname(fullUrl, options.host);
  172. // Append query parameters
  173. if (params) {
  174. fullUrl += fullUrl.includes('?') ? `&${params}` : `?${params}`;
  175. }
  176. return fullUrl;
  177. }
  178. /**
  179. * Check if the API response says project has been renamed. If so, redirect
  180. * user to new project slug
  181. */
  182. // TODO(ts): refine this type later
  183. export function hasProjectBeenRenamed(response: ResponseMeta) {
  184. const code = response?.responseJSON?.detail?.code;
  185. // XXX(billy): This actually will never happen because we can't intercept the 302
  186. // jQuery ajax will follow the redirect by default...
  187. //
  188. // TODO(epurkhiser): We use fetch now, is the above comment still true?
  189. if (code !== PROJECT_MOVED) {
  190. return false;
  191. }
  192. const slug = response?.responseJSON?.detail?.extra?.slug;
  193. redirectToProject(slug);
  194. return true;
  195. }
  196. // TODO(ts): move this somewhere
  197. export type APIRequestMethod = 'POST' | 'GET' | 'DELETE' | 'PUT';
  198. type FunctionCallback<Args extends any[] = any[]> = (...args: Args) => void;
  199. export type RequestCallbacks = {
  200. /**
  201. * Callback for the request completing (success or error)
  202. */
  203. complete?: (resp: ResponseMeta, textStatus: string) => void;
  204. /**
  205. * Callback for the request failing with an error
  206. */
  207. // TODO(ts): Update this when sentry is mostly migrated to TS
  208. error?: FunctionCallback;
  209. /**
  210. * Callback for the request completing successfully
  211. */
  212. success?: (data: any, textStatus?: string, resp?: ResponseMeta) => void;
  213. };
  214. export type RequestOptions = RequestCallbacks & {
  215. /**
  216. * Values to attach to the body of the request.
  217. */
  218. data?: any;
  219. /**
  220. * Headers add to the request.
  221. */
  222. headers?: Record<string, string>;
  223. /**
  224. * The host the request should be made to.
  225. */
  226. host?: string;
  227. /**
  228. * The HTTP method to use when making the API request
  229. */
  230. method?: APIRequestMethod;
  231. /**
  232. * Because of the async nature of API requests, errors will happen outside of
  233. * the stack that initated the request. a preservedError can be passed to
  234. * coalesce the stacks together.
  235. */
  236. preservedError?: Error;
  237. /**
  238. * Query parameters to add to the requested URL.
  239. */
  240. query?: Record<string, any>;
  241. };
  242. type ClientOptions = {
  243. /**
  244. * The base URL path to prepend to API request URIs.
  245. */
  246. baseUrl?: string;
  247. /**
  248. * Credentials policy to apply to each request
  249. */
  250. credentials?: RequestCredentials;
  251. /**
  252. * Base set of headers to apply to each request
  253. */
  254. headers?: HeadersInit;
  255. };
  256. type HandleRequestErrorOptions = {
  257. id: string;
  258. path: string;
  259. requestOptions: Readonly<RequestOptions>;
  260. };
  261. /**
  262. * The API client is used to make HTTP requests to Sentry's backend.
  263. *
  264. * This is they preferred way to talk to the backend.
  265. */
  266. export class Client {
  267. baseUrl: string;
  268. activeRequests: Record<string, Request>;
  269. headers: HeadersInit;
  270. credentials?: RequestCredentials;
  271. static JSON_HEADERS = {
  272. Accept: 'application/json; charset=utf-8',
  273. 'Content-Type': 'application/json',
  274. };
  275. constructor(options: ClientOptions = {}) {
  276. this.baseUrl = options.baseUrl ?? '/api/0';
  277. this.headers = options.headers ?? Client.JSON_HEADERS;
  278. this.activeRequests = {};
  279. this.credentials = options.credentials ?? 'include';
  280. }
  281. wrapCallback<T extends any[]>(
  282. id: string,
  283. func: FunctionCallback<T> | undefined,
  284. cleanup: boolean = false
  285. ) {
  286. return (...args: T) => {
  287. const req = this.activeRequests[id];
  288. if (cleanup === true) {
  289. delete this.activeRequests[id];
  290. }
  291. if (!req?.alive) {
  292. return undefined;
  293. }
  294. // Check if API response is a 302 -- means project slug was renamed and user
  295. // needs to be redirected
  296. // @ts-expect-error
  297. if (hasProjectBeenRenamed(...args)) {
  298. return undefined;
  299. }
  300. // Call success callback
  301. return func?.apply(req, args);
  302. };
  303. }
  304. /**
  305. * Attempt to cancel all active fetch requests
  306. */
  307. clear() {
  308. Object.values(this.activeRequests).forEach(r => r.cancel());
  309. }
  310. handleRequestError(
  311. {id, path, requestOptions}: HandleRequestErrorOptions,
  312. response: ResponseMeta,
  313. textStatus: string,
  314. errorThrown: string
  315. ) {
  316. const code = response?.responseJSON?.detail?.code;
  317. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  318. let didSuccessfullyRetry = false;
  319. if (isSudoRequired) {
  320. openSudo({
  321. isSuperuser: code === SUPERUSER_REQUIRED,
  322. sudo: code === SUDO_REQUIRED,
  323. retryRequest: async () => {
  324. try {
  325. const data = await this.requestPromise(path, requestOptions);
  326. requestOptions.success?.(data);
  327. didSuccessfullyRetry = true;
  328. } catch (err) {
  329. requestOptions.error?.(err);
  330. }
  331. },
  332. onClose: () =>
  333. // If modal was closed, then forward the original response
  334. !didSuccessfullyRetry && requestOptions.error?.(response),
  335. });
  336. return;
  337. }
  338. // Call normal error callback
  339. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  340. id,
  341. requestOptions.error
  342. );
  343. errorCb?.(response, textStatus, errorThrown);
  344. }
  345. /**
  346. * Initate a request to the backend API.
  347. *
  348. * Consider using `requestPromise` for the async Promise version of this method.
  349. */
  350. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  351. const method = options.method || (options.data ? 'POST' : 'GET');
  352. let fullUrl = buildRequestUrl(this.baseUrl, path, options);
  353. let data = options.data;
  354. if (data !== undefined && method !== 'GET') {
  355. data = JSON.stringify(data);
  356. }
  357. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  358. // object for GET requets. jQuery just sticks it onto the URL as query
  359. // parameters
  360. if (method === 'GET' && data) {
  361. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  362. if (queryString.length > 0) {
  363. fullUrl = fullUrl + (fullUrl.includes('?') ? '&' : '?') + queryString;
  364. }
  365. }
  366. const id = uniqueId();
  367. const startMarker = `api-request-start-${id}`;
  368. metric.mark({name: startMarker});
  369. /**
  370. * Called when the request completes with a 2xx status
  371. */
  372. const successHandler = (
  373. resp: ResponseMeta,
  374. textStatus: string,
  375. responseData: any
  376. ) => {
  377. metric.measure({
  378. name: 'app.api.request-success',
  379. start: startMarker,
  380. data: {status: resp?.status},
  381. });
  382. if (options.success !== undefined) {
  383. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  384. responseData,
  385. textStatus,
  386. resp
  387. );
  388. }
  389. };
  390. /**
  391. * Called when the request is non-2xx
  392. */
  393. const errorHandler = (
  394. resp: ResponseMeta,
  395. textStatus: string,
  396. errorThrown: string
  397. ) => {
  398. metric.measure({
  399. name: 'app.api.request-error',
  400. start: startMarker,
  401. data: {status: resp?.status},
  402. });
  403. this.handleRequestError(
  404. {id, path, requestOptions: options},
  405. resp,
  406. textStatus,
  407. errorThrown
  408. );
  409. };
  410. /**
  411. * Called when the request completes
  412. */
  413. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  414. this.wrapCallback<[ResponseMeta, string]>(
  415. id,
  416. options.complete,
  417. true
  418. )(resp, textStatus);
  419. // AbortController is optional, though most browser should support it.
  420. const aborter =
  421. typeof AbortController !== 'undefined' ? new AbortController() : undefined;
  422. // GET requests may not have a body
  423. const body = method !== 'GET' ? data : undefined;
  424. const headers = new Headers(this.headers);
  425. // Do not set the X-CSRFToken header when making a request outside of the
  426. // current domain. Because we use subdomains we loosely compare origins
  427. if (!csrfSafeMethod(method) && isSimilarOrigin(fullUrl, window.location.origin)) {
  428. headers.set('X-CSRFToken', getCsrfToken());
  429. }
  430. const fetchRequest = fetch(fullUrl, {
  431. method,
  432. body,
  433. headers,
  434. credentials: this.credentials,
  435. signal: aborter?.signal,
  436. });
  437. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  438. // compatibility layer which mimics that of the jquery response objects.
  439. fetchRequest
  440. .then(
  441. async response => {
  442. // The Response's body can only be resolved/used at most once.
  443. // So we clone the response so we can resolve the body content as text content.
  444. // Response objects need to be cloned before its body can be used.
  445. let responseJSON: any;
  446. let responseText: any;
  447. const {status, statusText} = response;
  448. let {ok} = response;
  449. let errorReason = 'Request not OK'; // the default error reason
  450. let twoHundredErrorReason;
  451. // Try to get text out of the response no matter the status
  452. try {
  453. responseText = await response.text();
  454. } catch (error) {
  455. twoHundredErrorReason = 'Failed awaiting response.text()';
  456. ok = false;
  457. if (error.name === 'AbortError') {
  458. errorReason = 'Request was aborted';
  459. } else {
  460. errorReason = error.toString();
  461. }
  462. }
  463. const responseContentType = response.headers.get('content-type');
  464. const isResponseJSON = responseContentType?.includes('json');
  465. const isStatus3XX = status >= 300 && status < 400;
  466. if (status !== 204 && !isStatus3XX) {
  467. try {
  468. responseJSON = JSON.parse(responseText);
  469. } catch (error) {
  470. twoHundredErrorReason = 'Failed trying to parse responseText';
  471. if (error.name === 'AbortError') {
  472. ok = false;
  473. errorReason = 'Request was aborted';
  474. } else if (isResponseJSON && error instanceof SyntaxError) {
  475. // If the MIME type is `application/json` but decoding failed,
  476. // this should be an error.
  477. ok = false;
  478. errorReason = 'JSON parse error';
  479. }
  480. }
  481. }
  482. const responseMeta: ResponseMeta = {
  483. status,
  484. statusText,
  485. responseJSON,
  486. responseText,
  487. getResponseHeader: (header: string) => response.headers.get(header),
  488. };
  489. // Respect the response content-type header
  490. const responseData = isResponseJSON ? responseJSON : responseText;
  491. if (ok) {
  492. successHandler(responseMeta, statusText, responseData);
  493. } else {
  494. // There's no reason we should be here with a 200 response, but we get
  495. // tons of events from this codepath with a 200 status nonetheless.
  496. // Until we know why, let's do what is essentially some very fancy print debugging.
  497. if (status === 200 && responseText) {
  498. const parameterizedPath = sanitizePath(path);
  499. const message = '200 treated as error';
  500. const scope = new Sentry.Scope();
  501. scope.setTags({endpoint: `${method} ${parameterizedPath}`, errorReason});
  502. scope.setExtras({
  503. twoHundredErrorReason,
  504. responseJSON,
  505. responseText,
  506. responseContentType,
  507. errorReason,
  508. });
  509. // Make sure all of these errors group, so we don't produce a bunch of noise
  510. scope.setFingerprint([message]);
  511. Sentry.captureException(
  512. new Error(`${message}: ${method} ${parameterizedPath}`),
  513. scope
  514. );
  515. }
  516. const shouldSkipErrorHandler =
  517. globalErrorHandlers.map(handler => handler(responseMeta)).filter(Boolean)
  518. .length > 0;
  519. if (!shouldSkipErrorHandler) {
  520. errorHandler(responseMeta, statusText, errorReason);
  521. }
  522. }
  523. completeHandler(responseMeta, statusText);
  524. },
  525. () => {
  526. // Ignore failed fetch calls or errors in the fetch request itself (e.g. cancelled requests)
  527. // Not related to errors in responses
  528. }
  529. )
  530. .catch(error => {
  531. // eslint-disable-next-line no-console
  532. console.error(error);
  533. Sentry.captureException(error);
  534. });
  535. const request = new Request(fetchRequest, aborter);
  536. this.activeRequests[id] = request;
  537. return request;
  538. }
  539. requestPromise<IncludeAllArgsType extends boolean>(
  540. path: string,
  541. {
  542. includeAllArgs,
  543. ...options
  544. }: {includeAllArgs?: IncludeAllArgsType} & Readonly<RequestOptions> = {}
  545. ): Promise<IncludeAllArgsType extends true ? ApiResult : any> {
  546. // Create an error object here before we make any async calls so that we
  547. // have a helpful stack trace if it errors
  548. //
  549. // This *should* get logged to Sentry only if the promise rejection is not handled
  550. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  551. // or handle with a user friendly error message
  552. const preservedError = new Error('API Request Error');
  553. return new Promise((resolve, reject) =>
  554. this.request(path, {
  555. ...options,
  556. preservedError,
  557. success: (data, textStatus, resp) => {
  558. if (includeAllArgs) {
  559. resolve([data, textStatus, resp] as any);
  560. } else {
  561. resolve(data);
  562. }
  563. },
  564. error: (resp: ResponseMeta) => {
  565. const errorObjectToUse = new RequestError(
  566. options.method,
  567. path,
  568. preservedError,
  569. resp
  570. );
  571. // Although `this.request` logs all error responses, this error object can
  572. // potentially be logged by Sentry's unhandled rejection handler
  573. reject(errorObjectToUse);
  574. },
  575. })
  576. );
  577. }
  578. }
  579. export function resolveHostname(path: string, hostname?: string): string {
  580. const storeState = OrganizationStore.get();
  581. const configLinks = ConfigStore.get('links');
  582. hostname = hostname ?? '';
  583. if (!hostname && storeState.organization?.features.includes('frontend-domainsplit')) {
  584. const isControlSilo = detectControlSiloPath(path);
  585. if (!isControlSilo && configLinks.regionUrl) {
  586. hostname = configLinks.regionUrl;
  587. }
  588. if (isControlSilo && configLinks.sentryUrl) {
  589. hostname = configLinks.sentryUrl;
  590. }
  591. }
  592. // If we're making a request to the applications' root
  593. // domain, we can drop the domain as webpack devserver will add one.
  594. // TODO(hybridcloud) This can likely be removed when sentry.types.region.Region.to_url()
  595. // loses the monolith mode condition.
  596. if (window.__SENTRY_DEV_UI && hostname === configLinks.sentryUrl) {
  597. hostname = '';
  598. }
  599. // When running as yarn dev-ui we can't spread requests across domains because
  600. // of CORS. Instead we extract the subdomain from the hostname
  601. // and prepend the URL with `/region/$name` so that webpack-devserver proxy
  602. // can route requests to the regions.
  603. if (hostname && window.__SENTRY_DEV_UI) {
  604. const domainpattern = /https?\:\/\/([^.]*)\.sentry\.io/;
  605. const domainmatch = hostname.match(domainpattern);
  606. if (domainmatch) {
  607. hostname = '';
  608. path = `/region/${domainmatch[1]}${path}`;
  609. }
  610. }
  611. if (hostname) {
  612. path = `${hostname}${path}`;
  613. }
  614. return path;
  615. }
  616. function detectControlSiloPath(path: string): boolean {
  617. path = path.startsWith('/') ? path.substring(1) : path;
  618. for (const pattern of controlsilopatterns) {
  619. if (pattern.test(path)) {
  620. return true;
  621. }
  622. }
  623. return false;
  624. }