Skip to content

fix(channels): authorize approval responders - #9574

Merged
JordanTheJet merged 21 commits into
zeroclaw-labs:masterfrom
jstar0:fix/channel-approval-responder-authorization
Sep 3, 2026
Merged

JordanTheJet merged 21 commits into
zeroclaw-labs:masterfrom
jstar0:fix/channel-approval-responder-authorization

Conversation

@jstar0

@jstar0 jstar0 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Base branch: master
  • What changed and why:
    • Bind pending Telegram, Slack, Lark, and Matrix tool approvals to the chat or room that received the prompt.
    • Resolve an approval only when the replying identity is allowed by the adapter's live peer resolver and the reply arrives in that original destination.
    • Distinguish an unknown approval token from a known-but-rejected or consumed token so rejected Slack and Matrix text replies cannot become normal agent messages.
    • Authenticate encrypted Lark/Feishu webhook envelopes against the exact raw body with the existing Encrypt Key before CBC decryption or routing. Plaintext callbacks compare the event's header.token to the configured Verification Token.
    • Register a Lark pending approval before the outbound card send, attach the returned message_id only if that entry is still present, and remove it on send failure only when the same request remains so an early operator callback still resolves.
    • Compare signed Lark webhook digests with the existing constant-time helper after normalizing a 64-hex signature. Missing, malformed, or partial signatures continue to fail closed.
    • Gate the shared approval resolver to its Matrix, Slack, and Telegram consumers so the strict no-default-feature workspace build remains warning-clean without suppressing dead-code diagnostics.
    • Add deterministic authorization coverage for all four adapters, including mocked Telegram getUpdates, Slack polling, Slack Socket Mode interactive envelopes, Matrix sync, and Lark's HTTP callback handler.
  • Scope boundary: This adds no configuration keys, principal model, network call, or Discord/WhatsApp approval behavior. It uses the existing Lark encrypt_key and verification_token at the HTTP ingress boundary; webhook mode now fails closed at startup when neither authentication setting is configured.
  • Blast radius: Interactive and text-reply approval handling in Telegram, Slack, Lark, and Matrix. Lark card send now registers pending state first; send-failure cleanup removes that entry only if a concurrent callback has not already consumed it. Timeout cleanup is otherwise unchanged.
  • Linked issue(s): Fixes [Bug]: interactive approval responses are accepted from any chat member on telegram, slack, lark and matrix #9387. Related fix(runtime): stop reporting an unanswerable approval as a user denial #9423 handles approval provenance rather than responder authentication.
  • Labels: bug, dependencies, channel, config, runtime, channel:slack, channel:telegram, channel:matrix, trusted contributor, channel:lark, domain:security, risk:high, size:L

Testing (required)

How you can test (when useful)

  • Reviewer testing requested? Yes; the authorization boundary is observable with the same steps on master and this branch.
  • Interface(s) exercised: channel:telegram, channel:slack, channel:lark, and channel:matrix.
  • Visual interface changed? N/A; this is a server-side webhook and approval-routing change.
  • Setup / preconditions: Configure one allowed operator and one non-allowed member in a shared chat or room, run supervised mode, and trigger a tool approval.
  • Steps to run: From the non-allowed member, choose Approve, Deny, or Always, then repeat from a different chat or room. Finally answer as the allowed operator in the original destination.
  • Expected on this branch (after): Rejected replies do not consume the pending approval or create an agent turn. The allowed operator can still resolve it in the original destination. Tampered or otherwise unauthenticated encrypted Lark callbacks fail at raw-body authentication before CBC decryption; valid signed encrypted callbacks and token-authenticated plaintext callbacks continue to route normally. A Lark approval card that is clicked after the provider accepts the send, but before that send returns, still resolves as an operator decision.
  • Prior behavior on master (before): Matching approval actions or tokens can resolve without responder and destination binding; in affected text paths, a rejected known token can also be dispatched as an ordinary message.

How I tested

  • CI checks relied on and why they cover this change: Formatting, focused Lark Clippy, the four-adapter approval suite, and the Lark webhook suite cover the changed crate and feature surface on this head. Hosted CI will re-run the workspace lint, test, and platform gates. The new Lark tests cover eventual approval resolution with a delayed send and functional signature acceptance/rejection through the constant-time helper; the delayed-send test does not establish callback-before-send-return.
  • Known CI coverage gap, if any: No live third-party channel credentials were used. The deterministic tests cover the production-owned ingress and authorization paths without provider network access.
  • Commands run and tail output:
cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval -- --nocapture
# test result: ok. 56 passed; 0 failed

cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark webhook_ -- --nocapture
# test result: ok. 9 passed; 0 failed

cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark --lib request_approval_registers_before_send -- --nocapture
# test result: ok. 1 passed; 0 failed

cargo clippy --locked -p zeroclaw-channels --no-default-features --features channel-lark --all-targets -- -D warnings
# completed with no diagnostics

cargo fmt --all -- --check
git diff --check origin/master...HEAD
# both exited 0
  • Beyond CI, what did you manually verify? Reviewed every pending-approval removal in the four adapters. The mocked Telegram long-poll test verifies two rejected callback updates are acknowledged, preserve the pending entry, and emit no ChannelMessage; the Slack tests drive both polling and Socket Mode interactive dispatch; the Matrix test sends timeline events through the registered sync handlers; and the Lark HTTP handler test verifies that invalid-padding and padding-valid/non-JSON encrypted envelopes both return the same 401 invalid authentication response before decryption, retain pending approval state, and do not affect a valid signed encrypted callback. The new Lark transport-seam test delays the send and verifies eventual Operator/Approve resolution, but it does not require the callback to complete before the send response returns. The new signature test accepts uppercase 64-hex digests and rejects prefix, suffix, truncated, and lengthened values through the constant-time helper. These paths verify live allowlist decisions, destination matching, retained pending state, webhook authentication, and dispatch suppression. I did not use live Telegram, Slack, Lark, or Matrix credentials.
  • If any command was intentionally skipped, why: Live provider-channel smoke tests require external credentials and were intentionally not run.

Security & Privacy Impact (required)

  • New permissions, capabilities, or file system access scope? No new permissions; approval resolution is narrowed to the existing allowlist and originating destination.
  • New external network calls? No
  • Secrets / tokens / credentials handling changed? Existing Lark Encrypt Key and Verification Token settings are used only at the HTTP callback boundary; encrypted envelopes are authenticated against the exact raw request body before CBC decryption, decrypted in memory only after successful authentication, and no values are logged, exposed, or persisted. Signed webhook digests are compared with the existing constant-time helper after 64-hex normalization. Webhook startup fails closed when both authentication settings are absent.
  • PII, real identities, or personal data in diff, tests, fixtures, or docs? No
  • Prompt injection or untrusted model-visible text introduced/changed? No
  • If any Yes, describe the risk and mitigation: Replies that previously resolved approvals despite missing responder or destination authorization are now rejected by design. Lark HTTP callbacks reject invalid provider authentication before decryption or approval routing and preserve the existing fail-closed approval checks.

Compatibility (required)

  • Backward compatible? No; this intentionally tightens the approval authorization contract for untrusted responders, cross-destination replies, and unauthenticated Lark HTTP callbacks.
  • Config / env / CLI surface changed? No new surface; existing Lark encrypt_key enables encrypted signed webhook delivery, while existing verification_token authenticates plaintext callbacks and URL verification. Webhook mode requires at least one of these existing settings.
  • Rust/MSRV/toolchain floor changed? No
  • If backward compatibility is No or either surface/floor question is Yes: No schema migration is required. Configure the intended operator in the existing peer allowlist, answer in the chat or room where the approval prompt was sent, and configure the existing Lark authentication setting that matches the provider callback mode.

Rollback (required for medium/high-risk PRs)

  • Fast rollback command/path: git revert cd61058cf 1e4ddfd8 bdc2b4c5 6137335d 74cd45b2 ef173834 afb3f0f0 b7b47988; no data or configuration migration is required.
  • Feature flags or config toggles: None
  • Observable failure symptoms: A valid allowed operator cannot resolve an approval from its original destination, or a correctly configured Lark webhook rejects a callback; channel logs report a rejected approval response or invalid callback/payload authentication. Webhook startup fails clearly when both authentication settings are absent.

Supersede Attribution (required only when Supersedes # is used)

N/A; this PR does not supersede another contribution.

@jstar0
jstar0 requested review from Audacity88 and tidux as code owners July 31, 2026 05:42
@github-actions github-actions Bot added channel Auto scope: src/channels/** changed. channel:slack Auto module: channel/slack changed. channel:telegram Auto module: channel/telegram changed. channel:matrix Auto module: channel/matrix changed. channel:lark Auto module: channel/lark changed. labels Jul 31, 2026
@ZeroClaw-Bot

ZeroClaw-Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

I reviewed PR #9574 at head d2e9c75c407db93843fa4ff8e34b8093421a34b3 against origin/master...HEAD. The 11-file, four-channel change is broad but coherent around one security boundary; the shared resolver and the Telegram, Slack, and Matrix ingress tests are useful. One security-critical test boundary remains unproven.

🔴 Blocking — Lark approval authorization is still tested below the production ingress

The new card_action_ingress_suppresses_rejected_approval_envelopes test in crates/zeroclaw-channels/src/lark.rs:5884-5979 constructs already-parsed JSON envelopes, extracts header.event_type and event itself at :5953-5960, and calls handle_card_action_ingress directly. Its subsequent parse_event_payload assertion only verifies that a card.action.trigger value is not treated as an ordinary message.

Neither production front door is exercised by this test:

  • listen_ws decodes the protobuf frame into LarkEvent and routes it at crates/zeroclaw-channels/src/lark.rs:1267-1275.
  • listen_http receives the Axum JSON payload, extracts /header/event_type and /event, and routes it at crates/zeroclaw-channels/src/lark.rs:3597-3607.

Therefore the regression stays green if protobuf/event deserialization, webhook extraction, or either wrapper's short-circuiting regresses. The authorization helper's state transitions are covered, but the security decision is not yet proven at the Lark production boundary. Add a deterministic test through the real webhook or WebSocket wrapper (or a shared router that is invoked by both wrappers) with a production-shaped card.action.trigger; verify that unauthorized and wrong-chat taps retain the pending approval, an authorized tap resolves it, and no ordinary ChannelMessage is emitted. The existing Telegram getUpdates, Slack polling, and Matrix sync tests show the intended boundary-level coverage.

✅ Resolved — Known approval replies no longer fall through

PendingApprovalResolution now distinguishes NotFound from rejected, resolved, and closed-receiver approvals. Slack and Matrix suppress every known token result, while Telegram and Lark consume callback events before ordinary message dispatch. The focused four-channel suite passes, including unauthorized/wrong-destination cases, so the earlier Slack/Matrix fall-through concern is addressed.

✅ Resolved — PR label metadata is synchronized

The live PR labels and the labels listed in the current PR body match; the earlier stale-label concern does not remain.

🟢 What looks good — One shared authorization boundary

The change keeps pending approval state as the source of truth, resolves the current peer allowlist at response time, binds responses to the originating destination, and retains pending entries after rejected responses so the legitimate operator can still answer. The adapter-specific identity handling is appropriately fail-closed: Telegram accepts either allowlisted username or numeric user ID, Matrix uses the canonical room ID, and Lark checks the card operator and chat ID.

Validation

  • cargo fmt --all -- --check — passed.
  • git diff --check origin/master...HEAD — passed.
  • cargo test -p zeroclaw-channels --locked --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval -- --nocapture — 50 passed, 0 failed.
  • Current-head GitHub checks were green for the required gate, formatting, lint, tests, security, parallel runtime, and platform/build legs; CodeQL and targeted Windows clippy were skipped.

🤖 Automated review by ZeroClaw-Bot. Posted as a comment: not a formal approval and does not satisfy the branch review requirement. Reviewed d2e9c75c407d. This comment is updated in place on re-review.

@ZeroClaw-Bot ZeroClaw-Bot added the needs-author-action Author response needed before review or merge can continue; not a stale warning. label Jul 31, 2026
@Audacity88 Audacity88 added this to the v0.8.5 milestone Jul 31, 2026
@Audacity88 Audacity88 added bug Something isn't working security Auto scope: src/security/** changed. domain:security Security domain priority:p1 High priority risk:high Trust, credential, compatibility, governance, release-authority, or security boundary. size:L Auto size: 501-1000 non-doc changed lines. labels Jul 31, 2026

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

@jstar0, I checked the automated review against current head 751a9135eb08. The production fall-through finding still applies, and the fix needs ingress-level regression coverage.

Rejected approval-shaped text can still fall through to ordinary agent dispatch because the shared resolver returns the same false result for “no pending token” and “pending token rejected.” The Slack and Matrix text paths continue normal message processing on that false result. The new tests call the resolver directly, so they do not prove that those rejected replies emit no ChannelMessage through the production ingress paths.

Please fix the fall-through, add the ingress regressions, resolve the current master conflict, and ping us when the PR is ready for re-review. If you disagree with the finding, reply on the thread with the production path or test evidence we should reconsider.

@jstar0
jstar0 force-pushed the fix/channel-approval-responder-authorization branch from 751a913 to 5240b43 Compare August 3, 2026 18:48
@github-actions github-actions Bot added runtime Auto scope: src/runtime/** changed. and removed security Auto scope: src/security/** changed. labels Aug 3, 2026
Audacity88 pushed a commit that referenced this pull request Aug 3, 2026
#9423)

- Carry operator-versus-runtime denial provenance through native channels, routed and fan-out approval, gateway WebSocket, RPC, and the runtime gate.
- Keep genuine operator denials attributed to the user while returning neutral model-visible text for unavailable, unreachable, timed-out, and other fail-closed runtime outcomes.
- Reject unknown Lark callback decisions without converting them into operator denials, and add cross-boundary regression coverage.

Closes #9642.
Related #9387 and #9574.
@jstar0
jstar0 force-pushed the fix/channel-approval-responder-authorization branch from 98db7cf to d2e9c75 Compare August 4, 2026 00:57
@jstar0

jstar0 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current master and completed the requested ingress coverage. The current head covers rejected approval dispatch suppression through Slack polling, Matrix sync, and Lark card-action ingress; the four-adapter approval suite passes (50 tests), runtime approval tests pass (6), and workspace Clippy is clean. The PR body has the exact verification details and current label snapshot. This is ready for re-review.

kckylechen1 added a commit to kckylechen1/zeroclaw that referenced this pull request Aug 4, 2026
* fix(security): redact Slack tokens in the leak detector (zeroclaw-labs#8918)

Add Slack-specific leak-detector patterns for current bot, user, app, workflow, refresh, and rotated access-token formats.

Keep static regex invariants explicit, constrain rotated-token matching to documented bot and user shapes, and cover benign dotted text to prevent false positives.

Co-authored-by: CedricConday <[email protected]>

* fix(parser): quote GLM curl URLs for POSIX shells (zeroclaw-labs#9444)

Branch history (the effective landing diff is parser-only):

- 5f97296 Inherited heartbeat-test foundation, already landed through zeroclaw-labs#9411
- a757999 fix(parser): quote GLM curl URLs for POSIX shells
- 6bd492d Merge master after zeroclaw-labs#9411 landed
- 33396ad Merge current master into the contributor branch

* fix(config): default context_compression.enabled to false and warn on the inert surface (zeroclaw-labs#9299)

- 480b605 fix(config): default context_compression.enabled to false and warn on the inert surface
- 21e0ad1 style(config): reword issue refs to satisfy comment hygiene gate
- b3d7852 fix(config): report cross-provider summary_model as inert instead of runtime-dispatched
- 6dfb813 fix(config): stop directing compression warning to an inert field
- d9b64c8 Merge branch 'master' into fix/9278-context-compression-default
- 1b53281 docs(config): clarify inert compression contract
- 9dbc974 Merge branch 'master' into fix/9278-context-compression-default

* fix(config): keep unknown-property sentinel matching typed (zeroclaw-labs#9445)

* fix(policy): retain actions when cutoff underflows (zeroclaw-labs#9448)

- 852c22e fix(policy): retain actions when cutoff underflows

* fix(runtime): reject non-file absolute shell paths (zeroclaw-labs#9441)

* fix(infra): make JSONL session rewrites atomic (zeroclaw-labs#9689)

- Stage complete JSONL rewrites in a same-directory temporary file, sync the new bytes, and replace the live session only after the rewrite succeeds.
- Serialize in-process JSONL mutations across `SessionStore` instances with an intentional sessions-directory lock, including atomic final-message replacement.
- Add failure-preservation, temporary-file cleanup, and concurrent append/update regression coverage.

This guarantees atomic visibility, not cross-process coordination or parent-directory power-loss durability.

Related zeroclaw-labs#9600 and zeroclaw-labs#9715.

* fix(agent): stream-hash tool args in loop_detector to avoid per-call deep clone (zeroclaw-labs#8936) (zeroclaw-labs#8937)

- c1d797f fix(agent): stream-hash tool args in loop_detector to avoid per-call deep clone
- 5d6244d fix(agent): add legacy canonicalise equivalence oracle for streaming loop-detector hash
- a04fefd fix(agent): preserve legacy numeric equivalence classes in streaming loop_detector hash
- 65aa07a Merge branch 'master' into fix/8936-loop-detector-streaming-hash

* fix(tools): stop ask_user hangs on wrong/structured-only channels (zeroclaw-labs#9452)

- 8e2d3b0 fix(tools): stop ask_user hangs on wrong/structured-only channels
- f8a34cd Merge remote-tracking branch 'upstream/master' into fix/zc-ask-user
- bc7131c fix(tools): route escalate_to_human and fail honestly on undeliverable channels
- 56cf572 Merge branch 'master' into fix/zc-ask-user
- 094730f fix(tools): make alert_channels a real escalation fallback

* fix(runtime): scope peer-agent turns to the recipient's cost context (zeroclaw-labs#9469)

- ec8cdaa fix(runtime): scope peer-agent turns to the recipient's cost context (zeroclaw-labs#9373)
- 10407c6 test(runtime): clarify peer budget scope
- 6a7df6c test(runtime): cover peer-turn cost scope through the real execute() boundary
- 839af30 Merge branch 'master' into fix/9373-peer-turn-cost-context

* refactor(providers): share OAuth refresh retry control flow (zeroclaw-labs#9400)

- f283ff7 refactor(providers): share OAuth refresh retry logic
- 832905f Merge branch 'master' into codex/pr-draft-9162
- d87a1cd chore: merge origin/master to refresh CI base
- c670144 Merge branch 'master' into codex/pr-draft-9162
- 78340d8 Merge branch 'master' into codex/pr-draft-9162

* feat(providers): carry model context window from the models.dev catalog (zeroclaw-labs#9347)

- cfdd46d feat(providers): carry model context window from the models.dev catalog
- 7ae2ea9 Merge branch 'master' into feat/model-context-window-from-catalog
- 9ead667 Merge branch 'master' into feat/model-context-window-from-catalog

* fix(config): expose workspace paths to config set (zeroclaw-labs#9616)

- Expose `PathBuf` configuration fields as string-valued schema properties.
- Let non-interactive `config set` materialize a missing agent alias and persist its workspace path.
- Add schema and CLI coverage for setting, reading, clearing, and dynamically materializing workspace paths.

* fix(log): preserve JSONL rows during schema migration (zeroclaw-labs#9449)

- 4974fb8 fix(log): preserve JSONL rows during schema migration
- eae9dde fix(log): make reload migration lossless
- d56e0dc fix(log): retain ownership after shutdown timeout
- 0d05b43 fix(log): preserve append boundary after migration
- c270cb9 Merge origin/master into codex/log-migration-integrity

* fix(runtime): stop reporting an unanswerable approval as a user denial (zeroclaw-labs#9423)

- Carry operator-versus-runtime denial provenance through native channels, routed and fan-out approval, gateway WebSocket, RPC, and the runtime gate.
- Keep genuine operator denials attributed to the user while returning neutral model-visible text for unavailable, unreachable, timed-out, and other fail-closed runtime outcomes.
- Reject unknown Lark callback decisions without converting them into operator denials, and add cross-boundary regression coverage.

Closes zeroclaw-labs#9642.
Related zeroclaw-labs#9387 and zeroclaw-labs#9574.

* fix(runtime): close run() agent-lifecycle bracket on every exit path (zeroclaw-labs#9490)

- cdaaba9 fix(runtime): close run() agent-lifecycle bracket on every exit path
- ae68327 Merge branch 'master' into fix/9374-run-lifecycle-guard

* fix(log): adapt fork flush_for_test + sync_active_file to upstream error-reporting contract

Upstream fb0ab6e changed Flush's ack type to Result<()> so flush failures
propagate to the caller. The fork had previously:
- simplified Flush(SyncSender<Result<()>>) to Flush(SyncSender<()>)
- made flush_for_test swallow all errors and return Ok(())
- made sync_active_file swallow open_active_file errors

Restored upstream semantics on all three so the migration tests pass:
worker sends Result, flush_for_test propagates it, sync_active_file uses ?
on open_active_file. Uses anyhow::Error::msg (not anyhow::anyhow!) to stay
compatible with the fork's disallowed-macros clippy lint.

Also fixes one clippy option_as_ref_deref from upstream 9695763 (zeroclaw-labs#9448)
in policy.rs test.

---------

Co-authored-by: Cedric Conday <[email protected]>
Co-authored-by: Dan Gilles <[email protected]>
Co-authored-by: Iftekhar Uddin <[email protected]>
Co-authored-by: wangmiao0668000666 <[email protected]>
Co-authored-by: Tidux <[email protected]>
Co-authored-by: JordanTheJet <[email protected]>
Co-authored-by: jmoneytech-stack <[email protected]>
Co-authored-by: Jason Perlow <[email protected]>
Co-authored-by: kckylechen1 <>

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

@jstar0, I re-reviewed current head d2e9c75c407db93843fa4ff8e34b8093421a34b3 against #9387. The earlier Slack and Matrix fall-through problem is fixed.

The 11-file, +1,212/-136 scope is broad but coherent: #9387 deliberately covers the same responder-authorization contract across four adapters, while the PR centralizes authorization and pending-state mutation in one shared resolver and leaves only transport-specific identity/envelope extraction in each channel. Splitting it would leave the security fix incomplete rather than produce cleaner ownership.

Two security-boundary issues remain.

✅ Resolved — Known approval responses no longer fall through

PendingApprovalResolution now distinguishes unknown tokens from rejected, resolved, and closed-receiver responses. Slack and Matrix suppress every known-token result, while Telegram and Lark consume their callback events before ordinary message dispatch. This addresses the blocker from my previous review.

🔴 Blocking — Authenticate Lark HTTP callbacks before trusting responder fields

listen_http validates the configured token only for the URL-verification challenge. Every ordinary callback proceeds to handle_card_action_ingress, which then trusts request-controlled operator.open_id, context.open_chat_id, approval_id, and decision when resolving a pending approval.

That means a forged request to the public callback endpoint can claim an allowlisted operator and originating chat and resolve a known pending approval. The general webhook weakness predates this PR, but this PR adds the approval-resolution path that makes those unauthenticated fields security-authoritative, so it directly bypasses the responder-authorization guarantee being added here.

Please authenticate the complete HTTP callback before routing it, using the official Lark verification/signature contract for this callback form and failing closed when authentication is absent or invalid. Preserve the raw request body and headers needed for that check, and add a regression proving an invalidly authenticated card action cannot consume pending state. Lark's official SDK performs this verification at the HTTP dispatch boundary before invoking application code.

🔴 Blocking — Cover the changed Lark and Slack production ingress wiring

The Lark regression manually extracts header.event_type and event, then calls handle_card_action_ingress directly. It therefore bypasses both the WebSocket decode/router and the Axum HTTP handler, so it would remain green if either production wrapper failed to authenticate, route, or short-circuit a card action.

Slack has the same remaining gap for Socket Mode: the polling listener regression is strong, but the separately changed interactive listener branch is covered only by parser unit tests. Those tests do not prove that the production listener connects the parsed responder and channel to authorization, retains rejected approvals, and suppresses approval envelopes from ordinary command dispatch.

A small production-owned full-envelope router shared by each transport and tested directly would be sufficient; live provider credentials are not required. For both changed paths, cover unauthorized and wrong-destination responses remaining pending, an authorized response resolving, and no ordinary ChannelMessage being emitted.

🟢 What looks good — Shared authorization stays fail-closed

The shared resolver checks authorization and destination before removal under one lock, so rejected responses remain available to the legitimate operator and concurrent responses cannot both resolve the same approval. The Matrix and Slack polling regressions exercise meaningful production boundaries.

Current-head required CI is green. I did not run additional local Cargo or live-provider validation for this review.

@zeroclaw-reviewer

Copy link
Copy Markdown

Review — PR #9574: authorize approval responders

Head reviewed: 0f6e665

I reviewed the complete current diff across the four channel adapters, the shared pending-approval resolver, the Lark configuration/dependency changes, the locale catalogues, the callers of the resolver, the current PR conversation and formal review history, and the linked issue #9387. The central authorization contract is now implemented coherently: pending approvals carry their originating destination, responder identity and destination are checked before resolution, known rejected tokens are suppressed from ordinary dispatch, and the current head restores the Matrix portion that was lost during the earlier merge conflict.

✅ Resolved — Matrix authorization was restored after the earlier merge conflict

The prior blocking review on head 900e8fb identified that the merge conflict had replaced Matrix with master's pre-fix implementation. The current diff again changes matrix.rs at the inbound handler and approval-registration sites, including room resolution before sending the approval and destination-aware resolution on sync ingress. The full four-adapter test run with an isolated configuration passed the Matrix production-shaped sync regression and the Matrix approval tests. I am not re-raising the settled merge-conflict finding.

✅ Resolved — Lark and Slack approval decisions now cross their production-owned ingress boundaries

The earlier Lark and Slack ingress findings are addressed on this head. handle_lark_webhook_event authenticates and decrypts the raw request before invoking handle_card_action_ingress, and listen_ws routes decoded card actions through that same shared ingress helper. The Lark webhook regression exercises the handler with forged, wrong-user, wrong-chat, authorized, and encrypted callbacks. Slack's handle_socket_mode_interactive is called by the live Socket Mode loop, and its regression covers the same rejected/authorized/suppressed cases. These changes satisfy the production-boundary coverage concern rather than only testing the helper in isolation.

🔴 Blocking — Compare the plaintext Lark verification token in constant time

crates/zeroclaw-channels/src/lark.rs:839-843 validates an unauthenticated plaintext event by returning token == Some(verification_token). This is an ordinary short-circuiting string comparison at a public webhook authentication boundary. An attacker who can send plaintext callbacks can use response timing to learn the configured verification token one prefix at a time, turning the token into a forgeable credential for the responder and destination fields that this PR now treats as authorization inputs.

The repository already provides zeroclaw_config::pairing::constant_time_eq for secret comparisons, and the still-open #9110 specifically records this Lark verification-token defect. Please require non-empty values and use constant_time_eq(token, verification_token) for this branch, while retaining the current fail-closed handling for missing, null, non-string, and empty tokens. The Encrypt Key/SHA-256 signature path is separate and is correctly covered by the current tests; this blocker is the plaintext header.token path.

🟡 Warning — Refresh the PR body's label snapshot

The PR body lists dependencies, but the current live label set is bug, channel, config, runtime, channel:slack, channel:telegram, channel:matrix, channel:lark, domain:security, needs-author-action, risk:high, and size:L; dependencies is not currently applied. This is maintainer-owned metadata rather than a code blocker, but the required public-artifact snapshot should be reconciled before approval so the description remains truthful.

🟢 What looks good — The shared resolver is fail-closed and preserves the operator's chance to answer

resolve_pending_approval checks responder authorization and the originating destination while holding the pending map lock, and it removes the entry only after both checks pass. Rejected and wrong-destination responses therefore leave the approval available to the legitimate operator, while NotFound remains distinguishable so ordinary text is not swallowed. The Telegram callback path also fails closed when from or the callback chat is absent, including under wildcard allowlists. This is the right shared state-transition shape for the four affected transports and directly addresses #9387.

Validation

  • cargo fmt --all -- --check — passed.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval -- --nocapture — passed: 54 passed, 0 failed.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark webhook_ -- --nocapture — passed: 7 passed, 0 failed.
  • cargo clippy --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --all-targets -- -D warnings — passed with no diagnostics.
  • cargo clippy --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --all-targets -- -A dead_code -D warnings — passed with no diagnostics.
  • cargo check --locked -p zeroclaw-channels --no-default-features --features channel-lark — passed.
  • cargo check --locked --workspace --exclude zeroclaw-desktop --features ci-all — passed.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram — the first run inherited the host's configured French locale and failed 12 existing locale-sensitive Slack/Telegram assertions that expect English literals. I reran the same command with ZEROCLAW_CONFIG_DIR=/tmp/zeroclaw-review-empty so locale detection was isolated from the host configuration; it passed: 1,348 passed, 0 failed, 5 ignored, plus 1 orchestration integration test, 3 pacing integration tests, and 0 doc-test failures.
  • git diff --check origin/master...HEAD — passed.
  • Current GitHub required gate — CI Required Gate passed on head 0f6e665.

No live Telegram, Slack, Lark, or Matrix provider smoke was run because no third-party credentials were available; the deterministic tests above cover the changed ingress and authorization paths.

Review disposition

Request changes for the one blocking plaintext-token comparison. The warning is maintainer-owned metadata cleanup. Once the comparison uses the shared constant-time helper and the body label snapshot is refreshed, the current authorization implementation and validation evidence look ready for another review.

@Audacity88

Copy link
Copy Markdown
Collaborator

@jstar0, current head 0f6e665c has merge conflicts with master; please resolve them and ping us for re-review on the resulting head.

…l-responder-authorization

Signed-off-by: King Star <[email protected]>

# Conflicts:
#	crates/zeroclaw-channels/Cargo.toml
#	crates/zeroclaw-channels/src/lark.rs
#	crates/zeroclaw-channels/src/telegram.rs
@github-actions github-actions Bot added the dependencies Auto scope: dependency manifest/lock/policy changed. label Aug 30, 2026
@jstar0

jstar0 commented Aug 30, 2026

Copy link
Copy Markdown
Contributor Author

Resolved the current master conflicts and the follow-up default-feature CI issue on exact head 884fdf0e919aae36a12d15e71983f4270af2c35a.

Verification:

  • hosted CI: 31 successful, 3 skipped, 0 failed or pending;
  • Check (default features, all targets) passed;
  • Matrix/Slack no-default-features all-targets checks passed;
  • focused approval_resolution_ tests passed (2 tests); and
  • cargo fmt --all -- --check passed.

The branch is ready for maintainer re-review.

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

Reviewed exact head 884fdf0e919aae36a12d15e71983f4270af2c35a across the shared pending-approval state transition and the Telegram, Slack, Matrix, and Lark ingress boundaries. The responder and destination binding is preserved on the current head, but the encrypted Lark webhook path introduces one security blocker.

🔴 Blocking — Authenticate encrypted webhooks before CBC decryption

handle_lark_http_event calls decrypt_lark_webhook_body before verify_lark_webhook_request. The decryptor accepts attacker-controlled AES-CBC/PKCS#7 ciphertext from the public callback endpoint, and the handler exposes distinguishable outcomes: invalid padding returns 400 invalid webhook payload, while padding-valid plaintext that is not JSON returns 400 invalid JSON payload (and valid JSON without authentication reaches the later 401). That creates a remote padding oracle before the raw-body signature is checked.

Please parse the outer envelope only far enough to select the authentication mode, verify the encrypted request's SHA-256(timestamp + nonce + encrypt_key + raw body) signature, and reject missing or invalid authentication before attempting CBC decryption. Add a regression that submits tampered encrypted envelopes and proves they are rejected at authentication without exposing decryption or parsing outcomes.

Can this be done in a follow up issue? No. The vulnerable code is introduced by this PR at a public security boundary; deferring it would ship an unauthenticated cryptographic oracle.

Blocker impact

  • Blocker: Encrypted Lark webhook ciphertext is decrypted before its raw-body signature is authenticated.
  • Why it matters: An unauthenticated remote caller can distinguish CBC padding from later parsing/authentication outcomes at the public webhook endpoint.
  • If ignored: Repeated adaptive requests can turn the endpoint into a padding oracle against captured encrypted webhook payloads, undermining the confidentiality/integrity boundary the Encrypt Key is meant to provide.
  • Can this be done in a follow up issue? No; the unsafe ordering is newly introduced here and must be corrected before this security change is approved.

use axum::response::IntoResponse;

let decrypted_body =
match decrypt_lark_webhook_body(&body, state.channel.encrypt_key.as_deref()) {

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.

This decrypts attacker-controlled AES-CBC/PKCS#7 ciphertext before the raw-body signature is verified. The handler then distinguishes invalid padding (invalid webhook payload) from padding-valid non-JSON (invalid JSON payload) and later authentication failure, exposing a remote padding oracle on the public callback endpoint. Authenticate encrypted envelopes against the exact raw body first, then decrypt only after that check succeeds.

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

@jstar0, I independently re-reviewed exact head 1e4ddfd837f36eee835d20d72f3641a12ea2383a across the Telegram, Slack, Lark, and Matrix approval-response authorization paths, their factory wiring and live identity resolvers, the linked contracts, focused tests, and the complete human-authored review history.

The previous Lark blocker applied to stale head 884fdf0e919aae36a12d15e71983f4270af2c35a. This head authenticates the exact raw encrypted webhook body before any CBC/PKCS#7 decryption. The focused regression also proves that unauthenticated invalid-padding and padding-valid/non-JSON ciphertexts return the same rejection without resolving a pending approval, while a correctly signed encrypted callback succeeds. The other channel adapters retain the required responder and destination authorization and consume approval-shaped traffic without ordinary message dispatch.

I found no substantive correctness, security, compatibility, or source-of-truth blocker on this exact head.

@jstar0

jstar0 commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

@JordanTheJet @Audacity88 Exact-head CI is green on 1e4ddfd. The current exact-head review confirms the Matrix recovery remains intact, and encrypted Lark webhooks now authenticate the exact raw body before CBC decryption. Please re-review when convenient.

@zeroclaw-reviewer

Copy link
Copy Markdown

Review — PR #9574: authorize approval responders

Head reviewed: 1e4ddfd

Verdict: Request changes

I reviewed the complete origin/master...HEAD diff, the changed files and their approval-ingress callers, the linked issue #9387, the current PR conversation, the full human review history, and the exact-head validation results. The shared responder/destination authorization contract is implemented coherently across Telegram, Slack, Matrix, and Lark, and the latest Lark change correctly moves authentication ahead of encrypted-body decryption. Two security/reliability issues remain in the current Lark path before I can approve this high-risk change.

Take stock

  • The earlier rejected-token fall-through finding is resolved: PendingApprovalResolution distinguishes unknown, rejected, resolved, and closed-receiver outcomes, and the affected ingress paths suppress known approval-shaped traffic before ordinary dispatch.
  • The earlier Lark and Slack production-ingress coverage findings are resolved on this head. The Lark HTTP handler and Slack Socket Mode dispatcher are now exercised by production-owned routing tests, while Matrix sync and Telegram getUpdates have corresponding boundary tests.
  • The Matrix conflict-resolution regression is resolved: the current diff again stores the canonical Matrix room, checks the live responder and room policy, and routes replies through the shared resolver.
  • The previous encrypted-Lark padding-oracle finding on head 884fdf0 is resolved on this head. handle_lark_http_event authenticates the raw encrypted envelope before attempting CBC/PKCS#7 decryption, and the focused test proves invalid-padding and padding-valid/non-JSON unauthenticated inputs receive the same authentication rejection without consuming pending state.
  • The latest formal review is an approval from @IftekharUddin on this exact head. The two findings below are independent current-head issues that are not addressed by that approval.
  • No inline thread remains open as a separate current-head blocker; the old Lark decryption-order inline comment is superseded by the current ordering and the exact-head regression.

🔴 Blocking — Register the Lark approval before exposing the card

crates/zeroclaw-channels/src/lark.rs:3174-3217 sends the interactive approval card and waits for the provider response before inserting the corresponding approval_id into pending_approvals. The HTTP and WebSocket listeners process callbacks concurrently with this request path. Therefore, once Lark has accepted the card, a fast legitimate operator can click it during the interval before line 3208 inserts the pending entry. handle_card_action_event then reaches take_pending_approval, sees no entry, returns the callback as an unknown/expired approval, and the waiting request eventually times out and records a runtime deny.

This loses valid approval decisions on the exact Lark path this PR is securing. The existing Lark tests populate the map manually and do not exercise the send/callback interleaving, so they cannot catch this race. Register the pending state before the outbound send, remove it if sending fails only when it is still the same pending request, and attach the returned message_id afterward without deleting an entry that a concurrent callback has already resolved. Add a deterministic transport-seam regression for a callback arriving after provider acceptance but before the send method returns.

🔴 Blocking — Compare the signed Lark digest without short-circuiting

crates/zeroclaw-channels/src/lark.rs:835-841 computes the provider's SHA-256 signature correctly, but then compares it with expected.eq_ignore_ascii_case(signature). This is a short-circuiting comparison of an attacker-controlled bearer authenticator at the public webhook boundary. The repository already provides zeroclaw_config::pairing::constant_time_eq at crates/zeroclaw-config/src/pairing.rs:316-335, and the verification-token branch uses it at lark.rs:790.

Normalize the accepted signature representation and compare it with the shared constant-time helper or compare decoded digest bytes with a constant-time operation. Preserve the current fail-closed behavior for missing, malformed, or partial signature headers, and add coverage for altered prefixes and suffixes. The current altered-signature test establishes rejection but does not establish constant-time comparison.

🟡 Warning — Refresh the PR body's live label snapshot

The PR body lists the labels that were present when it was drafted, but the current live label set also contains trusted contributor, which is absent from the body's Labels line. The template requires a current snapshot. This is maintainer-owned metadata and is not a code blocker, but the body should be refreshed before approval so the public artifact remains truthful.

✅ Resolved — Encrypted Lark callbacks authenticate before decryption

The current handler parses only the raw outer JSON needed to identify an encrypted envelope, verifies SHA-256(timestamp + nonce + encrypt_key + exact raw body), and returns the same 401 invalid authentication response for the unauthenticated ciphertext cases before invoking CBC decryption. The exact-head webhook_card_action_authenticates_before_decrypting_and_resolving_approval regression passes, and the current Lark webhook suite covers the encrypted and plaintext authentication branches. I am not re-raising the prior padding-oracle finding.

✅ Resolved — Responder and destination checks are centralized at ingress boundaries

The shared resolver keeps the allowlist decision, destination comparison, and pending-map removal under one lock, retaining rejected approvals for the legitimate operator and suppressing known rejected tokens from ordinary dispatch. Telegram supplies the callback user's allowlisted username/numeric ID and chat ID, Matrix supplies the live sender and canonical room, and Slack supplies the interactive/polling user and channel IDs. The current Lark and Slack production-owned dispatchers, Matrix sync handler, and Telegram polling listener all retain the intended fail-closed routing. I am not re-raising the prior fall-through, Matrix restoration, Lark wrapper, or Slack Socket Mode findings.

🟢 What looks good — The four-channel security slice remains coherent

The shared pending-approval state transition is a good architectural boundary for #9387: transport-specific code extracts the provider identity and destination, while one resolver owns the check-before-remove behavior. The tests also verify that rejected known tokens remain available and do not become ordinary agent turns. The Lark raw-body authentication ordering in this head is materially safer than the preceding revision and is backed by an exact production-handler regression.

Template and public-artifact checks

The PR body contains the required Summary, Testing, Security & Privacy Impact, Compatibility, Rollback, and Supersede Attribution sections. Fixes #9387 remains accurate for the four-adapter responder-authorization contract, and Related #9423 remains a non-closing relationship. The body contains no bot/AI attribution or sensitive values. The only metadata discrepancy found is the missing trusted contributor label in the required snapshot; the validation claims should also be refreshed when the new Lark lifecycle fix is made, because the current test suite does not cover the send/callback race.

Validation

The complete command output is preserved in /mnt/build/sop-pilot/logs/9574/step2.log. Commands were run in the detached worktree for exact head 1e4ddfd837f36eee835d20d72f3641a12ea2383a, with CARGO_TARGET_DIR=/mnt/build/cargo-target-review/9574 and the full Cargo output piped through the SOP log.

  • cargo fmt --all -- --check — passed from the reviewed worktree.
  • git diff --check origin/master...HEAD — passed.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval -- --nocapture — passed: 55 passed, 0 failed.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark webhook_ -- --nocapture — passed: 8 passed, 0 failed.
  • cargo test --locked -p zeroclaw-runtime channel_approval -- --nocapture — passed: 7 passed, 0 failed.
  • cargo build --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram — passed on the retry with CARGO_BUILD_JOBS=2.
  • cargo clippy --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --all-targets -- -D warnings — passed with no diagnostics.
  • ZEROCLAW_CONFIG_DIR=/tmp/zeroclaw-review-9574-empty cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --lib — passed: 1,399 passed, 0 failed, 5 ignored.
  • cargo check --locked --workspace --exclude zeroclaw-desktop --features ci-all — passed.
  • RUSTFLAGS='-D warnings' cargo check --locked --workspace --exclude zeroclaw-desktop --no-default-features — passed.
  • The full workspace cargo clippy --locked --workspace --exclude zeroclaw-desktop --all-targets --features ci-all -- -D warnings was attempted twice with CARGO_BUILD_JOBS=2, but both attempts exceeded the 900-second tool limit while the host was under concurrent Cargo load. No pass is claimed for that local command; the changed-crate all-targets Clippy command passed, and the exact-head hosted Lint check passed.
  • The initial package build attempt also exceeded the 900-second tool limit under the same host-wide Cargo load; the rerun completed successfully. No source failure was reported.
  • GitHub check runs for the exact head report 27 successful and 3 skipped checks, with no failures or pending checks. CI Required Gate, Lint, Test, Security, Build x86_64-unknown-linux-gnu, the feature checks, MSRV, and the platform checks are successful. The skipped checks are targeted/non-applicable workflow legs (Windows targeted Clippy, Nix Module Eval, and Docs Style).
  • No live Telegram, Slack, Lark, or Matrix credentials were used, so live-provider smoke testing was not performed.

Verdict

Request changes. The shared authorization implementation and the encrypted-Lark authentication ordering are in good shape, but Lark can lose a legitimate approval during the card-send/registration race, and the signed webhook digest comparison is still variable-time. The label snapshot is a non-blocking public-artifact cleanup. I would be ready to re-review after the two blocking issues are fixed and the exact-head validation/body evidence is refreshed.

Institutional findings consulted: 2026-07-31-pr-9574-rejected-approval-token-falls-through (resolved suppression boundary), 2026-07-31-pr-9574-approval-auth-boundary-not-exercised (resolved Lark production boundary), 2026-08-08-pr-9574-slack-socket-approval-ingress-no-production-regression (resolved Socket Mode boundary), 2026-08-21-pr-9574-lark-webhook-encrypt-key-not-applied (resolved encrypted callback routing), 2026-08-30-pr-9574-lark-approval-registration-after-send-race-current-head (current registration race), and 2026-08-30-pr-9574-lark-signed-webhook-signature-variable-time-current-head (current signature comparison issue).

Register the pending approval before the provider accepts the card so an
early operator callback still resolves. Compare signed webhook digests
with the shared constant-time helper after normalizing 64-hex input.

Co-authored-by: Cursor <[email protected]>
@jstar0

jstar0 commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the two current-head Lark blockers on exact head cd61058cf:

  • request_approval_attributed now inserts the pending approval before the outbound card send, attaches message_id only if that entry is still present, and removes the entry on send failure only when it remains. The new request_approval_registers_before_send_so_early_callback_resolves regression delivers an Approve callback while the provider send is still in flight.
  • Signed webhook digests are compared with zeroclaw_config::pairing::constant_time_eq after normalizing a 64-hex signature. Missing, malformed, prefix-altered, and suffix-altered signatures still fail closed.

The PR body Testing and label snapshot are refreshed for this head. @JordanTheJet @Audacity88 please re-review when convenient.

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

Re-review of PR #9574

Head reviewed: cd61058

@jstar0 — re-review after the recovery push and the Lark hardening round. My 2026-08-14 request-changes had exactly one blocker: the post-approval master merge had resolved the matrix.rs conflict by taking master's side, silently deleting the Matrix quarter of the fix. That is fully repaired, and the branch has grown genuinely better since. This closes my request-changes.

Take stock

  • My blocker is resolved below. @Audacity88's APPROVED from 812757e covered the original four-channel design; @IftekharUddin ran a fresh round on the Lark webhook surface (CHANGES_REQUESTED at 884fdf0 → APPROVED at 1e4ddfd). One commit landed after his approval — cd61058 — which I have reviewed directly below so no head goes unexamined.
  • CI is fully green at this exact head (36 checks). MERGEABLE; the only blocking review state is mine, which this review replaces.
  • The PR body is current and truthful again: the Matrix claims are true, the label snapshot matches the live set exactly, the validation section describes the new Lark tests specifically, and the rollback line names every commit including the newest.

✅ Resolved — The Matrix fix is restored, composed with #9911, and byte-different from master

crates/zeroclaw-channels/src/matrix.rs is back to carrying the fix: +232 lines against master, approvals routed through crate::util::resolve_pending_approval, and #9911's mention_only gating composed alongside it in the same file (the reply-parent fetch is even shared with the gate — cleaner than the two features merely coexisting). Both authorization regressions are present: pending_approval_requires_allowed_user_and_origin_room and sync_ingress_suppresses_rejected_approval_replies_and_delivers_authorized_one. The any-room-can-approve hole is closed again, and this time the body's claims about it are true.

✅ Resolved — The feature-gate side effect

fix(channels): align approval resolver feature gate (884fdf0) fixes the dead-code shape I flagged as the tell: the shared resolver's gate now matches its real consumer set, and the body documents the no-default-features build staying warning-clean without suppressions.

🟢 What looks good — The Lark round made the PR stronger than what was originally approved

The webhook surface @IftekharUddin pushed on is real security work: encrypted callbacks are authenticated before decryption (invalid-padding and padding-valid/non-JSON envelopes both return the same 401 before any decrypt work, preserving pending state), and the final commit replaces an eq_ignore_ascii_case signature comparison with a constant-time, fail-closed digest check that rejects wrong-length and non-hex input before the secret-bearing comparison. The same commit fixes a genuine race — the pending approval is now registered before the card send, so an operator reply that beats the send's return can still resolve, with send-failure cleanup removing the entry only if a concurrent callback hasn't consumed it. The transport-seam test proves exactly that interleaving.

Since that last commit landed after @IftekharUddin's approval, for the record: I read cd61058 in full — it is the constant-time comparison, the registration reordering, their tests, and nothing else.

🔵 Suggestion — Strip AI attribution from future commits

cd61058 carries a Co-authored-by: Cursor trailer; repository policy is no bot/AI attribution footers in commits. No need to rewrite pushed history — the squash body will be sanitized at merge time — just leave the trailer off future commits.

Validation

  • Restoration verified structurally: matrix.rs diffed against both master (fix present) and the branch history (resolver, destination capture, mention gating, both tests).
  • Focused suites run locally at this exact head with the body's exact feature matrix (--no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval): 56 passed / 0 failed.
  • Exact-head hosted CI: 36 checks green. The --no-default-features approval matrix run is recorded in the body with tails.

Verdict

Approve. The merge accident is repaired with the composition done right, the side effect is fixed, and the Lark hardening added since is work I'd have asked for had I known to. Thank you for the careful recovery — and for the patience across three weeks of review rounds; the four-channel authorization boundary this lands is worth it. With @Audacity88's design approval, @IftekharUddin's webhook round, and this review, the PR has its coverage; I'll clear needs-author-action on posting.

@JordanTheJet JordanTheJet removed the needs-author-action Author response needed before review or merge can continue; not a stale warning. label Sep 2, 2026

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

@jstar0 I re-reviewed cd61058cfe1ab043d4d855961ce1520d078eaa9e, including the complete Lark delta since 1e4ddfd8 and the affected approval and authentication paths. The accepted four-channel scope in #9387 remains coherent, and the previously restored Matrix protection is intact.

I approve the current implementation. The two latest Lark production findings are fixed. There is one nonblocking warning about what the new race test actually proves.

All 37 displayed hosted checks pass. The focused approval and webhook test results are your reported local runs; hosted CI's explicit Lark selector does not run the two new tests. I did not run local tests or live-provider smokes.

✅ Resolved — The prior production blockers

The latest zeroclaw-reviewer report identified registration after sending and a short-circuiting signature comparison. I independently checked both repairs: pending state is now inserted before token retrieval or the card send, a successful send only attaches its message ID if the entry remains, and send errors remove the pending entry. An authorized callback during a successful in-flight send can therefore retain its decision. Signed digests now use the existing constant-time helper after validating and normalizing the 64-character hex representation.

@JordanTheJet's Matrix restoration finding stays resolved: the current handler checks the responder and canonical room before removing pending state. @IftekharUddin's encrypted-webhook finding also stays resolved: raw-body authentication precedes CBC decryption. The earlier rejected-token fall-through and production-ingress coverage repairs remain present. JordanTheJet has now approved this exact head and replaced his earlier CHANGES_REQUESTED review.

🟢 What looks good

The existing responder policy and stored destination still govern resolution. Rejected replies leave the request available to the legitimate operator, and consumed entries are not recreated when the outbound send finishes. The Lark repair preserves the distinction between an operator decision and a runtime denial.

🟡 Warning — The race test does not enforce the claimed ordering

This is nonblocking because the production code now structurally registers the request before sending. In request_approval_registers_before_send_so_early_callback_resolves, however, the response is delayed 800 ms while the callback waits up to two seconds for pending state. The old implementation could finish the send, register the request, and still satisfy every assertion. The test establishes eventual resolution, not callback-before-send-return.

An optional follow-up should hold the HTTP response behind an explicit barrier, deliver the callback after the request arrives, and require callback completion before releasing the response. The test description should reflect the evidence it currently provides.

With JordanTheJet’s exact-head approval and this re-review, the two independent Core Team approvals required by FND-003 are covered.

@zeroclaw-reviewer

Copy link
Copy Markdown

Review — PR #9574: authorize approval responders

Head reviewed: 6baf196

@jstar0, I reviewed the complete 13-file diff (+2,250/-263) across the shared pending-approval state, Telegram, Slack, Matrix, and Lark/Feishu ingress paths, the Lark configuration and dependency changes, the locale catalogue additions, their production callers, the linked issue #9387, and the full conversation and formal review history.

The implementation on this exact head is materially stronger than the earlier revisions. The shared authorization core now checks the live responder policy and originating destination before consuming pending state; rejected known tokens remain suppressed rather than falling through to ordinary dispatch; Lark authenticates the raw webhook before decrypting; and the Lark send/registration race and signed-digest comparison have been addressed. The four-adapter scope remains coherent for #9387, although this is appropriately a high-risk, size-L security change.

Take stock

  • The earlier Slack/Matrix fall-through issue is resolved by PendingApprovalResolution, and the current ingress paths suppress known rejected/resolved/closed approvals before normal message dispatch. I am not re-raising it.
  • The Matrix merge-conflict regression from head 900e8fb is resolved: the current matrix.rs again stores the canonical room, checks responder and room authorization, routes through the shared resolver, and includes the sync-ingress regression. I am not re-raising it.
  • The earlier Lark production-wrapper, callback-authentication, encrypted-envelope, provider-contract, and constant-time-comparison findings are resolved on the current source. handle_lark_http_event authenticates the exact raw encrypted body before CBC/PKCS#7 decryption, plaintext callbacks use the verification token through constant_time_eq, and the Lark production regression covers both modes. I am not re-raising those findings.
  • The Lark registration race is resolved structurally: request_approval_attributed inserts the pending entry before the outbound card request and conditionally attaches the returned message ID or cleans up only after a failed send. The existing test honestly documents that it proves eventual resolution rather than callback completion before the send response returns; I am not treating that test limitation as a separate blocker because the production ordering is explicit.
  • The visible CHANGES_REQUESTED reviews are for older heads. @IftekharUddin approved 1e4ddfd, and both @JordanTheJet and @Audacity88 have approved the current exact head 6baf196. The PR's current review decision is APPROVED; no older substantive concern remains live on this revision.
  • The old inline Lark decryption-order comment is superseded by the current raw-body authentication ordering. Jordan's earlier nonblocking suggestion about the already-pushed Cursor trailer does not require history rewriting and is not re-raised here.

🔴 Blocking — The required rollback command does not roll back this PR

The live PR body at ## Rollback, line 75, says:

git revert cd61058cf 1e4ddfd8 bdc2b4c5 6137335d 74cd45b2 ef173834 afb3f0f0 b7b47988

That is not a complete rollback of the reviewed change. The non-merge commits in origin/master..6baf1965b2d63d48aa702c12b5b558450c629831 also include 884fdf0, ed27d5b, 2e64fa2, 362421c, 45921dd, 1e1aed3, and 812757e. The omitted commits are not cosmetic: they include the restored Matrix authorization in crates/zeroclaw-channels/src/matrix.rs, Lark event authentication/decryption changes in crates/zeroclaw-channels/src/lark.rs, the corresponding Lark config/dependency changes, and the shared feature-gate changes in crates/zeroclaw-channels/src/util.rs. Reverting only the listed hashes would leave part of this security boundary installed, and could also leave the branch in a misleading or inconsistent intermediate state.

Because .github/pull_request_template.md:73-77 makes rollback evidence mandatory for this medium/high-risk change, please replace the hand-picked list with a verified complete procedure. The safest post-merge path is to revert the single landed squash commit and verify the post-revert diff/build. If a pre-merge multi-commit rollback is required, document the complete ordered procedure, including merge handling, and verify that it removes every PR-introduced file change while preserving unrelated master work.

🟡 Warning — Refresh the stale validation narrative against the exact head

The current body at line 32 says that hosted CI “will re-run” the workspace gates, but the exact-head check runs are already complete: 32 checks succeeded and 4 completed as skipped (Docs Style, Nix Module Eval, targeted Windows Clippy, and Relay Container Fresh-Volume Smoke). The body should state the actual exact-head result rather than describe those checks as future work. It should also include the exact local evidence now available and the honest local gap: the workspace cargo check --locked --workspace --exclude zeroclaw-desktop --features ci-all attempt exceeded the 900-second command window, so no local pass should be claimed for it. This is public-artifact cleanup, not a code blocker.

✅ Resolved — The responder and destination authorization boundary is present on all four adapters

The current Telegram callback path reads both username/numeric identity and callback chat ID before resolving; Slack covers polling and Socket Mode with the responder and channel extracted from the production envelopes; Matrix resolves and stores the canonical room ID and gates both sender and room; and Lark checks the operator identity and originating open chat. resolve_pending_approval keeps the authorization/destination check and removal under one lock, so rejected responses remain available to the legitimate operator and cannot be dispatched as ordinary approval text.

✅ Resolved — The Lark webhook hardening and lifecycle repairs are retained on this head

crates/zeroclaw-channels/src/lark.rs:819-910 authenticates signed encrypted envelopes over the exact raw body before attempting decryption, rejects malformed signatures before the secret-bearing comparison, and decrypts only after authentication. :3174-3252 registers pending state before the card send, attaches response metadata only if the request remains pending, and removes failed sends without consuming a concurrent callback. These repairs survive the final merge commit and are covered by the focused webhook and transport-seam tests.

🟢 What looks good — Shared fail-closed state transitions and production-boundary tests

The shared PendingApprovalResolution state machine in crates/zeroclaw-channels/src/util.rs:521-603 is the right boundary: it distinguishes unknown tokens from known rejected/resolved/closed requests, preserves rejected state, and performs check-before-remove atomically. The channel adapters retain transport-specific identity extraction while sharing that state transition. The deterministic tests reach Telegram getUpdates, Slack polling and Socket Mode dispatch, Matrix sync handlers, and the Lark HTTP handler rather than stopping at only the resolver. The encrypted Lark test also verifies that invalid-padding and padding-valid/non-JSON ciphertexts receive the same authentication rejection before decryption and do not consume pending state.

Template and public-artifact checks

  • The required Summary, Testing, Security & Privacy Impact, Compatibility, Rollback, and conditional Supersede Attribution sections are present.
  • The live label set matches the body snapshot: bug, dependencies, channel, config, runtime, channel:slack, channel:telegram, channel:matrix, trusted contributor, channel:lark, domain:security, risk:high, and size:L.
  • Fixes #9387 is accurate for the four-adapter responder-authorization contract. Related #9423 is non-closing and accurately identifies the separate approval-provenance work.
  • The body is privacy-safe and contains no bot/AI attribution footer. Visual interface changed? N/A is present and this is not a visual-presentation change.
  • The only substantive public-artifact problem found is the incomplete rollback procedure. The validation wording should also be refreshed as described above.

Validation

Commands were run against exact head 6baf196 with CARGO_TARGET_DIR=/mnt/build/cargo-target-review/9574; complete output is preserved in /mnt/build/sop-pilot/logs/9574/step2.log.

  • git diff --check origin/master...HEAD — passed.
  • cargo fmt --all -- --check — passed.
  • cargo build --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram — passed.
  • The first invocation of the focused approval suite exceeded the 900-second command window while compiling under host-wide Cargo load; the required retry with CARGO_BUILD_JOBS=2 completed successfully: 56 passed, 0 failed, 0 ignored.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram approval -- --nocapture (retry) — passed: 56 passed, 0 failed, 0 ignored.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark webhook_ -- --nocapture — passed: 9 passed, 0 failed, 0 ignored.
  • cargo test --locked -p zeroclaw-channels --no-default-features --features channel-lark request_approval_registers_before_send -- --nocapture — passed: 1 passed, 0 failed, 0 ignored.
  • cargo clippy --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --all-targets -- -D warnings — passed with no changed-code diagnostics.
  • ZEROCLAW_CONFIG_DIR=/tmp/zeroclaw-review-9574-empty cargo test --locked -p zeroclaw-channels --no-default-features --features channel-slack,channel-lark,channel-matrix,channel-telegram --lib — passed: 1,409 passed, 0 failed, 5 ignored.
  • cargo test --locked -p zeroclaw-runtime channel_approval -- --nocapture — passed: 7 passed, 0 failed, 0 ignored.
  • cargo test --locked -p zeroclaw-config lark_config -- --nocapture — passed: 4 passed, 0 failed, 0 ignored.
  • cargo check --locked --workspace --exclude zeroclaw-desktop --features ci-all — did not complete within the 900-second command window; no local pass is claimed. Exact-head hosted checks cover the corresponding workspace feature checks and report success.
  • Cargo emitted the same future-incompatibility notice for registry dependency proc-macro-error2 v2.0.1 during the feature build/test/lint commands. cargo report future-incompatibilities --id 1 identifies the dependency's pub use proc_macro warning; Cargo.lock is unchanged by this PR, so this is pre-existing dependency debt rather than a changed-code warning.
  • Exact-head hosted checks: 32 successful and 4 skipped, with no failures or pending checks. CI Required Gate, Test, Lint, Security, Build x86_64-unknown-linux-gnu, MSRV, no-default/default/all-feature checks, and platform checks are successful. The four skipped checks are named in the public-artifact warning above.
  • No live Telegram, Slack, Lark, or Matrix credentials were used; deterministic tests cover the changed ingress and authorization boundaries.

Verdict

Request changes for the incomplete required rollback procedure. I found no current-head code or security-boundary blocker in the implementation itself, and the exact-head hosted checks plus focused local suites are green. Please correct the rollback path and refresh the stale validation wording; after that, the current code and review coverage look ready for merge.

Institutional finding recorded: 2026-09-02-pr-9574-rollback-command-omits-several-security-commits.

@JordanTheJet
JordanTheJet merged commit e762ce5 into zeroclaw-labs:master Sep 3, 2026
36 checks passed
belumume pushed a commit to belumume/zeroclaw that referenced this pull request Oct 9, 2026
zeroclaw-labs#9423)

- Carry operator-versus-runtime denial provenance through native channels, routed and fan-out approval, gateway WebSocket, RPC, and the runtime gate.
- Keep genuine operator denials attributed to the user while returning neutral model-visible text for unavailable, unreachable, timed-out, and other fail-closed runtime outcomes.
- Reject unknown Lark callback decisions without converting them into operator denials, and add cross-boundary regression coverage.

Closes zeroclaw-labs#9642.
Related zeroclaw-labs#9387 and zeroclaw-labs#9574.
kckylechen1 added a commit to kckylechen1/zeroclaw that referenced this pull request Oct 30, 2026
Port challenge verification from upstream aa6bc26 (zeroclaw-labs#9110) and signature authentication from e762ce5 (zeroclaw-labs#9574). Limit token-only authentication to plaintext setup challenges and enable Lark regressions in the channels leg.

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

Labels

bug Something isn't working channel:lark Auto module: channel/lark changed. channel:matrix Auto module: channel/matrix changed. channel:slack Auto module: channel/slack changed. channel:telegram Auto module: channel/telegram changed. channel Auto scope: src/channels/** changed. config Auto scope: src/config/** changed. dependencies Auto scope: dependency manifest/lock/policy changed. domain:security Security domain risk:high Trust, credential, compatibility, governance, release-authority, or security boundary. runtime Auto scope: src/runtime/** changed. size:L Auto size: 501-1000 non-doc changed lines. trusted contributor Contributor with 5+ merged PRs.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: interactive approval responses are accepted from any chat member on telegram, slack, lark and matrix

6 participants