/
auth_token.py
2148 lines (1733 loc) · 82.3 KB
/
auth_token.py
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
# Copyright 2010-2012 OpenStack Foundation
#
# Licensed 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.
"""
Token-based Authentication Middleware
This WSGI component:
* Verifies that incoming client requests have valid tokens by validating
tokens with the auth service.
* Rejects unauthenticated requests unless the auth_token middleware is in
'delay_auth_decision' mode, which means the final decision is delegated to
the downstream WSGI component (usually the OpenStack service).
* Collects and forwards identity information based on a valid token
such as user name, tenant, etc
Refer to: http://docs.openstack.org/developer/keystonemiddleware/\
middlewarearchitecture.html
Run this module directly to start a protected echo service on port 8000::
$ python -m keystonemiddleware.auth_token
When the ``auth_token`` module authenticates a request, the echo service
will respond with all the environment variables presented to it by this
module.
Headers
-------
The auth_token middleware uses headers sent in by the client on the request
and sets headers and environment variables for the downstream WSGI component.
Coming in from initial call from client or customer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
HTTP_X_AUTH_TOKEN
The client token being passed in.
HTTP_X_SERVICE_TOKEN
A service token being passed in.
Used for communication between components
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
WWW-Authenticate
HTTP header returned to a user indicating which endpoint to use
to retrieve a new token
What auth_token adds to the request for use by the OpenStack service
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When using composite authentication (a user and service token are
present) additional service headers relating to the service user
will be added. They take the same form as the standard headers but add
'_SERVICE_'. These headers will not exist in the environment if no
service token is present.
HTTP_X_IDENTITY_STATUS
'Confirmed' or 'Invalid'
The underlying service will only see a value of 'Invalid' if the Middleware
is configured to run in 'delay_auth_decision' mode
HTTP_X_DOMAIN_ID, HTTP_X_SERVICE_DOMAIN_ID
Identity service managed unique identifier, string. Only present if
this is a domain-scoped v3 token.
HTTP_X_DOMAIN_NAME, HTTP_X_SERVICE_DOMAIN_NAME
Unique domain name, string. Only present if this is a domain-scoped
v3 token.
HTTP_X_PROJECT_ID, HTTP_X_SERVICE_PROJECT_ID
Identity service managed unique identifier, string. Only present if
this is a project-scoped v3 token, or a tenant-scoped v2 token.
HTTP_X_PROJECT_NAME, HTTP_X_SERVICE_PROJECT_NAME
Project name, unique within owning domain, string. Only present if
this is a project-scoped v3 token, or a tenant-scoped v2 token.
HTTP_X_PROJECT_DOMAIN_ID, HTTP_X_SERVICE_PROJECT_DOMAIN_ID
Identity service managed unique identifier of owning domain of
project, string. Only present if this is a project-scoped v3 token. If
this variable is set, this indicates that the PROJECT_NAME can only
be assumed to be unique within this domain.
HTTP_X_PROJECT_DOMAIN_NAME, HTTP_X_SERVICE_PROJECT_DOMAIN_NAME
Name of owning domain of project, string. Only present if this is a
project-scoped v3 token. If this variable is set, this indicates that
the PROJECT_NAME can only be assumed to be unique within this domain.
HTTP_X_USER_ID, HTTP_X_SERVICE_USER_ID
Identity-service managed unique identifier, string
HTTP_X_USER_NAME, HTTP_X_SERVICE_USER_NAME
User identifier, unique within owning domain, string
HTTP_X_USER_DOMAIN_ID, HTTP_X_SERVICE_USER_DOMAIN_ID
Identity service managed unique identifier of owning domain of
user, string. If this variable is set, this indicates that the USER_NAME
can only be assumed to be unique within this domain.
HTTP_X_USER_DOMAIN_NAME, HTTP_X_SERVICE_USER_DOMAIN_NAME
Name of owning domain of user, string. If this variable is set, this
indicates that the USER_NAME can only be assumed to be unique within
this domain.
HTTP_X_ROLES, HTTP_X_SERVICE_ROLES
Comma delimited list of case-sensitive role names
HTTP_X_SERVICE_CATALOG
json encoded service catalog (optional).
For compatibility reasons this catalog will always be in the V2 catalog
format even if it is a v3 token.
Note: This is an exception in that it contains 'SERVICE' but relates to a
user token, not a service token. The existing user's
catalog can be very large; it was decided not to present a catalog
relating to the service token to avoid using more HTTP header space.
HTTP_X_TENANT_ID
*Deprecated* in favor of HTTP_X_PROJECT_ID
Identity service managed unique identifier, string. For v3 tokens, this
will be set to the same value as HTTP_X_PROJECT_ID
HTTP_X_TENANT_NAME
*Deprecated* in favor of HTTP_X_PROJECT_NAME
Project identifier, unique within owning domain, string. For v3 tokens,
this will be set to the same value as HTTP_X_PROJECT_NAME
HTTP_X_TENANT
*Deprecated* in favor of HTTP_X_TENANT_ID and HTTP_X_TENANT_NAME
identity server-assigned unique identifier, string. For v3 tokens, this
will be set to the same value as HTTP_X_PROJECT_ID
HTTP_X_USER
*Deprecated* in favor of HTTP_X_USER_ID and HTTP_X_USER_NAME
User name, unique within owning domain, string
HTTP_X_ROLE
*Deprecated* in favor of HTTP_X_ROLES
Will contain the same values as HTTP_X_ROLES.
Environment Variables
^^^^^^^^^^^^^^^^^^^^^
These variables are set in the request environment for use by the downstream
WSGI component.
keystone.token_info
Information about the token discovered in the process of validation. This
may include extended information returned by the token validation call, as
well as basic information about the tenant and user.
keystone.token_auth
A keystoneclient auth plugin that may be used with a
:py:class:`keystoneclient.session.Session`. This plugin will load the
authentication data provided to auth_token middleware.
"""
import contextlib
import datetime
import logging
import os
import stat
import tempfile
from keystoneclient import access
from keystoneclient import adapter
from keystoneclient import auth
from keystoneclient.auth.identity import base as base_identity
from keystoneclient.auth.identity import v2
from keystoneclient.auth import token_endpoint
from keystoneclient.common import cms
from keystoneclient import discover
from keystoneclient import exceptions
from keystoneclient import session
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six
from six.moves import urllib
from keystonemiddleware import _memcache_crypt as memcache_crypt
from keystonemiddleware.i18n import _, _LC, _LE, _LI, _LW
from keystonemiddleware.openstack.common import memorycache
# alternative middleware configuration in the main application's
# configuration file e.g. in nova.conf
# [keystone_authtoken]
# auth_host = 127.0.0.1
# auth_port = 35357
# auth_protocol = http
# admin_tenant_name = admin
# admin_user = admin
# admin_password = badpassword
# when deploy Keystone auth_token middleware with Swift, user may elect
# to use Swift memcache instead of the local auth_token memcache. Swift
# memcache is passed in from the request environment and its identified by the
# 'swift.cache' key. However it could be different, depending on deployment.
# To use Swift memcache, you must set the 'cache' option to the environment
# key where the Swift cache object is stored.
# NOTE(jamielennox): A number of options below are deprecated however are left
# in the list and only mentioned as deprecated in the help string. This is
# because we have to provide the same deprecation functionality for arguments
# passed in via the conf in __init__ (from paste) and there is no way to test
# that the default value was set or not in CONF.
# Also if we were to remove the options from the CONF list (as typical CONF
# deprecation works) then other projects will not be able to override the
# options via CONF.
_OPTS = [
cfg.StrOpt('auth_uri',
default=None,
# FIXME(dolph): should be default='http://127.0.0.1:5000/v2.0/',
# or (depending on client support) an unversioned, publicly
# accessible identity endpoint (see bug 1207517)
help='Complete public Identity API endpoint.'),
cfg.StrOpt('auth_version',
default=None,
help='API version of the admin Identity API endpoint.'),
cfg.BoolOpt('delay_auth_decision',
default=False,
help='Do not handle authorization requests within the'
' middleware, but delegate the authorization decision to'
' downstream WSGI components.'),
cfg.IntOpt('http_connect_timeout',
default=None,
help='Request timeout value for communicating with Identity'
' API server.'),
cfg.IntOpt('http_request_max_retries',
default=3,
help='How many times are we trying to reconnect when'
' communicating with Identity API Server.'),
cfg.StrOpt('cache',
default=None,
help='Env key for the swift cache.'),
cfg.StrOpt('certfile',
help='Required if identity server requires client certificate'),
cfg.StrOpt('keyfile',
help='Required if identity server requires client certificate'),
cfg.StrOpt('cafile', default=None,
help='A PEM encoded Certificate Authority to use when '
'verifying HTTPs connections. Defaults to system CAs.'),
cfg.BoolOpt('insecure', default=False, help='Verify HTTPS connections.'),
cfg.StrOpt('signing_dir',
help='Directory used to cache files related to PKI tokens.'),
cfg.ListOpt('memcached_servers',
deprecated_name='memcache_servers',
help='Optionally specify a list of memcached server(s) to'
' use for caching. If left undefined, tokens will instead be'
' cached in-process.'),
cfg.IntOpt('token_cache_time',
default=300,
help='In order to prevent excessive effort spent validating'
' tokens, the middleware caches previously-seen tokens for a'
' configurable duration (in seconds). Set to -1 to disable'
' caching completely.'),
cfg.IntOpt('revocation_cache_time',
default=10,
help='Determines the frequency at which the list of revoked'
' tokens is retrieved from the Identity service (in seconds). A'
' high number of revocation events combined with a low cache'
' duration may significantly reduce performance.'),
cfg.StrOpt('memcache_security_strategy',
default=None,
help='(Optional) If defined, indicate whether token data'
' should be authenticated or authenticated and encrypted.'
' Acceptable values are MAC or ENCRYPT. If MAC, token data is'
' authenticated (with HMAC) in the cache. If ENCRYPT, token'
' data is encrypted and authenticated in the cache. If the'
' value is not one of these options or empty, auth_token will'
' raise an exception on initialization.'),
cfg.StrOpt('memcache_secret_key',
default=None,
secret=True,
help='(Optional, mandatory if memcache_security_strategy is'
' defined) This string is used for key derivation.'),
cfg.IntOpt('memcache_pool_dead_retry',
default=5 * 60,
help='(Optional) Number of seconds memcached server is'
' considered dead before it is tried again.'),
cfg.IntOpt('memcache_pool_maxsize',
default=10,
help='(Optional) Maximum total number of open connections to'
' every memcached server.'),
cfg.IntOpt('memcache_pool_socket_timeout',
default=3,
help='(Optional) Socket timeout in seconds for communicating '
'with a memcache server.'),
cfg.IntOpt('memcache_pool_unused_timeout',
default=60,
help='(Optional) Number of seconds a connection to memcached'
' is held unused in the pool before it is closed.'),
cfg.IntOpt('memcache_pool_conn_get_timeout',
default=10,
help='(Optional) Number of seconds that an operation will wait '
'to get a memcache client connection from the pool.'),
cfg.BoolOpt('memcache_use_advanced_pool',
default=False,
help='(Optional) Use the advanced (eventlet safe) memcache '
'client pool. The advanced pool will only work under '
'python 2.x.'),
cfg.BoolOpt('include_service_catalog',
default=True,
help='(Optional) Indicate whether to set the X-Service-Catalog'
' header. If False, middleware will not ask for service'
' catalog on token validation and will not set the'
' X-Service-Catalog header.'),
cfg.StrOpt('enforce_token_bind',
default='permissive',
help='Used to control the use and type of token binding. Can'
' be set to: "disabled" to not check token binding.'
' "permissive" (default) to validate binding information if the'
' bind type is of a form known to the server and ignore it if'
' not. "strict" like "permissive" but if the bind type is'
' unknown the token will be rejected. "required" any form of'
' token binding is needed to be allowed. Finally the name of a'
' binding method that must be present in tokens.'),
cfg.BoolOpt('check_revocations_for_cached', default=False,
help='If true, the revocation list will be checked for cached'
' tokens. This requires that PKI tokens are configured on the'
' identity server.'),
cfg.ListOpt('hash_algorithms', default=['md5'],
help='Hash algorithms to use for hashing PKI tokens. This may'
' be a single algorithm or multiple. The algorithms are those'
' supported by Python standard hashlib.new(). The hashes will'
' be tried in the order given, so put the preferred one first'
' for performance. The result of the first hash will be stored'
' in the cache. This will typically be set to multiple values'
' only while migrating from a less secure algorithm to a more'
' secure one. Once all the old tokens are expired this option'
' should be set to a single value for better performance.'),
]
_AUTHTOKEN_GROUP = 'keystone_authtoken'
CONF = cfg.CONF
CONF.register_opts(_OPTS, group=_AUTHTOKEN_GROUP)
auth.register_conf_options(CONF, _AUTHTOKEN_GROUP)
_HEADER_TEMPLATE = {
'X%s-Domain-Id': 'domain_id',
'X%s-Domain-Name': 'domain_name',
'X%s-Project-Id': 'project_id',
'X%s-Project-Name': 'project_name',
'X%s-Project-Domain-Id': 'project_domain_id',
'X%s-Project-Domain-Name': 'project_domain_name',
'X%s-User-Id': 'user_id',
'X%s-User-Name': 'username',
'X%s-User-Domain-Id': 'user_domain_id',
'X%s-User-Domain-Name': 'user_domain_name',
}
_DEPRECATED_HEADER_TEMPLATE = {
'X-User': 'username',
'X-Tenant-Id': 'project_id',
'X-Tenant-Name': 'project_name',
'X-Tenant': 'project_name',
}
class _BIND_MODE(object):
DISABLED = 'disabled'
PERMISSIVE = 'permissive'
STRICT = 'strict'
REQUIRED = 'required'
KERBEROS = 'kerberos'
def _token_is_v2(token_info):
return ('access' in token_info)
def _token_is_v3(token_info):
return ('token' in token_info)
def _get_token_expiration(data):
if not data:
raise InvalidToken(_('Token authorization failed'))
if _token_is_v2(data):
return data['access']['token']['expires']
elif _token_is_v3(data):
return data['token']['expires_at']
else:
raise InvalidToken(_('Token authorization failed'))
def _confirm_token_not_expired(expires):
expires = timeutils.parse_isotime(expires)
expires = timeutils.normalize_time(expires)
utcnow = timeutils.utcnow()
if utcnow >= expires:
raise InvalidToken(_('Token authorization failed'))
def _v3_to_v2_catalog(catalog):
"""Convert a catalog to v2 format.
X_SERVICE_CATALOG must be specified in v2 format. If you get a token
that is in v3 convert it.
"""
v2_services = []
for v3_service in catalog:
# first copy over the entries we allow for the service
v2_service = {'type': v3_service['type']}
try:
v2_service['name'] = v3_service['name']
except KeyError:
pass
# now convert the endpoints. Because in v3 we specify region per
# URL not per group we have to collect all the entries of the same
# region together before adding it to the new service.
regions = {}
for v3_endpoint in v3_service.get('endpoints', []):
region_name = v3_endpoint.get('region')
try:
region = regions[region_name]
except KeyError:
region = {'region': region_name} if region_name else {}
regions[region_name] = region
interface_name = v3_endpoint['interface'].lower() + 'URL'
region[interface_name] = v3_endpoint['url']
v2_service['endpoints'] = list(regions.values())
v2_services.append(v2_service)
return v2_services
def _safe_quote(s):
"""URL-encode strings that are not already URL-encoded."""
return urllib.parse.quote(s) if s == urllib.parse.unquote(s) else s
def _conf_values_type_convert(conf):
"""Convert conf values into correct type."""
if not conf:
return {}
opt_types = {}
for o in (_OPTS + _AuthTokenPlugin.get_options()):
type_dest = (getattr(o, 'type', str), o.dest)
opt_types[o.dest] = type_dest
# Also add the deprecated name with the same type and dest.
for d_o in o.deprecated_opts:
opt_types[d_o.name] = type_dest
opts = {}
for k, v in six.iteritems(conf):
dest = k
try:
if v is not None:
type_, dest = opt_types[k]
v = type_(v)
except KeyError:
# This option is not known to auth_token.
pass
except ValueError as e:
raise ConfigurationError(
_('Unable to convert the value of %(key)s option into correct '
'type: %(ex)s') % {'key': k, 'ex': e})
opts[dest] = v
return opts
class InvalidToken(Exception):
pass
class ServiceError(Exception):
pass
class ConfigurationError(Exception):
pass
class RevocationListError(Exception):
pass
class _MiniResp(object):
def __init__(self, error_message, env, headers=[]):
# The HEAD method is unique: it must never return a body, even if
# it reports an error (RFC-2616 clause 9.4). We relieve callers
# from varying the error responses depending on the method.
if env['REQUEST_METHOD'] == 'HEAD':
self.body = ['']
else:
self.body = [error_message.encode()]
self.headers = list(headers)
self.headers.append(('Content-type', 'text/plain'))
class _AuthTokenPlugin(auth.BaseAuthPlugin):
def __init__(self, auth_host, auth_port, auth_protocol, auth_admin_prefix,
admin_user, admin_password, admin_tenant_name, admin_token,
identity_uri, log):
# NOTE(jamielennox): it does appear here that our default arguments
# are backwards. We need to do it this way so that we can handle the
# same deprecation strategy for CONF and the conf variable.
if not identity_uri:
log.warning(_LW('Configuring admin URI using auth fragments. '
'This is deprecated, use \'identity_uri\''
' instead.'))
if ':' in auth_host:
# Note(dzyu) it is an IPv6 address, so it needs to be wrapped
# with '[]' to generate a valid IPv6 URL, based on
# http://www.ietf.org/rfc/rfc2732.txt
auth_host = '[%s]' % auth_host
identity_uri = '%s://%s:%s' % (auth_protocol,
auth_host,
auth_port)
if auth_admin_prefix:
identity_uri = '%s/%s' % (identity_uri,
auth_admin_prefix.strip('/'))
self._identity_uri = identity_uri.rstrip('/')
# FIXME(jamielennox): Yes. This is wrong. We should be determining the
# plugin to use based on a combination of discovery and inputs. Much
# of this can be changed when we get keystoneclient 0.10. For now this
# hardcoded path is EXACTLY the same as the original auth_token did.
auth_url = '%s/v2.0' % self._identity_uri
if admin_token:
log.warning(_LW(
"The admin_token option in the auth_token middleware is "
"deprecated and should not be used. The admin_user and "
"admin_password options should be used instead. The "
"admin_token option may be removed in a future release."))
self._plugin = token_endpoint.Token(auth_url, admin_token)
else:
self._plugin = v2.Password(auth_url,
username=admin_user,
password=admin_password,
tenant_name=admin_tenant_name)
self._LOG = log
self._discover = None
def get_token(self, *args, **kwargs):
return self._plugin.get_token(*args, **kwargs)
def get_endpoint(self, session, interface=None, version=None, **kwargs):
"""Return an endpoint for the client.
There are no required keyword arguments to ``get_endpoint`` as a plugin
implementation should use best effort with the information available to
determine the endpoint.
:param session: The session object that the auth_plugin belongs to.
:type session: keystoneclient.session.Session
:param tuple version: The version number required for this endpoint.
:param str interface: what visibility the endpoint should have.
:returns: The base URL that will be used to talk to the required
service or None if not available.
:rtype: string
"""
if interface == auth.AUTH_INTERFACE:
return self._identity_uri
if not version:
# NOTE(jamielennox): This plugin can only be used within auth_token
# and auth_token will always provide version= with requests.
return None
if not self._discover:
self._discover = discover.Discover(session,
auth_url=self._identity_uri,
authenticated=False)
if not self._discover.url_for(version):
# NOTE(jamielennox): The requested version is not supported by the
# identity server.
return None
# NOTE(jamielennox): for backwards compatibility here we don't
# actually use the URL from discovery we hack it up instead. :(
if version[0] == 2:
return '%s/v2.0' % self._identity_uri
elif version[0] == 3:
return '%s/v3' % self._identity_uri
# NOTE(jamielennox): This plugin will only get called from auth_token
# middleware. The middleware should never request a version that the
# plugin doesn't know how to handle.
msg = _('Invalid version asked for in auth_token plugin')
raise NotImplementedError(msg)
def invalidate(self):
return self._plugin.invalidate()
@classmethod
def get_options(cls):
options = super(_AuthTokenPlugin, cls).get_options()
options.extend([
cfg.StrOpt('auth_admin_prefix',
default='',
help='Prefix to prepend at the beginning of the path. '
'Deprecated, use identity_uri.'),
cfg.StrOpt('auth_host',
default='127.0.0.1',
help='Host providing the admin Identity API endpoint. '
'Deprecated, use identity_uri.'),
cfg.IntOpt('auth_port',
default=35357,
help='Port of the admin Identity API endpoint. '
'Deprecated, use identity_uri.'),
cfg.StrOpt('auth_protocol',
default='https',
help='Protocol of the admin Identity API endpoint '
'(http or https). Deprecated, use identity_uri.'),
cfg.StrOpt('identity_uri',
default=None,
help='Complete admin Identity API endpoint. This '
'should specify the unversioned root endpoint '
'e.g. https://localhost:35357/'),
cfg.StrOpt('admin_token',
secret=True,
help='This option is deprecated and may be removed in '
'a future release. Single shared secret with the '
'Keystone configuration used for bootstrapping a '
'Keystone installation, or otherwise bypassing '
'the normal authentication process. This option '
'should not be used, use `admin_user` and '
'`admin_password` instead.'),
cfg.StrOpt('admin_user',
help='Service username.'),
cfg.StrOpt('admin_password',
secret=True,
help='Service user password.'),
cfg.StrOpt('admin_tenant_name',
default='admin',
help='Service tenant name.'),
])
return options
_AuthTokenPlugin.register_conf_options(CONF, _AUTHTOKEN_GROUP)
class _TokenData(object):
"""An abstraction to show auth_token consumers some of the token contents.
This is a simplified and cleaned up keystoneclient.access.AccessInfo object
with which services relying on auth_token middleware can find details of
the current token.
"""
def __init__(self, auth_ref):
self._stored_auth_ref = auth_ref
@property
def _is_v2(self):
return self._stored_auth_ref.version == 'v2.0'
@property
def auth_token(self):
"""The token data used to authenticate requests.
:returns: token data.
:rtype: str
"""
return self._stored_auth_ref.auth_token
@property
def user_id(self):
"""The user id associated with the authentication request.
:rtype: str
"""
return self._stored_auth_ref.user_id
@property
def user_domain_id(self):
"""Returns the domain id of the user associated with the authentication
request.
:returns: str
"""
# NOTE(jamielennox): v2 AccessInfo returns 'default' for domain_id
# because it can't know that value. We want to return None instead.
if self._is_v2:
return None
return self._stored_auth_ref.user_domain_id
@property
def project_id(self):
"""The project ID associated with the authentication.
:rtype: str
"""
return self._stored_auth_ref.project_id
@property
def project_domain_id(self):
"""The domain id of the project associated with the authentication
request.
:rtype: str
"""
# NOTE(jamielennox): v2 AccessInfo returns 'default' for domain_id
# because it can't know that value. We want to return None instead.
if self._is_v2:
return None
return self._stored_auth_ref.project_domain_id
@property
def trust_id(self):
"""Returns the trust id associated with the authentication request..
:rtype: str
"""
return self._stored_auth_ref.trust_id
@property
def role_ids(self):
"""Role ids of the user associated with the authentication request.
:rtype: set(str)
"""
return frozenset(self._stored_auth_ref.role_ids or [])
@property
def role_names(self):
"""Role names of the user associated with the authentication request.
:rtype: set(str)
"""
return frozenset(self._stored_auth_ref.role_names or [])
class _UserAuthPlugin(base_identity.BaseIdentityPlugin):
"""The incoming authentication credentials.
A plugin that represents the incoming user credentials. This can be
consumed by applications.
This object is not expected to be constructed directly by users. It is
created and passed by auth_token middleware and then can be used as the
authentication plugin when communicating via a session.
"""
def __init__(self, user_auth_ref, serv_auth_ref):
super(_UserAuthPlugin, self).__init__(reauthenticate=False)
self._user_auth_ref = user_auth_ref
self._serv_auth_ref = serv_auth_ref
self._user_data = None
self._serv_data = None
@property
def has_user_token(self):
"""Did this authentication request contained a user auth token."""
return self._user_auth_ref is not None
@property
def user(self):
"""Authentication information about the user token.
Will return None if a user token was not passed with this request.
"""
if not self.has_user_token:
return None
if not self._user_data:
self._user_data = _TokenData(self._user_auth_ref)
return self._user_data
@property
def has_service_token(self):
"""Did this authentication request contained a service token."""
return self._serv_auth_ref is not None
@property
def service(self):
"""Authentication information about the service token.
Will return None if a user token was not passed with this request.
"""
if not self.has_service_token:
return None
if not self._serv_data:
self._serv_data = _TokenData(self._serv_auth_ref)
return self._serv_data
def get_auth_ref(self, session, **kwargs):
# NOTE(jamielennox): We will always use the auth_ref that was
# calculated by the middleware. reauthenticate=False in __init__ should
# ensure that this function is only called on the first access.
return self._user_auth_ref
class AuthProtocol(object):
"""Middleware that handles authenticating client calls."""
def __init__(self, app, conf):
self._LOG = logging.getLogger(conf.get('log_name', __name__))
self._LOG.info(_LI('Starting Keystone auth_token middleware'))
# NOTE(wanghong): If options are set in paste file, all the option
# values passed into conf are string type. So, we should convert the
# conf value into correct type.
self._conf = _conf_values_type_convert(conf)
self._app = app
# delay_auth_decision means we still allow unauthenticated requests
# through and we let the downstream service make the final decision
self._delay_auth_decision = self._conf_get('delay_auth_decision')
self._include_service_catalog = self._conf_get(
'include_service_catalog')
self._identity_server = self._create_identity_server()
self._auth_uri = self._conf_get('auth_uri')
if not self._auth_uri:
self._LOG.warning(
_LW('Configuring auth_uri to point to the public identity '
'endpoint is required; clients may not be able to '
'authenticate against an admin endpoint'))
# FIXME(dolph): drop support for this fallback behavior as
# documented in bug 1207517.
self._auth_uri = self._identity_server.auth_uri
# signing
self._signing_dirname = self._conf_get('signing_dir')
if self._signing_dirname is None:
self._signing_dirname = tempfile.mkdtemp(
prefix='keystone-signing-')
self._LOG.info(
_LI('Using %s as cache directory for signing certificate'),
self._signing_dirname)
self._verify_signing_dir()
val = '%s/signing_cert.pem' % self._signing_dirname
self._signing_cert_file_name = val
val = '%s/cacert.pem' % self._signing_dirname
self._signing_ca_file_name = val
val = '%s/revoked.pem' % self._signing_dirname
self._revoked_file_name = val
self._token_cache = self._token_cache_factory()
self._token_revocation_list_prop = None
self._token_revocation_list_fetched_time_prop = None
self._token_revocation_list_cache_timeout = datetime.timedelta(
seconds=self._conf_get('revocation_cache_time'))
self._check_revocations_for_cached = self._conf_get(
'check_revocations_for_cached')
self._init_auth_headers()
def _conf_get(self, name):
# try config from paste-deploy first
if name in self._conf:
return self._conf[name]
else:
return CONF.keystone_authtoken[name]
def _call_app(self, env, start_response):
# NOTE(jamielennox): We wrap the given start response so that if an
# application with a 'delay_auth_decision' setting fails, or otherwise
# raises Unauthorized that we include the Authentication URL headers.
def _fake_start_response(status, response_headers, exc_info=None):
if status.startswith('401'):
response_headers.extend(self._reject_auth_headers)
return start_response(status, response_headers, exc_info)
return self._app(env, _fake_start_response)
def __call__(self, env, start_response):
"""Handle incoming request.
Authenticate send downstream on success. Reject request if
we can't authenticate.
"""
def _fmt_msg(env):
msg = ('user: user_id %s, project_id %s, roles %s '
'service: user_id %s, project_id %s, roles %s' % (
env.get('HTTP_X_USER_ID'), env.get('HTTP_X_PROJECT_ID'),
env.get('HTTP_X_ROLES'),
env.get('HTTP_X_SERVICE_USER_ID'),
env.get('HTTP_X_SERVICE_PROJECT_ID'),
env.get('HTTP_X_SERVICE_ROLES')))
return msg
self._token_cache.initialize(env)
self._remove_auth_headers(env)
try:
user_auth_ref = None
serv_auth_ref = None
try:
self._LOG.debug('Authenticating user token')
user_token = self._get_user_token_from_header(env)
user_token_info = self._validate_token(user_token, env)
user_auth_ref = access.AccessInfo.factory(
body=user_token_info,
auth_token=user_token)
env['keystone.token_info'] = user_token_info
user_headers = self._build_user_headers(user_auth_ref,
user_token_info)
self._add_headers(env, user_headers)
except InvalidToken:
if self._delay_auth_decision:
self._LOG.info(
_LI('Invalid user token - deferring reject '
'downstream'))
self._add_headers(env, {'X-Identity-Status': 'Invalid'})
else:
self._LOG.info(
_LI('Invalid user token - rejecting request'))
return self._reject_request(env, start_response)
try:
self._LOG.debug('Authenticating service token')
serv_token = self._get_service_token_from_header(env)
if serv_token is not None:
serv_token_info = self._validate_token(
serv_token, env)
serv_auth_ref = access.AccessInfo.factory(
body=serv_token_info,
auth_token=serv_token)
serv_headers = self._build_service_headers(serv_token_info)
self._add_headers(env, serv_headers)
except InvalidToken:
# Delayed auth not currently supported for service tokens.
# (Can be implemented if a use case is found.)
self._LOG.info(
_LI('Invalid service token - rejecting request'))
return self._reject_request(env, start_response)
env['keystone.token_auth'] = _UserAuthPlugin(user_auth_ref,
serv_auth_ref)
except ServiceError as e:
self._LOG.critical(_LC('Unable to obtain admin token: %s'), e)
return self._do_503_error(env, start_response)
self._LOG.debug("Received request from %s", _fmt_msg(env))
return self._call_app(env, start_response)
def _do_503_error(self, env, start_response):
resp = _MiniResp('Service unavailable', env)
start_response('503 Service Unavailable', resp.headers)
return resp.body
def _init_auth_headers(self):
"""Initialize auth header list.
Both user and service token headers are generated.
"""
auth_headers = ['X-Service-Catalog',
'X-Identity-Status',
'X-Roles',
'X-Service-Roles']
for key in six.iterkeys(_HEADER_TEMPLATE):
auth_headers.append(key % '')
# Service headers
auth_headers.append(key % '-Service')
# Deprecated headers
auth_headers.append('X-Role')
for key in six.iterkeys(_DEPRECATED_HEADER_TEMPLATE):