OAuth 2.1 Temporary HA Credentials Keyed by client_id Instead of Authorization Code Enables Cross-Session LLAT Swap / Race Condition
Description
Patches and workarounds
Fixed in homeassistant-ai/ha-mcp#2837: the token submitted on the consent form is bound to the authorization code it mints and consumed with it, and the consent POST enforces the transaction expiry.
ha-mcp(stable, PyPI and theha-mcpDocker image): no fixed release yet. The fix ships in the next stable release, 9.0.0.ha-mcp-dev(dev channel, PyPI and the dev Docker image): fixed in 9.0.0.dev3159.
Workaround for ha-mcp users running the ha-mcp-oauth entrypoint: switch to ha-mcp-dev 9.0.0.dev3159 or later, or wait for 9.0.0. The standard (ha-mcp-web), OIDC, app (add-on) and in-process component modes are not affected.
---
Summary
In ha-mcp-oauth mode (src/ha_mcp/auth/provider.py), HomeAssistantOAuthProvider temporarily stores the user's submitted Home Assistant Long-Lived Access Token (ha_token) in self.ha_credentials between POST /consent (_consent_post) and POST /token (exchange_authorization_code).
However, self.ha_credentials is keyed by client_id (self.ha_credentials[client_id]) rather than by the one-time auth_code_value generated in _consent_post (src/ha_mcp/auth/provider.py:171, 753, 830, 856). Additionally, _consent_post does not validate the 300-second expiration window (pending["created_at"]) that _consent_get checks (src/ha_mcp/auth/provider.py:678-686 vs 726-735).
Because ha_credentials is bound to client_id instead of the specific AuthorizationCode (and its PKCE code_challenge), two concurrent or overlapping authorization flows sharing the same client_id overwrite self.ha_credentials[client_id], causing exchange_authorization_code() to encode one session's ha_token into another session's OAuth token response.
---
Affected Code (src/ha_mcp/auth/provider.py)
- Credential storage keyed by
client_idin_consent_post(lines 752–778):
# Store credentials (no server-side validation - the token will be
# validated on first actual API call to the configured HA instance)
client_id = pending["client_id"]
self.ha_credentials[client_id] = HomeAssistantCredentials(
ha_token=str(ha_token),
)
logger.info(f"Stored HA credentials for client {client_id}")
# Generate authorization code
auth_code_value = f"ha_auth_code_{secrets.token_hex(16)}"
...
self.auth_codes[auth_code_value] = auth_code- Credential lookup and deletion by
client_idinexchange_authorization_code(lines 829–856):
# Get HA credentials for this client to encode in token
ha_credentials = self.ha_credentials.get(client.client_id)
if not ha_credentials:
raise TokenError(
"invalid_client",
f"No Home Assistant credentials found for client {client.client_id}",
)
...
access_token_value = self._encode_token(
ha_credentials.ha_token,
token_type="access",
expires_at=access_token_expires_at,
)
...
# Clean up temporary credentials (no longer needed after token issued)
self.ha_credentials.pop(client.client_id, None)- Missing expiry check in
_consent_post(lines 726–735):
Unlike _consent_get (which checks if time.time() - pending["created_at"] > 300:), _consent_post looks up self.pending_authorizations.get(str(txn_id)) without checking pending["created_at"].
---
Reproduction & Impact Scenarios
Scenario 1: Multi-User / Concurrent Consent Flows on a Shared OAuth Client
Per SECURITY.md ("Per-user Home Assistant credentials exist only in OAuth mode"), different users authenticating through the same registered OAuth client (same client_id) are intended to receive tokens bound to their own respective Home Assistant LLATs.
- Session A initiates
GET /authorizeforclient_id(with PKCEchallenge_A) and submitsPOST /consentwithha_token = "LLAT_USER_A".
- Server sets
self.ha_credentials[client_id] = HomeAssistantCredentials("LLAT_USER_A")and issuescode_A.
- Before
code_Ais exchanged atPOST /token(or if Session A's redirect is slow/interrupted), Session B submitsPOST /consentfor the sameclient_id(with PKCEchallenge_B) andha_token = "LLAT_USER_B".
- Server overwrites
self.ha_credentials[client_id] = HomeAssistantCredentials("LLAT_USER_B")and issuescode_B.
- Session A completes
POST /tokenpresentingcode_Aandverifier_A.
TokenHandlerverifiescode_Aagainstchallenge_Aand callsexchange_authorization_code(client, code_A).exchange_authorization_codereadsself.ha_credentials.get(client.client_id)— which now holds"LLAT_USER_B"— and returns statelessaccess_tokenandrefresh_tokencontainingLLAT_USER_Bto Session A.self.ha_credentials.pop(client.client_id, None)removes the entry, so Session B's subsequentPOST /tokenwithcode_Bfails withNo Home Assistant credentials found for client ....
Scenario 2: Unauthenticated Pre-Minted Authorization Code + Race Condition on Public Clients
For public PKCE clients (token_endpoint_auth_method: "none", supported for connectors such as Claude.ai/ChatGPT):
- Notice that
GET /authorizeredirects to/consent?txn_id=...onha-mcpitself (not toredirect_uri), andPOST /consentdoes not validateha_tokenagainst Home Assistant before issuingauth_code_valueand returning an HTTP303redirect (Location: <redirect_uri>?code=ha_auth_code_...). - Any party who knows a registered public
client_idand its registeredredirect_urican callGET /authorize(with their own PKCEcode_challenge) followed byPOST /consent(with a dummyha_token, without following redirects) and read a validcode_attackerdirectly from the303response'sLocationheader — without needing to controlredirect_uri. - Because
code_attackerremains valid for 5 minutes (AUTH_CODE_EXPIRY_SECONDS = 300), if a victim subsequently submitsPOST /consentfor the sameclient_idwith their realLLAT,self.ha_credentials[client_id]is overwritten with the victim'sLLAT. If the attacker redeemscode_attacker(with their owncode_verifier) atPOST /tokenbefore the legitimate client redeems the victim's code (or if the victim's callback fails to complete), the attacker receives anaccess_tokenandrefresh_tokenencoding the victim'sLLAT.
---
Severity Assessment
We assess this as Medium severity because:
- It only affects deployments explicitly running the beta
ha-mcp-oauthentrypoint. - Exploiting it maliciously requires knowing a registered public
client_id(and itsredirect_uri) and winning the race window between the victim'sPOST /consentand the legitimate client'sPOST /tokencall (or triggering a failed callback on the victim's redirect).
---
Recommended Fix
- Bind
ha_credentialstoauth_code_value(or attachha_tokentoAuthorizationCode) instead ofclient_id:
- In
_consent_post(src/ha_mcp/auth/provider.py:752-778), generateauth_code_valuefirst and storeself.ha_credentials[auth_code_value] = HomeAssistantCredentials(ha_token=str(ha_token)). - In
exchange_authorization_code(src/ha_mcp/auth/provider.py:830-856), retrieve and pop credentials byauthorization_code.code:ha_credentials = self.ha_credentials.pop(authorization_code.code, None). - In
load_authorization_code(src/ha_mcp/auth/provider.py:808-810), also clean upself.ha_credentials.pop(authorization_code, None)when an expired code is evicted.
- Enforce
created_atexpiration in_consent_post:
- Mirror the
if time.time() - pending["created_at"] > 300:check from_consent_getinside_consent_postbefore accepting the form submission.