Abnormal Security

Abnormal Security detects the whole spectrum of email attacks, from vendor email compromise and spear-phishing to unwanted email spam and graymail. To stop these advanced attacks, Abnormal leverages the industry’s most advanced behavioral data science to baseline known good behavior and detects anomalies.

Data Enrichment & Threat Intelligence · Abnormal Security

Details

IDAbnormal Security
ProviderAbnormal Security
CategoryData Enrichment & Threat Intelligence
From Version6.0.0
Docker Imagedemisto/python3:3.12.13.10116658
Supported ModulesAgentix XSIAM

README

Abnormal Security detects the whole spectrum of email attacks, from vendor email compromise and spear-phishing to unwanted email spam and graymail. To stop these advanced attacks, Abnormal leverages the industry’s most advanced behavioral data science to baseline known good behavior and detects anomalies.
This integration was integrated and tested with version 1.3.0 of Abnormal Security

Configure Abnormal Security in Cortex

Parameter Description Required
Server URL (e.g. https://api.abnormalplatform.com/v1)   True
API Key   True
Trust any certificate (not secure)   False
Use system proxy settings   False
Fetch incidents Retrieves incidents based on the customer’s selection from three categories: Threats, Account Takeover Cases, and Abuse Campaigns False
Maximum incidents to fetch. Maximum number of incidents per fetch. The default value is 200. False
Fetch Threats   False
Fetch Abuse Campaigns   False
Fetch Account Takeover Cases   False
First fetch time First alert created date to fetch. e.g., “1 min ago”,”2 weeks ago”,”3 months ago” False
Incident type   False
Incidents Fetch Interval   False
Polling Lag Time (in minutes) Time in minutes to subtract from polling time window for data consistency (Default : 2 mins) False
Maximum incidents pages to fetch Maximum number of pages to fetch for incidents 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.

abnormal-security-check-case-action-status


Check the status of an action requested on a case.

Base Command

abnormal-security-check-case-action-status

Input

Argument Name Description Required
case_id A string representing the email case. Can be retrieved by first running command to list cases. Required
action_id A string representing the email case. Can be retrieved from payload after performing an action on a case. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.ActionStatus.status String Status of the case after an action is performed
AbnormalSecurity.ActionStatus.description String Detailed description of the status

Command Example

!abnormal-security-check-case-action-status case_id=12345 action_id=abcdefgh-1234-5678-ijkl-mnop9qrstuvwx

Context Example

{
    "AbnormalSecurity": {
        "ActionStatus": {
            "description": "The request was completed successfully",
            "status": "acknowledged"
        }
    }
}

Human Readable Output

Results

description status
The request was completed successfully acknowledged

abnormal-security-check-threat-action-status


Check the status of an action requested on a threat.

Base Command

abnormal-security-check-threat-action-status

Input

Argument Name Description Required
threat_id A UUID representing a threat campaign. Full list of threat IDs can be obtained by first running the command to list a threat. Required
action_id A UUID representing the action id for a threat. Can be obtained from payload after performing an action on the threat. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.ActionStatus.status String The status of a threat after performing an action on it
AbnormalSecurity.ActionStatus.description String The description of the status

Command Example

!abnormal-security-check-threat-action-status threat_id=xwvutsrq-9pon-mlkj-i876-54321hgfedcba action_id=abcdefgh-1234-5678-ijkl-mnop9qrstuvwx

Context Example

{
    "AbnormalSecurity": {
        "ActionStatus": {
            "description": "The request was completed successfully",
            "status": "acknowledged"
        }
    }
}

Human Readable Output

Results

description status
The request was completed successfully acknowledged

abnormal-security-download-threat-log-csv


Download data from Threat Log in .csv format

Base Command

abnormal-security-download-threat-log-csv

Input

Argument Name Description Required
filter Filter the results based on a filter key. Value must be of the format filter={FILTER KEY} gte YYYY-MM-DDTHH:MM:SSZ lte YYYY-MM-DDTHH:MM:SSZ. Supported keys - [receivedTime]. Optional
mock-data Returns test data if set to True. Optional
source Filters threats based on the source of detection. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

There is no context output for this command.

Command Example

!abnormal-security-download-threat-log-csv filter="receivedTime gte 2020-12-01T01:01:01Z"

Context Example

{
    "File": {
        "EntryID": "2294@2ef16ace-2149-42b9-8b0f-fb7620ba7d44",
        "Extension": "csv",
        "Info": "csv",
        "MD5": "a981545ee72fe115888800725883ca8a",
        "Name": "threat_log.csv",
        "SHA1": "c3cbae11542dc7244e3bf04a0901d7063597d381",
        "SHA256": "296463cad959803d64bfc94fbffa24e30c9438ba58827a100a9e7c219f26b382",
        "SHA512": "21a53f61c7d22b533abd7181b16116bf9017b7a444c10e4d2336803794ef0d9dded56e65179f924252f0bf3231e35fa1b726c8d7723f10b2f08bae0b3bedddd1",
        "SSDeep": "12:dB2XRzmZIm88Rvu8R7b7+I78RQC5+GUHwgfdvvq:dB2XRMrt/C5+GYw",
        "Size": 449,
        "Type": "ASCII text, with CRLF line terminators"
    }
}

abnormal-security-list-abuse-mailbox-campaigns


Get a list of campaigns submitted to Abuse Mailbox

Base Command

abnormal-security-list-abuse-mailbox-campaigns

Input

Argument Name Description Required
filter Value must be of the format filter={FILTER KEY} gte YYYY-MM-DDTHH:MM:SSZ lte YYYY-MM-DDTHH:MM:SSZ. A {FILTER KEY} must be specified, and currently only the key lastReportedTime is supported for /abusecampaigns. At least one of gte/lte must be specified, with a datetime string following the YYYY-MM-DDTHH:MM:SSZ format. Do note that provided filter time is in UTC. Optional
page_size Number of abuse campaigns shown on each page. Each page of data will have at most page_size abuse campaign IDs. Optional
page_number 1-indexed page number to get a particular page of threats. Has no effect if filter is not specified. Optional
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.AbuseCampaign.campaigns.campaignId String An id which maps to an abuse campaign.
AbnormalSecurity.AbuseCampaign.pageNumber Number The current page number.
AbnormalSecurity.AbuseCampaign.nextPageNumber Number The next page number.

Command Example

!abnormal-security-list-abuse-mailbox-campaigns filter="lastReportedTime gte 2020-12-01T01:01:01Z"

Context Example

{
    "AbnormalSecurity": {
        "AbuseCampaign": {
            "campaigns": [
                {
                    "campaignId": "fff51768-c446-34e1-97a8-9802c29c3ebd"
                },
                {
                    "campaignId": "07434ea5-df7b-3ff4-8d07-4a82df0c655d"
                }
            ],
            "pageNumber": 1
        }
    }
}

Human Readable Output

List of Abuse Mailbox Campaigns

Campaign IDs

campaignId
fff51768-c446-34e1-97a8-9802c29c3ebd
07434ea5-df7b-3ff4-8d07-4a82df0c655d

abnormal-security-list-abnormal-cases


Get a list of Abnormal cases identified by Abnormal Security

Base Command

abnormal-security-list-abnormal-cases

Input

Argument Name Description Required
filter Value must be of the format filter={FILTER KEY} gte YYYY-MM-DDTHH:MM:SSZ lte YYYY-MM-DDTHH:MM:SSZ. A {FILTER KEY} must be specified, and currently the only key that is supported for /cases is lastModifiedTime. At least 1 of gte/lte must be specified, with a datetime string following the YYYY-MM-DDTHH:MM:SSZ format. Optional
page_size Number of cases that are on each page. Each page of data will have at most page_size threats. Has no effect if filter is not specified. Optional
page_number 1-indexed page number to get a particular page of cases. Has no effect if filter is not specified. Optional
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.inline_response_200_1.cases.caseId String A unique identifier for this case.
AbnormalSecurity.inline_response_200_1.cases.description String Description of the severity level for this case.
AbnormalSecurity.inline_response_200_1.pageNumber Number The current page number. Will not be be in the response if no filter query meter is passed in via the request.
AbnormalSecurity.inline_response_200_1.nextpageNumber Number The next page number. Will not be included in the response if there are no more pages of data or if no filter query meter is passed in via the request

Command Example

!abnormal-security-list-abnormal-cases filter="lastModifiedTime gte 2020-12-01T01:01:01Z"

Context Example

{
    "AbnormalSecurity": {
        "inline_response_200_1": {
            "cases": [
                {
                    "caseId": 1234,
                    "description": "Potential Account Takeover"
                }
            ],
            "nextPageNumber": 2,
            "pageNumber": 1
        }
    }
}

Human Readable Output

List of Cases

Case IDs

caseId description
1234 Potential Account Takeover

abnormal-security-list-threats


Get a list of threats

Base Command

abnormal-security-list-threats

Input

Argument Name Description Required
filter Value must be of the format filter={FILTER KEY} gte YYYY-MM-DDTHH:MM:SSZ lte YYYY-MM-DDTHH:MM:SSZ. A {FILTER KEY} must be specified, and currently the only key that is supported for /threats is receivedTime. At least 1 of gte/lte must be specified, with a datetime string following the YYYY-MM-DDTHH:MM:SSZ format. Optional
page_size Number of threats per page. Each page will contain up to page_size threats. This has no effect if no filter is specified. Optional
page_number 1-indexed page number to get a particular page of threats. Has no effect if filter is not specified. Optional
mock-data Returns test data if set to True. Optional
source Filters threats based on the source of detection. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.inline_response_200.threats.threatId String An id which maps to a threat campaign. A threat campaign might be received by multiple users.
AbnormalSecurity.inline_response_200.pageNumber Number The current page number. Will not be be in the response if no filter query meter is passed in via the request.
AbnormalSecurity.inline_response_200.nextpageNumber Number The next page number. Will not be included in the response if there are no more pages of data or if no filter query meter is passed in via the request

Command Example

!abnormal-security-list-threats filter="receivedTime gte 2020-12-01T01:01:01Z"

Context Example

{
    "AbnormalSecurity": {
        "inline_response_200": {
            "nextPageNumber": 2,
            "pageNumber": 1,
            "threats": [
                {
                    "threatId": "184712ab-6d8b-47b3-89d3-a314efef79e2"
                }
            ]
        }
    }
}

Human Readable Output

List of Threats

Threat IDs

threatId
184712ab-6d8b-47b3-89d3-a314efef79e2

abnormal-security-get-threat


Get details of a threat

Base Command

abnormal-security-get-threat

Input

Argument Name Description Required
threat_id A UUID representing a threat campaign. Full list of threat IDs can be obtained by first running the command to list a threat. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional
page_size Number of threats per page. Each page will contain up to page_size threats. This has no effect if no filter is specified. Optional
page_number 1-indexed page number to get a particular page of threats. Has no effect if filter is not specified. Optional

Context Output

Path Type Description
AbnormalSecurity.ThreatDetails.threatId String An id which maps to a threat campaign.
AbnormalSecurity.ThreatDetails.messages.abxMessageId Number A unique identifier for an individual message within a threat (i.e email campaign).
AbnormalSecurity.ThreatDetails.messages.abxPortalUrl String The URL at which the specific message details are viewable.
AbnormalSecurity.ThreatDetails.messages.attachmentCount Number The number of attachments in the email.
AbnormalSecurity.ThreatDetails.messages.attachmentNames Array List of the names of attachments in the email.
AbnormalSecurity.ThreatDetails.messages.attackStrategy String The attack strategy used in the threat.
AbnormalSecurity.ThreatDetails.messages.attackType String The type of threat the message represents.
AbnormalSecurity.ThreatDetails.messages.attackVector String The medium used for the attack.
AbnormalSecurity.ThreatDetails.messages.attackedParty String The party that was targeted by the attack.
AbnormalSecurity.ThreatDetails.messages.autoRemediated Boolean Whether the threat was automatically remediated.
AbnormalSecurity.ThreatDetails.messages.fromAddress String The email address of the sender.
AbnormalSecurity.ThreatDetails.messages.fromName String The display name of the sender.
AbnormalSecurity.ThreatDetails.messages.impersonatedParty String The party, if any, that was impersonated in the attack.
AbnormalSecurity.ThreatDetails.messages.internetMessageId String The Internet Message ID, per RFC 822.
AbnormalSecurity.ThreatDetails.messages.isRead Boolean Whether the email has been read.
AbnormalSecurity.ThreatDetails.messages.postRemediated Boolean Whether the threat was remediated after landing in the user’s mailbox.
AbnormalSecurity.ThreatDetails.messages.receivedTime String The timestamp at which this message arrived.
AbnormalSecurity.ThreatDetails.messages.recipientAddress String The email address of the user who actually received the message.
AbnormalSecurity.ThreatDetails.messages.remediationStatus String The status of remediation action.
AbnormalSecurity.ThreatDetails.messages.remediationTimestamp String The timestamp at which the message was remediated.
AbnormalSecurity.ThreatDetails.messages.sentTime String The timestamp at which this message was sent.
AbnormalSecurity.ThreatDetails.messages.subject String The subject of the email.
AbnormalSecurity.ThreatDetails.messages.threatId String An id which maps to a threat campaign.
AbnormalSecurity.ThreatDetails.messages.toAddresses Array All the email addresses to which the message was sent.
AbnormalSecurity.ThreatDetails.messages.ccEmails Array All the email addresses in CC.
AbnormalSecurity.ThreatDetails.messages.replyToEmails Array All the email addresses in the “Reply To” field.
AbnormalSecurity.ThreatDetails.messages.returnPath String The path where information is returned to the attacker.
AbnormalSecurity.ThreatDetails.messages.senderDomain String The domain of the sender.
AbnormalSecurity.ThreatDetails.messages.senderIpAddress String The IP address of the sender.
AbnormalSecurity.ThreatDetails.messages.summaryInsights Array Summary insights into the threat’s characteristics.
AbnormalSecurity.ThreatDetails.messages.urlCount Number The number of URLs contained in the email.
AbnormalSecurity.ThreatDetails.messages.urls Array List of all URLs contained in the email.

Command Example

!abnormal-security-get-threat threat_id=xwvutsrq-9pon-mlkj-i876-54321hgfedcba

Context Example

{
    "AbnormalSecurity": {
        "ThreatDetails": {
            "messages": [
                {
                    "abxMessageId": 4551618356913732000,
                    "abxPortalUrl": "https://portal.abnormalsecurity.com/home/threat-center/remediation-history/4551618356913732076",
                    "attachmentCount": null,
                    "attachmentNames": ["attachment.pdf"],
                    "attackStrategy": "Name Impersonation",
                    "attackType": "Extortion",
                    "attackVector": "Text",
                    "attackedParty": "VIP",
                    "autoRemediated": true,
                    "ccEmails": ["cc@example.com"],
                    "fromAddress": "support@secure-reply.org",
                    "fromName": "",
                    "impersonatedParty": "None / Others",
                    "internetMessageId": "<5edfca1c.1c69fb81.4b055.8fd5@mx.google.com>",
                    "isRead": true,
                    "postRemediated": true,
                    "receivedTime": "2020-06-09T17:42:59Z",
                    "recipientAddress": "example@example.com",
                    "remediationTimestamp": "2020-06-09T17:42:59Z",
                    "replyToEmails": ["reply-to@example.com"],
                    "returnPath": "support@secure-reply.org",
                    "senderDomain": "",
                    "senderIpAddress": "100.101.102.103",
                    "sentTime": "2020-06-09T17:42:59Z",
                    "subject": "Phishing Email",
                    "summaryInsights": ["Bitcoin Topics", "Personal Information Theft", "Unusual Sender"],
                    "threatId": "184712ab-6d8b-47b3-89d3-a314efef79e2",
                    "toAddresses": "example@example.com, another@example.com",
                    "urlCount": 0,
                    "urls": ["https://www.google.com/"]
                }
            ],
            "threatId": "184712ab-6d8b-47b3-89d3-a314efef79e2"
        }
    }
}

Human Readable Output

Messages in Threat 184712ab-6d8b-47b3-89d3-a314efef79e2

subject fromAddress toAddresses recipientAddress receivedTime attackType attackStrategy returnPath
Phishing Email support@secure-reply.org example@example.com, another@example.com example@example.com 2020-06-09T17:42:59Z Extortion Name Impersonation support@secure-reply.org etc

abnormal-security-get-abnormal-case


Get details of an Abnormal case

Base Command

abnormal-security-get-abnormal-case

Input

Argument Name Description Required
case_id A string representing the email case. Can be retrieved by first running command to list cases. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.AbnormalCaseDetails.caseId String A unique identifier for this case.
AbnormalSecurity.AbnormalCaseDetails.severity String Description of the severity level for this case.
AbnormalSecurity.AbnormalCaseDetails.affectedEmployee String Which employee this case pertains to.
AbnormalSecurity.AbnormalCaseDetails.firstObserved String First time suspicious behavior was observed.
AbnormalSecurity.AbnormalCaseDetails.genai_summary String Gen AI summary for this case

Command Example

!abnormal-security-get-abnormal-case case_id=12805

Context Example

{
    "AbnormalSecurity": {
        "AbnormalCaseDetails": {
            "affectedEmployee": "FirstName LastName",
            "analysis": "Mail Sent",
            "caseId": 1234,
            "case_status": "Action Required",
            "firstObserved": "2020-06-09T17:42:59Z",
            "remediation_status": "Not remediated",
            "severity": "Potential Account Takeover",
            "threatIds": ["184712ab-6d8b-47b3-89d3-a314efef79e2"],
            "genai_summary": "Observed 2 lateral phishing emails sent internally from the user's account"
        }
    }
}

Human Readable Output

Details of Case 1234

caseId severity affectedEmployee firstObserved threatIds
1234 Potential Account Takeover FirstName LastName 2020-06-09T17:42:59Z 184712ab-6d8b-47b3-89d3-a314efef79e2

abnormal-security-get-abuse-mailbox-campaign


Get details of an Abuse Mailbox campaign

Base Command

abnormal-security-get-abuse-mailbox-campaign

Input

Argument Name Description Required
campaign_id A UUID representing the abuse campaign id. Can be Can be retrieved by first running command to list abuse mailbox campaigns. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.AbuseCampaign.campaignId String An id which maps to an abuse campaign.
AbnormalSecurity.AbuseCampaign.firstReported String Date abuse campaign was first reported.
AbnormalSecurity.AbuseCampaign.lastReported String Date abuse campaign was last reported.
AbnormalSecurity.AbuseCampaign.messageId String A unique identifier for the first message in the abuse campaign.
AbnormalSecurity.AbuseCampaign.subject String Subject of the first email in the abuse campaign.
AbnormalSecurity.AbuseCampaign.fromName String The display name of the sender.
AbnormalSecurity.AbuseCampaign.fromAddress String The email address of the sender.
AbnormalSecurity.AbuseCampaign.recipientName String The email address of the recipient.
AbnormalSecurity.AbuseCampaign.recipientAddress String The email address of the recipient.
AbnormalSecurity.AbuseCampaign.judgementStatus String Judgement status of message.
AbnormalSecurity.AbuseCampaign.overallStatus String Overall status of message.
AbnormalSecurity.AbuseCampaign.attackType String The type of threat the message represents.

Command Example

!abnormal-security-get-abuse-mailbox-campaign campaign_id=xwvutsrq-9pon-mlkj-i876-54321hgfedcba

Context Example

{
    "AbnormalSecurity": {
        "AbuseCampaign": {
            "campaigns": {
                "attackType": "Attack Type: Spam",
                "campaignId": "fff51768-c446-34e1-97a8-9802c29c3ebd",
                "firstReported": "2020-11-11T13:11:40-08:00",
                "fromAddress": "example@example.com",
                "fromName": "Tom Dinkley",
                "judgementStatus": "Malicious",
                "lastReported": "2020-11-11T13:11:40-08:00",
                "messageId": "12345678910",
                "overallStatus": "Move attempted",
                "recipientAddress": "example_phisher@example.com",
                "recipientName": "Booker",
                "subject": "Fwd: This is spam"
            }
        }
    }
}

Human Readable Output

Results

attackType campaignId firstReported fromAddress fromName judgementStatus lastReported messageId overallStatus recipientAddress recipientName subject
Attack Type: Spam fff51768-c446-34e1-97a8-9802c29c3ebd 2020-11-11T13:11:40-08:00 example@example.com Tom Dinkley Malicious 2020-11-11T13:11:40-08:00 12345678910 Move attempted example_phisher@example.com Booker Fwd: This is spam

abnormal-security-get-employee-identity-analysis


Get employee identity analysis (Genome) data

Base Command

abnormal-security-get-employee-identity-analysis

Input

Argument Name Description Required
email_address Email address of the employee you want to retrieve data for. Required
mock-data Returns test data if set to True. Optional

Context Output

Path Type Description
AbnormalSecurity.Employee.email String Employee email
AbnormalSecurity.Employee.histograms.key String Genome key name
AbnormalSecurity.Employee.histograms.name String Genome title
AbnormalSecurity.Employee.histograms.description String Description of genome object
AbnormalSecurity.Employee.histograms.values.value String Category value
AbnormalSecurity.Employee.histograms.values.percentage Number Ratio of this category relative to others
AbnormalSecurity.Employee.histograms.values.total_count Number Number of occurences for this category

Command Example

!abnormal-security-get-employee-identity-analysis email_address="test@test.com"

Context Example

{
    "AbnormalSecurity": {
        "Employee": {
            "email": "test@test.com",
            "histograms": [
                {
                    "description": "Common IP addresses for user logins",
                    "key": "ip_address",
                    "name": "Common IP Addresses",
                    "values": [
                        {
                            "ratio": 0.25,
                            "raw_count": 12,
                            "text": "ip-address-0"
                        },
                        {
                            "ratio": 0.25,
                            "raw_count": 12,
                            "text": "ip-address-1"
                        },
                        {
                            "ratio": 0.25,
                            "raw_count": 12,
                            "text": "ip-address-2"
                        },
                        {
                            "ratio": 0.25,
                            "raw_count": 12,
                            "text": "ip-address-3"
                        }
                    ]
                }
            ]
        }
    }
}

Human Readable Output

Analysis of test@test.com

description key name values
Common IP addresses for user logins ip_address Common IP Addresses {‘text’: ‘ip-address-0’, ‘ratio’: 0.25, ‘raw_count’: 12},
{‘text’: ‘ip-address-1’, ‘ratio’: 0.25, ‘raw_count’: 12},
{‘text’: ‘ip-address-2’, ‘ratio’: 0.25, ‘raw_count’: 12},
{‘text’: ‘ip-address-3’, ‘ratio’: 0.25, ‘raw_count’: 12}

abnormal-security-get-employee-information


Get employee information

Base Command

abnormal-security-get-employee-information

Input

Argument Name Description Required
email_address Email address of the employee you want to retrieve data for. Required
mock-data Returns test data if set to True. Optional

Context Output

Path Type Description
AbnormalSecurity.Employee.name String Name of the employee.
AbnormalSecurity.Employee.email String Email of the employee.
AbnormalSecurity.Employee.title String Job title of the employee.
AbnormalSecurity.Employee.manager String Email address of the employee’s manager

Command Example

!abnormal-security-get-employee-information email_address="test@test.com"

Context Example

{
    "AbnormalSecurity": {
        "Employee": {
            "email": "testemail@email.com",
            "manager": "testmanageremail@email.net",
            "name": "test_name",
            "title": "Test Operator"
        }
    }
}

Human Readable Output

Results

email manager name title
testemail@email.com testmanageremail@email.net test_name Test Operator

abnormal-security-get-employee-last-30-days-login-csv


Get employee login information for last 30 days in csv format

Base Command

abnormal-security-get-employee-last-30-days-login-csv

Input

Argument Name Description Required
email_address Email address of the employee you want to retrieve data for. Required
mock-data Returns test data if set to True. Optional

Context Output

There is no context output for this command.

Command Example

!abnormal-security-get-employee-last-30-days-login-csv email_address="test@test.com"

Context Example

{
    "File": {
        "EntryID": "2338@2ef16ace-2149-42b9-8b0f-fb7620ba7d44",
        "Extension": "csv",
        "Info": "csv",
        "MD5": "11afb4879c5026e25bd868dfcf23e811",
        "Name": "employee_login_info_30_days.csv",
        "SHA1": "345ea1d24b52c96baf6b0e4d892d13d4efcf666d",
        "SHA256": "12620e0f576f4d74603b1f542919a3e5199e61435ffd99bcd68c26e02ed9c693",
        "SHA512": "f0e788981ce70d9668100ae3f93d1f28660f0d8a9dfda02284a70f08ac14ca5a356872284f460d8fb7970791e314e0db4a6c84b0032c35046efce62368a00da5",
        "SSDeep": "12:uR2xCC56aHoW2IY3zg05Eg05ng05Eg05V:uROjHn2IY3v5i5T5i5V",
        "Size": 484,
        "Type": "ASCII text, with CRLF line terminators"
    }
}

abnormal-security-get-latest-threat-intel-feed


DEPRECATED. Get the latest threat intel feed.

Base Command

abnormal-security-get-latest-threat-intel-feed

Input

Argument Name Description Required
mock-data Returns test data if set to True. Optional

Context Output

There is no context output for this command.

Command Example

!abnormal-security-get-latest-threat-intel-feed

Context Example

{
    "File": {
        "EntryID": "2314@2ef16ace-2149-42b9-8b0f-fb7620ba7d44",
        "Extension": "json",
        "Info": "application/json",
        "MD5": "a00e919efc9e28f77b8f7b7523b1ffe8",
        "Name": "threat_intel_feed.json",
        "SHA1": "53bf3e6075f407b53c95d5dd2197b9be0dfa5ced",
        "SHA256": "f842e7f6795fba081f2046617fce662c050b5a3c64cac9501f23fa7576788429",
        "SHA512": "27af66eefb1ed7227b4f8ec1c663ac8ef47660bb34ffd1d5853a7a58e25caec68615c2e66bfbd66577749faa889894e792f53cab70a826818b4d627ad02bbb04",
        "SSDeep": "49152:dY0GiMq58ZVhOH+sZwFp+h/s0pH6VRRxIGFe7V3dCLtJ/W7H8nsIdL0E:u",
        "Size": 8007799,
        "Type": "ASCII text"
    }
}

abnormal-security-manage-threat


Manage a Threat identified by Abnormal Security

Base Command

abnormal-security-manage-threat

Input

Argument Name Description Required
threat_id A UUID representing a threat campaign. Full list of threat IDs can be obtained by first running the command to list a threat. Required
action Action to perform on threat. Required
mock-data Returns test data if set to True. Optional

Context Output

Path Type Description
AbnormalSecurity.ThreatManageResults.action_id String ID of the action taken
AbnormalSecurity.ThreatManageResults.status_url String URL of the status of the action

Command Example

!abnormal-security-manage-threat threat_id=xwvutsrq-9pon-mlkj-i876-54321hgfedcba action=remediate

Context Example

{
    "AbnormalSecurity": {
        "ThreatManageResults": {
            "action_id": "a33a212a-89ff-461f-be34-ea52aff44a73",
            "status_url": "https://api.abnormalplatform.com/v1/threats/184712ab-6d8b-47b3-89d3-a314efef79e2/actions/a33a212a-89ff-461f-be34-ea52aff44a73"
        }
    }
}

Human Readable Output

Results

action_id status_url
a33a212a-89ff-461f-be34-ea52aff44a73 https://api.abnormalplatform.com/v1/threats/184712ab-6d8b-47b3-89d3-a314efef79e2/actions/a33a212a-89ff-461f-be34-ea52aff44a73

abnormal-security-manage-abnormal-case


Manage an Abnormal Case.

Base Command

abnormal-security-manage-abnormal-case

Input

Argument Name Description Required
case_id A string representing the email case. Can be retrieved by first running command to list cases. Required
action Action to perform on case. Required
mock-data Returns test data if set to True. Optional

Context Output

Path Type Description
AbnormalSecurity.CaseManageResults.action_id String ID of the action taken
AbnormalSecurity.CaseManageResults.status_url String URL of the status of the action

Command Example

!abnormal-security-manage-abnormal-case case_id=12805 action=action_required

Context Example

{
    "AbnormalSecurity": {
        "CaseManageResults": {
            "action_id": "61e76395-40d3-4d78-b6a8-8b17634d0f5b",
            "status_url": "https://api.abnormalplatform.com/v1/cases/1234/actions/61e76395-40d3-4d78-b6a8-8b17634d0f5b"
        }
    }
}

Human Readable Output

Results

action_id status_url
61e76395-40d3-4d78-b6a8-8b17634d0f5b https://api.abnormalplatform.com/v1/cases/1234/actions/61e76395-40d3-4d78-b6a8-8b17634d0f5b

abnormal-security-get-case-analysis-and-timeline


Provides the analysis and timeline details of a case

Base Command

abnormal-security-get-case-analysis-and-timeline

Input

Argument Name Description Required
case_id A string representing the email case. Can be retrieved by first running command to list cases. Required
mock-data Returns test data if set to True. Optional
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.CaseAnalysis.insights.signal String Insight signal or highlight of a case
AbnormalSecurity.CaseAnalysis.insights.description String Description of insight signal or highlight
AbnormalSecurity.CaseAnalysis.eventTimeline.event_timestamp String Time when event occurred
AbnormalSecurity.CaseAnalysis.eventTimeline.category String Type of event
AbnormalSecurity.CaseAnalysis.eventTimeline.title String Title of the event
AbnormalSecurity.CaseAnalysis.eventTimeline.ip_address String IP Address where user accessed mail from
AbnormalSecurity.CaseAnalysis.eventTimeline.field_labels Unknown Analysis labels associated with the fields in the timeline event

Command Example

!abnormal-security-get-case-analysis-and-timeline case_id=12345

Context Example

{
    "AbnormalSecurity": {
        "CaseAnalysis": {
            "eventTimeline": [
                {
                    "category": "Risk Event",
                    "description": "Impossible Travel Event was observed for test@lamronba.com.",
                    "event_timestamp": "2021-07-14T22:41:54Z",
                    "ip_address": "127.0.0.1",
                    "location": {
                        "city": "Aldie",
                        "country": "US",
                        "state": "Virginia"
                    },
                    "prev_location": {
                        "city": "Atherton",
                        "country": "US",
                        "state": "California"
                    },
                    "title": "Impossible Travel"
                },
                {
                    "category": "Mail Rule",
                    "condition": "hasNoCondition",
                    "event_timestamp": "2021-07-14T22:41:54Z",
                    "flagging_detectors": "DELETE_ALL",
                    "rule_name": "Swag Voice Note",
                    "title": "Mail Rule Change"
                },
                {
                    "category": "Mail Sent",
                    "event_timestamp": "2021-07-14T22:41:54Z",
                    "recipient": "Recipient Name",
                    "sender": "test@lamronba.com",
                    "subject": "Spoof email subject",
                    "title": "Unusual Correspondence"
                },
                {
                    "application": "Microsoft Office 365 Portal",
                    "browser": "Chrome 79.0.3453",
                    "category": "Sign In",
                    "description": "Suspicious Failed Sign In Attempt for test@lamronba.com",
                    "device_trust_type": "None",
                    "event_timestamp": "2021-07-14T22:41:54Z",
                    "field_labels": {
                        "ip_address": ["rare", "proxy"],
                        "operating_system": ["legacy"]
                    },
                    "ip_address": "127.0.0.1",
                    "isp": "NGCOM",
                    "location": {
                        "country": "Ireland"
                    },
                    "operating_system": "Windows XP",
                    "protocol": "Browser",
                    "title": "Suspicious Failed Sign In Attempt"
                }
            ],
            "insights": [
                {
                    "description": "There was a signin into test@lamronba.com from a location frequently used to launch attacks.",
                    "signal": "Risky Location"
                }
            ]
        }
    }
}

Human Readable Output

Insights for 12345

signal description
Risky Location There was a signin into test@lamronba.com from a location frequently used to launch attacks.

Event Timeline for

event_timestamp category title field_labels ip_address description location sender subject title rule_name
2021-07-14T22:41:54Z Risk Event Impossible Travel   127.0.0.1 Impossible Travel Event was observed for test@lamronba.com. city: Aldie
state: Virginia
country: US
    Impossible Travel  
2021-07-14T22:41:54Z Mail Rule Mail Rule Change             Mail Rule Change Swag Voice Note
2021-07-14T22:41:54Z Mail Sent Unusual Correspondence         test@lamronba.com Spoof email subject Unusual Correspondence  
2021-07-14T22:41:54Z Sign In Suspicious Failed Sign In Attempt ip_address: rare,
proxy
operating_system: legacy
127.0.0.1 Suspicious Failed Sign In Attempt for test@lamronba.com country: Ireland     Suspicious Failed Sign In Attempt  

[Deprecated] abnormal-security-submit-inquiry-to-request-a-report-on-misjudgement


Submit an Inquiry to request a report on misjudgement by Abnormal Security

Base Command

abnormal-security-submit-inquiry-to-request-a-report-on-misjudgement

Input

Argument Name Description Required
mock-data Returns test data if set to True. Optional
reporter Email of the reporter. Required
report_type Type of misjudgement reported. Required

Context Output

Path Type Description
AbnormalSecurity.SubmitInquiry.detail String Confirmation of inquiry sent

Command Example

!abnormal-security-submit-inquiry-to-request-a-report-on-misjudgement reporter=abc@def.com report_type=false-positive

Context Example

{
    "AbnormalSecurity": {
        "SubmitInquiry": {
            "detail": "Thank you for your feedback! We have sent your inquiry to our support staff."
        }
    }
}

Human Readable Output

Results

detail
Thank you for your feedback! We have sent your inquiry to our support staff.

abnormal-security-submit-false-negative-report


Submit a False Negative Report

Base Command

abnormal-security-submit-false-negative-report

Input

Argument Name Description Required
sender_email Email address of the sender. Required
recipient_email Email address of the recipient. Required
subject Email subject. Required

Command Example

!abnormal-security-submit-false-negative-report recipient_email=abc@def.com sender_email=def@def.com subject=hello

Human Readable Output

Results

detail
Thank you for your feedback! We have sent your inquiry to our support staff.

abnormal-security-submit-false-positive-report


Submit a False Positive Report

Base Command

abnormal-security-submit-false-positive-report

Input

Argument Name Description Required
portal_link URL link of threat log in abnormal security portal Required

Command Example

!abnormal-security-submit-false-positive-report portal_link=https://portal.abnormalsecurity.com/home/threat-center/remediation-history/123455667

Human Readable Output

Results

detail
Thank you for your feedback! We have sent your inquiry to our support staff.

abnormal-security-list-vendors


Get a list of vendors

Base Command

abnormal-security-list-vendors

Input

Argument Name Description Required
page_size Number of vendors that are on each page. Each page of data will have at most page_size vendors. Has no effect if filter is not specified. Optional
page_number 1-indexed page number to get a particular page of vendors. Has no effect if filter is not specified. Optional

Context Output

Path Type Description
AbnormalSecurity.VendorsList Unknown List of vendors.
AbnormalSecurity.VendorsList.vendorDomain String The domain of the vendor.

Command Example

!abnormal-security-list-vendors

Context Example

{
    "AbnormalSecurity": {
        "VendorsList": [
            {
                "vendorDomain": "test-domain-1.com"
            },
            {
                "vendorDomain": "test-domain-2.com"
            },
            {
                "vendorDomain": "test-domain-2.com"
            }
        ]
    }
}

Human Readable Output

List of Vendors

Vendor Domains

vendorDomain
test-domain-1.com

abnormal-security-get-vendor-details


Get details of a vendor

Base Command

abnormal-security-get-vendor-details

Input

Argument Name Description Required
vendor_domain The domain name of the vendor in question. It should be formatted as a fully qualified domain name (e.g., example.com). Required

Context Output

Path Type Description
AbnormalSecurity.VendorDetails.vendorDomain String The domain name of the vendor
AbnormalSecurity.VendorDetails.riskLevel String The risk level associated with the vendor.
AbnormalSecurity.VendorDetails.vendorContacts Unknown List of contacts related to the vendor.
AbnormalSecurity.VendorDetails.companyContacts Unknown List of contacts related to the company.
AbnormalSecurity.VendorDetails.vendorCountries Unknown List of countries associated with the vendor.
AbnormalSecurity.VendorDetails.analysis Unknown List of analyses associated with the vendor.
AbnormalSecurity.VendorDetails.vendorIpAddresses Unknown List of IP addresses associated with the vendor.

Command Example

!abnormal-security-get-vendor-details vendor_domain="test-domain-1.com"

Context Example

{
    "AbnormalSecurity": {
        "VendorDetails": {
            "vendorDomain": "test-domain-1.com",
            "riskLevel": "High",
            "vendorContacts": ["john.doe@test-domain-1.com"],
            "companyContacts": ["john.doe@test-domain-2.com", "jane.doe@test-domain-2.com"],
            "vendorCountries": ["USA"],
            "analysis": ["Vendor Compromise Seen in Abnormal Community"],
            "vendorIpAddresses": ["192.158. 1.38"]
        }
    }
}

Human Readable Output

Vendor Domain Details

vendorDomain riskLevel vendorContacts companyContacts vendorCountries analysis vendorIpAddresses
test-domain-1.com High john.doe@test-domain-1.com john.doe@test-domain-2.com, jane.doe@test-domain-2.com USA Vendor Compromise Seen in Abnormal Community 192.158.1.38

abnormal-security-get-vendor-activity


Get details of a vendor

Base Command

abnormal-security-get-vendor-activity

Input

Argument Name Description Required
vendor_domain The domain name of the vendor in question. It should be formatted as a fully qualified domain name (e.g., example.com). Required

Context Output

Path Type Description
AbnormalSecurity.VendorActivity.eventTimeline Unknown Event timeline for the vendor.
AbnormalSecurity.VendorActivity.eventTimeline.eventTimestamp String Timestamp of the event in the vendor’s activity timeline.
AbnormalSecurity.VendorActivity.eventTimeline.eventType String Type of event in the vendor’s activity timeline.
AbnormalSecurity.VendorActivity.eventTimeline.suspiciousDomain String Suspicious domain involved in the event.
AbnormalSecurity.VendorActivity.eventTimeline.domainIp String IP address of the suspicious domain.
AbnormalSecurity.VendorActivity.eventTimeline.ipGeolocation String Geolocation of the IP address.
AbnormalSecurity.VendorActivity.eventTimeline.attackGoal String The goal of the attack.
AbnormalSecurity.VendorActivity.eventTimeline.actionTaken String Action taken in response to the event.
AbnormalSecurity.VendorActivity.eventTimeline.hasEngagement Boolean Indicates whether the event involved any form of engagement.
AbnormalSecurity.VendorActivity.eventTimeline.recipient Unknown The recipient targeted by the event, if applicable.
AbnormalSecurity.VendorActivity.eventTimeline.threatId String Unique identifier for the threat.

Command Example

!abnormal-security-get-vendor-activity vendor_domain="test-domain-1.com"

Context Example

{
    "AbnormalSecurity": {
        "VendorActivity": {
            "eventTimeline": [
                {
                    "eventTimestamp": "2023-07-28T16:20:05Z",
                    "eventType": "Federated Signal",
                    "suspiciousDomain": "test@test-domain.com",
                    "domainIp": "192.158.1.38",
                    "ipGeolocation": null,
                    "attackGoal": "Spam",
                    "actionTaken": "Remediation Triggered",
                    "hasEngagement": false,
                    "recipient": "jane@doe.com",
                    "threatId": "184712ab-6d8b-47b3-89d3-a314efef79e2"
                }
            ]
        }
    }
}

Human Readable Output

Vendor Activity

eventTimestamp eventType suspiciousDomain domainIp ipGeolocation attackGoal actionTaken hasEngagement recipient threatId
2023-07-28T16:20:05Z Federated Signal Signal test@test-domain.com 192.158.1.38 null Spam Remediation Triggered false jane@doe.com 184712ab-6d8b-47b3-89d3-a314efef79e2

abnormal-security-list-vendor-cases


Get a list of vendor cases

Base Command

!abnormal-security-list-vendor-cases

Input

Argument Name Description Required
filter Value must be of the format filter={FILTER KEY} gte YYYY-MM-DDTHH:MM:SSZ lte YYYY-MM-DDTHH:MM:SSZ. A {FILTER KEY} must be specified, and currently the only keys that are supported are firstObservedTime and lastModifiedTime. At least 1 of gte/lte must be specified, with a datetime string following the YYYY-MM-DDTHH:MM:SSZ format. Optional
page_size Number of cases that are on each page. Optional
page_number 1-indexed page number to get a particular page of cases. Optional

Context Output

Path Type Description
AbnormalSecurity.VendorCases Unknown List of vendor cases.
AbnormalSecurity.VendorCases.vendorCaseId Number The identifier of the vendor case.

Command Example

!abnormal-security-list-vendor-cases filter="lastModifiedTime gte 2020-12-01T01:01:01Z"

Context Example

{
    "AbnormalSecurity": {
        "VendorCases": [
            {
                "vendorCaseId": 123
            },
            {
                "vendorCaseId": 456
            },
            {
                "vendorCaseId": 789
            }
        ]
    }
}

Human Readable Output

List of Cases

Vendor Case IDs

vendorCaseId
123

abnormal-security-get-vendor-case-details


Get details of a vendor case

Base Command

!abnormal-security-get-vendor-case-details

Input

Argument Name Description Required
case_id A string representing the email case. Can be retrieved by first running command to list cases. Required
subtenant Subtenant of the user (if applicable). Optional

Context Output

Path Type Description
AbnormalSecurity.VendorCaseDetails.vendorCaseId String The identifier of the vendor case.
AbnormalSecurity.VendorCaseDetails.vendorDomain String The vendor domain associated with the case.
AbnormalSecurity.VendorCaseDetails.firstObservedTime String The time the vendor case was first observed.
AbnormalSecurity.VendorCaseDetails.lastModifiedTime String The last time the vendor case was modified.
AbnormalSecurity.VendorCaseDetails.insights Unknown List of insights related to the vendor case.
AbnormalSecurity.VendorCaseDetails.timeline Unknown Timeline of events related to the vendor case.

Command Example

!abnormal-security-get-vendor-case-details case_id=123

Context Example

{
    "AbnormalSecurity": {
        "AbnormalCaseDetails": {
            "vendorCaseId": 123,
            "vendorDomain": "some-domain.com",
            "firstObservedTime": "2022-04-04T21:12:14Z",
            "lastModifiedTime": "2022-04-05T14:40:11Z",
            "insights": [
                {
                    "highlight": "Inconsistent Sender Domain Registrars",
                    "description": "The suspicious sending domain, \"some-domain.com\", was registered in \"City, United States\" to \"unknown\" on 2022-02-07 with registrar \"ABCD\". The legitimate domain for \"some-domain.com\", was registered through \"Test, LLC\" in \"City, United States\" on 1999-12-02."
                },
                {
                    "highlight": "Look-a-like Sender Domain",
                    "description": "The sending domain of this message, \"some-domain.com\", is attempting to impersonate the legitimate domain of \"some-domain.com\"."
                },
                {
                    "highlight": "Young Sender Domain",
                    "description": "The sender domain \"some-domain.com\" was 65 days old when the first engagement in this case was observed, a suspicious signal for a financial email conversation."
                }
            ],
            "timeline": [
                {
                    "eventTimestamp": "2022-04-04T21:12:14Z",
                    "senderAddress": "john-doe@some-domain.com",
                    "recipientAddress": "jane.doe@some-other-domain.com",
                    "subject": "Important Notice",
                    "markedAs": "Malicious",
                    "threatId": 1234
                },
                {
                    "eventTimestamp": "2022-04-04T21:12:14Z",
                    "senderAddress": "jand-doe@some-domain.com",
                    "recipientAddress": "john@some-other-domain.com",
                    "subject": "Important Notice",
                    "markedAs": "Malicious",
                    "threatId": 12345
                }
            ]
        }
    }
}

Human Readable Output

Case Details

vendorCaseId vendorDomain firstObservedTime lastModifiedTime insights timeline
123 some-domain.com 2022-04-04T21:12:14Z 2022-04-05T14:40:11Z {“highlight”: “Inconsistent Sender Domain Registrars”,”description”: “The suspicious sending domain, "some-domain.com", was registered in "City, United States" to "unknown" on 2022-02-07 with registrar "ABCD". The legitimate domain for "some-domain.com", was registered through "Test, LLC" in "City, United States" on 1999-12-02.”}… {“eventTimestamp”: “2022-04-04T21:12:14Z”,”senderAddress”: “john-doe@some-domain.com”,”recipientAddress”: “jane.doe@some-other-domain.com”,”subject”: “Important Notice”,”markedAs”: “Malicious”,”threatId”: 123}..

abnormal-security-search-messages


Search for messages using filters across abnormal or quarantine sources.

Base Command

abnormal-security-search-messages

Input

Argument Name Description Required
source Message source (abnormal or quarantine). Possible values are: abnormal, quarantine. Required
tenant_ids Comma-separated list of tenant IDs. Optional
start_time Start time for the search in ISO 8601 format (e.g., 2024-01-01T00:00:00Z). Required
end_time End time for the search in ISO 8601 format (e.g., 2024-01-31T23:59:59Z). Required
subject Filter by email subject. Optional
sender_email Filter by sender email address. Optional
sender_name Filter by sender name. Optional
recipient_email Filter by recipient email address. Optional
recipient_name Filter by recipient name. Optional
attachment_name Filter by attachment name. Optional
attachment_md5_hash Filter by attachment MD5 hash. Optional
internet_message_id Filter by internet message ID. Optional
body_link Filter by body link/URL. Optional
sender_ip Filter by sender IP address. Optional
judgement Filter by judgement status. Possible values are: attack, borderline, spam, graymail, safe. Optional
use_sender_regex Use regex for sender filtering (default false). Possible values are: true, false. Optional
use_recipient_regex Use regex for recipient filtering (default false). Possible values are: true, false. Optional
show_graymail Show graymail messages (default false). Possible values are: true, false. Optional
page_number Page number (default 1). Optional
page_size Page size (default 100, max 1000). Optional

Context Output

Path Type Description
AbnormalSecurity.MessageSearch.results Unknown List of messages matching the search criteria.
AbnormalSecurity.MessageSearch.results.abnormal_message_id String Abnormal message identifier.
AbnormalSecurity.MessageSearch.results.subject String Email subject.
AbnormalSecurity.MessageSearch.results.sender String Sender email address.
AbnormalSecurity.MessageSearch.results.mailbox_name String Mailbox name where the message was received.
AbnormalSecurity.MessageSearch.results.received_time String Time when message was received.
AbnormalSecurity.MessageSearch.results.decision_category String Decision category (malicious, spam, safe, graymail).
AbnormalSecurity.MessageSearch.results.judgement String Judgement status (attack, borderline, spam, graymail, safe).
AbnormalSecurity.MessageSearch.total Number Total number of messages found.
AbnormalSecurity.MessageSearch.pageNumber Number Current page number.
AbnormalSecurity.MessageSearch.nextPageNumber Number Next page number.

abnormal-security-remediate-messages


Remediate messages by performing actions like delete, move, or submit to Detection360.

Base Command

abnormal-security-remediate-messages

Input

Argument Name Description Required
action Action to perform on messages. Possible values are: delete, move_to_inbox, submit_to_d360, reclassify. Required
tenant_ids Comma-separated list of tenant IDs. Optional
source Message source (abnormal or quarantine). Possible values are: abnormal, quarantine. Required
remediation_reason Reason for remediation. Possible values are: false_negative, misdirected, unsolicited, other, groups_remediation, quarantine_release. Required
messages JSON string containing array of message objects to remediate. Required if remediate_all is false. Optional
remediate_all Whether to remediate all messages matching search filters (default false). Possible values are: true, false. Optional
target_folder Target folder for move actions (e.g., “Deleted Items”). Optional
submit_d360_case Whether to submit a Detection360 case (default false). Possible values are: true, false. Optional
start_time Start time for search filters when remediate_all is true (ISO 8601 format). Optional
end_time End time for search filters when remediate_all is true (ISO 8601 format). Optional
subject Subject filter when remediate_all is true. Optional
sender_email Sender email filter when remediate_all is true. Optional
sender_name Sender name filter when remediate_all is true. Optional
recipient_email Recipient email filter when remediate_all is true. Optional
recipient_name Recipient name filter when remediate_all is true. Optional
attachment_name Attachment name filter when remediate_all is true. Optional
attachment_md5_hash Attachment MD5 hash filter when remediate_all is true. Optional
internet_message_id Internet message ID filter when remediate_all is true. Optional
body_link Body link/URL filter when remediate_all is true. Optional
sender_ip Sender IP address filter when remediate_all is true. Optional
judgement Judgement filter when remediate_all is true. Possible values are: attack, borderline, spam, graymail, safe. Optional
use_sender_regex Use regex for sender filtering when remediate_all is true (default false). Possible values are: true, false. Optional
use_recipient_regex Use regex for recipient filtering when remediate_all is true (default false). Possible values are: true, false. Optional
show_graymail Show graymail messages when remediate_all is true (default false). Possible values are: true, false. Optional

Context Output

Path Type Description
AbnormalSecurity.MessageRemediation.activity_log_id Number Activity log ID for tracking the remediation request.
AbnormalSecurity.MessageRemediation.metadata Unknown Metadata about the request.

abnormal-security-list-activities


Get a list of activity logs for message search and remediation operations.

Base Command

abnormal-security-list-activities

Input

Argument Name Description Required
tenant_ids Comma-separated list of tenant IDs (will be sent as query parameters). Optional
action Filter by action type. Possible values are: search, remediation, csv_export. Optional
page_number Page number (default 1). Optional
page_size Page size (default 100, max 1000). Optional

Context Output

Path Type Description
AbnormalSecurity.Activities.activities Unknown List of activity logs.
AbnormalSecurity.Activities.activities.activity_id Number Activity log ID.
AbnormalSecurity.Activities.activities.action String Action type (search, remediate, csv_export).
AbnormalSecurity.Activities.activities.status String Activity status.
AbnormalSecurity.Activities.activities.performed_by String User who performed the action.
AbnormalSecurity.Activities.activities.timestamp String Timestamp of the activity.
AbnormalSecurity.Activities.activities.result_count Number Number of results from the activity.
AbnormalSecurity.Activities.total Number Total number of activities.
AbnormalSecurity.Activities.page Number Current page number.
AbnormalSecurity.Activities.size Number Page size.

abnormal-security-get-activity-status


Get the status and details of a specific activity log entry.

Base Command

abnormal-security-get-activity-status

Input

Argument Name Description Required
activity_log_id Activity log ID to get status for. Required
page Page number (default 1). Optional
size Page size (default 100, max 1000). Optional

Context Output

Path Type Description
AbnormalSecurity.ActivityStatus.activity_id Number Activity log ID.
AbnormalSecurity.ActivityStatus.action String Action type.
AbnormalSecurity.ActivityStatus.status String Activity status.
AbnormalSecurity.ActivityStatus.performed_by String User who performed the action.
AbnormalSecurity.ActivityStatus.timestamp String Timestamp of the activity.
AbnormalSecurity.ActivityStatus.result_count Number Number of results.
AbnormalSecurity.ActivityStatus.remediation_details Unknown Detailed remediation information for each message.
AbnormalSecurity.ActivityStatus.total Number Total number of remediation details.

abnormal-security-download-message-attachment


Download an attachment from a message found in search results. All required parameters can be obtained from the abnormal-security-search-messages command output.

Base Command

abnormal-security-download-message-attachment

Input

Argument Name Description Required
message_id Abnormal message ID (can be negative). Obtained from message search results. Required
attachment_name Name of the attachment to download. Obtained from message search results attachments field. Required
tenant_id Tenant ID for the message. Obtained from message search results. Required
raw_message_id Cloud provider message ID (O365/GSuite). Obtained from message search results as raw_message_id. Required
native_user_id Cloud provider user ID. Obtained from message search results as native_user_id. Required
recipient_mailbox Mailbox email address. Obtained from message search results as mailbox_name. Required

Context Output

There is no context output for this command.

abnormal-security-download-message-eml


Download a message in RFC822 EML format for forensic analysis. For quarantine messages, both quarantine_identity and recipient_mailbox parameters are required.

Base Command

abnormal-security-download-message-eml

Input

Argument Name Description Required
cloud_message_id The cloud_message_id from search results (format abx:CloudMessage:…). Use the cloud_message_id field from message search results. Required
quarantine_identity Quarantine identifier (required only for quarantine messages). Obtained from quarantine_info.identity field in search results. Optional
recipient_mailbox Recipient email address (required only for quarantine messages). Obtained from mailbox_name field in search results. Optional

Context Output

There is no context output for this command.

abnormal-security-list-unanalyzed-abuse-mailbox-campaigns


Get a list of unanalyzed Abuse Mailbox campaigns

Base Command

abnormal-security-list-unanalyzed-abuse-mailbox-campaigns

Input

Argument Name Description Required
start The start time for retrieving the list of unanalyzed abuse mailbox campaigns.. Optional
end The end time for retrieving the list of unanalyzed abuse mailbox campaigns. Optional

Context Output

Path Type Description
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.abx_message_id Number An id which maps to an abuse campaign.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.recipient.name String The name of the recipient.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.recipient.email String The email address of the recipient.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.reported_datetime String The datetime the report was made.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.reporter.email String The email address of the reporter.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.reporter.name String The name of the reporter.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.subject String The subject of the message.
AbnormalSecurity.UnanalyzedAbuseCampaigns.results.not_analyzed_reason String The reason the message was not analyzed.

Command Example

!abnormal-security-list-unanalyzed-abuse-mailbox-campaigns

Context Example

{
    "AbnormalSecurity": {
        "AbuseCampaign": {
            "results": [
                {
                    "abx_message_id": 123456789,
                    "recipient": {
                        "name": "John Doe",
                        "email": "john.doe@some-domain.com"
                    },
                    "reported_datetime": "2023-06-15T00:17:31Z",
                    "reporter": {
                        "email": "info@some-domain.com",
                        "name": "Support"
                    },
                    "subject": "URGENT",
                    "not_analyzed_reason": "INVALID_SUBMISSION"
                },
                {
                    "abx_message_id": 987654321,
                    "recipient": {
                        "name": "Jane Doe",
                        "email": "jane.doe@some-domain.com"
                    },
                    "reported_datetime": "2023-06-14T06:23:31Z",
                    "reporter": {
                        "email": "info@some-domain.com",
                        "name": "support"
                    },
                    "subject": "Hello",
                    "not_analyzed_reason": "INVALID_SUBMISSION"
                }
            ]
        }
    }
}

Human Readable Output

Unanalyzed Abuse Mailbox Campaigns

abx_message_id recipient reported_datetime reporter subject not_analyzed_reason
123456789 name: John Doe email: john.doe@some-domain.com 2023-06-15T00:17:31Z email : info@some-domain.com name: Support URGENT INVALID_SUBMISSION

Configuration parameters

  • url — Server URL (e.g. https://api.abnormalplatform.com/v1) (required)
  • api_key — API Key (required)
  • insecure — Trust any certificate (not secure)
  • proxy — Use system proxy settings
  • isFetch — Fetch incidents
  • max_fetch — Maximum incidents to fetch.
  • fetch_threats — Fetch Threats
  • fetch_abuse_campaigns — Fetch Abuse Campaigns
  • fetch_account_takeover_cases — Fetch Account Takeover Cases
  • first_fetch — First fetch time
  • incidentType — Incident type
  • incidentFetchInterval — Incidents Fetch Interval
  • polling_lag — Polling Lag Time (in minutes)
  • max_page_number — Maximum incidents pages to fetch

Commands (31)

  • abnormal-security-check-case-action-status

    Check the status of an action requested on a case.

  • abnormal-security-check-threat-action-status

    Check the status of an action requested on a threat.

  • abnormal-security-download-message-attachment

    Download an attachment from a message found in search results. All required parameters can be obtained from the abnormal-security-search-messages command output.

  • abnormal-security-download-message-eml

    Download a message in RFC822 EML format for forensic analysis. For quarantine messages, both quarantine_identity and recipient_mailbox parameters are required.

  • abnormal-security-download-threat-log-csv

    Download data from Threat Log in .csv format.

  • abnormal-security-get-abnormal-case

    Get details of an Abnormal case.

  • abnormal-security-get-abuse-mailbox-campaign

    Get details of an Abuse Mailbox campaign.

  • abnormal-security-get-activity-status

    Get the status and details of a specific activity log entry.

  • abnormal-security-get-case-analysis-and-timeline

    Provides the analysis and timeline details of a case.

  • abnormal-security-get-employee-identity-analysis

    Get employee identity analysis (Genome) data.

  • abnormal-security-get-employee-information

    Get employee information.

  • abnormal-security-get-employee-last-30-days-login-csv

    Get employee login information for last 30 days in csv format.

  • abnormal-security-get-latest-threat-intel-feed Deprecated

    Get the latest threat intel feed.

  • abnormal-security-get-threat

    Get details of a threat.

  • abnormal-security-get-vendor-activity

    Get the activity for a specific vendor.

  • abnormal-security-get-vendor-case-details

    Get the details of a vendor case.

  • abnormal-security-get-vendor-details

    Get the details of a specific vendor.

  • abnormal-security-list-abnormal-cases

    Get a list of Abnormal cases identified by Abnormal Security.

  • abnormal-security-list-abuse-mailbox-campaigns

    Get a list of campaigns submitted to Abuse Mailbox.

  • abnormal-security-list-activities

    Get a list of activity logs for message search and remediation operations.

  • abnormal-security-list-threats

    Get a list of threats.

  • abnormal-security-list-unanalyzed-abuse-mailbox-campaigns

    Get a list of unanalyzed abuse mailbox campaigns.

  • abnormal-security-list-vendor-cases

    Get a list of vendor cases.

  • abnormal-security-list-vendors

    Get a list of vendors.

  • abnormal-security-manage-abnormal-case

    Manage an Abnormal Case.

  • abnormal-security-manage-threat

    Manage a Threat identified by Abnormal Security.

  • abnormal-security-remediate-messages

    Remediate messages by performing actions like delete, move, or submit to Detection360.

  • abnormal-security-search-messages

    Search for messages using filters across abnormal or quarantine sources.

  • abnormal-security-submit-false-negative-report

    Submit a False Negative Report.

  • abnormal-security-submit-false-positive-report

    Submit a False Positive Report.

  • abnormal-security-submit-inquiry-to-request-a-report-on-misjudgement

    Submit an Inquiry to request a report on misjudgement by Abnormal Security.

import json
from datetime import datetime, timedelta, UTC
import demistomock as demisto
import pytest

from AbnormalSecurity import (
    Client,
    check_the_status_of_an_action_requested_on_a_case_command,
    check_the_status_of_an_action_requested_on_a_threat_command,
    get_a_list_of_abnormal_cases_identified_by_abnormal_security_command,
    get_a_list_of_threats_command,
    get_a_list_of_vendors_command,
    get_the_details_of_a_specific_vendor_command,
    get_the_activity_of_a_specific_vendor_command,
    get_a_list_of_vendor_cases_command,
    get_the_details_of_a_vendor_case_command,
    manage_a_threat_identified_by_abnormal_security_command,
    manage_an_abnormal_case_command,
    get_details_of_an_abnormal_case_command,
    get_details_of_an_abuse_mailbox_campaign_command,
    provides_the_analysis_and_timeline_details_of_a_case_command,
    submit_an_inquiry_to_request_a_report_on_misjudgement_by_abnormal_security_command,
    submit_false_negative_report_command,
    submit_false_positive_report_command,
    get_a_list_of_campaigns_submitted_to_abuse_mailbox_command,
    get_the_latest_threat_intel_feed_command,
    get_employee_identity_analysis_genome_data_command,
    get_employee_information_command,
    get_employee_login_information_for_last_30_days_in_csv_format_command,
    download_data_from_threat_log_in_csv_format_command,
    generate_threat_incidents,
    generate_abuse_campaign_incidents,
    generate_account_takeover_cases_incidents,
    _is_skippable_error,
    get_a_list_of_unanalyzed_abuse_mailbox_campaigns_command,
    fetch_incidents,
    ISO_8601_FORMAT,
)
from CommonServerPython import DemistoException
from test_data.fixtures import BASE_URL, apikey
from test_data.mock_paginated_response import create_mock_paginator_side_effect, create_mock_detail_side_effect


headers = {
    "Authorization": f"Bearer {apikey}",
}


class MockResponse:
    def __init__(self, data, status_code):
        self.data = data
        self.text = str(data)
        self.status_code = status_code
        # Add content attribute for file downloads
        self.content = data if isinstance(data, bytes) else str(data).encode("utf-8")


def util_load_json(path):
    with open(path, encoding="utf-8") as f:
        return json.loads(f.read())


def util_load_response(path):
    with open(path, encoding="utf-8") as f:
        return MockResponse(f.read(), 200)


def mock_client(mocker, response=None, side_effect=None, throw_error=False):
    mocker.patch.object(demisto, "getIntegrationContext", return_value={"current_refresh_token": "refresh_token"})
    client = Client(server_url=BASE_URL, verify=False, proxy=False, auth=None, headers=headers)
    mocker.patch.object(client, "_http_request", return_value=response, side_effect=side_effect)

    if throw_error:
        err_msg = "Error in API call [400] - BAD REQUEST}"
        mocker.patch.object(client, "_http_request", side_effect=DemistoException(err_msg, res={}))

    return client


"""
    Command Unit Tests
"""


@pytest.fixture
def mock_get_a_list_of_threats_request(mocker):
    mocker.patch("AbnormalSecurity.Client.get_a_list_of_threats_request").return_value = util_load_json(
        "test_data/test_get_list_of_abnormal_threats.json"
    )


@pytest.fixture
def mock_get_details_of_a_threat_request(mocker):
    threat_details = util_load_json("test_data/test_get_details_of_a_threat_page2.json")
    threat_details["messages"][0]["remediationTimestamp"] = "2023-09-17T15:43:09Z"
    mocker.patch("AbnormalSecurity.Client.get_details_of_a_threat_request").return_value = threat_details


@pytest.fixture
def mock_get_a_list_of_campaigns_submitted_to_abuse_mailbox_request(mocker):
    mocker.patch(
        "AbnormalSecurity.Client.get_a_list_of_campaigns_submitted_to_abuse_mailbox_request"
    ).return_value = util_load_json("test_data/test_get_list_of_abuse_campaigns.json")


@pytest.fixture
def mock_get_a_list_of_abnormal_cases_identified_by_abnormal_security_request(mocker):
    mocker.patch(
        "AbnormalSecurity.Client.get_a_list_of_abnormal_cases_identified_by_abnormal_security_request"
    ).return_value = util_load_json("test_data/test_get_list_of_abnormal_cases.json")


def test_check_the_status_of_an_action_requested_on_a_case_command(mocker):
    """
    When:
        - Checking status of an action request on a case
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_check_status_of_action_requested_on_threat.json"))
    results = check_the_status_of_an_action_requested_on_a_case_command(client, {})
    assert results.outputs.get("status") == "acknowledged"
    assert results.outputs_prefix == "AbnormalSecurity.ActionStatus"


def test_check_the_status_of_an_action_requested_on_a_threat_command(mocker):
    """
    When:
        - Checking status of an action request on a threat
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_check_status_of_action_requested_on_threat.json"))
    results = check_the_status_of_an_action_requested_on_a_threat_command(client, {})
    assert results.outputs.get("status") == "acknowledged"
    assert results.outputs_prefix == "AbnormalSecurity.ActionStatus"


def test_get_a_list_of_abnormal_cases_identified_by_abnormal_security_command(mocker):
    """
    When:
        - Retrieving list of abnormal cases identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    # Modify the mock response to have a nextPageNumber
    abnormal_cases_list = util_load_json("test_data/test_get_list_of_abnormal_cases.json")
    abnormal_cases_list["nextPageNumber"] = 2

    client = mock_client(mocker, abnormal_cases_list)
    results = get_a_list_of_abnormal_cases_identified_by_abnormal_security_command(client, {})
    assert results.outputs.get("cases")[0].get("caseId") == "1234"
    assert results.outputs.get("pageNumber", 0) > 0
    assert results.outputs.get("nextPageNumber") == results.outputs.get("pageNumber", 0) + 1
    assert results.outputs_prefix == "AbnormalSecurity.inline_response_200_1"


def test_get_a_list_of_threats_command(mocker):
    """
    When:
        - Retrieving list of cases identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_list_of_abnormal_threats.json"))
    results = get_a_list_of_threats_command(client, {})
    assert results.outputs.get("threats")[0].get("threatId") == "asdf097sdf907"
    assert results.outputs_prefix == "AbnormalSecurity.inline_response_200"


def test_get_a_list_of_vendors_command(mocker):
    """
    When:
        - Retrieving list of vendors identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_a_list_of_vendors.json"))
    results = get_a_list_of_vendors_command(client, {})
    assert results.outputs[0].get("vendorDomain") == "test-domain-1.com"
    assert results.outputs_prefix == "AbnormalSecurity.VendorsList"


def test_get_the_details_of_a_specific_vendor_command(mocker):
    """
    When:
        - Retrieving details of a vendor
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_the_details_of_a_specific_vendor.json"))
    results = get_the_details_of_a_specific_vendor_command(client, {"vendor_domain": "test-domain-1.com"})
    assert results.outputs.get("vendorDomain") == "test-domain-1.com"
    assert results.outputs.get("vendorContacts")[0] == "john.doe@test-domain-1.com"
    assert results.outputs_prefix == "AbnormalSecurity.VendorDetails"


def test_get_the_activity_of_a_specific_vendor_command(mocker):
    """
    When:
        - Retrieving activity of a vendor
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_the_activity_of_a_specific_vendor.json"))
    results = get_the_activity_of_a_specific_vendor_command(client, {"vendor_domain": "test-domain-1.com"})
    assert results.outputs.get("eventTimeline")[0].get("suspiciousDomain") == "test@test-domain.com"
    assert results.outputs_prefix == "AbnormalSecurity.VendorActivity"


def test_get_a_list_of_vendor_cases_command(mocker):
    """
    When:
        - Retrieving list of vendor cases identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_a_list_of_vendor_cases.json"))
    results = get_a_list_of_vendor_cases_command(client, {})
    assert results.outputs[0].get("vendorCaseId") == 123
    assert results.outputs_prefix == "AbnormalSecurity.VendorCases"


def test_get_the_details_of_a_vendor_case_command(mocker):
    """
    When:
        - Retrieving details of a vendor case
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_the_details_of_a_vendor_case.json"))
    results = get_the_details_of_a_vendor_case_command(client, {"case_id": 2})
    assert results.outputs.get("vendorCaseId") == 123
    assert results.outputs.get("timeline")[0].get("threatId") == 1234
    assert results.outputs_prefix == "AbnormalSecurity.VendorCaseDetails"


def test_get_a_list_of_unanalyzed_abuse_mailbox_campaigns_command(mocker):
    """
    When:
        - Retrieving a list of abuse mailbox messages that is yet to be analyzed
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_a_list_of_unanalyzed_abuse_mailbox_messages.json"))
    results = get_a_list_of_unanalyzed_abuse_mailbox_campaigns_command(client, {})
    assert results.outputs.get("results")[0].get("abx_message_id") == 123456789
    assert results.outputs.get("results")[0].get("recipient").get("email") == "john.doe@some-domain.com"
    assert results.outputs_prefix == "AbnormalSecurity.UnanalyzedAbuseCampaigns"


def test_get_details_of_an_abnormal_case_command(mocker):
    """
    When:
        - Retrieving details of an abnormal case identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_an_abnormal_case.json"))
    results = get_details_of_an_abnormal_case_command(client, {})
    assert results.outputs.get("caseId") == "1234"
    assert results.outputs.get("threatIds")[0] == "184712ab-6d8b-47b3-89d3-a314efef79e2"
    assert results.outputs_prefix == "AbnormalSecurity.AbnormalCaseDetails"


def test_manage_a_threat_identified_by_abnormal_security_command_failure(mocker):
    """
    When:
        - Cause an API error when parsing bad data
    Then
        - Assert error is thrown as expected
    """
    client = mock_client(mocker, None, False, True)
    with pytest.raises(DemistoException):
        manage_a_threat_identified_by_abnormal_security_command(client, {})


def test_manage_a_threat_identified_by_abnormal_security_command_success(mocker):
    """
    When:
        - Successfully manage a threat identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_manage_threat.json"))
    results = manage_a_threat_identified_by_abnormal_security_command(client, {})
    assert results.outputs.get("action_id") == "61e76395-40d3-4d78-b6a8-8b17634d0f5b"
    assert results.outputs_prefix == "AbnormalSecurity.ThreatManageResults"


def test_manage_an_abnormal_case_command_failure(mocker):
    """
    When:
        - Cause an API error when passing bad data
    Then
        - Assert error is thrown as expected
    """
    client = mock_client(mocker, None, False, True)
    with pytest.raises(DemistoException):
        manage_an_abnormal_case_command(client, {})


def test_manage_an_abnormal_case_command_success(mocker):
    """
    When:
        - Successfully manage a threat identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_manage_case.json"))
    results = manage_an_abnormal_case_command(client, {})
    assert results.outputs.get("action_id") == "61e76395-40d3-4d78-b6a8-8b17634d0f5b"
    assert results.outputs_prefix == "AbnormalSecurity.CaseManageResults"


def test_submit_an_inquiry_to_request_a_report_on_misjudgement_by_abnormal_security_command(mocker):
    """
    When:
        - Submit an inquiry
    Then
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, "Thank you for your feedback! We have sent your inquiry to our support staff.")
    args = {"reporter": "abc@def.com", "report_type": "false-positive"}

    results = submit_an_inquiry_to_request_a_report_on_misjudgement_by_abnormal_security_command(client, args)
    assert results.outputs_prefix == "AbnormalSecurity.SubmitInquiry"


def test_submit_a_false_negative_command(mocker):
    """
    When:
        - Submit a FN command
    Then
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, "Thank you for your feedback! We have sent your inquiry to our support staff.")
    args = {"sender_email": "abc@def.com", "recipient_email": "abc@def.com", "subject": "test"}

    results = submit_false_negative_report_command(client, args)
    assert results.readable_output == "Thank you for your feedback! We have sent your inquiry to our support staff."


def test_submit_a_false_positive_command(mocker):
    """
    When:
        - Submit a FP command
    Then
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, "Thank you for your feedback! We have sent your inquiry to our support staff.")
    args = {
        "portal_link": "https://portal.abnormalsecurity.com/home/threat-center/remediation-history/12345",
    }

    results = submit_false_positive_report_command(client, args)
    assert results.readable_output == "Thank you for your feedback! We have sent your inquiry to our support staff."


def test_get_the_latest_threat_intel_feed_command(mocker):
    """
    When:
        - Retrieve intel feed
    Then
        - Assert downloaded file name is as expected
    """
    client = mock_client(mocker, util_load_response("test_data/test_get_threat_intel_feed.json"))
    results = get_the_latest_threat_intel_feed_command(client)
    assert results["File"] == "threat_intel_feed.json"


def test_download_data_from_threat_log_in_csv_format_command(mocker):
    """
    When:
        - Downloading threat log in csv format
    Then
        - Assert downloaded file name is as expected
    """
    client = mock_client(mocker, util_load_response("test_data/test_download_data_from_threat_log_in_csv_format.csv"))
    results = download_data_from_threat_log_in_csv_format_command(client, {})

    assert results["File"] == "threat_log.csv"


def test_get_a_list_of_campaigns_submitted_to_abuse_mailbox_command(mocker):
    """
    When:
        - Retrieving list of abuse campaigns identified
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    # Modify the mock response to have a nextPageNumber
    abnormal_campaigns_list = util_load_json("test_data/test_get_list_of_abuse_campaigns.json")
    abnormal_campaigns_list["nextPageNumber"] = 2

    client = mock_client(mocker, abnormal_campaigns_list)
    results = get_a_list_of_campaigns_submitted_to_abuse_mailbox_command(client, {})
    assert results.outputs.get("campaigns")[0].get("campaignId") == "fff51768-c446-34e1-97a8-9802c29c3ebd"
    assert results.outputs.get("pageNumber", 0) > 0
    assert results.outputs.get("nextPageNumber") == results.outputs.get("pageNumber", 0) + 1
    assert results.outputs_prefix == "AbnormalSecurity.AbuseCampaign"


def test_get_details_of_an_abuse_mailbox_campaign_command(mocker):
    """
    When:
        - Retrieving details of an abuse mailbox campaign reported
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_abuse_campaign.json"))
    results = get_details_of_an_abuse_mailbox_campaign_command(client, {})
    assert results.outputs.get("campaignId") == "fff51768-c446-34e1-97a8-9802c29c3ebd"
    assert results.outputs.get("attackType") == "Attack Type: Spam"
    assert results.outputs_prefix == "AbnormalSecurity.AbuseCampaign"


def test_get_employee_identity_analysis_genome_data_command(mocker):
    """
    When:
        - Retrieving analysis histograms of employee
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_genome_data.json"))
    results = get_employee_identity_analysis_genome_data_command(client, {})
    assert len(results.outputs.get("histograms")) > 0
    assert results.outputs.get("histograms")[0]["key"] == "ip_address"
    for index, val in enumerate(results.outputs.get("histograms")[0]["values"]):
        assert val["text"] == f"ip-address-{index}"
    assert results.outputs_prefix == "AbnormalSecurity.Employee"


def test_get_employee_information_command(mocker):
    """
    When:
        - Retrieving company employee information
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_employee_info.json"))
    results = get_employee_information_command(client, {})
    assert results.outputs.get("name") == "test_name"
    assert results.outputs_prefix == "AbnormalSecurity.Employee"


def test_get_employee_login_information_for_last_30_days_in_csv_format_command(mocker):
    """
    When:
        - Downloading employee login information in csv format
    Then
        - Assert downloaded file name is as expected
    """
    client = mock_client(mocker, util_load_response("test_data/test_get_employee_login_info_csv.csv"))
    results = get_employee_login_information_for_last_30_days_in_csv_format_command(client, {})
    assert results["File"] == "employee_login_info_30_days.csv"


def test_provides_the_analysis_and_timeline_details_of_a_case_command(mocker):
    """
    When:
        - Retrieving anaylsis and timeline detail of a case
    Then
        - Assert the context data is as expected.
        - Assert output prefix data is as expected
    """
    client = mock_client(mocker, util_load_json("test_data/test_get_case_analysis_and_timeline.json"))
    results = provides_the_analysis_and_timeline_details_of_a_case_command(client, {})
    assert len(results.outputs.get("insights")) > 0
    assert len(results.outputs.get("eventTimeline")) > 0
    assert results.outputs_prefix == "AbnormalSecurity.CaseAnalysis"


def test_fetch_threat_incidents(mocker, mock_get_a_list_of_threats_request):
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_a_threat_page2.json"))
    first_fetch_time = datetime.now().strftime(ISO_8601_FORMAT)
    _, incidents = fetch_incidents(
        client=client,
        last_run={"last_fetch": "2023-09-17T14:43:09Z"},
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=200,
        fetch_account_takeover_cases=False,
        fetch_abuse_campaigns=False,
        fetch_threats=True,
    )
    assert len(incidents) == 1


def test_fetch_cases_incidents(mocker, mock_get_a_list_of_abnormal_cases_identified_by_abnormal_security_request):
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_an_abnormal_case.json"))
    first_fetch_time = datetime.now().strftime(ISO_8601_FORMAT)
    _, incidents = fetch_incidents(
        client=client,
        last_run={"last_fetch": "2023-09-17T14:43:09Z"},
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=200,
        fetch_account_takeover_cases=True,
        fetch_abuse_campaigns=False,
        fetch_threats=False,
    )
    assert len(incidents) == 1
    assert incidents[0].get("genaiSummary") == "genai_summary"


def test_fetch_abuse_campaign_incidents(mocker, mock_get_a_list_of_campaigns_submitted_to_abuse_mailbox_request):
    client = mock_client(mocker, util_load_json("test_data/test_get_details_of_abuse_campaign.json"))
    first_fetch_time = datetime.now().strftime(ISO_8601_FORMAT)
    _, incidents = fetch_incidents(
        client=client,
        last_run={"last_fetch": "2023-09-17T14:43:09Z"},
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=200,
        fetch_account_takeover_cases=False,
        fetch_abuse_campaigns=True,
        fetch_threats=False,
    )
    assert len(incidents) == 1


def test_get_details_of_a_threat_request_two_pages(mocker):
    return_val = util_load_json("test_data/test_get_details_of_a_threat.json")
    return_val["messages"][0]["remediationTimestamp"] = "2023-09-17T15:43:09Z"
    page_2 = util_load_json("test_data/test_get_details_of_a_threat_page2.json")
    page_2["messages"][0]["remediationTimestamp"] = "2023-09-17T16:43:09Z"

    client = mock_client(mocker, side_effect=[return_val, page_2])
    # Create datetime objects instead of using strings
    start_datetime = datetime(2023, 9, 17, 14, 43, 9, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 18, 14, 43, 9, tzinfo=UTC)

    incidents = generate_threat_incidents(client, [{"threatId": "asdf097sdf907"}], 2, start_datetime, end_datetime)
    assert len(incidents) == 1
    assert len(json.loads(incidents[0].get("rawJSON")).get("messages")) == 2


def test_get_details_of_a_threat_request_single_page(mocker):
    return_val = util_load_json("test_data/test_get_details_of_a_threat_page2.json")
    return_val["messages"][0]["remediationTimestamp"] = "2023-09-17T15:43:09Z"
    client = mock_client(mocker, response=return_val)
    # Create datetime objects instead of using strings
    start_datetime = datetime(2023, 9, 17, 14, 43, 9, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 18, 14, 43, 9, tzinfo=UTC)

    incidents = generate_threat_incidents(client, [{"threatId": "asdf097sdf907"}], 1, start_datetime, end_datetime)
    assert len(incidents) == 1


def test_get_details_of_a_threat_request_nanosecond_timestamp(mocker, mock_get_details_of_a_threat_request):
    client = mock_client(mocker, response=util_load_json("test_data/test_get_list_of_abnormal_threats.json"))
    last_run = {"last_fetch": "2023-09-17T14:43:09Z"}
    first_fetch_time = "3 days"
    max_incidents = 200
    # Call fetch_incidents with the polling lag
    _, incidents = fetch_incidents(
        client=client,
        last_run=last_run,
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=max_incidents,
        fetch_account_takeover_cases=False,
        fetch_abuse_campaigns=False,
        fetch_threats=True,
    )
    assert len(incidents) == 1
    assert incidents[0].get("occurred") == "2023-12-03T19:26:36.123456"


def test_polling_lag(mocker, mock_get_details_of_a_threat_request):
    """Test that polling lag is correctly applied when fetching incidents."""
    # Mock the client and its get_a_list_of_threats_request method
    return_val = util_load_json("test_data/test_get_list_of_abnormal_threats.json")
    client = mock_client(mocker, response=return_val)

    # Create a spy on the get_a_list_of_threats_request method to capture its calls
    get_threats_spy = mocker.spy(client, "get_a_list_of_threats_request")

    # Define test parameters
    last_run = {"last_fetch": "2023-09-17T14:43:09Z"}
    first_fetch_time = "3 days"
    max_incidents = 200

    # Set up a 5-minute polling lag
    polling_lag = timedelta(minutes=5)

    # Calculate expected timestamps
    original_timestamp = datetime.fromisoformat(last_run["last_fetch"][:-1]).replace(tzinfo=UTC) + timedelta(milliseconds=1)
    adjusted_start_time = original_timestamp - polling_lag
    expected_start_time = adjusted_start_time.strftime("%Y-%m-%dT%H:%M:%SZ")

    # Mock the get_current_datetime function to return a fixed time
    fixed_current_time = datetime(2023, 9, 18, 14, 43, 9, tzinfo=UTC)
    mocker.patch("AbnormalSecurity.get_current_datetime", return_value=fixed_current_time)

    # Calculate expected end time based on the fixed current time
    adjusted_end_time = fixed_current_time - polling_lag
    expected_end_time = adjusted_end_time.strftime("%Y-%m-%dT%H:%M:%SZ")

    expected_filter = f"latestTimeRemediated gte {expected_start_time} and latestTimeRemediated lte {expected_end_time}"

    # Call fetch_incidents with the polling lag
    _, _ = fetch_incidents(
        client=client,
        last_run=last_run,
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=max_incidents,
        fetch_account_takeover_cases=False,
        fetch_abuse_campaigns=False,
        fetch_threats=True,
        polling_lag=polling_lag,
    )

    # Check that the method was called with the expected filter
    get_threats_spy.assert_called_once()
    call_args = get_threats_spy.call_args[1]

    # Assert that the filter matches our expected filter
    assert call_args["filter_"] == expected_filter
    assert call_args["page_size"] == 100


def test_get_details_of_a_threat_request_time_window_filtering(mocker):
    """Test that messages outside the time window are filtered out."""
    # Create a mock response with 3 messages
    mock_response = {
        "threatId": "test-threat-id",
        "messages": [
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T15:00:00Z",
                "remediationTimestamp": "2023-09-17T15:30:00Z",  # Inside window
            },
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T16:00:00Z",
                "remediationTimestamp": "2023-09-17T16:30:00Z",  # Inside window
            },
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T12:00:00Z",
                "remediationTimestamp": "2023-09-17T12:30:00Z",  # Outside window (before start_time)
            },
        ],
    }

    client = mock_client(mocker, response=mock_response)

    # Define time window that includes only the first two messages
    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    incidents = generate_threat_incidents(client, [{"threatId": "test-threat-id"}], 1, start_datetime, end_datetime)

    # Verify we get one incident
    assert len(incidents) == 1

    # Verify the incident contains only the messages within the time window
    incident_data = json.loads(incidents[0]["rawJSON"])
    assert len(incident_data["messages"]) == 2

    # Verify the filtered messages are the ones we expect
    remediation_times = [msg["remediationTimestamp"] for msg in incident_data["messages"]]
    assert "2023-09-17T15:30:00Z" in remediation_times
    assert "2023-09-17T16:30:00Z" in remediation_times
    assert "2023-09-17T12:30:00Z" not in remediation_times


def test_get_details_of_a_threat_request_early_exit(mocker):
    """Test that processing stops early when encountering messages outside the time window."""
    # Create mock responses for two pages
    # Page 1 with 2 messages (both inside time window)
    page_1 = {
        "threatId": "test-threat-id",
        "messages": [
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T16:00:00Z",
                "remediationTimestamp": "2023-09-17T16:30:00Z",  # Inside window (latest)
            },
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T15:00:00Z",
                "remediationTimestamp": "2023-09-17T15:30:00Z",  # Inside window
            },
        ],
        "nextPageNumber": 2,  # Indicate there's a second page
    }

    # Page 2 with 2 messages (both outside time window)
    page_2 = {
        "threatId": "test-threat-id",
        "messages": [
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T13:00:00Z",
                "remediationTimestamp": "2023-09-17T13:30:00Z",  # Outside window
            },
            {
                "threatId": "test-threat-id",
                "receivedTime": "2023-09-17T12:00:00Z",
                "remediationTimestamp": "2023-09-17T12:30:00Z",  # Outside window (earliest)
            },
        ],
        "nextPageNumber": None,  # No more pages
    }

    # Create a spy for the get_details_of_a_threat_request method
    client = mock_client(mocker, side_effect=[page_1, page_2])
    get_details_spy = mocker.spy(client, "get_details_of_a_threat_request")

    # Define time window that includes only the first two messages
    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    incidents = generate_threat_incidents(client, [{"threatId": "test-threat-id"}], 3, start_datetime, end_datetime)

    # Verify we get one incident
    assert len(incidents) == 1

    # Verify the incident contains only the messages within the time window
    incident_data = json.loads(incidents[0]["rawJSON"])
    assert len(incident_data["messages"]) == 2

    # Verify the filtered messages are the ones we expect (from page 1 only)
    remediation_times = [msg["remediationTimestamp"] for msg in incident_data["messages"]]
    assert "2023-09-17T16:30:00Z" in remediation_times
    assert "2023-09-17T15:30:00Z" in remediation_times
    assert "2023-09-17T13:30:00Z" not in remediation_times
    assert "2023-09-17T12:30:00Z" not in remediation_times

    # Verify that get_details_of_a_threat_request was called exactly twice
    # (once for page 1, once for page 2 where we encounter messages outside the time window and exit early)
    assert get_details_spy.call_count == 2

    # Verify the calls were made with the correct page numbers
    first_call_args = get_details_spy.call_args_list[0][1]
    second_call_args = get_details_spy.call_args_list[1][1]
    assert first_call_args["page_number"] == 1
    assert second_call_args["page_number"] == 2


def test_pagination_methods_in_fetch_incidents(mocker):
    """
    Test that the pagination methods are called correctly from fetch_incidents.
    This test verifies:
    1. The methods are called with the correct parameters
    2. The pagination logic is executed as expected
    3. The returned incidents are correctly processed
    """
    # Create mock pagination side effects for threats, cases, and campaigns
    threat_list_side_effect = create_mock_paginator_side_effect("threat")
    case_list_side_effect = create_mock_paginator_side_effect("case")
    campaign_list_side_effect = create_mock_paginator_side_effect("campaign")

    # Create mock detail side effects
    threat_detail_side_effect = create_mock_detail_side_effect("threat")
    case_detail_side_effect = create_mock_detail_side_effect("case")
    campaign_detail_side_effect = create_mock_detail_side_effect("campaign")

    # Create client
    client = Client(server_url=BASE_URL, verify=False, proxy=False, auth=None, headers=headers)

    # Get threat response samples for the mock
    threat_page1 = threat_list_side_effect(page_number=1, page_size=2)
    threat_page2 = threat_list_side_effect(page_number=2, page_size=2)

    # Get case response samples for the mock
    case_page1 = case_list_side_effect(page_number=1, page_size=2)
    case_page2 = case_list_side_effect(page_number=2, page_size=2)

    # Get campaign response samples for the mock
    campaign_page1 = campaign_list_side_effect(page_number=1, page_size=2)
    campaign_page2 = campaign_list_side_effect(page_number=2, page_size=2)

    # Extract threat IDs for detail responses - for each page we'll get exactly page_size items
    threat_ids = [threat["threatId"] for threat in threat_page1.get("threats")[:2] + threat_page2.get("threats")[:2]]
    case_ids = [case["caseId"] for case in case_page1.get("cases")[:2] + case_page2.get("cases")[:2]]
    campaign_ids = [
        campaign["campaignId"] for campaign in campaign_page1.get("campaigns")[:2] + campaign_page2.get("campaigns")[:2]
    ]

    # Combine responses for each type
    threats_combined = {"threats": threat_page1.get("threats") + threat_page2.get("threats")}

    cases_combined = {"cases": case_page1.get("cases") + case_page2.get("cases")}

    campaigns_combined = {"campaigns": campaign_page1.get("campaigns") + campaign_page2.get("campaigns")}

    # Set up test parameters
    last_run = {"last_fetch": "2023-09-17T14:43:09Z"}
    first_fetch_time = "3 days"
    max_incidents = 200
    polling_lag = timedelta(minutes=5)

    # Mock the three pagination methods
    get_paginated_threats_spy = mocker.patch.object(client, "get_paginated_threats_list", return_value=threats_combined)

    get_paginated_cases_spy = mocker.patch.object(client, "get_paginated_cases_list", return_value=cases_combined)

    get_paginated_campaigns_spy = mocker.patch.object(
        client, "get_paginated_abusecampaigns_list", return_value=campaigns_combined
    )

    # Mock the get_details methods to return appropriate data for incident generation
    mocker.patch.object(
        client, "get_details_of_a_threat_request", side_effect=lambda threat_id, **kwargs: threat_detail_side_effect(threat_id)
    )

    mocker.patch.object(
        client, "get_details_of_an_abnormal_case_request", side_effect=lambda case_id, **kwargs: case_detail_side_effect(case_id)
    )

    mocker.patch.object(
        client,
        "get_details_of_an_abuse_mailbox_campaign_request",
        side_effect=lambda campaign_id, **kwargs: campaign_detail_side_effect(campaign_id),
    )

    # Mock the get_current_datetime function to return a fixed time
    mocker.patch("AbnormalSecurity.get_current_datetime", return_value=datetime(2023, 9, 18, 14, 43, 9, tzinfo=UTC))

    # Call fetch_incidents with all three fetch options enabled
    next_run, incidents = fetch_incidents(
        client=client,
        last_run=last_run,
        first_fetch_time=first_fetch_time,
        max_incidents_to_fetch=max_incidents,
        fetch_account_takeover_cases=True,
        fetch_abuse_campaigns=True,
        fetch_threats=True,
        polling_lag=polling_lag,
    )

    # Verify the pagination methods were called with the correct filters

    # 1. Verify threats pagination
    get_paginated_threats_spy.assert_called_once()
    threats_call_kwargs = get_paginated_threats_spy.call_args.kwargs

    # Verify the filter contains latestTimeRemediated with adjusted time due to polling lag
    assert "latestTimeRemediated gte" in threats_call_kwargs["filter_"]
    assert "latestTimeRemediated lte" in threats_call_kwargs["filter_"]
    assert threats_call_kwargs["max_incidents_to_fetch"] == max_incidents

    # 2. Verify abuse campaigns pagination (this is called next in the code)
    get_paginated_campaigns_spy.assert_called_once()
    campaigns_call_kwargs = get_paginated_campaigns_spy.call_args.kwargs

    # Verify the filter contains lastReportedTime
    assert "lastReportedTime gte" in campaigns_call_kwargs["filter_"]
    assert "lastReportedTime lte" in campaigns_call_kwargs["filter_"]
    assert campaigns_call_kwargs["max_incidents_to_fetch"] == max_incidents - len(threat_ids)

    # 3. Verify cases pagination (this is called last in the code)
    get_paginated_cases_spy.assert_called_once()
    cases_call_kwargs = get_paginated_cases_spy.call_args.kwargs
    # Verify the filter contains lastModifiedTime
    assert "lastModifiedTime gte" in cases_call_kwargs["filter_"]
    assert "lastModifiedTime lte" in cases_call_kwargs["filter_"]
    assert cases_call_kwargs["max_incidents_to_fetch"] == max_incidents - len(threat_ids) - len(campaign_ids)

    # Verify we got the expected number of incidents
    expected_incident_count = len(threat_ids) + len(case_ids) + len(campaign_ids)
    assert len(incidents) == expected_incident_count

    # Verify the types of incidents
    threat_incidents = [i for i in incidents if i.get("name") == "Threat"]
    case_incidents = [i for i in incidents if i.get("name") == "Account Takeover Case"]
    campaign_incidents = [i for i in incidents if i.get("name") == "Abuse Campaign"]

    assert len(threat_incidents) == len(threat_ids)
    assert len(case_incidents) == len(case_ids)
    assert len(campaign_incidents) == len(campaign_ids)

    # Verify next_run contains updated last_fetch timestamp
    assert next_run.get("last_fetch", None) is not None
    assert next_run.get("last_fetch") > last_run.get("last_fetch")


def test_get_paginated_threats_list(mocker):
    """
    Test the get_paginated_threats_list method to verify:
    1. It correctly handles pagination
    2. It respects the max_incidents_to_fetch parameter
    """
    # Create client
    client = Client(server_url=BASE_URL, verify=False, proxy=False, auth=None, headers=headers)

    # Create a side effect function for threats
    get_threats_side_effect = create_mock_paginator_side_effect("threat")

    # Mock the underlying get_a_list_of_threats_request method
    get_threats_mock = mocker.patch.object(client, "get_a_list_of_threats_request", side_effect=get_threats_side_effect)

    # Test case 1: Get all threats with high limit (max_incidents_to_fetch > existing items)
    # This should set page_size to the limit (10) but return only as many items as exist
    result = client.get_paginated_threats_list(filter_="test filter", max_incidents_to_fetch=10)

    # Verify the result contains threats (the exact count depends on the mock function)
    assert len(result["threats"]) > 0

    # Verify the first call was made with correct parameters
    assert get_threats_mock.call_count >= 1
    first_call_kwargs = get_threats_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 10
    assert first_call_kwargs["page_number"] == 1

    # Reset the mock for the next test
    get_threats_mock.reset_mock()

    # Test case 2: Limited page size (max_incidents_to_fetch = 2)
    # With many threats available and max_incidents_to_fetch=2, we expect page_size=2
    # This should result in multiple page calls since there are more threats than fit on one page
    result = client.get_paginated_threats_list(filter_="test filter", max_incidents_to_fetch=2)

    # Verify we got threats
    assert len(result["threats"]) > 0

    # Verify each page was requested with the correct parameters
    assert get_threats_mock.call_count >= 1

    # Check first call parameters
    first_call_kwargs = get_threats_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 2
    assert first_call_kwargs["page_number"] == 1

    # If there was a second call, check its parameters
    if get_threats_mock.call_count > 1:
        second_call_kwargs = get_threats_mock.call_args_list[1][1]
        assert second_call_kwargs["page_size"] == 2
        assert second_call_kwargs["page_number"] == 2

    # Reset the mock for the next test
    get_threats_mock.reset_mock()

    # Test case 3: One threat per page (max_incidents_to_fetch = 1)
    # With many threats available and max_incidents_to_fetch=1, we expect page_size=1
    # This should result in multiple page calls, one per threat
    result = client.get_paginated_threats_list(filter_="test filter", max_incidents_to_fetch=1)

    # Verify we got threats
    assert len(result["threats"]) > 0

    # Verify multiple pages were requested
    assert get_threats_mock.call_count >= 1

    # Check that all calls have the correct page_size
    for i in range(get_threats_mock.call_count):
        call_kwargs = get_threats_mock.call_args_list[i][1]
        assert call_kwargs["page_size"] == 1
        assert call_kwargs["page_number"] == i + 1

    # Reset the mock for the next test
    get_threats_mock.reset_mock()

    # Test case 4: No threats to fetch (max_incidents_to_fetch = 0)
    result = client.get_paginated_threats_list(filter_="test filter", max_incidents_to_fetch=0)

    # Verify that no threats were fetched
    assert len(result["threats"]) == 0

    # Verify that the underlying method was not called
    assert get_threats_mock.call_count == 0


def test_get_paginated_cases_list(mocker):
    """
    Test the get_paginated_cases_list method to verify:
    1. It correctly handles pagination
    2. It respects the max_incidents_to_fetch parameter
    """
    # Create client
    client = Client(server_url=BASE_URL, verify=False, proxy=False, auth=None, headers=headers)

    # Create a side effect function for cases
    get_cases_side_effect = create_mock_paginator_side_effect("case")

    # Mock the underlying get_a_list_of_abnormal_cases_identified_by_abnormal_security_request method
    get_cases_mock = mocker.patch.object(
        client, "get_a_list_of_abnormal_cases_identified_by_abnormal_security_request", side_effect=get_cases_side_effect
    )

    # Test case 1: Get all cases with high limit (max_incidents_to_fetch > existing items)
    # This should set page_size to the limit (10) but return only as many items as exist
    result = client.get_paginated_cases_list(filter_="test filter", max_incidents_to_fetch=10)

    # Verify the result contains cases (the exact count depends on the mock function)
    assert len(result["cases"]) > 0

    # Verify the first call was made with correct parameters
    assert get_cases_mock.call_count >= 1
    first_call_kwargs = get_cases_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 10
    assert first_call_kwargs["page_number"] == 1

    # Reset the mock for the next test
    get_cases_mock.reset_mock()

    # Test case 2: Limited page size (max_incidents_to_fetch = 2)
    # With many cases available and max_incidents_to_fetch=2, we expect page_size=2
    # This should result in multiple page calls since there are more cases than fit on one page
    result = client.get_paginated_cases_list(filter_="test filter", max_incidents_to_fetch=2)

    # Verify we got cases
    assert len(result["cases"]) > 0

    # Verify each page was requested with the correct parameters
    assert get_cases_mock.call_count >= 1

    # Check first call parameters
    first_call_kwargs = get_cases_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 2
    assert first_call_kwargs["page_number"] == 1

    # If there was a second call, check its parameters
    if get_cases_mock.call_count > 1:
        second_call_kwargs = get_cases_mock.call_args_list[1][1]
        assert second_call_kwargs["page_size"] == 2
        assert second_call_kwargs["page_number"] == 2

    # Reset the mock for the next test
    get_cases_mock.reset_mock()

    # Test case 3: One case per page (max_incidents_to_fetch = 1)
    # With many cases available and max_incidents_to_fetch=1, we expect page_size=1
    # This should result in multiple page calls, one per case
    result = client.get_paginated_cases_list(filter_="test filter", max_incidents_to_fetch=1)

    # Verify we got cases
    assert len(result["cases"]) > 0

    # Verify multiple pages were requested
    assert get_cases_mock.call_count >= 1

    # Check that all calls have the correct page_size
    for i in range(get_cases_mock.call_count):
        call_kwargs = get_cases_mock.call_args_list[i][1]
        assert call_kwargs["page_size"] == 1
        assert call_kwargs["page_number"] == i + 1

    # Reset the mock for the next test
    get_cases_mock.reset_mock()

    # Test case 4: No cases to fetch (max_incidents_to_fetch = 0)
    result = client.get_paginated_cases_list(filter_="test filter", max_incidents_to_fetch=0)

    # Verify that no cases were fetched
    assert len(result["cases"]) == 0

    # Verify that the underlying method was not called
    assert get_cases_mock.call_count == 0


def test_get_paginated_abusecampaigns_list(mocker):
    """
    Test the get_paginated_abusecampaigns_list method to verify:
    1. It correctly handles pagination
    2. It respects the max_incidents_to_fetch parameter
    """
    # Create client
    client = Client(server_url=BASE_URL, verify=False, proxy=False, auth=None, headers=headers)

    # Create a side effect function for campaigns
    get_campaigns_side_effect = create_mock_paginator_side_effect("campaign")

    # Mock the underlying get_a_list_of_campaigns_submitted_to_abuse_mailbox_request method
    get_campaigns_mock = mocker.patch.object(
        client, "get_a_list_of_campaigns_submitted_to_abuse_mailbox_request", side_effect=get_campaigns_side_effect
    )

    # Test case 1: Get all campaigns with high limit (max_incidents_to_fetch > existing items)
    # This should set page_size to the limit (10) but return only as many items as exist
    result = client.get_paginated_abusecampaigns_list(filter_="test filter", max_incidents_to_fetch=10)

    # Verify the result contains campaigns (the exact count depends on the mock function)
    assert len(result["campaigns"]) > 0

    # Verify the first call was made with correct parameters
    assert get_campaigns_mock.call_count >= 1
    first_call_kwargs = get_campaigns_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 10
    assert first_call_kwargs["page_number"] == 1

    # Reset the mock for the next test
    get_campaigns_mock.reset_mock()

    # Test case 2: Limited page size (max_incidents_to_fetch = 2)
    # With many campaigns available and max_incidents_to_fetch=2, we expect page_size=2
    # This should result in multiple page calls since there are more campaigns than fit on one page
    result = client.get_paginated_abusecampaigns_list(filter_="test filter", max_incidents_to_fetch=2)

    # Verify we got campaigns
    assert len(result["campaigns"]) > 0

    # Verify each page was requested with the correct parameters
    assert get_campaigns_mock.call_count >= 1

    # Check first call parameters
    first_call_kwargs = get_campaigns_mock.call_args_list[0][1]
    assert first_call_kwargs["filter_"] == "test filter"
    assert first_call_kwargs["page_size"] == 2
    assert first_call_kwargs["page_number"] == 1

    # If there was a second call, check its parameters
    if get_campaigns_mock.call_count > 1:
        second_call_kwargs = get_campaigns_mock.call_args_list[1][1]
        assert second_call_kwargs["page_size"] == 2
        assert second_call_kwargs["page_number"] == 2

    # Reset the mock for the next test
    get_campaigns_mock.reset_mock()

    # Test case 3: One campaign per page (max_incidents_to_fetch = 1)
    # With many campaigns available and max_incidents_to_fetch=1, we expect page_size=1
    # This should result in multiple page calls, one per campaign
    result = client.get_paginated_abusecampaigns_list(filter_="test filter", max_incidents_to_fetch=1)

    # Verify we got campaigns
    assert len(result["campaigns"]) > 0

    # Verify multiple pages were requested
    assert get_campaigns_mock.call_count >= 1

    # Check that all calls have the correct page_size
    for i in range(get_campaigns_mock.call_count):
        call_kwargs = get_campaigns_mock.call_args_list[i][1]
        assert call_kwargs["page_size"] == 1
        assert call_kwargs["page_number"] == i + 1

    # Reset the mock for the next test
    get_campaigns_mock.reset_mock()

    # Test case 4: No campaigns to fetch (max_incidents_to_fetch = 0)
    result = client.get_paginated_abusecampaigns_list(filter_="test filter", max_incidents_to_fetch=0)

    # Verify that no campaigns were fetched
    assert len(result["campaigns"]) == 0

    # Verify that the underlying method was not called
    assert get_campaigns_mock.call_count == 0


def test_search_messages_command(mocker):
    """
    Test the search_messages_command to verify:
    1. It correctly formats the request parameters
    2. It returns the expected output structure
    """
    from AbnormalSecurity import search_messages_command

    # Create mock response
    mock_response = {
        "results": [
            {
                "customer_id": 12345,
                "tenant_id": 1,
                "received_time": "2024-01-15T10:30:00Z",
                "subject": "Test Message",
                "sender": "sender@example.com",
                "mailbox_name": "user@company.com",
                "abnormal_message_id": "abnormal-uuid-123",
                "decision_category": "malicious",
                "judgement": "attack",
            }
        ],
        "total": 1,
        "pageNumber": 1,
        "nextPageNumber": None,
    }

    client = mock_client(mocker, mock_response)

    args = {
        "source": "abnormal",
        "tenant_ids": "1,2,3",
        "start_time": "2024-01-01T00:00:00Z",
        "end_time": "2024-01-31T23:59:59Z",
        "subject": "Test",
        "sender_email": "sender@example.com",
        "page_number": 1,
        "page_size": 100,
    }

    results = search_messages_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.MessageSearch"
    assert results.outputs_key_field == "abnormal_message_id"
    assert results.outputs.get("total") == 1
    assert len(results.outputs.get("results", [])) == 1
    assert results.outputs["results"][0]["abnormal_message_id"] == "abnormal-uuid-123"


def test_remediate_messages_command(mocker):
    """
    Test the remediate_messages_command to verify:
    1. It correctly handles remediation requests
    2. It returns the expected output structure
    """
    from AbnormalSecurity import remediate_messages_command

    # Create mock response
    mock_response = {"activity_log_id": 12345, "metadata": {"trace_id": "abc-123-def", "response_time": "150ms"}}

    client = mock_client(mocker, mock_response)

    args = {
        "action": "delete",
        "tenant_ids": "1,2,3",
        "source": "abnormal",
        "remediation_reason": "false_negative",
        "messages": json.dumps(
            [
                {
                    "tenant_id": 1,
                    "raw_message_id": "msg-123",
                    "abnormal_message_id": "abnormal-uuid-123",
                    "mailbox_name": "user@company.com",
                    "subject": "Test Message",
                    "sender": "sender@example.com",
                    "received_time": "2024-01-15T10:30:00Z",
                }
            ]
        ),
    }

    results = remediate_messages_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.MessageRemediation"
    assert results.outputs_key_field == "activity_log_id"
    assert results.outputs.get("activity_log_id") == 12345


def test_remediate_messages_command_remediate_all(mocker):
    """
    Test the remediate_messages_command with remediate_all option.
    """
    from AbnormalSecurity import remediate_messages_command

    # Create mock response
    mock_response = {"activity_log_id": 12346, "metadata": {"trace_id": "xyz-456-def", "response_time": "200ms"}}

    client = mock_client(mocker, mock_response)

    args = {
        "action": "delete",
        "tenant_ids": "1",
        "source": "abnormal",
        "remediation_reason": "false_negative",
        "remediate_all": "true",
        "start_time": "2024-01-01T00:00:00Z",
        "end_time": "2024-01-31T23:59:59Z",
        "subject": "Phishing",
        "sender_email": "attacker@example.com",
    }

    results = remediate_messages_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.MessageRemediation"
    assert results.outputs.get("activity_log_id") == 12346


def test_get_activities_list_command(mocker):
    """
    Test the get_activities_list_command to verify:
    1. It correctly formats the request parameters
    2. It returns the expected output structure
    """
    from AbnormalSecurity import get_activities_list_command

    # Create mock response
    mock_response = {
        "activities": [
            {
                "activity_id": 12345,
                "action": "remediate",
                "status": "success",
                "performed_by": "user@company.com",
                "timestamp": "2024-01-15T10:30:00Z",
                "result_count": 25,
            }
        ],
        "total": 1,
        "page": 1,
        "size": 100,
    }

    client = mock_client(mocker, mock_response)

    args = {
        "tenant_ids": "1,2,3",
        "action": "remediate",
        "status": "success",
        "start_date": "2024-01-01T00:00:00Z",
        "end_date": "2024-01-31T23:59:59Z",
        "page": 1,
        "size": 100,
    }

    results = get_activities_list_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.Activities"
    assert results.outputs_key_field == "activity_id"
    assert results.outputs.get("total") == 1
    assert len(results.outputs.get("activities", [])) == 1
    assert results.outputs["activities"][0]["activity_id"] == 12345


def test_get_activity_status_command(mocker):
    """
    Test the get_activity_status_command to verify:
    1. It correctly formats the request parameters
    2. It returns the expected output structure with remediation details
    """
    from AbnormalSecurity import get_activity_status_command

    # Create mock response
    mock_response = {
        "activity_id": 12345,
        "action": "remediate",
        "status": "success",
        "performed_by": "user@company.com",
        "timestamp": "2024-01-15T10:30:00Z",
        "result_count": 2,
        "remediation_details": [
            {
                "tenant_id": 1,
                "raw_message_id": "msg-123",
                "subject": "Test Message 1",
                "sender": "sender1@example.com",
                "mailbox_name": "user@company.com",
                "status": "success",
                "date_remediated": "2024-01-15T10:35:00Z",
            },
            {
                "tenant_id": 1,
                "raw_message_id": "msg-124",
                "subject": "Test Message 2",
                "sender": "sender2@example.com",
                "mailbox_name": "user@company.com",
                "status": "success",
                "date_remediated": "2024-01-15T10:35:00Z",
            },
        ],
        "total": 2,
        "page": 1,
        "size": 100,
    }

    client = mock_client(mocker, mock_response)

    args = {"activity_log_id": "12345", "page": 1, "size": 100}

    results = get_activity_status_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.ActivityStatus"
    assert results.outputs_key_field == "activity_id"
    assert results.outputs.get("activity_id") == 12345
    assert results.outputs.get("status") == "success"
    assert len(results.outputs.get("remediation_details", [])) == 2
    assert results.outputs.get("total") == 2


def test_get_activity_status_command_in_progress(mocker):
    """
    Test the get_activity_status_command when activity is in progress with null values
    """
    from AbnormalSecurity import get_activity_status_command

    # Create mock response with null values (activity in progress)
    mock_response = {
        "activity_id": 179049,
        "action": "remediation",
        "status": None,
        "performed_by": None,
        "timestamp": None,
        "result_count": None,
        "remediation_details": None,
        "total": None,
        "pageNumber": None,
        "pageSize": None,
        "metadata": {"trace_id": "2b8009b3784f4b5aa92fa203d59196f5", "response_time": "12.537802ms"},
    }

    client = mock_client(mocker, mock_response)

    args = {"activity_log_id": "179049"}

    results = get_activity_status_command(client, args)

    # Verify the output
    assert results.outputs_prefix == "AbnormalSecurity.ActivityStatus"
    assert results.outputs_key_field == "activity_id"
    assert results.outputs.get("activity_id") == 179049
    assert results.outputs.get("action") == "remediation"
    assert results.outputs.get("metadata", {}).get("trace_id") == "2b8009b3784f4b5aa92fa203d59196f5"
    # Verify readable output contains in-progress message
    assert "In Progress" in results.readable_output or "in progress" in results.readable_output


def test_download_message_attachment_command(mocker):
    """
    Test the download_message_attachment_command to verify:
    1. It correctly formats the request parameters
    2. It returns a file result
    """
    from AbnormalSecurity import download_message_attachment_command

    # Create mock response for file download
    mock_file_content = b"Mock attachment file content"
    mock_response = MockResponse(mock_file_content, 200)

    client = mock_client(mocker, mock_response)

    args = {
        "message_id": "abnormal-uuid-123",
        "attachment_name": "invoice.pdf",
        "tenant_id": 1,
        "raw_message_id": "msg-123",
        "native_user_id": "user-456",
        "recipient_mailbox": "user@company.com",
    }

    results = download_message_attachment_command(client, args)

    # Verify the file result
    assert results["File"] == "invoice.pdf"
    assert results["FileID"] is not None


def test_download_message_eml_command(mocker):
    """
    Test the download_message_eml_command to verify:
    1. It correctly formats the request parameters
    2. It returns a file result with EML format
    """
    from AbnormalSecurity import download_message_eml_command

    # Create mock response for EML file download
    mock_eml_content = b"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\n\r\nTest email body"
    mock_response = MockResponse(mock_eml_content, 200)

    client = mock_client(mocker, mock_response)

    args = {"cloud_message_id": "abx:CloudMessage:12345:67890"}

    results = download_message_eml_command(client, args)

    # Verify the file result
    assert results["File"] == "abx_CloudMessage_12345_67890.eml"
    assert results["FileID"] is not None


def test_download_message_eml_command_with_quarantine(mocker):
    """
    Test the download_message_eml_command with quarantine parameters.
    """
    from AbnormalSecurity import download_message_eml_command

    # Create mock response for EML file download
    mock_eml_content = b"From: sender@example.com\r\nTo: recipient@example.com\r\nSubject: Test\r\n\r\nTest email body"
    mock_response = MockResponse(mock_eml_content, 200)

    client = mock_client(mocker, mock_response)

    args = {
        "cloud_message_id": "abx:CloudMessage:12345:67890",
        "quarantine_identity": "quarantine-id-123",
        "recipient_mailbox": "user@company.com",
    }

    results = download_message_eml_command(client, args)

    # Verify the file result
    assert results["File"] == "abx_CloudMessage_12345_67890.eml"
    assert results["FileID"] is not None


"""
    _is_skippable_error Unit Tests
"""


@pytest.mark.parametrize(
    "status_code, expected",
    [
        (404, True),
        (400, True),
        (410, True),
        (405, True),
        (401, False),
        (403, False),
        (429, False),
        (500, False),
        (502, False),
    ],
)
def test_is_skippable_error(status_code, expected):
    """Test that _is_skippable_error correctly categorizes errors by response status code."""
    exc = DemistoException(f"Error in API call [{status_code}]", res=MockResponse(None, status_code))
    assert _is_skippable_error(exc) == expected


def test_is_skippable_error_no_response():
    """Test that errors without a response object are not skippable."""
    exc = DemistoException("Some unexpected error with no status code")
    assert _is_skippable_error(exc) is False


"""
    generate_threat_incidents Error Handling Tests
"""


def test_generate_threat_incidents_skips_4xx_error(mocker):
    """
    Test that skippable 4xx errors for one threat don't abort processing of other threats.

    When:
        - Fetching threat details for multiple threats
        - One threat returns a 404 error (deleted/archived)
    Then:
        - The errored threat should be skipped
        - Other threats should still be processed
    """
    valid_threat_response = {
        "threatId": "valid-threat-id",
        "messages": [
            {
                "threatId": "valid-threat-id",
                "receivedTime": "2023-09-17T15:00:00Z",
                "remediationTimestamp": "2023-09-17T15:30:00Z",
            }
        ],
    }

    def mock_get_details(threat_id, **kwargs):
        if threat_id == "deleted-threat-id":
            raise DemistoException("Error in API call [404] - Not Found", res=MockResponse(None, 404))
        return valid_threat_response

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_a_threat_request", side_effect=mock_get_details)

    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    threats = [
        {"threatId": "deleted-threat-id"},
        {"threatId": "valid-threat-id"},
    ]

    incidents = generate_threat_incidents(client, threats, 1, start_datetime, end_datetime)

    assert len(incidents) == 1
    assert incidents[0]["dbotMirrorId"] == "valid-threat-id"


@pytest.mark.parametrize("status_code,reason", [(401, "Unauthorized"), (403, "Forbidden"), (429, "Too Many Requests")])
def test_generate_threat_incidents_raises_non_skippable_errors(mocker, status_code, reason):
    """
    Test that non-skippable errors (401, 403, 429) are re-raised.
    """

    def mock_get_details(threat_id, **kwargs):
        raise DemistoException(f"Error in API call [{status_code}] - {reason}", res=MockResponse(None, status_code))

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_a_threat_request", side_effect=mock_get_details)

    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    threats = [{"threatId": "some-threat-id"}]

    with pytest.raises(DemistoException) as exc_info:
        generate_threat_incidents(client, threats, 1, start_datetime, end_datetime)

    assert str(status_code) in str(exc_info.value)


def test_generate_threat_incidents_raises_5xx_errors(mocker):
    """Test that 5xx errors are re-raised."""

    def mock_get_details(threat_id, **kwargs):
        raise DemistoException("Error in API call [500] - Internal Server Error", res=MockResponse(None, 500))

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_a_threat_request", side_effect=mock_get_details)

    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    with pytest.raises(DemistoException) as exc_info:
        generate_threat_incidents(client, [{"threatId": "id"}], 1, start_datetime, end_datetime)

    assert "500" in str(exc_info.value)


def test_generate_threat_incidents_handles_4xx_mid_pagination(mocker):
    """
    Test that skippable 4xx errors during pagination are handled gracefully.
    """

    def mock_get_details(threat_id, **kwargs):
        if threat_id == "paginating-threat-id":
            if kwargs.get("page_number", 1) == 1:
                return {
                    "threatId": "paginating-threat-id",
                    "messages": [
                        {
                            "threatId": "paginating-threat-id",
                            "receivedTime": "2023-09-17T15:00:00Z",
                            "remediationTimestamp": "2023-09-17T15:30:00Z",
                        }
                    ],
                    "nextPageNumber": 2,
                }
            else:
                raise DemistoException("Error in API call [404] - Not Found", res=MockResponse(None, 404))
        return {
            "threatId": "valid-threat-id",
            "messages": [
                {
                    "threatId": "valid-threat-id",
                    "receivedTime": "2023-09-17T16:00:00Z",
                    "remediationTimestamp": "2023-09-17T16:30:00Z",
                }
            ],
        }

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_a_threat_request", side_effect=mock_get_details)

    start_datetime = datetime(2023, 9, 17, 14, 0, 0, tzinfo=UTC)
    end_datetime = datetime(2023, 9, 17, 17, 0, 0, tzinfo=UTC)

    threats = [
        {"threatId": "paginating-threat-id"},
        {"threatId": "valid-threat-id"},
    ]

    incidents = generate_threat_incidents(client, threats, 5, start_datetime, end_datetime)

    assert len(incidents) == 1
    assert incidents[0]["dbotMirrorId"] == "valid-threat-id"


"""
    generate_abuse_campaign_incidents Error Handling Tests
"""


def test_generate_abuse_campaign_incidents_skips_4xx_error(mocker):
    """Test that skippable 4xx errors skip the campaign and continue."""
    valid_campaign_response = {
        "campaignId": "valid-campaign-id",
        "firstReported": "2023-09-17T15:00:00Z",
    }

    def mock_get_campaign(campaign_id, **kwargs):
        if campaign_id == "deleted-campaign-id":
            raise DemistoException("Error in API call [404] - Not Found", res=MockResponse(None, 404))
        return valid_campaign_response

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_an_abuse_mailbox_campaign_request", side_effect=mock_get_campaign)

    campaigns = [
        {"campaignId": "deleted-campaign-id"},
        {"campaignId": "valid-campaign-id"},
    ]

    incidents = generate_abuse_campaign_incidents(client, campaigns)

    assert len(incidents) == 1
    assert incidents[0]["dbotMirrorId"] == "valid-campaign-id"


def test_generate_abuse_campaign_incidents_raises_non_skippable_errors(mocker):
    """Test that non-skippable errors (401) are re-raised."""

    def mock_get_campaign(campaign_id, **kwargs):
        raise DemistoException("Error in API call [401] - Unauthorized", res=MockResponse(None, 401))

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_an_abuse_mailbox_campaign_request", side_effect=mock_get_campaign)

    with pytest.raises(DemistoException) as exc_info:
        generate_abuse_campaign_incidents(client, [{"campaignId": "id"}])

    assert "401" in str(exc_info.value)


"""
    generate_account_takeover_cases_incidents Error Handling Tests
"""


def test_generate_account_takeover_cases_incidents_skips_4xx_error(mocker):
    """Test that skippable 4xx errors skip the case and continue."""
    valid_case_response = {
        "caseId": "valid-case-id",
        "firstObserved": "2023-09-17T15:00:00Z",
        "genai_summary": "Test summary",
    }

    def mock_get_case(case_id, **kwargs):
        if case_id == "deleted-case-id":
            raise DemistoException("Error in API call [410] - Gone", res=MockResponse(None, 410))
        return valid_case_response

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_an_abnormal_case_request", side_effect=mock_get_case)

    cases = [
        {"caseId": "deleted-case-id", "description": "Deleted case"},
        {"caseId": "valid-case-id", "description": "Valid case"},
    ]

    incidents = generate_account_takeover_cases_incidents(client, cases)

    assert len(incidents) == 1
    assert incidents[0]["dbotMirrorId"] == "valid-case-id"


def test_generate_account_takeover_cases_incidents_raises_non_skippable_errors(mocker):
    """Test that non-skippable errors (429) are re-raised."""

    def mock_get_case(case_id, **kwargs):
        raise DemistoException("Error in API call [429] - Too Many Requests", res=MockResponse(None, 429))

    client = mock_client(mocker, response=None)
    mocker.patch.object(client, "get_details_of_an_abnormal_case_request", side_effect=mock_get_case)

    with pytest.raises(DemistoException) as exc_info:
        generate_account_takeover_cases_incidents(client, [{"caseId": "id", "description": "test"}])

    assert "429" in str(exc_info.value)