Skip to content

Commit

Permalink
Merge pull request #31 from Keyfactor/epic_55177
Browse files Browse the repository at this point in the history
Epic 55177
  • Loading branch information
spbsoluble authored Mar 14, 2024
2 parents 8ac97c8 + b7ff510 commit af3da9d
Show file tree
Hide file tree
Showing 8 changed files with 119 additions and 92 deletions.
67 changes: 34 additions & 33 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,33 @@ before:
# this is just an example and not a requirement for provider building/publishing
- go mod tidy
builds:
- env:
# goreleaser does not work with CGO, it could also complicate
# usage by users in CI/CD systems like Terraform Cloud where
# they are unable to install libraries.
- CGO_ENABLED=0
mod_timestamp: '{{ .CommitTimestamp }}'
flags:
- -trimpath
ldflags:
- '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}'
goos:
- freebsd
- windows
- linux
- darwin
goarch:
- amd64
- '386'
- arm
- arm64
ignore:
- goos: darwin
goarch: '386'
binary: '{{ .ProjectName }}_v{{ .Version }}'
- env:
# goreleaser does not work with CGO, it could also complicate
# usage by users in CI/CD systems like Terraform Cloud where
# they are unable to install libraries.
- CGO_ENABLED=0
mod_timestamp: '{{ .CommitTimestamp }}'
flags:
- -trimpath
ldflags:
- '-s -w -X main.version={{.Version}} -X main.commit={{.Commit}}'
goos:
- freebsd
- windows
- linux
- darwin
goarch:
- amd64
- '386'
- arm
- arm64
ignore:
- goos: darwin
goarch: '386'
binary: '{{ .ProjectName }}_v{{ .Version }}'
archives:
- format: zip
name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}'
- format: zip
name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}'
checksum:
extra_files:
- glob: 'integration-manifest.json'
Expand All @@ -51,6 +51,7 @@ signs:
- "--detach-sign"
- "${artifact}"
release:
prerelease: auto
extra_files:
- glob: 'integration-manifest.json'
name_template: '{{ .ProjectName }}_{{ .Version }}_manifest.json'
Expand All @@ -61,13 +62,13 @@ changelog:
use: github
filters:
exclude:
- '^test:'
- '^chore'
- 'merge conflict'
- Merge pull request
- Merge remote-tracking branch
- Merge branch
- go mod tidy
- '^test:'
- '^chore'
- 'merge conflict'
- Merge pull request
- Merge remote-tracking branch
- Merge branch
- go mod tidy
groups:
- title: Dependency updates
regexp: ".*(feat|fix)\\(deps\\)*:+.*$"
Expand Down
36 changes: 18 additions & 18 deletions api/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"log"
"net/http"

"github.com/Keyfactor/keyfactor-go-client-sdk/api/keyfactor"
kfc "github.com/Keyfactor/keyfactor-go-client-sdk/api/keyfactor"
)

// CreateStore takes arguments for CreateStoreFctArgs to facilitate the creation
Expand Down Expand Up @@ -134,8 +134,8 @@ func (c *Client) DeleteCertificateStore(storeId string) error {
xKeyfactorRequestedWith := "APIClient"
xKeyfactorApiVersion := "1"

configuration := keyfactor.NewConfiguration(make(map[string]string))
apiClient := keyfactor.NewAPIClient(configuration)
configuration := kfc.NewConfiguration(make(map[string]string))
apiClient := kfc.NewAPIClient(configuration)

resp, err := apiClient.CertificateStoreApi.CertificateStoreDeleteCertificateStore(context.Background(), storeId).XKeyfactorRequestedWith(xKeyfactorRequestedWith).XKeyfactorApiVersion(xKeyfactorApiVersion).Execute()

Expand Down Expand Up @@ -311,22 +311,22 @@ func (c *Client) AddCertificateToStores(config *AddCertificateToStore) ([]string
xKeyfactorRequestedWith := "APIClient"
xKeyfactorApiVersion := "1"

configuration := keyfactor.NewConfiguration(make(map[string]string))
apiClient := keyfactor.NewAPIClient(configuration)
configuration := kfc.NewConfiguration(make(map[string]string))
apiClient := kfc.NewAPIClient(configuration)

newCollectionId := int32(config.CollectionId)
var newCertStoresList []keyfactor.ModelsCertificateStoreEntry
var newCertStoresList []kfc.ModelsCertificateStoreEntry
for _, cert := range *config.CertificateStores {
newProvider := int32(cert.EntryPassword.Provider)
var newParams map[string]string
data, _ := json.Marshal(cert.EntryPassword.Parameters)
json.Unmarshal(data, &newParams)
var newEntryPassword = keyfactor.ModelsKeyfactorAPISecret{
var newEntryPassword = kfc.ModelsKeyfactorAPISecret{
SecretValue: &cert.EntryPassword.SecretValue,
Parameters: &newParams,
Provider: &newProvider,
}
var newCert = keyfactor.ModelsCertificateStoreEntry{
var newCert = kfc.ModelsCertificateStoreEntry{
CertificateStoreId: cert.CertificateStoreId,
Alias: &cert.Alias,
JobFields: nil,
Expand All @@ -339,9 +339,9 @@ func (c *Client) AddCertificateToStores(config *AddCertificateToStore) ([]string
}

jsonInvSched, _ := json.Marshal(config.InventorySchedule)
var newSchedule keyfactor.KeyfactorCommonSchedulingKeyfactorSchedule
var newSchedule kfc.KeyfactorCommonSchedulingKeyfactorSchedule
json.Unmarshal(jsonInvSched, newSchedule)
var newReq = keyfactor.KeyfactorApiModelsCertificateStoresAddCertificateRequest{
var newReq = kfc.KeyfactorApiModelsCertificateStoresAddCertificateRequest{
CertificateId: int32(config.CertificateId),
CertificateStores: newCertStoresList,
Schedule: newSchedule,
Expand All @@ -365,13 +365,13 @@ func (c *Client) RemoveCertificateFromStores(config *RemoveCertificateFromStore)
xKeyfactorRequestedWith := "APIClient"
xKeyfactorApiVersion := "1"

configuration := keyfactor.NewConfiguration(make(map[string]string))
apiClient := keyfactor.NewAPIClient(configuration)
configuration := kfc.NewConfiguration(make(map[string]string))
apiClient := kfc.NewAPIClient(configuration)

newCollectionId := int32(config.CollectionId)
var newCertStoresList []keyfactor.ModelsCertificateLocationSpecifier
var newCertStoresList []kfc.ModelsCertificateLocationSpecifier
for _, cert := range *config.CertificateStores {
var newCert = keyfactor.ModelsCertificateLocationSpecifier{
var newCert = kfc.ModelsCertificateLocationSpecifier{
Alias: &cert.Alias,
CertificateStoreId: &cert.CertificateStoreId,
JobFields: nil,
Expand All @@ -380,9 +380,9 @@ func (c *Client) RemoveCertificateFromStores(config *RemoveCertificateFromStore)
}

jsonInvSched, _ := json.Marshal(config.InventorySchedule)
var newSchedule keyfactor.KeyfactorCommonSchedulingKeyfactorSchedule
var newSchedule kfc.KeyfactorCommonSchedulingKeyfactorSchedule
json.Unmarshal(jsonInvSched, newSchedule)
var newReq = keyfactor.KeyfactorApiModelsCertificateStoresRemoveCertificateRequest{
var newReq = kfc.KeyfactorApiModelsCertificateStoresRemoveCertificateRequest{
CertificateStores: newCertStoresList,
Schedule: newSchedule,
CollectionId: &newCollectionId,
Expand All @@ -402,8 +402,8 @@ func (c *Client) GetCertStoreInventory(storeId string) (*[]CertStoreInventory, e
xKeyfactorRequestedWith := "APIClient"
xKeyfactorApiVersion := "1"

configuration := keyfactor.NewConfiguration(make(map[string]string))
apiClient := keyfactor.NewAPIClient(configuration)
configuration := kfc.NewConfiguration(make(map[string]string))
apiClient := kfc.NewAPIClient(configuration)

resp, _, err := apiClient.CertificateStoreApi.CertificateStoreGetCertificateStoreInventory(context.Background(), storeId).XKeyfactorRequestedWith(xKeyfactorRequestedWith).XKeyfactorApiVersion(xKeyfactorApiVersion).Execute()

Expand Down
2 changes: 2 additions & 0 deletions v2/api/certificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,8 @@ func (c *Client) GetCertificateContext(gca *GetCertificateContextArgs) (*GetCert
}
}
return &newestCert, nil
} else if len(lCerts) == 0 {
return nil, fmt.Errorf("no certificate found")
}
return &lCerts[0], nil // Return first cert in list
}
Expand Down
33 changes: 28 additions & 5 deletions v2/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
)
Expand All @@ -22,6 +23,7 @@ var (
EnvCommandPassword = "KEYFACTOR_PASSWORD"
EnvCommandDomain = "KEYFACTOR_DOMAIN"
EnvCommandAPI = "KEYFACTOR_API_PATH"
EnvCommandTimeout = "KEYFACTOR_TIMEOUT"
DefaultAPIPath = "KeyfactorAPI"
)

Expand All @@ -41,6 +43,7 @@ type AuthConfig struct {
Password string
Domain string
APIPath string
Timeout int
}

// NewKeyfactorClient creates a new Keyfactor client instance. A configured Client is returned with methods used to
Expand All @@ -51,6 +54,12 @@ func NewKeyfactorClient(auth *AuthConfig) (*Client, error) {
return nil, err
}

if auth.Timeout > 0 {
c.httpClient = &http.Client{Timeout: time.Duration(auth.Timeout) * time.Second}
} else {
c.httpClient = &http.Client{Timeout: MAX_WAIT_SECONDS * time.Second}
}

return c, nil
}

Expand Down Expand Up @@ -111,9 +120,21 @@ func loginToKeyfactor(auth *AuthConfig) (*Client, error) {
Headers: headers,
}

timeoutStr := os.Getenv(EnvCommandTimeout)
timeout := MAX_WAIT_SECONDS
if timeoutStr != "" {
//convert to int and check if greater than 0
timeoutInt, err := strconv.Atoi(timeoutStr)
if err == nil && timeoutInt > 0 {
timeout = timeoutInt
}
} else if auth.Timeout > 0 {
timeout = auth.Timeout
}

c := &Client{
Hostname: auth.Hostname,
httpClient: &http.Client{Timeout: 10 * time.Second},
httpClient: &http.Client{Timeout: time.Duration(timeout) * time.Second},
basicAuthString: buildBasicAuthString(auth),
ApiPath: auth.APIPath,
}
Expand Down Expand Up @@ -181,13 +202,13 @@ func (c *Client) sendRequest(request *request) (*http.Response, error) {
resp, respErr := c.httpClient.Do(req)

// check if context deadline exceeded
if respErr != nil && strings.Contains(respErr.Error(), "context deadline exceeded") || http.StatusRequestTimeout == resp.StatusCode {
// retry until max retries reached
switch {
case respErr != nil && (strings.Contains(respErr.Error(), "context deadline exceeded")):
sleepDuration := time.Duration(1) * time.Second
for i := 0; i < MAX_CONTEXT_DEADLINE_RETRIES; i++ {
// sleep for exponential backoff
if i > 0 {
sleepDuration = sleepDuration * 2
sleepDuration *= 2
if sleepDuration > time.Duration(MAX_WAIT_SECONDS)*time.Second {
sleepDuration = time.Duration(MAX_WAIT_SECONDS) * time.Second
}
Expand All @@ -206,8 +227,10 @@ func (c *Client) sendRequest(request *request) (*http.Response, error) {
break
}
}
} else if respErr != nil {
case respErr != nil:
return nil, respErr
case resp == nil:
return nil, errors.New("no response from Keyfactor Command")
}
var stringMessage string
if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusNoContent {
Expand Down
7 changes: 5 additions & 2 deletions v2/api/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,13 +196,16 @@ func (c *Client) GetSecurityRole(id interface{}) (*GetSecurityRoleResponse, erro
return nil, err
}

jsonResp := &GetSecurityRolesResponse{}
jsonResp := &[]GetSecurityRolesResponse{}
err = json.NewDecoder(resp.Body).Decode(&jsonResp)

for i, jResp := range *jsonResp {
log.Printf("[INFO] Getting Keyfactor security role with %v ID %v", i, jResp)
//convert ID from int to float64
formattedID := float64(jResp.ID)

return &GetSecurityRoleResponse{
Id: jResp.ID,
Id: formattedID,
Name: jResp.Name,
Description: jResp.Description,
Identities: jResp.Identities,
Expand Down
18 changes: 9 additions & 9 deletions v2/api/security_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,20 @@ type CreateSecurityIdentityResponse struct {
}

// GetSecurityRolesResponse holds the response data returned by /Security/Roles
type GetSecurityRolesResponse []struct {
ID int `json:"Id,omitempty"`
type GetSecurityRolesResponse struct {
ID float64 `json:"Id"`
Description string `json:"Description,omitempty"`
Enabled bool `json:"Enabled"`
Immutable bool `json:"Immutable"`
Valid bool `json:"Valid"`
Private bool `json:"Private"`
Identities []SecurityIdentity `json:"Identities,omitempty"`
Identities []SecurityIdentity `json:"Identities"`
Name string `json:"Name,omitempty"`
Permissions []string `json:"Permissions,omitempty"`
Permissions []string `json:"Permissions"`
}

type GetSecurityRoleResponse struct {
Id int `json:"Id,omitempty"`
Id float64 `json:"Id,omitempty"`
Name string `json:"Name,omitempty"`
Description string `json:"Description,omitempty"`
Identities []SecurityIdentity `json:"Identities,omitempty"`
Expand All @@ -53,10 +53,10 @@ type GetSecurityRoleResponse struct {

// SecurityIdentity contains the contains required elements to attach an identity to a role
type SecurityIdentity struct {
Id int `json:"Id,omitempty"`
AccountName string `json:"AccountName,omitempty"`
IdentityType string `json:"IdentityType,omitempty"`
Sid string `json:"Sid,omitempty"`
Id float64 `json:"Id"`
AccountName string `json:"AccountName"`
IdentityType string `json:"IdentityType"`
Sid string `json:"SID"`
}

// CreateSecurityRoleArg holds the function arguments required for CreateSecurityRole
Expand Down
42 changes: 21 additions & 21 deletions v2/api/store_type_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,28 @@ type CertificateStoreTypeGeneric struct {
type CertificateStoreType struct {
Name string `json:"Name"`
ShortName string `json:"ShortName"`
Capability string `json:"Capability"`
Capability string `json:"Capability,omitempty"`
StoreType int `json:"StoreType"`
ImportType int `json:"ImportType"`
LocalStore bool `json:"LocalStore"`
SupportedOperations *StoreTypeSupportedOperations `json:"SupportedOperations"`
Properties *[]StoreTypePropertyDefinition `json:"Properties"`
EntryParameters *[]EntryParameter `json:"EntryParameters"`
PasswordOptions *StoreTypePasswordOptions `json:"PasswordOptions"`
StorePathType string `json:"StorePathType"`
StorePathValue string `json:"StorePathValue"`
PrivateKeyAllowed string `json:"PrivateKeyAllowed"`
JobProperties *[]string `json:"JobProperties"`
ServerRequired bool `json:"ServerRequired"`
PowerShell bool `json:"PowerShell"`
BlueprintAllowed bool `json:"BlueprintAllowed"`
CustomAliasAllowed string `json:"CustomAliasAllowed"`
ServerRegistration int `json:"ServerRegistration"`
InventoryEndpoint string `json:"InventoryEndpoint"`
InventoryJobType string `json:"InventoryJobType"`
ManagementJobType string `json:"ManagementJobType"`
DiscoveryJobType string `json:"DiscoveryJobType"`
EnrollmentJobType string `json:"EnrollmentJobType"`
ImportType int `json:"ImportType,omitempty"`
LocalStore bool `json:"LocalStore,omitempty"`
SupportedOperations *StoreTypeSupportedOperations `json:"SupportedOperations,omitempty"`
Properties *[]StoreTypePropertyDefinition `json:"Properties,omitempty"`
EntryParameters *[]EntryParameter `json:"EntryParameters,omitempty"`
PasswordOptions *StoreTypePasswordOptions `json:"PasswordOptions,omitempty"`
StorePathType string `json:"StorePathType,omitempty"`
StorePathValue string `json:"StorePathValue,omitempty"`
PrivateKeyAllowed string `json:"PrivateKeyAllowed,omitempty"`
JobProperties *[]string `json:"JobProperties,omitempty"`
ServerRequired bool `json:"ServerRequired,omitempty"`
PowerShell bool `json:"PowerShell,omitempty"`
BlueprintAllowed bool `json:"BlueprintAllowed,omitempty"`
CustomAliasAllowed string `json:"CustomAliasAllowed,omitempty"`
ServerRegistration int `json:"ServerRegistration,omitempty"`
InventoryEndpoint string `json:"InventoryEndpoint,omitempty"`
InventoryJobType string `json:"InventoryJobType,omitempty"`
ManagementJobType string `json:"ManagementJobType,omitempty"`
DiscoveryJobType string `json:"DiscoveryJobType,omitempty"`
EnrollmentJobType string `json:"EnrollmentJobType,omitempty"`
}

type CertStoreTypeResponseList []struct {
Expand Down
Loading

0 comments on commit af3da9d

Please sign in to comment.