Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion .github/workflows/nuget-preview.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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('<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net8.0</TargetFramework></PropertyGroup><ItemGroup><PackageReference Include="DolphinDotNet.GameCube" Version="[' + version + ']" /></ItemGroup></Project>')
config = root / 'NuGet.Config'
config.write_text('<configuration><packageSources><clear /><add key="nuget.org" value="https://api.nuget.org/v3/index.json" /></packageSources></configuration>')
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
15 changes: 13 additions & 2 deletions docs/https.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -143,3 +147,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.
2 changes: 1 addition & 1 deletion docs/network-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
36 changes: 29 additions & 7 deletions scripts/ci_https.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<seed.Length;i++)if(seed[i]!=0)return 1;
if(TlsConfiguration.LastErrorCode!=0)return 32;
var pipeTask=TlsStream.ConnectAsync("localhost",$PORT,default);Wait(pipeTask);
using(var pipe=pipeTask.GetAwaiter().GetResult()){
var masks=new byte[256];pipe.FillRandom(masks,0,masks.Length);bool any=false;for(int i=0;i<masks.Length;i++)any|=masks[i]!=0;if(!any)return 31;
Expand All @@ -44,11 +45,12 @@ class Program {
pipe.Dispose();try{pipe.TryWrite(request,0,1);return 28;}catch(ObjectDisposedException){}
}
try{Wait(TlsStream.ConnectAsync("wrong.example",$PORT,default));return 29;}catch(IOException){}
if(TlsConfiguration.LastErrorCode>=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()){
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"}){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){}
Expand All @@ -57,12 +59,14 @@ 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"}){
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<n;i++)if(data[i]!=(byte)((total+i)%251))return 20;total+=n;}
if(total!=65567||largest>quantum||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){}}
Expand All @@ -74,10 +78,11 @@ class Program {
for(int i=0;i<rejected.Length;i++)if(rejected[i]!=0)return 12;
var localSeed=new byte[]{$LOCAL_ENTROPY};TlsConfiguration.InitializeFromLocalClock(ca,localSeed,$LOCAL);
for(int i=0;i<localSeed.Length;i++)if(localSeed[i]!=0)return 13;
if(TlsConfiguration.LastErrorCode!=0)return 34;
using(var client=new HttpClient()){var task=client.GetStringAsync($URL+"/final");Wait(task);if(task.GetAwaiter().GetResult()!="OK")return 14;}
TlsConfiguration.Reset();
NetworkRuntime.Stop();return 0;
}catch(Exception e){Console.WriteLine(e.Message);return 99;}}
}catch(Exception e){Console.WriteLine("TLS_ERROR="+TlsConfiguration.LastErrorCode);Console.WriteLine(e.Message);return 99;}}
}''').substitute(CA=json.dumps(roots),ENTROPY=','.join(map(str,entropy)),LOCAL_ENTROPY=','.join(map(str,local_entropy)),UTC=str(utc),LOCAL=str(utc+2*86400),URL=json.dumps(url),WRONG=json.dumps(wrong),PORT=str(__import__('urllib.parse',fromlist=['urlsplit']).urlsplit(url).port))

def main():
Expand All @@ -104,6 +109,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)
Expand All @@ -115,24 +121,40 @@ 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()
elif path==b'/cross':reply=f'HTTP/1.1 302 Found\r\nLocation: https://localhost:{ports[1]}/final\r\nContent-Length: 0\r\n\r\n'.encode()
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()
if path in (b'/pipe',b'/close-delimited'):stream.unwrap()
except (ssl.SSLError,ConnectionError,TimeoutError,OSError):pass
def serve(listener,index):
while True:
Expand All @@ -159,5 +181,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()
2 changes: 1 addition & 1 deletion src/DolphinDotNet.Core/Dolphin/Network/Http/Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
1 change: 1 addition & 0 deletions src/DolphinDotNet.Core/Dolphin/Network/NativeNetwork.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ internal static class NativeNetwork
internal static int TlsConfigure(byte[] roots,byte[] entropy,long unixSeconds)=>throw 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();
Expand Down
6 changes: 6 additions & 0 deletions src/DolphinDotNet.Core/Dolphin/Network/TlsConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ namespace Dolphin.Network;
/// copied natively. The entropy array is cleared, including on failure.</summary>
public static class TlsConfiguration
{
/// <summary>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.</summary>
public static int LastErrorCode=>NativeNetwork.TlsError();

/// <param name="trustedRootsPem">Explicit PEM trust anchors, maximum 256 KiB.</param>
/// <param name="freshEntropy">48–64 cryptographically random secret bytes, fresh
/// for every initialization and process boot. Never use Random, ticks, public
Expand Down
1 change: 1 addition & 0 deletions tools/DolphinDotNet.Compiler/NativeStorageBindings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading