Get_url to prefer external URL if SSL configured (#66039)

This commit is contained in:
Paulus Schoutsen 2022-02-07 15:44:02 -08:00 committed by GitHub
parent 7cc6770f83
commit 95a890c6e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 5 deletions

View File

@ -89,7 +89,7 @@ from .util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM, UnitSystem
# Typing imports that create a circular dependency
if TYPE_CHECKING:
from .auth import AuthManager
from .components.http import HomeAssistantHTTP
from .components.http import ApiConfig, HomeAssistantHTTP
from .config_entries import ConfigEntries
@ -1701,8 +1701,8 @@ class Config:
# List of loaded components
self.components: set[str] = set()
# API (HTTP) server configuration, see components.http.ApiConfig
self.api: Any | None = None
# API (HTTP) server configuration
self.api: ApiConfig | None = None
# Directory that holds the configuration
self.config_dir: str | None = None

View File

@ -41,14 +41,20 @@ def get_url(
allow_internal: bool = True,
allow_external: bool = True,
allow_cloud: bool = True,
allow_ip: bool = True,
prefer_external: bool = False,
allow_ip: bool | None = None,
prefer_external: bool | None = None,
prefer_cloud: bool = False,
) -> str:
"""Get a URL to this instance."""
if require_current_request and http.current_request.get() is None:
raise NoURLAvailableError
if prefer_external is None:
prefer_external = hass.config.api is not None and hass.config.api.use_ssl
if allow_ip is None:
allow_ip = hass.config.api is None or not hass.config.api.use_ssl
order = [TYPE_URL_INTERNAL, TYPE_URL_EXTERNAL]
if prefer_external:
order.reverse()

View File

@ -480,6 +480,12 @@ async def test_get_url(hass: HomeAssistant):
get_url(hass, prefer_external=True, allow_external=False)
== "http://example.local"
)
# Prefer external defaults to True if use_ssl=True
hass.config.api = Mock(use_ssl=True)
assert get_url(hass) == "https://example.com"
hass.config.api = Mock(use_ssl=False)
assert get_url(hass) == "http://example.local"
hass.config.api = None
with pytest.raises(NoURLAvailableError):
get_url(hass, allow_external=False, require_ssl=True)
@ -519,6 +525,19 @@ async def test_get_url(hass: HomeAssistant):
), pytest.raises(NoURLAvailableError):
_get_internal_url(hass, require_current_request=True)
# Test allow_ip defaults when SSL specified
await async_process_ha_core_config(
hass,
{"external_url": "https://1.1.1.1"},
)
assert hass.config.external_url == "https://1.1.1.1"
assert get_url(hass, allow_internal=False) == "https://1.1.1.1"
hass.config.api = Mock(use_ssl=False)
assert get_url(hass, allow_internal=False) == "https://1.1.1.1"
hass.config.api = Mock(use_ssl=True)
with pytest.raises(NoURLAvailableError):
assert get_url(hass, allow_internal=False)
async def test_get_request_host(hass: HomeAssistant):
"""Test getting the host of the current web request from the request context."""