-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGCPCASClient.cs
More file actions
608 lines (536 loc) · 27.2 KB
/
Copy pathGCPCASClient.cs
File metadata and controls
608 lines (536 loc) · 27.2 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
/*
Copyright © 2025 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.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Security.PrivateCA.V1;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Keyfactor.AnyGateway.Extensions;
using Keyfactor.Logging;
using Keyfactor.PKI.Enums.EJBCA;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using static Google.Rpc.Context.AttributeContext.Types;
namespace Keyfactor.Extensions.CAPlugin.GCPCAS.Client;
/// <summary>
/// Class <c>GCPCASClient</c> implements <see cref="IGCPCASClient"/> to provide a standard set of certificate-based operations on a GCP CAS specified by a Project ID, Location ID, CA Pool ID, and CA ID.
/// </summary>
///
/// <remarks><c>GCPCASClient</c> wraps a <see cref="Google.Cloud.Security.PrivateCA.V1.CertificateAuthorityServiceClient"/>. As such, valid <see langword="GCP Application Default Credentials" href="https://cloud.google.com/docs/authentication/application-default-credentials"/> must be configured before this class is used.</remarks>
public class GCPCASClient : IGCPCASClient
{
private ILogger _logger;
private CertificateAuthorityServiceClient _client;
bool _clientIsEnabled;
string _projectId;
string _locationId;
string _caPool;
string _caId;
/// <summary>
/// Initializes a new instance of the <see cref="GCPCASClient"/> class.
/// </summary>
/// <param name="locationId">The GCP location ID where the project containing the target GCP CAS CA is located. For example, <c>us-central1</c>.</param>
/// <param name="projectId">The GCP project ID where the target GCP CAS CA is located</param>
/// <param name="caPool">The CA Pool ID in GCP CAS to use for certificate operations. If the CA Pool has resource name <c>projects/my-project/locations/us-central1/caPools/my-pool</c>, this field should be set to <c>my-pool</c></param>
/// <param name="caId">The CA ID of a CA in the same CA Pool as CAPool. For example, to issue certificates from a CA with resource name <c>projects/my-project/locations/us-central1/caPools/my-pool/certificateAuthorities/my-ca</c>, this field should be set to <c>my-ca</c>.</param>
/// <param name="serviceAccountKey">Optional JSON service account key. When provided, used instead of Application Default Credentials.</param>
public GCPCASClient(string locationId, string projectId, string caPool, string caId, string serviceAccountKey = null)
{
_logger = LogHandler.GetClassLogger<GCPCASClient>();
_logger.MethodEntry();
_logger.LogDebug($"Creating GCP CA Services Client with Location: {locationId}, Project ID: {projectId}, CA Pool: {caPool}, CA ID: {caId}");
this._projectId = projectId;
this._locationId = locationId;
this._caPool = caPool;
this._caId = caId;
var builder = new CertificateAuthorityServiceClientBuilder();
if (!string.IsNullOrEmpty(serviceAccountKey))
{
_logger.LogTrace("Using provided service account key JSON for authentication");
builder.JsonCredentials = serviceAccountKey;
}
else
{
_logger.LogTrace($"Setting up a {typeof(CertificateAuthorityServiceClient).ToString()} using Application Default Credentials");
}
_client = builder.Build();
_logger.MethodExit();
}
public override string ToString()
{
return $"[locationId={_locationId} projectId={_projectId} caPool={_caPool} caId={_caId}]";
}
/// <summary>
/// Enables the <see cref="GCPCASClient"/> client. This must be called before any other operations are performed.
/// </summary>
/// <returns></returns>
public Task Enable()
{
_logger.MethodEntry();
if (!_clientIsEnabled)
{
_logger.LogDebug($"Enabling GCPCAS client {this.ToString()}");
_clientIsEnabled = true;
}
_logger.MethodExit();
return Task.CompletedTask;
}
/// <summary>
/// Disables the <see cref="GCPCASClient"/> client. After this is called, no further operations can be performed until <see cref="Enable"/> is called.
/// </summary>
/// <returns></returns>
public Task Disable()
{
_logger.MethodEntry();
if (_clientIsEnabled)
{
_logger.LogDebug($"Disabling GCPCAS client {this.ToString()}");
_clientIsEnabled = false;
}
_logger.MethodExit();
return Task.CompletedTask;
}
/// <summary>
/// Determines if the client is enabled.
/// </summary>
/// <returns>
/// A <see cref="bool"/> indicating if the client is enabled.
/// </returns>
public bool IsEnabled()
{
_logger.MethodEntry();
_logger.MethodExit();
return _clientIsEnabled;
}
/// <summary>
/// Attempts to connect to the GCP CAS service to verify connectivity. Verifies that the GCP Application Default Credentials are properly configured.
/// </summary>
/// <returns>
/// Returns nothing if the connection is successful.
/// </returns>
/// <exception cref="Exception">Thrown if the GCP Application Default Credentials are not properly configured, if the GCP CAS CA Pool/CA is not found/is not compatible, or if the <see cref="GCPCASClient"/> was not enabled via the <see cref="Enable"/> method.</exception>
public async Task ValidateConnection()
{
_logger.MethodEntry();
EnsureClientIsEnabled();
if (string.IsNullOrEmpty(_caId))
{
_logger.LogTrace($"Validating CA Pool {_caPool} since no specific CA ID was provided");
CaPoolName poolName = new CaPoolName(_projectId, _locationId, _caPool);
CaPool pool = await _client.GetCaPoolAsync(poolName);
if (pool.Tier != CaPool.Types.Tier.Enterprise)
{
string error = $"CA Pool {_caPool} is in Tier {pool.Tier}, expected {CaPool.Types.Tier.Enterprise}.";
_logger.LogError(error);
throw new Exception(error);
}
_logger.LogDebug($"CA Pool {_caPool} is Enterprise tier and valid.");
_logger.MethodExit();
return;
}
_logger.LogTrace($"Searching for CA called {_caId} in CA Pool {_caPool}");
CertificateAuthorityName caName = new CertificateAuthorityName(_projectId, _locationId, _caPool, _caId);
CertificateAuthority ca = await _client.GetCertificateAuthorityAsync(caName);
_logger.LogDebug($"Found CA {ca.CertificateAuthorityName.CertificateAuthorityId} in CA Pool {ca.CertificateAuthorityName.CaPoolId}");
if (ca.State != CertificateAuthority.Types.State.Enabled)
{
string error = $"CA {_caId} is in state {ca.State}. Expected Enabled.";
_logger.LogError(error);
throw new Exception(error);
}
if (ca.Tier != CaPool.Types.Tier.Enterprise)
{
string error = $"CA {_caId} is in tier {ca.Tier}. Only Enterprise tier is supported.";
_logger.LogError(error);
throw new Exception(error);
}
_logger.LogDebug($"{nameof(GCPCASClient)} is compatible with CA {_caId} in Pool {_caPool}.");
_logger.MethodExit();
}
/// <summary>
/// Downloads all issued certificates from the GCP CAS service and adds them to the provided <see cref="BlockingCollection{T}"/>. This call can be cancelled by passing a <see cref="CancellationToken"/>.
/// </summary>
/// <param name="certificatesBuffer">
/// A <see cref="BlockingCollection{T}"/> to which the downloaded certificates will be added.
/// </param>
/// <param name="cancelToken">
/// A <see cref="CancellationToken"/> that can be used to cancel the operation.
/// </param>
/// <returns>
/// The number of certificates downloaded.
/// </returns>
/// <exception cref="Exception">
/// Thrown if the <see cref="BlockingCollection{T}"/> is null or if the operation fails.
/// </exception>
public async Task<int> DownloadAllIssuedCertificates(BlockingCollection<AnyCAPluginCertificate> certificatesBuffer, CancellationToken cancelToken, DateTime? issuedAfter = null)
{
_logger.MethodEntry();
EnsureClientIsEnabled();
if (certificatesBuffer == null)
{
string message = "Failed to download issued certificates - certificatesBuffer is null";
_logger.LogError(message);
throw new ArgumentNullException(nameof(certificatesBuffer), message);
}
_logger.LogTrace($"Setting up {typeof(ListCertificatesRequest).ToString()} with {this.ToString()}");
ListCertificatesRequest request = new ListCertificatesRequest
{
ParentAsCaPoolName = new CaPoolName(_projectId, _locationId, _caPool),
};
string caFilter = null;
if (!string.IsNullOrEmpty(_caId))
{
caFilter = _caId;
_logger.LogDebug($"Will filter certificates client-side by issuing CA ID: {caFilter}");
}
if (issuedAfter != null)
{
Timestamp ts = Timestamp.FromDateTime(issuedAfter.Value.ToUniversalTime());
_logger.LogDebug($"Filtering issued certificates by update_time >= {ts}");
request.Filter = $"update_time >= {ts}";
}
_logger.LogTrace($"Setting up {typeof(CallSettings).ToString()} with provided {typeof(CancellationToken).ToString()} {this.ToString()}");
CallSettings settings = CallSettings.FromCancellationToken(cancelToken);
_logger.LogDebug($"Downloading all issued certificates from GCP CAS {this.ToString()}");
PagedAsyncEnumerable<ListCertificatesResponse, Certificate> certificates = _client.ListCertificatesAsync(request, settings);
int pageNumber = 0;
int numberOfCertificates = 0;
int skippedCertificates = 0;
try
{
await foreach (var response in certificates.AsRawResponses())
{
if (response.Certificates == null)
{
_logger.LogWarning($"GCP returned null certificate list for page number {pageNumber} - continuing {this.ToString()}");
continue;
}
foreach (Certificate certificate in response.Certificates)
{
if (caFilter != null)
{
CertificateAuthorityName issuer = CertificateAuthorityName.Parse(certificate.IssuerCertificateAuthority);
if (issuer.CertificateAuthorityId != caFilter)
{
_logger.LogTrace($"Skipping certificate {certificate.CertificateName.CertificateId} - issued by {issuer.CertificateAuthorityId}, not {caFilter}");
continue;
}
}
AnyCAPluginCertificate pluginCertificate = AnyCAPluginCertificateFromGCPCertificate(certificate);
// Mirror the subject handling the AnyCA Gateway performs when it builds the
// /v2/certificate/search response: `new X509Name(true, netCert.Subject)`. That call throws
// on subjects BouncyCastle cannot re-parse from .NET's string form, which 500s the entire
// gateway search page and aborts Command's CA sync. Skip such certs here so they never enter
// the gateway database and can never break the downstream sync.
if (!GatewayCanParseSubject(pluginCertificate.Certificate, out string subject, out string skipReason))
{
skippedCertificates++;
_logger.LogWarning($"[SYNC-SKIP] Skipping certificate {pluginCertificate.CARequestID} - its subject would fail the AnyCA Gateway X509Name parse and abort the sync. Subject='{subject}', reason: {skipReason}");
continue;
}
certificatesBuffer.Add(pluginCertificate);
numberOfCertificates++;
_logger.LogDebug($"Found Certificate with name {certificate.CertificateName.CertificateId} {this.ToString()}");
}
_logger.LogTrace($"Fetched page {pageNumber} - Next Page Token: {response.NextPageToken}");
pageNumber++;
}
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.ResourceExhausted)
{
_logger.LogError($"Rate limit exceeded while fetching certificates: {ex.Message}");
throw;
}
catch (OperationCanceledException)
{
_logger.LogWarning("Certificate download operation was canceled.");
throw;
}
catch (Exception ex)
{
_logger.LogError($"Unexpected error while fetching certificates: {ex.Message}");
throw;
}
finally
{
certificatesBuffer.CompleteAdding();
_logger.LogDebug($"Fetched {certificatesBuffer.Count} certificates from GCP over {pageNumber} pages.");
_logger.LogInformation($"[SYNC-DIAG] Handed {numberOfCertificates} certificate(s) to the AnyCA Gateway buffer; skipped {skippedCertificates} certificate(s) with subjects the gateway cannot parse. Review the per-record [SYNC-DIAG]/[SYNC-SKIP] lines above for details.");
}
_logger.MethodExit();
return numberOfCertificates;
}
/// <summary>
/// Downloads a certificate with the specified <paramref name="certificateId"/> in PEM format and stores it in a <see cref="AnyCAPluginCertificate"/>.
/// </summary>
/// <param name="certificateId">
/// The Certificate ID of the certificate to download.
/// </param>
/// <returns>
/// Returns a <see cref="Task"/> and task result as a <see cref="AnyCAPluginCertificate"/> containing the downloaded certificate.
/// </returns>
public async Task<AnyCAPluginCertificate> DownloadCertificate(string certificateId)
{
_logger.MethodEntry();
EnsureClientIsEnabled();
_logger.LogDebug($"Downloading certificate with ID {certificateId} {this.ToString()}");
_logger.LogTrace($"Setting up {typeof(GetCertificateRequest).ToString()} with {this.ToString()} and [certificateId={certificateId}]");
GetCertificateRequest request = new GetCertificateRequest
{
Name = new CertificateName(_projectId, _locationId, _caPool, certificateId).ToString()
};
Certificate certificate = await _client.GetCertificateAsync(request);
_logger.LogTrace("GetCertificateAsync succeeded");
_logger.MethodExit();
return AnyCAPluginCertificateFromGCPCertificate(certificate);
}
private AnyCAPluginCertificate AnyCAPluginCertificateFromGCPCertificate(Certificate certificate)
{
_logger.MethodEntry();
string productId = "";
if (certificate.CertificateTemplateAsCertificateTemplateName == null)
{
productId = GCPCASPluginConfig.NoTemplateName;
}
else
{
productId = certificate.CertificateTemplateAsCertificateTemplateName.CertificateTemplateId;
}
EndEntityStatus status = EndEntityStatus.GENERATED;
DateTime? revocationDate = null;
int? revocationReason = null;
// Certificate is considered as revoked if and only if RevocationDetails is not null
if (certificate.RevocationDetails != null)
{
revocationDate = certificate.RevocationDetails.RevocationTime.ToDateTime();
status = EndEntityStatus.REVOKED;
revocationReason = (int)certificate.RevocationDetails.RevocationState;
}
string caRequestId = certificate.CertificateName.CertificateId;
string pem = certificate.PemCertificate;
// DIAGNOSTIC: the AnyCA Gateway derives the synced certificate's fingerprint and notBefore
// (the fields Command's sync gates on) by parsing the content we put in AnyCAPluginCertificate.Certificate.
// Log the shape of that content and the metadata that *should* be derivable from it, so we can
// compare against what the Gateway stores / returns to Command on the /v2/certificate/search response.
LogCertificateContentDiagnostics(caRequestId, pem, status, revocationDate, revocationReason);
_logger.MethodExit();
return new AnyCAPluginCertificate
{
CARequestID = caRequestId,
Certificate = pem,
Status = (int)status,
ProductID = productId,
RevocationDate = revocationDate,
RevocationReason = revocationReason,
};
}
/// <summary>
/// Emits detailed diagnostics about the certificate content being handed to the AnyCA Gateway.
/// The Gateway parses <see cref="AnyCAPluginCertificate.Certificate"/> to populate the fingerprint and
/// notBefore fields that Command's incremental sync (IssuedDateSyncPartitionTracker) gates on. Logging
/// the raw shape and the parsed metadata here pinpoints whether the plugin is the source of empty/zero
/// values seen downstream.
/// </summary>
private void LogCertificateContentDiagnostics(string caRequestId, string pem, EndEntityStatus status, DateTime? revocationDate, int? revocationReason)
{
try
{
if (string.IsNullOrEmpty(pem))
{
_logger.LogWarning($"[SYNC-DIAG] CARequestID={caRequestId}: PemCertificate is NULL or EMPTY - the Gateway will have no content to derive fingerprint/notBefore from. status={status} revoked={(revocationDate != null)}");
return;
}
bool hasPemArmor = pem.Contains("-----BEGIN");
_logger.LogTrace($"[SYNC-DIAG] CARequestID={caRequestId}: PemCertificate length={pem.Length}, hasPemArmor={hasPemArmor}, first40='{pem.Substring(0, Math.Min(40, pem.Length)).Replace("\n", "\\n").Replace("\r", "\\r")}'");
// Parse exactly what the Gateway would parse to derive metadata.
using var parsed = X509Certificate2.CreateFromPem(pem);
long notBeforeEpochMs = new DateTimeOffset(parsed.NotBefore.ToUniversalTime()).ToUnixTimeMilliseconds();
long notAfterEpochMs = new DateTimeOffset(parsed.NotAfter.ToUniversalTime()).ToUnixTimeMilliseconds();
_logger.LogDebug(
$"[SYNC-DIAG] CARequestID={caRequestId}: parsed OK -> Thumbprint(fingerprint)={parsed.Thumbprint}, " +
$"SerialNumber={parsed.SerialNumber}, Subject='{parsed.Subject}', " +
$"NotBefore={parsed.NotBefore:o} (epochMs={notBeforeEpochMs}), NotAfter={parsed.NotAfter:o} (epochMs={notAfterEpochMs}), " +
$"status={status}, revoked={(revocationDate != null)}, revocationReason={revocationReason}");
}
catch (Exception ex)
{
_logger.LogWarning($"[SYNC-DIAG] CARequestID={caRequestId}: FAILED to parse PemCertificate into an X509Certificate2 - the Gateway will likely store an empty fingerprint / notBefore=0 for this record. Error: {ex.Message}");
}
}
/// <summary>
/// Mirrors the subject parsing the AnyCA Gateway performs when it builds the /v2/certificate/search
/// response: <c>new Org.BouncyCastle.Asn1.X509.X509Name(true, netCert.Subject)</c>. That call throws on
/// subjects BouncyCastle cannot re-parse from .NET's string representation, which 500s the entire gateway
/// search page and aborts Command's CA sync. Returning <see langword="false"/> lets the sync skip the
/// certificate so it never enters the gateway database and can never break the downstream Command sync.
/// </summary>
/// <param name="pem">The PEM certificate content that will be handed to the gateway.</param>
/// <param name="subject">The parsed .NET subject string, when available (for logging).</param>
/// <param name="failureReason">The exception message when parsing fails.</param>
/// <returns><see langword="true"/> if the gateway can parse the subject; otherwise <see langword="false"/>.</returns>
private bool GatewayCanParseSubject(string pem, out string subject, out string failureReason)
{
subject = null;
failureReason = null;
try
{
using X509Certificate2 netCert = X509Certificate2.CreateFromPem(pem);
subject = netCert.Subject;
// This is the exact operation the gateway performs and that throws on problematic subjects.
_ = new Org.BouncyCastle.Asn1.X509.X509Name(true, subject);
return true;
}
catch (Exception ex)
{
failureReason = ex.Message;
return false;
}
}
/// <summary>
/// Enrolls a certificate using a configured <see cref="ICreateCertificateRequestBuilder"/> and returns the result.
/// </summary>
/// <param name="createCertificateRequestBuilder">
/// The <see cref="ICreateCertificateRequestBuilder"/> to use for the enrollment. Must be configured before calling this method.
/// </param>
/// <param name="cancelToken">
/// The <see cref="CancellationToken"/> to cancel the operation.
/// </param>
/// <returns>
/// Returns a <see cref="Task"/> and task result as an <see cref="EnrollmentResult"/> containing the result of the enrollment.
/// </returns>
public async Task<EnrollmentResult> Enroll(ICreateCertificateRequestBuilder createCertificateRequestBuilder, CancellationToken cancelToken)
{
try
{
_logger.MethodEntry();
EnsureClientIsEnabled();
CreateCertificateRequest request = createCertificateRequestBuilder.Build(_locationId, _projectId, _caPool, _caId);
if (request != null)
{
_logger.LogTrace($"Request Json {JsonConvert.SerializeObject(request)}");
}
Certificate certificate = await _client.CreateCertificateAsync(request, cancelToken);
if (certificate != null)
{
_logger.LogTrace($"Response Json {JsonConvert.SerializeObject(certificate)}");
}
_logger.MethodExit();
return new EnrollmentResult
{
CARequestID = certificate.CertificateName.CertificateId,
Certificate = certificate.PemCertificate,
Status = (int)EndEntityStatus.GENERATED,
StatusMessage = $"Certificate with ID {certificate.CertificateName} has been issued",
};
}
catch (RpcException rpcEx)
{
_logger.LogError(rpcEx, "RPC Exception while creating certificate.");
return new EnrollmentResult
{
Status = (int)EndEntityStatus.FAILED,
StatusMessage = $"RPC Error: {rpcEx.Status.Detail}",
};
}
catch (OperationCanceledException)
{
_logger.LogWarning("Certificate enrollment operation was canceled.");
return new EnrollmentResult
{
Status = (int)EndEntityStatus.CANCELLED,
StatusMessage = "Certificate enrollment was canceled.",
};
}
catch (Exception ex)
{
_logger.LogError(ex, "Unexpected error during certificate enrollment.");
return new EnrollmentResult
{
Status = (int)EndEntityStatus.FAILED,
StatusMessage = $"Unexpected error: {ex.Message}",
};
}
}
/// <summary>
/// Revokes a certificate with the specified <paramref name="certificateId"/> and <paramref name="reason"/>.
/// </summary>
/// <param name="certificateId">
/// The Certificate ID of the certificate to revoke.
/// </param>
/// <param name="reason">
/// The <see cref="RevocationReason"/> to revoke the certificate.
/// </param>
/// <returns></returns>
public Task RevokeCertificate(string certificateId, RevocationReason reason)
{
_logger.MethodEntry();
EnsureClientIsEnabled();
_logger.LogDebug($"Revoking certificate with ID {certificateId} for reason {reason.ToString()} {this.ToString()}");
_logger.LogTrace($"Setting up {typeof(RevokeCertificateRequest).ToString()} with {this.ToString()} and [certificateId={certificateId}]");
RevokeCertificateRequest request = new RevokeCertificateRequest
{
Name = new CertificateName(_projectId, _locationId, _caPool, certificateId).ToString(),
Reason = reason,
};
_logger.MethodExit();
return _client.RevokeCertificateAsync(request);
}
/// <summary>
/// Retrieves the templates available in a GCP CAS project/region.
/// </summary>
/// <returns>
/// A <see cref="List{T}"/> of <see cref="string"/> containing the available <see cref="Google.Cloud.Security.PrivateCA.V1.CertificateTemplateName"/>s.
/// </returns>
public List<string> GetTemplates()
{
_logger.MethodEntry();
EnsureClientIsEnabled();
_logger.LogDebug($"Getting Certificate Templates from GCP CA Service for Project: {_projectId}, Location: {_locationId}");
LocationName location = new LocationName(_projectId, _locationId);
List<string> templateStrings = new List<string>();
PagedEnumerable<ListCertificateTemplatesResponse, CertificateTemplate> templates = _client.ListCertificateTemplates(location);
int pageNumber = 0;
// By iterating over templates or templates.AsRawResponses(),
// API requests are made transparently, propagating the page token from one response to the next request
// until all pages are fetched.
foreach (ListCertificateTemplatesResponse response in templates.AsRawResponses())
{
foreach (CertificateTemplate template in response.CertificateTemplates)
{
_logger.LogDebug($"Found Certificate Template: {template.Name}");
templateStrings.Add(template.CertificateTemplateName.CertificateTemplateId);
}
_logger.LogTrace($"Next Page Token: {response.NextPageToken}");
pageNumber++;
}
_logger.LogDebug($"Found {templateStrings.Count} Certificate Templates across {pageNumber} pages");
_logger.LogDebug($"Adding the default certificate template called {GCPCASPluginConfig.NoTemplateName}");
templateStrings.Add(GCPCASPluginConfig.NoTemplateName);
return templateStrings;
}
private void EnsureClientIsEnabled()
{
if (!_clientIsEnabled)
{
_logger.LogWarning("GCPCASClient client is disabled - throwing");
throw new Exception("GCPCASClient is disabled");
}
}
}