Skip to content

strings_to_heredocs emits an EOF delimiter without checking the body, producing HCL that will not parse #330

Open

Description

@livingstaccato

Summary

_deserialize_string_as_heredoc builds <<EOF ... EOF for every value it
converts, whatever the value contains. A string with a line reading EOF closes
its own heredoc early, and everything after that line becomes stray tokens: the
file this library just wrote cannot be read back, by this parser or by
Terraform.

#124 and #190 are the read-side half of this, both closed. This is the same
collision arriving from the write side, where the library picks the delimiter
and so can avoid it.

Reproduction

import hcl2
from hcl2.deserializer import DeserializerOptions

heredocs = DeserializerOptions(strings_to_heredocs=True)
out = hcl2.dumps({"x": r'"first\nEOF\nlast\n"'}, deserializer_options=heredocs)
print(out)
hcl2.loads(out)
x = <<EOF
first
EOF
last

EOF

lark.exceptions.UnexpectedToken: Unexpected token Token('NAME', 'EOF') at line 6, column 1.
Expected one of:
	* LBRACE

An indented marker line does it too — '" EOF\nx\n"' fails the same way,
because the grammar allows whitespace before a closing marker.

Why it matters

This is the round trip the option exists for: read a document, flatten it, hand
the dict to dumps. A value that happens to contain the delimiter word is
enough to produce a file that no longer parses, with no error raised at write
time. Log excerpts, embedded scripts and policy documents are exactly the
payloads people put in heredocs, and EOF is exactly the word such payloads
tend to contain.

Suggested shape of the fix

Choose a delimiter that does not appear as a line of the body, under the same
rule the parser uses for a closing marker (optional leading horizontal
whitespace, then the word, then end of line). EOF when it is safe, so ordinary
output is unchanged; otherwise a suffixed form — EOF_1, EOF_2 — or a
generated word.

If no safe delimiter can be found, leaving the value as a quoted string is
better than emitting a file that does not parse.

Related


This issue, and the investigation behind it, were produced by an AI assistant (Claude) working on behalf of the author. Please review with that provenance in mind.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions