Пример #1
0
    def __init__(self,
                 entity_id,
                 trusted_roots,
                 authority_hints=None,
                 default_lifetime=86400,
                 httpd=None,
                 priority=None,
                 entity_type='',
                 opponent_entity_type='',
                 registration_type='',
                 cwd='',
                 httpc_params=None,
                 config=None):
        OidcContext.__init__(self, config, entity_id=entity_id)
        self.collector = Collector(trust_anchors=trusted_roots,
                                   http_cli=httpd,
                                   cwd=cwd,
                                   httpc_params=httpc_params,
                                   db_conf=self.db_conf)
        self.entity_id = entity_id
        self.entity_type = entity_type
        self.opponent_entity_type = opponent_entity_type

        for iss, jwks in trusted_roots.items():
            self.keyjar.import_jwks(jwks, iss)

        self.authority_hints = authority_hints
        self.default_lifetime = default_lifetime
        self.tr_priority = priority or sorted(set(trusted_roots.keys()))
        self.registration_type = registration_type
    def test_context_with_entity_id_and_keys(self):
        conf = copy.deepcopy(self.conf)
        conf["keys"] = {"key_defs": KEYDEF}
        c = OidcContext(conf, entity_id="https://example.com")

        mem = c.dump()
        c2 = OidcContext().load(mem)
        assert set(c2.keyjar.owners()) == {"", "https://example.com"}
Пример #3
0
    def __init__(self,
                 entity_id="",
                 trusted_roots=None,
                 authority_hints=None,
                 default_lifetime=86400,
                 httpd=None,
                 priority=None,
                 entity_type='',
                 opponent_entity_type='',
                 registration_type='',
                 cwd='',
                 httpc_params=None,
                 config=None):
        if config is None:
            config = {}

        self.entity_id = entity_id or config["entity_id"]

        OidcContext.__init__(self, config, entity_id=self.entity_id)

        self.entity_type = entity_type or config.get("entity_type")
        self.opponent_entity_type = opponent_entity_type or config.get(
            "opponent_entity_type", "")
        self.registration_type = registration_type or config.get(
            "registration_type", "")
        self.default_lifetime = default_lifetime or config.get(
            "default_lifetime", 0)
        self.httpc_params = httpc_params or config.get("httpc_params", {})
        if not trusted_roots:
            trusted_roots = json.loads(open(config["trusted_roots"]).read())

        self.collector = Collector(trust_anchors=trusted_roots,
                                   http_cli=httpd,
                                   cwd=cwd,
                                   httpc_params=self.httpc_params)

        for iss, jwks in trusted_roots.items():
            self.keyjar.import_jwks(jwks, iss)

        if authority_hints is not None:
            self.authority_hints = authority_hints
        elif "authority_hints" in config:
            self.authority_hints = json.loads(
                open(config["authority_hints"]).read())
        else:
            raise ConfigurationError("Missing authority_hints specification")

        if priority:
            self.tr_priority = priority
        elif 'priority' in config:
            self.tr_priority = config["priority"]
        else:
            self.tr_priority = sorted(set(trusted_roots.keys()))
    def test_context_restore(self):
        conf = copy.deepcopy(self.conf)
        conf["keys"] = {"key_defs": KEYDEF}

        c = OidcContext(conf, entity_id="https://example.com")
        mem = c.dump()
        c2 = OidcContext().load(mem)

        assert set(c2.keyjar.owners()) == {"", "https://example.com"}
        assert len(c2.keyjar.get("sig", "EC")) == 1
        assert len(c2.keyjar.get("enc", "EC")) == 1
        assert len(c.keyjar.get("sig", "RSA")) == 0
        assert len(c.keyjar.get("sig", "oct")) == 0
    def test_context_with_entity_id_and_jwks(self):
        conf = copy.deepcopy(self.conf)
        conf["jwks"] = JWKS
        c = OidcContext(conf, entity_id="https://example.com")

        mem = c.dump()
        c2 = OidcContext().load(mem)

        assert set(c2.keyjar.owners()) == {"", "https://example.com"}
        assert len(c2.keyjar.get("sig", "RSA")) == 1
        assert len(c2.keyjar.get("sig", "RSA", issuer_id="https://example.com")) == 1
        assert len(c2.keyjar.get("sig", "oct")) == 1
        assert len(c2.keyjar.get("sig", "oct", issuer_id="https://example.com")) == 1
Пример #6
0
    def test_context_with_entity_id_and_jwks(self):
        conf = copy.deepcopy(self.conf)
        conf['jwks'] = JWKS

        c = OidcContext(conf, entity_id='https://example.com')
        assert set(c.keyjar.owners()) == {'', 'https://example.com'}
        assert len(c.keyjar.get('sig', 'RSA')) == 1
        assert len(c.keyjar.get('sig', 'RSA',
                                issuer_id='https://example.com')) == 1
        assert len(c.keyjar.get('sig', 'oct')) == 1
        assert len(c.keyjar.get('sig', 'oct',
                                issuer_id='https://example.com')) == 1
 def test_context_with_entity_id_no_keys(self):
     c = OidcContext(self.conf, entity_id="https://example.com")
     mem = c.dump()
     c2 = OidcContext().load(mem)
     assert c2.keyjar.owners() == []
     assert c2.issuer == "https://example.com"
def test_dump_load():
    c = OidcContext({})
    assert c.keyjar is not None
    mem = c.dump()
    c2 = OidcContext().load(mem)
    assert c2.keyjar is not None
Пример #9
0
    def __init__(
        self,
        conf: Union[dict, OPConfiguration],
        keyjar: Optional[KeyJar] = None,
        cwd: Optional[str] = "",
        cookie_handler: Optional[Any] = None,
        httpc: Optional[Any] = None,
    ):
        OidcContext.__init__(self, conf, keyjar, entity_id=conf.get("issuer", ""))
        self.conf = conf

        # For my Dev environment
        self.cdb = {}
        self.jti_db = {}
        self.registration_access_token = {}
        # self.session_db = {}

        self.cwd = cwd

        # Default values, to be changed below depending on configuration
        # arguments for endpoints add-ons
        self.args = {}
        self.authn_broker = None
        self.authz = None
        self.cookie_handler = cookie_handler
        self.endpoint_to_authn_method = {}
        self.httpc = httpc or requests
        self.idtoken = None
        self.issuer = ""
        self.jwks_uri = None
        self.login_hint_lookup = None
        self.login_hint2acrs = None
        self.par_db = {}
        self.provider_info = {}
        self.scope2claims = SCOPE2CLAIMS
        self.session_manager = None
        self.sso_ttl = 14400  # 4h
        self.symkey = rndstr(24)
        self.template_handler = None
        self.token_args_methods = []
        self.userinfo = None

        for param in [
            "issuer",
            "sso_ttl",
            "symkey",
            "client_authn",
            # "id_token_schema",
        ]:
            try:
                setattr(self, param, conf[param])
            except KeyError:
                pass

        self.th_args = get_token_handler_args(conf)

        # session db
        self._sub_func = {}
        self.do_sub_func()

        _handler = conf.get("template_handler")
        if _handler:
            self.template_handler = _handler
        else:
            _loader = conf.get("template_loader")

            if _loader is None:
                _template_dir = conf.get("template_dir")
                if _template_dir:
                    _loader = Environment(loader=FileSystemLoader(_template_dir), autoescape=True)

            if _loader:
                self.template_handler = Jinja2TemplateHandler(_loader)

        # self.setup = {}
        _keys_conf = conf.get("keys")
        if _keys_conf:
            jwks_uri_path = _keys_conf["uri_path"]

            if self.issuer.endswith("/"):
                self.jwks_uri = "{}{}".format(self.issuer, jwks_uri_path)
            else:
                self.jwks_uri = "{}/{}".format(self.issuer, jwks_uri_path)

        for item in [
            "cookie_handler",
            "authentication",
            "id_token",
            "scope2claims",
        ]:
            _func = getattr(self, "do_{}".format(item), None)
            if _func:
                _func()

        for item in ["login_hint2acrs"]:
            _func = getattr(self, "do_{}".format(item), None)
            if _func:
                _func()

        # which signing/encryption algorithms to use in what context
        self.jwx_def = {}

        # The HTTP clients request arguments
        _cnf = conf.get("httpc_params")
        if _cnf:
            self.httpc_params = get_http_params(_cnf)
        else:  # Backward compatibility
            self.httpc_params = {"verify": conf.get("verify_ssl", True)}

        self.set_scopes_handler()
        self.dev_auth_db = None
        self.claims_interface = None
Пример #10
0
    def test_context_with_entity_id_and_keys(self):
        conf = copy.deepcopy(self.conf)
        conf['keys'] = {'key_defs': KEYDEF}

        c = OidcContext(conf, entity_id='https://example.com')
        assert set(c.keyjar.owners()) == {'', 'https://example.com'}
Пример #11
0
 def test_context_with_entity_id_no_keys(self):
     c = OidcContext(self.conf, entity_id='https://example.com')
     assert c.keyjar.owners() == []
Пример #12
0
def test_context():
    c = OidcContext({})
    assert c.keyjar is not None
Пример #13
0
    def __init__(self,
                 config: Union[dict, Configuration],
                 entity_id: str = "",
                 server_get: Callable = None,
                 keyjar: Optional[KeyJar] = None,
                 authority_hints: Optional[Union[List[str], str]] = None,
                 default_lifetime: Optional[int] = 86400,
                 priority: Optional[List[str]] = None,
                 entity_type: Optional[str] = '',
                 opponent_entity_type: Optional[str] = '',
                 registration_type: Optional[str] = '',
                 trust_marks: Optional[List[str]] = None):

        self.config = config
        self.server_get = server_get
        self.entity_id = entity_id or config.get("entity_id")

        OidcContext.__init__(self, config, keyjar, entity_id=self.entity_id)

        self.entity_type = entity_type or config.get("entity_type")
        self.opponent_entity_type = opponent_entity_type or config.get(
            "opponent_entity_type", "")
        self.registration_type = registration_type or config.get(
            "registration_type", "")
        self.default_lifetime = default_lifetime or config.get(
            "default_lifetime", 0)
        self.trust_mark_issuer = None
        self.signed_trust_marks = []
        self.trust_marks = trust_marks or config.get("trust_marks", [])

        _trusted_roots = config.get("trusted_roots")
        if _trusted_roots is None:
            # Must be trust anchor then
            self.trusted_roots = {}
        elif isinstance(_trusted_roots, str):
            self.trusted_roots = json.loads(open(_trusted_roots).read())
        else:
            self.trusted_roots = _trusted_roots

        # Store own keys in the key jar under the entity's ID
        self.keyjar.import_jwks(self.keyjar.export_jwks(private=True),
                                issuer_id=self.entity_id)

        for iss, jwks in self.trusted_roots.items():
            self.keyjar.import_jwks(jwks, iss)

        if authority_hints is not None:
            self.authority_hints = authority_hints
        else:
            _hints = config.get("authority_hints")
            if _hints is None:
                print(f"{_hints}, {self.trusted_roots}")
                # if self.trusted_roots != {}:
                #     raise ConfigurationError("Missing authority_hints specification")
                self.authority_hints = []
            elif isinstance(_hints, str):
                self.authority_hints = json.loads(open(_hints).read())
            else:
                self.authority_hints = _hints

        if priority:
            self.tr_priority = priority
        elif 'priority' in config:
            self.tr_priority = config["priority"]
        else:
            self.tr_priority = sorted(set(self.trusted_roots.keys()))

        _sstm = config.get("self_signed_trust_marks")
        if _sstm:
            self.signed_trust_marks = create_self_signed_trust_marks(
                entity_id=self.entity_id, keyjar=self.keyjar, spec=_sstm)
    def __init__(self, base_url="", keyjar=None, config=None, state=None, **kwargs):
        if config is None:
            config = {}
        self.config = config

        OidcContext.__init__(self, config, keyjar, entity_id=config.get('client_id', ''))
        self.state = state or StateInterface()

        self.kid = {"sig": {}, "enc": {}}

        self.base_url = base_url
        # Below so my IDE won't complain
        self.allow = {}
        self.client_preferences = {}
        self.args = {}
        self.add_on = {}
        self.hash2issuer = {}
        self.httpc_params = {}
        self.issuer = ""
        self.client_id = ""
        self.client_secret = ""
        self.client_secret_expires_at = 0
        self.behaviour = {}
        self.provider_info = {}
        self.post_logout_redirect_uris = []
        self.redirect_uris = []
        self.register_args = {}
        self.registration_response = {}
        self.requests_dir = ''

        _def_value = copy.deepcopy(DEFAULT_VALUE)
        # Dynamic information
        for param in ['client_secret', 'client_id', 'redirect_uris', 'provider_info',
                      'behaviour', 'callback', 'issuer']:
            _val = config.get(param, _def_value[param])
            self.set(param, _val)
            if param == 'client_secret' and _val:
                self.keyjar.add_symmetric('', _val)

        if not self.issuer:
            self.issuer = self.provider_info.get("issuer", "")

        try:
            self.clock_skew = config['clock_skew']
        except KeyError:
            self.clock_skew = 15

        _seed = config.get("hash_seed")
        if _seed:
            self.hash_seed = as_bytes(_seed)
        else:
            self.hash_seed = as_bytes(rndstr(32))

        for key, val in kwargs.items():
            setattr(self, key, val)

        for attr in ['base_url', 'requests_dir', 'allow', 'client_preferences', 'verify_args']:
            try:
                setattr(self, attr, config[attr])
            except KeyError:
                pass

        for attr in RegistrationRequest.c_param:
            try:
                self.register_args[attr] = config[attr]
            except KeyError:
                pass

        if self.requests_dir:
            # make sure the path exists. If not, then make it.
            if not os.path.isdir(self.requests_dir):
                os.makedirs(self.requests_dir)

        # The name of the attribute used to be keys. Is not key_conf
        _key_conf = config.get('keys', config.get('key_conf'))
        if _key_conf:
            self.import_keys(_key_conf)