Skip to content

feat: remote scopes.json for login and status_message passthrough#1799

Draft
dc-bytedance wants to merge 6 commits into
mainfrom
feat/optimize-auth-permission-strategy
Draft

feat: remote scopes.json for login and status_message passthrough#1799
dc-bytedance wants to merge 6 commits into
mainfrom
feat/optimize-auth-permission-strategy

Conversation

@dc-bytedance

@dc-bytedance dc-bytedance commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

auth login previously computed its recommended authorization scopes from a compiled-in local table, so different CLI versions could request different scope sets and drift from the platform's own scope computation. This PR (1) switches the scope source to a remotely published per-brand scopes.json fetched at login time (~1s timeout, whole-file validation, silent fallback to the local computation on any failure), (2) removes the terminal interactive domain-selection page and the local auto-approve filter chain so --recommend is equivalent to --domain all, and (3) passes the authorization response's status_message through to the login result, so the server-rendered outcome text replaces the locally synthesized scope-breakdown text.

Changes

  • Add internal/auth/remote_scopes.go: brand-addressed GET with ~1s timeout and whole-file validation — a valid file is used verbatim (including domains/scopes unknown to this CLI build); any failure (non-2xx, empty body, bad JSON, missing/empty scopes, a domain missing user_scopes, or a malformed scope string: fewer than two :-separated segments, an empty segment, or characters outside [a-z0-9_.]) falls back silently to the local computation
  • cmd/auth/login.go: fetch remote scopes once per login and use them for domain validation, --domain all / bare-login / --recommend expansion, and per-domain scope selection; the --scope-only path never touches the catalog
  • Remove cmd/auth/login_interactive.go, the auto-approve loader chain in internal/registry/loader.go, and the service-description getters orphaned by the interactive-page removal
  • internal/auth/device_flow.go: read status_message from the token success response into DeviceFlowTokenData
  • cmd/auth/login_result.go + cmd/auth/login_messages.go: rework the login result into a granted / not-granted breakdown; a server-provided status_message is rendered verbatim (no parsing, no truncation) in place of the locally synthesized not-granted text, and the JSON warning payload now carries it in hint
  • Behavior changes (release-notes relevant): bare auth login in a non-TTY environment no longer fails fast — it initiates full-domain authorization and blocks up to ~10 minutes awaiting authorization (agent harnesses should use --no-wait); --recommend now requests the full domain scope set rather than the former auto-approve subset (the authorization page still shows every requested scope); the JSON warning payload no longer includes message — breaking for consumers reading .warning.message (the requested/granted/missing scope lists are unchanged)

Test Plan

  • make unit-test passed (CI green at head 3867fa0, confirmed by a local full run)
  • validate passed
  • local-eval passed (E2E 5/5, skillave N/A) — run against the remote-scopes changes (through 654ded6)
  • skipped: E2E/acceptance rerun for the status_message commits — requires a live authorization response carrying status_message; covered by unit tests in internal/auth/device_flow_test.go and cmd/auth/login_test.go
  • acceptance-reviewer passed (remote-scopes scope, through 654ded6)
  • manual verification: fetched the production scopes.json for both brands; whole-file validation accepts them; per-domain diff against the local synthesis — 20/21 domains identical

Related Issues

N/A

@dc-bytedance
dc-bytedance requested a review from liangshuo-1 as a code owner July 8, 2026 08:13
@github-actions github-actions Bot added the size/XL Architecture-level or global-impact change label Jul 8, 2026
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 42b7ddf6-fa70-4d69-95e6-1d22659b69ef

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

auth login now uses explicit or default domain scope resolution backed by validated remote scope data, removes interactive selection, and updates login messages. Registry auto-approve caching and service description helpers are consolidated, with corresponding tests updated.

Changes

Auth login scope resolution and messaging

Layer / File(s) Summary
Remote scopes fetch and validation
internal/auth/remote_scopes.go, internal/auth/remote_scopes_test.go
Adds brand-specific scopes.json retrieval, response limits, timeout handling, strict validation, and HTTP scenario tests.
Login domain and scope resolution
cmd/auth/login.go, cmd/auth/login_test.go
Removes interactive option handling, adds remote-aware legal-domain validation, supports --domain all, and resolves deduplicated sorted scopes with local fallback.
Interactive login messages removed
cmd/auth/login_interactive.go, cmd/auth/login_messages.go, cmd/auth/login_messages_test.go
Deletes the interactive login flow and selection-related message fields, and updates remaining message assertions.

Registry helper consolidation

Layer / File(s) Summary
Auto-approve cache consolidation
internal/registry/loader.go, internal/registry/registry_test.go, internal/registry/remote_test.go
Unifies auto-approve caches, removes obsolete exported helpers and tests, updates cache reset logic, and adds required-scope coverage.
Service description helper
internal/registry/service_desc.go
Keeps localized description lookup and removes title and detail-description helpers.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant authLoginRun
  participant FetchRemoteScopes
  participant ScopesEndpoint
  participant resolveScopesForDomains
  authLoginRun->>FetchRemoteScopes: fetch brand-specific scopes.json
  FetchRemoteScopes->>ScopesEndpoint: HTTP GET
  ScopesEndpoint-->>FetchRemoteScopes: validated domain scope map
  FetchRemoteScopes-->>authLoginRun: remote data or local fallback
  authLoginRun->>resolveScopesForDomains: resolve selected legal domains
  resolveScopesForDomains-->>authLoginRun: deduplicated sorted scopes
Loading

Possibly related PRs

Suggested labels: domain/base

Suggested reviewers: liangshuo-1, evandance, albertnusouo

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.67% 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
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.
Title check ✅ Passed The title is concise and accurately highlights the remote scopes.json login change and status_message passthrough.
Description check ✅ Passed The description follows the required template and includes a solid summary, changes list, test plan, and related issues section.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/optimize-auth-permission-strategy

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.

@codecov

codecov Bot commented Jul 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.57554% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.06%. Comparing base (6ff1022) to head (b2da915).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
cmd/auth/login.go 60.00% 18 Missing and 2 partials ⚠️
cmd/auth/login_result.go 88.37% 2 Missing and 3 partials ⚠️
internal/auth/remote_scopes.go 95.55% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1799      +/-   ##
==========================================
+ Coverage   74.98%   75.06%   +0.08%     
==========================================
  Files         895      895              
  Lines       94379    94284      -95     
==========================================
+ Hits        70767    70776       +9     
+ Misses      18197    18091     -106     
- Partials     5415     5417       +2     

☔ View full report in Codecov by Harness.
📢 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

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/optimize-auth-permission-strategy -y -g

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)

595-613: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add direct tests for legalDomainsFor The existing resolveScopesForDomains coverage doesn’t exercise this wrapper’s remote-key extraction/sort or the local fallback; add a minimal test for each branch.

🤖 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 595 - 613, Add direct unit tests for
legalDomainsFor to cover both branches explicitly, since resolveScopesForDomains
does not verify this wrapper’s behavior. Create one test with remoteOK true that
asserts the returned membership set uses the remote map keys and the slice is
sorted, and another with remoteOK false that asserts it falls back to
allKnownDomains and sortedKnownDomains for the given core.LarkBrand. Keep the
tests focused on the legalDomainsFor symbol so the remote-key extraction,
sorting, and local fallback are all exercised directly.

Source: Coding guidelines

🤖 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 595-613: Add direct unit tests for legalDomainsFor to cover both
branches explicitly, since resolveScopesForDomains does not verify this
wrapper’s behavior. Create one test with remoteOK true that asserts the returned
membership set uses the remote map keys and the slice is sorted, and another
with remoteOK false that asserts it falls back to allKnownDomains and
sortedKnownDomains for the given core.LarkBrand. Keep the tests focused on the
legalDomainsFor symbol so the remote-key extraction, sorting, and local fallback
are all exercised directly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 307cabaa-5785-49ad-aedc-d99271e3de15

📥 Commits

Reviewing files that changed from the base of the PR and between 9413e7c and 20c2a2d.

📒 Files selected for processing (14)
  • cmd/auth/login.go
  • cmd/auth/login_interactive.go
  • cmd/auth/login_messages.go
  • cmd/auth/login_messages_test.go
  • cmd/auth/login_result.go
  • cmd/auth/login_result_test.go
  • cmd/auth/login_test.go
  • internal/auth/device_flow.go
  • internal/auth/device_flow_test.go
  • internal/auth/remote_scopes.go
  • internal/auth/remote_scopes_test.go
  • internal/registry/loader.go
  • internal/registry/registry_test.go
  • internal/registry/remote_test.go
💤 Files with no reviewable changes (5)
  • cmd/auth/login_interactive.go
  • internal/registry/loader.go
  • cmd/auth/login_messages.go
  • internal/registry/registry_test.go
  • internal/registry/remote_test.go

@dc-bytedance
dc-bytedance force-pushed the feat/optimize-auth-permission-strategy branch 2 times, most recently from 05f4098 to 4f483b1 Compare July 14, 2026 07:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)

174-196: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Validate user-provided domains before expanding --domain all.

Because the --domain all expansion replaces selectedDomains with allLegalDomains before validation occurs, the validation loop unintentionally runs against the expanded set rather than the original user input. As a result, explicitly invalid domains are silently ignored if "all" is also present in the flag (e.g., --domain docs,invalid,all).

Validate the original user input first, skipping "all", and perform the expansion afterward.

🐛 Proposed fix to reorder validation and expansion
-		// Expand --domain all against the resolved legal domain set.
-		for _, d := range selectedDomains {
-			if strings.EqualFold(d, "all") {
-				selectedDomains = allLegalDomains
-				break
-			}
-		}
-
 		if len(selectedDomains) > 0 {
 			// Validate explicitly-supplied domain names and suggest corrections.
 			for _, d := range selectedDomains {
+				if strings.EqualFold(d, "all") {
+					continue
+				}
 				if !legalDomains[d] {
 					if suggestion := suggestDomain(d, legalDomains); suggestion != "" {
 						return errs.NewValidationError(errs.SubtypeInvalidArgument, "unknown domain %q, did you mean %q?", d, suggestion).WithParam("--domain")
 					}
 					available := make([]string, 0, len(legalDomains))
 					for k := range legalDomains {
 						available = append(available, k)
 					}
 					sort.Strings(available)
 					return errs.NewValidationError(errs.SubtypeInvalidArgument, "unknown domain %q, available domains: %s", d, strings.Join(available, ", ")).WithParam("--domain")
 				}
 			}
+
+			// Expand --domain all against the resolved legal domain set.
+			for _, d := range selectedDomains {
+				if strings.EqualFold(d, "all") {
+					selectedDomains = allLegalDomains
+					break
+				}
+			}
 		} else {
🤖 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 174 - 196, In the domain-selection flow,
validate the original selectedDomains user input before expanding any "all"
entry, skipping validation for the literal "all" while preserving the existing
suggestion and available-domain errors for other values. Move the
allLegalDomains replacement and break logic to run only after this validation
completes.
🧹 Nitpick comments (2)
cmd/auth/login_test.go (1)

1159-1159: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a valid brand constant for robust test execution.

Passing an empty string "" for core.LarkBrand bypasses realistic shortcut filtering since shortcuts.IsShortcutServiceAvailable expects and checks against known brand constants. Use a valid constant like core.BrandFeishu instead to ensure test accuracy.

  • cmd/auth/login_test.go#L1159-L1159: replace "" with core.BrandFeishu in the allKnownDomains call.
  • cmd/auth/login_test.go#L1169-L1169: replace "" with core.BrandFeishu in the collectScopesForDomains call.
🤖 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_test.go` at line 1159, Use the valid core.BrandFeishu constant
instead of an empty string for the brand argument in allKnownDomains and
collectScopesForDomains in cmd/auth/login_test.go at lines 1159 and 1169.
cmd/auth/login.go (1)

611-611: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Avoid computing allKnownDomains twice on the fallback path.

sortedKnownDomains(brand) internally calls allKnownDomains(brand). Calling them both here iterates the project and shortcut registries twice. Since legalDomainsFor needs both the map and the sorted slice, you can compute them both in a single pass.

♻️ Proposed refactor
-	return allKnownDomains(brand), sortedKnownDomains(brand)
+	m := allKnownDomains(brand)
+	sorted := make([]string, 0, len(m))
+	for d := range m {
+		sorted = append(sorted, d)
+	}
+	sort.Strings(sorted)
+	return m, sorted
🤖 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` at line 611, Update the fallback return in legalDomainsFor
to avoid invoking allKnownDomains through both return expressions: compute the
known-domain map once, derive the sorted domain slice from that map, and return
both values while preserving the existing ordering.
🤖 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/auth/login.go`:
- Around line 174-196: In the domain-selection flow, validate the original
selectedDomains user input before expanding any "all" entry, skipping validation
for the literal "all" while preserving the existing suggestion and
available-domain errors for other values. Move the allLegalDomains replacement
and break logic to run only after this validation completes.

---

Nitpick comments:
In `@cmd/auth/login_test.go`:
- Line 1159: Use the valid core.BrandFeishu constant instead of an empty string
for the brand argument in allKnownDomains and collectScopesForDomains in
cmd/auth/login_test.go at lines 1159 and 1169.

In `@cmd/auth/login.go`:
- Line 611: Update the fallback return in legalDomainsFor to avoid invoking
allKnownDomains through both return expressions: compute the known-domain map
once, derive the sorted domain slice from that map, and return both values while
preserving the existing ordering.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3e4da44b-ac4d-4021-9075-46fe2dfec006

📥 Commits

Reviewing files that changed from the base of the PR and between 05f4098 and 4f483b1.

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

@dc-bytedance
dc-bytedance force-pushed the feat/optimize-auth-permission-strategy branch 4 times, most recently from 2782221 to aece091 Compare July 15, 2026 03:57
@dc-bytedance
dc-bytedance marked this pull request as draft July 16, 2026 03:48
@dc-bytedance dc-bytedance changed the title feat: use remote scopes.json for login scope recommendations feat: remote scopes.json for login and status_message passthrough Jul 16, 2026
@JackZhao10086
JackZhao10086 force-pushed the feat/optimize-auth-permission-strategy branch from 3867fa0 to 00fa3e3 Compare July 16, 2026 07:53
Comment thread cmd/auth/login_result.go Outdated
Comment thread cmd/auth/login_result.go
@github-actions

Copy link
Copy Markdown

PR Quality Summary

CI did not complete successfully. Use the failed check links below to decide whether this PR needs a code change or a rerun.

Failed checks

dc-bytedance and others added 6 commits July 20, 2026 14:34
Switch auth login's recommended-permission source from the compiled-in
local table to a scopes.json fetched from the platform at login time.

- add internal/auth/remote_scopes.go: brand-addressed GET with a ~1s
  timeout and whole-file (binary) validation; scopes are used verbatim
  when the file is valid, and any fetch/parse/format failure falls back
  silently to the existing local computation
- login.go: fetch remote scopes once per login and use them for domain
  validation, all-expansion, and per-domain scope selection; drop the
  terminal interactive page and the local auto-approve filter chain, so
  --recommend is now equivalent to --domain all
- remove login_interactive.go and the service-description getters left
  orphaned by the interactive-page removal
- keep the three entry flags (bare login / --recommend / --domain all)
  as an equivalent transitional surface
@dc-bytedance
dc-bytedance force-pushed the feat/optimize-auth-permission-strategy branch from 05d64e2 to b2da915 Compare July 20, 2026 06:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature size/XL Architecture-level or global-impact change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants