Skip to content

fix(im): reject --user-id under bot identity for chat-messages-list#340

Merged
YangJunzhou-01 merged 1 commit intolarksuite:mainfrom
haozhenghua-code:fix/bot_identity
Apr 13, 2026
Merged

fix(im): reject --user-id under bot identity for chat-messages-list#340
YangJunzhou-01 merged 1 commit intolarksuite:mainfrom
haozhenghua-code:fix/bot_identity

Conversation

@haozhenghua-code
Copy link
Copy Markdown
Contributor

@haozhenghua-code haozhenghua-code commented Apr 8, 2026

Summary

lark-cli im +chat-messages-list --user-id ou_xxx resolves the target user's p2p chat_id through POST /open-apis/im/v1/chat_p2p/batch_query, which requires user identity. Invoking it under bot identity previously failed silently or returned wrong results. This PR rejects the combination at the entry point with a clear error.

Changes

  • shortcuts/im/im_chat_messages_list.go: Validate now rejects --user-id when runtime.IsBot(), pointing users to --as user or --chat-id. Flag description updated to note "user identity only".
  • shortcuts/im/helpers.go: resolveP2PChatID gains a defensive guard returning the same validation error, in case the helper is reached via another path.
  • skills/lark-im/references/lark-im-chat-messages-list.md: document the user-identity requirement on --user-id, add the new error row to the troubleshooting table, and update the AI usage guidance.
  • Tests:
    • builders_test.go: add subtests for mutual-exclusion and bot-identity rejection of --user-id.
    • helpers_network_test.go: introduce newUserShortcutRuntime helper; keep the p2p happy-path / not-found tests on user identity; add TestResolveP2PChatIDRejectsBot.
    • coverage_additional_test.go: TestResolveChatIDForMessagesList keeps the user-identity happy path and adds a bot-rejection subtest.

Test Plan

  • Unit tests pass: go test ./shortcuts/im/...
  • go build ./... clean
  • Manual verification with a real tenant:
    • lark-cli im +chat-messages-list --as bot --user-id ou_xxx → rejected at Validate with requires user identity
    • lark-cli im +chat-messages-list --as bot --chat-id oc_xxx → returns messages normally
    • lark-cli im +chat-messages-list --as user --user-id ou_xxx → resolves p2p chat and returns DM messages
    • lark-cli im +chat-messages-list --chat-id oc_xxx --user-id ou_xxx → mutual-exclusion error

Related Issues

  • None

Summary by CodeRabbit

  • Bug Fixes
    • Commands now reject using --user-id when authenticated as a bot, return a clear error directing users to use --chat-id or run as user, and avoid attempting p2p resolution under bot identity.
  • Documentation
    • Clarified docs/troubleshooting: automatic p2p chat resolution requires user identity; guidance to pass --as user or supply --chat-id.
  • Tests
    • Added/updated tests covering validation and p2p resolution behaviors for user vs. bot identities.

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 8, 2026

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added domain/im PR touches the im domain size/M Single-domain feat or fix with limited business impact labels Apr 8, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 8, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 20a72c4f-eb98-4065-a090-1cc9fc3729dd

📥 Commits

Reviewing files that changed from the base of the PR and between e01a48d and 03f60f7.

📒 Files selected for processing (6)
  • shortcuts/im/builders_test.go
  • shortcuts/im/coverage_additional_test.go
  • shortcuts/im/helpers.go
  • shortcuts/im/helpers_network_test.go
  • shortcuts/im/im_chat_messages_list.go
  • skills/lark-im/references/lark-im-chat-messages-list.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • shortcuts/im/builders_test.go
  • shortcuts/im/helpers.go
  • shortcuts/im/im_chat_messages_list.go
  • shortcuts/im/coverage_additional_test.go
  • shortcuts/im/helpers_network_test.go

📝 Walkthrough

Walkthrough

Validation now enforces that --user-id for P2P chat resolution is only accepted when running with user identity; bot identity rejects --user-id and requires --chat-id or --as user. Tests and docs updated to cover these checks and the early-reject behavior.

Changes

Cohort / File(s) Summary
Validation & Runtime
shortcuts/im/helpers.go, shortcuts/im/im_chat_messages_list.go
Add early guard rejecting --user-id when runtime.IsBot(); im_chat_messages_list Validate branches on bot vs user identity and emits FlagErrorf messages requiring --chat-id or --as user.
Builder Tests
shortcuts/im/builders_test.go
Added subtests for ImChatMessageList.Validate verifying mutual-exclusion and bot-vs-user identity error messages; imported github.com/larksuite/cli/internal/core to set resolved identity.
Coverage Tests
shortcuts/im/coverage_additional_test.go
Switched one subtest to use a user runtime and added a subtest asserting that bot runtime rejects --user-id with an appropriate error.
Network/Helper Tests
shortcuts/im/helpers_network_test.go
Added newUserShortcutRuntime helper, updated tests to use user runtime, removed Authorization header assertion, and added test verifying resolveP2PChatID rejects bot identity.
Documentation
skills/lark-im/references/lark-im-chat-messages-list.md
Clarified --user-id is user-identity-only, added troubleshooting entry for bot-identity rejection and guidance to use --as user or supply --chat-id.

Sequence Diagram(s)

sequenceDiagram
    participant User as "CLI User"
    participant CLI as "Command (Validate)"
    participant Runtime as "Runtime (resolvedAs)"
    participant P2P as "P2P Chat API"

    rect rgba(200,230,201,0.5)
    User->>CLI: run command with --user-id
    CLI->>Runtime: check resolvedAs / IsBot()
    end

    alt runtime is user
        Runtime-->>CLI: IsBot() == false
        CLI->>P2P: call resolveP2PChatID(--user-id)
        P2P-->>CLI: returns chat_id or not_found
        CLI->>User: proceed with chat_id or report not_found
    else runtime is bot
        Runtime-->>CLI: IsBot() == true
        CLI-->>User: validation error ("requires user identity" or "use --chat-id")
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • YangJunzhou-01
  • zhaoleibd

Poem

🐰 I hop through flags and identity,
I sniff where p2p chat ids should be,
If a bot's on the job, I kindly plea:
"Use --as user or hand me --chat-id," said me. 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(im): reject --user-id under bot identity for chat-messages-list' accurately and specifically describes the primary change, clearly summarizing the fix for the identified issue.
Description check ✅ Passed The description comprehensively covers all required template sections with detailed explanations of changes, thorough test plan with verification steps, and proper formatting.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Apr 8, 2026

Greptile Summary

This PR adds input validation to reject --user-id under bot identity for +chat-messages-list, fixing a silent failure when calling the user-only POST /open-apis/im/v1/chat_p2p/batch_query endpoint with bot credentials. The guard is applied at both Validate (primary enforcement) and inside resolveP2PChatID (defensive layer), with matching documentation and test coverage.

Confidence Score: 5/5

Safe to merge — the primary fix is correct and well-tested; remaining findings are minor test-quality suggestions.

No P0/P1 issues found. The validation logic is correct and covers all bot/user combinations. Both P2 findings (missing auth-header assertion in the migrated test, and the DryRun gap for bot+user-id) are non-blocking style/coverage suggestions that do not affect production behaviour.

shortcuts/im/helpers_network_test.go — the removed Authorization header assertion could be reinstated for user-identity coverage.

Important Files Changed

Filename Overview
shortcuts/im/im_chat_messages_list.go Validate now splits bot vs. user paths; bot identity rejects --user-id and requires --chat-id; user identity path retains existing ExactlyOne logic. DryRun still renders P2P description for bot+user-id but Validate gates execution.
shortcuts/im/helpers.go Defensive bot guard added at the top of resolveP2PChatID — prevents silent misuse if the helper is called from a path that bypasses Validate.
shortcuts/im/helpers_network_test.go newUserShortcutRuntime helper added; existing P2P tests migrated to user identity; TestResolveP2PChatIDRejectsBot added. The Authorization header assertion from the previous TestResolveP2PChatID was removed without a replacement user-token check.
shortcuts/im/builders_test.go Two new subtests cover mutual-exclusion and bot-identity rejection for ImChatMessageList.Validate; logic is correct.
shortcuts/im/coverage_additional_test.go P2P happy-path test migrated to newUserShortcutRuntime; bot-rejection subtest added with no-network guard; coverage is sound.
skills/lark-im/references/lark-im-chat-messages-list.md Docs updated to document user-identity requirement on --user-id, new error row added to troubleshooting table, AI guidance updated.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[lark-cli im +chat-messages-list] --> B{Validate}
    B --> C{IsBot?}
    C -- Yes --> D{--user-id set?}
    D -- Yes --> E[❌ Error: requires user identity]
    D -- No --> F{--chat-id set?}
    F -- No --> G[❌ Error: specify --chat-id]
    F -- Yes --> H[✅ Pass validation]
    C -- No --> I{ExactlyOne chat-id / user-id}
    I -- Neither --> J[❌ Error: specify at least one]
    I -- Both --> K[❌ Error: mutually exclusive]
    I -- Exactly one --> L[✅ Pass validation]
    H --> M[Execute]
    L --> M
    M --> N{user-id provided?}
    N -- Yes --> O[resolveP2PChatID]
    O --> P{IsBot? defensive guard}
    P -- Yes --> Q[❌ Error: requires user identity]
    P -- No --> R[POST /im/v1/chat_p2p/batch_query]
    R --> S[GET /im/v1/messages]
    N -- No --> S
Loading

Reviews (5): Last reviewed commit: "fix(im): reject --user-id under bot iden..." | Re-trigger Greptile

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
shortcuts/im/helpers.go (1)

378-410: ⚠️ Potential issue | 🟠 Major

LGTM on the bot-identity guard for resolveP2PChatID.

The defensive check correctly rejects bot identity before making the P2P API call, with a clear error message guiding users to use --as user or --chat-id.

However, im_messages_send.go also uses --user-id to resolve a target user but does not have this bot-identity check. In the Validate function, there is no check equivalent to the one in im_chat_messages_list.go (lines 77-79). This creates an inconsistency where:

  • im +chat-messages-list --user-id ou_xxx rejects bot identity ✓
  • im +messages-send --user-id ou_xxx accepts bot identity (and may silently fail or produce unexpected results)

Consider adding the same bot-identity validation to ImMessagesSend.Validate for consistency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/im/helpers.go` around lines 378 - 410, Add the same bot-identity
guard to ImMessagesSend.Validate that resolveP2PChatID and im_chat_messages_list
use: in the ImMessagesSend.Validate method check runtime.IsBot() and if true
return output.Errorf(output.ExitValidation, "validation", "--user-id requires
user identity (--as user); use --chat-id when calling with bot identity"); this
mirrors the existing behavior in resolveP2PChatID and ensures --user-id is
rejected when running as a bot.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@shortcuts/im/helpers.go`:
- Around line 378-410: Add the same bot-identity guard to
ImMessagesSend.Validate that resolveP2PChatID and im_chat_messages_list use: in
the ImMessagesSend.Validate method check runtime.IsBot() and if true return
output.Errorf(output.ExitValidation, "validation", "--user-id requires user
identity (--as user); use --chat-id when calling with bot identity"); this
mirrors the existing behavior in resolveP2PChatID and ensures --user-id is
rejected when running as a bot.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 69d09f44-d211-4344-bd21-4d4516ed51c2

📥 Commits

Reviewing files that changed from the base of the PR and between 63ea52b and 5d377cc.

📒 Files selected for processing (6)
  • shortcuts/im/builders_test.go
  • shortcuts/im/coverage_additional_test.go
  • shortcuts/im/helpers.go
  • shortcuts/im/helpers_network_test.go
  • shortcuts/im/im_chat_messages_list.go
  • skills/lark-im/references/lark-im-chat-messages-list.md

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 8, 2026

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@03f60f7e78af43863201064f90f456565db7db85

🧩 Skill update

npx skills add haozhenghua-code/larksuite-cli#fix/bot_identity -y -g

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
shortcuts/im/helpers_network_test.go (1)

164-173: Strengthen bot-rejection test by asserting no network dispatch.

The error assertion is good; add an explicit request counter so this test also enforces early-return behavior before any HTTP call.

🔍 Suggested tightening for the test
 func TestResolveP2PChatIDRejectsBot(t *testing.T) {
+	calls := 0
 	runtime := newBotShortcutRuntime(t, shortcutRoundTripFunc(func(req *http.Request) (*http.Response, error) {
+		calls++
 		return nil, fmt.Errorf("unexpected request: %s", req.URL.String())
 	}))
 
 	_, err := resolveP2PChatID(runtime, "ou_123")
 	if err == nil || !strings.Contains(err.Error(), "requires user identity") {
 		t.Fatalf("resolveP2PChatID() error = %v, want requires user identity", err)
 	}
+	if calls != 0 {
+		t.Fatalf("resolveP2PChatID() made %d HTTP call(s), want 0", calls)
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/im/helpers_network_test.go` around lines 164 - 173, The test
TestResolveP2PChatIDRejectsBot should assert no HTTP requests are made by adding
a request counter in the fake round-trip handler: declare a counter (e.g.,
reqCount := 0) and increment it inside the shortcutRoundTripFunc handler used by
newBotShortcutRuntime, then call resolveP2PChatID(runtime, "ou_123") and after
verifying the error contains "requires user identity" also assert reqCount == 0
to ensure resolveP2PChatID returns early and does not dispatch any network
request.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@shortcuts/im/helpers_network_test.go`:
- Around line 164-173: The test TestResolveP2PChatIDRejectsBot should assert no
HTTP requests are made by adding a request counter in the fake round-trip
handler: declare a counter (e.g., reqCount := 0) and increment it inside the
shortcutRoundTripFunc handler used by newBotShortcutRuntime, then call
resolveP2PChatID(runtime, "ou_123") and after verifying the error contains
"requires user identity" also assert reqCount == 0 to ensure resolveP2PChatID
returns early and does not dispatch any network request.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 62fd76e4-1bee-43e5-b3db-bb9a7cb5a6fd

📥 Commits

Reviewing files that changed from the base of the PR and between cb313d3 and e01a48d.

📒 Files selected for processing (6)
  • shortcuts/im/builders_test.go
  • shortcuts/im/coverage_additional_test.go
  • shortcuts/im/helpers.go
  • shortcuts/im/helpers_network_test.go
  • shortcuts/im/im_chat_messages_list.go
  • skills/lark-im/references/lark-im-chat-messages-list.md
✅ Files skipped from review due to trivial changes (1)
  • skills/lark-im/references/lark-im-chat-messages-list.md
🚧 Files skipped from review as they are similar to previous changes (4)
  • shortcuts/im/builders_test.go
  • shortcuts/im/coverage_additional_test.go
  • shortcuts/im/helpers.go
  • shortcuts/im/im_chat_messages_list.go

The chat_p2p/batch_query endpoint that resolves a user's p2p chat_id
requires user identity. Calling +chat-messages-list with --user-id
under bot identity previously failed silently or returned wrong
results.

- Validate: reject --user-id when runtime.IsBot(), with a hint to
  pass --as user or use --chat-id instead
- resolveP2PChatID: add defensive guard for the same condition in
  case the helper is reached via another path
- Update --user-id flag description and the lark-im skill reference
  to note the user-identity requirement
- Tests: add bot-rejection cases for Validate and resolveP2PChatID,
  switch p2p happy-path tests to a user-identity runtime helper
@YangJunzhou-01 YangJunzhou-01 merged commit 25534d7 into larksuite:main Apr 13, 2026
14 checks passed
yxzhaao pushed a commit to yxzhaao/cli that referenced this pull request Apr 14, 2026
…arksuite#340)

The chat_p2p/batch_query endpoint that resolves a user's p2p chat_id
requires user identity. Calling +chat-messages-list with --user-id
under bot identity previously failed silently or returned wrong
results.

- Validate: reject --user-id when runtime.IsBot(), with a hint to
  pass --as user or use --chat-id instead
- resolveP2PChatID: add defensive guard for the same condition in
  case the helper is reached via another path
- Update --user-id flag description and the lark-im skill reference
  to note the user-identity requirement
- Tests: add bot-rejection cases for Validate and resolveP2PChatID,
  switch p2p happy-path tests to a user-identity runtime helper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/im PR touches the im domain size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants