-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeystone.js
More file actions
565 lines (545 loc) · 18.7 KB
/
Copy pathkeystone.js
File metadata and controls
565 lines (545 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/**
* OpenStack client in Javascript.
* mds900 20150703
*/
// TODO: Restrict the scope of this
"use strict";
/**
* Client for the Identity API ("Keystone")
*/
osclient.Keystone = function(params) {
osclient.Client.apply(this, Array.prototype.slice.call(arguments));
if (arguments.length === 0) {
return; // Probably a subclass initialising its .prototype
}
$.extend(this, params);
if (!this.authURL) {
throw "No authURL supplied";
}
this.apiVersions = {};
this.userCacheByID = {};
this.cacheTenantByID = {};
this.cacheTenantByName = {};
};
osclient.Keystone.prototype = new osclient.Client();
$.extend(osclient.Keystone.prototype, {
/**
* Retrieve a list of available versions of the Identity API.
*/
retrieveVersions: function() {
var keystone = this;
if (!this.apiVersionsDeferred) {
this.apiVersionsDeferred = $.Deferred();
this.doRequest({
// jQuery interprets the HTTP status code 300 Multiple Choices as an error
error: function(jqxhr, status, errorThrown) {
// jqxhr.response is undefined in this error handler
var response;
if (300 === jqxhr.status) {
response = JSON.parse(jqxhr.responseText);
$(response.versions.values).each(function(i, version) {
keystone.apiVersions[version.id] = version;
});
keystone.apiVersionsDeferred.resolve(response);
} else {
keystone.apiVersionsDeferred.reject('Failed to receive expected 300 response');
}
},
url: this.authURL
});
}
return this.apiVersionsDeferred.promise();
},
/**
* Authenticate against an OpenStack Keystone Identity v2.0 service, yielding an authentication token.
*/
authenticatev2_0: function() {
var keystone = this, promise, authPayload = {
"auth": {
"passwordCredentials": {
"username": this.username,
"password": this.password,
}
}
};
if (!this.token && (!this.username || !this.password)) {
throw "Neither username and password nor token supplied";
}
// The tenant name and ID must not both be supplied.
if (this.tenantID) {
authPayload.auth.tenantId = this.tenantID;
} else if (this.tenantName) {
authPayload.auth.tenantName = this.tenantName;
}
promise = this.doRequest({
data: JSON.stringify(authPayload),
method: "POST",
processData: false,
url: this.authURL + "/v2.0/tokens"
}).promise();
promise.done(function(response, jqxhr, status) {
keystone.userID = response.access.user.id;
keystone.token = response.access.token.id;
if (response.access.token.tenant) {
if (response.access.token.tenant.id) {
keystone.tenantID = response.access.token.tenant.id;
}
if (response.access.token.tenant.name) {
keystone.tenantName = response.access.token.tenant.name;
}
}
if (!response.access.serviceCatalog) {
keystone.catalog = response.access.serviceCatalog;
}
});
return promise;
},
/**
* Authenticate against an OpenStack Keystone Identity v3 service, yielding an authentication token.
*/
authenticatev3: function() {
var keystone = this, promise, authPayload = {
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"password": this.password
}
}
}
}
};
if (this.username && this.domainID) {
// The username is unique within the domain with the given ID
authPayload.auth.identity.password.user.name = this.username;
authPayload.auth.identity.password.user.domain = { "id": this.domainID };
} else if (this.username && this.domainName) {
// The username is unique within the named domain
authPayload.auth.identity.password.user.name = this.username;
authPayload.auth.identity.password.user.domain = { "name": this.domainName };
} else if (this.userID) {
// The user ID is globally unique
authPayload.auth.identity.password.user.id = this.userID;
} else if (this.token) {
// No username, but token given
authPayload = {
"auth": {
"identity": {
"methods": [
"token"
],
"token": {
"id": this.token
}
}
}
};
} else {
throw "Neither username and domainID nor userID nor token supplied";
}
promise = this.doRequest({
data: JSON.stringify(authPayload),
method: "POST",
processData: false,
url: this.authURL + "/v3/auth/tokens"
}).promise();
promise.done(function(response, status, jqxhr) {
var newToken = jqxhr.getResponseHeader("X-Subject-Token");
if (newToken) {
keystone.token = newToken;
}
if (response.token.catalog) {
keystone.catalog = response.token.catalog;
}
if (response.token.user) {
if (response.token.user.id) {
keystone.userID = response.token.user.id;
}
}
});
return promise;
},
/**
* Authenticate against one of the available Identity Service API versions,
* if there is not already a valid authentication token.
*
* NOTE: In the 2.0 API, neither the tenant name nor tenant ID is required for authentication,
* but if neither of them is supplied, then the response contains an empty service catalog.
* Also, there does not seem to be a way in the 2.0 API to obtain the service catalog
* other than by authentication (though there is in the 3.0 API).
* Since the catalog is required, we must at some stage authorise with a tenant ID or name.
* But until we have authed, we don't know of any valid tenant IDs or names.
* So we auth without a tenant ID, find at least one valid tenant ID, then auth again with that.
*/
authenticate: function() {
var keystone = this;
if (!keystone.authenticateDeferred) { // cache promise object (promise result always gets cached anyway, i.e. re-calling "then" will call handlers immediately with whatever result has already been obtained)
// chain retrieveVersions promise with another promise returning catalog
keystone.authenticateDeferred = keystone.retrieveVersions().then(function() { // need to chain with "then" rather than "done", otherwise calling d.reject below does not propagate, and state of keystone.authenticateDeferred is "resolved"
var d = $.Deferred();
if ("v3.0" in keystone.apiVersions) {
keystone.authenticatev3().then(function() {
keystone.findIdentityEndpoints();
d.resolve(keystone.catalog);
});
} else if ("v2.0" in keystone.apiVersions) {
keystone.authenticatev2_0().then(function() {
if (keystone.tenantID && keystone.catalog) {
keystone.findIdentityEndpoints();
d.resolve(keystone.catalog);
} else {
// Use the token to obtain a list of accessible tenants
keystone.getTenants().then(function(tenants) {
if (!tenants.length) {
d.reject("No accessible tenants");
}
// Choose the first tenant listed
keystone.setTenantID(tenants[0].id);
// Authenticate again, this time with a tenant ID, to obtain the service catalog
keystone.authenticate2_0().then(function() {
keytone.findIdentityEndpoints();
d.resolve(keystone.catalog);
});
});
}
});
} else {
d.reject("No supported Identity API version found");
}
return d.promise();
});
}
return keystone.authenticateDeferred;
},
/**
* Find the three endpoint URLs for the preferred version of the Identity service.
* The initial endpoint URL we were passed at instantiation time was for
* an unknown one of the three possible endpoints, for an unknown version of the Identity service,
* multiple versions of which may exist simultaneously, with arbitrary types and names.
* (By experiment, as of Icehouse, if there exist two services with the same type then
* corrupt catalogs are served, forcing one to have services types eg "identity" and "identityv3").
* For the version 3 API, this initial URL can be used for all subsequent requests.
* But for the version 2 API, since certain requests need to be sent to certain endpoints,
* we need to know all three of the service's endpoints.
* This requires finding the v2.0 Identity service in the catalog, but we cannot
* search by either name or type, as these are arbitrary and distinct strings.
* Instead, we search the catalog for the initial endpoint we were passed,
* assume that the service containing an endpoint with that URL is the Identity service,
* then remember that service's three endpoints.
*/
findIdentityEndpoints: function() {
var
keystone = this,
findURL, // The URL to look for
foundService // The service that has an endpoint with the found URL
;
if ("v3.0" in keystone.apiVersions) {
findURL = keystone.apiVersions["v3.0"].links[0].href;
} else if ("v2.0" in this.apiVersions) {
findURL = keystone.apiVersions["v2.0"].links[0].href;
} else {
throw "No compatible version of the Identity API found";
}
findURL = findURL.replace(/\/$/, ''); // Strip trailing slash
// Find this URL in the catalog
$(this.catalog).each(function(i, service) {
$(service.endpoints).each(function(i, endpoint) {
$([ "url", "publicURL", "adminURL", "internalURL" ]).each(function(i, attribute) {
if (attribute in endpoint) {
var foundURL = endpoint[attribute].replace(/\/$/, ''); // Strip trailing slash
if (foundURL === findURL) {
foundService = service;
}
}
return !foundService;
});
return !foundService;
});
return !foundService;
});
if (foundService) {
$(foundService.endpoints).each(function(i, endpoint) {
$([ "public", "admin", "internal" ]).each(function(i, endpointType) {
if ((endpointType + "URL") in endpoint) {
keystone[endpointType + "URL"] = endpoint[endpointType + "URL"];
} else if ("url" in endpoint && endpoint.interface === endpointType) {
keystone[endpointType + "URL"] = endpoint.url;
}
});
});
if (!keystone.publicURL || !keystone.adminURL || !keystone.internalURL) {
throw "Missing public, admin or internal URL";
}
} else {
throw "No service found with an endpoint URL equal to '" + findURL + "'";
}
},
/**
* Find an endpoint in the service catalog matching all of the given constraints.
* Possible constraints include:
* serviceType: The type of OpenStack service, for example "compute"
* serviceName: The OpenStack project name, for example "nova"
* regionName: The name of an OpenStack region known to the OpenStack deployment, for example "RegionOne"
* endpointType: The endpoint type, for example "public"
* endpointID: The UUID of the endpoint.
*/
getEndpoint: function(params) {
var keystone = this, foundURL = undefined, parseCatalogDeferred;
parseCatalogDeferred = $.Deferred(function() {
keystone.authenticate().done(function() {
// TODO: version-specific matching based on version response and this catalog response.
$(keystone.catalog).each(function(i, service) {
if (
( !("serviceType" in params) || service.type === params.serviceType )
&& ( !("serviceName" in params) || service.name === params.serviceName )
) {
$(service.endpoints).each(function(i, endpoint) {
// v2.0 API response
if (
( !("regionName" in params) || endpoint.region === params.regionName)
&& ( !("endpointID" in params) || endpoint.id === params.endpointID)
&& ( !("endpointType" in params) || (params.endpointType + "URL") in endpoint)
) {
if ("endpointType" in params) {
foundURL = endpoint[params.endpointType + "URL"];
} else if ("publicURL" in endpoint) {
foundURL = endpoint.publicURL;
} else if ("adminURL" in endpoint) {
foundURL = endpoint.adminURL;
} else if ("internalURL" in endpoint) {
foundURL = endpoint.internalURL;
}
}
if (foundURL !== undefined) {
return false; // Terminate enumeration
}
// v3 API response
if (
( !("regionName" in params) || endpoint.region === params.regionName)
&& ( !("endpointID" in params) || endpoint.id === params.endpointID)
&& ( !("endpointType" in params) || endpoint.interface === params.endpointType)
) {
foundURL = endpoint.url;
}
if (foundURL !== undefined) {
return false; // Terminate enumeration
}
});
if (foundURL !== undefined) {
return false; // Terminate enumeration
}
}
});
if (foundURL) {
parseCatalogDeferred.resolve(foundURL);
}
});
});
return parseCatalogDeferred.promise();
},
/**
* Return the currently-in-use authentication token.
* Intended to be used to pass the token to other OpenStack services later.
*/
getToken: function() {
return this.token;
},
/**
* Clear the current authentication token, so that another token
* will be generated when needed.
* Intended for use when the user or tenant has changed,
* which changes the catalog (since it contains tenant IDs),
* so authentication should be performed anew.
*/
clearToken: function() {
this.token = null;
this.catalog = null;
this.authenticateDeferred = null;
},
/**
* Set the tenant ID. This will cause retrieval of a new catalog when required.
*/
setTenantID: function(newTenantID) {
this.tenantID = newTenantID;
this.tenantName = null;
this.clearToken();
},
setProjectID: function() {
return this.setTenantID.apply(this, arguments);
},
/**
* Set the tenant name. This will cause retrieval of a new catalog when required.
*/
setTenantName: function(newTenantName) {
this.tenantName = newTenantName;
this.tenantID = null;
this.clearToken();
},
setProjectName: function() {
return this.setTenantName.apply(this, arguments);
},
/**
* Retrieve a list of tenants.
* This can be all tenants, or only those accessible via the currently-in-use credentials.
*/
getTenants: function(includeAll, maxResults, startAfter) {
var promise, deferred = $.Deferred(), url, data = {};
// TODO: Accept a generalised params object rather than positional arguments
if ("v3.0" in this.apiVersions) {
url = this.publicURL;
if (includeAll) {
url += "/projects";
if (maxResults) {
data.per_page = maxResults;
}
if (startAfter) {
// FIXME: What is this 'page' parameter?
// Docs say only: "Enables you to page through the list.".
data.page = startAfter;
}
} else if (this.userID) {
url += "/users/" + this.userID + "/projects";
// FIXME: Is there really no way to do paging? Docs say no, but could be wrong.
if (maxResults || startAfter) {
throw "Unsupported option";
}
} else {
throw "Not all tenants requested, and no user ID";
}
} else if ("v2.0" in this.apiVersions) {
// The semantics of this request depend on the endpoint it was sent to
url = (includeAll ? this.adminURL : this.publicURL) + "/tenants";
if (maxResults !== undefined) {
data.limit = maxResults;
}
if (startAfter !== undefined) {
data.marker = startAfter;
}
} else {
throw "No compatible Identity API";
}
promise = this.doRequest({
data: data,
headers: { "X-Auth-Token": this.token },
processData: true,
url: url
}).promise();
promise.done(function(response) {
// Normalise the v2.0/v3 response
if ("tenants" in response) {
deferred.resolve(response.tenants);
} else if ("projects" in response) {
deferred.resolve(response.projects);
}
});
return deferred.promise();
},
getProjects: function() {
return this.getTenants.apply(this, arguments);
},
/**
* Retrieve details of the user with the given ID.
*/
getUserByID: function(userID) {
var url;
if (!this.userCacheByID[userID]) {
if ("v3.0" in this.apiVersions) {
url = this.publicURL;
} else if ("v2.0" in this.apiVersions) {
url = this.adminURL;
} else {
throw "No compatible Identity API";
}
this.userCacheByID[userID] = this.doRequest({
headers: { "X-Auth-Token": this.token },
url: url + '/users/' + userID
}).promise();
}
return this.userCacheByID[userID];
},
/**
* Retrieve details of the given-named user.
*/
getUserByName: function(username) {
// TODO: Cache these requests.
// Problem: User names are only unique within the one domain.
var url;
if ("v3.0" in this.apiVersions) {
url = this.publicURL;
} else if ("v2.0" in this.apiVersions) {
// In API 2.0, this request must go to the 'admin' URL rather than the public one,
// even if the user being enquired about is the user we previously authenticated as.
url = this.adminURL;
} else {
throw "No compatible Identity API";
}
return this.doRequest({
data: { name: username },
headers: { "X-Auth-Token": this.token },
processData: true,
url: this.publicURL + '/users'
}).promise();
},
/**
* Retrieve details of the tenant with the given ID.
* In various places within OpenStack, this entity is also called a "project".
*/
getTenantByID: function(tenantID) {
var url;
if (!this.cacheTenantByID[tenantID]) {
if ("v3.0" in this.apiVersions) {
url = this.publicURL + "/projects";
} else if ("v2.0" in this.apiVersions) {
// In API 2.0, this request must go to the 'admin' URL rather than the public one,
// even if the tenant being enquired about is one to which we have access using
// the user we previously authenticated as.
url = this.adminURL + "/tenants";
} else {
throw "No compatible Identity API";
}
this.cacheTenantByID[tenantID] = this.doRequest({
headers: { "X-Auth-Token": this.token },
// FIXME: Does this request need to go to the 'admin' URL rather than the public one?
url: url + "/" + tenantID
}).promise();
}
return this.cacheTenantByID[tenantID];
},
getProjectByID: function() {
return this.getTenantByID.apply(this, arguments);
},
/**
* Retrieve details of the given-named tenant.
* In various places within OpenStack, this entity is also called a "project".
*/
getTenantByName: function(tenantName) {
var url;
if (!this.cacheTenantByName[tenantName]) {
if ("v3.0" in this.apiVersions) {
url = this.publicURL + "/projects";
} else if ("v2.0" in this.apiVersions) {
// In API 2.0, this request must go to the 'admin' URL rather than the public one,
// even if the tenant being enquired about is one to which we have access using
// the user we previously authenticated as.
url = this.adminURL + "/tenants";
} else {
throw "No compatible Identity API";
}
this.cacheTenantByName[tenantName] = this.doRequest({
data: { name: tenantName },
headers: { "X-Auth-Token": this.token },
processData: true,
// FIXME: Does this request need to go to the 'admin' URL rather than the public one?
url: url
}).promise();
}
return this.cacheTenantByName[tenantName];
},
getProjectByName: function() {
return this.getTenantByName.apply(this, arguments);
}
// TODO: The rest of the Identity API 2.0, Identity admin API 2.0 and Identity API 3
});