-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathHttpClientHandlerTest.ClientCertificates.cs
252 lines (218 loc) · 10.6 KB
/
HttpClientHandlerTest.ClientCertificates.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
#if WINHTTPHANDLER_TEST
using HttpClientHandler = System.Net.Http.WinHttpClientHandler;
#endif
public abstract class HttpClientHandler_ClientCertificates_Test : HttpClientHandlerTestBase
{
public HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { }
[Fact]
public void ClientCertificateOptions_Default()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
}
}
[Theory]
[InlineData((ClientCertificateOption)2)]
[InlineData((ClientCertificateOption)(-1))]
public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
}
}
[Theory]
[InlineData(ClientCertificateOption.Automatic)]
[InlineData(ClientCertificateOption.Manual)]
public void ClientCertificateOptions_ValueArg_Roundtrips(ClientCertificateOption option)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = option;
Assert.Equal(option, handler.ClientCertificateOptions);
}
}
[Fact]
public void ClientCertificates_ClientCertificateOptionsAutomatic_ThrowsException()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
Assert.Throws<InvalidOperationException>(() => handler.ClientCertificates);
}
}
private HttpClient CreateHttpClientWithCert(X509Certificate2 cert)
{
HttpClientHandler handler = CreateHttpClientHandler(allowAllCertificates: true);
Assert.NotNull(cert);
handler.ClientCertificates.Add(cert);
Assert.True(handler.ClientCertificates.Contains(cert));
return CreateHttpClient(handler);
}
[ConditionalTheory]
[InlineData(1, true)]
[InlineData(2, true)]
[InlineData(3, false)]
public async Task Manual_CertificateOnlySentWhenValid_Success(int certIndex, bool serverExpectsClientCertificate)
{
// [ActiveIssue("https://github.com/dotnet/runtime/issues/69238")]
if (IsWinHttpHandler) throw new SkipTestException("https://github.com/dotnet/runtime/issues/69238");
var options = new LoopbackServer.Options { UseSsl = true };
X509Certificate2 GetClientCertificate(int certIndex) => certIndex switch
{
// This is a valid client cert since it has an EKU with a ClientAuthentication OID.
1 => Configuration.Certificates.GetClientCertificate(),
// This is a valid client cert since it has no EKU thus all usages are permitted.
2 => Configuration.Certificates.GetNoEKUCertificate(),
// This is an invalid client cert since it has an EKU but is missing ClientAuthentication OID.
3 => Configuration.Certificates.GetServerCertificate(),
_ => null
};
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using X509Certificate2 cert = GetClientCertificate(certIndex);
using HttpClient client = CreateHttpClientWithCert(cert);
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetStringAsync(url),
server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
if (serverExpectsClientCertificate)
{
_output.WriteLine(
"Client cert: {0}",
new X509Certificate2(sslStream.RemoteCertificate.Export(X509ContentType.Cert)).GetNameInfo(X509NameType.SimpleName, false));
Assert.Equal(cert, sslStream.RemoteCertificate);
}
else
{
Assert.Null(sslStream.RemoteCertificate);
}
await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
}));
}, options);
}
[OuterLoop("Uses GC and waits for finalizers")]
[Theory]
[InlineData(6, false)]
[InlineData(3, true)]
public async Task Manual_CertificateSentMatchesCertificateReceived_Success(
int numberOfRequests,
bool reuseClient) // validate behavior with and without connection pooling, which impacts client cert usage
{
var options = new LoopbackServer.Options { UseSsl = true };
async Task MakeAndValidateRequest(HttpClient client, LoopbackServer server, Uri url, X509Certificate2 cert)
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetStringAsync(url),
server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
Assert.Equal(cert, sslStream.RemoteCertificate);
await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
}));
};
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (X509Certificate2 cert = Configuration.Certificates.GetClientCertificate())
{
if (reuseClient)
{
using (HttpClient client = CreateHttpClientWithCert(cert))
{
for (int i = 0; i < numberOfRequests; i++)
{
await MakeAndValidateRequest(client, server, url, cert);
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
else
{
for (int i = 0; i < numberOfRequests; i++)
{
using (HttpClient client = CreateHttpClientWithCert(cert))
{
await MakeAndValidateRequest(client, server, url, cert);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
}, options);
}
[Theory]
[InlineData(ClientCertificateOption.Manual)]
[InlineData(ClientCertificateOption.Automatic)]
public async Task AutomaticOrManual_DoesntFailRegardlessOfWhetherClientCertsAreAvailable(ClientCertificateOption mode)
{
using (HttpClientHandler handler = CreateHttpClientHandler(allowAllCertificates: true))
using (HttpClient client = CreateHttpClient(handler))
{
handler.ClientCertificateOptions = mode;
await LoopbackServer.CreateServerAsync(async server =>
{
Task clientTask = client.GetStringAsync(server.Address);
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
await connection.ReadRequestHeaderAndSendResponseAsync();
});
await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed();
}, new LoopbackServer.Options { UseSsl = true });
}
}
#if TARGETS_ANDROID
[Fact]
public async Task Android_GetCertificateFromKeyStoreViaAlias()
{
var options = new LoopbackServer.Options { UseSsl = true };
(X509Store store, string alias) = AndroidKeyStoreHelper.AddCertificate(Configuration.Certificates.GetClientCertificate());
try
{
X509Certificate2 clientCertificate = AndroidKeyStoreHelper.GetCertificateViaAlias(store, alias);
Assert.True(clientCertificate.HasPrivateKey);
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using HttpClient client = CreateHttpClientWithCert(clientCertificate);
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetStringAsync(url),
server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
_output.WriteLine(
"Client cert: {0}",
new X509Certificate2(sslStream.RemoteCertificate.Export(X509ContentType.Cert)).GetNameInfo(X509NameType.SimpleName, false));
Assert.Equal(clientCertificate.GetCertHashString(), sslStream.RemoteCertificate.GetCertHashString());
await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
}));
}, options);
}
finally
{
Assert.True(AndroidKeyStoreHelper.DeleteAlias(store, alias));
store.Dispose();
}
}
#endif
}
}