Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 18 additions & 4 deletions custom_components/hacs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from homeassistant.helpers.start import async_at_start
from homeassistant.loader import async_get_integration

from .auth import TOKEN_KEYS, GitHubTokenManager
from .base import HacsBase
from .const import DOMAIN, HACS_SYSTEM_ID, MINIMUM_HA_VERSION
from .data_client import HacsDataClient
Expand Down Expand Up @@ -77,6 +78,7 @@ async def _async_initialize_integration(
)
hacs.system.running = True
hacs.session = clientsession
hacs.auth = GitHubTokenManager(hass, config_entry, clientsession)

hacs.core.lovelace_mode = LovelaceMode.YAML
try:
Expand Down Expand Up @@ -184,7 +186,18 @@ async def async_try_startup(_=None):

async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Set up this integration using UI."""
config_entry.async_on_unload(config_entry.add_update_listener(async_reload_entry))
options = dict(config_entry.options)
configuration = {
key: value for key, value in config_entry.data.items() if key not in TOKEN_KEYS
}

async def async_entry_updated(hass: HomeAssistant, entry: ConfigEntry) -> None:
if options != entry.options or configuration != {
key: value for key, value in entry.data.items() if key not in TOKEN_KEYS
}:
await async_reload_entry(hass, entry)

config_entry.async_on_unload(config_entry.add_update_listener(async_entry_updated))
setup_result = await _async_initialize_integration(hass=hass, config_entry=config_entry)
hacs: HacsBase = hass.data[DOMAIN]
return setup_result and not hacs.system.disabled
Expand All @@ -198,6 +211,9 @@ async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->
hacs.log.warning("Pending tasks, can not unload, try again later.")
return False

if hacs.auth is not None:
await hacs.auth.async_close()

# Clear out pending queue
hacs.queue.clear()

Expand Down Expand Up @@ -228,9 +244,7 @@ async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) ->

async def async_reload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Reload the HACS config entry."""
if not await async_unload_entry(hass, config_entry):
return
await async_setup_entry(hass, config_entry)
await hass.config_entries.async_reload(config_entry.entry_id)


async def async_remove_config_entry_device(
Expand Down
173 changes: 173 additions & 0 deletions custom_components/hacs/auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""Refresh GitHub device-flow credentials."""

from __future__ import annotations

import asyncio
from collections.abc import Mapping
import time
from typing import Any

from aiogithubapi import (
GitHubAuthenticationException,
GitHubConnectionException,
GitHubException,
)
from aiohttp import ClientError, ClientSession, ClientTimeout
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Event, HomeAssistant

from .const import CLIENT_ID
from .utils.logger import LOGGER

TOKEN_ENDPOINT = "https://github.com/login/oauth/access_token"
TOKEN_KEYS = frozenset({"token", "refresh_token", "expires_at", "refresh_token_expires_at"})
REFRESH_BUFFER = 300


def token_data(response: Mapping[str, Any], requested_at: float) -> dict[str, Any]:
"""Convert OAuth lifetimes to absolute expirations without retaining response extras."""
token = response.get("access_token")
if not isinstance(token, str) or not token:
raise GitHubException("GitHub returned an invalid access token response")

data: dict[str, Any] = {"token": token}
refresh_token = response.get("refresh_token")
if refresh_token is not None:
if not isinstance(refresh_token, str) or not refresh_token:
raise GitHubException("GitHub returned an invalid refresh token response")
data["refresh_token"] = refresh_token

for lifetime_key, expiry_key in (
("expires_in", "expires_at"),
("refresh_token_expires_in", "refresh_token_expires_at"),
):
lifetime = response.get(lifetime_key)
if lifetime is None and refresh_token is None:
continue
if type(lifetime) is not int or lifetime <= 0:
raise GitHubException("GitHub returned an invalid token lifetime")
data[expiry_key] = requested_at + lifetime
return data


class GitHubTokenManager:
"""Share token rotation across HACS requests and persist renewed credentials."""

def __init__(self, hass: HomeAssistant, entry: ConfigEntry, session: ClientSession) -> None:
"""Initialize the credential manager for one config entry."""
self.hass = hass
self.entry = entry
self.session = session
self._refresh_task: asyncio.Task[str] | None = None
self._retry_at = 0.0
self._invalid_refresh_token: str | None = None
self._closed = False
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_stop)
)

async def async_get_token(self) -> str:
"""Return a usable token, refreshing near expiry when supported."""
if self._closed:
raise GitHubConnectionException("HACS is unloading")
if self._refresh_task is not None and self._refresh_task.done():
self._refresh_task = None
if self._refresh_task is not None:
return await asyncio.shield(self._refresh_task)

data = self.entry.data
now = time.time()
expires_at = data.get("expires_at")
if expires_at is None or expires_at > now + REFRESH_BUFFER:
return data["token"]
refresh_token = data.get("refresh_token")
if (
not refresh_token
or refresh_token == self._invalid_refresh_token
or data.get("refresh_token_expires_at", 0) <= now
):
raise GitHubAuthenticationException(
"GitHub credentials expired; reauthentication required"
)
if now < self._retry_at:
raise GitHubConnectionException("GitHub token refresh is temporarily unavailable")

# A caller being cancelled must not interrupt saving a single-use token's replacement.
self._refresh_task = self.hass.async_create_task(
self._async_refresh(refresh_token), "HACS OAuth token refresh"
)
return await asyncio.shield(self._refresh_task)

async def async_close(self) -> None:
"""Finish rotation before another HACS instance can start using the credential."""
self._closed = True
if self._refresh_task is not None and not self._refresh_task.done():
try:
await asyncio.shield(self._refresh_task)
except GitHubException as exception:
LOGGER.warning("GitHub token refresh failed while unloading HACS: %s", exception)

async def _async_stop(self, _event: Event) -> None:
await self.async_close()

async def _async_refresh(self, refresh_token: str) -> str:
requested_at = time.time()
try:
try:
async with self.session.post(
TOKEN_ENDPOINT,
data={
"client_id": CLIENT_ID,
"grant_type": "refresh_token",
"refresh_token": refresh_token,
},
headers={"Accept": "application/json"},
timeout=ClientTimeout(total=30),
allow_redirects=False,
) as response:
payload = await response.json()
if not isinstance(payload, dict):
raise GitHubException("GitHub returned an invalid refresh response")
if self.entry.data.get("refresh_token") != refresh_token:
raise GitHubException("GitHub credentials changed during token refresh")
if response.status < 500 and payload.get("error") in (
"bad_refresh_token",
"invalid_grant",
):
self._invalid_refresh_token = refresh_token
raise GitHubAuthenticationException(
"GitHub rejected the refresh token; reauthentication required"
)
if response.status != 200 or payload.get("error"):
raise GitHubException("GitHub token refresh failed; try again later")
except (ClientError, TimeoutError, ValueError) as exception:
raise GitHubConnectionException(
"Unable to refresh GitHub credentials"
) from exception

renewed = token_data(payload, requested_at)
if "refresh_token" not in renewed:
raise GitHubException("GitHub returned an incomplete refresh response")
# Reauthentication or removal may have happened while the exchange was in flight.
if (
self.hass.config_entries.async_get_entry(self.entry.entry_id) is not self.entry
or self.entry.data.get("refresh_token") != refresh_token
):
raise GitHubException("GitHub credentials changed during token refresh")
self.hass.config_entries.async_update_entry(
self.entry,
data={
**{
key: value
for key, value in self.entry.data.items()
if key not in TOKEN_KEYS
},
**renewed,
},
)
self._retry_at = 0
return renewed["token"]
except GitHubException:
self._retry_at = time.time() + 30
raise
20 changes: 20 additions & 0 deletions custom_components/hacs/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from homeassistant.loader import Integration
from homeassistant.util import dt

from .auth import GitHubTokenManager
from .const import DOMAIN, TV, URL_BASE
from .coordinator import HacsUpdateCoordinator
from .data_client import HacsDataClient
Expand Down Expand Up @@ -359,6 +360,7 @@ class HacsBase:
data_client: HacsDataClient | None = None
github: GitHub | None = None
githubapi: GitHubAPI | None = None
auth: GitHubTokenManager | None = None
hass: HomeAssistant | None = None
integration: Integration | None = None
queue: QueueManager | None = None
Expand Down Expand Up @@ -482,6 +484,22 @@ async def async_can_update(self) -> int:

return 0

async def async_get_github_token(self) -> str:
"""Resolve the current credential for both GitHub clients."""
if self.auth is None:
return self.configuration.token
try:
token = await self.auth.async_get_token()
except GitHubAuthenticationException:
self.disable_hacs(HacsDisabledReason.INVALID_TOKEN)
raise
self.configuration.token = token
self.github.client.token = token
self.github.client.headers["Authorization"] = f"token {token}"
# aiogithubapi has no token setter; overriding request headers loses endpoint media types.
self.githubapi._client._base_request_data.token = token
return token

async def async_github_api_method(
self,
method: Callable[[], Awaitable[TV]],
Expand All @@ -493,6 +511,8 @@ async def async_github_api_method(
_exception = None

try:
if self.auth is not None:
await self.async_get_github_token()
return await method(*args, **kwargs)
Comment on lines +514 to 516
except GitHubAuthenticationException as exception:
self.disable_hacs(HacsDisabledReason.INVALID_TOKEN)
Expand Down
22 changes: 17 additions & 5 deletions custom_components/hacs/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
from contextlib import suppress
import time
from typing import TYPE_CHECKING

from aiogithubapi import (
Expand All @@ -22,6 +23,7 @@
from homeassistant.loader import async_get_integration
import voluptuous as vol

from .auth import TOKEN_KEYS, token_data
from .base import HacsBase
from .const import CLIENT_ID, DOMAIN, LOCALE, MINIMUM_HA_VERSION
from .utils.configuration_schema import (
Expand All @@ -48,6 +50,7 @@ class HacsFlowHandler(ConfigFlow, domain=DOMAIN):
_registration: GitHubLoginDeviceModel | None = None
_activation: GitHubLoginOauthModel | None = None
_reauth: bool = False
_token_data: dict | None = None

def __init__(self) -> None:
"""Initialize."""
Expand Down Expand Up @@ -79,8 +82,11 @@ async def async_step_device(self, _user_input):

async def _wait_for_activation() -> None:
try:
requested_at = time.time()
response = await self.device.activation(device_code=self._registration.device_code)
self._activation = response.data
# aiogithubapi's OAuth model retains expiry fields only in its raw response.
self._token_data = token_data(response.data._raw_data, requested_at)
finally:

async def _progress():
Expand All @@ -95,7 +101,7 @@ async def _progress():
**{"client_name": f"HACS/{integration.version}"},
)
try:
response = await self.device.register()
response = await self.device.register(scope="offline_access")
self._registration = response.data
except GitHubException as exception:
LOGGER.exception(exception)
Expand Down Expand Up @@ -152,16 +158,22 @@ async def async_step_device_done(self, user_input: dict[str, bool] | None = None
if self._reauth:
existing_entry = self.hass.config_entries.async_get_entry(self.context["entry_id"])
self.hass.config_entries.async_update_entry(
existing_entry, data={**existing_entry.data, "token": self._activation.access_token}
existing_entry,
data={
**{
key: value
for key, value in existing_entry.data.items()
if key not in TOKEN_KEYS
},
**self._token_data,
},
)
await self.hass.config_entries.async_reload(existing_entry.entry_id)
return self.async_abort(reason="reauth_successful")

return self.async_create_entry(
title="",
data={
"token": self._activation.access_token,
},
data=self._token_data,
options={
"experimental": True,
},
Expand Down
7 changes: 4 additions & 3 deletions custom_components/hacs/diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from .base import HacsBase
from .const import DOMAIN
from .exceptions import HacsException


async def async_get_config_entry_diagnostics(
Expand Down Expand Up @@ -72,9 +73,9 @@ async def async_get_config_entry_diagnostics(
)

try:
rate_limit_response = await hacs.githubapi.rate_limit()
rate_limit_response = await hacs.async_github_api_method(hacs.githubapi.rate_limit)
data["rate_limit"] = rate_limit_response.data.as_dict
except GitHubException as exception:
except (GitHubException, HacsException) as exception:
data["rate_limit"] = str(exception)

return async_redact_data(data, ("token",))
return async_redact_data(data, ("token", "refresh_token"))
1 change: 1 addition & 0 deletions custom_components/hacs/repositories/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,7 @@ async def async_get_legacy_repository_object(
) -> tuple[AIOGitHubAPIRepository, Any | None]:
"""Return a repository object."""
try:
await self.hacs.async_get_github_token()
repository = await self.hacs.github.get_repo(self.data.full_name, etag)
return repository, self.hacs.github.client.last_response.etag
except AIOGitHubAPINotModifiedException as exception:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/hacs/system_health.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async def system_health_info(hass: HomeAssistant) -> dict[str, Any]:
return {"Disabled": "HACS is not loaded, but HA still requests this information..."}

hacs: HacsBase = hass.data[DOMAIN]
response = await hacs.githubapi.rate_limit()
response = await hacs.async_github_api_method(hacs.githubapi.rate_limit)

data = {
"GitHub API": system_health.async_check_can_reach_url(hass, BASE_API_URL, GITHUB_STATUS),
Expand Down
Loading