Skip to content
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

Rework token acquire/refresh logic #282

Merged
merged 4 commits into from
Jan 5, 2025

Conversation

jschlyter
Copy link
Contributor

@jschlyter jschlyter commented Jan 4, 2025

Summary by CodeRabbit

  • Authentication Improvements

    • Enhanced token management with more robust error handling.
    • Added more granular control over token retrieval process with a new force parameter.
    • Improved logging and token validation mechanisms.
  • Code Quality

    • Refactored authentication methods for better maintainability.
    • Modularized token-related logic into separate methods.

Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

Walkthrough

The pull request introduces significant modifications to the authentication mechanism in the Polestar API implementation. The changes focus on enhancing token management within the PolestarAuth class by updating the get_token method to include a new force parameter, restructuring the token retrieval process, and improving error handling. Additionally, new methods for parsing token responses and refreshing tokens are added, while the get_ev_data method in the PolestarApi class is updated to simplify token retrieval.

Changes

File Changes
custom_components/polestar_api/pypolestar/auth.py - Updated get_token method signature with new force parameter
- Added _parse_token_response method for handling token responses
- Added _authorization_code method for obtaining initial tokens
- Added _token_refresh method for refreshing existing tokens
custom_components/polestar_api/pypolestar/polestar.py - Modified get_ev_data method to simplify token retrieval call

Sequence Diagram

sequenceDiagram
    participant Client
    participant PolestarAuth
    participant AuthService

    Client->>PolestarAuth: get_token(force=False)
    alt Token is valid
        PolestarAuth-->>Client: Return existing token
    else Token needs refresh
        PolestarAuth->>AuthService: Attempt token refresh
        alt Refresh successful
            AuthService-->>PolestarAuth: New token
            PolestarAuth-->>Client: Return new token
        else Refresh fails
            PolestarAuth->>AuthService: Request new authorization code
            AuthService-->>PolestarAuth: New token
            PolestarAuth-->>Client: Return new token
        end
    end
Loading

Poem

🐰 Tokens dance, a rabbit's delight,
Refreshed and parsed with coding might!
Authorization's new embrace,
Hopping through each API space,
With error handling, clean and bright! 🔑


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

@jschlyter
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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 (7)
custom_components/polestar_api/pypolestar/auth.py (7)

104-105: Clarify usage of new force parameter in docstring
The method docstring states "Ensure we have a valid access token," but does not specify what happens when force=True. It may be helpful to explicitly explain how force impacts token acquisition, particularly regarding forceful retrieval.


108-111: Reuse existing is_token_valid() check
These conditions partially repeat the logic in is_token_valid(). Consider using if not force and self.is_token_valid(): … to reduce duplication and streamline code.


129-131: Include underlying exception info in error message
When re-raising PolestarAuthException, consider adding context about the original exception to clarify why _authorization_code failed.

-except PolestarAuthException as exc:
-    raise PolestarAuthException("Unable to acquire initial token") from exc
+except PolestarAuthException as exc:
+    raise PolestarAuthException(
+        f"Unable to acquire initial token, reason: {exc}"
+    ) from exc

132-150: Handle missing token fields in payload
Currently, there is an assumption that access_token, refresh_token, and expires_in are always present. Consider adding defensive checks to avoid KeyError if the OIDC provider returns an unexpected response.


151-167: Avoid duplication between _authorization_code and _token_refresh
Much of the underlying logic around POSTing to the token endpoint overlaps. Consider unifying these calls into a shared method that accepts different parameters for clarity and maintainability.


173-177: Assess logging
The debug statement is valuable for tracing. This HTTP request can reveal sensitive data, so ensure that only non-sensitive parts of the request are logged if you ever expand logging.


179-196: Extend refresh request error handling
Similar to _authorization_code(), you might benefit from more robust error handling, especially around partial or malformed responses from the token endpoint.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca53c5f and bca24be.

📒 Files selected for processing (2)
  • custom_components/polestar_api/pypolestar/auth.py (1 hunks)
  • custom_components/polestar_api/pypolestar/polestar.py (1 hunks)
🔇 Additional comments (3)
custom_components/polestar_api/pypolestar/auth.py (2)

113-114: Confirm short-circuit logic
Logging a message and returning early if the token is valid is appropriate and appears consistent with the new parameters.


116-127: Fallback from token refresh to authorization code
Gracefully falling back to the authorization-code path if refresh fails is a good strategy. Just ensure the warning message is sufficiently clear for debugging token refresh issues.

custom_components/polestar_api/pypolestar/polestar.py (1)

200-200: Consider explicit force usage
Switching from await self.auth.get_token(refresh=True) to await self.auth.get_token() aligns with the new method signature. If an unconditional refresh is required, consider calling await self.auth.get_token(refresh=True, force=True) to ensure the token always updates.

@jschlyter jschlyter marked this pull request as ready for review January 4, 2025 20:29
@jschlyter jschlyter requested a review from a team as a code owner January 4, 2025 20:29
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 (5)
custom_components/polestar_api/pypolestar/auth.py (5)

104-130: LGTM! Consider enhancing error handling specificity.

The reworked token management flow with the new force parameter is well-structured and handles the token lifecycle effectively. The approach of attempting refresh before falling back to authorization code is robust.

Consider making the error handling more specific by:

  1. Using a custom exception for refresh failures
  2. Adding more context to the error message in line 122
-                    "Failed to refresh token, retry with code", exc_info=exc
+                    "Failed to refresh token (status=%s), falling back to authorization code",
+                    getattr(exc, 'status_code', 'unknown'),
+                    exc_info=exc

Line range hint 132-154: LGTM! Consider adding token validation.

The centralized token response parsing is well-implemented with proper error handling and state management.

Consider adding basic validation for the token values:

         try:
             self.access_token = payload["access_token"]
+            if not isinstance(self.access_token, str) or not self.access_token.strip():
+                raise ValueError("Invalid access token format")
             self.refresh_token = payload["refresh_token"]
             self.token_lifetime = payload["expires_in"]
+            if not isinstance(self.token_lifetime, (int, float)) or self.token_lifetime <= 0:
+                raise ValueError("Invalid token lifetime")
             self.token_expiry = datetime.now(tz=timezone.utc) + timedelta(
                 seconds=self.token_lifetime
             )

156-184: LGTM! Consider adding request validation.

The implementation of the authorization code flow with PKCE is secure and well-structured.

Consider validating the token endpoint URL before making the request:

+        if not self.oidc_configuration.get("token_endpoint", "").startswith(("https://", "http://localhost")):
+            raise PolestarAuthException("Invalid token endpoint URL")
+
         response = await self.client_session.post(
             self.oidc_configuration["token_endpoint"],
             data=token_request,
             timeout=HTTPX_TIMEOUT,
         )

186-206: LGTM! Consider adding retry mechanism.

The token refresh implementation is clean and follows good practices by reusing the common token response parsing logic.

Consider adding a retry mechanism for transient failures:

+    async def _token_refresh(self, max_retries: int = 2) -> None:
         """Refresh existing token."""
 
+        last_exception = None
+        for attempt in range(max_retries):
+            try:
                 token_request = {
                     "grant_type": "refresh_token",
                     "client_id": OIDC_CLIENT_ID,
                     "refresh_token": self.refresh_token,
                 }
 
                 self.logger.debug(
                     "Call token endpoint with grant_type=%s", token_request["grant_type"]
                 )
 
                 response = await self.client_session.post(
                     self.oidc_configuration["token_endpoint"],
                     data=token_request,
                     timeout=HTTPX_TIMEOUT,
                 )
                 response.raise_for_status()
                 self._parse_token_response(response)
+                return
+            except httpx.TransportError as exc:
+                last_exception = exc
+                if attempt < max_retries - 1:
+                    self.logger.warning("Retrying token refresh after transport error", exc_info=exc)
+                    continue
+        if last_exception:
+            raise PolestarAuthException("Failed to refresh token after retries") from last_exception

Line range hint 104-206: Consider implementing token persistence.

The token management implementation is robust and well-structured. To further enhance the system's reliability and user experience, consider implementing token persistence to maintain sessions across restarts.

Key considerations for token persistence:

  1. Secure storage of refresh tokens
  2. Handling of expired persisted tokens
  3. Migration strategy for existing sessions

Would you like me to provide a detailed design proposal for implementing secure token persistence?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bca24be and edef33d.

📒 Files selected for processing (1)
  • custom_components/polestar_api/pypolestar/auth.py (2 hunks)

@jschlyter jschlyter merged commit f633d20 into pypolestar:main Jan 5, 2025
5 checks passed
@jschlyter jschlyter deleted the update_token_refresh branch January 5, 2025 09:03
This was referenced Jan 5, 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.

3 participants