diff --git a/sidecar/src/syncbox/provider_http.py b/sidecar/src/syncbox/provider_http.py index 0810db2..e251335 100644 --- a/sidecar/src/syncbox/provider_http.py +++ b/sidecar/src/syncbox/provider_http.py @@ -47,10 +47,31 @@ def validate_url(url, hosts): raise ValueError("unsupported_network_destination") from None +# Per-address connect budget. A network with broken IPv6 resolves AAAA first; +# without a cap the first dead address eats the whole deadline and the working +# IPv4 address is never tried (browsers survive this via Happy Eyeballs). +CONNECT_ATTEMPT_TIMEOUT = 3 + + +def _interleave_families(addresses): + """RFC 8305 section 4 ordering: alternate address families, keep resolver order.""" + by_family = {} + for entry in addresses: + by_family.setdefault(entry[0], []).append(entry) + queues = list(by_family.values()) + ordered = [] + while any(queues): + for family_queue in queues: + if family_queue: + ordered.append(family_queue.pop(0)) + return ordered + + def public_connection(address, timeout=15, source_address=None): last_error = None deadline = time.monotonic() + timeout - for family, kind, proto, _, sockaddr in _addresses(address, timeout): + candidates = _interleave_families(_addresses(address, timeout)) + for index, (family, kind, proto, _, sockaddr) in enumerate(candidates): ip = ipaddress.ip_address(sockaddr[0]) if not ip.is_global or (ip.version == 6 and ip.ipv4_mapped and not ip.ipv4_mapped.is_global): raise ValueError("private_network_destination") @@ -59,7 +80,8 @@ def public_connection(address, timeout=15, source_address=None): remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError("provider_timeout") - sock.settimeout(remaining) + last_candidate = index == len(candidates) - 1 + sock.settimeout(remaining if last_candidate else min(remaining, CONNECT_ATTEMPT_TIMEOUT)) sock.connect(sockaddr) sock.settimeout(max(.001, deadline - time.monotonic())) return sock diff --git a/sidecar/src/syncbox/spotify.py b/sidecar/src/syncbox/spotify.py index fc10f9a..558b1e4 100644 --- a/sidecar/src/syncbox/spotify.py +++ b/sidecar/src/syncbox/spotify.py @@ -21,6 +21,7 @@ import base64 import hashlib import json +import logging import secrets as pysecrets import ssl import threading @@ -32,6 +33,8 @@ import certifi from syncbox import provider_http +log = logging.getLogger(__name__) + AUTHORIZE_URL = "https://accounts.spotify.com/authorize" TOKEN_URL = "https://accounts.spotify.com/api/token" API_BASE = "https://api.spotify.com/v1" @@ -165,6 +168,14 @@ def handle_callback(self, params: dict) -> dict: except SpotifyApiError as exc: self._authorization_result = "error" return {"ok": False, "error": f"token_exchange_failed_{exc.status_code}"} + except Exception as exc: + # Network/transport failure: the state is already consumed, so the + # attempt must end as a visible error, not a silent null result + # (the UI would report a timeout and a browser retry would hit + # state_mismatch). + log.warning("spotify token exchange failed: %r", exc) + self._authorization_result = "error" + return {"ok": False, "error": "token_exchange_unreachable"} self._authorization_result = "ok" return {"ok": True} diff --git a/sidecar/tests/test_provider_http.py b/sidecar/tests/test_provider_http.py index b17c687..7ace1f9 100644 --- a/sidecar/tests/test_provider_http.py +++ b/sidecar/tests/test_provider_http.py @@ -24,7 +24,36 @@ def close(self): monkeypatch.setattr(provider_http.socket, 'socket', lambda *a: Socket()) with pytest.raises(TimeoutError): provider_http.public_connection(('example.com', 443), timeout=15) - assert len(attempts) == 1 and clock[0] == 15 + # Each address is capped so one dead address cannot starve the rest, but + # all attempts together still never exceed the single deadline. + assert len(attempts) == 15 // provider_http.CONNECT_ATTEMPT_TIMEOUT + assert clock[0] == 15 + + +def test_dead_ipv6_falls_back_to_ipv4_within_the_deadline(monkeypatch): + clock = [0] + attempts = [] + monkeypatch.setattr(provider_http.time, 'monotonic', lambda: clock[0]) + v6 = [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', (f'2a04:4e42:{i}::810', 443, 0, 0)) for i in range(4)] + v4 = [(socket.AF_INET, socket.SOCK_STREAM, 0, '', (f'151.101.{i}.42', 443)) for i in range(4)] + monkeypatch.setattr(provider_http, '_addresses', lambda *a: v6 + v4) + class Socket: + def __init__(self, family): + self.family = family + def settimeout(self, timeout): + self.timeout = timeout + def connect(self, address): + attempts.append(address[0]) + if self.family == socket.AF_INET6: + clock[0] += self.timeout + raise TimeoutError('fixture: no IPv6 route') + def close(self): + pass + monkeypatch.setattr(provider_http.socket, 'socket', lambda family, *a: Socket(family)) + sock = provider_http.public_connection(('accounts.spotify.com', 443), timeout=15) + assert sock.family == socket.AF_INET + assert attempts == ['2a04:4e42:0::810', '151.101.0.42'] + assert clock[0] == provider_http.CONNECT_ATTEMPT_TIMEOUT def test_dns_wait_is_bounded_and_private_addresses_never_connect(monkeypatch): diff --git a/sidecar/tests/test_spotify.py b/sidecar/tests/test_spotify.py index 3b445dc..1252bbd 100644 --- a/sidecar/tests/test_spotify.py +++ b/sidecar/tests/test_spotify.py @@ -130,6 +130,22 @@ def test_callback_rejects_state_mismatch_error_and_missing_code(): assert auth.authorization_status() == {"pending": False, "result": "error"} +def test_callback_transport_failure_ends_attempt_as_error(): + auth, _, _ = make_auth() + + def unreachable(*args, **kwargs): + raise TimeoutError("provider_timeout") + + auth._transport = unreachable + auth.begin_authorization() + state = auth._state + assert auth.handle_callback({"code": "c", "state": state}) == { + "ok": False, + "error": "token_exchange_unreachable", + } + assert auth.authorization_status() == {"pending": False, "result": "error"} + + def test_authorization_state_expires_with_the_ui_poll_window(): now = [100.0] auth, _, _ = make_auth(clock=lambda: now[0])