Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions docs/guides/user/building-custom-agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,11 +446,12 @@ case "${STATUS}" in
echo "Agent needs more information"
;;
*)
# STATUS is model output: flatten CR/LF and cap it before logging, and
# use printf, which never expands backslash escapes, so a crafted value
# cannot start a new log line (a "::" workflow command).
shown="${STATUS//[$'\r\n']/ }"
printf '%s\n' "ERROR: Unknown or missing status '${shown:0:40}'"
# STATUS is model output: never echo any part of it, raw or otherwise.
# Flattening CR/LF and capping the length only defeats line-splitting —
# it does not defeat GitHub Actions' legacy "##[...]" logging-command
# syntax, which the log viewer recognizes anywhere in a line, not just
# at its start. The only safe fix is to never print the value at all.
echo "ERROR: unknown or missing status"
exit 1
;;
esac
Expand Down
60 changes: 60 additions & 0 deletions internal/agentnew/postscript_exec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"testing"
"unicode/utf8"
)

// writeRunDir lays out a run directory the way internal/cli/run.go does:
Expand Down Expand Up @@ -330,3 +331,62 @@ func TestGeneratedPostScriptOkRejectsANonGitHubIssueURL(t *testing.T) {
t.Fatalf("expected the ISSUE_URL rejection, got:\n%s", stderr)
}
}

// TestGeneratedPostScriptCountsCodePointsUnderInheritedCLocale pins that the
// script's `export LC_ALL=C.UTF-8` overrides an inherited C/POSIX locale
// rather than deferring to it. `${LC_ALL:-C.UTF-8}` (the previous form) only
// fills in a value when LC_ALL is unset, so a runner that already exports
// LC_ALL=C would make `${#summary}` count UTF-8 bytes instead of Unicode
// code points. 101 "é" characters are 101 code points but 202 bytes, so
// byte-counting would wrongly reject them as exceeding the schema's
// 200-code-point cap on summary.
func TestGeneratedPostScriptCountsCodePointsUnderInheritedCLocale(t *testing.T) {
if _, err := exec.LookPath("jq"); err != nil {
t.Skip("jq not installed; the generated post-script needs it")
}
script := renderPostScriptTo(t, t.TempDir())
summary := strings.Repeat("é", 101)
runDir := writeRunDir(t, map[string]any{
"iteration-1": map[string]any{"status": "findings", "summary": summary, "comment": "c"},
})
// LC_ALL=C simulates a runner environment that already set a non-UTF-8
// locale before invoking this script; it is appended after os.Environ()
// so it overrides any inherited value (bash keeps the last duplicate
// assignment when building its variable table from envp).
stdout, stderr, err := runPostScript(t, script, runDir, "LC_ALL=C")
if err != nil {
t.Fatalf("a 101-code-point summary must pass the 200-code-point cap even under an inherited C locale, got %v; stderr:\n%s", err, stderr)
}
if !strings.Contains(stdout, summary) {
t.Fatalf("expected the summary in the preview output, got:\n%s", stdout)
}
}

// TestGeneratedPostScriptTruncatesMultibyteCommentsOnACodePointBoundary pins
// that comment truncation, like the summary length check, counts code
// points rather than bytes: cutting a multibyte comment at a byte offset
// under an inherited C locale can slice a character in half and produce
// invalid UTF-8 in the posted comment.
func TestGeneratedPostScriptTruncatesMultibyteCommentsOnACodePointBoundary(t *testing.T) {
if _, err := exec.LookPath("jq"); err != nil {
t.Skip("jq not installed; the generated post-script needs it")
}
script := renderPostScriptTo(t, t.TempDir())
// One code point over the 16384-character cap, entirely multibyte so a
// byte-counting truncation would both miscompute the cut point and risk
// slicing a character.
comment := strings.Repeat("é", 16385)
runDir := writeRunDir(t, map[string]any{
"iteration-1": map[string]any{"status": "findings", "summary": "s", "comment": comment},
})
stdout, _, err := runPostScript(t, script, runDir, "LC_ALL=C")
if err != nil {
t.Fatalf("truncation must not fail the run, got %v", err)
}
if !strings.Contains(stdout, "_(truncated)_") {
t.Fatalf("expected the truncation marker, got:\n%s", stdout)
}
if !utf8.ValidString(stdout) {
t.Fatalf("truncated comment is not valid UTF-8 — a character was sliced in half")
}
}
79 changes: 36 additions & 43 deletions internal/agentnew/postscript_status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,43 @@ package agentnew
import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)

// TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging feeds a status
// that carries a line break (LF, CR alone, or CRLF) and a workflow-command
// prefix. The rejection message must stay on one line and must not reproduce
// the injected line, because the script's stderr lands in the runner log
// where `::` at line start is interpreted as a command.
func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) {
// stopCommandsTokenRe matches the stop-commands opening line the dry-run
// preview emits: "::stop-commands::<32 hex chars>".
var stopCommandsTokenRe = regexp.MustCompile(`^::stop-commands::([0-9a-f]{32})$`)

// TestGeneratedPostScriptNeverEchoesAnInvalidStatus feeds a variety of
// malicious status values — a line break paired with a `::`-style workflow
// command, and the legacy `##[...]` Actions logging-command form — and
// checks that none of them, or any other part of the raw value, ever reaches
// the rejection message. Capping and flattening (an earlier version of this
// script's approach) only defeats line-splitting: GitHub's Actions log
// viewer recognizes `##[...]` anywhere in a line, not only at its start, so
// a fixed prefix in front of the value does not neutralize it. The only
// reliable fix is to never print the value at all.
func TestGeneratedPostScriptNeverEchoesAnInvalidStatus(t *testing.T) {
if _, err := exec.LookPath("jq"); err != nil {
t.Skip("jq not installed; the generated post-script needs it")
}
script := renderPostScriptTo(t, t.TempDir())
for name, brk := range map[string]string{"LF": "\n", "CR": "\r", "CRLF": "\r\n"} {
cases := map[string]string{
"LF": "bogus\n::error::injected",
"CR": "bogus\r::error::injected",
"CRLF": "bogus\r\n::error::injected",
"legacy-warning": "##[warning]forged",
"legacy-add-mask": "##[add-mask]s3cr3t",
"long": strings.Repeat("x", 200),
"legacy-mid-sentence": "status is totally fine ##[error]nope, trust me",
}
for name, status := range cases {
t.Run(name, func(t *testing.T) {
runDir := writeRunDir(t, map[string]any{
"iteration-1": map[string]any{
"status": "bogus" + brk + "::error::injected",
"status": status,
"summary": "s",
"comment": "c",
},
Expand All @@ -32,24 +48,24 @@ func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) {
if err == nil {
t.Fatal("expected the script to reject an invalid status")
}
if !strings.Contains(stderr, "status must be ok, findings or error") {
t.Fatalf("expected the status rejection, got stderr:\n%s", stderr)
const wantMsg = "post-lint-docs: status must be ok, findings or error"
if strings.TrimSpace(stderr) != wantMsg {
t.Fatalf("expected the fixed rejection message %q and nothing else, got stderr:\n%s", wantMsg, stderr)
}
for _, line := range strings.FieldsFunc(stderr, func(r rune) bool { return r == '\n' || r == '\r' }) {
if strings.HasPrefix(line, "::") {
t.Fatalf("model-supplied status reached the log as its own line: %q", line)
}
}
if strings.ContainsRune(stderr, '\r') || strings.Count(strings.TrimSpace(stderr), "\n") != 0 {
t.Fatalf("rejection must be a single log line, got: %q", stderr)
}
})
}
}

// TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho runs the script
// with bash's xpg_echo option on, where `echo` interprets backslash escapes.
// A status carrying a literal backslash-n must still be logged on one line.
// Because the invalid-status message never includes the value, a status
// carrying a literal backslash-n must still produce the single fixed
// rejection line regardless of xpg_echo.
func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) {
if _, err := exec.LookPath("jq"); err != nil {
t.Skip("jq not installed; the generated post-script needs it")
Expand All @@ -76,33 +92,10 @@ func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) {
}
out := strings.TrimSpace(stderr.String())
if strings.Count(out, "\n") != 0 {
t.Fatalf("backslash escapes were expanded into a new log line:\n%s", out)
}
if !strings.Contains(out, `bogus\n::error::injected`) {
t.Fatalf("expected the literal value on the single line, got: %q", out)
}
}

// TestGeneratedPostScriptCapsALongInvalidStatus pins the 40-character cap on
// the logged value, so a long model-supplied status cannot flood the log.
func TestGeneratedPostScriptCapsALongInvalidStatus(t *testing.T) {
if _, err := exec.LookPath("jq"); err != nil {
t.Skip("jq not installed; the generated post-script needs it")
}
script := renderPostScriptTo(t, t.TempDir())
runDir := writeRunDir(t, map[string]any{
"iteration-1": map[string]any{
"status": strings.Repeat("x", 200),
"summary": "s",
"comment": "c",
},
})
_, stderr, err := runPostScript(t, script, runDir)
if err == nil {
t.Fatal("expected the script to reject an invalid status")
t.Fatalf("unexpected extra log line under xpg_echo:\n%s", out)
}
if !strings.Contains(stderr, "(got '"+strings.Repeat("x", 40)+"')") {
t.Fatalf("expected the status capped at 40 characters, got: %q", stderr)
if strings.Contains(out, `bogus`) {
t.Fatalf("the invalid status value must never appear in the log, got: %q", out)
}
}

Expand All @@ -123,7 +116,7 @@ func TestGeneratedPostScriptDryRunPreviewCannotIssueWorkflowCommands(t *testing.
"comment": "intro\n::error::injected\r::add-mask::x\n ::warning::indented",
},
})
token := regexp.MustCompile(`^::stop-commands::([0-9a-f]{32})$`)
token := stopCommandsTokenRe
var tokens []string
for i := 0; i < 2; i++ {
stdout, stderr, err := runPostScript(t, script, runDir)
Expand Down Expand Up @@ -160,7 +153,7 @@ func TestGeneratedPostScriptDryRunFailsClosedWithoutAToken(t *testing.T) {
t.Skip("jq not installed; the generated post-script needs it")
}
binDir := t.TempDir()
if err := os.WriteFile(filepath.Join(binDir, "od"), []byte("#!/usr/bin/env bash\nexit 0\n"), 0o755); err != nil {
if err := os.WriteFile(binDir+"/od", []byte("#!/usr/bin/env bash\nexit 0\n"), 0o755); err != nil {
t.Fatal(err)
}
script := renderPostScriptTo(t, t.TempDir())
Expand Down
22 changes: 13 additions & 9 deletions internal/agentnew/templates/post.sh.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ set -euo pipefail
# ${#var} and ${var:0:n} count characters in a UTF-8 locale and BYTES under
# C/POSIX. The result schema's maxLength counts Unicode code points, so
# without this a valid multibyte summary is rejected as too long and
# truncation can slice mid-character.
export LC_ALL="${LC_ALL:-C.UTF-8}"
# truncation can slice mid-character. Force this unconditionally: the
# runner may already export LC_ALL=C (or another non-UTF-8 locale), and
# `${LC_ALL:-C.UTF-8}` only fills in a value when LC_ALL is unset, so an
# inherited C/POSIX locale would otherwise pass straight through.
export LC_ALL=C.UTF-8

: "${ISSUE_URL:?ISSUE_URL must be set}"
: "${GH_TOKEN:?GH_TOKEN must be set}"
Expand Down Expand Up @@ -82,13 +85,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end'
case "${status}" in
ok|findings|error) ;;
*)
# status is model output: never echo it raw. A value carrying CR/LF would
# split the runner's log line (a workflow-command injection vector), so
# flatten it and cap it before it reaches stderr.
shown="${status//[$'\r\n']/ }"
# printf '%s' never interprets backslash escapes; echo does under xpg_echo,
# so a literal "\n" in the value could still forge a log line through echo.
printf '%s\n' "post-__AGENT_NAME__: status must be ok, findings or error (got '${shown:0:40}')" >&2
# status is model output: never echo any part of it, raw or otherwise.
# Flattening CR/LF and capping the length (as an earlier version of this
# script did) only defeats line-splitting — it does not defeat GitHub
# Actions' legacy "##[...]" logging-command syntax, which the log viewer
# recognizes anywhere in a line, not just at its start. A status such as
# "##[warning]forged" or "##[add-mask]..." would still reach the log.
# The only safe fix is to never print the value at all.
printf '%s\n' "post-__AGENT_NAME__: status must be ok, findings or error" >&2
exit 1
;;
esac
Expand Down
46 changes: 43 additions & 3 deletions internal/agentnew/templates/scripts/validate-output-schema.sh
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,57 @@ if ! python3 -c "
import json, sys
from jsonschema import validate, ValidationError

def _trusted_property_names(node, found):
# Collect every key declared under a 'properties' mapping anywhere in
# the schema document. These are schema-authored literals, never
# instance-controlled, so they are always safe to print.
if isinstance(node, dict):
props = node.get('properties')
if isinstance(props, dict):
found.update(k for k in props if isinstance(k, str))
for v in node.values():
_trusted_property_names(v, found)
elif isinstance(node, list):
for item in node:
_trusted_property_names(item, found)

with open(sys.argv[1]) as f:
instance = json.load(f)
with open(sys.argv[2]) as f:
schema = json.load(f)

trusted_keys = set()
_trusted_property_names(schema, trusted_keys)

try:
validate(instance=instance, schema=schema)
print('PASS: output validated against schema')
except ValidationError as e:
print(f'FAIL: schema validation error: {e.message}')
if e.path:
print(f' at: {\".\".join(str(p) for p in e.path)}')
# e.message is built from the offending instance (e.g. an enum error
# quotes the invalid value verbatim), and the instance is untrusted
# agent/model output. Printing it would let a value like
# '##[warning]forged' reach this step's log through the validation
# loop. Report only trusted schema metadata, never the instance.
#
# e.path can itself carry instance-controlled strings: when a schema
# uses additionalProperties/patternProperties instead of (or in
# addition to) a fixed property list, the offending instance's own key
# becomes a path component even though the schema never declared it.
# Only print path components that are literal property names found
# somewhere in the schema document (trusted_keys); array indices are
# plain integers and always safe; anything else is masked.
def _safe_component(p):
if isinstance(p, bool):
return str(p)
if isinstance(p, int):
return str(p)
if isinstance(p, str) and p in trusted_keys:
return p
return '<dynamic-key>'
path = '.'.join(_safe_component(p) for p in e.path) if e.path else '(root)'
print(f'FAIL: schema validation failed: \"{path}\" failed its \"{e.validator}\" check')

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] injection-vuln

ValidationError.path can contain instance-controlled keys, not just schema-declared property names. For a configured schema with additionalProperties requiring integers, the invalid instance {"\n::warning::forged\n": "bad"} places the malicious key in e.path. Joining and printing that path emits the payload into the diagnostic without escaping or a command fence, leaving a workflow-command injection path. The new tests cover status values under the generated schema, not dynamic property names.

Suggested fix: Omit instance paths, replace dynamic components with trusted placeholders, or fence diagnostics with an unpredictable stop-commands token. Add a regression test for additionalProperties or patternProperties with a malicious instance key.

if e.validator in ('enum', 'const'):
print(f' allowed values: {e.validator_value!r}')
if 'properties' in e.schema:
allowed = ', '.join(sorted(e.schema['properties'].keys()))
print(f' allowed properties: {allowed}')
Expand Down
22 changes: 13 additions & 9 deletions internal/agentnew/testdata/golden/triage.txt
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,11 @@ set -euo pipefail
# ${#var} and ${var:0:n} count characters in a UTF-8 locale and BYTES under
# C/POSIX. The result schema's maxLength counts Unicode code points, so
# without this a valid multibyte summary is rejected as too long and
# truncation can slice mid-character.
export LC_ALL="${LC_ALL:-C.UTF-8}"
# truncation can slice mid-character. Force this unconditionally: the
# runner may already export LC_ALL=C (or another non-UTF-8 locale), and
# `${LC_ALL:-C.UTF-8}` only fills in a value when LC_ALL is unset, so an
# inherited C/POSIX locale would otherwise pass straight through.
export LC_ALL=C.UTF-8

: "${ISSUE_URL:?ISSUE_URL must be set}"
: "${GH_TOKEN:?GH_TOKEN must be set}"
Expand Down Expand Up @@ -234,13 +237,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end'
case "${status}" in
ok|findings|error) ;;
*)
# status is model output: never echo it raw. A value carrying CR/LF would
# split the runner's log line (a workflow-command injection vector), so
# flatten it and cap it before it reaches stderr.
shown="${status//[$'\r\n']/ }"
# printf '%s' never interprets backslash escapes; echo does under xpg_echo,
# so a literal "\n" in the value could still forge a log line through echo.
printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2
# status is model output: never echo any part of it, raw or otherwise.
# Flattening CR/LF and capping the length (as an earlier version of this
# script did) only defeats line-splitting — it does not defeat GitHub
# Actions' legacy "##[...]" logging-command syntax, which the log viewer
# recognizes anywhere in a line, not just at its start. A status such as
# "##[warning]forged" or "##[add-mask]..." would still reach the log.
# The only safe fix is to never print the value at all.
printf '%s\n' "post-lint-docs: status must be ok, findings or error" >&2
exit 1
;;
esac
Expand Down
22 changes: 13 additions & 9 deletions internal/agentnew/testdata/golden/validation-loop.txt
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,11 @@ set -euo pipefail
# ${#var} and ${var:0:n} count characters in a UTF-8 locale and BYTES under
# C/POSIX. The result schema's maxLength counts Unicode code points, so
# without this a valid multibyte summary is rejected as too long and
# truncation can slice mid-character.
export LC_ALL="${LC_ALL:-C.UTF-8}"
# truncation can slice mid-character. Force this unconditionally: the
# runner may already export LC_ALL=C (or another non-UTF-8 locale), and
# `${LC_ALL:-C.UTF-8}` only fills in a value when LC_ALL is unset, so an
# inherited C/POSIX locale would otherwise pass straight through.
export LC_ALL=C.UTF-8

: "${ISSUE_URL:?ISSUE_URL must be set}"
: "${GH_TOKEN:?GH_TOKEN must be set}"
Expand Down Expand Up @@ -242,13 +245,14 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end'
case "${status}" in
ok|findings|error) ;;
*)
# status is model output: never echo it raw. A value carrying CR/LF would
# split the runner's log line (a workflow-command injection vector), so
# flatten it and cap it before it reaches stderr.
shown="${status//[$'\r\n']/ }"
# printf '%s' never interprets backslash escapes; echo does under xpg_echo,
# so a literal "\n" in the value could still forge a log line through echo.
printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2
# status is model output: never echo any part of it, raw or otherwise.
# Flattening CR/LF and capping the length (as an earlier version of this
# script did) only defeats line-splitting — it does not defeat GitHub
# Actions' legacy "##[...]" logging-command syntax, which the log viewer
# recognizes anywhere in a line, not just at its start. A status such as
# "##[warning]forged" or "##[add-mask]..." would still reach the log.
# The only safe fix is to never print the value at all.
printf '%s\n' "post-lint-docs: status must be ok, findings or error" >&2
exit 1
;;
esac
Expand Down
Loading
Loading