/
connector.go
1568 lines (1349 loc) · 46 KB
/
connector.go
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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018-2022 Venafi, Inc.
*
* 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.
*/
package cloud
import (
"archive/zip"
"bytes"
"crypto/rand"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io"
"log"
"net/http"
netUrl "net/url"
"strings"
"time"
"github.com/go-http-utils/headers"
"golang.org/x/crypto/nacl/box"
"github.com/Venafi/vcert/v5/pkg/certificate"
"github.com/Venafi/vcert/v5/pkg/endpoint"
"github.com/Venafi/vcert/v5/pkg/policy"
"github.com/Venafi/vcert/v5/pkg/util"
"github.com/Venafi/vcert/v5/pkg/verror"
)
type urlResource string
const (
apiURL = "api.venafi.cloud/"
apiVersion = "v1/"
basePath = "outagedetection/" + apiVersion
urlResourceUserAccounts urlResource = apiVersion + "useraccounts"
urlResourceCertificateRequests urlResource = basePath + "certificaterequests"
urlResourceCertificatesRetirement = urlResourceCertificates + "/retirement"
urlResourceCertificateStatus = urlResourceCertificateRequests + "/%s"
urlResourceCertificates urlResource = basePath + "certificates"
urlResourceCertificateByID = urlResourceCertificates + "/%s"
urlResourceCertificateRetrievePem = urlResourceCertificates + "/%s/contents"
urlResourceCertificateSearch urlResource = basePath + "certificatesearch"
urlResourceTemplate urlResource = basePath + "applications/%s/certificateissuingtemplates/%s"
urlAppDetailsByName urlResource = basePath + "applications/name/%s"
urlIssuingTemplate urlResource = apiVersion + "certificateissuingtemplates"
urlAppRoot urlResource = basePath + "applications"
urlCAAccounts urlResource = apiVersion + "certificateauthorities/%s/accounts"
urlCAAccountDetails = urlCAAccounts + "/%s"
urlResourceCertificateKS = urlResourceCertificates + "/%s/keystore"
urlDekPublicKey urlResource = apiVersion + "edgeencryptionkeys/%s"
urlUsers urlResource = apiVersion + "users"
urlUserById = urlUsers + "/%s"
urlUsersByName = urlUsers + "/username/%s"
urlTeams urlResource = apiVersion + "teams"
defaultAppName = "Default"
oauthTokenType = "Bearer"
)
type condorChainOption string
const (
condorChainOptionRootFirst condorChainOption = "ROOT_FIRST"
condorChainOptionRootLast condorChainOption = "EE_FIRST"
)
// Connector contains the base data needed to communicate with the Venafi Cloud servers
type Connector struct {
baseURL string
apiKey string
accessToken string
verbose bool
user *userDetails
trust *x509.CertPool
zone cloudZone
client *http.Client
userAgent string
}
// NewConnector creates a new Venafi Cloud Connector object used to communicate with Venafi Cloud
func NewConnector(url string, zone string, verbose bool, trust *x509.CertPool) (*Connector, error) {
cZone := cloudZone{zone: zone}
c := Connector{verbose: verbose, trust: trust, zone: cZone, userAgent: util.DefaultUserAgent}
var err error
c.baseURL, err = normalizeURL(url)
if err != nil {
return nil, err
}
return &c, nil
}
func (c *Connector) GetType() endpoint.ConnectorType {
return endpoint.ConnectorTypeCloud
}
func (c *Connector) SetZone(z string) {
cZone := cloudZone{zone: z}
c.zone = cZone
}
func (c *Connector) SetUserAgent(userAgent string) {
c.userAgent = userAgent
}
func (c *Connector) SetHTTPClient(client *http.Client) {
c.client = client
}
// Ping attempts to connect to the Venafi Cloud API and returns an error if it cannot
func (c *Connector) Ping() (err error) {
return nil
}
// Authenticate authenticates the user with Venafi Cloud using the provided API Key
func (c *Connector) Authenticate(auth *endpoint.Authentication) error {
if auth == nil {
return fmt.Errorf("failed to authenticate: missing credentials")
}
//1. Access token. Assign it to connector and return
if auth.AccessToken != "" {
c.accessToken = auth.AccessToken
return nil
}
//2. JWT and token URL. use it to request new access token
if auth.TokenURL != "" && auth.ExternalJWT != "" {
tokenResponse, err := c.GetAccessToken(auth)
if err != nil {
return err
}
c.accessToken = tokenResponse.AccessToken
return nil
}
// 3. API key. Get user to test authentication
c.apiKey = auth.APIKey
url := c.getURL(urlResourceUserAccounts)
statusCode, status, body, err := c.request("GET", url, nil, true)
if err != nil {
return err
}
ud, err := parseUserDetailsResult(http.StatusOK, statusCode, status, body)
if err != nil {
return err
}
c.user = ud
return nil
}
func (c *Connector) ReadPolicyConfiguration() (policy *endpoint.Policy, err error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
config, err := c.ReadZoneConfiguration()
if err != nil {
return nil, err
}
policy = &config.Policy
return
}
// ReadZoneConfiguration reads the Zone information needed for generating and requesting a certificate from Venafi Cloud
func (c *Connector) ReadZoneConfiguration() (config *endpoint.ZoneConfiguration, err error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
var template *certificateTemplate
var statusCode int
// to fully support the "headless registration" use case...
// if application does not exist and is for the default CIT, create the application
citAlias := c.zone.getTemplateAlias()
if citAlias == "Default" {
appName := c.zone.getApplicationName()
_, statusCode, err = c.getAppDetailsByName(appName)
if err != nil && statusCode == 404 {
log.Printf("creating application %s for issuing template %s", appName, citAlias)
ps := policy.PolicySpecification{}
template, err = getCit(c, citAlias)
if err != nil {
return
}
_, err = c.createApplication(appName, &ps, template)
if err != nil {
return
}
}
}
if template == nil {
template, err = c.getTemplateByID()
if err != nil {
return
}
}
config = getZoneConfiguration(template)
return config, nil
}
// GetZonesByParent returns a list of valid zones for a VaaS application specified by parent
func (c *Connector) GetZonesByParent(parent string) ([]string, error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
var zones []string
appDetails, _, err := c.getAppDetailsByName(parent)
if err != nil {
return nil, err
}
for citAlias := range appDetails.CitAliasToIdMap {
zone := fmt.Sprintf("%s\\%s", parent, citAlias)
zones = append(zones, zone)
}
return zones, nil
}
// ResetCertificate resets the state of a certificate.
func (c *Connector) ResetCertificate(_ *certificate.Request, _ bool) (err error) {
return fmt.Errorf("not supported by endpoint")
}
// RequestCertificate submits the CSR to the Venafi Cloud API for processing
func (c *Connector) RequestCertificate(req *certificate.Request) (requestID string, err error) {
if !c.isAuthenticated() {
return "", fmt.Errorf("must be autheticated to request a certificate")
}
url := c.getURL(urlResourceCertificateRequests)
cloudReq, err := c.getCloudRequest(req)
if err != nil {
return "", err
}
statusCode, status, body, err := c.request("POST", url, cloudReq)
if err != nil {
return "", err
}
cr, err := parseCertificateRequestResult(statusCode, status, body)
if err != nil {
return "", err
}
requestID = cr.CertificateRequests[0].ID
req.PickupID = requestID
return requestID, nil
}
// RetrieveCertificate retrieves the certificate for the specified ID
func (c *Connector) RetrieveCertificate(req *certificate.Request) (certificates *certificate.PEMCollection, err error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
if req.PickupID == "" && req.CertID == "" && req.Thumbprint != "" {
// search cert by Thumbprint and fill pickupID
var certificateRequestId string
searchResult, err := c.searchCertificatesByFingerprint(req.Thumbprint)
if err != nil {
return nil, fmt.Errorf("failed to retrieve certificate: %s", err)
}
if len(searchResult.Certificates) == 0 {
return nil, fmt.Errorf("no certificate found using fingerprint %s", req.Thumbprint)
}
var reqIds []string
isOnlyOneCertificateRequestId := true
for _, c := range searchResult.Certificates {
reqIds = append(reqIds, c.CertificateRequestId)
if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId {
isOnlyOneCertificateRequestId = false
}
if c.CertificateRequestId != "" {
certificateRequestId = c.CertificateRequestId
}
if c.Id != "" {
req.CertID = c.Id
}
}
if !isOnlyOneCertificateRequestId {
return nil, fmt.Errorf("more than one CertificateRequestId was found with the same Fingerprint: %s", reqIds)
}
req.PickupID = certificateRequestId
}
startTime := time.Now()
//Wait for certificate to be issued by checking its PickupID
//If certID is filled then certificate should be already issued.
var certificateId string
if req.CertID == "" {
for {
if req.PickupID == "" {
break
}
certStatus, err := c.getCertificateStatus(req.PickupID)
if err != nil {
return nil, fmt.Errorf("unable to retrieve: %s", err)
}
if certStatus.Status == "ISSUED" {
certificateId = certStatus.CertificateIdsList[0]
break // to fetch the cert itself
} else if certStatus.Status == "FAILED" {
return nil, fmt.Errorf("failed to retrieve certificate. Status: %v", certStatus)
}
// status.Status == "REQUESTED" || status.Status == "PENDING"
if req.Timeout == 0 {
return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID, Status: certStatus.Status}
} else {
log.Println("Issuance of certificate is pending...")
}
if time.Now().After(startTime.Add(req.Timeout)) {
return nil, endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID}
}
// fmt.Printf("pending... %s\n", status.Status)
time.Sleep(2 * time.Second)
}
} else {
certificateId = req.CertID
}
url := c.getURL(urlResourceCertificateRetrievePem)
url = fmt.Sprintf(url, certificateId)
var dekInfo *EdgeEncryptionKey
var currentId string
if req.CertID != "" {
dekInfo, err = getDekInfo(c, req.CertID)
currentId = req.CertID
} else if certificateId != "" {
dekInfo, err = getDekInfo(c, certificateId)
currentId = certificateId
}
if err == nil && dekInfo.Key != "" {
req.CertID = currentId
return retrieveServiceGeneratedCertData(c, req, dekInfo)
}
switch {
case req.CertID != "":
statusCode, status, body, err := c.waitForCertificate(url, req) //c.request("GET", url, nil)
if err != nil {
return nil, err
}
if statusCode != http.StatusOK {
return nil, fmt.Errorf("failed to retrieve certificate. StatusCode: %d -- Status: %s -- Server Data: %s", statusCode, status, body)
}
return newPEMCollectionFromResponse(body, certificate.ChainOptionIgnore)
case req.PickupID != "":
url += "?chainOrder=%s&format=PEM"
switch req.ChainOption {
case certificate.ChainOptionRootFirst:
url = fmt.Sprintf(url, condorChainOptionRootFirst)
default:
url = fmt.Sprintf(url, condorChainOptionRootLast)
}
statusCode, status, body, err := c.waitForCertificate(url, req) //c.request("GET", url, nil)
if err != nil {
return nil, err
}
if statusCode == http.StatusOK {
certificates, err = newPEMCollectionFromResponse(body, req.ChainOption)
if err != nil {
return nil, err
}
err = req.CheckCertificate(certificates.Certificate)
return certificates, err
} else if statusCode == http.StatusConflict { // Http Status Code 409 means the certificate has not been signed by the ca yet.
return nil, endpoint.ErrCertificatePending{CertificateID: req.PickupID}
} else {
return nil, fmt.Errorf("failed to retrieve certificate. StatusCode: %d -- Status: %s", statusCode, status)
}
}
return nil, fmt.Errorf("couldn't retrieve certificate because both PickupID and CertId are empty")
}
// RenewCertificate attempts to renew the certificate
func (c *Connector) RenewCertificate(renewReq *certificate.RenewalRequest) (requestID string, err error) {
if !c.isAuthenticated() {
return "", fmt.Errorf("must be autheticated to request a certificate")
}
/* 1st step is to get CertificateRequestId which is required to lookup managedCertificateId and zoneId */
var certificateRequestId string
if renewReq.Thumbprint != "" {
// by Thumbprint (aka Fingerprint)
searchResult, err := c.searchCertificatesByFingerprint(renewReq.Thumbprint)
if err != nil {
return "", fmt.Errorf("failed to create renewal request: %s", err)
}
if len(searchResult.Certificates) == 0 {
return "", fmt.Errorf("no certificate found using fingerprint %s", renewReq.Thumbprint)
}
var reqIds []string
isOnlyOneCertificateRequestId := true
for _, c := range searchResult.Certificates {
reqIds = append(reqIds, c.CertificateRequestId)
if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId {
isOnlyOneCertificateRequestId = false
}
certificateRequestId = c.CertificateRequestId
}
if !isOnlyOneCertificateRequestId {
return "", fmt.Errorf("error: more than one CertificateRequestId was found with the same Fingerprint: %s", reqIds)
}
} else if renewReq.CertificateDN != "" {
// by CertificateDN (which is the same as CertificateRequestId for current implementation)
certificateRequestId = renewReq.CertificateDN
} else {
return "", fmt.Errorf("failed to create renewal request: CertificateDN or Thumbprint required")
}
/* 2nd step is to get ManagedCertificateId & ZoneId by looking up certificate request record */
previousRequest, err := c.getCertificateStatus(certificateRequestId)
if err != nil {
return "", fmt.Errorf("certificate renew failed: %s", err)
}
applicationId := previousRequest.ApplicationId
templateId := previousRequest.TemplateId
certificateId := previousRequest.CertificateIdsList[0]
emptyField := ""
if certificateId == "" {
emptyField = "certificateId"
} else if applicationId == "" {
emptyField = "applicationId"
} else if templateId == "" {
emptyField = "templateId"
}
if emptyField != "" {
return "", fmt.Errorf("failed to submit renewal request for certificate: %s is empty, certificate status is %s", emptyField, previousRequest.Status)
}
/* 3rd step is to get Certificate Object by id
and check if latestCertificateRequestId there equals to certificateRequestId from 1st step */
managedCertificate, err := c.getCertificate(certificateId)
if err != nil {
return "", fmt.Errorf("failed to renew certificate: %s", err)
}
if managedCertificate.CertificateRequestId != certificateRequestId {
withThumbprint := ""
if renewReq.Thumbprint != "" {
withThumbprint = fmt.Sprintf("with thumbprint %s ", renewReq.Thumbprint)
}
return "", fmt.Errorf(
"certificate under requestId %s %s is not the latest under CertificateId %s."+
"The latest request is %s. This error may happen when revoked certificate is requested to be renewed",
certificateRequestId, withThumbprint, certificateId, managedCertificate.CertificateRequestId)
}
/* 4th step is to send renewal request */
url := c.getURL(urlResourceCertificateRequests)
req := certificateRequest{
ExistingCertificateId: certificateId,
ApplicationId: applicationId,
TemplateId: templateId,
}
if renewReq.CertificateRequest.Location != nil {
workload := renewReq.CertificateRequest.Location.Workload
if workload == "" {
workload = defaultAppName
}
nodeName := renewReq.CertificateRequest.Location.Instance
appName := workload
req.CertificateUsageMetadata = []certificateUsageMetadata{
{
AppName: appName,
NodeName: nodeName,
},
}
}
if renewReq.CertificateRequest != nil && len(renewReq.CertificateRequest.GetCSR()) != 0 {
req.CSR = string(renewReq.CertificateRequest.GetCSR())
req.ReuseCSR = false
} else {
req.ReuseCSR = true
return "", fmt.Errorf("reuseCSR option is not currently available for Renew Certificate operation. A new CSR must be provided in the request")
}
statusCode, status, body, err := c.request("POST", url, req)
if err != nil {
return
}
cr, err := parseCertificateRequestResult(statusCode, status, body)
if err != nil {
return "", fmt.Errorf("failed to renew certificate: %s", err)
}
return cr.CertificateRequests[0].ID, nil
}
// RetireCertificate attempts to retire the certificate
func (c *Connector) RetireCertificate(retireReq *certificate.RetireRequest) error {
if !c.isAuthenticated() {
return fmt.Errorf("must be autheticated to request a certificate")
}
url := c.getURL(urlResourceCertificatesRetirement)
/* 1st step is to get CertificateRequestId which is required to retire certificate */
var certificateRequestId string
if retireReq.Thumbprint != "" {
// by Thumbprint (aka Fingerprint)
searchResult, err := c.searchCertificatesByFingerprint(retireReq.Thumbprint)
if err != nil {
return fmt.Errorf("failed to create retire request: %s", err)
}
if len(searchResult.Certificates) == 0 {
return fmt.Errorf("no certificate found using fingerprint %s", retireReq.Thumbprint)
}
var reqIds []string
isOnlyOneCertificateRequestId := true
for _, c := range searchResult.Certificates {
reqIds = append(reqIds, c.CertificateRequestId)
if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId {
isOnlyOneCertificateRequestId = false
}
certificateRequestId = c.CertificateRequestId
}
if !isOnlyOneCertificateRequestId {
return fmt.Errorf("error: more than one CertificateRequestId was found with the same Fingerprint: %s", reqIds)
}
} else if retireReq.CertificateDN != "" {
// by CertificateDN (which is the same as CertificateRequestId for current implementation)
certificateRequestId = retireReq.CertificateDN
} else {
return fmt.Errorf("failed to create retire request: CertificateDN or Thumbprint required")
}
/* 2nd step is to get ManagedCertificateId & ZoneId by looking up certificate request record */
previousRequest, err := c.getCertificateStatus(certificateRequestId)
if err != nil {
if strings.Contains(err.Error(), "Unable to find certificateRequest") {
return fmt.Errorf("invalid thumbprint or certificate ID. No certificates were retired")
}
return fmt.Errorf("certificate retirement failed: error on getting Certificate ID: %s", err)
}
certificateId := previousRequest.CertificateIdsList[0]
/* Now we do retirement*/
retRequest := certificateRetireRequest{
CertificateIds: []string{certificateId},
}
statusCode, status, response, err := c.request("POST", url, retRequest)
if err != nil {
return err
}
err = checkCertificateRetireResults(statusCode, status, response)
if err != nil {
return err
}
return nil
}
// RevokeCertificate attempts to revoke the certificate
func (c *Connector) RevokeCertificate(_ *certificate.RevocationRequest) (err error) {
return fmt.Errorf("not supported by endpoint")
}
func (c *Connector) ImportCertificate(req *certificate.ImportRequest) (*certificate.ImportResponse, error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
pBlock, _ := pem.Decode([]byte(req.CertificateData))
if pBlock == nil {
return nil, fmt.Errorf("%w can`t parse certificate", verror.UserDataError)
}
zone := req.PolicyDN
if zone == "" {
appDetails, _, err := c.getAppDetailsByName(c.zone.getApplicationName())
if err != nil {
return nil, err
}
zone = appDetails.ApplicationId
}
ipAddr := endpoint.LocalIP
origin := endpoint.SDKName
for _, f := range req.CustomFields {
if f.Type == certificate.CustomFieldOrigin {
origin = f.Value
}
}
base64.StdEncoding.EncodeToString(pBlock.Bytes)
fingerprint := certThumbprint(pBlock.Bytes)
request := importRequest{
Certificates: []importRequestCertInfo{
{
Certificate: base64.StdEncoding.EncodeToString(pBlock.Bytes),
ApplicationIds: []string{zone},
ApiClientInformation: apiClientInformation{
Type: origin,
Identifier: ipAddr,
},
},
},
}
url := c.getURL(urlResourceCertificates)
statusCode, status, body, err := c.request("POST", url, request)
if err != nil {
return nil, fmt.Errorf("%w: %v", verror.ServerTemporaryUnavailableError, err)
}
var r importResponse
switch statusCode {
case http.StatusOK, http.StatusCreated, http.StatusAccepted:
case http.StatusBadRequest, http.StatusForbidden, http.StatusConflict:
return nil, fmt.Errorf("%w: certificate can`t be imported. %d %s %s", verror.ServerBadDataResponce, statusCode, status, string(body))
case http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable:
return nil, verror.ServerTemporaryUnavailableError
default:
return nil, verror.ServerError
}
err = json.Unmarshal(body, &r)
if err != nil {
return nil, fmt.Errorf("%w: can`t unmarshal json response %s", verror.ServerError, err)
} else if !(len(r.CertificateInformations) == 1) {
return nil, fmt.Errorf("%w: certificate was not imported on unknown reason", verror.ServerBadDataResponce)
}
time.Sleep(time.Second)
foundCert, err := c.searchCertificatesByFingerprint(fingerprint)
if err != nil {
return nil, err
}
if len(foundCert.Certificates) != 1 {
return nil, fmt.Errorf("%w certificate has been imported but could not be found on platform after that", verror.ServerError)
}
cert := foundCert.Certificates[0]
resp := &certificate.ImportResponse{CertificateDN: cert.SubjectCN[0], CertId: cert.Id}
return resp, nil
}
func (c *Connector) ListCertificates(filter endpoint.Filter) ([]certificate.CertificateInfo, error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
if c.zone.String() == "" {
return nil, fmt.Errorf("empty zone")
}
const batchSize = 50
limit := 100000000
if filter.Limit != nil {
limit = *filter.Limit
}
var buf [][]certificate.CertificateInfo
for page := 0; limit > 0; limit, page = limit-batchSize, page+1 {
var b []certificate.CertificateInfo
var err error
b, err = c.getCertsBatch(page, batchSize, filter.WithExpired)
if limit < batchSize && len(b) > limit {
b = b[:limit]
}
if err != nil {
return nil, err
}
buf = append(buf, b)
if len(b) < batchSize {
break
}
}
sumLen := 0
for _, b := range buf {
sumLen += len(b)
}
infos := make([]certificate.CertificateInfo, sumLen)
offset := 0
for _, b := range buf {
copy(infos[offset:], b[:])
offset += len(b)
}
return infos, nil
}
func (c *Connector) SearchCertificates(_ *certificate.SearchRequest) (*certificate.CertSearchResponse, error) {
panic("operation is not supported yet")
}
func (c *Connector) SearchCertificate(zone string, cn string, sans *certificate.Sans, certMinTimeLeft time.Duration) (certificateInfo *certificate.CertificateInfo, err error) {
if !c.isAuthenticated() {
return nil, fmt.Errorf("must be autheticated to request a certificate")
}
// retrieve application name from zone
appName := getAppNameFromZone(zone)
// get application id from name
app, _, err := c.getAppDetailsByName(appName)
if err != nil {
return nil, err
}
// format arguments for request
req := formatSearchCertificateArguments(cn, sans, certMinTimeLeft)
// perform request
searchResult, err := c.searchCertificates(req)
if err != nil {
return nil, err
}
// fail if no certificate is returned from api
if searchResult.Count == 0 {
return nil, verror.NoCertificateFoundError
}
// map (convert) response to an array of CertificateInfo
certificates := make([]*certificate.CertificateInfo, 0)
n := 0
for _, cert := range searchResult.Certificates {
if util.ArrayContainsString(cert.ApplicationIds, app.ApplicationId) {
match := cert.ToCertificateInfo()
certificates = append(certificates, &match)
n = n + 1
}
}
// fail if no certificates found with matching zone
if n == 0 {
return nil, verror.NoCertificateWithMatchingZoneFoundError
}
// at this point all certificates belong to our zone, the next step is
// finding the newest valid certificate matching the provided sans
return certificate.FindNewestCertificateWithSans(certificates, sans)
}
func (c *Connector) IsCSRServiceGenerated(req *certificate.Request) (bool, error) {
if !c.isAuthenticated() {
return false, fmt.Errorf("must be autheticated to request a certificate")
}
if req.PickupID == "" && req.CertID == "" && req.Thumbprint != "" {
// search cert by Thumbprint and fill pickupID
var certificateRequestId string
searchResult, err := c.searchCertificatesByFingerprint(req.Thumbprint)
if err != nil {
return false, fmt.Errorf("failed to retrieve certificate: %s", err)
}
if len(searchResult.Certificates) == 0 {
return false, fmt.Errorf("no certificate found using fingerprint %s", req.Thumbprint)
}
var reqIds []string
for _, c := range searchResult.Certificates {
reqIds = append(reqIds, c.CertificateRequestId)
if certificateRequestId != "" && certificateRequestId != c.CertificateRequestId {
return false, fmt.Errorf("more than one CertificateRequestId was found with the same Fingerprint: %s", reqIds)
}
if c.CertificateRequestId != "" {
certificateRequestId = c.CertificateRequestId
}
if c.Id != "" {
req.CertID = c.Id
}
}
req.PickupID = certificateRequestId
}
var dekInfo *EdgeEncryptionKey
var currentId string
var err error
if req.CertID != "" {
dekInfo, err = getDekInfo(c, req.CertID)
} else {
var certificateId string
certificateId, err = getCertificateId(c, req)
if err == nil && certificateId != "" {
dekInfo, err = getDekInfo(c, certificateId)
}
}
if err == nil && dekInfo.Key != "" {
req.CertID = currentId
return true, err
}
return false, nil
}
func (c *Connector) RetrieveCertificateMetaData(_ string) (*certificate.CertificateMetaData, error) {
panic("operation is not supported yet")
}
// SynchronousRequestCertificate It's not supported yet in VaaS
func (c *Connector) SynchronousRequestCertificate(_ *certificate.Request) (certificates *certificate.PEMCollection, err error) {
panic("operation is not supported yet")
}
// SupportSynchronousRequestCertificate returns if the connector support synchronous calls to request a certificate.
func (c *Connector) SupportSynchronousRequestCertificate() bool {
return false
}
func (c *Connector) RetrieveSystemVersion() (response string, err error) {
panic("operation is not supported yet")
}
func getCertificateId(c *Connector, req *certificate.Request) (string, error) {
startTime := time.Now()
//Wait for certificate to be issued by checking its PickupID
//If certID is filled then certificate should be already issued.
for {
if req.PickupID == "" {
break
}
certStatus, err := c.getCertificateStatus(req.PickupID)
if err != nil {
return "", fmt.Errorf("unable to retrieve: %s", err)
}
if certStatus.Status == "ISSUED" {
return certStatus.CertificateIdsList[0], nil
} else if certStatus.Status == "FAILED" {
return "", fmt.Errorf("failed to retrieve certificate. Status: %v", certStatus)
}
if req.Timeout == 0 {
return "", endpoint.ErrCertificatePending{CertificateID: req.PickupID, Status: certStatus.Status}
} else {
log.Println("Issuance of certificate is pending...")
}
if time.Now().After(startTime.Add(req.Timeout)) {
return "", endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID}
}
time.Sleep(2 * time.Second)
}
return "", endpoint.ErrRetrieveCertificateTimeout{CertificateID: req.PickupID}
}
// normalizeURL allows overriding the default URL used to communicate with Venafi Cloud
func normalizeURL(url string) (normalizedURL string, err error) {
if url == "" {
url = apiURL
}
normalizedURL = util.NormalizeUrl(url)
return normalizedURL, nil
}
func (c *Connector) GetAccessToken(auth *endpoint.Authentication) (*TLSPCAccessTokenResponse, error) {
if auth == nil || auth.TokenURL == "" || auth.ExternalJWT == "" {
return nil, fmt.Errorf("failed to authenticate: missing credentials")
}
url, err := getServiceAccountTokenURL(auth.TokenURL)
if err != nil {
return nil, fmt.Errorf("failed to authenticate: %w", err)
}
body := netUrl.Values{}
body.Set("grant_type", "client_credentials")
body.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
body.Set("client_assertion", auth.ExternalJWT)
r, err := http.NewRequest(http.MethodPost, url, strings.NewReader(body.Encode()))
if err != nil {
err = fmt.Errorf("%w: %v", verror.VcertError, err)
return nil, err
}
r.Header.Set(headers.UserAgent, c.userAgent)
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient := c.getHTTPClient()
resp, err := httpClient.Do(r)
if err != nil {
err = fmt.Errorf("%w: %v", verror.ServerUnavailableError, err)
return nil, err
}
statusCode := resp.StatusCode
status := resp.Status
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("%w: %v", verror.ServerError, err)
return nil, err
}
accessTokenResponse, err := parseAccessTokenResponse(http.StatusOK, statusCode, status, respBody)
if err != nil {
return nil, err
}
if !strings.EqualFold(accessTokenResponse.TokenType, oauthTokenType) {
return nil, fmt.Errorf(
"%w: got an access token but token type is not %s. Expected: %s. Got: %s", verror.ServerError,
oauthTokenType, oauthTokenType, accessTokenResponse.TokenType)
}
return accessTokenResponse, nil
}
func (c *Connector) isAuthenticated() bool {
if c.accessToken != "" {
return true
}
if c.user != nil && c.user.Company != nil {
return true
}
return false
}
func (c *Connector) getCloudRequest(req *certificate.Request) (*certificateRequest, error) {
ipAddr := endpoint.LocalIP
origin := endpoint.SDKName
for _, f := range req.CustomFields {
if f.Type == certificate.CustomFieldOrigin {
origin = f.Value
}
}
appDetails, _, err := c.getAppDetailsByName(c.zone.getApplicationName())
if err != nil {
return nil, err
}
templateId := appDetails.CitAliasToIdMap[c.zone.getTemplateAlias()]
cloudReq := certificateRequest{
ApplicationId: appDetails.ApplicationId,
TemplateId: templateId,
ApiClientInformation: certificateRequestClientInfo{
Type: origin,
Identifier: ipAddr,
},
}
if req.CsrOrigin != certificate.ServiceGeneratedCSR {
cloudReq.CSR = string(req.GetCSR())
} else {
cloudReq.IsVaaSGenerated = true
csrAttr, err := getCsrAttributes(c, req)
if err != nil {
return nil, err
}
cloudReq.CsrAttributes = *(csrAttr)
cloudReq.ApplicationServerTypeId = util.ApplicationServerTypeID
}
if req.Location != nil {
workload := req.Location.Workload
if workload == "" {
workload = defaultAppName
}
nodeName := req.Location.Instance
appName := workload
cloudReq.CertificateUsageMetadata = []certificateUsageMetadata{
{
AppName: appName,
NodeName: nodeName,
},
}
}
validityDuration := req.ValidityDuration
// DEPRECATED: ValidityHours is deprecated in favor of ValidityDuration, but we
// still support it for backwards compatibility.
if validityDuration == nil && req.ValidityHours > 0 { //nolint:staticcheck
duration := time.Duration(req.ValidityHours) * time.Hour //nolint:staticcheck
validityDuration = &duration
}
if validityDuration != nil {
cloudReq.ValidityPeriod = "PT" + strings.ToUpper((*validityDuration).Truncate(time.Second).String())
}
return &cloudReq, nil
}