Merge branch 'master' into 13804-no-shutdown-wanted-nodes
[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             });
31             return sessions;
32         },
33         loadLocal: function() {
34             var sessions = db.loadActive();
35             var s = false;
36             Object.keys(sessions).forEach(function(key) {
37                 if (sessions[key].isFromRails) {
38                     s = sessions[key];
39                     return;
40                 }
41             });
42             return s;
43         },
44         save: function(k, v) {
45             var sessions = db.loadAll();
46             sessions[k] = v;
47             Object.keys(sessions).forEach(function(key) {
48                 if (sessions[key].isFromRails) {
49                     delete sessions[key];
50                 }
51             });
52             window.localStorage.setItem('sessions', JSON.stringify(sessions));
53         },
54         trash: function(k) {
55             var sessions = db.loadAll();
56             delete sessions[k];
57             window.localStorage.setItem('sessions', JSON.stringify(sessions));
58         },
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
62             // use:
63             // sessionDB.findAPI('https://workbench.example/foo').then(sessionDB.login)
64             if (url.length === 5 && url.indexOf('.') < 0) {
65                 url += '.arvadosapi.com';
66             }
67             if (url.indexOf('://') < 0) {
68                 url = 'https://' + url;
69             }
70             url = new URL(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';
79                     }
80                     return resp.apiBaseURL;
81                 });
82             });
83         },
84         login: function(baseURL, fallbackLogin) {
85             // Initiate login procedure with given API base URL (e.g.,
86             // "http://api.example/").
87             //
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
91             // completed.
92             if (fallbackLogin === undefined) {
93                 fallbackLogin = true;
94             }
95             var session = db.loadLocal();
96             var apiHostname = new URL(session.baseURL).hostname;
97             db.discoveryDoc(session).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', {
105                                 headers: {
106                                     authorization: 'Bearer '+token
107                                 }
108                             }).then(function(user) {
109                                 // Federated login successful.
110                                 var remoteSession = {
111                                     user: user,
112                                     baseURL: baseURL,
113                                     token: token,
114                                     listedHost: (dd.uuidPrefix in localDD.remoteHosts)
115                                 };
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 = {
123                                         baseURL: baseURL,
124                                         listedHost: true
125                                     };
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);
131                                 }
132                             });
133                         });
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);
138                     }
139                 });
140             });
141             return false;
142         },
143         loginClassic: function(baseURL) {
144             document.location = baseURL + 'login?return_to=' + encodeURIComponent(document.location.href.replace(/\?.*/, '')+'?baseURL='+encodeURIComponent(baseURL));
145         },
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
149             // host again.
150             var sessions = db.loadAll();
151             delete sessions[k].token;
152             db.save(k, sessions[k]);
153         },
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;
164             });
165         },
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; }
171             var params = {};
172             document.location.search.slice(1).split('&').map(function(kv) {
173                 var e = kv.indexOf('=');
174                 if (e < 0) {
175                     return;
176                 }
177                 params[decodeURIComponent(kv.slice(0, e))] = decodeURIComponent(kv.slice(e+1));
178             });
179             if (!params.baseURL || !params.api_token) {
180                 // Have a query string, but it's not a login callback.
181                 return;
182             }
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);
187         },
188         fillMissingUUIDs: function() {
189             var sessions = db.loadAll();
190             Object.keys(sessions).map(function(key) {
191                 if (key.indexOf('://') < 0) {
192                     return;
193                 }
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', {
198                     headers: {
199                         authorization: 'OAuth2 '+session.token
200                     }
201                 }).then(function(user) {
202                     session.user = user;
203                     db.save(user.owner_uuid.slice(0, 5), session);
204                     db.trash(key);
205                 });
206             });
207         },
208         // Return the Workbench base URL advertised by the session's
209         // API server, or a reasonable guess, or (if neither strategy
210         // works out) null.
211         workbenchBaseURL: function(session) {
212             var dd = db.discoveryDoc(session)();
213             if (!dd) {
214                 // Don't fall back to guessing until we receive the discovery doc
215                 return null;
216             }
217             if (dd.workbenchUrl) {
218                 return dd.workbenchUrl;
219             }
220             // Guess workbench.{apihostport} is a Workbench... unless
221             // the host part of apihostport is an IPv4 or [IPv6]
222             // address.
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;
227             }
228             return null;
229         },
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];
234             if (!cache) {
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;
242                         }
243                         return dd;
244                     })
245                     .then(cache);
246             }
247             return cache;
248         },
249         // Return a promise with the local session token's UUID from the API server.
250         tokenUUID: function() {
251             var cache = db.tokenUUIDCache;
252             if (!cache) {
253                 var session = db.loadLocal();
254                 return db.request(session, '/arvados/v1/api_client_authorizations', {
255                     data: {
256                         filters: JSON.stringify([['api_token', '=', session.token]])
257                     }
258                 }).then(function(resp) {
259                     var uuid = resp.items[0].uuid;
260                     db.tokenUUIDCache = uuid;
261                     return uuid;
262                 });
263             } else {
264                 return new Promise(function(resolve, reject) {
265                     resolve(cache);
266                 });
267             }
268         },
269         request: function(session, path, opts) {
270             opts = opts || {};
271             opts.headers = opts.headers || {};
272             opts.headers.authorization = 'OAuth2 '+ session.token;
273             return m.request(session.baseURL + path, opts);
274         },
275         // Check non-federated remote active sessions if they should be migrated to
276         // a salted token.
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);
286                         }
287                     });
288                 }
289             });
290         },
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);
301                         });
302                     }
303                 });
304             });
305         },
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) {
313             path = 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)) {
318                 return;
319             }
320             db.discoveryDoc(session).map(function (d) {
321                 // Guess the remote host from the local discovery doc settings
322                 var rHost = null;
323                 if (d.remoteHosts[userUUIDPrefix]) {
324                     rHost = d.remoteHosts[userUUIDPrefix];
325                 } else if (d.remoteHostsViaDNS) {
326                     rHost = userUUIDPrefix + '.arvadosapi.com';
327                 } else {
328                     // This should not happen: having remote user whose uuid prefix
329                     // isn't listed on remoteHosts and dns mechanism is deactivated
330                     return;
331                 }
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;
336                     });
337                 });
338             });
339         }
340     });
341 };