api.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 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. * 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 undefined;
  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 undefined;
  247. }
  248. // Call success callback
  249. return func?.apply(req, args);
  250. };
  251. }
  252. /**
  253. * Attempt to cancel all active fetch requests
  254. */
  255. clear() {
  256. Object.values(this.activeRequests).forEach(r => r.cancel());
  257. }
  258. handleRequestError(
  259. {id, path, requestOptions}: HandleRequestErrorOptions,
  260. response: ResponseMeta,
  261. textStatus: string,
  262. errorThrown: string
  263. ) {
  264. const code = response?.responseJSON?.detail?.code;
  265. const isSudoRequired = code === SUDO_REQUIRED || code === SUPERUSER_REQUIRED;
  266. let didSuccessfullyRetry = false;
  267. if (isSudoRequired) {
  268. openSudo({
  269. isSuperuser: code === SUPERUSER_REQUIRED,
  270. sudo: code === SUDO_REQUIRED,
  271. retryRequest: async () => {
  272. try {
  273. const data = await this.requestPromise(path, requestOptions);
  274. requestOptions.success?.(data);
  275. didSuccessfullyRetry = true;
  276. } catch (err) {
  277. requestOptions.error?.(err);
  278. }
  279. },
  280. onClose: () =>
  281. // If modal was closed, then forward the original response
  282. !didSuccessfullyRetry && requestOptions.error?.(response),
  283. });
  284. return;
  285. }
  286. // Call normal error callback
  287. const errorCb = this.wrapCallback<[ResponseMeta, string, string]>(
  288. id,
  289. requestOptions.error
  290. );
  291. errorCb?.(response, textStatus, errorThrown);
  292. }
  293. /**
  294. * Initate a request to the backend API.
  295. *
  296. * Consider using `requestPromise` for the async Promise version of this method.
  297. */
  298. request(path: string, options: Readonly<RequestOptions> = {}): Request {
  299. const method = options.method || (options.data ? 'POST' : 'GET');
  300. let fullUrl = buildRequestUrl(this.baseUrl, path, options.query);
  301. let data = options.data;
  302. if (data !== undefined && method !== 'GET') {
  303. data = JSON.stringify(data);
  304. }
  305. // TODO(epurkhiser): Mimicking the old jQuery API, data could be a string /
  306. // object for GET requets. jQuery just sticks it onto the URL as query
  307. // parameters
  308. if (method === 'GET' && data) {
  309. const queryString = typeof data === 'string' ? data : qs.stringify(data);
  310. if (queryString.length > 0) {
  311. fullUrl = fullUrl + (fullUrl.indexOf('?') !== -1 ? '&' : '?') + queryString;
  312. }
  313. }
  314. const id = uniqueId();
  315. const startMarker = `api-request-start-${id}`;
  316. metric.mark({name: startMarker});
  317. /**
  318. * Called when the request completes with a 2xx status
  319. */
  320. const successHandler = (
  321. resp: ResponseMeta,
  322. textStatus: string,
  323. responseData: any
  324. ) => {
  325. metric.measure({
  326. name: 'app.api.request-success',
  327. start: startMarker,
  328. data: {status: resp?.status},
  329. });
  330. if (options.success !== undefined) {
  331. this.wrapCallback<[any, string, ResponseMeta]>(id, options.success)(
  332. responseData,
  333. textStatus,
  334. resp
  335. );
  336. }
  337. };
  338. /**
  339. * Called when the request is non-2xx
  340. */
  341. const errorHandler = (
  342. resp: ResponseMeta,
  343. textStatus: string,
  344. errorThrown: string
  345. ) => {
  346. metric.measure({
  347. name: 'app.api.request-error',
  348. start: startMarker,
  349. data: {status: resp?.status},
  350. });
  351. this.handleRequestError(
  352. {id, path, requestOptions: options},
  353. resp,
  354. textStatus,
  355. errorThrown
  356. );
  357. };
  358. /**
  359. * Called when the request completes
  360. */
  361. const completeHandler = (resp: ResponseMeta, textStatus: string) =>
  362. this.wrapCallback<[ResponseMeta, string]>(
  363. id,
  364. options.complete,
  365. true
  366. )(resp, textStatus);
  367. // AbortController is optional, though most browser should support it.
  368. const aborter =
  369. typeof AbortController !== 'undefined' ? new AbortController() : undefined;
  370. // GET requests may not have a body
  371. const body = method !== 'GET' ? data : undefined;
  372. const headers = new Headers({
  373. Accept: 'application/json; charset=utf-8',
  374. 'Content-Type': 'application/json',
  375. });
  376. // Do not set the X-CSRFToken header when making a request outside of the
  377. // current domain
  378. const absoluteUrl = new URL(fullUrl, window.location.origin);
  379. const isSameOrigin = window.location.origin === absoluteUrl.origin;
  380. if (!csrfSafeMethod(method) && isSameOrigin) {
  381. headers.set('X-CSRFToken', getCsrfToken());
  382. }
  383. const fetchRequest = fetch(fullUrl, {
  384. method,
  385. body,
  386. headers,
  387. credentials: 'include',
  388. signal: aborter?.signal,
  389. });
  390. // XXX(epurkhiser): We migrated off of jquery, so for now we have a
  391. // compatibility layer which mimics that of the jquery response objects.
  392. fetchRequest
  393. .then(async response => {
  394. // The Response's body can only be resolved/used at most once.
  395. // So we clone the response so we can resolve the body content as text content.
  396. // Response objects need to be cloned before its body can be used.
  397. let responseJSON: any;
  398. let responseText: any;
  399. const {status, statusText} = response;
  400. let {ok} = response;
  401. let errorReason = 'Request not OK'; // the default error reason
  402. // Try to get text out of the response no matter the status
  403. try {
  404. responseText = await response.text();
  405. } catch (error) {
  406. ok = false;
  407. if (error.name === 'AbortError') {
  408. errorReason = 'Request was aborted';
  409. } else {
  410. errorReason = error.toString();
  411. }
  412. }
  413. const responseContentType = response.headers.get('content-type');
  414. const isResponseJSON = responseContentType?.includes('json');
  415. const isStatus3XX = status >= 300 && status < 400;
  416. if (status !== 204 && !isStatus3XX) {
  417. try {
  418. responseJSON = JSON.parse(responseText);
  419. } catch (error) {
  420. if (error.name === 'AbortError') {
  421. ok = false;
  422. errorReason = 'Request was aborted';
  423. } else if (isResponseJSON && error instanceof SyntaxError) {
  424. // If the MIME type is `application/json` but decoding failed,
  425. // this should be an error.
  426. ok = false;
  427. errorReason = 'JSON parse error';
  428. }
  429. }
  430. }
  431. const responseMeta: ResponseMeta = {
  432. status,
  433. statusText,
  434. responseJSON,
  435. responseText,
  436. getResponseHeader: (header: string) => response.headers.get(header),
  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<IncludeAllArgsType extends true ? ApiResult : any> {
  466. // Create an error object here before we make any async calls so that we
  467. // have a helpful stack trace if it errors
  468. //
  469. // This *should* get logged to Sentry only if the promise rejection is not handled
  470. // (since SDK captures unhandled rejections). Ideally we explicitly ignore rejection
  471. // or handle with a user friendly error message
  472. const preservedError = new Error('API Request Error');
  473. return new Promise((resolve, reject) =>
  474. this.request(path, {
  475. ...options,
  476. preservedError,
  477. success: (data, textStatus, resp) => {
  478. if (includeAllArgs) {
  479. resolve([data, textStatus, resp] as any);
  480. } else {
  481. resolve(data);
  482. }
  483. },
  484. error: (resp: ResponseMeta) => {
  485. const errorObjectToUse = createRequestError(
  486. resp,
  487. preservedError,
  488. options.method,
  489. path
  490. );
  491. // Although `this.request` logs all error responses, this error object can
  492. // potentially be logged by Sentry's unhandled rejection handler
  493. reject(errorObjectToUse);
  494. },
  495. })
  496. );
  497. }
  498. }