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 db.discoveryDoc({baseURL: url.origin}).map(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 apiHostname = new URL(session.baseURL).hostname;
97 db.discoveryDoc({baseURL: session.baseURL}).map(function(localDD) {
98 var uuidPrefix = localDD.uuidPrefix;
99 db.discoveryDoc({baseURL: baseURL}).map(function(dd) {
100 if (uuidPrefix in dd.remoteHosts ||
101 (dd.remoteHostsViaDNS && apiHostname.endsWith('.arvadosapi.com'))) {
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')
237 .then(function (dd) {
238 // Just in case we're talking with an old API server.
239 dd.remoteHosts = dd.remoteHosts || {};
240 if (dd.remoteHostsViaDNS === undefined) {
241 dd.remoteHostsViaDNS = false;
249 // Return a promise with the local session token's UUID from the API server.
250 tokenUUID: function() {
251 var cache = db.tokenUUIDCache;
253 var session = db.loadLocal();
254 return db.request(session, '/arvados/v1/api_client_authorizations', {
256 filters: JSON.stringify([['api_token', '=', session.token]])
258 }).then(function(resp) {
259 var uuid = resp.items[0].uuid;
260 db.tokenUUIDCache = uuid;
264 return new Promise(function(resolve, reject) {
269 request: function(session, path, opts) {
271 opts.headers = opts.headers || {};
272 opts.headers.authorization = 'OAuth2 '+ session.token;
273 return m.request(session.baseURL + path, opts);
275 // Check non-federated remote active sessions if they should be migrated to
277 migrateNonFederatedSessions: function() {
278 var sessions = db.loadActive();
279 Object.keys(sessions).map(function(uuidPrefix) {
280 session = sessions[uuidPrefix];
281 if (!session.isFromRails && session.token) {
282 db.saltedToken(uuidPrefix).then(function(saltedToken) {
283 if (session.token != saltedToken) {
284 // Only try the federated login
285 db.login(session.baseURL, false);
291 // If remoteHosts is populated on the local API discovery doc, try to
292 // add any listed missing session.
293 autoLoadRemoteHosts: function() {
294 var sessions = db.loadAll();
295 var doc = db.discoveryDoc(db.loadLocal());
296 doc.map(function(d) {
297 Object.keys(d.remoteHosts).map(function(uuidPrefix) {
298 if (!(sessions[uuidPrefix])) {
299 db.findAPI(d.remoteHosts[uuidPrefix]).then(function(baseURL) {
300 db.login(baseURL, false);
306 // If the current logged in account is from a remote federated cluster,
307 // redirect the user to their home cluster's workbench.
308 // This is meant to avoid confusion when the user clicks through a search
309 // result on the home cluster's multi site search page, landing on the
310 // remote workbench and later trying to do another search by just clicking
311 // on the multi site search button instead of going back with the browser.
312 autoRedirectToHomeCluster: function(path) {
314 var session = db.loadLocal();
315 var userUUIDPrefix = session.user.uuid.slice(0, 5);
316 // If the current user is local to the cluster, do nothing.
317 if (userUUIDPrefix === session.user.owner_uuid.slice(0, 5)) {
320 db.discoveryDoc(session).map(function (d) {
321 // Guess the remote host from the local discovery doc settings
323 if (d.remoteHosts[userUUIDPrefix]) {
324 rHost = d.remoteHosts[userUUIDPrefix];
325 } else if (d.remoteHostsViaDNS) {
326 rHost = userUUIDPrefix + '.arvadosapi.com';
328 // This should not happen: having remote user whose uuid prefix
329 // isn't listed on remoteHosts and dns mechanism is deactivated
332 // Get the remote cluster workbench url & redirect there.
333 db.findAPI(rHost).then(function (apiUrl) {
334 db.discoveryDoc({baseURL: apiUrl}).map(function (d) {
335 document.location = d.workbenchUrl + path;