Repository navigation
feat(llm): enforce read-only Gremlin before execution - #456
yuangu-chengzi wants to merge 5 commits into
Conversation
5d4d8f0 to
3265723
Compare
Add GRAPH_GREMLIN_READ_ONLY (default true) and reject non-read-only Gremlin produced by the model or caller before GraphQueryNode or run_gremlin_query executes it. The conservative classifier mirrors the MCP read-only policy; GraphQueryNode falls back to the safe subgraph query, while run_gremlin_query raises a clear ValueError. Co-Authored-By: Claude Code <noreply@anthropic.com>
45a1fdf to
df928bf
Compare
|
Pushed CI fixes: ruff formatting in |
bitflicker64
left a comment
There was a problem hiding this comment.
Blocking: yes. Summary: The default-on read-only guard rejects 45 of the 80 bundled text2gremlin.csv read queries, and it classifies Groovy $name interpolation in double-quoted strings as safe, so it blocks valid reads while still letting the server evaluate caller expressions.
| "call", | ||
| "program", | ||
| } | ||
| _READ_METHODS = { |
There was a problem hiding this comment.
Important: with GRAPH_GREMLIN_READ_ONLY=true as the default, 45 of the 80 bundled text2gremlin.csv few-shot queries classify uncertain because project(), fold(), match(), hasNext(), predicates such as lt() and containing(), and __ traversals are not allowed, so Text2Gremlin execution of these read queries fails and GraphRAG drops to the subgraph fallback. Allow the read steps, predicates and anonymous traversals those examples use, and add a test that every query in text2gremlin.csv classifies safe.
|
|
||
| # ========== Classifier constants ========== | ||
|
|
||
| _DYNAMIC_MARKERS = ("${", "#{", "->") |
There was a problem hiding this comment.
Important: Groovy interpolates $name and $a.b in double-quoted strings without braces, but only ${ is checked, so g.V().hasLabel("$System.env.HOME") classifies safe and the server evaluates that property chain. Treat any $ inside a double-quoted or triple-double-quoted string as uncertain, and add a test for that form.
|
|
||
|
|
||
| def run_gremlin_query(query, fmt=True, connection=None): | ||
| if huge_settings.graph_gremlin_read_only: |
There was a problem hiding this comment.
Minor: no test exercises the guard calls in run_gremlin_query or GraphQueryNode._gremlin_generate_query; the new tests cover only the helper and the config flag. Add tests that a rejected query raises before the client runs and that GraphQueryNode skips execution and falls back to the subgraph query.
imbajin
left a comment
There was a problem hiding this comment.
Score: 5.0/10 · Confidence: medium
Blocking: yes
Summary
The fallback may execute unescaped vertex IDs outside the guard. Existing findings also identify rejected read queries and allowed Groovy interpolation.
Evidence
The rejection clears graph_result, so operator_schedule calls _subgraph_query, which interpolates matched_vid into Gremlin and executes it. Local classifier probes confirm the existing findings.
Validation notes
No live HugeGraph server, vertex ID acceptance, or deployed sandbox was tested.
| rejection_reason = gremlin_readonly_rejection_reason(gremlin) | ||
| if rejection_reason is not None: | ||
| log.error("Refusing to execute non-read-only generated Gremlin: %s", rejection_reason) | ||
| context["graph_result"] = [] |
There was a problem hiding this comment.
Clearing graph_result makes operator_schedule call _subgraph_query, which puts each matched_vid inside a single-quoted Gremlin string and executes it without the guard. If a matched stored ID contains a quote and Groovy statements, it can escape that literal and potentially execute a mutation with the configured credentials even when read-only mode is enabled. Please bind or safely encode fallback inputs and test a rejected query followed by a quoted ID. This depends on accepted vertex IDs and server sandbox behavior, which I could not verify against a live server.
b96e554 to
df928bf
Compare
|
Thanks — pushed a follow-up addressing the new findings:
Local: On the previous red |
|
Pushed the follow-up for the latest review (head |
965991b to
df928bf
Compare
…back
- Allow read-only project/fold/match/constant/hasNext/identity and the
predicates used by bundled examples; permit anonymous traversal roots.
- Reject bare $ interpolation in double-quoted GStrings, not only ${...}.
- Escape vertex IDs and keywords before building fallback Gremlin queries.
- Add tests for every bundled text2gremlin.csv query, interpolation,
run_gremlin_query rejection, and fallback escaping; fix a missing dot in
one bundled example.
Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Re-pushed with one more hardening change (property names are now encoded through the same Gremlin literal helper as vertex IDs), head |
…back
- Allow read-only project/fold/match/constant/hasNext/identity and the
predicates used by bundled examples; permit anonymous traversal roots.
- Reject bare $ interpolation in double-quoted GStrings, not only ${...}.
- Escape vertex IDs and keywords before building fallback Gremlin queries.
- Add tests for every bundled text2gremlin.csv query, interpolation,
run_gremlin_query rejection, and fallback escaping; fix a missing dot in
one bundled example.
Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Fixed the two Local checks still pass ( Could a maintainer approve the new |
bitflicker64
left a comment
There was a problem hiding this comment.
Blocking: yes. Summary: The earlier findings are fixed at this head, but a \uXXXX escape in a string or comment hides drop() from the classifier while Groovy still runs it, so model-generated writes pass the read-only guard.
|
|
||
| while index < length: | ||
| char = query[index] | ||
| if char == "\\": |
There was a problem hiding this comment.
Critical: Groovy translates \uXXXX escapes before lexing, so g.V().has('name','x\u0027).drop()//') and g.V() /* \u002a/.drop()// */ classify safe while Groovy 4.0.25 runs drop(). Classify any \u escape as uncertain and add tests for both forms.
…back - Allow the read-only steps, predicates, and anonymous traversals used by all 80 bundled text2gremlin.csv examples; add a test that every example is safe. - Reject bare $ interpolation in double-quoted GStrings and any Groovy unicode escape (\uXXXX), which is expanded before lexing and can hide a mutation in a string or comment. - Escape vertex IDs, keywords, and property names before building fallback Gremlin queries. - Add tests for the unicode-escape bypasses, run_gremlin_query rejection, GraphQueryNode fallback, and the full examples file; fix a missing dot in one bundled example. Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Fixed the
The new |
bitflicker64
left a comment
There was a problem hiding this comment.
Blocking: yes. Summary: The earlier findings are fixed at this head, but the default-on guard still classifies common read-only steps such as sum(), max(), is() and union() as uncertain, so Text2Gremlin refuses ordinary aggregation queries.
| "toset", | ||
| "explain", | ||
| "profile", | ||
| # Read-only projection, aggregation, and pattern-match steps. The bundled |
There was a problem hiding this comment.
Important: read-only steps outside the bundled examples, such as sum(), max(), min(), mean(), is(), union(), local() and next(), still classify uncertain, so with the default GRAPH_GREMLIN_READ_ONLY=true Text2Gremlin refuses a query like g.V().hasLabel('person').values('age').max(). Add these read steps to _READ_METHODS and test that each classifies safe.
imbajin
left a comment
There was a problem hiding this comment.
Score: 6.0/10 · Confidence: high
Blocking: yes
Summary
The fallback still interpolates schema edge labels without escaping; common valid read steps are also rejected by default.
Evidence
Traced guard rejection to fallback execution, schema label interpolation and the policy allowlist.
Validation notes
Source review only; mutation requires a crafted schema and permissive server sandbox; no live HugeGraph test.
| for matched_vid in matched_vids: | ||
| gremlin_query = VID_QUERY_NEIGHBOR_TPL.format( | ||
| keywords=f"'{matched_vid}'", | ||
| keywords=_gremlin_literal(matched_vid), |
There was a problem hiding this comment.
This fallback escapes the vertex ID, but edge_labels_str still wraps schema-derived labels in quotes without escaping and is inserted into the unguarded Gremlin below. A label containing a quote can break the query; a crafted label may inject a mutation when the guard rejects a generated traversal. Please encode each label with _gremlin_literal as well and test a quoted label. This depends on schema creation permissions and the server sandbox; I did not run a live mutation.
…back - Allow the read-only steps, predicates, anonymous traversals, aggregations (sum/max/min/mean), is/union/local/next, and all 80 bundled text2gremlin.csv examples. - Reject bare $ interpolation in double-quoted GStrings and any Groovy unicode escape (\uXXXX), which is expanded before lexing. - Escape vertex IDs, keywords, property names, and schema edge labels before building fallback Gremlin queries. - Add tests for unicode-escape bypasses, aggregation steps, run_gremlin_query rejection, GraphQueryNode fallback, and edge-label escaping. Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Addressed the latest review in head
Local policy/guard tests: 41 passed; ruff passes. The new |
bitflicker64
left a comment
There was a problem hiding this comment.
Blocking: yes. Summary: The guard also covers the Graph Tools Gremlin console, so operators lose write access there unless they turn off read-only protection for GraphRAG and Text2Gremlin too. The earlier interpolation, \uXXXX, read-step, guard-test and fallback-escaping comments are addressed at this head.
| if huge_settings.graph_gremlin_read_only: | ||
| rejection_reason = gremlin_readonly_rejection_reason(query) | ||
| if rejection_reason is not None: | ||
| raise ValueError(f"Refusing to execute non-read-only Gremlin: {rejection_reason}") |
There was a problem hiding this comment.
Important: run_gremlin_query also backs the Graph Tools console in create_other_block, so with the default GRAPH_GREMLIN_READ_ONLY=true operator-written queries such as g.addV('person') now raise, and allowing them again turns the guard off for GraphRAG and Text2Gremlin as well. Let the console call skip the check, for example through a read_only argument that create_other_block sets to False.
| The classifier is conservative: ``safe`` means a known read-only traversal, | ||
| ``unsafe`` means a write/mutation step was detected, and ``uncertain`` means the | ||
| query cannot be confirmed as read-only. Callers should execute only ``safe`` | ||
| queries. This mirrors the MCP classifier so both execution surfaces apply the |
There was a problem hiding this comment.
Minor: the docstring says both execution surfaces apply the same rules, but hugegraph-mcp/hugegraph_mcp/gremlin_policy.py lacks the \uXXXX and bare $ checks and still classifies g.V().has('name','x\u0027).drop()//') as safe. Drop the parity claim.
| return classify_gremlin_read_safety(gremlin_query) == "safe" | ||
|
|
||
|
|
||
| def _extract_method_names(query_without_strings: str) -> list[str]: |
There was a problem hiding this comment.
Minor: _extract_method_names, _has_unsafe_write_steps, _has_dynamic_construction_markers, _has_bare_identifier_arguments, _strip_string_literals, is_safe_gremlin_read and the GremlinSafety alias have no callers in hugegraph-llm. Remove them so check_gremlin_read stays the one entry point.
Summary
Implements the server-side read-only boundary requested in #455 for GraphRAG execution.
Adds
GRAPH_GREMLIN_READ_ONLY(defaulttrue). BeforeGraphQueryNodeorrun_gremlin_queryexecutes Gremlin produced by the model or supplied by a caller, a conservative classifier rejectsunsafeanduncertainqueries.Motivation
#455 exposes
/rag/graphas an MCP tool, but HugeGraph-AI executes model-generated Gremlin with its own graph credentials. The MCP layer cannot verify those credentials, so the boundary belongs at the execution point in HugeGraph-AI. This also protects the Text2Gremlin execution paths, which userun_gremlin_query.Relates to #455 and #225.
Changes
hugegraph_llm/utils/gremlin_policy.py, a conservative read-only classifier mirroring the MCP policy, andgremlin_guard.py.GraphQueryNode: when generated Gremlin is not read-only, log the rejection, cleargraph_result, and fall back to the safe subgraph query.run_gremlin_query: raise a clearValueErrorbefore executing non-read-only Gremlin;GremlinExecuteNodealready reports execution errors.GRAPH_GREMLIN_READ_ONLY(defaulttrue) toHugeGraphConfigand document it inconfig.md.test_gremlin_execute_surfaces_invalid_queryfocused on server-side error surfacing by disabling the read-only guard in that test; the guard itself has dedicated unit tests.text2gremlin.csvexamples (project,fold,match,constant,hasNext,identity, comparison/string predicates, and__roots), so the default-on guard does not reject Text2Gremlin's own examples.$inside double-quoted or triple-double-quoted GStrings, not only${...}, because Groovy also interpolates bare$nameand$a.b.\uXXXX) before lexing; Groovy expands it before tokenization and can use it to close a string/comment and hide a mutation.text2gremlin.csvquery,$interpolation,run_gremlin_queryrejection before client creation, and fallback escaping after a rejected generated query..beforewhere(...)in one bundled CSV example so the shipped example is valid Gremlin.Tests
pytest src/tests/utils/test_gremlin_policy.py src/tests/utils/test_gremlin_guard.py -q— 30 passed.src/tests/nodes/test_graph_query_node_guard.pyfor generated-Gremlin rejection and escaped fallback IDs; it runs in CI becausepycgraphis Linux-only.ruff format --checkandruff checkpass onsrc/.git diff --check— passed.Notes
uncertainqueries are rejected. Operators can setGRAPH_GREMLIN_READ_ONLY=falseonly for controlled write workflows; the default protects generated-Gremlin execution.hugegraph-mcp/gremlin_policy.py. A follow-up can move it into a shared package once Python-client release coordination allows it; this PR keeps the change insidehugegraph-llmto avoid a cross-package version dependency.🤖 Generated with Claude Code