Skip to content

pgn: reject line breaks in required header values - #1237

Open
PStarH wants to merge 1 commit into
niklasf:mainfrom
PStarH:fix/pgn-header-linebreaks
Open

PStarH wants to merge 1 commit into
niklasf:mainfrom
PStarH:fix/pgn-header-linebreaks

Conversation

@PStarH

@PStarH PStarH commented Nov 27, 2026

Copy link
Copy Markdown

Problem

Headers.__setitem__ rejects \n and \r for custom tags, but stores the Seven Tag Roster before that check:

def __setitem__(self, key: str, value: str) -> None:
    if key in TAG_ROSTER:
        self._tag_roster[key] = value
    elif not _TAG_NAME_REGEX.match(key):
        raise ValueError(...)
    elif "\n" in value or "\r" in value:
        raise ValueError(...)
    else:
        self._others[key] = value

So this is accepted:

game = chess.pgn.Game()
game.headers["Event"] = "a\nb"

and str(game) / StringExporter writes a raw line break inside the quoted header value. chess.pgn.read_headers() then returns None for the exported text. The same assignment to a custom tag (Annotator) correctly raises ValueError.

The PGN standard, Section 7 (Tokens), is explicit:

Non-printing characters like newline and tab are not permitted inside of strings.

Tag values are string tokens (Section 8.1), so the restriction applies to both roster and custom headers.

Reproduction

import io
import chess.pgn

game = chess.pgn.Game()
game.headers["Event"] = "a\nb"       # accepted
text = str(game)                     # malformed header line
assert chess.pgn.read_headers(io.StringIO(text)) is None

try:
    game.headers["Annotator"] = "a\nb"
except ValueError:
    pass                             # custom tags already reject this

Fix

Validate the value after key validation and before the roster/custom dispatch:

     def __setitem__(self, key: str, value: str) -> None:
-        if key in TAG_ROSTER:
-            self._tag_roster[key] = value
-        elif not _TAG_NAME_REGEX.match(key):
+        if key not in TAG_ROSTER and not _TAG_NAME_REGEX.match(key):
             raise ValueError(f"invalid pgn header tag: {key!r}")
-        elif "\n" in value or "\r" in value:
+        if "\n" in value or "\r" in value:
             raise ValueError(f"line break in pgn header {key}: {value!r}")
+        if key in TAG_ROSTER:
+            self._tag_roster[key] = value
         else:
             self._others[key] = value

This preserves the existing error precedence for invalid custom tag names and does not change any valid header value.

Tests

Added PgnTestCase.test_headers_reject_line_breaks:

def test_headers_reject_line_breaks(self):
    for tagname in chess.pgn.TAG_ROSTER + ["Annotator"]:
        for value in ["a\nb", "a\rb"]:
            with self.subTest(tagname=tagname, value=value):
                game = chess.pgn.Game()
                with self.assertRaises(ValueError):
                    game.headers[tagname] = value

Results on 393bdb3:

  • Before the fix: the new test reports 14 failures (7 roster tags × LF/CR); custom Annotator already passes.
  • After the fix: python3 -m unittest test.PgnTestCase → Ran 69 tests ... OK.
  • Full native suite: python3 -m unittest discover -p 'test*.py' → Ran 352 tests ... OK (skipped=22).
  • Additional bounded harness: SAN/FEN/UCI round-trips, 120 random PGN game trees with comments/variations, and 24 header rejection cases → all pass.

Notes

  • This is an API/export integrity issue: ordinary parsed PGN cannot contain CR/LF in header strings, but callers populating headers from external data can currently emit unreadable PGN.
  • Tab is also non-printing per the spec, but the existing setter does not reject tabs for any tag. I kept this change scoped to the existing LF/CR guard; happy to follow up with uniform tab handling if preferred.
  • No existing issue or PR appears to cover this specific gap. Recent header-escaping work (pgn: escape and unescape header values #1198) covers quotes/backslashes, not CR/LF rejection.

Headers.__setitem__ validated custom tags before checking for CR/LF, so the Seven Tag Roster accepted values containing line breaks and StringExporter emitted unreadable PGN. Validate the value for every tag before storing it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant