From b4161ec79d4d296453b39941161b8262baa338bf Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Mon, 28 Apr 2025 14:32:33 +0200 Subject: [PATCH 01/43] Fixed entity statement 'typ' header. --- edu_federation/README_identity.rst | 22 +++++++++++----------- edu_federation/trust_anchor/views.py | 3 ++- src/fedservice/entity_statement/create.py | 2 +- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/edu_federation/README_identity.rst b/edu_federation/README_identity.rst index e6f64d7a..fd0f7451 100644 --- a/edu_federation/README_identity.rst +++ b/edu_federation/README_identity.rst @@ -51,11 +51,11 @@ This will create a number of things in the *trust_anchor* directory All entities in the federation has to have some information about the trust mark. The information to pass along is collected by doing:: - ./get_info.py -k -t https://127.0.0.1:7010 > trust_anchor.json + ./get_info.py -k -t https://89.46.21.210:7010 > trust_anchor.json This must be done while the Trust anchor is running. Of course if you have changed the entity_id of the trust anchor from -https://127.0.0.1:7003 to something else you have to change this command accordingly. +https://89.46.21.210:7003 to something else you have to change this command accordingly. Now you're done with phase 1 concerning the trust anchor. So you can kill that process for the time being. @@ -92,11 +92,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t trust_mark_issuer/trust_anchors - echo -e "https://127.0.0.1:7010" >> trust_mark_issuer/authority_hints + echo -e "https://89.46.21.210:7010" >> trust_mark_issuer/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:6010 > tmp.json + ./get_info.py -k -s https://89.46.21.210:6010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates The fourth is presently done like this (may change in the future):: @@ -143,11 +143,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t openid_provider/trust_anchors - echo -e "https://127.0.0.1:7010" >> openid_provider/authority_hints + echo -e "https://89.46.21.210:7010" >> openid_provider/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4020 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4020 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -190,11 +190,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t relying_party_explicit/trust_anchors - echo -e "https://127.0.0.1:7010" >> relying_party_explicit/authority_hints + echo -e "https://89.46.21.210:7010" >> relying_party_explicit/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4010 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -237,11 +237,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t relying_party_automatic/trust_anchors - echo -e "https://127.0.0.1:7010" >> relying_party_automatic/authority_hints + echo -e "https://89.46.21.210:7010" >> relying_party_automatic/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4015 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -265,7 +265,7 @@ Creating a trust mark for an entity For this the script *create_trust_mark.py* is included. Typical usage:: - ./create_trust_mark.py -d trust_mark_issuer -m https://refeds.org/category/personalized -e https://127.0.0.1:4010 + ./create_trust_mark.py -d trust_mark_issuer -m https://refeds.org/category/personalized -e https://89.46.21.210:4010 > trust_mark.4010 diff --git a/edu_federation/trust_anchor/views.py b/edu_federation/trust_anchor/views.py index d312b8ed..7165dd4d 100644 --- a/edu_federation/trust_anchor/views.py +++ b/edu_federation/trust_anchor/views.py @@ -185,5 +185,6 @@ def wkof(): lifetime=_ctx.default_lifetime) response = make_response(_statement) - response.headers['Content-Type'] = 'application/jose; charset=UTF-8' + if 'Content-Type' not in response.headers: + response.headers['Content-Type'] = 'application/entity-statement+jwt' return response diff --git a/src/fedservice/entity_statement/create.py b/src/fedservice/entity_statement/create.py index 3fe26a82..9fd844b2 100644 --- a/src/fedservice/entity_statement/create.py +++ b/src/fedservice/entity_statement/create.py @@ -57,4 +57,4 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime) - return packer.pack(payload=msg) + return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) From df092b84d37694913a3a2a754d622082950093eb Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Tue, 29 Apr 2025 15:31:15 +0200 Subject: [PATCH 02/43] Fail gracefully --- src/fedservice/defaults.py | 2 + .../entity/function/trust_chain_collector.py | 30 ++++++++++--- .../entity/function/trust_mark_verifier.py | 44 ++++++++++++------ src/fedservice/entity_statement/create.py | 7 +-- tests/test_01_create.py | 45 +++++++++++++++---- 5 files changed, 97 insertions(+), 31 deletions(-) diff --git a/src/fedservice/defaults.py b/src/fedservice/defaults.py index 59c3de99..7f0e8420 100644 --- a/src/fedservice/defaults.py +++ b/src/fedservice/defaults.py @@ -221,3 +221,5 @@ def federation_functions(*apis): DEFAULT_FEDERATION_ENTITY_FUNCTIONS = federation_functions("trust_chain_collector", "verifier", "policy", "trust_mark_verifier") + +DEFAULT_SIGNING_ALGORITHM = "RS256" \ No newline at end of file diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index 1f0998e1..e62d2f6b 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -1,6 +1,8 @@ import logging -import time from ssl import SSLError +import sys +import time +import traceback from typing import Callable from typing import List from typing import Optional @@ -15,8 +17,9 @@ from idpyoidc.message import Message from requests.exceptions import ConnectionError -from fedservice.entity.function import collect_trust_chains +from fedservice.defaults import DEFAULT_SIGNING_ALGORITHM from fedservice.entity.function import Function +from fedservice.entity.function import collect_trust_chains from fedservice.entity.function import verify_trust_chains from fedservice.entity.utils import get_federation_entity from fedservice.entity_statement.cache import ESCache @@ -33,6 +36,11 @@ def unverified_entity_statement(signed_jwt): return _jws.jwt.payload() +def signing_algorithm(signed_jwt): + _jws = factory(signed_jwt) + return _jws.jwt.headers.get("alg", DEFAULT_SIGNING_ALGORITHM) + + def verify_self_signed_signature(statement): """ Verify signature using only keys in the entity statement. @@ -47,7 +55,7 @@ def verify_self_signed_signature(statement): if payload['iss'] not in keyjar: keyjar = import_jwks(keyjar, payload['jwks'], payload['iss']) - _jwt = JWT(key_jar=keyjar) + _jwt = JWT(key_jar=keyjar, sign_alg=signing_algorithm(statement)) _val = _jwt.unpack(statement) return _val @@ -229,7 +237,11 @@ def get_entity_statement(self, fetch_endpoint, issuer, subject): # if self.use_ssc: # signed_entity_statement = self.do_ssc_seq(_url, issuer) # else: - return self.get_document(_res['url']) + try: + return self.get_document(_res['url']) + except FailedConfigurationRetrieval: + logger.error(f"Failed to fetch {_res['url']}") + raise def collect_tree(self, entity_id: str, @@ -264,8 +276,14 @@ def collect_tree(self, for authority in entity_configuration['authority_hints']: if authority in seen: # loop ?! logger.warning(f"Loop detected at {authority}") - superior[authority] = self.collect_branch(entity_id, authority, seen, - max_superiors, stop_at=stop_at) + continue + try: + superior[authority] = self.collect_branch(entity_id, authority, seen, + max_superiors, stop_at=stop_at) + except Exception as err: + message = traceback.format_exception(*sys.exc_info()) + logger.error(message) + continue return superior diff --git a/src/fedservice/entity/function/trust_mark_verifier.py b/src/fedservice/entity/function/trust_mark_verifier.py index a86256c7..7150389c 100644 --- a/src/fedservice/entity/function/trust_mark_verifier.py +++ b/src/fedservice/entity/function/trust_mark_verifier.py @@ -5,6 +5,7 @@ from cryptojwt import KeyJar from cryptojwt.exception import Expired from cryptojwt.jws.jws import factory +from fedservice.entity import FederationEntity from idpyoidc.key_import import import_jwks from idpyoidc.message import Message @@ -31,8 +32,13 @@ class TrustMarkVerifier(Function): 4) Find a trust chain to the trust mark issuer 5) Verify the signature of the trust mark """ - def __init__(self, upstream_get: Callable): + def __init__(self, upstream_get: Optional[Callable] = None, + federation_entity: Optional[FederationEntity] = None + ): + if not upstream_get and not federation_entity: + raise ValueError("Must have one of upstream_get and federation_entity") Function.__init__(self, upstream_get) + self.federation_entity = federation_entity def check_delegation(self, trust_anchor_statement, trust_mark) -> bool: _owners = trust_anchor_statement.get("trust_mark_owners", {}) @@ -85,7 +91,11 @@ def __call__(self, raise # Get trust anchor information in order to verify the issuer and if needed the delegator. - _federation_entity = get_federation_entity(self) + if self.federation_entity: + _federation_entity = self.federation_entity + else: + _federation_entity = get_federation_entity(self) + trust_anchor_statement = get_verified_trust_anchor_statement(_federation_entity, trust_anchor) # Check delegation @@ -108,14 +118,16 @@ def __call__(self, return None # Now time to verify the signature of the trust mark - _trust_chains = get_verified_trust_chains(self, _trust_mark['iss']) - if not _trust_chains: - logger.warning(f"Could not find any verifiable trust chains for {_trust_mark['iss']}") - return None + _trust_chains = [] + if _trust_mark["iss"] != trust_anchor: + _trust_chains = get_verified_trust_chains(_federation_entity, _trust_mark['iss']) + if not _trust_chains: + logger.warning(f"Could not find any verifiable trust chains for {_trust_mark['iss']}") + return None - if trust_anchor not in [_tc.anchor for _tc in _trust_chains]: - logger.warning(f'No verified trust chain to the trust anchor: {trust_anchor}') - return None + if trust_anchor not in [_tc.anchor for _tc in _trust_chains]: + logger.warning(f'No verified trust chain to the trust anchor: {trust_anchor}') + return None # Now try to verify the signature on the trust_mark # should have the necessary keys @@ -124,10 +136,16 @@ def __call__(self, keys = keyjar.get_jwt_verify_keys(_jwt.jwt) if not keys: - _trust_chains = apply_policies(_federation_entity, _trust_chains) - keyjar = import_jwks(keyjar, - _trust_chains[0].verified_chain[-1]["jwks"], - _trust_chains[0].iss_path[0]) + if _trust_mark["iss"] != trust_anchor: + keyjar = import_jwks(keyjar, + trust_anchor_statement["jwks"], + trust_anchor_statement["iss"]) + else: + _trust_chains = apply_policies(_federation_entity, _trust_chains) + keyjar = import_jwks(keyjar, + _trust_chains[0].verified_chain[-1]["jwks"], + _trust_chains[0].iss_path[0]) + keys = keyjar.get_jwt_verify_keys(_jwt.jwt) try: diff --git a/src/fedservice/entity_statement/create.py b/src/fedservice/entity_statement/create.py index 9fd844b2..b66e646a 100644 --- a/src/fedservice/entity_statement/create.py +++ b/src/fedservice/entity_statement/create.py @@ -1,5 +1,6 @@ import logging from typing import Callable +from typing import Optional from cryptojwt.jwt import JWT @@ -8,7 +9,7 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=None, authority_hints=None, lifetime=86400, aud='', include_jwks=True, - constraints=None, **kwargs): + constraints=None, signing_alg: Optional[str] = "RS256", **kwargs): """ :param iss: The issuer of the signed JSON Web Token @@ -23,6 +24,7 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No :param aud: Possible audience for the JWT :param include_jwks: Add JWKS :param constraints: A dictionary with constraints. + :param signing_alg: Which signing algorithm that should be used :return: A signed JSON Web Token """ @@ -55,6 +57,5 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No # The public signing keys of the subject msg['jwks'] = key_jar.export_jwks() - packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime) - + packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime, sign_alg=signing_alg) return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) diff --git a/tests/test_01_create.py b/tests/test_01_create.py index 302f9078..356bfa91 100644 --- a/tests/test_01_create.py +++ b/tests/test_01_create.py @@ -1,8 +1,16 @@ +import json + +from cryptojwt import KeyJar +from cryptojwt.jwk.jwk import key_from_jwk_dict from cryptojwt.jws.jws import factory from cryptojwt.key_jar import build_keyjar +import pytest + +from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature from idpyoidc.key_import import import_jwks_as_json from fedservice.entity_statement.create import create_entity_statement +from tests import test_vector KEYSPEC = [ {"type": "RSA", "use": ["sig"]}, @@ -10,9 +18,13 @@ ] RECEIVER = 'https://example.org/op' +ISSUER_ID = "https://example.org" - -def test_create_self_signed(): +@pytest.mark.parametrize( + "alg", + ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"], +) +def test_create_self_signed(alg): metadata = { "application_type": "web", "claims": [ @@ -33,19 +45,34 @@ def test_create_self_signed(): ] } - iss = "https://example.com" + iss = ISSUER_ID sub = iss - key_jar = build_keyjar(KEYSPEC, issuer_id=iss) + json_priv_key = json.loads(test_vector.json_rsa_priv_key) + json_priv_key["alg"] = alg + json_pub_key = json.loads(test_vector.json_rsa_pub_key) + json_pub_key["alg"] = alg + + json_header_rsa = json.loads(test_vector.test_header_rsa) + json_header_rsa["alg"] = alg + + sign_key_jar = KeyJar() + _key = key_from_jwk_dict(json_priv_key) + _key.add_kid() + sign_key_jar.add_keys("", [_key]) authority = ["https://ntnu.no"] - _jwt = create_entity_statement(iss, sub, key_jar, metadata=metadata, authority_hints=authority) + _jwt = create_entity_statement(iss, sub, sign_key_jar, metadata=metadata, + authority_hints=authority, + signing_alg=alg) assert _jwt - _verifier = factory(_jwt) - keys = key_jar.get_jwt_verify_keys(_verifier.jwt) - res = _verifier.verify_compact(keys=keys) + # _verifier = factory(_jwt) + # verifier_key_jar = KeyJar() + # verifier_key_jar.add_keys("", [key_from_jwk_dict(json_pub_key)]) + # res = _verifier.verify_compact(keys=keys) + res = verify_self_signed_signature(_jwt) assert res assert res['iss'] == iss @@ -99,7 +126,7 @@ def test_signed_someone_else_metadata(): _verifier = factory(_jwt) keys = sub_key_jar.get_jwt_verify_keys(_verifier.jwt) - res = _verifier.verify_compact(keys=keys) + res = _verifier.verify_compact(keys=keys, sigalg="RS256") assert res assert res['iss'] == iss From dc472260c386fbacd895f8f3d1bf1393c86ff3de Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Wed, 30 Apr 2025 09:57:04 +0200 Subject: [PATCH 03/43] iss not part of the fetch query anymore. More logging. --- src/fedservice/entity/client/entity_statement.py | 6 ++---- src/fedservice/entity/function/trust_chain_collector.py | 5 +++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/fedservice/entity/client/entity_statement.py b/src/fedservice/entity/client/entity_statement.py index aecef8af..f7fd6920 100644 --- a/src/fedservice/entity/client/entity_statement.py +++ b/src/fedservice/entity/client/entity_statement.py @@ -86,9 +86,7 @@ def get_request_parameters( raise AttributeError("Missing endpoint") msg = Message() - if issuer: - msg['iss'] = issuer - if subject: - msg['sub'] = subject + # sub is a MUST + msg['sub'] = subject return {"url": msg.request(fetch_endpoint), 'method': method} diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index e62d2f6b..37861000 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -130,6 +130,9 @@ def get_document(self, url: str): elif response.status_code == 404: raise MissingPage(f"No such page: '{url}'") else: + logger.error(f"status_code: {response.status_code} on get {url}") + if response.text: + logger.info(f"Error description: {response.text}") raise FailedConfigurationRetrieval() def get_entity_configuration(self, entity_id): @@ -241,6 +244,7 @@ def get_entity_statement(self, fetch_endpoint, issuer, subject): return self.get_document(_res['url']) except FailedConfigurationRetrieval: logger.error(f"Failed to fetch {_res['url']}") + logger.error(f"Request: {_res}") raise def collect_tree(self, @@ -274,6 +278,7 @@ def collect_tree(self, return superior for authority in entity_configuration['authority_hints']: + logger.info(f"authority: {authority}") if authority in seen: # loop ?! logger.warning(f"Loop detected at {authority}") continue From f905e11f6215cb1c4d74f85dfc7bde0e6361d62a Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 1 May 2025 17:48:43 +0200 Subject: [PATCH 04/43] Working on different federation topologies. --- .../appserver/oauth2/authorization.py | 24 ++++- src/fedservice/entity/function/__init__.py | 6 +- src/fedservice/entity/function/verifier.py | 94 +++++++++++-------- src/fedservice/message.py | 7 ++ .../trust_mark_entity/server/trust_mark.py | 4 +- tests/test_07_utils.py | 21 +++-- tests/test_08_trust_mark.py | 3 + tests/test_13_automatic_registration_oauth.py | 85 ++++++++++++++++- tests/test_40_fe.py | 3 + tests/test_41_federation_entity.py | 23 +---- tests/test_70_trust_marks.py | 16 +++- 11 files changed, 207 insertions(+), 79 deletions(-) diff --git a/src/fedservice/appserver/oauth2/authorization.py b/src/fedservice/appserver/oauth2/authorization.py index 03e3ab8d..1504c7ce 100644 --- a/src/fedservice/appserver/oauth2/authorization.py +++ b/src/fedservice/appserver/oauth2/authorization.py @@ -2,6 +2,9 @@ from typing import List from typing import Optional +from idpyoidc.message import Message + +from fedservice.entity.function import get_payload from idpyoidc.message import oauth2 from idpyoidc.message.oauth2 import OauthClientMetadata from idpyoidc.node import topmost_unit @@ -65,7 +68,7 @@ def do_automatic_registration(self, entity_id: str, provided_trust_chain: List[s # pick one of the possible trust_chain = trust_chains[0] - _fe = topmost_unit(self)['federation_entity'] + _fe = get_federation_entity(self) _fe.trust_chain_anchor = trust_chain.anchor # handle the registration request as in the non-federation case. @@ -86,6 +89,21 @@ def do_automatic_registration(self, entity_id: str, provided_trust_chain: List[s except KeyError: return None + def get_trust_chain(self, request: Message) -> Optional[list]: + _trust_chain = request.get('trust_chain', []) + if not _trust_chain: + payload = {} + if "request" in request: + payload = get_payload(request["request"]) + elif "request_uri" in request: + # Fetch the request + _context = self.upstream_get("context") + _req = self._do_request_uri(request, client_id="", context=_context) + payload = get_payload(_req) + + _trust_chain = payload.get("trust_chain") + return _trust_chain + def client_authentication(self, request, auth=None, **kwargs): _cid = request["client_id"] _context = self.upstream_get("context") @@ -93,8 +111,8 @@ def client_authentication(self, request, auth=None, **kwargs): client_info = _context.cdb.get(_cid) if client_info is None: if 'automatic' in _context.provider_info.get('client_registration_types_supported'): - # try the federation way - _trust_chain = request.get('trust_chain', []) + _trust_chain = self.get_trust_chain(request) + # try the federation way. First, not using request object or request_uri registered_client_id = self.do_automatic_registration(_cid, _trust_chain) if registered_client_id is None: return { diff --git a/src/fedservice/entity/function/__init__.py b/src/fedservice/entity/function/__init__.py index badd5393..c01d8fa6 100644 --- a/src/fedservice/entity/function/__init__.py +++ b/src/fedservice/entity/function/__init__.py @@ -114,9 +114,9 @@ def verify_trust_chains(unit, chains: List[List[str]], *entity_statements): for c in chains: if entity_statements: c.extend(entity_statements) - trust_chain = _verifier(c) - if trust_chain: - res.append(trust_chain) + trust_chains = _verifier(c) + if trust_chains: + res.extend(trust_chains) return res diff --git a/src/fedservice/entity/function/verifier.py b/src/fedservice/entity/function/verifier.py index 6f698d0e..c605b397 100644 --- a/src/fedservice/entity/function/verifier.py +++ b/src/fedservice/entity/function/verifier.py @@ -1,6 +1,7 @@ import logging from typing import Callable from typing import List +from typing import Optional from cryptojwt import KeyBundle from cryptojwt.exception import MissingKey @@ -10,50 +11,56 @@ from fedservice.entity.utils import get_federation_entity from fedservice.entity_statement.constraints import meets_restrictions from fedservice.entity_statement.statement import TrustChain -from fedservice.exception import UnknownTrustAnchor logger = logging.getLogger(__name__) class TrustChainVerifier(Function): - def __init__(self, upstream_get: Callable): + def __init__(self, upstream_get: Callable, trust_anchor: Optional[List[str]] = None): Function.__init__(self, upstream_get) + self.trust_anchor = trust_anchor or [] - def trusted_anchor(self, entity_statement): + def trusted_anchor(self, entity_statement) -> bool: _jwt = factory(entity_statement) payload = _jwt.jwt.payload() - _federation_entity = get_federation_entity(self) - if _federation_entity: - if payload['iss'] not in _federation_entity.keyjar: - logger.warning( - f"Trust chain ending in a trust anchor I do not know: {payload['iss']}", ) - return False - else: - _keyjar = self.upstream_get("attribute", "keyjar") - if not _keyjar: - return False - elif payload['iss'] not in _keyjar: - logger.warning( - f"Trust chain ending in a trust anchor I do not know: {payload['iss']}", ) - return False - - return True + if self.trust_anchor: + return payload['iss'] in self.trust_anchor + elif self.upstream_get: + _federation = get_federation_entity(self) + return payload["iss"] in _federation.function.trust_chain_collector.trust_anchors + return False + + def verify_trust_chain(self, entity_statement_list: List) -> Optional[List]: + """ + Verifies the trust chain. Works its way down from the Trust Anchor to the leaf. - def verify_trust_chain(self, entity_statement_list): + :param entity_statement_list: List of entity statements. The entity's self-signed statement last. + :return: List of lists of verified entity statements + """ + logger.debug("Find verified trust chains") + res = [] + + for i in range(len(entity_statement_list) - 1, -1, -1): + if self.trusted_anchor(entity_statement_list[i]): + # Trust chain ending in a trust anchor I know. + verified_trust_chain = self._verify_trust_chain(entity_statement_list[i:]) + if verified_trust_chain: + res.append(verified_trust_chain) + if not res: + logger.debug("Found no verified trust anchors") + return res + + def _verify_trust_chain(self, entity_statement_list: List) -> Optional[List]: """ Verifies the trust chain. Works its way down from the Trust Anchor to the leaf. :param entity_statement_list: List of entity statements. The entity's self-signed statement last. :return: A sequence of verified entity statements """ - ves = [] - logger.debug("verify_trust_chain") - if not self.trusted_anchor(entity_statement_list[0]): - # Trust chain ending in a trust anchor I don't know. - logger.debug("Unknown trust anchor") - return ves + + verified_entity_statement = [] n = len(entity_statement_list) - 1 _keyjar = self.upstream_get("attribute", "keyjar") @@ -75,7 +82,7 @@ def verify_trust_chain(self, entity_statement_list): try: _jwks = res['jwks'] except KeyError: - if len(ves) != n: + if len(verified_entity_statement) != n: raise ValueError('Missing signing JWKS') else: _kb = KeyBundle(keys=_jwks['keys']) @@ -95,10 +102,10 @@ def verify_trust_chain(self, entity_statement_list): _kb.set(new) _keyjar.add_kb(res['sub'], _kb) - ves.append(res) + verified_entity_statement.append(res) - if ves and meets_restrictions(ves): - return ves + if verified_entity_statement and meets_restrictions(verified_entity_statement): + return verified_entity_statement else: return [] @@ -112,7 +119,7 @@ def trust_chain_expires_at(self, trust_chain): exp = entity_statement['exp'] return exp - def __call__(self, chain: List[str]): + def __call__(self, chain: List[str]) -> Optional[List]: """ :param chain: A chain of Entity Statements. The first one issued by a TA about an @@ -120,19 +127,24 @@ def __call__(self, chain: List[str]): :returns: A TrustChain instances """ logger.debug("Evaluate trust chain") - verified_trust_chain = self.verify_trust_chain(chain) + verified_trust_chains = self.verify_trust_chain(chain) - if not verified_trust_chain: + if not verified_trust_chains: return None - _expires_at = self.trust_chain_expires_at(verified_trust_chain) + trust_chains = [] + for verified_trust_chain in verified_trust_chains: + _expires_at = self.trust_chain_expires_at(verified_trust_chain) + + trust_chain = TrustChain(exp=_expires_at, verified_chain=verified_trust_chain) - trust_chain = TrustChain(exp=_expires_at, verified_chain=verified_trust_chain) + # Collect the issuers in the trust path + iss_path = [x['iss'] for x in verified_trust_chain] + trust_chain.anchor = iss_path[0] + iss_path.reverse() + trust_chain.iss_path = iss_path - iss_path = [x['iss'] for x in verified_trust_chain] - trust_chain.anchor = iss_path[0] - iss_path.reverse() - trust_chain.iss_path = iss_path - trust_chain.chain = chain + trust_chain.chain = chain + trust_chains.append(trust_chain) - return trust_chain + return trust_chains diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 379b4527..2ddebcd7 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -151,6 +151,13 @@ class FederationEntity(InformationalMetadataExtensions): # If it's a Trust Anchor # "trust_mark_owners": SINGLE_OPTIONAL_DICT, # "trust_mark_issuers": SINGLE_OPTIONAL_DICT, + "federation_fetch_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_list_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_resolve_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_status_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_list_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_historical_keys_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, }) diff --git a/src/fedservice/trust_mark_entity/server/trust_mark.py b/src/fedservice/trust_mark_entity/server/trust_mark.py index acb3660a..84d61cae 100644 --- a/src/fedservice/trust_mark_entity/server/trust_mark.py +++ b/src/fedservice/trust_mark_entity/server/trust_mark.py @@ -47,7 +47,7 @@ def process_request(self, _jws = _trust_mark_issuer.create_trust_mark(_id, _sub) - return {"http_response": _jws} + return {"response": _jws} def response_info( self, @@ -56,5 +56,7 @@ def response_info( error: Optional[str] = "", **kwargs ) -> dict: + if "http_response" in response_args: + return response_args["response"] if "response" in response_args: return response_args["response"] diff --git a/tests/test_07_utils.py b/tests/test_07_utils.py index 2863a5a1..ee08acf6 100644 --- a/tests/test_07_utils.py +++ b/tests/test_07_utils.py @@ -46,17 +46,20 @@ def test_eval_chains(): key_jar = import_jwks_as_json(key_jar, jwks, 'https://feide.no') _unit = Unit(keyjar=key_jar) - _verifier = TrustChainVerifier(upstream_get=_unit.unit_get) + _verifier = TrustChainVerifier(upstream_get=_unit.unit_get, + trust_anchor=['https://feide.no']) - trust_chain = _verifier(chains[0]) + trust_chains = _verifier(chains[0]) + assert len(trust_chains) == 1 - assert trust_chain.anchor == "https://feide.no" + for trust_chain in trust_chains: + assert trust_chain.anchor == "https://feide.no" - _policy = TrustChainPolicy(upstream_get=_unit.unit_get) - _policy(trust_chain) + _policy = TrustChainPolicy(upstream_get=_unit.unit_get) + _policy(trust_chain) - assert set(trust_chain.metadata.keys()) == {'openid_relying_party'} + assert set(trust_chain.metadata.keys()) == {'openid_relying_party'} - assert set(trust_chain.metadata['openid_relying_party'].keys()) == { - 'response_types', 'claims', 'contacts', 'application_type', 'redirect_uris', - 'id_token_signing_alg_values_supported', 'jwks_uri'} + assert set(trust_chain.metadata['openid_relying_party'].keys()) == { + 'response_types', 'claims', 'contacts', 'application_type', 'redirect_uris', + 'id_token_signing_alg_values_supported', 'jwks_uri'} diff --git a/tests/test_08_trust_mark.py b/tests/test_08_trust_mark.py index 312f694a..3d84454c 100644 --- a/tests/test_08_trust_mark.py +++ b/tests/test_08_trust_mark.py @@ -207,5 +207,8 @@ def test_metadata(self): 'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'organization_name'} assert _metadata["federation_entity"]["federation_trust_mark_endpoint"] == 'https://tmi.example.com/trust_mark' diff --git a/tests/test_13_automatic_registration_oauth.py b/tests/test_13_automatic_registration_oauth.py index 4e9df071..826f84e6 100644 --- a/tests/test_13_automatic_registration_oauth.py +++ b/tests/test_13_automatic_registration_oauth.py @@ -1,19 +1,20 @@ import os +import pytest +import responses from idpyoidc.client.defaults import DEFAULT_KEY_DEFS from idpyoidc.server.oidc.token import Token from idpyoidc.util import rndstr -import pytest -import responses from fedservice.defaults import COMBINED_DEFAULT_OAUTH2_SERVICES from fedservice.defaults import DEFAULT_OAUTH2_FED_SERVICES from fedservice.defaults import federation_endpoints from fedservice.defaults import federation_services +from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains +from . import create_trust_chain_messages from . import CRYPT_CONFIG from . import RESPONSE_TYPES_SUPPORTED -from . import create_trust_chain_messages from .build_federation import build_federation BASE_PATH = os.path.abspath(os.path.dirname(__file__)) @@ -266,3 +267,81 @@ def test_automatic_registration_new_client_id(self): # Assert that the client"s entity_id has been registered as a client assert self.oc.entity_id in self.oas["oauth_authorization_server"].get_context().cdb + + def test_authz_request_with_trust_chain(self): + # No clients registered with the OP at the beginning + assert len(self.oas["oauth_authorization_server"].get_context().cdb.keys()) == 0 + + #################################################### + # [1] Let the RP gather some provider info discovery + + # Point the RP to the OP + self.oc["oauth_client"].get_context().issuer = self.oas.entity_id + + # Create the URLs and messages that will be involved in this process AS -> TA + _msgs = create_trust_chain_messages(self.oas, self.ta) + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/entity-statement+jwt"}, + status=200) + + # The client collects trust chain from the AS + _trust_chains = get_verified_trust_chains(self.oc, self.oas["federation_entity"].entity_id) + + # one would assume this + # self.oc["oauth_client"].context.server_metadata = _trust_chains[0].metadata['oauth_authorization_server'] + # But NO this is what is expected + self.oc["oauth_client"].context.server_metadata = _trust_chains[0].metadata + self.oc["federation_entity"].client.context.server_metadata = _trust_chains[0].metadata + + # create trust chain client->TA. This will later be added to the Authz request + _msgs = create_trust_chain_messages(self.oc, self.im, self.ta) + trust_chain = [_msgs[es] for es in ['https://client.example.org/.well-known/openid-federation', + 'https://im.example.org/fetch', + 'https://ta.example.org/fetch']] + + # create authorization request with request object + _auth_service = self.oc["oauth_client"].get_service("authorization") + authn_request = _auth_service.construct( + request_args={"response_type": "code", "state": rndstr(), "trust_chain": trust_chain, + "redirect_uri": self.oc["oauth_client"].context.claims.get_preference("redirect_uris")[0]}) + + assert "request" in authn_request + _req_args = get_payload(authn_request["request"]) + assert set(_req_args.keys()) == {'aud', + 'client_id', + 'exp', + 'iat', + 'iss', + 'jti', + 'redirect_uri', + 'response_type', + 'state', + 'trust_chain'} + + # ------------------------------ + # <<<<<< On the AS's side >>>>>>> + + # _msgs = create_trust_chain_messages(self.oc, self.im, self.ta) + _msgs = {} + # add the jwks_uri + _jwks_uri = self.oc["oauth_client"].get_context().get_preference("jwks_uri") + if _jwks_uri: + _msgs[_jwks_uri] = self.oc["oauth_client"].keyjar.export_jwks_as_json() + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/entity-statement+jwt"}, + status=200) + + # The OP handles the authorization request + _authz_endpoint = self.oas["oauth_authorization_server"].get_endpoint("authorization") + try: + req = _authz_endpoint.parse_request(authn_request) + except Exception as err: + print(err) + + assert "response_type" in req diff --git a/tests/test_40_fe.py b/tests/test_40_fe.py index 436c0997..45ca6065 100644 --- a/tests/test_40_fe.py +++ b/tests/test_40_fe.py @@ -128,6 +128,9 @@ def test_server(self): 'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'homepage_uri', 'organization_name' } diff --git a/tests/test_41_federation_entity.py b/tests/test_41_federation_entity.py index 55ba7701..a57e9d95 100644 --- a/tests/test_41_federation_entity.py +++ b/tests/test_41_federation_entity.py @@ -89,26 +89,10 @@ def test_entity_configuration_request(self): def test_entity_statement_request(self): _serv = self.rp_fed.get_service('entity_statement') - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch") + _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", subject=self.rp_fed.entity_id) assert _res == { 'method': 'GET', - 'url': 'https://ta.example.org/fetch' - } - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", - issuer=self.ta_fed.entity_id) - assert _res == { - 'method': 'GET', - 'url': - 'https://ta.example.org/fetch?iss=https%3A%2F%2Fta.example.org' - } - - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", - issuer=self.ta_fed.entity_id, - subject=self.rp_fed.entity_id) - assert _res == { - 'method': 'GET', - 'url': 'https://ta.example.org/fetch?iss=https%3A%2F%2Fta.example' - '.org&sub=https%3A%2F%2Frp.example.org' + 'url': 'https://ta.example.org/fetch?sub=https%3A%2F%2Frp.example.org' } def test_resolve_request(self): @@ -306,6 +290,9 @@ def create_entities(self): def test_trust_chains_to_intermediate(self): _federation_entity = self.intermediate + # Should not be necessary. It's pytest that messes things up + if 'https://2nd.ta.example.org' in _federation_entity.function.trust_chain_collector.trust_anchors: + del _federation_entity.function.trust_chain_collector.trust_anchors['https://2nd.ta.example.org'] _msgs = create_trust_chain_messages(self.leaf, self.intermediate, self.ta1) _msgs.update(create_trust_chain_messages(self.leaf, self.ta2)) diff --git a/tests/test_70_trust_marks.py b/tests/test_70_trust_marks.py index 9d9bd2de..9b5dfdd5 100644 --- a/tests/test_70_trust_marks.py +++ b/tests/test_70_trust_marks.py @@ -7,7 +7,9 @@ from idpyoidc.message import Message from fedservice.defaults import LEAF_ENDPOINTS +from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains +from fedservice.message import TrustMark from fedservice.utils import make_federation_entity from tests import create_trust_chain_messages @@ -189,9 +191,14 @@ def test_get_trust_mark(self): _parse_req = _server_endpoint.parse_request(_req.to_dict(), get_client_info=get_client_info) _hw_resp = _server_endpoint.process_request(_parse_req) - _resp = _server_endpoint.do_response(_hw_resp) + _resp = _server_endpoint.do_response(response_args=_hw_resp) assert set(_resp.keys()) == {"response", "http_headers"} + # Check the signed JWT + _tm = TrustMark().from_jwt(_resp["response"], keyjar=_kj) + _tm.verify() + assert set(_tm.keys()) == {'iat', 'trust_mark_id', 'sub', 'exp', 'iss'} + # should be one item in the list _client_service = self.federation_entity.get_service("trust_mark_list") req_info = _client_service.get_request_parameters(request_args={"trust_mark_id": TRUST_MARK_ID}, @@ -215,4 +222,11 @@ def test_create_metadata(self): assert set(_metadata["federation_entity"].keys()) == {'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'organization_name'} + fe_metadata = _metadata["federation_entity"] + assert fe_metadata["federation_trust_mark_endpoint_auth_methods"] == ["private_key_jwt"] + assert fe_metadata["federation_trust_mark_list_endpoint_auth_methods"] == ["none"] + assert fe_metadata["federation_trust_mark_status_endpoint_auth_methods"] == ["none"] \ No newline at end of file From 3241745bdd0887e2c21632d3390ccede83249866 Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Mon, 28 Apr 2025 14:32:33 +0200 Subject: [PATCH 05/43] Fixed entity statement 'typ' header. --- edu_federation/README_identity.rst | 22 +++++++++++----------- edu_federation/trust_anchor/views.py | 3 ++- src/fedservice/entity_statement/create.py | 2 +- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/edu_federation/README_identity.rst b/edu_federation/README_identity.rst index e6f64d7a..fd0f7451 100644 --- a/edu_federation/README_identity.rst +++ b/edu_federation/README_identity.rst @@ -51,11 +51,11 @@ This will create a number of things in the *trust_anchor* directory All entities in the federation has to have some information about the trust mark. The information to pass along is collected by doing:: - ./get_info.py -k -t https://127.0.0.1:7010 > trust_anchor.json + ./get_info.py -k -t https://89.46.21.210:7010 > trust_anchor.json This must be done while the Trust anchor is running. Of course if you have changed the entity_id of the trust anchor from -https://127.0.0.1:7003 to something else you have to change this command accordingly. +https://89.46.21.210:7003 to something else you have to change this command accordingly. Now you're done with phase 1 concerning the trust anchor. So you can kill that process for the time being. @@ -92,11 +92,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t trust_mark_issuer/trust_anchors - echo -e "https://127.0.0.1:7010" >> trust_mark_issuer/authority_hints + echo -e "https://89.46.21.210:7010" >> trust_mark_issuer/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:6010 > tmp.json + ./get_info.py -k -s https://89.46.21.210:6010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates The fourth is presently done like this (may change in the future):: @@ -143,11 +143,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t openid_provider/trust_anchors - echo -e "https://127.0.0.1:7010" >> openid_provider/authority_hints + echo -e "https://89.46.21.210:7010" >> openid_provider/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4020 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4020 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -190,11 +190,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t relying_party_explicit/trust_anchors - echo -e "https://127.0.0.1:7010" >> relying_party_explicit/authority_hints + echo -e "https://89.46.21.210:7010" >> relying_party_explicit/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4010 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -237,11 +237,11 @@ Now four things have to happen:: The first two are simply:: ./add_info.py -s trust_anchor.json -t relying_party_automatic/trust_anchors - echo -e "https://127.0.0.1:7010" >> relying_party_automatic/authority_hints + echo -e "https://89.46.21.210:7010" >> relying_party_automatic/authority_hints The third would look like this:: - ./get_info.py -k -s https://127.0.0.1:4015 > tmp.json + ./get_info.py -k -s https://89.46.21.210:4010 > tmp.json ./add_info.py -s tmp.json -t trust_anchor/subordinates @@ -265,7 +265,7 @@ Creating a trust mark for an entity For this the script *create_trust_mark.py* is included. Typical usage:: - ./create_trust_mark.py -d trust_mark_issuer -m https://refeds.org/category/personalized -e https://127.0.0.1:4010 + ./create_trust_mark.py -d trust_mark_issuer -m https://refeds.org/category/personalized -e https://89.46.21.210:4010 > trust_mark.4010 diff --git a/edu_federation/trust_anchor/views.py b/edu_federation/trust_anchor/views.py index d312b8ed..7165dd4d 100644 --- a/edu_federation/trust_anchor/views.py +++ b/edu_federation/trust_anchor/views.py @@ -185,5 +185,6 @@ def wkof(): lifetime=_ctx.default_lifetime) response = make_response(_statement) - response.headers['Content-Type'] = 'application/jose; charset=UTF-8' + if 'Content-Type' not in response.headers: + response.headers['Content-Type'] = 'application/entity-statement+jwt' return response diff --git a/src/fedservice/entity_statement/create.py b/src/fedservice/entity_statement/create.py index 3fe26a82..9fd844b2 100644 --- a/src/fedservice/entity_statement/create.py +++ b/src/fedservice/entity_statement/create.py @@ -57,4 +57,4 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime) - return packer.pack(payload=msg) + return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) From d6bac985297fe7553ab3c8ef391b8f723c9abdcf Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Tue, 29 Apr 2025 15:31:15 +0200 Subject: [PATCH 06/43] Fail gracefully --- src/fedservice/defaults.py | 2 + .../entity/function/trust_chain_collector.py | 30 ++++++++++--- .../entity/function/trust_mark_verifier.py | 44 ++++++++++++------ src/fedservice/entity_statement/create.py | 7 +-- tests/test_01_create.py | 45 +++++++++++++++---- 5 files changed, 97 insertions(+), 31 deletions(-) diff --git a/src/fedservice/defaults.py b/src/fedservice/defaults.py index 59c3de99..7f0e8420 100644 --- a/src/fedservice/defaults.py +++ b/src/fedservice/defaults.py @@ -221,3 +221,5 @@ def federation_functions(*apis): DEFAULT_FEDERATION_ENTITY_FUNCTIONS = federation_functions("trust_chain_collector", "verifier", "policy", "trust_mark_verifier") + +DEFAULT_SIGNING_ALGORITHM = "RS256" \ No newline at end of file diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index 1f0998e1..e62d2f6b 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -1,6 +1,8 @@ import logging -import time from ssl import SSLError +import sys +import time +import traceback from typing import Callable from typing import List from typing import Optional @@ -15,8 +17,9 @@ from idpyoidc.message import Message from requests.exceptions import ConnectionError -from fedservice.entity.function import collect_trust_chains +from fedservice.defaults import DEFAULT_SIGNING_ALGORITHM from fedservice.entity.function import Function +from fedservice.entity.function import collect_trust_chains from fedservice.entity.function import verify_trust_chains from fedservice.entity.utils import get_federation_entity from fedservice.entity_statement.cache import ESCache @@ -33,6 +36,11 @@ def unverified_entity_statement(signed_jwt): return _jws.jwt.payload() +def signing_algorithm(signed_jwt): + _jws = factory(signed_jwt) + return _jws.jwt.headers.get("alg", DEFAULT_SIGNING_ALGORITHM) + + def verify_self_signed_signature(statement): """ Verify signature using only keys in the entity statement. @@ -47,7 +55,7 @@ def verify_self_signed_signature(statement): if payload['iss'] not in keyjar: keyjar = import_jwks(keyjar, payload['jwks'], payload['iss']) - _jwt = JWT(key_jar=keyjar) + _jwt = JWT(key_jar=keyjar, sign_alg=signing_algorithm(statement)) _val = _jwt.unpack(statement) return _val @@ -229,7 +237,11 @@ def get_entity_statement(self, fetch_endpoint, issuer, subject): # if self.use_ssc: # signed_entity_statement = self.do_ssc_seq(_url, issuer) # else: - return self.get_document(_res['url']) + try: + return self.get_document(_res['url']) + except FailedConfigurationRetrieval: + logger.error(f"Failed to fetch {_res['url']}") + raise def collect_tree(self, entity_id: str, @@ -264,8 +276,14 @@ def collect_tree(self, for authority in entity_configuration['authority_hints']: if authority in seen: # loop ?! logger.warning(f"Loop detected at {authority}") - superior[authority] = self.collect_branch(entity_id, authority, seen, - max_superiors, stop_at=stop_at) + continue + try: + superior[authority] = self.collect_branch(entity_id, authority, seen, + max_superiors, stop_at=stop_at) + except Exception as err: + message = traceback.format_exception(*sys.exc_info()) + logger.error(message) + continue return superior diff --git a/src/fedservice/entity/function/trust_mark_verifier.py b/src/fedservice/entity/function/trust_mark_verifier.py index a86256c7..7150389c 100644 --- a/src/fedservice/entity/function/trust_mark_verifier.py +++ b/src/fedservice/entity/function/trust_mark_verifier.py @@ -5,6 +5,7 @@ from cryptojwt import KeyJar from cryptojwt.exception import Expired from cryptojwt.jws.jws import factory +from fedservice.entity import FederationEntity from idpyoidc.key_import import import_jwks from idpyoidc.message import Message @@ -31,8 +32,13 @@ class TrustMarkVerifier(Function): 4) Find a trust chain to the trust mark issuer 5) Verify the signature of the trust mark """ - def __init__(self, upstream_get: Callable): + def __init__(self, upstream_get: Optional[Callable] = None, + federation_entity: Optional[FederationEntity] = None + ): + if not upstream_get and not federation_entity: + raise ValueError("Must have one of upstream_get and federation_entity") Function.__init__(self, upstream_get) + self.federation_entity = federation_entity def check_delegation(self, trust_anchor_statement, trust_mark) -> bool: _owners = trust_anchor_statement.get("trust_mark_owners", {}) @@ -85,7 +91,11 @@ def __call__(self, raise # Get trust anchor information in order to verify the issuer and if needed the delegator. - _federation_entity = get_federation_entity(self) + if self.federation_entity: + _federation_entity = self.federation_entity + else: + _federation_entity = get_federation_entity(self) + trust_anchor_statement = get_verified_trust_anchor_statement(_federation_entity, trust_anchor) # Check delegation @@ -108,14 +118,16 @@ def __call__(self, return None # Now time to verify the signature of the trust mark - _trust_chains = get_verified_trust_chains(self, _trust_mark['iss']) - if not _trust_chains: - logger.warning(f"Could not find any verifiable trust chains for {_trust_mark['iss']}") - return None + _trust_chains = [] + if _trust_mark["iss"] != trust_anchor: + _trust_chains = get_verified_trust_chains(_federation_entity, _trust_mark['iss']) + if not _trust_chains: + logger.warning(f"Could not find any verifiable trust chains for {_trust_mark['iss']}") + return None - if trust_anchor not in [_tc.anchor for _tc in _trust_chains]: - logger.warning(f'No verified trust chain to the trust anchor: {trust_anchor}') - return None + if trust_anchor not in [_tc.anchor for _tc in _trust_chains]: + logger.warning(f'No verified trust chain to the trust anchor: {trust_anchor}') + return None # Now try to verify the signature on the trust_mark # should have the necessary keys @@ -124,10 +136,16 @@ def __call__(self, keys = keyjar.get_jwt_verify_keys(_jwt.jwt) if not keys: - _trust_chains = apply_policies(_federation_entity, _trust_chains) - keyjar = import_jwks(keyjar, - _trust_chains[0].verified_chain[-1]["jwks"], - _trust_chains[0].iss_path[0]) + if _trust_mark["iss"] != trust_anchor: + keyjar = import_jwks(keyjar, + trust_anchor_statement["jwks"], + trust_anchor_statement["iss"]) + else: + _trust_chains = apply_policies(_federation_entity, _trust_chains) + keyjar = import_jwks(keyjar, + _trust_chains[0].verified_chain[-1]["jwks"], + _trust_chains[0].iss_path[0]) + keys = keyjar.get_jwt_verify_keys(_jwt.jwt) try: diff --git a/src/fedservice/entity_statement/create.py b/src/fedservice/entity_statement/create.py index 9fd844b2..b66e646a 100644 --- a/src/fedservice/entity_statement/create.py +++ b/src/fedservice/entity_statement/create.py @@ -1,5 +1,6 @@ import logging from typing import Callable +from typing import Optional from cryptojwt.jwt import JWT @@ -8,7 +9,7 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=None, authority_hints=None, lifetime=86400, aud='', include_jwks=True, - constraints=None, **kwargs): + constraints=None, signing_alg: Optional[str] = "RS256", **kwargs): """ :param iss: The issuer of the signed JSON Web Token @@ -23,6 +24,7 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No :param aud: Possible audience for the JWT :param include_jwks: Add JWKS :param constraints: A dictionary with constraints. + :param signing_alg: Which signing algorithm that should be used :return: A signed JSON Web Token """ @@ -55,6 +57,5 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No # The public signing keys of the subject msg['jwks'] = key_jar.export_jwks() - packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime) - + packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime, sign_alg=signing_alg) return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) diff --git a/tests/test_01_create.py b/tests/test_01_create.py index 302f9078..356bfa91 100644 --- a/tests/test_01_create.py +++ b/tests/test_01_create.py @@ -1,8 +1,16 @@ +import json + +from cryptojwt import KeyJar +from cryptojwt.jwk.jwk import key_from_jwk_dict from cryptojwt.jws.jws import factory from cryptojwt.key_jar import build_keyjar +import pytest + +from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature from idpyoidc.key_import import import_jwks_as_json from fedservice.entity_statement.create import create_entity_statement +from tests import test_vector KEYSPEC = [ {"type": "RSA", "use": ["sig"]}, @@ -10,9 +18,13 @@ ] RECEIVER = 'https://example.org/op' +ISSUER_ID = "https://example.org" - -def test_create_self_signed(): +@pytest.mark.parametrize( + "alg", + ["RS256", "RS384", "RS512", "PS256", "PS384", "PS512"], +) +def test_create_self_signed(alg): metadata = { "application_type": "web", "claims": [ @@ -33,19 +45,34 @@ def test_create_self_signed(): ] } - iss = "https://example.com" + iss = ISSUER_ID sub = iss - key_jar = build_keyjar(KEYSPEC, issuer_id=iss) + json_priv_key = json.loads(test_vector.json_rsa_priv_key) + json_priv_key["alg"] = alg + json_pub_key = json.loads(test_vector.json_rsa_pub_key) + json_pub_key["alg"] = alg + + json_header_rsa = json.loads(test_vector.test_header_rsa) + json_header_rsa["alg"] = alg + + sign_key_jar = KeyJar() + _key = key_from_jwk_dict(json_priv_key) + _key.add_kid() + sign_key_jar.add_keys("", [_key]) authority = ["https://ntnu.no"] - _jwt = create_entity_statement(iss, sub, key_jar, metadata=metadata, authority_hints=authority) + _jwt = create_entity_statement(iss, sub, sign_key_jar, metadata=metadata, + authority_hints=authority, + signing_alg=alg) assert _jwt - _verifier = factory(_jwt) - keys = key_jar.get_jwt_verify_keys(_verifier.jwt) - res = _verifier.verify_compact(keys=keys) + # _verifier = factory(_jwt) + # verifier_key_jar = KeyJar() + # verifier_key_jar.add_keys("", [key_from_jwk_dict(json_pub_key)]) + # res = _verifier.verify_compact(keys=keys) + res = verify_self_signed_signature(_jwt) assert res assert res['iss'] == iss @@ -99,7 +126,7 @@ def test_signed_someone_else_metadata(): _verifier = factory(_jwt) keys = sub_key_jar.get_jwt_verify_keys(_verifier.jwt) - res = _verifier.verify_compact(keys=keys) + res = _verifier.verify_compact(keys=keys, sigalg="RS256") assert res assert res['iss'] == iss From 6f73286cbf1cd6e40d2a8e5cfe8a91c1013bffeb Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Wed, 30 Apr 2025 09:57:04 +0200 Subject: [PATCH 07/43] iss not part of the fetch query anymore. More logging. --- src/fedservice/entity/client/entity_statement.py | 6 ++---- src/fedservice/entity/function/trust_chain_collector.py | 5 +++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/fedservice/entity/client/entity_statement.py b/src/fedservice/entity/client/entity_statement.py index aecef8af..f7fd6920 100644 --- a/src/fedservice/entity/client/entity_statement.py +++ b/src/fedservice/entity/client/entity_statement.py @@ -86,9 +86,7 @@ def get_request_parameters( raise AttributeError("Missing endpoint") msg = Message() - if issuer: - msg['iss'] = issuer - if subject: - msg['sub'] = subject + # sub is a MUST + msg['sub'] = subject return {"url": msg.request(fetch_endpoint), 'method': method} diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index e62d2f6b..37861000 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -130,6 +130,9 @@ def get_document(self, url: str): elif response.status_code == 404: raise MissingPage(f"No such page: '{url}'") else: + logger.error(f"status_code: {response.status_code} on get {url}") + if response.text: + logger.info(f"Error description: {response.text}") raise FailedConfigurationRetrieval() def get_entity_configuration(self, entity_id): @@ -241,6 +244,7 @@ def get_entity_statement(self, fetch_endpoint, issuer, subject): return self.get_document(_res['url']) except FailedConfigurationRetrieval: logger.error(f"Failed to fetch {_res['url']}") + logger.error(f"Request: {_res}") raise def collect_tree(self, @@ -274,6 +278,7 @@ def collect_tree(self, return superior for authority in entity_configuration['authority_hints']: + logger.info(f"authority: {authority}") if authority in seen: # loop ?! logger.warning(f"Loop detected at {authority}") continue From e3270cb6ece97bf5763413ebda8695ac8fc58e4f Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 1 May 2025 17:48:43 +0200 Subject: [PATCH 08/43] Working on different federation topologies. --- .../appserver/oauth2/authorization.py | 24 ++++- src/fedservice/entity/function/__init__.py | 6 +- src/fedservice/entity/function/verifier.py | 94 +++++++++++-------- src/fedservice/message.py | 7 ++ .../trust_mark_entity/server/trust_mark.py | 4 +- tests/test_07_utils.py | 21 +++-- tests/test_08_trust_mark.py | 3 + tests/test_13_automatic_registration_oauth.py | 85 ++++++++++++++++- tests/test_40_fe.py | 3 + tests/test_41_federation_entity.py | 23 +---- tests/test_70_trust_marks.py | 16 +++- 11 files changed, 207 insertions(+), 79 deletions(-) diff --git a/src/fedservice/appserver/oauth2/authorization.py b/src/fedservice/appserver/oauth2/authorization.py index 03e3ab8d..1504c7ce 100644 --- a/src/fedservice/appserver/oauth2/authorization.py +++ b/src/fedservice/appserver/oauth2/authorization.py @@ -2,6 +2,9 @@ from typing import List from typing import Optional +from idpyoidc.message import Message + +from fedservice.entity.function import get_payload from idpyoidc.message import oauth2 from idpyoidc.message.oauth2 import OauthClientMetadata from idpyoidc.node import topmost_unit @@ -65,7 +68,7 @@ def do_automatic_registration(self, entity_id: str, provided_trust_chain: List[s # pick one of the possible trust_chain = trust_chains[0] - _fe = topmost_unit(self)['federation_entity'] + _fe = get_federation_entity(self) _fe.trust_chain_anchor = trust_chain.anchor # handle the registration request as in the non-federation case. @@ -86,6 +89,21 @@ def do_automatic_registration(self, entity_id: str, provided_trust_chain: List[s except KeyError: return None + def get_trust_chain(self, request: Message) -> Optional[list]: + _trust_chain = request.get('trust_chain', []) + if not _trust_chain: + payload = {} + if "request" in request: + payload = get_payload(request["request"]) + elif "request_uri" in request: + # Fetch the request + _context = self.upstream_get("context") + _req = self._do_request_uri(request, client_id="", context=_context) + payload = get_payload(_req) + + _trust_chain = payload.get("trust_chain") + return _trust_chain + def client_authentication(self, request, auth=None, **kwargs): _cid = request["client_id"] _context = self.upstream_get("context") @@ -93,8 +111,8 @@ def client_authentication(self, request, auth=None, **kwargs): client_info = _context.cdb.get(_cid) if client_info is None: if 'automatic' in _context.provider_info.get('client_registration_types_supported'): - # try the federation way - _trust_chain = request.get('trust_chain', []) + _trust_chain = self.get_trust_chain(request) + # try the federation way. First, not using request object or request_uri registered_client_id = self.do_automatic_registration(_cid, _trust_chain) if registered_client_id is None: return { diff --git a/src/fedservice/entity/function/__init__.py b/src/fedservice/entity/function/__init__.py index badd5393..c01d8fa6 100644 --- a/src/fedservice/entity/function/__init__.py +++ b/src/fedservice/entity/function/__init__.py @@ -114,9 +114,9 @@ def verify_trust_chains(unit, chains: List[List[str]], *entity_statements): for c in chains: if entity_statements: c.extend(entity_statements) - trust_chain = _verifier(c) - if trust_chain: - res.append(trust_chain) + trust_chains = _verifier(c) + if trust_chains: + res.extend(trust_chains) return res diff --git a/src/fedservice/entity/function/verifier.py b/src/fedservice/entity/function/verifier.py index 6f698d0e..c605b397 100644 --- a/src/fedservice/entity/function/verifier.py +++ b/src/fedservice/entity/function/verifier.py @@ -1,6 +1,7 @@ import logging from typing import Callable from typing import List +from typing import Optional from cryptojwt import KeyBundle from cryptojwt.exception import MissingKey @@ -10,50 +11,56 @@ from fedservice.entity.utils import get_federation_entity from fedservice.entity_statement.constraints import meets_restrictions from fedservice.entity_statement.statement import TrustChain -from fedservice.exception import UnknownTrustAnchor logger = logging.getLogger(__name__) class TrustChainVerifier(Function): - def __init__(self, upstream_get: Callable): + def __init__(self, upstream_get: Callable, trust_anchor: Optional[List[str]] = None): Function.__init__(self, upstream_get) + self.trust_anchor = trust_anchor or [] - def trusted_anchor(self, entity_statement): + def trusted_anchor(self, entity_statement) -> bool: _jwt = factory(entity_statement) payload = _jwt.jwt.payload() - _federation_entity = get_federation_entity(self) - if _federation_entity: - if payload['iss'] not in _federation_entity.keyjar: - logger.warning( - f"Trust chain ending in a trust anchor I do not know: {payload['iss']}", ) - return False - else: - _keyjar = self.upstream_get("attribute", "keyjar") - if not _keyjar: - return False - elif payload['iss'] not in _keyjar: - logger.warning( - f"Trust chain ending in a trust anchor I do not know: {payload['iss']}", ) - return False - - return True + if self.trust_anchor: + return payload['iss'] in self.trust_anchor + elif self.upstream_get: + _federation = get_federation_entity(self) + return payload["iss"] in _federation.function.trust_chain_collector.trust_anchors + return False + + def verify_trust_chain(self, entity_statement_list: List) -> Optional[List]: + """ + Verifies the trust chain. Works its way down from the Trust Anchor to the leaf. - def verify_trust_chain(self, entity_statement_list): + :param entity_statement_list: List of entity statements. The entity's self-signed statement last. + :return: List of lists of verified entity statements + """ + logger.debug("Find verified trust chains") + res = [] + + for i in range(len(entity_statement_list) - 1, -1, -1): + if self.trusted_anchor(entity_statement_list[i]): + # Trust chain ending in a trust anchor I know. + verified_trust_chain = self._verify_trust_chain(entity_statement_list[i:]) + if verified_trust_chain: + res.append(verified_trust_chain) + if not res: + logger.debug("Found no verified trust anchors") + return res + + def _verify_trust_chain(self, entity_statement_list: List) -> Optional[List]: """ Verifies the trust chain. Works its way down from the Trust Anchor to the leaf. :param entity_statement_list: List of entity statements. The entity's self-signed statement last. :return: A sequence of verified entity statements """ - ves = [] - logger.debug("verify_trust_chain") - if not self.trusted_anchor(entity_statement_list[0]): - # Trust chain ending in a trust anchor I don't know. - logger.debug("Unknown trust anchor") - return ves + + verified_entity_statement = [] n = len(entity_statement_list) - 1 _keyjar = self.upstream_get("attribute", "keyjar") @@ -75,7 +82,7 @@ def verify_trust_chain(self, entity_statement_list): try: _jwks = res['jwks'] except KeyError: - if len(ves) != n: + if len(verified_entity_statement) != n: raise ValueError('Missing signing JWKS') else: _kb = KeyBundle(keys=_jwks['keys']) @@ -95,10 +102,10 @@ def verify_trust_chain(self, entity_statement_list): _kb.set(new) _keyjar.add_kb(res['sub'], _kb) - ves.append(res) + verified_entity_statement.append(res) - if ves and meets_restrictions(ves): - return ves + if verified_entity_statement and meets_restrictions(verified_entity_statement): + return verified_entity_statement else: return [] @@ -112,7 +119,7 @@ def trust_chain_expires_at(self, trust_chain): exp = entity_statement['exp'] return exp - def __call__(self, chain: List[str]): + def __call__(self, chain: List[str]) -> Optional[List]: """ :param chain: A chain of Entity Statements. The first one issued by a TA about an @@ -120,19 +127,24 @@ def __call__(self, chain: List[str]): :returns: A TrustChain instances """ logger.debug("Evaluate trust chain") - verified_trust_chain = self.verify_trust_chain(chain) + verified_trust_chains = self.verify_trust_chain(chain) - if not verified_trust_chain: + if not verified_trust_chains: return None - _expires_at = self.trust_chain_expires_at(verified_trust_chain) + trust_chains = [] + for verified_trust_chain in verified_trust_chains: + _expires_at = self.trust_chain_expires_at(verified_trust_chain) + + trust_chain = TrustChain(exp=_expires_at, verified_chain=verified_trust_chain) - trust_chain = TrustChain(exp=_expires_at, verified_chain=verified_trust_chain) + # Collect the issuers in the trust path + iss_path = [x['iss'] for x in verified_trust_chain] + trust_chain.anchor = iss_path[0] + iss_path.reverse() + trust_chain.iss_path = iss_path - iss_path = [x['iss'] for x in verified_trust_chain] - trust_chain.anchor = iss_path[0] - iss_path.reverse() - trust_chain.iss_path = iss_path - trust_chain.chain = chain + trust_chain.chain = chain + trust_chains.append(trust_chain) - return trust_chain + return trust_chains diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 379b4527..2ddebcd7 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -151,6 +151,13 @@ class FederationEntity(InformationalMetadataExtensions): # If it's a Trust Anchor # "trust_mark_owners": SINGLE_OPTIONAL_DICT, # "trust_mark_issuers": SINGLE_OPTIONAL_DICT, + "federation_fetch_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_list_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_resolve_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_status_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_trust_mark_list_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, + "federation_historical_keys_endpoint_auth_methods": OPTIONAL_LIST_OF_STRINGS, }) diff --git a/src/fedservice/trust_mark_entity/server/trust_mark.py b/src/fedservice/trust_mark_entity/server/trust_mark.py index acb3660a..84d61cae 100644 --- a/src/fedservice/trust_mark_entity/server/trust_mark.py +++ b/src/fedservice/trust_mark_entity/server/trust_mark.py @@ -47,7 +47,7 @@ def process_request(self, _jws = _trust_mark_issuer.create_trust_mark(_id, _sub) - return {"http_response": _jws} + return {"response": _jws} def response_info( self, @@ -56,5 +56,7 @@ def response_info( error: Optional[str] = "", **kwargs ) -> dict: + if "http_response" in response_args: + return response_args["response"] if "response" in response_args: return response_args["response"] diff --git a/tests/test_07_utils.py b/tests/test_07_utils.py index 2863a5a1..ee08acf6 100644 --- a/tests/test_07_utils.py +++ b/tests/test_07_utils.py @@ -46,17 +46,20 @@ def test_eval_chains(): key_jar = import_jwks_as_json(key_jar, jwks, 'https://feide.no') _unit = Unit(keyjar=key_jar) - _verifier = TrustChainVerifier(upstream_get=_unit.unit_get) + _verifier = TrustChainVerifier(upstream_get=_unit.unit_get, + trust_anchor=['https://feide.no']) - trust_chain = _verifier(chains[0]) + trust_chains = _verifier(chains[0]) + assert len(trust_chains) == 1 - assert trust_chain.anchor == "https://feide.no" + for trust_chain in trust_chains: + assert trust_chain.anchor == "https://feide.no" - _policy = TrustChainPolicy(upstream_get=_unit.unit_get) - _policy(trust_chain) + _policy = TrustChainPolicy(upstream_get=_unit.unit_get) + _policy(trust_chain) - assert set(trust_chain.metadata.keys()) == {'openid_relying_party'} + assert set(trust_chain.metadata.keys()) == {'openid_relying_party'} - assert set(trust_chain.metadata['openid_relying_party'].keys()) == { - 'response_types', 'claims', 'contacts', 'application_type', 'redirect_uris', - 'id_token_signing_alg_values_supported', 'jwks_uri'} + assert set(trust_chain.metadata['openid_relying_party'].keys()) == { + 'response_types', 'claims', 'contacts', 'application_type', 'redirect_uris', + 'id_token_signing_alg_values_supported', 'jwks_uri'} diff --git a/tests/test_08_trust_mark.py b/tests/test_08_trust_mark.py index 312f694a..3d84454c 100644 --- a/tests/test_08_trust_mark.py +++ b/tests/test_08_trust_mark.py @@ -207,5 +207,8 @@ def test_metadata(self): 'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'organization_name'} assert _metadata["federation_entity"]["federation_trust_mark_endpoint"] == 'https://tmi.example.com/trust_mark' diff --git a/tests/test_13_automatic_registration_oauth.py b/tests/test_13_automatic_registration_oauth.py index 4e9df071..826f84e6 100644 --- a/tests/test_13_automatic_registration_oauth.py +++ b/tests/test_13_automatic_registration_oauth.py @@ -1,19 +1,20 @@ import os +import pytest +import responses from idpyoidc.client.defaults import DEFAULT_KEY_DEFS from idpyoidc.server.oidc.token import Token from idpyoidc.util import rndstr -import pytest -import responses from fedservice.defaults import COMBINED_DEFAULT_OAUTH2_SERVICES from fedservice.defaults import DEFAULT_OAUTH2_FED_SERVICES from fedservice.defaults import federation_endpoints from fedservice.defaults import federation_services +from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains +from . import create_trust_chain_messages from . import CRYPT_CONFIG from . import RESPONSE_TYPES_SUPPORTED -from . import create_trust_chain_messages from .build_federation import build_federation BASE_PATH = os.path.abspath(os.path.dirname(__file__)) @@ -266,3 +267,81 @@ def test_automatic_registration_new_client_id(self): # Assert that the client"s entity_id has been registered as a client assert self.oc.entity_id in self.oas["oauth_authorization_server"].get_context().cdb + + def test_authz_request_with_trust_chain(self): + # No clients registered with the OP at the beginning + assert len(self.oas["oauth_authorization_server"].get_context().cdb.keys()) == 0 + + #################################################### + # [1] Let the RP gather some provider info discovery + + # Point the RP to the OP + self.oc["oauth_client"].get_context().issuer = self.oas.entity_id + + # Create the URLs and messages that will be involved in this process AS -> TA + _msgs = create_trust_chain_messages(self.oas, self.ta) + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/entity-statement+jwt"}, + status=200) + + # The client collects trust chain from the AS + _trust_chains = get_verified_trust_chains(self.oc, self.oas["federation_entity"].entity_id) + + # one would assume this + # self.oc["oauth_client"].context.server_metadata = _trust_chains[0].metadata['oauth_authorization_server'] + # But NO this is what is expected + self.oc["oauth_client"].context.server_metadata = _trust_chains[0].metadata + self.oc["federation_entity"].client.context.server_metadata = _trust_chains[0].metadata + + # create trust chain client->TA. This will later be added to the Authz request + _msgs = create_trust_chain_messages(self.oc, self.im, self.ta) + trust_chain = [_msgs[es] for es in ['https://client.example.org/.well-known/openid-federation', + 'https://im.example.org/fetch', + 'https://ta.example.org/fetch']] + + # create authorization request with request object + _auth_service = self.oc["oauth_client"].get_service("authorization") + authn_request = _auth_service.construct( + request_args={"response_type": "code", "state": rndstr(), "trust_chain": trust_chain, + "redirect_uri": self.oc["oauth_client"].context.claims.get_preference("redirect_uris")[0]}) + + assert "request" in authn_request + _req_args = get_payload(authn_request["request"]) + assert set(_req_args.keys()) == {'aud', + 'client_id', + 'exp', + 'iat', + 'iss', + 'jti', + 'redirect_uri', + 'response_type', + 'state', + 'trust_chain'} + + # ------------------------------ + # <<<<<< On the AS's side >>>>>>> + + # _msgs = create_trust_chain_messages(self.oc, self.im, self.ta) + _msgs = {} + # add the jwks_uri + _jwks_uri = self.oc["oauth_client"].get_context().get_preference("jwks_uri") + if _jwks_uri: + _msgs[_jwks_uri] = self.oc["oauth_client"].keyjar.export_jwks_as_json() + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/entity-statement+jwt"}, + status=200) + + # The OP handles the authorization request + _authz_endpoint = self.oas["oauth_authorization_server"].get_endpoint("authorization") + try: + req = _authz_endpoint.parse_request(authn_request) + except Exception as err: + print(err) + + assert "response_type" in req diff --git a/tests/test_40_fe.py b/tests/test_40_fe.py index 436c0997..45ca6065 100644 --- a/tests/test_40_fe.py +++ b/tests/test_40_fe.py @@ -128,6 +128,9 @@ def test_server(self): 'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'homepage_uri', 'organization_name' } diff --git a/tests/test_41_federation_entity.py b/tests/test_41_federation_entity.py index 3eea6abe..697e5097 100644 --- a/tests/test_41_federation_entity.py +++ b/tests/test_41_federation_entity.py @@ -89,26 +89,10 @@ def test_entity_configuration_request(self): def test_entity_statement_request(self): _serv = self.rp_fed.get_service('entity_statement') - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch") + _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", subject=self.rp_fed.entity_id) assert _res == { 'method': 'GET', - 'url': 'https://ta.example.org/fetch' - } - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", - issuer=self.ta_fed.entity_id) - assert _res == { - 'method': 'GET', - 'url': - 'https://ta.example.org/fetch?iss=https%3A%2F%2Fta.example.org' - } - - _res = _serv.get_request_parameters(fetch_endpoint=f"{self.ta_fed.entity_id}/fetch", - issuer=self.ta_fed.entity_id, - subject=self.rp_fed.entity_id) - assert _res == { - 'method': 'GET', - 'url': 'https://ta.example.org/fetch?iss=https%3A%2F%2Fta.example' - '.org&sub=https%3A%2F%2Frp.example.org' + 'url': 'https://ta.example.org/fetch?sub=https%3A%2F%2Frp.example.org' } def test_resolve_request(self): @@ -306,6 +290,9 @@ def create_entities(self): def test_trust_chains_to_intermediate(self): _federation_entity = self.intermediate + # Should not be necessary. It's pytest that messes things up + if 'https://2nd.ta.example.org' in _federation_entity.function.trust_chain_collector.trust_anchors: + del _federation_entity.function.trust_chain_collector.trust_anchors['https://2nd.ta.example.org'] _msgs = create_trust_chain_messages(self.leaf, self.intermediate, self.ta1) _msgs.update(create_trust_chain_messages(self.leaf, self.ta2)) diff --git a/tests/test_70_trust_marks.py b/tests/test_70_trust_marks.py index 9d9bd2de..9b5dfdd5 100644 --- a/tests/test_70_trust_marks.py +++ b/tests/test_70_trust_marks.py @@ -7,7 +7,9 @@ from idpyoidc.message import Message from fedservice.defaults import LEAF_ENDPOINTS +from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains +from fedservice.message import TrustMark from fedservice.utils import make_federation_entity from tests import create_trust_chain_messages @@ -189,9 +191,14 @@ def test_get_trust_mark(self): _parse_req = _server_endpoint.parse_request(_req.to_dict(), get_client_info=get_client_info) _hw_resp = _server_endpoint.process_request(_parse_req) - _resp = _server_endpoint.do_response(_hw_resp) + _resp = _server_endpoint.do_response(response_args=_hw_resp) assert set(_resp.keys()) == {"response", "http_headers"} + # Check the signed JWT + _tm = TrustMark().from_jwt(_resp["response"], keyjar=_kj) + _tm.verify() + assert set(_tm.keys()) == {'iat', 'trust_mark_id', 'sub', 'exp', 'iss'} + # should be one item in the list _client_service = self.federation_entity.get_service("trust_mark_list") req_info = _client_service.get_request_parameters(request_args={"trust_mark_id": TRUST_MARK_ID}, @@ -215,4 +222,11 @@ def test_create_metadata(self): assert set(_metadata["federation_entity"].keys()) == {'federation_trust_mark_endpoint', 'federation_trust_mark_list_endpoint', 'federation_trust_mark_status_endpoint', + 'federation_trust_mark_endpoint_auth_methods', + 'federation_trust_mark_list_endpoint_auth_methods', + 'federation_trust_mark_status_endpoint_auth_methods', 'organization_name'} + fe_metadata = _metadata["federation_entity"] + assert fe_metadata["federation_trust_mark_endpoint_auth_methods"] == ["private_key_jwt"] + assert fe_metadata["federation_trust_mark_list_endpoint_auth_methods"] == ["none"] + assert fe_metadata["federation_trust_mark_status_endpoint_auth_methods"] == ["none"] \ No newline at end of file From ed86873b5d6d56b1f6078320a9509eb8de0178ba Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 1 May 2025 20:25:37 +0200 Subject: [PATCH 09/43] Removed files --- tests/subordinate/.gitkeep | 0 tests/subordinate/https%3A%2F%2Frp.example.com | 1 - tests/subordinate/https%3A%2F%2Frp.example.com.lock | 0 3 files changed, 1 deletion(-) delete mode 100644 tests/subordinate/.gitkeep delete mode 100644 tests/subordinate/https%3A%2F%2Frp.example.com delete mode 100644 tests/subordinate/https%3A%2F%2Frp.example.com.lock diff --git a/tests/subordinate/.gitkeep b/tests/subordinate/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/subordinate/https%3A%2F%2Frp.example.com b/tests/subordinate/https%3A%2F%2Frp.example.com deleted file mode 100644 index 3b69a3c7..00000000 --- a/tests/subordinate/https%3A%2F%2Frp.example.com +++ /dev/null @@ -1 +0,0 @@ -{"jwks": {"keys": [{"kty": "RSA", "use": "sig", "kid": "MHgtMFdtV2RLem5MUEhLTl9GTWN6d09yTXBFZWxWNTFiRVotRHRYUU5Edw", "e": "AQAB", "n": "kug08yUQr9E9Go7EyYG3o3I838s_O3zKXhU1641ns23Uisyv58HdTGPyYo-hnnsO2di4WU2OBd_k4k1sAhXau08u0JevHAy3lF_9U5G9pBzs61vrhlm2jKE04mSXLZjoCQ4cvIhpRbb3XQe8WJ4J5VzKkYkDa8_85HRtK2XCmxEPrd_xVQePTDWPBKY1hOiYqTyua3_i0WrUoMsq8n03JQ-tAZGRI1yKcnEefwFipWTvQcxR-hpgYDYBMoiAH-FIgdk586obYPjlH2evkeYoohEkXMakDsUWQUUKlP6_DIyT8IlqDP1jGCYH_2QEkixeC9wAbcKan2MotzsO1h3eLw"}, {"kty": "EC", "use": "sig", "kid": "Z0gyUE1mMDVzallIMFd4WDZ6cnRmZXhiLXFRcmotY1puR3BsSXhGZDhDRQ", "crv": "P-256", "x": "VhGXHRlriZoid-5LcQ-0OpBbUw-P-2IyWGLb871Lzns", "y": "xjKNE5-75mzqkW6t_Is8n3eSt-cJVfvV7QFDUZPoVMU"}]}, "authority_hints": ["https://trust_anchor.example.com"]} \ No newline at end of file diff --git a/tests/subordinate/https%3A%2F%2Frp.example.com.lock b/tests/subordinate/https%3A%2F%2Frp.example.com.lock deleted file mode 100644 index e69de29b..00000000 From 3565a0ac677ed2f9e6c0af5fd17fc36989042841 Mon Sep 17 00:00:00 2001 From: Roland Hedberg Date: Thu, 1 May 2025 20:30:45 +0200 Subject: [PATCH 10/43] Scripts used in the interop. --- script/interop_resolve.py | 95 ++++++++++++++++++++ script/resolve.json | 11 +++ tests/test_10_explicit_registration_oidc.py | 2 +- tests/test_12_explicit_registration_oauth.py | 2 +- 4 files changed, 108 insertions(+), 2 deletions(-) create mode 100755 script/interop_resolve.py create mode 100644 script/resolve.json diff --git a/script/interop_resolve.py b/script/interop_resolve.py new file mode 100755 index 00000000..844861a7 --- /dev/null +++ b/script/interop_resolve.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +import json + +from cryptojwt.exception import BadSignature + +from fedservice.entity.function import apply_policies +from fedservice.entity.function import collect_trust_chains +from fedservice.entity.function import verify_trust_chains +from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature +from fedservice.entity.function.trust_mark_verifier import TrustMarkVerifier +from fedservice.utils import make_federation_entity + + +def get_trust_anchor_info(trust_anchor) -> dict: + federation_entity = make_federation_entity(entity_id="https://localhost", trust_anchors={}) + # federation_entity.keyjar.httpc_params = {"verify": False} + + _collector = federation_entity.get_function("trust_chain_collector") + + # Read the trust anchor entity configuration + _jws = _collector.get_entity_configuration(trust_anchor) + + # Verify the self signed signature + try: + entity_configuration = verify_self_signed_signature(_jws) + except BadSignature as err: + print("Bad signature on TA self-signed entity configuration") + print(_jws) + exit(1) + # + return entity_configuration + + +def get_trust_chains(entity_id, trust_anchors): + federation_entity = make_federation_entity(entity_id="https://localhost", + trust_anchors=trust_anchors) + #federation_entity.keyjar.httpc_params = {"verify": False} + + _ta = list(trust_anchors.keys())[0] + chains, leaf_ec = collect_trust_chains(federation_entity, entity_id=entity_id, stop_at=_ta) + if len(chains) == 0: + print("No chains") + + trust_chains = verify_trust_chains(federation_entity, chains, leaf_ec) + return apply_policies(federation_entity, trust_chains), federation_entity + + +if __name__ == '__main__': + test_set = json.loads(open("resolve.json").read()) + + for entity_id, anchors in test_set.items(): + for anchor in anchors: + print(f"************ {entity_id} @ {anchor} ************") + trust_anchor_entity_configuration = get_trust_anchor_info(anchor) + + # Now for collecting trust chain + trust_anchors = {trust_anchor_entity_configuration["iss"]: + trust_anchor_entity_configuration["jwks"]} + + trust_chains, federation_entity = get_trust_chains(entity_id=entity_id, + trust_anchors=trust_anchors) + + for trust_chain in trust_chains: + print(20 * "=", + f" Trust Chain for: {entity_id} ending in {trust_chain.anchor} ", + 20 * "=") + trust_chain.verified_chain.reverse() + for node in trust_chain.verified_chain: + if node["iss"] == node["sub"]: + print(20 * "-", f"Entity Configuration for: {node['iss']}", 20 * "-") + else: + if "trust_mark" in node: + print("'trust_mark' SHOULD NOT be used in a subordinate statement") + print(20 * "-", + f"Subordinate statement about: {node['sub']} from {node['iss']}", + 20 * "-") + # print JSON + print(json.dumps(node, sort_keys=True, indent=2)) + + print("== Metadata after metadata policy has been applied ==") + print(json.dumps(trust_chain.metadata, sort_keys=True, indent=2)) + + # Now verify trust marks + trust_marks = trust_chain.verified_chain[0].get("trust_marks") + if trust_marks: + ent = TrustMarkVerifier(federation_entity.upstream_get, + federation_entity=federation_entity) + print("== TRUST MARKS ==") + for trust_mark in trust_marks: + res = ent(trust_mark["trust_mark"], + trust_anchor_entity_configuration["iss"]) + if res: + if res["trust_mark_id"] != trust_mark["trust_mark_id"]: + print("*** Mismatch in trust_mark_id ***") + print(res) diff --git a/script/resolve.json b/script/resolve.json new file mode 100644 index 00000000..bb25b80e --- /dev/null +++ b/script/resolve.json @@ -0,0 +1,11 @@ +{ + "https://oidfed.luikyv.com": [ + "https://federation.pr-2721.ci.raidiam.io/federation_entity/5d0acc74-a8ea-4f9e-8238-3b4b22166e9a", + "https://ta.oidfed.data.kit.edu" + ], + "https://testop.nimbleidm.fi": [ + "https://federation.pr-2721.ci.raidiam.io/federation_entity/5d0acc74-a8ea-4f9e-8238-3b4b22166e9a", + "https://ta.oidfed.data.kit.edu" + ], + "https://circle.oidfed.data.kit.edu": ["https://ta.oidfed.data.kit.edu"] +} \ No newline at end of file diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index 969a937d..c1bb0d59 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -143,7 +143,7 @@ def test_create_reqistration_request(self): assert set(_info.keys()) == {"method", "url", "body", "headers", "request"} assert _info["method"] == "POST" assert _info["url"] == "https://op.example.org/registration" - assert _info["headers"] == {"Content-Type": "application/jose"} + assert _info["headers"] == {"Content-Type": "application/entity-statement+jwt"} _jws = _info["body"] _jwt = factory(_jws) diff --git a/tests/test_12_explicit_registration_oauth.py b/tests/test_12_explicit_registration_oauth.py index 64ed21b8..253e4e94 100644 --- a/tests/test_12_explicit_registration_oauth.py +++ b/tests/test_12_explicit_registration_oauth.py @@ -112,7 +112,7 @@ def test_create_reqistration_request(self): assert set(_info.keys()) == {"method", "url", "body", "headers", "request"} assert _info["method"] == "POST" assert _info["url"] == "https://op.example.org/registration" - assert _info["headers"] == {"Content-Type": "application/jose"} + assert _info["headers"] == {"Content-Type": 'application/entity-statement+jwt'} _jws = _info["body"] _jwt = factory(_jws) From 87b37895028a33bb050fff40bdc46642e2d4129e Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 12 May 2025 13:58:35 +0200 Subject: [PATCH 11/43] Worked on explicit client registration. --- src/fedservice/__init__.py | 2 +- .../appclient/oauth2/registration.py | 125 +++++++------- src/fedservice/appclient/oidc/registration.py | 114 ++++++++----- .../appserver/oauth2/registration.py | 33 ++-- src/fedservice/appserver/oidc/registration.py | 22 +-- src/fedservice/entity/function/__init__.py | 4 +- src/fedservice/entity/function/policy.py | 11 +- .../entity/function/trust_chain_collector.py | 6 +- tests/test_01_message.py | 160 ++++++++++++++++++ tests/test_04_tree2chains.py | 21 +++ tests/test_07a_entity_statement_request.py | 123 ++++++++++++++ tests/test_10_explicit_registration_oidc.py | 55 +++--- tests/test_12_explicit_registration_oauth.py | 32 ++-- tests/test_60_federation_topologies.py | 103 +++++++++++ tests/test_61_federation_topologies.py | 111 ++++++++++++ tests/test_62_federation_topologies.py | 118 +++++++++++++ 16 files changed, 864 insertions(+), 176 deletions(-) create mode 100644 tests/test_01_message.py create mode 100644 tests/test_07a_entity_statement_request.py create mode 100644 tests/test_60_federation_topologies.py create mode 100644 tests/test_61_federation_topologies.py create mode 100644 tests/test_62_federation_topologies.py diff --git a/src/fedservice/__init__.py b/src/fedservice/__init__.py index 788f0e41..a9f7c316 100644 --- a/src/fedservice/__init__.py +++ b/src/fedservice/__init__.py @@ -1,5 +1,5 @@ __author__ = 'Roland Hedberg' -__version__ = '5.1.0' +__version__ = '5.2.0' from typing import Optional diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index bbe2e7d6..fe591e5a 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -1,7 +1,7 @@ import logging from typing import Optional -from cryptojwt import KeyJar +from cryptojwt import JWT from idpyoidc.client.exception import ResponseError from idpyoidc.client.oidc import registration from idpyoidc.client.rp_handler import RPHandler @@ -11,12 +11,9 @@ from idpyoidc.node import topmost_unit from fedservice.entity.function import apply_policies -from fedservice.entity.function import collect_trust_chains from fedservice.entity.function import get_verified_trust_chains -from fedservice.entity.function import verify_trust_chains -from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature from fedservice.entity.utils import get_federation_entity -from fedservice.exception import SignatureFailure +from fedservice.exception import NoTrustedChains logger = logging.getLogger(__name__) @@ -31,6 +28,10 @@ class Registration(registration.Registration): content_type = "application/entity-statement+jwt" name = 'registration' + _supports = { + "client_registration_types": ["automatic", "explicit"] + } + def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs): registration.Registration.__init__(self, upstream_get, conf=conf) # @@ -88,7 +89,7 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) _combo = _federation_entity.upstream_get('unit') metadata = _combo.get_metadata(client=kwargs.get("client")) - _keyjar = _federation_entity.get_attribute("keyjar") + _federation_keyjar = _federation_entity.get_attribute("keyjar") _authority_hints = _federation_entity.get_authority_hints() _context = _federation_entity.get_context() _entity_id = _federation_entity.upstream_get('attribute', 'entity_id') @@ -101,7 +102,7 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) iss=_entity_id, sub=_entity_id, metadata=metadata, - key_jar=_keyjar, + key_jar=_federation_keyjar, authority_hints=_authority_hints, **kwargs) # store for later reference @@ -120,16 +121,6 @@ def parse_response(self, info, sformat="", state="", **kwargs): def _get_trust_anchor_id(self, entity_statement): return entity_statement.get('trust_anchor_id') - def _signature_verifies(self, entity_id, trust_anchor, federation_entity): - _chains, _ = collect_trust_chains(self.upstream_get('unit'), - entity_id=entity_id, - stop_at=trust_anchor) - if not _chains: - return False - - _trust_chains = verify_trust_chains(federation_entity, _chains) - return True - def parse_federation_registration_response(self, resp, **kwargs): """ Receives a dynamic client registration response, @@ -138,14 +129,16 @@ def parse_federation_registration_response(self, resp, **kwargs): :return: A set of metadata claims """ - # Find the part of me that deals with the federation + # Find the part of the entity that deals with the federation _federation_entity = get_federation_entity(self) - payload = verify_self_signed_signature(resp) + # verify signature with OP's federation keys + _jwt = JWT(key_jar=_federation_entity.keyjar) + payload = _jwt.unpack(resp) + # Do I trust the TA the OP chose ? logger.debug(f"trust_anchor_id: {payload['trust_anchor_id']}") - if (payload[ - 'trust_anchor_id'] not in + if (payload['trust_anchor_id'] not in _federation_entity.function.trust_chain_collector.trust_anchors): raise ValueError("Trust anchor I don't trust") @@ -159,66 +152,82 @@ def parse_federation_registration_response(self, resp, **kwargs): if _verifier_response: return _verifier_response else: - # verify the signature on the response from the OP - if not self._signature_verifies(payload["iss"], payload['trust_anchor_id'], - _federation_entity): - raise SignatureFailure("Could not verify signature") - # This is the trust chain from myself to the TA - _trust_chains = get_verified_trust_chains(self, entity_id=self.upstream_get('attribute', - 'entity_id')) + _entity_id = self.upstream_get('attribute', 'entity_id') + _trust_anchor = payload['trust_anchor_id'] + _trust_chains = get_verified_trust_chains(self, entity_id=_entity_id, stop_at=_trust_anchor) # should only be one chain - if len(_trust_chains) != 1: + if len(_trust_chains) == 0: + raise NoTrustedChains(_entity_id) + + _tcs = [t for t in _trust_chains if t.anchor == payload['trust_anchor_id']] + if len(_tcs) > 1: raise SystemError(f"More then one chain ending in {payload['trust_anchor_id']}") + else: + _trust_chains = _tcs _metadata = payload.get("metadata") if _metadata: + # replace the metadata provided by the client with the metadata received from the AS _trust_chains[0].verified_chain[-1]['metadata'] = _metadata - # If it's metadata_policy what to do ? + # If there is metadata_policy defined apply it _trust_chains = apply_policies(_federation_entity, _trust_chains) - _resp = _trust_chains[0].metadata + _resp = _trust_chains[0].verified_chain[-1] _context = self.upstream_get('context') _context.registration_response = _resp return _resp - def _add_client_secret_to_keyjar(self, context, client_id, metadata): - _client_secret = context.claims.get_usage("client_secret") - if _client_secret: - _keyjar = getattr(context, "keyjar", None) - if not _keyjar: - _entity = self.upstream_get("unit") - _keyjar = _entity.keyjar = KeyJar() - - context.client_secret = _client_secret - _keyjar.add_symmetric("", _client_secret) - _keyjar.add_symmetric(client_id, _client_secret) - - _expires_at = metadata.get("client_secret_expires_at", None) - if _expires_at: - context.set_usage("client_secret_expires_at", _expires_at) + # def _add_client_secret_to_keyjar(self, context, client_id, metadata): + # _client_secret = context.claims.get_usage("client_secret") + # if _client_secret: + # _keyjar = getattr(context, "keyjar", None) + # if not _keyjar: + # _entity = self.upstream_get("unit") + # _keyjar = _entity.keyjar = KeyJar() + # + # context.client_secret = _client_secret + # _keyjar.add_symmetric("", _client_secret) + # _keyjar.add_symmetric(client_id, _client_secret) + # + # _expires_at = metadata.get("client_secret_expires_at", None) + # if _expires_at: + # context.set_usage("client_secret_expires_at", _expires_at) def update_service_context(self, resp, **kwargs): # Updated service_context per entity type _root = topmost_unit(self) + _metadata = resp["metadata"] for guise, item in _root.items(): + _guise_metadata = _metadata.get(guise) + if not _guise_metadata: + continue + if isinstance(item, RPHandler): - try: - client = kwargs["behaviour_args"]["client"] - _context = client.context - _context.map_preferred_to_registered(resp[guise]) - - for arg in ["client_id", "client_secret"]: - _val = _context.claims.get_usage(arg) - if _val: - setattr(_context, arg, _val) - except KeyError: - pass + _behaviour_args = kwargs.get("behaviour_args") + if _behaviour_args: + _client = _behaviour_args.get("client") + if _client: + _context = _client.context + _context.map_preferred_to_registered(_guise_metadata) + + for arg in ["client_id", "client_secret"]: + _val = _context.claims.get_usage(arg) + if _val: + setattr(_context, arg, _val) + + if arg == "client_secret" and _val: + _context.keyjar.add_symmetric("", _val) + _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) else: _context = item.get_context() - _context.map_preferred_to_registered(resp[guise]) + _context.map_preferred_to_registered(_guise_metadata) _client_id = _context.claims.get_usage("client_id") if _client_id: _context.client_id = _client_id + + _client_secret = _context.claims.get_usage("client_secret") + _context.keyjar.add_symmetric("", _client_secret) + _context.keyjar.add_symmetric(_client_id, _client_secret) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index aed99df0..0785fade 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -1,17 +1,20 @@ import logging from typing import Optional +from typing import Union +from cryptojwt import JWT from idpyoidc.client.exception import ResponseError from idpyoidc.client.oidc import registration +from idpyoidc.client.rp_handler import RPHandler +from idpyoidc.message import Message from idpyoidc.message.oidc import RegistrationRequest from idpyoidc.message.oidc import RegistrationResponse +from idpyoidc.node import topmost_unit from fedservice.entity.function import apply_policies -from fedservice.entity.function import collect_trust_chains -from fedservice.entity.function import verify_trust_chains -from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature +from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.utils import get_federation_entity -from fedservice.exception import SignatureFailure +from fedservice.exception import NoTrustedChains logger = logging.getLogger(__name__) @@ -34,12 +37,6 @@ def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs) # self.post_construct.append(self.create_entity_statement) - # def get_provider_info_attributes(self): - # _pia = construct_provider_info(self.provider_info_attributes, **self.kwargs) - # if self.endpoint_name: - # _pia[self.endpoint_name] = self.full_path - # return _pia - @staticmethod def carry_receiver(request, **kwargs): if 'receiver' in kwargs: @@ -47,7 +44,7 @@ def carry_receiver(request, **kwargs): else: return request, {} - def create_entity_statement(self, request_args: Optional[dict]= None, **kwargs): + def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs): """ Create a self-signed entity statement @@ -61,7 +58,7 @@ def create_entity_statement(self, request_args: Optional[dict]= None, **kwargs): # _md = {_federation_context.entity_type: request_args.to_dict()} _root = _federation_entity.upstream_get('unit') _md = _root.get_metadata() - _keyjar = _federation_entity.get_attribute("keyjar") + _federation_keyjar = _federation_entity.get_attribute("keyjar") # _entity = self.upstream_get('unit') # if _entity.name not in _md: @@ -79,7 +76,7 @@ def create_entity_statement(self, request_args: Optional[dict]= None, **kwargs): iss=_entity_id, sub=_entity_id, metadata=_md, - key_jar=_keyjar, + key_jar=_federation_keyjar, authority_hints=_authority_hints, **kwargs) @@ -99,16 +96,6 @@ def parse_response(self, info, sformat="", state="", **kwargs): def _get_trust_anchor_id(self, entity_statement): return entity_statement.get('trust_anchor_id') - def _signature_verifies(self, entity_id, trust_anchor, federation_entity): - _chains, _ = collect_trust_chains(self.upstream_get('unit'), - entity_id=entity_id, - stop_at=trust_anchor) - if not _chains: - return False - - _trust_chains = verify_trust_chains(federation_entity, _chains) - return True - def parse_federation_registration_response(self, resp, **kwargs): """ Receives a dynamic client registration response, @@ -120,7 +107,10 @@ def parse_federation_registration_response(self, resp, **kwargs): # Find the part of me that deals with the federation _federation_entity = get_federation_entity(self) - payload = verify_self_signed_signature(resp) + # verify signature with OP's federation keys + _jwt = JWT(key_jar=_federation_entity.keyjar) + payload = _jwt.unpack(resp) + # Do I trust the TA the OP chose ? logger.debug(f"trust_anchor_id: {payload['trust_anchor_id']}") if payload[ @@ -137,28 +127,74 @@ def parse_federation_registration_response(self, resp, **kwargs): if _verifier_response: return _verifier_response else: - # verify the signature on the response from the OP - if not self._signature_verifies(payload["iss"], payload['trust_anchor_id'], - _federation_entity): - raise SignatureFailure("Could not verify signature") - # This is the trust chain from the RP to the TA - _chains, _ = collect_trust_chains(self.upstream_get('unit'), - entity_id=self.upstream_get('attribute', 'entity_id'), - stop_at=payload['trust_anchor_id']) - _trust_chains = verify_trust_chains(_federation_entity, _chains, resp) + _entity_id = self.upstream_get('attribute', 'entity_id') + _trust_anchor = payload['trust_anchor_id'] + _trust_chains = get_verified_trust_chains(self, entity_id=_entity_id, stop_at=_trust_anchor) + + # should only be one chain # should only be one chain - if len(_trust_chains) != 1: + if len(_trust_chains) == 0: + raise NoTrustedChains(_entity_id) + + _tcs = [t for t in _trust_chains if t.anchor == payload['trust_anchor_id']] + if len(_tcs) > 1: raise SystemError(f"More then one chain ending in {payload['trust_anchor_id']}") + else: + _trust_chains = _tcs + _metadata = payload.get("metadata") if _metadata: + # replace the metadata provided by the client with the metadata received from the AS _trust_chains[0].verified_chain[-1]['metadata'] = _metadata - # If it's metadata_policy what to do ? - _trust_chains = apply_policies(_federation_entity, _trust_chains) - _resp = _trust_chains[0].metadata['openid_relying_party'] + # If there is metadata_policy defined apply it + _trust_chains = apply_policies(_federation_entity, _trust_chains) + + _resp = _trust_chains[0].verified_chain[-1] _context = self.upstream_get('context') _context.registration_response = _resp return _resp - def update_service_context(self, resp, **kwargs): - registration.Registration.update_service_context(self, resp, **kwargs) + def update_service_context(self, resp: Union[Message, dict], **kwargs): + """ + Updates the service context with information from the Entity Statement return by the server + + :param resp: A Entity Statement + :param kwargs: extra key word arguments + """ + # Updated service_context per entity type + _root = topmost_unit(self) + _metadata = resp["metadata"] + for guise, item in _root.items(): + _guise_metadata = _metadata.get(guise) + if not _guise_metadata: + continue + + if isinstance(item, RPHandler): + _behaviour_args = kwargs.get("behaviour_args") + if _behaviour_args: + _client = _behaviour_args.get("client") + if _client: + _context = _client.context + _context.map_preferred_to_registered(_guise_metadata) + + for arg in ["client_id", "client_secret"]: + _val = _context.claims.get_usage(arg) + if _val: + setattr(_context, arg, _val) + + if arg == "client_secret" and _val: + _context.keyjar.add_symmetric("", _val) + _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) + + else: + _context = item.get_context() + _context.map_preferred_to_registered(_guise_metadata) + + _client_id = _context.claims.get_usage("client_id") + if _client_id: + _context.client_id = _client_id + + _client_secret = _context.claims.get_usage("client_secret") + _context.keyjar.add_symmetric("", _client_secret) + _context.keyjar.add_symmetric(_client_id, _client_secret) diff --git a/src/fedservice/appserver/oauth2/registration.py b/src/fedservice/appserver/oauth2/registration.py index 31f1abcd..846c6fae 100644 --- a/src/fedservice/appserver/oauth2/registration.py +++ b/src/fedservice/appserver/oauth2/registration.py @@ -20,12 +20,13 @@ from idpyoidc.util import sanitize from idpyoidc.util import split_uri +from fedservice import save_trust_chains from fedservice.appserver import import_client_keys from fedservice.entity.function import apply_policies -from fedservice.entity.function import collect_trust_chains -from fedservice.entity.function import verify_trust_chains +from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature from fedservice.entity.utils import get_federation_entity +from fedservice.exception import NoTrustedChains from fedservice.message import OauthClientInformationResponse logger = logging.getLogger(__name__) @@ -64,32 +65,32 @@ def process_request(self, request=None, **kwargs): 'trust_mark_issuer'}).pop() _federation_entity = get_federation_entity(self) - # Collect trust chains - _chains, _ = collect_trust_chains(self.upstream_get('unit'), - entity_id=payload['sub'], - signed_entity_configuration=request) - _trust_chains = verify_trust_chains(_federation_entity, _chains, request) + # Collect trust chains for client + _trust_chains = get_verified_trust_chains(self, entity_id=payload['sub']) + if not _trust_chains: + raise NoTrustedChains(f"No trust chains for {payload['sub']}") + + save_trust_chains(self.upstream_get("context"), _trust_chains) + _trust_chains = apply_policies(_federation_entity, _trust_chains) trust_chain = _federation_entity.pick_trust_chain(_trust_chains) _federation_entity.trust_chain_anchor = trust_chain.anchor + # Perform non-federation registration - req = oauth2.OauthClientMetadata(**trust_chain.metadata[opponent_entity_type]) + req = oauth2.OauthClientMetadata(**payload['metadata'][opponent_entity_type]) response_info = self.step2_process_request(req, **kwargs) if "response_args" in response_info: _context = _federation_entity.context - _policy_metadata = req.to_dict() - _policy_metadata.update(response_info['response_args']) - # Should I filter out stuff I have no reason to change ? - _policy_metadata = {k: v for k, v in _policy_metadata.items() if k not in [ - 'application_type', - 'jwks', - 'redirect_uris']} + _response_metadata = req.to_dict() + _response_metadata.update(response_info['response_args']) + entity_statement = _context.create_entity_statement( _federation_entity.upstream_get('attribute', 'entity_id'), payload['iss'], trust_anchor_id=trust_chain.anchor, - metadata={opponent_entity_type: _policy_metadata}, + metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], + include_jwks=False ) response_info["response_msg"] = entity_statement del response_info["response_args"] diff --git a/src/fedservice/appserver/oidc/registration.py b/src/fedservice/appserver/oidc/registration.py index a87f860d..aca2fc25 100644 --- a/src/fedservice/appserver/oidc/registration.py +++ b/src/fedservice/appserver/oidc/registration.py @@ -1,6 +1,5 @@ import logging -from fedservice.exception import NoTrustedChains from idpyoidc.message.oidc import RegistrationRequest from idpyoidc.server.oidc import registration @@ -8,6 +7,7 @@ from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.function.trust_chain_collector import verify_self_signed_signature from fedservice.entity.utils import get_federation_entity +from fedservice.exception import NoTrustedChains logger = logging.getLogger(__name__) @@ -61,25 +61,17 @@ def process_request(self, request=None, **kwargs): logger.debug(f"Registration response args: {response_info['response_args']}") _context = _federation_entity.context - for item in ["jwks", "jwks_uri", "signed_jwks_uri"]: - try: - del req[item] - except KeyError: - pass - - _policy_metadata = req.to_dict() - _policy_metadata.update(response_info['response_args']) - # Should I filter out stuff I have no reason to change ? - _policy_metadata = {k: v for k, v in _policy_metadata.items() if k not in [ - 'application_type', - 'redirect_uris']} + _response_metadata = req.to_dict() + _response_metadata.update(response_info['response_args']) + entity_statement = _context.create_entity_statement( _federation_entity.upstream_get('attribute', 'entity_id'), payload['iss'], trust_anchor_id=trust_chain.anchor, - metadata={opponent_entity_type: _policy_metadata}, + metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], - authority_hints=_federation_entity.get_authority_hints() + authority_hints=_federation_entity.get_authority_hints(), + include_jwks=False ) response_info["response_msg"] = entity_statement del response_info["response_args"] diff --git a/src/fedservice/entity/function/__init__.py b/src/fedservice/entity/function/__init__.py index c01d8fa6..4e3b016a 100644 --- a/src/fedservice/entity/function/__init__.py +++ b/src/fedservice/entity/function/__init__.py @@ -158,8 +158,8 @@ def __init__(self, upstream_get: Callable): self.upstream_get = upstream_get -def get_verified_trust_chains(unit, entity_id): - chains, leaf_ec = collect_trust_chains(unit, entity_id) +def get_verified_trust_chains(unit, entity_id: str, stop_at: Optional[str] = ""): + chains, leaf_ec = collect_trust_chains(unit, entity_id, stop_at=stop_at) if len(chains) == 0: return [] diff --git a/src/fedservice/entity/function/policy.py b/src/fedservice/entity/function/policy.py index 5f48d184..f7273db3 100644 --- a/src/fedservice/entity/function/policy.py +++ b/src/fedservice/entity/function/policy.py @@ -549,19 +549,16 @@ def apply_policy(self, metadata: dict, policy: dict, protocol: Optional[str] = " :return: A metadata statement that adheres to a metadata policy """ + _metadata_policy = policy.get('metadata_policy', None) + if _metadata_policy: + metadata = apply_metadata_policy(metadata, _metadata_policy, self.policy_operators) + _metadata = policy.get("metadata", None) if _metadata: # what's in metadata policy metadata overrides what's in leaf's metadata metadata.update(_metadata) metadata = _metadata - _metadata_policy = policy.get('metadata_policy', None) - if _metadata_policy: - metadata = apply_metadata_policy(metadata, _metadata_policy, self.policy_operators) - - # All that are in metadata but not in policy should just remain - # metadata.update(policy.get('metadata', {})) - # This is a protocol specific adjustment if protocol in ["oidc", "oauth2"]: return {k: v for k, v in metadata.items() if v != []} diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index 37861000..e1d414c3 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -234,8 +234,7 @@ def get_entity_statement(self, fetch_endpoint, issuer, subject): :return: A signed JWT """ _serv = self._get_service('entity_statement') - _res = _serv.get_request_parameters(subject=subject, fetch_endpoint=fetch_endpoint, - issuer=issuer) + _res = _serv.get_request_parameters(subject=subject, fetch_endpoint=fetch_endpoint) # if self.use_ssc: # signed_entity_statement = self.do_ssc_seq(_url, issuer) @@ -274,9 +273,10 @@ def collect_tree(self, logger.debug("No authority for this entity") return superior elif entity_configuration['iss'] == stop_at: - logger.debug("Reached trust anchor") + logger.debug("Reached stop point") return superior + logger.debug(f"Authority_hints: {entity_configuration['authority_hints']}") for authority in entity_configuration['authority_hints']: logger.info(f"authority: {authority}") if authority in seen: # loop ?! diff --git a/tests/test_01_message.py b/tests/test_01_message.py new file mode 100644 index 00000000..19c4555b --- /dev/null +++ b/tests/test_01_message.py @@ -0,0 +1,160 @@ +import json +import os + +from cryptojwt.jwt import utc_time_sans_frac + +from fedservice.message import EntityStatement +from fedservice.message import FederationEntity +from fedservice.message import JWKSet +from fedservice.message import TrustMark +from fedservice.message import TrustMarkIssuers +from fedservice.message import TrustMarkOwners + +BASE_PATH = os.path.abspath(os.path.dirname(__file__)) + + +def full_path(local_file): + return os.path.join(BASE_PATH, local_file) + + +def test_entity_statement(): + file = full_path("document_examples/entity_statement_jwt.json") + _data = json.loads(open(file, "r").read()) + _msg = EntityStatement().from_dict(_data) + _now = utc_time_sans_frac() + # Set expiration time to some time in the future + _msg["exp"] = _now + 100 + _msg.verify() + assert set(_msg["metadata"].keys()) == {"openid_provider", "oauth_client"} + assert set(_msg["metadata_policy"].keys()) == {"openid_provider", "oauth_client"} + + +def test_trust_mark_owners(): + file = full_path("document_examples/trust_mark_owners.json") + _data = json.loads(open(file, "r").read()) + _msg = TrustMarkOwners().from_dict(_data) + _msg.verify() + + +def test_trust_entity_statement_comb(): + file = full_path("document_examples/trust_mark_issuers.json") + _data = json.loads(open(file, "r").read()) + _msg = TrustMarkIssuers().from_dict(_data) + _msg.verify() + + +def test_entity_statement_comb(): + file_1 = full_path("document_examples/entity_statement_jwt.json") + _data = json.loads(open(file_1, "r").read()) + file_2 = full_path("document_examples/trust_mark_owners.json") + _data_2 = json.loads(open(file_2, "r").read()) + _data["trust_mark_owners"] = _data_2 + file_3 = full_path("document_examples/trust_mark_issuers.json") + _data_3 = json.loads(open(file_3, "r").read()) + _data["trust_mark_issuers"] = _data_3 + + _msg = EntityStatement().from_dict(_data) + _now = utc_time_sans_frac() + # Set expiration time to some time in the future + _msg["exp"] = _now + 100 + _msg.verify() + + assert set(_msg["trust_mark_issuers"].keys()) == {"https://openid.net/certification/op", + "https://refeds.org/wp-content/uploads/2016/01/Sirtfi-1.0.pdf"} + assert set(_msg["trust_mark_owners"].keys()) == {"https://refeds.org/wp-content/uploads/2016/01/Sirtfi-1.0.pdf"} + assert _msg["trust_mark_owners"]["https://refeds.org/wp-content/uploads/2016/01/Sirtfi-1.0.pdf"]["sub"] == \ + "https://refeds.org/sirtfi" + + +def test_federation_entity(): + file = full_path("document_examples/federation_entity.json") + _data = json.loads(open(file, "r").read()) + + _msg = FederationEntity().from_dict(_data) + + assert set(_msg.keys()) == {'federation_fetch_endpoint', + 'federation_list_endpoint', + 'federation_trust_mark_list_endpoint', + 'federation_trust_mark_status_endpoint', + 'homepage_uri', + 'organization_name'} + + +def test_oidc_rp(): + file = full_path("document_examples/oidc_rp.json") + _data = json.loads(open(file, "r").read()) + + _msg = FederationEntity().from_dict(_data) + + assert set(_msg.keys()) == {'iss', 'sub', 'iat', 'exp', 'metadata', 'jwks', 'authority_hints'} + assert set(_msg['metadata'].keys()) == {'openid_relying_party'} + assert set(_msg['metadata']['openid_relying_party'].keys()) == {'application_type', + 'client_registration_types', + 'grant_types', + 'jwks_uri', + 'logo_uri', + 'organization_name', + 'redirect_uris', + 'signed_jwks_uri'} + + +def test_oidc_op(): + file = full_path("document_examples/oidc_op.json") + _data = json.loads(open(file, "r").read()) + + _msg = FederationEntity().from_dict(_data) + + assert set(_msg.keys()) == {'iss', 'sub', 'iat', 'exp', 'metadata', 'jwks', 'authority_hints'} + assert set(_msg['metadata'].keys()) == {'openid_provider'} + assert set(_msg['metadata']['openid_provider'].keys()) == {'authorization_endpoint', + 'client_registration_types_supported', + 'federation_registration_endpoint', + 'grant_types_supported', + 'id_token_signing_alg_values_supported', + 'issuer', + 'logo_uri', + 'op_policy_uri', + 'pushed_authorization_request_endpoint', + 'request_object_signing_alg_values_supported', + 'response_types_supported', + 'signed_jwks_uri', + 'subject_types_supported', + 'token_endpoint', + 'token_endpoint_auth_methods_supported', + 'token_endpoint_auth_signing_alg_values_supported'} + + +def test_JWKSet(): + file = full_path("document_examples/jwks_claim_set.json") + _data = json.loads(open(file, "r").read()) + + _msg = JWKSet().from_dict(_data) + assert set(_msg.keys()) == {'iat', 'iss', 'sub', 'keys'} + assert len(_msg["keys"]) == 2 + +def test_trust_mark(): + file = full_path("document_examples/trust_mark.json") + _data = json.loads(open(file, "r").read()) + + _msg = EntityStatement().from_dict(_data) + assert set(_msg.keys()) == {'trust_marks', 'iss', 'iat', 'sub', 'exp', 'metadata'} + assert len(_msg['trust_marks']) == 1 + + # Set expiration time to some time in the future + _now = utc_time_sans_frac() + _msg["exp"] = _now + 100 + + _msg.verify() + +def test_trust_mark_delegation(): + file = full_path("document_examples/trust_mark_delegation.json") + _data = json.loads(open(file, "r").read()) + + _msg = TrustMark().from_dict(_data) + assert set(_msg.keys()) == {'iat', 'trust_mark_id', 'delegation', 'exp', 'sub', 'iss'} + + # Set expiration time to some time in the future + _now = utc_time_sans_frac() + _msg["exp"] = _now + 100 + + _msg.verify() diff --git a/tests/test_04_tree2chains.py b/tests/test_04_tree2chains.py index ce282fa8..57aae61f 100644 --- a/tests/test_04_tree2chains.py +++ b/tests/test_04_tree2chains.py @@ -75,6 +75,27 @@ def test_tree2chains_4(): assert chains[0] == ["statement3", "statement2", "statement1"] assert chains[1] == ["statement3", "statement5", "statement1"] +def test_tree2chains_a(): + tree = { + 'https://intermediate.example.org': ( + 'statement1', { + 'https://ta.example.org': ( + 'statement2', {} + ) + } + ), + 'https://intermediate2.example.org': ( + 'statement3', { + 'https://ta.example.org': ( + 'statement4', {} + ) + } + ) + } + chains = tree2chains(tree) + assert len(chains) == 2 + assert chains[0] == ['statement2', 'statement1'] + assert chains[1] == ['statement4', 'statement3'] def test_tree2chains_5(): tree = { diff --git a/tests/test_07a_entity_statement_request.py b/tests/test_07a_entity_statement_request.py new file mode 100644 index 00000000..96f10457 --- /dev/null +++ b/tests/test_07a_entity_statement_request.py @@ -0,0 +1,123 @@ +import os + +import pytest +import responses +from idpyoidc.client.defaults import DEFAULT_KEY_DEFS + +from fedservice.defaults import COMBINED_DEFAULT_OAUTH2_SERVICES +from fedservice.defaults import DEFAULT_OAUTH2_FED_SERVICES +from fedservice.defaults import federation_endpoints +from fedservice.defaults import federation_services +from fedservice.entity.utils import get_federation_entity +from tests import CRYPT_CONFIG +from tests.build_federation import build_federation + +BASE_PATH = os.path.abspath(os.path.dirname(__file__)) +ROOT_DIR = os.path.join(BASE_PATH, "base_data") + +TA_ID = "https://ta.example.org" +OC_ID = "https://client.example.org" +IM_ID = "https://im.example.org" + +SESSION_PARAMS = {"encrypter": CRYPT_CONFIG} + +OC_SERVICES = federation_services("entity_configuration", "entity_statement") +# OC_SERVICES.update(DEFAULT_OAUTH2_FED_SERVICES) + +AS_SERVICES = federation_services("entity_configuration", "entity_statement") +AS_SERVICES.update(DEFAULT_OAUTH2_FED_SERVICES) + +AS_ENDPOINTS = federation_endpoints("entity_configuration", "fetch") + +FEDERATION_CONFIG = { + TA_ID: { + "entity_type": "trust_anchor", + "subordinates": [IM_ID], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "endpoints": ["entity_configuration", "list", "fetch", "resolve"], + } + }, + OC_ID: { + "entity_type": "oauth_client", + "trust_anchors": [TA_ID], + "services": OC_SERVICES, + "kwargs": { + "authority_hints": [IM_ID], + "services": COMBINED_DEFAULT_OAUTH2_SERVICES, + "entity_type_config": { + # OAuth2 core keys + "keys": {"key_defs": DEFAULT_KEY_DEFS}, + "base_url": OC_ID, + "client_id": OC_ID, + "client_secret": "a longeeesh password", + "redirect_uris": ["https://rp.example.com/cli/authz_cb"], + "preference": { + "grant_types": ["authorization_code", "implicit", "refresh_token"], + "id_token_signed_response_alg": "ES256", + "token_endpoint_auth_method": "client_secret_basic", + "token_endpoint_auth_signing_alg": "ES256", + "client_registration_types": ["automatic"], + "request_parameter_supported": True + }, + "authorization_request_endpoints": [ + "authorization_endpoint", "pushed_authorization_request_endpoint" + ] + } + } + }, + IM_ID: { + "entity_type": "federation_entity", + "trust_anchors": [TA_ID], + "subordinates": [OC_ID], + "kwargs": { + "authority_hints": [TA_ID] + } + } +} + + +class TestFederationStatement(object): + + @pytest.fixture(autouse=True) + def create_endpoint(self): + # TA + # +---|---+ + # | | + # IM OAS + # | + # OC + + federation = build_federation(FEDERATION_CONFIG) + self.ta = federation[TA_ID] + self.oc = federation[OC_ID] + self.im = federation[IM_ID] + + def test_1(self): + _service = self.oc["federation_entity"].get_service("entity_statement") + _endpoint = get_federation_entity(self.ta).server.get_endpoint('entity_configuration') + _entcnf = _endpoint.process_request({})["response"] + + with responses.RequestsMock() as rsps: + rsps.add("GET", _endpoint.full_path, body=_entcnf, + adding_headers={"Content-Type": "application/json"}, status=200) + + args = _service.get_request_parameters(issuer=TA_ID, subject=IM_ID) + assert set(args.keys()) == {"url", "method"} + assert args["method"] == "GET" + assert args["url"] == 'https://ta.example.org/fetch?sub=https%3A%2F%2Fim.example.org' + + def test_2(self): + _service = self.oc["federation_entity"].get_service("entity_statement") + _endpoint = get_federation_entity(self.ta).server.get_endpoint('entity_configuration') + _entcnf = _endpoint.process_request({})["response"] + + args = _service.get_request_parameters(issuer=TA_ID, subject=IM_ID, + fetch_endpoint="https://ta.example.org/fetch") + assert set(args.keys()) == {"url", "method"} + assert args["method"] == "GET" + assert args["url"] == 'https://ta.example.org/fetch?sub=https%3A%2F%2Fim.example.org' diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index 969a937d..950c35af 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -1,10 +1,10 @@ import os +import pytest +import responses from cryptojwt.jws.jws import factory from idpyoidc.client.defaults import DEFAULT_KEY_DEFS from idpyoidc.client.defaults import DEFAULT_OIDC_SERVICES -import pytest -import responses from fedservice.defaults import DEFAULT_OIDC_FED_SERVICES from fedservice.entity.function import get_verified_trust_chains @@ -85,7 +85,7 @@ "path": "authz", 'class': 'fedservice.appserver.oidc.authorization.Authorization', "kwargs": {} - }},{ + }}, { "oidc_registration": { "path": "registration", 'class': 'fedservice.appserver.oidc.registration.Registration', @@ -220,21 +220,34 @@ def test_parse_registration_response(self): adding_headers={"Content-Type": "application/entity-statement+jwt"}, status=200) - claims = self.registration_service.parse_response(resp["response_msg"], - request=_info["body"]) - - assert set(claims.keys()) == {'client_id', - 'client_id_issued_at', - 'client_registration_types', - 'client_secret_expires_at', - 'client_secret', - 'default_max_age', - 'grant_types', - 'id_token_signed_response_alg', - 'request_object_signing_alg', - 'response_modes', - 'response_types', - 'subject_type', - 'token_endpoint_auth_method', - 'token_endpoint_auth_signing_alg', - 'userinfo_signed_response_alg'} + response = self.registration_service.parse_response(resp["response_msg"], + request=_info["body"]) + + metadata = response["metadata"] + # The response doesn't touch the federation_entity metadata, therefor it's not included + assert set(metadata.keys()) == {'openid_relying_party'} + + assert set(metadata["openid_relying_party"].keys()) == {'application_type', + 'client_id', + 'client_id_issued_at', + 'client_registration_types', + 'client_secret', + 'client_secret_expires_at', + 'default_max_age', + 'grant_types', + 'id_token_signed_response_alg', + 'jwks', + 'redirect_uris', + 'request_object_signing_alg', + 'response_modes', + 'response_types', + 'subject_type', + 'token_endpoint_auth_method', + 'token_endpoint_auth_signing_alg', + 'userinfo_signed_response_alg'} + + self.registration_service.update_service_context(response) + # There is a client secret + assert self.rp["openid_relying_party"].context.claims.get_usage("client_secret") + _keys = self.rp["openid_relying_party"].context.keyjar.get_signing_key(key_type="oct") + assert len(_keys) == 2 \ No newline at end of file diff --git a/tests/test_12_explicit_registration_oauth.py b/tests/test_12_explicit_registration_oauth.py index 64ed21b8..c6c8dacf 100644 --- a/tests/test_12_explicit_registration_oauth.py +++ b/tests/test_12_explicit_registration_oauth.py @@ -1,13 +1,13 @@ import os -from cryptojwt.jws.jws import factory -from idpyoidc.client.defaults import DEFAULT_KEY_DEFS import pytest import responses +from cryptojwt.jws.jws import factory +from idpyoidc.client.defaults import DEFAULT_KEY_DEFS from fedservice.defaults import DEFAULT_OAUTH2_FED_SERVICES -from fedservice.defaults import OAUTH2_FED_ENDPOINTS from fedservice.defaults import federation_services +from fedservice.defaults import OAUTH2_FED_ENDPOINTS from fedservice.entity.function import get_verified_trust_chains from . import create_trust_chain_messages from .build_federation import build_federation @@ -179,14 +179,18 @@ def test_parse_registration_response(self): adding_headers={"Content-Type": "application/entity-statement+jwt"}, status=200) - claims = self.registration_service.parse_response(resp["response_msg"], - request=_info["body"]) - - assert set(claims.keys()) == {'oauth_client','federation_entity'} - - assert set(claims["oauth_client"].keys()) == {'client_id', - 'client_id_issued_at', - 'client_secret', - 'client_secret_expires_at', - 'response_types', - 'token_endpoint_auth_method'} + response = self.registration_service.parse_response(resp["response_msg"], + request=_info["body"]) + + metadata = response["metadata"] + # The response doesn't touch the federation_entity metadata, therefor it's not included + assert set(metadata.keys()) == {'oauth_client'} + + assert set(metadata["oauth_client"].keys()) == {'client_id', + 'client_id_issued_at', + 'client_secret', + 'client_secret_expires_at', + 'jwks', + 'redirect_uris', + 'response_types', + 'token_endpoint_auth_method'} diff --git a/tests/test_60_federation_topologies.py b/tests/test_60_federation_topologies.py new file mode 100644 index 00000000..d661179a --- /dev/null +++ b/tests/test_60_federation_topologies.py @@ -0,0 +1,103 @@ +import pytest +import responses +from cryptojwt.jws.jws import factory + +from fedservice.entity.function import collect_trust_chains +from fedservice.entity.function import verify_trust_chains +from tests import create_trust_chain_messages +from tests.build_federation import build_federation + +TA1_ID = "https://ta.example.org" +TA2_ID = "https://2nd.ta.example.org" +LEAF_ID = "https://rp.example.org" +INTERMEDIATE_ID = "https://intermediate.example.org" + +FEDERATION_CONFIG = { + TA1_ID: { + "entity_type": "trust_anchor", + "subordinates": [TA2_ID], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "endpoints": ['entity_configuration', 'list', 'fetch', 'resolve'], + } + }, + TA2_ID: { + "entity_type": "trust_anchor", + "subordinates": [INTERMEDIATE_ID], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "authority_hints": [TA1_ID], + "endpoints": ['entity_configuration', 'list', 'fetch', 'resolve'], + } + }, + INTERMEDIATE_ID: { + "entity_type": "intermediate", + "trust_anchors": [TA2_ID, TA1_ID], + "subordinates": [LEAF_ID], + "kwargs": { + "authority_hints": [TA2_ID], + } + }, + LEAF_ID: { + "entity_type": "openid_relying_party", + "trust_anchors": [TA1_ID, TA2_ID], + "kwargs": { + "authority_hints": [INTERMEDIATE_ID] + } + } +} + +# Topology +# +# TA1 +# | +# TA2 +# | +# INTERMEDIATE +# | +# LEAF +# + +class TestServer(): + + @pytest.fixture(autouse=True) + def create_federation(self): + self.federation_entity = build_federation(FEDERATION_CONFIG) + self.ta1 = self.federation_entity[TA1_ID] + self.ta2 = self.federation_entity[TA2_ID] + self.leaf = self.federation_entity[LEAF_ID] + self.intermediate = self.federation_entity[INTERMEDIATE_ID] + + # Slightly more complex chain setup leaf->intermediate->trust anchor 2->trust anchor 1 + + def test_sequence_of_trust_anchors(self): + _federation_entity = self.leaf + + _msgs = create_trust_chain_messages(self.leaf, self.intermediate, self.ta2, self.ta1) + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/json"}, status=200) + + _chains, _entity_conf = collect_trust_chains(_federation_entity, self.leaf.entity_id) + + _jws = factory(_entity_conf) + _unver_entity_conf = _jws.jwt.payload() + assert _unver_entity_conf['iss'] == self.leaf.entity_id + assert _unver_entity_conf['sub'] == self.leaf.entity_id + + assert len(_chains) == 1 + assert len(_chains[0]) == 3 + + # Leaf trusts both trust anchors + _trust_chains = verify_trust_chains(_federation_entity, _chains, _entity_conf) + assert len(_trust_chains) == 2 diff --git a/tests/test_61_federation_topologies.py b/tests/test_61_federation_topologies.py new file mode 100644 index 00000000..264eb903 --- /dev/null +++ b/tests/test_61_federation_topologies.py @@ -0,0 +1,111 @@ +import pytest +import responses +from cryptojwt.jws.jws import factory + +from fedservice.entity.function import collect_trust_chains +from fedservice.entity.function import verify_trust_chains +from tests import create_trust_chain_messages +from tests.build_federation import build_federation + +TA1_ID = "https://ta.example.org" +TA2_ID = "https://2nd.ta.example.org" +LEAF_ID = "https://rp.example.org" +INTERMEDIATE_ID = "https://intermediate.example.org" + +FEDERATION_CONFIG = { + TA1_ID: { + "entity_type": "trust_anchor", + "subordinates": [INTERMEDIATE_ID], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "endpoints": ['entity_configuration', 'list', 'fetch', 'resolve'], + } + }, + TA2_ID: { + "entity_type": "trust_anchor", + "subordinates": [INTERMEDIATE_ID], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "endpoints": ['entity_configuration', 'list', 'fetch', 'resolve'], + } + }, + INTERMEDIATE_ID: { + "entity_type": "intermediate", + "trust_anchors": [TA2_ID, TA1_ID], + "subordinates": [LEAF_ID], + "kwargs": { + "authority_hints": [TA2_ID, TA1_ID], + } + }, + LEAF_ID: { + "entity_type": "openid_relying_party", + "trust_anchors": [TA1_ID, TA2_ID], + "kwargs": { + "authority_hints": [INTERMEDIATE_ID] + } + } +} + +# Topology +# +# TA1 TA2 +# | | +# +-- INTERMEDIATE --+ +# | +# LEAF +# + + +class TestServer(): + + @pytest.fixture(autouse=True) + def create_federation(self): + self.federation_entity = build_federation(FEDERATION_CONFIG) + self.ta1 = self.federation_entity[TA1_ID] + self.ta2 = self.federation_entity[TA2_ID] + self.leaf = self.federation_entity[LEAF_ID] + self.intermediate = self.federation_entity[INTERMEDIATE_ID] + + def test_multiple_trust_anchors(self): + _federation_entity = self.leaf + + _msgs = create_trust_chain_messages(self.leaf, self.intermediate, self.ta1) + _msgs.update(create_trust_chain_messages(self.intermediate, self.ta2)) + + assert len(_msgs) + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/json"}, status=200) + + _chains, _entity_conf = collect_trust_chains(_federation_entity, self.leaf.entity_id) + + _jws = factory(_entity_conf) + _unver_entity_conf = _jws.jwt.payload() + assert _unver_entity_conf['iss'] == self.leaf.entity_id + assert _unver_entity_conf['sub'] == self.leaf.entity_id + + assert len(_chains) == 2 + assert len(_chains[0]) == 2 + assert len(_chains[1]) == 2 + + # Leaf trusts both trust anchors + _trust_chains = verify_trust_chains(_federation_entity, _chains, _entity_conf) + assert len(_trust_chains) == 2 + assert _trust_chains[0].iss_path == ['https://rp.example.org', + 'https://intermediate.example.org', + 'https://2nd.ta.example.org'] + assert _trust_chains[1].iss_path == ['https://rp.example.org', + 'https://intermediate.example.org', + 'https://ta.example.org'] + + diff --git a/tests/test_62_federation_topologies.py b/tests/test_62_federation_topologies.py new file mode 100644 index 00000000..06bd4350 --- /dev/null +++ b/tests/test_62_federation_topologies.py @@ -0,0 +1,118 @@ +import pytest +import responses +from cryptojwt.jws.jws import factory + +from fedservice.entity.function import collect_trust_chains +from fedservice.entity.function import verify_trust_chains +from tests import create_trust_chain_messages +from tests.build_federation import build_federation + +TA1_ID = "https://ta.example.org" +LEAF_ID = "https://rp.example.org" +INTERMEDIATE_ID = "https://intermediate.example.org" +INTERMEDIATE_ID_2 = "https://intermediate2.example.org" + +FEDERATION_CONFIG = { + TA1_ID: { + "entity_type": "trust_anchor", + "subordinates": [INTERMEDIATE_ID, INTERMEDIATE_ID_2], + "kwargs": { + "preference": { + "organization_name": "The example federation operator", + "homepage_uri": "https://ta.example.org", + "contacts": "operations@ta.example.org" + }, + "endpoints": ['entity_configuration', 'list', 'fetch', 'resolve'], + } + }, + INTERMEDIATE_ID: { + "entity_type": "intermediate", + "trust_anchors": [TA1_ID], + "subordinates": [LEAF_ID], + "kwargs": { + "authority_hints": [TA1_ID], + } + }, + INTERMEDIATE_ID_2: { + "entity_type": "intermediate", + "trust_anchors": [TA1_ID], + "subordinates": [LEAF_ID], + "kwargs": { + "authority_hints": [TA1_ID], + } + }, + LEAF_ID: { + "entity_type": "openid_relying_party", + "trust_anchors": [TA1_ID], + "kwargs": { + "authority_hints": [INTERMEDIATE_ID, INTERMEDIATE_ID_2] + } + } +} + +# Topology +# +# +# TA1 +# | +# +------ + -----+ +# | | +# INTERMEDIATE INTERMEDIATE_2 +# | | +# +----- + ------+ +# | +# LEAF +# + +class TestServer(): + + @pytest.fixture(autouse=True) + def create_federation(self): + self.federation_entity = build_federation(FEDERATION_CONFIG) + self.ta1 = self.federation_entity[TA1_ID] + self.leaf = self.federation_entity[LEAF_ID] + self.intermediate = self.federation_entity[INTERMEDIATE_ID] + self.intermediate_2 = self.federation_entity[INTERMEDIATE_ID_2] + + def test_multiple_trust_anchors(self): + _federation_entity = self.leaf + + _msgs = create_trust_chain_messages(self.leaf, self.intermediate, self.ta1) + # Fetch normally isn't created with a query part, so I have to do it here + _fetch = _msgs["https://ta.example.org/fetch"] + _msgs["https://ta.example.org/fetch?sub=https%3A%2F%2Fintermediate.example.org"] = _fetch + del _msgs["https://ta.example.org/fetch"] + + _msgs.update(create_trust_chain_messages(self.leaf, self.intermediate_2, self.ta1)) + # and again add query part + _fetch = _msgs["https://ta.example.org/fetch"] + _msgs["https://ta.example.org/fetch?sub=https%3A%2F%2Fintermediate2.example.org"] = _fetch + del _msgs["https://ta.example.org/fetch"] + + assert len(_msgs) == 8 + + with responses.RequestsMock() as rsps: + for _url, _jwks in _msgs.items(): + rsps.add("GET", _url, body=_jwks, + adding_headers={"Content-Type": "application/json"}, status=200) + + _chains, _entity_conf = collect_trust_chains(_federation_entity, self.leaf.entity_id) + + _jws = factory(_entity_conf) + _unver_entity_conf = _jws.jwt.payload() + assert _unver_entity_conf['iss'] == self.leaf.entity_id + assert _unver_entity_conf['sub'] == self.leaf.entity_id + + assert len(_chains) == 2 + assert len(_chains[0]) == 2 + assert len(_chains[1]) == 2 + + # Two paths from leaf to TA. Through different intermediates + _trust_chains = verify_trust_chains(_federation_entity, _chains, _entity_conf) + assert len(_trust_chains) == 2 + assert _trust_chains[0].iss_path == ['https://rp.example.org', + 'https://intermediate.example.org', + 'https://ta.example.org'] + assert _trust_chains[1].iss_path == ['https://rp.example.org', + 'https://intermediate2.example.org', + 'https://ta.example.org'] From 286d3a7431e7cd4f1a65a77f6b5c779a411d8525 Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 12 May 2025 14:14:35 +0200 Subject: [PATCH 12/43] Worked on explicit client registration. --- tests/test_02_metadata_oauth2.py | 9 +++++++-- tests/test_09_parse_request_response.py | 3 ++- tests/test_12_explicit_registration_oauth.py | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/test_02_metadata_oauth2.py b/tests/test_02_metadata_oauth2.py index 0d813bed..34d7e600 100644 --- a/tests/test_02_metadata_oauth2.py +++ b/tests/test_02_metadata_oauth2.py @@ -36,6 +36,7 @@ def test_supported(self): 'client_uri', 'client_id', 'client_secret', + 'client_registration_types', 'contacts', 'grant_types', 'grant_types_supported', @@ -88,6 +89,7 @@ def test_setup(self): 'client_uri', 'client_id', 'client_secret', + 'client_registration_types', 'contacts', 'grant_types', 'jwks', @@ -109,7 +111,8 @@ def test_setup(self): ) # These are the claims that has default values. A default value should not be an empty list. - assert set(claims.prefer.keys()) == {'grant_types_supported', + assert set(claims.prefer.keys()) == {'client_registration_types', + 'grant_types_supported', 'response_types_supported', 'token_endpoint_auth_methods_supported'} @@ -169,7 +172,8 @@ def test_metadata(self): ) # These are the claims that the client has default values for after comparing with what the AS supports - assert set(claims.prefer.keys()) == {'grant_types_supported', + assert set(claims.prefer.keys()) == {'client_registration_types', + 'grant_types_supported', 'response_types_supported', 'token_endpoint_auth_methods_supported'} @@ -193,6 +197,7 @@ def test_preference(self): reg_req = claims.create_registration_request() assert set(reg_req.keys()) == {'client_name', + 'client_registration_types', 'grant_types', 'example_extension_parameter', 'policy_uri', diff --git a/tests/test_09_parse_request_response.py b/tests/test_09_parse_request_response.py index 63571bbc..c9f3d581 100644 --- a/tests/test_09_parse_request_response.py +++ b/tests/test_09_parse_request_response.py @@ -1,4 +1,5 @@ import pytest +from cryptojwt import BadSyntax from idpyoidc.client.defaults import DEFAULT_OIDC_SERVICES from idpyoidc.message.oauth2 import ResponseMessage @@ -100,7 +101,7 @@ def test_parse_error(self): } ) - with pytest.raises(ValueError): + with pytest.raises(BadSyntax): self.rp.parse_request_response(self.rp.get_service('registration'), _resp) def test_redirect(self): diff --git a/tests/test_12_explicit_registration_oauth.py b/tests/test_12_explicit_registration_oauth.py index a02d69f8..3d78ab38 100644 --- a/tests/test_12_explicit_registration_oauth.py +++ b/tests/test_12_explicit_registration_oauth.py @@ -157,7 +157,7 @@ def test_parse_registration_response(self): # Collect trust chain for RP->TA _msgs = create_trust_chain_messages(self.rp, self.ta) - del _msgs['https://rp.example.org/.well-known/openid-federation'] + # del _msgs['https://rp.example.org/.well-known/openid-federation'] with responses.RequestsMock() as rsps: for _url, _jwks in _msgs.items(): From f6a0f06b1351c0a067955420f21c02a5d4d7dcc1 Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 12 May 2025 14:15:40 +0200 Subject: [PATCH 13/43] Bumped version --- src/fedservice/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fedservice/__init__.py b/src/fedservice/__init__.py index a9f7c316..c494584f 100644 --- a/src/fedservice/__init__.py +++ b/src/fedservice/__init__.py @@ -1,5 +1,5 @@ __author__ = 'Roland Hedberg' -__version__ = '5.2.0' +__version__ = '5.3.0' from typing import Optional From 6ca3a55dc03ed7a1ebafe601f871177f4dd807f5 Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 12 May 2025 14:43:16 +0200 Subject: [PATCH 14/43] Change in parameter name. --- example/test_config.py | 1 + src/fedservice/appclient/oauth2/registration.py | 12 ++++++------ src/fedservice/appclient/oidc/registration.py | 13 ++++++------- src/fedservice/appserver/oauth2/authorization.py | 2 +- .../appserver/oauth2/pushed_authorization.py | 2 +- src/fedservice/appserver/oauth2/registration.py | 2 +- src/fedservice/appserver/oidc/authorization.py | 2 +- src/fedservice/appserver/oidc/registration.py | 2 +- src/fedservice/message.py | 2 +- tests/test_10_explicit_registration_oidc.py | 3 +-- tests/x_test_12_oidc_registration.py | 2 +- unused/server_metadata_verification.py | 12 ++++++------ 12 files changed, 27 insertions(+), 28 deletions(-) diff --git a/example/test_config.py b/example/test_config.py index 6910b627..5da5f966 100755 --- a/example/test_config.py +++ b/example/test_config.py @@ -8,6 +8,7 @@ from fedservice.utils import make_federation_combo subdir = sys.argv[1] + config_file = sys.argv[2] _cnf = load_values_from_file(load_config_file(f"{subdir}/{config_file}")) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index fe591e5a..a01f0214 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -119,7 +119,7 @@ def parse_response(self, info, sformat="", state="", **kwargs): return resp def _get_trust_anchor_id(self, entity_statement): - return entity_statement.get('trust_anchor_id') + return entity_statement.get('trust_anchor') def parse_federation_registration_response(self, resp, **kwargs): """ @@ -137,8 +137,9 @@ def parse_federation_registration_response(self, resp, **kwargs): payload = _jwt.unpack(resp) # Do I trust the TA the OP chose ? - logger.debug(f"trust_anchor_id: {payload['trust_anchor_id']}") - if (payload['trust_anchor_id'] not in + _trust_anchor = payload.get("trust_anchor") + logger.debug(f"trust_anchor(_id): {_trust_anchor}") + if (payload['trust_anchor'] not in _federation_entity.function.trust_chain_collector.trust_anchors): raise ValueError("Trust anchor I don't trust") @@ -154,16 +155,15 @@ def parse_federation_registration_response(self, resp, **kwargs): else: # This is the trust chain from myself to the TA _entity_id = self.upstream_get('attribute', 'entity_id') - _trust_anchor = payload['trust_anchor_id'] _trust_chains = get_verified_trust_chains(self, entity_id=_entity_id, stop_at=_trust_anchor) # should only be one chain if len(_trust_chains) == 0: raise NoTrustedChains(_entity_id) - _tcs = [t for t in _trust_chains if t.anchor == payload['trust_anchor_id']] + _tcs = [t for t in _trust_chains if t.anchor == _trust_anchor] if len(_tcs) > 1: - raise SystemError(f"More then one chain ending in {payload['trust_anchor_id']}") + raise SystemError(f"More then one chain ending in {_trust_anchor}") else: _trust_chains = _tcs diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 0785fade..ad27fb1f 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -94,7 +94,7 @@ def parse_response(self, info, sformat="", state="", **kwargs): return resp def _get_trust_anchor_id(self, entity_statement): - return entity_statement.get('trust_anchor_id') + return entity_statement.get('trust_anchor') def parse_federation_registration_response(self, resp, **kwargs): """ @@ -112,9 +112,9 @@ def parse_federation_registration_response(self, resp, **kwargs): payload = _jwt.unpack(resp) # Do I trust the TA the OP chose ? - logger.debug(f"trust_anchor_id: {payload['trust_anchor_id']}") - if payload[ - 'trust_anchor_id'] not in _federation_entity.function.trust_chain_collector.trust_anchors: + _trust_anchor = payload['trust_anchor'] + logger.debug(f"trust_anchor_id: {_trust_anchor}") + if _trust_anchor not in _federation_entity.function.trust_chain_collector.trust_anchors: raise ValueError("Trust anchor I don't trust") # This is where I should decide to use the metadata verification service or do it @@ -129,7 +129,6 @@ def parse_federation_registration_response(self, resp, **kwargs): else: # This is the trust chain from the RP to the TA _entity_id = self.upstream_get('attribute', 'entity_id') - _trust_anchor = payload['trust_anchor_id'] _trust_chains = get_verified_trust_chains(self, entity_id=_entity_id, stop_at=_trust_anchor) # should only be one chain @@ -137,9 +136,9 @@ def parse_federation_registration_response(self, resp, **kwargs): if len(_trust_chains) == 0: raise NoTrustedChains(_entity_id) - _tcs = [t for t in _trust_chains if t.anchor == payload['trust_anchor_id']] + _tcs = [t for t in _trust_chains if t.anchor == _trust_anchor] if len(_tcs) > 1: - raise SystemError(f"More then one chain ending in {payload['trust_anchor_id']}") + raise SystemError(f"More then one chain ending in {_trust_anchor}") else: _trust_chains = _tcs diff --git a/src/fedservice/appserver/oauth2/authorization.py b/src/fedservice/appserver/oauth2/authorization.py index 1504c7ce..ebcb67fb 100644 --- a/src/fedservice/appserver/oauth2/authorization.py +++ b/src/fedservice/appserver/oauth2/authorization.py @@ -144,5 +144,5 @@ def extra_response_args(self, aresp, **kwargs): if _client_id: _tcs = _fe.trust_chain.get(_client_id, {}) if _tcs: - aresp['trust_anchor_id'] = _tcs[0].anchor + aresp['trust_anchor'] = _tcs[0].anchor return aresp diff --git a/src/fedservice/appserver/oauth2/pushed_authorization.py b/src/fedservice/appserver/oauth2/pushed_authorization.py index c35b1b56..7bad579d 100644 --- a/src/fedservice/appserver/oauth2/pushed_authorization.py +++ b/src/fedservice/appserver/oauth2/pushed_authorization.py @@ -119,5 +119,5 @@ def extra_response_args(self, aresp, **kwargs): if _client_id: _tcs = _fe.trust_chain.get(_client_id, {}) if _tcs: - aresp['trust_anchor_id'] = _tcs[0].anchor + aresp['trust_anchor'] = _tcs[0].anchor return aresp diff --git a/src/fedservice/appserver/oauth2/registration.py b/src/fedservice/appserver/oauth2/registration.py index 846c6fae..f991f8f4 100644 --- a/src/fedservice/appserver/oauth2/registration.py +++ b/src/fedservice/appserver/oauth2/registration.py @@ -87,7 +87,7 @@ def process_request(self, request=None, **kwargs): entity_statement = _context.create_entity_statement( _federation_entity.upstream_get('attribute', 'entity_id'), payload['iss'], - trust_anchor_id=trust_chain.anchor, + trust_anchor=trust_chain.anchor, metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], include_jwks=False diff --git a/src/fedservice/appserver/oidc/authorization.py b/src/fedservice/appserver/oidc/authorization.py index e4e1ae0e..e3299285 100644 --- a/src/fedservice/appserver/oidc/authorization.py +++ b/src/fedservice/appserver/oidc/authorization.py @@ -135,5 +135,5 @@ def extra_response_args(self, aresp, **kwargs): if _client_id: _tcs = _fe.trust_chain.get(_client_id, {}) if _tcs: - aresp['trust_anchor_id'] = _tcs[0].anchor + aresp['trust_anchor'] = _tcs[0].anchor return aresp diff --git a/src/fedservice/appserver/oidc/registration.py b/src/fedservice/appserver/oidc/registration.py index aca2fc25..bc2cd036 100644 --- a/src/fedservice/appserver/oidc/registration.py +++ b/src/fedservice/appserver/oidc/registration.py @@ -67,7 +67,7 @@ def process_request(self, request=None, **kwargs): entity_statement = _context.create_entity_statement( _federation_entity.upstream_get('attribute', 'entity_id'), payload['iss'], - trust_anchor_id=trust_chain.anchor, + trust_anchor=trust_chain.anchor, metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], authority_hints=_federation_entity.get_authority_hints(), diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 2ddebcd7..271ac1cb 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -511,7 +511,7 @@ class EntityStatement(JsonWebToken): 'trust_mark_owners': SINGLE_OPTIONAL_JSON, 'trust_mark_issuers': SINGLE_OPTIONAL_JSON, # - 'trust_anchor_id': SINGLE_OPTIONAL_STRING + 'trust_anchor': SINGLE_OPTIONAL_STRING }) def verify(self, **kwargs): diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index e30599b1..dd36ae13 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -220,8 +220,7 @@ def test_parse_registration_response(self): adding_headers={"Content-Type": "application/entity-statement+jwt"}, status=200) - response = self.registration_service.parse_response(resp["response_msg"], - request=_info["body"]) + response = self.registration_service.parse_response(resp["response_msg"], request=_info["body"]) metadata = response["metadata"] # The response doesn't touch the federation_entity metadata, therefor it's not included diff --git a/tests/x_test_12_oidc_registration.py b/tests/x_test_12_oidc_registration.py index 49e5d52c..5ddf3a17 100644 --- a/tests/x_test_12_oidc_registration.py +++ b/tests/x_test_12_oidc_registration.py @@ -118,7 +118,7 @@ def test_registration_verification(self): _payload = _jws.jwt.payload() assert _payload['iss'] == self.op.entity_id assert _payload['sub'] == self.rp.entity_id - assert _payload['trust_anchor_id'] == self.ta.entity_id + assert _payload['trust_anchor'] == self.ta.entity_id assert _payload['aud'] == self.rp.entity_id ########################################################################### diff --git a/unused/server_metadata_verification.py b/unused/server_metadata_verification.py index 6b41bc44..6aee5e64 100644 --- a/unused/server_metadata_verification.py +++ b/unused/server_metadata_verification.py @@ -34,23 +34,23 @@ def process_request(self, request=None, **kwargs): _federation_entity = get_federation_entity(self) payload = verify_self_signed_signature(request['registration_response']) # Do I trust the TA the OP chose ? - logger.debug(f"trust_anchor_id: {payload['trust_anchor_id']}") - if payload[ - 'trust_anchor_id'] not in _federation_entity.function.trust_chain_collector.trust_anchors: + _trust_anchor = payload['trust_anchor'] + logger.debug(f"trust_anchor_id: {_trust_anchor}") + if _trust_anchor not in _federation_entity.function.trust_chain_collector.trust_anchors: raise ValueError("Trust anchor I don't trust") # Verify that I can collect a trust chain from the subject to a trust anchor _chains, _ = collect_trust_chains(self.upstream_get('unit'), entity_id=payload['sub'], - stop_at=payload['trust_anchor_id']) + stop_at=_trust_anchor) _trust_chains = verify_trust_chains(_federation_entity, _chains, request['registration_response']) # should only be one chain if _trust_chains == []: raise SystemError( - f"Could not verify any trust chain ending in {payload['trust_anchor_id']}") + f"Could not verify any trust chain ending in {_trust_anchor}") if len(_trust_chains) != 1: - raise SystemError(f"More then one chain ending in {payload['trust_anchor_id']}") + raise SystemError(f"More then one chain ending in {_trust_anchor}") _trust_chains[0].verified_chain[-1]['metadata'] = payload['metadata'] _trust_chains = apply_policies(_federation_entity, _trust_chains) From 5c23d29d32509f6c2e914564ccaa3755e2465d01 Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 12 May 2025 15:31:43 +0200 Subject: [PATCH 15/43] Change in parameter name. --- src/fedservice/appclient/oauth2/registration.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index a01f0214..b0b357a1 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -139,8 +139,7 @@ def parse_federation_registration_response(self, resp, **kwargs): # Do I trust the TA the OP chose ? _trust_anchor = payload.get("trust_anchor") logger.debug(f"trust_anchor(_id): {_trust_anchor}") - if (payload['trust_anchor'] not in - _federation_entity.function.trust_chain_collector.trust_anchors): + if _trust_anchor not in _federation_entity.function.trust_chain_collector.trust_anchors: raise ValueError("Trust anchor I don't trust") # This is where I should decide to use the metadata verification service or do it From c26d094af985eac904d66515ca4f94a744d63fa7 Mon Sep 17 00:00:00 2001 From: roland Date: Fri, 16 May 2025 11:33:36 +0200 Subject: [PATCH 16/43] Effects of changes in idpy-oidc --- src/fedservice/appclient/oidc/registration.py | 3 ++- src/fedservice/entity/function/policy.py | 4 ++-- tests/test_10_explicit_registration_oidc.py | 13 ++++++++++--- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index ad27fb1f..c991f2a3 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -10,6 +10,7 @@ from idpyoidc.message.oidc import RegistrationRequest from idpyoidc.message.oidc import RegistrationResponse from idpyoidc.node import topmost_unit +from idpyoidc.transform import RP_URI_CLAIMS from fedservice.entity.function import apply_policies from fedservice.entity.function import get_verified_trust_chains @@ -188,7 +189,7 @@ def update_service_context(self, resp: Union[Message, dict], **kwargs): else: _context = item.get_context() - _context.map_preferred_to_registered(_guise_metadata) + _context.map_preferred_to_registered(_guise_metadata, uri_claims=RP_URI_CLAIMS) _client_id = _context.claims.get_usage("client_id") if _client_id: diff --git a/src/fedservice/entity/function/policy.py b/src/fedservice/entity/function/policy.py index f7273db3..931a802f 100644 --- a/src/fedservice/entity/function/policy.py +++ b/src/fedservice/entity/function/policy.py @@ -567,7 +567,7 @@ def apply_policy(self, metadata: dict, policy: dict, protocol: Optional[str] = " def _policy(self, trust_chain: TrustChain, entity_type: str): combined_policy = self.gather_policies(trust_chain.verified_chain[:-1], entity_type) - logger.debug("Combined policy: %s", combined_policy) + logger.debug(f"Combined policy for '{entity_type}': {combined_policy}") try: # This should be the entity configuration metadata = trust_chain.verified_chain[-1]['metadata'][entity_type] @@ -577,7 +577,7 @@ def _policy(self, trust_chain: TrustChain, entity_type: str): # apply the combined metadata policies on the metadata trust_chain.combined_policy[entity_type] = combined_policy _metadata = self.apply_policy(metadata, combined_policy) - logger.debug(f"After applied policy: {_metadata}") + logger.debug(f"After applied policy for '{entity_type}': {_metadata}") return _metadata def __call__(self, trust_chain: TrustChain, entity_type: Optional[str] = ''): diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index dd36ae13..81673c20 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -48,7 +48,9 @@ "preference": { "organization_name": "The example federation operator", "homepage_uri": "https://ta.example.org", - "contacts": "operations@ta.example.org" + "contacts": "operations@ta.example.org", + "scopes_supported": ["openid", "profile"], + "response_types_supported": ['id_token', 'code', 'code id_token'] }, "endpoints": ["entity_configuration", "list", "fetch", "resolve"], } @@ -70,7 +72,8 @@ "grant_types": ["authorization_code", "implicit", "refresh_token"], "id_token_signed_response_alg": "ES256", "token_endpoint_auth_method": "client_secret_basic", - "token_endpoint_auth_signing_alg": "ES256" + "token_endpoint_auth_signing_alg": "ES256", + "scopes_supported": ["openid", "profile"] } } } @@ -245,8 +248,12 @@ def test_parse_registration_response(self): 'token_endpoint_auth_signing_alg', 'userinfo_signed_response_alg'} + response["metadata"]["openid_relying_party"]["scope"] = ["openid", "profile"] + self.registration_service.update_service_context(response) # There is a client secret assert self.rp["openid_relying_party"].context.claims.get_usage("client_secret") _keys = self.rp["openid_relying_party"].context.keyjar.get_signing_key(key_type="oct") - assert len(_keys) == 2 \ No newline at end of file + assert len(_keys) == 2 + + assert self.rp["openid_relying_party"].context.claims.get_usage("scope") == ["openid", "profile"] \ No newline at end of file From d241e4c618f21a54c3b5d84de2eab910a3c597f1 Mon Sep 17 00:00:00 2001 From: roland Date: Fri, 16 May 2025 12:08:32 +0200 Subject: [PATCH 17/43] Clean up before mapping. 'scope' is not part of an OIDC RP's metadata but is for a OAUTH2 client. --- src/fedservice/appclient/oauth2/registration.py | 6 +++++- src/fedservice/appclient/oidc/registration.py | 5 ++++- tests/test_10_explicit_registration_oidc.py | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index b0b357a1..6de8f560 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -9,6 +9,7 @@ from idpyoidc.message.oauth2 import OauthClientMetadata from idpyoidc.message.oauth2 import ResponseMessage from idpyoidc.node import topmost_unit +from idpyoidc.transform import CLIENT_URI_CLAIMS from fedservice.entity.function import apply_policies from fedservice.entity.function import get_verified_trust_chains @@ -209,7 +210,10 @@ def update_service_context(self, resp, **kwargs): _client = _behaviour_args.get("client") if _client: _context = _client.context - _context.map_preferred_to_registered(_guise_metadata) + _md = self.response_cls(**_guise_metadata) + _md.verify() + _md.weed() + _context.map_preferred_to_registered(_md, uri_claims=CLIENT_URI_CLAIMS) for arg in ["client_id", "client_secret"]: _val = _context.claims.get_usage(arg) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index c991f2a3..f74ca21c 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -189,7 +189,10 @@ def update_service_context(self, resp: Union[Message, dict], **kwargs): else: _context = item.get_context() - _context.map_preferred_to_registered(_guise_metadata, uri_claims=RP_URI_CLAIMS) + _md = self.response_cls(**_guise_metadata) + _md.verify() + _md.weed() + _context.map_preferred_to_registered(_md, uri_claims=RP_URI_CLAIMS) _client_id = _context.claims.get_usage("client_id") if _client_id: diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index 81673c20..6ab6a3ac 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -248,7 +248,7 @@ def test_parse_registration_response(self): 'token_endpoint_auth_signing_alg', 'userinfo_signed_response_alg'} - response["metadata"]["openid_relying_party"]["scope"] = ["openid", "profile"] + response["metadata"]["openid_relying_party"]["scope"] = "openid profile" self.registration_service.update_service_context(response) # There is a client secret From d35f93982f010194fc61b2b70db88d0aafd42223 Mon Sep 17 00:00:00 2001 From: roland Date: Fri, 23 May 2025 09:16:38 +0200 Subject: [PATCH 18/43] Set default client_registration_types. Add logging. --- .../relying_party_explicit/conf.json | 2 +- src/fedservice/appclient/__init__.py | 8 +++++ .../appclient/oidc/authorization.py | 6 +++- tests/test_10_explicit_registration_oidc.py | 31 ++++++++++++++++--- 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/edu_federation/relying_party_explicit/conf.json b/edu_federation/relying_party_explicit/conf.json index d283e448..d8cf398b 100644 --- a/edu_federation/relying_party_explicit/conf.json +++ b/edu_federation/relying_party_explicit/conf.json @@ -79,7 +79,7 @@ "services": [ "entity_configuration", "entity_statement", - "oauth_registration", + "oidc_registration", "list" ], "entity_type": { diff --git a/src/fedservice/appclient/__init__.py b/src/fedservice/appclient/__init__.py index ee9d2f70..6262593d 100644 --- a/src/fedservice/appclient/__init__.py +++ b/src/fedservice/appclient/__init__.py @@ -110,6 +110,14 @@ def __init__( if "add_ons" in config: do_add_ons(config["add_ons"], self._service) + # What's the default + registration_types = config["preference"].get("client_registration_types", ["automatic"]) + if "automatic" not in registration_types: + authz_service = self._service.get("authorization") + # Is it safe to assume it's the last item ? + # authz_service.pre_construct.pop() + authz_service.pre_construct.remove(authz_service._automatic_registration) + def setup_client_authn_methods(self, config): if config and "client_authn_methods" in config: _methods = config.get("client_authn_methods") diff --git a/src/fedservice/appclient/oidc/authorization.py b/src/fedservice/appclient/oidc/authorization.py index e8160486..4d8445c6 100644 --- a/src/fedservice/appclient/oidc/authorization.py +++ b/src/fedservice/appclient/oidc/authorization.py @@ -1,7 +1,10 @@ +import logging + from idpyoidc.client.exception import OtherError from idpyoidc.client.oidc import authorization from idpyoidc.exception import UnSupported +logger = logging.getLogger(__name__) class Authorization(authorization.Authorization): @@ -42,7 +45,8 @@ def _automatic_registration(self, request_args, post_args=None, **kwargs): _request_endpoints = _context.config.conf.get('authorization_request_endpoints') _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', - ['openid_provider', 'oauth_authorization_server']) + ['openid_provider', 'oauth_authorization_server']) + # what if request_param is already set ?? # What if request_param in not in client_auth ?? if _auth_meth_supported: diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index 6ab6a3ac..e1ed1433 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -5,6 +5,7 @@ from cryptojwt.jws.jws import factory from idpyoidc.client.defaults import DEFAULT_KEY_DEFS from idpyoidc.client.defaults import DEFAULT_OIDC_SERVICES +from idpyoidc.message.oidc import AuthorizationRequest from fedservice.defaults import DEFAULT_OIDC_FED_SERVICES from fedservice.entity.function import get_verified_trust_chains @@ -66,15 +67,15 @@ "entity_type_config": { "client_id": RP_ID, "client_secret": "a longesh password", - "redirect_uris": ["https://example.com/cli/authz_cb"], "keys": {"key_defs": DEFAULT_KEY_DEFS}, "preference": { "grant_types": ["authorization_code", "implicit", "refresh_token"], "id_token_signed_response_alg": "ES256", "token_endpoint_auth_method": "client_secret_basic", "token_endpoint_auth_signing_alg": "ES256", - "scopes_supported": ["openid", "profile"] - } + "scopes_supported": ["openid", "profile"], + "client_registration_types": ["explicit"] + }, } } }, @@ -109,6 +110,13 @@ def fed_setup(self): self.rp = federation[RP_ID] self.op = federation[OP_ID] + _context = self.rp["openid_relying_party"].context + _context.issuer = self.op.entity_id + _response_types = _context.get_preference( + "response_types_supported", _context.supports().get("response_types_supported", []) + ) + _context.construct_uris(_response_types) + self.entity_config_service = self.rp["federation_entity"].get_service( "entity_configuration") self.entity_config_service.upstream_get("context").issuer = OP_ID @@ -223,7 +231,7 @@ def test_parse_registration_response(self): adding_headers={"Content-Type": "application/entity-statement+jwt"}, status=200) - response = self.registration_service.parse_response(resp["response_msg"], request=_info["body"]) + response = self.registration_service.parse_response(resp["response_msg"], request=_info["body"]) metadata = response["metadata"] # The response doesn't touch the federation_entity metadata, therefor it's not included @@ -256,4 +264,17 @@ def test_parse_registration_response(self): _keys = self.rp["openid_relying_party"].context.keyjar.get_signing_key(key_type="oct") assert len(_keys) == 2 - assert self.rp["openid_relying_party"].context.claims.get_usage("scope") == ["openid", "profile"] \ No newline at end of file + assert self.rp["openid_relying_party"].context.claims.get_usage("scope") == ["openid", "profile"] + + req_args = { + "state": "ABCDE", + "nonce": "nonce", + } + + self.rp["openid_relying_party"].get_context().cstate.set("ABCDE", {"iss": "issuer"}) + + msg = self.rp["openid_relying_party"].get_service("authorization").construct(request_args=req_args) + assert isinstance(msg, AuthorizationRequest) + _jws = factory(jws) + reg_uris = _jws.jwt.payload()["metadata"]["openid_relying_party"]["redirect_uris"] + assert msg["redirect_uri"] in reg_uris From 18fcc6accfe8800c8fb7ccc4feb376caefacbd27 Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 26 May 2025 13:29:22 +0200 Subject: [PATCH 19/43] Remove functionality if need be. --- edu_federation/relying_party_explicit/conf.json | 2 +- edu_federation/trust_anchor/conf.json | 2 +- edu_federation/trust_mark_issuer/conf.json | 2 +- src/fedservice/appclient/__init__.py | 5 ++++- src/fedservice/appclient/oauth2/authorization.py | 1 + 5 files changed, 8 insertions(+), 4 deletions(-) diff --git a/edu_federation/relying_party_explicit/conf.json b/edu_federation/relying_party_explicit/conf.json index d8cf398b..ef3ea734 100644 --- a/edu_federation/relying_party_explicit/conf.json +++ b/edu_federation/relying_party_explicit/conf.json @@ -197,6 +197,6 @@ "port": 4010, "server_cert": "certs/cert.pem", "server_key": "certs/key.pem", - "domain": "127.0.0.1" + "domain": "0.0.0.0" } } diff --git a/edu_federation/trust_anchor/conf.json b/edu_federation/trust_anchor/conf.json index e4923287..29aa2734 100644 --- a/edu_federation/trust_anchor/conf.json +++ b/edu_federation/trust_anchor/conf.json @@ -85,7 +85,7 @@ "server_key": "certs/example.key", "cert_chain": null, "port": 7010, - "domain": "127.0.0.1", + "domain": "0.0.0.0", "debug": false } } diff --git a/edu_federation/trust_mark_issuer/conf.json b/edu_federation/trust_mark_issuer/conf.json index 19af8385..826c9381 100644 --- a/edu_federation/trust_mark_issuer/conf.json +++ b/edu_federation/trust_mark_issuer/conf.json @@ -125,7 +125,7 @@ "server_key": "certs/example.key", "cert_chain": null, "port": 6010, - "domain": "127.0.0.1", + "domain": "0.0.0.0", "debug": false } } diff --git a/src/fedservice/appclient/__init__.py b/src/fedservice/appclient/__init__.py index 6262593d..3def4961 100644 --- a/src/fedservice/appclient/__init__.py +++ b/src/fedservice/appclient/__init__.py @@ -116,7 +116,10 @@ def __init__( authz_service = self._service.get("authorization") # Is it safe to assume it's the last item ? # authz_service.pre_construct.pop() - authz_service.pre_construct.remove(authz_service._automatic_registration) + try: + authz_service.pre_construct.remove(authz_service._automatic_registration) + except AttributeError: + pass def setup_client_authn_methods(self, config): if config and "client_authn_methods" in config: diff --git a/src/fedservice/appclient/oauth2/authorization.py b/src/fedservice/appclient/oauth2/authorization.py index 2ee8ffb7..fca5294c 100644 --- a/src/fedservice/appclient/oauth2/authorization.py +++ b/src/fedservice/appclient/oauth2/authorization.py @@ -83,3 +83,4 @@ def create_request(self, request_args, **kwargs): return _args else: return request_args + From 6b5219a91f71522a431e6de76fc987fa093f8e5f Mon Sep 17 00:00:00 2001 From: roland Date: Tue, 27 May 2025 16:09:34 +0200 Subject: [PATCH 20/43] Fixed circular imports --- src/fedservice/__init__.py | 8 +++++ src/fedservice/entity/__init__.py | 33 +++++++++++++++---- src/fedservice/entity/function/__init__.py | 7 ---- .../entity/function/trust_mark_verifier.py | 3 +- src/fedservice/message.py | 1 - 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/src/fedservice/__init__.py b/src/fedservice/__init__.py index c494584f..fe7da6ca 100644 --- a/src/fedservice/__init__.py +++ b/src/fedservice/__init__.py @@ -3,6 +3,9 @@ from typing import Optional +from cryptojwt import as_unicode +from cryptojwt.jws.jws import factory + from fedservice.entity_statement.statement import chains2dict @@ -29,3 +32,8 @@ def get_trust_chain(federation_context, entity_id: str, trust_anchor: Optional[s else: return trust_info + +def get_payload(self_signed_statement): + _jws = as_unicode(self_signed_statement) + _jwt = factory(_jws) + return _jwt.jwt.payload() diff --git a/src/fedservice/entity/__init__.py b/src/fedservice/entity/__init__.py index 061944b7..cc244360 100644 --- a/src/fedservice/entity/__init__.py +++ b/src/fedservice/entity/__init__.py @@ -1,3 +1,5 @@ +__author__ = 'Roland Hedberg' + import logging from typing import Callable from typing import Optional @@ -5,26 +7,45 @@ from cryptojwt import KeyJar from cryptojwt.utils import importer +from idpyoidc.claims import Claims as ClaimsBase from idpyoidc.client.client_auth import client_auth_setup +from idpyoidc.key_import import import_jwks +from idpyoidc.node import Unit from idpyoidc.server.util import execute from idpyoidc.util import instantiate from requests import request from fedservice import message +from fedservice.entity.context import FederationContext from fedservice.entity.function import apply_policies from fedservice.entity.function import collect_trust_chains -from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.function import verify_trust_chains -__author__ = 'Roland Hedberg' +logger = logging.getLogger(__name__) -from fedservice.entity.context import FederationContext -from idpyoidc.node import Unit -from idpyoidc.key_import import import_jwks +class FederationEntityClaims(ClaimsBase): + _supports = { + 'organization_name': None, + 'contacts': None, + 'policy_uri': None, + 'logo_uri': None, + 'homepage_uri': None, + 'trust_mark_owners': None, + 'trust_mark_issuers': None + } -logger = logging.getLogger(__name__) + def metadata(self, supports): + _info = {} + for key in message.FederationEntity.c_param.keys(): + _val = self.get_preference(key, supports.get(key, None)) + if _val is not None: + _info[key] = _val + return _info + + def get_id(self, configuration: dict): + return '' class FederationEntity(Unit): diff --git a/src/fedservice/entity/function/__init__.py b/src/fedservice/entity/function/__init__.py index 4e3b016a..8f9f79d5 100644 --- a/src/fedservice/entity/function/__init__.py +++ b/src/fedservice/entity/function/__init__.py @@ -144,13 +144,6 @@ def apply_policies(unit, trust_chains): res.append(trust_chain) return res - -def get_payload(self_signed_statement): - _jws = as_unicode(self_signed_statement) - _jwt = factory(_jws) - return _jwt.jwt.payload() - - class Function(ImpExp): def __init__(self, upstream_get: Callable): diff --git a/src/fedservice/entity/function/trust_mark_verifier.py b/src/fedservice/entity/function/trust_mark_verifier.py index 7150389c..fd9f9558 100644 --- a/src/fedservice/entity/function/trust_mark_verifier.py +++ b/src/fedservice/entity/function/trust_mark_verifier.py @@ -5,6 +5,8 @@ from cryptojwt import KeyJar from cryptojwt.exception import Expired from cryptojwt.jws.jws import factory + +from fedservice import get_payload from fedservice.entity import FederationEntity from idpyoidc.key_import import import_jwks from idpyoidc.message import Message @@ -12,7 +14,6 @@ from fedservice import message from fedservice.entity import apply_policies from fedservice.entity.function import Function -from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.function import verify_signature from fedservice.entity.function.trust_anchor import get_verified_trust_anchor_statement diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 271ac1cb..a760ade0 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -33,7 +33,6 @@ from idpyoidc.message.oidc import SINGLE_OPTIONAL_BOOLEAN from idpyoidc.message.oidc import SINGLE_OPTIONAL_DICT -from fedservice.entity.function import get_payload from fedservice.exception import UnknownCriticalExtension from fedservice.exception import WrongSubject From c4c04fcb21f9ec5473458abae481f17676781699 Mon Sep 17 00:00:00 2001 From: roland Date: Tue, 27 May 2025 17:04:39 +0200 Subject: [PATCH 21/43] Logging --- edu_federation/relying_party_explicit/conf.json | 3 ++- src/fedservice/appclient/__init__.py | 10 ++++++---- src/fedservice/appserver/__init__.py | 9 ++------- src/fedservice/combo/__init__.py | 2 ++ src/fedservice/entity/__init__.py | 2 ++ src/fedservice/entity/client/__init__.py | 3 +++ src/fedservice/trust_mark_entity/entity.py | 5 +++++ 7 files changed, 22 insertions(+), 12 deletions(-) diff --git a/edu_federation/relying_party_explicit/conf.json b/edu_federation/relying_party_explicit/conf.json index ef3ea734..395bf980 100644 --- a/edu_federation/relying_party_explicit/conf.json +++ b/edu_federation/relying_party_explicit/conf.json @@ -197,6 +197,7 @@ "port": 4010, "server_cert": "certs/cert.pem", "server_key": "certs/key.pem", - "domain": "0.0.0.0" + "domain": "127.0.0.1", + "debug": true } } diff --git a/src/fedservice/appclient/__init__.py b/src/fedservice/appclient/__init__.py index 3def4961..8711f98b 100644 --- a/src/fedservice/appclient/__init__.py +++ b/src/fedservice/appclient/__init__.py @@ -111,8 +111,8 @@ def __init__( do_add_ons(config["add_ons"], self._service) # What's the default - registration_types = config["preference"].get("client_registration_types", ["automatic"]) - if "automatic" not in registration_types: + registration_types = config["preference"].get("client_registration_types", ["automatic"]) + if "automatic" not in registration_types: authz_service = self._service.get("authorization") # Is it safe to assume it's the last item ? # authz_service.pre_construct.pop() @@ -154,14 +154,16 @@ def get_client_id(self): return self.entity_id def get_metadata(self, entity_type="", *args): + logger.debug(f"{self.name}:get_metadata") if not entity_type: if self.client_type == "oauth2": entity_type = "oauth_client" elif self.client_type == "oidc": entity_type = "openid_relying_party" - return self.context.claims.get_client_metadata(entity_type=entity_type, - metadata_schema=self.metadata_class) + res = self.context.claims.get_client_metadata(entity_type=entity_type, + metadata_schema=self.metadata_class) + logger.debug(f"metadata:{entity_type} = {res}") def get_registration_metadata(self, entity_type="", *args): if not entity_type: diff --git a/src/fedservice/appserver/__init__.py b/src/fedservice/appserver/__init__.py index 30df939f..39bd80c0 100644 --- a/src/fedservice/appserver/__init__.py +++ b/src/fedservice/appserver/__init__.py @@ -159,6 +159,7 @@ def get_server(self, *args): return self def get_metadata(self, entity_type="", *args): + logger.debug(f"{self.name}:get_metadata") if not entity_type: entity_type = self.name _claims = self.get_context().claims @@ -169,13 +170,7 @@ def get_metadata(self, entity_type="", *args): if param in self.metadata_schema.c_param: metadata[param] = self.context.entity_id - # remove these from the metadata - # for item in ["jwks", "jwks_uri", "signed_jwks_uri"]: - # try: - # del metadata[item] - # except KeyError: - # pass - # collect endpoints + logger.debug(f"metadata:{entity_type} = {metadata}") return {entity_type: metadata} def pick_guise(self, entity_type: Optional[str] = "", *args): diff --git a/src/fedservice/combo/__init__.py b/src/fedservice/combo/__init__.py index 678bb0e6..c3cbc6b6 100644 --- a/src/fedservice/combo/__init__.py +++ b/src/fedservice/combo/__init__.py @@ -108,6 +108,7 @@ def _get_httpc_params(self, config): return config["federation_entity"].get("httpc_params") def get_metadata(self, client = None): + logger.debug(f"FederationCombo:get_metadata") res = {} for federation_type, item in self._part.items(): if isinstance(item, RPHandler): # Special treatment @@ -116,6 +117,7 @@ def get_metadata(self, client = None): res.update(_res) elif getattr(item, "get_metadata", None): res.update(item.get_metadata(entity_type=federation_type)) + logger.debug(f"metadata = {res}") return res def get_preferences(self): diff --git a/src/fedservice/entity/__init__.py b/src/fedservice/entity/__init__.py index cc244360..27ec390e 100644 --- a/src/fedservice/entity/__init__.py +++ b/src/fedservice/entity/__init__.py @@ -179,6 +179,7 @@ def registration_metadata(self, entity_type="federation_entity", *args): return {entity_type: metadata} def get_metadata(self, entity_type="federation_entity", *args): + logger.debug(f"{self.name}:get_metadata") _context = self.get_context() _claims = _context.claims @@ -186,6 +187,7 @@ def get_metadata(self, entity_type="federation_entity", *args): metadata = _claims.get_server_metadata(endpoints=self.get_all_endpoints(), metadata_schema=message.FederationEntity) + logger.debug(f"metadata:{entity_type} = {metadata}") return {entity_type: metadata} def get_preferences(self): diff --git a/src/fedservice/entity/client/__init__.py b/src/fedservice/entity/client/__init__.py index 7af28327..4e4cfb1e 100644 --- a/src/fedservice/entity/client/__init__.py +++ b/src/fedservice/entity/client/__init__.py @@ -132,6 +132,7 @@ def get_metadata_claim(self, claim, entity_type: Optional[List[str]] = ""): class FederationClientEntity(ClientUnit): + name = "federation_entity" def __init__( self, @@ -493,5 +494,7 @@ def parse_request_response(self, service, reqresp, response_body_type="", state= ) def get_metadata(self, *args): + logger.debug(f"{self.name}:get_metadata") metadata = self.context.claims.get_use() + logger.debug(f"metadata:{self.name} = {metadata}") return {self.name: metadata} diff --git a/src/fedservice/trust_mark_entity/entity.py b/src/fedservice/trust_mark_entity/entity.py index 8b53eb60..815309c5 100644 --- a/src/fedservice/trust_mark_entity/entity.py +++ b/src/fedservice/trust_mark_entity/entity.py @@ -1,3 +1,4 @@ +import logging from typing import Callable from typing import Optional @@ -15,6 +16,8 @@ from fedservice.trust_mark_entity.context import TrustMarkContext +logger = logging.getLogger(__name__) + def create_trust_mark(keyjar, entity_id, **kwargs): packer = JWT(key_jar=keyjar, iss=entity_id) return packer.pack(payload=kwargs) @@ -129,6 +132,7 @@ def list(self, trust_mark_id: str, sub: Optional[str] = "") -> list: return self.issued.list(trust_mark_id) def get_metadata(self): + logger.debug(f"{self.name}:get_metadata") # three endpoints md = {} for name, endp in self.endpoint.items(): @@ -139,6 +143,7 @@ def get_metadata(self): _val = getattr(endp, arg, None) if _val: md[f"{endp.name}_{txt}"] = _val + logger.debug(f"metadata:{self.name} = {md}") return {self.name: md} def get_context(self, *args): From f9c6ab266f0af220169d341e555baf196df5179c Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 28 May 2025 20:46:44 +0200 Subject: [PATCH 22/43] Logging --- src/fedservice/appclient/oidc/registration.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index f74ca21c..04df10b2 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -55,6 +55,7 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) :return: """ + logger.debug(f"Create Entity Configuration") _federation_entity = get_federation_entity(self) # _md = {_federation_context.entity_type: request_args.to_dict()} _root = _federation_entity.upstream_get('unit') From 3c6117e34b373fa17b738dc67374d48e332ed762 Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 28 May 2025 20:54:19 +0200 Subject: [PATCH 23/43] Logging --- src/fedservice/combo/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/fedservice/combo/__init__.py b/src/fedservice/combo/__init__.py index c3cbc6b6..925a1dbb 100644 --- a/src/fedservice/combo/__init__.py +++ b/src/fedservice/combo/__init__.py @@ -108,9 +108,10 @@ def _get_httpc_params(self, config): return config["federation_entity"].get("httpc_params") def get_metadata(self, client = None): - logger.debug(f"FederationCombo:get_metadata") + logger.debug(f"FederationCombo:get_metadata, client:{client}") res = {} for federation_type, item in self._part.items(): + logger.debug(f"federation_type:{federation_type}, item:{item}") if isinstance(item, RPHandler): # Special treatment if client: _res = client.get_metadata() From dff627a22d2e5f654280a68ffef2945aa8a81481 Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 29 May 2025 09:23:28 +0200 Subject: [PATCH 24/43] Need to know which client it is. --- src/fedservice/appclient/oidc/registration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 04df10b2..65876f0c 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -59,7 +59,7 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) _federation_entity = get_federation_entity(self) # _md = {_federation_context.entity_type: request_args.to_dict()} _root = _federation_entity.upstream_get('unit') - _md = _root.get_metadata() + _md = _root.get_metadata(client=kwargs.get("client")) _federation_keyjar = _federation_entity.get_attribute("keyjar") # _entity = self.upstream_get('unit') From 3f9c9b044e1d1172b91ef3bb1a6b7de41e00806f Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 29 May 2025 09:28:19 +0200 Subject: [PATCH 25/43] Have to return value --- src/fedservice/appclient/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/fedservice/appclient/__init__.py b/src/fedservice/appclient/__init__.py index 8711f98b..bfa54d74 100644 --- a/src/fedservice/appclient/__init__.py +++ b/src/fedservice/appclient/__init__.py @@ -164,6 +164,7 @@ def get_metadata(self, entity_type="", *args): res = self.context.claims.get_client_metadata(entity_type=entity_type, metadata_schema=self.metadata_class) logger.debug(f"metadata:{entity_type} = {res}") + return res def get_registration_metadata(self, entity_type="", *args): if not entity_type: From 006fda067cb4f0591c6f22df2d2e9630ffc15cac Mon Sep 17 00:00:00 2001 From: roland Date: Fri, 30 May 2025 09:46:01 +0200 Subject: [PATCH 26/43] Got explicit client registration working for OIDC. --- src/fedservice/appclient/__init__.py | 10 ++++++++-- src/fedservice/appclient/oauth2/authorization.py | 16 +++++++++------- src/fedservice/appclient/oidc/authorization.py | 3 ++- src/fedservice/appserver/oauth2/authorization.py | 2 +- src/fedservice/defaults.py | 4 +++- src/fedservice/entity/client/__init__.py | 6 ++---- src/fedservice/message.py | 1 + tests/test_13_automatic_registration_oauth.py | 2 +- tests/test_70_trust_marks.py | 1 - 9 files changed, 27 insertions(+), 18 deletions(-) diff --git a/src/fedservice/appclient/__init__.py b/src/fedservice/appclient/__init__.py index bfa54d74..03238166 100644 --- a/src/fedservice/appclient/__init__.py +++ b/src/fedservice/appclient/__init__.py @@ -27,6 +27,7 @@ from fedservice.defaults import COMBINED_DEFAULT_OAUTH2_SERVICES from fedservice.defaults import COMBINED_DEFAULT_OIDC_SERVICES +from fedservice.defaults import DEFAULT_REGISTRATION_TYPE from fedservice.message import OauthClientMetadata from fedservice.message import OIDCRPMetadata @@ -110,8 +111,13 @@ def __init__( if "add_ons" in config: do_add_ons(config["add_ons"], self._service) - # What's the default - registration_types = config["preference"].get("client_registration_types", ["automatic"]) + # What's the default ? explicit/automatic ? automatic for the time being. + _preference = config.get("preference") + if _preference: + registration_types = _preference.get("client_registration_types", [DEFAULT_REGISTRATION_TYPE]) + else: + registration_types = [DEFAULT_REGISTRATION_TYPE] + if "automatic" not in registration_types: authz_service = self._service.get("authorization") # Is it safe to assume it's the last item ? diff --git a/src/fedservice/appclient/oauth2/authorization.py b/src/fedservice/appclient/oauth2/authorization.py index fca5294c..dd1ad568 100644 --- a/src/fedservice/appclient/oauth2/authorization.py +++ b/src/fedservice/appclient/oauth2/authorization.py @@ -1,8 +1,12 @@ +import logging + from idpyoidc.client.exception import OtherError from idpyoidc.client.oauth2 import authorization from idpyoidc.client.oauth2.add_on.jar import construct_request_parameter from idpyoidc.exception import UnSupported +from idpyoidc.util import conf_get +logger = logging.getLogger(__name__) class Authorization(authorization.Authorization): @@ -38,9 +42,7 @@ def _automatic_registration(self, request_args, post_args=None, **kwargs): if post_args is None: post_args = {} - _request_endpoints = _context.config.get('authorization_request_endpoints') - if not _request_endpoints: - _request_endpoints = _context.config.conf.get('authorization_request_endpoints') + _request_endpoints = conf_get(_context.config, 'authorization_request_endpoints') # What does the server support if self.upstream_get('attribute', "client_type") == 'oidc': @@ -50,15 +52,15 @@ def _automatic_registration(self, request_args, post_args=None, **kwargs): else: raise KeyError("Unknown client_type") - _ams = _context.get_metadata_claim('request_authentication_methods_supported', [_entity_type]) + _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', [_entity_type]) # what if request_param is already set ?? # What if request_param in not in client_auth ?? - if _ams: + if _auth_meth_supported: for endpoint in _request_endpoints: - if endpoint in _ams: + if endpoint in _auth_meth_supported: _func = getattr(self, f'_use_{endpoint}') - post_args = _func(_context, post_args, _ams, _entity_type) + post_args = _func(_context, post_args, _auth_meth_supported, _entity_type) break else: # The OP does not support any authn methods # am I already registered ? diff --git a/src/fedservice/appclient/oidc/authorization.py b/src/fedservice/appclient/oidc/authorization.py index 4d8445c6..8d152e93 100644 --- a/src/fedservice/appclient/oidc/authorization.py +++ b/src/fedservice/appclient/oidc/authorization.py @@ -3,6 +3,7 @@ from idpyoidc.client.exception import OtherError from idpyoidc.client.oidc import authorization from idpyoidc.exception import UnSupported +from idpyoidc.util import conf_get logger = logging.getLogger(__name__) @@ -42,7 +43,7 @@ def _automatic_registration(self, request_args, post_args=None, **kwargs): _request_endpoints = _context.config.get('authorization_request_endpoints') if not _request_endpoints: - _request_endpoints = _context.config.conf.get('authorization_request_endpoints') + _request_endpoints = conf_get(_context.config, 'authorization_request_endpoints') _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', ['openid_provider', 'oauth_authorization_server']) diff --git a/src/fedservice/appserver/oauth2/authorization.py b/src/fedservice/appserver/oauth2/authorization.py index ebcb67fb..9652f1e1 100644 --- a/src/fedservice/appserver/oauth2/authorization.py +++ b/src/fedservice/appserver/oauth2/authorization.py @@ -4,12 +4,12 @@ from idpyoidc.message import Message -from fedservice.entity.function import get_payload from idpyoidc.message import oauth2 from idpyoidc.message.oauth2 import OauthClientMetadata from idpyoidc.node import topmost_unit from idpyoidc.server.oauth2 import authorization +from fedservice import get_payload from fedservice.appserver import import_client_keys from fedservice.entity.function import apply_policies from fedservice.entity.function import collect_trust_chains diff --git a/src/fedservice/defaults.py b/src/fedservice/defaults.py index 7f0e8420..109d9d35 100644 --- a/src/fedservice/defaults.py +++ b/src/fedservice/defaults.py @@ -222,4 +222,6 @@ def federation_functions(*apis): DEFAULT_FEDERATION_ENTITY_FUNCTIONS = federation_functions("trust_chain_collector", "verifier", "policy", "trust_mark_verifier") -DEFAULT_SIGNING_ALGORITHM = "RS256" \ No newline at end of file +DEFAULT_SIGNING_ALGORITHM = "RS256" + +DEFAULT_REGISTRATION_TYPE = "automatic" \ No newline at end of file diff --git a/src/fedservice/entity/client/__init__.py b/src/fedservice/entity/client/__init__.py index 4e4cfb1e..3628887a 100644 --- a/src/fedservice/entity/client/__init__.py +++ b/src/fedservice/entity/client/__init__.py @@ -23,6 +23,7 @@ from idpyoidc.key_import import import_jwks from idpyoidc.message import Message from idpyoidc.node import ClientUnit +from idpyoidc.util import conf_get from requests import request from fedservice.defaults import DEFAULT_FEDERATION_ENTITY_SERVICES @@ -281,10 +282,7 @@ def __init__( self.httpc = httpc or request - if isinstance(config, Configuration): - _add_ons = config.conf.get("add_ons") - else: - _add_ons = config.get("add_ons") + _add_ons = conf_get(config, "add_ons") if _add_ons: do_add_ons(_add_ons, self.service) diff --git a/src/fedservice/message.py b/src/fedservice/message.py index a760ade0..06386ef8 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -33,6 +33,7 @@ from idpyoidc.message.oidc import SINGLE_OPTIONAL_BOOLEAN from idpyoidc.message.oidc import SINGLE_OPTIONAL_DICT +from fedservice import get_payload from fedservice.exception import UnknownCriticalExtension from fedservice.exception import WrongSubject diff --git a/tests/test_13_automatic_registration_oauth.py b/tests/test_13_automatic_registration_oauth.py index 826f84e6..88f518fc 100644 --- a/tests/test_13_automatic_registration_oauth.py +++ b/tests/test_13_automatic_registration_oauth.py @@ -6,11 +6,11 @@ from idpyoidc.server.oidc.token import Token from idpyoidc.util import rndstr +from fedservice import get_payload from fedservice.defaults import COMBINED_DEFAULT_OAUTH2_SERVICES from fedservice.defaults import DEFAULT_OAUTH2_FED_SERVICES from fedservice.defaults import federation_endpoints from fedservice.defaults import federation_services -from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains from . import create_trust_chain_messages from . import CRYPT_CONFIG diff --git a/tests/test_70_trust_marks.py b/tests/test_70_trust_marks.py index 9b5dfdd5..f36fa80f 100644 --- a/tests/test_70_trust_marks.py +++ b/tests/test_70_trust_marks.py @@ -7,7 +7,6 @@ from idpyoidc.message import Message from fedservice.defaults import LEAF_ENDPOINTS -from fedservice.entity.function import get_payload from fedservice.entity.function import get_verified_trust_chains from fedservice.message import TrustMark from fedservice.utils import make_federation_entity From e3c0df1b4ee4764564d3babc941f9b77de3e058b Mon Sep 17 00:00:00 2001 From: roland Date: Mon, 2 Jun 2025 16:58:56 +0200 Subject: [PATCH 27/43] Refactor authorization services. --- .../appclient/oauth2/authorization.py | 157 ++++++++++-------- .../appclient/oidc/authorization.py | 63 +------ tests/test_10_explicit_registration_oidc.py | 2 + 3 files changed, 95 insertions(+), 127 deletions(-) diff --git a/src/fedservice/appclient/oauth2/authorization.py b/src/fedservice/appclient/oauth2/authorization.py index dd1ad568..76129898 100644 --- a/src/fedservice/appclient/oauth2/authorization.py +++ b/src/fedservice/appclient/oauth2/authorization.py @@ -8,81 +8,92 @@ logger = logging.getLogger(__name__) + +# The two variants of authorization +def use_authorization_endpoint(entity, context, post_args, ams, entity_type): + if 'pushed_authorization' in context.add_on: + # Turn off pushed auth + context.add_on['pushed_authorization']['apply'] = False + + if "request_object" in ams['authorization_endpoint']: + post_args['request_param'] = "request" + post_args['recv'] = context.get_metadata_claim("authorization_endpoint", [entity_type]) + post_args["with_jti"] = True + post_args["lifetime"] = entity.conf.get("request_object_expires_in", 300) + post_args['issuer'] = entity.upstream_get('attribute', 'entity_id') + else: + raise OtherError("Using request object in authentication not supported by OP") + + return post_args + + +def use_pushed_authorization_endpoint(entity, context, post_args, ams, entity_type): + if 'pushed_authorization' not in context.add_on: + raise UnSupported('Pushed Authorization not supported') + else: # Make it happen + context.add_on['pushed_authorization']['apply'] = True + + +def automatic_registration(request_args, service, post_args=None, **kwargs): + _context = service.upstream_get("context") + if post_args is None: + post_args = {} + + _request_endpoints = conf_get(_context.config, 'authorization_request_endpoints', + ["authorization_endpoint", "pushed_authorization_request_endpoint"] # default + ) + + # What does the server support + _client_type = service.upstream_get('attribute', "client_type") + if _client_type == 'oidc': + _entity_type = "openid_provider" + elif _client_type == 'oauth2': + _entity_type = "oauth_authorization_server" + else: + raise KeyError(f"Unknown client_type: {_client_type}") + + _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', [_entity_type]) + + # what if request_param is already set ?? + # What if request_param in not in client_auth ?? + if _auth_meth_supported: + for endpoint in _request_endpoints: + if endpoint in _auth_meth_supported: + _func = getattr(service, f'_use_{endpoint}') + post_args = _func(service, _context, post_args, _auth_meth_supported, _entity_type) + break + else: # The OP does not support any authn methods + # am I already registered ? + if not _context.registration_response: # Not registered + raise OtherError("Can not send an authorization request without being registered" + " and automatic registration not supported") + + client_id = request_args.get('client_id') + if not client_id: + request_args['client_id'] = service.upstream_get('attribute', 'entity_id') + + return request_args, post_args + + +def create_request(request_args, **kwargs): + request_arg = kwargs.get('request_param', "") + if request_arg == "request": + service = kwargs.get("service") + del kwargs["service"] + _args = {k: request_args[k] for k in service.msg_type().required_parameters() if k in request_args} + _req = construct_request_parameter(service, request_args, **kwargs) + _args["request"] = _req + return service.msg_type(**_args) + else: + return request_args + + class Authorization(authorization.Authorization): def __init__(self, upstream_get, conf=None): authorization.Authorization.__init__(self, upstream_get=upstream_get, conf=conf) - self.pre_construct.append(self._automatic_registration) - self.post_construct.append(self.create_request) - - def _use_authorization_endpoint(self, context, post_args, ams, entity_type): - if 'pushed_authorization' in context.add_on: - # Turn off pushed auth - context.add_on['pushed_authorization']['apply'] = False - - if "request_object" in ams['authorization_endpoint']: - post_args['request_param'] = "request" - post_args['recv'] = context.get_metadata_claim("authorization_endpoint", [entity_type]) - post_args["with_jti"] = True - post_args["lifetime"] = self.conf.get("request_object_expires_in", 300) - post_args['issuer'] = self.upstream_get('attribute', 'entity_id') - else: - raise OtherError("Using request object in authentication not supported by OP") - - return post_args - - def _use_pushed_authorization_endpoint(self, context, post_args, ams, entity_type): - if 'pushed_authorization' not in context.add_on: - raise UnSupported('Pushed Authorization not supported') - else: # Make it happen - context.add_on['pushed_authorization']['apply'] = True - - def _automatic_registration(self, request_args, post_args=None, **kwargs): - _context = self.upstream_get("context") - if post_args is None: - post_args = {} - - _request_endpoints = conf_get(_context.config, 'authorization_request_endpoints') - - # What does the server support - if self.upstream_get('attribute', "client_type") == 'oidc': - _entity_type = "openid_provider" - elif self.upstream_get('attribute', "client_type") == 'oauth2': - _entity_type = "oauth_authorization_server" - else: - raise KeyError("Unknown client_type") - - _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', [_entity_type]) - - # what if request_param is already set ?? - # What if request_param in not in client_auth ?? - if _auth_meth_supported: - for endpoint in _request_endpoints: - if endpoint in _auth_meth_supported: - _func = getattr(self, f'_use_{endpoint}') - post_args = _func(_context, post_args, _auth_meth_supported, _entity_type) - break - else: # The OP does not support any authn methods - # am I already registered ? - if not _context.registration_response: # Not registered - raise OtherError("Can not send an authorization request without being registered" - " and automatic registration not supported") - - client_id = request_args.get('client_id') - if not client_id: - request_args['client_id'] = self.upstream_get('attribute', 'entity_id') - - return request_args, post_args - - def create_request(self, request_args, **kwargs): - request_arg = kwargs.get('request_param', "") - if request_arg == "request": - service = kwargs.get("service") - del kwargs["service"] - _args = {k: request_args[k] for k in self.msg_type().required_parameters() if k in request_args} - _req = construct_request_parameter(service, request_args, **kwargs) - _args["request"] = _req - return _args - else: - return request_args + self.pre_construct.append(automatic_registration) + self.post_construct.append(create_request) + self._use_authorization_endpoint = use_authorization_endpoint + self._use_pushed_authorization_endpoint = use_pushed_authorization_endpoint \ No newline at end of file diff --git a/src/fedservice/appclient/oidc/authorization.py b/src/fedservice/appclient/oidc/authorization.py index 8d152e93..79f68f52 100644 --- a/src/fedservice/appclient/oidc/authorization.py +++ b/src/fedservice/appclient/oidc/authorization.py @@ -5,65 +5,20 @@ from idpyoidc.exception import UnSupported from idpyoidc.util import conf_get +from fedservice.appclient.oauth2.authorization import automatic_registration +from fedservice.appclient.oauth2.authorization import create_request +from fedservice.appclient.oauth2.authorization import use_authorization_endpoint +from fedservice.appclient.oauth2.authorization import use_pushed_authorization_endpoint + logger = logging.getLogger(__name__) class Authorization(authorization.Authorization): def __init__(self, upstream_get, conf=None): authorization.Authorization.__init__(self, upstream_get=upstream_get, conf=conf) - self.pre_construct.append(self._automatic_registration) - - def _use_authorization_endpoint(self, context, post_args, ams): - if 'pushed_authorization' in context.add_on: - # Turn off pushed auth - context.add_on['pushed_authorization']['apply'] = False - - if "request_object" in ams['authorization_endpoint']: - post_args['request_param'] = "request" - post_args['recv'] = context.get_metadata_claim("authorization_endpoint", - ['openid_provider', 'oauth_authorization_server']) - post_args["with_jti"] = True - post_args["lifetime"] = self.conf.get("request_object_expires_in", 300) - post_args['issuer'] = self.upstream_get('attribute', 'entity_id') - else: - raise OtherError("Using request object in authentication not supported by OP") - - return post_args - - def _use_pushed_authorization_endpoint(self, context, post_args, ams): - if 'pushed_authorization' not in context.add_on: - raise UnSupported('Pushed Authorization not supported') - else: # Make it happen - context.add_on['pushed_authorization']['apply'] = True - - def _automatic_registration(self, request_args, post_args=None, **kwargs): - _context = self.upstream_get("context") - if post_args is None: - post_args = {} - - _request_endpoints = _context.config.get('authorization_request_endpoints') - if not _request_endpoints: - _request_endpoints = conf_get(_context.config, 'authorization_request_endpoints') - - _auth_meth_supported = _context.get_metadata_claim('request_authentication_methods_supported', - ['openid_provider', 'oauth_authorization_server']) - - # what if request_param is already set ?? - # What if request_param in not in client_auth ?? - if _auth_meth_supported: - for endpoint in _request_endpoints: - if endpoint in _auth_meth_supported: - _func = getattr(self, f'_use_{endpoint}') - post_args = _func(_context, post_args, _auth_meth_supported) - break - else: # The OP does not support any authn methods - # am I already registered ? - if not _context.registration_response: # Not registered - raise OtherError("Can not send an authorization request without being registered" - " and automatic registration not supported") + self.pre_construct.append(automatic_registration) + self.post_construct.append(create_request) - client_id = request_args.get('client_id') - if not client_id: - request_args['client_id'] = self.upstream_get('attribute', 'entity_id') + self._use_authorization_endpoint = use_authorization_endpoint + self._use_pushed_authorization_endpoint = use_pushed_authorization_endpoint - return request_args, post_args diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index e1ed1433..e989a352 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -266,6 +266,7 @@ def test_parse_registration_response(self): assert self.rp["openid_relying_party"].context.claims.get_usage("scope") == ["openid", "profile"] + # Create a authorization request req_args = { "state": "ABCDE", "nonce": "nonce", @@ -275,6 +276,7 @@ def test_parse_registration_response(self): msg = self.rp["openid_relying_party"].get_service("authorization").construct(request_args=req_args) assert isinstance(msg, AuthorizationRequest) + _jws = factory(jws) reg_uris = _jws.jwt.payload()["metadata"]["openid_relying_party"]["redirect_uris"] assert msg["redirect_uri"] in reg_uris From c3cfb18056950da3f2e83bca1ebfdde3934f9bd1 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Fri, 12 Sep 2025 17:10:35 +0200 Subject: [PATCH 28/43] add script to store entity configuration in AbstractFilesystem --- script/entity_configuration_to_abfile.py | 66 ++++++++++++++++++++++++ script/get_entity_configuration.py | 4 +- 2 files changed, 69 insertions(+), 1 deletion(-) create mode 100755 script/entity_configuration_to_abfile.py diff --git a/script/entity_configuration_to_abfile.py b/script/entity_configuration_to_abfile.py new file mode 100755 index 00000000..be8df411 --- /dev/null +++ b/script/entity_configuration_to_abfile.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +import argparse +import json +import sys + +from idpyoidc.storage.abfile import AbstractFileSystem + + +def parse_args(): + parser = argparse.ArgumentParser(description="Load Entity Configuration into an AbstractFileSystem store.") + parser.add_argument("-s", "--source", required=True, help="Path to JSON file or '-' for stdin") + parser.add_argument("-t", "--target", required=True, help="AbstractFilesystem target directory") + parser.add_argument("-r", "--trust_anchor_info", action="store_true", help="Store Trust Anchor") + parser.add_argument("-u", "--subordinate_info", action="store_true", help="Store Subordinate info") + + return parser.parse_args() + + +def read_json(source: str): + if source == "-": + return json.load(sys.stdin) + with open(source, "r", encoding="utf-8") as fp: + return json.load(fp) + + +def main(): + args = parse_args() + + entity_configuration = read_json(args.source) + + info = None + if args.trust_anchor_info and not args.subordinate_info: + info = {entity_configuration["sub"]: entity_configuration["jwks"]} + elif args.subordinate_info and not args.trust_anchor_info: + _sub_info = { + "entity_types": list(entity_configuration["metadata"].keys()), + "jwks": entity_configuration["jwks"], + } + # Publishing the list endpoint makes this an intermediate + if ( + "federation_list_endpoint" + in entity_configuration["metadata"]["federation_entity"] + ): + _sub_info["intermediate"] = True + info = {entity_configuration["sub"]: _sub_info} + elif args.subordinate_info and args.trust_anchor_info: + print("You can only do one at the time!!") + else: + print("What do you expect me to do ??") + + store = AbstractFileSystem( + fdir=args.target, + key_conv="idpyoidc.util.Base64", + value_conv="idpyoidc.util.JSON", + ) + + wrote = 0 + for key, val in info.items(): + store[key] = val + wrote += 1 + + print(f"Done. {wrote} entr{'y' if wrote == 1 else 'ies'} written to {args.target}.") + + +if __name__ == "__main__": + main() diff --git a/script/get_entity_configuration.py b/script/get_entity_configuration.py index 5d52ea1d..3b6b779b 100755 --- a/script/get_entity_configuration.py +++ b/script/get_entity_configuration.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 import json +import sys from pygments import highlight from pygments.formatters.terminal import TerminalFormatter @@ -39,7 +40,8 @@ entity_configuration = verify_self_signed_signature(_jws) # Print json_str = json.dumps(entity_configuration, indent=2) - print(20 * "=" + f" Entity Configuration for {args.entity_id} " + 20 * "=") + #print(f"=== Entity Configuration for {args.entity_id} ===", file=sys.stderr) + print(20 * "=" + f" Entity Configuration for {args.entity_id} " + 20 * "=", file=sys.stderr) if args.format: print(highlight(json_str, JsonLexer(), TerminalFormatter())) else: From 0f447a45bd1eb213463978543409268d9f54b17a Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Fri, 12 Sep 2025 17:11:06 +0200 Subject: [PATCH 29/43] add script to get trust mark types from config on disk --- script/get_trust_mark_type.py | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 script/get_trust_mark_type.py diff --git a/script/get_trust_mark_type.py b/script/get_trust_mark_type.py new file mode 100644 index 00000000..ff5115ab --- /dev/null +++ b/script/get_trust_mark_type.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import argparse +import json +import sys +from pathlib import Path + +from idpyoidc.util import load_config_file + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Extract Trust Mark types from a Trust Mark Issuer config and output as JSON." + ) + parser.add_argument("directory", help="Path to the directory containing conf.json") + return parser.parse_args() + + +def main(): + args = parse_args() + + conf_path = Path(args.directory) / "conf.json" + if not conf_path.is_file(): + sys.exit(f"ERROR: Config file not found: {conf_path}") + + cnf = load_config_file(str(conf_path)) + + entity_id = cnf["entity"]["entity_id"] + _ids = list( + cnf["entity"]["trust_mark_entity"]["kwargs"]["trust_mark_specification"].keys() + ) + + print(json.dumps({entity_id: _ids})) + + +if __name__ == "__main__": + main() From 7a307e558e063338675c10a1a533deaa577e20b8 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Fri, 12 Sep 2025 17:12:02 +0200 Subject: [PATCH 30/43] add script to store trust mark types in AbstractFilesystem --- script/trust_mark_type_to_abfile.py | 72 +++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 script/trust_mark_type_to_abfile.py diff --git a/script/trust_mark_type_to_abfile.py b/script/trust_mark_type_to_abfile.py new file mode 100644 index 00000000..ba5f60ca --- /dev/null +++ b/script/trust_mark_type_to_abfile.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +import argparse +import json +import sys + +from idpyoidc.storage.abfile import AbstractFileSystem + + +def parse_args(): + parser = argparse.ArgumentParser(description="Update TA trust_mark_issuers AbstractFileSystem store") + parser.add_argument("-s", "--source", required=True, help="Path to JSON file or '-' for stdin") + parser.add_argument("-t", "--target", required=True, help="TA store dir (e.g. trust_anchor/trust_mark_issuers)") + parser.add_argument("--remove", action="store_true", help="Remove issuer from listed trust_mark_ids instead of adding") + parser.add_argument("--drop-empty", action="store_true", + help="If a removal would leave a Trust Mark type with an empty issuer list, " + "delete that key instead of writing an empty list") + return parser.parse_args() + + +def read_json(source: str): + if source == "-": + return json.load(sys.stdin) + with open(source, "r", encoding="utf-8") as fp: + return json.load(fp) + + +def main(): + args = parse_args() + + store = AbstractFileSystem( + fdir=args.target, + key_conv="idpyoidc.util.Base64", + value_conv="idpyoidc.util.JSON", + ) + + data = read_json(args.source) + + changes = 0 + would_be_empty = [] + for issuer, mark_ids in data.items(): + for tm_id in mark_ids: + current = store.get(tm_id, []) + if args.remove: + if issuer in current: + next_list = [i for i in current if i != issuer] + if not next_list: + # empty would mean “anyone can issue”. Avoid unless explicitly allowed. + if args.drop_empty: + # __delitem__ expects the serialized key, so serialize it explicitly. + del store[store.key_conv.serialize(tm_id)] + changes += 1 + else: + would_be_empty.append(tm_id) + store[tm_id] = next_list + changes += 1 + else: + if issuer not in current: + current.append(issuer) + store[tm_id] = current + changes += 1 + if would_be_empty: + tms = ", ".join(would_be_empty) + print( + f"Refusing to write empty issuer lists for: {tms}. " + f"Use --remove with --drop-empty to delete those keys instead.." + ) + + print(f"Applied {changes} change(s).") + + +if __name__ == "__main__": + main() From 3ea1c41ea54a72096841bcd667cb64a0623fa2af Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Thu, 18 Sep 2025 19:57:43 +0200 Subject: [PATCH 31/43] add script to inspect AbstractFileSystem-style files --- script/abfile_inspect.py | 266 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 266 insertions(+) create mode 100755 script/abfile_inspect.py diff --git a/script/abfile_inspect.py b/script/abfile_inspect.py new file mode 100755 index 00000000..e4d0ce7e --- /dev/null +++ b/script/abfile_inspect.py @@ -0,0 +1,266 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import json +import os +import re +import sys +from pathlib import Path +from typing import Iterator, List, Optional, Tuple + + +def base64url_decode_to_bytes(b64url_string: str) -> bytes: + padding = "=" * (-len(b64url_string) % 4) + return base64.urlsafe_b64decode(b64url_string + padding) + + +def base64url_decode_str(b64url_string: str) -> str: + return base64url_decode_to_bytes(b64url_string).decode("utf-8") + + +def _decoded_len_b64url(seg: str) -> int: + padding = "=" * (-len(seg) % 4) + return len(base64.urlsafe_b64decode(seg + padding)) + + +def try_decode_filename(name: str) -> Optional[str]: + try: + return base64url_decode_str(name) + except Exception: + return None + + +_B64URL_RE = re.compile(r"^[A-Za-z0-9_-]*$") # empty allowed (for detached JWS payload) + + +def _is_b64url(s: str) -> bool: + return bool(_B64URL_RE.fullmatch(s)) + + +def _decode_json_segment(segment: str) -> Optional[dict]: + try: + return json.loads(base64url_decode_to_bytes(segment).decode("utf-8")) + except Exception: + return None + + +def _classify_compact_jwt(compact: str) -> Tuple[Optional[dict], Optional[str]]: + """ + Returns (parsed_obj, type_label) for compact JOSE forms: + - JWS (3 parts): {"jws": {"header": {...}, "payload": , "sig_len": int, "detached": bool}} + - JWE (5 parts): {"jwe": {"protected": {...}, "parts": 5, "note": "..."}} + If not JWT-like, returns (None, None). + """ + s = compact.strip() + if not s: + return None, None + + parts = s.split(".") + if len(parts) not in (3, 5): + return None, None + + # All parts must be base64url (payload may be empty for detached JWS) + if not all(_is_b64url(p) for p in parts): + return None, None + + # Decode protected header + header = _decode_json_segment(parts[0]) + if header is None: + return None, None + + typ = header.get("typ") + + if len(parts) == 3: + # JWS: header SHOULD have "alg" + if "alg" not in header: + return None, None + + detached = parts[1] == "" + payload_obj = None if detached else _decode_json_segment(parts[1]) + payload_repr = ( + payload_obj + if payload_obj is not None + else ("[detached]" if detached else "[non-JSON payload]") + ) + + try: + sig_len = _decoded_len_b64url(parts[2]) + except Exception: + return None, None + + label = ( + f"JWT (JWS{', typ='+typ if typ else ''}{', detached' if detached else ''})" + ) + return { + "jws": { + "header": header, + "payload": payload_repr, + "sig_len": sig_len, + "detached": detached, + } + }, label + + # len(parts) == 5 -> JWE: header SHOULD have "enc" + if "enc" not in header: + return None, None + + label = f"JWT (JWE{', typ='+typ if typ else ''})" + return { + "jwe": { + "protected": header, + "parts": 5, + "note": "Compact JWE; content not decrypted or verified.", + } + }, label + + +def parse_content_text(text: str) -> Tuple[dict, str]: + """ + Decide between JSON vs Compact JWT vs Other. No signature verification. + JSON is attempted first. If the JSON is a string that looks like compact JOSE, + classify that token instead. + Returns (parsed_object, label). + """ + s = text.strip() + # Try full JSON first + try: + obj = json.loads(s) + except json.JSONDecodeError: + obj = None + + if obj is not None: + # If content is a JSON *string* holding a compact JOSE value, decode it. + if isinstance(obj, str): + parsed, label = _classify_compact_jwt(obj) + if parsed is not None: + return parsed, f"{label} (wrapped in JSON string)" + return obj, "JSON" + + # Not JSON. Try compact JOSE next. + parsed, label = _classify_compact_jwt(s) + if parsed is not None: + return parsed, label + + # 3) Fallback + return {"error": "Unrecognized content (not JSON and not compact JWT)."}, "Other" + + +def iter_entity_files(root: Path) -> Iterator[Tuple[Path, str]]: + """ + Yield (file_path, decoded_label) for files whose basename is base64url-decodable. + Skips files ending in '.lock'. + """ + if root.is_file(): + name = root.name + if name.endswith(".lock"): + return + decoded = try_decode_filename(name) + if decoded is not None: + yield root, decoded + return + + if root.is_dir(): + for dirpath, _, filenames in os.walk(root, followlinks=False): + for fname in filenames: + if fname.endswith(".lock"): + continue + decoded = try_decode_filename(fname) + if decoded is None: + continue + p = Path(dirpath) / fname + if p.is_file(): + yield p, decoded + + +def list_files_only(files: List[Tuple[Path, str]]) -> None: + for p, decoded in sorted(files, key=lambda x: str(x[0])): + print(f"{str(p)} -> {decoded}") + + +def describe_file(path: Path, decoded_label: str, max_bytes: int) -> None: + print(f"Path: {path}") + print(f" Decoded label: {decoded_label}") + + try: + size = path.stat().st_size + except Exception: + size = None + print(f" Size: {size} bytes" if size is not None else " Size: [unknown]") + + # Read up to max_bytes for safety + try: + with path.open("rb") as f: + data = f.read(max_bytes) + truncated = size is not None and size > max_bytes + text = data.decode("utf-8", errors="replace") + parsed, fmt = parse_content_text(text) + print(f" Parsed as: {fmt}") + if truncated: + print(f" [NOTE] Content truncated to --max-bytes={max_bytes} for safety.") + print(json.dumps(parsed, indent=2, ensure_ascii=False)) + except Exception as e: + print(" Parsed as: Other") + print(json.dumps({"error": str(e)}, indent=2)) + print("-" * 80) + + +def main(): + parser = argparse.ArgumentParser( + description=( + "List and inspect AbstractFileSystem files stored on the local filesystem." + "A file is included if its basename is base64url-decodable to UTF-8." + "False positives are expected.To reduce noise, scope the input directory " + "at the shell level or use --list and post-filter with standard tools like grep, awk, or jq." + ) + ) + parser.add_argument( + "path", + nargs="?", + default=".", + help="Path to scan or inspect (file or directory)", + ) + parser.add_argument( + "--list", + action="store_true", + help="Only list base64url-decodable filenames with their decoded labels", + ) + parser.add_argument( + "--max-bytes", + type=int, + default=1_000_000, + help="Max bytes to read from a file for inspection (default: 1MB)", + ) + args = parser.parse_args() + + root = Path(args.path) + + if not (root.exists() or root.is_file()): + print(f"Path does not exist or is not accessible: {args.path}", file=sys.stderr) + sys.exit(1) + + if root.is_file(): + name = root.name + if name.endswith(".lock"): + print(f"Skipping lock file: {str(root)}", file=sys.stderr) + sys.exit(1) + decoded = try_decode_filename(name) + if decoded is None: + print(f"Not a base64url-decodable filename: {str(root)}", file=sys.stderr) + sys.exit(1) + if args.list: + list_files_only([(root, decoded)]) + else: + describe_file(root, decoded, args.max_bytes) + return + + entries = list(iter_entity_files(root)) + if args.list: + list_files_only(entries) + else: + print(f"Scanning for base64url-decodable filenames under: {args.path}\n") + for p, decoded in sorted(entries, key=lambda x: str(x[0])): + describe_file(p, decoded, args.max_bytes) + + +if __name__ == "__main__": + main() From 5c24a509e8799e4d94e3b123f742f5aa909b05a5 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Thu, 18 Sep 2025 20:22:25 +0200 Subject: [PATCH 32/43] fix --- script/get_trust_mark_type.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 script/get_trust_mark_type.py diff --git a/script/get_trust_mark_type.py b/script/get_trust_mark_type.py old mode 100644 new mode 100755 From 882ad6ca08aaab5b0db24c372e17e4c01c24374c Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Sun, 21 Sep 2025 14:26:14 +0200 Subject: [PATCH 33/43] message.py: replace get_payload() with local _payload_from_jws() to break circular import --- src/fedservice/message.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 379b4527..f160c75f 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -1,4 +1,5 @@ """ Classes and functions used to describe information in an OpenID Connect Federation.""" +import contextlib import json import logging from urllib.parse import parse_qs @@ -33,7 +34,6 @@ from idpyoidc.message.oidc import SINGLE_OPTIONAL_BOOLEAN from idpyoidc.message.oidc import SINGLE_OPTIONAL_DICT -from fedservice.entity.function import get_payload from fedservice.exception import UnknownCriticalExtension from fedservice.exception import WrongSubject @@ -42,6 +42,17 @@ LOGGER = logging.getLogger(__name__) +def _payload_from_jws(token): + """ + Local helper to decode a compact JWS and return its payload as dict. + Replaces dependency on fedservice.entity.function.get_payload to avoid cycles. + """ + with contextlib.suppress(AttributeError, UnicodeDecodeError): + token = token.decode() + _jwt = factory(token) + return _jwt.jwt.payload() + + def dict_list_deser(val, sformat="dict"): res = [] if isinstance(val, list): @@ -549,7 +560,7 @@ def verify(self, **kwargs): for _tm in _trust_marks: _trust_mark = None if isinstance(_tm["trust_mark"], str): - _payload = get_payload(_tm["trust_mark"]) + _payload = _payload_from_jws(_tm["trust_mark"]) if _payload["trust_mark_id"] != _tm["trust_mark_id"]: raise ValueError("trust_mark_is values does not match") _trust_mark = TrustMark(**_payload) @@ -613,7 +624,7 @@ def verify(self, **kwargs): _delegation_jwt = self.get("delegation") if _delegation_jwt: # Not verifying the signature - _delegation = TrustMarkDelegation(**get_payload(_delegation_jwt)) + _delegation = TrustMarkDelegation(**_payload_from_jws(_delegation_jwt)) _delegation.verify() if self.get("iss") != _delegation["sub"]: raise ValueError("Not the issuer the delegation applies to") From f25373ccda17587397de7678759970ab59d17c97 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Sun, 21 Sep 2025 16:00:59 +0200 Subject: [PATCH 34/43] Add script to create Trust Marks --- script/create_trust_mark.py | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100755 script/create_trust_mark.py diff --git a/script/create_trust_mark.py b/script/create_trust_mark.py new file mode 100755 index 00000000..b1b09512 --- /dev/null +++ b/script/create_trust_mark.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +import argparse +import os +from pathlib import Path +import contextlib + +from idpyoidc.util import load_config_file + +from fedservice.utils import \ + make_federation_entity # type: ignore[attr-defined] + + +@contextlib.contextmanager +def pushd(new_dir: Path): + prev = Path.cwd() + os.chdir(new_dir) + try: + yield + finally: + os.chdir(prev) + + +def main() -> int: + p = argparse.ArgumentParser( + description="Create a Trust Mark with a fedservice Trust Mark Issuer.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + p.add_argument("-d", "--dir_name", required=True, help="Directory containing conf.json") + p.add_argument("-e", "--entity_id", required=True, help="Subject entity_id the Trust Mark applies to") + p.add_argument("-m", "--trust_mark_id", required=True, help="Trust Mark type identifier (URI)") + p.add_argument("--base-dir", help="Working directory to resolve relative paths in conf.json. " + "Defaults to the directory that contains conf.json.") + p.add_argument("-o", "--out", help="Write JWT to this file instead of stdout") + args = p.parse_args() + + conf_path = Path(args.dir_name, "conf.json").resolve() + base_dir = Path(args.base_dir).resolve() if args.base_dir else Path(args.dir_name).resolve().parent + + print(f"DIR: {base_dir}") + with pushd(base_dir): + cnf = load_config_file(str(conf_path)) + fe = make_federation_entity(**cnf["entity"]) + + # Trust Mark Issuer interface (handle both layouts) + tmi = getattr(fe, "trust_mark_entity", None) or getattr(fe, "server").trust_mark_entity + jwt_compact = tmi.create_trust_mark(args.trust_mark_id, args.entity_id) + + if args.out: + Path(args.out).write_text(jwt_compact + "\n", encoding="utf-8") + else: + print(jwt_compact) + + +if __name__ == "__main__": + main() From b1a7353276415957510a23921197af968038fa63 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Sun, 21 Sep 2025 16:46:16 +0200 Subject: [PATCH 35/43] ensure trust_mark_issuers is JSON-serializable by wrapping in dict() --- src/fedservice/entity/server/entity_configuration.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/fedservice/entity/server/entity_configuration.py b/src/fedservice/entity/server/entity_configuration.py index 9e224fe2..5b7f5a45 100644 --- a/src/fedservice/entity/server/entity_configuration.py +++ b/src/fedservice/entity/server/entity_configuration.py @@ -48,11 +48,12 @@ def process_request(self, request=None, **kwargs): _trust_mark_issuers = _fed_entity.context.trust_mark_issuers if _trust_mark_issuers: - args["trust_mark_issuers"] = _trust_mark_issuers + # Ensure trust_mark_issuers is JSON-serializable by wrapping in dict() + args["trust_mark_issuers"] = dict(_trust_mark_issuers) _trust_mark_owners = _fed_entity.context.trust_mark_owners if _trust_mark_owners: - args["trust_mark_owners"] = _trust_mark_owners + args["trust_mark_owners"] = dict(_trust_mark_owners) _ec = create_entity_statement(iss=_entity_id, From 6968aa01580772071490b263d14064453a7e7736 Mon Sep 17 00:00:00 2001 From: Stefan Halen Date: Sun, 21 Sep 2025 17:03:31 +0200 Subject: [PATCH 36/43] remove leftover line --- script/get_entity_configuration.py | 1 - 1 file changed, 1 deletion(-) diff --git a/script/get_entity_configuration.py b/script/get_entity_configuration.py index 3b6b779b..22d09108 100755 --- a/script/get_entity_configuration.py +++ b/script/get_entity_configuration.py @@ -40,7 +40,6 @@ entity_configuration = verify_self_signed_signature(_jws) # Print json_str = json.dumps(entity_configuration, indent=2) - #print(f"=== Entity Configuration for {args.entity_id} ===", file=sys.stderr) print(20 * "=" + f" Entity Configuration for {args.entity_id} " + 20 * "=", file=sys.stderr) if args.format: print(highlight(json_str, JsonLexer(), TerminalFormatter())) From 02ed3b9ca1ab0e1cebd1a3d397aee38f54a0f53e Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 29 Oct 2025 12:02:04 +0100 Subject: [PATCH 37/43] Trust Mark evaluation --- .../appclient/oauth2/authorization.py | 3 +- .../appclient/oauth2/registration.py | 286 +++++++++--------- src/fedservice/appclient/oidc/registration.py | 133 ++++---- .../appserver/oidc/authorization.py | 2 + tests/test_11_automatic_registration_oidc.py | 9 + 5 files changed, 206 insertions(+), 227 deletions(-) diff --git a/src/fedservice/appclient/oauth2/authorization.py b/src/fedservice/appclient/oauth2/authorization.py index 76129898..d148c0d3 100644 --- a/src/fedservice/appclient/oauth2/authorization.py +++ b/src/fedservice/appclient/oauth2/authorization.py @@ -96,4 +96,5 @@ def __init__(self, upstream_get, conf=None): self.post_construct.append(create_request) self._use_authorization_endpoint = use_authorization_endpoint - self._use_pushed_authorization_endpoint = use_pushed_authorization_endpoint \ No newline at end of file + self._use_pushed_authorization_endpoint = use_pushed_authorization_endpoint + diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index 6de8f560..97ef60e9 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -1,10 +1,13 @@ import logging from typing import Optional +from typing import Union from cryptojwt import JWT from idpyoidc.client.exception import ResponseError -from idpyoidc.client.oidc import registration +from idpyoidc.client.oauth2 import registration from idpyoidc.client.rp_handler import RPHandler +from idpyoidc.client.service import Service +from idpyoidc.message import Message from idpyoidc.message.oauth2 import OauthClientInformationResponse from idpyoidc.message.oauth2 import OauthClientMetadata from idpyoidc.message.oauth2 import ResponseMessage @@ -19,6 +22,131 @@ logger = logging.getLogger(__name__) +def create_entity_statement(request_args: Optional[dict] = None, service: Optional[Service] = None, **kwargs): + _combo = topmost_unit(service) + metadata = _combo.get_metadata(client=kwargs.get("client")) + federation_entity = get_federation_entity(service) + + _federation_keyjar = federation_entity.get_attribute("keyjar") + _authority_hints = federation_entity.get_authority_hints() + _context = federation_entity.get_context() + _entity_id = federation_entity.upstream_get('attribute', 'entity_id') + + kwargs = {} + if _context.trust_marks: + kwargs["trust_marks"] = _context.get_trust_marks() + + _jws = _context.create_entity_statement( + iss=_entity_id, + sub=_entity_id, + metadata=metadata, + key_jar=_federation_keyjar, + authority_hints=_authority_hints, + **kwargs) + # store for later reference + federation_entity.entity_configuration = _jws + return _jws + + +def parse_federation_registration_response(service, resp): + """ + Receives a dynamic client registration response, + + :param resp: An entity statement as a signed JWT + :return: A set of metadata claims + """ + + # Find the part of me that deals with the federation + federation_entity = get_federation_entity(service) + + # verify signature with OP's federation keys + _jwt = JWT(key_jar=federation_entity.keyjar) + payload = _jwt.unpack(resp) + + # Do I trust the TA the OP chose ? + _trust_anchor = payload.get("trust_anchor") + logger.debug(f"trust_anchor(_id): {_trust_anchor}") + if _trust_anchor not in federation_entity.function.trust_chain_collector.trust_anchors: + raise ValueError("Trust anchor I don't trust") + + # This is where I should decide to use the metadata verification service or do it + # all myself + # Do I have the necessary Function/Service installed + _verifier = federation_entity.get_function("metadata_verifier") + if _verifier: + # construct the query, send it and parse the response + _verifier_response = _verifier(resp) + if _verifier_response: + return _verifier_response + else: + # This is the trust chain from myself to the TA + entity_id = service.upstream_get('attribute', 'entity_id') + _trust_chains = get_verified_trust_chains(service, entity_id=entity_id, stop_at=_trust_anchor) + + # should only be one chain + if len(_trust_chains) == 0: + raise NoTrustedChains(entity_id) + + _tcs = [t for t in _trust_chains if t.anchor == _trust_anchor] + if len(_tcs) > 1: + raise SystemError(f"More then one chain ending in {_trust_anchor}") + else: + _trust_chains = _tcs + + _metadata = payload.get("metadata") + if _metadata: + # replace the metadata provided by the client with the metadata received from the AS + _trust_chains[0].verified_chain[-1]['metadata'] = _metadata + # If there is metadata_policy defined apply it + _trust_chains = apply_policies(federation_entity, _trust_chains) + + _resp = _trust_chains[0].verified_chain[-1] + _context = service.upstream_get('context') + _context.registration_response = _resp + return _resp + + +def shared_update_service_context(service, resp, **kwargs): + # Updated service_context per entity type + _root = topmost_unit(service) + _metadata = resp["metadata"] + for guise, item in _root.items(): + _guise_metadata = _metadata.get(guise) + if not _guise_metadata: + continue + + if isinstance(item, RPHandler): + _behaviour_args = kwargs.get("behaviour_args") + if _behaviour_args: + _client = _behaviour_args.get("client") + if _client: + _context = _client.context + _context.map_preferred_to_registered(_guise_metadata, uri_claims=service.uri_claims) + + for arg in ["client_id", "client_secret"]: + _val = _context.claims.get_usage(arg) + if _val: + setattr(_context, arg, _val) + + if arg == "client_secret" and _val: + _context.keyjar.add_symmetric("", _val) + _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) + else: + _context = item.get_context() + _md = service.response_cls(**_guise_metadata) + _md.verify() + _md.weed() + _context.map_preferred_to_registered(_md, service.uri_claims) + + _client_id = _context.claims.get_usage("client_id") + if _client_id: + _context.client_id = _client_id + + _client_secret = _context.claims.get_usage("client_secret") + _context.keyjar.add_symmetric("", _client_secret) + _context.keyjar.add_symmetric(_client_id, _client_secret) + + class Registration(registration.Registration): msg_type = OauthClientMetadata response_cls = OauthClientInformationResponse @@ -33,10 +161,15 @@ class Registration(registration.Registration): "client_registration_types": ["automatic", "explicit"] } + uri_claims = CLIENT_URI_CLAIMS + def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs): registration.Registration.__init__(self, upstream_get, conf=conf) # - self.post_construct.append(self.create_entity_statement) + self.post_construct.append(create_entity_statement) + + def update_service_context(self, resp: Union[Message, dict], **kwargs): + shared_update_service_context(service=self, resp=resp, **kwargs) @staticmethod def carry_receiver(request, **kwargs): @@ -76,42 +209,8 @@ def registration_metadata(self, combo, **kwargs): metadata.update(combo["federation_entity"].registration_metadata()) return metadata - def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs): - """ - Create a self-signed entity statement - - :param request_args: - :param service: - :param kwargs: - :return: - """ - - _federation_entity = get_federation_entity(self) - _combo = _federation_entity.upstream_get('unit') - metadata = _combo.get_metadata(client=kwargs.get("client")) - - _federation_keyjar = _federation_entity.get_attribute("keyjar") - _authority_hints = _federation_entity.get_authority_hints() - _context = _federation_entity.get_context() - _entity_id = _federation_entity.upstream_get('attribute', 'entity_id') - - kwargs = {} - if _context.trust_marks: - kwargs["trust_marks"] = _context.get_trust_marks() - - _jws = _context.create_entity_statement( - iss=_entity_id, - sub=_entity_id, - metadata=metadata, - key_jar=_federation_keyjar, - authority_hints=_authority_hints, - **kwargs) - # store for later reference - _federation_entity.entity_configuration = _jws - return _jws - def parse_response(self, info, sformat="", state="", **kwargs): - resp = self.parse_federation_registration_response(info, **kwargs) + resp = self.parse_federation_registration_response(self, info, **kwargs) if not resp: logger.error('Missing or faulty response') @@ -121,116 +220,3 @@ def parse_response(self, info, sformat="", state="", **kwargs): def _get_trust_anchor_id(self, entity_statement): return entity_statement.get('trust_anchor') - - def parse_federation_registration_response(self, resp, **kwargs): - """ - Receives a dynamic client registration response, - - :param resp: An entity statement as a signed JWT - :return: A set of metadata claims - """ - - # Find the part of the entity that deals with the federation - _federation_entity = get_federation_entity(self) - - # verify signature with OP's federation keys - _jwt = JWT(key_jar=_federation_entity.keyjar) - payload = _jwt.unpack(resp) - - # Do I trust the TA the OP chose ? - _trust_anchor = payload.get("trust_anchor") - logger.debug(f"trust_anchor(_id): {_trust_anchor}") - if _trust_anchor not in _federation_entity.function.trust_chain_collector.trust_anchors: - raise ValueError("Trust anchor I don't trust") - - # This is where I should decide to use the metadata verification service or do it - # all myself - # Do I have the necessary Function/Service installed - _verifier = _federation_entity.get_function("metadata_verifier") - if _verifier: - # construct the query, send it and parse the response - _verifier_response = _verifier(resp) - if _verifier_response: - return _verifier_response - else: - # This is the trust chain from myself to the TA - _entity_id = self.upstream_get('attribute', 'entity_id') - _trust_chains = get_verified_trust_chains(self, entity_id=_entity_id, stop_at=_trust_anchor) - - # should only be one chain - if len(_trust_chains) == 0: - raise NoTrustedChains(_entity_id) - - _tcs = [t for t in _trust_chains if t.anchor == _trust_anchor] - if len(_tcs) > 1: - raise SystemError(f"More then one chain ending in {_trust_anchor}") - else: - _trust_chains = _tcs - - _metadata = payload.get("metadata") - if _metadata: - # replace the metadata provided by the client with the metadata received from the AS - _trust_chains[0].verified_chain[-1]['metadata'] = _metadata - # If there is metadata_policy defined apply it - _trust_chains = apply_policies(_federation_entity, _trust_chains) - - _resp = _trust_chains[0].verified_chain[-1] - _context = self.upstream_get('context') - _context.registration_response = _resp - return _resp - - # def _add_client_secret_to_keyjar(self, context, client_id, metadata): - # _client_secret = context.claims.get_usage("client_secret") - # if _client_secret: - # _keyjar = getattr(context, "keyjar", None) - # if not _keyjar: - # _entity = self.upstream_get("unit") - # _keyjar = _entity.keyjar = KeyJar() - # - # context.client_secret = _client_secret - # _keyjar.add_symmetric("", _client_secret) - # _keyjar.add_symmetric(client_id, _client_secret) - # - # _expires_at = metadata.get("client_secret_expires_at", None) - # if _expires_at: - # context.set_usage("client_secret_expires_at", _expires_at) - - def update_service_context(self, resp, **kwargs): - # Updated service_context per entity type - _root = topmost_unit(self) - _metadata = resp["metadata"] - for guise, item in _root.items(): - _guise_metadata = _metadata.get(guise) - if not _guise_metadata: - continue - - if isinstance(item, RPHandler): - _behaviour_args = kwargs.get("behaviour_args") - if _behaviour_args: - _client = _behaviour_args.get("client") - if _client: - _context = _client.context - _md = self.response_cls(**_guise_metadata) - _md.verify() - _md.weed() - _context.map_preferred_to_registered(_md, uri_claims=CLIENT_URI_CLAIMS) - - for arg in ["client_id", "client_secret"]: - _val = _context.claims.get_usage(arg) - if _val: - setattr(_context, arg, _val) - - if arg == "client_secret" and _val: - _context.keyjar.add_symmetric("", _val) - _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) - else: - _context = item.get_context() - _context.map_preferred_to_registered(_guise_metadata) - - _client_id = _context.claims.get_usage("client_id") - if _client_id: - _context.client_id = _client_id - - _client_secret = _context.claims.get_usage("client_secret") - _context.keyjar.add_symmetric("", _client_secret) - _context.keyjar.add_symmetric(_client_id, _client_secret) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 65876f0c..47532017 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -5,13 +5,13 @@ from cryptojwt import JWT from idpyoidc.client.exception import ResponseError from idpyoidc.client.oidc import registration -from idpyoidc.client.rp_handler import RPHandler from idpyoidc.message import Message from idpyoidc.message.oidc import RegistrationRequest from idpyoidc.message.oidc import RegistrationResponse -from idpyoidc.node import topmost_unit from idpyoidc.transform import RP_URI_CLAIMS +from fedservice.appclient.oauth2.registration import create_entity_statement +from fedservice.appclient.oauth2.registration import shared_update_service_context from fedservice.entity.function import apply_policies from fedservice.entity.function import get_verified_trust_chains from fedservice.entity.utils import get_federation_entity @@ -33,10 +33,12 @@ class Registration(registration.Registration): "client_registration_types": ["automatic", "explicit"] } + uri_claims = RP_URI_CLAIMS + def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs): registration.Registration.__init__(self, upstream_get, conf=conf) # - self.post_construct.append(self.create_entity_statement) + self.post_construct.append(create_entity_statement) @staticmethod def carry_receiver(request, **kwargs): @@ -45,6 +47,9 @@ def carry_receiver(request, **kwargs): else: return request, {} + def update_service_context(self, resp: Union[Message, dict], **kwargs): + shared_update_service_context(service=self, resp=resp, **kwargs) + def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs): """ Create a self-signed entity statement @@ -57,33 +62,9 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) logger.debug(f"Create Entity Configuration") _federation_entity = get_federation_entity(self) - # _md = {_federation_context.entity_type: request_args.to_dict()} - _root = _federation_entity.upstream_get('unit') - _md = _root.get_metadata(client=kwargs.get("client")) - _federation_keyjar = _federation_entity.get_attribute("keyjar") - - # _entity = self.upstream_get('unit') - # if _entity.name not in _md: - # _md.update(_entity.get_metadata()) - - _authority_hints = _federation_entity.get_authority_hints() - _context = _federation_entity.get_context() - _entity_id = _federation_entity.upstream_get('attribute', 'entity_id') - - kwargs = {} - if _context.trust_marks: - kwargs["trust_marks"] = _context.trust_marks - - _jws = _context.create_entity_statement( - iss=_entity_id, - sub=_entity_id, - metadata=_md, - key_jar=_federation_keyjar, - authority_hints=_authority_hints, - **kwargs) - - # store for later reference - _federation_entity.entity_configuration = _jws + + _federation_entity = get_federation_entity(self) + _jws = create_entity_statement(_federation_entity, **kwargs) return _jws def parse_response(self, info, sformat="", state="", **kwargs): @@ -156,49 +137,49 @@ def parse_federation_registration_response(self, resp, **kwargs): _context.registration_response = _resp return _resp - def update_service_context(self, resp: Union[Message, dict], **kwargs): - """ - Updates the service context with information from the Entity Statement return by the server - - :param resp: A Entity Statement - :param kwargs: extra key word arguments - """ - # Updated service_context per entity type - _root = topmost_unit(self) - _metadata = resp["metadata"] - for guise, item in _root.items(): - _guise_metadata = _metadata.get(guise) - if not _guise_metadata: - continue - - if isinstance(item, RPHandler): - _behaviour_args = kwargs.get("behaviour_args") - if _behaviour_args: - _client = _behaviour_args.get("client") - if _client: - _context = _client.context - _context.map_preferred_to_registered(_guise_metadata) - - for arg in ["client_id", "client_secret"]: - _val = _context.claims.get_usage(arg) - if _val: - setattr(_context, arg, _val) - - if arg == "client_secret" and _val: - _context.keyjar.add_symmetric("", _val) - _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) - - else: - _context = item.get_context() - _md = self.response_cls(**_guise_metadata) - _md.verify() - _md.weed() - _context.map_preferred_to_registered(_md, uri_claims=RP_URI_CLAIMS) - - _client_id = _context.claims.get_usage("client_id") - if _client_id: - _context.client_id = _client_id - - _client_secret = _context.claims.get_usage("client_secret") - _context.keyjar.add_symmetric("", _client_secret) - _context.keyjar.add_symmetric(_client_id, _client_secret) + # def update_service_context(self, resp: Union[Message, dict], **kwargs): + # """ + # Updates the service context with information from the Entity Statement return by the server + # + # :param resp: A Entity Statement + # :param kwargs: extra key word arguments + # """ + # # Updated service_context per entity type + # _root = topmost_unit(self) + # _metadata = resp["metadata"] + # for guise, item in _root.items(): + # _guise_metadata = _metadata.get(guise) + # if not _guise_metadata: + # continue + # + # if isinstance(item, RPHandler): + # _behaviour_args = kwargs.get("behaviour_args") + # if _behaviour_args: + # _client = _behaviour_args.get("client") + # if _client: + # _context = _client.context + # _context.map_preferred_to_registered(_guise_metadata) + # + # for arg in ["client_id", "client_secret"]: + # _val = _context.claims.get_usage(arg) + # if _val: + # setattr(_context, arg, _val) + # + # if arg == "client_secret" and _val: + # _context.keyjar.add_symmetric("", _val) + # _context.keyjar.add_symmetric(_context.claims.get_usage("client_id"), _val) + # + # else: + # _context = item.get_context() + # _md = self.response_cls(**_guise_metadata) + # _md.verify() + # _md.weed() + # _context.map_preferred_to_registered(_md, uri_claims=RP_URI_CLAIMS) + # + # _client_id = _context.claims.get_usage("client_id") + # if _client_id: + # _context.client_id = _client_id + # + # _client_secret = _context.claims.get_usage("client_secret") + # _context.keyjar.add_symmetric("", _client_secret) + # _context.keyjar.add_symmetric(_client_id, _client_secret) diff --git a/src/fedservice/appserver/oidc/authorization.py b/src/fedservice/appserver/oidc/authorization.py index e3299285..40053bb5 100644 --- a/src/fedservice/appserver/oidc/authorization.py +++ b/src/fedservice/appserver/oidc/authorization.py @@ -101,6 +101,8 @@ def client_authentication(self, request, auth=None, **kwargs): if 'automatic' in _context.provider_info.get('client_registration_types_supported', []): if client_info and "automatic_registered" in client_info: # Remove the old one del _context.cdb[_cid] + if _cid in _context.keyjar: + del _context.keyjar[_cid] # try the federation way _trust_chain = request.get('trust_chain', []) registered_client_id = self.do_automatic_registration(_cid, _trust_chain) diff --git a/tests/test_11_automatic_registration_oidc.py b/tests/test_11_automatic_registration_oidc.py index 48831dbe..75ddab93 100644 --- a/tests/test_11_automatic_registration_oidc.py +++ b/tests/test_11_automatic_registration_oidc.py @@ -274,3 +274,12 @@ def test_automatic_registration(self): # Assert that the client's entity_id has been registered as a client assert self.rp.entity_id in self.op["openid_provider"].get_context().cdb + # Check that the RP's keys are reflected in the OP's keyjar + assert self.rp.entity_id in self.op["openid_provider"].keyjar + # There are three RP keys. One EC, one RSA and one OCT + rp_keyjar = self.rp["openid_relying_party"].keyjar + op_keyjar = self.op["openid_provider"].keyjar + for key_type in ["EC", "RSA", "OCT"]: + for key in rp_keyjar.get_signing_key(key_type=key_type): + vk = op_keyjar.get_verify_key(key_type=key_type, kid=key.kid, issuer_id=self.rp.entity_id) + assert vk \ No newline at end of file From 71ce85cdf535801b82a71fea411b6c6abbd6134a Mon Sep 17 00:00:00 2001 From: roland Date: Wed, 29 Oct 2025 12:36:46 +0100 Subject: [PATCH 38/43] Fixed references. --- src/fedservice/appclient/oauth2/registration.py | 2 +- src/fedservice/appclient/oidc/registration.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index 97ef60e9..0a974b50 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -210,7 +210,7 @@ def registration_metadata(self, combo, **kwargs): return metadata def parse_response(self, info, sformat="", state="", **kwargs): - resp = self.parse_federation_registration_response(self, info, **kwargs) + resp = parse_federation_registration_response(self, info) if not resp: logger.error('Missing or faulty response') diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 47532017..a9832d2c 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -64,7 +64,7 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) _federation_entity = get_federation_entity(self) _federation_entity = get_federation_entity(self) - _jws = create_entity_statement(_federation_entity, **kwargs) + _jws = create_entity_statement(service=_federation_entity, **kwargs) return _jws def parse_response(self, info, sformat="", state="", **kwargs): From 14d73c7cb245744e08a6fe9b6a6c947ccc2cc746 Mon Sep 17 00:00:00 2001 From: roland Date: Thu, 30 Oct 2025 18:42:24 +0100 Subject: [PATCH 39/43] Refactored. Split entity_statement into entity_configuration and subordinate_statement. --- example/display_entity.py | 4 +- .../appclient/oauth2/registration.py | 8 +- src/fedservice/appclient/oidc/registration.py | 18 ++-- .../appserver/oauth2/registration.py | 4 +- src/fedservice/appserver/oidc/registration.py | 19 ++-- src/fedservice/defaults.py | 2 +- .../entity/client/entity_configuration.py | 4 +- .../entity/client/entity_statement.py | 4 +- src/fedservice/entity/context.py | 60 +++++++++--- src/fedservice/entity/function/policy.py | 1 + .../entity/function/trust_chain_collector.py | 2 +- .../entity/server/entity_configuration.py | 33 +++---- src/fedservice/entity/server/fetch.py | 98 +++++++++---------- src/fedservice/entity/server/resolve.py | 16 +-- .../entity_statement/constraints.py | 54 +++++----- src/fedservice/entity_statement/create.py | 85 +++++++++++----- .../fetch_entity_statement/__init__.py | 11 ++- src/fedservice/message.py | 55 +++++++---- tests/__init__.py | 4 +- tests/test_01_message.py | 12 ++- tests/test_05_constraints.py | 74 +++++++------- tests/test_06_claims.py | 2 +- tests/test_10_explicit_registration_oidc.py | 6 +- tests/test_40_fe.py | 6 +- tests/test_53_publish_assigned_trust_mark.py | 3 +- 25 files changed, 334 insertions(+), 251 deletions(-) diff --git a/example/display_entity.py b/example/display_entity.py index cfd2dee9..d8c4106d 100755 --- a/example/display_entity.py +++ b/example/display_entity.py @@ -8,7 +8,7 @@ from idpyoidc.key_import import import_jwks from idpyoidc.server.exception import ServiceError -from fedservice.message import EntityStatement +from fedservice.message import EntityConfiguration def get_self_signed_entity_statement(entity_id): @@ -18,7 +18,7 @@ def get_self_signed_entity_statement(entity_id): raise ServiceError(_response.reason) _jws = factory(_response.text) _payload = _jws.jwt.payload() - entity_statement = EntityStatement(**_payload) + entity_statement = EntityConfiguration(**_payload) _key_jar = KeyJar() # verify entity_statement["iss"] _key_jar = import_jwks(_key_jar, entity_statement['jwks'], entity_id) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index 0a974b50..d7100783 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -22,7 +22,7 @@ logger = logging.getLogger(__name__) -def create_entity_statement(request_args: Optional[dict] = None, service: Optional[Service] = None, **kwargs): +def create_entity_configuration(request_args: Optional[dict] = None, service: Optional[Service] = None, **kwargs): _combo = topmost_unit(service) metadata = _combo.get_metadata(client=kwargs.get("client")) federation_entity = get_federation_entity(service) @@ -36,9 +36,9 @@ def create_entity_statement(request_args: Optional[dict] = None, service: Option if _context.trust_marks: kwargs["trust_marks"] = _context.get_trust_marks() - _jws = _context.create_entity_statement( + _jws = _context.create_entity_configuration( iss=_entity_id, - sub=_entity_id, + # sub=_entity_id, metadata=metadata, key_jar=_federation_keyjar, authority_hints=_authority_hints, @@ -166,7 +166,7 @@ class Registration(registration.Registration): def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs): registration.Registration.__init__(self, upstream_get, conf=conf) # - self.post_construct.append(create_entity_statement) + self.post_construct.append(create_entity_configuration) def update_service_context(self, resp: Union[Message, dict], **kwargs): shared_update_service_context(service=self, resp=resp, **kwargs) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index a9832d2c..6e7406e6 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -10,7 +10,7 @@ from idpyoidc.message.oidc import RegistrationResponse from idpyoidc.transform import RP_URI_CLAIMS -from fedservice.appclient.oauth2.registration import create_entity_statement +from fedservice.appclient.oauth2.registration import create_entity_configuration as oauth2_create_entity_configuration from fedservice.appclient.oauth2.registration import shared_update_service_context from fedservice.entity.function import apply_policies from fedservice.entity.function import get_verified_trust_chains @@ -38,7 +38,7 @@ class Registration(registration.Registration): def __init__(self, upstream_get, conf=None, client_authn_factory=None, **kwargs): registration.Registration.__init__(self, upstream_get, conf=conf) # - self.post_construct.append(create_entity_statement) + self.post_construct.append(oauth2_create_entity_configuration) @staticmethod def carry_receiver(request, **kwargs): @@ -50,7 +50,7 @@ def carry_receiver(request, **kwargs): def update_service_context(self, resp: Union[Message, dict], **kwargs): shared_update_service_context(service=self, resp=resp, **kwargs) - def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs): + def create_entity_configuration(self, request_args: Optional[dict] = None, **kwargs): """ Create a self-signed entity statement @@ -62,9 +62,15 @@ def create_entity_statement(self, request_args: Optional[dict] = None, **kwargs) logger.debug(f"Create Entity Configuration") _federation_entity = get_federation_entity(self) - - _federation_entity = get_federation_entity(self) - _jws = create_entity_statement(service=_federation_entity, **kwargs) + _context = _federation_entity.get_context() + authority_hints = _context.authority_hints + if authority_hints: + kwargs["authority_hints"] = authority_hints + if "key_jar" not in kwargs: + kwargs["key_jar"] = _federation_entity.keyjar + + _jws = _context.create_entity_configuration(iss=_federation_entity.entity_id, + **kwargs) return _jws def parse_response(self, info, sformat="", state="", **kwargs): diff --git a/src/fedservice/appserver/oauth2/registration.py b/src/fedservice/appserver/oauth2/registration.py index f991f8f4..92bfb95a 100644 --- a/src/fedservice/appserver/oauth2/registration.py +++ b/src/fedservice/appserver/oauth2/registration.py @@ -84,9 +84,9 @@ def process_request(self, request=None, **kwargs): _response_metadata = req.to_dict() _response_metadata.update(response_info['response_args']) - entity_statement = _context.create_entity_statement( + entity_statement = _context.create_entity_configuration( _federation_entity.upstream_get('attribute', 'entity_id'), - payload['iss'], + # payload['iss'], trust_anchor=trust_chain.anchor, metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], diff --git a/src/fedservice/appserver/oidc/registration.py b/src/fedservice/appserver/oidc/registration.py index bc2cd036..a8292e58 100644 --- a/src/fedservice/appserver/oidc/registration.py +++ b/src/fedservice/appserver/oidc/registration.py @@ -23,7 +23,7 @@ class Registration(registration.Registration): def __init__(self, upstream_get, **kwargs): registration.Registration.__init__(self, upstream_get, **kwargs) - self.post_construct.append(self.create_entity_statement) + self.post_construct.append(self.create_entity_configuration) def parse_request(self, request, auth=None, **kwargs): return request @@ -64,16 +64,16 @@ def process_request(self, request=None, **kwargs): _response_metadata = req.to_dict() _response_metadata.update(response_info['response_args']) - entity_statement = _context.create_entity_statement( + entity_configuration = _context.create_entity_configuration( _federation_entity.upstream_get('attribute', 'entity_id'), - payload['iss'], + # payload['iss'], trust_anchor=trust_chain.anchor, metadata={opponent_entity_type: _response_metadata}, aud=payload['iss'], authority_hints=_federation_entity.get_authority_hints(), include_jwks=False ) - response_info["response_msg"] = entity_statement + response_info["response_msg"] = entity_configuration del response_info["response_args"] return response_info @@ -85,8 +85,7 @@ def non_fed_process_request(self, req, **kwargs): return registration.Registration.process_request(self, req, authn=None, **kwargs) @staticmethod - def create_entity_statement(response_args, request, context, - **kwargs): + def create_entity_configuration(response_args, request, context, **kwargs): """ wrap the non-federation response in a federation response @@ -98,7 +97,7 @@ def create_entity_statement(response_args, request, context, """ _fe = context.federation_entity _md = {_fe.opponent_entity_type: response_args.to_dict()} - return _fe.create_entity_statement(_fe.entity_id, sub=_fe.entity_id, - metadata=_md, - authority_hints=_fe.get_authority_hints(), - trust_marks=_fe.context.trust_marks) + return _fe.create_entity_configuration(_fe.entity_id, + metadata=_md, + authority_hints=_fe.get_authority_hints(), + trust_marks=_fe.context.trust_marks) diff --git a/src/fedservice/defaults.py b/src/fedservice/defaults.py index 109d9d35..53ab18a6 100644 --- a/src/fedservice/defaults.py +++ b/src/fedservice/defaults.py @@ -51,7 +51,7 @@ "kwargs": {} }, "entity_statement": { - "class": 'fedservice.entity.client.entity_statement.EntityStatement', + "class": 'fedservice.entity.client.entity_statement.SubordinateStatement', "kwargs": {} }, "trust_mark_status": { diff --git a/src/fedservice/entity/client/entity_configuration.py b/src/fedservice/entity/client/entity_configuration.py index ce29de84..8c8847d4 100644 --- a/src/fedservice/entity/client/entity_configuration.py +++ b/src/fedservice/entity/client/entity_configuration.py @@ -13,7 +13,7 @@ from fedservice.entity import FederationEntity from fedservice.entity.service import FederationService from fedservice.entity.utils import get_federation_entity -from fedservice.message import EntityStatement +from fedservice.message import EntityConfiguration as MSG_EntityConfiguration logger = logging.getLogger(__name__) @@ -32,7 +32,7 @@ def construct_tenant_well_known_url(entity_id, typ): class EntityConfiguration(FederationService): msg_type = oauth2.Message - response_cls = EntityStatement + response_cls = MSG_EntityConfiguration error_msg = ResponseMessage synchronous = True service_name = "entity_configuration" diff --git a/src/fedservice/entity/client/entity_statement.py b/src/fedservice/entity/client/entity_statement.py index f7fd6920..d0b606ba 100644 --- a/src/fedservice/entity/client/entity_statement.py +++ b/src/fedservice/entity/client/entity_statement.py @@ -28,11 +28,11 @@ def construct_entity_configuration_query(api_endpoint, issuer="", subject=""): return f"{api_endpoint}" -class EntityStatement(FederationService): +class SubordinateStatement(FederationService): """The service that talks to the OIDC federation Fetch endpoint.""" msg_type = oauth2.Message - response_cls = message.EntityStatement + response_cls = message.SubordinateStatement error_msg = ResponseMessage synchronous = True service_name = "entity_statement" diff --git a/src/fedservice/entity/context.py b/src/fedservice/entity/context.py index 36644407..d2dee445 100644 --- a/src/fedservice/entity/context.py +++ b/src/fedservice/entity/context.py @@ -11,7 +11,7 @@ from idpyoidc.transform import preferred_to_registered from fedservice.entity.claims import FederationEntityClaims -from fedservice.entity_statement.create import create_entity_statement +from fedservice.entity_statement.create import create_entity_configuration def entity_type(metadata): @@ -108,8 +108,8 @@ def supports(self): def setup_client_authn_methods(self): self.client_authn_methods = client_auth_setup(self.config.get("client_authn_methods")) - def create_entity_statement(self, iss, sub, key_jar=None, metadata=None, metadata_policy=None, - authority_hints=None, lifetime=0, jwks=None, **kwargs): + def create_entity_configuration(self, iss, key_jar=None, metadata=None, metadata_policy=None, + authority_hints=None, lifetime=0, jwks=None, **kwargs): if jwks: kwargs["jwks"] = jwks else: @@ -130,9 +130,23 @@ def create_entity_statement(self, iss, sub, key_jar=None, metadata=None, metadat if _trust_marks: kwargs["trust_marks"] = _trust_marks - return create_entity_statement(iss, sub, key_jar=key_jar, metadata=metadata, - metadata_policy=metadata_policy, - authority_hints=authority_hints, lifetime=lifetime, **kwargs) + _trust_mark_owners = kwargs.get("trust_mark_owners") + if not _trust_mark_owners: + _trust_marks = self.get_trust_mark_owners() + if _trust_mark_owners: + kwargs["trust_mark_owners"] = _trust_mark_owners + + _trust_mark_issuers = kwargs.get("trust_mark_issuers") + if not _trust_mark_issuers: + _trust_mark_issuers = self.get_trust_mark_issuers() + if _trust_mark_issuers: + kwargs["trust_mark_issuers"] = _trust_mark_issuers + + if metadata_policy: + kwargs["metadata_policy"] = metadata_policy + + return create_entity_configuration(iss, key_jar=key_jar, metadata=metadata, + authority_hints=authority_hints, lifetime=lifetime, **kwargs) def map_preferred_to_registered(self, registration_response: Optional[dict] = None): self.claims.use = preferred_to_registered( @@ -167,7 +181,7 @@ def get_trusted_roots(self) -> dict: else: raise ValueError("trusted_roots") - def get_trust_marks(self)-> Optional[list]: + def get_trust_marks(self) -> Optional[list]: if self.trust_marks == None: return [] elif isinstance(self.trust_marks, str): @@ -179,6 +193,30 @@ def get_trust_marks(self)-> Optional[list]: else: raise ValueError("trust_marks") + def get_trust_mark_owners(self) -> Optional[dict]: + if self.trust_mark_owners == None: + return {} + elif isinstance(self.trust_mark_owners, str): + return json.loads(open(self.trust_mark_owners).read()) + elif isinstance(self.trust_mark_owners, dict): + return self.trust_mark_owners + elif isinstance(self.trust_mark_owners, Callable): + return self.trust_mark_owners() + else: + raise ValueError("trust_mark_owners") + + def get_trust_mark_issuers(self) -> Optional[dict]: + if self.trust_mark_issuers == None: + return {} + elif isinstance(self.trust_mark_issuers, str): + return json.loads(open(self.trust_mark_issuers).read()) + elif isinstance(self.trust_mark_issuers, dict): + return self.trust_mark_issuers + elif isinstance(self.trust_mark_issuers, Callable): + return self.trust_mark_issuers() + else: + raise ValueError("trust_mark_issuers") + class FederationServerContext(FederationContext): @@ -201,10 +239,10 @@ def __init__(self, _sstm = config.get("self_signed_trust_marks") if _sstm: _keyjar = upstream_get('attribute', "keyjar") - self.signed_trust_marks = self.create_entity_statement(iss=self.entity_id, - sub=self.entity_id, - keyjar=_keyjar, - trust_marks=_sstm) + self.signed_trust_marks = self.create_entity_configuration(iss=self.entity_id, + # sub=self.entity_id, + keyjar=_keyjar, + trust_marks=_sstm) self.trust_marks = trust_marks self.jti_db = {} diff --git a/src/fedservice/entity/function/policy.py b/src/fedservice/entity/function/policy.py index 931a802f..eae0cf80 100644 --- a/src/fedservice/entity/function/policy.py +++ b/src/fedservice/entity/function/policy.py @@ -589,6 +589,7 @@ def __call__(self, trust_chain: TrustChain, entity_type: Optional[str] = ''): if entity_type: trust_chain.metadata[entity_type] = self._policy(trust_chain, entity_type) else: + # rotate through the different entity types this entity has for _type in trust_chain.verified_chain[-1]['metadata'].keys(): trust_chain.metadata[_type] = self._policy(trust_chain, _type) else: diff --git a/src/fedservice/entity/function/trust_chain_collector.py b/src/fedservice/entity/function/trust_chain_collector.py index e1d414c3..c25bbd7c 100644 --- a/src/fedservice/entity/function/trust_chain_collector.py +++ b/src/fedservice/entity/function/trust_chain_collector.py @@ -105,7 +105,7 @@ def get_document(self, url: str): :param url: Target URL :param httpc_args: Arguments for the HTTP call. - :return: Signed EntityStatement + :return: Signed EntityConfiguration or SubordinateStatement """ _keyjar = self.upstream_get('attribute', 'keyjar') diff --git a/src/fedservice/entity/server/entity_configuration.py b/src/fedservice/entity/server/entity_configuration.py index 9e224fe2..1ce1afc1 100644 --- a/src/fedservice/entity/server/entity_configuration.py +++ b/src/fedservice/entity/server/entity_configuration.py @@ -3,18 +3,17 @@ from typing import Union from idpyoidc.message import Message - -from fedservice.entity.utils import get_federation_entity -from fedservice.entity_statement.create import create_entity_statement from idpyoidc.message import oauth2 from idpyoidc.server import Endpoint -from fedservice.message import EntityStatement +from fedservice import message +from fedservice.entity.utils import get_federation_entity +from fedservice.entity_statement.create import create_entity_configuration class EntityConfiguration(Endpoint): request_cls = oauth2.Message - response_cls = EntityStatement + response_cls = message.EntityConfiguration request_format = "" response_format = "jose" response_placement = "body" @@ -54,22 +53,20 @@ def process_request(self, request=None, **kwargs): if _trust_mark_owners: args["trust_mark_owners"] = _trust_mark_owners - - _ec = create_entity_statement(iss=_entity_id, - sub=_entity_id, - key_jar=_fed_entity.get_attribute('keyjar'), - metadata=_metadata, - authority_hints=_server.upstream_get('authority_hints'), - **args - ) + _ec = create_entity_configuration(iss=_entity_id, + key_jar=_fed_entity.get_attribute('keyjar'), + metadata=_metadata, + authority_hints=_server.upstream_get('authority_hints'), + **args + ) return {"response": _ec} def response_info( - self, - response_args: Optional[dict] = None, - request: Optional[Union[Message, dict]] = None, - error: Optional[str] = "", - **kwargs + self, + response_args: Optional[dict] = None, + request: Optional[Union[Message, dict]] = None, + error: Optional[str] = "", + **kwargs ) -> dict: if "response" in kwargs: return kwargs["response"] diff --git a/src/fedservice/entity/server/fetch.py b/src/fedservice/entity/server/fetch.py index ab9f8f0a..167fb3f3 100644 --- a/src/fedservice/entity/server/fetch.py +++ b/src/fedservice/entity/server/fetch.py @@ -3,18 +3,18 @@ from idpyoidc.message import oidc from idpyoidc.server.endpoint import Endpoint -from fedservice.entity_statement.create import create_entity_statement +from fedservice import message +from fedservice.entity_statement.create import create_subordinate_statement from fedservice.exception import UnknownEntity -from fedservice.message import EntityStatement logger = logging.getLogger(__name__) class Fetch(Endpoint): request_cls = oidc.Message - response_cls = EntityStatement + response_cls = message.SubordinateStatement response_format = "jose" - response_content_type="application/entity-statement+jwt" + response_content_type = "application/entity-statement+jwt" name = "fetch" endpoint_name = "federation_fetch_endpoint" @@ -28,59 +28,53 @@ def process_request(self, request=None, **kwargs): _context = self.upstream_get("context") _issuer = request.get("iss") if not _issuer: - _issuer = self.upstream_get('attribute','entity_id') + _issuer = self.upstream_get('attribute', 'entity_id') _sub = request.get("sub") _keyjar = self.upstream_get('attribute', 'keyjar') - if not _sub or _sub == _issuer: - _server = self.upstream_get("server") - _entity = _server.upstream_get('unit') - _metadata = _entity.get_metadata() - _es = create_entity_statement(iss=_entity.context.entity_id, - sub=_entity.context.entity_id, - key_jar=_keyjar, - metadata=_metadata, - authority_hints=self.upstream_get('authority_hints')) - else: - _server = self.upstream_get("unit") - # Contains jwks and possibly entity type and authority_hints - _response = _server.subordinate.get(_sub) - if not _response: - logger.debug(f"Unknown subordinate: {_sub}") - logger.debug(f"Known subordinates: {list(_server.subordinate.keys())}") - raise UnknownEntity(_sub) + # if not _sub or _sub == _issuer: + # _server = self.upstream_get("server") + # _entity = _server.upstream_get('unit') + # _metadata = _entity.get_metadata() + # _es = create_entity_configuration(iss=_entity.context.entity_id, + # sub=_entity.context.entity_id, + # key_jar=_keyjar, + # metadata=_metadata, + # authority_hints=self.upstream_get('authority_hints')) + # else: + _server = self.upstream_get("unit") + # Information stored about this entity. Contains jwks and possibly entity type and authority_hints + _response = _server.subordinate.get(_sub) + if not _response: + logger.debug(f"Unknown subordinate: {_sub}") + logger.debug(f"Known subordinates: {list(_server.subordinate.keys())}") + raise UnknownEntity(_sub) - if not 'authority_hints' in _response: - # If nothing specified add myself - _response["authority_hints"] = [_issuer] + _policy = _server.policy.get(_sub) + if not _policy: # No entity specific policy + if 'entity_types' in _response: + _entity_types = _response['entity_types'] + _response = {k: v for k, v in _response.items() if k != 'entity_types'} + _policy = {'metadata': {}, 'metadata_policy': {}} + for entity_type in _entity_types: + _et_policy = _server.policy.get(entity_type) + if not _et_policy: + continue + for _typ in ['metadata', 'metadata_policy']: + if _typ in _et_policy: + try: + _policy[_typ].update({entity_type: _et_policy[_typ]}) + except KeyError: + _policy[_typ] = {entity_type: _et_policy[_typ]} - _policy = _server.policy.get(_sub) - if not _policy: # No entity specific policy - if 'entity_types' in _response: - _entity_types = _response['entity_types'] - _response = {k: v for k, v in _response.items() if k != 'entity_types'} - _policy = {'metadata': {}, 'metadata_policy': {}} - for entity_type in _entity_types: - _et_policy = _server.policy.get(entity_type) - if not _et_policy: - continue - for _typ in ['metadata', 'metadata_policy']: - if _typ in _et_policy: - try: - _policy[_typ].update({entity_type: _et_policy[_typ]}) - except KeyError: - _policy[_typ] = {entity_type: _et_policy[_typ]} + if _policy == {'metadata': {}, 'metadata_policy': {}}: # Nothing has changed + _policy = None - if _policy == {'metadata': {}, 'metadata_policy': {}}: # Nothing has changed - _policy = None + if _policy: + _response.update(_policy) - if _policy: - _response.update(_policy) - - _es = create_entity_statement(iss=_issuer, - sub=_sub, - key_jar=_keyjar, - **_response - ) + _es = create_subordinate_statement(iss=_issuer, + sub=_sub, + key_jar=_keyjar, + **_response) return {"response_msg": _es} - diff --git a/src/fedservice/entity/server/resolve.py b/src/fedservice/entity/server/resolve.py index 58b6192e..bee75764 100644 --- a/src/fedservice/entity/server/resolve.py +++ b/src/fedservice/entity/server/resolve.py @@ -10,7 +10,7 @@ from fedservice.entity.function import collect_trust_chains from fedservice.entity.function import verify_trust_chains from fedservice.entity.utils import get_federation_entity -from fedservice.entity_statement.create import create_entity_statement +from fedservice.entity_statement.create import create_entity_configuration logger = logging.getLogger(__name__) @@ -55,7 +55,7 @@ def process_request(self, request=None, **kwargs): trust_anchor=_trust_anchor) if _verified_mark: verified_trust_marks.append({ - "trust_mark_id":_verified_mark["trust_mark_id"], + "trust_mark_id": _verified_mark["trust_mark_id"], "trust_mark": _trust_mark }) @@ -67,12 +67,12 @@ def process_request(self, request=None, **kwargs): else: args = {} - _jws = create_entity_statement(_federation_entity.entity_id, - sub=request["sub"], - key_jar=_federation_entity.get_attribute('keyjar'), - metadata=metadata, - trust_chain=trust_chain, - **args) + _jws = create_entity_configuration(_federation_entity.entity_id, + # sub=request["sub"], + key_jar=_federation_entity.get_attribute('keyjar'), + metadata=metadata, + trust_chain=trust_chain, + **args) return {'response_args': _jws} def response_info( diff --git a/src/fedservice/entity_statement/constraints.py b/src/fedservice/entity_statement/constraints.py index 289c34c8..d3101de3 100644 --- a/src/fedservice/entity_statement/constraints.py +++ b/src/fedservice/entity_statement/constraints.py @@ -1,30 +1,31 @@ +import logging from typing import List from typing import Union +from fedservice.message import Constraints from idpyoidc.message import Message -from fedservice.entity_statement.statement import TrustChain -from fedservice.message import EntityStatement +from fedservice import message +logger = logging.getLogger(__name__) -def calculate_path_length(constraints, current_max_path_length, max_assigned): - try: - _max_len = constraints['max_path_length'] - except KeyError: - if max_assigned: +def calculate_path_length(constraints, current_max_path_length, assigned): + _max_len = constraints.get('max_path_length') + if _max_len is None: + current_max_path_length -= 1 + return current_max_path_length + elif _max_len >= 0: + if assigned: current_max_path_length -= 1 - return current_max_path_length - - return 0 - - if max_assigned: - new_current = current_max_path_length - 1 - if _max_len < new_current: + if current_max_path_length < _max_len: + logger.error("Subordinate can not increase Max Path Length") + return -1 return _max_len else: - return new_current - - return _max_len + return _max_len + else: + logger.error("Too many intermediates, Max Path Length exceeded") + return -1 def remove_scheme(url): @@ -78,7 +79,7 @@ def update_specs(new_constraints: list, old_constraints: list): def add_constraints(new_constraints: dict, naming_constraints: dict): - for key in ['permitted','excluded']: + for key in ['permitted', 'excluded']: if not naming_constraints[key]: if key in new_constraints and new_constraints[key]: naming_constraints[key] = new_constraints[key][:] @@ -119,7 +120,7 @@ def permitted(subject_id: str, permitted_id: List[str]): return False -def meets_restrictions(trust_chain: List[EntityStatement]) -> bool: +def meets_restrictions(trust_chain: List[message.EntityConfiguration]) -> bool: """ Verifies that the trust chain fulfills the constraints specified in it. @@ -129,20 +130,19 @@ def meets_restrictions(trust_chain: List[EntityStatement]) -> bool: """ current_max_path_length = 0 - max_assigned = False + _assigned = False naming_constraints = { "permitted": None, "excluded": None } for statement in trust_chain[:-1]: # All but the last - try: - _constraints = statement['constraints'] - except KeyError: - continue - - current_max_path_length = calculate_path_length(_constraints, current_max_path_length, - max_assigned) + _constraints = statement.get('constraints') + if _constraints is None: + _constraints = Constraints() + else: + current_max_path_length = calculate_path_length(_constraints, current_max_path_length, _assigned) + _assigned = True if current_max_path_length < 0: return False diff --git a/src/fedservice/entity_statement/create.py b/src/fedservice/entity_statement/create.py index b66e646a..00e66836 100644 --- a/src/fedservice/entity_statement/create.py +++ b/src/fedservice/entity_statement/create.py @@ -7,9 +7,39 @@ logger = logging.getLogger(__name__) -def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=None, - authority_hints=None, lifetime=86400, aud='', include_jwks=True, - constraints=None, signing_alg: Optional[str] = "RS256", **kwargs): +def create_entity_statement(iss, sub, key_jar, lifetime=86400, include_jwks=True, + signing_alg: Optional[str] = "RS256", **kwargs): + """ + + :param iss: The issuer of the signed JSON Web Token + :param sub: The subject which the metadata describes + :param key_jar: A KeyJar instance + :param lifetime: The lifetime of the signed JWT. + :param include_jwks: Add JWKS + :param signing_alg: Which signing algorithm that should be used + :param kwargs: Additional arguments for the JSON object + :return: A signed JSON Web Token + """ + + msg = {'sub': sub} + + if kwargs: + msg.update(kwargs) + + if include_jwks: + if "jwks" in kwargs: + msg['jwks'] = kwargs['jwks'] + else: + # The public signing keys of the subject + msg['jwks'] = key_jar.export_jwks() + + packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime, sign_alg=signing_alg) + return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) + + +def create_entity_configuration(iss, key_jar, metadata=None, + authority_hints=None, lifetime=86400, include_jwks=True, + signing_alg: Optional[str] = "RS256", **kwargs): """ :param iss: The issuer of the signed JSON Web Token @@ -17,23 +47,16 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No :param key_jar: A KeyJar instance :param metadata: The entity's metadata organised as a dictionary with the entity type as key - :param metadata_policy: Metadata policy - :param authority_hints: A dictionary with immediate superiors in the - trust chains as keys and lists of identifier of trust roots as values. :param lifetime: The lifetime of the signed JWT. - :param aud: Possible audience for the JWT :param include_jwks: Add JWKS - :param constraints: A dictionary with constraints. :param signing_alg: Which signing algorithm that should be used :return: A signed JSON Web Token """ - msg = {'sub': sub} - if metadata: - msg['metadata'] = metadata + msg = {} - if metadata_policy: - msg['metadata_policy'] = metadata_policy + if metadata: + msg["metadata"] = metadata if authority_hints: if isinstance(authority_hints, Callable): @@ -41,21 +64,33 @@ def create_entity_statement(iss, sub, key_jar, metadata=None, metadata_policy=No else: msg['authority_hints'] = authority_hints - if aud: - msg['aud'] = aud + if kwargs: + msg.update(kwargs) + + return create_entity_statement(iss, iss, key_jar, lifetime=lifetime, include_jwks=include_jwks, + signing_alg=signing_alg, **msg) + + +def create_subordinate_statement(iss, sub, key_jar, lifetime=86400, include_jwks=True, constraints=None, + signing_alg: Optional[str] = "RS256", **kwargs): + """ + + :param iss: The issuer of the signed JSON Web Token + :param sub: The subject which the metadata describes + :param key_jar: A KeyJar instance + :param lifetime: The lifetime of the signed JWT. + :param include_jwks: Add JWKS + :param signing_alg: Which signing algorithm that should be used + :return: A signed JSON Web Token + """ if constraints: - msg['constraints'] = constraints + msg = {'constraints': constraints} + else: + msg = {} if kwargs: msg.update(kwargs) - if include_jwks: - if "jwks" in kwargs: - msg['jwks'] = kwargs['jwks'] - else: - # The public signing keys of the subject - msg['jwks'] = key_jar.export_jwks() - - packer = JWT(key_jar=key_jar, iss=iss, lifetime=lifetime, sign_alg=signing_alg) - return packer.pack(payload=msg, jws_headers={'typ': "entity-statement+jwt"}) + return create_entity_statement(iss, sub, key_jar, lifetime=lifetime, include_jwks=include_jwks, + signing_alg=signing_alg, **msg) diff --git a/src/fedservice/fetch_entity_statement/__init__.py b/src/fedservice/fetch_entity_statement/__init__.py index 21e3ef29..928993bf 100644 --- a/src/fedservice/fetch_entity_statement/__init__.py +++ b/src/fedservice/fetch_entity_statement/__init__.py @@ -2,10 +2,11 @@ from cryptojwt import KeyJar -from fedservice.entity_statement.create import create_entity_statement +from fedservice.entity_statement.create import create_subordinate_statement class FetchEntityStatement: + def __init__(self, iss, entity_id_pattern): self.iss = iss self.keyjar = KeyJar() @@ -30,8 +31,8 @@ def create_entity_statement(self, sub, **kwargs): _info.update(kwargs) _info['jwks'] = self.keyjar.export_jwks(issuer_id=self.make_entity_id(sub)) if sub.startswith("https"): - return create_entity_statement(self.make_entity_id(self.iss), unquote_plus(sub), - self.keyjar, **_info) + return create_subordinate_statement(self.make_entity_id(self.iss), unquote_plus(sub), + self.keyjar, **_info) - return create_entity_statement(self.make_entity_id(self.iss), self.make_entity_id(sub), - self.keyjar, **_info) + return create_subordinate_statement(self.make_entity_id(self.iss), self.make_entity_id(sub), + self.keyjar, **_info) diff --git a/src/fedservice/message.py b/src/fedservice/message.py index 06386ef8..f011fcdd 100644 --- a/src/fedservice/message.py +++ b/src/fedservice/message.py @@ -492,26 +492,16 @@ class EntityStatement(JsonWebToken): """The Entity Statement""" c_param = JsonWebToken.c_param.copy() c_param.update({ - "sub": SINGLE_REQUIRED_STRING, 'iss': SINGLE_REQUIRED_STRING, - 'exp': SINGLE_REQUIRED_INT, + 'sub': SINGLE_REQUIRED_STRING, 'iat': SINGLE_REQUIRED_INT, + 'exp': SINGLE_REQUIRED_INT, 'jwks': SINGLE_OPTIONAL_DICT, - 'aud': SINGLE_OPTIONAL_STRING, - "jti": SINGLE_OPTIONAL_STRING, - 'authority_hints': OPTIONAL_LIST_OF_STRINGS, +# 'aud': SINGLE_OPTIONAL_STRING, +# "jti": SINGLE_OPTIONAL_STRING, 'metadata': SINGLE_OPTIONAL_METADATA, - 'metadata_policy': SINGLE_OPTIONAL_METADATA_POLICY, - 'metadata_policy_crit': OPTIONAL_LIST_OF_STRINGS, - 'constraints': SINGLE_OPTIONAL_CONSTRAINS, "crit": OPTIONAL_LIST_OF_STRINGS, - "policy_language_crit": OPTIONAL_LIST_OF_STRINGS, - "source_endpoint": SINGLE_OPTIONAL_STRING, - 'trust_marks': OPTIONAL_LIST_OF_DICT, - 'trust_mark_owners': SINGLE_OPTIONAL_JSON, - 'trust_mark_issuers': SINGLE_OPTIONAL_JSON, - # - 'trust_anchor': SINGLE_OPTIONAL_STRING +# "policy_language_crit": OPTIONAL_LIST_OF_STRINGS, }) def verify(self, **kwargs): @@ -533,12 +523,20 @@ def verify(self, **kwargs): else: raise UnknownCriticalExtension(_musts.intersection(_extra_parameters)) - _metadata_policy = self.get('metadata_policy') - if _metadata_policy: - _crit = self.get("policy_language_crit") - if _crit: - _metadata_policy.verify(policy_language_crit=_crit, **kwargs) +class EntityConfiguration(EntityStatement): + c_param = EntityStatement.c_param.copy() + c_param.update({ + 'authority_hints': OPTIONAL_LIST_OF_STRINGS, + 'trust_marks': OPTIONAL_LIST_OF_DICT, + 'trust_mark_owners': SINGLE_OPTIONAL_JSON, + 'trust_mark_issuers': SINGLE_OPTIONAL_JSON, + # + 'trust_anchor': SINGLE_OPTIONAL_STRING + }) + + def verify(self, **kwargs): + super(EntityConfiguration, self).verify(**kwargs) _trust_mark_issuers = self.get("trust_mark_issuers") if _trust_mark_issuers: _tmi = TrustMarkIssuers(**_trust_mark_issuers) @@ -569,6 +567,23 @@ def verify(self, **kwargs): _trust_mark.verify() +class SubordinateStatement(EntityStatement): + c_param = EntityStatement.c_param.copy() + c_param.update({ + 'constraints': SINGLE_OPTIONAL_CONSTRAINS, + 'metadata_policy': SINGLE_OPTIONAL_METADATA_POLICY, + 'metadata_policy_crit': OPTIONAL_LIST_OF_STRINGS, + "source_endpoint": SINGLE_OPTIONAL_STRING, + }) + + def verify(self, **kwargs): + super(SubordinateStatement, self).verify(**kwargs) + _metadata_policy = self.get('metadata_policy') + if _metadata_policy: + _crit = self.get("policy_language_crit") + if _crit: + _metadata_policy.verify(policy_language_crit=_crit, **kwargs) + class TrustMarkDelegation(Message): c_param = { diff --git a/tests/__init__.py b/tests/__init__.py index 99c89206..48da5f1b 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -36,6 +36,7 @@ def create_trust_chain_messages(leaf, *entity): _endpoint = get_federation_entity(leaf).server.get_endpoint('entity_configuration') where_and_what[_endpoint.full_path] = _endpoint.process_request({})["response"] + # now for each intermediate up to the trust anchor for n in range(0, len(entity)): ent = entity[n] if isinstance(ent, FederationEntity): @@ -43,10 +44,11 @@ def create_trust_chain_messages(leaf, *entity): else: # A Combo _entity = ent['federation_entity'] + # First the entity configuration for the entity _endpoint = _entity.server.get_endpoint('entity_configuration') - where_and_what[_endpoint.full_path] = _endpoint.process_request({})["response"] + # then for the subordinate statement _endpoint = _entity.server.get_endpoint('fetch') if n == 0: if isinstance(leaf, str): diff --git a/tests/test_01_message.py b/tests/test_01_message.py index 19c4555b..bdb9e06a 100644 --- a/tests/test_01_message.py +++ b/tests/test_01_message.py @@ -4,6 +4,8 @@ from cryptojwt.jwt import utc_time_sans_frac from fedservice.message import EntityStatement +from fedservice.message import SubordinateStatement +from fedservice.message import EntityConfiguration from fedservice.message import FederationEntity from fedservice.message import JWKSet from fedservice.message import TrustMark @@ -17,10 +19,10 @@ def full_path(local_file): return os.path.join(BASE_PATH, local_file) -def test_entity_statement(): - file = full_path("document_examples/entity_statement_jwt.json") +def test_subordinate_statement(): + file = full_path("document_examples/subordinate_statement_jwt.json") _data = json.loads(open(file, "r").read()) - _msg = EntityStatement().from_dict(_data) + _msg = SubordinateStatement().from_dict(_data) _now = utc_time_sans_frac() # Set expiration time to some time in the future _msg["exp"] = _now + 100 @@ -44,7 +46,7 @@ def test_trust_entity_statement_comb(): def test_entity_statement_comb(): - file_1 = full_path("document_examples/entity_statement_jwt.json") + file_1 = full_path("document_examples/entity_configuration_jwt.json") _data = json.loads(open(file_1, "r").read()) file_2 = full_path("document_examples/trust_mark_owners.json") _data_2 = json.loads(open(file_2, "r").read()) @@ -53,7 +55,7 @@ def test_entity_statement_comb(): _data_3 = json.loads(open(file_3, "r").read()) _data["trust_mark_issuers"] = _data_3 - _msg = EntityStatement().from_dict(_data) + _msg = EntityConfiguration().from_dict(_data) _now = utc_time_sans_frac() # Set expiration time to some time in the future _msg["exp"] = _now + 100 diff --git a/tests/test_05_constraints.py b/tests/test_05_constraints.py index e59d9aec..eb003cb6 100644 --- a/tests/test_05_constraints.py +++ b/tests/test_05_constraints.py @@ -1,5 +1,5 @@ -from cryptojwt.jwt import utc_time_sans_frac import pytest +from cryptojwt.jwt import utc_time_sans_frac from fedservice.entity_statement.constraints import calculate_path_length from fedservice.entity_statement.constraints import excluded @@ -9,42 +9,39 @@ from fedservice.message import Constraints from fedservice.message import EntityStatement from fedservice.message import NamingConstraints - - -def test_max_path_length_start(): +from fedservice.message import SubordinateStatement + + +# def test_max_path_length_start(): +# current_max_path_length = 0 +# max_assigned = False +# constraints = Constraints(max_path_length=1) +# current_max_path_length = calculate_path_length(constraints, current_max_path_length, +# max_assigned) +# assert current_max_path_length == 1 + +@pytest.mark.parametrize( + "sequence, path_len", + [ + ([2, 1, -1], 0), + ([4, 2, -1], 1), + ([4, -1, 2], 2), + ([1, -1, -1], -1) + ] +) +def test_max_path_length_1(sequence, path_len): current_max_path_length = 0 - max_assigned = False - constraints = Constraints(max_path_length=1) - current_max_path_length = calculate_path_length(constraints, current_max_path_length, - max_assigned) - assert current_max_path_length == 1 - - -def test_max_path_length_decrease(): - current_max_path_length = 2 - max_assigned = True - constraints = Constraints(max_path_length=1) - current_max_path_length = calculate_path_length(constraints, current_max_path_length, - max_assigned) - assert current_max_path_length == 1 + assigned = False + for i in sequence: + if i >= 0: + constraints = Constraints(max_path_length=i) + current_max_path_length = calculate_path_length(constraints, current_max_path_length, assigned) + assigned = True + else : + constraints = Constraints() + current_max_path_length = calculate_path_length(constraints, current_max_path_length, assigned) - -def test_max_path_length_ignore(): - current_max_path_length = 2 - max_assigned = True - constraints = Constraints(max_path_length=3) - current_max_path_length = calculate_path_length(constraints, current_max_path_length, - max_assigned) - assert current_max_path_length == 1 - - -def test_max_path_length_no(): - current_max_path_length = 2 - max_assigned = True - constraints = Constraints() - current_max_path_length = calculate_path_length(constraints, current_max_path_length, - max_assigned) - assert current_max_path_length == 1 + assert current_max_path_length == path_len def test_naming_constr_1(): @@ -260,8 +257,8 @@ def test_crit_known_unknown_not_critical(): def test_crit_critical_not_supported(): entity_id = "https://ent.example.org" _now = utc_time_sans_frac() - _statement = EntityStatement(sub=entity_id, iss=entity_id, iat=_now, exp=_now + 3600, - foo="bar", crit=["foo"]) + _statement = SubordinateStatement(sub=entity_id, iss=entity_id, iat=_now, exp=_now + 3600, + foo="bar", crit=["foo"]) with pytest.raises(UnknownCriticalExtension): _statement.verify(known_extensions=["xyz"]) @@ -296,8 +293,7 @@ def test_crit_critical_not_supported(): def test_policy_language_crit_not_supported(): _now = utc_time_sans_frac() - _statement = EntityStatement(iat=_now, exp=_now + 3600, **MSG) - + _statement = SubordinateStatement(iat=_now, exp=_now + 3600, **MSG) _statement.verify(known_policy_extensions=["regexp"]) with pytest.raises(UnknownCriticalExtension): diff --git a/tests/test_06_claims.py b/tests/test_06_claims.py index f9a341e7..53b0755c 100644 --- a/tests/test_06_claims.py +++ b/tests/test_06_claims.py @@ -142,7 +142,7 @@ def test(self): 'userinfo_signed_response_alg'} # IN this case the Combo has no keys, The federation entity and the openid relying party has - # separate key jars. Same initial key owner IDs in both keyjars. + # separate key jars. Same initial key owner IDs in both key jars. assert self.combo.keyjar is None for _name, _item in self.combo._part.items(): assert set(_item.keyjar.owners()) == {'', 'https://anchor.example.com'} diff --git a/tests/test_10_explicit_registration_oidc.py b/tests/test_10_explicit_registration_oidc.py index e989a352..d17b50cc 100644 --- a/tests/test_10_explicit_registration_oidc.py +++ b/tests/test_10_explicit_registration_oidc.py @@ -144,12 +144,10 @@ def test_create_reqistration_request(self): assert jws _sc = self.registration_service.upstream_get("context") - self.registration_service.endpoint = _sc.get_metadata_claim( - "federation_registration_endpoint") + self.registration_service.endpoint = _sc.get_metadata_claim("federation_registration_endpoint") # construct the information needed to send the request - _info = self.registration_service.get_request_parameters( - request_body_type="jose", method="POST") + _info = self.registration_service.get_request_parameters(request_body_type="jose", method="POST") assert set(_info.keys()) == {"method", "url", "body", "headers", "request"} assert _info["method"] == "POST" diff --git a/tests/test_40_fe.py b/tests/test_40_fe.py index 45ca6065..a307a0df 100644 --- a/tests/test_40_fe.py +++ b/tests/test_40_fe.py @@ -116,8 +116,7 @@ def test_server(self): _resp_args = _endpoint.process_request(_req) _jwt = factory(_resp_args['response']) payload = _jwt.jwt.payload() - assert set(payload.keys()) == {'exp', 'jwks', 'sub', 'iat', - 'metadata', 'iss', 'authority_hints'} + assert set(payload.keys()) == {'exp', 'jwks', 'sub', 'iat', 'metadata', 'iss', 'authority_hints'} assert payload["iss"] == payload["sub"] assert set(payload['metadata'].keys()) == {'federation_entity'} # Full set of endpoints @@ -141,8 +140,7 @@ def test_fetch(self): _resp_args = _endpoint.process_request(_req) _jwt = factory(_resp_args['response_msg']) payload = _jwt.jwt.payload() - assert set(payload.keys()) == {'exp', 'jwks', 'sub', 'iat', - 'metadata_policy', 'iss', 'authority_hints'} + assert set(payload.keys()) == {'exp', 'jwks', 'sub', 'iat', 'metadata_policy', 'iss'} assert payload["iss"] == ENTITY_ID assert payload["sub"] == CHILD_ID assert set(payload['metadata_policy'].keys()) == {'openid_provider'} diff --git a/tests/test_53_publish_assigned_trust_mark.py b/tests/test_53_publish_assigned_trust_mark.py index ae7aaf38..99339abd 100644 --- a/tests/test_53_publish_assigned_trust_mark.py +++ b/tests/test_53_publish_assigned_trust_mark.py @@ -95,7 +95,8 @@ def test_federation_combo_metadata(): assert set(metadata.keys()) == {"openid_relying_party", "federation_entity"} assert entity["federation_entity"].context.trust_marks srv = entity["openid_relying_party"].get_service('registration') - jws = srv.create_entity_statement() + key_jar = entity['federation_entity'].keyjar + jws = srv.create_entity_configuration(entity.entity_id, key_jar=key_jar) assert jws _jws = factory(jws) _payload = _jws.jwt.payload() From 0e3fafda910f07912f237a573777b4233637871b Mon Sep 17 00:00:00 2001 From: roland Date: Fri, 31 Oct 2025 08:56:24 +0100 Subject: [PATCH 40/43] Clearer log message --- src/fedservice/appclient/oauth2/registration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index d7100783..883634a3 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -67,7 +67,7 @@ def parse_federation_registration_response(service, resp): _trust_anchor = payload.get("trust_anchor") logger.debug(f"trust_anchor(_id): {_trust_anchor}") if _trust_anchor not in federation_entity.function.trust_chain_collector.trust_anchors: - raise ValueError("Trust anchor I don't trust") + raise ValueError("OP chose Trust Anchor I don't trust") # This is where I should decide to use the metadata verification service or do it # all myself From d2df7490db2948007bc78d28390c393b6c57c32f Mon Sep 17 00:00:00 2001 From: YoNick Mastoris Date: Thu, 26 Jun 2025 09:01:55 +0000 Subject: [PATCH 41/43] replace trust_anchor_id with trust_anchor --- src/fedservice/appclient/oidc/registration.py | 6 +++--- src/fedservice/appserver/oauth2/registration.py | 2 +- src/fedservice/entity/function/trust_mark_verifier.py | 4 ++-- tests/xtest_13_explicit_registration_oauth.py | 2 +- tests/xtest_57_metadata_verification.py | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 6e7406e6..71159a53 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -82,7 +82,7 @@ def parse_response(self, info, sformat="", state="", **kwargs): return resp - def _get_trust_anchor_id(self, entity_statement): + def _get_trust_anchor(self, entity_statement): return entity_statement.get('trust_anchor') def parse_federation_registration_response(self, resp, **kwargs): @@ -102,7 +102,7 @@ def parse_federation_registration_response(self, resp, **kwargs): # Do I trust the TA the OP chose ? _trust_anchor = payload['trust_anchor'] - logger.debug(f"trust_anchor_id: {_trust_anchor}") + logger.debug(f"trust_anchor: {_trust_anchor}") if _trust_anchor not in _federation_entity.function.trust_chain_collector.trust_anchors: raise ValueError("Trust anchor I don't trust") @@ -188,4 +188,4 @@ def parse_federation_registration_response(self, resp, **kwargs): # # _client_secret = _context.claims.get_usage("client_secret") # _context.keyjar.add_symmetric("", _client_secret) - # _context.keyjar.add_symmetric(_client_id, _client_secret) + # _context.keyjar.add_symmetric(_client_id, _client_secret) \ No newline at end of file diff --git a/src/fedservice/appserver/oauth2/registration.py b/src/fedservice/appserver/oauth2/registration.py index 92bfb95a..6ac18a99 100644 --- a/src/fedservice/appserver/oauth2/registration.py +++ b/src/fedservice/appserver/oauth2/registration.py @@ -429,4 +429,4 @@ def create_entity_statement(response_args, request, context, def non_fed_process_request(self, req, **kwargs): # handle the registration request as in the non-federation case. - return registration.Registration.process_request(self, req, authn=None, **kwargs) + return registration.Registration.process_request(self, req, authn=None, **kwargs) \ No newline at end of file diff --git a/src/fedservice/entity/function/trust_mark_verifier.py b/src/fedservice/entity/function/trust_mark_verifier.py index fd9f9558..a9822c0d 100644 --- a/src/fedservice/entity/function/trust_mark_verifier.py +++ b/src/fedservice/entity/function/trust_mark_verifier.py @@ -156,11 +156,11 @@ def __call__(self, else: return _mark - def verify_delegation(self, trust_mark, trust_anchor_id): + def verify_delegation(self, trust_mark, trust_anchor): _federation_entity = get_federation_entity(self) _collector = _federation_entity.function.trust_chain_collector # Deal with the delegation - _entity_configuration = _collector.get_verified_self_signed_entity_configuration(trust_anchor_id) + _entity_configuration = _collector.get_verified_self_signed_entity_configuration(trust_anchor) if trust_mark['trust_mark_id'] not in _entity_configuration['trust_mark_issuers']: return None diff --git a/tests/xtest_13_explicit_registration_oauth.py b/tests/xtest_13_explicit_registration_oauth.py index 4d06f44d..12569a3d 100644 --- a/tests/xtest_13_explicit_registration_oauth.py +++ b/tests/xtest_13_explicit_registration_oauth.py @@ -250,7 +250,7 @@ def test_registration_verification(self): _payload = _jws.jwt.payload() assert _payload['iss'] == self.oauth_serv.entity_id assert _payload['sub'] == self.rp.entity_id - assert _payload['trust_anchor_id'] == self.ta.entity_id + assert _payload['trust_anchor'] == self.ta.entity_id assert _payload['aud'] == self.rp.entity_id ########################################################################### diff --git a/tests/xtest_57_metadata_verification.py b/tests/xtest_57_metadata_verification.py index b6ac6ce8..2d0126c2 100644 --- a/tests/xtest_57_metadata_verification.py +++ b/tests/xtest_57_metadata_verification.py @@ -260,7 +260,7 @@ def test_registration_verification(self): _payload = _jws.jwt.payload() assert _payload['iss'] == self.op.entity_id assert _payload['sub'] == self.rp.entity_id - assert _payload['trust_anchor_id'] == self.ta.entity_id + assert _payload['trust_anchor'] == self.ta.entity_id assert _payload['aud'] == self.rp.entity_id ########################################################################### From 2df50207c123da5ac32a31ef82bee63611258ebb Mon Sep 17 00:00:00 2001 From: Nick Mastoris Date: Fri, 9 Jan 2026 09:43:59 +0200 Subject: [PATCH 42/43] add more naming --- src/fedservice/appclient/oauth2/registration.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fedservice/appclient/oauth2/registration.py b/src/fedservice/appclient/oauth2/registration.py index 883634a3..7e5d1a0f 100644 --- a/src/fedservice/appclient/oauth2/registration.py +++ b/src/fedservice/appclient/oauth2/registration.py @@ -218,5 +218,5 @@ def parse_response(self, info, sformat="", state="", **kwargs): return resp - def _get_trust_anchor_id(self, entity_statement): + def _get_trust_anchor(self, entity_statement): return entity_statement.get('trust_anchor') From 415ed72cfe0b3ea778b0a21040f52ba5dcdf84b5 Mon Sep 17 00:00:00 2001 From: Nick Mastoris Date: Fri, 9 Jan 2026 09:48:48 +0200 Subject: [PATCH 43/43] minor fixes --- src/fedservice/appclient/oidc/registration.py | 2 +- src/fedservice/appserver/oauth2/registration.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/fedservice/appclient/oidc/registration.py b/src/fedservice/appclient/oidc/registration.py index 71159a53..1e3e91c1 100644 --- a/src/fedservice/appclient/oidc/registration.py +++ b/src/fedservice/appclient/oidc/registration.py @@ -188,4 +188,4 @@ def parse_federation_registration_response(self, resp, **kwargs): # # _client_secret = _context.claims.get_usage("client_secret") # _context.keyjar.add_symmetric("", _client_secret) - # _context.keyjar.add_symmetric(_client_id, _client_secret) \ No newline at end of file + # _context.keyjar.add_symmetric(_client_id, _client_secret) diff --git a/src/fedservice/appserver/oauth2/registration.py b/src/fedservice/appserver/oauth2/registration.py index 6ac18a99..92bfb95a 100644 --- a/src/fedservice/appserver/oauth2/registration.py +++ b/src/fedservice/appserver/oauth2/registration.py @@ -429,4 +429,4 @@ def create_entity_statement(response_args, request, context, def non_fed_process_request(self, req, **kwargs): # handle the registration request as in the non-federation case. - return registration.Registration.process_request(self, req, authn=None, **kwargs) \ No newline at end of file + return registration.Registration.process_request(self, req, authn=None, **kwargs)