sudoModal.tsx 9.9 KB

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