From fc84874b3bc7e22d73560d082da4e4f50ebbd1a8 Mon Sep 17 00:00:00 2001 From: capz <345101+capz@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:19:27 +0100 Subject: [PATCH 1/4] Expose native TLS provider error codes to bounded application diagnostics --- docs/https.md | 7 +++++++ scripts/ci_https.py | 3 +++ src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs | 1 + src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs | 6 ++++++ tools/DolphinDotNet.Compiler/NativeStorageBindings.cs | 1 + 5 files changed, 18 insertions(+) diff --git a/docs/https.md b/docs/https.md index 2fdd2ada..7667c6be 100644 --- a/docs/https.md +++ b/docs/https.md @@ -143,3 +143,10 @@ and unpredictable WebSocket masks; pool small draws. The existing bounded DRBG reseed interval still applies. Exhaustion fails closed: dispose connections, collect fresh platform entropy and reconfigure before reconnecting. This API never manufactures replacement entropy or changes certificate validation. + +`TlsConfiguration.LastErrorCode` exposes the existing native provider's last +numeric error for diagnostics. Successful initialization clears it to zero; +provider failures record a negative code. Read it immediately after failure, +before another TLS operation can replace this process-wide value. It contains +no credentials, certificate contents or application payloads and does not +change validation, cancellation or retry behavior. diff --git a/scripts/ci_https.py b/scripts/ci_https.py index 0e886f58..47aa849d 100644 --- a/scripts/ci_https.py +++ b/scripts/ci_https.py @@ -31,6 +31,7 @@ class Program { Wait(NetworkRuntime.StartAsync(new NetworkOptions{DnsServers=new[]{Dolphin.Network.IPAddress.Loopback},DnsPort=15353},default)); var ca=Dolphin.Text.Encoding.ASCII.GetBytes($CA);var seed=new byte[]{$ENTROPY};TlsConfiguration.Initialize(ca,seed,$UTC); for(int i=0;i=0)return 33; var noPipe=new System.Threading.CancellationTokenSource();noPipe.Cancel();try{TlsStream.ConnectAsync("localhost",$PORT,noPipe.Token);return 30;}catch(OperationCanceledException){} using(var client=new HttpClient()){ @@ -74,6 +76,7 @@ class Program { for(int i=0;ithrow Unsupported(); internal static int TlsConfigureLocalClock(byte[] roots,byte[] entropy,long localUnixSeconds)=>throw Unsupported(); internal static int TlsReset()=>throw Unsupported(); + internal static int TlsError()=>throw Unsupported(); internal static int TlsStart(int handle,string hostname)=>throw Unsupported(); internal static int TlsRandom(int handle,byte[] buffer,int offset,int count)=>throw Unsupported(); internal static int TlsHandshake(int handle)=>throw Unsupported(); diff --git a/src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs b/src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs index 9d563051..736b422f 100644 --- a/src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs +++ b/src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs @@ -6,6 +6,12 @@ namespace Dolphin.Network; /// copied natively. The entropy array is cleared, including on failure. public static class TlsConfiguration { + /// Last native TLS provider error, for immediate numeric diagnostics. + /// Zero follows successful initialization; a provider failure records a + /// negative code. Read before another TLS operation can replace it. This is + /// process-wide diagnostic state, not a connection result or retry policy. + public static int LastErrorCode=>NativeNetwork.TlsError(); + /// Explicit PEM trust anchors, maximum 256 KiB. /// 48–64 cryptographically random secret bytes, fresh /// for every initialization and process boot. Never use Random, ticks, public diff --git a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs index 47121492..df5b5baf 100644 --- a/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs +++ b/tools/DolphinDotNet.Compiler/NativeStorageBindings.cs @@ -225,6 +225,7 @@ internal static class NativeStorageBindings ["TlsConfigureLocalClock"]=("dnd_net_tls_configure_local_clock","aal",false), ["Fill"]=("dnd_platform_entropy_fill_array","ai",false), ["TlsReset"]=("dnd_net_tls_reset","",false), + ["TlsError"]=("dnd_net_tls_error","",false), ["TlsRandom"]=("dnd_net_tls_random","iaii",false), ["TlsStart"]=("dnd_net_tls_start","is",false),["TlsHandshake"]=("dnd_net_tls_handshake","i",false), ["NetStart"]=("dnd_net_start","iiii",false),["NetStatus"]=("dnd_net_status","",false),["NetTime"]=("dnd_net_time","",false),["NetError"]=("dnd_net_error","",false), From 52dae7684bd283d22cd81230450ba0243a8d7539 Mon Sep 17 00:00:00 2001 From: capz <345101+capz@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:24:38 +0100 Subject: [PATCH 2/4] Verify published SDK consumers and record dependency content hashes --- .github/workflows/nuget-preview.yml | 34 ++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/.github/workflows/nuget-preview.yml b/.github/workflows/nuget-preview.yml index 174618bb..5e056538 100644 --- a/.github/workflows/nuget-preview.yml +++ b/.github/workflows/nuget-preview.yml @@ -115,5 +115,37 @@ jobs: run: | test -n "$NUGET_API_KEY" for package in packages/*.nupkg; do - dotnet nuget push "$package" --source https://api.nuget.org/v3/index.json --api-key "$NUGET_API_KEY" + dotnet nuget push "$package" --source https://api.nuget.org/v3/index.json --api-key "$NUGET_API_KEY" --skip-duplicate done + + - name: Verify published packages restore + timeout-minutes: 6 + env: + PUBLISHED_SDK_VERSION: ${{ needs.verify.outputs.version }} + run: | + python3 - <<'PYTHON' + import json, os, pathlib, subprocess, tempfile, time + version = os.environ['PUBLISHED_SDK_VERSION'] + with tempfile.TemporaryDirectory(prefix='published-sdk-consumer-') as directory: + root = pathlib.Path(directory) + project = root / 'PublishedSdkConsumer.csproj' + project.write_text('net8.0') + config = root / 'NuGet.Config' + config.write_text('') + for attempt in range(10): + result = subprocess.run(['dotnet', 'restore', str(project), '--configfile', str(config), '--packages', str(root / 'packages'), '--use-lock-file', '--no-cache', '--force-evaluate'], text=True, capture_output=True, timeout=30) + if result.returncode == 0: + break + print(result.stdout[-2000:] + result.stderr[-2000:], flush=True) + if attempt == 9: + raise RuntimeError('Published SDK packages did not become restorable') + time.sleep(5) + locked = json.loads((root / 'packages.lock.json').read_text())['dependencies']['net8.0'] + hashes = {} + for name in ('DolphinDotNet.Core', 'DolphinDotNet.GameCube'): + package = locked[name] + if package['resolved'] != version or not package.get('contentHash'): + raise RuntimeError('Published SDK dependency identity differs: ' + name) + hashes[name] = {'version': package['resolved'], 'contentHash': package['contentHash']} + print('PUBLISHED_PACKAGE_HASHES ' + json.dumps(hashes, sort_keys=True), flush=True) + PYTHON From 4dd477b574f7fc9256c3260e44eee17b7d93b2ee Mon Sep 17 00:00:00 2001 From: capz <345101+capz@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:40:21 +0100 Subject: [PATCH 3/4] Keep framed HTTP responses open until the client consumes them Allow HTTP/1.1 peers to keep the transport open; the existing body framing closes each client-owned connection after the authenticated response is complete. This avoids asking Dolphin BBA to synthesize a remote reset while response data is pending. Exercise full fixed-length and chunked TLS responses with a peer that waits for client closure, and retain close-delimited compatibility coverage. --- docs/https.md | 8 ++++-- docs/network-runtime.md | 2 +- scripts/ci_https.py | 28 +++++++++++++++---- .../Dolphin/Network/Http/Http.cs | 2 +- 4 files changed, 31 insertions(+), 9 deletions(-) diff --git a/docs/https.md b/docs/https.md index 7667c6be..93e06e77 100644 --- a/docs/https.md +++ b/docs/https.md @@ -92,8 +92,12 @@ peer close-notify, so cancellation never blocks on TLS shutdown. Relative and scheme-relative redirects retain HTTPS. Cross-origin redirects (including scheme or effective-port changes) drop authorization/cookie headers. HTTPS-to-HTTP redirects fail. No application request bytes are sent until the -TLS handshake and server verification succeed. Existing Connection: close, -response buffering and body/header limits remain in force. +TLS handshake and server verification succeed. HTTP/1.1 requests allow the peer +to keep the connection open while the complete framed response is consumed. The +SDK still owns one connection per response and closes it at the content-length +or final chunk boundary, on disposal, cancellation or failure. Close-delimited +bodies still finish at peer EOF. There is no connection pooling. Response +buffering and body/header limits remain in force. ## Validation diff --git a/docs/network-runtime.md b/docs/network-runtime.md index 48d1ce75..da748b22 100644 --- a/docs/network-runtime.md +++ b/docs/network-runtime.md @@ -66,7 +66,7 @@ This is ordinary DNS, not DNSSEC or encrypted DNS. Query IDs combine a local cou HTTP uses an incremental parser over TCP. It supports fixed-length, chunked and close-delimited responses, informational responses, HEAD/no-body statuses, trailers, selected automatic GET/HEAD redirects, response headers and body streaming. Credentials are removed when redirects change authority. Redirect count defaults to five. Request framing headers are generated by the implementation and cannot be overridden. Ambiguous/duplicate framing, truncation, header injection and unsupported transfer/content encodings fail explicitly. -Headers are capped at 8 KiB/64 fields; chunk metadata at 256 bytes per line; trailers at 8 KiB. Convenience response buffering defaults to 64 KiB and can be configured through the Dolphin HttpClient API. Streamed bodies default to a 16 MiB cap. Set `Dolphin.Network.Http.HttpClient.MaximumStreamBytes` before sending a request to opt in to larger streamed bodies (up to `int.MaxValue` bytes). The limit is captured per request and applies to fixed, chunked and close-delimited bodies; buffered response limits remain independent. Use ResponseHeadersRead or GetStreamAsync for large data. GetStringAsync validates UTF-8. Connections use `Connection: close`; pooling, cookies, proxy support and decompression are deferred. +Headers are capped at 8 KiB/64 fields; chunk metadata at 256 bytes per line; trailers at 8 KiB. Convenience response buffering defaults to 64 KiB and can be configured through the Dolphin HttpClient API. Streamed bodies default to a 16 MiB cap. Set `Dolphin.Network.Http.HttpClient.MaximumStreamBytes` before sending a request to opt in to larger streamed bodies (up to `int.MaxValue` bytes). The limit is captured per request and applies to fixed, chunked and close-delimited bodies; buffered response limits remain independent. Use ResponseHeadersRead or GetStreamAsync for large data. GetStringAsync validates UTF-8. Requests use `Connection: keep-alive` so the peer can remain open until the complete framed response is consumed. Each response still owns one connection: the SDK closes it at the content-length or final chunk boundary, on disposal, cancellation or failure. Close-delimited bodies finish at peer EOF. Pooling, cookies, proxy support and decompression are deferred. `https://` is supported through the SDK native TLS provider after explicit trust, entropy and UTC initialization; see [HTTPS setup and limits](https.md). Missing configuration fails closed. There is no insecure certificate bypass. HTTP/2, HTTP/3/QUIC, HttpListener/ASP.NET, reflection serializers and legacy WebRequest/WebClient remain outside this subset. diff --git a/scripts/ci_https.py b/scripts/ci_https.py index 47aa849d..b169a07c 100644 --- a/scripts/ci_https.py +++ b/scripts/ci_https.py @@ -50,7 +50,7 @@ class Program { using(var client=new HttpClient()){ client.DefaultRequestHeaders.Add("authorization","test-secret"); -foreach(string path in new[]{"/final","/relative","/network","/cross","/chunked"}){var task=client.GetStringAsync($URL+path);Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 2;} +foreach(string path in new[]{"/final","/relative","/network","/cross","/chunked","/close-delimited"}){var task=client.GetStringAsync($URL+path);Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 2;} try{Wait(client.GetStringAsync($URL+"/downgrade"));return 3;}catch(IOException){} var streamTask=client.GetStreamAsync($URL+"/chunked");Wait(streamTask);using(var stream=streamTask.GetAwaiter().GetResult()){var b=new byte[8];int total=0;while(true){var r=stream.ReadAsync(b,0,b.Length);Wait(r);int n=r.GetAwaiter().GetResult();if(n==0)break;total+=n;}if(total!=2)return 4;} try{Wait(client.GetStringAsync($WRONG));return 5;}catch(IOException){} @@ -59,12 +59,13 @@ class Program { } foreach(int quantum in new[]{4096,16384}){ using(var client=new Dolphin.Network.Http.HttpClient()){client.StreamReadBufferSize=quantum; -foreach(string path in new[]{"/bulk","/bulk-chunked"}){ +foreach(string path in new[]{"/bulk","/bulk-chunked","/client-owned-close","/client-owned-close-chunked"}){ var pending=client.GetStreamAsync($URL+path);Wait(pending);using(var stream=pending.GetAwaiter().GetResult()){ var data=new byte[16384];int total=0,calls=0,largest=0; while(true){var read=stream.ReadAsync(data,0,data.Length);Wait(read);int n=read.GetAwaiter().GetResult();if(n==0)break;calls++;if(n>largest)largest=n;for(int i=0;iquantum||quantum==16384&&largest<=4096)return 21; Console.WriteLine("HTTP_QUANTUM="+quantum+" CALLS="+calls+" MAX="+largest+" BYTES="+total); +if(path=="/client-owned-close"||path=="/client-owned-close-chunked"){var closed=client.GetStringAsync($URL+"/client-owned-close-observed");Wait(closed);if(closed.GetAwaiter().GetResult()!="OK")return 35;} }}}} using(var bounds=new Dolphin.Network.Http.HttpClient()){foreach(int bad in new[]{0,4095,16385}){try{bounds.StreamReadBufferSize=bad;return 22;}catch(ArgumentOutOfRangeException){}}} TlsConfiguration.Reset();using(var client=new HttpClient()){try{Wait(client.GetStringAsync($URL+"/final"));return 6;}catch(IOException){}} @@ -107,6 +108,7 @@ def main(): listener=socket.socket();listener.bind(('127.0.0.1',0));listener.listen(8);listeners.append(listener) ports=[s.getsockname()[1] for s in listeners] errors=[] + owned_closed=threading.Event() def peer(connection,index): try: connection.settimeout(10) @@ -118,14 +120,26 @@ def peer(connection,index): request+=part path=request.split(b' ')[1] if index==1 and b'authorization:' in request.lower():errors.append('credentials crossed origins') - if path in (b'/bulk',b'/bulk-chunked'): + if path in (b'/bulk',b'/bulk-chunked',b'/client-owned-close',b'/client-owned-close-chunked'): + client_closes=path.startswith(b'/client-owned-close') + if client_closes: + owned_closed.clear() + if b'\r\nconnection: keep-alive\r\n' not in request.lower():errors.append('framed response requested premature server closure') data=bytes(i%251 for i in range(65567)) - chunked=path==b'/bulk-chunked' + chunked=path in (b'/bulk-chunked',b'/client-owned-close-chunked') stream.sendall(b'HTTP/1.1 200 OK\r\n'+(b'Transfer-Encoding: chunked' if chunked else b'Content-Length: 65567')+b'\r\n\r\n') for offset in range(0,len(data),16384): part=data[offset:offset+16384] stream.sendall((f'{len(part):x}\r\n'.encode()+part+b'\r\n') if chunked else part) if chunked:stream.sendall(b'0\r\n\r\n') + if client_closes: + try: + if stream.recv(1):errors.append('unexpected data after complete response') + else:owned_closed.set() + except (ssl.SSLEOFError,ssl.SSLZeroReturnError,ConnectionResetError): + owned_closed.set() + except (ssl.SSLError,TimeoutError,OSError) as error: + errors.append('client did not close framed response: '+type(error).__name__) return if path==b'/relative':reply=b'HTTP/1.1 302 Found\r\nLocation: /final\r\nContent-Length: 0\r\n\r\n' elif path==b'/network':reply=f'HTTP/1.1 302 Found\r\nLocation: //localhost:{ports[0]}/final\r\nContent-Length: 0\r\n\r\n'.encode() @@ -133,6 +147,10 @@ def peer(connection,index): elif path==b'/downgrade':reply=f'HTTP/1.1 302 Found\r\nLocation: http://localhost:{ports[0]}/final\r\nContent-Length: 0\r\n\r\n'.encode() elif path==b'/truncated':reply=b'HTTP/1.1 200 OK\r\nContent-Length: 50\r\n\r\nshort' elif path==b'/chunked':reply=b'HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n1\r\nO\r\n1\r\nK\r\n0\r\n\r\n' + elif path==b'/close-delimited':reply=b'HTTP/1.1 200 OK\r\nConnection: close\r\n\r\nOK' + elif path==b'/client-owned-close-observed': + if not owned_closed.wait(5):errors.append('framed response connection remained open') + reply=b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK' else:reply=b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK' for byte in reply:stream.sendall(bytes([byte])) if path==b'/pipe':stream.unwrap() @@ -162,5 +180,5 @@ def serve(listener,index): if errors:raise AssertionError(errors) finally: for listener in listeners:listener.close() - print('SDK HTTPS Debug/Release AOT + GC stress: exact/local-clock initialization and seed wiping, verified buffered/streamed/chunked bodies, relative redirects, credential isolation, downgrade rejection and missing configuration passed.') + print('SDK HTTPS Debug/Release AOT + GC stress: exact/local-clock initialization and seed wiping, verified buffered/streamed/chunked/close-delimited bodies, client-owned framed connection closure, relative redirects, credential isolation, downgrade rejection and missing configuration passed.') if __name__=='__main__':main() diff --git a/src/DolphinDotNet.Core/Dolphin/Network/Http/Http.cs b/src/DolphinDotNet.Core/Dolphin/Network/Http/Http.cs index a5791ed4..8bfbac4e 100644 --- a/src/DolphinDotNet.Core/Dolphin/Network/Http/Http.cs +++ b/src/DolphinDotNet.Core/Dolphin/Network/Http/Http.cs @@ -136,7 +136,7 @@ private bool Redirect(HttpResponseMessage response) } private byte[] BuildRequest() { - string text=string.Concat(string.Concat(request.Method.Method," "),string.Concat(url.Path," HTTP/1.1\r\nHost: "));text=string.Concat(text,string.Concat(url.Authority,"\r\nConnection: close\r\nAccept-Encoding: identity\r\n")); + string text=string.Concat(string.Concat(request.Method.Method," "),string.Concat(url.Path," HTTP/1.1\r\nHost: "));text=string.Concat(text,string.Concat(url.Authority,"\r\nConnection: keep-alive\r\nAccept-Encoding: identity\r\n")); Append(owner.DefaultRequestHeaders,ref text,crossOrigin);Append(request.Headers,ref text,crossOrigin);if(request.Content!=null){if(request.Content.Bytes==null)throw new NotSupportedException("Only bounded byte/string request content is supported.");Append(request.Content.Headers,ref text);text=string.Concat(text,string.Concat("Content-Length: ",string.Concat(request.Content.Bytes.Length.ToString(),"\r\n")));} text=string.Concat(text,"\r\n");var head=Encoding.ASCII.GetBytes(text);var payload=request.Content?.Bytes;if(head.Length>8192||(payload!=null&&payload.Length>65536))throw new IOException("HTTP request exceeds limits.");var all=new byte[head.Length+(payload==null?0:payload.Length)];Array.Copy(head,all,head.Length);if(payload!=null)Array.Copy(payload,0,all,head.Length,payload.Length);return all; } From 473a0286e78d21abf6b396b07f94cdcba51be295 Mon Sep 17 00:00:00 2001 From: capz <345101+capz@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:46:19 +0100 Subject: [PATCH 4/4] Send TLS close-notify for the close-delimited HTTPS fixture A response without HTTP length framing needs authenticated TLS EOF. Send close-notify as the existing raw TLS fixture does, retaining the provider's rejection of unauthenticated truncation. Include the current fixture path and numeric provider error in failure output. --- scripts/ci_https.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/scripts/ci_https.py b/scripts/ci_https.py index b169a07c..bebd82b0 100644 --- a/scripts/ci_https.py +++ b/scripts/ci_https.py @@ -50,7 +50,7 @@ class Program { using(var client=new HttpClient()){ client.DefaultRequestHeaders.Add("authorization","test-secret"); -foreach(string path in new[]{"/final","/relative","/network","/cross","/chunked","/close-delimited"}){var task=client.GetStringAsync($URL+path);Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 2;} +foreach(string path in new[]{"/final","/relative","/network","/cross","/chunked","/close-delimited"}){Console.WriteLine("HTTP_PATH="+path);var task=client.GetStringAsync($URL+path);Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 2;} try{Wait(client.GetStringAsync($URL+"/downgrade"));return 3;}catch(IOException){} var streamTask=client.GetStreamAsync($URL+"/chunked");Wait(streamTask);using(var stream=streamTask.GetAwaiter().GetResult()){var b=new byte[8];int total=0;while(true){var r=stream.ReadAsync(b,0,b.Length);Wait(r);int n=r.GetAwaiter().GetResult();if(n==0)break;total+=n;}if(total!=2)return 4;} try{Wait(client.GetStringAsync($WRONG));return 5;}catch(IOException){} @@ -60,6 +60,7 @@ class Program { foreach(int quantum in new[]{4096,16384}){ using(var client=new Dolphin.Network.Http.HttpClient()){client.StreamReadBufferSize=quantum; foreach(string path in new[]{"/bulk","/bulk-chunked","/client-owned-close","/client-owned-close-chunked"}){ +Console.WriteLine("HTTP_STREAM_PATH="+path+" QUANTUM="+quantum); var pending=client.GetStreamAsync($URL+path);Wait(pending);using(var stream=pending.GetAwaiter().GetResult()){ var data=new byte[16384];int total=0,calls=0,largest=0; while(true){var read=stream.ReadAsync(data,0,data.Length);Wait(read);int n=read.GetAwaiter().GetResult();if(n==0)break;calls++;if(n>largest)largest=n;for(int i=0;i