15736: Improve error handling for multisite search
[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 } from "~/services/services";
9 import Axios from "axios";
10 import { getUserFullname, User } from "~/models/user";
11 import { authActions } from "~/store/auth/auth-action";
12 import { Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH, ARVADOS_API_PATH } from "~/common/config";
13 import { normalizeURLPath } from "~/common/url";
14 import { Session, SessionStatus } from "~/models/session";
15 import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions";
16 import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service";
17 import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions";
18 import * as jsSHA from "jssha";
19
20 const getClusterInfo = async (origin: string): Promise<{ clusterId: string, baseUrl: string } | null> => {
21     // Try the new public config endpoint
22     try {
23         const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
24         return {
25             clusterId: config.ClusterID,
26             baseUrl: normalizeURLPath(`${config.Services.Controller.ExternalURL}/${ARVADOS_API_PATH}`)
27         };
28     } catch { }
29
30     // Fall back to discovery document
31     try {
32         const config = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
33         return {
34             clusterId: config.uuidPrefix,
35             baseUrl: normalizeURLPath(config.baseUrl)
36         };
37     } catch { }
38
39     return null;
40 };
41
42 interface RemoteHostInfo {
43     clusterId: string;
44     baseUrl: string;
45 }
46
47 const getRemoteHostInfo = async (remoteHost: string): Promise<RemoteHostInfo | null> => {
48     let url = remoteHost;
49     if (url.indexOf('://') < 0) {
50         url = 'https://' + url;
51     }
52     const origin = new URL(url).origin;
53
54     // Maybe it is an API server URL, try fetching config and discovery doc
55     let r = getClusterInfo(origin);
56     if (r !== null) {
57         return r;
58     }
59
60     // Maybe it is a Workbench2 URL, try getting config.json
61     try {
62         r = getClusterInfo((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
63         if (r !== null) {
64             return r;
65         }
66     } catch { }
67
68     // Maybe it is a Workbench1 URL, try getting status.json
69     try {
70         r = getClusterInfo((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
71         if (r !== null) {
72             return r;
73         }
74     } catch { }
75
76     return null;
77 };
78
79 const getUserDetails = async (baseUrl: string, token: string): Promise<UserDetailsResponse> => {
80     const resp = await Axios.get<UserDetailsResponse>(`${baseUrl}/users/current`, {
81         headers: {
82             Authorization: `OAuth2 ${token}`
83         }
84     });
85     return resp.data;
86 };
87
88 const invalidV2Token = "Must be a v2 token";
89
90 export const getSaltedToken = (clusterId: string, token: string) => {
91     const shaObj = new jsSHA("SHA-1", "TEXT");
92     const [ver, uuid, secret] = token.split("/");
93     if (ver !== "v2") {
94         throw new Error(invalidV2Token);
95     }
96     let salted = secret;
97     if (uuid.substr(0, 5) !== clusterId) {
98         shaObj.setHMACKey(secret, "TEXT");
99         shaObj.update(clusterId);
100         salted = shaObj.getHMAC("HEX");
101     }
102     return `v2/${uuid}/${salted}`;
103 };
104
105 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
106
107 export const validateCluster = async (info: RemoteHostInfo, useToken: string):
108     Promise<{ user: User; token: string }> => {
109
110     const saltedToken = getSaltedToken(info.clusterId, useToken);
111     const user = await getUserDetails(info.baseUrl, saltedToken);
112     return {
113         user: {
114             firstName: user.first_name,
115             lastName: user.last_name,
116             uuid: user.uuid,
117             ownerUuid: user.owner_uuid,
118             email: user.email,
119             isAdmin: user.is_admin,
120             isActive: user.is_active,
121             username: user.username,
122             prefs: user.prefs
123         },
124         token: saltedToken,
125     };
126 };
127
128 export const validateSession = (session: Session, activeSession: Session) =>
129     async (dispatch: Dispatch): Promise<Session> => {
130         dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
131         session.loggedIn = false;
132
133         const setupSession = (baseUrl: string, user: User, token: string) => {
134             session.baseUrl = baseUrl;
135             session.token = token;
136             session.email = user.email;
137             session.uuid = user.uuid;
138             session.name = getUserFullname(user);
139             session.loggedIn = true;
140         };
141
142         const info = await getRemoteHostInfo(session.remoteHost);
143         if (!info) {
144             throw new Error(`Could not get config for ${session.remoteHost}`);
145         }
146
147         let fail: Error | null = null;
148         try {
149             const { user, token } = await validateCluster(info, session.token);
150             setupSession(info.baseUrl, user, token);
151         } catch (e) {
152             fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
153             try {
154                 const { user, token } = await validateCluster(info, activeSession.token);
155                 setupSession(info.baseUrl, user, token);
156                 fail = null;
157             } catch (e) {
158                 if (e.message === invalidV2Token) {
159                     fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
160                 }
161             }
162         }
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 = () =>
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));
193                     } catch (e) {
194                         dispatch(snackbarActions.OPEN_SNACKBAR({
195                             message: e.message,
196                             kind: SnackbarKind.ERROR
197                         }));
198                     }
199                 }
200             }
201             services.authService.saveSessions(sessions);
202             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
203         }
204     };
205
206 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
207     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
208         const sessions = getState().auth.sessions;
209         const activeSession = getActiveSession(sessions);
210         let useToken: string | null = null;
211         if (token) {
212             useToken = token;
213         } else if (activeSession) {
214             useToken = activeSession.token;
215         }
216
217         if (useToken) {
218             const info = await getRemoteHostInfo(remoteHost);
219             if (!info) {
220                 dispatch(snackbarActions.OPEN_SNACKBAR({
221                     message: `Could not get config for ${remoteHost}`,
222                     kind: SnackbarKind.ERROR
223                 }));
224                 return;
225             }
226
227             try {
228                 const { user, token } = await validateCluster(info, useToken);
229                 const session = {
230                     loggedIn: true,
231                     status: SessionStatus.VALIDATED,
232                     active: false,
233                     email: user.email,
234                     name: getUserFullname(user),
235                     uuid: user.uuid,
236                     baseUrl: info.baseUrl,
237                     clusterId: info.clusterId,
238                     remoteHost,
239                     token
240                 };
241
242                 if (sessions.find(s => s.clusterId === info.clusterId)) {
243                     dispatch(authActions.UPDATE_SESSION(session));
244                 } else {
245                     dispatch(authActions.ADD_SESSION(session));
246                 }
247                 services.authService.saveSessions(getState().auth.sessions);
248
249                 return session;
250             } catch {
251                 if (sendToLogin) {
252                     const rootUrl = new URL(info.baseUrl);
253                     rootUrl.pathname = "";
254                     window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
255                     return;
256                 }
257             }
258         }
259         return Promise.reject(new Error("Could not validate cluster"));
260     };
261
262 export const toggleSession = (session: Session) =>
263     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
264         const s: Session = { ...session };
265
266         if (session.loggedIn) {
267             s.loggedIn = false;
268             dispatch(authActions.UPDATE_SESSION(s));
269         } else {
270             const sessions = getState().auth.sessions;
271             const activeSession = getActiveSession(sessions);
272             if (activeSession) {
273                 try {
274                     await dispatch(validateSession(s, activeSession));
275                 } catch (e) {
276                     dispatch(snackbarActions.OPEN_SNACKBAR({
277                         message: e.message,
278                         kind: SnackbarKind.ERROR
279                     }));
280                     s.loggedIn = false;
281                     dispatch(authActions.UPDATE_SESSION(s));
282                 }
283             }
284         }
285
286         services.authService.saveSessions(getState().auth.sessions);
287     };
288
289 export const initSessions = (authService: AuthService, config: Config, user: User) =>
290     (dispatch: Dispatch<any>) => {
291         const sessions = authService.buildSessions(config, user);
292         authService.saveSessions(sessions);
293         dispatch(authActions.SET_SESSIONS(sessions));
294         dispatch(validateSessions());
295     };
296
297 export const loadSiteManagerPanel = () =>
298     async (dispatch: Dispatch<any>) => {
299         try {
300             dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
301             dispatch(validateSessions());
302         } catch (e) {
303             return;
304         }
305     };