Skip to content

Refactor error messages for clarity and consistency in token handling - #36

Merged
evgenyk merged 1 commit into
mainfrom
ev/client_secret_redactor
Sep 8, 2025
Merged

Refactor error messages for clarity and consistency in token handling#36
evgenyk merged 1 commit into
mainfrom
ev/client_secret_redactor

Conversation

@evgenyk

@evgenyk evgenyk commented Sep 8, 2025

Copy link
Copy Markdown
Contributor

Improve error messages in login and whoami commands, and enhance token-related error handling in cliSession and token source implementations for better clarity and consistency.

…n-related error handling in cliSession and token source implementations for improved clarity and consistency.
@coderabbitai

coderabbitai Bot commented Sep 8, 2025

Copy link
Copy Markdown

Walkthrough

Error messages were standardized across CLI commands, CLI session storage, and OAuth2 token sources. cliSession adds a fallback from chunked storage to single-key retrieval in GetKey. Tests were updated to expect new error prefixes. Minor prompt formatting changes were made in NewCliSession.

Changes

Cohort / File(s) Summary of changes
CLI example commands: error message text
examples/cli/pkg/cmd/loginCommand.go, examples/cli/pkg/cmd/whoAmICommand.go
Updated wrapped error messages for token retrieval failures (“run login failed: %w”, “run whoami failed: %w”); no control-flow changes.
CLI session: storage errors + fallback
frameworks/cli/cliSession.go
Normalized error prefixes (“chunked storage”, “chunk count storage”, “raw token storage”, “code_verifier storage”). GetKey now falls back to single-key retrieval if chunk count fetch fails; combined error returned if fallback also fails. Prompt printing/newline tweaks in NewCliSession.
CLI session tests: expectations aligned
frameworks/cli/cliSession_test.go
Updated expected error substrings to match new prefixes and fallback behavior (“raw token storage: …”, “chunked storage: …”, etc.); no test logic changes.
OAuth2 token source: error wrapping
oauth2/authorization_code/token_source.go, oauth2/client_credentials/token_source.go
Standardized error wrapping messages (“session hook: %w”, “token source: %w”); logic and flow unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant CS as CliSession
  participant Store as Storage

  Client->>CS: GetKey(ctx, key)
  CS->>Store: Read chunk count
  alt Chunk count found and valid
    loop For each chunk i
      CS->>Store: Read chunk i
      alt Read fails
        CS-->>Client: error "chunked storage: …"
      end
    end
    CS-->>Client: Concatenated key
  else Chunk count missing/parse error
    note right of CS: New/changed flow: fallback
    CS->>Store: Read single key
    alt Fallback succeeds
      CS-->>Client: Key
    else Fallback fails
      CS-->>Client: error "chunked storage (chunked: …, fallback: …)"
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ev/client_secret_redactor

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.

@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: 0

🧹 Nitpick comments (8)
examples/cli/pkg/cmd/loginCommand.go (1)

33-52: Standardize error prefixing and context usage in runLogin

Wrap earlier failures with the same "run login failed" prefix and use the passed-in cmd.Context() consistently.

 deviceFlow, err := config.NewDeviceAuthorizationFlow(c.kindeDomain)
 if err != nil {
-    return err
+    return fmt.Errorf("run login failed: %w", err)
 }
 
-deviceAuth, err := deviceFlow.StartDeviceAuth(c.cmd.Context())
+deviceAuth, err := deviceFlow.StartDeviceAuth(cmd.Context())
 if err != nil {
-    return err
+    return fmt.Errorf("run login failed: %w", err)
 }
 ...
-err = deviceFlow.ExchangeDeviceAccessToken(c.cmd.Context(), deviceAuth)
+err = deviceFlow.ExchangeDeviceAccessToken(cmd.Context(), deviceAuth)
 if err != nil {
-    return err
+    return fmt.Errorf("run login failed: %w", err)
 }
 token, err := deviceFlow.GetToken(cmd.Context())
 if err != nil {
     return fmt.Errorf("run login failed: %w", err)
 }
examples/cli/pkg/cmd/whoAmICommand.go (2)

32-35: Prefix the constructor error to match the new scheme

Align with the PR’s error style.

 deviceFlow, err := config.NewDeviceAuthorizationFlow(c.kindeDomain)
 if err != nil {
-    return err
+    return fmt.Errorf("run whoami failed: %w", err)
 }

37-40: Avoid logging a nil error in the unauthenticated branch

Guard Err(err) to prevent logging “error=null”.

- if isAuthenticated, err := deviceFlow.IsAuthenticated(cmd.Context()); !isAuthenticated {
-     log.Error().Err(err).Msg("You are not authenticated")
+ if isAuthenticated, err := deviceFlow.IsAuthenticated(cmd.Context()); !isAuthenticated {
+     if err != nil {
+         log.Error().Err(err).Msg("You are not authenticated")
+     } else {
+         log.Error().Msg("You are not authenticated")
+     }
      return fmt.Errorf("you are not logged in. Please run 'login' command first")
 }
oauth2/client_credentials/token_source.go (1)

51-52: Propagate SetRawToken failure (currently ignored)

If persisting the token fails, callers lose that signal. Consider returning it (mirrors authorization_code.Token()).

- t.flow.sessionHooks.SetRawToken(possiblyNewToken)
- return possiblyNewToken, nil
+ if err := t.flow.sessionHooks.SetRawToken(possiblyNewToken); err != nil {
+     return possiblyNewToken, fmt.Errorf("session hook: %w", err)
+ }
+ return possiblyNewToken, nil
oauth2/authorization_code/token_source.go (1)

17-21: Avoid double-wrapping Token() errors here

Token() already prefixes with “session hook:”/“token source:”. Re-wrapping as “failed to get token” is redundant.

 token, err := t.Token()
 if err != nil {
-    return nil, fmt.Errorf("failed to get token: %w", err)
+    return nil, err
 }
frameworks/cli/cliSession.go (2)

84-89: Join chunked+fallback errors while keeping the stable prefix

Use errors.Join so callers can unwrap both causes; retain the “chunked storage:” prefix for test stability.

- ringItem, fallbackErr := c.keyring.Get(key)
- if fallbackErr != nil {
-     return nil, fmt.Errorf("chunked storage (chunked: %v, fallback: %w)", err, fallbackErr)
- }
+ ringItem, fallbackErr := c.keyring.Get(key)
+ if fallbackErr != nil {
+     return nil, fmt.Errorf("chunked storage: %w", errors.Join(err, fallbackErr))
+ }

263-267: Minor UX polish: write prompts/errors to stderr and use lowercase error starts

Keeps CLI stdout clean for piping and follows Go error style.

- fmt.Printf("%s\n", prompt)
+ fmt.Fprintln(os.Stderr, prompt)
 ...
- fmt.Printf("\nError reading password: %v\n", err)
+ fmt.Fprintf(os.Stderr, "\nerror reading password: %v\n", err)
frameworks/cli/cliSession_test.go (1)

1-12: Add a test for GetCodeVerifier error path

Given the new “code_verifier storage:” prefix, add a small test asserting the error substring when the key is missing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0c91c1 and c9c2738.

📒 Files selected for processing (6)
  • examples/cli/pkg/cmd/loginCommand.go (1 hunks)
  • examples/cli/pkg/cmd/whoAmICommand.go (1 hunks)
  • frameworks/cli/cliSession.go (9 hunks)
  • frameworks/cli/cliSession_test.go (7 hunks)
  • oauth2/authorization_code/token_source.go (1 hunks)
  • oauth2/client_credentials/token_source.go (1 hunks)
🔇 Additional comments (6)
oauth2/client_credentials/token_source.go (1)

42-45: LGTM on error prefix change

“token source: %w” matches the new, consistent taxonomy.

oauth2/authorization_code/token_source.go (1)

37-46: LGTM on standardized prefixes

“session hook: %w” and “token source: %w” improve traceability without over-specifying steps.

frameworks/cli/cliSession.go (3)

146-152: LGTM on “raw token storage” prefixing

Clear, consistent, and wraps both read and unmarshal failures.


200-220: LGTM on chunk save + count save prefixes

The “chunked storage:” and “chunk count storage:” labels make failures actionable.


185-205: Ensure Go version ≥1.22 and implement min() helper
No go.mod was found to declare Go 1.22 (required for for i := range chunks), and there’s no min() function in the codebase. Add a module file with go 1.22 (or bump CI) and define or import a min() helper before using it.

frameworks/cli/cliSession_test.go (1)

108-111: Tests updated to new prefixes — looks good

Assertions target stable substrings (“raw token storage: …”, “chunked storage: …”) and shouldn’t be brittle.

@evgenyk
evgenyk merged commit 480a00c into main Sep 8, 2025
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.

1 participant