CyberArkPAS

Use the CyberArk Privileged Access Management (PAM) solution to manage users, safes, vaults, and accounts from Cortex XSOAR.

Authentication & Identity Management · CyberArk

Details

IDCyberArkPAS
ProviderCyberArk
CategoryAuthentication & Identity Management
From Version5.0.0
Docker Imagedemisto/python3:3.12.13.10116658
Supported ModulesAgentix XSIAM

README

Use the CyberArk Privileged Access Management (PAM) solution to manage users, safes, vaults, and accounts from Cortex XSOAR.

Configure CyberArkPAM in Cortex

Parameter Description Required
url Server URL (e.g., https://example.net) True
credentials Username True
isFetch Fetch incidents False
max_fetch Max fetch False
fetch_time First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days, 3 months, 1 year) False
score CyberArk PAM score (0.0-100.0) False
incidentType Incident type False
insecure Trust any certificate (not secure) False
proxy Use system proxy settings False

Commands

You can execute these commands from the CLI, as part of an automation, or in a playbook.
After you successfully execute a command, a DBot message appears in the War Room with the command details.

cyberark-pas-user-add


Add a new user to the vault.

To run this command, you must have the following permissions:

  • Add Users
  • Update Users

Base Command

cyberark-pas-user-add

Input

Argument Name Description Required
username The name of the user. Required
user_type The user type according to the license. Optional
non_authorized_interfaces The CyberArkPAM interfaces that this user is not authorized to use, e.g., - “PSM”, “PSMP” Optional
location The location in the vault where the user will be created. Must begin with “\”. If just “\”, the vault is in the root. Optional
expiry_date The date when the user credentials expire. Must be in the following timestamp format: (<number> <time unit>, e.g., 12 hours, 7 days, 3 months, 1 year). Optional
password The password that the user will use to log in for the first time. Required
change_password_on_the_next_logon Whether or not the user must change the user password from the second log in onward. Can be ‘true’ or ‘false’. Default is ‘true’. Optional
password_never_expires Whether the user’s password will not expire unless they decide to change it. Can be ‘true’ or ‘false’. Default is ‘false’. Optional
vault_authorization A comma-separated list of user permissions. Valid values are: AuditUsers, AddUpdateUsers, ResetUsersPasswords, ActivateUsers, AddNetworkAreas, ManageDirectoryMapping, ManageServerFileCategories, BackupAllSafes, RestoreAllSafes e.g., AddSafes,AuditUsers Optional
description Notes and comments. Optional
email The email address of the user. Optional
first_name The first name of the user. Optional
last_name The last name of the user. Optional
enable_user Whether the user will be enabled upon creation. Can be ‘true’ or ‘false’. Default is ‘true’. Optional
distinguished_name The distinguished name of the user. The usage is for PKI authentication. This will match the certificate subject name or domain name. Optional
profession The profession of the user. Optional

Context Output

Path Type Description
CyberArkPAS.Users.id Number The unique ID of the user.
CyberArkPAS.Users.authenticationMethod String The authentication method of the user.
CyberArkPAS.Users.changePassOnNextLogon Boolean Whether or not the user must change the user password.
CyberArkPAS.Users.description String Description of the user.
CyberArkPAS.Users.enableUser Boolean Whether or not the user is enabled.
CyberArkPAS.Users.expiryDate Number The expiry date of the user credentials.
CyberArkPAS.Users.internet.businessEmail String The email address of the user.
CyberArkPAS.Users.lastSuccessfulLoginDate Number The last successful login date of the user.
CyberArkPAS.Users.location String The location in the vault where the user will be created.
CyberArkPAS.Users.personalDetails.profession String The profession of the user.
CyberArkPAS.Users.suspended Boolean Whether or not the user is suspended.
CyberArkPAS.Users.userType String The type of the user.
CyberArkPAS.Users.username String The name of the user.
CyberArkPAS.Users.vaultAuthorization String The permissions of the user.

Command Example

!cyberark-pas-user-add username="TestUser" password="12345Aa" change_password_on_the_next_logon=true description="new user for test" email="usertest@test.com" enable_user=true first_name="user" last_name="test" profession="testing integrations"

Context Example

{
    "CyberArkPAS": {
        "Users": {
            "authenticationMethod": [
                "AuthTypePass"
            ],
            "businessAddress": {
                "workCity": "",
                "workCountry": "",
                "workState": "",
                "workStreet": "",
                "workZip": ""
            },
            "changePassOnNextLogon": true,
            "componentUser": false,
            "description": "new user for test",
            "distinguishedName": "",
            "enableUser": true,
            "expiryDate": -62135578800,
            "groupsMembership": [],
            "id": 150,
            "internet": {
                "businessEmail": "usertest@test.com",
                "homeEmail": "",
                "homePage": "",
                "otherEmail": ""
            },
            "lastSuccessfulLoginDate": 1597830302,
            "location": "\\",
            "passwordNeverExpires": false,
            "personalDetails": {
                "city": "",
                "country": "",
                "department": "",
                "firstName": "user",
                "lastName": "test",
                "middleName": "",
                "organization": "",
                "profession": "testing integrations",
                "state": "",
                "street": "",
                "title": "",
                "zip": ""
            },
            "phones": {
                "businessNumber": "",
                "cellularNumber": "",
                "faxNumber": "",
                "homeNumber": "",
                "pagerNumber": ""
            },
            "source": "CyberArk",
            "suspended": false,
            "unAuthorizedInterfaces": [],
            "userType": "EPVUser",
            "username": "TestUser",
            "vaultAuthorization": []
        }
    }
}

Human Readable Output

Results

authenticationMethod businessAddress changePassOnNextLogon componentUser description distinguishedName enableUser expiryDate groupsMembership id internet lastSuccessfulLoginDate location passwordNeverExpires personalDetails phones source suspended unAuthorizedInterfaces userType username vaultAuthorization
AuthTypePass workStreet:
workCity:
workState:
workZip:
workCountry:
true false new user for test   true -62135578800   150 homePage:
homeEmail:
businessEmail: usertest@test.com
otherEmail:
1597830302 \ false street:
city:
state:
zip:
country:
title:
organization:
department:
profession: testing integrations
firstName: user
middleName:
lastName: test
homeNumber:
businessNumber:
cellularNumber:
faxNumber:
pagerNumber:
CyberArk false   EPVUser TestUser  

cyberark-pas-user-update


Update an existing vault user.

To run this command, you must have the following permissions:

  • Add Users or Update Users
  • In order to edit change_password_on_the_next_logon, you must have the Reset Password authorization

Base Command

cyberark-pas-user-update

Input

Argument Name Description Required
username The name of the user. Optional
user_type User type according to the license. Optional
non_authorized_interfaces The CyberArkPAM interfaces that this user is not authorized to use, e.g., “PSM”, “PSMP” Optional
location The location in the vault where the user will be created. Must begin with “\”. If just “\”, the vault is in the root. Optional
expiry_date The date when the user expires. Must be in the following timestamp format: (<number> <time unit>, e.g., 12 hours, 7 days, 3 months, 1 year). Optional
change_password_on_the_next_logon Whether or not the user must change their password from the second log on onward. Can be ‘true’ or ‘false’. Default is ‘true’. Optional
password_never_expires Whether the user’s password will not expire unless they decide to change it. Can be ‘true’ or ‘false’. Default is ‘false’. Optional
vault_authorization A comma-separated list of user permissions. Valid values are: AddSafes, AuditUsers, AddUpdateUsers, ResetUsersPasswords, ActivateUsers, AddNetworkAreas, ManageDirectoryMapping, ManageServerFileCategories, BackupAllSafes, RestoreAllSafes e.g., AddSafes,AuditUsers Optional
description Notes and comments. Optional
email The email addresses of the user. Optional
first_name The first name of the user. Optional
last_name The last name of the user. Optional
enable_user Whether the user will be enabled upon creation. Can be ‘true’ or ‘false’. Default is ‘true’. Optional
distinguished_name The distinguished name of the user. The usage is for PKI authentication. This will match the certificate subject name or domain name. Optional
profession The profession of the user. Optional
user_id The ID of the user to update. Required

Context Output

Path Type Description
CyberArkPAS.Users.id Number The unique ID of the user.
CyberArkPAS.Users.authenticationMethod String The authentication method for the user.
CyberArkPAS.Users.changePassOnNextLogon Boolean Whether or not the user must change the user password.
CyberArkPAS.Users.description String Description of the user.
CyberArkPAS.Users.enableUser Boolean Whether or not the user is enabled.
CyberArkPAS.Users.expiryDate Number The expiry date of the user.
CyberArkPAS.Users.internet.businessEmail String The email address of the user.
CyberArkPAS.Users.lastSuccessfulLoginDate Number The last successful login date of the user.
CyberArkPAS.Users.location String The location in the vault where the user will be created.
CyberArkPAS.Users.personalDetails.profession String The profession of the user.
CyberArkPAS.Users.suspended Boolean Whether or not the user is suspended.
CyberArkPAS.Users.userType String The type of the user.
CyberArkPAS.Users.username String The name of the user.
CyberArkPAS.Users.vaultAuthorization String The permissions of the user.

Command Example

!cyberark-pas-user-update user_id=150 change_password_on_the_next_logon=true description="updated description" email="update@test.com" first_name="test1" last_name="updated-name" username="TestUser1" profession="test1"

Context Example

{
    "CyberArkPAS": {
        "Users": {
            "authenticationMethod": [
                "AuthTypePass"
            ],
            "businessAddress": {
                "workCity": "",
                "workCountry": "",
                "workState": "",
                "workStreet": "",
                "workZip": ""
            },
            "changePassOnNextLogon": true,
            "componentUser": false,
            "description": "updated description",
            "distinguishedName": "",
            "enableUser": true,
            "expiryDate": -62135578800,
            "groupsMembership": [],
            "id": 150,
            "internet": {
                "businessEmail": "update@test.com",
                "homeEmail": "",
                "homePage": "",
                "otherEmail": ""
            },
            "lastSuccessfulLoginDate": 1597830302,
            "location": "\\",
            "passwordNeverExpires": false,
            "personalDetails": {
                "city": "",
                "country": "",
                "department": "",
                "firstName": "test1",
                "lastName": "updated-name",
                "middleName": "",
                "organization": "",
                "profession": "test1",
                "state": "",
                "street": "",
                "title": "",
                "zip": ""
            },
            "phones": {
                "businessNumber": "",
                "cellularNumber": "",
                "faxNumber": "",
                "homeNumber": "",
                "pagerNumber": ""
            },
            "source": "CyberArk",
            "suspended": false,
            "unAuthorizedInterfaces": [],
            "userType": "EPVUser",
            "username": "TestUser1",
            "vaultAuthorization": []
        }
    }
}

Human Readable Output

Results

authenticationMethod businessAddress changePassOnNextLogon componentUser description distinguishedName enableUser expiryDate groupsMembership id internet lastSuccessfulLoginDate location passwordNeverExpires personalDetails phones source suspended unAuthorizedInterfaces userType username vaultAuthorization
AuthTypePass workStreet:
workCity:
workState:
workZip:
workCountry:
true false updated description   true -62135578800   150 homePage:
homeEmail:
businessEmail: update@test.com
otherEmail:
1597830302 \ false street:
city:
state:
zip:
country:
title:
organization:
department:
profession: test1
firstName: test1
middleName:
lastName: updated-name
homeNumber:
businessNumber:
cellularNumber:
faxNumber:
pagerNumber:
CyberArk false   EPVUser TestUser1  

cyberark-pas-user-delete


Delete a specific user in the vault.

To run this command, you must have Add Users or Update Users permissions.

Base Command

cyberark-pas-user-delete

Input

Argument Name Description Required
user_id The ID of the user to delete. Required

Context Output

Path Type Description
CyberArkPAS.Users.Deleted Boolean Whether the user was deleted.

Command Example

!cyberark-pas-user-delete user_id=150

Context Example

{
    "CyberArkPAS": {
        "Users": {
            "Deleted": true,
            "id": "150"
        }
    }
}

Human Readable Output

User 150 was deleted

cyberark-pas-users-list


Return a list of all existing users in the vault that meet the filter and search criteria.

Base Command

cyberark-pas-users-list

Input

Argument Name Description Required
filter Retrieve users using filters. Valid values: userType, componentUser. Optional
search Search by the following values: username, first name, last name. Optional

Context Output

Path Type Description
CyberArkPAS.Users.id Number The unique IDs of the users.
CyberArkPAS.Users.username String The names of the users.
CyberArkPAS.Users.source String The sources of the users.
CyberArkPAS.Users.userType String The types of the users.
CyberArkPAS.Users.componentUser Boolean Whether the users are component users.
CyberArkPAS.Users.location String The locations in the vault where the users were created.
CyberArkPAS.Users.personalDetails.firstName String The first name of the users.
CyberArkPAS.Users.personalDetails.middleName String The middle name of the users.
CyberArkPAS.Users.personalDetails.lastName String The last name of the users.
CyberArkPAS.Users.vaultAuthorization String The permissions of the users.

Command Example


#### Context Example

{
“CyberArkPAS”: {
“Users”: [
{
“componentUser”: false,
“id”: 2,
“location”: “\”,
“personalDetails”: {
“firstName”: “”,
“lastName”: “”,
“middleName”: “”
},
“source”: “CyberArk”,
“userType”: “Built-InAdmins”,
“username”: “Administrator”,
“enableUser”: true,
“suspended”: false,
“vaultAuthorization”: [
“AddUpdateUsers”,
“AddSafes”,
“AddNetworkAreas”,
“ManageDirectoryMapping”,
“ManageServerFileCategories”,
“AuditUsers”,
“BackupAllSafes”,
“RestoreAllSafes”,
“ResetUsersPasswords”,
“ActivateUsers”
]
},
{
“componentUser”: false,
“id”: 3,
“location”: “\”,
“personalDetails”: {
“firstName”: “”,
“lastName”: “”,
“middleName”: “”
},
“source”: “CyberArk”,
“userType”: “Built-InAdmins”,
“username”: “Auditor”,
“enableUser”: true,
“suspended”: false,
“vaultAuthorization”: [
“AuditUsers”
]
}
}


#### Human Readable Output

>### There are 2 users
>
>|componentUser|id|location|personalDetails|source|userType|username|vaultAuthorization|
>|---|---|---|---|---|---|---|---|
>| false | 2 | \ | firstName: <br/>middleName: <br/>lastName:  | CyberArk | Built-InAdmins | Administrator | AddUpdateUsers,<br/>AddSafes,<br/>AddNetworkAreas,<br/>ManageDirectoryMapping,<br/>ManageServerFileCategories,<br/>AuditUsers,<br/>BackupAllSafes,<br/>RestoreAllSafes,<br/>ResetUsersPasswords,<br/>ActivateUsers |
>| false | 3 | \ | firstName: <br/>middleName: <br/>lastName:  | CyberArk | Built-InAdmins | Auditor | AuditUsers |

### cyberark-pas-user-activate

***
Activate an existing vault user who was suspended after entering incorrect credentials multiple times.
Uses the V1 of the API and may change in the future.

#### Base Command

`cyberark-pas-user-activate`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| user_id | The ID of the user to activate. | Required |

#### Context Output

There is no context output for this command.

#### Command Example

```!cyberark-pas-user-activate user_id=150```

#### Human Readable Output

>User 150 was activated

### cyberark-pas-safes-list

***
Return information about all of the user’s safes in the vault.

To run this command, you must be a member of the Safes in the Vault that are returned in the list.

#### Base Command

`cyberark-pas-safes-list`

#### Input

There are no input arguments for this command.

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.SafeName | String | The names of the safes. |
| CyberArkPAS.Safes.Description | String | The descriptions of the safes. |
| CyberArkPAS.Safes.Location | String | The locations of the safes. |
| CyberArkPAS.Safes.ManagingCPM | String | The name of the Central Policy Manager \(CPM\) user who will manage the safes. |
| CyberArkPAS.Safes.NumberOfDaysRetention | Number | The number of retained versions of every password that is stored in the safes. |
| CyberArkPAS.Safes.NumberOfVersionsRetention | Number | The number of days for which password versions are saved in the safes. |
| CyberArkPAS.Safes.OLACEnabled | Boolean | Whether or not to enable Object Level Access Control \(OLAC\) for the safes. |

#### Command Example

```!cyberark-pas-safes-list```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: [
{
“Description”: “”,
“Location”: “\”,
“SafeName”: “Internal”,
“SafeUrlId”: “Internal”
},
{
“Description”: “”,
“Location”: “\”,
“SafeName”: “Notification”,
“SafeUrlId”: “Notification”
},
{
“Description”: “”,
“Location”: “\”,
“SafeName”: “Reports”,
“SafeUrlId”: “Reports”
}
]
}
}


#### Human Readable Output

>### There are 3 safes
>
>|Description|Location|SafeName|SafeUrlId|
>|---|---|---|---|
>|  | \ | Internal | Internal |
>|  | \ | Notification | Notification |
>|  | \ | Reports | Reports |

### cyberark-pas-safe-get-by-name

***
Return information about a specific safe in the vault.

#### Base Command

`cyberark-pas-safe-get-by-name`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The name of the safe about which information is returned. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.SafeName | String | The name of the safe. |
| CyberArkPAS.Safes.Description | String | The description of the safe. |
| CyberArkPAS.Safes.Location | String | The location of the safe. |
| CyberArkPAS.Safes.ManagingCPM | String | The name of the Central Policy Manager \(CPM\) user who will manage the safe. |
| CyberArkPAS.Safes.NumberOfDaysRetention | Number | The number of retained versions of every password that is stored in the safe. |
| CyberArkPAS.Safes.NumberOfVersionsRetention | Number | The number of days for which password versions are saved in the safe. |
| CyberArkPAS.Safes.OLACEnabled | Boolean | Whether or not to enable Object Level Access Control \(OLAC\) for the safe. |

#### Command Example

```!cyberark-pas-safe-get-by-name safe_name=UpdatedName1```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“AutoPurgeEnabled”: false,
“Description”: “UpdatedSafe”,
“Location”: “\”,
“ManagingCPM”: “”,
“NumberOfDaysRetention”: 150,
“NumberOfVersionsRetention”: null,
“OLACEnabled”: true,
“SafeName”: “UpdatedName1”
}
}
}


#### Human Readable Output

>### Results
>
>|AutoPurgeEnabled|Description|Location|ManagingCPM|NumberOfDaysRetention|NumberOfVersionsRetention|OLACEnabled|SafeName|
>|---|---|---|---|---|---|---|---|
>| false | UpdatedSafe | \ |  | 150 |  | true | UpdatedName1 |

### cyberark-pas-safe-add

***
Add a new safe to the vault.

To run this command, you must have *Add Safes* permission in the Vault.

#### Base Command

`cyberark-pas-safe-add`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | Name of a safe to create. | Required |
| description | Description of the new safe. | Optional |
| OLAC_enabled | Whether or not to enable Object Level Access Control (OLAC) for the new<br/>safe. Valid values are: 'true' or 'false'. Default is 'true'. | Optional |
| managing_cpm | The name of the Central Policy Manager (CPM) user who will manage the new safe. | Optional |
| number_of_versions_retention | The number of retained versions of every password that is stored in the safe. | Optional |
| number_of_days_retention | The number of days for which password versions are saved in the safe. | Optional |
| location | The location of the new safe. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.SafeName | String | The name of the safe. |
| CyberArkPAS.Safes.Description | String | The description of the safe. |
| CyberArkPAS.Safes.Location | String | The location of the safe. |
| CyberArkPAS.Safes.ManagingCPM | String | The name of the Central Policy Manager \(CPM\) user who will manage the safe. |
| CyberArkPAS.Safes.NumberOfDaysRetention | Number | The number of retained versions of every password that is stored in the safe. |
| CyberArkPAS.Safes.NumberOfVersionsRetention | Number | The number of days for which password versions are saved in the safe. |
| CyberArkPAS.Safes.OLACEnabled | Boolean | Whether or not to enable Object Level Access Control \(OLAC\) for the safe. |

#### Command Example

```!cyberark-pas-safe-add safe_name="TestSafe1" description="safe for tests" number_of_days_retention=100```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“AutoPurgeEnabled”: false,
“Description”: “safe for tests”,
“Location”: “\”,
“ManagingCPM”: “”,
“NumberOfDaysRetention”: 100,
“NumberOfVersionsRetention”: null,
“OLACEnabled”: true,
“SafeName”: “TestSafe1”
}
}
}


#### Human Readable Output

>### Results
>
>|AutoPurgeEnabled|Description|Location|ManagingCPM|NumberOfDaysRetention|NumberOfVersionsRetention|OLACEnabled|SafeName|
>|---|---|---|---|---|---|---|---|
>| false | safe for tests | \ |  | 100 |  | true | TestSafe1 |

### cyberark-pas-safe-update

***
Update a single safe in the vault.

To run this command, you must have *Manage Safes* permission in the Vault.

#### Base Command

`cyberark-pas-safe-update`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The name of the safe that will be updated. | Required |
| description | The description of the updated safe. | Optional |
| OLAC_enabled | Whether or not to enable Object Level Access Control (OLAC) for the updated<br/>safe. Valid values are: 'true' or 'false'. Default is 'true'. | Optional |
| managing_cpm | The name of the Central Policy Manager (CPM) user who will manage the updated safe. | Optional |
| number_of_versions_retention | The number of retained versions of every password that is stored in the updated safe. | Optional |
| number_of_days_retention | The number of days for which password versions are saved in the updated safe. | Optional |
| safe_new_name | The new name of the safe. | Optional |
| location | The location of the updated safe. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.SafeName | String | The name of the updated safe. |
| CyberArkPAS.Safes.Description | String | The description of the updated safe. |
| CyberArkPAS.Safes.Location | String | The location of the updated safe. |
| CyberArkPAS.Safes.ManagingCPM | String | The name of the Central Policy Manager \(CPM\) user who will manage the safe. |
| CyberArkPAS.Safes.NumberOfDaysRetention | Number | The number of retained versions of every password that is stored in the updated safe. |
| CyberArkPAS.Safes.NumberOfVersionsRetention | Number | The number of days for which password versions are saved in the updated safe. |
| CyberArkPAS.Safes.OLACEnabled | Boolean | Whether or not to enable Object Level Access Control \(OLAC\) for the updated safe. |

#### Command Example

```!cyberark-pas-safe-update safe_name=TestSafe1 safe_new_name=UpdatedName1 description=UpdatedSafe number_of_days_retention=150```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“AutoPurgeEnabled”: false,
“Description”: “UpdatedSafe”,
“Location”: “\”,
“ManagingCPM”: “”,
“NumberOfDaysRetention”: 150,
“NumberOfVersionsRetention”: null,
“OLACEnabled”: true,
“SafeName”: “UpdatedName1”
}
}
}


#### Human Readable Output

>### Results
>
>|AutoPurgeEnabled|Description|Location|ManagingCPM|NumberOfDaysRetention|NumberOfVersionsRetention|OLACEnabled|SafeName|
>|---|---|---|---|---|---|---|---|
>| false | UpdatedSafe | \ |  | 150 |  | true | UpdatedName1 |

### cyberark-pas-safe-delete

***
Delete a safe from the vault.

To run this command, you must have *Manage Safes* permission in the Safe.

#### Base Command

`cyberark-pas-safe-delete`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The name of the safe that will be deleted. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Deleted | Boolean | Whether the safe was deleted. |

#### Command Example

```!cyberark-pas-safe-delete safe_name=UpdatedName1```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“Deleted”: true,
“SafeName”: “UpdatedName1”
}
}
}


#### Human Readable Output

>Safe UpdatedName1 was deleted

### cyberark-pas-safe-members-list

***
Return a list of the members of the safe.

To run this command, you must have *View Safe Members* permission in the Safe.

#### Base Command

`cyberark-pas-safe-members-list`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The name of the safe whose safe members will be listed. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Members.MemberName | String | The names of the safe members. |
| CyberArkPAS.Safes.Members.MembershipExpirationDate | Number | The expiration dates of the safe members. |
| CyberArkPAS.Safes.Members.Permissions | Unknown | The permissions of the safe members. |
| CyberArkPAS.Safes.Members.SearchIn | String | The vault or domain where the users or groups was found. |

#### Command Example

```!cyberark-pas-safe-members-list safe_name=UpdatedName1```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“Members”: [
{
“IsExpiredMembershipEnable”: false,
“IsPredefinedUser”: true,
“MemberName”: “Administrator”,
“MemberType”: “User”,
“MembershipExpirationDate”: null,
“Permissions”: {
“AccessWithoutConfirmation”: true,
“AddAccounts”: true,
“BackupSafe”: true,
“CreateFolders”: true,
“DeleteAccounts”: true,
“DeleteFolders”: true,
“InitiateCPMAccountManagementOperations”: true,
“ListAccounts”: true,
“ManageSafe”: true,
“ManageSafeMembers”: true,
“MoveAccountsAndFolders”: true,
“RenameAccounts”: true,
“RequestsAuthorizationLevel1”: true,
“RequestsAuthorizationLevel2”: false,
“RetrieveAccounts”: true,
“SpecifyNextAccountContent”: true,
“UnlockAccounts”: true,
“UpdateAccountContent”: true,
“UpdateAccountProperties”: true,
“UseAccounts”: true,
“ViewAuditLog”: true,
“ViewSafeMembers”: true
}
},
{
“IsExpiredMembershipEnable”: false,
“IsPredefinedUser”: false,
“MemberName”: “TestUser1”,
“MemberType”: “User”,
“MembershipExpirationDate”: null,
“Permissions”: {
“AccessWithoutConfirmation”: false,
“AddAccounts”: false,
“BackupSafe”: false,
“CreateFolders”: false,
“DeleteAccounts”: false,
“DeleteFolders”: false,
“InitiateCPMAccountManagementOperations”: false,
“ListAccounts”: false,
“ManageSafe”: false,
“ManageSafeMembers”: false,
“MoveAccountsAndFolders”: false,
“RenameAccounts”: false,
“RequestsAuthorizationLevel1”: false,
“RequestsAuthorizationLevel2”: false,
“RetrieveAccounts”: false,
“SpecifyNextAccountContent”: false,
“UnlockAccounts”: false,
“UpdateAccountContent”: false,
“UpdateAccountProperties”: false,
“UseAccounts”: true,
“ViewAuditLog”: false,
“ViewSafeMembers”: false
}
}
]
}
}
}


#### Human Readable Output

>### There are 2 safe members for UpdatedName1
>
>|IsExpiredMembershipEnable|IsPredefinedUser|MemberName|MemberType|MembershipExpirationDate|Permissions|
>|---|---|---|---|---|---|
>| false | true | Administrator | User |  | UseAccounts: true<br/>RetrieveAccounts: true<br/>ListAccounts: true<br/>AddAccounts: true<br/>UpdateAccountContent: true<br/>UpdateAccountProperties: true<br/>InitiateCPMAccountManagementOperations: true<br/>SpecifyNextAccountContent: true<br/>RenameAccounts: true<br/>DeleteAccounts: true<br/>UnlockAccounts: true<br/>ManageSafe: true<br/>ManageSafeMembers: true<br/>BackupSafe: true<br/>ViewAuditLog: true<br/>ViewSafeMembers: true<br/>AccessWithoutConfirmation: true<br/>CreateFolders: true<br/>DeleteFolders: true<br/>MoveAccountsAndFolders: true<br/>RequestsAuthorizationLevel1: true<br/>RequestsAuthorizationLevel2: false |
>| false | false | TestUser1 | User |  | UseAccounts: true<br/>RetrieveAccounts: false<br/>ListAccounts: false<br/>AddAccounts: false<br/>UpdateAccountContent: false<br/>UpdateAccountProperties: false<br/>InitiateCPMAccountManagementOperations: false<br/>SpecifyNextAccountContent: false<br/>RenameAccounts: false<br/>DeleteAccounts: false<br/>UnlockAccounts: false<br/>ManageSafe: false<br/>ManageSafeMembers: false<br/>BackupSafe: false<br/>ViewAuditLog: false<br/>ViewSafeMembers: false<br/>AccessWithoutConfirmation: false<br/>CreateFolders: false<br/>DeleteFolders: false<br/>MoveAccountsAndFolders: false<br/>RequestsAuthorizationLevel1: false<br/>RequestsAuthorizationLevel2: false |

### cyberark-pas-safe-member-add

***
Add an existing user as a safe member.

#### Base Command

`cyberark-pas-safe-member-add`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| member_name | The name of the user to add as a safe member. | Required |
| search_in | Search for the member in the vault or domain. | Optional |
| membership_expiration_date | The membership expiration date in the format MM\DD\YY. Leave empty if there is no expiration date. | Optional |
| permissions | The user’s permissions in the safe.<br/>Valid values: UseAccounts, RetrieveAccounts, ListAccounts, AddAccounts, UpdateAccountContent, UpdateAccountProperties, InitiateCPMAccountManagementOperations, InitiateCPMAccountManagementOperations, SpecifyNextAccountContent, RenameAccounts, DeleteAccounts, UnlockAccounts, ManageSafe, ManageSafeMembers, BackupSafe, ViewAuditLog, ViewAuditLog, ViewSafeMembers, AccessWithoutConfirmation, CreateFolders, DeleteFolders, MoveAccountsAndFolders<br/>e.g., UseAccounts,RetrieveAccounts. | Optional |
| safe_name | The URL encoded name of the safe to add a member to. | Required |
| requests_authorization_level | The request authorization levels.<br/>0 – cannot authorize<br/>1 – authorization level 1<br/>2 – authorization level 2<br/>Default is '0'. Possible values are: 0, 1, 2. Default is 0. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Members.MemberName | String | The name of the safe member. |
| CyberArkPAS.Safes.Members.MembershipExpirationDate | Number | The expiration date of the safe member. |
| CyberArkPAS.Safes.Members.Permissions | Unknown | The permissions of the safe member. |
| CyberArkPAS.Safes.Members.SearchIn | String | The vault or domain where the user or group was found. |

### cyberark-pas-safe-member-update

***
Update an existing safe member.
Uses the V1 of the API and may change in the future.

To run this command, you must have *Manage Safe Members* permission in the Vault.

#### Base Command

`cyberark-pas-safe-member-update`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| member_name | The member name that will be updated. | Required |
| membership_expiration_date | The membership expiration date in the format MM\DD\YY. Leave empty if there is no expiration date. | Optional |
| permissions | The user’s permissions in the safe.<br/>Valid values are:<br/>UseAccounts, RetrieveAccounts, ListAccounts, AddAccounts, UpdateAccountContent, UpdateAccountProperties, InitiateCPMAccountManagementOperations, InitiateCPMAccountManagementOperations, SpecifyNextAccountContent, RenameAccounts, DeleteAccounts, UnlockAccounts, ManageSafe, ManageSafeMembers, BackupSafe, ViewAuditLog, ViewAuditLog, ViewSafeMembers, RequestsAuthorizationLevel, AccessWithoutConfirmation, CreateFolders, DeleteFolders, MoveAccountsAndFolders<br/>e.g., UseAccounts,RetrieveAccounts | Optional |
| safe_name | The name of the safe to which the safe member belongs. | Required |
| requests_authorization_level | Request authorization levels.<br/>0 – cannot authorize<br/>1 – authorization level 1<br/>2 – authorization level 2<br/>Default is: '0'. | Optional |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Members.MemberName | String | The name of the safe member. |
| CyberArkPAS.Safes.Members.MembershipExpirationDate | Number | The expiration date of the safe member. |
| CyberArkPAS.Safes.Members.Permissions | Unknown | The permissions of the safe member. |
| CyberArkPAS.Safes.Members.SearchIn | String | The vault or domain where the user or group was found. |

#### Command Example

```!cyberark-pas-safe-member-update member_name="TestUser1" safe_name="UpdatedName1" permissions=UseAccounts```

#### Context Example

{
“CyberArkPAS”: {
“Safes”: {
“Members”: {
“MembershipExpirationDate”: “”,
“Permissions”: [
{
“Key”: “UseAccounts”,
“Value”: true
},
{
“Key”: “RetrieveAccounts”,
“Value”: false
},
{
“Key”: “ListAccounts”,
“Value”: false
},
{
“Key”: “AddAccounts”,
“Value”: false
},
{
“Key”: “UpdateAccountContent”,
“Value”: false
},
{
“Key”: “UpdateAccountProperties”,
“Value”: false
},
{
“Key”: “InitiateCPMAccountManagementOperations”,
“Value”: false
},
{
“Key”: “SpecifyNextAccountContent”,
“Value”: false
},
{
“Key”: “RenameAccounts”,
“Value”: false
},
{
“Key”: “DeleteAccounts”,
“Value”: false
},
{
“Key”: “UnlockAccounts”,
“Value”: false
},
{
“Key”: “ManageSafe”,
“Value”: false
},
{
“Key”: “ManageSafeMembers”,
“Value”: false
},
{
“Key”: “BackupSafe”,
“Value”: false
},
{
“Key”: “ViewAuditLog”,
“Value”: false
},
{
“Key”: “ViewSafeMembers”,
“Value”: false
},
{
“Key”: “AccessWithoutConfirmation”,
“Value”: false
},
{
“Key”: “CreateFolders”,
“Value”: false
},
{

cyberark-pas-safe-member-update


Update an existing safe member.

Base Command

cyberark-pas-safe-member-update

Input

Argument Name Description Required
member_name The member name that will be updated. Required
membership_expiration_date The membership expiration date in the format MM\DD\YY. Leave empty if there is no expiration date. Optional
permissions The user’s permissions in the safe.
Valid values are:
UseAccounts, RetrieveAccounts, ListAccounts, AddAccounts, UpdateAccountContent, UpdateAccountProperties, InitiateCPMAccountManagementOperations, InitiateCPMAccountManagementOperations, SpecifyNextAccountContent, RenameAccounts, DeleteAccounts, UnlockAccounts, ManageSafe, ManageSafeMembers, BackupSafe, ViewAuditLog, ViewAuditLog, ViewSafeMembers, RequestsAuthorizationLevel, AccessWithoutConfirmation, CreateFolders, DeleteFolders, MoveAccountsAndFolders
e.g., UseAccounts,RetrieveAccounts.
Optional
safe_name The URL encoded name of the safe to which the safe member belongs. Required
requests_authorization_level Request authorization levels.
0 – cannot authorize
1 – authorization level 1
2 – authorization level 2
Default is: ‘0’. Possible values are: 0, 1, 2. Default is 0.
Optional

Context Output

Path Type Description
CyberArkPAS.Safes.Members.MemberName String The name of the safe member.
CyberArkPAS.Safes.Members.MembershipExpirationDate Number The expiration date of the safe member.
CyberArkPAS.Safes.Members.Permissions Unknown The permissions of the safe member.
CyberArkPAS.Safes.Members.SearchIn String The vault or domain where the user or group was found.
    }
} } ```

Human Readable Output

Results

address categoryModificationTime createdTime id name platformId safeName secretManagement secretType userName
/ 1597863168 1597863168 89_3 TestAccount1 WinServerLocal TestSafe1 automaticManagementEnabled: true
lastModifiedTime: 1597848768
password TestUser

cyberark-pas-account-add


Add a new privileged account or SSH key to the vault.

To run this command, you must have the following permissions in the Safe:

  • For updating account properties: Update Password Properties.
  • For renaming accounts: Rename Accounts.
  • For moving accounts to a different folder: Move Accounts or Move Folders.

Base Command

cyberark-pas-account-add

Input

Argument Name Description Required
account_id The unique ID of the account to add. Required

Context Output

Path Type Description
CyberArkPAS.Accounts.id String The unique ID of the account.
CyberArkPAS.Accounts.categoryModificationTime Number The last modified date of the account.
CyberArkPAS.Accounts.createdTime Number The date the account was created.
CyberArkPAS.Accounts.name String The name of the account.
CyberArkPAS.Accounts.platformId String The platform assigned to this account.
CyberArkPAS.Accounts.safeName String The safe where the account was created.
CyberArkPAS.Accounts.secretManagement String Whether the account secret is automatically managed by the CPM.
CyberArkPAS.Accounts.secretType String The type of password.
CyberArkPAS.Accounts.userName String The user name of the account.
CyberArkPAS.Accounts.address String The name or address of the machine where the account will be used.

Command Example

!cyberark-pas-account-add safe_name=TestSafe account_name=TestAccount1 address=/ password=12345Aa platform_id=WinServerLocal username=TestUser

Context Example

{
    "CyberArkPAS": {
        "Accounts": {
            "address": "/",
            "categoryModificationTime": 1597863168,
            "createdTime": 1597863168,
            "id": "89_3",cyberark-pas-safe-member-add
            "name": "NewName",
            "platformId": "WinServerLocal",
            "safeName": "TestSafe1",
            "secretManagement": {
### cyberark-pas-safe-member-delete

***
Remove a specific member from a safe.

#### Base Command

`cyberark-pas-safe-member-delete`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The URL encoded name of the safe to delete a member from. | Required | 
| member_name | The name of the safe member to delete from the safe’s list of members. | Required | 

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Members.Deleted | Boolean | Whether the safe member was deleted. | 

#### Command Example

```!cyberark-pas-accounts-list limit=2```

#### Context Example

{
“CyberArkPAS”: {
“Accounts”: [
{
“address”: “string”,
“categoryModificationTime”: 1594569595,
“createdTime”: 1594573679,
“id”: “2_6”,
“name”: “account1”,
“platformAccountProperties”: {},
“platformId”: “Oracle”,
“safeName”: “VaultInternal”,
“secretManagement”: {
“automaticManagementEnabled”: true,
“lastModifiedTime”: 159459279
},
“secretType”: “password”,
“userName”: “string”
},
{
“address”: “string”,
“categoryModificationTime”: 1583345933,
“createdTime”: 157312750,
“id”: “2_3”,
“name”: “cybr”,
“platformAccountProperties”: {},
“platformId”: “WinDomain”,
“safeName”: “VaultInternal”,
“secretManagement”: {
“automaticManagementEnabled”: false,
“lastModifiedTime”: 157319750,
“manualManagementReason”: “NoReason”
},
“secretType”: “password”,
“userName”: “vault”
}
]
}
}


#### Human Readable Output

>### There are 2 accounts
>
>|address|categoryModificationTime|createdTime|id|name|platformAccountProperties|platformId|safeName|secretManagement|secretType|userName|
>|---|---|---|---|---|---|---|---|---|---|---|
>| string | 1594569595 | 1594573679 | 2_6 | account1 |  | Oracle | VaultInternal | automaticManagementEnabled: true<br/>lastModifiedTime: 1594559279 | password | string |
>| string | 1583345933 | 1573127750 | 2_3 | cybr|  | WinDomain | VaultInternal | automaticManagementEnabled: false<br/>manualManagementReason: NoReason<br/>lastModifiedTime: 1573109750 | password | vault |

### cyberark-pas-account-get-list-activity

***
Returns the activities of a specific account that is identified by its account ID.

#### Base Command

`cyberark-pas-account-get-list-activity`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| account_id | The ID of the account whose activities will be retrieved. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Activities.Action | String | The activity that was performed. |
| CyberArkPAS.Activities.ActionID | Number | The code identification of the specific activity. |
| CyberArkPAS.Activities.Alert | Boolean | Whether or not the activity caused an alert. |
| CyberArkPAS.Activities.ClientID | String | The name of the account. |
| CyberArkPAS.Activities.Date | Number | The date the account was created. |
| CyberArkPAS.Activities.MoreInfo | String | More information about the activity. |
| CyberArkPAS.Activities.Reason | String | The reason given by the user for the activity. |
| CyberArkPAS.Activities.User | String | The user who performed the activity. |

#### Command Example

```!cyberark-pas-account-get-list-activity account_id= 89_3```

#### Context Example

{
“CyberArkPAS”: {
“Activities”: [
{
“Action”: “Rename File”,
“ActionID”: 124,
“Alert”: false,
“ClientID”: “1”,
“Date”: 1597863265,
“MoreInfo”: “NewName”,

cyberark-pas-account-update


Update the details of an existing account.

To run this command, you must have the following permissions in the Safe:

  • For updating account properties: Update Password Properties.
  • For renaming accounts: Rename Accounts.
  • For moving accounts to a different folder: Move Accounts or Move Folders.

Base Command

cyberark-pas-account-update

Input

Argument Name Description Required
account_id The unique ID of the account to update. Required
account_name The name of the account to update. Optional
address The name or address of the machine where the account will be used. Optional
platform_id The platform assigned to this account. Optional
username The user name of the account. Optional

Context Output

Path Type Description
CyberArkPAS.Accounts.id String The unique ID of the account.
CyberArkPAS.Accounts.categoryModificationTime Number The last modified date of the account.
CyberArkPAS.Accounts.createdTime Number The date the account was created.
CyberArkPAS.Accounts.name String The name of the account.
CyberArkPAS.Accounts.platformId String The platform assigned to this account.
CyberArkPAS.Accounts.safeName String The safe where the account was created.
CyberArkPAS.Accounts.secretManagement String Whether the account secret is automatically managed by the CPM.
CyberArkPAS.Accounts.secretType String The type of password.
CyberArkPAS.Accounts.userName String The user name of the account.
CyberArkPAS.Accounts.address String The name or address of the machine where the account will be used.

Command Example

!cyberark-pas-account-update account_id= 89_3 account_name=NewName

Context Example

{
    "CyberArkPAS": {
        "Accounts": {
            "address": "/",
            "categoryModificationTime": 1597863168,
            "createdTime": 1597863168,
            "id": "89_3",
            "name": "NewName",
            "platformId": "WinServerLocal",
            "safeName": "TestSafe1",
            "secretManagement": {
### cyberark-pas-safe-member-delete

***
Remove a specific member from a safe.

#### Base Command

`cyberark-pas-safe-member-delete`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| safe_name | The URL encoded name of the safe to delete a member from. | Required | 
| member_name | The name of the safe member to delete from the safe’s list of members. | Required | 

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Safes.Members.Deleted | Boolean | Whether the safe member was deleted. | 

#### Command Example

```!cyberark-pas-accounts-list limit=2```

#### Context Example

{
“CyberArkPAS”: {
“Accounts”: [
{
“address”: “string”,
“categoryModificationTime”: 1594569595,
“createdTime”: 1594573679,
“id”: “2_6”,
“name”: “account1”,
“platformAccountProperties”: {},
“platformId”: “Oracle”,
“safeName”: “VaultInternal”,
“secretManagement”: {
“automaticManagementEnabled”: true,
“lastModifiedTime”: 159459279
},
“secretType”: “password”,
“userName”: “string”
},
{
“address”: “string”,
“categoryModificationTime”: 1583345933,
“createdTime”: 157312750,
“id”: “2_3”,
“name”: “cybr”,
“platformAccountProperties”: {},
“platformId”: “WinDomain”,
“safeName”: “VaultInternal”,
“secretManagement”: {
“automaticManagementEnabled”: false,
“lastModifiedTime”: 157319750,
“manualManagementReason”: “NoReason”
},
“secretType”: “password”,
“userName”: “vault”
}
]
}
}


#### Human Readable Output

>### There are 2 accounts
>
>|address|categoryModificationTime|createdTime|id|name|platformAccountProperties|platformId|safeName|secretManagement|secretType|userName|
>|---|---|---|---|---|---|---|---|---|---|---|
>| string | 1594569595 | 1594573679 | 2_6 | account1 |  | Oracle | VaultInternal | automaticManagementEnabled: true<br/>lastModifiedTime: 1594559279 | password | string |
>| string | 1583345933 | 1573127750 | 2_3 | cybr|  | WinDomain | VaultInternal | automaticManagementEnabled: false<br/>manualManagementReason: NoReason<br/>lastModifiedTime: 1573109750 | password | vault |

### cyberark-pas-account-get-list-activity

***
Returns the activities of a specific account that is identified by its account ID.

#### Base Command

`cyberark-pas-account-get-list-activity`

#### Input

| **Argument Name** | **Description** | **Required** |
| --- | --- | --- |
| account_id | The ID of the account whose activities will be retrieved. | Required |

#### Context Output

| **Path** | **Type** | **Description** |
| --- | --- | --- |
| CyberArkPAS.Activities.Action | String | The activity that was performed. |
| CyberArkPAS.Activities.ActionID | Number | The code identification of the specific activity. |
| CyberArkPAS.Activities.Alert | Boolean | Whether or not the activity caused an alert. |
| CyberArkPAS.Activities.ClientID | String | The name of the account. |
| CyberArkPAS.Activities.Date | Number | The date the account was created. |
| CyberArkPAS.Activities.MoreInfo | String | More information about the activity. |
| CyberArkPAS.Activities.Reason | String | The reason given by the user for the activity. |
| CyberArkPAS.Activities.User | String | The user who performed the activity. |

#### Command Example

```!cyberark-pas-account-get-list-activity account_id= 89_3```

#### Context Example

{
“CyberArkPAS”: {
“Activities”: [
{
“Action”: “Rename File”,
“ActionID”: 124,
“Alert”: false,
“ClientID”: “1”,
“Date”: 1597863265,
“MoreInfo”: “NewName”,

cyberark-pas-account-delete


Delete a specific account in the vault.

Base Command

cyberark-pas-account-delete

Input

Argument Name Description Required
account_id The unique ID of the account to delete. Required

Context Output

Path Type Description
CyberArkPAS.Accounts.id String The unique ID of the account.
CyberArkPAS.Accounts.secretManagement String Whether the account secret is automatically managed by the CPM.
CyberArkPAS.Accounts.address String The name or address of the machine where the account will be used.
CyberArkPAS.Accounts.secretType String The type of password.
CyberArkPAS.Accounts.safeName String The safe where the account was created.
CyberArkPAS.Accounts.userName String The user name of the account.
CyberArkPAS.Accounts.Deleted Boolean Whether the account was deleted.

Context Output

Path Type Description
CyberArkPAS.Accounts.id String The unique ID of the account.
CyberArkPAS.Accounts.categoryModificationTime Number The date the account was last modified.
CyberArkPAS.Accounts.createdTime Number The date the account was created.
CyberArkPAS.Accounts.name String The name of the account.
CyberArkPAS.Accounts.platformId String The platform assigned to this account.
CyberArkPAS.Accounts.safeName String The safe where the account is created.
CyberArkPAS.Accounts.secretManagement String Whether the account secret is automatically managed by the CPM.
CyberArkPAS.Accounts.secretType String The type of password.
CyberArkPAS.Accounts.userName String The name of the account user.
CyberArkPAS.Accounts.address String The name or address of the machine where the account will be used.

Command Example

!cyberark-pas-account-get-details account_id=46_7

Context Example

{
    "CyberArkPAS": {
        "Accounts": {
            "address": "address.com",
            "categoryModificationTime": 1597581174,
            "createdTime": 1595431869,
            "id": "46_7",
            "name": "Operating System-UnixSSH",
            "platformAccountProperties": {
                "Tags": "SSH",
                "UseSudoOnReconcile": "No"
            },
            "platformId": "UnixSSH",
            "safeName": "Linux Accounts",
            "secretManagement": {
                "automaticManagementEnabled": true,
                "lastModifiedTime": 1595417469,
                "lastReconciledTime": 1576120341,
                "status": "success"
            },
            "secretType": "password",
            "userName": "user1"
        }
    }
}

Human Readable Output

Results

address categoryModificationTime createdTime id name platformAccountProperties platformId safeName secretManagement secretType userName
address 1597581174 1595431869 46_7 Operating System-UnixSSH UseSudoOnReconcile: No
Tags: SSH
UnixSSH Linux Accounts automaticManagementEnabled: true
status: success
lastModifiedTime: 1595417469
lastReconciledTime: 1576120341
password user1

cyberark-pas-credentials-change-in-vault-only


Enable users to set account credentials and change them in the vault.

To run this command, you must have Update Password Value credentials in the Safe where the privileged account is stored.

Base Command

cyberark-pas-credentials-change-in-vault-only

Input

Argument Name Description Required
account_id The unique ID of the account. Required
new_credentials The new account credentials that will be allocated to the account in the vault. Required

Context Output

There is no context output for this command.

Command Example

!cyberark-pas-credentials-change-in-vault-only account_id=89_4 new_credentials=1234Asw

Human Readable Output

The password in the account 89_4 was changed

cyberark-pas-credentials-verify


Mark an account for verification by the Central Policy Manager (CPM).

To run this command, you must have Initiate CPM password management operations permission in the Safe where the privileged account is stored.

Base Command

cyberark-pas-credentials-verify

Input

Argument Name Description Required
account_id The unique ID of the account. Required

Context Output

There is no context output for this command.

Command Example

!cyberark-pas-credentials-verify account_id=89_4

Human Readable Output

The account 89_4 was marked for verification by the CPM

cyberark-pas-credentials-reconcile


Mark an account for automatic reconciliation by the Central Policy Manager (CPM).

To run this command, you must have Initiate CPM password management operations permission in the Safe where the privileged account is stored.

Base Command

cyberark-pas-credentials-reconcile

Input

Argument Name Description Required
account_id The unique ID of the account. Required

Context Output

There is no context output for this command.

Command Example

!cyberark-pas-credentials-reconcile account_id=89_4

Human Readable Output

The account 89_4 was marked for automatic reconciliation by the CPM.

cyberark-pas-credentials-change-random-password


Mark an account for an immediate credentials change by the CPM to a new random value.

To run this command, you must have the following permissions in the Safe where the privileged account is stored:

  • Initiate CPM password management operations
  • Specify next password value

Base Command

cyberark-pas-credentials-change-random-password

Input

Argument Name Description Required
account_id The unique ID of the account. Required

Context Output

There is no context output for this command.

Command Example

!cyberark-pas-credentials-change-random-password account_id=89_4

Human Readable Output

The password in the account 89_4 was changed

cyberark-pas-credentials-change-set-new-password


Enable users to set the account’s credentials to use for the next Central Policy Manager (CPM) change.

To run this command, you must have Update Password Value credentials in the Safe where the privileged account is stored.

Base Command

cyberark-pas-credentials-change-set-new-password

Input

Argument Name Description Required
account_id The unique ID of the account. Required
new_credentials The new account credentials that will be allocated to the account in the vault. Required

Context Output

There is no context output for this command.

Command Example

!cyberark-pas-credentials-change-set-new-password account_id=89_4

Human Readable Output

The password in the account 89_4 was changed

cyberark-pas-security-events-get


Return all Privileged Threat Analytics (PTA) security events.

Base Command

cyberark-pas-security-events-get

Input

Argument Name Description Required
start_time The starting date to get the security events from. Must be in the following timestamp format:
(<number> <time unit>, e.g., 12 hours, 7 days, 3 months, 1 year).
Required
limit The number of events that will be shown, from newest to oldest. Default is ‘50’. Optional

Context Output

Path Type Description
CyberArkPAS.SecurityEvents.id Number The unique ID of the security events.
CyberArkPAS.SecurityEvents.additionalData String Additional data about the security events.
CyberArkPAS.SecurityEvents.audits.createTime Number The time the security events were created.
CyberArkPAS.SecurityEvents.lastUpdateTime Number The last update time of the security events.
CyberArkPAS.SecurityEvents.mStatus String The status of the security events.
CyberArkPAS.SecurityEvents.score Number The score of the security events.
CyberArkPAS.SecurityEvents.type String The type of the security events.

Command Example

!cyberark-pas-security-events-get start_time="3 days" limit=2

Context Example

{
    "CyberArkPAS": {
        "SecurityEvents": [
            {
                "additionalData": {
                    "reason": "ip",
                    "station": "1.1.1.1",
                    "vault_user": "administrator"                
                },
                "audits": [
                    {
                        "action": "Logon",
                        "cloudData": {},
                        "createTime": 1597864497000,
                        "id": "1a2b3c4d",
                        "sensorType": "VAULT",
                        "source": {
                            "mOriginalAddress": "1.1.1.1",
                            "mResolvedAddress": {
                                "mAddress": "1.1.1.1",
                                "mFqdn": "1-2-3-4",
                                "mHostName": "1-2-3-4",
                                "mOriginalAddress": "1.1.1.1",
                            }
                        },
                        "type": "VAULT_LOGON",
                        "vaultUser": "Administrator"
                    }
                ],
                "createTime": 1597864497000,
                "id": "1",
                "lastUpdateTime": 1597864497000,
                "mStatus": "OPEN",
                "score": 25.751749103263528,
                "type": "VaultViaIrregularIp"
            },
            {
                "additionalData": {
                    "reason": "ip",
                    "station": "1.1.1.1",
                    "vault_user": "administrator"
                },
                "audits": [
                    {
                        "action": "Logon",
                        "cloudData": {},
                        "createTime": 1597864209000,
                        "id": "5f3d7911e4b0b8d4ac363b1b",
                        "sensorType": "VAULT",
                        "source": {
                            "mOriginalAddress": "1.1.1.1",
                            "mResolvedAddress": {
                                "mAddress": "1.1.1.1",
                                "mFqdn": "1-2-3-4",
                                "mHostName": "1-2-3-4",
                                "mOriginalAddress": "1.1.1.1",
                            }
                        },
                        "type": "VAULT_LOGON",
                        "vaultUser": "Administrator"
                    }
                ],
                "createTime": 1597864209000,
                "id": "2",
                "lastUpdateTime": 1597864209000,
                "mStatus": "OPEN",
                "score": 25.751749103263528,
                "type": "VaultViaIrregularIp"
            }
        ]
    }
}

Human Readable Output

Results

additionalData audits createTime id lastUpdateTime mStatus score type
station: 1.1.1.1
reason: ip
vault_user: administrator
{‘id’: ‘1’, ‘type’: ‘VAULT_LOGON’, ‘sensorType’: ‘VAULT’, ‘action’: ‘Logon’, ‘createTime’: 1597864497000, ‘vaultUser’: ‘Administrator’, ‘source’: {‘mOriginalAddress’: ‘1.1.1.1’, ‘mResolvedAddress’: {‘mOriginalAddress’: ‘1.1.1.1’, ‘mAddress’: ‘1.1.1.1’, ‘mHostName’: ‘1-2-3-4’, ‘mFqdn’: ‘1-2-3-4’}}, ‘cloudData’: {}} 1597864497000 1 1597864497000 OPEN 25.751749103263528 VaultViaIrregularIp
station: 1.1.1.1
reason: ip
vault_user: administrator
{‘id’: ‘2’, ‘type’: ‘VAULT_LOGON’, ‘sensorType’: ‘VAULT’, ‘action’: ‘Logon’, ‘createTime’: 1597864209000, ‘vaultUser’: ‘Administrator’, ‘source’: {‘mOriginalAddress’: ‘1.1.1.1’, ‘mResolvedAddress’: {‘mOriginalAddress’: ‘1.1.1.1’, ‘mAddress’: ‘1.1.1.1’, ‘mHostName’: ‘1-2-3-4’, ‘mFqdn’: ‘1-2-3-4’}}, ‘cloudData’: {}} 1597864209000 2 1597864209000 OPEN 25.751749103263528 VaultViaIrregularIp

cyberark-pas-account-add


Add a new privileged account or SSH key to the vault.

Base Command

cyberark-pas-account-add

Input

Argument Name Description Required
account_name The name of the account. Required
address The name or address of the machine where the account will be used. Required
platform_id The platform assigned to this account. Required
safe_name The name of the safe where the account will be created. Required
secret_type The type of password. Valid values are: ‘password’, ‘key’. Default is ‘password’. Possible values are: password, key. Default is password. Optional
username The The user name of the account. Required
password The password that the user will use to log on for the first time. Required
properties Object containing key-value pairs to associate with the account, as defined by the account platform.
e.g., {“Location”: “IT”, “OwnerName”: “MSSPAdmin”}.
Optional
automatic_management_enabled Whether the account secret is automatically managed by the Central Policy Manager (CPM). Can be ‘true’ or ‘false’. Default is ‘true’. Possible values are: true, false. Default is true. Optional
manual_management_reason The reason for disabling automatic secret management. Optional
remote_machines List of remote machines, separated by semicolons.
e.g., server1.cyberark.com;server2.cyberark.com.
Optional
access_restricted_to_remote_machines Whether or not to restrict access to specified remote machines only. Can be ‘true’ or ‘false’. Default is: ‘true’. Possible values are: true, false. Default is true. Optional

Context Output

Path Type Description
CyberArkPAS.Accounts.id String The unique ID of the account.
CyberArkPAS.Accounts.categoryModificationTime Number The last modified date of the account.
CyberArkPAS.Accounts.createdTime Number The date the account was created.
CyberArkPAS.Accounts.name String The name of the account.
CyberArkPAS.Accounts.platformId String The platform assigned to this account.
CyberArkPAS.Accounts.safeName String The safe where the account is created.
CyberArkPAS.Accounts.secretManagement String Whether the account secret is automatically managed by the CPM.
CyberArkPAS.Accounts.secretType String The type of password.
CyberArkPAS.Accounts.userName String The name of the account user.
CyberArkPAS.Accounts.address String The name or address of the machine where the account will be used.

Configuration parameters

  • url — Server URL (e.g., https://example.net) (required)
  • credentials — Username (required)
  • isFetch — Fetch incidents
  • max_fetch — Max fetch
  • fetch_time — First fetch timestamp (<number> <time unit>, e.g., 12 hours, 7 days, 3 months, 1 year)
  • score — CyberArk PAM score (0.0-100.0)
  • incidentType — Incident type
  • incidentFetchInterval — Incidents Fetch Interval
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings

Commands (26)

  • cyberark-pas-account-add

    Add a new privileged account or SSH key to the vault.

  • cyberark-pas-account-delete

    Delete a specific account in the vault.

  • cyberark-pas-account-get-details

    Returns information for the specified account, identified by the account ID.

  • cyberark-pas-account-get-list-activity

    Returns the activities of a specific account that is identified by its account ID.

  • cyberark-pas-account-update

    Update the details of an existing account.

  • cyberark-pas-accounts-list

    Return a list of all the accounts in the vault.

  • cyberark-pas-credentials-change-in-vault-only

    Enable users to set account credentials and change them in the vault.

  • cyberark-pas-credentials-change-random-password

    Mark an account for an immediate credentials change by the CPM to a new random value.

  • cyberark-pas-credentials-change-set-new-password

    Enable users to set the account's credentials to use for the next Central Policy Manager (CPM) change.

  • cyberark-pas-credentials-reconcile

    Mark an account for automatic reconciliation by the Central Policy Manager (CPM).

  • cyberark-pas-credentials-verify

    Mark an account for verification by the Central Policy Manager (CPM).

  • cyberark-pas-safe-add

    Add a new safe to the vault.

  • cyberark-pas-safe-delete

    Delete a safe from the vault.

  • cyberark-pas-safe-get-by-name

    Return information about a specific safe in the vault.

  • cyberark-pas-safe-member-add

    Add an existing user as a safe member.

  • cyberark-pas-safe-member-delete

    Remove a specific member from a safe.

  • cyberark-pas-safe-member-update

    Update an existing safe member.

  • cyberark-pas-safe-members-list

    Return a list of the members of the safe.

  • cyberark-pas-safe-update

    Update a single safe in the vault.

  • cyberark-pas-safes-list

    Return information about all of the user’s safes in the vault.

  • cyberark-pas-security-events-get

    Return all Privileged Threat Analytics (PTA) security events.

  • cyberark-pas-user-activate

    Activate an existing vault user who was suspended after entering incorrect credentials multiple times.

  • cyberark-pas-user-add

    Add a new user to the vault.

  • cyberark-pas-user-delete

    Delete a specific user in the vault.

  • cyberark-pas-user-update

    Update an existing vault user.

  • cyberark-pas-users-list

    Return a list of all existing users in the vault that meet the filter and search criteria.

import demistomock as demisto  # noqa: F401
from CommonServerPython import *  # noqa: F401

from CommonServerUserPython import *

import urllib3
import traceback

# Disable insecure warnings

urllib3.disable_warnings()
DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ"


def parse_date_range_expire_date(date_range):
    """
    Parses date_range string to a tuple date strings (start, end). Input must be in format 'number date_range_unit')
    Examples: (2 hours, 4 minutes, 6 month, 1 day, etc.)

    :type date_range: ``str``
    :param date_range: The date range to be parsed (required)

    :return: The parsed date range forward in sec (and not msec)
    :rtype: ``int``
    """
    range_split = date_range.split(" ")
    if len(range_split) != 2:
        return_error('date_range must be "number date_range_unit", examples: (2 hours, 4 minutes,6 months, 1 day, etc.)')

    number = int(range_split[0])
    if range_split[1] not in ["minute", "minutes", "hour", "hours", "day", "days", "month", "months", "year", "years"]:
        return_error("The unit of date_range is invalid. Must be minutes, hours, days, months or years")

    start_time = datetime.now() + timedelta(hours=0)
    end_time = datetime.now() + timedelta(hours=0)

    unit = range_split[1]
    if "minute" in unit:
        end_time = start_time + timedelta(minutes=number)
    elif "hour" in unit:
        end_time = start_time + timedelta(hours=number)
    elif "day" in unit:
        end_time = start_time + timedelta(days=number)
    elif "month" in unit:
        end_time = start_time + timedelta(days=number * 30)
    elif "year" in unit:
        end_time = start_time + timedelta(days=number * 365)

    return date_to_timestamp(end_time) / 1000


def incident_priority_to_dbot_score(score: float) -> int:
    """Converts the CyberArk score to DBot score representation,
    while the CyberArk score is a value between 0.0-100.0 and the DBot score is 1,2 or 3.
    Can be one of:
        0.0 - 35.0 ->  1
        35.1 - 75.0 ->  2
        75.1 - 100.0 ->  3
    """

    if 0 <= score <= 35:
        return 1
    elif 35 < score <= 75:
        return 2
    elif 75 < score <= 100:
        return 3
    return 0


def order_properties_to_dict(properties: str | dict) -> dict:
    """
    ordering the properties so that they are valid json for the api
    """
    if not properties:
        return {}
    if isinstance(properties, dict):
        return properties
    elif isinstance(properties, str):
        try:
            return json.loads(properties.replace("'", '"'))
        except json.decoder.JSONDecodeError:
            raise ValueError(f"Properties ({properties}) are not valid JSON")
    else:
        raise ValueError(f"Properties must be a JSON string or dictionary (got {properties})")


def filter_by_score(events_data: list, score: int) -> list:
    if score == 0:
        return events_data

    filtered_event_score = []
    for event in events_data:
        if event.get("score") >= score:
            filtered_event_score.append(event)
    return filtered_event_score


class Client(BaseClient):
    """
    Client to use in the CyberArk PAS integration. Uses BaseClient
    """

    def __init__(self, server_url: str, username: str, password: str, use_ssl: bool, proxy: bool, max_fetch: int):
        super().__init__(base_url=server_url, verify=use_ssl, proxy=proxy)
        self._username = username
        self._password = password
        self._max_fetch = max_fetch
        self._token = self._generate_token()
        self._headers = {"Authorization": self._token, "Content-Type": "application/json"}

    def _generate_token(self) -> str:
        """Generate an Access token using the user name and password
        :return: valid token
        """
        body = {
            "username": self._username,
            "password": self._password,
        }

        headers = {"Content-Type": "application/json"}
        return self._http_request("POST", "/PasswordVault/API/Auth/CyberArk/Logon", headers=headers, json_data=body)

    def _logout(self):
        self._http_request("POST", "/PasswordVault/API/Auth/Logoff")

    def add_user(
        self,
        username: str,
        user_type: str,
        non_authorized_interfaces: list,
        expiry_date: str,
        password: str,
        change_password_on_the_next_logon: str,
        password_never_expires: str,
        vault_authorization: list,
        description: str,
        email: str,
        first_name: str,
        last_name: str,
        enable_user: str,
        profession: str,
        distinguished_name: str,
        location: str,
    ):
        url_suffix = "/PasswordVault/api/Users"
        body = {
            "username": username,
            "userType": user_type,
            "initialPassword": password,
            "authenticationMethod": ["AuthTypePass"],
            "location": location,
            "unAuthorizedInterfaces": non_authorized_interfaces,
            "expiryDate": expiry_date,
            "vaultAuthorization": vault_authorization,
            "enableUser": enable_user == "true",
            "changePassOnNextLogon": change_password_on_the_next_logon == "true",  # guardrails-disable-line
            "passwordNeverExpires": password_never_expires == "true",  # guardrails-disable-line
            "distinguishedName": distinguished_name,
            "description": description,
            "internet": {
                "businessEmail": email,
            },
            "personalDetails": {
                "profession": profession,
                "firstName": first_name,
                "lastName": last_name,
            },
        }

        return self._http_request("POST", url_suffix, json_data=body)

    def update_user(
        self,
        user_id: str,
        username: str,
        user_type: str,
        non_authorized_interfaces: list,
        expiry_date: str,
        change_password_on_the_next_logon: str,
        password_never_expires: str,
        vault_authorization: list,
        description: str,
        email: str,
        first_name: str,
        last_name: str,
        enable_user: str,
        profession: str,
        distinguished_name: str,
        location: str,
    ):
        url_suffix = f"/PasswordVault/api/Users/{user_id}"
        body = {
            "enableUser": enable_user == "true",
            "changePassOnNextLogon": change_password_on_the_next_logon == "true",  # guardrails-disable-line
            "expiryDate": expiry_date,
            "unAuthorizedInterfaces": non_authorized_interfaces,
            "authenticationMethod": ["AuthTypePass"],
            "passwordNeverExpires": password_never_expires == "true",  # guardrails-disable-line
            "distinguishedName": distinguished_name,
            "description": description,
            "internet": {
                "businessEmail": email,
            },
            "personalDetails": {"profession": profession, "firstName": first_name, "lastName": last_name},
            "id": user_id,
            "username": username,
            "source": "CyberArk",
            "userType": user_type,
            "vaultAuthorization": vault_authorization,
            "location": location,
        }

        return self._http_request("PUT", url_suffix, json_data=body)

    def delete_user(self, user_id: str):
        url_suffix = f"/PasswordVault/api/Users/{user_id}"

        # json is not defined for this response, therefore we wish to get the "text" value back
        self._http_request("DELETE", url_suffix, resp_type="text")

    def get_users(
        self,
        filter: str,
        search: str,
    ):
        url_suffix = "/PasswordVault/api/Users"

        params = {
            "filter": filter,
            "search": search,
        }

        return self._http_request("GET", url_suffix, params=params)

    def activate_user(self, user_id: str):
        url_suffix = f"/PasswordVault/API/Users/{user_id}/Activate"

        self._http_request("POST", url_suffix, resp_type="text")

    def get_list_safes(self):
        url_suffix = "/PasswordVault/api/Safes"

        return self._http_request("GET", url_suffix)

    def get_safe_by_name(self, safe_name: str):
        url_suffix = f"/PasswordVault/api/Safes/{safe_name}"

        return self._http_request("GET", url_suffix)

    def add_safe(
        self,
        safe_name: str,
        description: str,
        OLAC_enabled: str,
        managing_cpm: str,
        number_of_versions_retention: str,
        number_of_days_retention: str,
        location: str,
    ):
        url_suffix = "/PasswordVault/api/Safes"

        body = {
            "SafeName": safe_name,
            "Description": description,
            "OLACEnabled": OLAC_enabled == "true",
            "ManagingCPM": managing_cpm,
            "NumberOfVersionsRetention": number_of_versions_retention,
            "NumberOfDaysRetention": number_of_days_retention,
            "Location": location,
        }
        return self._http_request("POST", url_suffix, json_data=body)

    def update_safe(
        self,
        safe_name: str,
        safe_new_name: str,
        description: str,
        OLAC_enabled: str,
        managing_cpm: str,
        number_of_versions_retention: str,
        number_of_days_retention: str,
        location: str = "",
    ):
        url_suffix = f"/PasswordVault/api/Safes/{safe_name}"
        if not safe_new_name:
            safe_new_name = safe_name
        body = {
            "SafeName": safe_new_name,
            "Description": description,
            "OLACEnabled": OLAC_enabled == "true",
            "ManagingCPM": managing_cpm,
            "NumberOfVersionsRetention": number_of_versions_retention,
            "NumberOfDaysRetention": number_of_days_retention,
            "Location": location,
        }
        return self._http_request("PUT", url_suffix, json_data=body)

    def delete_safe(
        self,
        safe_name: str,
    ):
        url_suffix = f"/PasswordVault/api/Safes/{safe_name}"

        # json is not defined for this response, therefore we wish to get the "text" value back
        return self._http_request("DELETE", url_suffix, resp_type="text")

    def list_safe_members(self, safe_name: str):
        url_suffix = f"/PasswordVault/api/Safes/{safe_name}/Members"

        return self._http_request("GET", url_suffix)

    def add_safe_member(
        self,
        safe_name: str,
        member_name: str,
        requests_authorization_level: str,
        membership_expiration_date: str,
        permissions: list,
        search_in: str,
    ):
        url_suffix = f"/PasswordVault/API/Safes/{safe_name}/Members"

        body = {
            "member": {
                "MemberName": member_name,
                "SearchIn": search_in,
                "MembershipExpirationDate": membership_expiration_date,
                "Permissions": [
                    {"Key": "UseAccounts", "Value": "UseAccounts" in permissions},
                    {"Key": "RetrieveAccounts", "Value": "RetrieveAccounts" in permissions},
                    {"Key": "ListAccounts", "Value": "ListAccounts" in permissions},
                    {"Key": "AddAccounts", "Value": "AddAccounts" in permissions},
                    {"Key": "UpdateAccountContent", "Value": "UpdateAccountContent" in permissions},
                    {"Key": "UpdateAccountProperties", "Value": "UpdateAccountProperties" in permissions},
                    {
                        "Key": "InitiateCPMAccountManagementOperations",
                        "Value": "InitiateCPMAccountManagementOperations" in permissions,
                    },
                    {"Key": "SpecifyNextAccountContent", "Value": "SpecifyNextAccountContent" in permissions},
                    {"Key": "RenameAccounts", "Value": "RenameAccounts" in permissions},
                    {"Key": "DeleteAccounts", "Value": "DeleteAccounts" in permissions},
                    {"Key": "UnlockAccounts", "Value": "UnlockAccounts" in permissions},
                    {"Key": "ManageSafe", "Value": "ManageSafe" in permissions},
                    {"Key": "ManageSafeMembers", "Value": "ManageSafeMembers" in permissions},
                    {"Key": "BackupSafe", "Value": "BackupSafe" in permissions},
                    {"Key": "ViewAuditLog", "Value": "ViewAuditLog" in permissions},
                    {"Key": "ViewSafeMembers", "Value": "ViewSafeMembers" in permissions},
                    {"Key": "RequestsAuthorizationLevel", "Value": int(requests_authorization_level)},
                    {"Key": "AccessWithoutConfirmation", "Value": "AccessWithoutConfirmation" in permissions},
                    {"Key": "CreateFolders", "Value": "CreateFolders" in permissions},
                    {"Key": "DeleteFolders", "Value": "DeleteFolders" in permissions},
                    {"Key": "MoveAccountsAndFolders", "Value": "MoveAccountsAndFolders" in permissions},
                ],
            }
        }
        return self._http_request("POST", url_suffix, json_data=body)

    def add_account(
        self,
        account_name: str,
        address: str,
        username: str,
        platform_id: str,
        safe_name: str,
        password: str,
        secret_type: str,
        properties: dict,
        automatic_management_enabled: str,
        manual_management_reason: str,
        remote_machines: str,
        access_restricted_to_temote_machines: str,
    ):
        url_suffix = "/PasswordVault/api/Accounts"

        body = {
            "name": account_name,
            "address": address,
            "userName": username,
            "platformId": platform_id,
            "safeName": safe_name,
            "secretType": secret_type,
            "secret": password,
            "platformAccountProperties": properties,
            "secretManagement": {
                "automaticManagementEnabled": automatic_management_enabled == "true",
                "manualManagementReason": manual_management_reason,
            },
            "remoteMachinesAccess": {
                "remoteMachines": remote_machines,
                "accessRestrictedToRemoteMachines": access_restricted_to_temote_machines == "true",
            },
        }
        return self._http_request("POST", url_suffix, json_data=body)

    def update_safe_member(
        self,
        safe_name: str,
        member_name: str,
        requests_authorization_level: str,
        membership_expiration_date: str,
        permissions: list,
    ):
        """
        This function uses the V1 CyberArk PAS api, currently there is no matching function in V2
        """
        url_suffix = f"/PasswordVault/API/Safes/{safe_name}/Members/{member_name}"

        body = {
            "member": {
                "MembershipExpirationDate": membership_expiration_date,
                "Permissions": [
                    {"Key": "UseAccounts", "Value": "UseAccounts" in permissions},
                    {"Key": "RetrieveAccounts", "Value": "RetrieveAccounts" in permissions},
                    {"Key": "ListAccounts", "Value": "ListAccounts" in permissions},
                    {"Key": "AddAccounts", "Value": "AddAccounts" in permissions},
                    {"Key": "UpdateAccountContent", "Value": "UpdateAccountContent" in permissions},
                    {"Key": "UpdateAccountProperties", "Value": "UpdateAccountProperties" in permissions},
                    {
                        "Key": "InitiateCPMAccountManagementOperations",
                        "Value": "InitiateCPMAccountManagementOperations" in permissions,
                    },
                    {"Key": "SpecifyNextAccountContent", "Value": "SpecifyNextAccountContent" in permissions},
                    {"Key": "RenameAccounts", "Value": "RenameAccounts" in permissions},
                    {"Key": "DeleteAccounts", "Value": "DeleteAccounts" in permissions},
                    {"Key": "UnlockAccounts", "Value": "UnlockAccounts" in permissions},
                    {"Key": "ManageSafe", "Value": "ManageSafe" in permissions},
                    {"Key": "ManageSafeMembers", "Value": "ManageSafeMembers" in permissions},
                    {"Key": "BackupSafe", "Value": "BackupSafe" in permissions},
                    {"Key": "ViewAuditLog", "Value": "ViewAuditLog" in permissions},
                    {"Key": "ViewSafeMembers", "Value": "ViewSafeMembers" in permissions},
                    {"Key": "RequestsAuthorizationLevel", "Value": int(requests_authorization_level)},
                    {"Key": "AccessWithoutConfirmation", "Value": "AccessWithoutConfirmation" in permissions},
                    {"Key": "CreateFolders", "Value": "CreateFolders" in permissions},
                    {"Key": "DeleteFolders", "Value": "DeleteFolders" in permissions},
                    {"Key": "MoveAccountsAndFolders", "Value": "MoveAccountsAndFolders" in permissions},
                ],
            }
        }
        return self._http_request("PUT", url_suffix, json_data=body)

    def delete_safe_member(
        self,
        safe_name: str,
        member_name: str,
    ):
        """
        This function uses the V1 CyberArk PAS api, currently there is no matching function in V2
        """
        url_suffix = f"/PasswordVault/API/Safes/{safe_name}/Members/{member_name}"

        self._http_request("DELETE", url_suffix, resp_type="text")

    def delete_account(
        self,
        account_id: str,
    ):
        url_suffix = f"/PasswordVault/api/Accounts/{account_id}"

        self._http_request("DELETE", url_suffix, resp_type="text")

    def get_list_accounts(
        self,
        search: str,
        sort: str,
        offset: str,
        limit: str,
        filter: str,
    ):
        url_suffix = f"/PasswordVault/api/Accounts?search={search}&sort={sort}&offset={offset}&limit={limit}&filter={filter}"
        return self._http_request("GET", url_suffix)

    def get_list_account_activity(
        self,
        account_id: str,
    ):
        url_suffix = f"/PasswordVault/api/Accounts/{account_id}/Activities"
        return self._http_request("GET", url_suffix)

    def get_account_details(
        self,
        account_id: str,
    ):
        url_suffix = f"/PasswordVault/api/Accounts/{account_id}"
        return self._http_request("GET", url_suffix)

    def change_credentials_random_password(
        self,
        account_id: str,
    ):
        url_suffix = f"/PasswordVault/API/Accounts/{account_id}/Change"
        body = {"ChangeEntireGroup": "true"}
        self._http_request("POST", url_suffix, json_data=body, resp_type="text")

    def change_credentials_set_new_password(
        self,
        account_id: str,
        new_credentials: str,
    ):
        url_suffix = f"/passwordvault/api/Accounts/{account_id}/SetNextPassword"
        body = {
            "ChangeImmediately": True,
            "NewCredentials": new_credentials,
        }
        self._http_request("POST", url_suffix, json_data=body, resp_type="text")

    def change_credentials_in_vault_only(
        self,
        account_id: str,
        new_credentials: str,
    ):
        url_suffix = f"/passwordvault/api/Accounts/{account_id}/Password/Update"
        body = {
            "NewCredentials": new_credentials,
        }
        self._http_request("POST", url_suffix, json_data=body, resp_type="text")

    def verify_credentials(
        self,
        account_id: str,
    ):
        """
        This function uses the V1 CyberArk PAS api, currently there is no matching function in V2
        """
        url_suffix = f"/PasswordVault/API/Accounts/{account_id}/Verify"

        self._http_request("POST", url_suffix, resp_type="text")

    def reconcile_credentials(
        self,
        account_id: str,
    ):
        url_suffix = f"/PasswordVault/API/Accounts/{account_id}/Reconcile"

        self._http_request("POST", url_suffix, resp_type="text")

    def update_account(
        self,
        account_id: str,
        account_name: str,
        address: str,
        username: str,
        platform_id: str,
    ):
        url_suffix = f"/PasswordVault/api/Accounts/{account_id}"

        arguments = {"name": account_name, "address": address, "userName": username, "platformId": platform_id}
        body = []
        for key, value in arguments.items():
            if value:
                body.append({"op": "replace", "path": f"/{key}", "value": f"{value}"})

        return self._http_request("PATCH", url_suffix, data=str(body))

    def get_security_events(self, next_run: str):
        url_suffix = "/PasswordVault/API/pta/API/Events/"
        self._headers["lastUpdatedEventDate"] = next_run
        return self._http_request("GET", url_suffix)


def test_module(
    client: Client,
) -> str:
    """
    If a client was made then an accesses token was successfully reached,
    therefor, the username and password are valid and a connection was made
    checks that the fetch command works as well, using the client function -
    :param client: the client object with an access token
    :return: ok if got a valid accesses token
    """
    start, _ = parse_date_range("7 days")
    start_time_timestamp = str(date_to_timestamp(start))
    security_events = client.get_security_events(start_time_timestamp)
    # if there were security events in the last week
    if security_events:
        event = security_events[0]
        if not event.get("id") or not event.get("type") or not event.get("score"):
            raise Exception("Security events from CyberArk PAS are missing mandatory fields.")
    return "ok"


def add_user_command(
    client: Client,
    username: str,
    user_type: str = "EPVUser",
    non_authorized_interfaces: str = "",
    expiry_date: str = "",
    password: str = "",
    change_password_on_the_next_logon: str = "true",
    password_never_expires: str = "false",
    vault_authorization: str = "",
    description: str = "",
    email: str = "",
    first_name: str = "",
    last_name: str = "",
    enable_user: str = "true",
    profession: str = "",
    distinguished_name: str = "",
    location: str = "\\",
) -> CommandResults:
    """Add a new user to the vault.
    :param client: The client object with an access token
    :param username: The name of the user.
    :param user_type: User type according to the license.
    :param non_authorized_interfaces: The CyberArkPAS interfaces that this user is not authorized to.
    :param expiry_date: The date when the user expires as timestamp.
    :param password: The password that the user will use to log on for the first time.
    :param change_password_on_the_next_logon: Whether or not the user must change their password from the second
        log on onward.
    :param password_never_expires: Whether the user's password will not expire unless they decide
        to change it.
    :param vault_authorization: The user permissions.
    :param description: Notes and comments.
    :param email: The user's email addresses.
    :param first_name: The user's first name.
    :param last_name: The user's last name.
    :param enable_user: Whether the user will be enabled upon creation.
    :param profession: The user's profession.
    :param distinguished_name: The user's distinguished name.
    :param location: The location in the vault where the user will be created.
    :return: CommandResults
    """
    non_authorized_interfaces_list = argToList(non_authorized_interfaces)
    vault_authorization_list = argToList(vault_authorization)
    if expiry_date:
        expiry_date_epoch = parse_date_range_expire_date(expiry_date)
    else:
        expiry_date_epoch = ""

    response = client.add_user(
        username,
        user_type,
        non_authorized_interfaces_list,
        expiry_date_epoch,
        password,
        change_password_on_the_next_logon,
        password_never_expires,
        vault_authorization_list,
        description,
        email,
        first_name,
        last_name,
        enable_user,
        profession,
        distinguished_name,
        location,
    )
    results = CommandResults(raw_response=response, outputs_prefix="CyberArkPAS.Users", outputs_key_field="id", outputs=response)
    return results


def update_user_command(
    client: Client,
    user_id: str,
    username: str,
    user_type: str = "EPVUser",
    non_authorized_interfaces: str = "",
    expiry_date: str = "",
    change_password_on_the_next_logon: str = "true",
    password_never_expires: str = "false",
    vault_authorization: str = "",
    description: str = "",
    email: str = "",
    first_name: str = "",
    last_name: str = "",
    enable_user: str = "true",
    profession: str = "",
    distinguished_name: str = "",
    location: str = "\\",
) -> CommandResults:
    """Updates an existing vault user.
    :param client: The client object with an access token
    :param user_id: The user's unique ID.
    :param username: The name of the user.
    :param user_type: User type according to the license.
    :param non_authorized_interfaces: The CyberArkPAS interfaces that this user is not authorized to.
    :param expiry_date: The date when the user expires as timestamp.
    :param change_password_on_the_next_logon: Whether or not the user must change their password from the second
        log on onward.
    :param password_never_expires: Whether the user's password will not expire unless they decide
        to change it.
    :param vault_authorization: The user permissions.
    :param description: Notes and comments.
    :param email: The user's email addresses.
    :param first_name: The user's first name.
    :param last_name: The user's last name.
    :param enable_user: Whether the user will be enabled upon creation.
    :param profession: The user's profession.
    :param distinguished_name: The user's distinguished name.
    :param location: The location in the vault where the user will be created.
    :return: CommandResults
    """
    non_authorized_interfaces_list = argToList(non_authorized_interfaces)
    vault_authorization_list = argToList(vault_authorization)
    if expiry_date:
        expiry_date_epoch = parse_date_range_expire_date(expiry_date)
    else:
        expiry_date_epoch = ""
    response = client.update_user(
        user_id,
        username,
        user_type,
        non_authorized_interfaces_list,
        expiry_date_epoch,
        change_password_on_the_next_logon,
        password_never_expires,
        vault_authorization_list,
        description,
        email,
        first_name,
        last_name,
        enable_user,
        profession,
        distinguished_name,
        location,
    )
    results = CommandResults(raw_response=response, outputs_prefix="CyberArkPAS.Users", outputs_key_field="id", outputs=response)
    return results


def delete_user_command(
    client: Client,
    user_id: str,
) -> CommandResults:
    """Delete a specific user in the vault.
    :param client: The client object with an access token
    :param user_id: The user's unique ID.
    :return: CommandResults
    """
    # the response should be an empty string, if an error raised it would be caught in the main block
    client.delete_user(user_id)
    return CommandResults(
        readable_output=f"User {user_id} was deleted",
        outputs_prefix="CyberArkPAS.Users",
        outputs_key_field="id",
        outputs={"id": user_id, "Deleted": True},
    )


def get_users_command(
    client: Client,
    filter: str = "",
    search: str = "",
) -> CommandResults:
    """Returns a list of all existing users in the vault.
    :param client: The client object with an access token
    :param filter: Retrieve users using filters.
    :param search: Search by the values.
    :return: CommandResults
    """
    response = client.get_users(filter, search)
    total_users = response.get("Total")
    headline = f"There are {total_users} users"
    users = response.get("Users")
    results = CommandResults(
        raw_response=response,
        readable_output=tableToMarkdown(headline, users),
        outputs_prefix="CyberArkPAS.Users",
        outputs_key_field="id",
        outputs=users,
    )
    return results


def activate_user_command(
    client: Client,
    user_id: str,
) -> str:
    """Activate an existing vault user who was suspended after entering incorrect credentials multiple times.
    :param client: The client object with an access token
    :param user_id: The user's unique ID.
    :return: CommandResults
    """
    # the response should be an empty string, if an error raised it would be caught in the main block
    client.activate_user(user_id)
    return f"User {user_id} was activated"


def get_list_safes_command(
    client: Client,
):
    """Returns information about all of the user's Safes in the vault.
    :param client: The client object with an access token
    :return: CommandResults
    """
    response = client.get_list_safes()
    # from 12.1 version the response's structure was changed (Total -> count, Safes -> value)
    total_safes = response.get("Total", response.get("count"))
    headline = f"There are {total_safes} safes"
    safes = response.get("Safes", response.get("value"))
    results = CommandResults(
        raw_response=response,
        readable_output=tableToMarkdown(name=headline, t=safes),
        outputs_prefix="CyberArkPAS.Safes",
        outputs_key_field="SafeName",
        outputs=safes,
    )
    return results


def add_safe_command(
    client: Client,
    safe_name: str,
    description: str = "",
    OLAC_enabled: str = "true",
    managing_cpm: str = "",
    number_of_versions_retention: str = "",
    number_of_days_retention: str = "",
    location: str = "",
) -> CommandResults:
    """Add a new safe to the vault.
    :param client: The client object with an access token
    :param safe_name: Name of a safe to create.
    :param description: Description of the new safe.
    :param OLAC_enabled: Whether or not to enable Object Level Access Control for the new safe.
    :param managing_cpm: The name of the CPM user who will manage the new safe.
    :param number_of_versions_retention: The number of retained versions of every password that is stored in the safe.
    :param number_of_days_retention: The number of days for which password versions are saved in the safe.
    :param location: The location of the safe.
    :return: CommandResults
    """
    response = client.add_safe(
        safe_name, description, OLAC_enabled, managing_cpm, number_of_versions_retention, number_of_days_retention, location
    )
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Safes", outputs_key_field="SafeName", outputs=response
    )
    return results


def update_safe_command(
    client: Client,
    safe_name: str,
    safe_new_name: str = "",
    description: str = "",
    OLAC_enabled: str = "true",
    managing_cpm: str = "",
    number_of_versions_retention: str = "",
    number_of_days_retention: str = "",
    location: str = "",
) -> CommandResults:
    """Update a single safe in the vault.
    :param client: The client object with an access token
    :param safe_name: The name of the safe that will be updated.
    :param safe_new_name: The new name of the safe.
    :param description: Description of the new safe.
    :param OLAC_enabled: Whether or not to enable Object Level Access Control for the new safe.
    :param managing_cpm: The name of the CPM user who will manage the new safe.
    :param number_of_versions_retention: The number of retained versions of every password that is stored in the safe.
    :param number_of_days_retention: The number of days for which password versions are saved in the safe.
    :param location: The location of the safe.
    :return: CommandResults
    """
    response = client.update_safe(
        safe_name,
        safe_new_name,
        description,
        OLAC_enabled,
        managing_cpm,
        number_of_versions_retention,
        number_of_days_retention,
        location,
    )
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Safes", outputs_key_field="SafeName", outputs=response
    )
    return results


def delete_safe_command(
    client: Client,
    safe_name: str,
) -> CommandResults:
    """Delete a safe from the vault.
    :param client: The client object with an access token
    :param safe_name: Name of the safe that will be deleted.
    :return: CommandResults
    """
    # the response should be an empty string, if an error raised it would be caught in the main block
    client.delete_safe(safe_name)
    return CommandResults(
        readable_output=f"Safe {safe_name} was deleted",
        outputs_prefix="CyberArkPAS.Safes",
        outputs_key_field="SafeName",
        outputs={"SafeName": safe_name, "Deleted": True},
    )


def get_safe_by_name_command(
    client: Client,
    safe_name: str,
) -> CommandResults:
    """Return information about a specific safe in the vault.
    :param client: The client object with an access token
    :param safe_name: The name of the safe about which information is returned.
    :return: CommandResults
    """
    response = client.get_safe_by_name(safe_name)
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Safes", outputs_key_field="SafeName", outputs=response
    )
    return results


def list_safe_members_command(client: Client, safe_name: str) -> CommandResults:
    """Return a list of the members of the safe.
    :param client: The client object with an access token
    :param safe_name: The name of the safe whose safe members will be listed.
    :return: CommandResults
    """
    response = client.list_safe_members(safe_name)
    # from 12.1 version the response's structure was changed (Total -> count, SafeMembers -> value)
    total_safe_members = response.get("Total", response.get("count"))
    headline = f"There are {total_safe_members} safe members for {safe_name}"
    members = response.get("SafeMembers", response.get("value"))
    results = CommandResults(
        raw_response=response,
        readable_output=tableToMarkdown(name=headline, t=members),
        outputs_prefix="CyberArkPAS.Safes.Members",
        outputs_key_field="MemberName",
        outputs=members,
    )
    return results


def add_safe_member_command(
    client: Client,
    safe_name: str,
    member_name: str,
    requests_authorization_level: str = "0",
    membership_expiration_date: str = "",
    permissions: str = "",
    search_in: str = "",
) -> CommandResults:
    """Add an existing user as a safe member.
    :param client: The client object with an access token
    :param safe_name: The URL encoded name of the safe to add a member to.
    :param member_name: The name of the user to add as a Safe member.
    :param requests_authorization_level: Requests authorization level, can be 0/1/2.
    :param membership_expiration_date: MM|DD|YY or empty if there is no expiration date.
    :param permissions: User's permissions in the safe.
    :param search_in: Search for the member in the vault or domain.
    :return: CommandResults
    """
    permissions_list = argToList(permissions)
    response = client.add_safe_member(
        safe_name, member_name, requests_authorization_level, membership_expiration_date, permissions_list, search_in
    )
    results = CommandResults(raw_response=response, outputs_prefix="CyberArkPAS.Safes.Members", outputs=response.get("member"))
    return results


def update_safe_member_command(
    client: Client,
    safe_name: str,
    member_name: str,
    requests_authorization_level: str = "0",
    membership_expiration_date: str = "",
    permissions: str = "",
) -> CommandResults:
    """Update an existing safe member.
    :param client: The client object with an access token
    :param safe_name: URL encoded name of the safe to which the safe member belongs.
    :param member_name: Member name that will be updated.
    :param requests_authorization_level: Requests authorization level, can be 0/1/2.
    :param membership_expiration_date: MM|DD|YY or empty if there is no expiration date.
    :param permissions: User's permissions in the safe.
    :return: CommandResults
    """
    permissions_list = argToList(permissions)
    response = client.update_safe_member(
        safe_name, member_name, requests_authorization_level, membership_expiration_date, permissions_list
    )
    results = CommandResults(
        raw_response=response,
        outputs_prefix="CyberArkPAS.Safes.Members",
        outputs_key_field=member_name,
        outputs=response.get("member"),
    )
    return results


def delete_safe_member_command(
    client: Client,
    safe_name: str,
    member_name: str,
) -> CommandResults:
    """Remove a specific member from a safe.
    :param client: The client object with an access token
    :param safe_name: Name of the safe to which the safe member belongs.
    :param member_name: The name of the safe member to delete from the safe's list of members.
    :return: CommandResults
    """
    # the response should be an empty string, if an error raised it would be caught in the main block
    client.delete_safe_member(safe_name, member_name)
    return CommandResults(
        readable_output=f"Member {member_name} was deleted from {safe_name} safe",
        outputs_prefix="CyberArkPAS.Safes.Members",
        outputs_key_field="MemberName",
        outputs={"MemberName": member_name, "Deleted": True},
    )


def add_account_command(
    client: Client,
    account_name: str = "",
    address: str = "",
    username: str = "",
    platform_id: str = "",
    safe_name: str = "",
    password: str = "",
    secret_type: str = "password",
    properties: dict | str = "",
    automatic_management_enabled: str = "true",
    manual_management_reason: str = "",
    remote_machines: str = "",
    access_restricted_to_remote_machines: str = "true",
) -> CommandResults:
    """Add a new privileged account or SSH key to the vault.
    :param client: The client object with an access token
    :param account_name: The name of the account.
    :param address: The name or address of the machine where the account will be used.
    :param username: The account username.
    :param platform_id: The platform assigned to this account.
    :param safe_name: The safe where the account will be created.
    :param password: The password value.
    :param secret_type: The type of password.
    :param properties: Object containing key-value pairs to associate with the account,
     as defined by the account platform. e.g.- {"Location": "IT", "OwnerName": "MSSPAdmin"}
    :param automatic_management_enabled: Whether the account secret is automatically managed by the CPM.
    :param manual_management_reason: Reason for disabling automatic secret management.
    :param remote_machines: List of remote machines, separated by semicolons.
    :param access_restricted_to_remote_machines: Whether or not to restrict access only to specified remote machines.
    :return: CommandResults
    """
    response = client.add_account(
        account_name,
        address,
        username,
        platform_id,
        safe_name,
        password,
        secret_type,
        order_properties_to_dict(properties),
        automatic_management_enabled,
        manual_management_reason,
        remote_machines,
        access_restricted_to_remote_machines,
    )
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Accounts", outputs_key_field="id", outputs=response
    )
    return results


def update_account_command(
    client: Client,
    account_id: str = "",
    account_name: str = "",
    address: str = "",
    username: str = "",
    platform_id: str = "",
) -> CommandResults:
    """Update an existing account's details.
    :param client: The client object with an access token
    :param account_id: The unique id of the account to update.
    :param account_name: The name of the account.
    :param address: The name or address of the machine where the account will be used.
    :param username: The account username.
    :param platform_id: The platform assigned to this account.
    :return: CommandResults
    """
    response = client.update_account(account_id, account_name, address, username, platform_id)
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Accounts", outputs_key_field="id", outputs=response
    )
    return results


def delete_account_command(
    client: Client,
    account_id: str = "",
) -> CommandResults:
    """Delete a specific account in the vault.
    :param client: The client object with an access token
    :param account_id: The unique id of the account to delete.
    :return: CommandResults
    """
    # Get account details before deletion to return complete information
    account_details = client.get_account_details(account_id)

    # Delete the account
    client.delete_account(account_id)

    # Add the deleted flag to the account details
    account_details["Deleted"] = True

    return CommandResults(
        readable_output=f"Account {account_id} was deleted",
        outputs_prefix="CyberArkPAS.Accounts",
        outputs_key_field="id",
        outputs=account_details,
    )


def get_list_accounts_command(
    client: Client,
    search: str = "",
    sort: str = "",
    offset: str = "0",
    limit: str = "50",
    filter: str = "",
) -> CommandResults:
    """Return a list of all the accounts in the vault.
    :param client: The client object with an access token
    :param search: List of keywords to search for in accounts. Separated with a space, e.g- Windows admin
    :param sort: Property or properties by which to sort returned accounts.
    :param offset: Offset of the first account that is returned in the collection of results.
    :param limit: Maximum number of returned accounts.
    :param filter: Search for accounts filtered by a specific safe.
    :return: CommandResults
    """
    response = client.get_list_accounts(search, sort, offset, limit, filter)
    total_accounts = response.get("count")
    accounts = response.get("value")
    headline = f"There are {total_accounts} accounts"
    results = CommandResults(
        raw_response=response,
        readable_output=tableToMarkdown(headline, accounts),
        outputs_prefix="CyberArkPAS.Accounts",
        outputs_key_field="id",
        outputs=accounts,
    )
    return results


def get_list_account_activity_command(
    client: Client,
    account_id: str = "",
) -> CommandResults:
    """Returns the activities of a specific account that is identified by its account id.
    :param client: The client object with an access token
    :param account_id: The id of the account whose activities will be retrieved.
    :return: CommandResults
    """
    response = client.get_list_account_activity(account_id)
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Activities", outputs_key_field="", outputs=response.get("Activities")
    )
    return results


def get_account_details_command(
    client: Client,
    account_id: str = "",
) -> CommandResults:
    """Returns information of a specific account that is identified by its account id.
    :param client: The client object with an access token
    :param account_id: The id of the account whose details will be retrieved.
    :return: CommandResults
    """
    response = client.get_account_details(account_id)
    results = CommandResults(
        raw_response=response, outputs_prefix="CyberArkPAS.Accounts", outputs_key_field="id", outputs=response
    )
    return results


def change_credentials_random_password_command(
    client: Client,
    account_id: str,
) -> str:
    """Mark an account for an immediate credentials change by the CPM to a new random value.
    :param client: The client object with an access token
    :param account_id: The unique ID of the account.
    :return: Action was succeeded notice
    """
    client.change_credentials_random_password(account_id)
    return f"The password in the account {account_id} was changed"


def change_credentials_set_new_password_command(
    client: Client,
    account_id: str,
    new_credentials: str,
) -> str:
    """Enables users to set the account's credentials to use for the next CPM change.
    :param client: The client object with an access token
    :param account_id: The unique ID of the account.
    :param new_credentials: The new account credentials that will be allocated to the account in the vault.
    :return: Action was succeeded notice
    """
    client.change_credentials_set_new_password(account_id, new_credentials)
    return f"The password in the account {account_id} was changed"


def change_credentials_in_vault_only_command(
    client: Client,
    account_id: str,
    new_credentials: str,
) -> str:
    """Enables users to set account credentials and change them in the vault.
    :param client: The client object with an access token
    :param account_id: The unique ID of the account.
    :param new_credentials: The new account credentials that will be allocated to the account in the vault.
    :return: Action was succeeded notice
    """
    client.change_credentials_in_vault_only(account_id, new_credentials)
    return f"The password in the account {account_id} was changed"


def verify_credentials_command(
    client: Client,
    account_id: str,
) -> str:
    """Mark an account for verification by the CPM.
    :param client: The client object with an access token
    :param account_id: The unique ID of the account.
    :return: Action was succeeded notice
    """
    client.verify_credentials(account_id)
    return f"The account {account_id} was marked for verification by the CPM"


def reconcile_credentials_command(
    client: Client,
    account_id: str,
) -> str:
    """Marks an account for automatic reconciliation by the CPM.
    :param client: The client object with an access token
    :param account_id: The unique ID of the account.
    :return: Action was succeeded notice
    """
    client.reconcile_credentials(account_id)
    return f"The account {account_id} was marked for automatic reconciliation by the CPM."


def get_security_events_command(client: Client, start_time: str, limit: str = "50") -> CommandResults:
    """Returns all PTA security events.
    :param client: The client object with an access token
    :param start_time: The starting date to get the security events from as timestamp.
    :param limit: The number of events that will be shown, from newest to oldest.
    :return: Action was succeeded notice
    """

    start, _ = parse_date_range(start_time)
    start_time_timestamp = str(date_to_timestamp(start))

    events_data = client.get_security_events(start_time_timestamp)

    if not events_data:
        return CommandResults(outputs="No events were found")

    if limit:
        events_data = events_data[0 : int(limit)]

    results = CommandResults(
        outputs=events_data,
        raw_response=events_data,
        outputs_prefix="CyberArkPAS.SecurityEvents",
        outputs_key_field="id",
    )
    return results


def fetch_incidents(
    client: Client, last_run: dict, first_fetch_time: str, score: str, max_fetch: str = "50"
) -> tuple[dict, list]:
    # if first time fetching
    if not last_run:
        start_time, _ = parse_date_range(first_fetch_time)
        start_time_timestamp = str(date_to_timestamp(start_time))
        next_run = {"time": start_time_timestamp, "last_event_ids": []}
    else:
        next_run = last_run

    events_data = client.get_security_events(str(next_run.get("time")))

    if not events_data:
        return next_run, []

    filtered_events_data = filter_by_score(events_data, int(score))

    # the events are sorted from the newest to the oldest so first we reverse the list
    reverse_events_data = filtered_events_data[::-1]

    incidents = []
    if reverse_events_data:
        last_event_ids = last_run.get("last_event_ids", [])
        new_event_ids = []
        event_updated_time = None

        incidents_num = 0

        for event_data in reverse_events_data:
            # by reversing the list before, we can now go over the items from the oldest to the newest
            event_id = event_data.get("id")

            if event_id not in last_event_ids:  # check that event was not fetched in the last fetch
                incidents_num += 1
                event_updated_time = event_data.get("lastUpdateTime")
                incident = {
                    "name": f"CyberArk PAS Incident: {event_id}.",
                    "occurred": timestamp_to_datestring(event_updated_time),
                    "severity": incident_priority_to_dbot_score(float(event_data.get("score"))),
                    "rawJSON": json.dumps(event_data),
                }
                incidents.append(incident)
                new_event_ids.append(event_id)

            # make sure that there are no more than max_fetch incidents that are being created
            if incidents_num >= int(max_fetch):
                break

        if new_event_ids and event_updated_time:
            next_run = {
                "time": str(event_updated_time),
                "last_event_ids": json.dumps(new_event_ids),  # save the event IDs from the last fetch
            }
    demisto.debug(f"CyberArk PAS last fetch data: {str(next_run)}")
    return next_run, incidents


def main():
    params = demisto.params()
    username = params.get("credentials").get("identifier")
    password = params.get("credentials").get("password")
    url = params.get("url")
    use_ssl = not params.get("insecure", False)
    proxy = params.get("proxy", False)

    max_fetch = min("200", params.get("max_fetch", "200"))
    first_fetch_time = params.get("fetch_time", "3 days").strip()
    score = params.get("score", "0")

    command = demisto.command()
    LOG(f"Command being called in CyberArkPAS is: {command}")
    commands = {
        "test-module": test_module,
        "cyberark-pas-user-add": add_user_command,
        "cyberark-pas-user-update": update_user_command,
        "cyberark-pas-user-delete": delete_user_command,
        "cyberark-pas-users-list": get_users_command,
        "cyberark-pas-user-activate": activate_user_command,
        "cyberark-pas-safe-add": add_safe_command,
        "cyberark-pas-safe-update": update_safe_command,
        "cyberark-pas-safe-delete": delete_safe_command,
        "cyberark-pas-safes-list": get_list_safes_command,
        "cyberark-pas-safe-get-by-name": get_safe_by_name_command,
        "cyberark-pas-safe-member-add": add_safe_member_command,
        "cyberark-pas-safe-member-update": update_safe_member_command,
        "cyberark-pas-safe-member-delete": delete_safe_member_command,
        "cyberark-pas-safe-members-list": list_safe_members_command,
        "cyberark-pas-account-add": add_account_command,
        "cyberark-pas-account-update": update_account_command,
        "cyberark-pas-account-delete": delete_account_command,
        "cyberark-pas-accounts-list": get_list_accounts_command,
        "cyberark-pas-account-get-list-activity": get_list_account_activity_command,
        "cyberark-pas-account-get-details": get_account_details_command,
        "cyberark-pas-credentials-change-random-password": change_credentials_random_password_command,
        "cyberark-pas-credentials-change-set-new-password": change_credentials_set_new_password_command,
        "cyberark-pas-credentials-change-in-vault-only": change_credentials_in_vault_only_command,
        "cyberark-pas-credentials-verify": verify_credentials_command,
        "cyberark-pas-credentials-reconcile": reconcile_credentials_command,
        "cyberark-pas-security-events-get": get_security_events_command,
    }

    try:
        client = Client(
            server_url=url, username=username, password=password, use_ssl=use_ssl, proxy=proxy, max_fetch=int(max_fetch)
        )

        if command in commands:
            return_results(commands[command](client, **demisto.args()))  # type: ignore[operator]
        elif command == "fetch-incidents":
            next_run, incidents = fetch_incidents(
                client=client, last_run=demisto.getLastRun(), first_fetch_time=first_fetch_time, score=score, max_fetch=max_fetch
            )
            demisto.setLastRun(next_run)
            demisto.incidents(incidents)

        else:
            raise NotImplementedError(f"{command} is not an existing CyberArk PAS command")
    except Exception as err:
        return_error(f"Unexpected error: {str(err)}", error=traceback.format_exc())
    finally:
        try:
            client._logout()
        except Exception as err:
            demisto.info(f"CyberArk PAS error: {str(err)}")


if __name__ in ["__main__", "builtin", "builtins"]:
    main()