Skip to content

fix: pre-initialize mTLS flag from stored alias to handle TLS session resumption in Wear OS onboarding#6663

Draft
smhc wants to merge 1 commit intohome-assistant:mainfrom
smhc:fix/wear-mtls-tls-session-resumption
Draft

fix: pre-initialize mTLS flag from stored alias to handle TLS session resumption in Wear OS onboarding#6663
smhc wants to merge 1 commit intohome-assistant:mainfrom
smhc:fix/wear-mtls-tls-session-resumption

Conversation

@smhc
Copy link
Copy Markdown

@smhc smhc commented Mar 31, 2026

fix: Pre-initialize mTLS flag from stored key alias to handle TLS session resumption in Wear OS onboarding

Problem

When setting up a Wear OS device through the Home Assistant phone app, the mTLS certificate
selection screen is silently skipped, causing the watch to register without a client certificate
and the server to respond with HTTP 400.

The root cause is TLS session resumption:

  1. The main HA app WebView authenticates with the server — a TLS session ticket is created.
  2. The user opens the Wear OS onboarding flow (either from the watch or via the phone app).
  3. The onboarding WebView connects to the same host; the OS TLS stack resumes the existing
    session (abbreviated handshake — no new CertificateRequest from the server).
  4. WebViewClient.onReceivedClientCertRequest() is never invoked.
  5. TLSWebViewClient.isTLSClientAuthNeeded remains false.
  6. requiredMTLS = false is passed through ConnectionNavigationEvent.Authenticated
    OnboardingNavigation skips wearMTLSScreen.
  7. The watch is registered without a cert → server returns 400 Bad Request.

This happens regardless of whether ssl_session_tickets / ssl_session_cache are disabled on
the server, because Android's Chromium network stack also maintains its own in-process TLS
session cache that persists across WebView instances.

Fix

KeyChainRepositoryImpl already persists the chosen key alias via PrefsRepository.saveKeyAlias().
We expose a new suspend fun loadAlias(): String? on the KeyChainRepository interface that reads
this persisted value without requiring load() to have been called first (i.e., it works after a
cold start or force-stop).

TLSWebViewClient gains a new suspend fun preInitializeTLSClientAuthState() that checks for a
stored alias and pre-sets isTLSClientAuthNeeded = true if one exists. This is called from
ConnectionViewModel.init before buildAuthUrl(), so the flag is correct whether or not the
subsequent WebView connection is a resumed TLS session.

Changes

File Change
common/.../data/keychain/KeyChainRepository.kt Add suspend fun loadAlias(): String? to interface
common/.../data/keychain/KeyChainRepositoryImpl.kt Implement loadAlias() via PrefsRepository
common/.../data/keychain/KeyStoreRepositoryImpl.kt Implement loadAlias() returning in-memory alias
app/.../util/TLSWebViewClient.kt Add suspend fun preInitializeTLSClientAuthState()
app/.../onboarding/connection/ConnectionViewModel.kt Call preInitializeTLSClientAuthState() in init
app/.../onboarding/connection/ConnectionViewModelTest.kt Two new tests covering pre-init behaviour

Behaviour

  • Happy path (cold start, TLS resumption): alias is stored → isTLSClientAuthNeeded = true
    before any WebView request → mTLS cert screen shown during Wear onboarding ✓
  • No cert configured: loadAlias() returns null → flag stays false → behaviour unchanged ✓
  • False positive (alias stored but server no longer requires mTLS): mTLS screen appears but
    the user can dismiss it without selecting a cert; the watch then connects without a cert, which
    succeeds against a non-requiring server ✓
  • onReceivedClientCertRequest still fires (fresh TLS handshake): callback sets the flag to
    true as before; preInitializeTLSClientAuthState() is a no-op because the flag is already
    true

Testing

  • Two new unit tests in ConnectionViewModelTest cover:
    • stored alias present → isTLSClientAuthNeeded pre-set to true
    • no stored alias → isTLSClientAuthNeeded remains false
  • All existing tests continue to pass because keyChainRepository is mockk(relaxed = true) and
    loadAlias() returns null by default.

Copilot AI review requested due to automatic review settings March 31, 2026 10:14
Copy link
Copy Markdown

@home-assistant home-assistant bot left a comment

Choose a reason for hiding this comment

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

Hello @smhc,

When attempting to inspect the commits of your pull request for CLA signature status among all authors we encountered commit(s) which were not linked to a GitHub account, thus not allowing us to determine their status(es).

The commits that are missing a linked GitHub account are the following:

Unfortunately, we are unable to accept this pull request until this situation is corrected.

Here are your options:

  1. If you had an email address set for the commit that simply wasn't linked to your GitHub account you can link that email now and it will retroactively apply to your commits. The simplest way to do this is to click the link to one of the above commits and look for a blue question mark in a blue circle in the top left. Hovering over that bubble will show you what email address you used. Clicking on that button will take you to your email address settings on GitHub. Just add the email address on that page and you're all set. GitHub has more information about this option in their help center.

  2. If you didn't use an email address at all, it was an invalid email, or it's one you can't link to your GitHub, you will need to change the authorship information of the commit and your global Git settings so this doesn't happen again going forward. GitHub provides some great instructions on how to change your authorship information in their help center.

    • If you only made a single commit you should be able to run
      git commit --amend --author="Author Name <email@address.com>"
      
      (substituting "Author Name" and "email@address.com" for your actual information) to set the authorship information.
    • If you made more than one commit and the commit with the missing authorship information is not the most recent one you have two options:
      1. You can re-create all commits missing authorship information. This is going to be the easiest solution for developers that aren't extremely confident in their Git and command line skills.
      2. You can use this script that GitHub provides to rewrite history. Please note: this should be used only if you are very confident in your abilities and understand its impacts.
    • Whichever method you choose, I will come by to re-check the pull request once you push the fixes to this branch.

We apologize for this inconvenience, especially since it usually bites new contributors to Home Assistant. We hope you understand the need for us to protect ourselves and the great community we all have built legally. The best thing to come out of this is that you only need to fix this once and it benefits the entire Home Assistant and GitHub community.

Thanks, I look forward to checking this PR again soon! ❤️

@home-assistant
Copy link
Copy Markdown

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant home-assistant bot marked this pull request as draft March 31, 2026 10:14
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 addresses a TLS session resumption issue in Wear OS onboarding where the mTLS certificate selection screen was being silently skipped. When the main Home Assistant app's WebView has an active TLS session with the server, the Wear OS onboarding WebView resumes that session rather than performing a fresh handshake. This bypass prevents the onReceivedClientCertRequest() callback from firing, leaving the mTLS requirement undetected. The solution pre-initializes the TLS client authentication flag from any previously stored certificate alias before the WebView loads, ensuring the mTLS screen is displayed regardless of TLS session resumption.

Changes:

  • Added suspend fun loadAlias(): String? to KeyChainRepository interface to load stored key alias without requiring full key material
  • Implemented loadAlias() in both KeyChainRepositoryImpl (reading from persistent prefs storage) and KeyStoreRepositoryImpl (reading from in-memory state)
  • Added suspend fun preInitializeTLSClientAuthState() to TLSWebViewClient to pre-set the mTLS flag from stored alias
  • Modified ConnectionViewModel.init() to call preInitializeTLSClientAuthState() before loading the auth URL
  • Added two unit tests verifying mTLS flag is set when alias exists and remains false when it doesn't

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated no comments.

Show a summary per file
File Description
common/.../data/keychain/KeyChainRepository.kt Added loadAlias() interface method with documentation
common/.../data/keychain/KeyChainRepositoryImpl.kt Implemented loadAlias() to read from persistent prefs and populate in-memory cache
common/.../data/keychain/KeyStoreRepositoryImpl.kt Implemented loadAlias() to return in-memory alias
app/.../util/TLSWebViewClient.kt Added preInitializeTLSClientAuthState() to pre-set flag from stored alias
app/.../onboarding/connection/ConnectionViewModel.kt Integrated pre-initialization call in init block before URL loading
app/.../onboarding/connection/ConnectionViewModelTest.kt Added two tests covering stored and missing alias scenarios

@smhc smhc force-pushed the fix/wear-mtls-tls-session-resumption branch from 2df4c5c to a1cb322 Compare March 31, 2026 10:20
Copy link
Copy Markdown

@home-assistant home-assistant bot left a comment

Choose a reason for hiding this comment

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

Hi @smhc

It seems you haven't yet signed a CLA. Please do so here.

Once you do that we will be able to review and accept this pull request.

Thanks!

@smhc smhc marked this pull request as ready for review March 31, 2026 10:23
@home-assistant home-assistant bot dismissed stale reviews from themself March 31, 2026 10:23

Stale

…session resumption in Wear OS onboarding

When setting up a Wear OS device the mTLS certificate-selection screen
was silently skipped if TLS session resumption occurred, causing the
watch to register without a client certificate and the server to return
HTTP 400.

Root cause: isTLSClientAuthNeeded in TLSWebViewClient is only set inside
onReceivedClientCertRequest. When the onboarding WebView reuses the main
app's existing TLS session (abbreviated handshake), the server never
issues a new CertificateRequest so the callback never fires — even with
ssl_session_tickets disabled on the server, because Android's Chromium
network stack maintains its own in-process TLS session cache.

Fix: add TLSWebViewClient.preInitializeTLSClientAuthState() which checks
whether a private key is already loaded in KeyChainRepository (non-null
getPrivateKey()). A non-null key means the phone is currently connected
to an mTLS-protected instance, so isTLSClientAuthNeeded is pre-set to
true before the WebView starts loading. If the app was force-stopped
first, in-memory state is cleared and no TLS session can be resumed, so
onReceivedClientCertRequest fires naturally on the fresh handshake.

ConnectionViewModel.init calls preInitializeTLSClientAuthState() before
emitting the auth URL so the navigation layer sees the correct value.

Also adds two unit tests to ConnectionViewModelTest covering the
in-memory key present and absent cases.
@smhc smhc force-pushed the fix/wear-mtls-tls-session-resumption branch from a1cb322 to 817e33a Compare March 31, 2026 10:41
@smhc
Copy link
Copy Markdown
Author

smhc commented Mar 31, 2026

Known limitation — no host comparison

The current fix uses keyChainRepository.getPrivateKey() != null to detect whether the phone is connected to an mTLS-protected instance. This is an in-memory check and does not compare the Wear onboarding target host against the host for which the certificate was loaded.

Potential false positive: if a user has multiple HA servers configured where Server A requires mTLS and Server B does not, and the phone is currently connected to Server A (key loaded in memory) while setting up the watch for Server B, the mTLS certificate selection screen will appear unnecessarily during Wear onboarding.

In practice this is a very advanced scenario — most users have a single HA instance, and anyone running split mTLS/non-mTLS multi-server setups is technical enough to recognise the cert selection screen and dismiss it without selecting a certificate, allowing the watch to onboard against Server B without a cert as expected.

A more precise fix would store the host from request.host inside onReceivedClientCertRequest in the shared KeyChainRepository singleton and compare it against rawUrl.host in preInitializeTLSClientAuthState. Happy to add that if reviewers feel it is warranted.

Comment on lines +67 to +69
if (!isTLSClientAuthNeeded) {
isTLSClientAuthNeeded = keyChainRepository.getPrivateKey() != null
}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A more precise fix would store the host from request.host inside onReceivedClientCertRequest in the shared KeyChainRepository singleton and compare it against rawUrl.host in preInitializeTLSClientAuthState. Happy to add that if reviewers feel it is warranted.

Indeed, if I'm not wrong it means that if I onboard a new server that is not using mTLS but one of my server has mTLS I'm going to be forced to pick a cert for the wear where I might have none. It shouldn't be an issue to give a "fake" cert but still a pretty bad experience.

We could try to store the host information indeed.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I had assumed the cert picker in the UI was optional even if the cert was considered "mandatory". I must admit I didn't check or I was remembering an old implementation.

It might want it to be optional anyway, in the event the server specifies it is optional. Although I believe at the moment it only presents this screen if it's mandatory (and if you don't hit this bug).

We could alternatively set a flag stating that it is "probably/optionally required" and let the user decide whether to provide one or not.

but one of my server has mTLS

I understand this will only be the case if the server you are currently logged into in the phone app requires mTLS. Note prior to this change it wouldn't work at all in this scenario if the server you are onboarding the watch to also requires mTLS (most common case). You get a "could not register watch" toast and no further info.

I can add the host matching - but am a bit concerned about matching domain suffixes, http vs https and so on.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I can add the host matching - but am a bit concerned about matching domain suffixes, http vs https and so on.

What is your concern?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I just meant matching myhainstance vs mhainstance.lan vs http://127.0.01 vs https://localhost etc, it's not a simple strcmp. I guess the certificate CNAME has to match anyway.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We have some utils already for that in the repo like

fun URL.baseIsEqual(other: URL?): Boolean = if (other == null) {
or
fun HttpUrl.hasSameOrigin(other: HttpUrl): Boolean {

@TimoPtr TimoPtr marked this pull request as draft March 31, 2026 12:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants