sudoModal.tsx 9.7 KB

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