8000 feat: add create API key functionality and corresponding tests by RaHehl · Pull Request #482 · uilibs/uiprotect · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: add create API key functionality and corresponding tests #482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 24, 2025

Conversation

RaHehl
Copy link
Collaborator
@RaHehl RaHehl commented May 24, 2025

Description of change

adds a method to create api keys for the current user

Pull-Request Checklist

  • Code is up-to-date with the main branch
  • This pull request follows the contributing guidelines.
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • Documentation has been updated to reflect this change
  • The new commits follow conventions outlined in the conventional commit spec, such as "fix(api): prevent racing of requests".
  • If pre-commit.ci is failing, try pre-commit run -a for further information.
  • If CI / test is failing, try poetry run pytest for further information.

Summary by CodeRabbit

  • New Features

    • Added a command-line option to create a new API key with a specified name and display it directly in the console.
  • Bug Fixes

    • Improved error handling for API key creation, including validation for empty names and missing user context.
  • Tests

    • Introduced new tests to verify successful API key creation and proper handling of invalid input and error scenarios.
    • Added tests to confirm correct API request URL construction with custom and default API paths.
  • Chores

    • Removed the "protect-url" command from the CLI command set.

Copy link
Contributor
coderabbitai bot commented May 24, 2025

"""

Walkthrough

A new asynchronous method for creating API keys was added to the Protect API client, along with a corresponding CLI command. The API client methods were updated to accept an optional API path parameter. Tests were added for the new API key creation method and API path usage, and a CLI command registration was removed.

Changes

File(s) Change Summary
src/uiprotect/api.py Added create_api_key async method; updated api_request_raw and api_request to accept api_path.
src/uiprotect/cli/init.py Added new CLI command create_api_key to generate API keys via the CLI.
src/uiprotect/cli/base.py Removed registration of the protect_url command from CLI device commands.
tests/test_api.py Added async pytest tests for create_api_key (success, validation, errors) and for api_request_raw.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant ProtectApiClient
    participant API Server

    User->>CLI: Run create_api_key command with name
    CLI->>ProtectApiClient: create_api_key(name)
    ProtectApiClient->>ProtectApiClient: Validate name, extract user_id
    ProtectApiClient->>API Server: POST /proxy/users/api/v2/user/{user_id}/keys (with name)
    API Server-->>ProtectApiClient: Response with full_api_key
    ProtectApiClient-->>CLI: Return full_api_key
    CLI-->>User: Print API key
Loading

Poem

In the warren of code, a new key is born,
With a hop to the CLI, no need to forlorn.
Async requests scamper, tests nibble with glee,
Now rabbits and users unlock with a key!
🐇🔑
"""

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 41b3bad and f591232.

📒 Files selected for processing (1)
  • tests/test_api.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_api.py
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test (3.12, ubuntu-latest, 2)
  • GitHub Check: test (3.13, ubuntu-latest, 2)
  • GitHub Check: test (3.10, ubuntu-latest, 2)
  • GitHub Check: test (3.11, ubuntu-latest, 2)
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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
codecov bot commented May 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Files with missing lines Coverage Δ
src/uiprotect/api.py 60.83% <100.00%> (+1.37%) ⬆️
🚀 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.

bdraco
bdraco previously approved these changes May 24, 2025
@RaHehl RaHehl requested a review from bdraco May 24, 2025 19:40
@RaHehl RaHehl marked this pull request as ready for review May 24, 2025 19:40
Copy link
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/uiprotect/api.py (1)

2047-2073: Well-implemented API key creation with proper validation.

The method includes comprehensive input validation, user context checking, and response validation. The error handling appropriately raises BadRequest exceptions for various failure scenarios.

Consider adding rate limiting information to the docstring, as API key creation is typically a sensitive operation that may be rate-limited by the backend.

Consider enhancing the docstring:

-    """Create an API key with the given name and return the full API key."""
+    """Create an API key with the given name and return the full API key.
+    
+    Args:
+        name: The name for the API key (cannot be empty)
+        
+    Returns:
+        The full API key string
+        
+    Raises:
+        BadRequest: If name is empty, user ID unavailable, or creation fails
+        
+    Note:
+        This operation may be rate-limited by the backend.
+    """
src/uiprotect/cli/__init__.py (1)

325-340: LGTM! CLI command follows established patterns.

The implementation correctly follows the existing CLI patterns with proper async handling, session cleanup, and logging setup. The command appropriately uses typer.Argument for the required name parameter.

Consider adding error handling to provide better user feedback when API key creation fails:

 @app.command()
 def create_api_key(
     ctx: typer.Context,
     name: str = typer.Argument(..., help="Name for the API key"),
 ) -> None:
     """Create a new API key for the current user."""
     protect = cast(ProtectApiClient, ctx.obj.protect)

     async def callback() -> str:
-        api_key = await protect.create_api_key(name)
+        try:
+            api_key = await protect.create_api_key(name)
+        except Exception as e:
+            typer.secho(f"Failed to create API key: {e}", fg="red")
+            sys.exit(1)
         await protect.close_session()
         return api_key

     _setup_logger()
     result = run_async(callback())
     typer.echo(result)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between eb9bb66 and 41b3bad.

📒 Files selected for processing (4)
  • src/uiprotect/api.py (3 hunks)
  • src/uiprotect/cli/__init__.py (1 hunks)
  • src/uiprotect/cli/base.py (0 hunks)
  • tests/test_api.py (1 hunks)
💤 Files with no reviewable changes (1)
  • src/uiprotect/cli/base.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/uiprotect/cli/__init__.py (4)
src/uiprotect/api.py (3)
  • create_api_key (2047-2073)
  • callback (1600-1604)
  • close_session (299-305)
src/uiprotect/cli/base.py (1)
  • callback (36-39)
src/uiprotect/cli/backup.py (1)
  • _setup_logger (377-393)
src/uiprotect/utils.py (1)
  • run_async (632-637)
🪛 GitHub Check: codecov/patch
src/uiprotect/api.py

[warning] 397-397: src/uiprotect/api.py#L397
Added line #L397 was not covered by tests

🔇 Additional comments (6)
src/uiprotect/api.py (2)

393-398: LGTM! Good design for API path flexibility.

The addition of the optional api_path parameter enables calling different API endpoints while maintaining backward compatibility. The implementation correctly defaults to self.api_path when no override is provided.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 397-397: src/uiprotect/api.py#L397
Added line #L397 was not covered by tests


455-455: LGTM! Consistent parameter propagation.

The api_path parameter is correctly propagated from api_request to api_request_raw, maintaining consistency across the API request methods.

Also applies to: 463-463

tests/test_api.py (4)

1198-1212: LGTM! Comprehensive success scenario test.

The test correctly validates the happy path for API key creation, including proper mocking of the API response, verification of the returned key, and assertion of the correct API call parameters. The use of api_path parameter aligns with the enhanced API client methods mentioned in the summary.


1214-1218: LGTM! Good input validation test.

The test properly validates that empty API key names are rejected with a clear error message. This ensures the method enforces basic input validation requirements.


1221-1227: LGTM! Proper failure handling test.

The test correctly simulates an API failure scenario where the response doesn't contain the expected key structure, ensuring that appropriate error handling is in place with a descriptive error message.


1229-1237: LGTM! Comprehensive edge case coverage.

The test thoroughly covers scenarios where user ID is not available, testing both None and empty dictionary cases for the token decode. This ensures robust error handling when authentication context is missing or incomplete.

@bdraco bdraco merged commit 3b74740 into main May 24, 2025
9 of 10 checks passed
@bdraco bdraco deleted the api-key-create branch May 24, 2025 22:11
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
0