11454: When adding a uuid prefix on the add session box, append
[arvados.git] / apps / workbench / app / assets / javascripts / models / session_db.js
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 window.SessionDB = function() {
6     var db = this
7     Object.assign(db, {
8         discoveryCache: {},
9         tokenUUIDCache: null,
10         loadFromLocalStorage: function() {
11             try {
12                 return JSON.parse(window.localStorage.getItem('sessions')) || {}
13             } catch(e) {}
14             return {}
15         },
16         loadAll: function() {
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
21             }
22             return all
23         },
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))
28                     delete sessions[key]
29             })
30             return sessions
31         },
32         loadLocal: function() {
33             var sessions = db.loadActive()
34             var s = false
35             Object.values(sessions).forEach(function(session) {
36                 if (session.isFromRails) {
37                     s = session
38                     return
39                 }
40             })
41             return s
42         },
43         save: function(k, v) {
44             var sessions = db.loadAll()
45             sessions[k] = v
46             Object.keys(sessions).forEach(function(key) {
47                 if (sessions[key].isFromRails)
48                     delete sessions[key]
49             })
50             window.localStorage.setItem('sessions', JSON.stringify(sessions))
51         },
52         trash: function(k) {
53             var sessions = db.loadAll()
54             delete sessions[k]
55             window.localStorage.setItem('sessions', JSON.stringify(sessions))
56         },
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
60             // use:
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
66             url = new URL(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) {
73                     if (!resp.apiBaseURL)
74                         throw 'no apiBaseURL in status response'
75                     return resp.apiBaseURL
76                 })
77             })
78         },
79         login: function(baseURL, fallbackLogin = true) {
80             // Initiate login procedure with given API base URL (e.g.,
81             // "http://api.example/").
82             //
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
86             // completed.
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', {
96                             headers: {
97                                 authorization: 'Bearer '+token,
98                             },
99                         }).then(function(user) {
100                             var remoteSession = {
101                                 user: user,
102                                 baseURL: baseURL,
103                                 token: token
104                             }
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})
111                         })
112                     })
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))
117                 }
118             })
119             return false
120         },
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
124             // host again.
125             var sessions = db.loadAll()
126             delete sessions[k].token
127             db.save(k, sessions[k])
128         },
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
139             })
140         },
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] != '?')
146                 return
147             var params = {}
148             document.location.search.slice(1).split('&').map(function(kv) {
149                 var e = kv.indexOf('=')
150                 if (e < 0)
151                     return
152                 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1))
153             })
154             if (!params.baseURL || !params.api_token)
155                 // Have a query string, but it's not a login callback.
156                 return
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)
161         },
162         fillMissingUUIDs: function() {
163             var sessions = db.loadAll()
164             Object.keys(sessions).map(function(key) {
165                 if (key.indexOf('://') < 0)
166                     return
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', {
171                     headers: {
172                         authorization: 'OAuth2 '+session.token,
173                     },
174                 }).then(function(user) {
175                     session.user = user
176                     db.save(user.owner_uuid.slice(0, 5), session)
177                     db.trash(key)
178                 })
179             })
180         },
181         // Return the Workbench base URL advertised by the session's
182         // API server, or a reasonable guess, or (if neither strategy
183         // works out) null.
184         workbenchBaseURL: function(session) {
185             var dd = db.discoveryDoc(session)()
186             if (!dd)
187                 // Don't fall back to guessing until we receive the discovery doc
188                 return null
189             if (dd.workbenchUrl)
190                 return dd.workbenchUrl
191             // Guess workbench.{apihostport} is a Workbench... unless
192             // the host part of apihostport is an IPv4 or [IPv6]
193             // address.
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
198             }
199             return null
200         },
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]
205             if (!cache) {
206                 db.discoveryCache[session.baseURL] = cache = m.stream()
207                 m.request(session.baseURL+'discovery/v1/apis/arvados/v1/rest').then(cache)
208             }
209             return cache
210         },
211         // Return a promise with the local session token's UUID from the API server.
212         tokenUUID: function() {
213             var cache = db.tokenUUIDCache
214             if (!cache) {
215                 var session = db.loadLocal()
216                 return db.request(session, '/arvados/v1/api_client_authorizations', {
217                     data: {
218                         filters: JSON.stringify([['api_token', '=', session.token]]),
219                     }
220                 }).then(function(resp) {
221                     var uuid = resp.items[0].uuid
222                     db.tokenUUIDCache = uuid
223                     return uuid
224                 })
225             } else {
226                 return new Promise(function(resolve, reject) {
227                     resolve(cache)
228                 })
229             }
230         },
231         request: function(session, path, opts) {
232             opts = opts || {}
233             opts.headers = opts.headers || {}
234             opts.headers.authorization = 'OAuth2 '+ session.token
235             return m.request(session.baseURL + path, opts)
236         },
237         // Check non-federated remote active sessions if they should be migrated to
238         // a salted token.
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)
246                 }
247             })
248         },
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)
259                         })
260                     }
261                 })
262             })
263         },
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)) {
275                 return
276             }
277             var doc = db.discoveryDoc(session)
278             doc.map(function(d) {
279                 // Guess the remote host from the local discovery doc settings
280                 var rHost = null
281                 if (d.remoteHosts[userUUIDPrefix]) {
282                     rHost = d.remoteHosts[userUUIDPrefix]
283                 } else if (d.remoteHostsViaDNS) {
284                     rHost = userUUIDPrefix + '.arvadosapi.com'
285                 } else {
286                     // This should not happen: having remote user whose uuid prefix
287                     // isn't listed on remoteHosts and dns mechanism is deactivated
288                     return
289                 }
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
295                     })
296                 })
297             })
298         },
299     })
300 }