1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
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";
23 const getClusterConfig = async (origin: string): Promise<Config | null> => {
24 let configFromDD: Config | undefined;
26 const dd = (await Axios.get<any>(`${origin}/${DISCOVERY_DOC_PATH}`)).data;
28 baseUrl: normalizeURLPath(dd.baseUrl),
29 keepWebServiceUrl: dd.keepWebServiceUrl,
30 remoteHosts: dd.remoteHosts,
32 uuidPrefix: dd.uuidPrefix,
33 websocketUrl: dd.websocketUrl,
34 workbenchUrl: dd.workbenchUrl,
35 workbench2Url: dd.workbench2Url,
38 fileViewersConfigUrl: "",
39 clusterConfig: mockClusterConfigJSON({}),
40 apiRevision: parseInt(dd.revision, 10),
44 // Try the new public config endpoint
46 const config = (await Axios.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
47 return {...buildConfig(config), apiRevision: configFromDD ? configFromDD.apiRevision : 0};
50 // Fall back to discovery document
51 if (configFromDD !== undefined) {
58 const getRemoteHostConfig = async (remoteHost: string): Promise<Config | null> => {
60 if (url.indexOf('://') < 0) {
61 url = 'https://' + url;
63 const origin = new URL(url).origin;
65 // Maybe it is an API server URL, try fetching config and discovery doc
66 let r = await getClusterConfig(origin);
71 // Maybe it is a Workbench2 URL, try getting config.json
73 r = await getClusterConfig((await Axios.get<any>(`${origin}/config.json`)).data.API_HOST);
79 // Maybe it is a Workbench1 URL, try getting status.json
81 r = await getClusterConfig((await Axios.get<any>(`${origin}/status.json`)).data.apiBaseURL);
90 const invalidV2Token = "Must be a v2 token";
92 export const getSaltedToken = (clusterId: string, token: string) => {
93 const shaObj = new jsSHA("SHA-1", "TEXT");
94 const [ver, uuid, secret] = token.split("/");
96 throw new Error(invalidV2Token);
99 if (uuid.substr(0, 5) !== clusterId) {
100 shaObj.setHMACKey(secret, "TEXT");
101 shaObj.update(clusterId);
102 salted = shaObj.getHMAC("HEX");
104 return `v2/${uuid}/${salted}`;
107 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
109 export const validateCluster = async (config: Config, useToken: string):
110 Promise<{ user: User; token: string }> => {
112 const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
114 const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
115 setAuthorizationHeader(svc, saltedToken);
117 const user = await svc.authService.getUserDetails();
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;
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;
139 let fail: Error | null = null;
140 const config = await getRemoteHostConfig(session.remoteHost);
141 if (config !== null) {
142 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
144 const { user, token } = await validateCluster(config, session.token);
145 setupSession(config.baseUrl, user, token, config.apiRevision);
147 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
149 const { user, token } = await validateCluster(config, activeSession.token);
150 setupSession(config.baseUrl, user, token, config.apiRevision);
153 if (e.message === invalidV2Token) {
154 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
159 fail = new Error(`Could not get config for ${session.remoteHost}`);
161 session.status = SessionStatus.VALIDATED;
162 dispatch(authActions.UPDATE_SESSION(session));
171 export const validateSessions = () =>
172 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
173 const sessions = getState().auth.sessions;
174 const activeSession = getActiveSession(sessions);
176 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
177 for (const session of sessions) {
178 if (session.status === SessionStatus.INVALIDATED) {
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));
191 dispatch(snackbarActions.OPEN_SNACKBAR({
193 kind: SnackbarKind.ERROR
198 services.authService.saveSessions(getState().auth.sessions);
199 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
203 export const addRemoteConfig = (remoteHost: string) =>
204 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
205 const config = await getRemoteHostConfig(remoteHost);
207 dispatch(snackbarActions.OPEN_SNACKBAR({
208 message: `Could not get config for ${remoteHost}`,
209 kind: SnackbarKind.ERROR
213 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
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;
223 } else if (activeSession) {
224 useToken = activeSession.token;
228 const config = await getRemoteHostConfig(remoteHost);
230 dispatch(snackbarActions.OPEN_SNACKBAR({
231 message: `Could not get config for ${remoteHost}`,
232 kind: SnackbarKind.ERROR
238 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
239 const { user, token } = await validateCluster(config, useToken);
242 status: SessionStatus.VALIDATED,
245 name: getUserDisplayName(user),
247 baseUrl: config.baseUrl,
248 clusterId: config.uuidPrefix,
251 apiRevision: config.apiRevision,
254 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
255 await dispatch(authActions.UPDATE_SESSION(session));
257 await dispatch(authActions.ADD_SESSION(session));
259 services.authService.saveSessions(getState().auth.sessions);
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()));
271 return Promise.reject(new Error("Could not validate cluster"));
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);
281 export const toggleSession = (session: Session) =>
282 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
283 const s: Session = { ...session };
285 if (session.loggedIn) {
287 dispatch(authActions.UPDATE_SESSION(s));
289 const sessions = getState().auth.sessions;
290 const activeSession = getActiveSession(sessions);
293 await dispatch(validateSession(s, activeSession));
295 dispatch(snackbarActions.OPEN_SNACKBAR({
297 kind: SnackbarKind.ERROR
300 dispatch(authActions.UPDATE_SESSION(s));
305 services.authService.saveSessions(getState().auth.sessions);
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());
315 export const loadSiteManagerPanel = () =>
316 async (dispatch: Dispatch<any>) => {
318 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
319 dispatch(validateSessions());