Skip to content

feat(drive): add +apply-permission to request doc access#588

Open
caojie0621 wants to merge 4 commits intomainfrom
feat/perm_apply
Open

feat(drive): add +apply-permission to request doc access#588
caojie0621 wants to merge 4 commits intomainfrom
feat/perm_apply

Conversation

@caojie0621
Copy link
Copy Markdown
Collaborator

@caojie0621 caojie0621 commented Apr 21, 2026

Summary

Wrap the POST /open-apis/drive/v1/permissions/:token/members/apply
endpoint as a new drive +apply-permission shortcut. The endpoint lets a
user request view or edit access on a doc/sheet/file/wiki/bitable/docx
(plus mindnote / minutes / slides) from its owner; the CLI previously
exposed no first-class path for it, forcing bare lark-cli api calls.

Shortcut

Aspect Value
Command drive +apply-permission
Scope docs:permission.member:apply
AuthTypes ["user"] — the endpoint rejects tenant_access_token, so bot identity is refused up-front
Risk write (sends a push notification to the document owner)

Flags

  • --token (required): accepts either a bare token or a document URL.
    URL path markers auto-infer type: /docx/, /sheets/, /base/,
    /bitable/, /file/, /wiki/, /doc/, /mindnote/, /minutes/,
    /slides/.
  • --type: optional when the URL shape is recognized; required with a
    bare token. Explicit --type always wins over URL inference.
  • --perm (required): view or edit. full_access is refused
    client-side to match the spec (the server also rejects it but catching
    it locally avoids a wasted request and an opaque server error).
  • --remark: optional note attached to the request card shown to the
    owner; omitted from the body when empty.

Test plan

  • go test ./shortcuts/drive/ ./internal/output/

Skill docs

  • New skills/lark-drive/references/lark-drive-apply-permission.md with
    usage, parameter table, identity/scope requirements, rate-limit
    callout, and full error-code table.
  • skills/lark-drive/SKILL.md shortcut table gains a row for the new
    command.

Summary by CodeRabbit

  • New Features

    • Added drive +apply-permission shortcut to request view/edit access from document owners, with optional remark and --dry-run preview.
  • Bug Fixes

    • Improved CLI error messages for permission-apply: explicit per-day rate-limit guidance and a clear "not applicable" explanation when a request cannot be applied.
  • Documentation

    • New detailed guide covering usage, parameters, quotas, examples, and common errors.
  • Tests

    • Added unit, integration, and end-to-end tests; increased Drive CLI coverage.

Wrap the POST /drive/v1/permissions/:token/members/apply endpoint as a
user-only shortcut. --token accepts either a bare token or a document
URL, with type auto-inferred from the URL path (/docx/, /sheets/,
/base/, /bitable/, /file/, /wiki/, /doc/, /mindnote/, /minutes/,
/slides/); an explicit --type always wins. --perm is limited to view or
edit; full_access is rejected client-side to match the spec.

Classifier gains two domain-specific hints for the endpoint's newly
documented error codes: 1063006 (per-user-per-document quota of 5/day
reached) and 1063007 (document does not accept apply requests — covers
disallow-external-apply, already-has-access, and unsupported-type).
@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/L Large or sensitive change across domains or core paths labels Apr 21, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 21, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1996976c-ee21-4806-a969-83d5eede30bf

📥 Commits

Reviewing files that changed from the base of the PR and between d0c876e and ff73571.

📒 Files selected for processing (2)
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go

📝 Walkthrough

Walkthrough

Adds a new Drive shortcut command +apply-permission that parses token/URL and optional type, builds and posts permission-apply requests to the Drive API, extends Lark error classification for permission-apply error codes, and includes unit, integration, e2e tests and documentation.

Changes

Cohort / File(s) Summary
Error Handling
internal/output/lark_errors.go, internal/output/lark_errors_test.go
Added constants LarkErrDrivePermApplyRateLimit = 1063006 and LarkErrDrivePermApplyNotApplicable = 1063007; extended ClassifyLarkError to map rate-limit → ExitAPI/rate_limit with quota hint and not-applicable → ExitAPI/invalid_params with contextual messaging. Tests assert mappings and hint text.
New Shortcut Implementation
shortcuts/drive/drive_apply_permission.go, shortcuts/drive/drive_apply_permission_test.go
Introduced DriveApplyPermission shortcut, resolvePermApplyTarget (URL→token/type inference, validation), request body builder, DryRun/Execute flows that POST to /open-apis/drive/v1/permissions/:token/members/apply. Tests cover validation, URL→type inference, dry-run output, request composition, and API error handling.
Shortcut Registry
shortcuts/drive/shortcuts.go, shortcuts/drive/shortcuts_test.go
Registered DriveApplyPermission in Shortcuts() and updated registry test to expect +apply-permission.
Documentation
skills/lark-drive/SKILL.md, skills/lark-drive/references/lark-drive-apply-permission.md
Added skill index entry and reference doc describing usage, auth requirements (user-only), allowed perms (view/edit), examples, rate limits (5/day), error mappings, and the OpenAPI endpoint.
E2E / Coverage Updates
tests/cli_e2e/drive/coverage.md, tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go
Added dry-run E2E tests and updated coverage doc to include drive +apply-permission dry-run scenarios validating inference, request shape, and client-side validation.
Tests (unit/integration)
shortcuts/drive/drive_apply_permission_test.go, internal/output/lark_errors_test.go, shortcuts/drive/shortcuts_test.go
New and updated tests exercising validation, enum checks, dry-run/integration flows, and error-code handling for permission-apply responses.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as "CLI\n(command)"
    participant Validator as "Validator\n(resolvePermApplyTarget)"
    participant APIClient as "API Client"
    participant Server as "Drive API"

    User->>CLI: drive +apply-permission --token <token|url> --perm <view|edit> [--type] [--remark]
    CLI->>Validator: resolvePermApplyTarget(rawTokenOrURL, explicitType)
    Validator-->>CLI: (token, docType) or error
    alt validation succeeds
        CLI->>CLI: build body {perm, optional remark}
        CLI->>APIClient: POST /open-apis/drive/v1/permissions/:token/members/apply?type=docType
        APIClient->>Server: Send request
        Server-->>APIClient: 200 OK or error (1063006 / 1063007 ...)
        APIClient-->>CLI: response
        CLI-->>User: print status or classified error (rate_limit / invalid_params)
    else validation fails
        CLI-->>User: print validation error
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • fangshuyu-768

Poem

🐇 I sniffed a URL and found a token bright,
I hopped to ask the Owner for view or edit right,
Five tiny quotas hum their daily tune,
If blocked, I whisper hints beneath the moon,
A carrot note sent — permission takes flight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding a new drive shortcut command to request document access.
Description check ✅ Passed The description covers all required template sections with comprehensive detail on motivation, specific changes, test verification, and related issues.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/perm_apply

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 21, 2026

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/perm_apply -y -g

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 21, 2026

Codecov Report

❌ Patch coverage is 94.20290% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 61.12%. Comparing base (fbed6be) to head (ff73571).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/drive/drive_apply_permission.go 93.54% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #588      +/-   ##
==========================================
+ Coverage   60.92%   61.12%   +0.19%     
==========================================
  Files         399      401       +2     
  Lines       34089    34199     +110     
==========================================
+ Hits        20770    20903     +133     
+ Misses      11395    11370      -25     
- Partials     1924     1926       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
shortcuts/drive/drive_apply_permission_test.go (1)

218-239: Rate-limit test asserts only err != nil; consider mirroring NotApplicableHint.

The sibling TestDriveApplyPermission_ExecuteNotApplicableHint verifies the surfaced server/hint text, but this test stops at non-nil error. Since the function name includes Hint, asserting on the hint substring (e.g., "5 times per day") would lock in that the classifier wiring for LarkErrDrivePermApplyRateLimit reaches the user.

♻️ Suggested assertion
 	if err == nil {
 		t.Fatal("expected error for 1063006")
 	}
+	if !strings.Contains(err.Error(), "5 times per day") {
+		t.Fatalf("expected rate-limit hint, got: %v", err)
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/drive/drive_apply_permission_test.go` around lines 218 - 239,
TestDriveApplyPermission_ExecuteRateLimitHint currently only checks err != nil;
update it to assert the returned error contains the rate-limit hint text (mirror
the approach in TestDriveApplyPermission_ExecuteNotApplicableHint). After
calling mountAndRunDrive with DriveApplyPermission, check that the error string
includes the expected rate-limit hint substring (e.g., "5 times per day" or the
canonical hint produced by the LarkErrDrivePermApplyRateLimit classifier) so the
test verifies the classifier wiring surfaces the hint to the user.
🤖 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/drive/drive_apply_permission_test.go`:
- Around line 218-239: TestDriveApplyPermission_ExecuteRateLimitHint currently
only checks err != nil; update it to assert the returned error contains the
rate-limit hint text (mirror the approach in
TestDriveApplyPermission_ExecuteNotApplicableHint). After calling
mountAndRunDrive with DriveApplyPermission, check that the error string includes
the expected rate-limit hint substring (e.g., "5 times per day" or the canonical
hint produced by the LarkErrDrivePermApplyRateLimit classifier) so the test
verifies the classifier wiring surfaces the hint to the user.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 19903b7d-5e47-4c48-a516-02b4d7437f75

📥 Commits

Reviewing files that changed from the base of the PR and between e02c442 and b5a381a.

📒 Files selected for processing (8)
  • internal/output/lark_errors.go
  • internal/output/lark_errors_test.go
  • shortcuts/drive/drive_apply_permission.go
  • shortcuts/drive/drive_apply_permission_test.go
  • shortcuts/drive/shortcuts.go
  • shortcuts/drive/shortcuts_test.go
  • skills/lark-drive/SKILL.md
  • skills/lark-drive/references/lark-drive-apply-permission.md

Comment thread shortcuts/drive/drive_apply_permission_test.go
Invoke the real CLI binary via clie2e.RunCmd under --dry-run and
parse the rendered request JSON with gjson to lock in method, URL
path (including the token segment), type query parameter (auto-inferred
for docx / sheet / slides URLs, taken from explicit --type for bare
tokens), perm body field, and remark presence/omission. A separate
test asserts --perm full_access is rejected by the enum validator
before reaching the server. Fake LARKSUITE_CLI_APP_ID / APP_SECRET /
BRAND are enough because dry-run short-circuits before any API call.

Update drive coverage.md to add a row and refresh metrics.
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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go`:
- Around line 68-78: The test case labeled "bare token with explicit type wins
over inference" doesn't actually exercise URL-derived type override because the
args use a bare token; update the test row in
drive_apply_permission_dryrun_test.go so it either (A) supplies a URL-like token
(e.g., include a "--url" or a token that contains a host/path) alongside the
explicit "--type" to force an inference path to be present and ensure wantType
"bitable" overrides it, or (B) rename the test and its description to remove the
claim about URL-inference; modify the args array and/or the name string
accordingly and keep the expected fields wantURL, wantType, and wantPerm
consistent with the change.
- Around line 28-32: Add t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) to
isolate the CLI config for subprocesses: in the TestDrive_ApplyPermissionDryRun
test (and the other E2E test in this file that spawns the real CLI subprocess)
set the LARKSUITE_CLI_CONFIG_DIR environment variable to t.TempDir() at the
start of the test so the subprocess cannot read/write the developer's real CLI
config.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 59dfe81c-e8fe-4a38-9b50-298045c81df5

📥 Commits

Reviewing files that changed from the base of the PR and between b5a381a and 3cc22c5.

📒 Files selected for processing (2)
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go

Comment thread tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go
Comment thread tests/cli_e2e/drive/drive_apply_permission_dryrun_test.go Outdated
Set LARKSUITE_CLI_CONFIG_DIR to t.TempDir() in both +apply-permission
dry-run tests so the subprocess can't read a developer's real
credentials/profile instead of the fake env vars the tests inject.
Previous "bare token with explicit type wins over inference" row used a
bare token, which has no URL-derived type to override. Replace it with
a /docx/ URL + --type wiki combo that actually forces the explicit flag
to win over URL inference, and add a separate bare-token row to keep
the simpler path covered. Refresh coverage.md wording to match.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm domain size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant