sudoModal.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import {Fragment, useContext, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import trimEnd from 'lodash/trimEnd';
  4. import {logout} from 'sentry/actionCreators/account';
  5. import type {ModalRenderProps} from 'sentry/actionCreators/modal';
  6. import {Alert} from 'sentry/components/alert';
  7. import {Button, LinkButton} from 'sentry/components/button';
  8. import SecretField from 'sentry/components/forms/fields/secretField';
  9. import Form from 'sentry/components/forms/form';
  10. import Hook from 'sentry/components/hook';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import U2fContainer from 'sentry/components/u2f/u2fContainer';
  13. import {ErrorCodes} from 'sentry/constants/superuserAccessErrors';
  14. import {t} from 'sentry/locale';
  15. import ConfigStore from 'sentry/stores/configStore';
  16. import {space} from 'sentry/styles/space';
  17. import type {Authenticator} from 'sentry/types/auth';
  18. import useApi from 'sentry/utils/useApi';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import {useNavigate} from 'sentry/utils/useNavigate';
  21. import {useUser} from 'sentry/utils/useUser';
  22. import {OrganizationLoaderContext} from 'sentry/views/organizationContext';
  23. import TextBlock from 'sentry/views/settings/components/text/textBlock';
  24. type OnTapProps = NonNullable<React.ComponentProps<typeof U2fContainer>['onTap']>;
  25. type DefaultProps = {
  26. closeButton?: boolean;
  27. };
  28. type State = {
  29. authenticators: Array<Authenticator>;
  30. error: boolean;
  31. errorType: string;
  32. isLoading: boolean;
  33. showAccessForms: boolean;
  34. superuserAccessCategory: string;
  35. superuserReason: string;
  36. };
  37. type Props = DefaultProps &
  38. Pick<ModalRenderProps, 'Body' | 'Header'> & {
  39. closeModal: () => void;
  40. /**
  41. * User is a superuser without an active su session
  42. */
  43. isSuperuser?: boolean;
  44. needsReload?: boolean;
  45. /**
  46. * expects a function that returns a Promise
  47. */
  48. retryRequest?: () => Promise<any>;
  49. };
  50. function SudoModal({
  51. closeModal,
  52. isSuperuser,
  53. needsReload,
  54. retryRequest,
  55. Header,
  56. Body,
  57. closeButton,
  58. }: Props) {
  59. const user = useUser();
  60. const navigate = useNavigate();
  61. const api = useApi();
  62. const [state, setState] = useState<State>({
  63. authenticators: [] as Authenticator[],
  64. error: false,
  65. errorType: '',
  66. showAccessForms: true,
  67. superuserAccessCategory: '',
  68. superuserReason: '',
  69. isLoading: true,
  70. });
  71. const {
  72. authenticators,
  73. error,
  74. errorType,
  75. showAccessForms,
  76. superuserAccessCategory,
  77. superuserReason,
  78. } = state;
  79. const {organizationPromise} = useContext(OrganizationLoaderContext);
  80. const location = useLocation();
  81. useEffect(() => {
  82. const getAuthenticators = async () => {
  83. try {
  84. // Await all preload requests
  85. await Promise.allSettled([
  86. organizationPromise,
  87. ...Object.values(window.__sentry_preload),
  88. ]);
  89. } catch {
  90. // ignore errors
  91. }
  92. // Fetch authenticators after preload requests to avoid overwriting session cookie
  93. try {
  94. const fetchedAuthenticators = await api.requestPromise('/authenticators/');
  95. setState(prevState => ({
  96. ...prevState,
  97. authenticators: fetchedAuthenticators ?? [],
  98. isLoading: false,
  99. }));
  100. } catch {
  101. setState(prevState => ({
  102. ...prevState,
  103. isLoading: false,
  104. }));
  105. }
  106. };
  107. getAuthenticators();
  108. }, [api, organizationPromise]);
  109. const handleSubmitCOPS = () => {
  110. setState(prevState => ({
  111. ...prevState,
  112. superuserAccessCategory: 'cops_csm',
  113. superuserReason: 'COPS and CSM use',
  114. }));
  115. };
  116. const handleSubmit = async data => {
  117. const disableU2FForSUForm = ConfigStore.get('disableU2FForSUForm');
  118. const suAccessCategory = superuserAccessCategory || data.superuserAccessCategory;
  119. const suReason = superuserReason || data.superuserReason;
  120. if (!authenticators.length && !disableU2FForSUForm) {
  121. handleError(ErrorCodes.NO_AUTHENTICATOR);
  122. return;
  123. }
  124. if (showAccessForms && isSuperuser && !disableU2FForSUForm) {
  125. setState(prevState => ({
  126. ...prevState,
  127. showAccessForms: false,
  128. superuserAccessCategory: suAccessCategory,
  129. superuserReason: suReason,
  130. }));
  131. } else {
  132. try {
  133. await api.requestPromise('/auth/', {method: 'PUT', data});
  134. handleSuccess();
  135. } catch (err) {
  136. handleError(err);
  137. }
  138. }
  139. };
  140. const handleSuccess = () => {
  141. if (isSuperuser) {
  142. navigate(
  143. {pathname: location.pathname, state: {forceUpdate: new Date()}},
  144. {replace: true}
  145. );
  146. if (needsReload) {
  147. window.location.reload();
  148. }
  149. return;
  150. }
  151. if (!retryRequest) {
  152. closeModal();
  153. return;
  154. }
  155. retryRequest().then(() => {
  156. setState(prevState => ({...prevState, showAccessForms: true}));
  157. closeModal();
  158. });
  159. };
  160. const handleError = err => {
  161. let newErrorType = ''; // Create a new variable to store the error type
  162. if (err.status === 403) {
  163. if (err.responseJSON.detail.code === 'no_u2f') {
  164. newErrorType = ErrorCodes.NO_AUTHENTICATOR;
  165. } else {
  166. newErrorType = ErrorCodes.INVALID_PASSWORD;
  167. }
  168. } else if (err.status === 401) {
  169. newErrorType = ErrorCodes.INVALID_SSO_SESSION;
  170. } else if (err.status === 400) {
  171. newErrorType = ErrorCodes.INVALID_ACCESS_CATEGORY;
  172. } else if (err === ErrorCodes.NO_AUTHENTICATOR) {
  173. newErrorType = ErrorCodes.NO_AUTHENTICATOR;
  174. } else {
  175. newErrorType = ErrorCodes.UNKNOWN_ERROR;
  176. }
  177. setState(prevState => ({
  178. ...prevState,
  179. error: true,
  180. errorType: newErrorType,
  181. showAccessForms: true,
  182. }));
  183. };
  184. const handleU2fTap = async (data: Parameters<OnTapProps>[0]) => {
  185. try {
  186. data.isSuperuserModal = isSuperuser;
  187. data.superuserAccessCategory = state.superuserAccessCategory;
  188. data.superuserReason = state.superuserReason;
  189. await api.requestPromise('/auth/', {method: 'PUT', data});
  190. handleSuccess();
  191. } catch (err) {
  192. // u2fInterface relies on this
  193. throw err;
  194. }
  195. };
  196. const getAuthLoginPath = (): string => {
  197. const authLoginPath = `/auth/login/?next=${encodeURIComponent(window.location.href)}`;
  198. const {superuserUrl} = window.__initialData.links;
  199. if (window.__initialData?.customerDomain && superuserUrl) {
  200. return `${trimEnd(superuserUrl, '/')}${authLoginPath}`;
  201. }
  202. return authLoginPath;
  203. };
  204. const renderBodyContent = () => {
  205. const isSelfHosted = ConfigStore.get('isSelfHosted');
  206. const validateSUForm = ConfigStore.get('validateSUForm');
  207. if (errorType === ErrorCodes.INVALID_SSO_SESSION) {
  208. logout(api, getAuthLoginPath());
  209. return null;
  210. }
  211. if (state.isLoading) {
  212. return <LoadingIndicator />;
  213. }
  214. if (
  215. (!user.hasPasswordAuth && authenticators.length === 0) ||
  216. (isSuperuser && !isSelfHosted && validateSUForm)
  217. ) {
  218. return (
  219. <Fragment>
  220. <StyledTextBlock>
  221. {isSuperuser
  222. ? t(
  223. 'You are attempting to access a resource that requires superuser access, please re-authenticate as a superuser.'
  224. )
  225. : t('You will need to reauthenticate to continue')}
  226. </StyledTextBlock>
  227. {error && (
  228. <StyledAlert type="error" showIcon>
  229. {errorType}
  230. </StyledAlert>
  231. )}
  232. {isSuperuser ? (
  233. <Form
  234. apiMethod="PUT"
  235. apiEndpoint="/auth/"
  236. submitLabel={showAccessForms ? t('Continue') : t('Re-authenticate')}
  237. onSubmit={handleSubmit}
  238. onSubmitSuccess={handleSuccess}
  239. onSubmitError={handleError}
  240. initialData={{isSuperuserModal: isSuperuser}}
  241. extraButton={
  242. <BackWrapper>
  243. <Button type="submit" onClick={handleSubmitCOPS}>
  244. {t('COPS/CSM')}
  245. </Button>
  246. </BackWrapper>
  247. }
  248. resetOnError
  249. >
  250. {!isSelfHosted && showAccessForms && (
  251. <Hook name="component:superuser-access-category" />
  252. )}
  253. {!isSelfHosted && !showAccessForms && (
  254. <U2fContainer
  255. authenticators={authenticators}
  256. displayMode="sudo"
  257. onTap={handleU2fTap}
  258. />
  259. )}
  260. </Form>
  261. ) : (
  262. <LinkButton priority="primary" href={getAuthLoginPath()}>
  263. {t('Continue')}
  264. </LinkButton>
  265. )}
  266. </Fragment>
  267. );
  268. }
  269. return (
  270. <Fragment>
  271. <StyledTextBlock>
  272. {isSuperuser
  273. ? t(
  274. 'You are attempting to access a resource that requires superuser access, please re-authenticate as a superuser.'
  275. )
  276. : t('Help us keep your account safe by confirming your identity.')}
  277. </StyledTextBlock>
  278. {error && (
  279. <StyledAlert type="error" showIcon>
  280. {errorType}
  281. </StyledAlert>
  282. )}
  283. <Form
  284. apiMethod="PUT"
  285. apiEndpoint="/auth/"
  286. submitLabel={t('Confirm Password')}
  287. onSubmitSuccess={handleSuccess}
  288. onSubmitError={handleError}
  289. hideFooter={!user.hasPasswordAuth && authenticators.length === 0}
  290. initialData={{isSuperuserModal: isSuperuser}}
  291. resetOnError
  292. >
  293. {user.hasPasswordAuth && (
  294. <StyledSecretField
  295. inline={false}
  296. label={t('Password')}
  297. name="password"
  298. autoFocus
  299. flexibleControlStateSize
  300. />
  301. )}
  302. <U2fContainer
  303. authenticators={authenticators}
  304. displayMode="sudo"
  305. onTap={handleU2fTap}
  306. />
  307. </Form>
  308. </Fragment>
  309. );
  310. };
  311. return (
  312. <Fragment>
  313. <Header closeButton={closeButton}>{t('Confirm Password to Continue')}</Header>
  314. <Body>{renderBodyContent()}</Body>
  315. </Fragment>
  316. );
  317. }
  318. export default SudoModal;
  319. const StyledTextBlock = styled(TextBlock)`
  320. margin-bottom: ${space(1)};
  321. `;
  322. const StyledSecretField = styled(SecretField)`
  323. padding-left: 0;
  324. `;
  325. const StyledAlert = styled(Alert)`
  326. margin-bottom: 0;
  327. `;
  328. const BackWrapper = styled('div')`
  329. width: 100%;
  330. margin-left: ${space(4)};
  331. `;