Skip to content

Commit

Permalink
feat: use a struct to group validate input function parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
btfhernandez committed Jul 3, 2024
1 parent 695c216 commit 335b81a
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 50 deletions.
51 changes: 34 additions & 17 deletions TestClient.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"github.com/BeyondTrust/go-client-library-passwordsafe/api/authentication"
logging "github.com/BeyondTrust/go-client-library-passwordsafe/api/logging"
managed_accounts "github.com/BeyondTrust/go-client-library-passwordsafe/api/managed_account"
"github.com/BeyondTrust/go-client-library-passwordsafe/api/secrets"
"github.com/BeyondTrust/go-client-library-passwordsafe/api/utils"

//"os"
Expand All @@ -26,9 +25,9 @@ func main() {
// create a zap logger wrapper
zapLogger := logging.NewZapLogger(logger)

apiUrl := "https://example.com:443/BeyondTrust/api/public/v3/"
clientId := ""
clientSecret := ""
apiUrl := "https://jury2310.ps-dev.beyondtrustcloud.com:443/BeyondTrust/api/public/v3/"
clientId := "6138d050-e266-4b05-9ced-35e7dd5093ae"
clientSecret := "71svdPLh2AR97sPs5gfPjGjpqSUxZTKSPmEvvbMx89o="
separator := "/"
certificate := ""
certificateKey := ""
Expand All @@ -45,8 +44,23 @@ func main() {
//certificate = os.Getenv("CERTIFICATE")
//certificateKey = os.Getenv("CERTIFICATE_KEY")

// Create an instance of ValidationParams
params := utils.ValidationParams{
ClientID: clientId,
ClientSecret: clientSecret,
ApiUrl: &apiUrl,
ClientTimeOutInSeconds: clientTimeOutInSeconds,
Separator: &separator,
VerifyCa: verifyCa,
Logger: zapLogger,
Certificate: certificate,
CertificateKey: certificateKey,
RetryMaxElapsedTimeMinutes: &retryMaxElapsedTimeMinutes,
MaxFileSecretSizeBytes: &maxFileSecretSizeBytes,
}

// validate inputs
errorsInInputs := utils.ValidateInputs(clientId, clientSecret, &apiUrl, clientTimeOutInSeconds, &separator, verifyCa, zapLogger, certificate, certificateKey, &retryMaxElapsedTimeMinutes, &maxFileSecretSizeBytes)
errorsInInputs := utils.ValidateInputs(params)

if errorsInInputs != nil {
return
Expand All @@ -64,26 +78,29 @@ func main() {
return
}

// instantiating secret obj
secretObj, _ := secrets.NewSecretObj(*authenticate, zapLogger, maxFileSecretSizeBytes)
/*
// instantiating secret obj
secretObj, _ := secrets.NewSecretObj(*authenticate, zapLogger, maxFileSecretSizeBytes)
secretPaths := []string{"fake/Client", "fake/test_file_1"}
secretPaths := []string{"fake/Client", "fake/test_file_1"}
gotSecrets, _ := secretObj.GetSecrets(secretPaths, separator)
gotSecrets, _ := secretObj.GetSecrets(secretPaths, separator)
// WARNING: Do not log secrets in production code, the following log statement logs test secrets for testing purposes:
zapLogger.Warn(fmt.Sprintf("%v", gotSecrets))
// WARNING: Do not log secrets in production code, the following log statement logs test secrets for testing purposes:
zapLogger.Warn(fmt.Sprintf("%v", gotSecrets))
// getting single secret
gotSecret, _ := secretObj.GetSecret("fake/Test1", separator)
// getting single secret
gotSecret, _ := secretObj.GetSecret("fake/Test1", separator)
// WARNING: Do not log secrets in production code, the following log statement logs test secrets for testing purposes:
zapLogger.Warn(fmt.Sprintf("Secret Test: %v", gotSecret))
// WARNING: Do not log secrets in production code, the following log statement logs test secrets for testing purposes:
zapLogger.Warn(fmt.Sprintf("Secret Test: %v", gotSecret))
*/

// instantiating managed account obj
manageAccountObj, _ := managed_accounts.NewManagedAccountObj(*authenticate, zapLogger)

newSecretPaths := []string{"fake/account01", "fake/account01"}
newSecretPaths := []string{"system01/managed_account01", "system01/managed_account01"}

//managedAccountList := strings.Split(paths, ",")
gotManagedAccounts, _ := manageAccountObj.GetSecrets(newSecretPaths, separator)
Expand All @@ -92,7 +109,7 @@ func main() {
zapLogger.Warn(fmt.Sprintf("%v", gotManagedAccounts))

// getting single managed account
gotManagedAccount, _ := manageAccountObj.GetSecret("fake/account04", separator)
gotManagedAccount, _ := manageAccountObj.GetSecret("system01/managed_account01", separator)

// WARNING: Do not log secrets in production code, the following log statement logs test secrets for testing purposes:
zapLogger.Warn(fmt.Sprintf("%v", gotManagedAccount))
Expand Down
78 changes: 46 additions & 32 deletions api/utils/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,20 @@ import (
validator "github.com/go-playground/validator/v10"
)

type ValidationParams struct {
ClientID string
ClientSecret string
ApiUrl *string
ClientTimeOutInSeconds int
Separator *string
VerifyCa bool
Logger logging.Logger
Certificate string
CertificateKey string
RetryMaxElapsedTimeMinutes *int
MaxFileSecretSizeBytes *int
}

// UserInputValidaton responsible for input paramerter validation.
type UserInputValidaton struct {
ClientId string `validate:"required,min=36,max=36"`
Expand All @@ -27,89 +41,89 @@ type UserInputValidaton struct {
var validate *validator.Validate

// ValidateInputs is responsible for validating end-user inputs.
func ValidateInputs(clientId string, clientSecret string, apiUrl *string, clientTimeOutinSeconds int, separator *string, verifyCa bool, logger logging.Logger, certificate string, certificate_key string, retryMaxElapsedTimeMinutes *int, maxFileSecretSizeBytes *int) error {
func ValidateInputs(params ValidationParams) error {

if clientTimeOutinSeconds == 0 {
clientTimeOutinSeconds = 30
if params.ClientTimeOutInSeconds == 0 {
params.ClientTimeOutInSeconds = 30
}

if *retryMaxElapsedTimeMinutes == 0 {
*retryMaxElapsedTimeMinutes = 2
if *params.RetryMaxElapsedTimeMinutes == 0 {
*params.RetryMaxElapsedTimeMinutes = 2
}

if *maxFileSecretSizeBytes == 0 {
*maxFileSecretSizeBytes = 4000000
if *params.MaxFileSecretSizeBytes == 0 {
*params.MaxFileSecretSizeBytes = 4000000
}

if strings.TrimSpace(*separator) == "" {
*separator = "/"
if strings.TrimSpace(*params.Separator) == "" {
*params.Separator = "/"
}

*apiUrl = strings.TrimSpace(*apiUrl)
*params.ApiUrl = strings.TrimSpace(*params.ApiUrl)

err := ValidateURL(*apiUrl)
err := ValidateURL(*params.ApiUrl)
if err != nil {
logger.Error(err.Error())
params.Logger.Error(err.Error())
return err
}

validate = validator.New(validator.WithRequiredStructEnabled())

userInput := &UserInputValidaton{
ClientId: clientId,
ClientSecret: clientSecret,
ApiUrl: *apiUrl,
ClientTimeOutinSeconds: clientTimeOutinSeconds,
Separator: *separator,
MaxFileSecretSizeBytes: *maxFileSecretSizeBytes,
ClientId: params.ClientID,
ClientSecret: params.ClientSecret,
ApiUrl: *params.ApiUrl,
ClientTimeOutinSeconds: params.ClientTimeOutInSeconds,
Separator: *params.Separator,
MaxFileSecretSizeBytes: *params.MaxFileSecretSizeBytes,
}

if !verifyCa {
logger.Warn("verifyCa=false is insecure, instructs not to verify the certificate authority.")
if !params.VerifyCa {
params.Logger.Warn("verifyCa=false is insecure, instructs not to verify the certificate authority.")
}

err = validate.Struct(userInput)
if err != nil {
logger.Error(err.Error())
params.Logger.Error(err.Error())
return err
}

message := ""

if certificate != "" && certificate_key != "" {
if params.Certificate != "" && params.CertificateKey != "" {

certificateLengthInBits := utf8.RuneCountInString(certificate) * 8
certificateLengthInBits := utf8.RuneCountInString(params.Certificate) * 8

if certificateLengthInBits > 32768 {
message = "invalid length for certificate, the maximum size is 32768 bits"
logger.Error(message)
params.Logger.Error(message)
return errors.New(message)
}

certificateKeyLengthInBits := utf8.RuneCountInString(certificate_key) * 8
certificateKeyLengthInBits := utf8.RuneCountInString(params.CertificateKey) * 8

if certificateKeyLengthInBits > 32768 {
message = "invalid length for certificate key, the maximum size is 32768 bits"
logger.Error(message)
params.Logger.Error(message)
return errors.New(message)
}

if !strings.HasPrefix(certificate, "-----BEGIN CERTIFICATE-----") || !strings.HasSuffix(certificate, "-----END CERTIFICATE-----") {
if !strings.HasPrefix(params.Certificate, "-----BEGIN CERTIFICATE-----") || !strings.HasSuffix(params.Certificate, "-----END CERTIFICATE-----") {
message = "invalid certificate content, must contain BEGIN and END CERTIFICATE"
logger.Error(message)
params.Logger.Error(message)
return errors.New(message)
}

if !strings.HasPrefix(certificate_key, "-----BEGIN PRIVATE KEY-----") || !strings.HasSuffix(certificate_key, "-----END PRIVATE KEY-----") {
if !strings.HasPrefix(params.CertificateKey, "-----BEGIN PRIVATE KEY-----") || !strings.HasSuffix(params.CertificateKey, "-----END PRIVATE KEY-----") {
message = "invalid certificate key content, must contain BEGIN and END PRIVATE KEY"
logger.Error(message)
params.Logger.Error(message)
return errors.New(message)
}

}

message = fmt.Sprintf("Library settings: ClientId=%v, ApiUrl=%v, ClientTimeOutinSeconds=%v, Separator=%v, VerifyCa=%v, MaxFileSecretSizeBytes=%v, UsingCertificate=%v", userInput.ClientId, userInput.ApiUrl, userInput.ClientTimeOutinSeconds, userInput.Separator, verifyCa, userInput.MaxFileSecretSizeBytes, certificate != "")
logger.Debug(message)
message = fmt.Sprintf("Library settings: ClientId=%v, ApiUrl=%v, ClientTimeOutinSeconds=%v, Separator=%v, VerifyCa=%v, MaxFileSecretSizeBytes=%v, UsingCertificate=%v", userInput.ClientId, userInput.ApiUrl, userInput.ClientTimeOutinSeconds, userInput.Separator, params.VerifyCa, userInput.MaxFileSecretSizeBytes, params.Certificate != "")
params.Logger.Debug(message)
return nil
}

Expand Down
17 changes: 16 additions & 1 deletion performancetest/PerformanceTest.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,23 @@ func callPasswordSafeAPI() {
retryMaxElapsedTimeMinutes := 15
maxFileSecretSizeBytes := 5000000

// Create an instance of ValidationParams
params := utils.ValidationParams{
ClientID: clientId,
ClientSecret: clientSecret,
ApiUrl: &apiUrl,
ClientTimeOutInSeconds: clientTimeOutInSeconds,
Separator: &separator,
VerifyCa: verifyCa,
Logger: zapLogger,
Certificate: certificate,
CertificateKey: certificateKey,
RetryMaxElapsedTimeMinutes: &retryMaxElapsedTimeMinutes,
MaxFileSecretSizeBytes: &maxFileSecretSizeBytes,
}

// validate inputs
errorsInInputs := utils.ValidateInputs(clientId, clientSecret, &apiUrl, clientTimeOutInSeconds, &separator, verifyCa, zapLogger, certificate, certificateKey, &retryMaxElapsedTimeMinutes, &maxFileSecretSizeBytes)
errorsInInputs := utils.ValidateInputs(params)
if errorsInInputs != nil {
return
}
Expand Down

0 comments on commit 335b81a

Please sign in to comment.