This repository was archived by the owner on Nov 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathVaultHttpClient.cs
More file actions
200 lines (173 loc) · 8.24 KB
/
VaultHttpClient.cs
File metadata and controls
200 lines (173 loc) · 8.24 KB
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
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Vault
{
public class VaultHttpClient : IVaultHttpClient
{
private static HttpClient HttpClientInitialization()
{
HttpClient httpClient = null;
#if NET45
if (!string.IsNullOrEmpty(Vault.VaultOptions.Default.CertPath))
{
WebRequestHandler requestHandler = new WebRequestHandler();
requestHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
requestHandler.ClientCertificates.Add(new X509Certificate2(Vault.VaultOptions.Default.CertPath));
httpClient = new HttpClient(requestHandler);
}
else
httpClient = new HttpClient();
#else
if (!string.IsNullOrEmpty(Vault.VaultOptions.Default.CertPath))
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
const SslPolicyErrors unforgivableErrors =
SslPolicyErrors.RemoteCertificateNotAvailable |
SslPolicyErrors.RemoteCertificateNameMismatch;
if ((errors & unforgivableErrors) != 0)
{
return false;
}
X509Certificate2 remoteRoot = chain.ChainElements[chain.ChainElements.Count - 1].Certificate;
return new X509Certificate2(Vault.VaultOptions.Default.CertPath).RawData.SequenceEqual(remoteRoot.RawData);
};
httpClient = new HttpClient(handler);
}
else
{
httpClient = new HttpClient();
}
#endif
return httpClient;
}
private static readonly HttpClient HttpClient = HttpClientInitialization();
public VaultHttpClient()
{
HttpClient.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public Task<T> Get<T>(Uri uri, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
return HttpRequest<T>(HttpMethod.Get, uri, null, vaultToken, wrapTtl, ct);
}
public Task<byte[]> GetRaw(Uri uri, string vaultToken, CancellationToken ct)
{
return HttpRequestRaw(HttpMethod.Get, uri, null, vaultToken, ct);
}
public Task PostVoid<T>(Uri uri, T content, string vaultToken, CancellationToken ct)
{
var httpContent = JsonSerialize(content);
return HttpRequestVoid(HttpMethod.Post, uri, httpContent, vaultToken, ct);
}
public Task<TO> Post<TI, TO>(Uri uri, TI content, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
var httpContent = JsonSerialize(content);
return HttpRequest<TO>(HttpMethod.Post, uri, httpContent, vaultToken, wrapTtl, ct);
}
public Task PutVoid(Uri uri, string vaultToken, CancellationToken ct)
{
return HttpRequestVoid(HttpMethod.Put, uri, null, vaultToken, ct);
}
public Task PutVoid<T>(Uri uri, T content, string vaultToken, CancellationToken ct)
{
var httpContent = JsonSerialize(content);
return HttpRequestVoid(HttpMethod.Put, uri, httpContent, vaultToken, ct);
}
public Task<T> Put<T>(Uri uri, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
return HttpRequest<T>(HttpMethod.Put, uri, null, vaultToken, wrapTtl, ct);
}
public Task<TO> Put<TI, TO>(Uri uri, TI content, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
var httpContent = JsonSerialize(content);
return HttpRequest<TO>(HttpMethod.Put, uri, httpContent, vaultToken, wrapTtl, ct);
}
public Task DeleteVoid(Uri uri, string vaultToken, CancellationToken ct)
{
return HttpRequestVoid(HttpMethod.Delete, uri, null, vaultToken, ct);
}
private static Task<HttpResponseMessage> HttpSendRequest(HttpMethod method, Uri uri, string body, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
var requestMessage = new HttpRequestMessage(method, uri);
if (vaultToken != null)
{
requestMessage.Headers.Add("X-Vault-Token", vaultToken);
}
if (wrapTtl != TimeSpan.Zero)
{
requestMessage.Headers.Add("X-Vault-Wrap-TTL", $"{(int)wrapTtl.TotalSeconds}");
}
if (body != null)
{
requestMessage.Content = new StringContent(body, Encoding.UTF8, "application/json");
}
return HttpClient.SendAsync(requestMessage, ct);
}
private static async Task HttpRequestVoid(HttpMethod method, Uri uri, string body, string vaultToken, CancellationToken ct)
{
await HttpRequest(method, uri, body, vaultToken, TimeSpan.Zero, ct).ConfigureAwait(false);
}
private static async Task<T> HttpRequest<T>(HttpMethod method, Uri uri, string body, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
return JsonDeserialize<T>(await HttpRequest(method, uri, body, vaultToken, wrapTtl, ct).ConfigureAwait(false));
}
private static async Task<string> HttpRequest(HttpMethod method, Uri uri, string body, string vaultToken, TimeSpan wrapTtl, CancellationToken ct)
{
using (var r = await HttpSendRequest(method, uri, body, vaultToken, wrapTtl, ct).ConfigureAwait(false))
{
if (r.StatusCode != HttpStatusCode.NotFound) {
if (!r.IsSuccessStatusCode)
{
throw new VaultRequestException($"Unexpected response, status code {r.StatusCode}", r.StatusCode);
}
if (r.Content.Headers.ContentType.MediaType != "application/json") {
throw new VaultRequestException($"Unexpected content media type {r.Content.Headers.ContentType.MediaType}", HttpStatusCode.InternalServerError);
}
}
return await r.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
private static async Task<byte[]> HttpRequestRaw(HttpMethod method, Uri uri, string body, string vaultToken, CancellationToken ct)
{
using (var r = await HttpSendRequest(method, uri, body, vaultToken, TimeSpan.Zero, ct).ConfigureAwait(false))
{
if (r.StatusCode != HttpStatusCode.NotFound) {
if (!r.IsSuccessStatusCode)
{
throw new VaultRequestException($"Unexpected response, status code {r.StatusCode}", r.StatusCode);
}
if (r.Content.Headers.ContentType.MediaType == "application/json") {
throw new VaultRequestException($"Unexpected content media type {r.Content.Headers.ContentType.MediaType}", HttpStatusCode.InternalServerError);
}
}
return await r.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
}
private static string JsonSerialize<T>(T content)
{
return JsonConvert.SerializeObject(content, VaultJsonSerializerSettings());
}
private static T JsonDeserialize<T>(string result)
{
return JsonConvert.DeserializeObject<T>(result, VaultJsonSerializerSettings());
}
private static JsonSerializerSettings VaultJsonSerializerSettings()
{
return new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.Ignore
};
}
}
}