-
Notifications
You must be signed in to change notification settings - Fork 925
Expand file tree
/
Copy pathopenstack_identity.py
More file actions
2036 lines (1665 loc) · 65.2 KB
/
openstack_identity.py
File metadata and controls
2036 lines (1665 loc) · 65.2 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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Common / shared code for handling authentication against OpenStack identity
service (Keystone).
"""
import datetime
from collections import namedtuple
from libcloud.utils.py3 import httplib
from libcloud.common.base import Response, ConnectionUserAndKey, CertificateConnection
from libcloud.compute.types import LibcloudError, InvalidCredsError, MalformedResponseError
from libcloud.utils.iso8601 import parse_date
try:
import simplejson as json
except ImportError:
import json # type: ignore
AUTH_API_VERSION = "1.1"
AUTH_TOKEN_HEADER = "X-Auth-Token"
# Auth versions which contain token expiration information.
AUTH_VERSIONS_WITH_EXPIRES = [
"1.1",
"2.0",
"2.0_apikey",
"2.0_password",
"2.0_voms",
"3.0",
"3.x_password",
"3.x_appcred",
"3.x_oidc_access_token",
]
# How many seconds to subtract from the auth token expiration time before
# testing if the token is still valid.
# The time is subtracted to account for the HTTP request latency and prevent
# user from getting "InvalidCredsError" if token is about to expire.
AUTH_TOKEN_EXPIRES_GRACE_SECONDS = 5
__all__ = [
"OpenStackAuthenticationCache",
"OpenStackAuthenticationCacheKey",
"OpenStackAuthenticationContext",
"OpenStackIdentityVersion",
"OpenStackIdentityDomain",
"OpenStackIdentityProject",
"OpenStackIdentityUser",
"OpenStackIdentityRole",
"OpenStackServiceCatalog",
"OpenStackServiceCatalogEntry",
"OpenStackServiceCatalogEntryEndpoint",
"OpenStackIdentityEndpointType",
"OpenStackIdentityConnection",
"OpenStackIdentity_1_0_Connection",
"OpenStackIdentity_1_1_Connection",
"OpenStackIdentity_2_0_Connection",
"OpenStackIdentity_2_0_Connection_VOMS",
"OpenStackIdentity_3_0_Connection",
"OpenStackIdentity_3_0_Connection_AppCred",
"OpenStackIdentity_3_0_Connection_OIDC_access_token",
"get_class_for_auth_version",
]
class OpenStackAuthenticationCache:
"""
Base class for external OpenStack authentication caches.
Authentication tokens are always cached in memory in
:class:`OpenStackIdentityConnection`.auth_token and related fields. These
tokens are lost when the driver is garbage collected. To share tokens
among multiple drivers, processes, or systems, use an
:class:`OpenStackAuthenticationCache` in
OpenStackIdentityConnection.auth_cache.
Cache implementers should inherit this class and define the methods below.
"""
def get(self, key):
"""
Get an authentication context from the cache.
:param key: Key to fetch.
:type key: :class:`.OpenStackAuthenticationCacheKey`
:return: The cached context for the given key, if present; None if not.
:rtype: :class:`OpenStackAuthenticationContext`
"""
raise NotImplementedError
def put(self, key, context):
"""
Put an authentication context into the cache.
:param key: Key where the context will be stored.
:type key: :class:`.OpenStackAuthenticationCacheKey`
:param context: The context to cache.
:type context: :class:`.OpenStackAuthenticationContext`
"""
raise NotImplementedError
def clear(self, key):
"""
Clear an authentication context from the cache.
:param key: Key to clear.
:type key: :class:`.OpenStackAuthenticationCacheKey`
"""
raise NotImplementedError
OpenStackAuthenticationCacheKey = namedtuple(
"OpenStackAuthenticationCacheKey",
[
"auth_url",
"user_id",
"token_scope",
"tenant_name",
"domain_name",
"tenant_domain_id",
],
)
class OpenStackAuthenticationContext:
"""
An authentication token and related context.
"""
def __init__(self, token, expiration=None, user=None, roles=None, urls=None):
self.token = token
self.expiration = expiration
self.user = user
self.roles = roles
self.urls = urls
class OpenStackIdentityEndpointType:
"""
Enum class for openstack identity endpoint type.
"""
INTERNAL = "internal"
EXTERNAL = "external"
ADMIN = "admin"
class OpenStackIdentityTokenScope:
"""
Enum class for openstack identity token scope.
"""
PROJECT = "project"
DOMAIN = "domain"
UNSCOPED = "unscoped"
class OpenStackIdentityVersion:
def __init__(self, version, status, updated, url):
self.version = version
self.status = status
self.updated = updated
self.url = url
def __repr__(self):
return "<OpenStackIdentityVersion version=%s, status=%s, " "updated=%s, url=%s>" % (
self.version,
self.status,
self.updated,
self.url,
)
class OpenStackIdentityDomain:
def __init__(self, id, name, enabled):
self.id = id
self.name = name
self.enabled = enabled
def __repr__(self):
return "<OpenStackIdentityDomain id={}, name={}, enabled={}>".format(
self.id,
self.name,
self.enabled,
)
class OpenStackIdentityProject:
def __init__(self, id, name, description, enabled, domain_id=None):
self.id = id
self.name = name
self.description = description
self.enabled = enabled
self.domain_id = domain_id
def __repr__(self):
return "<OpenStackIdentityProject id=%s, domain_id=%s, name=%s, " "enabled=%s>" % (
self.id,
self.domain_id,
self.name,
self.enabled,
)
class OpenStackIdentityRole:
def __init__(self, id, name, description, enabled):
self.id = id
self.name = name
self.description = description
self.enabled = enabled
def __repr__(self):
return "<OpenStackIdentityRole id=%s, name=%s, description=%s, " "enabled=%s>" % (
self.id,
self.name,
self.description,
self.enabled,
)
class OpenStackIdentityUser:
def __init__(self, id, domain_id, name, email, description, enabled):
self.id = id
self.domain_id = domain_id
self.name = name
self.email = email
self.description = description
self.enabled = enabled
def __repr__(self):
return "<OpenStackIdentityUser id=%s, domain_id=%s, name=%s, " "email=%s, enabled=%s>" % (
self.id,
self.domain_id,
self.name,
self.email,
self.enabled,
)
class OpenStackServiceCatalog:
"""
http://docs.openstack.org/api/openstack-identity-service/2.0/content/
This class should be instantiated with the contents of the
'serviceCatalog' in the auth response. This will do the work of figuring
out which services actually exist in the catalog as well as split them up
by type, name, and region if available
"""
_auth_version = None
_service_catalog = None
def __init__(self, service_catalog, auth_version=AUTH_API_VERSION):
self._auth_version = auth_version
# Check this way because there are a couple of different 2.0_*
# auth types.
if "3.x" in self._auth_version:
entries = self._parse_service_catalog_auth_v3(service_catalog=service_catalog)
elif "2.0" in self._auth_version:
entries = self._parse_service_catalog_auth_v2(service_catalog=service_catalog)
elif ("1.1" in self._auth_version) or ("1.0" in self._auth_version):
entries = self._parse_service_catalog_auth_v1(service_catalog=service_catalog)
else:
raise LibcloudError('auth version "%s" not supported' % (self._auth_version))
# Force consistent ordering by sorting the entries
entries = sorted(entries, key=lambda x: x.service_type + (x.service_name or ""))
self._entries = entries # stories all the service catalog entries
def get_entries(self):
"""
Return all the entries for this service catalog.
:rtype: ``list`` of :class:`.OpenStackServiceCatalogEntry`
"""
return self._entries
def get_catalog(self):
"""
Deprecated in the favor of ``get_entries`` method.
"""
return self.get_entries()
def get_public_urls(self, service_type=None, name=None):
"""
Retrieve all the available public (external) URLs for the provided
service type and name.
"""
endpoints = self.get_endpoints(service_type=service_type, name=name)
result = []
for endpoint in endpoints:
endpoint_type = endpoint.endpoint_type
if endpoint_type == OpenStackIdentityEndpointType.EXTERNAL:
result.append(endpoint.url)
return result
def get_endpoints(self, service_type=None, name=None):
"""
Retrieve all the endpoints for the provided service type and name.
:rtype: ``list`` of :class:`.OpenStackServiceCatalogEntryEndpoint`
"""
endpoints = []
for entry in self._entries:
# Note: "if XXX and YYY != XXX" comparison is used to support
# partial lookups.
# This allows user to pass in only one argument to the method (only
# service_type or name), both of them or neither.
if service_type and entry.service_type != service_type:
continue
if name and entry.service_name != name:
continue
for endpoint in entry.endpoints:
endpoints.append(endpoint)
return endpoints
def get_endpoint(
self,
service_type=None,
name=None,
region=None,
endpoint_type=OpenStackIdentityEndpointType.EXTERNAL,
):
"""
Retrieve a single endpoint using the provided criteria.
Note: If no or more than one matching endpoint is found, an exception
is thrown.
"""
endpoints = []
for entry in self._entries:
if service_type and entry.service_type != service_type:
continue
if name and entry.service_name != name:
continue
for endpoint in entry.endpoints:
if region and endpoint.region != region:
continue
if endpoint_type and endpoint.endpoint_type != endpoint_type:
continue
endpoints.append(endpoint)
if len(endpoints) == 1:
return endpoints[0]
elif len(endpoints) > 1:
raise ValueError("Found more than 1 matching endpoint")
else:
raise LibcloudError("Could not find specified endpoint")
def get_regions(self, service_type=None):
"""
Retrieve a list of all the available regions.
:param service_type: If specified, only return regions for this
service type.
:type service_type: ``str``
:rtype: ``list`` of ``str``
"""
regions = set()
for entry in self._entries:
if service_type and entry.service_type != service_type:
continue
for endpoint in entry.endpoints:
if endpoint.region:
regions.add(endpoint.region)
return sorted(list(regions))
def get_service_types(self, region=None):
"""
Retrieve all the available service types.
:param region: Optional region to retrieve service types for.
:type region: ``str``
:rtype: ``list`` of ``str``
"""
service_types = set()
for entry in self._entries:
include = True
for endpoint in entry.endpoints:
if region and endpoint.region != region:
include = False
break
if include:
service_types.add(entry.service_type)
return sorted(list(service_types))
def get_service_names(self, service_type=None, region=None):
"""
Retrieve list of service names that match service type and region.
:type service_type: ``str``
:type region: ``str``
:rtype: ``list`` of ``str``
"""
names = set()
if "2.0" not in self._auth_version:
raise ValueError("Unsupported version: %s" % (self._auth_version))
for entry in self._entries:
if service_type and entry.service_type != service_type:
continue
include = True
for endpoint in entry.endpoints:
if region and endpoint.region != region:
include = False
break
if include and entry.service_name:
names.add(entry.service_name)
return sorted(list(names))
def _parse_service_catalog_auth_v1(self, service_catalog):
entries = []
for service, endpoints in service_catalog.items():
entry_endpoints = []
for endpoint in endpoints:
region = endpoint.get("region", None)
public_url = endpoint.get("publicURL", None)
private_url = endpoint.get("internalURL", None)
if public_url:
entry_endpoint = OpenStackServiceCatalogEntryEndpoint(
region=region,
url=public_url,
endpoint_type=OpenStackIdentityEndpointType.EXTERNAL,
)
entry_endpoints.append(entry_endpoint)
if private_url:
entry_endpoint = OpenStackServiceCatalogEntryEndpoint(
region=region,
url=private_url,
endpoint_type=OpenStackIdentityEndpointType.INTERNAL,
)
entry_endpoints.append(entry_endpoint)
entry = OpenStackServiceCatalogEntry(service_type=service, endpoints=entry_endpoints)
entries.append(entry)
return entries
def _parse_service_catalog_auth_v2(self, service_catalog):
entries = []
for service in service_catalog:
service_type = service["type"]
service_name = service.get("name", None)
entry_endpoints = []
for endpoint in service.get("endpoints", []):
region = endpoint.get("region", None)
public_url = endpoint.get("publicURL", None)
private_url = endpoint.get("internalURL", None)
if public_url:
entry_endpoint = OpenStackServiceCatalogEntryEndpoint(
region=region,
url=public_url,
endpoint_type=OpenStackIdentityEndpointType.EXTERNAL,
)
entry_endpoints.append(entry_endpoint)
if private_url:
entry_endpoint = OpenStackServiceCatalogEntryEndpoint(
region=region,
url=private_url,
endpoint_type=OpenStackIdentityEndpointType.INTERNAL,
)
entry_endpoints.append(entry_endpoint)
entry = OpenStackServiceCatalogEntry(
service_type=service_type,
endpoints=entry_endpoints,
service_name=service_name,
)
entries.append(entry)
return entries
def _parse_service_catalog_auth_v3(self, service_catalog):
entries = []
for item in service_catalog:
service_type = item["type"]
service_name = item.get("name", None)
entry_endpoints = []
for endpoint in item["endpoints"]:
region = endpoint.get("region", None)
url = endpoint["url"]
endpoint_type = endpoint["interface"]
if endpoint_type == "internal":
endpoint_type = OpenStackIdentityEndpointType.INTERNAL
elif endpoint_type == "public":
endpoint_type = OpenStackIdentityEndpointType.EXTERNAL
elif endpoint_type == "admin":
endpoint_type = OpenStackIdentityEndpointType.ADMIN
entry_endpoint = OpenStackServiceCatalogEntryEndpoint(
region=region, url=url, endpoint_type=endpoint_type
)
entry_endpoints.append(entry_endpoint)
entry = OpenStackServiceCatalogEntry(
service_type=service_type,
service_name=service_name,
endpoints=entry_endpoints,
)
entries.append(entry)
return entries
class OpenStackServiceCatalogEntry:
def __init__(self, service_type, endpoints=None, service_name=None):
"""
:param service_type: Service type.
:type service_type: ``str``
:param endpoints: Endpoints belonging to this entry.
:type endpoints: ``list``
:param service_name: Optional service name.
:type service_name: ``str``
"""
self.service_type = service_type
self.endpoints = endpoints or []
self.service_name = service_name
# For consistency, sort the endpoints
self.endpoints = sorted(self.endpoints, key=lambda x: x.url or "")
def __eq__(self, other):
return (
self.service_type == other.service_type
and self.endpoints == other.endpoints
and other.service_name == self.service_name
)
def __ne__(self, other):
return not self.__eq__(other=other)
def __repr__(self):
return "<OpenStackServiceCatalogEntry service_type=%s, " "service_name=%s, endpoints=%s" % (
self.service_type,
self.service_name,
repr(self.endpoints),
)
class OpenStackServiceCatalogEntryEndpoint:
VALID_ENDPOINT_TYPES = [
OpenStackIdentityEndpointType.INTERNAL,
OpenStackIdentityEndpointType.EXTERNAL,
OpenStackIdentityEndpointType.ADMIN,
]
def __init__(self, region, url, endpoint_type="external"):
"""
:param region: Endpoint region.
:type region: ``str``
:param url: Endpoint URL.
:type url: ``str``
:param endpoint_type: Endpoint type (external / internal / admin).
:type endpoint_type: ``str``
"""
if endpoint_type not in self.VALID_ENDPOINT_TYPES:
raise ValueError("Invalid type: %s" % (endpoint_type))
# TODO: Normalize / lowercase all the region names
self.region = region
self.url = url
self.endpoint_type = endpoint_type
def __eq__(self, other):
return (
self.region == other.region
and self.url == other.url
and self.endpoint_type == other.endpoint_type
)
def __ne__(self, other):
return not self.__eq__(other=other)
def __repr__(self):
return "<OpenStackServiceCatalogEntryEndpoint region=%s, url=%s, " "type=%s" % (
self.region,
self.url,
self.endpoint_type,
)
class OpenStackAuthResponse(Response):
def success(self):
return self.status in [
httplib.OK,
httplib.CREATED,
httplib.ACCEPTED,
httplib.NO_CONTENT,
httplib.MULTIPLE_CHOICES,
httplib.UNAUTHORIZED,
httplib.INTERNAL_SERVER_ERROR,
]
def parse_body(self):
if not self.body:
return None
if "content-type" in self.headers:
key = "content-type"
elif "Content-Type" in self.headers:
key = "Content-Type"
else:
raise LibcloudError("Missing content-type header", driver=OpenStackIdentityConnection)
content_type = self.headers[key]
if content_type.find(";") != -1:
content_type = content_type.split(";")[0]
if content_type == "application/json":
try:
data = json.loads(self.body)
except Exception:
driver = OpenStackIdentityConnection
raise MalformedResponseError("Failed to parse JSON", body=self.body, driver=driver)
elif content_type == "text/plain":
data = self.body
else:
data = self.body
return data
class OpenStackIdentityConnection(ConnectionUserAndKey):
"""
Base identity connection class which contains common / shared logic.
Note: This class shouldn't be instantiated directly.
"""
responseCls = OpenStackAuthResponse
timeout = None
auth_version = None # type: str
def __init__(
self,
auth_url,
user_id,
key,
tenant_name=None,
tenant_domain_id="default",
domain_name="Default",
token_scope=OpenStackIdentityTokenScope.PROJECT,
timeout=None,
proxy_url=None,
parent_conn=None,
auth_cache=None,
):
super().__init__(
user_id=user_id, key=key, url=auth_url, timeout=timeout, proxy_url=proxy_url
)
self.parent_conn = parent_conn
# enable tests to use the same mock connection classes.
if parent_conn:
self.conn_class = parent_conn.conn_class
self.driver = parent_conn.driver
else:
self.driver = None
self.auth_url = auth_url
self.tenant_name = tenant_name
self.domain_name = domain_name
self.tenant_domain_id = tenant_domain_id
self.token_scope = token_scope
self.timeout = timeout
self.auth_cache = auth_cache
self.urls = {}
self.auth_token = None
self.auth_token_expires = None
self.auth_user_info = None
self.auth_user_roles = None
def authenticated_request(
self, action, params=None, data=None, headers=None, method="GET", raw=False
):
"""
Perform an authenticated request against the identity API.
"""
if not self.auth_token:
raise ValueError("Need to be authenticated to perform this request")
headers = headers or {}
headers[AUTH_TOKEN_HEADER] = self.auth_token
response = self.request(
action=action,
params=params,
data=data,
headers=headers,
method=method,
raw=raw,
)
# Evict cached auth token if we receive Unauthorized while using it
if response.status == httplib.UNAUTHORIZED:
self.clear_cached_auth_context()
return response
def morph_action_hook(self, action):
_, _, _, request_path = self._tuple_from_url(self.auth_url)
if request_path == "":
# No path is provided in the auth_url, use action passed to this
# method.
return action
return super().morph_action_hook(action=action)
def add_default_headers(self, headers):
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json; charset=UTF-8"
return headers
def is_token_valid(self):
"""
Return True if the current auth token is already cached and hasn't
expired yet.
:return: ``True`` if the token is still valid, ``False`` otherwise.
:rtype: ``bool``
"""
if not self.auth_token:
return False
if not self.auth_token_expires:
return False
expires = self.auth_token_expires - datetime.timedelta(
seconds=AUTH_TOKEN_EXPIRES_GRACE_SECONDS
)
time_tuple_expires = expires.utctimetuple()
time_tuple_now = datetime.datetime.utcnow().utctimetuple()
if time_tuple_now < time_tuple_expires:
return True
return False
def authenticate(self, force=False):
"""
Authenticate against the identity API.
:param force: Forcefully update the token even if it's already cached
and still valid.
:type force: ``bool``
"""
raise NotImplementedError("authenticate not implemented")
def clear_cached_auth_context(self):
"""
Clear the cached authentication context.
The context is cleared from fields on this connection and from the
external cache, if one is configured.
"""
self.auth_token = None
self.auth_token_expires = None
self.auth_user_info = None
self.auth_user_roles = None
self.urls = {}
if self.auth_cache is not None:
self.auth_cache.clear(self._cache_key)
def list_supported_versions(self):
"""
Retrieve a list of all the identity versions which are supported by
this installation.
:rtype: ``list`` of :class:`.OpenStackIdentityVersion`
"""
response = self.request("/", method="GET")
result = self._to_versions(data=response.object["versions"]["values"])
result = sorted(result, key=lambda x: x.version)
return result
def _to_versions(self, data):
result = []
for item in data:
version = self._to_version(data=item)
result.append(version)
return result
def _to_version(self, data):
try:
updated = parse_date(data["updated"])
except Exception:
updated = None
try:
url = data["links"][0]["href"]
except IndexError:
url = None
version = OpenStackIdentityVersion(
version=data["id"], status=data["status"], updated=updated, url=url
)
return version
def _is_authentication_needed(self, force=False):
"""
Determine if the authentication is needed or if the existing token (if
any exists) is still valid.
"""
if force:
return True
if self.auth_version not in AUTH_VERSIONS_WITH_EXPIRES:
return True
if self.is_token_valid():
return False
# See if there's a new token in the cache
self._load_auth_context_from_cache()
# If there was a token in the cache, it is now stored in our local
# auth_token and related fields. Ensure it is still valid.
if self.is_token_valid():
return False
return True
def _to_projects(self, data):
result = []
for item in data:
project = self._to_project(data=item)
result.append(project)
return result
def _to_project(self, data):
project = OpenStackIdentityProject(
id=data["id"],
name=data["name"],
description=data["description"],
enabled=data["enabled"],
domain_id=data.get("domain_id", None),
)
return project
@property
def _cache_key(self):
"""
The key where this connection's authentication context will be cached.
:rtype: :class:`OpenStackAuthenticationCacheKey`
"""
return OpenStackAuthenticationCacheKey(
self.auth_url,
self.user_id,
self.token_scope,
self.tenant_name,
self.domain_name,
self.tenant_domain_id,
)
def _cache_auth_context(self, context):
"""
Store an authentication context in memory and the cache.
:param context: Authentication context to cache.
:type key: :class:`.OpenStackAuthenticationContext`
"""
self.urls = context.urls
self.auth_token = context.token
self.auth_token_expires = context.expiration
self.auth_user_info = context.user
self.auth_user_roles = context.roles
if self.auth_cache is not None:
self.auth_cache.put(self._cache_key, context)
def _load_auth_context_from_cache(self):
"""
Fetch an authentication context for this connection from the cache.
:rtype: :class:`OpenStackAuthenticationContext`
"""
if self.auth_cache is None:
return None
context = self.auth_cache.get(self._cache_key)
if context is None:
return None
self.urls = context.urls
self.auth_token = context.token
self.auth_token_expires = context.expiration
self.auth_user_info = context.user
self.auth_user_roles = context.roles
return context
class OpenStackIdentity_1_0_Connection(OpenStackIdentityConnection):
"""
Connection class for Keystone API v1.0.
"""
responseCls = OpenStackAuthResponse
name = "OpenStack Identity API v1.0"
auth_version = "1.0"
def authenticate(self, force=False):
if not self._is_authentication_needed(force=force):
return self
headers = {
"X-Auth-User": self.user_id,
"X-Auth-Key": self.key,
}
resp = self.request("/v1.0", headers=headers, method="GET")
if resp.status == httplib.UNAUTHORIZED:
# HTTP UNAUTHORIZED (401): auth failed
raise InvalidCredsError()
elif resp.status not in [httplib.NO_CONTENT, httplib.OK]:
body = "code: {} body:{} headers:{}".format(
resp.status,
resp.body,
resp.headers,
)
raise MalformedResponseError("Malformed response", body=body, driver=self.driver)
else:
headers = resp.headers
# emulate the auth 1.1 URL list
self.urls = {}
self.urls["cloudServers"] = [
{"publicURL": headers.get("x-server-management-url", None)}
]
self.urls["cloudFilesCDN"] = [{"publicURL": headers.get("x-cdn-management-url", None)}]
self.urls["cloudFiles"] = [{"publicURL": headers.get("x-storage-url", None)}]
self.auth_token = headers.get("x-auth-token", None)
self.auth_user_info = None
if not self.auth_token: