Skip to content

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

Open
haozhenghua-code wants to merge 1 commit intolarksuite:mainfrom
haozhenghua-code:fix/bot_identity
Open

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

Conversation

@haozhenghua-code
Copy link
Copy Markdown

@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
    • Validation now rejects using --user-id when running as a bot, showing a clear error and directing users to use --chat-id or run as user.
  • Documentation
    • Clarified docs and 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 for user vs. bot identities.

@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@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

📝 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 documentation updated to reflect and cover these checks.

Changes

Cohort / File(s) Summary
Validation Logic
shortcuts/im/helpers.go, shortcuts/im/im_chat_messages_list.go
Reject --user-id early when runtime is bot (validation/FlagError / ExitValidation); resolveP2PChatID returns a validation error for bot runtimes instead of calling P2P.
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 runtime identity.
Coverage Tests
shortcuts/im/coverage_additional_test.go
Swapped one subtest to use a user runtime; added subtest asserting bot runtime rejects --user-id in chat resolution.
Network/Helper Tests
shortcuts/im/helpers_network_test.go
Added newUserShortcutRuntime helper, updated tests to use user runtime, removed outbound 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 guidance when --user-id is used under bot identity and recommended using --as user or supplying --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
  • liangshuo-1

Poem

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

🚥 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 clearly and specifically describes the main change: rejecting the --user-id flag under bot identity for the chat-messages-list command, which matches the core objective of the PR.
Description check ✅ Passed The description fully addresses the template with clear Summary, comprehensive Changes across all modified files, detailed Test Plan with checkmarks for verification, and Related Issues section.

✏️ 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 a guard in Validate and a defensive check in resolveP2PChatID to reject --user-id under bot identity for the chat-messages-list command, preventing a silent failure when the p2p resolution API endpoint requires user identity. Documentation and tests are updated accordingly and coverage is solid.

Confidence Score: 5/5

Safe to merge; the core fix is correct and well-tested. The two remaining findings are minor style/consistency notes.

Both findings are P2: the DryRun inconsistency only affects preview output (Validate correctly blocks execution), and the dead-code guard is harmless defensive boilerplate. No correctness, data-integrity, or security issues remain.

shortcuts/im/im_chat_messages_list.go — DryRun should mirror the bot+user-id guard from Validate for consistent preview output.

Important Files Changed

Filename Overview
shortcuts/im/im_chat_messages_list.go Validate correctly rejects bot+user-id; DryRun does not check bot identity when --user-id is set and will emit a misleading "Will resolve P2P" description that Validate would reject.
shortcuts/im/helpers.go Defensive bot guard added at the top of resolveP2PChatID; the dead-code guard in resolveChatIDForMessagesList (chatId == "" after resolveP2PChatID) is logically unreachable but harmless.
shortcuts/im/builders_test.go New subtests for mutual-exclusion and bot-identity rejection are correct and well-structured.
shortcuts/im/helpers_network_test.go newUserShortcutRuntime helper added; TestResolveP2PChatIDRejectsBot and updated happy-path/not-found tests look correct.
shortcuts/im/coverage_additional_test.go Bot-rejection subtest in TestResolveChatIDForMessagesList correctly exercises the defensive guard in resolveP2PChatID.
skills/lark-im/references/lark-im-chat-messages-list.md Documentation accurately reflects the user-identity requirement and new error row; AI guidance is clear.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["lark-cli im +chat-messages-list"] --> B{Validate}
    B -->|bot identity + --user-id| C["❌ FlagErrorf: requires user identity"]
    B -->|bot identity, no --chat-id| D["❌ FlagErrorf: specify --chat-id"]
    B -->|user identity, both flags| E["❌ ExactlyOne: mutually exclusive"]
    B -->|user identity, neither flag| F["❌ FlagErrorf: specify at least one"]
    B -->|passes| G{Execute}
    G -->|--chat-id set| H["Use chat_id directly"]
    G -->|--user-id set| I{resolveP2PChatID}
    I -->|bot identity| J["❌ bot guard error"]
    I -->|user identity| K["POST /im/v1/chat_p2p/batch_query"]
    K -->|found| L["GET /im/v1/messages"]
    K -->|not found| M["❌ P2P chat not found"]
    H --> L
    L --> N["Return formatted messages"]
Loading

Reviews (4): 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@ac55dbf8f0021b974346d9956265e1429bac79d7

🧩 Skill update

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

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

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.

3 participants