Exemplo n.º 1
0
    def restore_state(self, filename):
        txt = open(filename).read()
        state = json.loads(txt)
        self.trace.start = state["trace_log"]["start"]
        self.trace.trace = state["trace_log"]["trace"]
        self.flow_index = state["flow_index"]
        self.client_config = state["client_config"]
        self.test_output = state["test_output"]

        self.client.behaviour = state["client"]["behaviour"]
        self.client.keyjar.restore(state["client"]["keyjar"])
        pcr = ProviderConfigurationResponse().from_json(
            state["client"]["provider_info"])
        self.client.provider_info = pcr
        self.client.client_id = state["client"]["client_id"]
        self.client.client_secret = state["client"]["client_secret"]

        for key, val in pcr.items():
            if key.endswith("_endpoint"):
                setattr(self.client, key, val)

        try:
            self.client.registration_response = RegistrationResponse(
            ).from_json(state["client"]["registration_resp"])
        except KeyError:
            pass
Exemplo n.º 2
0
    def restore_state(self, filename):
        txt = open(filename).read()
        state = json.loads(txt)
        self.trace.start = state["trace_log"]["start"]
        self.trace.trace = state["trace_log"]["trace"]
        self.flow_index = state["flow_index"]
        self.client_config = state["client_config"]
        self.test_output = state["test_output"]

        self.client.behaviour = state["client"]["behaviour"]
        self.client.keyjar.restore(state["client"]["keyjar"])
        pcr = ProviderConfigurationResponse().from_json(
            state["client"]["provider_info"])
        self.client.provider_info = pcr
        self.client.client_id = state["client"]["client_id"]
        self.client.client_secret = state["client"]["client_secret"]

        for key, val in pcr.items():
            if key.endswith("_endpoint"):
                setattr(self.client, key, val)

        try:
            self.client.registration_response = RegistrationResponse().from_json(
                state["client"]["registration_resp"])
        except KeyError:
            pass
Exemplo n.º 3
0
def _create_client(provider_metadata, client_metadata, verify_ssl=True):
    """
    Create a pyoidc client instance.
    :param provider_metadata: provider configuration information
    :type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
    :param client_metadata: client metadata
    :type client_metadata: Mapping[str, Union[str, Sequence[str]]]
    :return: client instance to use for communicating with the configured provider
    :rtype: oic.oic.Client
    """
    client = oic.Client(
        client_authn_method=CLIENT_AUTHN_METHOD, verify_ssl=verify_ssl
    )

    # Provider configuration information
    if "authorization_endpoint" in provider_metadata:
        # no dynamic discovery necessary
        client.handle_provider_config(ProviderConfigurationResponse(**provider_metadata),
                                      provider_metadata["issuer"])
    else:
        # do dynamic discovery
        client.provider_config(provider_metadata["issuer"])

    # Client information
    if "client_id" in client_metadata:
        # static client info provided
        client.store_registration_info(RegistrationRequest(**client_metadata))
    else:
        # do dynamic registration
        client.register(client.provider_info['registration_endpoint'],
                        **client_metadata)

    client.subject_type = (client.registration_response.get("subject_type") or
                           client.provider_info["subject_types_supported"][0])
    return client
Exemplo n.º 4
0
 def run(self):
     if self.dynamic:
         self.catch_exception(self.conv.entity.provider_config,
                              **self.op_args)
     else:
         self.conv.entity.provider_info = ProviderConfigurationResponse(
             **self.conf.INFO["provider_info"])
Exemplo n.º 5
0
def openid_configuration(environ, start_response, logger, handle):
    _oas = environ["oic.server"]
    _path = geturl(environ, False, False)

    conf = ProviderConfigurationResponse(issuer=_oas.name,
            authorization_endpoint=_path+"/authorization",
            token_endpoint=_path+"/token",
            user_info_endpoint=_path+"/user_info",
            check_session_endpoint=_path+"/check",
            refresh_session_endpoint=_path+"/refresh_session",
            end_session_endpoint=_path+"/end_session",
            registration_endpoint=_path+"/registration",
            scopes_supported=["openid"],
            flows_supported=["code", "id_token", "token"])

    resp = Response(conf.to_json())
    return resp(environ, start_response)
Exemplo n.º 6
0
 def run(self):
     if self.dynamic:
         self.catch_exception_and_error(self.conv.entity.provider_config,
                                        **self.op_args)
     else:
         self.conv.events.store(EV_NOOP, "Dynamic discovery")
         self.conv.entity.provider_info = ProviderConfigurationResponse(
             **self.conv.entity_config["provider_info"])
Exemplo n.º 7
0
 def __call__(self, conv, **kwargs):
     cli = conv.client
     name = self.id + b64encode(str(
         conv.client_config["srv_discovery_url"]))
     f = open(name)
     info = json.loads(f.read())
     f.close()
     cli.token[self.scope] = info["token"]
     cli.provider_info = ProviderConfigurationResponse().from_dict(
         info["provider_info"])
Exemplo n.º 8
0
def test_check_http_response_200():
    _info = setup_conv()
    _conv = _info['conv']

    _conv.events.store(EV_HTTP_RESPONSE, RESPONSE_200)
    _conv.events.store(
        EV_PROTOCOL_RESPONSE,
        ProviderConfigurationResponse(
            issuer='https://example.com',
            authorization_endpoint='https://example.com/authz',
            jwks_uri='https://example.com/jwks.json',
            subject_types_supported=['public'],
            id_token_signing_alg_values_supported=['RS256']))

    cr = CheckHTTPResponse()
    res = cr._func(_conv)
    assert res == {}
    assert cr._status == OK
Exemplo n.º 9
0
    def fetch_op_keys(self, client, state):
        """
        Fetch op keys

        :type client: Client
        :type state: dict[str, str]

        :param client: oidc client
        :param state: A dictionary with all state values for the backend module.
        :return: oidc client with op keys.
        """
        client.keyjar = KeyJar(verify_ssl=self.config.VERIFY_SSL)
        pcr = ProviderConfigurationResponse()
        pcr['jwks_uri'] = state[StateKeys.JWKS_URI]
        client.handle_provider_config(pcr, self.config.OP_URL)
        for issuer, keybundle_list in client.keyjar.issuer_keys.items():
            for kb in keybundle_list:
                if kb.remote:
                    kb.do_remote()
        return client
Exemplo n.º 10
0
    def __init__(self, provider_configuration, redirect_uri):
        """
        Args:
            provider_configuration (flask_pyoidc.provider_configuration.ProviderConfiguration)
        """
        self._provider_configuration = provider_configuration
        self._client = Client(client_authn_method=CLIENT_AUTHN_METHOD)

        provider_metadata = provider_configuration.ensure_provider_metadata()
        self._client.handle_provider_config(
            ProviderConfigurationResponse(**provider_metadata.to_dict()),
            provider_metadata['issuer'])

        if self._provider_configuration.registered_client_metadata:
            client_metadata = self._provider_configuration.registered_client_metadata.to_dict(
            )
            registration_response = RegistrationResponse(**client_metadata)
            self._client.store_registration_info(registration_response)

        self._redirect_uri = redirect_uri
Exemplo n.º 11
0
def test_verify_response_missing():
    _info = setup_conv()
    _conv = _info['conv']

    # Add responses
    _conv.events.store(
        EV_PROTOCOL_RESPONSE,
        ProviderConfigurationResponse(
            issuer='https://example.com',
            authorization_endpoint='https://example.com/authz',
            jwks_uri='https://example.com/jwks.json',
            subject_types_supported=['public'],
            id_token_signing_alg_values_supported=['RS256']))

    vr = VerifyResponse()
    vr._kwargs = {
        "response_cls": ["AccessTokenResponse", "AuthorizationResponse"]
    }
    res = vr._func(_conv)
    assert res == {}
    assert vr._status == ERROR
Exemplo n.º 12
0
    def create_client(self, userid="", **kwargs):
        """
        Do an instantiation of a client instance

        :param userid: An identifier of the user
        :param: Keyword arguments
            Keys are ["srv_discovery_url", "client_info", "client_registration",
            "provider_info"]
        :return: client instance
        """

        _key_set = set(kwargs.keys())
        args = {}
        for param in ["verify_ssl"]:
            try:
                args[param] = kwargs[param]
            except KeyError:
                pass
            else:
                _key_set.discard(param)

        client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD,
                                 behaviour=kwargs["behaviour"], verify_ssl=self.config.VERIFY_SSL, **args)

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")
        for param in ["allow"]:
            try:
                setattr(client, param, kwargs[param])
            except KeyError:
                pass
            else:
                _key_set.discard(param)

        if _key_set == set(["client_info"]):  # Everything dynamic
            # There has to be a userid
            if not userid:
                raise MissingAttribute("Missing userid specification")

            # Find the service that provides information about the OP
            issuer = client.wf.discovery_query(userid)
            # Gather OP information
            _ = client.provider_config(issuer)
            # register the client
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["client_info", "srv_discovery_url"]):
            # Ship the webfinger part
            # Gather OP information
            _ = client.provider_config(kwargs["srv_discovery_url"])
            # register the client
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["provider_info", "client_info"]):
            client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["provider_info", "client_registration"]):
            client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            client.store_registration_info(RegistrationResponse(
                **kwargs["client_registration"]))
        elif _key_set == set(["srv_discovery_url", "client_registration"]):
            _ = client.provider_config(kwargs["srv_discovery_url"])
            client.store_registration_info(RegistrationResponse(
                **kwargs["client_registration"]))
        else:
            raise Exception("Configuration error ?")

        return client
Exemplo n.º 13
0
authzsrv = uma_as.main(BASE, AS_CookieHandler)

RS_PORT = 8089
RS_HOST = "https://*****:*****@example.com"],
    "redirect_uris": [callback]
}

# link to the client that will talk to the AS
Exemplo n.º 14
0
def create_client(**kwargs):
    """
    kwargs = config.CLIENT.iteritems
    """
    _key_set = set(kwargs.keys())
    args = {}
    for param in ["verify_ssl", "client_id", "client_secret"]:
        try:
            args[param] = kwargs[param]
        except KeyError:
            try:
                args[param] = kwargs['client_registration'][param]
            except KeyError:
                pass
        else:
            _key_set.discard(param)

    client = Client(client_authn_method=CLIENT_AUTHN_METHOD,
                    behaviour=kwargs["behaviour"],
                    verify_ssl=conf.VERIFY_SSL,
                    **args)

    # The behaviour parameter is not significant for the election process
    _key_set.discard("behaviour")
    # I do not understand how this was ever working without discarding this
    # Below is not a case where _key_set includes "registration_response"
    _key_set.discard("registration_response")
    for param in ["allow"]:
        try:
            setattr(client, param, kwargs[param])
        except KeyError:
            pass
        else:
            _key_set.discard(param)

    if _key_set == set(["client_info"]):  # Everything dynamic
        # There has to be a userid
        if not userid:
            raise MissingAttribute("Missing userid specification")

        # Find the service that provides information about the OP
        issuer = client.wf.discovery_query(userid)
        # Gather OP information
        _ = client.provider_config(issuer)
        # register the client
        _ = client.register(client.provider_info["registration_endpoint"],
                            **kwargs["client_info"])
    elif _key_set == set(["client_info", "srv_discovery_url"]):
        # Ship the webfinger part
        # Gather OP information
        _ = client.provider_config(kwargs["srv_discovery_url"])
        # register the client
        _ = client.register(client.provider_info["registration_endpoint"],
                            **kwargs["client_info"])
    elif _key_set == set(["provider_info", "client_info"]):
        client.handle_provider_config(
            ProviderConfigurationResponse(**kwargs["provider_info"]),
            kwargs["provider_info"]["issuer"])
        _ = client.register(client.provider_info["registration_endpoint"],
                            **kwargs["client_info"])
    elif _key_set == set(["provider_info", "client_registration"]):
        client.handle_provider_config(
            ProviderConfigurationResponse(**kwargs["provider_info"]),
            kwargs["provider_info"]["issuer"])
        client.store_registration_info(
            RegistrationResponse(**kwargs["client_registration"]))
    elif _key_set == set(["srv_discovery_url", "client_registration"]):
        _ = client.provider_config(kwargs["srv_discovery_url"])
        client.store_registration_info(
            RegistrationResponse(**kwargs["client_registration"]))
    else:
        raise Exception("Configuration error ?")

    return client
Exemplo n.º 15
0
    def create_client(self, **kwargs):
        """
        Do an instantiation of a client instance

        :param: Keyword arguments
            Keys are:
                srv_discovery_url
                client_info
                client_registration
                provider_info
                behaviour
        :return: client instance
        """

        _key_set = set(list(kwargs.keys()))
        try:
            _verify_ssl = kwargs['verify_ssl']
        except KeyError:
            _verify_ssl = self.verify_ssl
        else:
            _key_set.discard('verify_ssl')

        _client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD,
                                  behaviour=kwargs["behaviour"],
                                  verify_ssl=_verify_ssl)

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")

        for param in ["allow"]:
            try:
                setattr(_client, param, kwargs[param])
            except KeyError:
                pass
            else:
                _key_set.discard(param)

        if _key_set == {"client_info", "srv_discovery_url"}:
            # Ship the webfinger part
            # Gather OP information
            _client.provider_config(kwargs["srv_discovery_url"])
            # register the client
            _client.register(_client.provider_info["registration_endpoint"],
                             **kwargs["client_info"])
            self.get_path(kwargs['client_info']['redirect_uris'],
                          kwargs["srv_discovery_url"])
        elif _key_set == {"provider_info", "client_info"}:
            _client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            _client.register(_client.provider_info["registration_endpoint"],
                             **kwargs["client_info"])

            self.get_path(kwargs['client_info']['redirect_uris'],
                          kwargs["provider_info"]["issuer"])
        elif _key_set == {"provider_info", "client_registration"}:
            _client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            _client.store_registration_info(ClientInfoResponse(
                **kwargs["client_registration"]))
            self.get_path(kwargs['client_info']['redirect_uris'],
                          kwargs["provider_info"]["issuer"])
        elif _key_set == {"srv_discovery_url", "client_registration"}:
            _client.provider_config(kwargs["srv_discovery_url"])
            _client.store_registration_info(ClientInfoResponse(
                **kwargs["client_registration"]))
            self.get_path(kwargs['client_registration']['redirect_uris'],
                          kwargs["srv_discovery_url"])
        else:
            raise Exception("Configuration error ?")

        return client
Exemplo n.º 16
0
    def create_client(self, **kwargs):
        """
        Instantiate a client instance

        :param: Keyword arguments
            Keys are ["srv_discovery_url", "client_info", "client_registration",
            "provider_info". "keys]
        :return: client instance
        """

        _key_set = set(kwargs.keys())
        args = {}

        client = self.client_cls(client_authn_methods=CLIENT_AUTHN_METHOD,
                                 behaviour=kwargs["behaviour"],
                                 verify_ssl=self.config.VERIFY_SSL,
                                 **args)

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")
        try:
            setattr(client, "allow", kwargs["allow"])
        except KeyError:
            pass
        else:
            _key_set.discard("allow")

        try:
            jwks = keyjar_init(client, kwargs["keys"])
        except KeyError:
            pass
        else:
            # export JWKS
            p = urlparse(self.config.CLIENT["key_export_url"] % self._port)
            f = open("." + p.path, "w")
            f.write(json.dumps(jwks))
            f.close()
            client.jwks_uri = p.geturl()

        self.test_features = _key_set

        try:
            client.client_prefs = copy.copy(kwargs["preferences"])
        except KeyError:
            pass
        else:
            _key_set.discard("preferences")

        if "client_info" in _key_set:
            client.redirect_uris = self.config.CLIENT["client_info"][
                "redirect_uris"]
        elif "client_registration" in _key_set:
            reg_info = self.config.CLIENT["client_registration"]
            client.redirect_uris = reg_info["redirect_uris"]
            client.client_id = reg_info["client_id"]
            try:
                client.client_secret = reg_info["client_secret"]
            except KeyError:
                pass

        if "provider_info" in _key_set:
            client.provider_info = ProviderConfigurationResponse(
                **self.config.CLIENT["provider_info"])

            for key, val in self.config.CLIENT["provider_info"].items():
                if key.endswith("_endpoint"):
                    setattr(client, key, val)
                elif key == "jwks_uri":
                    client.keyjar.load_keys(client.provider_info,
                                            client.provider_info["issuer"])

        return client