-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGCPStore.cs
More file actions
502 lines (435 loc) · 23.1 KB
/
Copy pathGCPStore.cs
File metadata and controls
502 lines (435 loc) · 23.1 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
// Copyright 2021 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.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using Keyfactor.Orchestrators.Common.Enums;
using Keyfactor.Orchestrators.Extensions;
using Keyfactor.Logging;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Compute.v1.Data;
using Google.Apis.Services;
using Data = Google.Apis.Compute.v1.Data;
using static Google.Apis.Requests.BatchRequest;
namespace Keyfactor.Extensions.Orchestrator.GCPLoadBalancer
{
public class GCPStore
{
private string jsonKey;
private string project;
private string region = string.Empty;
private ComputeService service;
ILogger logger;
private const int OPERATION_MAX_WAIT_MILLISECONDS = 300000;
private const int OPERATION_INTERVAL_WAIT_MILLISECONDS = 5000;
private const string OPERATION_DONE = "DONE";
private const string TEMP_ALIAS_SUFFIX = "-temp";
private const int MAX_ALIAS_LENGTH = 63;
public GCPStore(string storePath, Dictionary<string, string> storeProperties)
{
logger = LogHandler.GetClassLogger<Management>();
SetProjectAndRegion(storePath);
this.jsonKey = storeProperties["jsonKey"];
logger.LogDebug("project: " + this.project);
logger.LogDebug("jsonKey size:" + this.jsonKey.Length);
}
public void insert(SslCertificate sslCertificate, bool overwrite)
{
string alias = sslCertificate.Name;
string tempAlias = CreateTempAlias(alias);
string targetCertificateSelfLink = string.Empty;
string tempCertificateSelfLink = string.Empty;
try
{
try
{
targetCertificateSelfLink = GetCeritificateSelfLink(alias);
}
catch (Google.GoogleApiException ex)
{
if (ex.HttpStatusCode != System.Net.HttpStatusCode.NotFound)
throw;
}
//SCENARIO => certificate alias exists, but overwrite flag not set. ERROR
if (!string.IsNullOrEmpty(targetCertificateSelfLink) && !overwrite)
{
string message = "Overwrite flag not set but certificate exists. If attempting to renew, please check overwrite when scheduling this job.";
logger.LogError(message);
throw new Exception(message);
}
//SCENARIO => certificate alias does not exist and overwrite not set. Because overwrite was not set we do not need to check for temporary alias that may have been created in an earlier
// job but not removed due to error. Since overwrite is not set, the renewal workflow that could have generated a temporary alias would not have been run. INSERT NEW CERTIFICATE, NO BINDINGS
if (string.IsNullOrEmpty(targetCertificateSelfLink) && !overwrite)
{
logger.LogDebug("Certificate is not in GCP. Insert new certificate.");
insert(sslCertificate);
return;
}
// check for existence of cert with this temporary alias in GCP
logger.LogDebug($"Get cert for temp alias - {tempAlias}");
try
{
tempCertificateSelfLink = GetCeritificateSelfLink(tempAlias);
}
catch (Google.GoogleApiException ex)
{
if (ex.HttpStatusCode != System.Net.HttpStatusCode.NotFound)
throw;
}
//SCENARIO => Overwrite flag set. Neither the passed in alias nor the temporary alias exists, so no clean up from a previous job is necessary. No
// certificate exists. INSERT NEW CERTIFICATE, NO BINDINGS
if (string.IsNullOrEmpty(targetCertificateSelfLink) && string.IsNullOrEmpty(tempCertificateSelfLink))
{
logger.LogDebug("Certificate is not in GCP. Insert new certificate.");
insert(sslCertificate);
return;
}
//SCENARIO => certificate exists for passed in alias
if (!string.IsNullOrEmpty(targetCertificateSelfLink))
{
//SCENARIO => if temporary certificate does not already exist, it must be added so it can be bound next as a temporary pre-cursor to removing desired alias, adding it and binding with it
if (string.IsNullOrEmpty(tempCertificateSelfLink))
{
logger.LogDebug("Certificate exists in GCP. Begin renewal by adding certificate with temporary alias.");
SslCertificate tempSSLCertificate = new SslCertificate() { Certificate = sslCertificate.Certificate, PrivateKey = sslCertificate.PrivateKey, Name = tempAlias };
insert(tempSSLCertificate);
try
{
tempCertificateSelfLink = GetCeritificateSelfLink(tempAlias);
}
catch (Google.GoogleApiException ex)
{
if (ex.HttpStatusCode != System.Net.HttpStatusCode.NotFound)
throw ex;
}
}
//SCENARIO => renew certificate process - bind to temporary alias, delete previous version of cert with desired alias, add renewed certificate, update bindings to renewed cert and remove temp bindings,
// delete cert with temp alias
logger.LogDebug("Replace bindings with renewed certificate added with temporary alias");
processBindings(targetCertificateSelfLink, tempCertificateSelfLink);
logger.LogDebug("Delete previous certificate");
delete(alias);
logger.LogDebug("Add renewed certificate with desired alias");
insert(sslCertificate);
logger.LogDebug("Replace bindings with renewed certificate added with desired alias");
processBindings(tempCertificateSelfLink, targetCertificateSelfLink);
logger.LogDebug("Remove certificate previously added with temporary alias");
delete(tempAlias);
}
//SCENARIO => certificate does NOT exist for passed in alias. certificate MUST exist for temporary alias since we already know one or both MUST exist from previous check.
// Add renewed certificate with passed in alias, bind it while removing temporary alias from binding (if exists), delete temporary alias cert
else
{
logger.LogDebug("Certificate is not in GCP, but temporary one is - Cleanup of prior error state. insert renewed certificate, bind renewed certificate and remove temp binding, delete temporary certificate.");
logger.LogDebug("Insert renewed certificate with desired alias");
insert(sslCertificate);
logger.LogDebug("Replace bindings with renewed certificate added with desired alias");
processBindings(tempCertificateSelfLink, targetCertificateSelfLink);
logger.LogDebug("Remove certificate previously added with temporary alias");
delete(tempAlias);
return;
}
}
catch (Exception ex)
{
logger.LogError("Error adding or binding certificate: " + ex.Message);
logger.LogDebug(ex.StackTrace);
throw ex;
}
}
public List<CurrentInventoryItem> list()
{
List<CurrentInventoryItem> inventoryItems = new List<CurrentInventoryItem>();
SslCertificatesResource.ListRequest globalRequest = getComputeService().SslCertificates.List(this.project);
RegionSslCertificatesResource.ListRequest regionRequest = getComputeService().RegionSslCertificates.List(this.project, this.region);
SslCertificateList response;
do
{
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
response = string.IsNullOrEmpty(region) ? globalRequest.Execute() : regionRequest.Execute();
// response = string.IsNullOrEmpty(region) ? await globalRequest.ExecuteAsync() : await regionRequest.ExecuteAsync();
if (response.Items == null)
{
continue;
}
logger.LogDebug("Found certificates:" + response.Items.Count);
// Record inventory
/*AgentInventoryItemStatus aiis = existing.ContainsKey(sslCertificate.Name)
? existing[sslCertificate.Name].Equals(x.Thumbprint, StringComparison.OrdinalIgnoreCase)
? AgentInventoryItemStatus.Unchanged
: AgentInventoryItemStatus.Modified
: AgentInventoryItemStatus.New;*/
foreach (Data.SslCertificate sslCertificate in response.Items)
{
//logger.LogDebug(JsonConvert.SerializeObject(sslCertificate));
if (sslCertificate.Type == "MANAGED")
{
logger.LogDebug("Adding Google Managed Certificate:" + sslCertificate.Name);
inventoryItems.Add(new CurrentInventoryItem()
{
Alias = sslCertificate.Name,
Certificates = new string[] { sslCertificate.Certificate },
ItemStatus = OrchestratorInventoryItemStatus.Unknown,
PrivateKeyEntry = true,
UseChainLevel = false
});
}
else
{
logger.LogDebug("Adding Self Managed Certificate with Alias:" + sslCertificate.Name);
inventoryItems.Add(new CurrentInventoryItem()
{
Alias = sslCertificate.Name,
Certificates = new string[] { sslCertificate.SelfManaged.Certificate },
ItemStatus = OrchestratorInventoryItemStatus.Unknown,
PrivateKeyEntry = true,
UseChainLevel = false
});
}
}
if (string.IsNullOrEmpty(region))
{
globalRequest.PageToken = response.NextPageToken;
}
else
{
regionRequest.PageToken = response.NextPageToken;
}
} while (response.NextPageToken != null);
return inventoryItems;
}
public void insert(SslCertificate sslCertificate)
{
Operation response = new Operation();
if (string.IsNullOrEmpty(region))
{
SslCertificatesResource.InsertRequest request = getComputeService().SslCertificates.Insert(sslCertificate, this.project);
response = request.Execute();
System.Threading.Thread.Sleep(10000);
}
else
{
RegionSslCertificatesResource.InsertRequest request = getComputeService().RegionSslCertificates.Insert(sslCertificate, this.project, region);
response = request.Execute();
System.Threading.Thread.Sleep(10000);
}
if (response.HttpErrorStatusCode != null)
{
logger.LogError("Error performing certificate add: " + response.HttpErrorMessage);
logger.LogDebug(response.HttpErrorStatusCode.ToString());
throw new Exception(response.HttpErrorMessage);
}
if (response.Error != null)
{
logger.LogError("Error performing certificate add: " + response.Error.ToString());
logger.LogDebug(response.Error.ToString());
throw new Exception(response.Error.ToString());
}
if (response.Status.ToUpper() != OPERATION_DONE)
WaitForOperation(response.Name, $"Inserting certificate for alias {sslCertificate.Name}");
}
public void delete(string alias)
{
Operation response = new Operation();
if (string.IsNullOrEmpty(region))
{
SslCertificatesResource.DeleteRequest request = getComputeService().SslCertificates.Delete(this.project, alias);
response = request.Execute();
}
else
{
RegionSslCertificatesResource.DeleteRequest request = getComputeService().RegionSslCertificates.Delete(this.project, region, alias);
response = request.Execute();
}
if (response.HttpErrorStatusCode != null)
{
logger.LogError("Error performing certificate delete: " + response.HttpErrorMessage);
logger.LogDebug(response.HttpErrorStatusCode.ToString());
throw new Exception(response.HttpErrorMessage);
}
if (response.Error != null)
{
logger.LogError("Error performing certificate delete: " + response.Error.ToString());
logger.LogDebug(response.Error.ToString());
throw new Exception(response.Error.ToString());
}
if (response.Status.ToUpper() != OPERATION_DONE)
WaitForOperation(response.Name, $"Deleting {alias}");
}
private void WaitForOperation(string operationName, string function)
{
logger.LogDebug($"Begin WAIT for {function}.");
System.DateTime endTime = System.DateTime.Now.AddMilliseconds(OPERATION_MAX_WAIT_MILLISECONDS);
Operation response = new Operation();
while (System.DateTime.Now < endTime)
{
logger.LogDebug($"Attempting WAIT for {function} at {System.DateTime.Now.ToString()}.");
if (string.IsNullOrEmpty(region))
{
GlobalOperationsResource.WaitRequest request = getComputeService().GlobalOperations.Wait(this.project, operationName);
response = request.Execute();
}
else
{
RegionOperationsResource.WaitRequest request = getComputeService().RegionOperations.Wait(this.project, region, operationName);
response = request.Execute();
}
if (response.Status == OPERATION_DONE)
{
logger.LogDebug($"End WAIT for {function}. Task DONE.");
return;
}
System.Threading.Thread.Sleep(OPERATION_INTERVAL_WAIT_MILLISECONDS);
}
throw new Exception($"{function} was still processing after the {OPERATION_MAX_WAIT_MILLISECONDS.ToString()} millisecond maximum wait time.");
}
private void processBindings(string prevCertificateSelfLink, string newCertificateSelfLink)
{
try
{
// For HTTPS proxy resources
TargetHttpsProxyList httpsProxyList = new TargetHttpsProxyList();
if (string.IsNullOrEmpty(region))
{
TargetHttpsProxiesResource.ListRequest request = new TargetHttpsProxiesResource(getComputeService()).List(project);
httpsProxyList = request.Execute();
}
else
{
RegionTargetHttpsProxiesResource.ListRequest request = new RegionTargetHttpsProxiesResource(getComputeService()).List(project, region);
httpsProxyList = request.Execute();
}
if (httpsProxyList.Items != null)
{
foreach (TargetHttpsProxy proxy in httpsProxyList.Items)
{
if (proxy.SslCertificates.Contains(prevCertificateSelfLink) || proxy.SslCertificates.Contains(newCertificateSelfLink))
{
List<string> sslCertificates = (List<string>)proxy.SslCertificates;
if (proxy.SslCertificates.Contains(prevCertificateSelfLink))
sslCertificates.Remove(prevCertificateSelfLink);
if (proxy.SslCertificates.Contains(newCertificateSelfLink))
sslCertificates.Remove(newCertificateSelfLink);
sslCertificates.Add(newCertificateSelfLink);
Operation response = new Operation();
if (string.IsNullOrEmpty(region))
{
TargetHttpsProxiesSetSslCertificatesRequest httpsCertRequest = new TargetHttpsProxiesSetSslCertificatesRequest();
httpsCertRequest.SslCertificates = sslCertificates;
TargetHttpsProxiesResource.SetSslCertificatesRequest setSSLRequest = new TargetHttpsProxiesResource(getComputeService()).SetSslCertificates(httpsCertRequest, project, proxy.Name);
response = setSSLRequest.Execute();
}
else
{
RegionTargetHttpsProxiesSetSslCertificatesRequest httpsCertRequest = new RegionTargetHttpsProxiesSetSslCertificatesRequest();
httpsCertRequest.SslCertificates = sslCertificates;
RegionTargetHttpsProxiesResource.SetSslCertificatesRequest setSSLRequest = new RegionTargetHttpsProxiesResource(getComputeService()).SetSslCertificates(httpsCertRequest, project, region, proxy.Name);
response = setSSLRequest.Execute();
}
if (response.HttpErrorStatusCode != null)
{
logger.LogError($"Error setting SSL Certificates for resource: {proxy.Name} " + response.HttpErrorMessage);
throw new Exception(response.HttpErrorMessage);
}
if (response.Error != null)
{
logger.LogError($"Error setting SSL Certificates for resource: {proxy.Name} " + response.Error.ToString());
throw new Exception(response.Error.ToString());
}
if (response.Status.ToUpper() != OPERATION_DONE)
WaitForOperation(response.Name, $"Binding for {newCertificateSelfLink}");
}
}
}
}
catch (Exception ex)
{
string message = "Error attempting to bind added certificate to resource " + ex.Message;
logger.LogError(message);
throw new Exception(message);
}
}
private string GetCeritificateSelfLink(string prevAlias)
{
SslCertificate certificate = new SslCertificate();
if (string.IsNullOrEmpty(region))
{
SslCertificatesResource.GetRequest request = this.getComputeService().SslCertificates.Get(project, prevAlias);
certificate = request.Execute();
}
else
{
RegionSslCertificatesResource.GetRequest request = this.getComputeService().RegionSslCertificates.Get(project, region, prevAlias);
certificate = request.Execute();
}
if (certificate == null || string.IsNullOrEmpty(certificate.Certificate))
return null;
return certificate.SelfLink;
}
private ComputeService getComputeService()
{
if (this.service == null) {
logger.LogDebug("Initializing new Compute Service");
this.service = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
}
return this.service;
}
private GoogleCredential GetCredential()
{
//Example Environment variable for Application Default
//Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"C:\development\GCPAnyAgent\Tests\GCPCreds.json");
//Example reading from File
//GoogleCredential credential = GoogleCredential.FromFile("Keyfactor.Extensions.Orchestrator.GCP.Tests.GCPCreds.json");
GoogleCredential credential;
if (String.IsNullOrWhiteSpace(this.jsonKey))
{
logger.LogDebug("Loading credentials from application default");
credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
}
else
{
logger.LogDebug("Loading key from store properties");
credential = GoogleCredential.FromJson(jsonKey);
}
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
private void SetProjectAndRegion(string storePath)
{
project = storePath;
if (storePath.Contains("/"))
{
string[] projectRegion = storePath.Split('/');
project = projectRegion[0];
region = projectRegion[1];
}
}
private string CreateTempAlias(string alias)
{
return MAX_ALIAS_LENGTH - TEMP_ALIAS_SUFFIX.Length >= alias.Length ? alias + TEMP_ALIAS_SUFFIX : alias.Substring(0, MAX_ALIAS_LENGTH - TEMP_ALIAS_SUFFIX.Length) + TEMP_ALIAS_SUFFIX;
}
}
}