api.tsx 17 KB

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