alandtse / tesla

Tesla custom integration for Home Assistant. This requires a refresh token be generated by third-party apps to login.
Apache License 2.0
555 stars 99 forks source link

Unable to refresh sso oauth token after restart my home assistant #941

Open florianfish opened 2 months ago

florianfish commented 2 months ago

Is there an existing issue for this?

I have read about the Fleet API and understand I may need to use it

Version of the Tesla component

3.20.5

Version of the Tesla car software

2024.8.9

Model

Model 3

Current Behavior

Everything works, but if I restart home assistant, the proxy launches fine but I have a disconnection alert and my entities linked to my vehicle no longer exist.

Expected Behavior

The token appears to still be valid. When I regenerate a token via the proxy and restart the configuration it works (but not necessarily on the first try)

Debug logs

2024-04-12 16:37:55.774 WARNING (SyncWorker_1) [homeassistant.loader] We found a custom integration hacs which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant
2024-04-12 16:37:55.776 WARNING (SyncWorker_1) [homeassistant.loader] We found a custom integration tesla_custom which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant
2024-04-12 16:37:59.856 WARNING (MainThread) [homeassistant.helpers.frame] Detected that custom integration 'hacs' accesses hass.components.frontend. This is deprecated and will stop working in Home Assistant 2024.9, it should be updated to import functions used from frontend directly at custom_components/hacs/frontend.py, line 68: hass.components.frontend.async_register_built_in_panel(, please create a bug report at https://github.com/hacs/integration/issues
2024-04-12 16:38:32.025 WARNING (zeroconf-ServiceBrowser-_googlecast._tcp-111) [pychromecast.dial] Failed to determine cast type for host <unknown> (<urlopen error _ssl.c:983: The handshake operation timed out>) (services:{MDNSServiceInfo(name='Pioneer-VSX-832-2eed9b759085b44e4e932f09d32065f7._googlecast._tcp.local.')})
2024-04-12 16:41:14.128 ERROR (MainThread) [homeassistant.config_entries] Error setting up entry florian@domain.com for tesla_custom
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/config_entries.py", line 551, in async_setup
    result = await component.async_setup_entry(hass, self)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/tesla_custom/__init__.py", line 254, in async_setup_entry
    cars = await controller.generate_car_objects(wake_if_asleep=wake_if_asleep)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 394, in generate_car_objects
    self._vehicle_data[vin] = await self.get_vehicle_data(
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 325, in get_vehicle_data
    await self.api(
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 1348, in api
    await self.wake_up(car_id=car_id)
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 486, in wake_up
    response = await self.get_vehicle_summary(vin=car_vin)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 343, in get_vehicle_summary
    await self.api(
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 1375, in api
    return await self.__post_with_retries_except_unavailable(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/_asyncio.py", line 88, in async_wrapped
    return await fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/_asyncio.py", line 47, in __call__
    do = self.iter(retry_state=retry_state)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/tenacity/__init__.py", line 314, in iter
    return fut.result()
           ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 449, in result
    return self.__get_result()
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/concurrent/futures/_base.py", line 401, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.12/site-packages/tenacity/_asyncio.py", line 50, in __call__
    result = await fn(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/controller.py", line 1407, in __post_with_retries_except_unavailable
    return await self.__connection.post(command, method=method, data=data, url=url)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/connection.py", line 166, in post
    return await self.__open(url, method=method, headers=self.head, data=data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/teslajsonpy/connection.py", line 207, in __open
    resp: httpx.Response = await getattr(self.websession, method)(
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1801, in get
    return await self.request(
           ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1574, in request
    return await self.send(request, auth=auth, follow_redirects=follow_redirects)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1661, in send
    response = await self._send_handling_auth(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1689, in _send_handling_auth
    response = await self._send_handling_redirects(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1726, in _send_handling_redirects
    response = await self._send_single_request(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_client.py", line 1763, in _send_single_request
    response = await transport.handle_async_request(request)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpx/_transports/default.py", line 373, in handle_async_request
    resp = await self._pool.handle_async_request(req)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/connection_pool.py", line 216, in handle_async_request
    raise exc from None
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/connection_pool.py", line 196, in handle_async_request
    response = await connection.handle_async_request(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/connection.py", line 101, in handle_async_request
    return await self._connection.handle_async_request(request)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/http11.py", line 143, in handle_async_request
    raise exc
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/http11.py", line 113, in handle_async_request
    ) = await self._receive_response_headers(**kwargs)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/http11.py", line 186, in _receive_response_headers
    event = await self._receive_event(timeout=timeout)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_async/http11.py", line 224, in _receive_event
    data = await self._network_stream.read(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/httpcore/_backends/anyio.py", line 34, in read
    return await self._stream.receive(max_bytes=max_bytes)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/streams/tls.py", line 205, in receive
    data = await self._call_sslobject_method(self._ssl_object.read, max_bytes)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/streams/tls.py", line 147, in _call_sslobject_method
    data = await self.transport_stream.receive()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 1133, in receive
    await self._protocol.read_event.wait()
  File "/usr/local/lib/python3.12/asyncio/locks.py", line 212, in wait
    await fut
asyncio.exceptions.CancelledError
2024-04-12 16:41:49.443 DEBUG (MainThread) [custom_components.tesla_custom.config_flow] Running in supervised environment
2024-04-12 16:41:49.542 DEBUG (MainThread) [custom_components.tesla_custom.config_flow] Found addon: c03d64a7_tesla_http_proxy
2024-04-12 16:41:57.596 DEBUG (MainThread) [custom_components.tesla_custom.config_flow] Credentials successfully connected to the Tesla API
2024-04-12 16:41:57.598 DEBUG (MainThread) [custom_components.tesla_custom] <ssl.SSLContext object at 0xffffb531dcd0>
2024-04-12 16:41:57.647 DEBUG (MainThread) [teslajsonpy.controller] 552 endpoints loaded
2024-04-12 16:41:57.648 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:18:03
2024-04-12 16:41:57.648 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:41:57.649 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:41:57.982 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:41:57.983 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': '4f3b29e2-f57b-4adb-8372-3bb683d235e6-1712932917851'}
2024-04-12 16:41:59.636 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:18:01
2024-04-12 16:41:59.636 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:41:59.636 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:41:59.951 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:41:59.951 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': '628612e4-d2a6-4351-90fa-6bb16fa5f689-1712932919841'}
2024-04-12 16:42:02.493 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:17:58
2024-04-12 16:42:02.493 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:42:02.494 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:42:02.865 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:42:02.865 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': '89f3a5aa-b7c2-4d18-b44d-9d54def24a81-1712932922689'}
2024-04-12 16:42:07.510 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:17:53
2024-04-12 16:42:07.510 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:42:07.511 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:42:07.878 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:42:07.878 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': 'fa866dd9-1e0b-47c0-a1ee-8b11a5b8d760-1712932927740'}
2024-04-12 16:42:12.650 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:17:48
2024-04-12 16:42:12.651 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:42:12.651 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:42:13.156 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:42:13.156 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': '865ca128-0871-4d97-aff5-3dd94d71a73b-1712932933046'}
2024-04-12 16:42:13.157 WARNING (MainThread) [homeassistant.config_entries] Config entry 'florian@domain.com' for tesla_custom integration could not authenticate
2024-04-12 16:42:20.364 DEBUG (MainThread) [custom_components.tesla_custom] <ssl.SSLContext object at 0xffffb531dcd0>
2024-04-12 16:42:20.414 DEBUG (MainThread) [teslajsonpy.controller] 552 endpoints loaded
2024-04-12 16:42:20.414 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19826 days, 7:17:40
2024-04-12 16:42:20.414 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-04-12 16:42:20.414 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-04-12 16:42:20.720 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-04-12 16:42:20.720 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'Login required', 'referenceID': '923151d9-18f6-4434-a632-d930b039879a-1712932940602'}

Anything else?

No response

baylanger commented 2 months ago

I noticed as well on HA restart the integration fails claiming the token expired.

“ Authentication expired for ….@abc.xxx “

Reconfiguring with the same refresh token fixes the issue, it hasn’t expired.

baylanger commented 2 months ago

Well after doing the reconfigure I mentioned above, somehow in the log this pops up:

2024-04-12 11:04:25.101 WARNING (MainThread) [homeassistant.config_entries] Config entry '...@abc.xxx' for tesla_custom integration could not authenticate

In the UI it shows Tesla Custom Integration -> Re-authentication was successful

Navigating to the Tesla integration, even if the above says successful there appears to be a problem:

2024-04-12_11-07-47
llamafilm commented 2 months ago

The Re-authentication was successful message in the UI cannot be trusted (since the Fleet API update). Something is wrong with the config flow code and I don’t know how to fix it.

L2v2P commented 2 months ago

I would like to kindly request a clarification on this. I have a 2018 MX, so I don't need the Fleet API, correct? At the same time there is an issue with the 3.20.x version that breaks the Owner API for my car. Is this also correct? If so, can I downgrade to 3.19.x to get things working again? If so, how do I do this? From what I can tell I can only downgrade to 3.20.2 or later. Thanks for any clarification.

SamMousa commented 2 months ago

For me it worked using the browser extension to get a new refresh token.

darek-margas commented 1 month ago

I am getting the same. It did work with old API but never worked with fleet API. When I set this up, the below is what I get:

`2024-05-10 15:56:08.927 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19854 days, 8:03:52

2024-05-10 15:56:08.927 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected

2024-05-10 15:56:08.927 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token

2024-05-10 15:56:09.735 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token

2024-05-10 15:56:09.735 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'The refresh_token is invalid', 'referenceID': 'aa3f3b29-3c3a-4303-ba79-951f81dd0125-1715320569583. For more information, visit: https://developer.tesla.com/docs/fleet-api#help-and-support'} ` It does not matter how many times I get fresh refresh token, it is always the same. With expiration in nearly 20,000 days. Uninstall/reinstall/etc does not change it. I use iphone app to get token but the one obtained by add-on gave same result.

nickshine commented 1 month ago

I have run in to this issue as well.

2024-05-26 21:26:09.658 DEBUG (MainThread) [teslajsonpy.connection] Successfully refreshed oauth
2024-05-26 21:26:09.658 DEBUG (MainThread) [teslajsonpy.connection] get: https://<hostname>:4430/api/1/products {}
2024-05-26 21:26:11.607 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in 7:59:58
...
2024-05-26 21:26:29.671 DEBUG (MainThread) [teslajsonpy.controller] 552 endpoints loaded
2024-05-26 21:26:29.672 DEBUG (MainThread) [teslajsonpy.connection] Token expiration in -19870 days, 2:33:31
2024-05-26 21:26:29.672 DEBUG (MainThread) [teslajsonpy.connection] Oauth expiration detected
2024-05-26 21:26:29.672 DEBUG (MainThread) [teslajsonpy.connection] Refreshing access token with refresh_token
2024-05-26 21:26:29.890 DEBUG (MainThread) [teslajsonpy.connection] Unable to refresh sso oauth token
2024-05-26 21:26:29.890 DEBUG (MainThread) [teslajsonpy.connection] Auth returned {'error': 'login_required', 'error_description': 'The refresh_token is invalid', 'referenceID': '31972244-7547-4273-ac31-55bf00327e42-1716776789821. For more information, visit: https://developer.tesla.com/docs/fleet-api#help-and-support'}

I wonder if it has to do with this token behavior change from Tesla back in February:

2024-02-01: Auth Access token policy change As part of a security improvement, the acquisition of a new Refresh token will now render the user’s previous Refresh token and its associated Access tokens invalid.

https://github.com/teslamotors/vehicle-command/issues/160

Discussion on this here - https://github.com/alandtse/tesla/discussions/918

I do have two "products" returned from the api/1/products api call, a vehicle and a wall connector. I wonder if that is causing the double refresh.

craigrouse commented 3 weeks ago

I am experiencing this issue too, and my workaround was to switch back to the last known working version - 3.19.11. Every time a new version has been released, I've upgraded, and experienced the issue again, and rolled back. I couldn't see anything obvious in the code that might cause it, so perhaps it's an issue in the underlying python library - teslajsonpy? @alandtse do you have any ideas what might be causing this?

Lenbok commented 1 week ago

I'm getting the same issue. @craigrouse How does one install that older version? The redownload option in HACS doesn't go that far back.

craigrouse commented 1 week ago

@Lenbok go to releases on GitHub and download the zip file of that release. Take the contents of the file, and overwrite the files in the custom_components/tesla_custom directory. Restart HA and you'll be running the old version. It's easier to do this if you have the SMB add-on for HA so you can connect to it from another machine on your network. That said, I'm migrating to Teslemetry, which has a small cost, but is now a core HA component and uses the Tesla Fleet API without you having to host your own proxy. I'm impressed so far - everything works nicely.

Lenbok commented 1 week ago

@craigrouse Thanks, I've managed to downgrade and it's authenticating fine now. I may have to bump up a version to where support for the Fleet API was added, but at least for now I have the telemetry info.

It definitely smells like a bug in teslajsonpy given that it's error messages are reporting tokens having expired around 19870 days ago (that's over 50 years).

Peke140 commented 1 week ago

Found a solution.

https://github.com/llamafilm/tesla-http-proxy-addon/discussions/111

You should use the token generated from het http proxy plugin not from somewhere else.

nickshine commented 1 week ago

I should note that https://github.com/alandtse/tesla/issues/941#issuecomment-2132565548 is using the token generated from the temporary http proxy UI.

rubin110 commented 14 hours ago

Suppose I should actually post here. I'm hitting this issue now. I don't know if it was today or yesterday, but the integration is reporting an issue with authentication. When I provide all of the required fleet info, I see Token expiration in -19910 days, 22:49:49 errors. I am using the refresh token provided by the http proxy.

darek-margas commented 13 hours ago

As I mentioned above, I had the same, nothing helped, including downgrade, uninstalled it and watching here if anyone figures it out.