-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoDaddyClient.cs
More file actions
758 lines (638 loc) · 29.9 KB
/
GoDaddyClient.cs
File metadata and controls
758 lines (638 loc) · 29.9 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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// Copyright 2024 Keyfactor
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Logging;
using Keyfactor.PKI.Enums.EJBCA;
using Microsoft.Extensions.Logging;
using RestSharp;
using RestSharp.Authenticators;
using RestSharp.Serializers.Json;
namespace Keyfactor.Extensions.CAPlugin.GoDaddy.Client;
public class GoDaddyAuthenticator : AuthenticatorBase
{
readonly string _baseUrl;
readonly string _apiKey;
readonly string _apiSecret;
public GoDaddyAuthenticator(string apiToken, string apiSecret) : base("")
{
_apiKey = apiToken;
_apiSecret = apiSecret;
}
protected override ValueTask<RestSharp.Parameter> GetAuthenticationParameter(string accessToken)
{
var parameter = new HeaderParameter(KnownHeaders.Authorization, $"sso-key {_apiKey}:{_apiSecret}");
return new ValueTask<RestSharp.Parameter>(parameter);
}
}
public class GoDaddyClient : IGoDaddyClient, IDisposable
{
private ILogger _logger;
readonly RestClient _client;
bool _clientIsEnabled;
RateLimiter rateLimiter = new RateLimiter(60);
private static int _retriesPerRestOperation = 3;
private static int _pageSize = 50;
string _shopperId;
string _customerId;
public class Builder : IGoDaddyClientBuilder
{
private bool _enabled { get; set; }
private string _baseUrl { get; set; }
private string _apiKey { get; set; }
private string _apiSecret { get; set; }
private string _shopperId { get; set; }
public IGoDaddyClientBuilder WithApiKey(string apiToken)
{
_apiKey = apiToken;
return this;
}
public IGoDaddyClientBuilder WithApiSecret(string apiSecret)
{
_apiSecret = apiSecret;
return this;
}
public IGoDaddyClientBuilder WithBaseUrl(string baseUrl)
{
_baseUrl = baseUrl;
return this;
}
public IGoDaddyClientBuilder WithShopperId(string shopperId)
{
_shopperId = shopperId;
return this;
}
public IGoDaddyClient Build()
{
IGoDaddyClient client = new GoDaddyClient(_baseUrl, _apiKey, _apiSecret, _shopperId);
return client;
}
}
public GoDaddyClient(string apiUrl, string apiKey, string apiSecret, string shopperId)
{
_logger = LogHandler.GetClassLogger<GoDaddyClient>();
_logger.LogDebug($"Creating GoDaddyClient with API URL: {apiUrl}, API Key: {apiKey}, Shopper ID: {shopperId}");
var options = new RestClientOptions(apiUrl)
{
Authenticator = new GoDaddyAuthenticator(apiKey, apiSecret),
};
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
_client = new RestClient(
options,
configureSerialization: s => s.UseSystemTextJson(jsonSerializerOptions)
);
this._shopperId = shopperId;
this._clientIsEnabled = true;
}
public Task Enable()
{
if (!_clientIsEnabled)
{
_logger.LogDebug("Enabling GoDaddy API client");
_clientIsEnabled = true;
}
return Task.CompletedTask;
}
public Task Disable()
{
if (_clientIsEnabled)
{
_logger.LogDebug("Disabling GoDaddy API client");
_clientIsEnabled = false;
}
return Task.CompletedTask;
}
public bool IsEnabled()
{
return _clientIsEnabled;
}
public async Task Ping()
{
EnsureClientIsEnabled();
_logger.LogDebug("Validating GoDaddy API connection");
string path = $"/v1/shoppers/{_shopperId}";
IDictionary<string, string> query = new Dictionary<string, string> {
{ "includes", "customerId" }
};
try
{
ShopperDetailsRestResponse shopper = await GetAsync<ShopperDetailsRestResponse>(path, query);
_logger.LogDebug($"Successfully connected to GoDaddy API with Shopper ID: {_shopperId}, Customer ID: {shopper.customerId}");
}
catch (Exception e)
{
_logger.LogError($"Failed to connect to GoDaddy API: {e.Message}");
throw;
}
}
private string GetCustomerId()
{
EnsureClientIsEnabled();
if (string.IsNullOrEmpty(_shopperId))
{
_logger.LogError("Shopper ID is required to get customer ID");
throw new ArgumentNullException(nameof(_shopperId));
}
if (!string.IsNullOrEmpty(_customerId))
{
_logger.LogTrace($"Returning cached customer ID: {_customerId}");
return _customerId;
}
_logger.LogDebug($"Getting customer ID for shopper ID: {_shopperId}");
string path = $"/v1/shoppers/{_shopperId}";
IDictionary<string, string> query = new Dictionary<string, string> {
{ "includes", "customerId" }
};
ShopperDetailsRestResponse shopper = GetAsync<ShopperDetailsRestResponse>(path, query).Result;
_logger.LogTrace($"Customer ID for shopper ID {_shopperId} is {shopper.customerId}");
_customerId = shopper.customerId;
return _customerId;
}
public async Task<AnyCAPluginCertificate> DownloadCertificate(string certificateId)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Downloading certificate with ID: {certificateId}");
string path = $"/v1/certificates/{certificateId}/download";
DownloadCertificateRestResponse certificate = await GetAsync<DownloadCertificateRestResponse>(path);
CertificateDetailsRestResponse details = await GetCertificateDetails(certificateId);
return new AnyCAPluginCertificate
{
CARequestID = details.certificateId,
Certificate = certificate.pems.certificate,
Status = GoDaddyCertificateStatusToCAStatus(details.status),
ProductID = details.productType,
RevocationDate = details.revokedAt
};
}
public async Task<string> DownloadCertificatePem(string certificateId)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Downloading certificate with ID: {certificateId}");
string path = $"/v1/certificates/{certificateId}/download";
DownloadCertificateRestResponse certificate = await GetAsync<DownloadCertificateRestResponse>(path);
return certificate.pems.certificate;
}
public async Task<CertificateDetailsRestResponse> GetCertificateDetails(string certificateId)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Getting certificate details for certificate ID: {certificateId}");
string path = $"/v1/certificates/{certificateId}";
CertificateDetailsRestResponse certificateDetails = await GetAsync<CertificateDetailsRestResponse>(path);
_logger.LogTrace($"Retrieved details for certificate with ID {certificateId} [status: {certificateDetails.status}, type: {certificateDetails.productType}]");
return certificateDetails;
}
public async Task<int> DownloadAllIssuedCertificates(BlockingCollection<AnyCAPluginCertificate> certificatesBuffer, CancellationToken cancelToken)
{
EnsureClientIsEnabled();
_logger.LogDebug("Getting all issued certificates");
string path = $"/v2/customers/{GetCustomerId()}/certificates";
IDictionary<string, string> query = new Dictionary<string, string> {
{ "limit", _pageSize.ToString() },
};
int numberOfCertificates = 0;
int currentPage = 1;
bool allPagesDownloaded = false;
do
{
if (cancelToken.IsCancellationRequested)
{
_logger.LogDebug("Cancellation requested - stopping certificate download");
break;
}
_logger.LogTrace($"Getting page {currentPage} (page size {_pageSize.ToString()})");
query["offset"] = currentPage.ToString();
CustomerCertificatesRestResponse certificatesWithPagination = await GetAsync<CustomerCertificatesRestResponse>(path, query);
foreach (CertificateDetail certificateDetail in certificatesWithPagination.certificates)
{
string debugMessage = "Downloading certificate ";
if (!string.IsNullOrEmpty(certificateDetail.commonName))
debugMessage += $"with CN {certificateDetail.commonName} ";
if (!string.IsNullOrEmpty(certificateDetail.validStartAt))
debugMessage += $"[issued at {certificateDetail.validStartAt}] ";
if (!string.IsNullOrEmpty(certificateDetail.validEndAt))
debugMessage += $"[expires at {certificateDetail.validEndAt}] ";
if (null != certificateDetail.revokedAt)
debugMessage += $"[revoked at {certificateDetail.revokedAt}]";
_logger.LogDebug(debugMessage);
string certificatePemString;
try
{
certificatePemString = await DownloadCertificatePem(certificateDetail.certificateId);
}
catch (DownloadNotAllowed)
{
_logger.LogWarning($"Certificate with request ID {certificateDetail.certificateId} cannot be downloaded (status 409)");
continue;
}
certificatesBuffer.Add(new AnyCAPluginCertificate()
{
CARequestID = certificateDetail.certificateId,
Certificate = certificatePemString,
Status = GoDaddyCertificateStatusToCAStatus(certificateDetail.status),
ProductID = certificateDetail.type,
RevocationDate = certificateDetail.revokedAt
});
numberOfCertificates++;
}
currentPage++;
allPagesDownloaded = certificatesWithPagination.pagination.previous == certificatesWithPagination.pagination.last;
}
while (!allPagesDownloaded);
certificatesBuffer.CompleteAdding();
return numberOfCertificates;
}
public async Task<EnrollmentResult> Enroll(CertificateOrderRestRequest request, CancellationToken cancelToken)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Enrolling CSR with common name {request.CommonName}");
string path = $"/v1/certificates";
CertificateOrderRestResponse certificateOrder = await PostAsync<CertificateOrderRestRequest, CertificateOrderRestResponse>(path, request);
_logger.LogDebug($"Created Certificate order with ID {certificateOrder.certificateId} - Waiting for certificate to be issued");
const int delay = 1000;
CertificateDetailsRestResponse details;
DateTime startTime = DateTime.Now;
TaskCompletionSource<bool> callbackCompletionSource = new TaskCompletionSource<bool>();
cancelToken.Register(async () =>
{
_logger.LogWarning($"Cancellation requested - cancelling certificate with ID {certificateOrder.certificateId}");
await CancelCertificateOrder(certificateOrder.certificateId);
callbackCompletionSource.SetResult(true);
});
do
{
if (cancelToken.IsCancellationRequested)
{
await callbackCompletionSource.Task;
_logger.LogTrace("Cancellation callback task complete - throwing TaskCanceledException");
throw new TaskCanceledException("Cancellation requested - certificate order cancelled");
}
details = await GetCertificateDetails(certificateOrder.certificateId);
if ((int)EndEntityStatus.GENERATED == GoDaddyCertificateStatusToCAStatus(details.status))
{
_logger.LogDebug($"Certificate with ID {certificateOrder.certificateId} has been issued");
break;
}
_logger.LogDebug($"Waiting for certificate with ID {certificateOrder.certificateId} to be issued ({DateTime.Now - startTime} elapsed)");
await Task.Delay(delay);
}
while (true);
// Sanity check
if (details == null)
{
throw new Exception("Failed to get certificate details");
}
_logger.LogDebug($"Certificate with ID {certificateOrder.certificateId} has been issued - downloading certificate ({DateTime.Now - startTime} elapsed)");
string certificatePemString = await DownloadCertificatePem(certificateOrder.certificateId);
return new EnrollmentResult
{
CARequestID = certificateOrder.certificateId,
Certificate = certificatePemString,
Status = GoDaddyCertificateStatusToCAStatus(details.status),
StatusMessage = $"Certificate with ID {certificateOrder.certificateId} has been issued",
};
}
public async Task<EnrollmentResult> Reissue(string certificateId, ReissueCertificateRestRequest request, CancellationToken cancelToken)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Reissuing certificate with ID {certificateId}");
string path = $"/v1/certificates/{certificateId}/reissue";
ReissueCertificateRestResponse certificateOrder = await PostAsync<ReissueCertificateRestRequest, ReissueCertificateRestResponse>(path, request);
if (string.IsNullOrEmpty(certificateOrder.certificateId))
{
throw new Exception($"Certificate reissue failed - no certificate ID returned");
}
_logger.LogDebug($"Successfully submitted request to reissue certificate with ID {certificateId} - new certificate ID is {certificateOrder.certificateId} - Waiting for certificate to be issued");
TaskCompletionSource<bool> callbackCompletionSource = new TaskCompletionSource<bool>();
cancelToken.Register(async () =>
{
_logger.LogWarning($"Cancellation requested - cancelling certificate with ID {certificateOrder.certificateId}");
await CancelCertificateOrder(certificateOrder.certificateId);
callbackCompletionSource.SetResult(true);
});
const int delay = 1000;
CertificateDetailsRestResponse details;
do
{
if (cancelToken.IsCancellationRequested)
{
await callbackCompletionSource.Task;
_logger.LogTrace("Cancellation callback task complete - throwing TaskCanceledException");
throw new TaskCanceledException("Cancellation requested - certificate order cancelled");
}
details = await GetCertificateDetails(certificateOrder.certificateId);
if ((int)EndEntityStatus.GENERATED == GoDaddyCertificateStatusToCAStatus(details.status))
{
_logger.LogDebug($"Certificate with ID {certificateId} has been reissued - new certificate ID is {certificateOrder.certificateId}");
break;
}
await Task.Delay(delay);
}
while (true);
// Sanity check
if (details == null)
{
throw new Exception("Failed to get certificate details");
}
string certificatePemString = await DownloadCertificatePem(certificateOrder.certificateId);
return new EnrollmentResult
{
CARequestID = details.certificateId,
Certificate = certificatePemString,
Status = GoDaddyCertificateStatusToCAStatus(details.status),
StatusMessage = $"Certificate with ID {certificateId} has been reissued - new certificate ID is {certificateOrder.certificateId}"
};
}
public async Task<EnrollmentResult> Renew(string certificateId, RenewCertificateRestRequest request, CancellationToken cancelToken)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Renewing certificate with ID {certificateId}");
string path = $"v1/certificates/{certificateId}/renew";
RenewCertificateRestResponse certificateOrder = await PostAsync<RenewCertificateRestRequest, RenewCertificateRestResponse>(path, request);
_logger.LogDebug($"Successfully submitted request to renew certificate with ID {certificateId} - new certificate ID is {certificateOrder.certificateId} - Waiting for certificate to be issued");
TaskCompletionSource<bool> callbackCompletionSource = new TaskCompletionSource<bool>();
cancelToken.Register(async () =>
{
_logger.LogWarning($"Cancellation requested - cancelling certificate with ID {certificateOrder.certificateId}");
await CancelCertificateOrder(certificateOrder.certificateId);
callbackCompletionSource.SetResult(true);
});
const int delay = 1000;
CertificateDetailsRestResponse details;
do
{
if (cancelToken.IsCancellationRequested)
{
await callbackCompletionSource.Task;
_logger.LogTrace("Cancellation callback task complete - throwing TaskCanceledException");
throw new TaskCanceledException("Cancellation requested - certificate order cancelled");
}
details = await GetCertificateDetails(certificateOrder.certificateId);
if ((int)EndEntityStatus.GENERATED == GoDaddyCertificateStatusToCAStatus(details.status))
{
_logger.LogDebug($"Certificate with ID {certificateId} has been renewed - new certificate ID is {certificateOrder.certificateId}");
break;
}
await Task.Delay(delay);
}
while (true);
// Sanity check
if (details == null)
{
throw new Exception("Failed to get certificate details");
}
string certificatePemString = await DownloadCertificatePem(certificateOrder.certificateId);
return new EnrollmentResult
{
CARequestID = details.certificateId,
Certificate = certificatePemString,
Status = GoDaddyCertificateStatusToCAStatus(details.status),
StatusMessage = $"Certificate with ID {certificateId} has been renewed - new certificate ID is {certificateOrder.certificateId}",
};
}
public async Task RevokeCertificate(string certificateId, RevokeReason reason)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Revoking certificate with ID {certificateId} [reason: {reason.ToString()}]");
RevokeCertificateRestRequest request = new RevokeCertificateRestRequest(reason.ToString());
string path = $"/v1/certificates/{certificateId}/revoke";
await PostAsync<RevokeCertificateRestRequest, RevokeCertificateRestResponse>(path, request);
}
public async Task CancelCertificateOrder(string certificateId)
{
EnsureClientIsEnabled();
_logger.LogDebug($"Cancelling certificate order with ID {certificateId}");
CancelCertificateOrderRestRequest request = new CancelCertificateOrderRestRequest();
string path = $"/v1/certificates/{certificateId}/cancel";
await PostAsync<CancelCertificateOrderRestRequest, CancelCertificateOrderRestResponse>(path, request);
_logger.LogDebug($"Successfully cancelled certificate order with ID {certificateId}");
}
public async Task<TResponse> GetAsync<TResponse>(string endpoint, IDictionary<string, string> query = null)
where TResponse : class
{
EnsureClientIsEnabled();
_logger.LogTrace($"Setting up GET request to {endpoint}");
var request = new RestRequest(endpoint, Method.Get);
if (query == null)
{
query = new Dictionary<string, string>();
}
foreach (var param in query)
{
request.AddQueryParameter(param.Key, param.Value);
_logger.LogTrace($"Adding query parameter: {param.Key}={param.Value}");
}
for (int i = 0; i < _retriesPerRestOperation; i++)
{
try
{
await rateLimiter.WaitForWindowAsync();
_logger.LogTrace($"Sending GET request to {endpoint}");
var response = await _client.ExecuteAsync(request);
var expectedResponseCodeAttribute = (ApiResponseAttribute)Attribute.GetCustomAttribute(typeof(TResponse), typeof(ApiResponseAttribute));
if (expectedResponseCodeAttribute != null && response.StatusCode == expectedResponseCodeAttribute.StatusCode && response.StatusCode == HttpStatusCode.NoContent)
{
_logger.LogTrace($"Received response with expected status code [{response.StatusCode}] - skipping serialization to {typeof(TResponse).ToString()}");
return Activator.CreateInstance<TResponse>();
}
else if (expectedResponseCodeAttribute != null && response.StatusCode == expectedResponseCodeAttribute.StatusCode)
{
_logger.LogTrace($"Received response with expected status code [{response.StatusCode}] - serializing response content to {typeof(TResponse).ToString()}");
return JsonSerializer.Deserialize<TResponse>(response.Content);
}
_logger.LogError($"Received response with unexpected status code [{response.StatusCode}]");
if (response.StatusCode == HttpStatusCode.Conflict)
{
throw new DownloadNotAllowed($"Conflict error occurred: {response.Content}");
}
if (response.Content == null)
{
throw new Exception("Response was not successful and no content was returned.");
}
if (!string.IsNullOrEmpty(response.Content))
{
_logger.LogTrace($"Error content: {response.Content}");
}
Error errorResponse;
try
{
_logger.LogTrace("Serializing response content to error object");
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
errorResponse = JsonSerializer.Deserialize<Error>(response.Content, jsonSerializerOptions);
}
catch (JsonException)
{
throw new Exception($"Failed to GET {endpoint}: {response.Content} (failed to serialize to error)");
}
if (errorResponse.IsRateLimitError())
{
_logger.LogWarning($"Rate limit exceeded - waiting for more requests to be available");
await rateLimiter.WaitForWindowAsync();
continue;
}
string message = $"Failed to GET {endpoint}: {errorResponse.ToString()}";
_logger.LogError(message);
throw new Exception(message);
}
catch (Exception e)
{
_logger.LogError($"Retry handler - {e.Message}");
if (i == _retriesPerRestOperation - 1)
{
_logger.LogError($"Failed to GET {endpoint} after {_retriesPerRestOperation} retries");
throw;
}
_logger.LogWarning($"Retrying GET request to {endpoint} [{i + 1}/{_retriesPerRestOperation}]");
}
}
throw new Exception("Failed to GET request after all retries");
}
public async Task<TResponse> PostAsync<TRequest, TResponse>(string endpoint, TRequest body, IDictionary<string, string> query = null)
where TRequest : class
where TResponse : class
{
EnsureClientIsEnabled();
_logger.LogTrace($"Setting up POST request to {endpoint}");
var request = new RestRequest(endpoint, Method.Post);
request.AddJsonBody<TRequest>(body);
if (query == null)
{
query = new Dictionary<string, string>();
}
foreach (var param in query)
{
request.AddQueryParameter(param.Key, param.Value);
_logger.LogTrace($"Adding query parameter: {param.Key}={param.Value}");
}
for (int i = 0; i < _retriesPerRestOperation; i++)
{
try
{
await rateLimiter.WaitForWindowAsync();
_logger.LogTrace($"Sending POST request to {endpoint}");
RestResponse response;
try
{
response = await _client.ExecuteAsync(request);
}
catch (HttpRequestException e)
{
_logger.LogError($"Failed to POST {endpoint}: {e.Message}");
throw;
}
var expectedResponseCodeAttribute = (ApiResponseAttribute)Attribute.GetCustomAttribute(typeof(TResponse), typeof(ApiResponseAttribute));
if (expectedResponseCodeAttribute != null && response.StatusCode == expectedResponseCodeAttribute.StatusCode && response.StatusCode == HttpStatusCode.NoContent)
{
_logger.LogTrace($"Received response with expected status code [{response.StatusCode}] - skipping serialization to {typeof(TResponse).ToString()}");
return Activator.CreateInstance<TResponse>();
}
else if (expectedResponseCodeAttribute != null && response.StatusCode == expectedResponseCodeAttribute.StatusCode)
{
_logger.LogTrace($"Received response with expected status code [{response.StatusCode}] - serializing response content to {typeof(TResponse).ToString()}");
return JsonSerializer.Deserialize<TResponse>(response.Content);
}
_logger.LogError($"Received response with unexpected status code [{response.StatusCode}]");
if (response.Content == null)
{
_logger.LogError($"Response was not successful and no content was returned.");
throw new Exception("Response was not successful and no content was returned.");
}
if (!string.IsNullOrEmpty(response.Content))
{
_logger.LogTrace($"Error content: {response.Content}");
}
Error errorResponse;
try
{
_logger.LogTrace("Serializing response content to error object");
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
errorResponse = JsonSerializer.Deserialize<Error>(response.Content, jsonSerializerOptions);
}
catch (JsonException)
{
_logger.LogError($"Failed to POST {endpoint}: {response.Content} (failed to serialize to error)");
throw new Exception($"Failed to GET {endpoint}: {response.Content} (failed to serialize to error)");
}
string message = $"Failed to POST {endpoint}: {errorResponse.ToString()}";
_logger.LogError(message);
throw new Exception(message);
}
catch (Exception)
{
if (i == _retriesPerRestOperation - 1)
{
_logger.LogError($"Failed to POST {endpoint} after {_retriesPerRestOperation} retries");
throw;
}
_logger.LogWarning($"Retrying POST request to {endpoint} [{i + 1}/{_retriesPerRestOperation}]");
}
}
throw new Exception("Failed to POST request after all retries");
}
private void EnsureClientIsEnabled()
{
if (!_clientIsEnabled)
{
_logger.LogWarning("GoDaddy API client is disabled - throwing");
throw new Exception("GoDaddy API client is disabled");
}
}
record GoDaddySingleObject<T>(T Data);
public void Dispose()
{
_client?.Dispose();
GC.SuppressFinalize(this);
}
private static int GoDaddyCertificateStatusToCAStatus(string status)
{
switch (status)
{
case "CANCELED":
return (int)EndEntityStatus.CANCELLED;
case "DENIED":
return (int)EndEntityStatus.FAILED;
case "ISSUED":
return (int)EndEntityStatus.GENERATED;
case "PENDING_ISSUANCE":
return (int)EndEntityStatus.INPROCESS;
case "PENDING_REKEY":
return (int)EndEntityStatus.INPROCESS;
case "PENDING_REVOCATION":
return (int)EndEntityStatus.INPROCESS;
case "REVOKED":
return (int)EndEntityStatus.REVOKED;
default:
return (int)EndEntityStatus.FAILED;
}
}
}