Skip to content

🔒 fix: use json instead of ast.literal_eval for state data - #12484

Merged
undivisible merged 5 commits into
mainfrom
security-fix-task-integrations-ast-literal-eval-5719183998940294315
Sep 7, 2026
Merged

undivisible merged 5 commits into
mainfrom
security-fix-task-integrations-ast-literal-eval-5719183998940294315

Conversation

@undivisible

@undivisible undivisible commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

🎯 What: The vulnerability fixed was the use of ast.literal_eval to parse state_data_str when retrieving OAuth state data from Redis.
⚠️ Risk: While safer than eval(), ast.literal_eval can still cause a denial-of-service (crashing the process) if provided deeply nested structures.
🛡️ Solution: Changed the serialization of state_data to use json.dumps and deserialization to use json.loads. Also updated the mocked redis payloads in tests to match the new json.dumps format. In-flight pre-migration str(dict) payloads (single quotes, 10-minute TTL) are still accepted by mapping them to JSON.

Failure-Class: none

Rebase note (2026-09-07): the branch was rebased onto current main; the former head commit 99d2c4cbca (desktop_manual config sync) was dropped because it was fully superseded by #12788 (e02d56da68, same intent + newer dashboard paths).

Verification: rebased-branch unit tests: 70 passed (test_task_integrations_oauth_atomic, test_merge_validation, test_batch_upload_storage).


PR created automatically by Jules for task 5719183998940294315 started by @undivisible


Note

Medium Risk
Touches OAuth CSRF state parsing on the task-integrations callback path; behavior change is mostly format-safe with a brittle legacy fallback, so mis-parsed state could reject valid in-flight logins briefly.

Overview
Task integration OAuth CSRF state in Redis is now written with json.dumps and read with json.loads, replacing str(dict) plus ast.literal_eval. That removes a DoS class from maliciously nested literal structures while keeping the existing atomic GETDEL consume path.

validate_and_consume_oauth_state also rejects non-dict payloads and, for a short migration window, still accepts legacy single-quote str(dict) values by normalizing quotes before json.loads (no ast).

Unit tests were updated: OAuth atomic tests use JSON fixtures; merge/batch upload import stubs set PROJECTION_FAMILY_FIELDS on the mocked models.client_processing module.

Reviewed by Cursor Bugbot for commit f767a71. Configure here.

Product invariants affected

  • INV-TASK-2

@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-06T17:16:55.836282Z f767a71 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9406559a16

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread backend/routers/task_integrations.py Resolved

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this — the core change is right, and it brings task_integrations.py in line with the sibling OAuth state handling in routers/integrations.py, which already serializes with json.dumps/json.loads. Two things need fixing before merge:

Blocking

  1. Stray pr_body.md committed at the repo root. The failure-class contract is evaluated against the PR description (the preflight pulls it from the GitHub API), never against a file in the diff — so this file doesn't satisfy the check and would land in the repo root on main. Please delete it from the branch and add Failure-Class: none on its own line in the PR description instead. That's exactly what the failing Hygiene job (failure-class-protocol → missing_declaration) is asking for: all three commits have fix: subjects and the current description has no declaration. The next push re-runs Hygiene with both fixes in place.
  2. Stale docstring in backend/tests/unit/test_task_integrations_oauth_atomic.py — lines 6–7 still read "(This handler parses the stored value with ast.literal_eval, so the fixture stores a Python repr rather than JSON.)". You updated the fixtures to json.dumps (L109, L120) but not this sentence; it now documents the opposite of the code under test.

Non-blocking observations

  • backend/routers/task_integrations.py L112/L278: the round-trip is correct — the only writer (get_oauth_url) stores json.dumps({'uid', 'app_key', 'created_at'}), all string values, and the callback's state_data.get('app_key') / ['uid'] access behaves identically on the JSON-loaded dict.
  • Rollout note: states written before deploy hold Python-repr strings; consuming one now raises inside the try and returns None (invalid_state). Keys expire after OAUTH_STATE_EXPIRY = 600s, so the blip is bounded to in-flight flows within a ~10-minute window at deploy time. Fine — just worth knowing when this ships.
  • The sibling validate_and_consume_oauth_state in routers/integrations.py additionally guards isinstance(loaded, dict) before returning; not strictly needed here since this writer only ever stores a dict, but it would be a cheap consistency win.

Requesting changes for the stray file and the stale docstring; the serialization swap itself looks good.

Automated review on behalf of the maintainers. Human sign-off specifically wanted on the OAuth state serialization change in the auth flow 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 security-review Touches auth, provider routing, secrets, or security-sensitive surfaces needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Aug 31, 2026

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

Approve only: legitimate security hardening (ast.literal_eval->json) but PR Metadata Preflight CI check is failing — hard floor blocks merge.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cursor

cursor Bot commented Sep 1, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_2003998c-6a35-4ff2-adeb-6b7abd43cab8)

@undivisible

Copy link
Copy Markdown
Collaborator Author

Addressed Git-on-my-level CRs + Codex P2:

  • deleted stray root pr_body.md
  • Failure-Class: none in the PR body
  • docstring now says json.loads / JSON fixtures
  • in-flight pre-migration str(dict) OAuth state (10-min TTL) is still accepted by mapping single quotes to JSON, without bringing back ast.literal_eval

Pushed in f80686a.

@Git-on-my-level
Git-on-my-level dismissed their stale review September 1, 2026 17:29

Resolved on f80686a: the stray pr_body.md is gone (diff is now only task_integrations.py and its unit test), the stale ast.literal_eval docstring is corrected, and Failure-Class: none is declared (failure-class-protocol passes). No remaining change requests from this review.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks — all three items from the earlier change request are verified fixed on f80686a:

  • pr_body.md is gone; the diff now touches only backend/routers/task_integrations.py and backend/tests/unit/test_task_integrations_oauth_atomic.py.
  • The stale docstring in test_task_integrations_oauth_atomic.py (L6–7) now correctly says the handler parses with json.loads and the fixture stores JSON — matching the fixtures at L109/L120.
  • Failure-Class: none is declared in the description, and failure-class-protocol passes on this head.

The serialization change itself reads right at the new head: get_oauth_url (L287) writes json.dumps(...), and validate_and_consume_oauth_state (L111–125) parses with json.loads plus a bounded fallback that maps pre-migration single-quote str(dict) payloads to JSON (fail-closed to None on anything unparseable, window bounded by the 10-minute OAUTH_STATE_EXPIRY). The new isinstance(state_data, dict) guard mirrors the sibling implementation in routers/integrations.py, and the atomic GETDEL consume path is untouched. Since the writer always stored string-only values with created_at already ISO-formatted at write time, the round-trip behavior for uid/app_key is unchanged.

One thing that is not yours: the failing PR Metadata Preflight job. It fails in firestore-query-coverage with "baseline registered_serving is 62, current inventory reports 73" — I reproduced the identical failure on unmodified main (the committed baseline is stale relative to recently merged query work; your head's coverage inventory is identical to main's). This diff adds or changes no Firestore query, so nothing here can turn it green; it should clear when the baseline regen lands (see #12480). The advisory "task_integrations.py is 905 lines" warning is likewise pre-existing.

Once that repo-side blocker clears, this just needs a fresh maintainer sign-off on the current head, since the earlier approval predates f80686a's fallback logic.

Automated review on behalf of the maintainers. Human sign-off specifically wanted on the current head's OAuth state parse-fallback in the auth flow 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 the positive-signal Automation verified a genuine fix/quality contribution label Sep 1, 2026

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

Genuine CSRF/DoS-hardening fix replacing ast.literal_eval with json.dumps/loads for OAuth state stored in Redis, with backward-compat parsing for legacy single-quote values and updated tests; would score 5/5 on the confidence gate but 'PR Metadata Preflight' and 'Hygiene' required checks are actively failing, which trips the CI hard floor. Approve-only, held from merge on CI.

@undivisible
undivisible force-pushed the security-fix-task-integrations-ast-literal-eval-5719183998940294315 branch from f80686a to 9103753 Compare September 5, 2026 10:28
@cursor

cursor Bot commented Sep 5, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_31a5a7fd-956e-453e-8322-173df5fffe3b)

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 910375370a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Pre-migration writers stored str(dict) (single quotes). Those keys
# expire after OAUTH_STATE_EXPIRY (10 min). Map them to JSON without
# reintroducing ast.literal_eval.
state_data = json.loads(raw.replace("'", '"'))

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 Badge Preserve quoted UIDs when parsing legacy state

For an in-flight state whose UID contains a single or double quote, blindly replacing every apostrophe does not produce the JSON encoding of the old Python representation; for example, str({'uid': "o'connor"}).replace("'", '"') raises JSONDecodeError. The authentication layer can return unvalidated UID strings, and because GETDEL has already consumed the record, the affected OAuth callback cannot be retried. Fresh evidence beyond the earlier migration comment is this quoted-UID case; the updated tests exercise only new JSON records and never the compatibility branch, so parse the legacy representation without altering string contents and add a regression case.

AGENTS.md reference: AGENTS.md:L32-L32

Useful? React with 👍 / 👎.

Comment on lines +115 to +119
except json.JSONDecodeError:
# Pre-migration writers stored str(dict) (single quotes). Those keys
# expire after OAUTH_STATE_EXPIRY (10 min). Map them to JSON without
# reintroducing ast.literal_eval.
state_data = json.loads(raw.replace("'", '"'))

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 Badge Record successful use of the legacy-state fallback

During the rollout window, a callback that reaches this newly added branch switches from failed JSON parsing to a recovered legacy serialization mode, but successful recovery emits no fallback telemetry. Operators therefore cannot determine whether old state records are still being consumed or whether the compatibility path can safely be removed; call the shared record_fallback helper with a recovered outcome after the legacy parse succeeds.

AGENTS.md reference: backend/AGENTS.md:L304-L304

Useful? React with 👍 / 👎.

@undivisible
undivisible force-pushed the security-fix-task-integrations-ast-literal-eval-5719183998940294315 branch from 3aad6f2 to 69348e1 Compare September 5, 2026 11:27
@cursor

cursor Bot commented Sep 5, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_b75964d4-c7c2-418e-8aac-04378860838d)

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified on 99d2c4c — the two Sep 5 commits are clean CI repair on top of the security fix, and the previously failing checks (PR Metadata Preflight, Hygiene, hermetic merge gate) are green on this head.

Security fix (unchanged since f80686a, re-verified at head):

  • backend/routers/task_integrations.py — get_oauth_url (L287) writes json.dumps(state_data); validate_and_consume_oauth_state (L111–125) parses with json.loads, keeps the bounded single-quote→JSON fallback for pre-migration str(dict) payloads (window bounded by the 10-minute OAUTH_STATE_EXPIRY), and the isinstance(state_data, dict) guard fails closed to None. No ast usage remains, and this now matches the sibling OAuth state handling in routers/integrations.py.

CI-repair commits:

  • backend/config/task_intelligence_sources_v1.json — the retired owner paths (WhatMattersNowSection.swift, DashboardPage.swift) were removed from the tree by One chat shell: every content block renders everywhere, plus chat ergonomics (#12598) #12607 (verified absent on main); DashboardViewModel.swift exists and defines all four new goal anchors (createGoal L128, deleteGoal L197, updateGoal/updateGoalProgress L144). The dropped DesktopAutomationActivationActions.swift task anchors referenced symbols that no longer occur in that file, so removing them is correct. Config-only edit; no runtime behavior change.
  • backend/tests/unit/test_batch_upload_storage.py and backend/tests/unit/test_merge_validation.py — correct isolation stubs: models.client_processing.PROJECTION_FAMILY_FIELDS = frozenset({'client_processing'}) matches the real backend/models/client_processing.py (L46) exactly.
  • backend/tests/unit/test_task_integrations_oauth_atomic.py — fixtures and docstring consistently moved to JSON (json.dumps at both stores, L109/L120 region).

Both maintainer approvals (Sep 1 / Sep 3) predate this head, so keeping security-review / needs-maintainer-review for a final sign-off on 99d2c4c — an OAuth state-parsing change followed by a post-#12607 config sync is exactly the head that deserves one last human look before merge. Nothing blocking found from automation.


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

undivisible and others added 5 commits September 7, 2026 01:05
Failure-Class: none

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Failure-Class: none

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
utils.conversations.merge_conversations imports
utils.conversations.projection_payload, which does
`from models.client_processing import PROJECTION_FAMILY_FIELDS`. The
module-scoped merge fixtures in test_batch_upload_storage.py and
test_merge_validation.py stub `models` with an empty __path__, so the real
models.client_processing could not be found and every merge-fixture test
errored with ModuleNotFoundError on CI (job 101292145767).

Same fix as #12776: add models.client_processing to the model_submods dict
and, after the stub loop, replace the MagicMock with a real frozenset so
strip_client_processing cannot hang iterating a mock.

Test-only change; no production code touched.

Verified: cd backend && python -m pytest tests/unit/test_batch_upload_storage.py tests/unit/test_merge_validation.py -q --tb=line
Before: 24 passed, 43 errors (ModuleNotFoundError: No module named 'models.client_processing')
After: 67 passed in 2.49s

Failure-Class: none
@undivisible
undivisible force-pushed the security-fix-task-integrations-ast-literal-eval-5719183998940294315 branch from 99d2c4c to f767a71 Compare September 6, 2026 17:13
@cursor

cursor Bot commented Sep 6, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_dec059c0-6599-4cc6-a81a-af1f85c65982)

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified on the rebased head f767a71 — summarizing the state for the post-rebase re-review:

Security fix (unchanged through the rebase, re-verified at this head):

  • backend/routers/task_integrations.py — get_oauth_url writes json.dumps(state_data); validate_and_consume_oauth_state parses with json.loads, keeps the single-quote→JSON fallback for in-flight pre-migration str(dict) payloads (bounded by the 10-minute OAUTH_STATE_EXPIRY), and the isinstance(state_data, dict) guard fails closed to None. No ast import or literal_eval call remains, and the shared oauth_state: namespace now has both writers (task_integrations.py, routers/integrations.py) in JSON form with matching dict guards. Against the new base (1c196bb), ast.literal_eval + str(state_data) are still what main does, so the fix is still needed.
  • The commit dropped in the rebase (99d2c4cbca, desktop_manual config sync) is superseded by fix(backend): refresh task intelligence desktop owner paths after #12607 #12788 — the remaining diff is only the security fix plus test updates.
  • backend/tests/unit/test_task_integrations_oauth_atomic.py — fixtures store json.dumps(...) and the module docstring now correctly documents json.loads; both GETDEL single-use/replay tests are retained.

Test-harness notes (no production behavior):

  • backend/tests/unit/test_batch_upload_storage.py and backend/tests/unit/test_merge_validation.py — the added models.client_processing stub entries with a concrete frozenset({"client_processing"}) are the right repair: main now defines PROJECTION_FAMILY_FIELDS in models/client_processing.py, and a bare MagicMock attribute would satisfy membership checks as a truthy MagicMock instead of behaving like a frozenset.

CI on f767a71: Backend Hermetic Merge Gate, Hermetic Backend E2E, Hygiene, Formatting, and the image-smoke suite are all green — the metadata/hygiene failures that held the Sep 3 approval are resolved.

Non-blocking nit: the legacy fallback's raw.replace("'", '"') is character-blind, so a legacy payload containing a quote character inside a value would fail to parse and return None (the user simply retries the flow). Given the ≤10-minute window and that uid/app_key values don't realistically contain quotes, that's acceptable as-is.

Since the rebase produced new commit SHAs, both earlier approvals predate this head — re-confirmation from a maintainer on f767a71 is the remaining step before merge.

by AI on behalf of David

@undivisible
undivisible merged commit 85debae into main Sep 7, 2026
45 checks passed
@undivisible
undivisible deleted the security-fix-task-integrations-ast-literal-eval-5719183998940294315 branch September 7, 2026 06:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants