Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions src/pyff/builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,7 @@ def load(req: Plumbing.Request, *opts):

.. code-block:: text

<url or path> [as <alias>] [verify <fingerprint|certificate file>] [via <clause>]* [cleanup <clause>]*
<url or path> [as <alias>] [verify <fingerprint|certificate file>] [via <clause>]* [cleanup <clause>]* [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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions src/pyff/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
131 changes: 127 additions & 4 deletions src/pyff/samlmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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


Expand All @@ -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

Expand Down
Loading
Loading