xamarin-macios/tests/monotouch-test/System.Net.Http/MessageHandlers.cs

598 строки
21 KiB
C#
Исходник Обычный вид История

//
// MessageHandlers.cs
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Linq;
using System.IO;
using NUnit.Framework;
using System.Net;
using System.Net.Http.Headers;
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
using System.Security.Authentication;
using System.Text;
using Foundation;
#if MONOMAC
using Foundation;
#endif
using ObjCRuntime;
namespace MonoTests.System.Net.Http
{
[TestFixture]
public class MessageHandlerTest
{
void PrintHandlerToTest ()
{
#if !__WATCHOS__
Console.WriteLine (new HttpClientHandler ());
Console.WriteLine (new CFNetworkHandler ());
#endif
Console.WriteLine (new NSUrlSessionHandler ());
}
HttpMessageHandler GetHandler (Type handler_type)
{
return (HttpMessageHandler) Activator.CreateInstance (handler_type);
}
[Test]
#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
[TestCase (typeof (CFNetworkHandler))]
#endif
[TestCase (typeof (NSUrlSessionHandler))]
public void DnsFailure (Type handlerType)
{
TestRuntime.AssertSystemVersion (PlatformName.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);
PrintHandlerToTest ();
bool done = false;
string response = null;
Exception ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (GetHandler (handlerType));
response = await client.GetStringAsync ("http://doesnotexist.xamarin.com");
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
Assert.IsTrue (done, "Did not time out");
Assert.IsNull (response, $"Response is not null {response}");
[httpclient] Change NSUrlSessionHandler and CFNetworkHandler to throw HttpRequestException. Fix #6439 (#6477) Our 3 different handlers were inconsistent with each others. Only the managed version, `HttpClientHandler`, was throwing the documented `HttpRequestException` exception. The inconsistency make this hard to consume from .net standard libraries even more when the type is not, itself, available in .net standard stack trace (for NSUrlSessionHandler) ``` 2019-07-02 10:58:08.352 gh6439[18579:15880723] System.Net.WebException: The Internet connection appears to be offline. ---> Foundation.NSErrorException: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x283b6d350 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <55894EBD-B898-4803-9981-46317EEFE280>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <55894EBD-B898-4803-9981-46317EEFE280>.<1>" ), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=https://www.microsoft.com/fr-ca/, NSErrorFailingURLKey=https://www.microsoft.com/fr-ca/, _kCFStreamErrorDomainKey=1} --- End of inner exception stack trace --- at System.Net.Http.NSUrlSessionHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x001d4] in /Users/poupou/git/xcode11/xamarin-macios/src/Foundation/NSUrlSessionHandler.cs:541 at System.Net.Http.HttpClient.SendAsyncWorker (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x0009e] in /Users/poupou/git/xcode11/xamarin-macios/external/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:281 ``` stack trace (for CFNetworkHandler) ``` 2019-07-02 11:04:35.407 gh6439[18580:15881497] CoreFoundation.CFException: The operation couldn’t be completed. Network is down at System.Net.Http.CFNetworkHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken, System.Boolean isFirstRequest) [0x002f2] in /Users/poupou/git/xcode11/xamarin-macios/src/System.Net.Http/CFNetworkHandler.cs:266 at System.Net.Http.CFNetworkHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00034] in /Users/poupou/git/xcode11/xamarin-macios/src/System.Net.Http/CFNetworkHandler.cs:199 at System.Net.Http.HttpClient.SendAsyncWorker (System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) [0x0009e] in /Users/poupou/git/xcode11/xamarin-macios/external/mono/mcs/class/System.Net.Http/System.Net.Http/HttpClient.cs:281 ``` references: * https://github.com/xamarin/xamarin-macios/issues/6439 * https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=netstandard-2.0#System_Net_Http_HttpClient_PostAsync_System_String_System_Net_Http_HttpContent_System_Threading_CancellationToken_
2019-07-04 16:50:27 +03:00
Assert.IsInstanceOfType (typeof (HttpRequestException), ex, "Exception");
}
#if !__WATCHOS__
// ensure that we do get the same cookies as the managed handler
[Test]
public void TestNSUrlSessionHandlerCookies ()
{
var managedCookieResult = false;
var nativeCookieResult = false;
Exception ex = null;
var completed = false;
IEnumerable<string> nativeCookies = null;
IEnumerable<string> managedCookies = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
var url = NetworkResources.Httpbin.GetSetCookieUrl ("cookie", "chocolate-chip");
try {
var managedHandler = new HttpClientHandler () {
AllowAutoRedirect = false,
};
var managedClient = new HttpClient (managedHandler);
var managedResponse = await managedClient.GetAsync (url);
managedCookieResult = managedResponse.Headers.TryGetValues ("Set-Cookie", out managedCookies);
var nativeHandler = new NSUrlSessionHandler () {
AllowAutoRedirect = false,
};
nativeHandler.AllowAutoRedirect = true;
var nativeClient = new HttpClient (nativeHandler);
var nativeResponse = await nativeClient.GetAsync (url);
nativeCookieResult = nativeResponse.Headers.TryGetValues ("Set-Cookie", out nativeCookies);
} catch (Exception e) {
ex = e;
} finally {
completed = true;
}
}, () => completed);
Assert.IsNull (ex, "Exception");
Assert.IsTrue (managedCookieResult, $"Failed to get managed cookies");
Assert.IsTrue (nativeCookieResult, $"Failed to get native cookies");
Assert.AreEqual (1, managedCookies.Count (), $"Managed Cookie Count");
Assert.AreEqual (1, nativeCookies.Count (), $"Native Cookie Count");
Assert.That (nativeCookies.First (), Is.StringStarting ("cookie=chocolate-chip;"), $"Native Cookie Value");
Assert.That (managedCookies.First (), Is.StringStarting ("cookie=chocolate-chip;"), $"Managed Cookie Value");
}
// ensure that we can use a cookie container to set the cookies for a url
[Test]
public void TestNSUrlSessionHandlerCookieContainer ()
{
var url = NetworkResources.Httpbin.CookiesUrl;
var cookie = new Cookie ("cookie", "chocolate-chip");
var cookieContainer = new CookieContainer ();
cookieContainer.Add (new Uri (url), cookie);
string managedCookieResult = null;
string nativeCookieResult = null;
Exception ex = null;
var completed = false;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var managedHandler = new HttpClientHandler () {
AllowAutoRedirect = false,
CookieContainer = cookieContainer,
};
var managedClient = new HttpClient (managedHandler);
var managedResponse = await managedClient.GetAsync (url);
managedCookieResult = await managedResponse.Content.ReadAsStringAsync ();
var nativeHandler = new NSUrlSessionHandler () {
AllowAutoRedirect = true,
CookieContainer = cookieContainer,
};
var nativeClient = new HttpClient (nativeHandler);
var nativeResponse = await nativeClient.GetAsync (url);
nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
} catch (Exception e) {
ex = e;
} finally {
completed = true;
}
}, () => completed);
Assert.IsNull (ex, "Exception");
Assert.IsNotNull (managedCookieResult, "Managed cookies result");
Assert.IsNotNull (nativeCookieResult, "Native cookies result");
Assert.AreEqual (managedCookieResult, nativeCookieResult, "Cookies");
}
// ensure that the Set-Cookie headers do update the CookieContainer
[Test]
public void TestNSurlSessionHandlerCookieContainerSetCookie ()
{
var url = NetworkResources.Httpbin.GetSetCookieUrl ("cookie", "chocolate-chip");
var cookieContainer = new CookieContainer ();
string nativeCookieResult = null;
Exception ex = null;
var completed = false;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var nativeHandler = new NSUrlSessionHandler () {
AllowAutoRedirect = true,
CookieContainer = cookieContainer,
};
var nativeClient = new HttpClient (nativeHandler);
var nativeResponse = await nativeClient.GetAsync (url);
nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
} catch (Exception e) {
ex = e;
} finally {
completed = true;
}
}, () => completed);
Assert.IsNull (ex, "Exception");
Assert.IsNotNull (nativeCookieResult, "Native cookies result");
var cookiesFromServer = cookieContainer.GetCookies (new Uri (url));
Assert.AreEqual (1, cookiesFromServer.Count, "Cookies received from server.");
}
[Test]
public void TestNSUrlSessionDefaultDisabledCookies ()
{
// simple test. send a request with a set-cookie url, get the data
// and ensure that the second request does not send any cookies.
var url = NetworkResources.Httpbin.GetSetCookieUrl ("cookie", "chocolate-chip");
string nativeSetCookieResult = null;
string nativeCookieResult = null;
Exception ex = null;
var completed = false;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var nativeHandler = new NSUrlSessionHandler () {
AllowAutoRedirect = true,
UseCookies = false,
};
var nativeClient = new HttpClient (nativeHandler);
var nativeResponse = await nativeClient.GetAsync (url);
nativeSetCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
// got the response, perofm a second queries to the cookies endpoint to get
// the actual cookies sent from the storage
nativeResponse = await nativeClient.GetAsync (NetworkResources.Httpbin.CookiesUrl);
nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
} catch (Exception e) {
ex = e;
} finally {
completed = true;
}
}, () => completed);
Assert.IsNull (ex, "Exception");
Assert.IsNotNull (nativeSetCookieResult, "Native set-cookies result");
Assert.IsNotNull (nativeCookieResult, "Native cookies result");
Assert.IsFalse (nativeCookieResult.Contains ("chocolate-chip"));
}
[Test]
public void TestNSUrlSessionDefaultDisableCookiesWithManagedContainer ()
{
// simple test. send a request with a set-cookie url, get the data
// and ensure that the second request does not send any cookies.
var url = NetworkResources.Httpbin.GetSetCookieUrl ("cookie", "chocolate-chip");
string nativeSetCookieResult = null;
string nativeCookieResult = null;
var cookieContainer = new CookieContainer ();
Exception ex = null;
var completed = false;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var nativeHandler = new NSUrlSessionHandler () {
AllowAutoRedirect = true,
UseCookies = false,
};
var nativeClient = new HttpClient (nativeHandler);
var nativeResponse = await nativeClient.GetAsync (url);
nativeSetCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
// got the response, preform a second queries to the cookies endpoint to get
// the actual cookies sent from the storage
nativeResponse = await nativeClient.GetAsync (NetworkResources.Httpbin.CookiesUrl);
nativeCookieResult = await nativeResponse.Content.ReadAsStringAsync ();
} catch (Exception e) {
ex = e;
} finally {
completed = true;
}
}, () => completed);
Assert.IsNull (ex, "Exception");
Assert.IsNotNull (nativeSetCookieResult, "Native set-cookies result");
Assert.IsNotNull (nativeCookieResult, "Native cookies result");
Assert.IsFalse (nativeCookieResult.Contains ("chocolate-chip"));
var cookiesFromServer = cookieContainer.GetCookies (new Uri (url));
Assert.AreEqual (0, cookiesFromServer.Count, "Cookies received from server.");
}
[Test]
public void TestNSUrlSessionEphemeralDisabledCookies ()
{
// assert we do throw an exception with ephmeral configs.
using (var config = NSUrlSessionConfiguration.EphemeralSessionConfiguration) {
Assert.True (config.SessionType == NSUrlSessionConfiguration.SessionConfigurationType.Ephemeral, "Session type.");
var nativeHandler = new NSUrlSessionHandler (config);
Assert.Throws<InvalidOperationException> (() => {
nativeHandler.UseCookies = false;
});
}
}
#endif
// ensure that if we have a redirect, we do not have the auth headers in the following requests
#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
[TestCase (typeof (CFNetworkHandler))]
#endif
[TestCase (typeof (NSUrlSessionHandler))]
public void RedirectionWithAuthorizationHeaders (Type handlerType)
{
TestRuntime.AssertSystemVersion (PlatformName.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);
bool containsAuthorizarion = false;
bool containsHeaders = false;
string json = "";
bool done = false;
Exception ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (GetHandler (handlerType));
client.BaseAddress = NetworkResources.Httpbin.Uri;
var byteArray = new UTF8Encoding ().GetBytes ("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String(byteArray));
var result = await client.GetAsync (NetworkResources.Httpbin.GetRedirectUrl (3));
// get the data returned from httpbin which contains the details of the requested performed.
json = await result.Content.ReadAsStringAsync ();
containsAuthorizarion = json.Contains ("Authorization");
containsHeaders = json.Contains ("headers"); // ensure we do have the headers in the response
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else if (!containsHeaders) {
Assert.Inconclusive ("Response from httpbin does not contain headers, therefore we cannot ensure that if the authoriation is present.");
} else {
Assert.IsFalse (containsAuthorizarion, $"Authorization header did reach the final destination. {json}");
Assert.IsNull (ex, $"Exception {ex} for {json}");
}
}
#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
#endif
[TestCase (typeof (NSUrlSessionHandler))]
public void RejectSslCertificatesServicePointManager (Type handlerType)
{
TestRuntime.AssertSystemVersion (PlatformName.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);
#if __MACOS__
if (handlerType == typeof (NSUrlSessionHandler) && TestRuntime.CheckSystemVersion (PlatformName.MacOSX, 10, 10, 0) && !TestRuntime.CheckSystemVersion (PlatformName.MacOSX, 10, 11, 0))
Assert.Ignore ("Fails on macOS 10.10: https://github.com/xamarin/maccore/issues/1645");
#endif
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
bool validationCbWasExecuted = false;
bool customValidationCbWasExecuted = false;
bool invalidServicePointManagerCbWasExcuted = false;
bool done = false;
Exception ex = null;
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
Type expectedExceptionType = null;
HttpResponseMessage result = null;
var handler = GetHandler (handlerType);
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
if (handler is HttpClientHandler ch) {
expectedExceptionType = typeof (AuthenticationException);
ch.ServerCertificateCustomValidationCallback = (sender, certificate, chain, errors) => {
validationCbWasExecuted = true;
// return false, since we want to test that the exception is raised
return false;
};
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => {
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
invalidServicePointManagerCbWasExcuted = true;
return false;
};
} else if (handler is NSUrlSessionHandler ns) {
expectedExceptionType = typeof (WebException);
ns.TrustOverride += (a,b) => {
validationCbWasExecuted = true;
// return false, since we want to test that the exception is raised
return false;
};
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
} else {
Assert.Fail ($"Invalid HttpMessageHandler: '{handler.GetType ()}'.");
}
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (handler);
client.BaseAddress = NetworkResources.Httpbin.Uri;
var byteArray = new UTF8Encoding ().GetBytes ("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String(byteArray));
result = await client.GetAsync (NetworkResources.Httpbin.GetRedirectUrl (3));
} catch (Exception e) {
ex = e;
} finally {
done = true;
ServicePointManager.ServerCertificateValidationCallback = null;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else {
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
// the ServicePointManager.ServerCertificateValidationCallback will never be executed.
Assert.False(invalidServicePointManagerCbWasExcuted);
Assert.True(validationCbWasExecuted);
// assert the exception type
Assert.IsNotNull (ex, (result == null)? "Expected exception is missing and got no result" : $"Expected exception but got {result.Content.ReadAsStringAsync ().Result}");
Assert.IsInstanceOfType (typeof (HttpRequestException), ex);
Assert.IsNotNull (ex.InnerException);
Bump to mono:2019-10 (#7192) ## Miscellaneous fixes * Fixed `/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/builds/mono-ios-sdk-destdir/ios-sources/external/linker/src/linker/Linker.Steps/OutputStep.cs(110,15): error CS0246: The type or namespace name ‘OutputException’ could not be found (are you missing a using directive or an assembly reference?) [/Users/builder/jenkins/workspace/xamarin-macios/xamarin-macios/tools/mmp/mmp.csproj]` * Changed the name of the method that is used from linker. Because of this commit https://github.com/mono/linker/commit/6be26771b9bc6d40305a8f005d38f08dfa423252 * Added `OutputException.cs` file on `mtouch.csproj`. * Removing enter_gc_safe and exit_gc_safe because now it's already gc_safe in this part of code, after a mono change. * Added known exceptions to LLVM exception list. * Needs `ifdef` because of this https://github.com/mono/mono/pull/17260. * Bump MIN_MONO_VERSION to 6.8.0.41 and point MIN_MONO_URL to the PR. * Add ENABLE_IOS=1 and ENABLE_MAC=1. * Added switch to disable packaged mono build * [Tests] Ignore tests that fail on 32b. Ignore the test on 32b, and filled issue: https://github.com/mono/mono/issues/17752 * [Tests] Ignore a couple of tests causing OOM. Hopefully fixes https://github.com/xamarin/maccore/issues/1659 for good. * Ignore `MM0135` test on Catalina+ because it needs Xcode 9.4. * [monotouch-test] Add null checks for teardown when test didn't run because of a too early OS version. * [CFNetwork]: Http 2.0 requires OS X 10.11 or later. Check whether `_HTTPVersion2_0` is available and fallback to HTTP 1.1 otherwise. ## Bring HttpClient from CoreFX * #7346 * This bumps Mono to use https://github.com/mono/mono/pull/17645 (which is the 2019-10 backport of https://github.com/mono/mono/pull/17628). * The big user-visible change is in regards to certificate validation, everything below are just some minor adjustments to tests. ### SocketsHttpHandler CoreFX uses a completely new `HttpClientHandler` implementation called `SocketsHttpHandler`, which you can find at https://github.com/dotnet/corefx/tree/release/3.0/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler. Since this is not based on the web stack anymore, it does not use any of the related APIs such as `ServicePointManager` or `WebException`. ### Certificate Validation Changes There is a new API called `HttpClientHandler.ServerCertificateCustomValidationCallback`. - https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.servercertificatecustomvalidationcallback?view=netframework-4.8 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Unix.cs#L154 - https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs#L383 The `ServicePointManager.ServerCertificateValidationCallback` is no longer invoked and on certificate validation failure, `AuthenticationException` (from `System.Security.Authentication`) is thrown instead of `WebException`. At the moment, the `NSUrlSessionHandler` still uses it's own validation callback and also still throws `WebException` on failure; we should probably look into making this consistent with the other handlers. ### Minor adjustments related to internal Mono APIs * `HttpContent.SerializeToStreamAsync()` is now `protected` (changed from `protected internal`). - src/Foundation/NSUrlSessionHandler.cs: changed overload accordingly. - src/System.Net.Http/CFContentStream.cs: likewise. * `HttpHeaders.GetKnownHeaderKind()` is an internal Mono API. There is a new internal API called `System.Net.Http.PlatformHelper.IsContentHeader(key)` which exists in both the old as well as the new implementation. The correct way of doing it with the CoreFX handler is `HeaderDescriptor.TryGet (key, out var descriptor) && descriptor.HeaderType == HttpHeaderType.Content` ### Minor adjustments to tests. * `HttpClientHandler.MaxRequestContentBufferSize` is now longer supported, you can set it to any non-negative value, the getter will always return 0. See https://github.com/dotnet/corefx/blob/c1778515a3bee34cc09c757b5563d0af0c8b1e99/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs#L18. - tests/linker/ios/link sdk/HttpClientHandlerTest.cs: removed assertion from test. * `HttpMessageInvoker.handler` is a `protected private` field - in the CoreFX handler, it is called `_handler` and `private`. This is accessed via reflection by some of the tests, which are now using the new name. - tests/mmptest/src/MMPTest.cs: here - tests/mtouch/MTouch.cs: here * tests/monotouch-test/System.Net.Http/MessageHandlers.cs: Adjust `RejectSslCertificatesServicePointManager` to reflect the certificate validation changes described above. - FIXME: There was an `Assert.Ignore()` related to `NSUrlSessionHandler` and macOS 10.10; I removed that to reenable the test because the description linked to an old issue in the private repo that was referenced by several "Merged" PR's, so it looked to me that this might have already been fixed - and I also didn't see why it would fail there.
2019-12-04 23:10:32 +03:00
Assert.IsInstanceOfType (expectedExceptionType, ex.InnerException);
}
}
#if !__WATCHOS__
[TestCase (typeof (HttpClientHandler))]
#endif
[TestCase (typeof (NSUrlSessionHandler))]
public void AcceptSslCertificatesServicePointManager (Type handlerType)
{
TestRuntime.AssertSystemVersion (PlatformName.MacOSX, 10, 9, throwIfOtherPlatform: false);
TestRuntime.AssertSystemVersion (PlatformName.iOS, 7, 0, throwIfOtherPlatform: false);
bool servicePointManagerCbWasExcuted = false;
bool done = false;
Exception ex = null;
var handler = GetHandler (handlerType);
if (handler is NSUrlSessionHandler ns) {
ns.TrustOverride += (a,b) => {
servicePointManagerCbWasExcuted = true;
return true;
};
} else {
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => {
servicePointManagerCbWasExcuted = true;
return true;
};
}
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () =>
{
try {
HttpClient client = new HttpClient (handler);
client.BaseAddress = NetworkResources.Httpbin.Uri;
var byteArray = new UTF8Encoding ().GetBytes ("username:password");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue ("Basic", Convert.ToBase64String(byteArray));
var result = await client.GetAsync (NetworkResources.Httpbin.GetRedirectUrl (3));
} catch (Exception e) {
ex = e;
} finally {
done = true;
ServicePointManager.ServerCertificateValidationCallback = null;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else {
// assert that we did not get an exception
if (ex != null && ex.InnerException != null) {
// we could get here.. if we have a diff issue, in that case, lets get the exception message and assert is not the trust issue
Assert.AreNotEqual (ex.InnerException.Message, "Error: TrustFailure");
}
}
}
[Test]
public void AssertDefaultValuesNSUrlSessionHandler ()
{
using (var handler = new NSUrlSessionHandler ()) {
Assert.True (handler.AllowAutoRedirect, "Default redirects value");
Assert.True (handler.AllowsCellularAccess, "Default cellular data value.");
}
using (var config = NSUrlSessionConfiguration.DefaultSessionConfiguration) {
config.AllowsCellularAccess = false;
using (var handler = new NSUrlSessionHandler (config)) {
Assert.False (handler.AllowsCellularAccess, "Configuration cellular data value.");
}
}
}
[TestCase (HttpStatusCode.OK, "mandel", "1234", "mandel", "1234")]
[TestCase (HttpStatusCode.Unauthorized, "mandel", "1234", "mandel", "4321")]
[TestCase (HttpStatusCode.Unauthorized, "mandel", "1234", "", "")]
public void GHIssue8342 (HttpStatusCode expectedStatus, string validUsername, string validPassword, string username, string password)
{
// create a http client to use with some creds that we do know are not valid
var handler = new NSUrlSessionHandler () {
Credentials = new NetworkCredential (username, password, "")
};
var client = new HttpClient (handler);
bool done = false;
HttpStatusCode httpStatus = HttpStatusCode.NotFound;
Exception ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var result = await client.GetAsync ($"https://httpbin.org/basic-auth/{validUsername}/{validPassword}");
httpStatus = result.StatusCode;
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Request timedout.");
} else {
Assert.IsNull (ex, "Exception not null");
Assert.AreEqual (expectedStatus, httpStatus, "Status not ok");
}
}
[TestCase]
public void GHIssue8344 ()
{
var username = "mandel";
var password = "1234";
var url = $"https://httpbin.org/basic-auth/{username}/{password}";
// perform two requests, one that will get a 200 with valid creds, one that wont and assert that
// the second call does get a 401
// create a http client to use with some creds that we do know are not valid
var firstHandler = new NSUrlSessionHandler () {
Credentials = new NetworkCredential (username, password, "")
};
var firstClient = new HttpClient (firstHandler);
bool done = false;
HttpStatusCode httpStatus = HttpStatusCode.NotFound;
Exception ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var result = await firstClient.GetAsync (url);
httpStatus = result.StatusCode;
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("First request timedout.");
} else {
Assert.IsNull (ex, "First request exception not null");
Assert.AreEqual (HttpStatusCode.OK, httpStatus, "First status not ok");
}
// exactly same operation, diff handler, wrong password, should fail
var secondHandler = new NSUrlSessionHandler () {
Credentials = new NetworkCredential (username, password + password, "")
};
var secondClient = new HttpClient (secondHandler);
done = false;
httpStatus = HttpStatusCode.NotFound;
ex = null;
TestRuntime.RunAsync (DateTime.Now.AddSeconds (30), async () => {
try {
var result = await secondClient.GetAsync (url);
httpStatus = result.StatusCode;
} catch (Exception e) {
ex = e;
} finally {
done = true;
}
}, () => done);
if (!done) { // timeouts happen in the bots due to dns issues, connection issues etc.. we do not want to fail
Assert.Inconclusive ("Second request timedout.");
} else {
Assert.IsNull (ex, "Second request exception not null");
Assert.AreEqual (HttpStatusCode.Unauthorized, httpStatus, "Second status not ok");
}
}
}
}