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.userIsActive = user.isActive;
134 session.uuid = user.uuid;
135 session.name = getUserDisplayName(user);
136 session.loggedIn = true;
137 session.apiRevision = apiRevision;
140 let fail: Error | null = null;
141 const config = await getRemoteHostConfig(session.remoteHost);
142 if (config !== null) {
143 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
145 const { user, token } = await validateCluster(config, session.token);
146 setupSession(config.baseUrl, user, token, config.apiRevision);
148 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
150 const { user, token } = await validateCluster(config, activeSession.token);
151 setupSession(config.baseUrl, user, token, config.apiRevision);
154 if (e.message === invalidV2Token) {
155 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
160 fail = new Error(`Could not get config for ${session.remoteHost}`);
162 session.status = SessionStatus.VALIDATED;
163 dispatch(authActions.UPDATE_SESSION(session));
172 export const validateSessions = () =>
173 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
174 const sessions = getState().auth.sessions;
175 const activeSession = getActiveSession(sessions);
177 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
178 for (const session of sessions) {
179 if (session.status === SessionStatus.INVALIDATED) {
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));
192 dispatch(snackbarActions.OPEN_SNACKBAR({
194 kind: SnackbarKind.ERROR
199 services.authService.saveSessions(getState().auth.sessions);
200 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
204 export const addRemoteConfig = (remoteHost: string) =>
205 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
206 const config = await getRemoteHostConfig(remoteHost);
208 dispatch(snackbarActions.OPEN_SNACKBAR({
209 message: `Could not get config for ${remoteHost}`,
210 kind: SnackbarKind.ERROR
214 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
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;
224 } else if (activeSession) {
225 useToken = activeSession.token;
229 const config = await getRemoteHostConfig(remoteHost);
231 dispatch(snackbarActions.OPEN_SNACKBAR({
232 message: `Could not get config for ${remoteHost}`,
233 kind: SnackbarKind.ERROR
239 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
240 const { user, token } = await validateCluster(config, useToken);
243 status: SessionStatus.VALIDATED,
246 userIsActive: user.isActive,
247 name: getUserDisplayName(user),
249 baseUrl: config.baseUrl,
250 clusterId: config.uuidPrefix,
253 apiRevision: config.apiRevision,
256 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
257 await dispatch(authActions.UPDATE_SESSION(session));
259 await dispatch(authActions.ADD_SESSION(session));
261 services.authService.saveSessions(getState().auth.sessions);
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()));
273 return Promise.reject(new Error("Could not validate cluster"));
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);
283 export const toggleSession = (session: Session) =>
284 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
285 const s: Session = { ...session };
287 if (session.loggedIn) {
289 dispatch(authActions.UPDATE_SESSION(s));
291 const sessions = getState().auth.sessions;
292 const activeSession = getActiveSession(sessions);
295 await dispatch(validateSession(s, activeSession));
297 dispatch(snackbarActions.OPEN_SNACKBAR({
299 kind: SnackbarKind.ERROR
302 dispatch(authActions.UPDATE_SESSION(s));
307 services.authService.saveSessions(getState().auth.sessions);
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());
317 export const loadSiteManagerPanel = () =>
318 async (dispatch: Dispatch<any>) => {
320 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
321 dispatch(validateSessions());