api.tsx 16 KB

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