11454: (WIP) Login to remote clusters using federated identity.
[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(rhosts) {
6     var db = this
7     Object.assign(db, {
8         remoteHosts: rhosts || [],
9         discoveryCache: {},
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)
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.indexOf('://') < 0)
63                 url = 'https://' + url
64             url = new URL(url)
65             return m.request(url.origin + '/discovery/v1/apis/arvados/v1/rest').then(function() {
66                 return url.origin + '/'
67             }).catch(function(err) {
68                 // If url is a Workbench site (and isn't too old),
69                 // /status.json will tell us its API host.
70                 return m.request(url.origin + '/status.json').then(function(resp) {
71                     if (!resp.apiBaseURL)
72                         throw 'no apiBaseURL in status response'
73                     return resp.apiBaseURL
74                 })
75             })
76         },
77         login: function(baseURL) {
78             // Initiate login procedure with given API base URL (e.g.,
79             // "http://api.example/").
80             //
81             // Any page that has a button that invokes login() must
82             // also call checkForNewToken() on (at least) its first
83             // render. Otherwise, the login procedure can't be
84             // completed.
85             var remoteAPI = new URL(baseURL)
86             db.saltedToken(remoteAPI.hostname.split('.')[0]).then(function(token) {
87                 document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href.replace(/\?.*/, '')+'?baseURL='+encodeURIComponent(baseURL)) + '&api_token='+encodeURIComponent(token)
88             })
89             return false
90         },
91         logout: function(k) {
92             // Forget the token, but leave the other info in the db so
93             // the user can log in again without providing the login
94             // host again.
95             var sessions = db.loadAll()
96             delete sessions[k].token
97             db.save(k, sessions[k])
98         },
99         saltedToken: function(uuid_prefix) {
100             // Takes a cluster UUID prefix and returns a salted token to allow
101             // log into said cluster using federated identity.
102             var session = db.loadLocal()
103             var st = m.stream()
104             return db.request(session, '/arvados/v1/api_client_authorizations', {
105                 data: {
106                     filters: JSON.stringify([['api_token', '=', session.token]]),
107                 }
108             }).then(function(resp) {
109                 if (resp.items.length == 1) {
110                     var token_uuid = resp.items[0].uuid
111                     if (token_uuid.length !== '') {
112                         var shaObj = new jsSHA("SHA-1", "TEXT")
113                         shaObj.setHMACKey(session.token, "TEXT")
114                         shaObj.update(uuid_prefix)
115                         var hmac = shaObj.getHMAC("HEX")
116                         return 'v2/' + token_uuid + '/' + hmac
117                     } else { return null }
118                 }
119             }).catch(function(err) { return null })
120         },
121         checkForNewToken: function() {
122             // If there's a token and baseURL in the location bar (i.e.,
123             // we just landed here after a successful login), save it and
124             // scrub the location bar.
125             if (document.location.search[0] != '?')
126                 return
127             var params = {}
128             document.location.search.slice(1).split('&').map(function(kv) {
129                 var e = kv.indexOf('=')
130                 if (e < 0)
131                     return
132                 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1))
133             })
134             if (!params.baseURL || !params.api_token)
135                 // Have a query string, but it's not a login callback.
136                 return
137             params.token = params.api_token
138             delete params.api_token
139             db.save(params.baseURL, params)
140             history.replaceState({}, '', document.location.origin + document.location.pathname)
141         },
142         fillMissingUUIDs: function() {
143             var sessions = db.loadAll()
144             Object.keys(sessions).map(function(key) {
145                 if (key.indexOf('://') < 0)
146                     return
147                 // key is the baseURL placeholder. We need to get our user
148                 // record to find out the cluster's real uuid prefix.
149                 var session = sessions[key]
150                 m.request(session.baseURL+'arvados/v1/users/current', {
151                     headers: {
152                         authorization: 'OAuth2 '+session.token,
153                     },
154                 }).then(function(user) {
155                     session.user = user
156                     db.save(user.owner_uuid.slice(0, 5), session)
157                     db.trash(key)
158                 })
159             })
160         },
161         // Return the Workbench base URL advertised by the session's
162         // API server, or a reasonable guess, or (if neither strategy
163         // works out) null.
164         workbenchBaseURL: function(session) {
165             var dd = db.discoveryDoc(session)()
166             if (!dd)
167                 // Don't fall back to guessing until we receive the discovery doc
168                 return null
169             if (dd.workbenchUrl)
170                 return dd.workbenchUrl
171             // Guess workbench.{apihostport} is a Workbench... unless
172             // the host part of apihostport is an IPv4 or [IPv6]
173             // address.
174             if (!session.baseURL.match('://(\\[|\\d+\\.\\d+\\.\\d+\\.\\d+[:/])')) {
175                 var wbUrl = session.baseURL.replace('://', '://workbench.')
176                 // Remove the trailing slash, if it's there.
177                 return wbUrl.slice(-1) == '/' ? wbUrl.slice(0, -1) : wbUrl
178             }
179             return null
180         },
181         // Return a m.stream that will get fulfilled with the
182         // discovery doc from a session's API server.
183         discoveryDoc: function(session) {
184             var cache = db.discoveryCache[session.baseURL]
185             if (!cache) {
186                 db.discoveryCache[session.baseURL] = cache = m.stream()
187                 m.request(session.baseURL+'discovery/v1/apis/arvados/v1/rest').then(cache)
188             }
189             return cache
190         },
191         request: function(session, path, opts) {
192             opts = opts || {}
193             opts.headers = opts.headers || {}
194             opts.headers.authorization = 'OAuth2 '+ session.token
195             return m.request(session.baseURL + path, opts)
196         },
197     })
198 }