Skip to content

Add default CLI app keys management support in credentials#1350

Merged
PasanT9 merged 4 commits intowso2:masterfrom
manodyaSenevirathne:fix/get-keys-command
Mar 26, 2026
Merged

Add default CLI app keys management support in credentials#1350
PasanT9 merged 4 commits intowso2:masterfrom
manodyaSenevirathne:fix/get-keys-command

Conversation

@manodyaSenevirathne
Copy link
Copy Markdown
Contributor

@manodyaSenevirathne manodyaSenevirathne commented Mar 26, 2026

Purpose

Adds support for storing and retrieving the default CLI application's consumer key and secret per environment. These changes ensure that the CLI can persist and later retrieve these credentials, as those credentials can view only once and backend masks them in subsequent API responses.

Summary by CodeRabbit

  • New Features

    • Default CLI app consumer credentials can be saved per environment and are automatically used when regenerating authentication tokens.
    • New commands to set and retrieve a default app’s consumer key/secret for each environment.
  • Bug Fixes

    • Clearing one credential type no longer removes the entire environment; environments are deleted only when all credentials are absent.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 26, 2026

Warning

Rate limit exceeded

@manodyaSenevirathne has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 16 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 88100d1e-1761-4500-96e9-40efe59c8f9a

📥 Commits

Reviewing files that changed from the base of the PR and between ff1f59f and 6fd400f.

📒 Files selected for processing (1)
  • import-export-cli/credentials/jsonstore.go

Walkthrough

Added persistent storage for a default CLI application's consumer credentials: new DefaultAppKey type and Environment.DefaultApp field, store interface methods GetDefaultAppKeys/SetDefaultAppKeys, JsonStore implementations with Base64 encode/decode and helper, and integration in key-generation flow to load and persist keys.

Changes

Cohort / File(s) Summary
Data Structure
import-export-cli/credentials/credentials.go
Added DefaultAppKey (ConsumerKey, ConsumerSecret) and DefaultApp *DefaultAppKey on Environment (defaultApp,omitempty).
Store Interface
import-export-cli/credentials/store.go
Added GetDefaultAppKeys(env string) (string, string, error) and SetDefaultAppKeys(env, consumerKey, consumerSecret string) error.
JsonStore Implementation
import-export-cli/credentials/jsonstore.go
Implemented GetDefaultAppKeys/SetDefaultAppKeys with Base64 decode/encode, added defaultAppExists helper, updated EraseAPIM to keep environment when MI or default-app exists, and persist changes via s.persist().
Key Generation Integration
import-export-cli/impl/getKeys.go
Load default app keys via store when regenerating tokens; persist newly generated consumer key/secret via SetDefaultAppKeys. Store errors are non-fatal and guarded.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as "CLI (getKeys)"
    participant Store as "JsonStore (credentials)"
    participant Keygen as "Key Generation API"
    participant Token as "Token Generator"

    CLI->>Store: GetDefaultAppKeys(env)
    alt keys found
        Store-->>CLI: consumerKey, consumerSecret
        CLI->>Token: getNewToken(using consumerKey/secret)
    else keys missing
        CLI->>Keygen: createAppOrRegenerate()
        Keygen-->>CLI: ConsumerKey, ConsumerSecret
        CLI->>Store: SetDefaultAppKeys(env, consumerKey, consumerSecret)
        Store-->>CLI: persist OK
        CLI->>Token: getNewToken(using new consumerKey/secret)
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I nibble bytes and hide a key,

I Base64-wrap it snug for thee,
When tokens bloom I dance and cheer,
Stored safe in burrow, crystal clear,
A tiny hop — credentials dear! 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is largely incomplete. It includes only the Purpose section with a brief explanation, but is missing most other required sections from the template (Goals, Approach, User stories, Release note, Documentation, Training, Certification, Marketing, Automation tests, Security checks, Samples, Related PRs, Migrations, Test environment, and Learning). Complete the pull request description by adding the missing required sections from the template, such as Goals, Approach, User stories, Release note, Documentation, Security checks, and Automation tests information.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: adding default CLI app keys management support to the credentials module.

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

@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 the current code and only fix it if needed.

Inline comments:
In `@import-export-cli/credentials/credentials.go`:
- Around line 65-68: When EraseAPIM clears APIM credentials it must also remove
any APIM-scoped DefaultApp; update the EraseAPIM implementation in
import-export-cli/credentials/jsonstore.go so that after setting
environment.APIM to an empty/zero value it also sets environment.DefaultApp =
nil (or deletes the DefaultApp entry) on the Environment struct, ensuring
DefaultApp is cleared when APIM is erased.

In `@import-export-cli/credentials/jsonstore.go`:
- Around line 214-221: The SetDefaultAppKeys method currently persists a
long-lived consumer secret without notifying the user; update
JsonStore.SetDefaultAppKeys to emit the same PlainTextWarnMessage that
SetAPIMCredentials and SetMICredentials print (e.g., call/print
PlainTextWarnMessage) when writing the DefaultApp keys so users are warned
before s.persist() is invoked; keep the existing Base64Encode usage and
placement of s.persist() unchanged.

In `@import-export-cli/impl/getKeys.go`:
- Around line 133-135: The credential cache write is currently ignoring errors
from credentials.GetDefaultCredentialStore and store.SetDefaultAppKeys (seen
around the use of keyGenEnv and keygenResponse.ConsumerKey/ConsumerSecret), so
change the code to check and handle both errors: capture the error returned by
credentials.GetDefaultCredentialStore, log/return it if non-nil, then call
store.SetDefaultAppKeys and check its error; if SetDefaultAppKeys fails, log the
failure and propagate/return the error (or at minimum surface it as a warning so
callers know persistence failed) so the run does not silently drop the stored
keys.
- Around line 106-115: When using appKeys.List[0] and
credentials.GetDefaultCredentialStore()/store.GetDefaultAppKeys(keyGenEnv),
detect the case where GetDefaultAppKeys returns missing/empty or masked secrets
(e.g., empty string or mask like "*****") and do not silently fall back to the
masked values from getApplicationKeys(); instead either invoke the key
rotation/regeneration flow (implement and call a clear function such as
rotateOrGenerateAppKeys(...) that performs generation and persists the real
consumerKey/consumerSecret into the credential store) before calling
getNewToken(appKey, scopes), or return an explicit error that tells the user to
regenerate/rotate CLI app keys; update the branch around appKeys.List[0],
store.GetDefaultAppKeys, and the call to getNewToken to enforce this check and
remediation path.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c8b28bf8-9a3f-4b83-b3be-a96b700c9924

📥 Commits

Reviewing files that changed from the base of the PR and between 41ece4b and 5c3f1bc.

📒 Files selected for processing (4)
  • import-export-cli/credentials/credentials.go
  • import-export-cli/credentials/jsonstore.go
  • import-export-cli/credentials/store.go
  • import-export-cli/impl/getKeys.go

Comment thread import-export-cli/credentials/credentials.go
Comment thread import-export-cli/credentials/jsonstore.go Outdated
Comment thread import-export-cli/impl/getKeys.go
Comment thread import-export-cli/impl/getKeys.go
manodyaSenevirathne and others added 2 commits March 26, 2026 13:37
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@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

🧹 Nitpick comments (1)
import-export-cli/credentials/jsonstore.go (1)

252-260: Consider adding defaultAppExists check for consistency with EraseAPIM.

EraseMI currently deletes the environment if APIM credentials don't exist, but doesn't check for DefaultApp. While the current design ties DefaultApp to APIM flows (making this unlikely to cause issues), adding the check would provide defensive consistency:

-	if !apimCredentialsExists(environment.APIM) {
+	if !apimCredentialsExists(environment.APIM) && !defaultAppExists(environment.DefaultApp) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@import-export-cli/credentials/jsonstore.go` around lines 252 - 260, EraseMI
currently deletes the environment if apimCredentialsExists(environment.APIM)
returns false, but it doesn't check defaultAppExists(environment.DefaultApp)
like EraseAPIM does; update the EraseMI logic (in the EraseMI function in
jsonstore.go) to only delete s.credentials.Environments[env] when both
apimCredentialsExists(environment.APIM) and
defaultAppExists(environment.DefaultApp) are false, otherwise clear
environment.MI = MiCredential{} and write back s.credentials.Environments[env];
keep the final return s.persist() unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@import-export-cli/credentials/jsonstore.go`:
- Around line 226-227: There is an extra closing brace '}' at the end of the
file (stray brace on line 227) that causes a syntax error; remove the stray '}'
so the surrounding function/block in jsonstore.go correctly ends where it should
(ensuring the braces for the function/method in this file are balanced and the
function that currently ends at line 226 remains the final closing brace).

---

Nitpick comments:
In `@import-export-cli/credentials/jsonstore.go`:
- Around line 252-260: EraseMI currently deletes the environment if
apimCredentialsExists(environment.APIM) returns false, but it doesn't check
defaultAppExists(environment.DefaultApp) like EraseAPIM does; update the EraseMI
logic (in the EraseMI function in jsonstore.go) to only delete
s.credentials.Environments[env] when both
apimCredentialsExists(environment.APIM) and
defaultAppExists(environment.DefaultApp) are false, otherwise clear
environment.MI = MiCredential{} and write back s.credentials.Environments[env];
keep the final return s.persist() unchanged.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cd6276e5-daf3-40ab-a401-64079f576ac5

📥 Commits

Reviewing files that changed from the base of the PR and between 5c3f1bc and 91e1aa3.

📒 Files selected for processing (1)
  • import-export-cli/credentials/jsonstore.go

Comment thread import-export-cli/credentials/jsonstore.go Outdated
Copy link
Copy Markdown
Contributor

@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 the current code and only fix it if needed.

Inline comments:
In `@import-export-cli/credentials/jsonstore.go`:
- Around line 224-227: The code contains duplicated unreachable statements after
a return in jsonstore.go: remove the duplicate fmt.Printf(PlainTextWarnMessage,
s.Path) and the second return nil that follow the earlier return nil (these are
merge artifacts); keep a single fmt.Printf(PlainTextWarnMessage, s.Path) before
the return nil (or remove the print entirely if that was already executed
earlier) so that the function that references s.Path and PlainTextWarnMessage
has no dead code and compiles cleanly.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 624b21f8-c3cc-42bc-9e4b-da9bfb21c50c

📥 Commits

Reviewing files that changed from the base of the PR and between 91e1aa3 and ff1f59f.

📒 Files selected for processing (1)
  • import-export-cli/credentials/jsonstore.go

Comment thread import-export-cli/credentials/jsonstore.go Outdated
@PasanT9 PasanT9 merged commit e1e6268 into wso2:master Mar 26, 2026
3 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants