Skip to content

[Bug]: ORM filter_by interpolates string values without escaping #31378

Closed

Description

@Ariznawlll

DRAFT 5 (SDK, 2026-10-27) — candidate issue, not yet filed

Title: [Bug]: ORM filter_by() interpolates strings without escaping and silently ignores unknown columns

Description

(filter_by silently dropping predicates for unknown fields / string-table queries is already filed as #31207 — CLOSED. This report covers the remaining unfiled defect: unescaped raw interpolation. The silent-drop aspect is context here, since it multiplies with the quoting flaw below.)

BaseMatrixOneQuery.filter_by(**kwargs) (matrixone/orm.py) has two defects:

1. String values are interpolated raw — no quote escaping

if isinstance(value, str):
    self._where_conditions.append(f"{key} = '{value}'")   # raw f-string, no '' doubling

Any string value containing a single quote breaks the literal or injects:

q.filter_by(name="o'rien")   # → WHERE name = 'o'rien'         (broken/injectable)
q.filter_by(tag="x' OR '1'='1")  # → WHERE tag = 'x' OR '1'='1'  (predicate rewritten)

This is the same escaping-family defect filed today in #31375 (_escape_string no-op) and #31376 (single-row _build_insert_sql) — filter_by takes the third path: it doesn't call the (no-op) helper at all, it interpolates inline. Note the sibling method filter() correctly routes string ?-params through substitution (which itself has the same quoting flaw), so the codebase has three different unescaped interpolation sites in one ORM class.

2. Unknown columns are silently ignored

if key in self._columns:
    ...append condition...
# else: nothing — no error, no warning

A typo in a filter key (filter_by(nmae="x")) produces a query with no WHERE clause at all — the equivalent of SELECT * FROM users returning the entire table. SQLAlchemy's filter_by raises AttributeError/InvalidRequestError for unknown attributes; here the mistake is silently swallowed.

Verified statically (both code paths quoted above from orm.py); behavior follows directly from the source. Combined worst case: caller builds filter_by(active=true, acount_id=42) (typo), the acount_id filter vanishes, and the query runs unfiltered against the table.

Reproduction

from matrixone import Client
c = Client(); c.connect(...)
q = c.query(User).filter_by(name="o'rien")
sql, params = q._build_select_sql()      # inspect emitted SQL: name = 'o'rien'
# typo behavior (silently no WHERE): already covered by #31207; the *new* defect here is the raw interpolation above

Impact

  • The filter_by API is the friendly/Pythonic entry point (users pass values, not SQL fragments); it is exactly where unescaped interpolation hurts most, because values are application data (user names, tags, search terms) rather than trusted SQL.
  • The silent-ignore on unknown keys turns every typo into a full-table operation — a correctness footgun magnified by the fact that ORM users expect filter_by(hostile_input) to constrain results.
  • int/float bypass quoting (fine), but bool, None, datetime fall into the ?-param path — combined with the ?-substitution bug from the same class, those values are also at risk (already filed separately where measured).

Expected behavior

  1. Escape single quotes in string interpolation (value.replace("'", "''")), or better: keep key = ? for all types and route values through _where_params uniformly — the substitution machinery then owns quoting in one place.
  2. Raise on unknown keys (SQLAlchemy parity): a clear ValueError(f"Unknown column {key!r} for model ...") instead of silence. If backward compatibility requires leniency, at least emit a warning.

Relation to today's other finds

Activity

  1. added
    kind/bug
    on Oct 27, 2026
  2. added this to the MO-202610 milestone on Oct 27, 2026
  3. added theissue type on Oct 27, 2026
  4. MatrixAdventurer commented on Oct 28, 2026

    @MatrixAdventurer
    Contributor

    已在当前 main(e9dc8c4)复核,本 issue 的两个缺陷都已修复:

    1. 字符串值未转义: 已由 fix(python-sdk): unify query contracts and atomic manager operations #31262(28e8760)修复。clients/python/matrixone/orm.py 中 MatrixOneQuery.filter_by 现在通过 sql_literal(value) 渲染值(L981)。filter_by(name="x' OR '1'='1") 生成 WHERE name = 'x'' OR ''1''=''1',单引号被正确加倍,谓词没有被改写。Query.filter_by 改为 = ? 加参数绑定(L205)。
    2. 未知字段被静默忽略: 已由 fix(python-sdk): unify query contracts and atomic manager operations #31262 和 fix(python-sdk): preserve legacy filter_by predicates #31427(a772c02)修复。三个 Query 类(Query、BaseMatrixOneQuery、MatrixOneQuery)的 filter_by(nmae='x') 都会抛出 ValueError: Unknown model field: nmae(L199、L970)。

    验证方式: 在 main 上用本地脚本对三个类分别检查了上面两种输入;另外运行 pytest tests/offline -k filter_by,结果为 5 passed。

    因此按已完成关闭。

    本操作由 LW 授权的 Grok Bot 智能体执行

  5. added
    no-pr-linked
    on Oct 28, 2026
  6. added a commit that references this issue on Oct 30, 2026
    bbfe556
  7. XuPeng-SH commented on Oct 30, 2026

    @XuPeng-SH
    Contributor

    QA handoff for merged #31774 (main bbfe55669a1440424914d45a283a1d0e36f722fa): please verify the public SDK contract and failure/recovery controls for ORM filter_by interpolates string values without escaping. This isolated QA run inspected the issue and source but did not run functional tests or a live MatrixOne service at this SHA because the existing resource guard left insufficient headroom. Author-reported PR validation is separate evidence, not a result of this QA run.

  8. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试通过。同步 ORM filter_by 对引号等数据按字面值过滤,未知模型字段明确拒绝,没有静默去掉条件。

    关键证据

    待解决点

    • 本次未覆盖异步 ORM、所有 SQL mode 或所有字符编码,也不声称验证了数据库权限隔离;未运行完整 MOTR suite。Add build constraint to assembly source files #295 尚未合入,SDK 回归需显式启用和匹配源码,默认 SKIP 不计通过。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triageno-pr-linked

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions