From 8b7269c00a51cf23a89524e506fd1298c7bdd2a4 Mon Sep 17 00:00:00 2001 From: Johan Wassberg Date: Fri, 27 Nov 2026 09:16:20 +0100 Subject: [PATCH] Add inherit_entity_attributes source flag for group-level entity attributes A load resource can now carry the inherit_entity_attributes flag, off by default. If on the group's values are merged into each entity's attribute with the same Name and NameFormat. Closes #285 --- src/pyff/builtins.py | 35 ++- src/pyff/resource.py | 2 + src/pyff/samlmd.py | 131 ++++++++- .../test/test_inherit_entity_attributes.py | 265 ++++++++++++++++++ 4 files changed, 427 insertions(+), 6 deletions(-) create mode 100644 src/pyff/test/test_inherit_entity_attributes.py diff --git a/src/pyff/builtins.py b/src/pyff/builtins.py index 63e6efc4..69d40861 100644 --- a/src/pyff/builtins.py +++ b/src/pyff/builtins.py @@ -689,7 +689,7 @@ def load(req: Plumbing.Request, *opts): .. code-block:: text - [as ] [verify ] [via ]* [cleanup ]* + [as ] [verify ] [via ]* [cleanup ]* [inherit_entity_attributes] - ``as``: name the resource, e.g. to refer to it in later pipeline steps. - ``verify``: check the XML signature of the resource, using either a PEM certificate file or a SHA-1 @@ -701,6 +701,34 @@ def load(req: Plumbing.Request, *opts): - ``via``: name of a ``when`` clause in the same pipeline that is applied to the loaded metadata, for example to remove entities with ``fork merge remove``. - ``cleanup``: name of a ``when`` clause used to pre-process the parsed metadata before it is validated. + - ``inherit_entity_attributes``: a flag, off unless given, and unlike the keywords above it takes no argument. + Entity attributes in ``md:EntitiesDescriptor/md:Extensions`` are bound to every entity in that group + (sstc-metadata-attr-cs-01, 2.3), but pyFF keeps only the entities, so they are lost by default. With this + flag they are merged into each entity as the resource is parsed. For an attribute with the same ``Name`` + and ``NameFormat`` the group's values are added to the entity's own, which stay first, and values the + entity already has are not repeated; other attributes are added as they are. The attributes of every + enclosing ``md:EntitiesDescriptor`` apply to an entity, and a ``saml:Assertion`` there, which the + specification does not allow, is ignored. It applies to one resource only, so the attributes of one + aggregate never reach the entities of another. It is passed on to the resources found by a directory, + XRD or MDSL resource, and the word is reserved: it is not a ``verify`` value. For example: + + .. code-block:: yaml + + - load: + - http://example.com/aggregate.xml as AGG inherit_entity_attributes + - http://example.com/other.xml + + .. warning:: + + Every entity gets its own copy of the group's attributes, so the metadata grows by the size of + those attributes times the number of entities, plus a small wrapper for each entity that had no + entity attributes before. The entities of a large aggregate are many, so the result can be much + larger than the input: in a test, 5000 minimal entities and a group attribute with two values grew + the published feed from 2.6 MB to 4.7 MB (about 420 bytes per entity). This costs memory in pyFF + and time when signing, publishing and fetching, and every consumer has to parse the larger + document. Turn it on only for aggregates whose group attributes you need on each entity, keep the + group's attributes few and short, and check the size of the result. pyFF logs how many values it + added to how many entities. A resource may also be an XRD or eIDAS MDSL file listing metadata URLs. Each listed URL is loaded and verified with the certificates given for it in the file, as if with ``verify``; any one of them is accepted, so a key @@ -738,7 +766,10 @@ def load(req: Plumbing.Request, *opts): while len(r) > 0: elt = r.pop(0) - if elt in ("as", "verify", "via", "cleanup"): + if elt == "inherit_entity_attributes": + # a flag, so unlike the keywords below it has no argument + child_opts.inherit_entity_attributes = True + elif elt in ("as", "verify", "via", "cleanup"): # These elements have an argument if len(r) > 0: value = r.pop(0) diff --git a/src/pyff/resource.py b/src/pyff/resource.py index 5d620779..d6cee801 100644 --- a/src/pyff/resource.py +++ b/src/pyff/resource.py @@ -218,6 +218,8 @@ class ResourceOpts(BaseModel): # set to False to turn off all XML schema validation validate_schema: bool = Field(True, alias='validate') verify_tls: bool = False + # merge the entity attributes of md:EntitiesDescriptor/md:Extensions into every entity of the group + inherit_entity_attributes: bool = False model_config = ConfigDict(arbitrary_types_allowed=True) @field_validator('verify', mode='before') diff --git a/src/pyff/samlmd.py b/src/pyff/samlmd.py index f5584ec2..0796650f 100644 --- a/src/pyff/samlmd.py +++ b/src/pyff/samlmd.py @@ -128,6 +128,13 @@ def parse_saml_metadata( t = root(t) + if opts.inherit_entity_attributes and t.tag == "{{{}}}EntitiesDescriptor".format(NS['md']): + added = inherit_entity_attributes(t) # before validation, so that what is added is validated too + log.info( + f"{base_url}: inherit_entity_attributes added {added} attribute values " + f"to {len(list(iter_entities(t)))} entities" + ) + filter_invalid = opts.filter_invalid if opts.fail_on_error: filter_invalid = False @@ -1315,8 +1322,16 @@ def entity_extensions(e): """ ext = e.find("./{{{}}}Extensions".format(NS['md'])) if ext is None: - ext = etree.Element("{{{}}}Extensions".format(NS['md'])) - e.insert(0, ext) + position = 0 + for i, child in enumerate(e): + if child.tag == "{{{}}}Signature".format(NS['ds']): + position = i + 1 # the schema puts Extensions after an enveloped signature + break + # Create it in place, then move it: an element created on its own is serialized with a + # namespace declaration of its own, while one created under its parent reuses the parent's. + ext = etree.SubElement(e, "{{{}}}Extensions".format(NS['md'])) + e.remove(ext) + e.insert(position, ext) return ext @@ -1363,8 +1378,7 @@ def _entity_attributes(e): ext = entity_extensions(e) ea = ext.find(".//{{{}}}EntityAttributes".format(NS['mdattr'])) if ea is None: - ea = etree.Element("{{{}}}EntityAttributes".format(NS['mdattr'])) - ext.append(ea) + ea = etree.SubElement(ext, "{{{}}}EntityAttributes".format(NS['mdattr'])) return ea @@ -1387,6 +1401,115 @@ def _eattribute(e, attr, nf): return a +def _group_attributes(group): + """The saml:Attribute elements an md:EntitiesDescriptor binds to the entities in it.""" + ext = group.find("./{{{}}}Extensions".format(NS['md'])) + if ext is None: + return [] + ea = ext.find("./{{{}}}EntityAttributes".format(NS['mdattr'])) + if ea is None: + return [] + attribute = "{{{}}}Attribute".format(NS['saml']) + assertion = "{{{}}}Assertion".format(NS['saml']) + found = [] + for child in ea: + if child.tag == attribute: + found.append(child) + elif child.tag == assertion: + log.warning(f"ignoring saml:Assertion in the Extensions of EntitiesDescriptor {group.get('Name')}") + return found + + +def _value_key(value): + """What makes two saml:AttributeValue elements the same value.""" + if len(list(value)) == 0: + return value.text or "", tuple(sorted(value.attrib.items())) + return dumptree(value, xml_declaration=False) + + +def _merge_attribute(entity, source): + """ + Merge the values of the saml:Attribute ``source`` into the attribute of ``entity`` with the same Name and + NameFormat, creating it if the entity has none. Values the entity already has are not added again. + + :return: the number of values added + """ + values = source.findall("./{{{}}}AttributeValue".format(NS['saml'])) + if not values: + return 0 + + saml_attribute = "{{{}}}Attribute".format(NS['saml']) + saml_value = "{{{}}}AttributeValue".format(NS['saml']) + name, nf = source.get('Name'), source.get('NameFormat') + + ea = _entity_attributes(entity) + target = None + for a in ea.iter(saml_attribute): + if a.get('Name') == name and a.get('NameFormat') == nf: + target = a + break + + present = set() if target is None else {_value_key(v) for v in target.findall(f"./{saml_value}")} + added = 0 + for value in values: + key = _value_key(value) + if key in present: + continue + if target is None: + target = etree.SubElement(ea, saml_attribute) + if name is not None: + target.set('Name', name) + if nf is not None: + target.set('NameFormat', nf) + if len(list(value)) == 0 and len(value.attrib) == 0: + # A plain value is made in place, which keeps the document small: a copy would repeat + # the namespace declarations it was parsed with. Anything else may use a prefix declared + # where it was parsed (xsi:type="xs:string"), so it is copied as it is. + etree.SubElement(target, saml_value).text = value.text + else: + target.append(deepcopy(value)) + present.add(key) + added += 1 + return added + + +def inherit_entity_attributes(t): + """ + Merge the entity attributes of every md:EntitiesDescriptor into the entities below it. + + The attributes in md:EntitiesDescriptor/md:Extensions are bound to each md:EntityDescriptor within the + group (sstc-metadata-attr-cs-01, 2.3). The attributes of every enclosing group apply to an entity. For each + attribute with the same Name and NameFormat the group's values are added to the entity's own, which stay + first; values the entity already has are not repeated. Other attributes are added as they are. + + This copies the group's attributes into every entity, so the document grows by about the size of the + attributes times the number of entities. + + :param t: an md:EntitiesDescriptor (or a tree with one as root), modified in place + :return: the number of attribute values added to entities + """ + t = root(t) + if t.tag != "{{{}}}EntitiesDescriptor".format(NS['md']): + return 0 + + entity = "{{{}}}EntityDescriptor".format(NS['md']) + group = "{{{}}}EntitiesDescriptor".format(NS['md']) + added = 0 + + def _walk(node, inherited): + nonlocal added + attributes = inherited + _group_attributes(node) + for child in node: + if child.tag == entity: + for attribute in attributes: + added += _merge_attribute(child, attribute) + elif child.tag == group: + _walk(child, attributes) + + _walk(t, []) + return added + + def set_entity_attributes(e, d, nf=NF_URI): """Set an entity attribute on an EntityDescriptor diff --git a/src/pyff/test/test_inherit_entity_attributes.py b/src/pyff/test/test_inherit_entity_attributes.py new file mode 100644 index 00000000..110f7e3e --- /dev/null +++ b/src/pyff/test/test_inherit_entity_attributes.py @@ -0,0 +1,265 @@ +""" +The ``inherit_entity_attributes`` source option (#285). + +Entity attributes in md:EntitiesDescriptor/md:Extensions are bound to every md:EntityDescriptor in +that group. With the option on, they are merged into each entity as the source is parsed. +""" + +import logging +import os +import shutil +import tempfile +from io import BytesIO +from unittest import TestCase + +from pyff.constants import NS +from pyff.samlmd import inherit_entity_attributes, iter_entities +from pyff.test.test_pipeline import PipeLineTest +from pyff.utils import dumptree, parse_xml, root + +CATEGORY = "http://macedir.org/entity-category-support" +RS = "http://refeds.org/category/research-and-scholarship" +OWN = "http://own.example.org/category" +NF_URI = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri" +NF_BASIC = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic" + +HEAD = ( + '' +) + + +def _attribute(name, *values, nf=NF_URI): + vals = "".join(f"{v}" for v in values) + return f'{vals}' + + +def _extensions(*attributes): + return f"{''.join(attributes)}" + + +def _idp(entity_id, *attributes): + ext = _extensions(*attributes) if attributes else "" + return ( + f'{ext}' + '' + '' + ) + + +def _sp(entity_id, *attributes): + ext = _extensions(*attributes) if attributes else "" + return ( + f'{ext}' + '' + '' + ) + + +def _group(name, group_attributes, *members): + ext = _extensions(*group_attributes) if group_attributes else "" + return f"{HEAD.format(name=name)}{ext}{''.join(members)}" + + +def _tree(xml): + return root(parse_xml(BytesIO(xml.encode("utf-8")))) + + +def _attributes(entity): + """{(Name, NameFormat): [[values of the first such attribute element], [values of the second], ...]}""" + found = {} + for a in entity.iter(f"{{{NS['saml']}}}Attribute"): + values = [v.text for v in a.findall(f"{{{NS['saml']}}}AttributeValue")] + found.setdefault((a.get("Name"), a.get("NameFormat")), []).append(values) + return found + + +def _by_id(t): + return {e.get("entityID"): e for e in iter_entities(t)} + + +class InheritFixtures: + def setUp(self): + super().setUp() + self.dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.dir, True) + + def write(self, name, xml): + path = os.path.join(self.dir, name) + with open(path, "w") as fh: + fh.write(xml) + return path + + +class TestInheritFunction(TestCase): + def test_entity_without_attributes_gets_the_groups(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _sp("https://sp"))) + inherit_entity_attributes(t) + assert _attributes(_by_id(t)["https://sp"]) == {(CATEGORY, NF_URI): [[RS]]} + + def test_values_are_merged_into_one_attribute_own_values_first(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _idp("https://idp", _attribute(CATEGORY, OWN)))) + inherit_entity_attributes(t) + assert _attributes(_by_id(t)["https://idp"]) == {(CATEGORY, NF_URI): [[OWN, RS]]} + + def test_value_already_present_is_not_duplicated(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _idp("https://idp", _attribute(CATEGORY, RS, OWN)))) + inherit_entity_attributes(t) + assert _attributes(_by_id(t)["https://idp"]) == {(CATEGORY, NF_URI): [[RS, OWN]]} + + def test_running_twice_changes_nothing(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _idp("https://idp", _attribute(CATEGORY, OWN)))) + inherit_entity_attributes(t) + inherit_entity_attributes(t) + assert _attributes(_by_id(t)["https://idp"]) == {(CATEGORY, NF_URI): [[OWN, RS]]} + + def test_other_name_format_is_a_different_attribute(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _idp("https://idp", _attribute(CATEGORY, OWN, nf=NF_BASIC)))) + inherit_entity_attributes(t) + assert _attributes(_by_id(t)["https://idp"]) == {(CATEGORY, NF_BASIC): [[OWN]], (CATEGORY, NF_URI): [[RS]]} + + def test_every_enclosing_group_applies(self): + inner = _group("inner", [_attribute("urn:y", "Y")], _idp("https://b")) + outer = _group("outer", [_attribute("urn:x", "X")], _idp("https://a"), inner) + t = _tree(outer) + inherit_entity_attributes(t) + got = {k: _attributes(v) for k, v in _by_id(t).items()} + assert got["https://a"] == {("urn:x", NF_URI): [["X"]]} + assert got["https://b"] == {("urn:x", NF_URI): [["X"]], ("urn:y", NF_URI): [["Y"]]} + + def test_typed_value_keeps_the_namespaces_its_type_needs(self): + typed = ( + '' + 'v' + "" + ) + t = _tree(_group("g", [typed], _sp("https://sp"))) + inherit_entity_attributes(t) + out = dumptree(_by_id(t)["https://sp"], xml_declaration=False).decode() + assert 'xsi:type="xs:string"' in out + assert 'xmlns:xs="http://www.w3.org/2001/XMLSchema"' in out # or the type would not resolve + + def test_plain_value_adds_no_namespace_declarations(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _sp("https://sp"))) + inherit_entity_attributes(t) + out = dumptree(_by_id(t)["https://sp"], xml_declaration=False).decode() + assert "ns0:" not in out + assert f"{RS}" in out + + def test_group_without_attributes_changes_nothing(self): + t = _tree(_group("g", [], _sp("https://sp"))) + assert inherit_entity_attributes(t) == 0 + assert _attributes(_by_id(t)["https://sp"]) == {} + + def test_assertions_in_a_group_are_ignored(self): + assertion = '' + t = _tree(_group("g", [assertion, _attribute(CATEGORY, RS)], _sp("https://sp"))) + inherit_entity_attributes(t) + sp = _by_id(t)["https://sp"] + assert _attributes(sp) == {(CATEGORY, NF_URI): [[RS]]} + assert sp.find(f".//{{{NS['saml']}}}Assertion") is None + + def test_extensions_go_after_an_enveloped_signature(self): + sig = '' + sp = _sp("https://sp").replace('entityID="https://sp">', f'entityID="https://sp">{sig}', 1) + t = _tree(_group("g", [_attribute(CATEGORY, RS)], sp)) + inherit_entity_attributes(t) + tags = [c.tag for c in _by_id(t)["https://sp"]] + assert tags[0] == "{http://www.w3.org/2000/09/xmldsig#}Signature" + assert tags[1] == f"{{{NS['md']}}}Extensions" + + def test_the_groups_own_attributes_are_not_modified(self): + t = _tree(_group("g", [_attribute(CATEGORY, RS)], _idp("https://idp", _attribute(CATEGORY, OWN)))) + inherit_entity_attributes(t) + group_ext = t.find(f"{{{NS['md']}}}Extensions") + values = [v.text for v in group_ext.iter(f"{{{NS['saml']}}}AttributeValue")] + assert values == [RS] + + def test_returns_number_of_values_added(self): + t = _tree( + _group("g", [_attribute(CATEGORY, RS)], _sp("https://a"), _idp("https://b", _attribute(CATEGORY, RS))) + ) + assert inherit_entity_attributes(t) == 1 # b already has it + + +class TestInheritInPipeline(InheritFixtures, PipeLineTest): + def _entities(self, res): + return {k: _attributes(v) for k, v in _by_id(res).items()} + + def test_off_by_default(self): + """The reporter's case: nothing is inherited unless the source asks for it.""" + path = self.write( + "a.xml", + _group("a", [_attribute(CATEGORY, RS)], _sp("https://sp"), _idp("https://idp", _attribute(CATEGORY, OWN))), + ) + res, _md = self.exec_pipeline(f"- load:\n - {path}\n- select\n") + got = self._entities(res) + assert got["https://sp"] == {} + assert got["https://idp"] == {(CATEGORY, NF_URI): [[OWN]]} + + def test_on_for_the_source(self): + path = self.write( + "a.xml", + _group("a", [_attribute(CATEGORY, RS)], _sp("https://sp"), _idp("https://idp", _attribute(CATEGORY, OWN))), + ) + res, _md = self.exec_pipeline(f"- load:\n - {path} inherit_entity_attributes\n- select\n") + got = self._entities(res) + assert got["https://sp"] == {(CATEGORY, NF_URI): [[RS]]} + assert got["https://idp"] == {(CATEGORY, NF_URI): [[OWN, RS]]} + + def test_only_the_flagged_source(self): + a = self.write("a.xml", _group("a", [_attribute("urn:a", "A")], _sp("https://a-sp"))) + b = self.write("b.xml", _group("b", [_attribute("urn:b", "B")], _sp("https://b-sp"))) + res, _md = self.exec_pipeline(f"- load:\n - {a} inherit_entity_attributes\n - {b}\n- select\n") + got = self._entities(res) + assert got["https://a-sp"] == {("urn:a", NF_URI): [["A"]]} + assert got["https://b-sp"] == {} + + def test_attributes_do_not_cross_between_flagged_sources(self): + a = self.write("a.xml", _group("a", [_attribute("urn:a", "A")], _sp("https://a-sp"))) + b = self.write("b.xml", _group("b", [_attribute("urn:b", "B")], _sp("https://b-sp"))) + res, _md = self.exec_pipeline( + f"- load:\n - {a} inherit_entity_attributes\n - {b} inherit_entity_attributes\n- select\n" + ) + got = self._entities(res) + assert got["https://a-sp"] == {("urn:a", NF_URI): [["A"]]} + assert got["https://b-sp"] == {("urn:b", NF_URI): [["B"]]} + + def test_flag_works_with_other_keywords(self): + a = self.write("a.xml", _group("a", [_attribute("urn:a", "A")], _sp("https://a-sp"))) + res, _md = self.exec_pipeline(f"- load:\n - {a} as AAA inherit_entity_attributes\n- select: AAA\n") + assert self._entities(res)["https://a-sp"] == {("urn:a", NF_URI): [["A"]]} + + def test_directory_source(self): + self.write("one.xml", _group("one", [_attribute("urn:one", "1")], _sp("https://one"))) + self.write("two.xml", _group("two", [_attribute("urn:two", "2")], _sp("https://two"))) + res, _md = self.exec_pipeline(f"- load:\n - {self.dir} inherit_entity_attributes\n- select\n") + got = self._entities(res) + assert got["https://one"] == {("urn:one", NF_URI): [["1"]]} + assert got["https://two"] == {("urn:two", NF_URI): [["2"]]} + + def test_nested_groups(self): + inner = _group("inner", [_attribute("urn:y", "Y")], _idp("https://b")) + path = self.write("n.xml", _group("outer", [_attribute("urn:x", "X")], _idp("https://a"), inner)) + res, _md = self.exec_pipeline(f"- load:\n - {path} inherit_entity_attributes\n- select\n") + got = self._entities(res) + assert got["https://a"] == {("urn:x", NF_URI): [["X"]]} + assert got["https://b"] == {("urn:x", NF_URI): [["X"]], ("urn:y", NF_URI): [["Y"]]} + + def test_result_is_still_schema_valid_and_signable_input(self): + path = self.write("a.xml", _group("a", [_attribute(CATEGORY, RS)], _sp("https://sp"))) + res, _md = self.exec_pipeline( + f"- load fail_on_error True:\n - {path} inherit_entity_attributes\n- select\n- validate\n" + ) + assert len(list(iter_entities(res))) == 1 + + def test_logs_how_much_was_added(self): + path = self.write("a.xml", _group("a", [_attribute(CATEGORY, RS)], _sp("https://x"), _sp("https://y"))) + with self._caplog.at_level(logging.INFO): + self.exec_pipeline(f"- load:\n - {path} inherit_entity_attributes\n- select\n") + assert "inherit_entity_attributes" in self.captured_log_text + assert "2 entities" in self.captured_log_text