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