diff --git a/docs/guides/user/building-custom-agents.md b/docs/guides/user/building-custom-agents.md index a2fb278711..0d25562284 100644 --- a/docs/guides/user/building-custom-agents.md +++ b/docs/guides/user/building-custom-agents.md @@ -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 diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index b615b7bc71..529bca7e6c 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" "testing" + "unicode/utf8" ) // writeRunDir lays out a run directory the way internal/cli/run.go does: @@ -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") + } +} diff --git a/internal/agentnew/postscript_status_test.go b/internal/agentnew/postscript_status_test.go index 36e810055b..8cc812cf5d 100644 --- a/internal/agentnew/postscript_status_test.go +++ b/internal/agentnew/postscript_status_test.go @@ -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", }, @@ -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") @@ -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) } } @@ -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) @@ -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()) diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index ee2a089efa..f3d4fc9696 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -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}" @@ -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 diff --git a/internal/agentnew/templates/scripts/validate-output-schema.sh b/internal/agentnew/templates/scripts/validate-output-schema.sh index e074aaf15d..f70314998a 100755 --- a/internal/agentnew/templates/scripts/validate-output-schema.sh +++ b/internal/agentnew/templates/scripts/validate-output-schema.sh @@ -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 '' + 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') + 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}') diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 11341920bf..651c9e01d6 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -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}" @@ -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 diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index a78b499f8c..8484c088c3 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -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}" @@ -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 diff --git a/internal/agentnew/validate_output_schema_test.go b/internal/agentnew/validate_output_schema_test.go new file mode 100644 index 0000000000..ce7392c197 --- /dev/null +++ b/internal/agentnew/validate_output_schema_test.go @@ -0,0 +1,205 @@ +package agentnew + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// pythonJSONSchemaAvailable skips a test when python3 or the jsonschema +// package it depends on is not installed, mirroring the jq skip used by the +// post-script tests. +func pythonJSONSchemaAvailable(t *testing.T) { + t.Helper() + if _, err := exec.LookPath("python3"); err != nil { + t.Skip("python3 not installed; the generated validation script needs it") + } + if err := exec.Command("python3", "-c", "import jsonschema").Run(); err != nil { + t.Skip("python3 jsonschema package not installed; the generated validation script needs it") + } +} + +// renderValidationScriptAndSchema writes the generated validate-output-schema.sh +// and its matching result schema (as produced for a real agent with +// --validation-loop) to dir, and returns their paths. +func renderValidationScriptAndSchema(t *testing.T, dir string) (script, schema string) { + t.Helper() + opts := testOptions("lint-docs", "triage") + opts.ValidationLoop = true + files, err := Render(opts) + if err != nil { + t.Fatal(err) + } + script = filepath.Join(dir, "validate-output-schema.sh") + if err := os.WriteFile(script, fileByPath(t, files, "scripts/validate-output-schema.sh").Data, 0o755); err != nil { + t.Fatal(err) + } + schema = filepath.Join(dir, "schema.json") + if err := os.WriteFile(schema, fileByPath(t, files, "schemas/lint-docs-result.schema.json").Data, 0o644); err != nil { + t.Fatal(err) + } + return script, schema +} + +// TestGeneratedValidationScriptNeverEchoesTheInstance pins the fix for the +// second finding in #7949: python's jsonschema ValidationError.message quotes +// the offending instance verbatim (e.g. "'##[warning]forged' is not one of +// [...]"), and that instance is untrusted agent/model output. Printing +// e.message directly would let a value like "##[warning]forged" reach the +// validation loop's step log through this path, exactly like the +// post-script's own status field does. The script must report only trusted +// schema metadata (the field path and the failed keyword), never the +// instance. +func TestGeneratedValidationScriptNeverEchoesTheInstance(t *testing.T) { + pythonJSONSchemaAvailable(t) + dir := t.TempDir() + script, schema := renderValidationScriptAndSchema(t, dir) + + outputDir := filepath.Join(dir, "output") + if err := os.MkdirAll(outputDir, 0o755); err != nil { + t.Fatal(err) + } + + cases := map[string]string{ + "legacy-warning": `{"status": "##[warning]forged", "summary": "s", "comment": "c"}`, + "legacy-add-mask": `{"status": "##[add-mask]s3cr3t", "summary": "s", "comment": "c"}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + if err := os.WriteFile(filepath.Join(outputDir, "agent-result.json"), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command("bash", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "FULLSEND_OUTPUT_SCHEMA="+schema) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected validation to fail for an invalid status, got exit 0; output:\n%s", out) + } + for _, leak := range []string{"##[warning]", "##[add-mask]", "forged", "s3cr3t"} { + if strings.Contains(string(out), leak) { + t.Fatalf("instance value leaked into validator output (%q found); output:\n%s", leak, out) + } + } + if !strings.Contains(string(out), `"enum"`) { + t.Fatalf("expected the failed keyword in the output, got:\n%s", out) + } + }) + } +} + +// TestGeneratedValidationScriptNeverEchoesInstanceControlledPathKeys pins the +// fix for the first finding in #7950: ValidationError.path can contain a key +// taken straight from the instance, not just schema-declared property names, +// whenever the failing (sub)schema uses additionalProperties or +// patternProperties instead of a fixed property list. Joining and printing +// that path unescaped would let a crafted key such as +// "\n::warning::forged\n" reach the validation loop's step log exactly like +// the instance value itself. Only property names that are literally +// declared somewhere in the schema document may appear in the printed path; +// anything else must be masked. +func TestGeneratedValidationScriptNeverEchoesInstanceControlledPathKeys(t *testing.T) { + pythonJSONSchemaAvailable(t) + dir := t.TempDir() + script, schema := renderValidationScriptAndSchema(t, dir) + + // The script is generic (works against whatever schema is configured), + // so replace the generated schema with one that uses additionalProperties + // to accept arbitrary keys, matching the scenario from the finding. + maliciousSchema := `{ + "type": "object", + "additionalProperties": {"type": "integer"} + }` + if err := os.WriteFile(schema, []byte(maliciousSchema), 0o644); err != nil { + t.Fatal(err) + } + + outputDir := filepath.Join(dir, "output") + if err := os.MkdirAll(outputDir, 0o755); err != nil { + t.Fatal(err) + } + maliciousInstance := "{\"\\n::warning::forged\\n\": \"bad\"}" + if err := os.WriteFile(filepath.Join(outputDir, "agent-result.json"), []byte(maliciousInstance), 0o644); err != nil { + t.Fatal(err) + } + + cmd := exec.Command("bash", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "FULLSEND_OUTPUT_SCHEMA="+schema) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected validation to fail for a non-integer additional property, got exit 0; output:\n%s", out) + } + for _, leak := range []string{"::warning::", "forged"} { + if strings.Contains(string(out), leak) { + t.Fatalf("instance-controlled path key leaked into validator output (%q found); output:\n%s", leak, out) + } + } + if !strings.Contains(string(out), `"type"`) { + t.Fatalf("expected the failed keyword in the output, got:\n%s", out) + } + if !strings.Contains(string(out), "") { + t.Fatalf("expected the masked path placeholder in the output, got:\n%s", out) + } +} + +// TestGeneratedValidationScriptStillReportsUsefulContextOnFailure checks the +// fix did not turn every failure into an opaque message: the field path, +// the failing keyword, and (for enum/const) the trusted allowed-values list +// from the schema should still appear. +func TestGeneratedValidationScriptStillReportsUsefulContextOnFailure(t *testing.T) { + pythonJSONSchemaAvailable(t) + dir := t.TempDir() + script, schema := renderValidationScriptAndSchema(t, dir) + + outputDir := filepath.Join(dir, "output") + if err := os.MkdirAll(outputDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(outputDir, "agent-result.json"), + []byte(`{"status": "bogus", "summary": "s", "comment": "c"}`), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command("bash", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "FULLSEND_OUTPUT_SCHEMA="+schema) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("expected validation to fail, got exit 0; output:\n%s", out) + } + for _, want := range []string{"status", "enum", "ok", "findings", "error"} { + if !strings.Contains(string(out), want) { + t.Errorf("expected %q in the failure output, got:\n%s", want, out) + } + } +} + +// TestGeneratedValidationScriptPassesAValidResult is the control case: a +// well-formed result validates cleanly, so the rewritten error handling did +// not break the success path. +func TestGeneratedValidationScriptPassesAValidResult(t *testing.T) { + pythonJSONSchemaAvailable(t) + dir := t.TempDir() + script, schema := renderValidationScriptAndSchema(t, dir) + + outputDir := filepath.Join(dir, "output") + if err := os.MkdirAll(outputDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(outputDir, "agent-result.json"), + []byte(`{"status": "ok", "summary": "All clear", "comment": "Nothing to report."}`), 0o644); err != nil { + t.Fatal(err) + } + cmd := exec.Command("bash", script) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "FULLSEND_OUTPUT_SCHEMA="+schema) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("expected a valid result to pass, got %v; output:\n%s", err, out) + } + if !strings.Contains(string(out), "PASS") { + t.Fatalf("expected a PASS message, got:\n%s", out) + } +}