Skip to content

feat(auth): support --exclude flag and combine --scope with --domain/…#844

Open
JackZhao10086 wants to merge 4 commits into
larksuite:mainfrom
cqc-a11y:feat/auth-login-exclude-and-combine-scopes
Open

feat(auth): support --exclude flag and combine --scope with --domain/…#844
JackZhao10086 wants to merge 4 commits into
larksuite:mainfrom
cqc-a11y:feat/auth-login-exclude-and-combine-scopes

Conversation

@JackZhao10086
Copy link
Copy Markdown
Collaborator

@JackZhao10086 JackZhao10086 commented May 12, 2026

…--recommend in auth login

  • Add --exclude flag to remove specific scopes from the requested set, with structured ErrValidation when an excluded scope is unknown or when exclusion empties the entire set.
  • Allow --scope to be combined additively with --domain / --recommend instead of erroring out, deduplicating into a deterministic sorted scope string.
  • Cover new behavior with unit tests in cmd/auth/login_test.go, including device-authorization request body assertions via httpmock.

Fixes #766

Summary by CodeRabbit

  • New Features

    • auth login adds an --exclude flag to omit specific scopes; scope sources (--scope, --domain, --recommend) now combine additively into the final scope set.
    • --exclude is treated as a valid non-interactive option to avoid triggering prompts when it’s the only flag.
  • Bug Fixes

    • Validation now errors if exclusions remove all requested scopes or reference scopes not present.

Review Change Stack

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 12, 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
📝 Walkthrough

Walkthrough

Adds an --exclude flag to auth login, merges domain/recommend-derived scopes additively with --scope, deterministically joins scope sets, applies exclusions (with validation), and treats --exclude as a selecting option to avoid interactive prompts when used alone.

Changes

Auth Login: scope merging and --exclude

Layer / File(s) Summary
CLI flag and LoginOptions
cmd/auth/login.go
Adds Exclude []string to LoginOptions and registers a repeatable/comma-separated --exclude flag bound to opts.Exclude.
Option selection detection
cmd/auth/login.go
Considers --exclude when determining whether any option was provided (prevents interactive flow when only --exclude is set).
Resolve domain/recommend scopes
cmd/auth/login.go
Resolve candidate scopes for --domain/--recommend without rejecting presence of --scope, enabling additive combination.
Merge scopes and apply excludes
cmd/auth/login.go
Merge resolved candidate scopes and explicit --scope into a deterministic space-delimited string, parse and subtract --exclude values (validating unknown exclusions), and error if no scopes remain. Helpers joinSortedScopeSet and applyExcludeScopes are added.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • larksuite/cli#764: Both PRs modify cmd/auth/login.go’s auth login scope handling by changing how scope strings are parsed/combined.
  • larksuite/cli#317: Modifies cmd/auth/login.go scope handling and requested/granted scope reconciliation.

Suggested reviewers

  • albertnusouo
  • yux1a0-63

Poem

🐰 I hopped into login with a flag to exclude,
pulling scopes apart like leaves from a sprig.
Combine domain, scope, and recommend in line,
then nibble the bits you don't want to bind.
🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% 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 describes the main changes: adding --exclude flag and enabling scope combination with --domain/--recommend.
Description check ✅ Passed The description covers key changes, test plan confirmation, and links the related issue (#766), aligning with the template structure.
Linked Issues check ✅ Passed All main objectives from #766 are met: --exclude flag added, --scope combined with --domain/--recommend, scopes deduplicated/sorted, backward compatibility preserved, and unit tests added.
Out of Scope Changes check ✅ Passed All changes are directly related to the --exclude flag feature and scope combination requirements specified in #766; no unrelated modifications detected.

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

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

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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 May 12, 2026
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)
cmd/auth/login.go (1)

226-240: 💤 Low value

Consider simplifying the empty-scope check.

Line 237 uses strings.TrimSpace(finalScope) before the empty check, but joinSortedScopeSet (called on line 236) already filters blank scopes, so finalScope can only be "" or a non-blank string—never " ". The TrimSpace is defensive but unnecessary.

Optional simplification
-		if strings.TrimSpace(finalScope) == "" {
+		if finalScope == "" {
🤖 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/auth/login.go` around lines 226 - 240, The empty-scope check after
applying excludes is overly defensive: since joinSortedScopeSet (used to produce
finalScope) already filters blank entries, finalScope will be either "" or a
non-blank string, so replace the strings.TrimSpace(finalScope) == "" check with
a direct finalScope == "" comparison in the block that handles
applyExcludeScopes/finalScope; update the conditional that returns
ErrValidation("no scopes left after applying --exclude; nothing to authorize")
to use finalScope == "" and remove the unnecessary TrimSpace call.
🤖 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.

Nitpick comments:
In `@cmd/auth/login.go`:
- Around line 226-240: The empty-scope check after applying excludes is overly
defensive: since joinSortedScopeSet (used to produce finalScope) already filters
blank entries, finalScope will be either "" or a non-blank string, so replace
the strings.TrimSpace(finalScope) == "" check with a direct finalScope == ""
comparison in the block that handles applyExcludeScopes/finalScope; update the
conditional that returns ErrValidation("no scopes left after applying --exclude;
nothing to authorize") to use finalScope == "" and remove the unnecessary
TrimSpace call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 071ff8f1-7690-4a8d-890d-08b7a5fe3884

📥 Commits

Reviewing files that changed from the base of the PR and between 1180baa and 03de1cc.

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

@codecov
Copy link
Copy Markdown

codecov Bot commented May 12, 2026

Codecov Report

❌ Patch coverage is 97.91667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 65.90%. Comparing base (db1a3fc) to head (03de1cc).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cmd/auth/login.go 97.91% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #844      +/-   ##
==========================================
+ Coverage   65.77%   65.90%   +0.13%     
==========================================
  Files         516      517       +1     
  Lines       48625    48803     +178     
==========================================
+ Hits        31985    32166     +181     
+ Misses      13881    13872       -9     
- Partials     2759     2765       +6     

☔ 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@03de1cc7c58fecc31f5589c2b2527e1041204fff

🧩 Skill update

npx skills add cqc-a11y/cli#feat/auth-login-exclude-and-combine-scopes -y -g

@JackZhao10086 JackZhao10086 added the domain/auth Authentication subsystem label May 13, 2026
当使用--exclude参数时,必须同时指定--scope、--domain或--recommend中的至少一个,避免非法参数调用
@cqc-a11y cqc-a11y force-pushed the feat/auth-login-exclude-and-combine-scopes branch from a0ad3d2 to 9a89aa0 Compare May 13, 2026 12:09
@github-actions github-actions Bot removed the domain/auth Authentication subsystem label May 13, 2026
1. 新增--exclude命令行标志用于排除指定的授权范围
2. 移除--scope与--domain/--recommend的互斥限制,改为叠加使用
3. 重构范围合并与排除逻辑,增加校验和辅助工具函数
4. 更新--scope参数的帮助文档说明叠加行为
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

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

Inline comments:
In `@cmd/auth/login.go`:
- Around line 161-164: The code references opts.Exclude in the validation but
LoginOptions doesn't define an Exclude field and the flag isn't registered; add
a new field Exclude []string to the LoginOptions struct and register the CLI
flag in NewCmdAuthLogin by calling cmd.Flags().StringSliceVar(&opts.Exclude,
"exclude", nil, "scopes to exclude (repeatable or comma-separated)"), ensuring
the flag name and option variable match the existing validation that checks
opts.Exclude.
🪄 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: ea7ce13d-ddd9-4e24-86f5-fd250d94d2e9

📥 Commits

Reviewing files that changed from the base of the PR and between a0ad3d2 and 9a89aa0.

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

Comment thread cmd/auth/login.go Outdated
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: 4

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

Inline comments:
In `@cmd/auth/login.go`:
- Around line 624-663: applyExcludeScopes currently treats every exclude entry
as a literal and flags patterns like "drive:*" as unknown; update it to
recognize wildcard/pattern excludes (e.g., "*" or "prefix:*" or other simple
glob-like patterns) by splitting excludes into literal entries and pattern
entries, using pattern matching (e.g., strings.HasPrefix for "prefix:*" or
path.Match/regexp for general globs) when computing unknown and when filtering
requestedSet; change the unknown-detection loop to consider a pattern as known
if it matches at least one requested scope, and change the final filtering to
remove any requested scope that matches any exclude pattern or literal (keep
joinSortedScopeSet, requestedSet, excludeSet, and the applyExcludeScopes
signature intact).
- Around line 162-163: The code treats opts.Exclude as a "present option" via
hasAnyOption, which allows `--exclude` alone to bypass the no-option path and
later causes unknown-exclude errors; change the logic so that hasAnyOption
ignores opts.Exclude (i.e., only consider opts.Scope, opts.Recommend, and
selectedDomains) and/or add an explicit validation: if len(opts.Exclude) > 0 and
none of opts.Scope, opts.Recommend, or selectedDomains are set, return an error
rejecting `--exclude` without a base selector. Update the checks that use
hasAnyOption and the validation around excludes (references: hasAnyOption,
opts.Exclude, opts.Scope, opts.Recommend, selectedDomains) so the
interactive/no-option path and exclude validation behave correctly.
- Around line 215-227: The merge currently adds tokens from the raw opts.Scope,
which can contain comma-normalized values and produce a single literal token;
instead merge from the normalized scope string produced earlier (not raw
opts.Scope). Update the loop that currently iterates over
strings.Fields(opts.Scope) to iterate over the normalized scope value (the
variable created by the earlier normalization step) so that merged
map[string]bool receives the correctly split scope tokens before calling
joinSortedScopeSet and assigning finalScope.
- Line 66: The help string for the "scope" flag is duplicated and malformed in
the StringVar call that sets opts.Scope (cmd.Flags().StringVar(&opts.Scope,
"scope", ...)); open that call and remove the repeated trailing text so the flag
description is a single well-formed string (e.g., "scopes to request (space- or
comma-separated). Combines additively with --domain/--recommend)"), ensuring the
call to StringVar uses a single quoted string for the help text.
🪄 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: 481d0b7e-328a-4b1a-9645-088b267a47f0

📥 Commits

Reviewing files that changed from the base of the PR and between 9a89aa0 and d558864.

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

Comment thread cmd/auth/login.go Outdated
Comment thread cmd/auth/login.go Outdated
Comment thread cmd/auth/login.go
Comment thread cmd/auth/login.go
Comment on lines +624 to +663
// applyExcludeScopes removes the provided exclude entries from the requested
// scope string. Each --exclude flag value may itself contain comma- or
// whitespace-separated scopes. Returns the filtered scope string and any
// exclude entries that were not present in the requested set (callers can
// surface those as a validation error to catch typos like
// `--exclude drive:file:downlod`).
func applyExcludeScopes(requested string, excludes []string) (string, []string) {
requestedSet := make(map[string]bool)
for _, s := range strings.Fields(requested) {
requestedSet[s] = true
}

excludeSet := make(map[string]bool)
for _, raw := range excludes {
// --exclude already splits on commas (StringSliceVar), but also
// tolerate whitespace-separated entries inside a single value.
for _, s := range strings.Fields(strings.ReplaceAll(raw, ",", " ")) {
excludeSet[s] = true
}
}

var unknown []string
for s := range excludeSet {
if !requestedSet[s] {
unknown = append(unknown, s)
}
}
if len(unknown) > 0 {
sort.Strings(unknown)
return requested, unknown
}

kept := make(map[string]bool, len(requestedSet))
for s := range requestedSet {
if !excludeSet[s] {
kept[s] = true
}
}
return joinSortedScopeSet(kept), nil
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Wildcard/pattern excludes are not implemented yet.

The linked issue says --exclude should accept wildcard/pattern entries, but this helper only does exact set membership. Inputs like --exclude drive:* will always be returned in unknown, even when the requested set contains matching drive: scopes.

🧰 Tools
🪛 GitHub Check: security

[failure] 646-646:
expected declaration, found 'for'

🤖 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/auth/login.go` around lines 624 - 663, applyExcludeScopes currently
treats every exclude entry as a literal and flags patterns like "drive:*" as
unknown; update it to recognize wildcard/pattern excludes (e.g., "*" or
"prefix:*" or other simple glob-like patterns) by splitting excludes into
literal entries and pattern entries, using pattern matching (e.g.,
strings.HasPrefix for "prefix:*" or path.Match/regexp for general globs) when
computing unknown and when filtering requestedSet; change the unknown-detection
loop to consider a pattern as known if it matches at least one requested scope,
and change the final filtering to remove any requested scope that matches any
exclude pattern or literal (keep joinSortedScopeSet, requestedSet, excludeSet,
and the applyExcludeScopes signature intact).

@JackZhao10086 JackZhao10086 requested a review from yux1a0-63 May 13, 2026 12:48
移除了重复的参数说明文本,整理冗余的注释内容,让帮助文档更清晰易读
@cqc-a11y cqc-a11y force-pushed the feat/auth-login-exclude-and-combine-scopes branch from 78297c8 to 792f3eb Compare May 13, 2026 15:57
添加--exclude参数必须配合其他可选参数使用的校验,避免无效的exclude参数调用
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.

Feature Request: Support --exclude flag in auth login to exclude specific scopes

3 participants