### Install SDK via Go modules Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/getting_started.md Configure Git credentials for private repositories and download the SDK package. ```shell export GOPRIVATE=1 git config --global url."https://:@github.com".insteadOf "https://github.com" go get github.com/cyberark/idsec-sdk-golang ``` -------------------------------- ### Example Test Generation Command Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/README.md An example of using `make gene2e` to create a new test file for creating and deleting a safe. ```bash make gene2e SERVICE=pcloud/safes NAME=CreateAndDeleteSafe ``` -------------------------------- ### Test File Organization Example Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/CONTRIBUTING.md Illustrates the recommended directory structure for test files and utilities within a Go package. Place test files alongside source code and organize utilities in a 'testutils' directory. ```go pkg/example/ ├── example.go ├── example_test.go └── testutils/ ├── shared_mocks.go # Mock implementations for external dependencies ├── test_helpers.go # Helper functions for test setup and validation └── test_fixtures.go # Test data, constants, and sample inputs ``` -------------------------------- ### Create Cloud Access Policy Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Example of creating a cloud access policy for AWS accounts using the SDK. Ensure necessary imports and error handling are in place. ```go package main import ( "fmt" "github.com/cyberark/idsec-sdk-golang/v2/pkg/idsec/client" "github.com/cyberark/idsec-sdk-golang/v2/pkg/idsec/models/policycloudaccessmodels" ) func main() { // Assuming 'c' is an initialized idsec.Client c := client.NewClient(client.WithTenantURL("https://example.com"), client.WithAPIKey("your-api-key")) policy, err := c.PolicyCloudAccess().Create(policycloudaccessmodels.IdsecPolicyCloudAccess{ Name: "Example AWS Policy", Description: "Policy for accessing AWS resources", Enabled: true, Targets: policycloudaccessmodels.IdsecPolicyCloudAccessTargets{ ``` -------------------------------- ### Example Test Output Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/QUICKSTART.md This is an example of the expected output when running E2E tests, showing test execution progress and results. ```text === RUN TestListConnectors connectors_test.go:XX: isp authenticator created and authenticated connectors_test.go:XX: pvwa authenticator created and authenticated connectors_test.go:XX: E2E test context initialized successfully connectors_test.go:XX: ============================================================ connectors_test.go:XX: Test: List SIA Connectors connectors_test.go:XX: ============================================================ connectors_test.go:XX: Listing SIA connectors... connectors_test.go:XX: Found 0 connector(s) --- PASS: TestListConnectors (2.34s) ``` -------------------------------- ### Import and Configure OAuth2 Server Webapp Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md This example demonstrates how to authenticate to an ISP tenant, import an OAuth2 server webapp template, and configure its permissions using the CyberArk Identity SDK for Golang. Ensure you have set the IDSEC_SECRET environment variable. ```go package main import ( "encoding/json" "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" "github.com/cyberark/idsec-sdk-golang/pkg/common" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/identity" webappsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/identity/webapps/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } identityAPI, err := identity.NewIdsecIdentityAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } // Import the OAuth Server template and configure it as an example app, err := identityAPI.Webapps().Import( &webappsmodels.IdsecIdentityImportWebapp{ IdsecIdentityWebappAppsConfiguration: webappsmodels.IdsecIdentityWebappAppsConfiguration{ OAuthProfile: &webappsmodels.IdsecIdentityWebappOAuthProfile{ // #nosec G101 AllowedAuth: []string{ "ClientCreds", }, Audience: common.Ptr("company://audience"), Issuer: common.Ptr("mycompany.com"), KnownScopes: []webappsmodels.IdsecIdentityWebappOAuthScope{ { Scope: "scope1", Description: "Scope 1", }, }, TokenType: "JwtRS256", TokenLifetimeString: "0.05:00:00", }, }, TemplateName: "OAuth2Server", WebappName: common.Ptr("OAuth App"), ServiceName: common.Ptr("app_id"), }, ) if err != nil { panic(err) } appJson, err := json.MarshalIndent(app, "", " ") if err != nil { panic(err) } fmt.Printf("Imported App Result:\n%s\n", string(appJson)) // Configure permissions perms, err := identityAPI.Webapps().SetPermissions(&webappsmodels.IdsecIdentitySetWebappPermissions{ WebappID: app.WebappID, Grants: []webappsmodels.IdsecIdentityWebappGrant{ { Principal: "user@cyberark.cloud.12345", PrincipalType: "User", Rights: []string{ webappsmodels.GrantRightAdmin, webappsmodels.GrantRightGrant, webappsmodels.GrantRightView, webappsmodels.GrantRightViewDetail, webappsmodels.GrantRightExecute, webappsmodels.GrantRightAutomatic, webappsmodels.GrantRightDelete, }, }, }, }) if err != nil { panic(err) } permsJson, err := json.MarshalIndent(perms, "", " ") if err != nil { panic(err) } fmt.Printf("Set Permissions Result:\n%s\n", string(permsJson)) } ``` -------------------------------- ### Write a New E2E Test Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/QUICKSTART.md Create a new Go test file within the `tests/e2e` directory to write custom E2E tests. Use the `framework.Run` function to manage test context and setup. ```go //go:build e2e package myservice import ( "testing" "github.com/stretchr/testify/require" myservice "github.com/cyberark/idsec-sdk-golang/pkg/services/myservice" "github.com/cyberark/idsec-sdk-golang/tests/e2e/framework" ) func TestMyFeature(t *testing.T) { framework.Run(t, func(ctx *framework.TestContext) { // Get service service, err := ctx.API.MyService() require.NoError(t, err) // Test something result, err := service.ListItems() require.NoError(t, err) require.NotNil(t, result) }, myservice.ServiceConfig) } ``` -------------------------------- ### Define Function Documentation Format Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/CONTRIBUTING.md Standard template for documenting exported functions, including parameters, return values, and usage examples. ```go // FunctionName describes what the function does in one line. // // Provide a detailed description of the function's behavior, including any important // details about its implementation or usage patterns. // // Parameters: // - param1: Description of the parameter and its expected values // - param2: Description of the parameter and its constraints // - param3: Optional parameter description (use "nil for no limit" style) // // Returns description of what the function returns, including error conditions. // // Example: // result, err := FunctionName( // "example input", // 42, // &optionalParam, // ) // if err != nil { // // handle error // } func FunctionName(param1 string, param2 int, param3 *int) (ResultType, error) { ``` -------------------------------- ### Example Idsec Profile Configuration Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/howto/working_with_profiles.md JSON structure for defining authentication profiles. Place this file in the $HOME/.idsec/profiles directory. ```json { "profile_name": "idsec", "profile_description": "Default Idsec Profile", "auth_profiles": { "isp": { "username": "tina@cyberark.cloud.1234567", "auth_method": "identity", "auth_method_settings": { "identity_mfa_method": "email", "identity_mfa_interactive": true, "identity_application": null, "identity_url": null } } } } ``` -------------------------------- ### Example SCA JSON Configuration Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/sca/README.md A sample JSON configuration file for SCA E2E tests, demonstrating the structure for authentication and cloud access target details. This file contains non-secret data. ```json { "auth": { "method": "identity", "identity_url": "https://identity.example.com" }, "azure_cloudaccess": { "principal": { "principal_id": "user-id", "principal_name": "eva_user@tenant.example", "source_directory_name": "CyberArk Cloud Directory", "source_directory_id": "directory-id" }, "targets": { "targets": [ { "roleId": "role-id", "workspaceId": "workspace-id", "orgId": "organization-id", "workspaceType": "directory" } ] } } } ``` -------------------------------- ### Configure and Run E2E Tests Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/README.md Set environment variables for authentication (ISP and/or PVWA) and then run the E2E tests using `go test`. You can run all tests or target specific packages. ```bash # --- Option 1: Multi-auth (recommended) --- # Configure both ISP and PVWA credentials so all tests run: export IDSEC_E2E_ISP_USERNAME="serviceuser@tenant.cyberark.cloud.12345" export IDSEC_E2E_ISP_SECRET="your_isp_secret" export IDSEC_E2E_PVWA_USERNAME="your_pvwa_username" export IDSEC_E2E_PVWA_SECRET="your_pvwa_password" export IDSEC_E2E_PVWA_URL="https://pvwa.example.com" # --- Option 2: ISP-only --- export IDSEC_E2E_AUTH_EXPECT=isp export IDSEC_E2E_ISP_USERNAME="serviceuser@tenant.cyberark.cloud.12345" export IDSEC_E2E_ISP_SECRET="your_isp_secret" # --- Option 3: PVWA-only --- export IDSEC_E2E_AUTH_EXPECT=pvwa export IDSEC_E2E_PVWA_USERNAME="your_pvwa_username" export IDSEC_E2E_PVWA_SECRET="your_pvwa_password" export IDSEC_E2E_PVWA_URL="https://pvwa.example.com" # Run all E2E tests go test -tags=e2e -v ./tests/e2e/... # Run specific package go test -tags=e2e -v ./tests/e2e/pcloud/ ``` -------------------------------- ### Import and Configure AWS Webapp Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Demonstrates how to authenticate to an ISP tenant, import an AWS webapp template, and configure it with normal credentials. Requires setting up an ISP authentication profile and providing AWS account details. ```go package main import ( "encoding/json" "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" "github.com/cyberark/idsec-sdk-golang/pkg/common" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/identity" webappsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/identity/webapps/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } identityAPI, err := identity.NewIdsecIdentityAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } // Get the template and print it out template, err := identityAPI.Webapps().GetTemplate(&webappsmodels.IdsecIdentityGetWebappTemplate{ WebappTemplateName: "Amazon AWS", }) if err != nil { panic(err) } templateJson, err := json.MarshalIndent(template, "", " ") if err != nil { panic(err) } fmt.Printf("Webapp Template:\n%s\n", string(templateJson)) // Import the template and configure with the AWS Account importedWebapp, err := identityAPI.Webapps().Import(&webappsmodels.IdsecIdentityImportWebapp{ TemplateName: "Amazon AWS", WebappName: common.Ptr("AWS App Normal"), Description: common.Ptr("This is my imported AWS app"), IdsecIdentityWebappAppsConfiguration: webappsmodels.IdsecIdentityWebappAppsConfiguration{ AdditionalIdentifierValue: common.Ptr("123456789234"), UserNameStrategy: common.Ptr("Fixed"), Username: common.Ptr("awsuser"), Password: common.Ptr("mypass"), }, IdsecIdentityWebappPolicyConfiguration: webappsmodels.IdsecIdentityWebappPolicyConfiguration{ WebAppLoginType: common.Ptr("AuthenticationRule"), DefaultAuthProfile: common.Ptr("AlwaysAllowed"), AuthRules: &webappsmodels.IdsecIdentityWebappPolicyAuthRule{ Enabled: true, Type: "RowSet", UniqueKey: "Condition", Value: []webappsmodels.IdsecIdentityWebappPolicyAuthRuleConditions{ { Conditions: []webappsmodels.IdsecIdentityWebappPolicyAuthRuleCondition{ { Op: common.Ptr("OpInCorpIpRange"), Prop: common.Ptr("IpAddress"), }, }, ProfileId: common.Ptr("13e3bc1a-6ff7-4b7d-ae90-0ed21d3c393e"), }, }, }, }, }) if err != nil { panic(err) } importedWebappJson, err := json.MarshalIndent(importedWebapp, "", " ") if err != nil { panic(err) } fmt.Printf("Imported Webapp:\n%s\n", string(importedWebappJson)) // Import another template and configure with the AWS Account and Credentials from pCloud importedpCloudWebapp, err := identityAPI.Webapps().Import(&webappsmodels.IdsecIdentityImportWebapp{ TemplateName: "Amazon AWS", WebappName: common.Ptr("AWS App pCloud"), Description: common.Ptr("This is my imported AWS app"), IdsecIdentityWebappAppsConfiguration: webappsmodels.IdsecIdentityWebappAppsConfiguration{ AdditionalIdentifierValue: common.Ptr("123456789234"), UserNameStrategy: common.Ptr("Fixed"), Safe: common.Ptr("mysafe"), AccountName: common.Ptr("myaccount"), ExtAccountId: common.Ptr("123_456"), IsPrivilegedApp: common.Ptr(true), }, IdsecIdentityWebappPolicyConfiguration: webappsmodels.IdsecIdentityWebappPolicyConfiguration{ WebAppLoginType: common.Ptr("AuthenticationRule"), DefaultAuthProfile: common.Ptr("AlwaysAllowed"), AuthRules: &webappsmodels.IdsecIdentityWebappPolicyAuthRule{ Enabled: true, Type: "RowSet", UniqueKey: "Condition", Value: []webappsmodels.IdsecIdentityWebappPolicyAuthRuleConditions{ { Conditions: []webappsmodels.IdsecIdentityWebappPolicyAuthRuleCondition{ { Op: common.Ptr("OpInCorpIpRange"), Prop: common.Ptr("IpAddress"), }, }, ProfileId: common.Ptr("13e3bc1a-6ff7-4b7d-ae90-0ed21d3c393e"), }, }, }, }, }) if err != nil { panic(err) } importedpCloudWebappJson, err := json.MarshalIndent(importedpCloudWebapp, "", " ") if err != nil { panic(err) } fmt.Printf("Imported pCloud Webapp:\n%s\n", string(importedpCloudWebappJson)) // Configure permissions for Normal AWS App perms, err := identityAPI.Webapps().SetPermissions(&webappsmodels.IdsecIdentitySetWebappPermissions{ ``` -------------------------------- ### Running Unit Tests in Go Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/CONTRIBUTING.md Provides common bash commands for running unit tests in a Go project. Use 'make unit-test-all' for all tests, 'go test' for specific packages, and '-v' for verbose output. ```bash # Run all unit tests with coverage reporting make unit-test-all # Run tests for specific packages go test ./pkg/example/... # Run tests with verbose output go test -v ./... ``` -------------------------------- ### Generated E2E Test Skeleton Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/README.md A Go code skeleton generated for an E2E test, including necessary imports, framework setup, and placeholders for test logic. ```go //go:build e2e package pcloud import ( "testing" "github.com/stretchr/testify/require" safes "github.com/cyberark/idsec-sdk-golang/pkg/services/pcloud/safes" "github.com/cyberark/idsec-sdk-golang/tests/e2e/framework" ) func TestCreateAndDeleteSafe(t *testing.T) { framework.Run(t, func(ctx *framework.TestContext) { framework.LogSection(t, "Test: Create And Delete Safe") svc, err := ctx.API.PcloudSafes() require.NoError(t, err) // TODO: Create resource // TODO: Register cleanup // TODO: Add test assertions }, safes.ServiceConfig) } ``` -------------------------------- ### Update SIA Settings Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Demonstrates how to authenticate to an ISP tenant, retrieve all SIA settings, modify a specific setting, and update it. Also shows how to partially update a specific setting. ```go package main import ( "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" "github.com/cyberark/idsec-sdk-golang/pkg/common" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/sia" settingsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/sia/settings/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } siaAPI, err := sia.NewIdsecSIAAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } // Load all settings settings, err := siaAPI.Settings().ListSettings() if err != nil { panic(err) } ssettings.AdbMfaCaching.IsMfaCachingEnabled = common.Ptr(false) // Update settings _, err = siaAPI.Settings().SetSettings(settings) if err != nil { panic(err) } // Set specific setting partially adbMfa := &settingsmodels.IdsecSIASettingsAdbMfaCaching{ KeyExpirationTimeSec: common.Ptr(7200), ClientIPEnforced: common.Ptr(false), } _, err = siaAPI.Settings().SetAdbMfaCaching(adbMfa) if err != nil { panic(err) } } ``` -------------------------------- ### Authenticate and Connect via SIA SSH Gateway (Golang) Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Demonstrates authenticating to an ISP tenant and connecting to a target host using the SIA SSH gateway. It covers running single commands, privileged commands requiring a TTY, and opening interactive terminal sessions. Caching and extra SSH arguments are also shown. ```go package main import ( "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/sia" sshmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/sia/ssh/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } siaAPI, err := sia.NewIdsecSIAAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } // Mode 1: run a single command on the remote target through the SIA SSH // gateway. Output is streamed to this process' stdout/stderr. fmt.Println("Running single command via SIA SSH gateway...") if err := siaAPI.Ssh().Connect(&sshmodels.IdsecSIASSHConnectExecution{ IdsecSIASSHBaseExecution: sshmodels.IdsecSIASSHBaseExecution{ TargetAddress: "10.0.0.42", TargetUsername: "ec2-user", }, Command: "uname -a && id", }); err != nil { panic(err) } // Mode 2: run a privileged remote command that needs a TTY (sudo with a // password prompt). ForceTTY translates to `ssh -t`. fmt.Println("Running privileged remote command via SIA SSH gateway...") if err := siaAPI.Ssh().Connect(&sshmodels.IdsecSIASSHConnectExecution{ IdsecSIASSHBaseExecution: sshmodels.IdsecSIASSHBaseExecution{ TargetAddress: "10.0.0.42", TargetUsername: "ec2-user", NetworkName: "prod-network", }, Command: "sudo systemctl status nginx", ForceTTY: true, }); err != nil { panic(err) } // Mode 3: open an interactive terminal session through the SIA SSH // gateway. Omit Command to get an interactive shell — stdin/stdout/stderr // are wired to the parent process, matching the UX of the DB service's // interactive clients. AllowCaching reuses a previously-issued short-lived // SSH key from the SSO keyring cache when present. ExtraArgs is passed // through verbatim to the SSH client. fmt.Println("Opening interactive SSH terminal via SIA SSH gateway...") if err := siaAPI.Ssh().Connect(&sshmodels.IdsecSIASSHConnectExecution{ IdsecSIASSHBaseExecution: sshmodels.IdsecSIASSHBaseExecution{ TargetAddress: "10.0.0.42", TargetUsername: "ec2-user", TargetPort: 2222, }, AllowCaching: true, ExtraArgs: []string{"-L", "8080:127.0.0.1:80"}, }); err != nil { panic(err) } } ``` -------------------------------- ### Create VM Access Policy Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Demonstrates how to create a VM access policy using the Idsec SDK. This policy defines access rules for virtual machines. ```go package main import ( "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" commonmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/common" policy "github.com/cyberark/idsec-sdk-golang/pkg/services/policy" policycommomodels "github.com/cyberark/idsec-sdk-golang/pkg/services/policy/common/models" policyvmmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/policy/vm/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &policycommomodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: policycommomodels.Identity, AuthMethodSettings: &policycommomodels.IdentityIdsecAuthMethodSettings{}, }, &policycommomodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } policyAPI, err := policy.NewIdsecPolicyAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } policy, err := policyAPI.VM().CreatePolicy( &policyvmmodels.IdsecPolicyVMPlatformAccessPolicy{ IdsecPolicyCommonAccessPolicy: policycommomodels.IdsecPolicyCommonAccessPolicy{ Metadata: policycommomodels.IdsecPolicyMetadata{ Name: "Example VM Access Policy", Description: "This is an example of a VM access policy for Infrastructure.", Status: policycommomodels.IdsecPolicyStatus{ Status: policycommomodels.StatusTypeActive, }, PolicyEntitlement: policycommomodels.IdsecPolicyEntitlement{ TargetCategory: commonmodels.CategoryTypeVM, LocationType: commonmodels.WorkspaceTypeFQDNIP, PolicyType: policycommomodels.PolicyTypeRecurring, }, PolicyTags: []string{}, }, Principals: []policycommomodels.IdsecPolicyPrincipal{ { Type: policycommomodels.PrincipalTypeUser, ID: "user-id", Name: "user@cyberark.cloud.12345", SourceDirectoryName: "CyberArk", SourceDirectoryID: "12345", }, }, }, Conditions: policycommomodels.IdsecPolicyInfraCommonConditions{ IdsecPolicyConditions: policycommomodels.IdsecPolicyConditions{ AccessWindow: policycommomodels.IdsecPolicyTimeCondition{ DaysOfTheWeek: []int{1, 2, 3, 4, 5}, FromHour: "09:00", ToHour: "17:00", }, MaxSessionDuration: 4, }, IdleTime: 10, }, }, Targets: policyvmmodels.IdsecPolicyVMPlatformTargets{ FQDNIPResource: &policyvmmodels.IdsecPolicyVMFQDNIPResource{ FQDNRules: []policyvmmodels.IdsecPolicyVMFQDNRule{ { Operator: policyvmmodels.VMFQDNOperatorExactly, ComputernamePattern: "example-vm", Domain: "mydomain.com", }, }, }, }, Behavior: policyvmmodels.IdsecPolicyVMBehavior{ SSHProfile: &policyvmmodels.IdsecPolicyVMSSHProfile{ Username: "root", }, RDPProfile: &policyvmmodels.IdsecPolicyVMRDPProfile{ LocalEphemeralUser: &policyvmmodels.IdsecPolicyVMEphemeralUser{ AssignGroups: []string{"Remote Desktop Users"}, }, }, }, }, ) if err != nil { panic(err) } fmt.Printf("Policy created successfully: %s\n", policy.Metadata.PolicyID) } ``` -------------------------------- ### Add VM Secret and Target Set Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md This snippet demonstrates how to authenticate to an ISP tenant, add a VM secret, and then create a target set associated with that secret. ```go package main import ( "fmt" "github.com/cyberark/idsec-sdk-golang/pkg/auth" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" vmsecretsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/sia/secretsvm/models" targetsetsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/sia/workspacestargetsets/models" "github.com/cyberark/idsec-sdk-golang/pkg/services/sia" "os" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } // Add a VM secret siaAPI, err := sia.NewIdsecSIAAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } secret, err := siaAPI.VMSecrets().AddSecret( &vmsecretsmodels.IdsecSIAVMAddSecret{ SecretType: "ProvisionerUser", ProvisionerUsername: "CoolUser", ProvisionerPassword: "CoolPassword", }, ) if err != nil { panic(err) } // Add VM target set targetSet, err := siaAPI.WorkspacesTargetSets().AddTargetSet( &targetsetsmodels.IdsecSIAAddTargetSet{ Name: "mydomain.com", Type: "Domain", SecretID: secret.SecretID, SecretType: secret.SecretType, }, ) if err != nil { panic(err) } fmt.Printf("Target set %s created\n", targetSet.Name) } ``` -------------------------------- ### Create VM Access Policy with Idsec SDK Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/howto/policy/vm_policy_sdk_workflow.md This Go code demonstrates how to authenticate to the Idsec platform and create a VM access policy. It includes configuration for policy metadata, principals, conditions, targets (FQDN/IP), and behavior settings like SSH and RDP profiles. Ensure the IDSEC_SECRET environment variable is set for authentication. ```go package main import ( "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" commonmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/common" "github.com/cyberark/idsec-sdk-golang/pkg/services/policy" policycommomodels "github.com/cyberark/idsec-sdk-golang/pkg/services/policy/common/models" policyvmmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/policy/vm/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } policyAPI, err := policy.NewIdsecPolicyAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } policy, err := policyAPI.VM().CreatePolicy( &policyvmmodels.IdsecPolicyVMAccessPolicy{ IdsecPolicyInfraCommonAccessPolicy: policycommomodels.IdsecPolicyInfraCommonAccessPolicy{ IdsecPolicyCommonAccessPolicy: policycommomodels.IdsecPolicyCommonAccessPolicy{ Metadata: policycommomodels.IdsecPolicyMetadata{ Name: "Example VM Access Policy", Description: "This is an example of a VM access policy for Infrastructure.", Status: policycommomodels.IdsecPolicyStatus{ Status: policycommomodels.StatusTypeActive, }, PolicyEntitlement: policycommomodels.IdsecPolicyEntitlement{ TargetCategory: commonmodels.CategoryTypeVM, LocationType: commonmodels.WorkspaceTypeFQDNIP, PolicyType: policycommomodels.PolicyTypeRecurring, }, PolicyTags: []string{}, }, Principals: []policycommomodels.IdsecPolicyPrincipal{ { Type: policycommomodels.PrincipalTypeUser, ID: "user-id", Name: "user@cyberark.cloud.12345", SourceDirectoryName: "CyberArk", SourceDirectoryID: "12345", }, }, }, Conditions: policycommomodels.IdsecPolicyInfraCommonConditions{ IdsecPolicyConditions: policycommomodels.IdsecPolicyConditions{ AccessWindow: policycommomodels.IdsecPolicyTimeCondition{ DaysOfTheWeek: []int{1, 2, 3, 4, 5}, FromHour: "09:00", ToHour: "17:00", }, MaxSessionDuration: 4, }, IdleTime: 10, }, }, Targets: policyvmmodels.IdsecPolicyVMPlatformTargets{ FQDNIPResource: &policyvmmodels.IdsecPolicyVMFQDNIPResource{ FQDNRules: []policyvmmodels.IdsecPolicyVMFQDNRule{ { Operator: policyvmmodels.VMFQDNOperatorExactly, ComputernamePattern: "example-vm", Domain: "mydomain.com", }, }, }, }, Behavior: policyvmmodels.IdsecPolicyVMBehavior{ SSHProfile: &policyvmmodels.IdsecPolicyVMSSHProfile{ Username: "root", }, RDPProfile: &policyvmmodels.IdsecPolicyVMRDPProfile{ LocalEphemeralUser: &policyvmmodels.IdsecPolicyVMEphemeralUser{ AssignGroups: []string{"Remote Desktop Users"}, }, }, }, }, ) if err != nil { panic(err) } fmt.Printf("Policy created successfully: %s\n", policy.Metadata.PolicyID) } ``` -------------------------------- ### SDK Testing Framework Usage Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/QUICKSTART.md Utilize the `framework.Run()` function to manage test context, authentication checks, and resource cleanup. Use `framework.RandomResourceName()` for generating unique resource names and `framework.LogSection()` for organizing test output. ```go framework.Run() ``` ```go framework.RandomResourceName() ``` ```go framework.LogSection() ``` -------------------------------- ### Usage of Test Utilities in Go Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/CONTRIBUTING.md Demonstrates how to import and utilize test utilities, fixtures, and mocks within a Go unit test. Ensure test utilities are imported from the package's 'testutils' directory. ```go import ( "your-project/pkg/example/testutils" ) func TestExample(t *testing.T) { // Use test fixtures input := testutils.SampleValidInput() // Use test helpers mockClient := testutils.NewMockClient() // Use shared mocks mockService := testutils.MockExternalService{} // ... rest of test } ``` -------------------------------- ### Create and Delete Resource Pattern Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/tests/e2e/QUICKSTART.md Demonstrates a common pattern for creating a resource, registering it for automatic cleanup, and then testing it. The `ctx.TrackResourceByType` function ensures the resource is deleted after the test. ```go func TestCreateResource(t *testing.T) { framework.Run(t, func(ctx *framework.TestContext) { service, _ := ctx.API.MyService() // Create with unique name name := framework.RandomResourceName("e2e-test") resource, err := service.Create(name) require.NoError(t, err) // Register cleanup ctx.TrackResourceByType("MyResource", resource.ID, func() error { return service.Delete(resource.ID) }) // Test the resource // ... cleanup happens automatically }, myservice.ServiceConfig) } ``` -------------------------------- ### Import pCloud Target Platform Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Authenticates to an ISP tenant and imports a target platform using a zip file. Requires the IDSEC_SECRET environment variable. ```go package main import ( "fmt" "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/pcloud" targetplatformsmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/pcloud/targetplatforms/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } // Import and get the target platform pcloudAPI, err := pcloud.NewIdsecPCloudAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } importedPlatform, err := pcloudAPI.TargetPlatforms().Import( &targetplatformsmodels.IdsecPCloudImportTargetPlatform{PlatformZipPath: "/path/to/platform.zip"}, ) if err != nil { panic(err) } fmt.Printf("Imported platform: %v\n", importedPlatform) } ``` -------------------------------- ### Create Identity Policy Source: https://github.com/cyberark/idsec-sdk-golang/blob/main/docs/examples/sdk_examples.md Authenticates to an ISP tenant, creates an authentication profile, and then creates an identity policy. Requires the IDSEC_SECRET environment variable. ```go package main import ( "os" "github.com/cyberark/idsec-sdk-golang/pkg/auth" authmodels "github.com/cyberark/idsec-sdk-golang/pkg/models/auth" "github.com/cyberark/idsec-sdk-golang/pkg/services/identity" authprofilesmodels "github.com/cyberark/idsec-sdk-golang/pkg/services/identity/authprofiles/models" policymodels "github.com/cyberark/idsec-sdk-golang/pkg/services/identity/policies/models" ) func main() { // Perform authentication using IdsecISPAuth to the platform // First, create an ISP authentication class // Afterwards, perform the authentication ispAuth := auth.NewIdsecISPAuth(false) _, err := ispAuth.Authenticate( nil, &authmodels.IdsecAuthProfile{ Username: "user@cyberark.cloud.12345", AuthMethod: authmodels.Identity, AuthMethodSettings: &authmodels.IdentityIdsecAuthMethodSettings{}, }, &authmodels.IdsecSecret{ Secret: os.Getenv("IDSEC_SECRET"), }, false, false, ) if err != nil { panic(err) } // Create auth profile identityAPI, err := identity.NewIdsecIdentityAPI(ispAuth.(*auth.IdsecISPAuth)) if err != nil { panic(err) } authProfile, err := identityAPI.AuthProfiles().CreateAuthProfile(&authprofilesmodels.IdsecIdentityCreateAuthProfile{ AuthProfileName: "My Auth Profile", FirstChallenges: []string{"UP"}, SecondChallenges: []string{"EMAIL"}, DurationInMinutes: 60, }) if err != nil { panic(err) } policy, err := identityAPI.Policies().CreatePolicy(&policymodels.IdsecIdentityCreatePolicy{ PolicyName: "My Identity Policy", PolicyStatus: policymodels.PolicyStatusActive, Description: "This is my identity policy", RoleNames: []string{"Admin", "User"}, AuthProfileName: authProfile.AuthProfileName, Settings: map[string]interface{}{ "/Core/Authentication/IwaSetKnownEndpoint": "false", "/Core/Authentication/IwaSatisfiesAllMechs": "false", "/Core/Authentication/AllowZso": "true", "/Core/Authentication/ZsoSkipChallenge": "true", "/Core/Authentication/ZsoSetKnownEndpoint": "false", "/Core/Authentication/ZsoSatisfiesAllMechs": "false", }, }) if err != nil { panic(err) } println("Policy created with name:", policy.PolicyName) } ```