diff --git a/src/Foundation/NSUrlSessionHandler.cs b/src/Foundation/NSUrlSessionHandler.cs index cd11b15cf7c8..58cd2cf9b43a 100644 --- a/src/Foundation/NSUrlSessionHandler.cs +++ b/src/Foundation/NSUrlSessionHandler.cs @@ -379,6 +379,7 @@ internal void EnsureModifiability () static Exception createExceptionForNSError (NSError error) { var innerException = new NSErrorException (error); + var requestError = HttpRequestError.Unknown; // errors that exists in both share the same error code, so we can use a single switch/case // this also ease watchOS integration as if does not expose CFNetwork but (I would not be @@ -392,10 +393,28 @@ static Exception createExceptionForNSError (NSError error) case (NSUrlError) NSNetServicesStatus.CancelledError: // No more processing is required so just return. return new OperationCanceledException (error.LocalizedDescription, innerException); + case NSUrlError.CannotFindHost: + case NSUrlError.DNSLookupFailed: + requestError = HttpRequestError.NameResolutionError; + break; + case NSUrlError.CannotConnectToHost: + case NSUrlError.NetworkConnectionLost: + case NSUrlError.NotConnectedToInternet: + requestError = HttpRequestError.ConnectionError; + break; + case NSUrlError.SecureConnectionFailed: + case NSUrlError.ServerCertificateHasBadDate: + case NSUrlError.ServerCertificateUntrusted: + case NSUrlError.ServerCertificateHasUnknownRoot: + case NSUrlError.ServerCertificateNotYetValid: + case NSUrlError.ClientCertificateRejected: + case NSUrlError.ClientCertificateRequired: + requestError = HttpRequestError.SecureConnectionError; + break; } } - return new HttpRequestException (error.LocalizedDescription, innerException); + return new HttpRequestException (requestError, error.LocalizedDescription, innerException); } string GetHeaderSeparator (string name) @@ -972,6 +991,17 @@ void UpdateManagedCookieContainer (Uri absoluteUri, NSHttpCookie [] cookies) } } + void ClearClientCertificateException (InflightData inflight) + { + lock (inflight.Lock) { + if (!inflight.IsClientCertificateException) + return; + + inflight.Exception = null; + inflight.IsClientCertificateException = false; + } + } + [Preserve (Conditional = true)] public override void DidReceiveResponse (NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action completionHandler) { @@ -992,6 +1022,8 @@ void DidReceiveResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask return; } + ClearClientCertificateException (inflight); + try { var urlResponse = (NSHttpUrlResponse) response; var status = (int) urlResponse.StatusCode; @@ -1120,7 +1152,19 @@ public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTas inflight.CancellationTokenSource.Cancel (); inflight.Errored = true; - var exc = inflight.Exception ?? createExceptionForNSError (error ?? serverError!); // client errors wont happen if we get server errors + var nativeException = createExceptionForNSError (error ?? serverError!); + var nativeExceptionIsSecureConnectionError = nativeException is HttpRequestException requestException && + requestException.HttpRequestError == HttpRequestError.SecureConnectionError; + Exception? exception; + bool isClientCertificateException; + lock (inflight.Lock) { + exception = inflight.Exception; + isClientCertificateException = inflight.IsClientCertificateException; + } + if (isClientCertificateException && !nativeExceptionIsSecureConnectionError) + exception = null; + + var exc = exception ?? nativeException; // client errors wont happen if we get server errors inflight.CompletionSource.TrySetException (exc); inflight.Stream.TrySetException (exc); } else { @@ -1188,14 +1232,16 @@ void WillCacheResponseImpl (NSUrlSession session, NSUrlSessionDataTask dataTask, [Preserve (Conditional = true)] public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action completionHandler) { - if (!sessionHandler.AllowAutoRedirect) { + var inflight = GetInflightData (task); + + if (inflight is null) { completionHandler (null); return; } - var inflight = GetInflightData (task); + ClearClientCertificateException (inflight); - if (inflight is null) { + if (!sessionHandler.AllowAutoRedirect) { completionHandler (null); return; } @@ -1257,7 +1303,8 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl // user callback rejected the certificate, we want to set the exception, else the user will // see as if the request was cancelled. lock (inflight.Lock) { - inflight.Exception = new HttpRequestException ("An error occurred while sending the request.", new WebException ("Error: TrustFailure")); + inflight.IsClientCertificateException = false; + inflight.Exception = new HttpRequestException (HttpRequestError.SecureConnectionError, "An error occurred while sending the request.", new WebException ("Error: TrustFailure")); } completionHandler (NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null!); } @@ -1277,7 +1324,8 @@ void DidReceiveChallengeImpl (NSUrlSession session, NSUrlSessionTask task, NSUrl // that allows the developer to identify this, ask the user for a certificate, add it to the ClientCertificates collection // and then re-try the request. lock (inflight.Lock) { - inflight.Exception = new HttpRequestException ("An error occurred while sending the request.", + inflight.IsClientCertificateException = true; + inflight.Exception = new HttpRequestException (HttpRequestError.SecureConnectionError, "An error occurred while sending the request.", new WebException ("Error: Certificate Required", new AuthenticationException ("Error: Certificate Required"), WebExceptionStatus.SecureChannelFailure, null)); @@ -1486,6 +1534,7 @@ class InflightData { public HttpResponseMessage? Response { get; set; } public Exception? Exception { get; set; } + public bool IsClientCertificateException { get; set; } public bool ResponseSent { get; set; } public bool Errored { get; set; } public bool Disposed { get; set; } diff --git a/tests/monotouch-test/System.Net.Http/MessageHandlers.cs b/tests/monotouch-test/System.Net.Http/MessageHandlers.cs index 9172c64c587c..c570605a3268 100644 --- a/tests/monotouch-test/System.Net.Http/MessageHandlers.cs +++ b/tests/monotouch-test/System.Net.Http/MessageHandlers.cs @@ -831,11 +831,17 @@ public void TestNSUrlSessionHandlerDetectMissingClientCertificate () await client.GetAsync ($"https://localhost:{port}/"); }, out var ex); Assert.That (done, Is.True, "Request to localhost timed out."); - Assert.That (ex, Is.Not.Null, "Exception was expected."); - Assert.That (ex, Is.InstanceOf (typeof (HttpRequestException)), "Exception"); - Assert.That (ex!.InnerException, Is.InstanceOf (typeof (WebException)), "InnerException Type"); - Assert.That (((WebException) ex.InnerException!).Status, Is.EqualTo (WebExceptionStatus.SecureChannelFailure), "InnerException Status"); - Assert.That (ex.InnerException.InnerException, Is.InstanceOf (typeof (AuthenticationException)), "InnerException.InnerException Type"); + var requestException = ex as HttpRequestException; + Assert.That (requestException, Is.Not.Null, "Exception was expected."); + if (requestException is null) + return; + Assert.That (requestException.HttpRequestError, Is.EqualTo (HttpRequestError.SecureConnectionError), "HttpRequestError"); + var webException = requestException.InnerException as WebException; + Assert.That (webException, Is.Not.Null, "InnerException Type"); + if (webException is null) + return; + Assert.That (webException.Status, Is.EqualTo (WebExceptionStatus.SecureChannelFailure), "InnerException Status"); + Assert.That (webException.InnerException, Is.InstanceOf (typeof (AuthenticationException)), "InnerException.InnerException Type"); } finally { listener?.Cancel (); listener?.Dispose (); diff --git a/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs b/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs index e6741dc56b36..83e192716ce8 100644 --- a/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs +++ b/tests/monotouch-test/System.Net.Http/NSUrlSessionHandlerTest.cs @@ -5,15 +5,18 @@ using System; using System.Collections.Concurrent; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Net.Sockets; +using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Foundation; using NUnit.Framework; +using ObjCRuntime; using Xamarin.Utils; namespace MonoTests.System.Net.Http { @@ -27,6 +30,234 @@ public class NSUrlSessionHandlerTest { // behavior if these tests ever turn out to be flaky on the bots. bool ignoreLocalOnlyCIFailures = false; + [TestCase (NSUrlError.CannotFindHost, "url", HttpRequestError.NameResolutionError)] + [TestCase (NSUrlError.DNSLookupFailed, "network", HttpRequestError.NameResolutionError)] + [TestCase (NSUrlError.CannotConnectToHost, "url", HttpRequestError.ConnectionError)] + [TestCase (NSUrlError.SecureConnectionFailed, "url", HttpRequestError.SecureConnectionError)] + [TestCase (NSUrlError.ServerCertificateUntrusted, "network", HttpRequestError.SecureConnectionError)] + [TestCase (NSUrlError.BadServerResponse, "url", HttpRequestError.Unknown)] + [TestCase (NSUrlError.CannotFindHost, "other", HttpRequestError.Unknown)] + public void NativeErrorHasHttpRequestError (NSUrlError code, string domain, HttpRequestError expected) + { + using var configuration = NSUrlSessionConfiguration.EphemeralSessionConfiguration; + using var protocolClasses = NSArray.FromNSObjects (new Class (typeof (FailingUrlProtocol))); + configuration.WeakProtocolClasses = protocolClasses; + + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var handler = new NSUrlSessionHandler (configuration); + using var client = new HttpClient (handler); + await client.GetAsync ($"https://{domain}.test/{((int) code).ToString (CultureInfo.InvariantCulture)}").ConfigureAwait (false); + }, out var exception); + + Assert.That (done, Is.True, "Request timed out"); + var requestException = exception as HttpRequestException; + Assert.That (requestException, Is.Not.Null, "Exception"); + if (requestException is null) + return; + Assert.That (requestException.HttpRequestError, Is.EqualTo (expected), "HttpRequestError"); + var innerException = requestException.InnerException as NSErrorException; + Assert.That (innerException, Is.Not.Null, "Inner exception"); + if (innerException is null) + return; + Assert.That (innerException.Code, Is.EqualTo ((nint) code), "Native error code"); + Assert.That (requestException.Message, Is.EqualTo (innerException.Error.LocalizedDescription), "Message"); + } + + [Preserve (AllMembers = true)] + public class FailingUrlProtocol : NSUrlProtocol { + [Export ("canInitWithRequest:")] + public static new bool CanInitWithRequest (NSUrlRequest request) => true; + + [Export ("canonicalRequestForRequest:")] + public static new NSUrlRequest GetCanonicalRequest (NSUrlRequest request) => request; + + [Export ("initWithRequest:cachedResponse:client:")] + public FailingUrlProtocol (NSUrlRequest request, NSCachedUrlResponse? cachedResponse, INSUrlProtocolClient client) + : base (request, cachedResponse, client) + { + } + + [Export ("startLoading")] + public override void StartLoading () + { + var url = Request.Url; + if (url is null || !int.TryParse (url.LastPathComponent, NumberStyles.Integer, CultureInfo.InvariantCulture, out var errorCode)) + throw new InvalidOperationException ("The URL must contain an error code in its last path component."); + var domain = url.Host switch { + "url.test" => NSError.NSUrlErrorDomain, + "network.test" => NSError.CFNetworkErrorDomain, + _ => NSError.CocoaErrorDomain, + }; + using var error = new NSError (domain, errorCode); + Client.FailedWithError (this, error); + } + + [Export ("stopLoading")] + public override void StopLoading () + { + } + } + + [TestCase ("connection", NSUrlError.CannotConnectToHost, HttpRequestError.ConnectionError)] + [TestCase ("redirect", NSUrlError.ServerCertificateUntrusted, HttpRequestError.SecureConnectionError)] + public void ClientCertificateErrorDoesNotMaskLaterNativeError (string scenario, NSUrlError expectedCode, HttpRequestError expectedError) + { + using var configuration = NSUrlSessionConfiguration.EphemeralSessionConfiguration; + using var protocolClasses = NSArray.FromNSObjects (new Class (typeof (ClientCertificateUrlProtocol))); + configuration.WeakProtocolClasses = protocolClasses; + + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var handler = new NSUrlSessionHandler (configuration) { + ClientCertificateOptions = ClientCertificateOption.Manual, + UseProxy = false, + }; + using var client = new HttpClient (handler); + await client.GetAsync ($"https://client-certificate.test/{scenario}").ConfigureAwait (false); + }, out var exception); + + Assert.That (done, Is.True, "Request timed out"); + var requestException = exception as HttpRequestException; + Assert.That (requestException, Is.Not.Null, "Exception"); + if (requestException is null) + return; + Assert.That (requestException.HttpRequestError, Is.EqualTo (expectedError), "HttpRequestError"); + var innerException = requestException.InnerException as NSErrorException; + Assert.That (innerException, Is.Not.Null, "Inner exception"); + if (innerException is null) + return; + Assert.That (innerException.Code, Is.EqualTo ((nint) expectedCode), "Native error code"); + } + + [Preserve (AllMembers = true)] + public class ClientCertificateUrlProtocol : NSUrlProtocol { + ClientCertificateChallengeSender? challengeSender; + + [DllImport (Constants.ObjectiveCLibrary, EntryPoint = "objc_msgSend")] + static extern IntPtr InitChallenge (IntPtr receiver, IntPtr selector, IntPtr space, IntPtr credential, nint failureCount, IntPtr response, IntPtr error, IntPtr sender); + + [Export ("canInitWithRequest:")] + public static new bool CanInitWithRequest (NSUrlRequest request) => true; + + [Export ("canonicalRequestForRequest:")] + public static new NSUrlRequest GetCanonicalRequest (NSUrlRequest request) => request; + + [Export ("initWithRequest:cachedResponse:client:")] + public ClientCertificateUrlProtocol (NSUrlRequest request, NSCachedUrlResponse? cachedResponse, INSUrlProtocolClient client) + : base (request, cachedResponse, client) + { + } + + [Export ("startLoading")] + public override void StartLoading () + { + var url = Request.Url ?? throw new InvalidOperationException ("The request must have a URL."); + if (url.LastPathComponent == "tls") { + Fail (NSUrlError.ServerCertificateUntrusted); + return; + } + + challengeSender = new ClientCertificateChallengeSender (this); + using var space = new NSUrlProtectionSpace ("client-certificate.test", 443, NSUrlProtectionSpace.HTTPS, null, NSUrlProtectionSpace.AuthenticationMethodClientCertificate); + // The managed constructor requires a non-null credential and an NSUrlConnection sender. + var allocated = Messaging.IntPtr_objc_msgSend (Class.GetHandle (typeof (NSUrlAuthenticationChallenge)), Selector.GetHandle ("alloc")); + var handle = InitChallenge (allocated, Selector.GetHandle ("initWithProtectionSpace:proposedCredential:previousFailureCount:failureResponse:error:sender:"), space.Handle, IntPtr.Zero, 0, IntPtr.Zero, IntPtr.Zero, challengeSender.Handle); + using var challenge = Runtime.GetNSObject (handle, owns: true) ?? throw new InvalidOperationException ("Could not create an authentication challenge."); + Client.ReceivedAuthenticationChallenge (this, challenge); + } + + public void CompleteChallenge () + { + var url = Request.Url ?? throw new InvalidOperationException ("The request must have a URL."); + if (url.LastPathComponent == "connection") { + Fail (NSUrlError.CannotConnectToHost); + return; + } + if (url.LastPathComponent != "redirect") + throw new InvalidOperationException ("Unexpected request URL."); + + using var destination = new NSUrl ("https://client-certificate.test/tls"); + using var request = new NSUrlRequest (destination); + using var headers = new NSDictionary ("Location", "https://client-certificate.test/tls"); + using var response = new NSHttpUrlResponse (url, 302, "HTTP/1.1", headers); + Client.Redirected (this, request, response); + } + + public void Fail (NSUrlError code) + { + using var error = new NSError (NSError.NSUrlErrorDomain, (nint) code); + Client.FailedWithError (this, error); + } + + [Export ("stopLoading")] + public override void StopLoading () + { + challengeSender = null; + } + } + + [Preserve (AllMembers = true)] + public class ClientCertificateChallengeSender : NSObject, INSUrlAuthenticationChallengeSender { + readonly ClientCertificateUrlProtocol protocol; + + public ClientCertificateChallengeSender (ClientCertificateUrlProtocol protocol) + { + this.protocol = protocol; + } + + [Export ("useCredential:forAuthenticationChallenge:")] + public void UseCredential (NSUrlCredential credential, NSUrlAuthenticationChallenge challenge) => protocol.Fail (NSUrlError.ClientCertificateRejected); + + [Export ("continueWithoutCredentialForAuthenticationChallenge:")] + public void ContinueWithoutCredential (NSUrlAuthenticationChallenge challenge) => protocol.CompleteChallenge (); + + [Export ("cancelAuthenticationChallenge:")] + public void CancelAuthenticationChallenge (NSUrlAuthenticationChallenge challenge) => protocol.Fail (NSUrlError.UserCancelledAuthentication); + + [Export ("performDefaultHandlingForAuthenticationChallenge:")] + public void PerformDefaultHandling (NSUrlAuthenticationChallenge challenge) => protocol.CompleteChallenge (); + + [Export ("rejectProtectionSpaceAndContinueWithChallenge:")] + public void RejectProtectionSpaceAndContinue (NSUrlAuthenticationChallenge challenge) => protocol.Fail (NSUrlError.UserAuthenticationRequired); + } + + [TestCase (0)] + [TestCase (1)] + [TestCase (2)] + public void RejectedServerCertificateHasSecureConnectionError (int callback) + { + using var listener = TlsTestServer.CreateNWTlsListener (requireClientCert: false); + try { + var done = TestRuntime.TryRunAsync (TimeSpan.FromSeconds (30), async () => { + using var handler = new NSUrlSessionHandler { UseProxy = false }; + if (callback == 1) + handler.TrustOverrideForUrl = (sender, url, trust) => false; + else if (callback == 2) + handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) => false; + using var client = new HttpClient (handler); + await client.GetAsync ($"https://localhost:{listener.Port}/").ConfigureAwait (false); + }, out var exception); + + Assert.That (done, Is.True, "Request timed out"); + var requestException = exception as HttpRequestException; + Assert.That (requestException, Is.Not.Null, "Exception"); + if (requestException is null) + return; + Assert.That (requestException.HttpRequestError, Is.EqualTo (HttpRequestError.SecureConnectionError), "HttpRequestError"); + if (callback == 0) { + Assert.That (requestException.InnerException, Is.TypeOf (), "Inner exception"); + } else { + Assert.That (requestException.Message, Is.EqualTo ("An error occurred while sending the request."), "Message"); + var innerException = requestException.InnerException as WebException; + Assert.That (innerException, Is.Not.Null, "Inner exception"); + if (innerException is null) + return; + Assert.That (innerException.Message, Is.EqualTo ("Error: TrustFailure"), "Inner exception message"); + } + } finally { + listener.Cancel (); + } + } + [Test] public void StreamReadAsyncWaitsForDataWithoutPolling () {