From 59ccfe266a8e2d4771d136492b76c17299091511 Mon Sep 17 00:00:00 2001 From: Yussuf Shaikh Date: Mon, 10 Jan 2022 12:34:31 +0530 Subject: [PATCH] Revamp session code to include URL Signed-off-by: Yussuf Shaikh --- clients/instance/ibm-pi-helper.go | 3 +- clients/instance/ibm-pi-instance.go | 2 +- clients/instance/ibm-pi-key.go | 9 +- clients/instance/ibm-pi-tenant.go | 2 +- examples/cloud-connection/main.go | 21 ++- examples/dhcp/main.go | 21 ++- examples/images/main.go | 21 ++- examples/instance/main.go | 21 ++- examples/key/main.go | 22 ++- examples/key_authenticator/main.go | 73 -------- examples/network/main.go | 22 ++- examples/snapshot/main.go | 24 ++- examples/storage_capacity_pools/main.go | 21 ++- examples/volume/main.go | 21 ++- examples/vpn/main.go | 21 ++- go.mod | 4 +- go.sum | 10 +- helpers/env.go | 6 + helpers/env_test.go | 86 ++++++++++ ibmpisession/ibmpowersession.go | 190 -------------------- ibmpisession/session.go | 104 +++++++++++ ibmpisession/session_test.go | 219 ++++++++++++++++++++++++ ibmpisession/utils.go | 66 +++++++ ibmpisession/utils_test.go | 125 ++++++++++++++ 24 files changed, 815 insertions(+), 299 deletions(-) delete mode 100644 examples/key_authenticator/main.go create mode 100644 helpers/env_test.go delete mode 100644 ibmpisession/ibmpowersession.go create mode 100644 ibmpisession/session.go create mode 100644 ibmpisession/session_test.go create mode 100644 ibmpisession/utils.go create mode 100644 ibmpisession/utils_test.go diff --git a/clients/instance/ibm-pi-helper.go b/clients/instance/ibm-pi-helper.go index 8da5da24..72f1f8cf 100644 --- a/clients/instance/ibm-pi-helper.go +++ b/clients/instance/ibm-pi-helper.go @@ -21,11 +21,10 @@ type IBMPIClient struct { // NewIBMPIClient ... func NewIBMPIClient(ctx context.Context, sess *ibmpisession.IBMPISession, cloudInstanceID string) *IBMPIClient { - authInfo := ibmpisession.NewAuth(sess, cloudInstanceID) return &IBMPIClient{ session: sess, cloudInstanceID: cloudInstanceID, - authInfo: authInfo, + authInfo: sess.AuthInfo(cloudInstanceID), ctx: ctx, } } diff --git a/clients/instance/ibm-pi-instance.go b/clients/instance/ibm-pi-instance.go index ef8a7bd9..4a7ba31e 100644 --- a/clients/instance/ibm-pi-instance.go +++ b/clients/instance/ibm-pi-instance.go @@ -57,7 +57,7 @@ func (f *IBMPIInstanceClient) Create(body *models.PVMInstanceCreate) (*models.PV params := p_cloud_p_vm_instances.NewPcloudPvminstancesPostParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). WithCloudInstanceID(f.cloudInstanceID).WithBody(body) - postok, postcreated, postAccepted, err := f.session.Power.PCloudpVMInstances.PcloudPvminstancesPost(params, ibmpisession.NewAuth(f.session, f.cloudInstanceID)) + postok, postcreated, postAccepted, err := f.session.Power.PCloudpVMInstances.PcloudPvminstancesPost(params, f.authInfo) if err != nil { return nil, fmt.Errorf("failed to Create PVM Instance :%w", err) } diff --git a/clients/instance/ibm-pi-key.go b/clients/instance/ibm-pi-key.go index 99200283..0b51e667 100644 --- a/clients/instance/ibm-pi-key.go +++ b/clients/instance/ibm-pi-key.go @@ -26,7 +26,7 @@ func NewIBMPIKeyClient(ctx context.Context, sess *ibmpisession.IBMPISession, clo // Get Key... func (f *IBMPIKeyClient) Get(id string) (*models.SSHKey, error) { - var tenantid = f.session.UserAccount + var tenantid = f.session.Options.UserAccount params := p_cloud_tenants_ssh_keys.NewPcloudTenantsSshkeysGetParams(). WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut). WithTenantID(tenantid).WithSshkeyName(id) @@ -42,7 +42,7 @@ func (f *IBMPIKeyClient) Get(id string) (*models.SSHKey, error) { // GetAll Information about all the PVM Instances for a Client func (f *IBMPIKeyClient) GetAll() (*models.SSHKeys, error) { - var tenantid = f.session.UserAccount + var tenantid = f.session.Options.UserAccount params := p_cloud_tenants_ssh_keys.NewPcloudTenantsSshkeysGetallParams(). WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut). WithTenantID(tenantid) @@ -58,9 +58,10 @@ func (f *IBMPIKeyClient) GetAll() (*models.SSHKeys, error) { // Create PI Key ... func (f *IBMPIKeyClient) Create(body *models.SSHKey) (*models.SSHKey, error) { + var tenantid = f.session.Options.UserAccount params := p_cloud_tenants_ssh_keys.NewPcloudTenantsSshkeysPostParams(). WithContext(f.ctx).WithTimeout(helpers.PICreateTimeOut). - WithTenantID(f.session.UserAccount).WithBody(body) + WithTenantID(tenantid).WithBody(body) postok, postcreated, err := f.session.Power.PCloudTenantsSSHKeys.PcloudTenantsSshkeysPost(params, f.authInfo) if err != nil { return nil, fmt.Errorf(errors.CreatePIKeyOperationFailed, err) @@ -76,7 +77,7 @@ func (f *IBMPIKeyClient) Create(body *models.SSHKey) (*models.SSHKey, error) { // Delete ... func (f *IBMPIKeyClient) Delete(id string) error { - var tenantid = f.session.UserAccount + var tenantid = f.session.Options.UserAccount params := p_cloud_tenants_ssh_keys.NewPcloudTenantsSshkeysDeleteParams(). WithContext(f.ctx).WithTimeout(helpers.PIDeleteTimeOut). WithTenantID(tenantid).WithSshkeyName(id) diff --git a/clients/instance/ibm-pi-tenant.go b/clients/instance/ibm-pi-tenant.go index 5945330a..a90e5e7b 100644 --- a/clients/instance/ibm-pi-tenant.go +++ b/clients/instance/ibm-pi-tenant.go @@ -41,7 +41,7 @@ func (f *IBMPITenantClient) Get(tenantid string) (*models.Tenant, error) { func (f *IBMPITenantClient) GetSelfTenant() (*models.Tenant, error) { params := p_cloud_tenants.NewPcloudTenantsGetParams(). WithContext(f.ctx).WithTimeout(helpers.PIGetTimeOut). - WithTenantID(f.session.UserAccount) + WithTenantID(f.session.Options.UserAccount) resp, err := f.session.Power.PCloudTenants.PcloudTenantsGet(params, f.authInfo) if err != nil { return nil, fmt.Errorf("failed to get self tenant with error %w", err) diff --git a/examples/cloud-connection/main.go b/examples/cloud-connection/main.go index 6b947d99..2ebfe542 100644 --- a/examples/cloud-connection/main.go +++ b/examples/cloud-connection/main.go @@ -9,6 +9,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) const ( @@ -22,14 +23,30 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // Cloud connection inputs name := " < NAME OF THE CONNECTION > " piID := " < POWER INSTANCE ID > " var speed int64 = 5000 - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/dhcp/main.go b/examples/dhcp/main.go index 4ebddf1a..60792d58 100644 --- a/examples/dhcp/main.go +++ b/examples/dhcp/main.go @@ -6,6 +6,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -15,12 +16,28 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // dhcp inputs piID := " < POWER INSTANCE ID > " - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/images/main.go b/examples/images/main.go index 32525f35..40b51521 100644 --- a/examples/images/main.go +++ b/examples/images/main.go @@ -8,6 +8,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -17,14 +18,30 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // Image inputs piID := " < POWER INSTANCE ID > " name := " < NAME OF THE IMAGE > " image := " " - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/instance/main.go b/examples/instance/main.go index 523ed7e9..f8c7447c 100644 --- a/examples/instance/main.go +++ b/examples/instance/main.go @@ -7,6 +7,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -16,7 +17,7 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // volume inputs name := " < NAME OF THE volume > " @@ -32,7 +33,23 @@ func main() { procType := "shared" sysType := "s922" - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/key/main.go b/examples/key/main.go index 9c0a449d..3de20170 100644 --- a/examples/key/main.go +++ b/examples/key/main.go @@ -7,6 +7,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -16,14 +17,31 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // ssh inputs name := " < NAME OF THE ssh > " piID := " < POWER INSTANCE ID > " ssh := " " - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/key_authenticator/main.go b/examples/key_authenticator/main.go deleted file mode 100644 index 512f43e7..00000000 --- a/examples/key_authenticator/main.go +++ /dev/null @@ -1,73 +0,0 @@ -package main - -import ( - "context" - "log" - - v "github.com/IBM-Cloud/power-go-client/clients/instance" - ps "github.com/IBM-Cloud/power-go-client/ibmpisession" - "github.com/IBM-Cloud/power-go-client/power/models" - "github.com/IBM/go-sdk-core/v5/core" -) - -func main() { - - //session Inputs - region := " < REGION > " - zone := " < ZONE > " - accountID := " < ACCOUNT ID > " - - // ssh inputs - name := " < NAME OF THE ssh > " - piID := " < POWER INSTANCE ID > " - ssh := " " - - // Create the authenticator - authenticator := &core.IamAuthenticator{ - ApiKey: " < APIKEY > ", - } - - // Create the session options struct - options := &ps.PIOptions{ - Authenticator: authenticator, - UserAccount: accountID, - Region: region, - Zone: zone, - } - - // Construct the session service instance - session, err := ps.NewSession(options) - if err != nil { - log.Fatal(err) - } - powerClient := v.NewIBMPIKeyClient(context.Background(), session, piID) - if err != nil { - log.Fatal(err) - } - getAllResp, err := powerClient.GetAll() - if err != nil { - log.Fatal(err) - } - log.Printf("***************[0]****************** %+v \n", *getAllResp) - - body := &models.SSHKey{ - Name: &name, - SSHKey: &ssh, - } - createRespOk, err := powerClient.Create(body) - if err != nil { - log.Fatal(err) - } - log.Printf("***************[1]****************** %+v\n", *createRespOk) - - sshID := *createRespOk.Name - getResp, err := powerClient.Get(sshID) - if err != nil { - log.Fatal(err) - } - log.Printf("***************[2]****************** %+v \n", *getResp) - err = powerClient.Delete(sshID) - if err != nil { - log.Fatal(err) - } -} diff --git a/examples/network/main.go b/examples/network/main.go index d63616bc..74bae7c6 100644 --- a/examples/network/main.go +++ b/examples/network/main.go @@ -11,6 +11,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -20,7 +21,7 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // network public vlan inputs // name := " < NAME OF THE network > " @@ -39,7 +40,24 @@ func main() { gateway, startIP, endIP := generateIPData(cidr) jumbo := false - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/snapshot/main.go b/examples/snapshot/main.go index dd967c2a..3bcd44f7 100644 --- a/examples/snapshot/main.go +++ b/examples/snapshot/main.go @@ -7,6 +7,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -16,16 +17,30 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region+".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" piID := " < POWER INSTANCE ID > " instance_id := " < INSTANCE ID > " snap_name := " < SNAPSHOT NAME > " description := " < DESCRIPTION > " - snapshotBody := &models.SnapshotCreate{Name: &snap_name, Description: description} - - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } @@ -35,6 +50,7 @@ func main() { log.Fatal(err) } + snapshotBody := &models.SnapshotCreate{Name: &snap_name, Description: description} createRespSnapOk, err := powerClient.CreatePvmSnapShot(instance_id, snapshotBody) if err != nil { log.Fatal(err) diff --git a/examples/storage_capacity_pools/main.go b/examples/storage_capacity_pools/main.go index 68fbcced..8db0271b 100644 --- a/examples/storage_capacity_pools/main.go +++ b/examples/storage_capacity_pools/main.go @@ -6,6 +6,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -15,14 +16,30 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region + ".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // pool inputs piID := " < POWER INSTANCE ID > " storageType := "tier1" storagePool := "Tier1-Flash-2" - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/volume/main.go b/examples/volume/main.go index a1ed0bf5..aabfcfd8 100644 --- a/examples/volume/main.go +++ b/examples/volume/main.go @@ -7,6 +7,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) func main() { @@ -16,7 +17,7 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region + ".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // volume inputs piID := " < POWER INSTANCE ID > " @@ -25,7 +26,23 @@ func main() { vtype := "tier1" sharable := true - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/examples/vpn/main.go b/examples/vpn/main.go index 65db16f3..2774011b 100644 --- a/examples/vpn/main.go +++ b/examples/vpn/main.go @@ -9,6 +9,7 @@ import ( v "github.com/IBM-Cloud/power-go-client/clients/instance" ps "github.com/IBM-Cloud/power-go-client/ibmpisession" "github.com/IBM-Cloud/power-go-client/power/models" + "github.com/IBM/go-sdk-core/v5/core" ) const ( @@ -23,7 +24,7 @@ func main() { region := " < REGION > " zone := " < ZONE > " accountID := " < ACCOUNT ID > " - //os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", region + ".power-iaas.test.cloud.ibm.com") + url := region + ".power-iaas.test.cloud.ibm.com" // VPN inputs name := " < NAME OF THE VPN CONNECTION > " @@ -32,7 +33,23 @@ func main() { ipsecPolicyName := " < NAME OF THE IPSEC POLICY > " networks := []string{" < NAME OF THE NETWORK > "} - session, err := ps.New(token, region, true, accountID, zone) + authenticator := &core.BearerTokenAuthenticator{ + BearerToken: token, + } + // authenticator := &core.IamAuthenticator{ + // ApiKey: "< API KEY >", + // // Uncomment for test environment + // URL: "https://iam.test.cloud.ibm.com", + // } + // Create the session + options := &ps.IBMPIOptions{ + Authenticator: authenticator, + UserAccount: accountID, + Zone: zone, + URL: url, + Debug: true, + } + session, err := ps.NewIBMPISession(options) if err != nil { log.Fatal(err) } diff --git a/go.mod b/go.mod index 22ab4883..15887764 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,11 @@ module github.com/IBM-Cloud/power-go-client go 1.13 require ( - github.com/IBM/go-sdk-core/v5 v5.8.0 + github.com/IBM/go-sdk-core/v5 v5.9.1 github.com/apparentlymart/go-cidr v1.1.0 github.com/go-openapi/errors v0.20.1 github.com/go-openapi/runtime v0.21.0 - github.com/go-openapi/strfmt v0.21.0 + github.com/go-openapi/strfmt v0.21.1 github.com/go-openapi/swag v0.19.15 github.com/go-openapi/validate v0.20.3 ) diff --git a/go.sum b/go.sum index bd6a11be..dfa88129 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,6 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/IBM/go-sdk-core/v5 v5.8.0 h1:Bn9BxTaKYKWpd+BDpVsL6XOOJl4QDgxux4gSdWi31vE= -github.com/IBM/go-sdk-core/v5 v5.8.0/go.mod h1:+YbdhrjCHC84ls4MeBp+Hj4NZCni+tDAc0XQUqRO9Jc= +github.com/IBM/go-sdk-core/v5 v5.9.1 h1:06pXbD9Rgmqqe2HA5YAeQbB4eYRRFgIoOT+Kh3cp1zo= +github.com/IBM/go-sdk-core/v5 v5.9.1/go.mod h1:axE2JrRq79gIJTjKPBwV6gWHswvVptBjbcvvCPIxARM= github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= @@ -104,8 +104,9 @@ github.com/go-openapi/strfmt v0.19.5/go.mod h1:eftuHTlB/dI8Uq8JJOyRlieZf+WkkxUuk github.com/go-openapi/strfmt v0.19.11/go.mod h1:UukAYgTaQfqJuAFlNxxMWNvMYiwiXtLsF2VwmoFtbtc= github.com/go-openapi/strfmt v0.20.0/go.mod h1:UukAYgTaQfqJuAFlNxxMWNvMYiwiXtLsF2VwmoFtbtc= github.com/go-openapi/strfmt v0.20.2/go.mod h1:43urheQI9dNtE5lTZQfuFJvjYJKPrxicATpEfZwHUNk= -github.com/go-openapi/strfmt v0.21.0 h1:hX2qEZKmYks+t0hKeb4VTJpUm2UYsdL3+DCid5swxIs= github.com/go-openapi/strfmt v0.21.0/go.mod h1:ZRQ409bWMj+SOgXofQAGTIo2Ebu72Gs+WaRADcS5iNg= +github.com/go-openapi/strfmt v0.21.1 h1:G6s2t5V5kGCHLVbSdZ/6lI8Wm4OzoPFkc3/cjAsKQrM= +github.com/go-openapi/strfmt v0.21.1/go.mod h1:I/XVKeLc5+MM5oPNN7P6urMOpuLXEcNrCX/rPGuWb0k= github.com/go-openapi/swag v0.17.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.18.0/go.mod h1:AByQ+nYG6gQg71GINrmuDXCPWdL640yX49/kXLo40Tg= github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= @@ -279,8 +280,9 @@ go.mongodb.org/mongo-driver v1.4.3/go.mod h1:WcMNYLx/IlOxLe6JRJiv2uXuCz6zBLndR4S go.mongodb.org/mongo-driver v1.4.4/go.mod h1:WcMNYLx/IlOxLe6JRJiv2uXuCz6zBLndR4SoGjYphSc= go.mongodb.org/mongo-driver v1.4.6/go.mod h1:WcMNYLx/IlOxLe6JRJiv2uXuCz6zBLndR4SoGjYphSc= go.mongodb.org/mongo-driver v1.5.1/go.mod h1:gRXCHX4Jo7J0IJ1oDQyUxF7jfy19UfxniMS4xxMmUqw= -go.mongodb.org/mongo-driver v1.7.3 h1:G4l/eYY9VrQAK/AUgkV0koQKzQnyddnWxrd/Etf0jIs= go.mongodb.org/mongo-driver v1.7.3/go.mod h1:NqaYOwnXWr5Pm7AOpO5QFxKJ503nbMse/R79oO62zWg= +go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9VI= +go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190320223903-b7391e95e576/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= diff --git a/helpers/env.go b/helpers/env.go index 3b65d26b..64051390 100644 --- a/helpers/env.go +++ b/helpers/env.go @@ -11,3 +11,9 @@ func EnvFallBack(envs []string, defaultValue string) string { } return defaultValue } + +// GetPowerEndPoint +func GetPowerEndPoint(region string) string { + defaultURL := region + ".power-iaas.cloud.ibm.com" + return EnvFallBack([]string{"IBMCLOUD_POWER_API_ENDPOINT"}, defaultURL) +} diff --git a/helpers/env_test.go b/helpers/env_test.go new file mode 100644 index 00000000..3fe1f5af --- /dev/null +++ b/helpers/env_test.go @@ -0,0 +1,86 @@ +package helpers + +import ( + "os" + "testing" +) + +func TestEnvFallBack(t *testing.T) { + os.Setenv("MY_ENV_VAR", "hello") + type args struct { + envs []string + defaultValue string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "Get Value for Known Environment Variable", + args: args{[]string{"MY_ENV_VAR"}, "default"}, + want: "hello", + }, + { + name: "Get Value for Unknown Environment Variable", + args: args{[]string{"NO_ENV_VAR"}, "default"}, + want: "default", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := EnvFallBack(tt.args.envs, tt.args.defaultValue); got != tt.want { + t.Errorf("EnvFallBack() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetPowerEndPoint(t *testing.T) { + type args struct { + region string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "Get Value from Environment Variable", + args: args{"dal"}, + want: "dal.power-iaas.cloud.ibm.com", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetPowerEndPoint(tt.args.region); got != tt.want { + t.Errorf("GetPowerEndPoint() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestGetPowerEndPointFromEnv(t *testing.T) { + os.Setenv("IBMCLOUD_POWER_API_ENDPOINT", "test.cloud.ibm.com") + type args struct { + region string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "Get Value from Environment Variable", + args: args{"dal"}, + want: "test.cloud.ibm.com", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetPowerEndPoint(tt.args.region); got != tt.want { + t.Errorf("GetPowerEndPoint() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/ibmpisession/ibmpowersession.go b/ibmpisession/ibmpowersession.go deleted file mode 100644 index 0d2150b8..00000000 --- a/ibmpisession/ibmpowersession.go +++ /dev/null @@ -1,190 +0,0 @@ -/* -Code to call the IBM IAM Services and get a session object that will be used by the Power Colo Code. - - -*/ - -package ibmpisession - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "strings" - - "github.com/go-openapi/runtime" - httptransport "github.com/go-openapi/runtime/client" - "github.com/go-openapi/strfmt" - - "github.com/IBM-Cloud/power-go-client/power/client" - "github.com/IBM-Cloud/power-go-client/power/models" - "github.com/IBM-Cloud/power-go-client/utils" - "github.com/IBM/go-sdk-core/v5/core" -) - -// IBMPISession ... -type IBMPISession struct { - IAMToken string - IMSToken string - Power *client.PowerIaasAPI - UserAccount string - Region string - Zone string - Authenticator core.Authenticator -} - -// PIOptions -type PIOptions struct { - // Enable/Disable http transport debugging log - Debug bool - - // Account id of the Power Cloud Service Instance - // Required - UserAccount string - - // Region of the Power Cloud Service Instance - // Required - Region string - - // Zone of the Power Cloud Service Instance; Use Region if not set - Zone string - - // The authenticator used to configure the appropriate type of authentication - // Required - Authenticator core.Authenticator -} - -func powerJSONConsumer() runtime.Consumer { - return runtime.ConsumerFunc(func(reader io.Reader, data interface{}) error { - buf := new(bytes.Buffer) - _, err := buf.ReadFrom(reader) - if err != nil { - return err - } - b := buf.Bytes() - if b != nil { - dec := json.NewDecoder(bytes.NewReader(b)) - dec.UseNumber() // preserve number formats - err = dec.Decode(data) - } - if string(b) == "null" || err != nil { - errorRecord, _ := data.(*models.Error) - log.Printf("The errorrecord is %s ", errorRecord.Error) - return nil - } - return err - }) -} - -// Create a IBMPISession -func NewSession(options *PIOptions) (*IBMPISession, error) { - newSession := &IBMPISession{ - UserAccount: options.UserAccount, - Region: options.Region, - Zone: options.Zone, - Authenticator: options.Authenticator, - } - - session, err := process(newSession, options.Debug) - if err != nil { - return nil, err - } - - return session, nil -} - -// New ... -// - deprecated: New function can be used, but is slated to become `obsolete`, Instead try using NewSession function. -func New(iamtoken, region string, debug bool, useraccount string, zone string) (*IBMPISession, error) { - //fmt.Println("Warning - New function is slated to become `obsolete`, Instead try using NewSession function.") - session := &IBMPISession{ - IAMToken: iamtoken, - UserAccount: useraccount, - Region: region, - Zone: zone, - } - - session, err := process(session, debug) - if err != nil { - return nil, err - } - return session, nil -} - -// Assign appropriate PowerIaas client to the session after appropriate evaluation -func process(session *IBMPISession, debug bool) (*IBMPISession, error) { - http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: false} - apiEndpointURL := utils.GetPowerEndPoint(session.Region) - transport := httptransport.New(apiEndpointURL, "/", []string{"https"}) - if debug { - transport.Debug = debug - } - transport.SetLogger(IBMPILogger{}) - transport.Consumers[runtime.JSONMime] = powerJSONConsumer() - session.Power = client.New(transport, nil) - return session, nil -} - -// Fetch Authorization token -// Authenticate using Authenticator if set in the session -// Otherwise return IAMToken set in the session -func fetchAuthorizationData(s *IBMPISession) (string, error) { - var authdata = s.IAMToken - if s.Authenticator != nil { - req := &http.Request{ - Header: make(http.Header), - } - if err := s.Authenticator.Authenticate(req); err != nil { - return "", err - } - authdata = req.Header.Get("Authorization") - } - return authdata, nil -} - -// NewAuth ... -func NewAuth(sess *IBMPISession, cloudInstanceID string) runtime.ClientAuthInfoWriter { - var crndata = crnBuilder(cloudInstanceID, sess.UserAccount, sess.Region, sess.Zone) - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - authdata, err := fetchAuthorizationData(sess) - if err != nil { - return err - } - if err := r.SetHeaderParam("Authorization", authdata); err != nil { - return err - } - return r.SetHeaderParam("CRN", crndata) - }) -} - -// BearerTokenAndCRN ... -func BearerTokenAndCRN(session *IBMPISession, crn string) runtime.ClientAuthInfoWriter { - return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { - authdata, err := fetchAuthorizationData(session) - if err != nil { - return err - } - if err := r.SetHeaderParam("Authorization", authdata); err != nil { - return err - } - return r.SetHeaderParam("CRN", crn) - }) -} - -// crnBuilder ... -func crnBuilder(cloudInstanceID, useraccount, region, zone string) string { - var service string - if strings.Contains(utils.GetPowerEndPoint(region), ".power-iaas.cloud.ibm.com") { - service = "bluemix" - } else { - service = "staging" - } - if zone == "" { - zone = region - } - return fmt.Sprintf("crn:v1:%s:public:power-iaas:%s:a/%s:%s::", service, zone, useraccount, cloudInstanceID) -} diff --git a/ibmpisession/session.go b/ibmpisession/session.go new file mode 100644 index 00000000..6d60bd87 --- /dev/null +++ b/ibmpisession/session.go @@ -0,0 +1,104 @@ +package ibmpisession + +import ( + "fmt" + "strings" + + "github.com/go-openapi/runtime" + "github.com/go-openapi/strfmt" + + "github.com/IBM-Cloud/power-go-client/helpers" + "github.com/IBM-Cloud/power-go-client/power/client" + "github.com/IBM/go-sdk-core/v5/core" +) + +// IBMPISession ... +type IBMPISession struct { + CRNFormat string + Power *client.PowerIaasAPI + Options *IBMPIOptions +} + +// PIOptions +type IBMPIOptions struct { + // The authenticator implementation to be used by the + // service instance to authenticate outbound requests + // Required + Authenticator core.Authenticator + + // Enable/Disable http transport debugging log + Debug bool + + // Region of the Power Cloud Service Instance + // For generating the default host + // Required when URL is not provided else ignored + Region string + + // Power Virtual Server host or URL + // This will be used instead of generating the default host + // eg: dal.power-iaas.cloud.ibm.com + // Required when Region is not provided + URL string + + // Account id of the Power Cloud Service Instance + // It will be part of the CRN string + // Required + UserAccount string + + // Zone of the Power Cloud Service Instance + // It will be part of the CRN string + // Required + Zone string +} + +// Create a IBMPISession +func NewIBMPISession(o *IBMPIOptions) (*IBMPISession, error) { + if core.IsNil(o) { + return nil, fmt.Errorf("options is required") + } + + if core.IsNil(o.Authenticator) { + return nil, fmt.Errorf("option Authenticator is required") + } + + if o.UserAccount == "" { + return nil, fmt.Errorf("option UserAccount is required") + } + + if o.Zone == "" { + return nil, fmt.Errorf("option Zone is required") + } + + if o.URL == "" && o.Region == "" { + return nil, fmt.Errorf("atleast one of Region or URL is required") + } + + serviceURL := o.URL + if serviceURL == "" { + serviceURL = helpers.GetPowerEndPoint(o.Region) + } + + // We need just the server host from the URL + serviceURL = strings.TrimPrefix(serviceURL, "https://") + serviceURL = strings.TrimPrefix(serviceURL, "http://") + + return &IBMPISession{ + CRNFormat: crnBuilder(o.UserAccount, o.Zone, serviceURL), + Options: o, + Power: getPIClient(o.Debug, serviceURL), + }, nil +} + +// authInfo ... +func (s *IBMPISession) AuthInfo(cloudInstanceID string) runtime.ClientAuthInfoWriter { + return runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, _ strfmt.Registry) error { + auth, err := fetchAuthorizationData(s.Options.Authenticator) + if err != nil { + return err + } + if err := r.SetHeaderParam("Authorization", auth); err != nil { + return err + } + return r.SetHeaderParam("CRN", fmt.Sprintf(s.CRNFormat, cloudInstanceID)) + }) +} diff --git a/ibmpisession/session_test.go b/ibmpisession/session_test.go new file mode 100644 index 00000000..8914bc26 --- /dev/null +++ b/ibmpisession/session_test.go @@ -0,0 +1,219 @@ +package ibmpisession + +import ( + "fmt" + "testing" + + "github.com/IBM/go-sdk-core/v5/core" + "github.com/go-openapi/runtime" +) + +func TestNewIBMPISession(t *testing.T) { + bearerTokenAuth := &core.BearerTokenAuthenticator{BearerToken: "sample"} + o1 := &IBMPIOptions{ + Authenticator: bearerTokenAuth, + UserAccount: "1234", + Region: "dal", + Zone: "dal12", + URL: "dal.power-iaas.test.cloud.ibm.com", + } + type args struct { + o *IBMPIOptions + } + tests := []struct { + name string + args args + want *IBMPISession + wantErr bool + }{ + { + name: "Simple BearerTokenAuthenticator", + args: args{ + o: o1, + }, + want: &IBMPISession{ + Options: o1, + CRNFormat: "crn:v1:staging:public:power-iaas:dal12:a/1234:%s::", + }, + }, + { + name: "Without Options", + args: args{ + o: nil, + }, + wantErr: true, + }, + { + name: "Invalid Authenticator", + args: args{ + o: &IBMPIOptions{ + Authenticator: &core.BearerTokenAuthenticator{}, + }, + }, + wantErr: true, + }, + { + name: "Without Authenticator", + args: args{ + o: &IBMPIOptions{ + UserAccount: "1234", + Zone: "dal12", + URL: "dal.power-iaas.test.cloud.ibm.com", + }, + }, + wantErr: true, + }, + { + name: "Without UserAccount", + args: args{ + o: &IBMPIOptions{ + Authenticator: bearerTokenAuth, + Zone: "dal12", + URL: "dal.power-iaas.test.cloud.ibm.com", + }, + }, + wantErr: true, + }, + { + name: "Without Zone", + args: args{ + o: &IBMPIOptions{ + Authenticator: bearerTokenAuth, + UserAccount: "1234", + URL: "dal.power-iaas.test.cloud.ibm.com", + }, + }, + wantErr: true, + }, + { + name: "Without URL and Region", + args: args{ + o: &IBMPIOptions{ + Authenticator: bearerTokenAuth, + UserAccount: "1234", + Zone: "dal12", + }, + }, + wantErr: true, + }, + { + name: "Without URL but with region", + args: args{ + o: &IBMPIOptions{ + Authenticator: bearerTokenAuth, + UserAccount: "1234", + Zone: "dal12", + Region: "dal", + }, + }, + want: &IBMPISession{ + Options: o1, + CRNFormat: "crn:v1:bluemix:public:power-iaas:dal12:a/1234:%s::", + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := NewIBMPISession(tt.args.o) + if (err != nil) != tt.wantErr { + t.Errorf("NewIBMPISession() error = %v, wantErr %v", err, tt.wantErr) + return + } + if same, msg := isIBMPISessionEqual(got, tt.want); !same { + t.Error(msg) + } + }) + } +} + +func isIBMPISessionEqual(x *IBMPISession, y *IBMPISession) (bool, string) { + if x == nil && y == nil { + return true, "" + } + if (x == nil && y != nil) || (x != nil && y == nil) { + return true, fmt.Sprintf("NewIBMPISession() = %v, want %v", x, y) + } + if x.Options.Authenticator != y.Options.Authenticator { + return false, fmt.Sprintf("NewIBMPISession() Authenticator = %v, want %v", x.Options.Authenticator, y.Options.Authenticator) + } + if x.CRNFormat != y.CRNFormat { + return false, fmt.Sprintf("NewIBMPISession() CRNFormat = %v, want %v", x.CRNFormat, y.CRNFormat) + } + return true, "" +} + +func TestIBMPISession_AuthInfo(t *testing.T) { + type args struct { + cloudInstanceID string + } + type wantHeaders struct { + auth string + crn string + } + tests := []struct { + name string + s *IBMPISession + args args + wantHeaders wantHeaders + wantErr bool + }{ + { + name: "Auth", + s: &IBMPISession{ + Options: &IBMPIOptions{ + Authenticator: &core.BearerTokenAuthenticator{BearerToken: "sample"}, + Zone: "dal12", + URL: "dal.power-iaas.test.cloud.ibm.com", + }, + CRNFormat: "crn...:%s::", + }, + args: args{ + cloudInstanceID: "1234", + }, + wantHeaders: wantHeaders{ + auth: "Bearer sample", + crn: "crn...:1234::", + }, + }, + { + name: "Incorrect Auth", + s: &IBMPISession{ + Options: &IBMPIOptions{ + Authenticator: &core.IamAuthenticator{ApiKey: "sample"}, + Zone: "dal12", + URL: "dal.power-iaas.test.cloud.ibm.com", + }, + CRNFormat: "crn...:%s::", + }, + args: args{ + cloudInstanceID: "1234", + }, + wantHeaders: wantHeaders{}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.s.AuthInfo(tt.args.cloudInstanceID) + if got == nil { + t.Errorf("NewAuth() = %v", got) + } + // Authenticate the request + r := &runtime.TestClientRequest{} + err := got.AuthenticateRequest(r, nil) + if (err != nil) != tt.wantErr { + t.Errorf("AuthInfo().AuthenticateRequest() error = %v, wantErr %v", err, tt.wantErr) + return + } + // Test the header values + auth := r.Headers.Get("Authorization") + if auth != tt.wantHeaders.auth { + t.Errorf("AuthInfo().AuthenticateRequest() Authorization = %v, want %v", auth, tt.wantHeaders.auth) + } + crn := r.Headers.Get("CRN") + if crn != tt.wantHeaders.crn { + t.Errorf("AuthInfo().AuthenticateRequest() CRN = %v, want %v", crn, tt.wantHeaders.crn) + } + }) + } +} diff --git a/ibmpisession/utils.go b/ibmpisession/utils.go new file mode 100644 index 00000000..4ce137ce --- /dev/null +++ b/ibmpisession/utils.go @@ -0,0 +1,66 @@ +package ibmpisession + +import ( + "bytes" + "crypto/tls" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/IBM-Cloud/power-go-client/power/client" + "github.com/IBM/go-sdk-core/v5/core" + "github.com/go-openapi/runtime" + httptransport "github.com/go-openapi/runtime/client" +) + +// fetchAuthorizationData Fetch Authorization token using the Authenticator +func fetchAuthorizationData(a core.Authenticator) (string, error) { + req := &http.Request{ + Header: make(http.Header), + } + if err := a.Authenticate(req); err != nil { + return "", err + } + return req.Header.Get("Authorization"), nil +} + +// crnBuilder Return string format to create CRN using the cloud instance id +// The result string will have crn data with a string placeholder to set the cloud instance id +// Usage: +// `crn := fmt.Sprintf(crnBuilder(useraccount, regionZone, host), )` +func crnBuilder(useraccount, zone, host string) string { + var service string + if strings.Contains(host, ".power-iaas.cloud.ibm.com") { + service = "bluemix" + } else { + service = "staging" + } + crn := fmt.Sprintf("crn:v1:%s:public:power-iaas:%s:a/%s:", service, zone, useraccount) + return crn + "%s::" +} + +func powerJSONConsumer() runtime.Consumer { + return runtime.ConsumerFunc(func(reader io.Reader, data interface{}) error { + buf := new(bytes.Buffer) + _, err := buf.ReadFrom(reader) + if err != nil { + return err + } + b := buf.Bytes() + dec := json.NewDecoder(bytes.NewReader(b)) + dec.UseNumber() // preserve number formats + return dec.Decode(data) + }) +} + +// getPIClient generates a PowerIaas client +func getPIClient(debug bool, host string) *client.PowerIaasAPI { + http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: false} + transport := httptransport.New(host, "/", []string{"https"}) + transport.Debug = debug + transport.SetLogger(IBMPILogger{}) + transport.Consumers[runtime.JSONMime] = powerJSONConsumer() + return client.New(transport, nil) +} diff --git a/ibmpisession/utils_test.go b/ibmpisession/utils_test.go new file mode 100644 index 00000000..cb3b5137 --- /dev/null +++ b/ibmpisession/utils_test.go @@ -0,0 +1,125 @@ +package ibmpisession + +import ( + "bytes" + "testing" + + "github.com/IBM/go-sdk-core/v5/core" +) + +func Test_fetchAuthorizationData(t *testing.T) { + type args struct { + a core.Authenticator + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + name: "Fetch Sample Bearer Token", + args: args{ + a: &core.BearerTokenAuthenticator{ + BearerToken: "sample", + }, + }, + want: "Bearer sample", + }, + { + name: "Fetch Incorrect IAM Token", + args: args{ + a: &core.IamAuthenticator{ + ApiKey: "sample", + }, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := fetchAuthorizationData(tt.args.a) + if (err != nil) != tt.wantErr { + t.Errorf("fetchAuthorizationData() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("fetchAuthorizationData() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_crnBuilder(t *testing.T) { + type args struct { + useraccount string + regionZone string + host string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "Generate for Prod", + args: args{"12345", "dal12", "dal.power-iaas.cloud.ibm.com"}, + want: "crn:v1:bluemix:public:power-iaas:dal12:a/12345:%s::", + }, + { + name: "Generate for Staging", + args: args{"12345", "dal12", "dal.power-iaas.test.cloud.ibm.com"}, + want: "crn:v1:staging:public:power-iaas:dal12:a/12345:%s::", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := crnBuilder(tt.args.useraccount, tt.args.regionZone, tt.args.host); got != tt.want { + t.Errorf("crnBuilder() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_powerJSONConsumer(t *testing.T) { + var data struct { + Name string + ID int + } + tests := []struct { + name string + json string + wantErr bool + }{ + { + name: "Simple powerJSONConsumer", + json: `{"name":"Somebody","id":1}`, + wantErr: false, + }, + { + name: "Null value", + json: "null", + wantErr: false, + }, + { + name: "Nil value", + json: "nil", + wantErr: true, + }, + { + name: "Empty value", + json: "", + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := powerJSONConsumer() + err := got.Consume(bytes.NewBuffer([]byte(tt.json)), &data) + if (err != nil) != tt.wantErr { + t.Errorf("powerJSONConsumer().Consume() error = %v, wantErr %v", err, tt.wantErr) + return + } + }) + } +}