Skip to content

fix: fallback for self-signed unraid certs#184

Merged
ruaan-deysel merged 4 commits intoruaan-deysel:mainfrom
Snuffy2:Fix-Verify-SSL
Mar 7, 2026
Merged

fix: fallback for self-signed unraid certs#184
ruaan-deysel merged 4 commits intoruaan-deysel:mainfrom
Snuffy2:Fix-Verify-SSL

Conversation

@Snuffy2
Copy link
Contributor

@Snuffy2 Snuffy2 commented Mar 6, 2026

Description

This pull request refactors SSL certificate error handling in the Unraid integration's config flow, introducing a dedicated exception for SSL certificate verification failures and improving the retry logic for self-signed certificates. It also ensures that the CONF_SSL flag is correctly set and updated in configuration entries during reauth and reconfigure flows. Comprehensive tests have been added and updated to verify the new behavior.

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • 🔧 Configuration change
  • ♻️ Code refactoring (no functional changes)
  • ⚡ Performance improvement
  • ✅ Test update

Related Issue

Fixes #170

Changes Made

Improved SSL error handling and retry logic

  • Introduced a new SSLCertificateError exception to distinguish SSL certificate verification failures from generic connection errors, and updated error handling throughout the config flow to use this exception. [1] [2] [3]
  • Refactored the connection test logic to retry with verify_ssl=False only when an SSL certificate error is detected, ensuring that self-signed certificates are handled gracefully and avoiding unnecessary retries for other connection errors. [1] [2]

Configuration entry updates

  • Updated reauth and reconfigure flows to merge and update the CONF_SSL flag in config entries based on the outcome of the connection test, ensuring that the SSL verification status is accurately reflected in the entry data. [1] [2]

Test enhancements

  • Added and updated tests to verify the new SSL error handling, including retry logic, correct closure of API clients, and proper updating of the CONF_SSL flag during reauth and reconfigure flows. Tests now distinguish between SSL certificate errors and other connection errors. [1] [2] [3] [4]
  • Updated test imports and exception usage to reflect the new SSLCertificateError class. [1] [2]

Testing

  • Code lints successfully (./scripts/lint)
  • Tests pass (pytest)
  • Tested in development environment (./scripts/develop)
  • Manual testing completed

Checklist

  • This PR addresses only one issue or feature (not multiple unrelated changes)
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have updated the documentation accordingly
  • My changes generate no new warnings or errors
  • I have added tests that prove my fix is effective or that my feature works
  • All new and existing tests pass

Screenshots (if applicable)

Additional Context


📌 Reminder: Please keep pull requests small and focused on a single issue or feature. This makes review and testing much easier! If you have multiple changes, please submit separate PRs. See CONTRIBUTING.md for more details.

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved SSL certificate error handling with automatic fallback retry mechanism that disables SSL verification if initial connection fails.
    • Enhanced exception mapping to properly distinguish SSL certificate verification failures from other connection errors.
  • New Features

    • Introduced dedicated exception type for SSL certificate errors, providing clearer error reporting and handling.
  • Tests

    • Expanded test coverage for SSL retry scenarios, legacy entries, and error handling across various connection and authentication failures.

Copilot AI review requested due to automatic review settings March 6, 2026 16:22
@coderabbitai
Copy link

coderabbitai bot commented Mar 6, 2026

Warning

Rate limit exceeded

@ruaan-deysel has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 23 minutes and 12 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 24b98a34-8a8b-41c4-84d8-4ef4322d06fc

📥 Commits

Reviewing files that changed from the base of the PR and between c05dfbd and 9cc3f3b.

📒 Files selected for processing (2)
  • custom_components/unraid/config_flow.py
  • tests/test_config_flow.py
📝 Walkthrough

Walkthrough

Implement SSL certificate error handling with automatic fallback to unverified SSL for Unraid connections. Introduces new SSLCertificateError exception and updates config flow to retry connections with verify_ssl=False when certificate validation fails, tracking SSL state throughout setup and reauth flows.

Changes

Cohort / File(s) Summary
SSL Error Handling & Exception Mapping
custom_components/unraid/config_flow.py
Introduces SSLCertificateError exception class as CannotConnectError subclass. Maps SSL-related errors (UnraidSSLError, ClientSSLError) to new exception. Implements fallback retry logic in _test_connection to retry with verify_ssl=False on certificate errors, updating internal _use_ssl state on success. Updates reauth and reconfigure flows to merge SSL flag (CONF_SSL) derived from internal state.
SSL Retry Test Coverage
tests/test_config_flow.py
Adds imports for CONF_SSL and SSLCertificateError. Tracks multiple UnraidClient instances to verify both original and retry clients are created and properly closed during SSL fallback flows. Extends reauth tests to validate SSL flag presence and value for legacy entries. Adds parametrised error test cases across user, reauth, and reconfigure flows covering SSL certificate errors, timeouts, and authentication failures. Differentiates between SSL and non-SSL connection errors in retry behaviour validation.

Sequence Diagram

sequenceDiagram
    participant User
    participant ConfigFlow
    participant UnraidClient
    participant SSLHandler
    
    User->>ConfigFlow: Test connection (HTTPS with self-signed cert)
    ConfigFlow->>UnraidClient: Create client (verify_ssl=True)
    UnraidClient->>SSLHandler: Attempt connection
    SSLHandler-->>UnraidClient: SSLCertVerificationError
    UnraidClient-->>ConfigFlow: SSLCertificateError raised
    
    ConfigFlow->>ConfigFlow: Close current client
    ConfigFlow->>UnraidClient: Create new client (verify_ssl=False)
    ConfigFlow->>SSLHandler: Retry connection
    SSLHandler-->>UnraidClient: Connection successful
    UnraidClient-->>ConfigFlow: Connection confirmed
    
    ConfigFlow->>ConfigFlow: Set _use_ssl=False
    ConfigFlow->>ConfigFlow: Log successful retry
    ConfigFlow-->>User: Connection successful (SSL disabled)
Loading

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A self-signed cert caused quite a fright,
But our SSL handler set things right,
With fallback retry, no more despair,
Unraid connections float through the air,
Hopping along where certificates dare! 🔐

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarises the main change: introducing a fallback mechanism for self-signed Unraid certificates by implementing SSL error handling with retry logic.
Linked Issues check ✅ Passed The PR fully addresses issue #170 by implementing SSL certificate error handling with verify_ssl=False fallback, enabling successful connection to Unraid despite self-signed certificates.
Out of Scope Changes check ✅ Passed All changes directly relate to SSL certificate handling in the config flow and corresponding test updates; no unrelated modifications were introduced.
Docstring Coverage ✅ Passed Docstring coverage is 82.35% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📋 Issue Planner

Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).

View plan for ticket: #170

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
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 fixes a regression (issue #170) where the Unraid integration fails when Unraid's "Use SSL/TLS" setting is enabled with a self-signed certificate. The fix introduces a dedicated SSLCertificateError exception class and refactors the connection retry logic to attempt verify_ssl=False only when a certificate verification failure is specifically detected (rather than any connection error containing "ssl" in the string). It also ensures CONF_SSL is correctly persisted to config entries during reauth and reconfigure flows.

Changes:

  • Introduces SSLCertificateError as a subclass of CannotConnectError to distinguish SSL cert failures from generic connection errors, and uses it in _validate_connection exception mapping and _handle_generic_error
  • Refactors _test_connection to only retry with verify_ssl=False on SSLCertificateError (not any CannotConnectError), with a renamed fallback_client for clarity and explicit api_client.close() paths
  • Updates reauth and reconfigure flows to write CONF_SSL from self._use_ssl into the config entry data; adds corresponding tests

Reviewed changes

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

File Description
custom_components/unraid/config_flow.py New SSLCertificateError exception; refined SSL retry logic; CONF_SSL persisted in reauth/reconfigure flows
tests/test_config_flow.py New tests for SSL fallback in user/reauth flows, CONF_SSL persistence, and non-SSL no-retry behavior; asserts client closure
uv.lock Adds unraid-api 1.6.0 as a tracked dependency; bumps ruff from 0.14.14 to 0.15.0; removes three greenlet s390x wheel entries

@Snuffy2 Snuffy2 marked this pull request as ready for review March 6, 2026 16:44
Copilot AI review requested due to automatic review settings March 6, 2026 16:52
Copy link

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@custom_components/unraid/config_flow.py`:
- Around line 313-315: The current branch that raises SSLCertificateError based
on generic "ssl" or "certificate" substrings is too broad; restrict it to
certificate-verification failures only by checking for concrete verification
signals: if the exception is an instance of ssl.SSLCertVerificationError (or the
library-specific cert verification exception) or if error_str contains
verification-specific phrases such as "certificate verify failed",
"CERTIFICATE_VERIFY_FAILED", "self signed certificate", or "certificate has
expired" then raise SSLCertificateError(msg) from err; otherwise do not convert
the error to SSLCertificateError. Keep references to the existing variables and
symbol names (error_str, err, SSLCertificateError) so you update the same branch
in config_flow.py.
- Around line 420-423: The reconfigure path replaces the whole entry data with
only user_input plus CONF_SSL (merged_data) which can drop previously saved keys
like CONF_PORT; instead, build merged_data by starting from
reconfigure_entry.data (or a shallow copy) and update it with user_input and
CONF_SSL so existing persisted fields are preserved, then pass that merged_data
into self.hass.config_entries.async_update_entry (referencing reconfigure_entry,
merged_data, CONF_SSL, user_input).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ceb18c5f-8068-4b15-8f99-d36f0f1d865c

📥 Commits

Reviewing files that changed from the base of the PR and between c699079 and c05dfbd.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • custom_components/unraid/config_flow.py
  • tests/test_config_flow.py

Co-Authored-By: Copilot <175728472+Copilot@users.noreply.github.com>
Copy link
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

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

assert entry.data[CONF_API_KEY] == "new-key"
assert entry.data[CONF_SSL] is False


Copy link

Copilot AI Mar 6, 2026

Choose a reason for hiding this comment

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

There is a missing blank line between test_reconfigure_flow_updates_ssl_flag_when_cert_changes (ending at line 1258) and test_reconfigure_flow_connection_error (starting at line 1259). Python style (PEP 8) and the project's ruff configuration require two blank lines between top-level function definitions. This will likely cause a lint failure.

Suggested change

Copilot uses AI. Check for mistakes.
@ruaan-deysel ruaan-deysel merged commit fb8c423 into ruaan-deysel:main Mar 7, 2026
3 checks passed
@Snuffy2 Snuffy2 deleted the Fix-Verify-SSL branch March 7, 2026 15:06
@ruaan-deysel
Copy link
Owner

@Snuffy2 Thanks for the help and contribution. Appreciate it!

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.

[Bug]: Integration fails when Unraid "Use SSL/TLS" is enabled (self-signed cert), works when disabled

3 participants