Skip to content

Feishu plugin tool calls fall back to global defaultAccount (not the agent's bound account) on non-inbound turns (cron / inter-session relay / heartbeat) → cross-tenant 99991672 / 403 #96657

Open

Description

@yubingjiaocn

Title: Feishu plugin tool calls fall back to global defaultAccount (not the agent's bound account) on non-inbound turns (cron / inter-session relay / heartbeat) → cross-tenant 99991672 / 403

Labels (suggest): bug, impact:auth-provider, impact:security


Summary

In a multi-account Feishu setup where each agent is bound to its own Feishu app via bindings, Feishu tool calls (feishu_bitable_*, feishu_doc, feishu_wiki, feishu_drive, feishu_perm) pick the wrong app credential whenever the turn is not driven by an inbound Feishu message.

On inbound Feishu messages the tool resolves the correct account. But on cron / inter-session (sessions_send) relay / heartbeat turns, the account context is missing and the resolver falls back to the global channels.feishu.defaultAccount — not the account bound to the agent. In a multi-tenant setup this sends the call through the wrong app, which cannot see the target tenant's resources → code 99991672 (or HTTP 400/403).

This is the tool-execution sibling of #49507 (which is about cron message delivery choosing the wrong account). Same theme (non-interactive turns lose account context), different surface and code path. #49507's maintainer direction (binding-aware precedence, and explicit rejection of naive agentId→accountId) applies here too.

Environment

  • Plugin: @openclaw/feishu 2026.6.10 (latest; also present in 2026.6.5)
  • OpenClaw multi-agent, single instance, several agents bound to distinct Feishu apps via bindings
  • Feishu self-built apps; tenant_access_token (bot identity)

Setup that triggers it

// channels.feishu
{
  "defaultAccount": "kasper",      // a generic/shared app
  "accounts": {
    "kasper": { "appId": "cli_AAA..." },   // NO bitable/wiki scope, different tenant
    "may2":   { "appId": "cli_BBB..." }    // the agent's real app, has the resources
  }
}
// bindings: { agentId: "may", match: { channel: "feishu", accountId: "may2" } }

Agent may is bound to may2. All its resources live in may2's tenant.

Steps to reproduce

  1. From the agent's own Feishu DM, ask it to read/write a Bitable in its tenant → works (inbound turn carries the account).
  2. Trigger the same agent via a cron job, a sessions_send from another session, or a heartbeat, and have it call e.g. feishu_bitable_list_fields on the same Bitable.
  3. → code 99991672 "you don't have permission" (or 400/403). The call went out under defaultAccount (kasper), which is a different tenant and cannot see the resource.

Root cause (source, v2026.6.10)

Tool account resolution — dist/drive-djUl8IRC.js (extensions/feishu/src/tool-account.ts):

function resolveImplicitToolAccountId(params) {
  // 1. explicit accountId in tool params (bitable/doc/wiki tools DON'T expose this)
  const explicitAccountId = normalizeOptionalString(params.executeParams?.accountId);
  if (explicitAccountId) return explicitAccountId;

  // 2. contextual account from the turn (ctx.agentAccountId)
  const contextualAccountId = normalizeOptionalString(params.defaultAccountId);
  if (contextualAccountId && listFeishuAccountIds(params.api.config).includes(contextualAccountId)) {
    if (resolveFeishuAccount({ cfg: params.api.config, accountId: contextualAccountId }).enabled)
      return contextualAccountId;
  }

  // 3. GLOBAL fallback — wrong account in multi-tenant setups
  const configuredDefaultAccountId =
    normalizeOptionalString((params.api.config?.channels?.feishu)?.defaultAccount);
  if (configuredDefaultAccountId) return configuredDefaultAccountId;

  // 4. (added in 2026.6.10) first enabled+configured account that has the required tool family
  if (params.requiredTool && params.api.config) for (const accountId of listFeishuAccountIds(params.api.config)) {
    const account = resolveFeishuAccount({ cfg: params.api.config, accountId });
    if (account.enabled && account.configured && resolveToolsConfig(account.config.tools)[params.requiredTool.family])
      return accountId;
  }
}

Note on the 2026.6.10 change: a 4th fallback was added (scan accounts for one that has the required tool family), but it sits after the global defaultAccount at step 3. On a relay turn, step 2 is skipped and step 3 immediately returns defaultAccount, so step 4 is never reached and the misrouting still happens. The fallback is in the right spirit but at the wrong precedence position, and it still doesn't consult the current agent's binding.

params.defaultAccountId comes from ctx.agentAccountId at tool registration, e.g. registerFeishuDriveTools:

api.registerTool((ctx) => {
  const defaultAccountId = ctx.agentAccountId;   // <-- only set on inbound Feishu turns
  ...
  const client = createFeishuToolClient({ api, executeParams: p, defaultAccountId });

And ctx.agentAccountId is only populated by the inbound Feishu message path (monitor.account-*.js, buildCtxPayloadForAgent → route.accountId = agentAccountId). Cron / inter-session relay / heartbeat turns never go through that path, so ctx.agentAccountId is undefined, step 2 is skipped, and step 3 routes through the global defaultAccount (step 4 never runs).

The resolver never consults the agent's bindings entry. So even though may is bound to may2, a relay turn ignores that and uses defaultAccount.

Impact

  • Functional: Any agent doing Feishu resource work outside a live inbound message (scheduled jobs, orchestration via sessions_send, heartbeat-driven work) hits cross-tenant permission errors. Looks like a scope/permission problem but is actually account misrouting.
  • Security: Same class as [Bug] Cron Job 使用错误的飞书账号发送消息 - 缺少 accountId 自动推断 #49507 — in mixed-trust multi-account setups, a relay turn can route requests through a different app/tenant than intended.

Suggested fix

Insert a binding-aware step before the global defaultAccount, and move the existing step-4 capability scan up as well, i.e. precedence:

  1. explicit accountId in tool params (where supported)
  2. ctx.agentAccountId (inbound turns)
  3. the account bound to the current agent via bindings (channel = feishu) ← new
  4. (existing 2026.6.10 scan) first enabled+configured account with the required tool family
  5. global defaultAccount (last resort)

The key change is that defaultAccount must drop to last; right now it short-circuits at step 3 and pre-empts both the binding and the 6.10 capability scan. This matches the direction maintainers already set on #49507 (binding-aware precedence; not naive agentId→accountId). For agents with exactly one bound Feishu account this fully resolves the misrouting; for unbound contexts behavior is unchanged.

Alternatively (or additionally), thread the agent's bound account into the relay/cron/heartbeat turn context so ctx.agentAccountId is populated consistently across all turn kinds, not just inbound messages.

Workaround (verified)

Disable the plugin's Feishu resource tools for the affected agent and drive Feishu via the official @larksuite/cli, pinning the app with a named profile:

lark-cli config init --name <profile> --app-id <app_id> --app-secret-stdin --force-init
lark-cli base +field-list --base-token <t> --table-id <t> --profile <profile> --as bot

--profile pins the credential to a single app regardless of turn kind, so relay/cron turns no longer drift. Verified end-to-end (read/create/delete records).

Related

Activity

  1. clawsweeper commented on Jun 25, 2026

    @clawsweeper
    Contributor

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed August 3, 2026, 2:43 AM ET / 06:43 UTC.

    Summary
    Keep open for a maintainer decision on background-turn account authority. Current main still chooses channels.feishu.defaultAccount before the capability fallback whenever a Feishu tool has no valid contextual account, while the shared routing helper already treats peerless cron-style callers as bound-account-aware; applying that behavior to plugin tools needs an explicit, ambiguity-safe SDK/context contract rather than a local reverse-lookup shortcut.

    Reproducibility: yes. at source level: configure distinct default and bound Feishu accounts, invoke a resource tool with no valid contextual account, and the resolver returns the global default before any binding-aware path exists. A live tenant request was not run in this read-only review.

    Root-cause cluster
    Relationship: canonical
    Canonical: #96657
    Summary: This is the canonical report for Feishu resource-tool credential selection outside inbound turns; the delivery issue and closed PRs overlap in account identity but do not safely replace this unresolved tool-execution decision.

    Members:

    Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

    Maintainer decision needed

    Question Recommendation
    Should an agent’s channel binding be authoritative for Feishu tool credentials on background turns, and should multiple matching Feishu bindings fail closed rather than select by configuration order? Adopt binding-aware background credentials: Expose an SDK/runtime fact for the active agent’s unique Feishu binding, fail closed when the binding is ambiguous, and place it ahead of capability and global-default fallback.

    Why: Bindings are documented as inbound routing, while tool execution currently receives only an optional contextual account; choosing reverse-binding precedence and ambiguity behavior establishes a cross-plugin identity contract rather than a local Feishu-only fix.

    Next step
    Protected security/product-review labels and the unresolved binding-authority decision make this unsafe for an autonomous repair PR.

    Security
    Needs attention: The report identifies a concrete tenant-credential selection boundary that needs an ambiguity-safe design before implementation.

    Review details

    Best possible solution:

    Define a generic, SDK-visible background credential-resolution contract: use one unambiguous Feishu binding for the active agent, fail closed on ambiguous bindings, and retain capability/default fallback only when no binding applies; add regression coverage for cron, relay, heartbeat, unbound, and ambiguous cases.

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

    Yes, at source level: configure distinct default and bound Feishu accounts, invoke a resource tool with no valid contextual account, and the resolver returns the global default before any binding-aware path exists. A live tenant request was not run in this read-only review.

    Is this the best way to solve the issue?

    No — directly reverse-looking up bindings inside the extension would create an undocumented cross-boundary policy and leave ambiguity unresolved. A prepared SDK/runtime account fact with explicit ambiguity handling is the safer owner-boundary repair.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • Using the first reverse-matched binding without an explicit contract can silently choose one tenant when an agent has multiple Feishu bindings.
    • Importing the existing core routing helper directly from the Feishu extension would violate the plugin boundary; a generic SDK/runtime seam or prepared account fact is required.
    • Current source confirms the precedence defect but this read-only review did not run a live multi-tenant Feishu request, so provider-side behavior remains source-reproducible rather than live-reproduced.

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

    Label changes

    Label changes:

    • remove clawsweeper:needs-maintainer-review: Current issue advisory state no longer selects this label.

    Label justifications:

    • P2: Multi-account Feishu background work can fail or reach the wrong tenant, but the impact is bounded to configurations with multiple accounts and background tool use.
    • impact:session-state: The failure arises when account identity available on an inbound turn is absent from cron, relay, or heartbeat execution context.
    • impact:security: Default-account fallback can send a resource request through a different tenant application than the agent’s intended binding.
    • impact:auth-provider: The affected resolver selects the Feishu account credential used by tool clients.
    Evidence reviewed

    Security concerns:

    • [medium] Avoid silently selecting among multiple bound tenant accounts — extensions/feishu/src/tool-account.ts:72
      A background tool call can be sent under a different Feishu application if the resolver falls through to the global default; any binding-aware repair must reject ambiguous bindings rather than preserve configuration-order tenant selection.
      Confidence: 0.92

    What I checked:

    • Current resolver still prefers the global default: The resolver accepts an explicit account and a valid contextual account, but then returns channels.feishu.defaultAccount before checking whether an enabled account supports the required tool family. A background turn without a real contextual account therefore routes through the global default. (extensions/feishu/src/tool-account.ts:72, fb692c47f20a)
    • Current regression coverage encodes the disputed fallback: The Feishu routing test passes a non-account agentAccountId and expects the tool to choose the configured/default selection, so it does not cover a bound background agent selecting its Feishu account. (extensions/feishu/src/tool-account-routing.test.ts:372, fb692c47f20a)
    • Shared routing already has peerless binding semantics: resolveFirstBoundAccountId deliberately returns the first matching agent/channel binding for cron and other peerless callers. That proves the repository has an existing ordering rule, but it also means a tool-side adoption must decide how ambiguous Feishu bindings should behave. (src/routing/bound-account-read.ts:102, fb692c47f20a)
    • Bindings are publicly described as inbound routing: The multi-agent documentation says bindings route inbound messages, so extending them into an authoritative background credential-selection contract changes a documented boundary and should be decided explicitly. Public docs: docs/concepts/multi-agent.md. (docs/concepts/multi-agent.md:79, fb692c47f20a)
    • Latest available main does not alter this surface: The checkout is one commit behind origin/main at ad46acf102fc3ce9a026dbdc2f76cda1e4e24dc6; the path-scoped diff to that ref is empty for Feishu, routing, and channel docs, so the inspected resolver remains current for this issue. (extensions/feishu/src/tool-account.ts:23, ad46acf102fc)
    • Feature-history routing candidates: Path history identifies Peter Steinberger as the most frequent contributor to the tool-account surface; current-line blame attributes the present resolver block to Shakker, and the Feishu account-family test history includes Agustin Rivera’s account-gate work. (extensions/feishu/src/tool-account.ts:23, 3f3136ad5a9a)

    Likely related people:

    • steipete: Feature-history shortlog shows the strongest contribution concentration on the Feishu tool-account path, including recent extension refactoring around its tests. (role: recent area contributor; confidence: medium; commits: 960b050add1f, 2d2ddc43d0dc; files: extensions/feishu/src/tool-account.ts, extensions/feishu/src/tool-account-routing.test.ts)
    • Shakker: Current-line blame attributes the resolver block containing the default-account precedence to this author. (role: current resolver provenance; confidence: medium; commits: 3f3136ad5a9a; files: extensions/feishu/src/tool-account.ts)
    • Agustin Rivera: Recent Feishu tool-account-routing test history includes the account tool-family-gate repair, an adjacent constraint on any revised selection order. (role: adjacent account-tool contributor; confidence: medium; commits: d4f11d3005a5; files: extensions/feishu/src/tool-account-routing.test.ts)
    How this review workflow works
    • 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.
  2. added
    P2Normal backlog priority with limited blast radius.
    impact:securitySecurity boundary, credential, authz, sandbox, or sensitive-data risk.
    impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.
    impact:auth-providerAuth, provider routing, model choice, or SecretRef resolution may break.
    issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.
    clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.
    clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.
    clawsweeper:needs-maintainer-reviewClawSweeper marked this issue as needing maintainer review before automation.
    clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.
    clawsweeper:needs-security-reviewClawSweeper marked this issue as needing security-sensitive review.
    issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.
    clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.
    clawsweeper:fix-shape-clearClawSweeper found a clear likely implementation shape for this issue.
    and removed
    clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.
    issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.
    on Jun 25, 2026
  3. added
    issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.
    clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.
    issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.
    clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.
    clawsweeper:needs-security-reviewClawSweeper marked this issue as needing security-sensitive review.
    and removed
    clawsweeper:fix-shape-clearClawSweeper found a clear likely implementation shape for this issue.
    clawsweeper:needs-security-reviewClawSweeper marked this issue as needing security-sensitive review.
    clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.
    issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.
    clawsweeper:needs-live-reproClawSweeper needs live local, crabbox, or manual validation to confirm this issue.
    issue-rating: 🐚 platinum hermitGood issue quality with a plausible reproduction path needing some confirmation.
    clawsweeper:needs-maintainer-reviewClawSweeper marked this issue as needing maintainer review before automation.
    on Jul 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2Normal backlog priority with limited blast radius.clawsweeper:needs-product-decisionClawSweeper marked this issue as needing a product or behavior decision.clawsweeper:needs-security-reviewClawSweeper marked this issue as needing security-sensitive review.clawsweeper:no-new-fix-prClawSweeper does not recommend queueing a new automated fix PR for this issue.clawsweeper:source-reproClawSweeper found a high-confidence source-level issue reproduction.impact:auth-providerAuth, provider routing, model choice, or SecretRef resolution may break.impact:securitySecurity boundary, credential, authz, sandbox, or sensitive-data risk.impact:session-stateSession, memory, transcript, context, or agent state can drift or corrupt.issue-rating: 🦞 diamond lobsterVery strong issue quality with high-confidence source-level or clear reproduction.

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions