api.tsx 16 KB

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