api.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. import {browserHistory} from 'react-router';
  2. import {Severity} from '@sentry/react';
  3. import Cookies from 'js-cookie';
  4. import isUndefined from 'lodash/isUndefined';
  5. import * as qs from 'query-string';
  6. import {openSudo, redirectToProject} from 'app/actionCreators/modal';
  7. import {EXPERIMENTAL_SPA} from 'app/constants';
  8. import {
  9. PROJECT_MOVED,
  10. SUDO_REQUIRED,
  11. SUPERUSER_REQUIRED,
  12. } from 'app/constants/apiErrorCodes';
  13. import {metric} from 'app/utils/analytics';
  14. import {run} from 'app/utils/apiSentryClient';
  15. import getCsrfToken from 'app/utils/getCsrfToken';
  16. import {uniqueId} from 'app/utils/guid';
  17. import createRequestError from 'app/utils/requestError/createRequestError';
  18. export class Request {
  19. /**
  20. * Is the request still in flight
  21. */
  22. alive: boolean;
  23. /**
  24. * Promise which will be resolved when the request has completed
  25. */
  26. requestPromise: Promise<Response>;
  27. /**
  28. * AbortController to cancel the in-flight request. This will not be set in
  29. * unsupported browsers.
  30. */
  31. aborter?: AbortController;
  32. constructor(requestPromise: Promise<Response>, aborter?: AbortController) {
  33. this.requestPromise = requestPromise;
  34. this.aborter = aborter;
  35. this.alive = true;
  36. }
  37. cancel() {
  38. this.alive = false;
  39. this.aborter?.abort();
  40. metric('app.api.request-abort', 1);
  41. }
  42. }
  43. export type ResponseMeta<R = any> = {
  44. /**
  45. * The response status code
  46. */
  47. status: Response['status'];
  48. /**
  49. * The response status code text
  50. */
  51. statusText: Response['statusText'];
  52. /**
  53. * The string value of the response
  54. */
  55. responseText: string;
  56. /**
  57. * The response body decoded from json
  58. */
  59. responseJSON: R;
  60. /**
  61. * Get a header value from the response
  62. */
  63. getResponseHeader: (header: string) => string | null;
  64. };
  65. /**
  66. * Check if the requested method does not require CSRF tokens
  67. */
  68. function csrfSafeMethod(method?: string) {
  69. // these HTTP methods do not require CSRF protection
  70. return /^(GET|HEAD|OPTIONS|TRACE)$/.test(method ?? '');
  71. }
  72. // TODO: Need better way of identifying anonymous pages that don't trigger redirect
  73. const ALLOWED_ANON_PAGES = [
  74. /^\/accept\//,
  75. /^\/share\//,
  76. /^\/auth\/login\//,
  77. /^\/join-request\//,
  78. ];
  79. const globalErrorHandlers: ((resp: ResponseMeta) => void)[] = [];
  80. export const initApiClientErrorHandling = () =>
  81. globalErrorHandlers.push((resp: ResponseMeta) => {
  82. const pageAllowsAnon = ALLOWED_ANON_PAGES.find(regex =>
  83. regex.test(window.location.pathname)
  84. );
  85. // Ignore error unless it is a 401
  86. if (!resp || resp.status !== 401 || pageAllowsAnon) {
  87. return;
  88. }
  89. const code = resp?.responseJSON?.detail?.code;
  90. const extra = resp?.responseJSON?.detail?.extra;
  91. // 401s can also mean sudo is required or it's a request that is allowed to fail
  92. // Ignore if these are the cases
  93. if (
  94. [
  95. 'sudo-required',
  96. 'ignore',
  97. '2fa-required',
  98. 'app-connect-authentication-error',
  99. 'itunes-authentication-error',
  100. 'itunes-2fa-required',
  101. ].includes(code)
  102. ) {
  103. return;
  104. }
  105. // If user must login via SSO, redirect to org login page
  106. if (code === 'sso-required') {
  107. window.location.assign(extra.loginUrl);
  108. return;
  109. }
  110. if (code === 'member-disabled-over-limit') {
  111. browserHistory.replace(extra.next);
  112. }
  113. // Otherwise, the user has become unauthenticated. Send them to auth
  114. Cookies.set('session_expired', '1');
  115. if (EXPERIMENTAL_SPA) {
  116. browserHistory.replace('/auth/login/');
  117. } else {
  118. window.location.reload();
  119. }
  120. });
  121. /**
  122. * Construct a full request URL
  123. */
  124. function buildRequestUrl(baseUrl: string, path: string, query: RequestOptions['query']) {
  125. let params: string;
  126. try {
  127. params = qs.stringify(query ?? []);
  128. } catch (err) {
  129. run(Sentry =>
  130. Sentry.withScope(scope => {
  131. scope.setExtra('path', path);
  132. scope.setExtra('query', query);
  133. Sentry.captureException(err);
  134. })
  135. );
  136. throw err;
  137. }
  138. // Append the baseUrl
  139. let fullUrl = path.includes(baseUrl) ? path : baseUrl + path;
  140. // Append query parameters
  141. if (params) {
  142. fullUrl += fullUrl.includes('?') ? `&${params}` : `?${params}`;
  143. }
  144. return fullUrl;
  145. }
  146. /**
  147. * Check if the API response says project has been renamed. If so, redirect
  148. * user to new project slug
  149. */
  150. // TODO(ts): refine this type later
  151. export function hasProjectBeenRenamed(response: ResponseMeta) {
  152. const code = response?.responseJSON?.detail?.code;
  153. // XXX(billy): This actually will never happen because we can't intercept the 302
  154. // jQuery ajax will follow the redirect by default...
  155. //
  156. // TODO(epurkhiser): We use fetch now, is the above comment still true?
  157. if (code !== PROJECT_MOVED) {
  158. return false;
  159. }
  160. const slug = response?.responseJSON?.detail?.extra?.slug;
  161. redirectToProject(slug);
  162. return true;
  163. }
  164. // TODO(ts): move this somewhere
  165. export type APIRequestMethod = 'POST' | 'GET' | 'DELETE' | 'PUT';
  166. type FunctionCallback<Args extends any[] = any[]> = (...args: Args) => void;
  167. export type RequestCallbacks = {
  168. /**
  169. * Callback for the request completing (success or error)
  170. */
  171. complete?: (resp: ResponseMeta, textStatus: string) => void;
  172. /**
  173. * Callback for the request completing successfully
  174. */
  175. success?: (data: any, textStatus?: string, resp?: ResponseMeta) => void;
  176. /**
  177. * Callback for the request failing with an error
  178. */
  179. // TODO(ts): Update this when sentry is mostly migrated to TS
  180. error?: FunctionCallback;
  181. };
  182. export type RequestOptions = RequestCallbacks & {
  183. /**
  184. * The HTTP method to use when making the API request
  185. */
  186. method?: APIRequestMethod;
  187. /**
  188. * Values to attach to the body of the request.
  189. */
  190. data?: any;
  191. /**
  192. * Query parameters to add to the requested URL.
  193. */
  194. query?: Array<any> | object;
  195. /**
  196. * Because of the async nature of API requests, errors will happen outside of
  197. * the stack that initated the request. a preservedError can be passed to
  198. * coalesce the stacks together.
  199. */
  200. preservedError?: Error;
  201. };
  202. type ClientOptions = {
  203. /**
  204. * The base URL path to prepend to API request URIs.
  205. */
  206. baseUrl?: string;
  207. };
  208. type HandleRequestErrorOptions = {
  209. id: string;
  210. path: string;
  211. requestOptions: Readonly<RequestOptions>;
  212. };
  213. /**
  214. * The API client is used to make HTTP requests to Sentry's backend.
  215. *
  216. * This is they preferred way to talk to the backend.
  217. */
  218. export class Client {
  219. baseUrl: string;
  220. activeRequests: Record<string, Request>;
  221. constructor(options: ClientOptions = {}) {
  222. this.baseUrl = options.baseUrl ?? '/api/0';
  223. this.activeRequests = {};
  224. }
  225. wrapCallback<T extends any[]>(
  226. id: string,
  227. func: FunctionCallback<T> | undefined,
  228. cleanup: boolean = false
  229. ) {
  230. return (...args: T) => {
  231. const req = this.activeRequests[id];
  232. if (cleanup === true) {
  233. delete this.activeRequests[id];
  234. }
  235. if (!req?.alive) {
  236. return;
  237. }
  238. // Check if API response is a 302 -- means project slug was renamed and user
  239. // needs to be redirected
  240. // @ts-expect-error
  241. if (hasProjectBeenRenamed(...args)) {
  242. return;
  243. }
  244. if (isUndefined(func)) {
  245. return;
  246. }
  247. // Call success callback
  248. return func.apply(req, args); // eslint-disable-line
  249. };
  250. }
  251. /**
  252. * Attempt to cancel all active fetch requests
  253. */
  254. clear() {
  255. Object.values(this.activeRequests).forEach(r => r.cancel());
  256. }
  257. handleRequestError(
  258. {id, path, requestOptions}: HandleRequestErrorOptions,
  259. response: ResponseMeta,
  260. textStatus: string,
  261. errorThrown: string
  262. ) {
  263. const code = response?.responseJSON?.detail?.code;
  264. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  265. let didSuccessfullyRetry = false;
  266. if (isSudoRequired) {
  267. openSudo({
  268. superuser: code === SUPERUSER_REQUIRED,
  269. sudo: code === SUDO_REQUIRED,
  270. retryRequest: async () => {
  271. try {
  272. const data = await this.requestPromise(path, requestOptions);
  273. requestOptions.success?.(data);
  274. didSuccessfullyRetry = true;
  275. } catch (err) {
  276. requestOptions.error?.(err);
  277. }
  278. },
  279. onClose: () =>
  280. // If modal was closed, then forward the original response
  281. !didSuccessfullyRetry && requestOptions.error?.(response),
  282. });
  283. return;
  284. }
  285. // Call normal error callback
  286. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  287. id,
  288. requestOptions.error
  289. );
  290. errorCb?.(response, textStatus, errorThrown);
  291. }
  292. /**
  293. * Initate a request to the backend API.
  294. *
  295. * Consider using `requestPromise` for the async Promise version of this method.
  296. */
  297. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  298. const method = options.method || (options.data ? 'POST' : 'GET');
  299. let fullUrl = buildRequestUrl(this.baseUrl, path, options.query);
  300. let data = options.data;
  301. if (!isUndefined(data) && method !== 'GET') {
  302. data = JSON.stringify(data);
  303. }
  304. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  305. // object for GET requets. jQuery just sticks it onto the URL as query
  306. // parameters
  307. if (method === 'GET' && data) {
  308. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  309. if (queryString.length > 0) {
  310. fullUrl = fullUrl + (fullUrl.indexOf('?') !== -1 ? '&' : '?') + queryString;
  311. }
  312. }
  313. const id = uniqueId();
  314. const startMarker = `api-request-start-${id}`;
  315. metric.mark({name: startMarker});
  316. const errorObject = new Error();
  317. /**
  318. * Called when the request completes with a 2xx status
  319. */
  320. const successHandler = (
  321. resp: ResponseMeta,
  322. textStatus: string,
  323. responseData: any
  324. ) => {
  325. metric.measure({
  326. name: 'app.api.request-success',
  327. start: startMarker,
  328. data: {status: resp?.status},
  329. });
  330. if (!isUndefined(options.success)) {
  331. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  332. responseData,
  333. textStatus,
  334. resp
  335. );
  336. }
  337. };
  338. /**
  339. * Called when the request is non-2xx
  340. */
  341. const errorHandler = (
  342. resp: ResponseMeta,
  343. textStatus: string,
  344. errorThrown: string
  345. ) => {
  346. metric.measure({
  347. name: 'app.api.request-error',
  348. start: startMarker,
  349. data: {status: resp?.status},
  350. });
  351. if (
  352. resp &&
  353. resp.status !== 0 &&
  354. resp.status !== 404 &&
  355. errorThrown !== 'Request was aborted'
  356. ) {
  357. run(Sentry =>
  358. Sentry.withScope(scope => {
  359. // `requestPromise` can pass its error object
  360. const preservedError = options.preservedError ?? errorObject;
  361. const errorObjectToUse = createRequestError(
  362. resp,
  363. preservedError.stack,
  364. method,
  365. path
  366. );
  367. errorObjectToUse.removeFrames(3);
  368. // Setting this to warning because we are going to capture all failed requests
  369. scope.setLevel(Severity.Warning);
  370. scope.setTag('http.statusCode', String(resp.status));
  371. scope.setTag('error.reason', errorThrown);
  372. Sentry.captureException(errorObjectToUse);
  373. })
  374. );
  375. }
  376. this.handleRequestError(
  377. {id, path, requestOptions: options},
  378. resp,
  379. textStatus,
  380. errorThrown
  381. );
  382. };
  383. /**
  384. * Called when the request completes
  385. */
  386. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  387. this.wrapCallback<[ResponseMeta, string]>(
  388. id,
  389. options.complete,
  390. true
  391. )(resp, textStatus);
  392. // AbortController is optional, though most browser should support it.
  393. const aborter =
  394. typeof AbortController !== 'undefined' ? new AbortController() : undefined;
  395. // GET requests may not have a body
  396. const body = method !== 'GET' ? data : undefined;
  397. const headers = new Headers({
  398. Accept: 'application/json; charset=utf-8',
  399. 'Content-Type': 'application/json',
  400. });
  401. // Do not set the X-CSRFToken header when making a request outside of the
  402. // current domain
  403. const absoluteUrl = new URL(fullUrl, window.location.origin);
  404. const isSameOrigin = window.location.origin === absoluteUrl.origin;
  405. if (!csrfSafeMethod(method) && isSameOrigin) {
  406. headers.set('X-CSRFToken', getCsrfToken());
  407. }
  408. const fetchRequest = fetch(fullUrl, {
  409. method,
  410. body,
  411. headers,
  412. credentials: 'same-origin',
  413. signal: aborter?.signal,
  414. });
  415. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  416. // compatibility layer which mimics that of the jquery response objects.
  417. fetchRequest
  418. .then(async response => {
  419. // The Response's body can only be resolved/used at most once.
  420. // So we clone the response so we can resolve the body content as text content.
  421. // Response objects need to be cloned before its body can be used.
  422. const responseClone = response.clone();
  423. let responseJSON: any;
  424. let responseText: any;
  425. const {status, statusText} = response;
  426. let {ok} = response;
  427. let errorReason = 'Request not OK'; // the default error reason
  428. // Try to get text out of the response no matter the status
  429. try {
  430. responseText = await response.text();
  431. } catch (error) {
  432. ok = false;
  433. if (error.name === 'AbortError') {
  434. errorReason = 'Request was aborted';
  435. } else {
  436. errorReason = error.toString();
  437. }
  438. }
  439. const responseContentType = response.headers.get('content-type');
  440. const isResponseJSON = responseContentType?.includes('json');
  441. const isStatus3XX = status >= 300 && status < 400;
  442. if (status !== 204 && !isStatus3XX) {
  443. try {
  444. responseJSON = await responseClone.json();
  445. } catch (error) {
  446. if (error.name === 'AbortError') {
  447. ok = false;
  448. errorReason = 'Request was aborted';
  449. } else if (isResponseJSON && error instanceof SyntaxError) {
  450. // If the MIME type is `application/json` but decoding failed,
  451. // this should be an error.
  452. ok = false;
  453. errorReason = 'JSON parse error';
  454. }
  455. }
  456. }
  457. const responseMeta: ResponseMeta = {
  458. status,
  459. statusText,
  460. responseJSON,
  461. responseText,
  462. getResponseHeader: (header: string) => response.headers.get(header),
  463. };
  464. // Respect the response content-type header
  465. const responseData = isResponseJSON ? responseJSON : responseText;
  466. if (ok) {
  467. successHandler(responseMeta, statusText, responseData);
  468. } else {
  469. globalErrorHandlers.forEach(handler => handler(responseMeta));
  470. errorHandler(responseMeta, statusText, errorReason);
  471. }
  472. completeHandler(responseMeta, statusText);
  473. })
  474. .catch(err => {
  475. // Aborts are expected
  476. if (err?.name === 'AbortError') {
  477. return;
  478. }
  479. // The request failed for other reason
  480. run(Sentry =>
  481. Sentry.withScope(scope => {
  482. scope.setLevel(Severity.Warning);
  483. Sentry.captureException(err);
  484. })
  485. );
  486. });
  487. const request = new Request(fetchRequest, aborter);
  488. this.activeRequests[id] = request;
  489. return request;
  490. }
  491. requestPromise<IncludeAllArgsType extends boolean>(
  492. path: string,
  493. {
  494. includeAllArgs,
  495. ...options
  496. }: {includeAllArgs?: IncludeAllArgsType} & Readonly<RequestOptions> = {}
  497. ): Promise<
  498. IncludeAllArgsType extends true
  499. ? [any, string | undefined, ResponseMeta | undefined]
  500. : any
  501. > {
  502. // Create an error object here before we make any async calls so that we
  503. // have a helpful stack trace if it errors
  504. //
  505. // This *should* get logged to Sentry only if the promise rejection is not handled
  506. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  507. // or handle with a user friendly error message
  508. const preservedError = new Error();
  509. return new Promise((resolve, reject) =>
  510. this.request(path, {
  511. ...options,
  512. preservedError,
  513. success: (data, textStatus, resp) => {
  514. if (includeAllArgs) {
  515. resolve([data, textStatus, resp] as any);
  516. } else {
  517. resolve(data);
  518. }
  519. },
  520. error: (resp: ResponseMeta) => {
  521. const errorObjectToUse = createRequestError(
  522. resp,
  523. preservedError.stack,
  524. options.method,
  525. path
  526. );
  527. errorObjectToUse.removeFrames(2);
  528. // Although `this.request` logs all error responses, this error object can
  529. // potentially be logged by Sentry's unhandled rejection handler
  530. reject(errorObjectToUse);
  531. },
  532. })
  533. );
  534. }
  535. }