-
Notifications
You must be signed in to change notification settings - Fork 22
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
Conversation
""" WalkthroughA 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
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
Poem
Note ⚡️ AI Code Reviews for VS Code, Cursor, WindsurfCodeRabbit 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. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (4)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAll modified and coverable lines are covered by tests ✅
🚀 New features to boost your workflow:
|
There was a problem hiding this 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
📒 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 toself.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 fromapi_request
toapi_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.
Description of change
adds a method to create api keys for the current user
Pull-Request Checklist
main
branchFixes #0000
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Chores