Skip to content

feat: add token validation enhancements#49

Merged
eman merged 1 commit intomainfrom
feat/token-validation-enhancements
Dec 17, 2025
Merged

feat: add token validation enhancements#49
eman merged 1 commit intomainfrom
feat/token-validation-enhancements

Conversation

@eman
Copy link
Copy Markdown
Owner

@eman eman commented Dec 17, 2025

Summary

This PR implements three token validation enhancements to improve error handling and prevent silent failures due to stale authentication credentials.

Changes

1. Add has_valid_tokens Property (HIGH PRIORITY)

  • File: src/nwp500/auth.py
  • What it does: Checks if tokens exist AND are not expired (both JWT and AWS credentials)
  • Use case: Pre-flight validation before creating MQTT clients or token-dependent operations
  • Benefit: Fails fast instead of silently accepting stale tokens

Implementation:

@property
def has_valid_tokens(self) -> bool:
    """Check if both JWT and AWS credentials are valid and not expired."""
    if not self._auth_response:
        return False
    tokens = self._auth_response.tokens
    return not tokens.is_expired and not tokens.are_aws_credentials_expired

2. Enhance NavienMqttClient.__init__ Validation (HIGH PRIORITY)

  • File: src/nwp500/mqtt_client.py
  • What it does: Validates token validity before MQTT client creation
  • New check: Rejects MQTT client creation if tokens are stale/expired
  • Error message: Guides users to call ensure_valid_token() or re_authenticate()
  • Benefit: Prevents silent MQTT connection failures due to expired credentials

New validation:

if not auth_client.has_valid_tokens:
    raise MqttCredentialsError(
        "Tokens are stale/expired. "
        "Call ensure_valid_token() or re_authenticate() first."
    )

3. Add recover_connection() Helper Method (MEDIUM PRIORITY)

  • File: src/nwp500/mqtt_client.py
  • What it does:
    • Refreshes authentication tokens
    • Attempts MQTT reconnection
    • Returns boolean success status
  • Use case: Recovering from auth-related connection failures
  • Benefit: Provides explicit, documented recovery pattern

Example usage:

mqtt_client = NavienMqttClient(auth_client)
try:
    await mqtt_client.connect()
except MqttConnectionError:
    if await mqtt_client.recover_connection():
        print("Successfully recovered connection")
    else:
        print("Recovery failed, check logs")

Validation

Linting: All checks passed (ruff format + ruff check)
Type checking: No type errors found (mypy)
Tests: 127 tests passed
Custom validation: All three features verified working correctly

Why These Changes Matter

  • Fail fast: Clear errors before MQTT connection attempts instead of silent failures
  • Prevent state corruption: Block creation of MQTT clients with stale tokens
  • Document recovery pattern: Make token refresh flow explicit and discoverable
  • Help all integrations: Not just Home Assistant, but any consumer of nwp500-python

Backward Compatibility

These are additive changes with no breaking changes:

  • New property on existing class (optional to use)
  • Enhanced validation (stricter, catches problematic scenarios early)
  • New public method (optional to use)

Files Changed

  • src/nwp500/auth.py: Added has_valid_tokens property
  • src/nwp500/mqtt_client.py: Enhanced init validation + added recover_connection() method

Related Issues

Addresses concerns about token expiration handling and silent MQTT connection failures.

@eman eman requested a review from Copilot December 17, 2025 19:17
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds token validation enhancements to prevent silent failures from stale authentication credentials. The changes introduce pre-flight validation checks and a recovery mechanism for MQTT connections.

Key changes:

  • Added has_valid_tokens property to validate both JWT and AWS credentials before operations
  • Enhanced MQTT client initialization to reject creation with expired tokens
  • Added recover_connection() method for explicit token refresh and reconnection flow

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 3 comments.

File Description
src/nwp500/auth.py Added has_valid_tokens property for combined JWT and AWS credential validation
src/nwp500/mqtt_client.py Enhanced init validation to check token validity and added recover_connection() recovery method

@eman eman force-pushed the feat/token-validation-enhancements branch 2 times, most recently from 78025fb to 4145768 Compare December 17, 2025 19:30
- Add has_valid_tokens property to NavienAuthClient
  * Checks if tokens exist AND are not expired (JWT + AWS credentials)
  * Provides pre-flight validation before token-dependent operations
  * Fails fast instead of silently accepting stale tokens

- Enhance NavienMqttClient.__init__ validation
  * Validates token validity before MQTT client creation
  * Rejects clients with stale/expired tokens
  * Clear error message guides users to refresh tokens

- Add recover_connection() helper method to NavienMqttClient
  * Refreshes tokens and attempts reconnection
  * Useful for recovering from auth-related connection failures
  * Provides explicit, documented recovery pattern

These changes improve error handling and make the library more robust
by preventing silent failures due to stale authentication credentials.
@eman eman force-pushed the feat/token-validation-enhancements branch from 4145768 to edead2a Compare December 17, 2025 19:37
@eman eman merged commit 40ad3d4 into main Dec 17, 2025
10 checks passed
@eman eman deleted the feat/token-validation-enhancements branch December 17, 2025 19:48
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