api.tsx 17 KB

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