sudoModal.tsx 10 KB

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