api.tsx 16 KB

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