Beispiel #1
0
def get_subject_conf(entity_type, id):
    if entity_type in ["openid_provider", "openid_relying_party"]:
        head, tail = os.path.split(dir_path)
        _path = os.path.join(head, entity_type, id)
        e_cnf = {"class": CNF_MAP[entity_type], "attr": ATTR_MAP[entity_type]}
        if entity_type == "openid_provider":
            e_cnf["path"] = ["op", "server_info"]

        _conf = create_from_config_file(Configuration,
                                        entity_conf=[e_cnf],
                                        filename=os.path.join(
                                            _path, "conf.json"),
                                        base_path=_path)
        ent_conf = _conf[ATTR_MAP[entity_type]]

        keys_args = {
            k: v
            for k, v in ent_conf["federation"]["keys"].items()
            if k != "uri_path"
        }
        _keyjar = init_key_jar(**keys_args)

        _entity_id = ent_conf["federation"].get("entity_id")
        if _entity_id.endswith("/{}"):  # allow tenant ID
            _entity_id = _entity_id[:-3]
        d_path = os.path.join("authorities", i_am, entity_type,
                              quote_plus(_entity_id))
        if os.path.isdir(d_path):
            pass
        else:
            os.makedirs(d_path)
        file_path = os.path.join(d_path, "jwks.json")
        return file_path, _keyjar
    else:
        _path = os.path.join(dir_path, entity_type, id)
        _conf = create_from_config_file(
            FedEntityConfiguration,
            filename=os.path.join(_path, "conf.json"),
            file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
            base_path=_path)
        keys_args = {k: v for k, v in _conf["keys"].items() if k != "uri_path"}
        _keyjar = init_key_jar(**keys_args)
        d_path = os.path.join("authorities", i_am, id)
        if os.path.isdir(d_path):
            pass
        else:
            os.makedirs(d_path)
        file_path = os.path.join(d_path, "jwks.json")

        return file_path, _keyjar
Beispiel #2
0
def oidc_provider_init_app(config_file, name=None, **kwargs):
    name = name or __name__
    app = Flask(name, static_url_path='', **kwargs)

    app.srv_config = create_from_config_file(Configuration,
                                             entity_conf=[{
                                                 "class": FedRPConfiguration,
                                                 "attr": "rp"
                                             }],
                                             filename=config_file,
                                             base_path=dir_path)

    app.users = {'test_user': {'name': 'Testing Name'}}

    try:
        from .views import oidc_rp_views
    except ImportError:
        from views import oidc_rp_views

    app.register_blueprint(oidc_rp_views)

    # Initialize the oidc_provider after views to be able to set correct urls
    app.rph = init_oidc_rp_handler(app.srv_config.rp, dir_path)

    return app
Beispiel #3
0
def init_app(config_file, name=None, **kwargs) -> Flask:
    name = name or __name__
    app = Flask(name, static_url_path='', **kwargs)

    app.srv_config = create_from_config_file(Configuration,
                                             entity_conf=[{
                                                 "class":
                                                 FedEntityConfiguration,
                                                 "attr":
                                                 "federation",
                                                 "path": ["federation"]
                                             }],
                                             filename=config_file,
                                             base_path=dir_path)

    # app.users = {'test_user': {'name': 'Testing Name'}}

    try:
        from .views import intermediate
    except ImportError:
        from views import intermediate

    app.register_blueprint(intermediate)

    # Initialize the oidc_provider after views to be able to set correct urls
    app.server = init_entity(app.srv_config.federation, dir_path)

    return app
Beispiel #4
0
    def __init__(self, base_path, entity_id_pattern="https://{}", federation_entities="", **kwargs):
        self.lifetime = kwargs["lifetime"]
        self.entity_id_pattern = create_regex(entity_id_pattern)
        self.signer = {}
        for iss in os.listdir(federation_entities):
            _signer = FetchEntityStatement(iss, entity_id_pattern)
            _signer.fe_base_path = os.path.join(base_path, federation_entities, iss)
            _signer.auth_base_path = os.path.join(base_path, kwargs["authorities"], iss)
            cargs = {k: kwargs[k] for k in ['domain', 'port'] if k in kwargs}
            _conf = create_from_config_file(FedEntityConfiguration,
                                            filename=os.path.join(_signer.fe_base_path,
                                                                  "conf.json"),
                                            file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
                                            base_path=_signer.fe_base_path,
                                            **cargs)
            _conf.entity_type = "federation_entity"
            _signer.federation_api_endpoint = kwargs["federation_api_endpoint"].format(
                domain=kwargs["domain"], port=kwargs["port"])
            _signer.conf = _conf
            keys_args = {k: v for k, v in _conf["keys"].items() if k != "uri_path"}
            keys_args["issuer_id"] = _signer.make_entity_id(iss)
            _signer.keyjar = init_key_jar(**keys_args)

            if 'url_prefix' in kwargs:
                self.url_prefix = kwargs['url_prefix']
            self.signer[iss] = _signer
Beispiel #5
0
def get_federation_config(entities, id):
    _dir, _, _conf_file, _sub = entities[id]
    _config = create_from_config_file(Configuration,
                                      filename=os.path.join(_dir, _conf_file))
    if id == 'OP':
        return _config["conf"]["op"]["server_info"]["federation"]
    else:
        return _config["conf"]["federation"]
Beispiel #6
0
def get_subject_info(ta):
    _path = os.path.join(dir_path, "signing_service", "federation_entity", ta)
    _conf = create_from_config_file(
        FedEntityConfiguration,
        filename=os.path.join(_path, "conf.json"),
        file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
        base_path=_path)
    keys_args = {k: v for k, v in _conf["keys"].items() if k != "uri_path"}
    _keyjar = init_key_jar(**keys_args)

    return _keyjar
Beispiel #7
0
def test_init_rp():
    config = create_from_config_file(
        FedRPConfiguration,
        entity_conf=[{
            "class": FedRPConfiguration,
            "attr": "rp"
        }],
        filename=full_path('conf_foodle.uninett.no_auto.json'),
        base_path=BASE_PATH)
    rph = init_oidc_rp_handler(config, BASE_PATH)
    rp = rph.init_client('ntnu')
    assert rp
def test_dict():
    configuration = create_from_config_file(RPConfiguration,
                                            filename=os.path.join(
                                                _dirname, 'rp_conf.yaml'),
                                            base_path=_dirname)
    assert configuration

    assert configuration.base_url == "https://127.0.0.1:8090"
    assert configuration.httpc_params == {"verify": False}
    assert set(configuration.services.keys()) == {
        'discovery', 'registration', 'authorization', 'accesstoken',
        'userinfo', 'end_session'
    }
    assert set(configuration.clients.keys()) == {'', 'bobcat', 'flop'}
def test_entity_config(filename):
    configuration = create_from_config_file(EntityConfiguration,
                                            filename=os.path.join(
                                                _dirname, filename),
                                            base_path=_dirname)
    assert configuration

    assert configuration.base_url == "https://127.0.0.1:8090"
    assert configuration.httpc_params == {"verify": False}
    assert configuration['keys']
    ni = dict(configuration.items())
    assert len(ni) == 9
    assert set(ni.keys()) == {
        'base_url', '_dir_attributes', '_file_attributes', 'hash_seed',
        'httpc_params', 'keys', 'conf', 'port', 'domain'
    }
def test_server_config():
    configuration = create_from_config_file(Configuration,
                                            entity_conf=[{
                                                "class": EntityConfiguration,
                                                "attr": "entity"
                                            }],
                                            filename=os.path.join(
                                                _dirname, 'server_conf.json'),
                                            base_path=_dirname)
    assert configuration
    assert set(configuration.web_conf.keys()) == {
        'port', 'domain', 'server_cert', 'server_key', 'debug'
    }

    entity_config = configuration.entity
    assert entity_config.base_url == "https://127.0.0.1:8090"
    assert entity_config.httpc_params == {"verify": False}
Beispiel #11
0
    def create_rph(self):
        _file = os.path.join(BASE_PATH, "conf_rp_auto.json")
        # automatic means no implicit registration
        config = create_from_config_file(
            RPConfiguration,
            entity_conf=[{
                "class": FedEntityConfiguration,
                "attr": "federation",
                "path": ["federation"]
            }],
            filename=_file,
            base_path=BASE_PATH,
            file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES)

        self.rph1 = init_rp_handler(config)
        self.rph2 = init_rp_handler(config)

        self.subject = 'https://op.umu.se'
        self.intermediate = 'https://umu.se'
        self.fedop = 'https://swamid.se'
def test_yaml_config():
    c = create_from_config_file(Configuration,
                                entity_conf=[{
                                    "class": RPConfiguration,
                                    "attr": "rp"
                                }],
                                filename=os.path.join(_dirname, 'conf.yaml'),
                                base_path=_dirname)
    assert c
    assert set(c.web_conf.keys()) == {
        'port', 'domain', 'server_cert', 'server_key', 'debug'
    }

    rp_config = c.rp
    assert rp_config.base_url == "https://127.0.0.1:8090"
    assert rp_config.httpc_params == {"verify": False}
    assert set(rp_config.services.keys()) == {
        'discovery', 'registration', 'authorization', 'accesstoken',
        'userinfo', 'end_session'
    }
    assert set(rp_config.clients.keys()) == {'', 'bobcat', 'flop'}
Beispiel #13
0
def init_app(config_file: str, name: Optional[str] = "", **kwargs) -> Tuple[Flask, Configuration]:
    name = name or __name__
    app = Flask(name, static_url_path='', **kwargs)

    try:
        from .views import sigserv_views
    except ImportError:
        from views import sigserv_views

    app.register_blueprint(sigserv_views)

    _config = create_from_config_file(Configuration,
                                      entity_conf=[{
                                          'class': FedSigServConfiguration,
                                          'attr': 'sigsrv'
                                      }],
                                      filename=config_file)

    app.signing_service = SigningService(_config.sigsrv.server_info, cwd=dir_path,
                                         domain=_config.domain, port=_config.port)

    return app, _config
Beispiel #14
0
def main(config_file, args):
    logging.basicConfig(level=logging.DEBUG)
    config = create_from_config_file(
        Configuration,
        entity_conf=[{
            "class": FedOpConfiguration,
            "attr": "op",
            "path": ["op", "server_info"]
        }],
        file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
        filename=config_file)
    app = oidc_provider_init_app(config, name=args.name)

    web_conf = config.web_conf

    context = create_context(dir_path, web_conf)

    kwargs = {}

    _srv_context = app.server.server_get("endpoint_context")

    if args.display:
        print(json.dumps(_srv_context.provider_info, indent=4, sort_keys=True))
        exit(0)

    if args.insecure:
        _srv_context.federation_entity.collector.insecure = True

    _cert = os.path.join(dir_path, lower_or_upper(web_conf, "server_cert"))
    _srv_context.federation_entity.collector.web_cert_path = _cert

    app.run(host=web_conf['domain'],
            port=web_conf['port'],
            debug=web_conf['debug'],
            ssl_context=context,
            **kwargs)
Beispiel #15
0
from oidcmsg.configure import create_from_config_file

from oidcrp.configure import Configuration
from oidcrp.configure import RPConfiguration
from oidcrp.util import create_context

try:
    from . import application
except ImportError:
    import application

dir_path = os.path.dirname(os.path.realpath(__file__))

if __name__ == "__main__":
    conf = sys.argv[1]
    name = 'oidc_rp'
    template_dir = os.path.join(dir_path, 'templates')

    _config = create_from_config_file(Configuration,
                                      entity_conf=[{"class": RPConfiguration, "attr": "rp"}],
                                      filename=conf)

    app = application.oidc_provider_init_app(_config.rp, name, template_folder=template_dir)
    _web_conf = _config.web_conf
    context = create_context(dir_path, _web_conf)

    debug = _web_conf.get('debug', True)
    app.run(host=_web_conf["domain"], port=_web_conf["port"],
            debug=_web_conf.get("debug", False), ssl_context=context)
Beispiel #16
0
    _path = os.path.join(dir_path, "signing_service", "federation_entity", ta)
    _conf = create_from_config_file(
        FedEntityConfiguration,
        filename=os.path.join(_path, "conf.json"),
        file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
        base_path=_path)
    keys_args = {k: v for k, v in _conf["keys"].items() if k != "uri_path"}
    _keyjar = init_key_jar(**keys_args)

    return _keyjar


if __name__ == "__main__":
    config_file = "signing_service/conf.json"

    _config = create_from_config_file(Configuration,
                                      entity_conf=[{
                                          'class': FedSigServConfiguration,
                                          'attr': 'sigsrv'
                                      }],
                                      filename=config_file)

    _pattern = _config.sigsrv.server_info["kwargs"]["entity_id_pattern"]

    res = {}
    for ta in sys.argv[1:]:
        _keyjar = get_subject_info(ta)
        entity_id = _pattern.format(ta)
        res[entity_id] = _keyjar.export_jwks()

    print(json.dumps(res, indent=2, sort_keys=True))
Beispiel #17
0
    def test_explicit_registration(self):
        config = create_from_config_file(
            Configuration,
            entity_conf=[{
                "class": FedRPConfiguration,
                "attr": "rp"
            }],
            filename=full_path('conf_foodle.uninett.no_expl.json'),
            file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
            base_path=BASE_PATH)

        config.rp.federation.web_cert_path = "{}/{}".format(
            dir_path, lower_or_upper(config.web_conf, "server_cert"))

        rph = init_oidc_rp_handler(config.rp, BASE_PATH)

        # MUST be an unknown entity
        rp = rph.init_client('https://op.umu.se')
        rp.client_get(
            "service_context").federation_entity.collector = DummyCollector(
                httpd=Publisher(ROOT_DIR),
                trusted_roots=ANCHOR,
                root_dir=ROOT_DIR)

        _service = rp.client_get("service", 'provider_info')

        args = self.provider_endpoint.process_request()
        info = self.provider_endpoint.do_response(**args)

        _resp = _service.parse_response(info["response"])

        with responses.RequestsMock() as rsps:
            _jwks = open(
                os.path.join(BASE_PATH, 'base_data', 'umu.se', 'op.umu.se',
                             'jwks.json')).read()
            rsps.add("GET",
                     'https://op.umu.se/static/umu_se_jwks.json',
                     body=_jwks,
                     adding_headers={"Content-Type": "application/json"},
                     status=200)
            _service.update_service_context(_resp)

        # Do the client registration request
        # First let the client construct the client registration request
        _service = rp.client_get("service", 'registration')
        #_request_args = _service.get_request_parameters(behaviour_args={'add_callbacks':{'add_hash':False}})
        _request_args = _service.get_request_parameters()

        # On the provider side
        args = self.registration_endpoint.process_request(
            _request_args["body"])
        response_args = self.provider_endpoint.do_response(**args)

        # Let the client deal with the response from the provider

        _resp = _service.parse_response(response_args["response"],
                                        request=_request_args["body"])
        _service.update_service_context(_resp)

        # and we're done
        reg_resp = _service.client_get("service_context").get(
            "registration_response")
        assert reg_resp["token_endpoint_auth_method"] == "private_key_jwt"
Beispiel #18
0
    def test_automatic_registration(self):
        config = create_from_config_file(
            Configuration,
            entity_conf=[{
                "class": FedRPConfiguration,
                "attr": "rp"
            }],
            filename=full_path('conf_foodle.uninett.no_auto.json'),
            file_attributes=DEFAULT_FED_FILE_ATTRIBUTE_NAMES,
            base_path=BASE_PATH)

        rph = init_oidc_rp_handler(config.rp, BASE_PATH)

        rp = rph.init_client('https://op.umu.se')
        rp.client_get(
            "service_context").federation_entity.collector = DummyCollector(
                httpd=Publisher(ROOT_DIR),
                trusted_roots=ANCHOR,
                root_dir=ROOT_DIR)

        _service = rp.client_get("service", 'provider_info')

        # don't need to parse the request since there is none
        args = self.provider_endpoint.process_request()
        info = self.provider_endpoint.do_response(**args)

        _resp = _service.parse_response(info["response"])

        with responses.RequestsMock() as rsps:
            _jwks = open(
                os.path.join(BASE_PATH, 'base_data', 'umu.se', 'op.umu.se',
                             'jwks.json')).read()
            rsps.add("GET",
                     'https://op.umu.se/static/umu_se_jwks.json',
                     body=_jwks,
                     adding_headers={"Content-Type": "application/json"},
                     status=200)
            _service.update_service_context(_resp)

        # Do the client authorization request
        # First let the client construct the authorization request
        _service = rp.client_get("service", 'authorization')
        _request_args = _service.get_request_parameters()

        # send it to the provider
        _req_args = parse_qs(_request_args['url'].split('?')[1])
        with responses.RequestsMock() as rsps:
            _jwks = open(os.path.join(BASE_PATH,
                                      'static/jwks_auto.json')).read()
            _url = 'https://foodle.uninett.no/jwks.json'
            rsps.add("GET",
                     _url,
                     body=_jwks,
                     adding_headers={"Content-Type": "application/json"},
                     status=200)
            _req_args = self.authorization_endpoint.parse_request(
                compact(_req_args))

        # need to register a user session info
        args = self.authorization_endpoint.process_request(_req_args)
        response_args = self.authorization_endpoint.do_response(**args)

        # Let the client deal with the response from the provider

        _resp = _service.parse_response(response_args["response"],
                                        request=compact(_req_args))
        _service.update_service_context(_resp)

        # and we're done
        assert 'trust_anchor_id' in _resp