Skip to content

fix(plugins): parse the Redis transcript buffer as a literal, not code - #13664

Closed
ajanraj wants to merge 5 commits into
BasedHardware:mainfrom
ajanraj:fix/db-transcript-segments-eval
Closed

ajanraj wants to merge 5 commits into
BasedHardware:mainfrom
ajanraj:fix/db-transcript-segments-eval

Conversation

@ajanraj

@ajanraj ajanraj commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Problem

get_upsert_segment_to_transcript_plugin in plugins/db.py parsed the per-session transcript buffer read from Redis with eval(). eval executes arbitrary expressions, so any non-literal value stored under plugin:{plugin_id}:session:{session_id}:transcript_segments — a manual redis-cli edit, a sibling writer on the shared instance, corruption — ran as Python inside the plugin process, which holds OpenAI and Redis credentials. Malformed values also crashed the /mentor webhook until the key expired.

Issue: #13663

Fix

  • ast.literal_eval(segments.decode('utf-8')) parses the identical format str(segments) writes — TranscriptSegment fields are all str/int/float/bool/None, so repr output is always a valid literal — while rejecting anything executable. In-flight session buffers keep working; stored payloads raise instead of running.
  • A stored literal that parses to a non-list shape resets to an empty buffer instead of crashing extend/TranscriptSegment(**x).
  • SET key value ex=300 writes the value and TTL atomically (a crash between set and expire previously left the key persistent); return annotation corrected to List[TranscriptSegment].

Tests

plugins/test_db_transcript_segments.py stubs redis/models and exercises the real function: segment round-trip, a stored call-expression raising without executing (pre-fix it ran — the test fails RED on main), and a value written in the previous format still reading correctly. Registered in the checks manifest as plugin-db-transcript-segments-tests (local + ci lanes, hermetic — no Redis needed).

Verification

  • python3 plugins/test_db_transcript_segments.py → 3 tests, all pass (payload test failed pre-fix: eval executed the sentinel write)
  • Pre-push manifest gate: all selected checks pass

Failure-Class: none

Review in cubic

get_upsert_segment_to_transcript_plugin ran eval() on the raw bytes read
from the session transcript key in Redis. eval() executes arbitrary
expressions, so any value that is not a plain repr literal under that key
ran as Python inside the plugin process (which holds OpenAI and Redis
credentials), and any malformed value crashed the mentor webhook.

ast.literal_eval() parses the identical format str(segments) writes while
rejecting anything that is not a literal, so in-flight session buffers
keep working and stored payloads raise instead of executing.

Regression test stubs redis and models, exercises the real function, and
asserts a stored call expression raises without running.

Verified: python3 plugins/test_db_transcript_segments.py — 3 tests
fail on the payload test pre-fix, all pass post-fix.

Failure-Class: none
- reset to an empty buffer when the stored literal parses to a non-list
  shape instead of crashing or extending with dict keys
- decode explicitly as utf-8 like the file's other getters
- correct the return annotation to List[TranscriptSegment]
- set the value and the 5-minute TTL atomically via SET ex= so a crash
  between SET and EXPIRE can no longer leave the key persistent

Verified: python3 plugins/test_db_transcript_segments.py — 3 passed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Moderate findings remain for malformed payload recovery and test isolation.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

Hardens Redis transcript-buffer handling by replacing eval() with safe literal parsing.

Changes:

  • Adds safe parsing and non-list handling.
  • Uses atomic Redis TTL writes.
  • Adds regression tests and CI manifest registration.
File summaries
File Description
plugins/test_db_transcript_segments.py Adds transcript persistence and security tests.
plugins/db.py Implements safe parsing and atomic expiry.
.github/checks-manifest.yaml Registers the hermetic test check.
Review details

Suppressed comments (3)

plugins/db.py:104

  • The malformed-Redis failure mode is still present for values such as b'not a literal' or [1]: literal_eval propagates SyntaxError/ValueError, and a list with a non-dict element still fails at TranscriptSegment(**segment), so /mentor can continue returning an error until the key expires. Validate the parsed list/materialized segments and clear or replace invalid buffers if avoiding that outage is part of this fix; keep the no-execution assertion for non-literal payloads.
        segments = ast.literal_eval(segments.decode('utf-8'))
        if not isinstance(segments, list):
            segments = []

plugins/test_db_transcript_segments.py:30

  • This fake Redis client discards ex, and expire() is a no-op, so the new atomic-TTL behavior is not exercised: the test suite would still pass if this regressed to the old separate set/expire sequence. Record the ex argument (or model TTL in the fake) and assert the write uses the five-minute expiration.
    def set(self, key, value, ex=None):
        self.store[key] = value

    def expire(self, key, seconds):
        return True

plugins/test_db_transcript_segments.py:86

  • This uses a predictable file in the process-wide temp directory and unconditionally unlinks it before and after the test. Parallel runs can race, and an unrelated file with this name could be deleted; use TemporaryDirectory or NamedTemporaryFile to isolate the sentinel path.
        pwned = Path(tempfile.gettempdir()) / 'omi_db_eval_pwned'
        pwned.unlink(missing_ok=True)
  • Files reviewed: 3/3 changed files
  • Comments generated: 2
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread plugins/db.py
Comment on lines +103 to +104
if not isinstance(segments, list):
segments = []
Comment thread plugins/db.py

# expire 5m
r.expire(key, 60 * 5)
r.set(key, str(segments), ex=60 * 5)

@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.

1 issue found across 3 files

Confidence score: 5/5

  • plugins/test_db_transcript_segments.py does not verify the fake client's TTL and Redis-call behavior, so a regression could make the upsert issue separate or missing expiration calls while tests still pass; record those calls and assert exactly one set(..., ex=300) without a separate expire.
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_transcript_segments.py">

<violation number="1" location="plugins/test_db_transcript_segments.py:27">
P2: Record the TTL and Redis calls in the fake client, then assert that the upsert performs one `set(..., ex=300)` call without a separate `expire`; the current tests pass even if the atomic TTL implementation regresses.</violation>
</file>

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

Re-trigger cubic

Comment thread plugins/test_db_transcript_segments.py Resolved
Comment thread plugins/db.py Resolved
return value.encode() if isinstance(value, str) else value

def set(self, key, value, ex=None):
self.store[key] = value

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: Record the TTL and Redis calls in the fake client, then assert that the upsert performs one set(..., ex=300) call without a separate expire; the current tests pass even if the atomic TTL implementation regresses.

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

<comment>Record the TTL and Redis calls in the fake client, then assert that the upsert performs one `set(..., ex=300)` call without a separate `expire`; the current tests pass even if the atomic TTL implementation regresses.</comment>

<file context>
@@ -0,0 +1,105 @@
+        return value.encode() if isinstance(value, str) else value
+
+    def set(self, key, value, ex=None):
+        self.store[key] = value
+
+    def expire(self, key, seconds):
</file context>

Review follow-ups: a stored value that is not a literal at all, or a list
containing non-dict elements, left /mentor erroring until the key expired;
the buffer now resets/filters instead. The fake Redis records the ex
argument so the atomic 300s TTL is asserted, and the exploit sentinel uses
an isolated TemporaryDirectory.

Verified: python3 plugins/test_db_transcript_segments.py — 5 passed.
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @ajanraj — this is a genuinely valuable security fix, and the verification work shows.

What I verified:

plugins/db.py

  • eval(segments) → ast.literal_eval(segments.decode('utf-8')) under except (ValueError, SyntaxError) — since UnicodeDecodeError subclasses ValueError, corrupted bytes are covered too.
  • The literal round-trip claim holds: every TranscriptSegment field (plugins/omi-plugin-sdk/src/omi_plugin_sdk/models.py) is str/int/float/bool/Optional[...], so str(segments) output always re-parses.
  • r.set(key, str(segments), ex=60*5) collapses the old set+expire pair — no persistent-key window if the process dies between them. The return annotation fix (List[dict] → List[TranscriptSegment]) matches what the function already returned; the only caller (plugins/basic/mentor.py) just uses len(...), so it's behavior-neutral.

plugins/test_db_transcript_segments.py

  • Ran the suite in a clean python:3.12 container against this branch: 5/5 pass. Ran the same tests against main's db.py: test_stored_payload_is_parsed_not_executed fails with the sentinel file actually created — the pre-fix code really did execute the stored payload, and the test has teeth. Legacy-format and non-dict-element coverage are both present, and the sys.modules stubbing is restored in finally.

.github/checks-manifest.yaml

  • Registration only (plugin-db-transcript-segments-tests, local+ci lanes, sensible triggers); Hygiene and the Backend Hermetic Merge Gate both pass on this head, so the entry works.

CI note for maintainers: the failing Dart Analyze & Tests lane is not from this PR. The analyzer errors sit in app/test/providers/deletion_consistency_test.dart / app/test/widgets/chat_content_blocks_test.dart against the ActionItemsFetcher typedef introduced by #13570 (merged yesterday; its own merge push path-skipped the Dart lane). This PR touches no Dart files, so the lane shouldn't gate this merge.

Two optional, non-blocking nits:

  • A pathological deeply-nested literal (thousands of nested brackets) can raise RecursionError/MemoryError, which the current except doesn't catch. Pre-fix eval was strictly worse here, so this is hardening at the margin, not a blocker.
  • A stored valid-literal-non-list (e.g. "42") would exercise the isinstance(segments, list) reset; an explicit test for that shape would lock the guard in.

This changes parsing of Redis-stored payloads inside a process that holds credentials — leaving for human maintainer sign-off before merge.


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 positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces python labels Sep 13, 2026
…guard

A stored deeply nested literal can exhaust the parser (RecursionError/
MemoryError); reset to an empty buffer there too. Add an explicit test for
the valid-literal-non-list path so the isinstance guard stays pinned.

Verified: python3 plugins/test_db_transcript_segments.py — 6 passed.

@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.

backend/plugins bug fix, 5/5 confidence: real linked issue (#13663), root cause explained, scoped diff, tests demonstrate red/green (eval RCE -> ast.literal_eval), CI all green. Confirmed not yet fixed on origin/main.

@ajanraj

ajanraj commented Sep 13, 2026

Copy link
Copy Markdown
Contributor Author

The same diff landed via #13713 (merged), so this PR is no longer needed. Closing — thanks for the review.

@ajanraj ajanraj closed this Sep 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Hey @ajanraj 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

positive-signal Automation verified a genuine fix/quality contribution 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.

4 participants