github.com/Venafi/vcert/v5@v5.10.2/pkg/venafi/cloud/connector_test.go (about)

     1  /*
     2   * Copyright 2018 Venafi, Inc.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *  http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package cloud
    18  
    19  import (
    20  	"crypto/rand"
    21  	"crypto/rsa"
    22  	"crypto/sha1"
    23  	"crypto/x509"
    24  	"crypto/x509/pkix"
    25  	"encoding/hex"
    26  	"encoding/pem"
    27  	"errors"
    28  	"fmt"
    29  	"math/big"
    30  	"net"
    31  	"net/url"
    32  	"os"
    33  	"reflect"
    34  	"strconv"
    35  	"strings"
    36  	"testing"
    37  	"time"
    38  
    39  	"github.com/Venafi/vcert/v5/pkg/certificate"
    40  	"github.com/Venafi/vcert/v5/pkg/endpoint"
    41  	"github.com/Venafi/vcert/v5/pkg/policy"
    42  	"github.com/Venafi/vcert/v5/pkg/util"
    43  	"github.com/Venafi/vcert/v5/pkg/verror"
    44  	"github.com/Venafi/vcert/v5/test"
    45  )
    46  
    47  var ctx *test.Context
    48  
    49  func init() {
    50  	ctx = test.GetEnvContext()
    51  	// http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    52  
    53  	if ctx.CloudAPIkey == "" {
    54  		fmt.Println("API key cannot be empty. See Makefile")
    55  		os.Exit(1)
    56  	}
    57  }
    58  
    59  func getTestConnector(zone string) *Connector {
    60  	url, _ := normalizeURL(ctx.CloudUrl)
    61  	c, _ := NewConnector(url, zone, true, nil)
    62  	return c
    63  }
    64  
    65  func TestPing(t *testing.T) {
    66  	conn := getTestConnector("")
    67  	err := conn.Ping()
    68  	if err != nil {
    69  		t.Fatalf("%s", err)
    70  	}
    71  }
    72  
    73  func TestAuthenticate(t *testing.T) {
    74  	conn := getTestConnector(ctx.CloudZone)
    75  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
    76  	if err != nil {
    77  		t.Fatalf("%s", err)
    78  	}
    79  }
    80  
    81  func TestReadZoneConfiguration(t *testing.T) {
    82  	conn := getTestConnector(ctx.CloudZone)
    83  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
    84  	if err != nil {
    85  		t.Fatalf("%s", err)
    86  	}
    87  
    88  	conn.SetZone("d686146b-799b-4836-8ac3-f4a2d3a38934")
    89  	_, err = conn.ReadZoneConfiguration()
    90  	if !errors.Is(err, verror.ZoneNotFoundError) {
    91  		t.Fatalf("Unknown zone should have resulted in an error")
    92  	}
    93  	testCases := []struct {
    94  		zone       string
    95  		zoneConfig endpoint.ZoneConfiguration
    96  	}{
    97  		{ctx.CloudZone, endpoint.ZoneConfiguration{
    98  			CustomAttributeValues: make(map[string]string),
    99  		}},
   100  		{ctx.CloudZoneRestricted, endpoint.ZoneConfiguration{
   101  			Organization:          "Venafi Inc.",
   102  			OrganizationalUnit:    []string{"Integrations"},
   103  			Country:               "US",
   104  			Province:              "Utah",
   105  			Locality:              "Salt Lake",
   106  			CustomAttributeValues: make(map[string]string),
   107  			KeyConfiguration:      &endpoint.AllowedKeyConfiguration{KeyType: certificate.KeyTypeRSA, KeySizes: []int{4096}},
   108  		}},
   109  	}
   110  	for _, c := range testCases {
   111  		conn.SetZone(c.zone)
   112  		zoneConfig, err := conn.ReadZoneConfiguration()
   113  		if err != nil {
   114  			t.Fatalf("%s", err)
   115  		}
   116  		zoneConfig.Policy = endpoint.Policy{}
   117  		if !reflect.DeepEqual(*zoneConfig, c.zoneConfig) {
   118  			t.Fatalf("zone config for zone %s is not as expected \nget:    %+v \nexpect: %+v", c.zone, *zoneConfig, c.zoneConfig)
   119  		}
   120  	}
   121  
   122  }
   123  
   124  func TestRequestCertificate(t *testing.T) {
   125  	conn := getTestConnector(ctx.CloudZone)
   126  	conn.verbose = true
   127  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   128  	if err != nil {
   129  		t.Fatalf("%s", err)
   130  	}
   131  	zoneConfig, err := conn.ReadZoneConfiguration()
   132  	if err != nil {
   133  		t.Fatalf("%s", err)
   134  	}
   135  	req := certificate.Request{}
   136  	req.Subject.CommonName = test.RandCN()
   137  	req.Subject.Organization = []string{"Venafi, Inc."}
   138  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   139  	err = conn.GenerateRequest(zoneConfig, &req)
   140  	if err != nil {
   141  		t.Fatalf("%s", err)
   142  	}
   143  	_, err = conn.RequestCertificate(&req)
   144  	if err != nil {
   145  		t.Fatalf("%s", err)
   146  	}
   147  }
   148  
   149  func TestRequestCertificateED25519WithValidation(t *testing.T) {
   150  	conn := getTestConnector(ctx.VAASzoneEC)
   151  	conn.verbose = true
   152  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   153  	if err != nil {
   154  		t.Fatalf("%s", err)
   155  	}
   156  
   157  	req := certificate.Request{}
   158  	req.Subject.CommonName = test.RandSpecificCN("vfidev.com")
   159  	req.DNSNames = []string{req.Subject.CommonName}
   160  	req.Subject.Organization = []string{"Venafi Inc."}
   161  	req.Subject.OrganizationalUnit = []string{"Integrations"}
   162  	req.Subject.Locality = []string{"Salt Lake"}
   163  	req.Subject.Province = []string{"Utah"}
   164  	req.Subject.Country = []string{"US"}
   165  	req.KeyType = certificate.KeyTypeED25519
   166  
   167  	zoneConfig, err := conn.ReadZoneConfiguration()
   168  	if err != nil {
   169  		t.Fatalf("%s", err)
   170  	}
   171  
   172  	err = zoneConfig.ValidateCertificateRequest(&req)
   173  	if err != nil {
   174  		t.Fatalf("could not validate certificate request: %s", err)
   175  	}
   176  
   177  	zoneConfig.UpdateCertificateRequest(&req)
   178  
   179  	err = conn.GenerateRequest(zoneConfig, &req)
   180  	if err != nil {
   181  		t.Fatalf("%s", err)
   182  	}
   183  	_, err = conn.RequestCertificate(&req)
   184  	if err != nil {
   185  		t.Fatalf("%s", err)
   186  	}
   187  }
   188  
   189  func TestRequestCertificateED25519WithPolicyValidation(t *testing.T) {
   190  	conn := getTestConnector(ctx.VAASzoneEC)
   191  	conn.verbose = true
   192  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   193  	if err != nil {
   194  		t.Fatalf("%s", err)
   195  	}
   196  
   197  	req := certificate.Request{}
   198  	req.Subject.CommonName = test.RandSpecificCN("vfidev.com")
   199  	req.DNSNames = []string{req.Subject.CommonName}
   200  	req.Subject.Organization = []string{"Venafi Inc."}
   201  	req.Subject.OrganizationalUnit = []string{"Integrations"}
   202  	req.Subject.Locality = []string{"Salt Lake"}
   203  	req.Subject.Province = []string{"Utah"}
   204  	req.Subject.Country = []string{"US"}
   205  	req.KeyType = certificate.KeyTypeED25519
   206  
   207  	policy, err := conn.ReadPolicyConfiguration()
   208  	if err != nil {
   209  		t.Fatalf("could not read policy config certificate request: %s", err)
   210  	}
   211  
   212  	err = policy.ValidateCertificateRequest(&req)
   213  	if err != nil {
   214  		t.Fatalf("could not validate certificate request from policy: %s", err)
   215  	}
   216  
   217  	err = conn.GenerateRequest(nil, &req)
   218  	if err != nil {
   219  		t.Fatalf("%s", err)
   220  	}
   221  	_, err = conn.RequestCertificate(&req)
   222  	if err != nil {
   223  		t.Fatalf("%s", err)
   224  	}
   225  }
   226  
   227  func TestRequestCertificateWithUsageMetadata(t *testing.T) {
   228  	conn := getTestConnector(ctx.CloudZone)
   229  	conn.verbose = true
   230  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   231  	if err != nil {
   232  		t.Fatalf("%s", err)
   233  	}
   234  	zoneConfig, err := conn.ReadZoneConfiguration()
   235  	if err != nil {
   236  		t.Fatalf("%s", err)
   237  	}
   238  	req := certificate.Request{}
   239  	req.Subject.CommonName = test.RandCN()
   240  	req.Subject.Organization = []string{"Venafi, Inc."}
   241  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   242  
   243  	location := certificate.Location{
   244  		Instance: "vcert-sdk",
   245  	}
   246  	req.Location = &location
   247  
   248  	err = conn.GenerateRequest(zoneConfig, &req)
   249  	if err != nil {
   250  		t.Fatalf("%s", err)
   251  	}
   252  	_, err = conn.RequestCertificate(&req)
   253  	if err != nil {
   254  		t.Fatalf("%s", err)
   255  	}
   256  }
   257  
   258  func TestRequestCertificateWithValidityHours(t *testing.T) {
   259  	conn := getTestConnector(ctx.CloudZone)
   260  	conn.verbose = true
   261  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   262  	if err != nil {
   263  		t.Fatalf("%s", err)
   264  	}
   265  	zoneConfig, err := conn.ReadZoneConfiguration()
   266  	if err != nil {
   267  		t.Fatalf("%s", err)
   268  	}
   269  
   270  	req := &certificate.Request{}
   271  	req.Subject.CommonName = test.RandCN()
   272  	req.Subject.Organization = []string{"Venafi, Inc."}
   273  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   274  
   275  	nrHours := 144
   276  	req.ValidityHours = nrHours
   277  	req.IssuerHint = util.IssuerHintMicrosoft
   278  
   279  	err = conn.GenerateRequest(zoneConfig, req)
   280  	if err != nil {
   281  		t.Fatalf("%s", err)
   282  	}
   283  	pickupID, err := conn.RequestCertificate(req)
   284  	if err != nil {
   285  		t.Fatalf("%s", err)
   286  	}
   287  
   288  	req.PickupID = pickupID
   289  	req.ChainOption = certificate.ChainOptionRootLast
   290  
   291  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   292  	startTime := time.Now()
   293  	for {
   294  
   295  		pcc, err = conn.RetrieveCertificate(req)
   296  		if err != nil {
   297  			_, ok := err.(endpoint.ErrCertificatePending)
   298  			if ok {
   299  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   300  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   301  					break
   302  				}
   303  				time.Sleep(time.Duration(10) * time.Second)
   304  				continue
   305  			}
   306  			break
   307  		}
   308  		break
   309  	}
   310  	if err != nil {
   311  		t.Fatalf("%s", err)
   312  	}
   313  	p, _ := pem.Decode([]byte(pcc.Certificate))
   314  	cert, err := x509.ParseCertificate(p.Bytes)
   315  	if err != nil {
   316  		t.Fatalf("%s", err)
   317  	}
   318  
   319  	certValidUntil := cert.NotAfter.Format("2006-01-02")
   320  
   321  	//need to convert local date on utc, since the certificate' NotAfter value we got on previous step, is on utc
   322  	//so for comparing them we need to have both dates on utc.
   323  	loc, _ := time.LoadLocation("UTC")
   324  	expectedValidDate := time.Now().Add(time.Duration(nrHours) * time.Hour).In(loc).Format("2006-01-02")
   325  
   326  	if expectedValidDate != certValidUntil {
   327  		t.Fatalf("Expiration date is different than expected, expected: %s, but got %s: ", expectedValidDate, certValidUntil)
   328  	}
   329  
   330  }
   331  
   332  func TestRequestCertificateWithValidityDuration(t *testing.T) {
   333  	conn := getTestConnector(ctx.CloudZone)
   334  	conn.verbose = true
   335  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   336  	if err != nil {
   337  		t.Fatalf("%s", err)
   338  	}
   339  	zoneConfig, err := conn.ReadZoneConfiguration()
   340  	if err != nil {
   341  		t.Fatalf("%s", err)
   342  	}
   343  
   344  	req := &certificate.Request{}
   345  	req.Subject.CommonName = test.RandCN()
   346  	req.Subject.Organization = []string{"Venafi, Inc."}
   347  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   348  
   349  	validDuration := 144 * time.Hour
   350  	req.ValidityDuration = &validDuration
   351  	req.IssuerHint = util.IssuerHintMicrosoft
   352  
   353  	err = conn.GenerateRequest(zoneConfig, req)
   354  	if err != nil {
   355  		t.Fatalf("%s", err)
   356  	}
   357  	pickupID, err := conn.RequestCertificate(req)
   358  	if err != nil {
   359  		t.Fatalf("%s", err)
   360  	}
   361  
   362  	req.PickupID = pickupID
   363  	req.ChainOption = certificate.ChainOptionRootLast
   364  
   365  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   366  	startTime := time.Now()
   367  	for {
   368  
   369  		pcc, err = conn.RetrieveCertificate(req)
   370  		if err != nil {
   371  			_, ok := err.(endpoint.ErrCertificatePending)
   372  			if ok {
   373  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   374  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   375  					break
   376  				}
   377  				time.Sleep(time.Duration(10) * time.Second)
   378  				continue
   379  			}
   380  			break
   381  		}
   382  		break
   383  	}
   384  	if err != nil {
   385  		t.Fatalf("%s", err)
   386  	}
   387  	p, _ := pem.Decode([]byte(pcc.Certificate))
   388  	cert, err := x509.ParseCertificate(p.Bytes)
   389  	if err != nil {
   390  		t.Fatalf("%s", err)
   391  	}
   392  
   393  	certValidUntil := cert.NotAfter.Format("2006-01-02")
   394  
   395  	//need to convert local date on utc, since the certificate' NotAfter value we got on previous step, is on utc
   396  	//so for comparing them we need to have both dates on utc.
   397  	loc, _ := time.LoadLocation("UTC")
   398  	expectedValidDate := time.Now().Add(validDuration).In(loc).Format("2006-01-02")
   399  
   400  	if expectedValidDate != certValidUntil {
   401  		t.Fatalf("Expiration date is different than expected, expected: %s, but got %s: ", expectedValidDate, certValidUntil)
   402  	}
   403  
   404  }
   405  
   406  func TestRetrieveCertificate(t *testing.T) {
   407  	conn := getTestConnector(ctx.CloudZone)
   408  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   409  	if err != nil {
   410  		t.Fatalf("%s", err)
   411  	}
   412  	zoneConfig, err := conn.ReadZoneConfiguration()
   413  	if err != nil {
   414  		t.Fatalf("%s", err)
   415  	}
   416  	req := &certificate.Request{}
   417  	req.Subject.CommonName = test.RandCN()
   418  	req.Subject.Organization = []string{"Venafi, Inc."}
   419  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   420  	err = conn.GenerateRequest(zoneConfig, req)
   421  	if err != nil {
   422  		t.Fatalf("%s", err)
   423  	}
   424  	pickupID, err := conn.RequestCertificate(req)
   425  	if err != nil {
   426  		t.Fatalf("%s", err)
   427  	}
   428  	req.PickupID = pickupID
   429  	req.ChainOption = certificate.ChainOptionRootLast
   430  
   431  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   432  	startTime := time.Now()
   433  	for {
   434  
   435  		pcc, err = conn.RetrieveCertificate(req)
   436  		if err != nil {
   437  			_, ok := err.(endpoint.ErrCertificatePending)
   438  			if ok {
   439  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   440  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   441  					break
   442  				}
   443  				time.Sleep(time.Duration(10) * time.Second)
   444  				continue
   445  			}
   446  			break
   447  		}
   448  		break
   449  	}
   450  	if err != nil {
   451  		t.Fatalf("%s", err)
   452  	}
   453  	p, _ := pem.Decode([]byte(pcc.Certificate))
   454  	cert, err := x509.ParseCertificate(p.Bytes)
   455  	if err != nil {
   456  		t.Fatalf("%s", err)
   457  	}
   458  	if req.Subject.CommonName != cert.Subject.CommonName {
   459  		t.Fatalf("Retrieved certificate did not contain expected CN.  Expected: %s -- Actual: %s", req.Subject.CommonName, cert.Subject.CommonName)
   460  	}
   461  
   462  	p, _ = pem.Decode([]byte(pcc.Chain[0]))
   463  	cert, err = x509.ParseCertificate(p.Bytes)
   464  	if err != nil {
   465  		t.Fatalf("%s", err)
   466  	}
   467  	if !cert.IsCA || fmt.Sprintf("%v", cert.Subject) == fmt.Sprintf("%v", cert.Issuer) {
   468  		t.Fatalf("Expected Intermediate Root Certificate first, instead got Subject: %v -- Issuer %v", cert.Subject, cert.Issuer)
   469  	}
   470  }
   471  
   472  func TestRetrieveCertificateRootFirst(t *testing.T) {
   473  	conn := getTestConnector(ctx.CloudZone)
   474  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   475  	if err != nil {
   476  		t.Fatalf("%s", err)
   477  	}
   478  	zoneConfig, err := conn.ReadZoneConfiguration()
   479  	if err != nil {
   480  		t.Fatalf("%s", err)
   481  	}
   482  	req := &certificate.Request{}
   483  	req.Subject.CommonName = test.RandCN()
   484  	req.Subject.Organization = []string{"Venafi, Inc."}
   485  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   486  	err = conn.GenerateRequest(zoneConfig, req)
   487  	if err != nil {
   488  		t.Fatalf("%s", err)
   489  	}
   490  	pickupID, err := conn.RequestCertificate(req)
   491  	if err != nil {
   492  		t.Fatalf("%s", err)
   493  	}
   494  	req.PickupID = pickupID
   495  	req.ChainOption = certificate.ChainOptionRootFirst
   496  
   497  	startTime := time.Now()
   498  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   499  	for {
   500  		pcc, err = conn.RetrieveCertificate(req)
   501  		if err != nil {
   502  			_, ok := err.(endpoint.ErrCertificatePending)
   503  			if ok {
   504  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   505  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   506  					break
   507  				}
   508  				time.Sleep(time.Duration(10) * time.Second)
   509  				continue
   510  			}
   511  			break
   512  		}
   513  		break
   514  	}
   515  	if err != nil {
   516  		t.Fatalf("%s", err)
   517  	}
   518  	if len(pcc.Chain) <= 0 {
   519  		t.Fatalf("Chain Option was root to be first, chain count is %d", len(pcc.Chain))
   520  	}
   521  	p, _ := pem.Decode([]byte(pcc.Chain[0]))
   522  	cert, err := x509.ParseCertificate(p.Bytes)
   523  	if err != nil {
   524  		t.Fatalf("%s", err)
   525  	}
   526  	if !cert.IsCA || fmt.Sprintf("%v", cert.Subject) != fmt.Sprintf("%v", cert.Issuer) {
   527  		t.Fatalf("Expected Root Certificate first, instead got Subject: %v -- Issuer %v", cert.Subject, cert.Issuer)
   528  	}
   529  
   530  	p, _ = pem.Decode([]byte(pcc.Certificate))
   531  	cert, err = x509.ParseCertificate(p.Bytes)
   532  	if err != nil {
   533  		t.Fatalf("%s", err)
   534  	}
   535  	if req.Subject.CommonName != cert.Subject.CommonName {
   536  		t.Fatalf("Retrieved certificate did not contain expected CN.  Expected: %s -- Actual: %s", req.Subject.CommonName, cert.Subject.CommonName)
   537  	}
   538  }
   539  
   540  func TestGetCertificateStatus(t *testing.T) {
   541  	conn := getTestConnector(ctx.CloudZone)
   542  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   543  	if err != nil {
   544  		t.Fatalf("%s", err)
   545  	}
   546  	zoneConfig, err := conn.ReadZoneConfiguration()
   547  	if err != nil {
   548  		t.Fatalf("%s", err)
   549  	}
   550  	req := &certificate.Request{}
   551  	req.Subject.CommonName = test.RandCN()
   552  	req.Subject.Organization = []string{"Venafi, Inc."}
   553  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   554  	err = conn.GenerateRequest(zoneConfig, req)
   555  	if err != nil {
   556  		t.Fatalf("%s", err)
   557  	}
   558  	reqId, err := conn.RequestCertificate(req)
   559  	if err != nil {
   560  		t.Fatalf("%s", err)
   561  	}
   562  
   563  	_, err = conn.getCertificateStatus(reqId)
   564  	if err != nil {
   565  		t.Fatalf("failed to get certificate request status: %s", err)
   566  	}
   567  
   568  	invalidCertificateRequestId := "42424242-63a0-11e8-b5a3-f186be5c5fab"
   569  	_, err = conn.getCertificateStatus(invalidCertificateRequestId)
   570  	if err == nil {
   571  		t.Fatalf("it should return error when there is not such request found")
   572  	}
   573  }
   574  
   575  func TestRenewCertificate(t *testing.T) {
   576  	t.Skip() //todo: remove if condor team fix bug. check after 2020.04
   577  	conn := getTestConnector(ctx.CloudZone)
   578  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   579  	if err != nil {
   580  		t.Fatalf("%s", err)
   581  	}
   582  	zoneConfig, err := conn.ReadZoneConfiguration()
   583  	if err != nil {
   584  		t.Fatalf("%s", err)
   585  	}
   586  	req := &certificate.Request{}
   587  	req.Subject.CommonName = test.RandCN()
   588  	req.Subject.Organization = []string{"Venafi, Inc."}
   589  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   590  	err = conn.GenerateRequest(zoneConfig, req)
   591  	if err != nil {
   592  		t.Fatalf("%s", err)
   593  	}
   594  	pickupID, err := conn.RequestCertificate(req)
   595  	if err != nil {
   596  		t.Fatalf("%s", err)
   597  	}
   598  
   599  	renewTooEarly := &certificate.RenewalRequest{CertificateDN: pickupID}
   600  	_, err = conn.RenewCertificate(renewTooEarly)
   601  	if err == nil {
   602  		t.Fatal("it should return error on attempt to renew a certificate that is not issued yet")
   603  	}
   604  
   605  	req.PickupID = pickupID
   606  	req.ChainOption = certificate.ChainOptionRootFirst
   607  	startTime := time.Now()
   608  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   609  	for {
   610  		pcc, err = conn.RetrieveCertificate(req)
   611  		if err != nil {
   612  			_, ok := err.(endpoint.ErrCertificatePending)
   613  			if ok {
   614  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   615  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   616  					break
   617  				}
   618  				time.Sleep(time.Duration(10) * time.Second)
   619  				continue
   620  			}
   621  			break
   622  		}
   623  		break
   624  	}
   625  	if err != nil {
   626  		t.Fatalf("%s", err)
   627  	}
   628  
   629  	p, _ := pem.Decode([]byte(pcc.Certificate))
   630  	cert, err := x509.ParseCertificate(p.Bytes)
   631  	if err != nil {
   632  		t.Fatalf("%s", err)
   633  	}
   634  	fp := sha1.Sum(cert.Raw)
   635  	fingerprint := strings.ToUpper(hex.EncodeToString(fp[:]))
   636  	t.Logf("CERT: %s\n", pcc.Certificate)
   637  	t.Logf("FINGERPRINT: %s\n", fingerprint)
   638  
   639  	// time to renew
   640  	renewByFingerprint := &certificate.RenewalRequest{Thumbprint: strings.ToUpper(fingerprint)}
   641  	reqId3, err := conn.RenewCertificate(renewByFingerprint)
   642  	if err != nil {
   643  		t.Fatal(err)
   644  	}
   645  	t.Logf("requested renewal for %s, will pickup by %s", fingerprint, reqId3)
   646  
   647  	renewByCertificateDN := &certificate.RenewalRequest{CertificateDN: reqId3}
   648  	reqId1, err := conn.RenewCertificate(renewByCertificateDN)
   649  	if err != nil {
   650  		t.Fatal(err)
   651  	}
   652  	t.Logf("requested renewal for %s, will pickup by %s", pickupID, reqId1)
   653  
   654  }
   655  
   656  func TestRenewCertificateWithUsageMetadata(t *testing.T) {
   657  	t.Skip() //todo: remove if condor team fix bug. check after 2020.04
   658  	conn := getTestConnector(ctx.CloudZone)
   659  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   660  	if err != nil {
   661  		t.Fatalf("%s", err)
   662  	}
   663  	zoneConfig, err := conn.ReadZoneConfiguration()
   664  	if err != nil {
   665  		t.Fatalf("%s", err)
   666  	}
   667  	req := &certificate.Request{}
   668  	req.Subject.CommonName = test.RandCN()
   669  	req.Subject.Organization = []string{"Venafi, Inc."}
   670  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   671  
   672  	location := certificate.Location{
   673  		Instance: "vcert-sdk",
   674  	}
   675  	req.Location = &location
   676  
   677  	err = conn.GenerateRequest(zoneConfig, req)
   678  	if err != nil {
   679  		t.Fatalf("%s", err)
   680  	}
   681  	pickupID, err := conn.RequestCertificate(req)
   682  	if err != nil {
   683  		t.Fatalf("%s", err)
   684  	}
   685  
   686  	renewTooEarly := &certificate.RenewalRequest{CertificateDN: pickupID}
   687  	renewTooEarly.CertificateRequest.Location = &location
   688  
   689  	_, err = conn.RenewCertificate(renewTooEarly)
   690  	if err == nil {
   691  		t.Fatal("it should return error on attempt to renew a certificate that is not issued yet")
   692  	}
   693  
   694  	req.PickupID = pickupID
   695  	req.ChainOption = certificate.ChainOptionRootFirst
   696  	startTime := time.Now()
   697  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   698  	for {
   699  		pcc, err = conn.RetrieveCertificate(req)
   700  		if err != nil {
   701  			_, ok := err.(endpoint.ErrCertificatePending)
   702  			if ok {
   703  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   704  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   705  					break
   706  				}
   707  				time.Sleep(time.Duration(10) * time.Second)
   708  				continue
   709  			}
   710  			break
   711  		}
   712  		break
   713  	}
   714  	if err != nil {
   715  		t.Fatalf("%s", err)
   716  	}
   717  
   718  	p, _ := pem.Decode([]byte(pcc.Certificate))
   719  	cert, err := x509.ParseCertificate(p.Bytes)
   720  	if err != nil {
   721  		t.Fatalf("%s", err)
   722  	}
   723  	fp := sha1.Sum(cert.Raw)
   724  	fingerprint := strings.ToUpper(hex.EncodeToString(fp[:]))
   725  	t.Logf("CERT: %s\n", pcc.Certificate)
   726  	t.Logf("FINGERPRINT: %s\n", fingerprint)
   727  
   728  	// time to renew
   729  	renewByFingerprint := &certificate.RenewalRequest{Thumbprint: strings.ToUpper(fingerprint)}
   730  	renewByFingerprint.CertificateRequest.Location = &location
   731  	reqId3, err := conn.RenewCertificate(renewByFingerprint)
   732  	if err != nil {
   733  		t.Fatal(err)
   734  	}
   735  	t.Logf("requested renewal for %s, will pickup by %s", fingerprint, reqId3)
   736  
   737  	renewByCertificateDN := &certificate.RenewalRequest{CertificateDN: reqId3}
   738  	renewByCertificateDN.CertificateRequest.Location = &location
   739  	reqId1, err := conn.RenewCertificate(renewByCertificateDN)
   740  	if err != nil {
   741  		t.Fatal(err)
   742  	}
   743  	t.Logf("requested renewal for %s, will pickup by %s", pickupID, reqId1)
   744  
   745  }
   746  
   747  func TestReadPolicyConfiguration(t *testing.T) {
   748  	//todo: add more zones
   749  	conn := getTestConnector(ctx.CloudZone)
   750  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   751  	if err != nil {
   752  		t.Fatalf("%s", err)
   753  	}
   754  	policy, err := conn.ReadPolicyConfiguration()
   755  	if err != nil {
   756  		t.Fatalf("%s", err)
   757  	}
   758  	expectedPolice := endpoint.Policy{
   759  		SubjectCNRegexes:         []string{"^.*$"},
   760  		SubjectORegexes:          []string{"^.*$"},
   761  		SubjectOURegexes:         []string{"^.*$"},
   762  		SubjectSTRegexes:         []string{"^.*$"},
   763  		SubjectLRegexes:          []string{"^.*$"},
   764  		SubjectCRegexes:          []string{"^.*$"},
   765  		AllowedKeyConfigurations: []endpoint.AllowedKeyConfiguration{{certificate.KeyTypeRSA, []int{2048, 4096}, nil}},
   766  		DnsSanRegExs:             []string{"^.*$"},
   767  		AllowWildcards:           true,
   768  		AllowKeyReuse:            true,
   769  	}
   770  
   771  	if !reflect.DeepEqual(*policy, expectedPolice) {
   772  		t.Fatalf("policy for zone %s is not as expected \nget:    %+v \nexpect: %+v", ctx.CloudZone, *policy, expectedPolice)
   773  	}
   774  }
   775  
   776  func TestRetireCertificate(t *testing.T) {
   777  	conn := getTestConnector(ctx.CloudZone)
   778  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   779  	if err != nil {
   780  		t.Fatalf("%s", err)
   781  	}
   782  	zoneConfig, err := conn.ReadZoneConfiguration()
   783  	if err != nil {
   784  		t.Fatalf("%s", err)
   785  	}
   786  	req := &certificate.Request{}
   787  	req.Subject.CommonName = test.RandCN()
   788  	req.Subject.Organization = []string{"Venafi, Inc."}
   789  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   790  	err = conn.GenerateRequest(zoneConfig, req)
   791  	if err != nil {
   792  		t.Fatalf("%s", err)
   793  	}
   794  	pickupID, err := conn.RequestCertificate(req)
   795  	if err != nil {
   796  		t.Fatalf("%s", err)
   797  	}
   798  	req.PickupID = pickupID
   799  	req.ChainOption = certificate.ChainOptionRootLast
   800  
   801  	pcc, _ := certificate.NewPEMCollection(nil, nil, nil)
   802  	startTime := time.Now()
   803  	for {
   804  		pcc, err = conn.RetrieveCertificate(req)
   805  		if err != nil {
   806  			_, ok := err.(endpoint.ErrCertificatePending)
   807  			if ok {
   808  				if time.Now().After(startTime.Add(time.Duration(600) * time.Second)) {
   809  					err = endpoint.ErrRetrieveCertificateTimeout{CertificateID: pickupID}
   810  					break
   811  				}
   812  				time.Sleep(time.Duration(10) * time.Second)
   813  				continue
   814  			}
   815  			break
   816  		}
   817  		break
   818  	}
   819  	if err != nil {
   820  		t.Fatalf("%s", err)
   821  	}
   822  
   823  	p, _ := pem.Decode([]byte(pcc.Certificate))
   824  	cert, err := x509.ParseCertificate(p.Bytes)
   825  	retireReq := &certificate.RetireRequest{}
   826  	thumbprint := sha1.Sum(cert.Raw)
   827  	hexThumbprint := hex.EncodeToString((thumbprint[:]))
   828  	retireReq.Thumbprint = hexThumbprint
   829  
   830  	// Letting VaaS some time to load certificate into inventory.
   831  	// VaaS may be able to retrieve cert from API immediately, but storing in inventory may take a few seconds
   832  	// or even stuck into it
   833  	time.Sleep(time.Duration(2) * time.Second)
   834  	err = conn.RetireCertificate(retireReq)
   835  	if err != nil {
   836  		t.Fatalf("%s", err)
   837  	}
   838  }
   839  
   840  func TestRetireCertificateWithPickUpID(t *testing.T) {
   841  	conn := getTestConnector(ctx.CloudZone)
   842  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   843  	if err != nil {
   844  		t.Fatalf("%s", err)
   845  	}
   846  	zoneConfig, err := conn.ReadZoneConfiguration()
   847  	if err != nil {
   848  		t.Fatalf("%s", err)
   849  	}
   850  	req := &certificate.Request{}
   851  	req.Subject.CommonName = test.RandCN()
   852  	req.Subject.Organization = []string{"Venafi, Inc."}
   853  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   854  	err = conn.GenerateRequest(zoneConfig, req)
   855  	if err != nil {
   856  		t.Fatalf("%s", err)
   857  	}
   858  	pickupID, err := conn.RequestCertificate(req)
   859  	if err != nil {
   860  		t.Fatalf("%s", err)
   861  	}
   862  
   863  	retireReq := &certificate.RetireRequest{}
   864  	retireReq.CertificateDN = pickupID
   865  
   866  	// Letting VaaS some time to load certificate into inventory.
   867  	// VaaS may be able to retrieve cert from API immediately, but storing in inventory may take a few seconds
   868  	// or even stuck into it
   869  	time.Sleep(time.Duration(2) * time.Second)
   870  	err = conn.RetireCertificate(retireReq)
   871  	if err != nil {
   872  		t.Fatalf("%s", err)
   873  	}
   874  }
   875  
   876  func TestRetireCertificateTwice(t *testing.T) {
   877  	conn := getTestConnector(ctx.CloudZone)
   878  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   879  	if err != nil {
   880  		t.Fatalf("%s", err)
   881  	}
   882  	zoneConfig, err := conn.ReadZoneConfiguration()
   883  	if err != nil {
   884  		t.Fatalf("%s", err)
   885  	}
   886  	req := &certificate.Request{}
   887  	req.Subject.CommonName = test.RandCN()
   888  	req.Subject.Organization = []string{"Venafi, Inc."}
   889  	req.Subject.OrganizationalUnit = []string{"Automated Tests"}
   890  	err = conn.GenerateRequest(zoneConfig, req)
   891  	if err != nil {
   892  		t.Fatalf("%s", err)
   893  	}
   894  	pickupID, err := conn.RequestCertificate(req)
   895  	if err != nil {
   896  		t.Fatalf("%s", err)
   897  	}
   898  
   899  	retireReq := &certificate.RetireRequest{}
   900  	retireReq.CertificateDN = pickupID
   901  
   902  	// Letting VaaS some time to load certificate into inventory.
   903  	// VaaS may be able to retrieve cert from API immediately, but storing in inventory may take a few seconds
   904  	// or even stuck into it
   905  	time.Sleep(time.Duration(2) * time.Second)
   906  	err = conn.RetireCertificate(retireReq)
   907  	if err != nil {
   908  		t.Fatalf("%s", err)
   909  	}
   910  	t.Log("Trying to retire the certificate a second time")
   911  	retireReqSecond := &certificate.RetireRequest{}
   912  	retireReqSecond.CertificateDN = pickupID
   913  
   914  	err = conn.RetireCertificate(retireReqSecond)
   915  	if err != nil {
   916  		t.Fatalf("%s", err)
   917  	}
   918  }
   919  
   920  func TestReadPolicyConfigurationOnlyEC(t *testing.T) {
   921  	// IMPORTANT NOTE: Now in VCert, we are treating ED25519 Keys, as per it's a different algorithm from ECDSA, as another
   922  	// type of key. This is conflicting with how VaaS handles EC Keys, as it considers ED25519 as another curve, which is
   923  	// it shouldn't, this test may need to change in the future once this is solved
   924  	//todo: add more zones
   925  	conn := getTestConnector(ctx.VAASzoneEC)
   926  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   927  	if err != nil {
   928  		t.Fatalf("%s", err)
   929  	}
   930  	// This calls at the end of everything: policy.toPolicy() which is the function we wanted to test the KeyCurves
   931  	policy, err := conn.ReadPolicyConfiguration()
   932  	if err != nil {
   933  		t.Fatalf("%s", err)
   934  	}
   935  	expectedPolice := endpoint.Policy{
   936  		SubjectCNRegexes:         []string{"^.*\\.vfidev\\.com$"},
   937  		SubjectORegexes:          []string{"^Venafi Inc.$"},
   938  		SubjectOURegexes:         []string{"^Integrations$", "^Integration$"},
   939  		SubjectSTRegexes:         []string{"^Utah$"},
   940  		SubjectLRegexes:          []string{"^Salt Lake$"},
   941  		SubjectCRegexes:          []string{"^US$"},
   942  		AllowedKeyConfigurations: []endpoint.AllowedKeyConfiguration{{certificate.KeyTypeECDSA, nil, []certificate.EllipticCurve{certificate.EllipticCurveP256, certificate.EllipticCurveP384, certificate.EllipticCurveP521, certificate.EllipticCurveED25519}}},
   943  		DnsSanRegExs:             []string{"^.*\\.vfidev\\.com$"},
   944  		AllowWildcards:           true,
   945  		AllowKeyReuse:            false,
   946  	}
   947  
   948  	if !reflect.DeepEqual(*policy, expectedPolice) {
   949  		t.Fatalf("policy for zone %s is not as expected \nget:    %+v \nexpect: %+v", ctx.CloudZone, *policy, expectedPolice)
   950  	}
   951  }
   952  
   953  func newSelfSignedCert() (string, error) {
   954  	rootKey, err := rsa.GenerateKey(rand.Reader, 2048)
   955  	if err != nil {
   956  		return "", err
   957  	}
   958  	serialNumber, _ := rand.Int(rand.Reader, big.NewInt(53298479))
   959  	template := x509.Certificate{
   960  		SerialNumber: serialNumber,
   961  		Subject: pkix.Name{
   962  			CommonName: test.RandCN(),
   963  		},
   964  		NotBefore:             time.Now().Add(-time.Minute),
   965  		NotAfter:              time.Now().Add(time.Hour * 24 * 365),
   966  		KeyUsage:              x509.KeyUsageCertSign,
   967  		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
   968  		BasicConstraintsValid: true,
   969  		IsCA:                  true,
   970  	}
   971  	derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &rootKey.PublicKey, rootKey)
   972  	if err != nil {
   973  		return "", fmt.Errorf("can't generate fake cert")
   974  	}
   975  	b := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
   976  	return string(b), nil
   977  }
   978  
   979  func TestImportCertificate(t *testing.T) {
   980  
   981  	conn := getTestConnector(ctx.CloudZone)
   982  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
   983  	if err != nil {
   984  		t.Fatalf("%s", err)
   985  	}
   986  	crt, err := newSelfSignedCert()
   987  	if err != nil {
   988  		t.Fatalf("%s", err)
   989  	}
   990  	importReq := &certificate.ImportRequest{
   991  		PolicyDN:        "",
   992  		ObjectName:      fmt.Sprintf("import%v.venafi.example.com", time.Now().Unix()),
   993  		CertificateData: crt,
   994  		PrivateKeyData:  "",
   995  		Reconcile:       false,
   996  	}
   997  
   998  	importResp, err := conn.ImportCertificate(importReq)
   999  	if err != nil {
  1000  		t.Fatalf("failed to import certificate: %s", err)
  1001  	}
  1002  	fmt.Printf("%+v\n", importResp)
  1003  }
  1004  
  1005  func TestSetBaseURL(t *testing.T) {
  1006  	var err error
  1007  	condor := Connector{}
  1008  	url := "http://api2.projectc.venafi.com/v1"
  1009  	condor.baseURL, err = normalizeURL(url)
  1010  	if err != nil {
  1011  		t.Fatalf("err is not nil, err: %s url: %s", err, url)
  1012  	}
  1013  	if !strings.EqualFold(condor.baseURL, expectedURL) {
  1014  		t.Fatalf("Base URL did not match expected value. Expected: %s Actual: %s", expectedURL, condor.baseURL)
  1015  	}
  1016  
  1017  	url = "http://api2.projectc.venafi.com/v1"
  1018  	condor.baseURL = ""
  1019  	condor.baseURL, err = normalizeURL(url)
  1020  	if err != nil {
  1021  		t.Fatalf("err is not nil, err: %s url: %s", err, url)
  1022  	}
  1023  	if !strings.EqualFold(condor.baseURL, expectedURL) {
  1024  		t.Fatalf("Base URL did not match expected value. Expected: %s Actual: %s", expectedURL, condor.baseURL)
  1025  	}
  1026  
  1027  	url = "http://api2.projectc.venafi.com/v1/"
  1028  	condor.baseURL = ""
  1029  	condor.baseURL, err = normalizeURL(url)
  1030  	if err != nil {
  1031  		t.Fatalf("err is not nil, err: %s url: %s", err, url)
  1032  	}
  1033  	if !strings.EqualFold(condor.baseURL, expectedURL) {
  1034  		t.Fatalf("Base URL did not match expected value. Expected: %s Actual: %s", expectedURL, condor.baseURL)
  1035  	}
  1036  
  1037  	url = "api2.projectc.venafi.com/v1/"
  1038  	condor.baseURL = ""
  1039  	condor.baseURL, err = normalizeURL(url)
  1040  	if err != nil {
  1041  		t.Fatalf("err is not nil, err: %s url: %s", err, url)
  1042  	}
  1043  	if !strings.EqualFold(condor.baseURL, expectedURL) {
  1044  		t.Fatalf("Base URL did not match expected value. Expected: %s Actual: %s", expectedURL, condor.baseURL)
  1045  	}
  1046  }
  1047  
  1048  func TestGetURL(t *testing.T) {
  1049  	var err error
  1050  	condor := Connector{}
  1051  	url := "http://api2.projectc.venafi.com/v1/"
  1052  	condor.baseURL = ""
  1053  	condor.baseURL, err = normalizeURL(url)
  1054  	if err != nil {
  1055  		t.Fatalf("err is not nil, err: %s url: %s", err, url)
  1056  	}
  1057  	if !strings.EqualFold(condor.baseURL, expectedURL) {
  1058  		t.Fatalf("Base URL did not match expected value. Expected: %s Actual: %s", expectedURL, condor.baseURL)
  1059  	}
  1060  
  1061  	url = condor.getURL(urlResourceUserAccounts)
  1062  	if !strings.EqualFold(url, fmt.Sprintf("%s%s", expectedURL, urlResourceUserAccounts)) {
  1063  		t.Fatalf("Get URL did not match expected value. Expected: %s Actual: %s", fmt.Sprintf("%s%s", expectedURL, urlResourceUserAccounts), url)
  1064  	}
  1065  
  1066  	url = condor.getURL(urlResourceCertificateRequests)
  1067  	if !strings.EqualFold(url, fmt.Sprintf("%s%s", expectedURL, urlResourceCertificateRequests)) {
  1068  		t.Fatalf("Get URL did not match expected value. Expected: %s Actual: %s", fmt.Sprintf("%s%s", expectedURL, urlResourceCertificateRequests), url)
  1069  	}
  1070  
  1071  	url = condor.getURL(urlResourceCertificateRetrievePem)
  1072  	if !strings.EqualFold(url, fmt.Sprintf("%s%s", expectedURL, urlResourceCertificateRetrievePem)) {
  1073  		t.Fatalf("Get URL did not match expected value. Expected: %s Actual: %s", fmt.Sprintf("%s%s", expectedURL, urlResourceCertificateRetrievePem), url)
  1074  	}
  1075  	condor.baseURL = ""
  1076  	url = condor.getURL(urlResourceUserAccounts)
  1077  	if url == "" {
  1078  		t.Fatalf("Get URL did not return an error when the base url had not been set.")
  1079  	}
  1080  }
  1081  
  1082  func TestRetrieveCertificatesList(t *testing.T) {
  1083  	conn := getTestConnector(ctx.CloudZone)
  1084  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1085  	if err != nil {
  1086  		t.Fatalf("%s", err)
  1087  	}
  1088  	for _, count := range []int{10, 100, 101, 153} {
  1089  		timeStarted := time.Now()
  1090  		l, err := conn.ListCertificates(endpoint.Filter{Limit: &count})
  1091  		if err != nil {
  1092  			t.Fatal(err)
  1093  		}
  1094  		set := make(map[string]struct{})
  1095  		for _, c := range l {
  1096  			set[c.Thumbprint] = struct{}{}
  1097  			if c.ValidTo.Before(timeStarted) {
  1098  				t.Errorf("cert %s is expired: %v", c.Thumbprint, c.ValidTo)
  1099  			}
  1100  		}
  1101  		if len(set) != count {
  1102  			t.Errorf("mismatched certificates number: wait %d, got %d (%d)", count, len(set), len(l))
  1103  		}
  1104  	}
  1105  }
  1106  
  1107  func TestSearchCertificate(t *testing.T) {
  1108  	conn := getTestConnector(ctx.CloudZone)
  1109  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1110  	if err != nil {
  1111  		t.Fatal(err)
  1112  	}
  1113  	zoneConfig, err := conn.ReadZoneConfiguration()
  1114  	if err != nil {
  1115  		t.Fatal(err)
  1116  	}
  1117  
  1118  	req := certificate.Request{}
  1119  	req.Subject.CommonName = test.RandCN()
  1120  	req.Timeout = time.Second * 10
  1121  	err = conn.GenerateRequest(zoneConfig, &req)
  1122  	if err != nil {
  1123  		t.Fatal(err)
  1124  	}
  1125  	req.PickupID, err = conn.RequestCertificate(&req)
  1126  	if err != nil {
  1127  		t.Fatal(err)
  1128  	}
  1129  	cert, err := conn.RetrieveCertificate(&req)
  1130  	if err != nil {
  1131  		t.Fatal(err)
  1132  	}
  1133  	p, _ := pem.Decode([]byte(cert.Certificate))
  1134  	thumbprint := certThumbprint(p.Bytes)
  1135  	_, err = conn.searchCertificatesByFingerprint(thumbprint)
  1136  	if err != nil {
  1137  		t.Fatal(err)
  1138  	}
  1139  }
  1140  
  1141  func TestSetPolicy(t *testing.T) {
  1142  	appName := test.RandAppName()
  1143  
  1144  	policyName := appName + "\\" + test.RandCitName()
  1145  	conn := getTestConnector(ctx.CloudZone)
  1146  	conn.verbose = true
  1147  
  1148  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1149  
  1150  	if err != nil {
  1151  		t.Fatalf("%s", err)
  1152  	}
  1153  
  1154  	localPolicy := test.GetCloudPolicySpecification()
  1155  
  1156  	_, err = conn.SetPolicy(policyName, localPolicy)
  1157  
  1158  	if err != nil {
  1159  		t.Fatalf("%s", err)
  1160  	}
  1161  
  1162  	//now update policy.
  1163  	t.Log("updating policy, modifying ps.Policy.Subject.OrgUnits = []string{\"DevOps\", \"QA\"}.")
  1164  	localPolicy.Policy.Subject.OrgUnits = []string{"DevOps", "QA"}
  1165  	//policyName = appName + "\\" + test.RandCitName()
  1166  	_, err = conn.SetPolicy(policyName, localPolicy)
  1167  
  1168  	if err != nil {
  1169  		t.Fatalf("%s", err)
  1170  	}
  1171  
  1172  	ps, err := conn.GetPolicy(policyName)
  1173  
  1174  	if err != nil {
  1175  		t.Fatalf("%s", err)
  1176  	}
  1177  
  1178  	//validate each attribute
  1179  	userDetails, err := conn.getUserDetails()
  1180  	//validating the default users attribute was created
  1181  	users := []string{
  1182  		//"jenkins@opensource.qa.venafi.io",
  1183  		userDetails.User.Username,
  1184  	}
  1185  	valid := test.IsArrayStringEqual(users, ps.Users)
  1186  	if !valid {
  1187  		t.Fatalf("It was expected that the current user %s be set as user of the PolicySpecification created but got %+q", users[0], ps.Users)
  1188  	}
  1189  
  1190  	//Validating the addition of a user
  1191  	users = append(users, "resource-owner@opensource.qa.venafi.io")
  1192  	ps.Users = users
  1193  
  1194  	_, err = conn.SetPolicy(policyName, ps)
  1195  
  1196  	if err != nil {
  1197  		t.Fatalf("%s", err)
  1198  	}
  1199  
  1200  	ps, err = conn.GetPolicy(policyName)
  1201  
  1202  	if err != nil {
  1203  		t.Fatalf("%s", err)
  1204  	}
  1205  
  1206  	valid = test.IsArrayStringEqual(users, ps.Users)
  1207  	if !valid {
  1208  		t.Fatalf("The users are different, expected %+q but got %+q", users, ps.Users)
  1209  	}
  1210  
  1211  	//validate subject attributes
  1212  
  1213  	if ps == nil {
  1214  		t.Fatalf("specified Policy wasn't found")
  1215  	}
  1216  
  1217  	if ps.Policy.Domains != nil && localPolicy.Policy.Domains != nil {
  1218  		valid := test.IsArrayStringEqual(localPolicy.Policy.Domains, ps.Policy.Domains)
  1219  		if !valid {
  1220  			t.Fatalf("specified domains are different, expected %+q but got %+q", localPolicy.Policy.Domains, ps.Policy.Domains)
  1221  		}
  1222  	}
  1223  
  1224  	if *(ps.Policy.MaxValidDays) != *(localPolicy.Policy.MaxValidDays) {
  1225  		t.Fatalf("specified validity period is different")
  1226  	}
  1227  
  1228  	//validate cert authority
  1229  	if ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == "" {
  1230  		t.Fatalf("venafi policy doesn't have a certificate authority")
  1231  	}
  1232  	if *(ps.Policy.CertificateAuthority) != *(localPolicy.Policy.CertificateAuthority) {
  1233  		t.Fatalf("certificate authority value doesn't match, get: %s but expected: %s", *(ps.Policy.CertificateAuthority), *(localPolicy.Policy.CertificateAuthority))
  1234  	}
  1235  
  1236  	if len(localPolicy.Policy.Subject.Orgs) > 0 {
  1237  
  1238  		valid := test.IsArrayStringEqual(localPolicy.Policy.Subject.Orgs, ps.Policy.Subject.Orgs)
  1239  		if !valid {
  1240  			t.Fatalf("specified policy orgs are different, expected %+q but got %+q", localPolicy.Policy.Subject.Orgs, ps.Policy.Subject.Orgs)
  1241  		}
  1242  
  1243  	}
  1244  
  1245  	if len(localPolicy.Policy.Subject.OrgUnits) > 0 {
  1246  
  1247  		valid := test.IsArrayStringEqual(localPolicy.Policy.Subject.OrgUnits, ps.Policy.Subject.OrgUnits)
  1248  		if !valid {
  1249  			t.Fatalf("specified policy orgs units are different, expected %+q but got %+q", localPolicy.Policy.Subject.OrgUnits, ps.Policy.Subject.OrgUnits)
  1250  		}
  1251  
  1252  	}
  1253  
  1254  	if len(localPolicy.Policy.Subject.Localities) > 0 {
  1255  
  1256  		valid := test.IsArrayStringEqual(localPolicy.Policy.Subject.Localities, ps.Policy.Subject.Localities)
  1257  		if !valid {
  1258  			t.Fatalf("specified policy localities are different, expected %+q but got %+q", localPolicy.Policy.Subject.Localities, ps.Policy.Subject.Localities)
  1259  		}
  1260  
  1261  	}
  1262  
  1263  	if len(localPolicy.Policy.Subject.States) > 0 {
  1264  
  1265  		valid := test.IsArrayStringEqual(localPolicy.Policy.Subject.States, ps.Policy.Subject.States)
  1266  		if !valid {
  1267  			t.Fatalf("specified policy states are different, expected %+q, but got %+q", localPolicy.Policy.Subject.States, ps.Policy.Subject.States)
  1268  		}
  1269  
  1270  	}
  1271  
  1272  	if len(localPolicy.Policy.Subject.Countries) > 0 {
  1273  
  1274  		valid := test.IsArrayStringEqual(localPolicy.Policy.Subject.Countries, ps.Policy.Subject.Countries)
  1275  		if !valid {
  1276  			t.Fatalf("specified policy countries are different, expected %+q but got %+q", localPolicy.Policy.Subject.Countries, ps.Policy.Subject.Countries)
  1277  		}
  1278  
  1279  	}
  1280  
  1281  	//validate key pair values.
  1282  
  1283  	if len(localPolicy.Policy.KeyPair.KeyTypes) > 0 {
  1284  
  1285  		valid := test.IsArrayStringEqual(localPolicy.Policy.KeyPair.KeyTypes, ps.Policy.KeyPair.KeyTypes)
  1286  		if !valid {
  1287  			t.Fatalf("specified policy key types are different, expected %+q but got %+q", localPolicy.Policy.KeyPair.KeyTypes, ps.Policy.KeyPair.KeyTypes)
  1288  		}
  1289  
  1290  	}
  1291  
  1292  	if len(localPolicy.Policy.KeyPair.RsaKeySizes) > 0 {
  1293  
  1294  		valid := test.IsArrayIntEqual(localPolicy.Policy.KeyPair.RsaKeySizes, ps.Policy.KeyPair.RsaKeySizes)
  1295  		if !valid {
  1296  			t.Fatalf("specified policy rsa key sizes are different, expected %+q but got %+q", localPolicy.Policy.KeyPair.RsaKeySizes, ps.Policy.KeyPair.RsaKeySizes)
  1297  		}
  1298  
  1299  	}
  1300  
  1301  	if localPolicy.Policy.KeyPair.ReuseAllowed != nil {
  1302  
  1303  		if ps.Policy.KeyPair.ReuseAllowed == nil {
  1304  			t.Fatalf("specified policy rsa key sizes are not specified")
  1305  		}
  1306  
  1307  		if *(ps.Policy.KeyPair.ReuseAllowed) != *(localPolicy.Policy.KeyPair.ReuseAllowed) {
  1308  			t.Fatalf("specified policy rsa key sizes are different")
  1309  		}
  1310  
  1311  	}
  1312  
  1313  	//validate default values.
  1314  	if localPolicy.Default.Subject.Org != nil {
  1315  		if ps.Default.Subject.Org == nil {
  1316  			t.Fatalf("specified policy default org is not specified")
  1317  		}
  1318  		if *(ps.Default.Subject.Org) != *(localPolicy.Default.Subject.Org) {
  1319  			t.Fatalf("specified policy default org is different")
  1320  		}
  1321  	}
  1322  
  1323  	if len(localPolicy.Default.Subject.OrgUnits) > 0 {
  1324  
  1325  		valid := test.IsArrayStringEqual(localPolicy.Default.Subject.OrgUnits, ps.Default.Subject.OrgUnits)
  1326  
  1327  		if !valid {
  1328  			t.Fatalf("specified policy default org unit are different, expected %+q but got %+q", localPolicy.Default.Subject.OrgUnits, ps.Default.Subject.OrgUnits)
  1329  		}
  1330  
  1331  	}
  1332  
  1333  	if localPolicy.Default.Subject.Locality != nil {
  1334  		if ps.Default.Subject.Locality == nil {
  1335  			t.Fatalf("specified policy default locality is not specified")
  1336  		}
  1337  		if *(ps.Default.Subject.Locality) != *(localPolicy.Default.Subject.Locality) {
  1338  			t.Fatalf("specified policy default locality is different")
  1339  		}
  1340  	}
  1341  
  1342  	if localPolicy.Default.Subject.State != nil {
  1343  		if ps.Default.Subject.State == nil {
  1344  			t.Fatalf("specified policy default state is not specified")
  1345  		}
  1346  		if *(ps.Default.Subject.State) != *(localPolicy.Default.Subject.State) {
  1347  			t.Fatalf("specified policy default state is different")
  1348  		}
  1349  	}
  1350  
  1351  	if localPolicy.Default.Subject.Country != nil {
  1352  		if ps.Default.Subject.Country == nil {
  1353  			t.Fatalf("policy default country is not specified")
  1354  		}
  1355  		if *(ps.Default.Subject.Country) != *(localPolicy.Default.Subject.Country) {
  1356  			t.Fatalf("specified policy default country is different")
  1357  		}
  1358  	}
  1359  
  1360  	if localPolicy.Default.KeyPair.KeyType != nil {
  1361  		if ps.Default.KeyPair.KeyType == nil {
  1362  			t.Fatalf("policy default key type is not specified ")
  1363  		}
  1364  		if *(ps.Default.KeyPair.KeyType) != *(localPolicy.Default.KeyPair.KeyType) {
  1365  			t.Fatalf("specified policy default key type is different")
  1366  		}
  1367  	}
  1368  
  1369  	if localPolicy.Default.KeyPair.RsaKeySize != nil {
  1370  		if ps.Default.KeyPair.RsaKeySize == nil {
  1371  			t.Fatalf("policy default rsa key size is not specified")
  1372  		}
  1373  		if *(ps.Default.KeyPair.RsaKeySize) != *(localPolicy.Default.KeyPair.RsaKeySize) {
  1374  			t.Fatalf("specified policy default rsa key size is different")
  1375  		}
  1376  	}
  1377  
  1378  	//validate SAN values.
  1379  	if *(localPolicy.Policy.SubjectAltNames.UriAllowed) != *(ps.Policy.SubjectAltNames.UriAllowed) {
  1380  		t.Fatalf("uriAllowed value is different, expected: %v but got %v",
  1381  			*(localPolicy.Policy.SubjectAltNames.UriAllowed),
  1382  			*(ps.Policy.SubjectAltNames.UriAllowed))
  1383  	}
  1384  
  1385  	if *(localPolicy.Policy.SubjectAltNames.EmailAllowed) != *(ps.Policy.SubjectAltNames.EmailAllowed) {
  1386  		t.Fatalf("uriAllowed value is different, expected: %v but got %v",
  1387  			*(localPolicy.Policy.SubjectAltNames.EmailAllowed),
  1388  			*(ps.Policy.SubjectAltNames.EmailAllowed))
  1389  	}
  1390  
  1391  	if *(localPolicy.Policy.SubjectAltNames.IpAllowed) != *(ps.Policy.SubjectAltNames.IpAllowed) {
  1392  		t.Fatalf("uriAllowed value is different, expected: %v but got %v",
  1393  			*(localPolicy.Policy.SubjectAltNames.IpAllowed),
  1394  			*(ps.Policy.SubjectAltNames.IpAllowed))
  1395  	}
  1396  
  1397  	if len(localPolicy.Policy.SubjectAltNames.UriProtocols) > 0 {
  1398  		if len(ps.Policy.SubjectAltNames.UriProtocols) == 0 {
  1399  			t.Fatal("got 0 elements on uriProtocols ")
  1400  		}
  1401  		valid := test.IsArrayStringEqual(localPolicy.Policy.SubjectAltNames.UriProtocols, ps.Policy.SubjectAltNames.UriProtocols)
  1402  		if !valid {
  1403  			t.Fatalf("uri protocols are different, expected %+q but get %+q", localPolicy.Policy.SubjectAltNames.UriProtocols, ps.Policy.SubjectAltNames.UriProtocols)
  1404  		}
  1405  	}
  1406  
  1407  	if len(localPolicy.Policy.SubjectAltNames.IpConstraints) > 0 {
  1408  		if len(ps.Policy.SubjectAltNames.IpConstraints) == 0 {
  1409  			t.Fatal("got 0 elements on ipConstrains ")
  1410  		}
  1411  		valid := test.IsArrayStringEqual(localPolicy.Policy.SubjectAltNames.IpConstraints, ps.Policy.SubjectAltNames.IpConstraints)
  1412  		if !valid {
  1413  			t.Fatalf("ip constrains are different, expected %+q but get %+q", localPolicy.Policy.SubjectAltNames.IpConstraints, ps.Policy.SubjectAltNames.IpConstraints)
  1414  		}
  1415  	}
  1416  
  1417  }
  1418  
  1419  func TestGetPolicy(t *testing.T) {
  1420  
  1421  	t.Skip() //this is just for development purpose
  1422  
  1423  	policyName := os.Getenv("CLOUD_POLICY_MANAGEMENT_SAMPLE")
  1424  	conn := getTestConnector(ctx.CloudZone)
  1425  	conn.verbose = true
  1426  
  1427  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1428  
  1429  	if err != nil {
  1430  		t.Fatalf("%s", err)
  1431  	}
  1432  
  1433  	specifiedPS := test.GetCloudPolicySpecification()
  1434  
  1435  	ps, err := conn.GetPolicy(policyName)
  1436  
  1437  	if err != nil {
  1438  		t.Fatalf("%s", err)
  1439  	}
  1440  
  1441  	//validate each attribute
  1442  	//validate subject attributes
  1443  
  1444  	if ps == nil {
  1445  		t.Fatalf("specified Policy wasn't found")
  1446  	}
  1447  
  1448  	if ps.Policy.Domains != nil && specifiedPS.Policy.Domains != nil {
  1449  		domains := policy.ConvertToRegex(specifiedPS.Policy.Domains, policy.IsWildcardAllowed(*(specifiedPS)))
  1450  		valid := test.IsArrayStringEqual(domains, ps.Policy.Domains)
  1451  		if !valid {
  1452  			t.Fatalf("specified domains are different")
  1453  		}
  1454  	}
  1455  
  1456  	if *(ps.Policy.MaxValidDays) != *(specifiedPS.Policy.MaxValidDays) {
  1457  		t.Fatalf("specified validity period is different")
  1458  	}
  1459  
  1460  	//validate cert authority
  1461  	if ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == "" {
  1462  		t.Fatalf("venafi policy doesn't have a certificate authority")
  1463  	}
  1464  	if *(ps.Policy.CertificateAuthority) != *(specifiedPS.Policy.CertificateAuthority) {
  1465  		t.Fatalf("certificate authority value doesn't match, get: %s but expected: %s", *(ps.Policy.CertificateAuthority), *(specifiedPS.Policy.CertificateAuthority))
  1466  	}
  1467  
  1468  	if specifiedPS.Policy.Subject.Orgs != nil {
  1469  
  1470  		if ps.Policy.Subject.Orgs == nil {
  1471  			t.Fatalf("specified policy orgs are not specified")
  1472  		}
  1473  
  1474  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Orgs, ps.Policy.Subject.Orgs)
  1475  		if !valid {
  1476  			t.Fatalf("specified policy orgs are different")
  1477  		}
  1478  
  1479  	}
  1480  
  1481  	if specifiedPS.Policy.Subject.OrgUnits != nil {
  1482  
  1483  		if ps.Policy.Subject.OrgUnits == nil {
  1484  			t.Fatalf("specified policy orgs units are not specified")
  1485  		}
  1486  
  1487  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.OrgUnits, ps.Policy.Subject.OrgUnits)
  1488  		if !valid {
  1489  			t.Fatalf("specified policy orgs units are different")
  1490  		}
  1491  
  1492  	}
  1493  
  1494  	if specifiedPS.Policy.Subject.Localities != nil {
  1495  
  1496  		if ps.Policy.Subject.Localities == nil {
  1497  			t.Fatalf("specified policy localities are not specified")
  1498  		}
  1499  
  1500  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Localities, ps.Policy.Subject.Localities)
  1501  		if !valid {
  1502  			t.Fatalf("specified policy localities are different")
  1503  		}
  1504  
  1505  	}
  1506  
  1507  	if specifiedPS.Policy.Subject.States != nil {
  1508  
  1509  		if ps.Policy.Subject.States == nil {
  1510  			t.Fatalf("specified policy states are not specified")
  1511  		}
  1512  
  1513  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.States, ps.Policy.Subject.States)
  1514  		if !valid {
  1515  			t.Fatalf("specified policy states are different")
  1516  		}
  1517  
  1518  	}
  1519  
  1520  	if specifiedPS.Policy.Subject.Countries != nil {
  1521  
  1522  		if ps.Policy.Subject.Countries == nil {
  1523  			t.Fatalf("specified policy countries are not specified")
  1524  		}
  1525  
  1526  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Countries, ps.Policy.Subject.Countries)
  1527  		if !valid {
  1528  			t.Fatalf("specified policy countries are different")
  1529  		}
  1530  
  1531  	}
  1532  
  1533  	//validate key pair values.
  1534  
  1535  	if specifiedPS.Policy.KeyPair.KeyTypes != nil {
  1536  
  1537  		if ps.Policy.KeyPair.KeyTypes == nil {
  1538  			t.Fatalf("specified policy key types are not specified")
  1539  		}
  1540  
  1541  		valid := test.IsArrayStringEqual(specifiedPS.Policy.KeyPair.KeyTypes, ps.Policy.KeyPair.KeyTypes)
  1542  		if !valid {
  1543  			t.Fatalf("specified policy key types are different")
  1544  		}
  1545  
  1546  	}
  1547  
  1548  	if specifiedPS.Policy.KeyPair.RsaKeySizes != nil {
  1549  
  1550  		if ps.Policy.KeyPair.RsaKeySizes == nil {
  1551  			t.Fatalf("specified policy rsa key sizes are not specified")
  1552  		}
  1553  
  1554  		valid := test.IsArrayIntEqual(specifiedPS.Policy.KeyPair.RsaKeySizes, ps.Policy.KeyPair.RsaKeySizes)
  1555  		if !valid {
  1556  			t.Fatalf("specified policy rsa key sizes are different")
  1557  		}
  1558  
  1559  	}
  1560  
  1561  	if specifiedPS.Policy.KeyPair.ReuseAllowed != nil {
  1562  
  1563  		if ps.Policy.KeyPair.ReuseAllowed == nil {
  1564  			t.Fatalf("specified policy rsa key sizes are not specified")
  1565  		}
  1566  
  1567  		if *(ps.Policy.KeyPair.ReuseAllowed) != *(specifiedPS.Policy.KeyPair.ReuseAllowed) {
  1568  			t.Fatalf("specified policy rsa key sizes are different")
  1569  		}
  1570  
  1571  	}
  1572  
  1573  	//validate default values.
  1574  	if specifiedPS.Default.Subject.Org != nil {
  1575  		if ps.Default.Subject.Org == nil {
  1576  			t.Fatalf("specified policy default org is not specified")
  1577  		}
  1578  		if *(ps.Default.Subject.Org) != *(specifiedPS.Default.Subject.Org) {
  1579  			t.Fatalf("specified policy default org is different")
  1580  		}
  1581  	}
  1582  
  1583  	if specifiedPS.Default.Subject.OrgUnits != nil {
  1584  
  1585  		if ps.Default.Subject.OrgUnits == nil {
  1586  			t.Fatalf("specified policy default org is not specified")
  1587  		}
  1588  
  1589  		valid := test.IsArrayStringEqual(specifiedPS.Default.Subject.OrgUnits, ps.Default.Subject.OrgUnits)
  1590  
  1591  		if !valid {
  1592  			t.Fatalf("specified policy default org unit are different")
  1593  		}
  1594  
  1595  	}
  1596  
  1597  	if specifiedPS.Default.Subject.Locality != nil {
  1598  		if ps.Default.Subject.Locality == nil {
  1599  			t.Fatalf("specified policy default locality is not specified")
  1600  		}
  1601  		if *(ps.Default.Subject.Locality) != *(specifiedPS.Default.Subject.Locality) {
  1602  			t.Fatalf("specified policy default locality is different")
  1603  		}
  1604  	}
  1605  
  1606  	if specifiedPS.Default.Subject.State != nil {
  1607  		if ps.Default.Subject.State == nil {
  1608  			t.Fatalf("specified policy default state is not specified")
  1609  		}
  1610  		if *(ps.Default.Subject.State) != *(specifiedPS.Default.Subject.State) {
  1611  			t.Fatalf("specified policy default state is different")
  1612  		}
  1613  	}
  1614  
  1615  	if specifiedPS.Default.Subject.Country != nil {
  1616  		if ps.Default.Subject.Country == nil {
  1617  			t.Fatalf("policy default country is not specified")
  1618  		}
  1619  		if *(ps.Default.Subject.Country) != *(specifiedPS.Default.Subject.Country) {
  1620  			t.Fatalf("specified policy default country is different")
  1621  		}
  1622  	}
  1623  
  1624  	if specifiedPS.Default.KeyPair.KeyType != nil {
  1625  		if ps.Default.KeyPair.KeyType == nil {
  1626  			t.Fatalf("policy default key type is not specified ")
  1627  		}
  1628  		if *(ps.Default.KeyPair.KeyType) != *(specifiedPS.Default.KeyPair.KeyType) {
  1629  			t.Fatalf("specified policy default key type is different")
  1630  		}
  1631  	}
  1632  
  1633  	if specifiedPS.Default.KeyPair.RsaKeySize != nil {
  1634  		if ps.Default.KeyPair.RsaKeySize == nil {
  1635  			t.Fatalf("policy default rsa key size is not specified")
  1636  		}
  1637  		if *(ps.Default.KeyPair.RsaKeySize) != *(specifiedPS.Default.KeyPair.RsaKeySize) {
  1638  			t.Fatalf("specified policy default rsa key size is different")
  1639  		}
  1640  	}
  1641  
  1642  }
  1643  
  1644  func TestGetPolicyOnlyEC(t *testing.T) {
  1645  
  1646  	// This test covers GetPolicy function from connector to test EC curves are return correctly for all the values,
  1647  	// including RecommendSettings
  1648  
  1649  	policyName := os.Getenv("VAAS_ZONE_EC")
  1650  	conn := getTestConnector(ctx.VAASzoneEC)
  1651  	conn.verbose = true
  1652  
  1653  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1654  
  1655  	if err != nil {
  1656  		t.Fatalf("%s", err)
  1657  	}
  1658  
  1659  	specifiedPS := test.GetVAASpolicySpecificationEC()
  1660  
  1661  	ps, err := conn.GetPolicy(policyName)
  1662  
  1663  	if err != nil {
  1664  		t.Fatalf("%s", err)
  1665  	}
  1666  
  1667  	//validate each attribute
  1668  	//validate subject attributes
  1669  
  1670  	if ps == nil {
  1671  		t.Fatalf("specified Policy wasn't found")
  1672  	}
  1673  
  1674  	if ps.Policy.Domains != nil && specifiedPS.Policy.Domains != nil {
  1675  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Domains, ps.Policy.Domains)
  1676  		if !valid {
  1677  			t.Fatalf("specified domains are different")
  1678  		}
  1679  	}
  1680  
  1681  	if *(ps.Policy.MaxValidDays) != *(specifiedPS.Policy.MaxValidDays) {
  1682  		t.Fatalf("specified validity period is different")
  1683  	}
  1684  
  1685  	//validate cert authority
  1686  	if ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == "" {
  1687  		t.Fatalf("venafi policy doesn't have a certificate authority")
  1688  	}
  1689  	if *(ps.Policy.CertificateAuthority) != *(specifiedPS.Policy.CertificateAuthority) {
  1690  		t.Fatalf("certificate authority value doesn't match, get: %s but expected: %s", *(ps.Policy.CertificateAuthority), *(specifiedPS.Policy.CertificateAuthority))
  1691  	}
  1692  
  1693  	if specifiedPS.Policy.Subject.Orgs != nil {
  1694  
  1695  		if ps.Policy.Subject.Orgs == nil {
  1696  			t.Fatalf("specified policy orgs are not specified")
  1697  		}
  1698  
  1699  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Orgs, ps.Policy.Subject.Orgs)
  1700  		if !valid {
  1701  			t.Fatalf("specified policy orgs are different")
  1702  		}
  1703  
  1704  	}
  1705  
  1706  	if specifiedPS.Policy.Subject.OrgUnits != nil {
  1707  
  1708  		if ps.Policy.Subject.OrgUnits == nil {
  1709  			t.Fatalf("specified policy orgs units are not specified")
  1710  		}
  1711  
  1712  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.OrgUnits, ps.Policy.Subject.OrgUnits)
  1713  		if !valid {
  1714  			t.Fatalf("specified policy orgs units are different")
  1715  		}
  1716  
  1717  	}
  1718  
  1719  	if specifiedPS.Policy.Subject.Localities != nil {
  1720  
  1721  		if ps.Policy.Subject.Localities == nil {
  1722  			t.Fatalf("specified policy localities are not specified")
  1723  		}
  1724  
  1725  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Localities, ps.Policy.Subject.Localities)
  1726  		if !valid {
  1727  			t.Fatalf("specified policy localities are different")
  1728  		}
  1729  
  1730  	}
  1731  
  1732  	if specifiedPS.Policy.Subject.States != nil {
  1733  
  1734  		if ps.Policy.Subject.States == nil {
  1735  			t.Fatalf("specified policy states are not specified")
  1736  		}
  1737  
  1738  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.States, ps.Policy.Subject.States)
  1739  		if !valid {
  1740  			t.Fatalf("specified policy states are different")
  1741  		}
  1742  
  1743  	}
  1744  
  1745  	if specifiedPS.Policy.Subject.Countries != nil {
  1746  
  1747  		if ps.Policy.Subject.Countries == nil {
  1748  			t.Fatalf("specified policy countries are not specified")
  1749  		}
  1750  
  1751  		valid := test.IsArrayStringEqual(specifiedPS.Policy.Subject.Countries, ps.Policy.Subject.Countries)
  1752  		if !valid {
  1753  			t.Fatalf("specified policy countries are different")
  1754  		}
  1755  
  1756  	}
  1757  
  1758  	//validate key pair values.
  1759  
  1760  	if specifiedPS.Policy.KeyPair.KeyTypes != nil {
  1761  
  1762  		if ps.Policy.KeyPair.KeyTypes == nil {
  1763  			t.Fatalf("specified policy key types are not specified")
  1764  		}
  1765  
  1766  		valid := test.IsArrayStringEqual(specifiedPS.Policy.KeyPair.KeyTypes, ps.Policy.KeyPair.KeyTypes)
  1767  		if !valid {
  1768  			t.Fatalf("specified policy key types are different")
  1769  		}
  1770  
  1771  	}
  1772  
  1773  	if specifiedPS.Policy.KeyPair.RsaKeySizes != nil {
  1774  
  1775  		if ps.Policy.KeyPair.RsaKeySizes == nil {
  1776  			t.Fatalf("specified policy rsa key sizes are not specified")
  1777  		}
  1778  
  1779  		valid := test.IsArrayIntEqual(specifiedPS.Policy.KeyPair.RsaKeySizes, ps.Policy.KeyPair.RsaKeySizes)
  1780  		if !valid {
  1781  			t.Fatalf("specified policy rsa key sizes are different")
  1782  		}
  1783  
  1784  	}
  1785  
  1786  	if specifiedPS.Policy.KeyPair.ReuseAllowed != nil {
  1787  
  1788  		if ps.Policy.KeyPair.ReuseAllowed == nil {
  1789  			t.Fatalf("specified policy rsa key sizes are not specified")
  1790  		}
  1791  
  1792  		if *(ps.Policy.KeyPair.ReuseAllowed) != *(specifiedPS.Policy.KeyPair.ReuseAllowed) {
  1793  			t.Fatalf("specified policy rsa key sizes are different")
  1794  		}
  1795  
  1796  	}
  1797  
  1798  	//validate default values.
  1799  	if specifiedPS.Default.Subject.Org != nil {
  1800  		if ps.Default.Subject.Org == nil {
  1801  			t.Fatalf("specified policy default org is not specified")
  1802  		}
  1803  		if *(ps.Default.Subject.Org) != *(specifiedPS.Default.Subject.Org) {
  1804  			t.Fatalf("specified policy default org is different")
  1805  		}
  1806  	}
  1807  
  1808  	if specifiedPS.Default.Subject.OrgUnits != nil {
  1809  
  1810  		if ps.Default.Subject.OrgUnits == nil {
  1811  			t.Fatalf("specified policy default org is not specified")
  1812  		}
  1813  
  1814  		valid := test.IsArrayStringEqual(specifiedPS.Default.Subject.OrgUnits, ps.Default.Subject.OrgUnits)
  1815  
  1816  		if !valid {
  1817  			t.Fatalf("specified policy default org unit are different")
  1818  		}
  1819  
  1820  	}
  1821  
  1822  	if specifiedPS.Default.Subject.Locality != nil {
  1823  		if ps.Default.Subject.Locality == nil {
  1824  			t.Fatalf("specified policy default locality is not specified")
  1825  		}
  1826  		if *(ps.Default.Subject.Locality) != *(specifiedPS.Default.Subject.Locality) {
  1827  			t.Fatalf("specified policy default locality is different")
  1828  		}
  1829  	}
  1830  
  1831  	if specifiedPS.Default.Subject.State != nil {
  1832  		if ps.Default.Subject.State == nil {
  1833  			t.Fatalf("specified policy default state is not specified")
  1834  		}
  1835  		if *(ps.Default.Subject.State) != *(specifiedPS.Default.Subject.State) {
  1836  			t.Fatalf("specified policy default state is different")
  1837  		}
  1838  	}
  1839  
  1840  	if specifiedPS.Default.Subject.Country != nil {
  1841  		if ps.Default.Subject.Country == nil {
  1842  			t.Fatalf("policy default country is not specified")
  1843  		}
  1844  		if *(ps.Default.Subject.Country) != *(specifiedPS.Default.Subject.Country) {
  1845  			t.Fatalf("specified policy default country is different")
  1846  		}
  1847  	}
  1848  
  1849  	if specifiedPS.Default.KeyPair.KeyType != nil {
  1850  		if ps.Default.KeyPair.KeyType == nil {
  1851  			t.Fatalf("policy default key type is not specified ")
  1852  		}
  1853  		psDefaultKeyType := ps.Default.KeyPair.KeyType
  1854  		psDefaultKeyTypeConverted := test.UnifyECvalue(*psDefaultKeyType)
  1855  		ps.Default.KeyPair.KeyType = &psDefaultKeyTypeConverted
  1856  		if *(ps.Default.KeyPair.KeyType) != *(specifiedPS.Default.KeyPair.KeyType) {
  1857  
  1858  			t.Fatalf("specified policy default key type is different")
  1859  		}
  1860  	}
  1861  
  1862  	if specifiedPS.Default.KeyPair.RsaKeySize != nil {
  1863  		if ps.Default.KeyPair.RsaKeySize == nil {
  1864  			t.Fatalf("policy default rsa key size is not specified")
  1865  		}
  1866  		if *(ps.Default.KeyPair.RsaKeySize) != *(specifiedPS.Default.KeyPair.RsaKeySize) {
  1867  			t.Fatalf("specified policy default rsa key size is different")
  1868  		}
  1869  	}
  1870  
  1871  }
  1872  
  1873  func TestSetEmptyPolicy(t *testing.T) {
  1874  
  1875  	policyName := test.RandAppName() + "\\" + test.RandCitName()
  1876  	conn := getTestConnector(ctx.CloudZone)
  1877  	conn.verbose = true
  1878  
  1879  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1880  
  1881  	if err != nil {
  1882  		t.Fatalf("%s", err)
  1883  	}
  1884  
  1885  	specification := policy.PolicySpecification{}
  1886  
  1887  	_, err = conn.SetPolicy(policyName, &specification)
  1888  
  1889  	if err != nil {
  1890  		t.Fatalf("%s", err)
  1891  	}
  1892  
  1893  }
  1894  
  1895  func TestSetDefaultPolicyValuesAndValidate(t *testing.T) {
  1896  
  1897  	policyName := test.RandAppName() + "\\" + test.RandCitName()
  1898  	conn := getTestConnector(ctx.CloudZone)
  1899  	conn.verbose = true
  1900  
  1901  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1902  
  1903  	if err != nil {
  1904  		t.Fatalf("%s", err)
  1905  	}
  1906  
  1907  	specification := test.GetCloudPolicySpecification()
  1908  
  1909  	specification.Policy = nil
  1910  	ec := "P384"
  1911  	serGenerated := true
  1912  	specification.Default.KeyPair.EllipticCurve = &ec
  1913  	specification.Default.KeyPair.ServiceGenerated = &serGenerated
  1914  	ctx.CloudZone = policyName
  1915  
  1916  	_, err = conn.SetPolicy(policyName, specification)
  1917  
  1918  	if err != nil {
  1919  		t.Fatalf("%s", err)
  1920  	}
  1921  
  1922  	//get the created policy
  1923  	ps, err := conn.GetPolicy(policyName)
  1924  
  1925  	if err != nil {
  1926  		t.Fatalf("%s", err)
  1927  	}
  1928  
  1929  	if ps.Default == nil {
  1930  		t.Fatalf("policy's defaults are nil")
  1931  	}
  1932  	localDefault := specification.Default
  1933  	remoteDefault := ps.Default
  1934  
  1935  	if remoteDefault.Subject == nil {
  1936  		t.Fatalf("policy's default subject is nil")
  1937  	}
  1938  	if *(remoteDefault.Subject.Locality) != *(localDefault.Subject.Locality) {
  1939  		t.Fatalf("policy's default locality is different expected: %s but get %s", *(localDefault.Subject.Locality), *(remoteDefault.Subject.Locality))
  1940  	}
  1941  
  1942  	if *(remoteDefault.Subject.Country) != *(localDefault.Subject.Country) {
  1943  		t.Fatalf("policy's default country is different expected: %s but get %s", *(localDefault.Subject.Country), *(remoteDefault.Subject.Country))
  1944  	}
  1945  
  1946  	if *(remoteDefault.Subject.State) != *(localDefault.Subject.State) {
  1947  		t.Fatalf("policy's default state is different expected: %s but get %s", *(localDefault.Subject.State), *(remoteDefault.Subject.State))
  1948  	}
  1949  
  1950  	if *(remoteDefault.Subject.Org) != *(localDefault.Subject.Org) {
  1951  		t.Fatalf("policy's default org is different expected: %s but get %s", *(localDefault.Subject.Org), *(remoteDefault.Subject.Org))
  1952  	}
  1953  
  1954  	valid := test.IsArrayStringEqual(remoteDefault.Subject.OrgUnits, localDefault.Subject.OrgUnits)
  1955  	if !valid {
  1956  		t.Fatalf("policy's default orgUnits are different")
  1957  	}
  1958  
  1959  	if remoteDefault.KeyPair == nil {
  1960  		t.Fatalf("policy's default keyPair is nil")
  1961  	}
  1962  
  1963  	if *(remoteDefault.KeyPair.KeyType) != *(localDefault.KeyPair.KeyType) {
  1964  		t.Fatalf("policy's default keyType is different expected: %s but get %s", *(localDefault.KeyPair.KeyType), *(remoteDefault.KeyPair.KeyType))
  1965  	}
  1966  
  1967  	if *(remoteDefault.KeyPair.RsaKeySize) != *(localDefault.KeyPair.RsaKeySize) {
  1968  		t.Fatalf("policy's default RsaKeySize is different expected: %s but get %s", strconv.Itoa(*(localDefault.KeyPair.RsaKeySize)), strconv.Itoa(*(remoteDefault.KeyPair.RsaKeySize)))
  1969  	}
  1970  
  1971  }
  1972  
  1973  func TestSetPolicyValuesAndValidate(t *testing.T) {
  1974  
  1975  	policyName := test.RandAppName() + "\\" + test.RandCitName()
  1976  	conn := getTestConnector(ctx.CloudZone)
  1977  	conn.verbose = true
  1978  
  1979  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  1980  
  1981  	if err != nil {
  1982  		t.Fatalf("%s", err)
  1983  	}
  1984  
  1985  	specification := test.GetCloudPolicySpecification()
  1986  
  1987  	specification.Default = nil
  1988  	ctx.CloudZone = policyName
  1989  
  1990  	_, err = conn.SetPolicy(policyName, specification)
  1991  
  1992  	if err != nil {
  1993  		t.Fatalf("%s", err)
  1994  	}
  1995  
  1996  	//get the created policy
  1997  	ps, err := conn.GetPolicy(policyName)
  1998  
  1999  	if err != nil {
  2000  		t.Fatalf("%s", err)
  2001  	}
  2002  
  2003  	if ps.Policy == nil {
  2004  		t.Fatalf("policy is nil")
  2005  	}
  2006  	localPolicy := specification.Policy
  2007  	remotePolicy := ps.Policy
  2008  
  2009  	if remotePolicy.Subject == nil {
  2010  		t.Fatalf("policy's subject is nil")
  2011  	}
  2012  
  2013  	valid := test.IsArrayStringEqual(remotePolicy.Subject.Localities, localPolicy.Subject.Localities)
  2014  	if !valid {
  2015  		t.Fatalf("policy's localities are different expected: %+q but get  %+q ", localPolicy.Subject.Localities, remotePolicy.Subject.Localities)
  2016  	}
  2017  
  2018  	valid = test.IsArrayStringEqual(remotePolicy.Subject.Countries, localPolicy.Subject.Countries)
  2019  	if !valid {
  2020  		t.Fatalf("policy's countries are different expected: %+q but get  %+q", localPolicy.Subject.Countries, remotePolicy.Subject.Countries)
  2021  	}
  2022  
  2023  	valid = test.IsArrayStringEqual(remotePolicy.Subject.States, localPolicy.Subject.States)
  2024  	if !valid {
  2025  		t.Fatalf("policy's states are different expected: %+q but get  %+q", localPolicy.Subject.States, remotePolicy.Subject.States)
  2026  	}
  2027  
  2028  	valid = test.IsArrayStringEqual(remotePolicy.Subject.Orgs, localPolicy.Subject.Orgs)
  2029  	if !valid {
  2030  		t.Fatalf("policy's default org are different expected: %+q but get  %+q", localPolicy.Subject.Orgs, remotePolicy.Subject.Orgs)
  2031  	}
  2032  
  2033  	valid = test.IsArrayStringEqual(remotePolicy.Subject.OrgUnits, localPolicy.Subject.OrgUnits)
  2034  	if !valid {
  2035  		t.Fatalf("policy's org units are different expected: %+q but get  %+q", localPolicy.Subject.OrgUnits, remotePolicy.Subject.OrgUnits)
  2036  	}
  2037  
  2038  	if remotePolicy.KeyPair == nil {
  2039  		t.Fatalf("policy's keyPair is nil")
  2040  	}
  2041  
  2042  	valid = test.IsArrayStringEqual(remotePolicy.KeyPair.KeyTypes, localPolicy.KeyPair.KeyTypes)
  2043  	if !valid {
  2044  		t.Fatalf("policy's keyTypes are different expected: %+q but get  %+q", localPolicy.KeyPair.KeyTypes, remotePolicy.KeyPair.KeyTypes)
  2045  	}
  2046  
  2047  	valid = test.IsArrayIntEqual(remotePolicy.KeyPair.RsaKeySizes, localPolicy.KeyPair.RsaKeySizes)
  2048  	if !valid {
  2049  		t.Fatalf("policy's RsaKeySizes are different expected:  %+q but get  %+q", localPolicy.KeyPair.RsaKeySizes, remotePolicy.KeyPair.RsaKeySizes)
  2050  	}
  2051  
  2052  }
  2053  
  2054  // This test is just for verifying that a policy can be created using ENTRUST CA.
  2055  func TestSetPolicyEntrust(t *testing.T) {
  2056  
  2057  	policyName := test.RandAppName() + "\\" + test.RandCitName()
  2058  	conn := getTestConnector(ctx.CloudZone)
  2059  	conn.verbose = true
  2060  
  2061  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2062  
  2063  	if err != nil {
  2064  		t.Fatalf("%s", err)
  2065  	}
  2066  
  2067  	specification := test.GetCloudPolicySpecification()
  2068  	//change default CA to Entrust
  2069  	caName := os.Getenv("CLOUD_ENTRUST_CA_NAME")
  2070  	specification.Policy.CertificateAuthority = &caName
  2071  
  2072  	_, err = conn.SetPolicy(policyName, specification)
  2073  
  2074  	if err != nil {
  2075  		t.Fatalf("%s", err)
  2076  	}
  2077  
  2078  	ps, err := conn.GetPolicy(policyName)
  2079  
  2080  	if ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == "" {
  2081  		t.Fatalf("venafi policy doesn't have a certificate authority")
  2082  	}
  2083  	if *(ps.Policy.CertificateAuthority) != *(specification.Policy.CertificateAuthority) {
  2084  		t.Fatalf("certificate authority value doesn't match, get: %s but expected: %s", *(ps.Policy.CertificateAuthority), *(specification.Policy.CertificateAuthority))
  2085  	}
  2086  
  2087  }
  2088  
  2089  /*
  2090  *
  2091  This test is just for verifying that a policy can be created using DIGICERT	 CA.
  2092  */
  2093  func TestSetPolicyDigicert(t *testing.T) {
  2094  
  2095  	policyName := test.RandAppName() + "\\" + test.RandCitName()
  2096  	conn := getTestConnector(ctx.CloudZone)
  2097  	conn.verbose = true
  2098  
  2099  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2100  
  2101  	if err != nil {
  2102  		t.Fatalf("%s", err)
  2103  	}
  2104  
  2105  	specification := test.GetCloudPolicySpecification()
  2106  
  2107  	//change default CA to Digiert
  2108  	caName := os.Getenv("CLOUD_DIGICERT_CA_NAME")
  2109  	specification.Policy.CertificateAuthority = &caName
  2110  	_, err = conn.SetPolicy(policyName, specification)
  2111  
  2112  	if err != nil {
  2113  		t.Fatalf("%s", err)
  2114  	}
  2115  
  2116  	ps, err := conn.GetPolicy(policyName)
  2117  
  2118  	if ps.Policy.CertificateAuthority == nil || *(ps.Policy.CertificateAuthority) == "" {
  2119  		t.Fatalf("venafi policy doesn't have a certificate authority")
  2120  	}
  2121  	if *(ps.Policy.CertificateAuthority) != *(specification.Policy.CertificateAuthority) {
  2122  		t.Fatalf("certificate authority value doesn't match, get: %s but expected: %s", *(ps.Policy.CertificateAuthority), *(specification.Policy.CertificateAuthority))
  2123  	}
  2124  }
  2125  
  2126  func TestCreateCertServiceCSR(t *testing.T) {
  2127  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2128  	conn := getTestConnector(policyName)
  2129  	conn.verbose = true
  2130  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2131  	if err != nil {
  2132  		t.Fatalf("%s", err)
  2133  	}
  2134  	if err != nil {
  2135  		t.Fatalf("%s", err)
  2136  	}
  2137  	req := getBasicRequest()
  2138  	req.DNSNames = []string{req.Subject.CommonName}
  2139  
  2140  	req.CsrOrigin = certificate.ServiceGeneratedCSR
  2141  
  2142  	id, err := conn.RequestCertificate(&req)
  2143  	if err != nil {
  2144  		t.Fatalf("%s", err)
  2145  	}
  2146  	req.PickupID = id
  2147  	req.ChainOption = certificate.ChainOptionRootFirst
  2148  	req.KeyPassword = "abcede"
  2149  	req.Timeout = time.Duration(180) * time.Second
  2150  	pcc, err := conn.RetrieveCertificate(&req)
  2151  
  2152  	if pcc.Certificate == "" {
  2153  		t.Fatalf("certificate with pickup id: %s is empty", req.PickupID)
  2154  	}
  2155  	if pcc.PrivateKey == "" {
  2156  		t.Fatalf("private key for certificate with pickup id: %s is empty", req.PickupID)
  2157  	}
  2158  	if len(pcc.Chain) == 0 {
  2159  		t.Fatalf("chai for certificate with pickup id: %s is empty", req.PickupID)
  2160  	}
  2161  
  2162  }
  2163  
  2164  func TestCreateCertServiceCSRWithDefaults(t *testing.T) {
  2165  	t.Skip("it will enabled on the future")
  2166  	conn := getTestConnector("App Alfa\\Amoo")
  2167  	conn.verbose = true
  2168  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2169  	if err != nil {
  2170  		t.Fatalf("%s", err)
  2171  	}
  2172  	if err != nil {
  2173  		t.Fatalf("%s", err)
  2174  	}
  2175  	req := certificate.Request{}
  2176  	req.Subject.CommonName = test.RandCN()
  2177  
  2178  	req.CsrOrigin = certificate.ServiceGeneratedCSR
  2179  
  2180  	id, err := conn.RequestCertificate(&req)
  2181  	if err != nil {
  2182  		t.Fatalf("%s", err)
  2183  	}
  2184  	req.PickupID = id
  2185  	req.ChainOption = certificate.ChainOptionRootFirst
  2186  	req.KeyPassword = "abcede"
  2187  	req.Timeout = time.Duration(180) * time.Second
  2188  	pcc, err := conn.RetrieveCertificate(&req)
  2189  
  2190  	if pcc.Certificate == "" {
  2191  		t.Fatalf("certificate with pickup id: %s is empty", req.PickupID)
  2192  	}
  2193  	if pcc.PrivateKey == "" {
  2194  		t.Fatalf("private key for certificate with pickup id: %s is empty", req.PickupID)
  2195  	}
  2196  	if len(pcc.Chain) == 0 {
  2197  		t.Fatalf("chai for certificate with pickup id: %s is empty", req.PickupID)
  2198  	}
  2199  
  2200  }
  2201  
  2202  func TestGetDefaultCsrAttributes(t *testing.T) {
  2203  
  2204  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2205  	conn := getTestConnector(policyName)
  2206  	conn.verbose = true
  2207  	request := &certificate.Request{}
  2208  	request.Subject.CommonName = "test.vfidev.com"
  2209  
  2210  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2211  
  2212  	if err != nil {
  2213  		t.Fatalf("%s", err)
  2214  	}
  2215  	attributes, err := getCsrAttributes(conn, request)
  2216  
  2217  	if err != nil {
  2218  		t.Fatalf("%s", err)
  2219  	}
  2220  
  2221  	if attributes == nil {
  2222  		t.Fatal("attributes are nil")
  2223  	}
  2224  }
  2225  
  2226  func TestGetCsrAttributes(t *testing.T) {
  2227  
  2228  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2229  	conn := getTestConnector(policyName)
  2230  	conn.verbose = true
  2231  	req := getBasicRequest()
  2232  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2233  
  2234  	if err != nil {
  2235  		t.Fatalf("%s", err)
  2236  	}
  2237  	attributes, err := getCsrAttributes(conn, &req)
  2238  
  2239  	if err != nil {
  2240  		t.Fatalf("%s", err)
  2241  	}
  2242  
  2243  	if attributes == nil {
  2244  		t.Fatal("attributes are nil")
  2245  	}
  2246  }
  2247  
  2248  func TestCertificateSanTypes(t *testing.T) {
  2249  
  2250  	ip := net.ParseIP("127.0.0.1")
  2251  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2252  	conn := getTestConnector(policyName)
  2253  	conn.verbose = true
  2254  	req := getBasicRequest()
  2255  
  2256  	//email sans
  2257  	req.EmailAddresses = []string{fmt.Sprint("test@", req.Subject.CommonName)}
  2258  
  2259  	//ip sans˘
  2260  	req.IPAddresses = []net.IP{ip}
  2261  
  2262  	//uri sans
  2263  	uri, _ := url.Parse(fmt.Sprint("https://", req.Subject.CommonName))
  2264  	req.URIs = []*url.URL{uri}
  2265  
  2266  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2267  
  2268  	if err != nil {
  2269  		t.Fatalf("%s", err)
  2270  	}
  2271  	attributes, err := getCsrAttributes(conn, &req)
  2272  
  2273  	if err != nil {
  2274  		t.Fatalf("%s", err)
  2275  	}
  2276  
  2277  	if attributes == nil {
  2278  		t.Fatal("attributes are nil")
  2279  	}
  2280  }
  2281  
  2282  func TestVerifyCSRServiceGenerated(t *testing.T) {
  2283  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2284  
  2285  	conn := getTestConnector(policyName)
  2286  	conn.verbose = true
  2287  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2288  	if err != nil {
  2289  		t.Fatalf("%s", err)
  2290  	}
  2291  
  2292  	req := getBasicRequest()
  2293  
  2294  	req.CsrOrigin = certificate.ServiceGeneratedCSR
  2295  
  2296  	id, err := conn.RequestCertificate(&req)
  2297  	if err != nil {
  2298  		t.Fatalf("%s", err)
  2299  	}
  2300  	req.PickupID = id
  2301  	req.ChainOption = certificate.ChainOptionRootFirst
  2302  	req.KeyPassword = "abcede"
  2303  	req.Timeout = time.Duration(180) * time.Second
  2304  
  2305  	isCSRService, err := conn.IsCSRServiceGenerated(&req)
  2306  
  2307  	if err != nil {
  2308  		t.Fatalf("%s", err)
  2309  	}
  2310  
  2311  	if !isCSRService {
  2312  		t.Fatal("Requested certificate should be CSR service generated")
  2313  	}
  2314  
  2315  }
  2316  
  2317  func TestGenerateCertificateEC(t *testing.T) {
  2318  	policyName := os.Getenv("VAAS_ZONE_ONLY_EC")
  2319  
  2320  	conn := getTestConnector(policyName)
  2321  	conn.verbose = true
  2322  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2323  	if err != nil {
  2324  		t.Fatalf("%s", err)
  2325  	}
  2326  	if err != nil {
  2327  		t.Fatalf("%s", err)
  2328  	}
  2329  	req := getBasicRequest()
  2330  	req.KeyType = certificate.KeyTypeECDSA
  2331  	req.KeyCurve = certificate.EllipticCurveP384
  2332  	req.CsrOrigin = certificate.ServiceGeneratedCSR
  2333  
  2334  	id, err := conn.RequestCertificate(&req)
  2335  	if err != nil {
  2336  		t.Fatalf("%s", err)
  2337  	}
  2338  	req.PickupID = id
  2339  	req.ChainOption = certificate.ChainOptionRootFirst
  2340  	req.KeyPassword = "abcede"
  2341  	req.Timeout = time.Duration(180) * time.Second
  2342  
  2343  	isCSRService, err := conn.IsCSRServiceGenerated(&req)
  2344  
  2345  	if err != nil {
  2346  		t.Fatalf("%s", err)
  2347  	}
  2348  
  2349  	if !isCSRService {
  2350  		t.Fatal("Requested certificate should be CSR service generated")
  2351  	}
  2352  
  2353  }
  2354  
  2355  func TestGenerateCertificateECDefault(t *testing.T) {
  2356  	policyName := os.Getenv("VAAS_ZONE_ONLY_EC")
  2357  
  2358  	conn := getTestConnector(policyName)
  2359  	conn.verbose = true
  2360  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2361  	if err != nil {
  2362  		t.Fatalf("%s", err)
  2363  	}
  2364  	if err != nil {
  2365  		t.Fatalf("%s", err)
  2366  	}
  2367  	req := getBasicRequest()
  2368  	req.KeyType = certificate.KeyTypeECDSA
  2369  	req.CsrOrigin = certificate.ServiceGeneratedCSR
  2370  
  2371  	id, err := conn.RequestCertificate(&req)
  2372  	if err != nil {
  2373  		t.Fatalf("%s", err)
  2374  	}
  2375  	req.PickupID = id
  2376  	req.ChainOption = certificate.ChainOptionRootFirst
  2377  	req.KeyPassword = "abcede"
  2378  	req.Timeout = time.Duration(180) * time.Second
  2379  
  2380  	isCSRService, err := conn.IsCSRServiceGenerated(&req)
  2381  
  2382  	if err != nil {
  2383  		t.Fatalf("%s", err)
  2384  	}
  2385  
  2386  	if !isCSRService {
  2387  		t.Fatal("Requested certificate should be CSR service generated")
  2388  	}
  2389  
  2390  }
  2391  
  2392  func TestGetType(t *testing.T) {
  2393  	policyName := os.Getenv("CLOUD_ZONE_RESTRICTED")
  2394  
  2395  	conn := getTestConnector(policyName)
  2396  
  2397  	if endpoint.ConnectorTypeCloud != conn.GetType() {
  2398  		t.Fatalf("expected: %s but get %s", endpoint.ConnectorTypeCloud.String(), conn.GetType().String())
  2399  	}
  2400  
  2401  }
  2402  
  2403  func getBasicRequest() certificate.Request {
  2404  
  2405  	req := certificate.Request{}
  2406  	req.Subject.CommonName = test.RandSpecificCN("test.vfidev.com")
  2407  	req.Subject.Organization = []string{"Venafi Inc."}
  2408  	req.Subject.OrganizationalUnit = []string{"Integrations"}
  2409  	req.Subject.Locality = []string{"Salt Lake"}
  2410  	req.Subject.Province = []string{"Utah"}
  2411  	req.Subject.Country = []string{"US"}
  2412  	req.DNSNames = []string{req.Subject.CommonName}
  2413  
  2414  	return req
  2415  }
  2416  
  2417  // TODO: Expand unit tests to cover more cases
  2418  func TestSearchValidCertificate(t *testing.T) {
  2419  	conn := getTestConnector(ctx.CloudZone)
  2420  	err := conn.Authenticate(&endpoint.Authentication{APIKey: ctx.CloudAPIkey})
  2421  	if err != nil {
  2422  		t.Fatal(err)
  2423  	}
  2424  
  2425  	cn := "one.example.com"
  2426  	// There are 2 certificates here
  2427  	sans := &certificate.Sans{DNS: []string{cn, "two.example.com"}}
  2428  	// and 2 more, certificates here
  2429  	// sans := &certificate.Sans{DNS: []string{cn, "two.example.com", "three.example.com"}}
  2430  
  2431  	// TODO: Filter zone
  2432  	// with this zone you should be able to find those certificates
  2433  	zone := "Open Source Integrations\\Unrestricted"
  2434  	// but not with this (or any non valid zone)
  2435  	// zone := "Invalid zone\\The CIT"
  2436  
  2437  	// use time.Duration instead of integer
  2438  	day := 24 * time.Hour
  2439  	certMinTimeLeft := 3 * day
  2440  
  2441  	certificate, err := conn.SearchCertificate(zone, cn, sans, certMinTimeLeft)
  2442  	if err != nil {
  2443  		t.Fatalf("%v", err)
  2444  	}
  2445  
  2446  	if certificate == nil {
  2447  		t.Fatal("Should have found a certificate")
  2448  	}
  2449  
  2450  	fmt.Printf("%v\n", util.GetJsonAsString(*certificate))
  2451  }