Skip to content

fix: annotate auto-grant permission failures with required_scope and console_url#1045

Open
ZEden0 wants to merge 1 commit into
larksuite:mainfrom
ZEden0:fix/auto-grant-permission-error-annotation
Open

fix: annotate auto-grant permission failures with required_scope and console_url#1045
ZEden0 wants to merge 1 commit into
larksuite:mainfrom
ZEden0:fix/auto-grant-permission-error-annotation

Conversation

@ZEden0
Copy link
Copy Markdown
Collaborator

@ZEden0 ZEden0 commented May 22, 2026

Summary

Follow-up to #1015. When AutoGrantCurrentUserDrivePermission fails with a
permission-class API error (lark code 99991672 / 99991679), the result map
now carries lark_code, required_scope, and console_url so AI agents
and CLI users can jump straight to the developer console to enable the
missing scope, instead of seeing only a generic "retry later" hint.

Changes

  • shortcuts/common/permission_grant.go — add annotateGrantPermissionError
    helper that inspects *output.ExitError, extracts permission_violations,
    picks the recommended scope, builds a brand-aware console URL, and
    overrides the generic fallback hint with an actionable one.
  • internal/registry/scope_hint.go (new) — extract three helpers shared
    between the two permission-error paths:
    • ExtractRequiredScopes — parse permission_violations defensively.
    • SelectRecommendedScopeFromStrings — string wrapper around the existing
      SelectRecommendedScope, with a "first scope" fallback.
    • BuildConsoleScopeURL — construct the scope-apply URL with brand
      routing (open.feishu.cn vs open.larksuite.com) and proper escaping.
  • cmd/root.go — refactor enrichPermissionError to delegate to the new
    helpers; deletes the local extractRequiredScopes and inline URL building
    that previously duplicated this logic.
  • internal/registry/scope_hint_test.go (new) — table-driven tests
    covering happy path, malformed input, brand variants, empty input, and
    the priority-table-vs-fallback ordering.
  • shortcuts/common/permission_grant_test.go — add 6 new tests:
    app-scope-not-enabled annotation, lark brand console URL, non-permission
    errors no-op, missing violations, empty appID, nil-args safety, plus an
    integration test through AutoGrantCurrentUserDrivePermission with a
    mocked 99991672 response.

Test Plan

  • go test -race -count=1 ./internal/registry/... ./shortcuts/common/... ./cmd/... passes
  • golangci-lint v2.1.6 run --new-from-rev=origin/main: 0 issues
  • go vet clean; go mod tidy is a no-op
  • Patch coverage on touched code well above the 60% target:
    • ExtractRequiredScopes 100%, BuildConsoleScopeURL 100%
    • SelectRecommendedScopeFromStrings 87.5%
    • annotateGrantPermissionError 91.3%
  • Manual verification: triggered lark drive +upload-file against an
    app missing the drive:drive scope; confirmed JSON result now contains
    lark_code, required_scope, console_url, and that the hint text
    references the developer console.

Related Issues

Follow-up to #1015.

Summary by CodeRabbit

  • New Features
    • Permission error messages now include required OAuth scopes and direct links to the developer console for applying missing permissions.

Review Change Stack

…console_url

When AutoGrantCurrentUserDrivePermission encounters lark code 99991672/99991679,
extract permission_violations from the underlying ExitError and surface
lark_code, required_scope, and console_url on the result map. Override the
generic fallback hint with one pointing at the developer console — the
concrete next step a user can take.

Refactor extractRequiredScopes / SelectRecommendedScope wrapping / console URL
construction out of cmd/root.go into internal/registry/scope_hint.go so both
the top-level enrichPermissionError path and the best-effort sub-call path in
shortcuts/common share one implementation.

Change-Id: Ida63ed160d1167b7961b6faac5c2cf9b7f971c65
@CLAassistant
Copy link
Copy Markdown

CLAassistant commented May 22, 2026

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label May 22, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 22, 2026

📝 Walkthrough

Walkthrough

This PR adds OAuth scope extraction and URL-building infrastructure for permission error enrichment. New registry helpers parse required scopes from API errors, select recommended scopes with fallback logic, and generate brand-specific developer console URLs. These helpers are integrated into permission grant error annotation and refactored into cmd/root.go's existing enrichment logic, replacing duplicate inline implementations.

Changes

Scope helpers and permission grant enrichment

Layer / File(s) Summary
Registry scope helpers and tests
internal/registry/scope_hint.go, internal/registry/scope_hint_test.go
ExtractRequiredScopes parses permission_violations.subject from error details, SelectRecommendedScopeFromStrings picks a recommended scope with fallback, and BuildConsoleScopeURL formats brand-specific developer console URLs with URL-encoded parameters. Unit tests verify extraction, host selection, encoding, and priority-based scope selection.
Permission grant error annotation
shortcuts/common/permission_grant.go, shortcuts/common/permission_grant_test.go
New annotateGrantPermissionError helper uses registry functions to enrich permission-related API failures with lark_code, required_scope, console_url, and an updated hint. AutoGrantCurrentUserDrivePermission calls the helper after building a failed result. Seven unit tests and one integration test verify correct annotation for missing scopes, brand-specific hosts, violations extraction, edge cases (nil/empty arguments, no violations, empty AppID), and that non-permission errors are ignored.
Refactor cmd/root.go enrichment
cmd/root.go
enrichPermissionError switches to registry.ExtractRequiredScopes, registry.SelectRecommendedScopeFromStrings, and registry.BuildConsoleScopeURL, removing the local extractRequiredScopes helper and the net/url import.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • larksuite/cli#1015: Both PRs enhance the permission grant flow—this PR adds structured scope extraction and console URL generation for permission errors, while the referenced PR adds user-facing stderr warnings and basic hint text for skipped/failed results.

Suggested labels

size/L, domain/ccm

Suggested reviewers

  • SunPeiYang996
  • GeekyMax

Poem

🐰 Scopes scattered across the error, now gathered with care,
Registry helpers parse what's needed, guide users to where
The console awaits with the fix they require—
Permission enriched, no more confusion to tire! 🎯

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: annotating auto-grant permission failures with required_scope and console_url, which is the central feature added across all modified files.
Description check ✅ Passed The description follows the template structure with complete Summary, Changes, Test Plan, and Related Issues sections. All required sections are present and well-populated with specific details about modifications and test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 unit tests (beta)
  • Create PR with unit tests

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.

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)
cmd/root.go (1)

406-440: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Guard console-specific hints when console_url is unavailable.

At Line 406, BuildConsoleScopeURL can return "" (e.g., missing AppID/scope), but Lines 419/428/435/438 still tell users to “see console_url”. That produces misleading guidance.

Suggested patch
 	// Build admin console URL with the recommended scope
 	consoleURL := registry.BuildConsoleScopeURL(cfg.Brand, cfg.AppID, recommended)
+	hasConsoleURL := consoleURL != ""
@@
 	case output.LarkErrUserScopeInsufficient, output.LarkErrUserNotAuthorized:
 		// User has not authorized the scope → re-authorize
 		exitErr.Detail.Message = fmt.Sprintf("User not authorized: required scope %s [%d]", recommended, larkCode)
 		if isBot {
-			exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
+			if hasConsoleURL {
+				exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
+			} else {
+				exitErr.Detail.Hint = "enable the required scope in developer console, then retry"
+			}
 		} else {
 			exitErr.Detail.Hint = fmt.Sprintf("run `lark-cli auth login --scope \"%s\"` in the background. It blocks and outputs a verification URL — retrieve the URL and open it in a browser to complete login.", recommended)
 		}
-		exitErr.Detail.ConsoleURL = consoleURL
+		if hasConsoleURL {
+			exitErr.Detail.ConsoleURL = consoleURL
+		}
@@
 	case output.LarkErrAppScopeNotEnabled:
 		// App has not enabled the API scope → admin console
 		exitErr.Detail.Message = fmt.Sprintf("App scope not enabled: required scope %s [%d]", recommended, larkCode)
-		exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
-		exitErr.Detail.ConsoleURL = consoleURL
+		if hasConsoleURL {
+			exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
+			exitErr.Detail.ConsoleURL = consoleURL
+		} else {
+			exitErr.Detail.Hint = "enable the required scope in developer console, then retry"
+		}
@@
 	default:
 		// Other permission errors (matched by keyword)
 		exitErr.Detail.Message = fmt.Sprintf("Permission denied: required scope %s [%d]", recommended, larkCode)
 		if isBot {
-			exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
+			if hasConsoleURL {
+				exitErr.Detail.Hint = "enable the scope in developer console (see console_url)"
+			} else {
+				exitErr.Detail.Hint = "enable the required scope in developer console, then retry"
+			}
 		} else {
 			exitErr.Detail.Hint = fmt.Sprintf(
 				"enable scope in console (see console_url), or run `lark-cli auth login --scope \"%s\"` in the background. It blocks and outputs a verification URL — retrieve the URL and open it in a browser to complete login.", recommended)
 		}
-		exitErr.Detail.ConsoleURL = consoleURL
+		if hasConsoleURL {
+			exitErr.Detail.ConsoleURL = consoleURL
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cmd/root.go` around lines 406 - 440, The code assumes
registry.BuildConsoleScopeURL(cfg.Brand, cfg.AppID, recommended) (consoleURL) is
always present but sometimes returns "", so adjust the permission-error handling
(switch block around consoleURL, exitErr.Detail.Message/Hint/ConsoleURL) to
guard console-specific hints: compute consoleURL once, then before setting
exitErr.Detail.Hint or exitErr.Detail.ConsoleURL check if consoleURL != "" and
only then append or use phrases like "(see console_url)" and set
exitErr.Detail.ConsoleURL = consoleURL; otherwise provide alternative hint text
that omits the console_url reference (for both isBot and non-bot branches) and
ensure exitErr.Detail.ConsoleURL is left empty/nil when consoleURL == "".
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@cmd/root.go`:
- Around line 406-440: The code assumes registry.BuildConsoleScopeURL(cfg.Brand,
cfg.AppID, recommended) (consoleURL) is always present but sometimes returns "",
so adjust the permission-error handling (switch block around consoleURL,
exitErr.Detail.Message/Hint/ConsoleURL) to guard console-specific hints: compute
consoleURL once, then before setting exitErr.Detail.Hint or
exitErr.Detail.ConsoleURL check if consoleURL != "" and only then append or use
phrases like "(see console_url)" and set exitErr.Detail.ConsoleURL = consoleURL;
otherwise provide alternative hint text that omits the console_url reference
(for both isBot and non-bot branches) and ensure exitErr.Detail.ConsoleURL is
left empty/nil when consoleURL == "".

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 182ddedc-7f43-488b-b1e3-4574fb68631c

📥 Commits

Reviewing files that changed from the base of the PR and between 5c01a7f and bd70f7c.

📒 Files selected for processing (5)
  • cmd/root.go
  • internal/registry/scope_hint.go
  • internal/registry/scope_hint_test.go
  • shortcuts/common/permission_grant.go
  • shortcuts/common/permission_grant_test.go

@codecov
Copy link
Copy Markdown

codecov Bot commented May 22, 2026

Codecov Report

❌ Patch coverage is 92.75362% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 67.79%. Comparing base (816927f) to head (bd70f7c).
⚠️ Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/common/permission_grant.go 85.71% 2 Missing and 2 partials ⚠️
internal/registry/scope_hint.go 97.36% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1045      +/-   ##
==========================================
+ Coverage   67.72%   67.79%   +0.06%     
==========================================
  Files         575      591      +16     
  Lines       54360    55237     +877     
==========================================
+ Hits        36817    37448     +631     
- Misses      14496    14680     +184     
- Partials     3047     3109      +62     

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

@github-actions
Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add ZEden0/cli#fix/auto-grant-permission-error-annotation -y -g

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

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants