Skip to content

[Bug]: metadata_scan and moctl interpolate args unescaped; moctl hard-crashes on non-JSON output #31384

Closed

Description

@Ariznawlll

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

Title: [Bug]: MetadataManager and MoCtlManager interpolate identifiers/params into SQL unescaped; MoCtl also hard-crashes on non-JSON results

Description

Two unexplored SDK managers interpolate raw user strings into SQL — the remaining unfiled members of the escaping family opened by #31375/#31376/#31378:

1. MetadataManager._build_metadata_scan_sql (metadata.py:~147)

table_ref = f"{dbname}.{tablename}.?{indexname}"      # raw concat
return f"SELECT * FROM metadata_scan('{table_ref}', '*') g"

dbname/tablename/indexname are caller-supplied and land inside a single-quoted SQL literal with no escaping. A table named x' UNION SELECT ... -- (or a value coming from any external naming source) rewrites the metadata_scan argument — and since metadata_scan exposes internal object metadata, this path is security-sensitive (file-level metadata enumeration).

All public entry points route through it: scan(), get_table_brief_stats(), get_table_detail_stats() (each passing the other two components too, e.g. include_indexes feeds indexname).

2. MoCtlManager._execute_moctl (moctl.py:~129)

sql = f"SELECT mo_ctl('{method}', '{target}', '{params}')"

Three caller strings into one quoted-arg function call, zero escaping. mo_ctl is the administrative control plane (flush, checkpoint, task ops) — an injection here can trigger admin operations (e.g. crafted params that close the string and add a second statement fragment; multi-statements are driver-blocked, but argument-boundary injection inside a single mo_ctl call is enough to redirect the command). Typical control-plane code passes method/target from config tables or request parameters.

Additionally, _execute_moctl does:

result_str = result.rows[0][0]
parsed_result = json.loads(result_str)      # no guard

mo_ctl does not always return JSON (version/build variants return plain text or an error banner). json.loads then raises JSONDecodeError, which the enclosing except rewraps into a generic MoCtlError("Failed to execute: ..."), hiding that the command actually succeeded with a non-JSON body. The SDK cannot report the raw output in that (common) case.

Reproduction

# metadata
c.metadata.scan(dbname="db", tablename="' OR '1'='1")
# emitted: SELECT * FROM metadata_scan('db.' OR '1'='1', '*') g → parse error / unexpected enumeration

# moctl
c.moctl.flush_database("acc', 'extra') -- ")
# emitted: SELECT mo_ctl('flush', 'database', 'acc', 'extra') -- ')

Impact

  • Both managers accept names/params that in real deployments come from outside (DB listers, request payloads, config). The metadata path enumerates internal storage objects; the moctl path can influence maintenance operations (flush/checkpoint storms) — the highest-privilege surface in the SDK.
  • The JSON hard-assumption makes legitimate outputs (plain-text mo_ctl replies) surface as generic errors, sabotaging ops tooling that needs the raw returnStr.

Expected behavior

  1. Escape ' (doubling) inside all interpolated literal args — or better, since these are fixed-shape calls, SQLAlchemy text() with bindparams (the SDK already depends on SQLAlchemy).
  2. _execute_moctl: try json.loads; on failure return a structured {"raw": result_str} (or attach raw under a key) instead of erroring, and raise with the raw text preserved in the exception message.
  3. Add hostile-name regression tests for both managers (quote/backslash payloads) asserting single-literal rendering.

Cross-references

Escaping-family tracker context: #31375 (helpers are no-ops), #31376 (insert builder), #31378 (filter_by). These two managers are the remaining unaudited interpolation sites found in today's sweep of modules not covered before (metadata.py, moctl.py were untouched by prior reports).

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 只修复了一部分,暂不关闭。

    已修复(#31262、#31322):

    仍未修复: 预期行为第 2 条,即 mo_ctl 返回非 JSON 文本时的处理。现在不会崩溃,但 moctl.py L155-156 抛出的是 MoCtlError("Failed to parse mo_ctl result: Expecting value: line 1 column 1 (char 0)"),原始返回文本丢失,调用方拿不到 mo_ctl 实际输出了什么。在 main 上用 mock 返回 plain text banner OK 验证过。

    我会单独提一个小 PR,在这个错误里保留原始返回文本,并附回归测试。

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

  5. XuPeng-SH commented on Oct 28, 2026

    @XuPeng-SH
    Contributor

    QA on merged SDK f97056d1107a89854bfac2c06202698e3aafd41e (#31524): the offline stage/moctl files passed 67 tests, including sync/async non-JSON raw-output preservation and no double wrapping. The release-boundary and metadata offline tests passed 31 additional cases. A task-only facade probe exercised sync/async metadata.scan and _execute_moctl with quote payloads, metadata backslash input and a mo_ctl backslash argument; generated SQL kept values inside one literal or used hex conversion. The first added backslash probe failed because its expected hex encoded two backslashes while the input had one; after correcting that test expectation it passed. No live control-plane operation was performed.

    These checks cover the reported SDK rendering and raw-output contract. Stage SQL tests are separate from this issue.

  6. Ariznawlll commented on Oct 28, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试通过。metadata_scan 和 mo_ctl 参数的引号按单个字面量处理,同步及异步非 JSON 返回可从异常取得原始文本。

    关键证据

    • 版本:官方 main@9eb05ce0f5ac5ddce36024aaa21c4c79d3e4334c,包含 修复 PR #31524 和此前的字面量修复;隔离 1 Log + 1 TN + 2 CN,Python SDK 和服务版本一致。
    • SDK 离线 metadata/mo_ctl 测试 42/42 通过;新增 MOTR 回归 定向 3/3:注入样式的单引号按一个字符串生成,并由真实服务对 SQL 字面量进行值验证;同步与异步 mo_ctl 的构造参数和非 JSON 异常均保留原始 plain text banner OK。
    • 非 JSON 返回通过受控客户端响应夹具模拟,未执行外部控制面故障;正常 JSON 返回也通过夹具验证,未将其他 Stage 问题算作本项通过。

    待解决点

    • 本轮未运行完整 SDK suite 和完整 MOTR suite;MOTR PR Dev/api updates #287 的托管 CI 尚在运行。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions