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, { AxiosInstance } 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, apiClient: AxiosInstance): Promise<Config | null> => {
24 let configFromDD: Config | undefined;
26 const dd = (await apiClient.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 public config endpoint
46 const config = (await apiClient.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, useApiClient?: AxiosInstance): Promise<Config | null> => {
59 const apiClient = useApiClient || Axios.create({ headers: {} });
62 if (url.indexOf('://') < 0) {
63 url = 'https://' + url;
65 const origin = new URL(url).origin;
67 // Maybe it is an API server URL, try fetching config and discovery doc
68 let r = await getClusterConfig(origin, apiClient);
73 // Maybe it is a Workbench2 URL, try getting config.json
75 r = await getClusterConfig((await apiClient.get<any>(`${origin}/config.json`)).data.API_HOST, apiClient);
81 // Maybe it is a Workbench1 URL, try getting status.json
83 r = await getClusterConfig((await apiClient.get<any>(`${origin}/status.json`)).data.apiBaseURL, apiClient);
92 const invalidV2Token = "Must be a v2 token";
94 export const getSaltedToken = (clusterId: string, token: string) => {
95 const shaObj = new jsSHA("SHA-1", "TEXT");
96 const [ver, uuid, secret] = token.split("/");
98 throw new Error(invalidV2Token);
101 if (uuid.substr(0, 5) !== clusterId) {
102 shaObj.setHMACKey(secret, "TEXT");
103 shaObj.update(clusterId);
104 salted = shaObj.getHMAC("HEX");
106 return `v2/${uuid}/${salted}`;
109 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
111 export const validateCluster = async (config: Config, useToken: string):
112 Promise<{ user: User; token: string }> => {
114 const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
116 const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
117 setAuthorizationHeader(svc, saltedToken);
119 const user = await svc.authService.getUserDetails(false);
126 export const validateSession = (session: Session, activeSession: Session, useApiClient?: AxiosInstance) =>
127 async (dispatch: Dispatch): Promise<Session> => {
128 dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
129 session.loggedIn = false;
131 const setupSession = (baseUrl: string, user: User, token: string, apiRevision: number) => {
132 session.baseUrl = baseUrl;
133 session.token = token;
134 session.email = user.email;
135 session.userIsActive = user.isActive;
136 session.uuid = user.uuid;
137 session.name = getUserDisplayName(user);
138 session.loggedIn = true;
139 session.apiRevision = apiRevision;
142 let fail: Error | null = null;
143 const config = await getRemoteHostConfig(session.remoteHost, useApiClient);
144 if (config !== null) {
145 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
147 const { user, token } = await validateCluster(config, session.token);
148 setupSession(config.baseUrl, user, token, config.apiRevision);
150 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
152 const { user, token } = await validateCluster(config, activeSession.token);
153 setupSession(config.baseUrl, user, token, config.apiRevision);
156 if (e.message === invalidV2Token) {
157 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
162 fail = new Error(`Could not get config for ${session.remoteHost}`);
164 session.status = SessionStatus.VALIDATED;
165 dispatch(authActions.UPDATE_SESSION(session));
174 export const validateSessions = (useApiClient?: AxiosInstance) =>
175 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
176 const sessions = getState().auth.sessions;
177 const activeSession = getActiveSession(sessions);
179 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
180 for (const session of sessions) {
181 if (session.status === SessionStatus.INVALIDATED) {
183 /* Here we are dispatching a function, not an
184 action. This is legal (it calls the
185 function with a 'Dispatch' object as the
186 first parameter) but the typescript
187 annotations don't understand this case, so
188 we get an error from typescript unless
189 override it using Dispatch<any>. This
190 pattern is used in a bunch of different
191 places in Workbench2. */
192 await dispatch(validateSession(session, activeSession, useApiClient));
194 // Don't do anything here. User may get
195 // spammed with multiple messages that are not
196 // helpful. They can see the individual
197 // errors by going to site manager and trying
198 // to toggle the session.
202 services.authService.saveSessions(getState().auth.sessions);
203 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
207 export const addRemoteConfig = (remoteHost: string) =>
208 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
209 const config = await getRemoteHostConfig(remoteHost);
211 dispatch(snackbarActions.OPEN_SNACKBAR({
212 message: `Could not get config for ${remoteHost}`,
213 kind: SnackbarKind.ERROR
217 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
220 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
221 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
222 const sessions = getState().auth.sessions;
223 const activeSession = getActiveSession(sessions);
224 let useToken: string | null = null;
227 } else if (activeSession) {
228 useToken = activeSession.token;
232 const config = await getRemoteHostConfig(remoteHost);
234 dispatch(snackbarActions.OPEN_SNACKBAR({
235 message: `Could not get config for ${remoteHost}`,
236 kind: SnackbarKind.ERROR
242 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
243 const { user, token } = await validateCluster(config, useToken);
246 status: SessionStatus.VALIDATED,
249 userIsActive: user.isActive,
250 name: getUserDisplayName(user),
252 baseUrl: config.baseUrl,
253 clusterId: config.uuidPrefix,
256 apiRevision: config.apiRevision,
259 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
260 await dispatch(authActions.UPDATE_SESSION(session));
262 await dispatch(authActions.ADD_SESSION(session));
264 services.authService.saveSessions(getState().auth.sessions);
269 const rootUrl = new URL(config.baseUrl);
270 rootUrl.pathname = "";
271 window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
276 return Promise.reject(new Error("Could not validate cluster"));
280 export const removeSession = (clusterId: string) =>
281 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
282 await dispatch(authActions.REMOVE_SESSION(clusterId));
283 services.authService.saveSessions(getState().auth.sessions);
286 export const toggleSession = (session: Session) =>
287 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
288 const s: Session = { ...session };
290 if (session.loggedIn) {
292 dispatch(authActions.UPDATE_SESSION(s));
294 const sessions = getState().auth.sessions;
295 const activeSession = getActiveSession(sessions);
298 await dispatch(validateSession(s, activeSession));
300 dispatch(snackbarActions.OPEN_SNACKBAR({
302 kind: SnackbarKind.ERROR
305 dispatch(authActions.UPDATE_SESSION(s));
310 services.authService.saveSessions(getState().auth.sessions);
313 export const initSessions = (authService: AuthService, config: Config, user: User) =>
314 (dispatch: Dispatch<any>) => {
315 const sessions = authService.buildSessions(config, user);
316 dispatch(authActions.SET_SESSIONS(sessions));
317 dispatch(validateSessions(authService.getApiClient()));
320 export const loadSiteManagerPanel = () =>
321 async (dispatch: Dispatch<any>) => {
323 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
324 dispatch(validateSessions());