From a8af5dfbe7db076df609144695c9bd2b685e406e Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Thu, 12 Nov 2026 10:07:18 -0500 Subject: [PATCH] fix(transport): coordinate verified dual-stack connections in Gleam --- priv/boot-modules.txt | 2 + robot-docs/provider-requests.md | 19 ++ src/albedo/openai_api/albedo_connect.erl | 286 ++++++++++++++++++ .../openai_api/albedo_openai_transport.erl | 109 ++----- src/albedo/openai_api/connect.gleam | 227 ++++++++++++++ test/albedo_test_runner.erl | 3 +- test/e2e/areas.toml | 14 + .../albedo_transport_dual_stack_test.erl | 220 +++++++++++++- 8 files changed, 777 insertions(+), 103 deletions(-) create mode 100644 src/albedo/openai_api/albedo_connect.erl create mode 100644 src/albedo/openai_api/connect.gleam diff --git a/priv/boot-modules.txt b/priv/boot-modules.txt index bbce70ec..6c88c7e2 100644 --- a/priv/boot-modules.txt +++ b/priv/boot-modules.txt @@ -89,6 +89,7 @@ albedo@harness@runtime@observation albedo@harness@runtime@preparation albedo@openai_api albedo@openai_api@chat +albedo@openai_api@connect albedo@openai_api@fields albedo@openai_api@reasoning albedo@openai_api@replay @@ -105,6 +106,7 @@ albedo_bus albedo_cache_ttl albedo_capability_catalog albedo_commands +albedo_connect albedo_context_snapshot albedo_conversation albedo_file_fingerprint diff --git a/robot-docs/provider-requests.md b/robot-docs/provider-requests.md index c4f7a12a..6c1ebd04 100644 --- a/robot-docs/provider-requests.md +++ b/robot-docs/provider-requests.md @@ -67,6 +67,25 @@ handles streaming exchanges, and receive and deadline-based receive functions. Do not assume every stream wait has a timeout. +The [connection coordinator](../src/albedo/openai_api/connect.gleam) tries IPv4 +and IPv6 concurrently for hostnames. HTTPS selects the first connection that +completes certificate verification, so a failed or stalled TLS handshake on one +family does not discard a usable connection on the other. IP literals use only +their own address family. + +One monotonic deadline covers fresh connection establishment, including DNS, +TCP, TLS, and socket handoff. Cleanup confirms that losing attempts have stopped +before returning. Cleanup can finish after that deadline while workers are being +stopped. This budget does not replace the separate send, first-event, or +response-body budgets. + +Keep socket ownership and process cleanup in the +[native adapter](../src/albedo/openai_api/albedo_connect.erl), and connection +selection policy in the coordinator. Attempts must not send HTTP requests. Only +the selected connection reaches the existing request guard and HTTP writer. +Preserve certificate and hostname verification, pool ownership, and the rule +that guarded requests never replay implicitly when changing this path. + ## Mistral wire projection The [Mistral wire module](../src/albedo/harness/extensions/mistral/wire.gleam) diff --git a/src/albedo/openai_api/albedo_connect.erl b/src/albedo/openai_api/albedo_connect.erl new file mode 100644 index 00000000..e658825a --- /dev/null +++ b/src/albedo/openai_api/albedo_connect.erl @@ -0,0 +1,286 @@ +-module(albedo_connect). +-export([ + with_coordinator/1, + start/6, + receive_event/2, + adopt/4, + cleanup/1, + publish/3, + families/1, + is_timeout/1, + is_missing_family/1 +]). + +%% Only the coordinator receives attempt messages. A guardian ends it when the +%% caller dies, including while it is inside a socket ownership operation. +with_coordinator(Run) -> + Caller = self(), + Reference = make_ref(), + {Coordinator, Monitor} = spawn_monitor(fun() -> + process_flag(trap_exit, true), + Context = {Caller, Reference}, + put(attempts, []), + put(reported, []), + put(sockets, []), + try Run(Context) of + Result -> + cleanup(Context), + close_retained(), + Caller ! {Reference, Result}, + receive + {Reference, acknowledged} -> ok + end + after + cleanup(Context), + close_retained() + end + end), + spawn(fun() -> guard(Caller, Coordinator) end), + await_result(Coordinator, Monitor, Reference, none). + +await_result(Coordinator, Monitor, Reference, Published) -> + receive + {Reference, publishing, Socket} -> + await_result(Coordinator, Monitor, Reference, {some, Socket}); + {Reference, Result} -> + Coordinator ! {Reference, acknowledged}, + receive + {'DOWN', Monitor, process, Coordinator, _} -> ok + end, + case Result of + {error, _} -> close_published(Published); + {ok, _} -> ok + end, + Result; + {'DOWN', Monitor, process, Coordinator, Reason} -> + close_published(Published), + {error, {connection_failed, {connector_exit, Reason}}} + end. + +close_published(none) -> ok; +close_published({some, Socket}) -> close_socket(Socket). + +guard(Caller, Coordinator) -> + CallerMonitor = monitor(process, Caller), + CoordinatorMonitor = monitor(process, Coordinator), + receive + {'DOWN', CallerMonitor, process, Caller, _} -> exit(Coordinator, kill); + {'DOWN', CoordinatorMonitor, process, Coordinator, _} -> ok + end. + +families(Host) -> + case inet:parse_address(binary_to_list(Host)) of + {ok, Address} when tuple_size(Address) =:= 4 -> [ipv4]; + {ok, _} -> [ipv6]; + {error, _} -> [ipv4, ipv6] + end. + +start(Context, Endpoint, Family, Options, TlsOptions, Deadline) -> + start_attempt(Context, Endpoint, Family, Options, TlsOptions, Deadline). + +start_attempt({_Caller, Reference}, Endpoint, Family, Options, TlsOptions, Deadline) -> + Coordinator = self(), + {Worker, Monitor} = spawn_opt( + fun() -> + Result = dial(Endpoint, Family, Options, TlsOptions, Deadline), + case Result of + {ok, Socket} -> + Coordinator ! {Reference, ready, self(), Socket}, + receive + {Reference, adopt} -> + Transfer = controlling_process(Socket, Coordinator), + Coordinator ! {Reference, transferred, self(), Transfer}, + case Transfer of + ok -> ok; + {error, _} -> close_socket(Socket) + end + end; + {error, {tls_failure, Reason}} -> + Coordinator ! {Reference, failed, self(), verifying_tls, Reason}; + {error, Reason} -> + Coordinator ! {Reference, failed, self(), connecting, Reason} + end + end, + [link, monitor] + ), + Attempt = {Worker, Monitor}, + put(attempts, [Attempt | get(attempts)]), + Attempt. + +receive_event(Context, Remaining) -> + receive_before(Context, erlang:monotonic_time(millisecond) + Remaining). + +receive_before({_Caller, Reference} = Context, Deadline) -> + receive + {Reference, ready, Worker, Socket} -> + {ready, attempt(Worker), Socket}; + {Reference, failed, Worker, Phase, Reason} -> + put(reported, [Worker | get(reported)]), + {failed, attempt(Worker), Phase, Reason}; + {'DOWN', Monitor, process, Worker, Reason} -> + Attempts = get(attempts), + put(attempts, lists:delete({Worker, Monitor}, Attempts)), + case + lists:member({Worker, Monitor}, Attempts) andalso + not lists:member(Worker, get(reported)) + of + true -> {failed, {Worker, Monitor}, connecting, {attempt_exit, Reason}}; + false -> receive_before(Context, Deadline) + end; + {'EXIT', _, _} -> + receive_before(Context, Deadline) + after remaining(Deadline) -> wait_expired + end. + +attempt(Worker) -> lists:keyfind(Worker, 1, get(attempts)). + +adopt({_Caller, Reference}, {Worker, Monitor} = Attempt, Socket, Deadline) -> + Worker ! {Reference, adopt}, + receive + {Reference, transferred, Worker, ok} -> + put(sockets, [Socket | get(sockets)]), + case remaining(Deadline) of + 0 -> {error, timeout}; + _ -> {ok, Socket} + end; + {Reference, transferred, Worker, {error, Reason}} -> + {error, Reason}; + {'DOWN', Monitor, process, Worker, Reason} -> + put(attempts, lists:delete(Attempt, get(attempts))), + {error, {attempt_exit, Reason}} + after remaining(Deadline) -> {error, timeout} + end. + +%% DOWN is an ordering barrier: every earlier message from that worker has +%% arrived before its monitor notification, so draining cannot miss a reply. +cleanup({_Caller, Reference}) -> + Attempts = get(attempts), + [exit(Worker, kill) || {Worker, _} <- Attempts], + [ + receive + {'DOWN', Monitor, process, Worker, _} -> ok + end + || {Worker, Monitor} <- Attempts + ], + put(attempts, []), + drain(Reference), + ok. + +drain(Reference) -> + receive + {Reference, _, _, _} -> drain(Reference); + {Reference, _, _, _, _} -> drain(Reference); + {'EXIT', _, _} -> drain(Reference) + after 0 -> ok + end. + +publish({Caller, Reference}, Socket, Deadline) -> + case remaining(Deadline) of + 0 -> + {error, timeout}; + _ -> + %% Announce before transfer so caller can close the socket even + %% if the coordinator dies before publishing its terminal result. + Caller ! {Reference, publishing, Socket}, + case controlling_process(Socket, Caller) of + ok -> + put(sockets, lists:delete(Socket, get(sockets))), + case remaining(Deadline) of + 0 -> + close_socket(Socket), + {error, timeout}; + _ -> + {ok, Socket} + end; + {error, Reason} -> + {error, Reason} + end + end. + +close_retained() -> + [close_socket(Socket) || Socket <- get(sockets)], + put(sockets, []). + +remaining(Deadline) -> max(0, Deadline - erlang:monotonic_time(millisecond)). + +is_timeout(timeout) -> true; +is_timeout(_) -> false. + +is_missing_family(Reason) -> + lists:member(Reason, [nxdomain, eafnosupport, enetunreach, eaddrnotavail, einval]). + +dial({endpoint, Transport, Host, Port}, Family, Options, TlsOptions, Deadline) -> + Name = binary_to_list(Host), + Address = + case inet:parse_address(Name) of + {ok, IP} -> IP; + _ -> Name + end, + NativeFamily = + case Family of + ipv4 -> inet; + ipv6 -> inet6 + end, + case remaining(Deadline) of + 0 -> + {error, timeout}; + Timeout -> + case gen_tcp:connect(Address, Port, [NativeFamily | Options], Timeout) of + {ok, Tcp} when Transport =:= tcp -> {ok, {tcp, Tcp}}; + {ok, Tcp} -> + case upgrade(Tcp, Address, TlsOptions, Deadline) of + {error, Reason} -> {error, {tls_failure, Reason}}; + Success -> Success + end; + {error, _} = Error -> + Error + end + end. + +upgrade(Tcp, Address, TlsOptions, Deadline) -> + Options = + case is_tuple(Address) of + true -> + [ + {server_name_indication, disable} + | proplists:delete(server_name_indication, TlsOptions) + ]; + false -> + TlsOptions + end, + case remaining(Deadline) of + 0 -> + gen_tcp:close(Tcp), + {error, timeout}; + Timeout -> + case ssl:connect(Tcp, Options, Timeout) of + {ok, Tls} -> + verify_ip(Tls, Address); + {error, _} = Error -> + gen_tcp:close(Tcp), + Error + end + end. + +verify_ip(Tls, Address) when is_tuple(Address) -> + case ssl:peercert(Tls) of + {ok, Certificate} -> + case public_key:pkix_verify_hostname(Certificate, [{ip, Address}]) of + true -> + {ok, {tls, Tls}}; + false -> + ssl:close(Tls), + {error, {tls_alert, {bad_certificate, "IP address mismatch"}}} + end; + {error, _} = Error -> + ssl:close(Tls), + Error + end; +verify_ip(Tls, _Host) -> + {ok, {tls, Tls}}. + +controlling_process({tcp, Socket}, Owner) -> gen_tcp:controlling_process(Socket, Owner); +controlling_process({tls, Socket}, Owner) -> ssl:controlling_process(Socket, Owner). + +close_socket({tcp, Socket}) -> gen_tcp:close(Socket); +close_socket({tls, Socket}) -> ssl:close(Socket). diff --git a/src/albedo/openai_api/albedo_openai_transport.erl b/src/albedo/openai_api/albedo_openai_transport.erl index 9cefe0ae..ebb0c51b 100644 --- a/src/albedo/openai_api/albedo_openai_transport.erl +++ b/src/albedo/openai_api/albedo_openai_transport.erl @@ -212,103 +212,28 @@ connect(Transport, Host, Port, Timeout) -> {ok, IP} -> IP; {error, _} -> Host end, - case Transport of - tcp -> - connect_tcp(Address, Port, Options, Timeout); - tls -> - case application:ensure_all_started(ssl) of - {ok, _} -> connect_tls(Address, Port, Options, Timeout); - {error, Reason} -> {error, {ssl_not_started, Reason}} - end - end. - -%% TLS starts on the connection that won the race, so a slow handshake on one -%% address family never decides which family is used. -connect_tls(Address, Port, Options, Timeout) -> - case connect_tcp(Address, Port, Options, Timeout) of - {ok, Socket} -> - case ssl:connect(Socket, tls_options(Address), Timeout) of - {ok, _} = Ok -> - Ok; - {error, _} = Error -> - gen_tcp:close(Socket), - Error + case ensure_tls(Transport) of + ok -> + Endpoint = {endpoint, Transport, unicode:characters_to_binary(Host), Port}, + case + 'albedo@openai_api@connect':connect( + Endpoint, Options, tls_options(Address), Timeout + ) + of + {ok, {_Kind, Socket}} -> {ok, Socket}; + {error, deadline_expired} -> {error, timeout}; + {error, {connection_failed, Reason}} -> {error, Reason} end; {error, _} = Error -> Error end. -%% An address literal connects directly. A name is tried over IPv6 and IPv4 at -%% once: a host may publish only one family, or a network resolve only one, -%% and a name that resolves for one family may not be reachable over it. The -%% first connection wins and the other attempt is dropped. -connect_tcp(Address, Port, Options, Timeout) when is_tuple(Address) -> - gen_tcp:connect(Address, Port, Options, Timeout); -connect_tcp(Host, Port, Options, Timeout) -> - Owner = self(), - Ref = make_ref(), - Racers = [ - spawn(fun() -> racer(Owner, Ref, Family, Host, Port, Options, Timeout) end) - || Family <- [inet, inet6] - ], - {Result, Losers} = race(Ref, Racers, [], Timeout + 1000), - %% A loser that is still connecting dies with its socket, and anything it - %% already sent must not linger in the caller's mailbox. - [exit(Loser, kill) || Loser <- Losers], - flush_race(Ref), - Result. - -%% Connects over one family and hands the socket over once the owner takes -%% it. A racer whose owner has gone away exits, which closes its socket. -racer(Owner, Ref, Family, Host, Port, Options, Timeout) -> - Monitor = erlang:monitor(process, Owner), - case gen_tcp:connect(Host, Port, [Family | Options], Timeout) of - {ok, Socket} -> - Owner ! {Ref, self(), Family, {ok, Socket}}, - receive - {Ref, take} -> - gen_tcp:controlling_process(Socket, Owner), - Owner ! {Ref, taken}; - {'DOWN', Monitor, process, Owner, _} -> - ok - end; - {error, Reason} -> - Owner ! {Ref, self(), Family, {error, Reason}} - end. - -%% {Result, StillRacing}: the first socket to connect, or the errors once -%% every family has failed. -race(_, [], Errors, _) -> - {{error, race_error(lists:reverse(Errors))}, []}; -race(Ref, Racers, Errors, Wait) -> - receive - {Ref, Racer, _, {ok, Socket}} -> - Racer ! {Ref, take}, - receive - {Ref, taken} -> {{ok, Socket}, lists:delete(Racer, Racers)} - after Wait -> {{error, timeout}, Racers} - end; - {Ref, Racer, Family, {error, Reason}} -> - race(Ref, lists:delete(Racer, Racers), [{Family, Reason} | Errors], Wait) - after Wait -> - {{error, timeout}, Racers} - end. - -flush_race(Ref) -> - receive - {Ref, _, _, _} -> flush_race(Ref); - {Ref, taken} -> flush_race(Ref) - after 0 -> - ok - end. - -%% What a failed race reports: the first error that is not just a family the -%% host or this machine lacks, else the IPv4 one, as before the race. -race_error(Errors) -> - Lacking = [nxdomain, eafnosupport, enetunreach, eaddrnotavail, einval], - case [Reason || {_, Reason} <- Errors, not lists:member(Reason, Lacking)] of - [Reason | _] -> Reason; - [] -> proplists:get_value(inet, Errors, nxdomain) +ensure_tls(tcp) -> + ok; +ensure_tls(tls) -> + case application:ensure_all_started(ssl) of + {ok, _} -> ok; + {error, Reason} -> {error, {ssl_not_started, Reason}} end. %% A response body may stay silent for as long as the server takes, so diff --git a/src/albedo/openai_api/connect.gleam b/src/albedo/openai_api/connect.gleam new file mode 100644 index 00000000..5519d532 --- /dev/null +++ b/src/albedo/openai_api/connect.gleam @@ -0,0 +1,227 @@ +//// Select a usable connection under one establishment deadline. Socket and +//// process ownership stay in the native adapter; HTTP bytes are sent only by +//// the transport after this function returns. + +import albedo/clock +import gleam/list + +pub type Transport { + Tcp + Tls +} + +pub type Family { + Ipv4 + Ipv6 +} + +pub type Endpoint { + Endpoint(transport: Transport, host: String, port: Int) +} + +pub type Socket + +pub type SocketOptions + +pub type Reason + +pub type Context + +pub type Attempt + +pub type Error { + DeadlineExpired + ConnectionFailed(reason: Reason) +} + +type Phase { + Connecting + VerifyingTls + Transferring +} + +type Event { + Ready(attempt: Attempt, socket: Socket) + Failed(attempt: Attempt, phase: Phase, reason: Reason) + WaitExpired +} + +type Failure { + Failure(family: Family, phase: Phase, reason: Reason) +} + +/// A fresh connection's budget covers DNS, TCP, TLS, and socket handoff. Cleanup +/// confirms worker termination even when the deadline has already expired. +pub fn connect( + endpoint: Endpoint, + options: SocketOptions, + tls_options: SocketOptions, + timeout_ms: Int, +) -> Result(Socket, Error) { + let deadline_ms = clock.monotonic_ms() + timeout_ms + with_coordinator(fn(context) { + let attempts = + families(endpoint.host) + |> list.map(fn(family) { + #( + family, + start(context, endpoint, family, options, tls_options, deadline_ms), + ) + }) + let result = choose(context, attempts, [], deadline_ms) + cleanup(context) + case result { + Ok(socket) -> + case publish(context, socket, deadline_ms) { + Ok(socket) -> Ok(socket) + Error(reason) -> Error(connection_error(reason)) + } + Error(error) -> Error(error) + } + }) +} + +fn choose( + context: Context, + pending: List(#(Family, Attempt)), + failures: List(Failure), + deadline_ms: Int, +) -> Result(Socket, Error) { + let remaining_ms = deadline_ms - clock.monotonic_ms() + case remaining_ms <= 0, pending { + True, _ -> Error(DeadlineExpired) + False, [] -> Error(choose_error(list.reverse(failures))) + False, _ -> + case receive_event(context, remaining_ms) { + Ready(attempt, socket) -> + case adopt(context, attempt, socket, deadline_ms) { + Ok(socket) -> Ok(socket) + Error(reason) -> + failed( + context, + pending, + failures, + attempt, + Transferring, + reason, + deadline_ms, + ) + } + Failed(attempt, phase, reason) -> + failed( + context, + pending, + failures, + attempt, + phase, + reason, + deadline_ms, + ) + WaitExpired -> Error(DeadlineExpired) + } + } +} + +fn failed( + context: Context, + pending: List(#(Family, Attempt)), + failures: List(Failure), + attempt: Attempt, + phase: Phase, + reason: Reason, + deadline_ms: Int, +) -> Result(Socket, Error) { + let failures = case list.find(pending, fn(entry) { entry.1 == attempt }) { + Ok(#(family, _)) -> [Failure(family, phase, reason), ..failures] + Error(_) -> failures + } + choose( + context, + list.filter(pending, fn(entry) { entry.1 != attempt }), + failures, + deadline_ms, + ) +} + +// A refusal on one family must not hide certificate verification failure on +// the other. Otherwise prefer a substantive failure over an absent family. +fn choose_error(failures: List(Failure)) -> Error { + case + list.find(failures, fn(failure) { + case failure.phase { + VerifyingTls -> True + Connecting | Transferring -> False + } + }) + { + Ok(failure) -> connection_error(failure.reason) + Error(_) -> choose_connection_error(failures) + } +} + +fn choose_connection_error(failures: List(Failure)) -> Error { + case list.find(failures, fn(failure) { !is_missing_family(failure.reason) }) { + Ok(failure) -> connection_error(failure.reason) + Error(_) -> + case list.find(failures, fn(failure) { failure.family == Ipv4 }) { + Ok(failure) -> connection_error(failure.reason) + Error(_) -> + case failures { + [failure, ..] -> connection_error(failure.reason) + [] -> DeadlineExpired + } + } + } +} + +fn connection_error(reason: Reason) -> Error { + case is_timeout(reason) { + True -> DeadlineExpired + False -> ConnectionFailed(reason) + } +} + +@external(erlang, "albedo_connect", "with_coordinator") +fn with_coordinator( + run: fn(Context) -> Result(Socket, Error), +) -> Result(Socket, Error) + +@external(erlang, "albedo_connect", "families") +fn families(host: String) -> List(Family) + +@external(erlang, "albedo_connect", "start") +fn start( + context: Context, + endpoint: Endpoint, + family: Family, + options: SocketOptions, + tls_options: SocketOptions, + deadline_ms: Int, +) -> Attempt + +@external(erlang, "albedo_connect", "receive_event") +fn receive_event(context: Context, remaining_ms: Int) -> Event + +@external(erlang, "albedo_connect", "adopt") +fn adopt( + context: Context, + attempt: Attempt, + socket: Socket, + deadline_ms: Int, +) -> Result(Socket, Reason) + +@external(erlang, "albedo_connect", "cleanup") +fn cleanup(context: Context) -> Nil + +@external(erlang, "albedo_connect", "publish") +fn publish( + context: Context, + socket: Socket, + deadline_ms: Int, +) -> Result(Socket, Reason) + +@external(erlang, "albedo_connect", "is_timeout") +fn is_timeout(reason: Reason) -> Bool + +@external(erlang, "albedo_connect", "is_missing_family") +fn is_missing_family(reason: Reason) -> Bool diff --git a/test/albedo_test_runner.erl b/test/albedo_test_runner.erl index 5c732fac..1a3a9789 100644 --- a/test/albedo_test_runner.erl +++ b/test/albedo_test_runner.erl @@ -17,7 +17,8 @@ 'harness@bedrock_converse_http_test', 'openai_api@transport_test', %% Changes the VM-wide clock scale, which other suites must not observe. - albedo_transport_once_test + albedo_transport_once_test, + albedo_transport_dual_stack_test ]). main() -> diff --git a/test/e2e/areas.toml b/test/e2e/areas.toml index be283d5b..7e6ff0a7 100644 --- a/test/e2e/areas.toml +++ b/test/e2e/areas.toml @@ -181,6 +181,20 @@ "context_test.py", "prompt_test.py", ] +"src/albedo/openai_api/connect.gleam" = [ + "antigravity_test.py", + "provider_protocols_test.py", + "integration_test.py", + "context_test.py", + "prompt_test.py", +] +"src/albedo/openai_api/albedo_connect.erl" = [ + "antigravity_test.py", + "provider_protocols_test.py", + "integration_test.py", + "context_test.py", + "prompt_test.py", +] "src/albedo/harness/albedo_http.erl" = [ "antigravity_test.py", "integration_test.py", diff --git a/test/harness/albedo_transport_dual_stack_test.erl b/test/harness/albedo_transport_dual_stack_test.erl index 98d68676..1be0ee18 100644 --- a/test/harness/albedo_transport_dual_stack_test.erl +++ b/test/harness/albedo_transport_dual_stack_test.erl @@ -5,6 +5,7 @@ %% answers, even when the other refuses. -module(albedo_transport_dual_stack_test). -include_lib("eunit/include/eunit.hrl"). +-include_lib("public_key/include/public_key.hrl"). -define(V4, {127, 0, 0, 1}). -define(V6, {0, 0, 0, 0, 0, 0, 0, 1}). @@ -50,17 +51,80 @@ refused_connection_reports_refusal_not_a_missing_family_test() -> ) end). -losing_attempt_leaves_nothing_behind_test() -> - with_listener(?V6, fun(Port) -> - with_hosts( - [{?V4, "clean.dual-stack.test"}, {?V6, "clean.dual-stack.test"}], - fun() -> - ok = fetch("clean.dual-stack.test", Port), - ?assertEqual({messages, []}, process_info(self(), messages)) - end - ) +%% Both orientations matter: the TCP winner must not decide the TLS winner. +https_uses_the_family_that_completes_verified_tls_test() -> + lists:foreach( + fun(Stalled) -> + with_tls_servers([?V4, ?V6], Stalled, fun(Port, Servers, Ref) -> + with_hosts([{?V4, "tls.dual-stack.test"}, {?V6, "tls.dual-stack.test"}], fun() -> + ?assertEqual(ok, fetch_url(tls_url("tls.dual-stack.test", Port), 2000)), + await_servers(Servers, Ref) + end) + end) + end, + [?V4, ?V6] + ). + +https_establishment_uses_one_budget_and_closes_timed_out_sockets_test() -> + with_tls_servers([?V4], ?V4, fun(Port, Servers, Ref) -> + with_hosts([{?V4, "tls.dual-stack.test"}], fun() -> + Started = erlang:monotonic_time(millisecond), + ?assertEqual( + {error, timed_out}, + albedo_openai_transport:open( + <<"GET">>, tls_url("tls.dual-stack.test", Port), [], <<>>, 250 + ) + ), + Elapsed = erlang:monotonic_time(millisecond) - Started, + %% Allows scheduling overhead, but not the old extra 1000 ms wait. + ?assert(Elapsed < 750), + await_servers(Servers, Ref) + end) end). +caller_death_closes_an_in_progress_tls_attempt_test() -> + with_tls_servers([?V4], ?V4, fun(Port, Servers, Ref) -> + with_hosts([{?V4, "tls.dual-stack.test"}], fun() -> + {Caller, Monitor} = spawn_monitor(fun() -> + albedo_openai_transport:open( + <<"GET">>, tls_url("tls.dual-stack.test", Port), [], <<>>, 10000 + ) + end), + receive + {Ref, accepted, _} -> ok + after 3000 -> error(no_tls_connection) + end, + exit(Caller, kill), + receive + {'DOWN', Monitor, process, Caller, killed} -> ok + after 3000 -> error(caller_still_alive) + end, + await_servers(Servers, Ref) + end) + end). + +https_checks_dns_and_ip_certificate_identity_test() -> + lists:foreach( + fun({Address, Host, Expected}) -> + with_tls_servers([Address], none, fun(Port, Servers, Ref) -> + with_hosts([{Address, Host}], fun() -> + Result = fetch_url(tls_url(Host, Port), 2000), + case Expected of + trusted -> ?assertEqual(ok, Result); + wrong_name -> ?assertMatch({error, {transport_error, _}}, Result) + end, + await_servers(Servers, Ref) + end) + end) + end, + [ + {?V4, "tls.dual-stack.test", trusted}, + {?V4, "127.0.0.1", trusted}, + {?V6, "[::1]", trusted}, + {?V4, "wrong.dual-stack.test", wrong_name} + ] + ). + only_ipv6_name_reaches_httpc_front_door_test() -> with_listener(?V6, fun(Port) -> with_hosts([{?V6, "httpc-v6.dual-stack.test"}], fun() -> @@ -83,7 +147,15 @@ only_ipv4_name_reaches_httpc_front_door_test() -> fetch(Host, Port) -> URL = iolist_to_binary(io_lib:format("http://~s:~B/", [Host, Port])), - {ok, Connection} = albedo_openai_transport:open(<<"GET">>, URL, [], <<>>, 3000), + fetch_url(URL, 3000). + +fetch_url(URL, Timeout) -> + case albedo_openai_transport:open(<<"GET">>, URL, [], <<>>, Timeout) of + {error, _} = Error -> Error; + {ok, Connection} -> read_response(Connection) + end. + +read_response(Connection) -> try {ok, {headers, 200, _, false}} = albedo_openai_transport:receive_message(Connection), {ok, {data, <<"ok">>, true}} = albedo_openai_transport:receive_message(Connection), @@ -134,11 +206,139 @@ serve(Listen) -> %% Names resolve from the in-memory host table for the test's duration. with_hosts(Hosts, Run) -> Previous = inet_db:res_option(lookup), + PreviousHosts = [{Address, Names} || {host, Address, Names} <- inet_db:get_rc()], inet_db:set_lookup([file | Previous]), [ok = inet_db:add_host(Address, [Name]) || {Address, Name} <- Hosts], try Run() after [inet_db:del_host(Address) || {Address, _} <- Hosts], + [inet_db:add_host(Address, Names) || {Address, Names} <- PreviousHosts], inet_db:set_lookup(Previous) end. + +%% Raw listeners let one family accept TCP without completing its TLS handshake. +%% The other uses a real certificate signed by a temporary trusted root. +with_tls_servers(Addresses, Stalled, Run) -> + {ok, _} = application:ensure_all_started(ssl), + PreviousRoots = public_key:cacerts_get(), + Name = #'Extension'{ + extnID = ?'id-ce-subjectAltName', + critical = false, + extnValue = [ + {dNSName, "tls.dual-stack.test"}, + {iPAddress, <<127, 0, 0, 1>>}, + {iPAddress, <<0:120, 1>>} + ] + }, + Key = [{key, {namedCurve, ?secp256r1}}, {digest, sha256}], + #{server_config := Config, client_config := Client} = public_key:pkix_test_data(#{ + server_chain => #{root => Key, intermediates => [], peer => [{extensions, [Name]} | Key]}, + client_chain => #{root => Key, intermediates => [], peer => Key} + }), + ok = load_roots(proplists:get_value(cacerts, Client)), + Ref = make_ref(), + Parent = self(), + {Listeners, Port} = tls_listeners(Addresses, 0, []), + Gate = spawn(fun() -> release_accepted(length(Listeners), []) end), + Servers = [ + spawn_monitor(fun() -> tls_serve(Listen, Address =:= Stalled, Config, Parent, Ref, Gate) end) + || {Address, Listen} <- Listeners + ], + try + Run(Port, Servers, Ref) + after + exit(Gate, kill), + [exit(Pid, kill) || {Pid, _} <- Servers], + [gen_tcp:close(Listen) || {_, Listen} <- Listeners], + [erlang:demonitor(Monitor, [flush]) || {_, Monitor} <- Servers], + load_roots([Der || #cert{der = Der} <- PreviousRoots]), + flush_server_messages(Ref) + end. + +tls_listeners([], Port, Acc) -> + {lists:reverse(Acc), Port}; +tls_listeners([Address | Rest], Port, Acc) -> + FamilyOptions = + case Address of + ?V6 -> [inet6, {ipv6_v6only, true}]; + _ -> [inet] + end, + {ok, Listen} = gen_tcp:listen(Port, [ + binary, {ip, Address}, {active, false}, {reuseaddr, true} | FamilyOptions + ]), + {ok, ActualPort} = inet:port(Listen), + tls_listeners(Rest, ActualPort, [{Address, Listen} | Acc]). + +%% Neither handshake advances until every TCP attempt reaches its listener. +release_accepted(0, Accepted) -> + [Pid ! proceed || Pid <- Accepted]; +release_accepted(Left, Accepted) -> + receive + {accepted, Pid} -> release_accepted(Left - 1, [Pid | Accepted]) + end. + +tls_serve(Listen, Stalled, Config, Parent, Ref, Gate) -> + {ok, Socket} = gen_tcp:accept(Listen, 5000), + Parent ! {Ref, accepted, self()}, + Gate ! {accepted, self()}, + receive + proceed -> ok + after 5000 -> error(other_family_did_not_connect) + end, + case Stalled of + true -> + await_peer_close(Socket); + false -> + case ssl:handshake(Socket, Config, 3000) of + {ok, Secure} -> + {ok, Request} = ssl:recv(Secure, 0, 3000), + true = binary:match(Request, <<"GET ">>) =/= nomatch, + ok = ssl:send( + Secure, + <<"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok">> + ), + ssl:close(Secure); + {error, _} -> + gen_tcp:close(Socket) + end + end. + +await_peer_close(Socket) -> + case gen_tcp:recv(Socket, 0, 3000) of + {ok, _Handshake} -> await_peer_close(Socket); + {error, closed} -> ok; + Other -> error({peer_not_closed, Other}) + end. + +await_servers([], _Ref) -> + ok; +await_servers([{Pid, Monitor} | Rest], Ref) -> + receive + {Ref, accepted, Pid} -> await_servers([{Pid, Monitor} | Rest], Ref); + {'DOWN', Monitor, process, Pid, normal} -> await_servers(Rest, Ref); + {'DOWN', Monitor, process, Pid, Reason} -> error({tls_server_failed, Reason}) + after 5000 -> error({tls_server_still_running, Pid}) + end. + +flush_server_messages(Ref) -> + receive + {Ref, accepted, _} -> flush_server_messages(Ref) + after 0 -> ok + end. + +tls_url(Host, Port) -> iolist_to_binary(io_lib:format("https://~s:~B/", [Host, Port])). + +load_roots(Roots) -> + Path = filename:join( + os:getenv("TMPDIR", "/tmp"), + "albedo-dual-stack-ca-" ++ integer_to_list(erlang:unique_integer([positive])) ++ ".pem" + ), + ok = file:write_file( + Path, public_key:pem_encode([{'Certificate', Der, not_encrypted} || Der <- Roots]) + ), + try + public_key:cacerts_load(Path) + after + file:delete(Path) + end. -- knotmirror 0.0.1