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