5fc8cffb0da1b540b80b810f56ec7cf4f002259a
[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();
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.userIsActive = user.isActive;
134             session.uuid = user.uuid;
135             session.name = getUserDisplayName(user);
136             session.loggedIn = true;
137             session.apiRevision = apiRevision;
138         };
139
140         let fail: Error | null = null;
141         const config = await getRemoteHostConfig(session.remoteHost);
142         if (config !== null) {
143             dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
144             try {
145                 const { user, token } = await validateCluster(config, session.token);
146                 setupSession(config.baseUrl, user, token, config.apiRevision);
147             } catch (e) {
148                 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
149                 try {
150                     const { user, token } = await validateCluster(config, activeSession.token);
151                     setupSession(config.baseUrl, user, token, config.apiRevision);
152                     fail = null;
153                 } catch (e2) {
154                     if (e.message === invalidV2Token) {
155                         fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
156                     }
157                 }
158             }
159         } else {
160             fail = new Error(`Could not get config for ${session.remoteHost}`);
161         }
162         session.status = SessionStatus.VALIDATED;
163         dispatch(authActions.UPDATE_SESSION(session));
164
165         if (fail) {
166             throw fail;
167         }
168
169         return session;
170     };
171
172 export const validateSessions = () =>
173     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
174         const sessions = getState().auth.sessions;
175         const activeSession = getActiveSession(sessions);
176         if (activeSession) {
177             dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
178             for (const session of sessions) {
179                 if (session.status === SessionStatus.INVALIDATED) {
180                     try {
181                         /* Here we are dispatching a function, not an
182                            action.  This is legal (it calls the
183                            function with a 'Dispatch' object as the
184                            first parameter) but the typescript
185                            annotations don't understand this case, so
186                            we get an error from typescript unless
187                            override it using Dispatch<any>.  This
188                            pattern is used in a bunch of different
189                            places in Workbench2. */
190                         await dispatch(validateSession(session, activeSession));
191                     } catch (e) {
192                         dispatch(snackbarActions.OPEN_SNACKBAR({
193                             message: e.message,
194                             kind: SnackbarKind.ERROR
195                         }));
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                     userIsActive: user.isActive,
247                     name: getUserDisplayName(user),
248                     uuid: user.uuid,
249                     baseUrl: config.baseUrl,
250                     clusterId: config.uuidPrefix,
251                     remoteHost,
252                     token,
253                     apiRevision: config.apiRevision,
254                 };
255
256                 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
257                     await dispatch(authActions.UPDATE_SESSION(session));
258                 } else {
259                     await dispatch(authActions.ADD_SESSION(session));
260                 }
261                 services.authService.saveSessions(getState().auth.sessions);
262
263                 return session;
264             } catch {
265                 if (sendToLogin) {
266                     const rootUrl = new URL(config.baseUrl);
267                     rootUrl.pathname = "";
268                     window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
269                     return;
270                 }
271             }
272         }
273         return Promise.reject(new Error("Could not validate cluster"));
274     };
275
276
277 export const removeSession = (clusterId: string) =>
278     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
279         await dispatch(authActions.REMOVE_SESSION(clusterId));
280         services.authService.saveSessions(getState().auth.sessions);
281     };
282
283 export const toggleSession = (session: Session) =>
284     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
285         const s: Session = { ...session };
286
287         if (session.loggedIn) {
288             s.loggedIn = false;
289             dispatch(authActions.UPDATE_SESSION(s));
290         } else {
291             const sessions = getState().auth.sessions;
292             const activeSession = getActiveSession(sessions);
293             if (activeSession) {
294                 try {
295                     await dispatch(validateSession(s, activeSession));
296                 } catch (e) {
297                     dispatch(snackbarActions.OPEN_SNACKBAR({
298                         message: e.message,
299                         kind: SnackbarKind.ERROR
300                     }));
301                     s.loggedIn = false;
302                     dispatch(authActions.UPDATE_SESSION(s));
303                 }
304             }
305         }
306
307         services.authService.saveSessions(getState().auth.sessions);
308     };
309
310 export const initSessions = (authService: AuthService, config: Config, user: User) =>
311     (dispatch: Dispatch<any>) => {
312         const sessions = authService.buildSessions(config, user);
313         dispatch(authActions.SET_SESSIONS(sessions));
314         dispatch(validateSessions());
315     };
316
317 export const loadSiteManagerPanel = () =>
318     async (dispatch: Dispatch<any>) => {
319         try {
320             dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
321             dispatch(validateSessions());
322         } catch (e) {
323             return;
324         }
325     };