Ejemplo n.º 1
0
    def __init__(self,
                 conf,
                 keyjar=None,
                 client_db=None,
                 session_db=None,
                 cwd='',
                 cookie_dealer=None):
        self.conf = conf
        self.keyjar = keyjar or KeyJar()
        self.cwd = cwd

        if session_db:
            self.sdb = session_db
        else:
            self.sdb = create_session_db(
                conf['password'],
                db=None,
                token_expires_in=conf['token_expires_in'],
                grant_expires_in=conf['grant_expires_in'],
                refresh_token_expires_in=conf['refresh_token_expires_in'],
                sso_db=SSODb())

        # client database
        self.cdb = client_db or {}

        try:
            self.seed = bytes(conf['seed'], 'utf-8')
        except KeyError:
            self.seed = bytes(rndstr(16), 'utf-8')

        # Default values, to be changed below depending on configuration
        self.endpoint = {}
        self.issuer = ''
        self.verify_ssl = True
        self.jwks_uri = None
        self.sso_ttl = 14400  # 4h
        self.symkey = rndstr(24)
        self.id_token_schema = IdToken
        self.endpoint_to_authn_method = {}
        self.cookie_dealer = cookie_dealer

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

        template_dir = conf["template_dir"]
        jinja_env = Environment(loader=FileSystemLoader(template_dir))

        self.setup = {}
        try:
            self.jwks_uri = '{}/{}'.format(self.issuer,
                                           conf['jwks']['public_path'])
        except KeyError:
            self.jwks_uri = ''

        self.endpoint = build_endpoints(
            conf['endpoint'],
            endpoint_context=self,
            client_authn_method=CLIENT_AUTHN_METHOD,
            issuer=conf['issuer'])
        try:
            _cap = conf['capabilities']
        except KeyError:
            _cap = {}

        for endpoint in ['authorization', 'token', 'userinfo', 'registration']:
            try:
                endpoint_spec = self.endpoint[endpoint]
            except KeyError:
                pass
            else:
                _cap[endpoint_spec.endpoint_name] = '{}'.format(
                    self.endpoint[endpoint].endpoint_path)

        try:
            authz_spec = conf['authz']
        except KeyError:
            self.authz = authz.Implicit(self)
        else:
            if 'args' in authz_spec:
                self.authz = authz.factory(authz_spec['name'],
                                           **authz_spec['args'])
            else:
                self.authz = authz.factory(self, authz_spec['name'])

        try:
            _authn = conf['authentication']
        except KeyError:
            self.authn_broker = None
        else:
            self.authn_broker = AuthnBroker()

            for authn_spec in _authn:
                try:
                    _args = authn_spec['kwargs']
                except KeyError:
                    _args = {}

                if 'template' in _args:
                    _args['template_env'] = jinja_env

                _args['endpoint_context'] = self
                authn_method = user.factory(authn_spec['name'], **_args)
                args = {
                    k: authn_spec[k]
                    for k in ['acr', 'level', 'authn_authority']
                    if k in authn_spec
                }

                self.authn_broker.add(method=authn_method, **args)
                self.endpoint_to_authn_method[
                    authn_method.url_endpoint] = authn_method

        try:
            _conf = conf['userinfo']
        except KeyError:
            pass
        else:
            try:
                kwargs = _conf['kwargs']
            except KeyError:
                kwargs = {}

            if 'db_file' in kwargs:
                kwargs['db_file'] = os.path.join(self.cwd, kwargs['db_file'])
            self.userinfo = _conf['class'](**kwargs)

        self.provider_info = self.create_providerinfo(_cap)

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

        # special type of logging
        self.events = None
Ejemplo n.º 2
0
    def __init__(
        self,
        conf,
        keyjar=None,
        client_db=None,
        session_db=None,
        cwd="",
        cookie_dealer=None,
        httpc=None,
        cookie_name=None,
        jwks_uri_path=None,
    ):
        self.conf = conf
        self.keyjar = keyjar or KeyJar()
        self.cwd = cwd

        # client database
        self.cdb = client_db or {}

        try:
            self.seed = bytes(conf["seed"], "utf-8")
        except KeyError:
            self.seed = bytes(rndstr(16), "utf-8")

        # Default values, to be changed below depending on configuration
        self.endpoint = {}
        self.issuer = ""
        self.httpc = httpc or requests
        self.verify_ssl = True
        self.jwks_uri = None
        self.sso_ttl = 14400  # 4h
        self.symkey = rndstr(24)
        self.id_token_schema = IdToken
        self.endpoint_to_authn_method = {}
        self.cookie_dealer = cookie_dealer
        self.login_hint_lookup = None

        if cookie_name:
            self.cookie_name = cookie_name
        elif "cookie_name" in conf:
            self.cookie_name = conf["cookie_name"]
        else:
            self.cookie_name = {
                "session": "oidcop",
                "register": "oidc_op_rp",
                "session_management": "sman",
            }

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

        try:
            self.template_handler = conf["template_handler"]
        except KeyError:
            try:
                loader = conf["template_loader"]
            except KeyError:
                template_dir = conf["template_dir"]
                loader = Environment(loader=FileSystemLoader(template_dir),
                                     autoescape=True)
            self.template_handler = Jinja2TemplateHandler(loader)

        self.setup = {}
        if not jwks_uri_path:
            try:
                jwks_uri_path = conf["jwks"]["uri_path"]
            except KeyError:
                pass

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

        if self.keyjar is None or self.keyjar.owners() == []:
            args = {k: v for k, v in conf["jwks"].items() if k != "uri_path"}
            self.keyjar = init_key_jar(**args)

        try:
            _conf = conf["cookie_dealer"]
        except KeyError:
            pass
        else:
            if self.cookie_dealer:  # already defined
                raise ValueError("Cookie Dealer already defined")
            self.cookie_dealer = init_service(_conf)

        try:
            _conf = conf["sub_func"]
        except KeyError:
            sub_func = None
        else:
            sub_func = {}
            for key, args in _conf.items():
                if "class" in args:
                    sub_func[key] = init_service(args)
                elif "function" in args:
                    if isinstance(args["function"], str):
                        sub_func[key] = util.importer(args["function"])
                    else:
                        sub_func[key] = args["function"]

        if session_db:
            self.sdb = session_db
        else:
            try:
                _th_args = conf["token_handler_args"]
            except KeyError:
                # create 3 keys
                keydef = [
                    {
                        "type": "oct",
                        "bytes": "24",
                        "use": ["enc"],
                        "kid": "code"
                    },
                    {
                        "type": "oct",
                        "bytes": "24",
                        "use": ["enc"],
                        "kid": "token"
                    },
                    {
                        "type": "oct",
                        "bytes": "24",
                        "use": ["enc"],
                        "kid": "refresh"
                    },
                ]

                jwks_def = {
                    "private_path": "private/token_jwks.json",
                    "key_defs": keydef,
                    "read_only": False,
                }

                _th_args = {"jwks_def": jwks_def}
                for typ, tid in [("code", 600), ("token", 3600),
                                 ("refresh", 86400)]:
                    _th_args[typ] = {"lifetime": tid}

            self.sdb = create_session_db(self,
                                         _th_args,
                                         db=None,
                                         sso_db=SSODb(),
                                         sub_func=sub_func)

        self.endpoint = build_endpoints(
            conf["endpoint"],
            endpoint_context=self,
            client_authn_method=CLIENT_AUTHN_METHOD,
            issuer=conf["issuer"],
        )
        try:
            _cap = conf["capabilities"]
        except KeyError:
            _cap = {}

        for endpoint, endpoint_instance in self.endpoint.items():
            if endpoint_instance.provider_info:
                _cap.update(endpoint_instance.provider_info)

            if endpoint in ["webfinger", "provider_info"]:
                continue

            _cap[endpoint_instance.endpoint_name] = "{}".format(
                endpoint_instance.endpoint_path)

        try:
            authz_spec = conf["authz"]
        except KeyError:
            self.authz = authz.Implicit(self)
        else:
            self.authz = init_service(authz_spec, self)

        try:
            _authn = conf["authentication"]
        except KeyError:
            self.authn_broker = None
        else:
            self.authn_broker = populate_authn_broker(_authn, self,
                                                      self.template_handler)

        try:
            _conf = conf["id_token"]
        except KeyError:
            self.idtoken = IDToken(self)
        else:
            self.idtoken = init_service(_conf, self)

        try:
            _conf = conf["userinfo"]
        except KeyError:
            pass
        else:
            self.userinfo = init_user_info(_conf, self.cwd)
            self.sdb.userinfo = self.userinfo

        try:
            _conf = conf["login_hint_lookup"]
        except KeyError:
            pass
        else:
            self.login_hint_lookup = init_service(_conf)
            if self.userinfo:
                self.login_hint_lookup.user_info = self.userinfo

        try:
            _conf = conf["login_hint2acrs"]
        except KeyError:
            self.login_hint2acrs = None
        else:
            self.login_hint2acrs = init_service(_conf)

        self.provider_info = self.create_providerinfo(_cap)

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

        # special type of logging
        self.events = None

        # client registration access tokens
        self.registration_access_token = {}
Ejemplo n.º 3
0
 def do_session_db(self, sso_db, db=None):
     self.sdb = create_session_db(self,
                                  self.th_args,
                                  db=db,
                                  sso_db=sso_db,
                                  sub_func=self._sub_func)