Skip to content

fix: validate auth login scopes locally#454

Open
lttlin wants to merge 1 commit intolarksuite:mainfrom
lttlin:fix/416-auth-scope-validation
Open

fix: validate auth login scopes locally#454
lttlin wants to merge 1 commit intolarksuite:mainfrom
lttlin:fix/416-auth-scope-validation

Conversation

@lttlin
Copy link
Copy Markdown

@lttlin lttlin commented Apr 13, 2026

Problem

lark-cli auth login --scope currently forwards the raw scope string to the device authorization endpoint. If the input contains malformed spacing, line breaks, or a typo in one scope name, the user only sees the remote OAuth error saying the scope list is invalid, without any indication of which scope caused it.

Root Cause

The explicit --scope path does not normalize user input or validate the requested scope names against the CLI's known scope registry before making the device authorization request.

Fix

Normalize explicit scope input with strings.Fields, deduplicate repeated entries, and validate each requested scope against the union of known registry scopes and shortcut scopes before calling the OAuth device authorization endpoint. Invalid scope names now fail fast with a local validation error that points users to auth scopes or the domain-based recommend flow.

Validation

  • Static code review of the new auth login validation path
  • Added unit tests covering whitespace normalization, invalid scope rejection, and early failure before network calls

Closes #416

Summary by CodeRabbit

  • New Features

    • The auth login command now validates scopes to ensure only recognized authentication scopes are accepted.
    • Scope parameters are automatically normalized, removing whitespace variations and duplicate scopes.
    • Invalid scopes are rejected with helpful error messages guiding users to valid options.
  • Tests

    • Added test coverage for scope validation functionality.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 13, 2026

📝 Walkthrough

Walkthrough

The PR adds explicit scope validation and normalization to the auth login command. When the --scope flag is provided, the code splits the input, validates each scope against a computed set of known scopes, deduplicates entries, and normalizes the final scope string before any network operations. Invalid scopes trigger validation errors with helpful hints.

Changes

Cohort / File(s) Summary
Scope Validation Logic
cmd/auth/login.go
Added validateExplicitScopes and knownScopesForIdentity helper functions to normalize, validate, and deduplicate user-provided scopes. Integrates scope validation into authLoginRun with error handling for invalid or empty scope input.
Scope Validation Tests
cmd/auth/login_test.go
Added three test functions covering whitespace normalization and deduplication, rejection of unknown scopes with specific error messages (including CLI hint for scope discovery), and early validation failure before network operations.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • liangshuo-1

Poem

🐰 A rabbit hops through scope-filled lands,
Checking each one with careful hands,
Duplicates vanish, invalid scopes fade,
Better error messages are displayed!
Clear paths to auth—no more charade. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.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 accurately summarizes the main change: validating auth login scopes locally before sending to the OAuth endpoint.
Description check ✅ Passed The PR description covers problem statement, root cause, fix implementation, and validation approach. All required template sections are present and completed.
Linked Issues check ✅ Passed The PR directly addresses issue #416 by implementing local scope validation that provides clear error messages for invalid scopes, replacing remote OAuth errors with actionable local diagnostics.
Out of Scope Changes check ✅ Passed All changes are scoped to auth login scope validation: new validation helpers, local scope normalization, and deduplication—all directly addressing the linked issue.

✏️ 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.

@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label Apr 13, 2026
@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.


voita seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

@JackZhao10086 JackZhao10086 self-requested a review April 17, 2026 05:09
@JackZhao10086 JackZhao10086 marked this pull request as ready for review April 17, 2026 05:12
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/auth/login.go (1)

189-202: ⚠️ Potential issue | 🟡 Minor

Run the --scope vs --domain/--recommend mutex check before validating scopes.

Today, when a user passes both --scope "bogus_scope" and --domain calendar, they receive an invalid scope(s): bogus_scope error instead of the clearer cannot use --scope together with --domain/--recommend message at line 201. The mutex check should run first so users get the more actionable diagnostic (and we avoid unnecessary scope-set construction on a request that will be rejected anyway).

♻️ Proposed reordering
 	finalScope := opts.Scope
-	if finalScope != "" {
-		normalizedScope, err := validateExplicitScopes(finalScope, "user")
-		if err != nil {
-			return err
-		}
-		finalScope = normalizedScope
-	}
 
 	// Resolve scopes from domain/permission filters
 	if len(selectedDomains) > 0 || opts.Recommend {
 		if opts.Scope != "" {
 			return output.ErrValidation("cannot use --scope together with --domain/--recommend")
 		}
 
 		var candidateScopes []string
 		if len(selectedDomains) > 0 {
 			candidateScopes = collectScopesForDomains(selectedDomains, "user")
 		} else {
 			// --recommend without --domain: all domains
 			candidateScopes = collectScopesForDomains(sortedKnownDomains(), "user")
 		}
 
 		// Filter to auto-approve scopes if --recommend or interactive "common"
 		if opts.Recommend || scopeLevel == "common" {
 			candidateScopes = registry.FilterAutoApproveScopes(candidateScopes)
 		}
 
 		if len(candidateScopes) == 0 {
 			return output.ErrValidation("no matching scopes found, check domain/scope options")
 		}
 
 		finalScope = strings.Join(candidateScopes, " ")
+	} else if finalScope != "" {
+		normalizedScope, err := validateExplicitScopes(finalScope, "user")
+		if err != nil {
+			return err
+		}
+		finalScope = normalizedScope
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/auth/login.go` around lines 189 - 202, The mutex check between --scope
and --domain/--recommend should run before validating the explicit scope: move
the block that checks if len(selectedDomains) > 0 || opts.Recommend and returns
output.ErrValidation("cannot use --scope together with --domain/--recommend")
(and its inner opts.Scope check) to occur before calling validateExplicitScopes
on finalScope; keep the validateExplicitScopes call (and assignment to
finalScope) only after the mutex check passes so
validateExplicitScopes(finalScope, "user") is not invoked when the request will
be rejected. Ensure you reference finalScope, opts.Scope, selectedDomains,
opts.Recommend, validateExplicitScopes, and output.ErrValidation in the change.
🧹 Nitpick comments (1)
cmd/auth/login.go (1)

541-558: Deduplicate invalid scopes before rendering the error message.

The seen map only filters duplicates of valid scopes; invalid tokens get appended unconditionally. Input like "foo foo" produces invalid scope(s): foo, foo, which is awkward for both humans and the AI agents parsing these errors (per coding guidelines, error messages should be structured and specific for AI agent parsing).

♻️ Proposed fix
 	knownScopes := knownScopesForIdentity(identity)
 	invalid := make([]string, 0)
 	result := make([]string, 0, len(normalized))
 	seen := make(map[string]bool, len(normalized))
+	invalidSeen := make(map[string]bool)
 	for _, s := range normalized {
 		if !knownScopes[s] {
-			invalid = append(invalid, s)
+			if !invalidSeen[s] {
+				invalidSeen[s] = true
+				invalid = append(invalid, s)
+			}
 			continue
 		}
 		if seen[s] {
 			continue
 		}
 		seen[s] = true
 		result = append(result, s)
 	}

As per coding guidelines: "Make error messages structured, actionable, and specific for AI agent parsing".

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

In `@cmd/auth/login.go` around lines 541 - 558, The code appends invalid scope
tokens to invalid without deduplication, causing repeated entries; update the
loop that iterates over normalized (using normalized, knownScopes, invalid,
seen, result) to skip adding an invalid token if it's already recorded (either
reuse the existing seen map for invalids or add a separate seenInvalid map) so
invalid contains only unique scope names before the ErrValidation call; keep the
rest of the error formatting the same.
🤖 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 `@cmd/auth/login.go`:
- Around line 189-202: The mutex check between --scope and --domain/--recommend
should run before validating the explicit scope: move the block that checks if
len(selectedDomains) > 0 || opts.Recommend and returns
output.ErrValidation("cannot use --scope together with --domain/--recommend")
(and its inner opts.Scope check) to occur before calling validateExplicitScopes
on finalScope; keep the validateExplicitScopes call (and assignment to
finalScope) only after the mutex check passes so
validateExplicitScopes(finalScope, "user") is not invoked when the request will
be rejected. Ensure you reference finalScope, opts.Scope, selectedDomains,
opts.Recommend, validateExplicitScopes, and output.ErrValidation in the change.

---

Nitpick comments:
In `@cmd/auth/login.go`:
- Around line 541-558: The code appends invalid scope tokens to invalid without
deduplication, causing repeated entries; update the loop that iterates over
normalized (using normalized, knownScopes, invalid, seen, result) to skip adding
an invalid token if it's already recorded (either reuse the existing seen map
for invalids or add a separate seenInvalid map) so invalid contains only unique
scope names before the ErrValidation call; keep the rest of the error formatting
the same.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b0f19f65-c8bb-4a3d-bc39-0de774a6e2be

📥 Commits

Reviewing files that changed from the base of the PR and between 74f7de3 and a74b59f.

📒 Files selected for processing (2)
  • cmd/auth/login.go
  • cmd/auth/login_test.go

@JackZhao10086
Copy link
Copy Markdown
Collaborator

please check UT

@github-actions
Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add lttlin/cli#fix/416-auth-scope-validation -y -g

Copy link
Copy Markdown
Collaborator

@JackZhao10086 JackZhao10086 left a comment

Choose a reason for hiding this comment

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

please check UT

@JackZhao10086 JackZhao10086 self-assigned this Apr 17, 2026
@JackZhao10086 JackZhao10086 added the domain/auth Authentication subsystem label Apr 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/auth Authentication subsystem 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