"""Check XML element selection against a verifier-supplied ID; not an XML signature verifier."""
import json
from xml.etree import ElementTree as ET

SAML = "urn:oasis:names:tc:SAML:2.0:assertion"
PROTOCOL = "urn:oasis:names:tc:SAML:2.0:protocol"


def consume_verified_assertion(xml_bytes, verified_id):
    if not isinstance(xml_bytes, bytes) or len(xml_bytes) > 65536:
        raise ValueError("Expected at most 64 KiB of XML bytes")
    xml_text = xml_bytes.decode("utf-8")
    if "\x00" in xml_text:
        raise ValueError("Only UTF-8 XML text is accepted")
    if "<!DOCTYPE" in xml_text.upper() or "<!ENTITY" in xml_text.upper():
        raise ValueError("DTD/entity declarations rejected")
    root = ET.fromstring(xml_text)
    if root.tag != f"{{{PROTOCOL}}}Response":
        raise ValueError("Expected SAML Response")
    assertions = list(root.iter(f"{{{SAML}}}Assertion"))
    if len(assertions) != 1 or assertions[0] not in list(root):
        raise ValueError("Ambiguous or relocated assertion")
    matching = [node for node in root.iter() if node.get("ID") == verified_id]
    if len(matching) != 1 or matching[0] is not assertions[0]:
        raise ValueError("Verified element differs from consumed assertion")
    names = assertions[0].findall(f"{{{SAML}}}Subject/{{{SAML}}}NameID")
    if len(names) != 1 or not names[0].text:
        raise ValueError("Expected exactly one subject NameID")
    return names[0].text


def replay():
    def response(inner):
        return (f'<p:Response xmlns:p="{PROTOCOL}" xmlns:s="{SAML}">{inner}</p:Response>').encode()
    real = '<s:Assertion ID="real"><s:Subject><s:NameID>fixture-citizen</s:NameID></s:Subject></s:Assertion>'
    other = '<s:Assertion ID="other"><s:Subject><s:NameID>fixture-admin</s:NameID></s:Subject></s:Assertion>'
    assert consume_verified_assertion(response(real), "real") == "fixture-citizen"
    rejected = 0
    for body, verified in [(response(other + real), "real"), (response(real), "missing"),
                           (response('<Wrapper>' + real + '</Wrapper>'), "real"),
                           (response('<Extra ID="real"/>' + real), "real")]:
        try:
            consume_verified_assertion(body, verified)
        except ValueError:
            rejected += 1
        else:
            raise AssertionError("Ambiguous or mismatched element accepted")
    assert rejected == 4
    return {"valid_subject": "fixture-citizen", "rejected_cases": rejected,
            "scope": "Owned element-binding fixtures only. verified_id must come from a real trusted verifier; no XMLDSig or SPID validation implemented."}


if __name__ == "__main__":
    print(json.dumps(replay(), indent=2))
