Skip to content

fix(plugins): replace unsafe eval with ast.literal_eval in db.py (#13663) - #13694

Merged
kodjima33 merged 5 commits into
BasedHardware:mainfrom
dwaddle:fix/plugins-db-utc-timestamp-parsing
Sep 21, 2026
Merged

kodjima33 merged 5 commits into
BasedHardware:mainfrom
dwaddle:fix/plugins-db-utc-timestamp-parsing

Conversation

@dwaddle

@dwaddle dwaddle commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Closes #13663

Summary

Fixes a security vulnerability and potential crash in get_upsert_segment_to_transcript_plugin in plugins/db.py where the Redis transcript buffer was parsed with Python's eval().

Changes Made

• Replaced eval(segments) with safe ast.literal_eval(segments_raw).
• Added bytes decoding handling for Redis byte string responses.
• Added element dictionary validation: filters parsed elements to ensure only valid dictionary objects containing required keys (text, speaker, is_user, start, end) are accepted.
• Added hermetic unit tests in plugins/test_db.py without permanent sys.modules mutation.
• Registered test in .github/checks-manifest.yaml.

Failure-Class: none

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 2 files

Confidence score: 3/5

  • plugins/test_db.py is omitted from .github/checks-manifest.yaml, so the new security regression test will not run in CI or preflight lanes and the eval-to-literal_eval fix could regress unnoticed—register the test in the manifest.
  • plugins/test_db.py permanently replaces sys.modules["redis"] and sys.modules["models"] at module import, which can contaminate later tests in a shared pytest session—restore the original modules or scope the stubs with test isolation.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="plugins/test_db.py">

<violation number="1" location="plugins/test_db.py:40">
P3: The module-scope `sys.modules["redis"] = redis_stub` / `sys.modules["models"] = models_stub` override installs permanently at import and is never restored, so every later import in a shared pytest session silently resolves to these hand-rolled stub objects (e.g. a non-Pydantic `TranscriptSegment`). This can mask real model behavior and bleed into co-run test files; it also duplicates the repo's sanctioned `backend/testing/import_isolation.stub_modules` helper. Prefer that helper (or defer imports into a per-test context) instead of permanently mutating `sys.modules`.</violation>

<violation number="2" location="plugins/test_db.py:46">
P2: The new hermetic regression test for the eval->literal_eval security fix is not registered in `.github/checks-manifest.yaml`, so no CI or preflight lane ever runs `plugins/test_db.py` (no trigger covers `plugins/db.py` changes). The test only executes when a developer manually runs pytest, which silently leaves the security regression unguarded. Register a check with `command: ["pytest", "plugins/test_db.py"]`, `triggers: ["plugins/db.py", "plugins/test_db.py", "plugins/models.py"]`, and `lanes: ["local", "ci"]`, matching the existing per-app plugin test entries.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread plugins/db.py Resolved
Comment thread plugins/test_db.py
from models import TranscriptSegment


class TestPluginDb(unittest.TestCase):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The new hermetic regression test for the eval->literal_eval security fix is not registered in .github/checks-manifest.yaml, so no CI or preflight lane ever runs plugins/test_db.py (no trigger covers plugins/db.py changes). The test only executes when a developer manually runs pytest, which silently leaves the security regression unguarded. Register a check with command: ["pytest", "plugins/test_db.py"], triggers: ["plugins/db.py", "plugins/test_db.py", "plugins/models.py"], and lanes: ["local", "ci"], matching the existing per-app plugin test entries.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plugins/test_db.py, line 46:

<comment>The new hermetic regression test for the eval->literal_eval security fix is not registered in `.github/checks-manifest.yaml`, so no CI or preflight lane ever runs `plugins/test_db.py` (no trigger covers `plugins/db.py` changes). The test only executes when a developer manually runs pytest, which silently leaves the security regression unguarded. Register a check with `command: ["pytest", "plugins/test_db.py"]`, `triggers: ["plugins/db.py", "plugins/test_db.py", "plugins/models.py"]`, and `lanes: ["local", "ci"]`, matching the existing per-app plugin test entries.</comment>

<file context>
@@ -0,0 +1,111 @@
+from models import TranscriptSegment
+
+
+class TestPluginDb(unittest.TestCase):
+
+    @mock.patch.object(db, 'r')
</file context>

Comment thread plugins/test_db.py Outdated

models_stub = types.ModuleType("models")
models_stub.TranscriptSegment = TranscriptSegment
sys.modules["models"] = models_stub

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The module-scope sys.modules["redis"] = redis_stub / sys.modules["models"] = models_stub override installs permanently at import and is never restored, so every later import in a shared pytest session silently resolves to these hand-rolled stub objects (e.g. a non-Pydantic TranscriptSegment). This can mask real model behavior and bleed into co-run test files; it also duplicates the repo's sanctioned backend/testing/import_isolation.stub_modules helper. Prefer that helper (or defer imports into a per-test context) instead of permanently mutating sys.modules.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At plugins/test_db.py, line 40:

<comment>The module-scope `sys.modules["redis"] = redis_stub` / `sys.modules["models"] = models_stub` override installs permanently at import and is never restored, so every later import in a shared pytest session silently resolves to these hand-rolled stub objects (e.g. a non-Pydantic `TranscriptSegment`). This can mask real model behavior and bleed into co-run test files; it also duplicates the repo's sanctioned `backend/testing/import_isolation.stub_modules` helper. Prefer that helper (or defer imports into a per-test context) instead of permanently mutating `sys.modules`.</comment>

<file context>
@@ -0,0 +1,111 @@
+
+    models_stub = types.ModuleType("models")
+    models_stub.TranscriptSegment = TranscriptSegment
+    sys.modules["models"] = models_stub
+
+import db
</file context>

@dwaddle

dwaddle commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all 3 review items in commit c363ccbba2:

  1. Element Dictionary Validation: Updated get_upsert_segment_to_transcript_plugin in plugins/db.py to filter parsed elements, ensuring only valid dictionary objects containing required keys (text, speaker, is_user, start, end) are accepted. Wrapped segment object construction in safe error handling to prevent uncaught Pydantic ValidationError exceptions.
  2. Hermetic Test Isolation: Refactored plugins/test_db.py to avoid permanent sys.modules mutation.
  3. CI Registration: Registered plugin-db-eval-security-tests in .github/checks-manifest.yaml with triggers for plugins/db.py and plugins/test_db.py on local and ci lanes.

Verified with pytest plugins/test_db.py (5/5 passed).

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified at head af4a9d5 — this is a correct fix for the eval() code-execution issue (#13663), and both items from the earlier review round are resolved:

  • plugins/db.py: eval(segments) → ast.literal_eval with bytes decoding and a (ValueError, SyntaxError) fallback. The only writer to plugin:{id}:session:{id}:transcript_segments is this function itself (str() of TranscriptSegment.dict() output), so the literal parser is a drop-in for the stored format, and a poisoned or corrupted value now degrades to an empty buffer instead of executing. The new per-element try/except around TranscriptSegment(**segment) also means a hostile element can no longer raise into the /mentor webhook (plugins/basic/mentor.py).
  • plugins/test_db.py: ran the suite hermetically (stubbed redis/models) — 5/5 pass, including rejection of a stored __import__('os').system(...) payload and bytes-response handling. The stubs only install when real imports fail and never overwrite live modules, so the earlier sys.modules-contamination concern is resolved.
  • .github/checks-manifest.yaml: plugin-db-eval-security-tests is registered with the right triggers/lanes, so the earlier missing-CI-registration concern is resolved.

Two non-blocking notes:

  1. The element filter requires all of text, speaker, is_user, start, end. That matches what this function itself writes, and is fine as a hardened check — just noting the SDK model only hard-requires four of those (speaker has a default), so the filter is intentionally stricter than the model.
  2. Dropped malformed elements are silently skipped; a short log line there would make a corrupted Redis buffer much easier to diagnose in production.

Heads-up for maintainers: #13664 (by the issue reporter) fixes the same bug with slightly different trade-offs (RecursionError/MemoryError handling, atomic r.set(..., ex=...), isinstance-only element checks). Choosing between the two — and the bounty attribution on #13663 — needs a maintainer call. Since this removes a code-execution path from a credentialed service, it warrants maintainer sign-off before merge either way.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-maintainer-review Needs a human maintainer to sign off before merge python labels Sep 13, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator

Keeping this open on af4a9d5bac6b.

DIRTY eval→ast.literal_eval in plugins/db.py + tests; rebase (cancelled Hygiene/Formatting).

I am not approving or merging this SHA.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Legitimate security fix removing eval() (arbitrary code execution via Redis-stored transcript buffer) in favor of ast.literal_eval with dict/key validation, matches the explicit non-abuse carve-out for PRs that remove existing eval() calls. Hermetic test proves both safe parsing and that a malicious import payload no longer executes. CI fully green.

@kodjima33
kodjima33 merged commit 4182459 into BasedHardware:main Sep 21, 2026
36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge python security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

plugins/db.py parses the session transcript buffer from Redis with eval()

4 participants