def test_register_post_logout_redirect_uri_with_fragment(self):
     _msg = msg.copy()
     _msg["post_logout_redirect_uris"] = [
         "https://rp.example.com/pl#fragment"
     ]
     _req = self.endpoint.parse_request(
         RegistrationRequest(**_msg).to_json())
     _resp = self.endpoint.process_request(request=_req)
     assert _resp["error"] == "invalid_configuration_parameter"
Beispiel #2
0
def test_internal_signing_service():
    iss = InternalSigningService('https://swamid.sunet.se',
                                 KJ['https://swamid.sunet.se'])
    res = iss.sign(
        RegistrationRequest(redirect_uris=['https://example.com/rp/cb']),
        receiver='https://example.com/rp')

    _jws = factory(res)
    assert _jws.jwt.headers['alg'] == 'RS256'
    msg = _jws.jwt.payload()
    assert msg['iss'] == 'https://swamid.sunet.se'
    assert msg['aud'] == ['https://example.com/rp']
    def test_sector_uri_missing_redirect_uri(self, httpserver):
        _msg = msg.copy()
        _msg["redirect_uris"] = ["custom://cb.example.com"]
        _msg["application_type"] = "native"
        _msg["sector_identifier_uri"] = httpserver.url

        httpserver.serve_content(
            json.dumps(["https://example.com", "https://example.org"]),
            headers={"Content-Type": "application/json"},
        )
        _req = self.endpoint.parse_request(
            RegistrationRequest(**_msg).to_json())
        _resp = self.endpoint.process_request(request=_req)
        assert "error" in _resp
Beispiel #4
0
 def test_register_alg_keys(self):
     _msg = MSG.copy()
     _msg["id_token_signed_response_alg"] = "RS256"
     _msg["userinfo_signed_response_alg"] = "ES256"
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     with responses.RequestsMock() as rsps:
         rsps.add(
             "GET",
             _msg["jwks_uri"],
             body=JWKS,
             adding_headers={"Content-Type": "application/json"},
             status=200,
         )
         _resp = self.endpoint.process_request(request=_req)
     assert "response_args" in _resp
Beispiel #5
0
 def test_register_custom_redirect_uri_native(self):
     _msg = MSG.copy()
     _msg["redirect_uris"] = ["custom://cb.example.com"]
     _msg["application_type"] = "native"
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     with responses.RequestsMock() as rsps:
         rsps.add(
             "GET",
             _msg["jwks_uri"],
             body=JWKS,
             adding_headers={"Content-Type": "application/json"},
             status=200,
         )
         _resp = self.endpoint.process_request(request=_req)
     assert "response_args" in _resp
Beispiel #6
0
    def do_client_registration(self,
                               client=None,
                               iss_id: Optional[str] = '',
                               state: Optional[str] = '',
                               request_args: Optional[dict] = None,
                               behaviour_args: Optional[dict] = None):
        """
        Prepare for and do client registration if configured to do so

        :param iss_id: Issuer ID
        :param behaviour_args: To fine tune behaviour
        :param client: A Client instance
        :param state: A key by which the state of the session can be
            retrieved
        """

        logger.debug(20 * "*" + " do_client_registration " + 20 * "*")

        if not client:
            if state:
                client = self.get_client_from_session_key(state)
            else:
                raise ValueError('Missing state/session key')

        _context = client.client_get("service_context")
        _iss = _context.get('issuer')
        self.hash2issuer[iss_id] = _iss

        # This should only be interesting if the client supports Single Log Out
        # if _context.callback.get("post_logout_redirect_uri") is None:
        #     _context.callback["post_logout_redirect_uri"] = [self.base_url]

        if not client.get_client_id(
        ):  # means I have to do dynamic client registration
            if request_args is None:
                request_args = {}

            if behaviour_args:
                _params = RegistrationRequest().parameters()
                request_args.update(
                    {k: v
                     for k, v in behaviour_args.items() if k in _params})

            load_registration_response(client, request_args=request_args)
Beispiel #7
0
    def test_sector_uri_missing_redirect_uri(self):
        _url = "https://github.com/sector"

        _msg = MSG.copy()
        _msg["redirect_uris"] = ["custom://cb.example.com"]
        _msg["application_type"] = "native"
        _msg["sector_identifier_uri"] = _url

        with responses.RequestsMock() as rsps:
            rsps.add(
                "GET",
                _url,
                body=json.dumps(["https://example.com", "https://example.org"]),
                adding_headers={"Content-Type": "application/json"},
                status=200,
            )

            _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
            _resp = self.endpoint.process_request(request=_req)
            assert "error" in _resp
Beispiel #8
0
def test_metadata():
    client_info = RegistrationRequest(
        **{
            "application_type": "web",
            "claims": ["sub", "name", "email", "picture"],
            "id_token_signing_alg_values_supported": ["RS256", "RS512"],
            "redirect_uris": ["https://foodle.uninett.no/callback"],
            "response_types": ["code"]
        })
    metadata = Metadata()
    metadata['openid_relying_party'] = client_info

    _mj = metadata.to_json()

    _metadata = Metadata().from_json(_mj)

    assert set(_metadata.keys()) == {'openid_relying_party'}
    assert set(_metadata['openid_relying_party'].keys()) == {
        'application_type', 'claims', 'id_token_signing_alg_values_supported',
        'redirect_uris', 'response_types'
    }
Beispiel #9
0
def test_web_signing_service():
    _kj = KJ['https://swamid.sunet.se']
    iss = InternalSigningService('https://swamid.sunet.se', _kj)
    _sms = iss.create(
        RegistrationRequest(redirect_uris=['https://example.com/rp/cb']),
        'https://example.com/rp')

    _jwks = _kj.export_jwks()
    _vkj = KeyJar()
    _vkj.import_jwks(_jwks, 'https://swamid.sunet.se')

    wss = WebSigningServiceClient('https://swamid.sunet.se',
                                  'https://swamid.sunet.se/mdss',
                                  'https://example.com/rp', _vkj)

    response = Response(200, _sms,
                        {'Location': 'https://swamid.sunet.se/mdss/abcdefg'})

    _res = wss.parse_response(response)

    assert set(_res.keys()) == {'sms', 'loc'}
Beispiel #10
0
    def do_automatic_registration(self, entity_id):
        _fe = self.endpoint_context.federation_entity

        # get self-signed entity statement
        _sses = _fe.get_configuration_information(entity_id)

        # Collect all the trust chains, verify them and apply policies. return the result
        statements = _fe.collect_metadata_statements(_sses,
                                                     "openid_relying_party")

        # pick one of the possible
        statement = _fe.pick_metadata(statements)

        # handle the registration request as in the non-federation case.
        req = RegistrationRequest(**statement.metadata)
        req['client_id'] = entity_id
        new_id = self.automatic_registration_endpoint.kwargs.get(
            "new_id", False)
        response_info = self.automatic_registration_endpoint.non_fed_process_request(
            req, new_id=new_id)
        try:
            return response_info["response_args"]["client_id"]
        except KeyError:
            return None
Beispiel #11
0
    "token_endpoint_auth_method": "client_secret_basic",
    "jwks_uri": "https://client.example.org/my_public_keys.jwks",
    "userinfo_encrypted_response_alg": "RSA-OAEP",
    "userinfo_encrypted_response_enc": "A128CBC-HS256",
    "contacts": ["*****@*****.**", "*****@*****.**"],
    "request_uris": [
        "https://client.example.org/rf.txt#qpXaRLh_n93TT",
        "https://client.example.org/rf.txt",
    ],
    "post_logout_redirect_uris": [
        "https://rp.example.com/pl?foo=bar",
        "https://rp.example.com/pl",
    ],
}

CLI_REQ = RegistrationRequest(**msg)


class TestEndpoint(object):
    @pytest.fixture(autouse=True)
    def create_endpoint(self):
        conf = {
            "issuer": "https://example.com/",
            "password": "******",
            "token_expires_in": 600,
            "grant_expires_in": 300,
            "refresh_token_expires_in": 86400,
            "verify_ssl": False,
            "capabilities": CAPABILITIES,
            "keys": {"key_defs": KEYDEFS, "uri_path": "static/jwks.json"},
            "cookie_handler": {
Beispiel #12
0
print("comb", comb_policy.verify())

# apply policy

res = apply_policy(es['metadata']["openid_provider"], comb_policy)
res_pcr = ProviderConfigurationResponse(**res)
print("provider config", res_pcr.verify())

fp = open('a.1.8_res.json', 'w')
fp.write(json.dumps(res_pcr.to_dict(), indent=2, sort_keys=True))
fp.close()

# ============== A.2.1.2 ==================

metadata = open("A.2.1.2_3.json".format(sec)).read()
reg_req = RegistrationRequest()
reg_req.from_json(metadata)

org = open("A.2.1.2_1.json".format(sec)).read()
org_es = MetadataPolicy().from_json(org)

fed = open("A.2.1.2_2.json".format(sec)).read()
fed_es = MetadataPolicy().from_json(fed)

comb_policy = MetadataPolicy(**combine_policy(fed_es['openid_relying_party'],
                                              org_es['openid_relying_party']))
print("comb", comb_policy.verify())

# apply policy

res = apply_policy(reg_req, comb_policy)
 def test_incorrect_request(self):
     _msg = msg.copy()
     _msg["default_max_age"] = "five"
     with pytest.raises(ValueError):
         self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
Beispiel #14
0
    "token_endpoint_auth_method": "client_secret_basic",
    "jwks_uri": "https://client.example.org/my_public_keys.jwks",
    "userinfo_encrypted_response_alg": "RSA-OAEP",
    "userinfo_encrypted_response_enc": "A128CBC-HS256",
    "contacts": ["*****@*****.**", "*****@*****.**"],
    "request_uris": [
        "https://client.example.org/rf.txt#qpXaRLh_n93TT",
        "https://client.example.org/rf.txt",
    ],
    "post_logout_redirect_uris": [
        "https://rp.example.com/pl?foo=bar",
        "https://rp.example.com/pl",
    ],
}

CLI_REQ = RegistrationRequest(**MSG)


class TestEndpoint(object):
    @pytest.fixture(autouse=True)
    def create_endpoint(self):
        conf = {
            "issuer": "https://example.com/",
            "password": "******",
            "verify_ssl": False,
            "capabilities": {
                "subject_types_supported": ["public", "pairwise", "ephemeral"],
                "grant_types_supported": [
                    "authorization_code",
                    "implicit",
                    "urn:ietf:params:oauth:grant-type:jwt-bearer",
Beispiel #15
0
 def test_register_unsupported_algo(self):
     _msg = MSG.copy()
     _msg["id_token_signed_response_alg"] = "XYZ256"
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     _resp = self.endpoint.process_request(request=_req)
     assert _resp["error"] == "invalid_request"
Beispiel #16
0
 def test_register_unsupported_set(self):
     _msg = MSG.copy()
     _msg["grant_types"] = ["authorization_code", "external"]
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     _resp = self.endpoint.process_request(request=_req)
     assert _resp["error"] == "invalid_request"
Beispiel #17
0
 def test_register_sector_identifier_uri(self):
     _msg = MSG.copy()
     _msg["sector_identifier_uri"] = "https://rp.example.com/si#fragment"
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     _resp = self.endpoint.process_request(request=_req)
     assert _resp["error"] == "invalid_configuration_parameter"
Beispiel #18
0
 def test_register_custom_redirect_uri_web(self):
     _msg = MSG.copy()
     _msg["redirect_uris"] = ["custom://cb.example.com"]
     _req = self.endpoint.parse_request(RegistrationRequest(**_msg).to_json())
     _resp = self.endpoint.process_request(request=_req)
     assert "error" in _resp