"Fossies" - the Fresh Open Source Software Archive

Member "keystone-18.0.0/keystone/token/providers/jws/core.py" (14 Oct 2020, 8005 Bytes) of package /linux/misc/openstack/keystone-18.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "core.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 17.0.0_vs_18.0.0.

    1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
    2 # not use this file except in compliance with the License. You may obtain
    3 # a copy of the License at
    4 #
    5 #      http://www.apache.org/licenses/LICENSE-2.0
    6 #
    7 # Unless required by applicable law or agreed to in writing, software
    8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
   10 # License for the specific language governing permissions and limitations
   11 # under the License.
   12 
   13 import datetime
   14 import os
   15 
   16 import jwt
   17 from oslo_utils import timeutils
   18 
   19 from keystone.common import utils
   20 import keystone.conf
   21 from keystone import exception
   22 from keystone.i18n import _
   23 from keystone.token.providers import base
   24 
   25 CONF = keystone.conf.CONF
   26 
   27 
   28 class Provider(base.Provider):
   29 
   30     def __init__(self, *args, **kwargs):
   31         super(Provider, self).__init__(*args, **kwargs)
   32 
   33         # NOTE(lbragstad): We add these checks here because if the jws
   34         # provider is going to be used and either the `key_repository` is empty
   35         # or doesn't exist we should fail, hard. It doesn't make sense to start
   36         # keystone and just 500 because we can't do anything with an empty or
   37         # non-existant key repository.
   38         private_key = os.path.join(
   39             CONF.jwt_tokens.jws_private_key_repository, 'private.pem'
   40         )
   41         public_key_repo = CONF.jwt_tokens.jws_public_key_repository
   42 
   43         if not os.path.exists(private_key):
   44             subs = {'private_key': private_key}
   45             raise SystemExit(_(
   46                 '%(private_key)s does not exist. You can generate a key pair '
   47                 'using `keystone-manage create_jws_keypair`.') % subs)
   48         if not os.path.exists(public_key_repo):
   49             subs = {'public_key_repo': public_key_repo}
   50             raise SystemExit(_(
   51                 '%(public_key_repo)s does not exist. Please make sure the '
   52                 'directory exists and is readable by the process running '
   53                 'keystone.') % subs)
   54         if len(os.listdir(public_key_repo)) == 0:
   55             subs = {'public_key_repo': public_key_repo}
   56             msg = _(
   57                 '%(public_key_repo)s must contain at least one public '
   58                 'key but it is empty. You can generate a key pair using '
   59                 '`keystone-manage create_jws_keypair`.'
   60             )
   61             raise SystemExit(msg % subs)
   62         self.token_formatter = JWSFormatter()
   63 
   64     def generate_id_and_issued_at(self, token):
   65         return self.token_formatter.create_token(
   66             token.user_id, token.expires_at, token.audit_ids, token.methods,
   67             system=token.system, domain_id=token.domain_id,
   68             project_id=token.project_id, trust_id=token.trust_id,
   69             federated_group_ids=token.federated_groups,
   70             identity_provider_id=token.identity_provider_id,
   71             protocol_id=token.protocol_id,
   72             access_token_id=token.access_token_id,
   73             app_cred_id=token.application_credential_id
   74         )
   75 
   76     def validate_token(self, token_id):
   77         return self.token_formatter.validate_token(token_id)
   78 
   79 
   80 class JWSFormatter(object):
   81 
   82     # NOTE(lbragstad): If in the future we expand support for different
   83     # algorithms, make this configurable and validate it against a blessed list
   84     # of supported algorithms.
   85     algorithm = 'ES256'
   86 
   87     @property
   88     def private_key(self):
   89         private_key_path = os.path.join(
   90             CONF.jwt_tokens.jws_private_key_repository, 'private.pem'
   91         )
   92         with open(private_key_path, 'r') as f:
   93             key = f.read()
   94         return key
   95 
   96     @property
   97     def public_keys(self):
   98         keys = []
   99         key_repo = CONF.jwt_tokens.jws_public_key_repository
  100         for keyfile in os.listdir(key_repo):
  101             with open(os.path.join(key_repo, keyfile), 'r') as f:
  102                 keys.append(f.read())
  103         return keys
  104 
  105     def create_token(self, user_id, expires_at, audit_ids, methods,
  106                      system=None, domain_id=None, project_id=None,
  107                      trust_id=None, federated_group_ids=None,
  108                      identity_provider_id=None, protocol_id=None,
  109                      access_token_id=None, app_cred_id=None):
  110 
  111         issued_at = utils.isotime(subsecond=True)
  112         issued_at_int = self._convert_time_string_to_int(issued_at)
  113         expires_at_int = self._convert_time_string_to_int(expires_at)
  114 
  115         payload = {
  116             # public claims
  117             'sub': user_id,
  118             'iat': issued_at_int,
  119             'exp': expires_at_int,
  120             # private claims
  121             'openstack_methods': methods,
  122             'openstack_audit_ids': audit_ids,
  123             'openstack_system': system,
  124             'openstack_domain_id': domain_id,
  125             'openstack_project_id': project_id,
  126             'openstack_trust_id': trust_id,
  127             'openstack_group_ids': federated_group_ids,
  128             'openstack_idp_id': identity_provider_id,
  129             'openstack_protocol_id': protocol_id,
  130             'openstack_access_token_id': access_token_id,
  131             'openstack_app_cred_id': app_cred_id
  132         }
  133 
  134         # NOTE(lbragstad): Calling .items() on a dictionary in python 2 returns
  135         # a list but returns an iterable in python 3. Casting to a list makes
  136         # it safe to modify the dictionary while iterating over it, regardless
  137         # of the python version.
  138         for k, v in list(payload.items()):
  139             if v is None:
  140                 payload.pop(k)
  141 
  142         token_id = jwt.encode(
  143             payload,
  144             self.private_key,
  145             algorithm=JWSFormatter.algorithm
  146         )
  147         return token_id, issued_at
  148 
  149     def validate_token(self, token_id):
  150         payload = self._decode_token_from_id(token_id)
  151 
  152         user_id = payload['sub']
  153         expires_at_int = payload['exp']
  154         issued_at_int = payload['iat']
  155         methods = payload['openstack_methods']
  156         audit_ids = payload['openstack_audit_ids']
  157 
  158         system = payload.get('openstack_system', None)
  159         domain_id = payload.get('openstack_domain_id', None)
  160         project_id = payload.get('openstack_project_id', None)
  161         trust_id = payload.get('openstack_trust_id', None)
  162         federated_group_ids = payload.get('openstack_group_ids', None)
  163         identity_provider_id = payload.get('openstack_idp_id', None)
  164         protocol_id = payload.get('openstack_protocol_id', None)
  165         access_token_id = payload.get('openstack_access_token_id', None)
  166         app_cred_id = payload.get('openstack_app_cred_id', None)
  167 
  168         issued_at = self._convert_time_int_to_string(issued_at_int)
  169         expires_at = self._convert_time_int_to_string(expires_at_int)
  170 
  171         return (
  172             user_id, methods, audit_ids, system, domain_id, project_id,
  173             trust_id, federated_group_ids, identity_provider_id, protocol_id,
  174             access_token_id, app_cred_id, issued_at, expires_at
  175         )
  176 
  177     def _decode_token_from_id(self, token_id):
  178         options = dict()
  179         options['verify_exp'] = False
  180         for public_key in self.public_keys:
  181             try:
  182                 return jwt.decode(
  183                     token_id, public_key, algorithms=JWSFormatter.algorithm,
  184                     options=options
  185                 )
  186             except (jwt.InvalidSignatureError, jwt.DecodeError):
  187                 pass    # nosec: We want to exhaustively try all public keys
  188         raise exception.TokenNotFound(token_id=token_id)
  189 
  190     def _convert_time_string_to_int(self, time_str):
  191         time_object = timeutils.parse_isotime(time_str)
  192         normalized = timeutils.normalize_time(time_object)
  193         epoch = datetime.datetime.utcfromtimestamp(0)
  194         return int((normalized - epoch).total_seconds())
  195 
  196     def _convert_time_int_to_string(self, time_int):
  197         time_object = datetime.datetime.utcfromtimestamp(time_int)
  198         return utils.isotime(at=time_object, subsecond=True)