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 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 keepWebInlineServiceUrl: dd.keepWebInlineServiceUrl,
31 remoteHosts: dd.remoteHosts,
33 uuidPrefix: dd.uuidPrefix,
34 websocketUrl: dd.websocketUrl,
35 workbenchUrl: dd.workbenchUrl,
36 workbench2Url: dd.workbench2Url,
39 fileViewersConfigUrl: "",
40 clusterConfig: mockClusterConfigJSON({}),
41 apiRevision: parseInt(dd.revision, 10),
45 // Try public config endpoint
47 const config = (await apiClient.get<ClusterConfigJSON>(`${origin}/${CLUSTER_CONFIG_PATH}`)).data;
48 return { ...buildConfig(config), apiRevision: configFromDD ? configFromDD.apiRevision : 0 };
51 // Fall back to discovery document
52 if (configFromDD !== undefined) {
59 export const getRemoteHostConfig = async (remoteHost: string, useApiClient?: AxiosInstance): Promise<Config | null> => {
60 const apiClient = useApiClient || Axios.create({ headers: {} });
63 if (url.indexOf('://') < 0) {
64 url = 'https://' + url;
66 const origin = new URL(url).origin;
68 // Maybe it is an API server URL, try fetching config and discovery doc
69 let r = await getClusterConfig(origin, apiClient);
74 // Maybe it is a Workbench2 URL, try getting config.json
76 r = await getClusterConfig((await apiClient.get<any>(`${origin}/config.json`)).data.API_HOST, apiClient);
82 // Maybe it is a Workbench1 URL, try getting status.json
84 r = await getClusterConfig((await apiClient.get<any>(`${origin}/status.json`)).data.apiBaseURL, apiClient);
93 const invalidV2Token = "Must be a v2 token";
95 export const getSaltedToken = (clusterId: string, token: string) => {
96 const shaObj = new jsSHA("SHA-1", "TEXT");
97 const [ver, uuid, secret] = token.split("/");
99 throw new Error(invalidV2Token);
102 if (uuid.substring(0, 5) !== clusterId) {
103 shaObj.setHMACKey(secret, "TEXT");
104 shaObj.update(clusterId);
105 salted = shaObj.getHMAC("HEX");
107 return `v2/${uuid}/${salted}`;
110 export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active);
112 export const validateCluster = async (config: Config, useToken: string):
113 Promise<{ user: User; token: string }> => {
115 const saltedToken = getSaltedToken(config.uuidPrefix, useToken);
117 const svc = createServices(config, { progressFn: () => { }, errorFn: () => { } });
118 setAuthorizationHeader(svc, saltedToken);
120 const user = await svc.authService.getUserDetails(false);
127 export const validateSession = (session: Session, activeSession: Session, useApiClient?: AxiosInstance) =>
128 async (dispatch: Dispatch): Promise<Session> => {
129 dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED }));
130 session.loggedIn = false;
132 const setupSession = (baseUrl: string, user: User, token: string, apiRevision: number) => {
133 session.baseUrl = baseUrl;
134 session.token = token;
135 session.email = user.email;
136 session.userIsActive = user.isActive;
137 session.uuid = user.uuid;
138 session.name = getUserDisplayName(user);
139 session.loggedIn = true;
140 session.apiRevision = apiRevision;
143 let fail: Error | null = null;
144 const config = await getRemoteHostConfig(session.remoteHost, useApiClient);
145 if (config !== null) {
146 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
148 const { user, token } = await validateCluster(config, session.token);
149 setupSession(config.baseUrl, user, token, config.apiRevision);
151 fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`);
153 const { user, token } = await validateCluster(config, activeSession.token);
154 setupSession(config.baseUrl, user, token, config.apiRevision);
157 if (e.message === invalidV2Token) {
158 fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`);
163 fail = new Error(`Could not get config for ${session.remoteHost}`);
165 session.status = SessionStatus.VALIDATED;
166 dispatch(authActions.UPDATE_SESSION(session));
175 export const validateSessions = (useApiClient?: AxiosInstance) =>
176 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
177 const sessions = getState().auth.sessions;
178 const activeSession = getActiveSession(sessions);
180 dispatch(progressIndicatorActions.START_WORKING("sessionsValidation"));
181 for (const session of sessions) {
182 if (session.status === SessionStatus.INVALIDATED) {
184 /* Here we are dispatching a function, not an
185 action. This is legal (it calls the
186 function with a 'Dispatch' object as the
187 first parameter) but the typescript
188 annotations don't understand this case, so
189 we get an error from typescript unless
190 override it using Dispatch<any>. This
191 pattern is used in a bunch of different
192 places in Workbench2. */
193 await dispatch(validateSession(session, activeSession, useApiClient));
195 // Don't do anything here. User may get
196 // spammed with multiple messages that are not
197 // helpful. They can see the individual
198 // errors by going to site manager and trying
199 // to toggle the session.
203 services.authService.saveSessions(getState().auth.sessions);
204 dispatch(progressIndicatorActions.STOP_WORKING("sessionsValidation"));
208 export const addRemoteConfig = (remoteHost: string) =>
209 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
210 const config = await getRemoteHostConfig(remoteHost);
212 dispatch(snackbarActions.OPEN_SNACKBAR({
213 message: `Could not get config for ${remoteHost}`,
214 kind: SnackbarKind.ERROR
218 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
221 export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) =>
222 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
223 const sessions = getState().auth.sessions;
224 const activeSession = getActiveSession(sessions);
225 let useToken: string | null = null;
228 } else if (activeSession) {
229 useToken = activeSession.token;
233 const config = await getRemoteHostConfig(remoteHost);
235 dispatch(snackbarActions.OPEN_SNACKBAR({
236 message: `Could not get config for ${remoteHost}`,
237 kind: SnackbarKind.ERROR
243 dispatch(authActions.REMOTE_CLUSTER_CONFIG({ config }));
244 const { user, token } = await validateCluster(config, useToken);
247 status: SessionStatus.VALIDATED,
250 userIsActive: user.isActive,
251 name: getUserDisplayName(user),
253 baseUrl: config.baseUrl,
254 clusterId: config.uuidPrefix,
257 apiRevision: config.apiRevision,
260 if (sessions.find(s => s.clusterId === config.uuidPrefix)) {
261 await dispatch(authActions.UPDATE_SESSION(session));
263 await dispatch(authActions.ADD_SESSION(session));
265 services.authService.saveSessions(getState().auth.sessions);
270 const rootUrl = new URL(config.baseUrl);
271 rootUrl.pathname = "";
272 window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString()));
277 return Promise.reject(new Error("Could not validate cluster"));
281 export const removeSession = (clusterId: string) =>
282 async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
283 await dispatch(authActions.REMOVE_SESSION(clusterId));
284 services.authService.saveSessions(getState().auth.sessions);
287 export const toggleSession = (session: Session) =>
288 async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
289 const s: Session = { ...session };
291 if (session.loggedIn) {
293 dispatch(authActions.UPDATE_SESSION(s));
295 const sessions = getState().auth.sessions;
296 const activeSession = getActiveSession(sessions);
299 await dispatch(validateSession(s, activeSession));
301 dispatch(snackbarActions.OPEN_SNACKBAR({
303 kind: SnackbarKind.ERROR
306 dispatch(authActions.UPDATE_SESSION(s));
311 services.authService.saveSessions(getState().auth.sessions);
314 export const initSessions = (authService: AuthService, config: Config, user: User) =>
315 (dispatch: Dispatch<any>) => {
316 const sessions = authService.buildSessions(config, user);
317 dispatch(authActions.SET_SESSIONS(sessions));
318 dispatch(validateSessions(authService.getApiClient()));
321 export const loadSiteManagerPanel = () =>
322 async (dispatch: Dispatch<any>) => {
324 dispatch(setBreadcrumbs([{ label: 'Site Manager' }]));
325 dispatch(validateSessions());