Skip to content

feat: restore client-secret app credentials - #2322

Open
albertnusouo wants to merge 1 commit into
mainfrom
feat/app-credential-restore
Open

feat: restore client-secret app credentials#2322
albertnusouo wants to merge 1 commit into
mainfrom
feat/app-credential-restore

Conversation

@albertnusouo

@albertnusouo albertnusouo commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

Summary

When the locally stored client secret can no longer be read, users need a way to re-register the same application instead of creating a new one. This PR adds config init --restore, which uses the App ID and brand from the selected existing profile and writes back the newly issued client secret.

Changes

  • Add the --restore mode and local flag conflict validation in cmd/config/init.go and cmd/config/init_restore.go
  • Select the existing app through the global --profile context, send its App ID in the app-registration begin form, and reuse the existing poll flow unchanged
  • Accept restored credentials only when the returned client ID matches the configured App ID, then update only that profile's secret and resolved brand
  • Add two focused end-to-end tests for successful profile restoration and mismatched App ID rejection

Test Plan

  • make unit-test passed
  • validate passed (go vet ./..., gofmt -l ., go mod tidy, golangci-lint, and repository lint checks)
  • skipped: local-eval is not applicable because this PR changes no shortcut or skill surface
  • skipped: live manual restore requires an existing application registration session; the begin, poll, Keychain, config, output, and mismatch paths are covered by deterministic tests

Related Issues

N/A

Summary by CodeRabbit

  • New Features

    • Added a --restore option to restore an existing app configuration.
    • Restore mode recreates credentials for the selected app, securely saves them, updates configuration, and verifies connectivity.
    • New app registration can preserve and submit an existing app ID when applicable.
  • Bug Fixes

    • Prevented mismatched app IDs from being saved during restoration.
    • Improved validation and error handling for incomplete or invalid restore settings.

@github-actions github-actions Bot added the size/XL Architecture-level or global-impact change label Aug 12, 2026
@codecov

codecov Bot commented Aug 12, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 56.60377% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.46%. Comparing base (1e87f67) to head (e919dc0).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
cmd/config/init_restore.go 55.88% 9 Missing and 6 partials ⚠️
cmd/config/init.go 54.54% 3 Missing and 2 partials ⚠️
cmd/config/init_interactive.go 40.00% 2 Missing and 1 partial ⚠️

❌ Your patch check has failed because the patch coverage (56.60%) is below the target coverage (60.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2322      +/-   ##
==========================================
+ Coverage   76.44%   76.46%   +0.01%     
==========================================
  Files        1025     1026       +1     
  Lines      113704   113766      +62     
==========================================
+ Hits        86921    86990      +69     
+ Misses      20111    20091      -20     
- Partials     6672     6685      +13     

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

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The CLI adds config init --restore for existing apps. It validates flag combinations, re-registers the selected app, stores returned credentials, updates configuration, probes the app, and adds restore-aware registration tests.

Changes

Configuration app restoration

Layer / File(s) Summary
Restore-aware registration contract
internal/auth/app_registration.go, internal/auth/app_registration_test.go
RequestAppRegistration accepts an optional app ID and sends it in the begin request. Tests cover restore and new-app registration paths.
Restore command entry
cmd/config/init.go, cmd/config/init_interactive.go, cmd/config/init_restore.go
config init exposes restore mode, validates incompatible flags, bypasses interactive initialization, and passes an optional app ID through registration.
Restore persistence and validation
cmd/config/init_restore.go, cmd/config/init_restore_test.go
Restore validates the returned app ID, persists the secret and brand, saves configuration, emits masked output, probes the app, and tests success and mismatch failures.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant ConfigInit
  participant RestoreFlow
  participant AppRegistration
  participant Keychain
  participant ConfigStore
  participant AppProbe
  User->>ConfigInit: run config init --restore
  ConfigInit->>RestoreFlow: selected profile and app ID
  RestoreFlow->>AppRegistration: request credentials for app ID
  AppRegistration-->>RestoreFlow: restored credentials and brand
  RestoreFlow->>Keychain: store app secret
  RestoreFlow->>ConfigStore: save profile configuration
  RestoreFlow->>AppProbe: probe restored app
  AppProbe-->>User: restore result
Loading

Suggested reviewers: liangshuo-1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.41% 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 concisely describes the main change: restoring client-secret credentials for an existing application.
Description check ✅ Passed The description includes the required summary, changes, test plan, and related-issues sections with relevant implementation and verification details.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/app-credential-restore

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.

@github-actions

github-actions Bot commented Aug 12, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/app-credential-restore -y -g

@github-actions

github-actions Bot commented Aug 12, 2026

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

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
cmd/config/init_restore_test.go (1)

836-848: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add defer cancel() for the cancellable context.

Line 836 creates ctx, cancel and only calls cancel inside the transport closure. If the transport is never reached, the context leaks and go vet's lostcancel check can report the unused cancel path. Other tests in this file use defer cancel().

🛠️ Proposed fix
 			ctx, cancel := context.WithCancel(context.Background())
+			defer cancel()
 			var beginAppID string
🤖 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/config/init_restore_test.go` around lines 836 - 848, Add defer cancel()
immediately after creating the cancellable context in the test setup, while
retaining the existing cancel() call in the restoreRoundTripFunc closure. Update
the context initialization around ctx and cancel so every execution path
releases the context.
internal/auth/app_registration.go (1)

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

Reuse the validated userCode in the returned struct.

Line 164 validates userCode. Line 172 calls getStr(data, "user_code") again for the returned UserCode field. The two values are equal today, so behavior is correct. Reusing the local variable keeps the validated value as the single source for the response and prevents a future edit from returning an unvalidated string.

♻️ Proposed refactor
 	return &AppRegistrationResponse{
 		DeviceCode:              deviceCode,
-		UserCode:                getStr(data, "user_code"),
+		UserCode:                userCode,
 		VerificationUri:         verificationUri,
🤖 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 `@internal/auth/app_registration.go` around lines 163 - 172, Reuse the
validated userCode variable when assigning the UserCode field in the
AppRegistrationResponse returned by the registration flow, instead of calling
getStr again; leave the existing validation and other response fields unchanged.
cmd/config/init.go (1)

363-371: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for the relocated --name validation.

validateRestoreFlags runs first, so --restore with --name fails before this block. That ordering is correct. Codecov reports lines 367-369 as uncovered, and TestConfigInit_NameStillAcceptedForOrdinaryInit uses a runF override, so it never reaches configInitRun. Add one case that calls configInitRun with an invalid ProfileName and asserts errs.SubtypeInvalidArgument with Param == "--name".

🤖 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/config/init.go` around lines 363 - 371, Add a test that invokes
configInitRun directly with an invalid ProfileName during ordinary
initialization, without the runF override. Assert the returned validation error
has errs.SubtypeInvalidArgument and Param equal to "--name", covering the
core.ValidateProfileName failure path while preserving the existing restore-flag
ordering.

Source: Linters/SAST tools

🤖 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/config/init_restore_test.go`:
- Around line 1043-1052: Isolate configuration for both Factory-backed tests in
cmd/config/init_restore_test.go: at lines 1043-1052, create a temp config
directory and set LARKSUITE_CLI_CONFIG_DIR for every subtest, while writing
config.json only for malformedConfig cases; at lines 783-790, set
LARKSUITE_CLI_CONFIG_DIR to t.TempDir() before cmdutil.TestFactory(t, nil).

---

Nitpick comments:
In `@cmd/config/init_restore_test.go`:
- Around line 836-848: Add defer cancel() immediately after creating the
cancellable context in the test setup, while retaining the existing cancel()
call in the restoreRoundTripFunc closure. Update the context initialization
around ctx and cancel so every execution path releases the context.

In `@cmd/config/init.go`:
- Around line 363-371: Add a test that invokes configInitRun directly with an
invalid ProfileName during ordinary initialization, without the runF override.
Assert the returned validation error has errs.SubtypeInvalidArgument and Param
equal to "--name", covering the core.ValidateProfileName failure path while
preserving the existing restore-flag ordering.

In `@internal/auth/app_registration.go`:
- Around line 163-172: Reuse the validated userCode variable when assigning the
UserCode field in the AppRegistrationResponse returned by the registration flow,
instead of calling getStr again; leave the existing validation and other
response fields unchanged.
🪄 Autofix

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 Plus

Run ID: 65ee6cd5-c298-4e0c-bc24-8085eff3291b

📥 Commits

Reviewing files that changed from the base of the PR and between f98db39 and 58b8a76.

📒 Files selected for processing (10)
  • cmd/config/config_test.go
  • cmd/config/init.go
  • cmd/config/init_interactive.go
  • cmd/config/init_interactive_test.go
  • cmd/config/init_restore.go
  • cmd/config/init_restore_test.go
  • internal/auth/app_registration.go
  • internal/auth/app_registration_test.go
  • internal/recovery/context.go
  • internal/recovery/hint_test.go

Comment thread cmd/config/init_restore_test.go Outdated
@albertnusouo
albertnusouo force-pushed the feat/app-credential-restore branch from 58b8a76 to e919dc0 Compare August 12, 2026 15:26
@github-actions github-actions Bot added size/L Large or sensitive change across domains or core paths and removed size/XL Architecture-level or global-impact change labels Aug 12, 2026

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

Actionable comments posted: 2

🤖 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/config/init_restore.go`:
- Around line 65-68: Update the restore success output in
cmd/config/init_restore.go lines 65-68 to use msg.ConfigSaved or a
restore-specific message instead of msg.AppCreated. In
cmd/config/init_restore_test.go lines 102-108, capture stderr from
cmdutil.TestFactory and assert that it contains the restore success message and
does not report application creation.

In `@internal/auth/app_registration_test.go`:
- Around line 87-89: The test currently checks only the value of app_id, so it
cannot distinguish an omitted field from an explicitly empty one. Update the
relevant app-registration request assertions to check map-key presence directly:
require app_id to exist for restore requests and require the key to be absent
for normal requests, while preserving the existing value assertion where
applicable.
🪄 Autofix

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 Plus

Run ID: d83bbf1e-333f-4466-80d7-33e5615ebeae

📥 Commits

Reviewing files that changed from the base of the PR and between 58b8a76 and e919dc0.

📒 Files selected for processing (6)
  • cmd/config/init.go
  • cmd/config/init_interactive.go
  • cmd/config/init_restore.go
  • cmd/config/init_restore_test.go
  • internal/auth/app_registration.go
  • internal/auth/app_registration_test.go

Comment on lines +65 to +68
output.PrintSuccess(f.IOStreams.ErrOut, fmt.Sprintf(msg.AppCreated, app.AppId))
output.PrintJson(f.IOStreams.Out, map[string]interface{}{
"appId": app.AppId, "appSecret": "****", "brand": app.Brand,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Report restore success instead of app creation.

The restore path updates an existing application. msg.AppCreated reports the wrong operation. Use msg.ConfigSaved or add a restore-specific message. Capture stderr in the success test and assert that it does not report application creation.

  • cmd/config/init_restore.go#L65-L68: replace msg.AppCreated with a restore-appropriate success message.
  • cmd/config/init_restore_test.go#L102-L108: capture stderr from cmdutil.TestFactory and assert the restore success message.

As per coding guidelines: “Preserve established CLI behavior, tests, lint, CI, output contracts, and public APIs unless a breaking change is explicitly requested.”

📍 Affects 2 files
  • cmd/config/init_restore.go#L65-L68 (this comment)
  • cmd/config/init_restore_test.go#L102-L108
🤖 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/config/init_restore.go` around lines 65 - 68, Update the restore success
output in cmd/config/init_restore.go lines 65-68 to use msg.ConfigSaved or a
restore-specific message instead of msg.AppCreated. In
cmd/config/init_restore_test.go lines 102-108, capture stderr from
cmdutil.TestFactory and assert that it contains the restore success message and
does not report application creation.

Source: Coding guidelines

Comment on lines +87 to +89
if got := r.Form.Get("app_id"); got != c.appID {
t.Errorf("begin app_id = %q, want %q", got, c.appID)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert that normal requests omit app_id.

r.Form.Get("app_id") returns "" for both an absent field and app_id=. The test passes if RequestAppRegistration always sends an empty app_id field. Assert map-key presence for restore requests and absence for normal requests.

Proposed test change
-				if got := r.Form.Get("app_id"); got != c.appID {
+				_, present := r.Form["app_id"]
+				if want := c.appID != ""; present != want {
+					t.Errorf("begin app_id present = %t, want %t", present, want)
+				}
+				if got := r.Form.Get("app_id"); got != c.appID {
 					t.Errorf("begin app_id = %q, want %q", got, c.appID)
 				}

As per coding guidelines: “Every behavior change requires a nearby regression test that fails when the implementation is reverted; tests should assert fields, requests, typed errors, or side effects directly.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if got := r.Form.Get("app_id"); got != c.appID {
t.Errorf("begin app_id = %q, want %q", got, c.appID)
}
_, present := r.Form["app_id"]
if want := c.appID != ""; present != want {
t.Errorf("begin app_id present = %t, want %t", present, want)
}
if got := r.Form.Get("app_id"); got != c.appID {
t.Errorf("begin app_id = %q, want %q", got, c.appID)
}
🤖 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 `@internal/auth/app_registration_test.go` around lines 87 - 89, The test
currently checks only the value of app_id, so it cannot distinguish an omitted
field from an explicitly empty one. Update the relevant app-registration request
assertions to check map-key presence directly: require app_id to exist for
restore requests and require the key to be absent for normal requests, while
preserving the existing value assertion where applicable.

Source: Coding guidelines

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

Labels

feature 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