X-Git-Url: https://git.arvados.org/arvados-workbench2.git/blobdiff_plain/78224728bc808a560718e934ef124afa77b81834..ceb4f50aeca2bb6b0354a7bd96a599b4a14147fe:/src/store/auth/auth-action-session.ts diff --git a/src/store/auth/auth-action-session.ts b/src/store/auth/auth-action-session.ts index d36d5a33..2a9733f0 100644 --- a/src/store/auth/auth-action-session.ts +++ b/src/store/auth/auth-action-session.ts @@ -9,36 +9,71 @@ import { ServiceRepository } from "~/services/services"; import Axios from "axios"; import { getUserFullname, User } from "~/models/user"; import { authActions } from "~/store/auth/auth-action"; -import { Config, DISCOVERY_URL } from "~/common/config"; +import { Config, ClusterConfigJSON, CLUSTER_CONFIG_PATH, DISCOVERY_DOC_PATH, ARVADOS_API_PATH } from "~/common/config"; +import { normalizeURLPath } from "~/common/url"; import { Session, SessionStatus } from "~/models/session"; import { progressIndicatorActions } from "~/store/progress-indicator/progress-indicator-actions"; import { AuthService, UserDetailsResponse } from "~/services/auth-service/auth-service"; +import { snackbarActions, SnackbarKind } from "~/store/snackbar/snackbar-actions"; import * as jsSHA from "jssha"; -const getRemoteHostBaseUrl = async (remoteHost: string): Promise => { +const getClusterInfo = async (origin: string): Promise<{ clusterId: string, baseUrl: string } | null> => { + // Try the new public config endpoint + try { + const config = (await Axios.get(`${origin}/${CLUSTER_CONFIG_PATH}`)).data; + return { + clusterId: config.ClusterID, + baseUrl: normalizeURLPath(`${config.Services.Controller.ExternalURL}/${ARVADOS_API_PATH}`) + }; + } catch { } + + // Fall back to discovery document + try { + const config = (await Axios.get(`${origin}/${DISCOVERY_DOC_PATH}`)).data; + return { + clusterId: config.uuidPrefix, + baseUrl: normalizeURLPath(config.baseUrl) + }; + } catch { } + + return null; +}; + +interface RemoteHostInfo { + clusterId: string; + baseUrl: string; +} + +const getRemoteHostInfo = async (remoteHost: string): Promise => { let url = remoteHost; if (url.indexOf('://') < 0) { url = 'https://' + url; } const origin = new URL(url).origin; - let baseUrl: string | null = null; + // Maybe it is an API server URL, try fetching config and discovery doc + let r = getClusterInfo(origin); + if (r !== null) { + return r; + } + + // Maybe it is a Workbench2 URL, try getting config.json try { - const resp = await Axios.get(`${origin}/${DISCOVERY_URL}`); - baseUrl = resp.data.baseUrl; - } catch (err) { - try { - const resp = await Axios.get(`${origin}/status.json`); - baseUrl = resp.data.apiBaseURL; - } catch (err) { + r = getClusterInfo((await Axios.get(`${origin}/config.json`)).data.API_HOST); + if (r !== null) { + return r; } - } + } catch { } - if (baseUrl && baseUrl[baseUrl.length - 1] === '/') { - baseUrl = baseUrl.substr(0, baseUrl.length - 1); - } + // Maybe it is a Workbench1 URL, try getting status.json + try { + r = getClusterInfo((await Axios.get(`${origin}/status.json`)).data.apiBaseURL); + if (r !== null) { + return r; + } + } catch { } - return baseUrl; + return null; }; const getUserDetails = async (baseUrl: string, token: string): Promise => { @@ -50,40 +85,30 @@ const getUserDetails = async (baseUrl: string, token: string): Promise => { - if (token.startsWith("v2/")) { - const uuid = token.split("/")[1]; - return Promise.resolve(uuid); - } - - const resp = await Axios.get(`${baseUrl}/api_client_authorizations`, { - headers: { - Authorization: `OAuth2 ${token}` - }, - data: { - filters: JSON.stringify([['api_token', '=', token]]) - } - }); +const invalidV2Token = "Must be a v2 token"; - return resp.data.items[0].uuid; -}; - -const getSaltedToken = (clusterId: string, tokenUuid: string, token: string) => { +export const getSaltedToken = (clusterId: string, token: string) => { const shaObj = new jsSHA("SHA-1", "TEXT"); - let secret = token; - if (token.startsWith("v2/")) { - secret = token.split("/")[2]; + const [ver, uuid, secret] = token.split("/"); + if (ver !== "v2") { + throw new Error(invalidV2Token); } - shaObj.setHMACKey(secret, "TEXT"); - shaObj.update(clusterId); - const hmac = shaObj.getHMAC("HEX"); - return `v2/${tokenUuid}/${hmac}`; + let salted = secret; + if (uuid.substr(0, 5) !== clusterId) { + shaObj.setHMACKey(secret, "TEXT"); + shaObj.update(clusterId); + salted = shaObj.getHMAC("HEX"); + } + return `v2/${uuid}/${salted}`; }; -const clusterLogin = async (clusterId: string, baseUrl: string, activeSession: Session): Promise<{ user: User, token: string }> => { - const tokenUuid = await getTokenUuid(activeSession.baseUrl, activeSession.token); - const saltedToken = getSaltedToken(clusterId, tokenUuid, activeSession.token); - const user = await getUserDetails(baseUrl, saltedToken); +export const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active); + +export const validateCluster = async (info: RemoteHostInfo, useToken: string): + Promise<{ user: User; token: string }> => { + + const saltedToken = getSaltedToken(info.clusterId, useToken); + const user = await getUserDetails(info.baseUrl, saltedToken); return { user: { firstName: user.first_name, @@ -92,41 +117,56 @@ const clusterLogin = async (clusterId: string, baseUrl: string, activeSession: S ownerUuid: user.owner_uuid, email: user.email, isAdmin: user.is_admin, - identityUrl: user.identity_url, + isActive: user.is_active, + username: user.username, prefs: user.prefs }, - token: saltedToken + token: saltedToken, }; }; -const getActiveSession = (sessions: Session[]): Session | undefined => sessions.find(s => s.active); - -export const validateCluster = async (remoteHost: string, clusterId: string, activeSession: Session): Promise<{ user: User; token: string, baseUrl: string }> => { - const baseUrl = await getRemoteHostBaseUrl(remoteHost); - if (!baseUrl) { - return Promise.reject(`Could not find base url for ${remoteHost}`); - } - const { user, token } = await clusterLogin(clusterId, baseUrl, activeSession); - return { baseUrl, user, token }; -}; - export const validateSession = (session: Session, activeSession: Session) => async (dispatch: Dispatch): Promise => { dispatch(authActions.UPDATE_SESSION({ ...session, status: SessionStatus.BEING_VALIDATED })); session.loggedIn = false; - try { - const { baseUrl, user, token } = await validateCluster(session.remoteHost, session.clusterId, activeSession); + + const setupSession = (baseUrl: string, user: User, token: string) => { session.baseUrl = baseUrl; session.token = token; session.email = user.email; - session.username = getUserFullname(user); + session.uuid = user.uuid; + session.name = getUserFullname(user); session.loggedIn = true; - } catch { - session.loggedIn = false; - } finally { - session.status = SessionStatus.VALIDATED; - dispatch(authActions.UPDATE_SESSION(session)); + }; + + let fail: Error | null = null; + const info = await getRemoteHostInfo(session.remoteHost); + if (info !== null) { + try { + const { user, token } = await validateCluster(info, session.token); + setupSession(info.baseUrl, user, token); + } catch (e) { + fail = new Error(`Getting current user for ${session.remoteHost}: ${e.message}`); + try { + const { user, token } = await validateCluster(info, activeSession.token); + setupSession(info.baseUrl, user, token); + fail = null; + } catch (e2) { + if (e.message === invalidV2Token) { + fail = new Error(`Getting current user for ${session.remoteHost}: ${e2.message}`); + } + } + } + } else { + fail = new Error(`Could not get config for ${session.remoteHost}`); } + session.status = SessionStatus.VALIDATED; + dispatch(authActions.UPDATE_SESSION(session)); + + if (fail) { + throw fail; + } + return session; }; @@ -138,7 +178,23 @@ export const validateSessions = () => dispatch(progressIndicatorActions.START_WORKING("sessionsValidation")); for (const session of sessions) { if (session.status === SessionStatus.INVALIDATED) { - await dispatch(validateSession(session, activeSession)); + try { + /* Here we are dispatching a function, not an + action. This is legal (it calls the + function with a 'Dispatch' object as the + first parameter) but the typescript + annotations don't understand this case, so + we get an error from typescript unless + override it using Dispatch. This + pattern is used in a bunch of different + places in Workbench2. */ + await dispatch(validateSession(session, activeSession)); + } catch (e) { + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: e.message, + kind: SnackbarKind.ERROR + })); + } } } services.authService.saveSessions(sessions); @@ -146,54 +202,93 @@ export const validateSessions = () => } }; -export const addSession = (remoteHost: string) => +export const addSession = (remoteHost: string, token?: string, sendToLogin?: boolean) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { const sessions = getState().auth.sessions; const activeSession = getActiveSession(sessions); - if (activeSession) { - const clusterId = remoteHost.match(/^(\w+)\./)![1]; - if (sessions.find(s => s.clusterId === clusterId)) { - return Promise.reject("Cluster already exists"); + let useToken: string | null = null; + if (token) { + useToken = token; + } else if (activeSession) { + useToken = activeSession.token; + } + + if (useToken) { + const info = await getRemoteHostInfo(remoteHost); + if (!info) { + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: `Could not get config for ${remoteHost}`, + kind: SnackbarKind.ERROR + })); + return; } + try { - const { baseUrl, user, token } = await validateCluster(remoteHost, clusterId, activeSession); + const { user, token } = await validateCluster(info, useToken); const session = { loggedIn: true, status: SessionStatus.VALIDATED, active: false, email: user.email, - username: getUserFullname(user), + name: getUserFullname(user), + uuid: user.uuid, + baseUrl: info.baseUrl, + clusterId: info.clusterId, remoteHost, - baseUrl, - clusterId, token }; - dispatch(authActions.ADD_SESSION(session)); + if (sessions.find(s => s.clusterId === info.clusterId)) { + dispatch(authActions.UPDATE_SESSION(session)); + } else { + dispatch(authActions.ADD_SESSION(session)); + } services.authService.saveSessions(getState().auth.sessions); return session; - } catch (e) { + } catch { + if (sendToLogin) { + const rootUrl = new URL(info.baseUrl); + rootUrl.pathname = ""; + window.location.href = `${rootUrl.toString()}/login?return_to=` + encodeURI(`${window.location.protocol}//${window.location.host}/add-session?baseURL=` + encodeURI(rootUrl.toString())); + return; + } } } - return Promise.reject("Could not validate cluster"); + return Promise.reject(new Error("Could not validate cluster")); }; -export const toggleSession = (session: Session) => + +export const removeSession = (clusterId: string) => async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { - let s = { ...session }; + await dispatch(authActions.REMOVE_SESSION(clusterId)); + services.authService.saveSessions(getState().auth.sessions); + }; + +export const toggleSession = (session: Session) => + async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => { + const s: Session = { ...session }; if (session.loggedIn) { s.loggedIn = false; + dispatch(authActions.UPDATE_SESSION(s)); } else { const sessions = getState().auth.sessions; const activeSession = getActiveSession(sessions); if (activeSession) { - s = await dispatch(validateSession(s, activeSession)) as Session; + try { + await dispatch(validateSession(s, activeSession)); + } catch (e) { + dispatch(snackbarActions.OPEN_SNACKBAR({ + message: e.message, + kind: SnackbarKind.ERROR + })); + s.loggedIn = false; + dispatch(authActions.UPDATE_SESSION(s)); + } } } - dispatch(authActions.UPDATE_SESSION(s)); services.authService.saveSessions(getState().auth.sessions); }; @@ -202,6 +297,7 @@ export const initSessions = (authService: AuthService, config: Config, user: Use const sessions = authService.buildSessions(config, user); authService.saveSessions(sessions); dispatch(authActions.SET_SESSIONS(sessions)); + dispatch(validateSessions()); }; export const loadSiteManagerPanel = () =>