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))
32 loadLocal: function() {
33 var sessions = db.loadActive()
35 Object.values(sessions).forEach(function(session) {
36 if (session.isFromRails) {
43 save: function(k, v) {
44 var sessions = db.loadAll()
46 Object.keys(sessions).forEach(function(key) {
47 if (sessions[key].isFromRails)
50 window.localStorage.setItem('sessions', JSON.stringify(sessions))
53 var sessions = db.loadAll()
55 window.localStorage.setItem('sessions', JSON.stringify(sessions))
57 findAPI: function(url) {
58 // Given a Workbench or API host or URL, return a promise
59 // for the corresponding API server's base URL. Typical
61 // sessionDB.findAPI('https://workbench.example/foo').then(sessionDB.login)
62 if (url.length === 5 && url.indexOf('.') < 0)
63 url += '.arvadosapi.com'
64 if (url.indexOf('://') < 0)
65 url = 'https://' + url
67 return m.request(url.origin + '/discovery/v1/apis/arvados/v1/rest').then(function() {
68 return url.origin + '/'
69 }).catch(function(err) {
70 // If url is a Workbench site (and isn't too old),
71 // /status.json will tell us its API host.
72 return m.request(url.origin + '/status.json').then(function(resp) {
74 throw 'no apiBaseURL in status response'
75 return resp.apiBaseURL
79 login: function(baseURL, fallbackLogin = true) {
80 // Initiate login procedure with given API base URL (e.g.,
81 // "http://api.example/").
83 // Any page that has a button that invokes login() must
84 // also call checkForNewToken() on (at least) its first
85 // render. Otherwise, the login procedure can't be
87 var session = db.loadLocal()
88 var uuidPrefix = session.user.owner_uuid.slice(0, 5)
89 var apiHostname = new URL(session.baseURL).hostname
90 m.request(baseURL+'discovery/v1/apis/arvados/v1/rest').then(function(dd) {
91 if (uuidPrefix in dd.remoteHosts ||
92 (dd.remoteHostsViaDNS && apiHostname.indexOf('arvadosapi.com') >= 0)) {
93 // Federated identity login via salted token
94 db.saltedToken(dd.uuidPrefix).then(function(token) {
95 m.request(baseURL+'arvados/v1/users/current', {
97 authorization: 'Bearer '+token,
99 }).then(function(user) {
100 var remoteSession = {
105 db.save(dd.uuidPrefix, remoteSession)
106 }).catch(function(e) {
107 // If the remote system is configured to allow federated
108 // logins from this cluster, but rejected the salted
109 // token, save as a logged out session anyways.
110 db.save(dd.uuidPrefix, {baseURL: baseURL})
113 } else if (fallbackLogin) {
114 // Classic login will be used when the remote system doesn't list this
115 // cluster as part of the federation.
116 document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href.replace(/\?.*/, '')+'?baseURL='+encodeURIComponent(baseURL))
121 logout: function(k) {
122 // Forget the token, but leave the other info in the db so
123 // the user can log in again without providing the login
125 var sessions = db.loadAll()
126 delete sessions[k].token
127 db.save(k, sessions[k])
129 saltedToken: function(uuid_prefix) {
130 // Takes a cluster UUID prefix and returns a salted token to allow
131 // log into said cluster using federated identity.
132 var session = db.loadLocal()
133 return db.tokenUUID().then(function(token_uuid){
134 var shaObj = new jsSHA("SHA-1", "TEXT")
135 shaObj.setHMACKey(session.token, "TEXT")
136 shaObj.update(uuid_prefix)
137 var hmac = shaObj.getHMAC("HEX")
138 return 'v2/' + token_uuid + '/' + hmac
141 checkForNewToken: function() {
142 // If there's a token and baseURL in the location bar (i.e.,
143 // we just landed here after a successful login), save it and
144 // scrub the location bar.
145 if (document.location.search[0] != '?')
148 document.location.search.slice(1).split('&').map(function(kv) {
149 var e = kv.indexOf('=')
152 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1))
154 if (!params.baseURL || !params.api_token)
155 // Have a query string, but it's not a login callback.
157 params.token = params.api_token
158 delete params.api_token
159 db.save(params.baseURL, params)
160 history.replaceState({}, '', document.location.origin + document.location.pathname)
162 fillMissingUUIDs: function() {
163 var sessions = db.loadAll()
164 Object.keys(sessions).map(function(key) {
165 if (key.indexOf('://') < 0)
167 // key is the baseURL placeholder. We need to get our user
168 // record to find out the cluster's real uuid prefix.
169 var session = sessions[key]
170 m.request(session.baseURL+'arvados/v1/users/current', {
172 authorization: 'OAuth2 '+session.token,
174 }).then(function(user) {
176 db.save(user.owner_uuid.slice(0, 5), session)
181 // Return the Workbench base URL advertised by the session's
182 // API server, or a reasonable guess, or (if neither strategy
184 workbenchBaseURL: function(session) {
185 var dd = db.discoveryDoc(session)()
187 // Don't fall back to guessing until we receive the discovery doc
190 return dd.workbenchUrl
191 // Guess workbench.{apihostport} is a Workbench... unless
192 // the host part of apihostport is an IPv4 or [IPv6]
194 if (!session.baseURL.match('://(\\[|\\d+\\.\\d+\\.\\d+\\.\\d+[:/])')) {
195 var wbUrl = session.baseURL.replace('://', '://workbench.')
196 // Remove the trailing slash, if it's there.
197 return wbUrl.slice(-1) == '/' ? wbUrl.slice(0, -1) : wbUrl
201 // Return a m.stream that will get fulfilled with the
202 // discovery doc from a session's API server.
203 discoveryDoc: function(session) {
204 var cache = db.discoveryCache[session.baseURL]
206 db.discoveryCache[session.baseURL] = cache = m.stream()
207 m.request(session.baseURL+'discovery/v1/apis/arvados/v1/rest').then(cache)
211 // Return a promise with the local session token's UUID from the API server.
212 tokenUUID: function() {
213 var cache = db.tokenUUIDCache
215 var session = db.loadLocal()
216 return db.request(session, '/arvados/v1/api_client_authorizations', {
218 filters: JSON.stringify([['api_token', '=', session.token]]),
220 }).then(function(resp) {
221 var uuid = resp.items[0].uuid
222 db.tokenUUIDCache = uuid
226 return new Promise(function(resolve, reject) {
231 request: function(session, path, opts) {
233 opts.headers = opts.headers || {}
234 opts.headers.authorization = 'OAuth2 '+ session.token
235 return m.request(session.baseURL + path, opts)
237 // Check non-federated remote active sessions if they should be migrated to
239 migrateNonFederatedSessions: function() {
240 var sessions = db.loadActive()
241 Object.keys(sessions).map(function(uuidPrefix) {
242 session = sessions[uuidPrefix]
243 if (!session.isFromRails && session.token && session.token.indexOf('v2/') < 0) {
244 // Only try the federated login
245 db.login(session.baseURL, false)
249 // If remoteHosts is listed on the local API discovery doc, try to add any
250 // listed remote without an active session.
251 autoLoadRemoteHosts: function() {
252 var activeSessions = db.loadActive()
253 var doc = db.discoveryDoc(db.loadLocal())
254 doc.map(function(d) {
255 Object.keys(d.remoteHosts).map(function(uuidPrefix) {
256 if (!(uuidPrefix in Object.keys(activeSessions))) {
257 db.findAPI(d.remoteHosts[uuidPrefix]).then(function(baseURL) {
258 db.login(baseURL, false)
264 // If the current logged in account is from a remote federated cluster,
265 // redirect the user to their home cluster's workbench.
266 // This is meant to avoid confusion when the user clicks through a search
267 // result on the home cluster's multi site search page, landing on the
268 // remote workbench and later trying to do another search by just clicking
269 // on the multi site search button instead of going back with the browser.
270 autoRedirectToHomeCluster: function(path = '/') {
271 var session = db.loadLocal()
272 var userUUIDPrefix = session.user.uuid.slice(0, 5)
273 // If the current user is local to the cluster, do nothing.
274 if (userUUIDPrefix == session.user.owner_uuid.slice(0, 5)) {
277 var doc = db.discoveryDoc(session)
278 doc.map(function(d) {
279 // Guess the remote host from the local discovery doc settings
281 if (d.remoteHosts[userUUIDPrefix]) {
282 rHost = d.remoteHosts[userUUIDPrefix]
283 } else if (d.remoteHostsViaDNS) {
284 rHost = userUUIDPrefix + '.arvadosapi.com'
286 // This should not happen: having remote user whose uuid prefix
287 // isn't listed on remoteHosts and dns mechanism is deactivated
290 // Get the remote cluster workbench url & redirect there.
291 db.findAPI(rHost).then(function(apiUrl) {
292 var doc = db.discoveryDoc({baseURL: apiUrl})
293 doc.map(function(d) {
294 document.location = d.workbenchUrl + path