1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 window.SessionDB = function() {
10 loadFromLocalStorage: function() {
12 return JSON.parse(window.localStorage.getItem('sessions')) || {};
17 var all = db.loadFromLocalStorage();
18 if (window.defaultSession) {
19 window.defaultSession.isFromRails = true;
20 all[window.defaultSession.user.uuid.slice(0, 5)] = window.defaultSession;
24 loadActive: function() {
25 var sessions = db.loadAll();
26 Object.keys(sessions).forEach(function(key) {
27 if (!sessions[key].token || (sessions[key].user && !sessions[key].user.is_active)) {
33 loadLocal: function() {
34 var sessions = db.loadActive();
36 Object.keys(sessions).forEach(function(key) {
37 if (sessions[key].isFromRails) {
44 save: function(k, v) {
45 var sessions = db.loadAll();
47 Object.keys(sessions).forEach(function(key) {
48 if (sessions[key].isFromRails) {
52 window.localStorage.setItem('sessions', JSON.stringify(sessions));
55 var sessions = db.loadAll();
57 window.localStorage.setItem('sessions', JSON.stringify(sessions));
59 findAPI: function(url) {
60 // Given a Workbench or API host or URL, return a promise
61 // for the corresponding API server's base URL. Typical
63 // sessionDB.findAPI('https://workbench.example/foo').then(sessionDB.login)
64 if (url.length === 5 && url.indexOf('.') < 0) {
65 url += '.arvadosapi.com';
67 if (url.indexOf('://') < 0) {
68 url = 'https://' + url;
71 return m.request(url.origin + '/discovery/v1/apis/arvados/v1/rest').then(function() {
72 return url.origin + '/';
73 }).catch(function(err) {
74 // If url is a Workbench site (and isn't too old),
75 // /status.json will tell us its API host.
76 return m.request(url.origin + '/status.json').then(function(resp) {
77 if (!resp.apiBaseURL) {
78 throw 'no apiBaseURL in status response';
80 return resp.apiBaseURL;
84 login: function(baseURL, fallbackLogin) {
85 // Initiate login procedure with given API base URL (e.g.,
86 // "http://api.example/").
88 // Any page that has a button that invokes login() must
89 // also call checkForNewToken() on (at least) its first
90 // render. Otherwise, the login procedure can't be
92 if (fallbackLogin === undefined) {
95 var session = db.loadLocal();
96 var uuidPrefix = session.user.owner_uuid.slice(0, 5);
97 var apiHostname = new URL(session.baseURL).hostname;
98 m.request(session.baseURL+'discovery/v1/apis/arvados/v1/rest').then(function(localDD) {
99 m.request(baseURL+'discovery/v1/apis/arvados/v1/rest').then(function(dd) {
100 if (uuidPrefix in dd.remoteHosts ||
101 (dd.remoteHostsViaDNS && apiHostname.indexOf('arvadosapi.com') >= 0)) {
102 // Federated identity login via salted token
103 db.saltedToken(dd.uuidPrefix).then(function(token) {
104 m.request(baseURL+'arvados/v1/users/current', {
106 authorization: 'Bearer '+token
108 }).then(function(user) {
109 // Federated login successful.
110 var remoteSession = {
114 listedHost: (dd.uuidPrefix in localDD.remoteHosts)
116 db.save(dd.uuidPrefix, remoteSession);
117 }).catch(function(e) {
118 if (dd.uuidPrefix in localDD.remoteHosts) {
119 // If the remote system is configured to allow federated
120 // logins from this cluster, but rejected the salted
121 // token, save as a logged out session anyways.
122 var remoteSession = {
126 db.save(dd.uuidPrefix, remoteSession);
127 } else if (fallbackLogin) {
128 // Remote cluster not listed as a remote host and rejecting
129 // the salted token, try classic login.
130 db.loginClassic(baseURL);
134 } else if (fallbackLogin) {
135 // Classic login will be used when the remote system doesn't list this
136 // cluster as part of the federation.
137 db.loginClassic(baseURL);
143 loginClassic: function(baseURL) {
144 document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href.replace(/\?.*/, '')+'?baseURL='+encodeURIComponent(baseURL));
146 logout: function(k) {
147 // Forget the token, but leave the other info in the db so
148 // the user can log in again without providing the login
150 var sessions = db.loadAll();
151 delete sessions[k].token;
152 db.save(k, sessions[k]);
154 saltedToken: function(uuid_prefix) {
155 // Takes a cluster UUID prefix and returns a salted token to allow
156 // log into said cluster using federated identity.
157 var session = db.loadLocal();
158 return db.tokenUUID().then(function(token_uuid) {
159 var shaObj = new jsSHA("SHA-1", "TEXT");
160 shaObj.setHMACKey(session.token, "TEXT");
161 shaObj.update(uuid_prefix);
162 var hmac = shaObj.getHMAC("HEX");
163 return 'v2/' + token_uuid + '/' + hmac;
166 checkForNewToken: function() {
167 // If there's a token and baseURL in the location bar (i.e.,
168 // we just landed here after a successful login), save it and
169 // scrub the location bar.
170 if (document.location.search[0] != '?') { return; }
172 document.location.search.slice(1).split('&').map(function(kv) {
173 var e = kv.indexOf('=');
177 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1));
179 if (!params.baseURL || !params.api_token) {
180 // Have a query string, but it's not a login callback.
183 params.token = params.api_token;
184 delete params.api_token;
185 db.save(params.baseURL, params);
186 history.replaceState({}, '', document.location.origin + document.location.pathname);
188 fillMissingUUIDs: function() {
189 var sessions = db.loadAll();
190 Object.keys(sessions).map(function(key) {
191 if (key.indexOf('://') < 0) {
194 // key is the baseURL placeholder. We need to get our user
195 // record to find out the cluster's real uuid prefix.
196 var session = sessions[key];
197 m.request(session.baseURL+'arvados/v1/users/current', {
199 authorization: 'OAuth2 '+session.token
201 }).then(function(user) {
203 db.save(user.owner_uuid.slice(0, 5), session);
208 // Return the Workbench base URL advertised by the session's
209 // API server, or a reasonable guess, or (if neither strategy
211 workbenchBaseURL: function(session) {
212 var dd = db.discoveryDoc(session)();
214 // Don't fall back to guessing until we receive the discovery doc
217 if (dd.workbenchUrl) {
218 return dd.workbenchUrl;
220 // Guess workbench.{apihostport} is a Workbench... unless
221 // the host part of apihostport is an IPv4 or [IPv6]
223 if (!session.baseURL.match('://(\\[|\\d+\\.\\d+\\.\\d+\\.\\d+[:/])')) {
224 var wbUrl = session.baseURL.replace('://', '://workbench.');
225 // Remove the trailing slash, if it's there.
226 return wbUrl.slice(-1) === '/' ? wbUrl.slice(0, -1) : wbUrl;
230 // Return a m.stream that will get fulfilled with the
231 // discovery doc from a session's API server.
232 discoveryDoc: function(session) {
233 var cache = db.discoveryCache[session.baseURL];
235 db.discoveryCache[session.baseURL] = cache = m.stream();
236 m.request(session.baseURL+'discovery/v1/apis/arvados/v1/rest').then(cache);
240 // Return a promise with the local session token's UUID from the API server.
241 tokenUUID: function() {
242 var cache = db.tokenUUIDCache;
244 var session = db.loadLocal();
245 return db.request(session, '/arvados/v1/api_client_authorizations', {
247 filters: JSON.stringify([['api_token', '=', session.token]])
249 }).then(function(resp) {
250 var uuid = resp.items[0].uuid;
251 db.tokenUUIDCache = uuid;
255 return new Promise(function(resolve, reject) {
260 request: function(session, path, opts) {
262 opts.headers = opts.headers || {};
263 opts.headers.authorization = 'OAuth2 '+ session.token;
264 return m.request(session.baseURL + path, opts);
266 // Check non-federated remote active sessions if they should be migrated to
268 migrateNonFederatedSessions: function() {
269 var sessions = db.loadActive();
270 Object.keys(sessions).map(function(uuidPrefix) {
271 session = sessions[uuidPrefix];
272 if (!session.isFromRails && session.token && session.token.indexOf('v2/') < 0) {
273 // Only try the federated login
274 db.login(session.baseURL, false);
278 // If remoteHosts is listed on the local API discovery doc, try to add any
279 // listed remote without an active session.
280 autoLoadRemoteHosts: function() {
281 var activeSessions = db.loadActive();
282 var doc = db.discoveryDoc(db.loadLocal());
283 doc.map(function(d) {
284 Object.keys(d.remoteHosts).map(function(uuidPrefix) {
285 if (!(uuidPrefix in Object.keys(activeSessions))) {
286 db.findAPI(d.remoteHosts[uuidPrefix]).then(function(baseURL) {
287 db.login(baseURL, false);
293 // If the current logged in account is from a remote federated cluster,
294 // redirect the user to their home cluster's workbench.
295 // This is meant to avoid confusion when the user clicks through a search
296 // result on the home cluster's multi site search page, landing on the
297 // remote workbench and later trying to do another search by just clicking
298 // on the multi site search button instead of going back with the browser.
299 autoRedirectToHomeCluster: function(path) {
301 var session = db.loadLocal();
302 var userUUIDPrefix = session.user.uuid.slice(0, 5);
303 // If the current user is local to the cluster, do nothing.
304 if (userUUIDPrefix === session.user.owner_uuid.slice(0, 5)) {
307 var doc = db.discoveryDoc(session);
308 doc.map(function(d) {
309 // Guess the remote host from the local discovery doc settings
311 if (d.remoteHosts[userUUIDPrefix]) {
312 rHost = d.remoteHosts[userUUIDPrefix];
313 } else if (d.remoteHostsViaDNS) {
314 rHost = userUUIDPrefix + '.arvadosapi.com';
316 // This should not happen: having remote user whose uuid prefix
317 // isn't listed on remoteHosts and dns mechanism is deactivated
320 // Get the remote cluster workbench url & redirect there.
321 db.findAPI(rHost).then(function (apiUrl) {
322 var doc = db.discoveryDoc({baseURL: apiUrl});
323 doc.map(function (d) {
324 document.location = d.workbenchUrl + path;