Skip to content

feat: core rpc cookie#189

Merged
pauldelucia merged 3 commits into
v0.8.4-devfrom
feat/core-rpc-cookie
Mar 11, 2025
Merged

feat: core rpc cookie#189
pauldelucia merged 3 commits into
v0.8.4-devfrom
feat/core-rpc-cookie

Conversation

@PastaPastaPasta
Copy link
Copy Markdown
Member

@PastaPastaPasta PastaPastaPasta commented Mar 6, 2025

This PR implements a change in behavior where cookie authentication with dash core will be the default attempted configuration.

When dash core is launched with RPC on, but w/o a user/pw combo it will use cookie authentication by default. Where the cookie is placed in core's directory. As long as DET can read this cookie it can use it.

This branch changes the default behavior to always try cookie auth, but doesn't change any of the setup process, so the vast majority of users will still use user/pw auth.

Summary by CodeRabbit

  • New Features

    • Introduced flexible handling of user data directories across different environments.
    • Added a new authentication mechanism that first attempts secure file-based credentials before falling back to traditional login.
  • Refactor

    • Streamlined network connection and error handling processes to enhance overall reliability and maintainability.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 6, 2025

Walkthrough

This changeset introduces several functions to enhance directory path handling and authentication logic. A new generic function for obtaining user data directory paths and a specific function for DashCore have been added. The cookie path is now dynamically generated based on network type and optional development network name. Additionally, the logic for retrieving chain locks in the backend task is refactored and consolidated in a new method. Changes in provider initialization now include a network parameter and a cookie-based authentication flow with a fallback to user/password handling.

Changes

File(s) Change Summary
src/app_dir.rs Added user_data_dir_path(app: &str), core_user_data_dir_path(), and core_cookie_path(network, devnet_name) to generalize directory path retrieval and cookie file handling.
src/backend_task/core/mod.rs Introduced get_best_chain_lock method to centralize chain lock retrieval logic, simplified error handling, and updated imports to use NetworkConfig and core_cookie_path.
src/context.rs, src/context_provider.rs Modified Provider initialization to accept a network parameter, implementing cookie-based authentication that falls back to user/password, with updated method signatures and imports.

Sequence Diagram(s)

sequenceDiagram
    participant C as Caller
    participant P as Provider
    participant F as Filesystem (Cookie)
    participant S as Config Source

    C->>P: Initialize Provider with network & config
    P->>F: Retrieve cookie via core_cookie_path
    alt Cookie exists and valid
        F-->>P: Return cookie data
        P->>P: Parse cookie and create Client with cookie auth
    else Cookie missing/invalid
        F-->>P: Return error/not found
        P->>S: Retrieve user/password from config
        P->>P: Create Client with user/password auth
    end
    P-->>C: Return initialized Client
Loading

Possibly related PRs

Suggested reviewers

  • QuantumExplorer
  • thephez
  • pauldelucia

Poem

I’m a rabbit in a code garden bright,
Hopping through functions under moonlight.
New paths and cookies line my way,
With network steps, I proudly play.
In this realm of logic so divine,
I celebrate these changes—hoppy and fine!
🐇💻

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Nitpick comments (2)
src/app_dir.rs (1)

46-57: Handle potential panic in network matching.

The function uses unimplemented!() for unknown network types, which could cause a runtime panic.

Consider handling all possible network variants to avoid runtime panics:

pub fn core_cookie_path(network: Network, devnet_name: &Option<String>) -> Result<PathBuf, std::io::Error> {
    core_user_data_dir_path().map(|path| {
        let network_dir = match network {
            Network::Dash => "",
            Network::Testnet => "testnet3",
            Network::Devnet => devnet_name.as_deref().unwrap_or(""),
            Network::Regtest => "regtest",
-           _ => unimplemented!(),
+           _ => {
+               tracing::warn!("Unsupported network type: {:?}", network);
+               ""
+           },
        };
        path.join(network_dir).join(".cookie")
    })
}
src/context_provider.rs (1)

25-47: Add validation for cookie file content.

The cookie parsing assumes the file contains exactly one colon separator, but there's no validation or error handling for malformed cookies.

Consider adding validation for the cookie format:

let (user, pass) = if let Ok(cookie) = cookie {
    // split the cookie at ":", first part is user (__cookie__), second part is password
    let cookie_parts: Vec<&str> = cookie.split(':').collect();
-   let user = cookie_parts[0];
-   let password = cookie_parts[1];
-   (user.to_string(), password.to_string())
+   if cookie_parts.len() == 2 {
+       let user = cookie_parts[0];
+       let password = cookie_parts[1];
+       (user.to_string(), password.to_string())
+   } else {
+       tracing::warn!("Malformed cookie file: expected format 'user:password'");
+       (
+           config.core_rpc_user.clone(),
+           config.core_rpc_password.clone(),
+       )
+   }
} else {
    // Fall back to the pre-set user / pass if needed
    (
        config.core_rpc_user.clone(),
        config.core_rpc_password.clone(),
    )
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 02103f3 and 8418299.

📒 Files selected for processing (4)
  • src/app_dir.rs (1 hunks)
  • src/backend_task/core/mod.rs (3 hunks)
  • src/context.rs (3 hunks)
  • src/context_provider.rs (2 hunks)
🔇 Additional comments (7)
src/app_dir.rs (2)

12-20: Good abstraction of directory path logic.

The creation of a generic user_data_dir_path function improves code reusability and maintains consistent directory path resolution across the application.


26-44: Appropriate platform-specific directory handling.

The implementation correctly handles platform differences, especially for Linux where .dashcore is in the home directory, while using the standard application directories for other platforms.

src/context.rs (3)

1-1: Appropriate import of the new directory utility functions.

The import correctly references the new functions added to the app_dir module.


74-74: Updated Provider initialization with network parameter.

The Provider::new call now correctly includes the network parameter, aligning with the updated method signature.


90-109: Well-structured cookie authentication with fallback.

The implementation follows a good pattern: attempt cookie authentication first, then fall back to user/password if that fails. The error message is informative and helps with debugging.

src/backend_task/core/mod.rs (2)

97-139: Good refactoring for chain lock retrieval.

The creation of a centralized get_best_chain_lock method reduces code duplication and improves maintainability. The error handling is comprehensive and provides detailed messages.

The same cookie validation suggestion applies here as in the context_provider.rs file regarding potential malformed cookie files.


60-65: Clean implementation of chain lock retrieval.

The code now uses the new get_best_chain_lock method in a clean and readable way, passing the appropriate network configurations.

@pauldelucia pauldelucia changed the base branch from master to v0.8.4-dev March 11, 2025 07:30
@pauldelucia pauldelucia merged commit 01f1b49 into v0.8.4-dev Mar 11, 2025
@pauldelucia pauldelucia deleted the feat/core-rpc-cookie branch March 11, 2025 07:33
@coderabbitai coderabbitai Bot mentioned this pull request Mar 11, 2025
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