api.tsx 18 KB

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