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