Skip to content

Conversation

@ekain-fr
Copy link

@ekain-fr ekain-fr commented Oct 13, 2025

Summary

Adds support for reading OAuth credentials from custom locations via $CLAUDE_CONFIG_DIR environment variable, with proper priority ordering that respects explicit user configuration.

Changes

File: src/utils/credentials.rs

Refactored get_oauth_token_file() to check environment variable first:

Priority Order

  1. $CLAUDE_CONFIG_DIR/.credentials.json (if CLAUDE_CONFIG_DIR is set)
  2. ~/.claude/.credentials.json (default fallback)
  3. None (if both fail)

Implementation

  • Check if CLAUDE_CONFIG_DIR env var is set
  • If set, attempt to read from $CLAUDE_CONFIG_DIR/.credentials.json
  • If not set or fails, fall back to default ~/.claude/.credentials.json
  • Return None only if both paths fail

Motivation

This change provides flexibility for users with non-standard Claude Code installations while maintaining backward compatibility:

  • Custom installations: Users can specify alternate config directories
  • Containerized environments: Docker/Kubernetes deployments with mounted config paths
  • Multi-user setups: Isolated config paths per user
  • CI/CD pipelines: Temporary config locations for automated testing
  • Development workflows: Testing with different credential sets

Backward Compatibility

No breaking changes

  • Default behavior unchanged for users without CLAUDE_CONFIG_DIR set
  • Existing installations continue to work with ~/.claude/.credentials.json
  • Graceful fallback if custom path doesn't exist

Testing

  • ✅ Compiles successfully: cargo build --release
  • ✅ Tests pass: cargo test
  • ✅ Maintains existing functionality with default path
  • ✅ Respects CLAUDE_CONFIG_DIR when set
  • ✅ Falls back correctly when custom path fails

Technical Details

Lines changed: 1 file, 31 insertions, 6 deletions

The refactoring extracts get_oauth_token_from_config_dir() as a separate function for cleaner code organization and reusability.


🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

Summary by Sourcery

Prioritize loading OAuth credentials from $CLAUDE_CONFIG_DIR/.credentials.json over the default ~/.claude/.credentials.json path and refactor credential retrieval logic into helper functions

New Features:

  • Allow loading OAuth credentials from $CLAUDE_CONFIG_DIR/.credentials.json

Enhancements:

  • Prioritize CLAUDE_CONFIG_DIR over the default ~/.claude/.credentials.json path when retrieving tokens
  • Refactor credential retrieval into get_oauth_token_from_config_dir and get_credentials_path helper functions

Add support for reading OAuth credentials from $CLAUDE_CONFIG_DIR/.credentials.json
with proper priority ordering. When CLAUDE_CONFIG_DIR is set, it takes precedence
over the default ~/.claude/.credentials.json location.

Priority order:
1. Try $CLAUDE_CONFIG_DIR/.credentials.json (if env var is set)
2. Fall back to ~/.claude/.credentials.json (default)
3. Return None if both fail

This respects explicit user configuration via environment variable while maintaining
backward compatibility with existing installations that use the default path.

Use cases:
- Custom Claude Code installations in non-standard locations
- Containerized environments with custom config directories
- Multi-user setups with isolated config paths
- CI/CD pipelines with temporary config locations

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@sourcery-ai
Copy link

sourcery-ai bot commented Oct 13, 2025

Reviewer's Guide

Refactors OAuth token retrieval to first attempt reading credentials from a custom directory specified by CLAUDE_CONFIG_DIR, falling back to the default ~/.claude/.credentials.json and returning None if both attempts fail.

Sequence diagram for OAuth token retrieval with CLAUDE_CONFIG_DIR priority

sequenceDiagram
    participant "get_oauth_token_file()"
    participant "Environment"
    participant "get_oauth_token_from_config_dir()"
    participant "get_credentials_path()"
    participant "Filesystem"

    "get_oauth_token_file()"->>"Environment": Check CLAUDE_CONFIG_DIR
    alt CLAUDE_CONFIG_DIR is set
        "get_oauth_token_file()"->>"get_oauth_token_from_config_dir()": Try custom config dir
        "get_oauth_token_from_config_dir()"->>"Filesystem": Read $CLAUDE_CONFIG_DIR/.credentials.json
        alt Credentials found
            "get_oauth_token_from_config_dir()"-->>"get_oauth_token_file()": Return token
        else Credentials not found
            "get_oauth_token_from_config_dir()"-->>"get_oauth_token_file()": Return None
        end
    end
    alt Token not found in custom dir
        "get_oauth_token_file()"->>"get_credentials_path()": Get default path
        "get_oauth_token_file()"->>"Filesystem": Read ~/.claude/.credentials.json
        alt Credentials found
            "get_oauth_token_file()"-->>"Caller": Return token
        else Credentials not found
            "get_oauth_token_file()"-->>"Caller": Return None
        end
    end
Loading

Class diagram for updated credential retrieval functions

classDiagram
    class CredentialsFile {
        claude_ai_oauth: Option<ClaudeAiOAuth>
    }
    class ClaudeAiOAuth {
        access_token: String
    }
    class "get_oauth_token_file()" {
        +get_oauth_token_file() Option<String>
    }
    class "get_oauth_token_from_config_dir()" {
        +get_oauth_token_from_config_dir() Option<String>
    }
    class "get_credentials_path()" {
        +get_credentials_path() Option<PathBuf>
    }

    CredentialsFile --> "ClaudeAiOAuth"
    "get_oauth_token_file()" --> "get_oauth_token_from_config_dir()"
    "get_oauth_token_file()" --> "get_credentials_path()"
Loading

File-Level Changes

Change Details Files
Refactor get_oauth_token_file to support prioritized lookup
  • Check CLAUDE_CONFIG_DIR environment variable before default path
  • Return token early if found in custom directory
  • Fall back to default credentials path if custom lookup fails
  • Return None only after both lookup attempts fail
src/utils/credentials.rs
Extract get_oauth_token_from_config_dir helper
  • Read CLAUDE_CONFIG_DIR env var and construct credentials path
  • Check file existence and read JSON content
  • Parse JSON to extract access_token
src/utils/credentials.rs
Extract get_credentials_path helper
  • Resolve home directory with dirs::home_dir()
  • Build default path ~/.claude/.credentials.json
  • Remove duplicate function definition
src/utils/credentials.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `src/utils/credentials.rs:73-83` </location>
<code_context>
+
+    // Fall back to default ~/.claude/.credentials.json
+    if let Some(credentials_path) = get_credentials_path() {
+        if credentials_path.exists() {
+            if let Ok(content) = std::fs::read_to_string(&credentials_path) {
+                if let Ok(creds_file) = serde_json::from_str::<CredentialsFile>(&content) {
+                    if let Some(token) = creds_file.claude_ai_oauth.map(|oauth| oauth.access_token) {
</code_context>

<issue_to_address>
**suggestion:** Consider logging or surfacing errors when reading or parsing the credentials file.

If silent failure is not intended, add error logging to help diagnose issues with file access or JSON parsing.

```suggestion
    if let Some(credentials_path) = get_credentials_path() {
        if credentials_path.exists() {
            match std::fs::read_to_string(&credentials_path) {
                Ok(content) => {
                    match serde_json::from_str::<CredentialsFile>(&content) {
                        Ok(creds_file) => {
                            if let Some(token) = creds_file.claude_ai_oauth.map(|oauth| oauth.access_token) {
                                return Some(token);
                            }
                        }
                        Err(e) => {
                            eprintln!(
                                "Failed to parse credentials file as JSON ({}): {}",
                                credentials_path.display(),
                                e
                            );
                        }
                    }
                }
                Err(e) => {
                    eprintln!(
                        "Failed to read credentials file ({}): {}",
                        credentials_path.display(),
                        e
                    );
                }
            }
        }
    }
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

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