Skip to content

fix(matrix): block plaintext attachments in encrypted rooms - #118609

Merged
steipete merged 4 commits into
mainfrom
codex/qa0803-matrix-encrypted-upload
Aug 3, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/qa0803-matrix-encrypted-upload

Conversation

@steipete

@steipete steipete commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Make the Matrix outbound owner authoritatively verify room encryption before plaintext text, attachments, or thumbnails can leave the client.
  • Fail closed unless authenticated room-state lookup conclusively returns Matrix 404 M_NOT_FOUND; preserve persistent crypto-state downgrade protection and require a hydrated SDK room/backend.
  • Validate actual final and retry payloads, reject plaintext media/location thumbnails in encrypted rooms, remove exposed filename/MIME metadata from encrypted uploads, and reject caller-forged encrypted/redaction wire event types.

Exact-head real Matrix homeserver and authenticated Gateway proof

Reviewed head: 6ddbffc783029d6223af5eac810e1b5ecc1c1ba9.

A real pinned Tuwunel homeserver, its actual HTTP recording proxy, three ephemeral accounts, an encrypted and normal Matrix room, and an actual token-authenticated running OpenClaw Gateway were used. The Matrix account deliberately had encryption disabled. The actual running Gateway was independently verified to load the reviewed bundled source plugin—not stale built artifacts—before every scenario.

Literal redacted runtime transcript:

{"phase":"authoritative-room-state","encryptedStatus":200,"encryptedAlgorithm":"m.megolm.v1.aes-sha2","plainStatus":404,"plainErrcode":"M_NOT_FOUND"}
{"phase":"reviewed-plugin-runtime","id":"matrix","status":"loaded","origin":"bundled","source":"extensions/matrix/index.ts","preuploadOwnerGuard":true,"legacyUploadHelper":false}
{"phase":"actual-gateway-plugin-loader","sameProcessSourceProvenance":true,"origin":"bundled","source":"extensions/matrix/index.ts","packageLocalBuiltArtifacts":false}
{"phase":"actual-gateway-live-registry","matrixLoaded":true,"origin":"bundled","failurePhase":null}
{"phase":"actual-gateway-matrix-account","configured":true,"enabled":true,"running":true,"connected":true,"lifecycle":"ready","lastError":null}
{"case":"encrypted-room-attachment","cliExit":1,"actionableGuidance":true,"mediaUploads":0,"plaintextTimelineSends":0,"encryptedTimelineSends":0,"routes":[]}
{"case":"encrypted-room-text","cliExit":1,"actionableGuidance":true,"mediaUploads":0,"plaintextTimelineSends":0,"encryptedTimelineSends":0,"routes":[]}
{"case":"ordinary-room-attachment","cliExit":0,"mediaUploads":1,"plaintextTimelineSends":1,"encryptedTimelineSends":0,"routes":[{"method":"POST","route":"/_matrix/media/v3/upload","status":200},{"method":"PUT","route":"/_matrix/client/v3/rooms/{roomId}/send/m.room.message/{transactionId}","status":200}]}
{"case":"ordinary-room-text","cliExit":0,"mediaUploads":0,"plaintextTimelineSends":1,"encryptedTimelineSends":0,"routes":[{"method":"PUT","route":"/_matrix/client/v3/rooms/{roomId}/send/m.room.message/{transactionId}","status":200}]}
{"result":"PASS","cases":4,"providerCalls":0,"actualHomeserver":"pinned-tuwunel","actualGatewayAuth":"token"}

The two encrypted-room actions both fail visibly with guidance to enable encryption before any homeserver media upload or timeline send. The ordinary-room controls prove real attachment upload and normal plaintext delivery still work. No provider calls or real user credentials were involved.

Security owner boundaries

  • Cached missing room state is unknown; only authenticated 404 M_NOT_FOUND proves a plaintext room. Network errors, authentication failures, generic 404s, and malformed state fail closed.
  • Persisted SDK crypto state prevents server/cache downgrade. A real room with either cached encryption state or persistent backend-positive state is usable; the SDK does not require both.
  • Main attachments and thumbnails refresh authoritative room policy immediately before upload; encrypted ciphertext uses application/octet-stream without exposing original filename.
  • Final sendMessage, generic sendEvent, and actual pending retry payloads reject plaintext attachment or thumbnail references, including standard location thumbnails; committed SENT retries preserve idempotency.
  • Generic callers cannot forge reserved m.room.encrypted or redaction wire types to trick the installed SDK into skipping encryption.
  • Dedicated redaction, polls, standard plaintext-room behavior, custom text URLs, and protocol-required plaintext m.reaction remain unchanged. Reactions intentionally remain plaintext under the Matrix dependency contract; the only shipped reaction producer constructs the canonical safe annotation shape.
  • Temporary authoritative-state unavailability intentionally fails closed even if an old durable retry could otherwise proceed; confidentiality takes priority over transient availability.

Verification

  • Deterministic red-before-green regressions cover state/cache misses, downgrade, no crypto, no hydrated room, text, uploads, metadata, race transitions, mixed thumbnails, retry payloads, generic events, reserved wire spoofing, and location thumbnails.
  • Complete affected and sibling suites: 230 passed.
  • Actual matrix-js-sdk room-state, MatrixError, event-encryption, media-upload, reaction, redaction, and retry contracts inspected directly.
  • Independent final structured security review: clean, confidence 0.94; independent test-only CI correction review: clean, confidence 0.99.
  • Required exact-head hosted CI gate: success.
  • Production-code delta: +39 lines for concrete encrypted-room confidentiality and upstream SDK wire-event invariants.

Maintainer decision: accept fail-closed behavior for unknown encrypted state; any lookup outcome except an authenticated SDK MatrixError with HTTP 404 and M_NOT_FOUND intentionally blocks plaintext sends with actionable operator guidance.

@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: XS maintainer Maintainer-authored PR labels Aug 3, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. labels Aug 3, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 3, 2026, 7:19 AM ET / 11:19 UTC.

ClawSweeper review

What this changes

The branch makes Matrix classify encrypted rooms before outbound sends and attachment or thumbnail uploads, rejecting plaintext media when encryption is unavailable or the room state changes during preparation.

Merge readiness

⛔ Blocked until real behavior proof is added - 5 items remain

This PR remains necessary: current main can still take the media-upload path without first enforcing the encrypted-room boundary, while this branch moves that decision to the Matrix client owner and rechecks it at upload and wire-dispatch boundaries. The patch has no concrete correctness finding from source review, but the protected maintainer label, its fail-closed upgrade behavior, unavailable direct SDK source, and missing inspectable real Matrix proof mean it should not merge yet.

Priority: P0
Reviewed head: 6ddbffc783029d6223af5eac810e1b5ecc1c1ba9

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The owner-boundary repair and regression coverage look solid, but the missing real Matrix behavior proof remains a merge gate.
Proof confidence 🧂 unranked krab (1/6) Needs real behavior proof before merge: The PR body reports deterministic tests but contains no inspectable redacted after-fix Matrix runtime transcript, terminal output, recording, log, or artifact showing rejection before a plaintext upload; add that proof and update the PR body to trigger re-review automatically, or ask a maintainer to comment @clawsweeper re-review if needed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR body reports deterministic tests but contains no inspectable redacted after-fix Matrix runtime transcript, terminal output, recording, log, or artifact showing rejection before a plaintext upload; add that proof and update the PR body to trigger re-review automatically, or ask a maintainer to comment @clawsweeper re-review if needed.
Evidence reviewed 6 items Current-main gap: Current main derives media encryption in uploadMediaMaybeEncrypted from an optional crypto facade; it has no mandatory room-preparation check at the media-upload boundary. The normal send path only asks for the wire type when durable identity is present.
PR safety boundary: At the reviewed head, uploads call prepareRoomForMessageSend immediately before choosing encrypted versus plaintext bytes; encrypted rooms without crypto throw before uploadContent, and the client owner rejects event content that still references plaintext media after a room becomes encrypted.
Retry and final-dispatch coverage: The branch also prepares both a failed transaction retry and a normal sendMessage immediately before matrix-js-sdk dispatch, closing paths that could otherwise bypass the earlier media decision.
Findings None None.
Security None None.

How this fits together

The Matrix channel resolves a room, creates message and media content, uploads attachments to the homeserver, and then sends the event through matrix-js-sdk. The changed decision point determines whether those media bytes may be uploaded plaintext or must be encrypted and sent only after the room is ready.

flowchart LR
  A[Outbound Matrix request] --> B[Resolve destination room]
  B --> C[Classify room encryption]
  C --> D[Prepare encrypted room]
  D --> E[Upload media or thumbnail]
  E --> F[Dispatch Matrix event]
  C --> G[Reject unsafe plaintext media]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR body reports deterministic tests but contains no inspectable redacted after-fix Matrix runtime transcript, terminal output, recording, log, or artifact showing rejection before a plaintext upload; add that proof and update the PR body to trigger re-review automatically, or ask a maintainer to comment @clawsweeper re-review if needed.
  • Resolve merge risk (P1) - Unknown locally cached rooms now require a homeserver state lookup before a plaintext send; any non-404 response fails closed, so upgrade proof must show the intended operator-visible failure and normal plaintext-room behavior.
  • Resolve merge risk (P1) - The direct [email protected] source contract for the new MatrixError classification could not be independently inspected because no dependency source was installed and network/DNS was unavailable.
  • Resolve merge risk (P1) - The branch still lacks inspectable real Matrix evidence that an encrypted room rejects before the homeserver receives a plaintext attachment or thumbnail.
  • Complete next step (P2) - The protected maintainer label and missing real Matrix proof require human merge handling rather than an automated repair lane.
Agent review details

Security

None.

PR surface

Source +39, Tests +601. Total +640 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 108 69 +39
Tests 4 637 36 +601
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 745 105 +640

Review metrics

Metric Value Why it matters
Production vs test delta production +108/-69 (net +39); tests +637/-36 (net +601) The production growth is tied to a named confidentiality boundary and is accompanied by substantially expanded Matrix regression coverage.

Merge-risk options

Maintainer options:

  1. Add exact-head encrypted-media proof (recommended)
    Before merge, add a redacted Matrix runtime transcript, terminal capture, or log showing an encrypted room rejects the attachment before any plaintext upload, plus a normal plaintext-room control run.
  2. Accept the fail-closed upgrade behavior
    Merge with an explicit maintainer acceptance that unknown local room state now performs a homeserver lookup and blocks sends on non-404 lookup failures rather than risking plaintext media disclosure.

Technical review

Best possible solution:

Keep one canonical encrypted-room decision in the Matrix client owner, preserve normal plaintext-room delivery, and add redacted real-runtime proof that encrypted media is rejected before any plaintext upload while the fail-closed recovery message tells the operator what to do next.

Do we have a high-confidence way to reproduce the issue?

No, not at high confidence from this read-only environment: current-main source exposes the unsafe optional-crypto upload decision and the branch provides targeted regression tests, but no local execution or inspectable real Matrix run was available.

Is this the best way to solve the issue?

Yes at the architectural level: moving encrypted-room classification to the outbound client owner and rechecking at upload and dispatch boundaries is safer than relying on a late SDK rejection. Merge confidence remains incomplete until the direct SDK contract and real after-fix behavior are evidenced.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against e87fb689b533.

Labels

Label justifications:

  • P0: A plaintext attachment in an encrypted Matrix room is a direct confidentiality failure on a channel security boundary.
  • merge-risk: 🚨 compatibility: Existing Matrix deployments may newly block sends when room state is unknown or encryption is unavailable, requiring retry or sync recovery.
  • merge-risk: 🚨 security-boundary: The patch changes the decision that prevents media bytes and metadata from leaving through a plaintext homeserver upload path.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR body reports deterministic tests but contains no inspectable redacted after-fix Matrix runtime transcript, terminal output, recording, log, or artifact showing rejection before a plaintext upload; add that proof and update the PR body to trigger re-review automatically, or ask a maintainer to comment @clawsweeper re-review if needed.

Evidence

What I checked:

  • Current-main gap: Current main derives media encryption in uploadMediaMaybeEncrypted from an optional crypto facade; it has no mandatory room-preparation check at the media-upload boundary. The normal send path only asks for the wire type when durable identity is present. (extensions/matrix/src/matrix/send/media.ts:300, e87fb689b533)
  • PR safety boundary: At the reviewed head, uploads call prepareRoomForMessageSend immediately before choosing encrypted versus plaintext bytes; encrypted rooms without crypto throw before uploadContent, and the client owner rejects event content that still references plaintext media after a room becomes encrypted. (extensions/matrix/src/matrix/send/media.ts:263, 6ddbffc78302)
  • Retry and final-dispatch coverage: The branch also prepares both a failed transaction retry and a normal sendMessage immediately before matrix-js-sdk dispatch, closing paths that could otherwise bypass the earlier media decision. (extensions/matrix/src/matrix/sdk/client-core.ts:212, 6ddbffc78302)
  • Regression coverage: The supplied branch tests cover encrypted primary media, encrypted thumbnails, plaintext rooms, and a room becoming encrypted while an image thumbnail is prepared; the latter expects no event dispatch after detecting unencrypted content. (extensions/matrix/src/matrix/send.test.ts:937, 6ddbffc78302)
  • Area provenance: Current-main blame attributes the pre-PR wire-type and media-upload behavior to the recent Matrix state/media work, while history shows subsequent durable-send work in the same client area. (extensions/matrix/src/matrix/sdk/client-core.ts:219, bd23864508c6)
  • Proof and dependency gap: The PR body reports focused tests, but no redacted after-fix Matrix transcript, terminal output, runtime log, recording, or artifact is available in the supplied discussion. Direct matrix-js-sdk 41.9.0 source was not installed locally, and the network/DNS failure prevented fetching it or GitHub evidence for independent contract inspection. (extensions/matrix/package.json:15, e87fb689b533)

Likely related people:

  • steipete: Peter Steinberger authored the current PR and prior merged Matrix state/media work that appears in the current-main history for the affected client and media paths. (role: feature owner and recent area contributor; confidence: high; commits: 9922ea02e962, bd23864508c6; files: extensions/matrix/src/matrix/sdk/client-core.ts, extensions/matrix/src/matrix/send/media.ts)
  • joshavant: Recent durable-send reconciliation work touches the same outbound Matrix client flow, including the retry behavior this patch now prepares before resend. (role: recent adjacent contributor; confidence: medium; commits: 07b7d6446ca1; files: extensions/matrix/src/matrix/sdk/client-core.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Post redacted exact-head evidence showing encrypted attachment rejection before any plaintext uploadContent call and a successful plaintext-room control case.
  • Allow exact-head CI to complete, then retain the focused Matrix suite evidence with the proof.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-03T09:33:20.855Z sha c6653e6 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-03T09:41:38.181Z sha b64fe6d :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-03T11:08:50.555Z sha 76d3b0a :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Aug 3, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 3, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Aug 3, 2026
@steipete
steipete merged commit 2a8f2e6 into main Aug 3, 2026
115 of 117 checks passed
@steipete
steipete deleted the codex/qa0803-matrix-encrypted-upload branch August 3, 2026 11:33
@steipete

steipete commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 4, 2026
…#118609)

* fix(matrix): block plaintext uploads to encrypted rooms

* test(matrix): spy on room encryption detection safely

* fix(matrix): enforce encrypted room confidentiality at outbound owner

* test(matrix): keep delivery trace client aligned with send owner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant