Merge branch '16941-inactive-remotes' refs #16941
[arvados-workbench2.git] / src / store / auth / auth-action-session.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from "redux";
6 import { setBreadcrumbs } from "~/store/breadcrumbs/breadcrumbs-actions";
7 import { RootState } from "~/store/store";
8 import { ServiceRepository, createServices, setAuthorizationHeader } from "~/services/services";
9 import Axios, { AxiosInstance } from "axios";
10 import { User, getUserDisplayName } from "~/models/user";
11 import { authActions } from "~/store/auth/auth-action";
12 import {
13     Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH,
14     buildConfig, mockClusterConfigJSON
15 } from "~/common/config";
16 import { normalizeURLPath } from "~/common/url";
17 import { Session, SessionStatus } from "~/models/session";
18 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
19 import { AuthService } from "~/services/auth-service/auth-service";
20 import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
21 import * as jsSHA from "jssha";
22
23 const getClusterConfig = async (origin: string, apiClient: AxiosInstance): Promise<Config | null> => {
24     let configFromDD: Config | undefined;
25     try {
26         const dd = (await apiClient.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
27         configFromDD = {
28             baseUrl: normalizeURLPath(dd.baseUrl),
29             keepWebServiceUrl: dd.keepWebServiceUrl,
30             remoteHosts: dd.remoteHosts,
31             rootUrl: dd.rootUrl,
32             uuidPrefix: dd.uuidPrefix,
33             websocketUrl: dd.websocketUrl,
34             workbenchUrl: dd.workbenchUrl,
35             workbench2Url: dd.workbench2Url,
36             loginCluster: "",
37             vocabularyUrl: "",
38             fileViewersConfigUrl: "",
39             clusterConfig: mockClusterConfigJSON({}),
40             apiRevision: parseInt(dd.revision, 10),
41         };
42     } catch { }
43
44     // Try public config endpoint
45     try {
46         const config = (await apiClient.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
47         return { ...buildConfig(config), apiRevision: configFromDD ? configFromDD.apiRevision : 0 };
48     } catch { }
49
50     // Fall back to discovery document
51     if (configFromDD !== undefined) {
52         return configFromDD;
53     }
54
55     return null;
56 };
57
58 const getRemoteHostConfig = async (remoteHost: string, useApiClient?: AxiosInstance): Promise<Config | null> => {
59     const apiClient = useApiClient || Axios.create({ headers: {} });
60
61     let url = remoteHost;
62     if (url.indexOf('://') < 0) {
63         url = 'https://' + url;
64     }
65     const origin = new URL(url).origin;
66
67     // Maybe it is an API server URL, try fetching config and discovery doc
68     let r = await getClusterConfig(origin, apiClient);
69     if (r !== null) {
70         return r;
71     }
72
73     // Maybe it is a Workbench2 URL, try getting config.json
74     try {
75         r = await getClusterConfig((await apiClient.get<any>(`${origin}/config.json`)).data.API_HOST, apiClient);
76         if (r !== null) {
77             return r;
78         }
79     } catch { }
80
81     // Maybe it is a Workbench1 URL, try getting status.json
82     try {
83         r = await getClusterConfig((await apiClient.get<any>(`${origin}/status.json`)).data.apiBaseURL, apiClient);
84         if (r !== null) {
85             return r;
86         }
87     } catch { }
88
89     return null;
90 };
91
92 const invalidV2Token = "Must be a v2 token";
93
94 export const getSaltedToken = (clusterId: string, token: string) => {
95     const shaObj = new jsSHA("SHA-1", "TEXT");
96     const [ver, uuid, secret] = token.split("/");
97     if (ver !== "v2") {
98         throw new Error(invalidV2Token);
99     }
100     let salted = secret;
101     if (uuid.substr(0, 5) !== clusterId) {
102         shaObj.setHMACKey(secret, "TEXT");
103         shaObj.update(clusterId);
104         salted = shaObj.getHMAC("HEX");
105     }
106     return `v2/${uuid}/${salted}`;
107 };
108
109 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
110
111 export const validateCluster = async (config: Config, useToken: string):
112     Promise<{ user: User; token: string }> => {
113
114     const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
115
116     const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
117     setAuthorizationHeader(svc, saltedToken);
118
119     const user = await svc.authService.getUserDetails(false);
120     return {
121         user,
122         token: saltedToken,
123     };
124 };
125
126 export const validateSession = (session: Session, activeSession: Session, useApiClient?: AxiosInstance) =>
127     async (dispatch: Dispatch): Promise<Session> => {
128         dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
129         session.loggedIn = false;
130
131         const setupSession = (baseUrl: string, user: User, token: string, apiRevision: number) => {
132             session.baseUrl = baseUrl;
133             session.token = token;
134             session.email = user.email;
135             session.userIsActive = user.isActive;
136             session.uuid = user.uuid;
137             session.name = getUserDisplayName(user);
138             session.loggedIn = true;
139             session.apiRevision = apiRevision;
140         };
141
142         let fail: Error | null = null;
143         const config = await getRemoteHostConfig(session.remoteHost, useApiClient);
144         if (config !== null) {
145             dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
146             try {
147                 const { user, token } = await validateCluster(config, session.token);
148                 setupSession(config.baseUrl, user, token, config.apiRevision);
149             } catch (e) {
150                 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
151                 try {
152                     const { user, token } = await validateCluster(config, activeSession.token);
153                     setupSession(config.baseUrl, user, token, config.apiRevision);
154                     fail = null;
155                 } catch (e2) {
156                     if (e.message === invalidV2Token) {
157                         fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
158                     }
159                 }
160             }
161         } else {
162             fail = new Error(`Could not get config for ${session.remoteHost}`);
163         }
164         session.status = SessionStatus.VALIDATED;
165         dispatch(authActions.UPDATE_SESSION(session));
166
167         if (fail) {
168             throw fail;
169         }
170
171         return session;
172     };
173
174 export const validateSessions = (useApiClient?: AxiosInstance) =>
175     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
176         const sessions = getState().auth.sessions;
177         const activeSession = getActiveSession(sessions);
178         if (activeSession) {
179             dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
180             for (const session of sessions) {
181                 if (session.status === SessionStatus.INVALIDATED) {
182                     try {
183                         /* Here we are dispatching a function, not an
184                            action.  This is legal (it calls the
185                            function with a 'Dispatch' object as the
186                            first parameter) but the typescript
187                            annotations don't understand this case, so
188                            we get an error from typescript unless
189                            override it using Dispatch<any>.  This
190                            pattern is used in a bunch of different
191                            places in Workbench2. */
192                         await dispatch(validateSession(session, activeSession, useApiClient));
193                     } catch (e) {
194                         // Don't do anything here.  User may get
195                         // spammed with multiple messages that are not
196                         // helpful.  They can see the individual
197                         // errors by going to site manager and trying
198                         // to toggle the session.
199                     }
200                 }
201             }
202             services.authService.saveSessions(getState().auth.sessions);
203             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
204         }
205     };
206
207 export const addRemoteConfig = (remoteHost: string) =>
208     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
209         const config = await getRemoteHostConfig(remoteHost);
210         if (!config) {
211             dispatch(snackbarActions.OPEN_SNACKBAR({
212                 message: `Could not get config for ${remoteHost}`,
213                 kind: SnackbarKind.ERROR
214             }));
215             return;
216         }
217         dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
218     };
219
220 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
221     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
222         const sessions = getState().auth.sessions;
223         const activeSession = getActiveSession(sessions);
224         let useToken: string | null = null;
225         if (token) {
226             useToken = token;
227         } else if (activeSession) {
228             useToken = activeSession.token;
229         }
230
231         if (useToken) {
232             const config = await getRemoteHostConfig(remoteHost);
233             if (!config) {
234                 dispatch(snackbarActions.OPEN_SNACKBAR({
235                     message: `Could not get config for ${remoteHost}`,
236                     kind: SnackbarKind.ERROR
237                 }));
238                 return;
239             }
240
241             try {
242                 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
243                 const { user, token } = await validateCluster(config, useToken);
244                 const session = {
245                     loggedIn: true,
246                     status: SessionStatus.VALIDATED,
247                     active: false,
248                     email: user.email,
249                     userIsActive: user.isActive,
250                     name: getUserDisplayName(user),
251                     uuid: user.uuid,
252                     baseUrl: config.baseUrl,
253                     clusterId: config.uuidPrefix,
254                     remoteHost,
255                     token,
256                     apiRevision: config.apiRevision,
257                 };
258
259                 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
260                     await dispatch(authActions.UPDATE_SESSION(session));
261                 } else {
262                     await dispatch(authActions.ADD_SESSION(session));
263                 }
264                 services.authService.saveSessions(getState().auth.sessions);
265
266                 return session;
267             } catch {
268                 if (sendToLogin) {
269                     const rootUrl = new URL(config.baseUrl);
270                     rootUrl.pathname = "";
271                     window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
272                     return;
273                 }
274             }
275         }
276         return Promise.reject(new Error("Could not validate cluster"));
277     };
278
279
280 export const removeSession = (clusterId: string) =>
281     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
282         await dispatch(authActions.REMOVE_SESSION(clusterId));
283         services.authService.saveSessions(getState().auth.sessions);
284     };
285
286 export const toggleSession = (session: Session) =>
287     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
288         const s: Session = { ...session };
289
290         if (session.loggedIn) {
291             s.loggedIn = false;
292             dispatch(authActions.UPDATE_SESSION(s));
293         } else {
294             const sessions = getState().auth.sessions;
295             const activeSession = getActiveSession(sessions);
296             if (activeSession) {
297                 try {
298                     await dispatch(validateSession(s, activeSession));
299                 } catch (e) {
300                     dispatch(snackbarActions.OPEN_SNACKBAR({
301                         message: e.message,
302                         kind: SnackbarKind.ERROR
303                     }));
304                     s.loggedIn = false;
305                     dispatch(authActions.UPDATE_SESSION(s));
306                 }
307             }
308         }
309
310         services.authService.saveSessions(getState().auth.sessions);
311     };
312
313 export const initSessions = (authService: AuthService, config: Config, user: User) =>
314     (dispatch: Dispatch<any>) => {
315         const sessions = authService.buildSessions(config, user);
316         dispatch(authActions.SET_SESSIONS(sessions));
317         dispatch(validateSessions(authService.getApiClient()));
318     };
319
320 export const loadSiteManagerPanel = () =>
321     async (dispatch: Dispatch<any>) => {
322         try {
323             dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
324             dispatch(validateSessions());
325         } catch (e) {
326             return;
327         }
328     };