16941: Remove debug statement.
[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                         dispatch(snackbarActions.OPEN_SNACKBAR({
195                             message: e.message,
196                             kind: SnackbarKind.ERROR
197                         }));
198                     }
199                 }
200             }
201             services.authService.saveSessions(getState().auth.sessions);
202             dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
203         }
204     };
205
206 export const addRemoteConfig = (remoteHost: string) =>
207     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
208         const config = await getRemoteHostConfig(remoteHost);
209         if (!config) {
210             dispatch(snackbarActions.OPEN_SNACKBAR({
211                 message: `Could not get config for ${remoteHost}`,
212                 kind: SnackbarKind.ERROR
213             }));
214             return;
215         }
216         dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
217     };
218
219 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
220     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
221         const sessions = getState().auth.sessions;
222         const activeSession = getActiveSession(sessions);
223         let useToken: string | null = null;
224         if (token) {
225             useToken = token;
226         } else if (activeSession) {
227             useToken = activeSession.token;
228         }
229
230         if (useToken) {
231             const config = await getRemoteHostConfig(remoteHost);
232             if (!config) {
233                 dispatch(snackbarActions.OPEN_SNACKBAR({
234                     message: `Could not get config for ${remoteHost}`,
235                     kind: SnackbarKind.ERROR
236                 }));
237                 return;
238             }
239
240             try {
241                 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
242                 const { user, token } = await validateCluster(config, useToken);
243                 const session = {
244                     loggedIn: true,
245                     status: SessionStatus.VALIDATED,
246                     active: false,
247                     email: user.email,
248                     userIsActive: user.isActive,
249                     name: getUserDisplayName(user),
250                     uuid: user.uuid,
251                     baseUrl: config.baseUrl,
252                     clusterId: config.uuidPrefix,
253                     remoteHost,
254                     token,
255                     apiRevision: config.apiRevision,
256                 };
257
258                 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
259                     await dispatch(authActions.UPDATE_SESSION(session));
260                 } else {
261                     await dispatch(authActions.ADD_SESSION(session));
262                 }
263                 services.authService.saveSessions(getState().auth.sessions);
264
265                 return session;
266             } catch {
267                 if (sendToLogin) {
268                     const rootUrl = new URL(config.baseUrl);
269                     rootUrl.pathname = "";
270                     window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
271                     return;
272                 }
273             }
274         }
275         return Promise.reject(new Error("Could not validate cluster"));
276     };
277
278
279 export const removeSession = (clusterId: string) =>
280     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
281         await dispatch(authActions.REMOVE_SESSION(clusterId));
282         services.authService.saveSessions(getState().auth.sessions);
283     };
284
285 export const toggleSession = (session: Session) =>
286     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
287         const s: Session = { ...session };
288
289         if (session.loggedIn) {
290             s.loggedIn = false;
291             dispatch(authActions.UPDATE_SESSION(s));
292         } else {
293             const sessions = getState().auth.sessions;
294             const activeSession = getActiveSession(sessions);
295             if (activeSession) {
296                 try {
297                     await dispatch(validateSession(s, activeSession));
298                 } catch (e) {
299                     dispatch(snackbarActions.OPEN_SNACKBAR({
300                         message: e.message,
301                         kind: SnackbarKind.ERROR
302                     }));
303                     s.loggedIn = false;
304                     dispatch(authActions.UPDATE_SESSION(s));
305                 }
306             }
307         }
308
309         services.authService.saveSessions(getState().auth.sessions);
310     };
311
312 export const initSessions = (authService: AuthService, config: Config, user: User) =>
313     (dispatch: Dispatch<any>) => {
314         const sessions = authService.buildSessions(config, user);
315         dispatch(authActions.SET_SESSIONS(sessions));
316         dispatch(validateSessions(authService.getApiClient()));
317     };
318
319 export const loadSiteManagerPanel = () =>
320     async (dispatch: Dispatch<any>) => {
321         try {
322             dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
323             dispatch(validateSessions());
324         } catch (e) {
325             return;
326         }
327     };