feat: normalize base_url and strip credentials from logs

New url_util.py (deliberately separate from the vendored files, so a
future upstream re-sync never conflicts with it): normalize_base_url
strips whitespace/trailing slashes and rejects non-http(s) or hostless
URLs; sanitize_url_for_logging masks embedded basic-auth credentials
for Task 7's discovery logging.

Wires normalization into config_flow.validate_input before the client
is built, with a new invalid_base_url form error.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01739Seac5eMAfNwFeiwV5r4
This commit is contained in:
Adam SmithandClaude Sonnet 5 committed 2026-09-17 17:53:10 -04:00
1 parent 564c52159f
commit 914c89dc6b
4 files changed
+86

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
"""URL hygiene: normalize input, never log credentials."""
import pytest
from custom_components.openai_compatible.url_util import (
InvalidBaseURL,
normalize_base_url,
sanitize_url_for_logging,
)
@pytest.mark.parametrize(
("raw", "expected"),
[
("http://192.0.2.10:4000/v1", "http://192.0.2.10:4000/v1"),
("http://192.0.2.10:4000/v1/", "http://192.0.2.10:4000/v1"),
(" https://api.openai.com/v1 ", "https://api.openai.com/v1"),
("http://host:4000/v1///", "http://host:4000/v1"),
],
)
def test_normalize(raw, expected):
assert normalize_base_url(raw) == expected
@pytest.mark.parametrize("raw", ["ftp://host/v1", "not-a-url", "", " "])
def test_normalize_rejects(raw):
with pytest.raises(InvalidBaseURL):
normalize_base_url(raw)
def test_sanitize_strips_credentials():
assert (
sanitize_url_for_logging("https://user:secret@host:4000/v1")
== "https://***@host:4000/v1"
)
def test_sanitize_leaves_clean_urls_alone():
assert sanitize_url_for_logging("http://host:4000/v1") == "http://host:4000/v1"