Skip to content

Commit 78f0ace

Browse files
fix(tools): close ROADMAP-02/03/04 — markdown escaping, bounded reads, finite results (#120)
Three P0 ROADMAP fixes from the 2026-10-27 assessment, squash-merged as one commit. - ROADMAP-02 (#94): sql_readonly cells (and column names) escaped backslash-first, then pipes/newlines/control characters, with a MAX_CELL_CHARS rendered-length cap — a database value can no longer forge table rows or smuggle prompt structure. - ROADMAP-03 (#95): read_file byte cap enforced by one bounded read(max_bytes + 1) instead of stat-check then re-open, closing the check-then-read race; exact-cap files stay readable. - ROADMAP-04 (#96): calculator rejects non-finite results and overflowing float literals (1e999); Pow pair guard literals named (MAX_POW_BASE_MAGNITUDE/MAX_POW_PAIR_EXPONENT), values unchanged. 11 tests added; 494 passing, 30 skipped hermetic + live tier green; ruff/mypy clean. Closes #94, closes #95, closes #96.
1 parent 486894b commit 78f0ace

7 files changed

Lines changed: 223 additions & 13 deletions

File tree

‎agentkit/tools/builtin/calculator.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,18 @@
11
"""Safe arithmetic calculator tool powered by strict Python AST parsing."""
22

33
import ast
4+
import math
45

56
from agentkit.tools.registry import tool
67

78
MAX_EXPRESSION_LEN = 1000
89
MAX_AST_NODES = 100
910
MAX_EXPONENT = 1000
11+
#: When the base magnitude grows too, an exponent well below MAX_EXPONENT can already
12+
#: overflow a float (``1000.0 ** 100`` is ~1e300; ``1999.0 ** 101`` is inf), so pairs of an
13+
#: oversized base and a still-large exponent are rejected before the operation runs.
14+
MAX_POW_BASE_MAGNITUDE = 1000
15+
MAX_POW_PAIR_EXPONENT = 100
1016

1117
#: Rough ceiling on the bit length of an exponentiation result. 10**1000 is ~3322 bits and
1218
#: still cheap once, but the ReAct loop can repeat the call, so the result size itself is
@@ -23,6 +29,11 @@ def _evaluate_node(node: ast.AST) -> int | float:
2329
# Explicitly reject boolean, string, None, complex, etc.
2430
if isinstance(node.value, bool) or not isinstance(node.value, (int, float)):
2531
raise ValueError(f"Disallowed operand type: {type(node.value).__name__}")
32+
# A float literal that overflows Python's double range (e.g. ``1e999``) silently
33+
# becomes inf at parse time; anchoring finiteness here keeps it out of every
34+
# subsequent operation.
35+
if isinstance(node.value, float) and not math.isfinite(node.value):
36+
raise ValueError("Numeric literal is not finite (out of range)")
2637
return node.value
2738

2839
if isinstance(node, ast.UnaryOp):
@@ -56,7 +67,9 @@ def _evaluate_node(node: ast.AST) -> int | float:
5667
raise ValueError("Modulo by zero")
5768
return left % right
5869
if isinstance(node.op, ast.Pow):
59-
if abs(right) > MAX_EXPONENT or (abs(left) > 1000 and right > 100):
70+
if abs(right) > MAX_EXPONENT or (
71+
abs(left) > MAX_POW_BASE_MAGNITUDE and right > MAX_POW_PAIR_EXPONENT
72+
):
6073
raise ValueError(f"Exponent too large (maximum allowed is {MAX_EXPONENT})")
6174

6275
# The exponent bound alone still permits enormous big integers (10**1000 is a
@@ -108,7 +121,16 @@ def safe_calculate(expression: str) -> int | float:
108121
if len(nodes) > MAX_AST_NODES:
109122
raise ValueError(f"Expression too complex (exceeds {MAX_AST_NODES} AST nodes).")
110123

111-
return _evaluate_node(tree)
124+
result = _evaluate_node(tree)
125+
126+
# Any float operand is finite, but sums/products/divisions can still overflow into
127+
# inf or collapse into nan. Intercept once at the exit so neither ever reaches the
128+
# prompt or history. (The only finite value derivable from an inf intermediate is
129+
# inf ** 0 == 1.0, which is the correct x**0 answer rather than a masked overflow.)
130+
if isinstance(result, float) and not math.isfinite(result):
131+
raise ValueError("Result is not a finite number")
132+
133+
return result
112134

113135

114136
@tool

‎agentkit/tools/builtin/read_file.py‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,18 @@ def read_sandboxed_file(
5050
if not target.is_file():
5151
raise ValueError(f"Target is not a regular file: '{file_path}'")
5252

53-
file_size = target.stat().st_size
54-
if file_size > max_bytes:
55-
raise ValueError(
56-
f"File '{file_path}' exceeds maximum size limit of {max_bytes} bytes (size: {file_size} bytes)."
57-
)
53+
# The byte cap is enforced on the bytes actually read, not on a prior st_size: a file
54+
# grown between a stat check and a second open would otherwise be read in full (the
55+
# check-then-read race). One bounded read of max_bytes + 1 closes that window while
56+
# making oversize still fail — and an exact-cap file stays fully readable.
57+
with target.open("rb") as handle:
58+
data = handle.read(max_bytes + 1)
59+
60+
if len(data) > max_bytes:
61+
raise ValueError(f"File '{file_path}' exceeds maximum size limit of {max_bytes} bytes.")
5862

5963
try:
60-
return target.read_text(encoding="utf-8")
64+
return data.decode("utf-8")
6165
except UnicodeDecodeError as exc:
6266
raise ValueError(f"File '{file_path}' is not a valid UTF-8 text file.") from exc
6367

‎agentkit/tools/builtin/sql_readonly.py‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,26 @@
3636
DEFAULT_ROW_LIMIT = 50
3737
DEFAULT_STATEMENT_TIMEOUT_S = 10.0
3838

39+
#: Per-cell character ceiling for rendered table cells. The executor budget
40+
#: (TOOL_OUTPUT_MAX_CHARS) bounds the whole table afterwards, but one wide column value
41+
#: should not be able to consume most of that budget — or hide a large payload — behind
42+
#: row truncation.
43+
MAX_CELL_CHARS = 200
44+
45+
#: Row-breaking and invisible control characters are rewritten to visible escapes, and
46+
#: every other C0 control character (plus DEL) is rendered as ``\\uXXXX`` so no control
47+
#: byte reaches the prompt as structure.
48+
_CONTROL_CHAR_ESCAPES: dict[int, str] = {
49+
ord("\n"): "\\n",
50+
ord("\r"): "\\r",
51+
ord("\t"): "\\t",
52+
**{
53+
code: f"\\u{code:04x}"
54+
for code in (*range(0x20), 0x7F)
55+
if code not in (ord("\n"), ord("\r"), ord("\t"))
56+
},
57+
}
58+
3959
DISALLOWED_KEYWORDS = (
4060
"insert",
4161
"update",
@@ -402,17 +422,36 @@ def _dollar_quote_end(sql: str, start: int) -> int | None:
402422
return len(sql) if closing == -1 else closing + len(tag)
403423

404424

425+
def _escape_cell_text(raw_text: str) -> str:
426+
"""Escape and bound a single table cell so it cannot alter the markdown structure.
427+
428+
A pipe would forge additional columns, a newline would forge additional rows, and
429+
invisible control characters could smuggle prompt structure — the classic stored
430+
prompt injection through attacker-influenced database values. Backslash is escaped
431+
first so it cannot escape its own escape sequences. Finiteness of the rendered
432+
length (not the raw value) is the cap, so the displayed cell is bounded no matter
433+
how the escapes inflated the text.
434+
"""
435+
escaped = raw_text.replace("\\", "\\\\").replace("|", "\\|")
436+
escaped = escaped.translate(_CONTROL_CHAR_ESCAPES)
437+
if len(escaped) > MAX_CELL_CHARS:
438+
escaped = escaped[:MAX_CELL_CHARS] + "[Truncated]"
439+
return escaped
440+
441+
442+
def _format_cell(value: Any) -> str:
443+
"""Render one SQL result value as a safe markdown table cell."""
444+
return "NULL" if value is None else _escape_cell_text(str(value))
445+
446+
405447
def format_rows_as_markdown(columns: Sequence[str], rows: Sequence[Any]) -> str:
406448
"""Format tabular SQL results into clean Markdown table string."""
407449
if not rows:
408450
return "No rows returned."
409451

410-
header = "| " + " | ".join(columns) + " |"
452+
header = "| " + " | ".join(_format_cell(col) for col in columns) + " |"
411453
divider = "| " + " | ".join(["---"] * len(columns)) + " |"
412-
data_lines = [
413-
"| " + " | ".join(str(val) if val is not None else "NULL" for val in row) + " |"
414-
for row in rows
415-
]
454+
data_lines = ["| " + " | ".join(_format_cell(val) for val in row) + " |" for row in rows]
416455
return "\n".join([header, divider, *data_lines])
417456

418457

‎docs/PROGRESS.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ This document tracks execution progress across all backlog tasks, including pull
7676
| FU-85 | AUDIT | Real-Infra Provisioning Failures | `test/real-infra-provisioning-failures` | #90 | 1 | Done | Provisioning errors fail the live SQL-isolation tier instead of skipping it |
7777
| FU-88 | AUDIT | Audit History Consistency | `docs/audit-history-consistency` | #90 | 1 | Done | Canonical 12-layer/14-commit wording; stale "AST validation" row corrected and guarded |
7878
| FU-89 | AUDIT | uv Lockfile Policy | `chore/repo-uv-lock` | #90 | 1 | Done | `uv.lock` ignored; pip-based CI does not consume a uv lock |
79+
| ROADMAP-02 | ROADMAP | SQL Markdown Cell Escaping | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | Cells escaped (`\|`, `\n`, `\uXXXX` controls) and length-capped before markdown output; closes #94 |
80+
| ROADMAP-03 | ROADMAP | read_file Read-After-Stat Race | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | Byte cap enforced on a bounded `read(max_bytes + 1)` in one open; closes #95 |
81+
| ROADMAP-04 | ROADMAP | Calculator Non-Finite Result Guard | `fix/roadmap-02-03-04-tools-hardening` | #120 | 1 | Done | `math.isfinite` result check, inf literals rejected, pow pair guard named; closes #96 |
7982

8083
---
8184

@@ -505,3 +508,9 @@ This document tracks execution progress across all backlog tasks, including pull
505508
- **#85 (test reliability)** — `tests/real/test_sql_isolation_real.py::readonly_engine` no longer converts `provision_readonly_role()` failures into `pytest.skip`. The upstream `real_database_url` fixture already applies migrations and fails loudly when PostgreSQL is unreachable, so a provisioning error is a defect and now turns CI red instead of leaving the isolation tier green-by-skip.
506509
- **#88 (docs)** — `docs/AUDIT.md` records the canonical "linear 12-layer stack, merged as 14 commits (12 layer commits plus two progress-bookkeeping commits)" wording instead of "nine branches", and the historical M4-T04 row describes the lexer plus dedicated read-only role instead of "Strict SELECT AST validation". `tests/unit/test_docs_accuracy.py` guards both claims.
507510
- **#89 (repo hygiene)** — `.gitignore` ignores `uv.lock` with a comment explaining that all three CI jobs install from `pyproject.toml` with pip, so a lockfile is not part of the reproducible build. Adopting uv properly (commit the lock, switch CI to `uv sync --locked`) remains a separate decision.
511+
512+
### PR #120: ROADMAP-02 / ROADMAP-03 / ROADMAP-04 Tools-Hardening Batch (P0 quick fixes)
513+
- **Status**: Done
514+
- **PR**: `fix/roadmap-02-03-04-tools-hardening` — PR #120 (three `fix(tools)` commits, squash-merged; docs rows in this commit)
515+
- **Commits**: 3 (+1 docs)
516+
- **Notes**: Closed the first three `ROADMAP` issues filed from the 2026-10-27 assessment. **#94** — `format_rows_as_markdown` now routes every cell (and column name) through `_format_cell`/`_escape_cell_text`: backslash first, then `|` → `\|`, newline/CR/tab → `\n`/`\r`/`\t`, every other C0/DEL control character → `\uXXXX`, and a rendered-length cap `MAX_CELL_CHARS` (200) with a `[Truncated]` marker, so a database value can no longer forge table rows, columns or prompt structure (stored prompt injection). **#95** — `read_sandboxed_file` enforces the byte cap on the bytes actually read (`read(max_bytes + 1)` from a single open) instead of a `stat().st_size` check + second open; oversize keeps the same user-visible phrase, an exact-cap file stays fully readable, and a regression test stands in for the race by lying about `st_size` (the old code returned the full oversized file). **#96** — `safe_calculate` rejects non-finite float results (`1e308 * 10 ** 3` no longer renders `inf` into the prompt) and non-finite float literals (`1e999` parses to inf) at the operand boundary; the `Pow` guard's bare `1000`/`100` literals became `MAX_POW_BASE_MAGNITUDE`/`MAX_POW_PAIR_EXPONENT` with unchanged values. 11 tests added (`test_tool_sql_readonly.py`, `test_tool_read_file.py`, `test_tool_calculator.py`); suite moved from 483 to 494 passing.

‎tests/unit/test_tool_calculator.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,29 @@ def test_dos_protection_large_exponents() -> None:
9393
safe_calculate("10 ** 10000")
9494

9595

96+
def test_non_finite_results_rejected() -> None:
97+
with pytest.raises(ValueError, match="not a finite number"):
98+
safe_calculate("1e308 * 10 ** 3")
99+
100+
with pytest.raises(ValueError, match="not a finite number"):
101+
safe_calculate("1e308 * 2")
102+
103+
104+
def test_overflowing_float_literal_rejected() -> None:
105+
# A float literal beyond double range silently parses to inf at AST level.
106+
with pytest.raises(ValueError, match="not finite"):
107+
safe_calculate("1e999")
108+
109+
with pytest.raises(ValueError, match="not finite"):
110+
safe_calculate("-1e999")
111+
112+
113+
def test_large_integer_results_still_allowed() -> None:
114+
assert safe_calculate("2 ** 1000") == 2**1000
115+
assert safe_calculate("10 ** 100") == 10**100
116+
assert safe_calculate("1000 ** 100") == 1000**100
117+
118+
96119
def test_calculator_tool_function() -> None:
97120
assert calculator("10 + 20") == "30"
98121
assert calculator("7 / 2") == "3.5"

‎tests/unit/test_tool_read_file.py‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""Unit and security tests for sandboxed file reader tool."""
22

3+
import os
34
from pathlib import Path
45

56
import pytest
@@ -90,6 +91,52 @@ def test_max_bytes_limit_enforced(tmp_path: Path) -> None:
9091
read_sandboxed_file("large.txt", base_dir=tmp_path, max_bytes=100)
9192

9293

94+
def test_exact_cap_file_is_readable(tmp_path: Path) -> None:
95+
doc = tmp_path / "exact.txt"
96+
doc.write_text("A" * 40, encoding="utf-8")
97+
98+
assert read_sandboxed_file("exact.txt", base_dir=tmp_path, max_bytes=40) == "A" * 40
99+
100+
101+
def test_size_cap_enforced_on_the_read_not_on_stat(
102+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
103+
) -> None:
104+
"""A file whose stat lies small is still capped by the bytes actually read.
105+
106+
Regression: the cap used to consult ``stat().st_size`` and then re-open the file, so a
107+
file grown between the two calls bypassed the limit completely. Lying about the size is
108+
an observable stand-in for that race; the bounded read must reject it regardless.
109+
"""
110+
doc = tmp_path / "growing.txt"
111+
doc.write_text("A" * 50, encoding="utf-8")
112+
113+
real_stat = Path.stat
114+
115+
def lying_stat(self: Path, *, follow_symlinks: bool = True) -> "os.stat_result":
116+
st = real_stat(self, follow_symlinks=follow_symlinks)
117+
# Report st_size = 10 while the real content is 50 bytes.
118+
return os.stat_result(
119+
(
120+
st.st_mode,
121+
st.st_ino,
122+
st.st_dev,
123+
st.st_nlink,
124+
st.st_uid,
125+
st.st_gid,
126+
10,
127+
st.st_atime,
128+
st.st_mtime,
129+
st.st_ctime,
130+
)
131+
)
132+
133+
monkeypatch.setattr(Path, "stat", lying_stat)
134+
135+
# The old stat-driven cap would have passed this file through and returned all 50 bytes.
136+
with pytest.raises(ValueError, match="exceeds maximum size limit"):
137+
read_sandboxed_file("growing.txt", base_dir=tmp_path, max_bytes=40)
138+
139+
93140
def test_binary_file_rejected(tmp_path: Path) -> None:
94141
doc = tmp_path / "binary.bin"
95142
doc.write_bytes(b"\x80\x81\xff\xfe\x00\x01")

‎tests/unit/test_tool_sql_readonly.py‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
88

99
from agentkit.tools.builtin.sql_readonly import (
10+
MAX_CELL_CHARS,
1011
execute_sql_query,
12+
format_rows_as_markdown,
1113
sql_readonly,
1214
validate_sql_query,
1315
)
@@ -158,3 +160,67 @@ async def test_sql_tool_registry_integration(
158160
bad_result = await registry.execute(bad_call)
159161
assert bad_result.ok is False
160162
assert "Only SELECT" in (bad_result.error or "")
163+
164+
165+
def test_markdown_escapes_pipe_and_backslash_per_cell() -> None:
166+
"""A pipe in a cell value cannot forge additional columns, and rows stay intact."""
167+
output = format_rows_as_markdown(["customer"], [("Al|ice",), ("a\\b",), ("Bob",)])
168+
169+
assert output.splitlines() == [
170+
"| customer |",
171+
"| --- |",
172+
"| Al\\|ice |",
173+
"| a\\\\b |",
174+
"| Bob |",
175+
]
176+
177+
178+
def test_markdown_escapes_newlines_and_control_characters() -> None:
179+
"""A newline in a cell value cannot forge additional rows."""
180+
output = format_rows_as_markdown(["text"], [("line1\nline2\r\nline3\x07end\x7f",)])
181+
182+
assert output.splitlines() == [
183+
"| text |",
184+
"| --- |",
185+
"| line1\\nline2\\r\\nline3\\u0007end\\u007f |",
186+
]
187+
188+
189+
def test_markdown_null_and_unchanged_basics() -> None:
190+
output = format_rows_as_markdown(["a", "b"], [(None, 150.0)])
191+
192+
assert output.splitlines() == ["| a | b |", "| --- | --- |", "| NULL | 150.0 |"]
193+
194+
195+
def test_markdown_truncates_oversized_cell() -> None:
196+
output = format_rows_as_markdown(["c"], [("x" * 5_000,)])
197+
lines = output.splitlines()
198+
199+
# One data row, one bounded cell, marker appended inside the cell.
200+
assert len(lines) == 3
201+
assert lines[-1].endswith("[Truncated] |")
202+
assert len(lines[-1]) <= MAX_CELL_CHARS + len("[Truncated]") + 4
203+
204+
205+
def test_markdown_escapes_column_names_too() -> None:
206+
output = format_rows_as_markdown(["name|extra"], [("v",)])
207+
208+
assert output.splitlines()[0] == "| name\\|extra |"
209+
210+
211+
@pytest.mark.asyncio
212+
async def test_execute_sql_query_escapes_adversarial_cells(demo_db_engine: AsyncEngine) -> None:
213+
async with demo_db_engine.begin() as conn:
214+
await conn.execute(
215+
text("INSERT INTO orders (customer, amount) VALUES ('Al|ice\nEvil', 7.5)")
216+
)
217+
218+
output = await execute_sql_query(
219+
"SELECT customer, amount FROM orders ORDER BY id", engine=demo_db_engine
220+
)
221+
lines = [line for line in output.strip().split("\n") if line.strip()]
222+
223+
# Header + divider + 4 data rows: the injected pipe and newline are escapes within
224+
# one cell, not structure that adds a line or column.
225+
assert len(lines) == 6
226+
assert "Al\\|ice\\nEvil" in output

0 commit comments

Comments
 (0)