api.tsx 16 KB

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