KatInterview

Extract and Safely Parse an XML Document Nested in CDATA

StringsModel answer
MediumModel answerStringsxmlsecurityparsing

Last updated

Implement a function that pulls a nested XML document out of a CDATA section and reads an attribute from its root, while blocking XXE and entity-expansion attacks.

Background

You're writing a middleware component that ingests messages from legacy systems. Each message is a well-formed XML envelope, but one specific field carries a second, self-contained XML document stored verbatim inside a CDATA section. Your job is to safely unpack that inner document and read a named attribute from its root element.

Task

Implement the function below:

def extract_and_parse_nested(xml_string: str, target_tag: str, attribute_name: str) -> str:
    """
    1. Parse xml_string as an XML document.
    2. Find the first element whose tag matches target_tag.
    3. Treat that element's text content as a second XML document.
    4. Return the value of attribute_name on the root of that second document.

    Return "" if anything is absent, malformed, or unsafe.
    """
    pass

Example

Given this envelope:

<message>
  <data><![CDATA[<record id="A123"><body>Content</body></record>]]></data>
</message>

Called as extract_and_parse_nested(xml_string, "data", "id"), the function should return "A123".

Constraints and requirements

  • Return "" for every failure condition instead of raising. The middleware must not crash the processing pipeline.
  • The input may be malformed at the outer or inner level.
  • target_tag may be absent in the outer document, or the element may be empty.
  • The inner content may not be valid XML.
  • Security: both the outer envelope and the inner payload must be parsed with protections against XML External Entity (XXE) injection and entity-expansion (billion-laughs) attacks.
  • Do not use regex to locate or strip the <![CDATA[...]]> delimiters; rely on a conforming XML parser.

Edge cases to handle

ScenarioExpected return
Outer XML is malformed""
target_tag not present""
CDATA section is empty or missing""
Inner content is not valid XML""
attribute_name not on inner root""
Either document contains a DTD or entity declaration""

What failure contract does your design guarantee, and how do you ensure the inner payload is treated with the same level of suspicion as the outer envelope?

Hints

Hint 1

A conforming XML parser unwraps CDATA automatically — after parsing, node.text is already the raw string that was between the CDATA markers. There is no need to search for or strip the <![CDATA[ and ]]> delimiters yourself.

Hint 2

Both the outer and inner documents need the same security hardening. Many candidates harden only the first parse, but the inner payload is attacker-controlled data that arrived inside the envelope — it deserves at least as much scrutiny. The two classic XML attacks (XXE and billion laughs) both require a DOCTYPE declaration, so forbidding any DTD closes both at once.

Hint 3

Python's standard library gives you expat directly via xml.parsers.expat. You can run a cheap pre-pass that installs handlers for StartDoctypeDeclHandler and EntityDeclHandler that raise immediately, then build the ElementTree only if the pre-pass succeeds. This gives you DTD rejection without a third-party dependency.