api.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. 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 ApiResult<Data = any> = [
  42. data: Data,
  43. statusText: string | undefined,
  44. resp: ResponseMeta | undefined
  45. ];
  46. export type ResponseMeta<R = any> = {
  47. /**
  48. * Get a header value from the response
  49. */
  50. getResponseHeader: (header: string) => string | null;
  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. * Headers add to the request.
  193. */
  194. headers?: Record<string, string>;
  195. /**
  196. * The HTTP method to use when making the API request
  197. */
  198. method?: APIRequestMethod;
  199. /**
  200. * Because of the async nature of API requests, errors will happen outside of
  201. * the stack that initated the request. a preservedError can be passed to
  202. * coalesce the stacks together.
  203. */
  204. preservedError?: Error;
  205. /**
  206. * Query parameters to add to the requested URL.
  207. */
  208. query?: Record<string, any>;
  209. };
  210. type ClientOptions = {
  211. /**
  212. * The base URL path to prepend to API request URIs.
  213. */
  214. baseUrl?: string;
  215. };
  216. type HandleRequestErrorOptions = {
  217. id: string;
  218. path: string;
  219. requestOptions: Readonly<RequestOptions>;
  220. };
  221. /**
  222. * The API client is used to make HTTP requests to Sentry's backend.
  223. *
  224. * This is they preferred way to talk to the backend.
  225. */
  226. export class Client {
  227. baseUrl: string;
  228. activeRequests: Record<string, Request>;
  229. constructor(options: ClientOptions = {}) {
  230. this.baseUrl = options.baseUrl ?? '/api/0';
  231. this.activeRequests = {};
  232. }
  233. wrapCallback<T extends any[]>(
  234. id: string,
  235. func: FunctionCallback<T> | undefined,
  236. cleanup: boolean = false
  237. ) {
  238. return (...args: T) => {
  239. const req = this.activeRequests[id];
  240. if (cleanup === true) {
  241. delete this.activeRequests[id];
  242. }
  243. if (!req?.alive) {
  244. return undefined;
  245. }
  246. // Check if API response is a 302 -- means project slug was renamed and user
  247. // needs to be redirected
  248. // @ts-expect-error
  249. if (hasProjectBeenRenamed(...args)) {
  250. return undefined;
  251. }
  252. // Call success callback
  253. return func?.apply(req, args);
  254. };
  255. }
  256. /**
  257. * Attempt to cancel all active fetch requests
  258. */
  259. clear() {
  260. Object.values(this.activeRequests).forEach(r => r.cancel());
  261. }
  262. handleRequestError(
  263. {id, path, requestOptions}: HandleRequestErrorOptions,
  264. response: ResponseMeta,
  265. textStatus: string,
  266. errorThrown: string
  267. ) {
  268. const code = response?.responseJSON?.detail?.code;
  269. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  270. let didSuccessfullyRetry = false;
  271. if (isSudoRequired) {
  272. openSudo({
  273. isSuperuser: code === SUPERUSER_REQUIRED,
  274. sudo: code === SUDO_REQUIRED,
  275. retryRequest: async () => {
  276. try {
  277. const data = await this.requestPromise(path, requestOptions);
  278. requestOptions.success?.(data);
  279. didSuccessfullyRetry = true;
  280. } catch (err) {
  281. requestOptions.error?.(err);
  282. }
  283. },
  284. onClose: () =>
  285. // If modal was closed, then forward the original response
  286. !didSuccessfullyRetry && requestOptions.error?.(response),
  287. });
  288. return;
  289. }
  290. // Call normal error callback
  291. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  292. id,
  293. requestOptions.error
  294. );
  295. errorCb?.(response, textStatus, errorThrown);
  296. }
  297. /**
  298. * Initate a request to the backend API.
  299. *
  300. * Consider using `requestPromise` for the async Promise version of this method.
  301. */
  302. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  303. const method = options.method || (options.data ? 'POST' : 'GET');
  304. let fullUrl = buildRequestUrl(this.baseUrl, path, options.query);
  305. let data = options.data;
  306. if (data !== undefined && method !== 'GET') {
  307. data = JSON.stringify(data);
  308. }
  309. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  310. // object for GET requets. jQuery just sticks it onto the URL as query
  311. // parameters
  312. if (method === 'GET' && data) {
  313. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  314. if (queryString.length > 0) {
  315. fullUrl = fullUrl + (fullUrl.indexOf('?') !== -1 ? '&' : '?') + queryString;
  316. }
  317. }
  318. const id = uniqueId();
  319. const startMarker = `api-request-start-${id}`;
  320. metric.mark({name: startMarker});
  321. /**
  322. * Called when the request completes with a 2xx status
  323. */
  324. const successHandler = (
  325. resp: ResponseMeta,
  326. textStatus: string,
  327. responseData: any
  328. ) => {
  329. metric.measure({
  330. name: 'app.api.request-success',
  331. start: startMarker,
  332. data: {status: resp?.status},
  333. });
  334. if (options.success !== undefined) {
  335. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  336. responseData,
  337. textStatus,
  338. resp
  339. );
  340. }
  341. };
  342. /**
  343. * Called when the request is non-2xx
  344. */
  345. const errorHandler = (
  346. resp: ResponseMeta,
  347. textStatus: string,
  348. errorThrown: string
  349. ) => {
  350. metric.measure({
  351. name: 'app.api.request-error',
  352. start: startMarker,
  353. data: {status: resp?.status},
  354. });
  355. this.handleRequestError(
  356. {id, path, requestOptions: options},
  357. resp,
  358. textStatus,
  359. errorThrown
  360. );
  361. };
  362. /**
  363. * Called when the request completes
  364. */
  365. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  366. this.wrapCallback<[ResponseMeta, string]>(
  367. id,
  368. options.complete,
  369. true
  370. )(resp, textStatus);
  371. // AbortController is optional, though most browser should support it.
  372. const aborter =
  373. typeof AbortController !== 'undefined' ? new AbortController() : undefined;
  374. // GET requests may not have a body
  375. const body = method !== 'GET' ? data : undefined;
  376. const headers = new Headers({
  377. Accept: 'application/json; charset=utf-8',
  378. 'Content-Type': 'application/json',
  379. ...options.headers,
  380. });
  381. // Do not set the X-CSRFToken header when making a request outside of the
  382. // current domain
  383. const absoluteUrl = new URL(fullUrl, window.location.origin);
  384. const isSameOrigin = window.location.origin === absoluteUrl.origin;
  385. if (!csrfSafeMethod(method) && isSameOrigin) {
  386. headers.set('X-CSRFToken', getCsrfToken());
  387. }
  388. const fetchRequest = fetch(fullUrl, {
  389. method,
  390. body,
  391. headers,
  392. credentials: 'include',
  393. signal: aborter?.signal,
  394. });
  395. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  396. // compatibility layer which mimics that of the jquery response objects.
  397. fetchRequest
  398. .then(async response => {
  399. // The Response's body can only be resolved/used at most once.
  400. // So we clone the response so we can resolve the body content as text content.
  401. // Response objects need to be cloned before its body can be used.
  402. let responseJSON: any;
  403. let responseText: any;
  404. const {status, statusText} = response;
  405. let {ok} = response;
  406. let errorReason = 'Request not OK'; // the default error reason
  407. let twoHundredErrorReason;
  408. // Try to get text out of the response no matter the status
  409. try {
  410. responseText = await response.text();
  411. } catch (error) {
  412. twoHundredErrorReason = 'Failed awaiting response.text()';
  413. ok = false;
  414. if (error.name === 'AbortError') {
  415. errorReason = 'Request was aborted';
  416. } else {
  417. errorReason = error.toString();
  418. }
  419. }
  420. const responseContentType = response.headers.get('content-type');
  421. const isResponseJSON = responseContentType?.includes('json');
  422. const isStatus3XX = status >= 300 && status < 400;
  423. if (status !== 204 && !isStatus3XX) {
  424. try {
  425. responseJSON = JSON.parse(responseText);
  426. } catch (error) {
  427. twoHundredErrorReason = 'Failed trying to parse responseText';
  428. if (error.name === 'AbortError') {
  429. ok = false;
  430. errorReason = 'Request was aborted';
  431. } else if (isResponseJSON && error instanceof SyntaxError) {
  432. // If the MIME type is `application/json` but decoding failed,
  433. // this should be an error.
  434. ok = false;
  435. errorReason = 'JSON parse error';
  436. }
  437. }
  438. }
  439. const responseMeta: ResponseMeta = {
  440. status,
  441. statusText,
  442. responseJSON,
  443. responseText,
  444. getResponseHeader: (header: string) => response.headers.get(header),
  445. };
  446. // Respect the response content-type header
  447. const responseData = isResponseJSON ? responseJSON : responseText;
  448. if (ok) {
  449. successHandler(responseMeta, statusText, responseData);
  450. } else {
  451. // There's no reason we should be here with a 200 response, but we get
  452. // tons of events from this codepath with a 200 status nonetheless.
  453. // Until we know why, let's do what is essentially some very fancy print debugging.
  454. if (status === 200) {
  455. const responseTextUndefined = responseText === undefined;
  456. // Pass a scope object rather than using `withScope` to avoid even
  457. // the possibility of scope bleed.
  458. const scope = new Sentry.Scope();
  459. scope.setTags({errorReason});
  460. if (!responseTextUndefined) {
  461. // Grab everything that could conceivably be helpful to know
  462. scope.setExtras({
  463. twoHundredErrorReason,
  464. responseJSON,
  465. // Force `undefined` and the empty string to print so they're differentiable in the UI
  466. responseText: String(responseText) || '[empty string]',
  467. responseContentType,
  468. errorReason,
  469. });
  470. }
  471. const message = responseTextUndefined
  472. ? '200 API response with undefined responseText'
  473. : '200 treated as error';
  474. // Make sure all of these errors group, so we don't produce a bunch of noise
  475. scope.setFingerprint([message]);
  476. Sentry.captureException(new Error(`${message}: ${method} ${path}`), scope);
  477. }
  478. const shouldSkipErrorHandler =
  479. globalErrorHandlers.map(handler => handler(responseMeta)).filter(Boolean)
  480. .length > 0;
  481. if (!shouldSkipErrorHandler) {
  482. errorHandler(responseMeta, statusText, errorReason);
  483. }
  484. }
  485. completeHandler(responseMeta, statusText);
  486. })
  487. .catch(() => {
  488. // Ignore all failed requests
  489. });
  490. const request = new Request(fetchRequest, aborter);
  491. this.activeRequests[id] = request;
  492. return request;
  493. }
  494. requestPromise<IncludeAllArgsType extends boolean>(
  495. path: string,
  496. {
  497. includeAllArgs,
  498. ...options
  499. }: {includeAllArgs?: IncludeAllArgsType} & Readonly<RequestOptions> = {}
  500. ): Promise<IncludeAllArgsType extends true ? ApiResult : any> {
  501. // Create an error object here before we make any async calls so that we
  502. // have a helpful stack trace if it errors
  503. //
  504. // This *should* get logged to Sentry only if the promise rejection is not handled
  505. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  506. // or handle with a user friendly error message
  507. const preservedError = new Error('API Request Error');
  508. return new Promise((resolve, reject) =>
  509. this.request(path, {
  510. ...options,
  511. preservedError,
  512. success: (data, textStatus, resp) => {
  513. if (includeAllArgs) {
  514. resolve([data, textStatus, resp] as any);
  515. } else {
  516. resolve(data);
  517. }
  518. },
  519. error: (resp: ResponseMeta) => {
  520. const errorObjectToUse = new RequestError(
  521. options.method,
  522. path,
  523. preservedError,
  524. resp
  525. );
  526. // Although `this.request` logs all error responses, this error object can
  527. // potentially be logged by Sentry's unhandled rejection handler
  528. reject(errorObjectToUse);
  529. },
  530. })
  531. );
  532. }
  533. }