Metadata-Version: 2.4
Name: ciaops
Version: 3.4.0
Summary: Python library - modules for processing data from the TI, ASM, DRP and IMC systems collected in one library. It wraps the products' APIs and lets you filter and page through their data.
Author-email: Group-IB <integration@group-ib.com>
License-Expression: MIT
Keywords: group-ib,threat intelligence,digital risk protection,attack surface management,incident management,cybersecurity,ti,drp,asm,imc,api client
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Security
Classifier: Typing :: Typed
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Natural Language :: English
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Requires-Dist: urllib3>=2.0.2
Provides-Extra: misp
Requires-Dist: pyaml>=25.7.0; extra == "misp"
Dynamic: license-file

# ciaops

[![Python](https://img.shields.io/badge/python-v3.9+-blue?logo=python)](https://python.org/downloads/release/python-390/)

**ciaops** - Python library to communicate with **Group-IB Products** (TI, DRP, ASM, IMC) via **API**. DRP is covered on both of its APIs: the client API v2 (`DRPV2Poller`) and the legacy client API (`DRPPoller`).

## **License**

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## **Content**

- [ciaops](#ciaops)
  - [**License**](#license)
  - [**Content**](#content)
  - [**Installation**](#installation)
  - [**Usage**](#usage)
    - [Initialization](#initialization)
    - [Threads and rate limits](#threads-and-rate-limits)
    - [Transport options](#transport-options)
    - [Collection constants](#collection-constants)
    - [Collections mapping](#collections-mapping)
    - [Portions generator](#portions-generator)
    - [Walk objects](#walk-objects)
    - [TIPoller extra methods](#tipoller-extra-methods)
      - [Available collections](#available-collections)
      - [Find feed by ID](#find-feed-by-id)
      - [Download file](#download-file)
      - [Download PDF reports](#download-pdf-reports)
      - [IP scoring](#ip-scoring)
      - [Domain scoring](#domain-scoring)
      - [Scoring in batches](#scoring-in-batches)
      - [One page, a search, a record by id](#one-page-a-search-a-record-by-id)
      - [The full text of a public leak](#the-full-text-of-a-public-leak)
      - [MITRE ATT\&CK](#mitre-attck)
      - [Global search](#global-search)
    - [DRPPoller methods](#drppoller-methods)
    - [DRPV2Poller methods](#drpv2poller-methods)
      - [Syncing violations](#syncing-violations)
      - [Filtering violations](#filtering-violations)
      - [Reading a violation](#reading-a-violation)
      - [Counting violations](#counting-violations)
      - [Downloading captures](#downloading-captures)
      - [Companies, brands and tags](#companies-brands-and-tags)
      - [Writing](#writing)
      - [Errors](#errors)
      - [Moving from DRPPoller](#moving-from-drppoller)
    - [ASMPoller methods](#asmpoller-methods)
    - [IMCPoller methods](#imcpoller-methods)
      - [Consuming incidents](#consuming-incidents)
      - [Filtering incidents](#filtering-incidents)
      - [Reading an incident](#reading-an-incident)
      - [Drilling into the evidence](#drilling-into-the-evidence)
      - [Resolving matches to TI records](#resolving-matches-to-ti-records)
    - [Close session](#close-session)
  - [Parsing](#parsing)
    - [Parse portion method](#parse-portion-method)
    - [Get IoCs method](#get-iocs-method)
  - [Filtering and masking records](#filtering-and-masking-records)
  - [Utilities](#utilities)
    - [ParserHelper](#parserhelper)
      - [find\_by\_template](#find_by_template)
      - [find\_element\_by\_key](#find_element_by_key)
      - [unpack\_iocs](#unpack_iocs)
    - [Validator](#validator)
  - [Portal Links](#portal-links)
    - [Simple collections (single ID in URL)](#simple-collections-single-id-in-url)
    - [Multi-part URL templates](#multi-part-url-templates)
    - [Custom prefix override](#custom-prefix-override)
    - [Embedding portal links in parsed output](#embedding-portal-links-in-parsed-output)
    - [Inspecting the TI URL map](#inspecting-the-ti-url-map)
  - [Adapter utilities](#adapter-utilities)
    - [ConfigParser](#configparser)
    - [FileHandler](#filehandler)
  - [Examples](#examples)
    - [Full program](#full-program)
  - [API logic](#api-logic)
    - [Sequence update logic](#sequence-update-logic)
      - [API response](#api-response)
      - [Iteration steps](#iteration-steps)
      - [Stop the iteration](#stop-the-iteration)
    - [Search logic](#search-logic)
      - [Global search](#global-search-1)
      - [Iteration steps](#iteration-steps-1)
      - [Stop the iteration](#stop-the-iteration-1)
  - [Records limits](#records-limits)
  - [Recommended TTL](#recommended-ttl)
  - [Troubleshooting](#troubleshooting)
    - [401 response code](#401-response-code)
    - [403 response code](#403-response-code)
    - [504 response code or timeout](#504-response-code-or-timeout)
  - [FAQ](#faq)

<br>

## **Installation**

Lib deps: **requests**, **urllib3**.

ciaops lib is available on PyPI:

```
pip install ciaops
```

Or use a Portal WHL archive. Replace `X.X.X` with current lib version:

```
pip install ./ciaops-X.X.X-py3-none-any.whl
```

<br>

## **Usage**

### Initialization

Initialize a **poller** with your credentials. TLS certificate verification is enabled by default.

Call `set_verify()` only when you need to override the default: pass `False` to disable verification (e.g. local testing behind a corporate proxy), or pass a path to a custom CA bundle.

```python
from ciaops import TIPoller, DRPPoller, DRPV2Poller, ASMPoller, IMCPoller

# Threat Intelligence
ti = TIPoller(username='example@example.corp', api_key='API_KEY', api_url='TI_API_URL')

# Digital Risk Protection, client API v2 (https://drp.group-ib.com/api/v2/)
drp = DRPV2Poller(username='example@example.corp', api_key='API_KEY', api_url='DRP_V2_API_URL')

# Digital Risk Protection, legacy client API (https://drp.group-ib.com/client_api/)
drp_legacy = DRPPoller(username='example@example.corp', api_key='API_KEY', api_url='DRP_API_URL')

# Attack Surface Management
asm = ASMPoller(username='example@example.corp', api_key='API_KEY', api_url='ASM_API_URL')

# Incident Management Center
imc = IMCPoller(username='example@example.corp', api_key='API_KEY', api_url='TI_API_URL')

# Override only when needed:
ti.set_verify(False)                  # disable TLS check (local testing only)
ti.set_verify('/path/to/ca-bundle')   # custom CA bundle
```

Every poller takes `timeout=`: the seconds a request may take to connect
and, separately, to deliver each piece of its response, as one number or a
`(connect, read)` pair; unset, 120 seconds. `send_request(timeout=...)`
sets it for one request.

```python
ti = TIPoller(username='...', api_key='...', api_url='TI_API_URL', timeout=(10, 600))
```

**Retries.** A request the library may repeat (a `GET` everywhere, and a
`POST` on TI and ASM, whose POSTs read) is retried on `429`, `500`, `502`,
`503` and `504` (six times, with backoff, honoring `Retry-After` up to 300
seconds and waiting at least a second after a `429` without one), on a
failed read, and when the response body cannot be decoded or ends early. A
repeat waits on the poller's rate limiter. A refused certificate, TLS
version or proxy tunnel is not repeated: it would fail the same way.
A request that changes state (the DRP writes and the ASM routes in
`ASMPoller.WRITE_ROUTES`) is sent once: a failure after it left raises, and
the record is yours to read back before sending it again. It does not
follow a redirect: a `3xx` raises `ConnectionException`, and
`send_request(allow_redirects=True)` follows it. A failed TCP connect is
retried for every request, since nothing was sent. When the retries on a
`429` or a server error run out, the `ConnectionException` carries that
status, its message starts with `Retries exhausted for`, and its cause is
a `requests.exceptions.RetryError`. When the time budget (`total_timeout`)
ends the repeats, the exception keeps the status as well, with
`kind="total_timeout"`.

Proxy setup (all pollers share the same interface):

```python
ti.set_proxies(
    proxy_protocol='https',
    proxy_ip='10.0.0.1',
    proxy_port='3128',
    proxy_username='user',       # optional
    proxy_password='secret',     # optional
)
```

Pass the credentials as they are: they are percent-encoded into the proxy
URL, and a value that is already percent-encoded is written unchanged.

Use pollers as context managers so the session is closed on exit (a session
you pass in with `session=` stays open):

```python
with TIPoller(username='...', api_key='...', api_url='...') as ti:
    generator = ti.create_update_generator('apt/threat', sequpdate=16172928022293)
    for portion in generator:
        print(portion.parse_portion())
```

Tag your integration in the User-Agent header with `set_product()`:

```python
ti.set_product(
    product_type='SIEM',
    product_name='MySIEM',
    product_version='2.1',
    integration_name='ciaops-siem',
    integration_version='1.0',
)
```

### Threads and rate limits

**Use one poller per thread.** A poller owns an HTTP session, the
`set_keys` mappings and (for ASM, IMC and the DRP client API v2) the rate
limiter it hands to every request or walk it drives; a feed generator owns
cursor state. None of it is synchronized except the rate limiter.

More importantly, the rate limits are **per account, not per connection**
(ASM: 1 request/second; TI: 1 request/second per route). IMC and the DRP
client API v2 publish no limit; IMC requests and DRP v2 walks are paced to
1 request/second. Running the same account from several threads therefore
buys no throughput: each thread paces itself independently, so together
they exceed the limit and collect `429`s, which the transport then repeats
after a pause. Where you need more data per second, widen the page size
or the time window rather than the thread count.

To hold several pollers of one account to one pace, give them one limiter:
`RateLimiter` is thread-safe, `RouteRateLimiter` paces each route on its
own, and `FileLockRateLimiter` shares one pace between processes on a host.

```python
from ciaops import FileLockRateLimiter, RouteRateLimiter, TIPoller

shared = RouteRateLimiter(1.0)            # one start per second per route
a = TIPoller(username='...', api_key='...', api_url='...', rate_limiter=shared)
b = TIPoller(username='...', api_key='...', api_url='...', rate_limiter=shared)

across_processes = FileLockRateLimiter(1.0, key='ti-collector')   # one pace per key
```

On `TIPoller`, `DRPPoller` and `ASMPoller` every request waits on a
`rate_limiter`; on `IMCPoller` and `DRPV2Poller` it takes the place of
their own limiter, which paces their walks, the match resolver and the
write waiter. `TIPoller(rate_limit_delay=...)` builds a `RouteRateLimiter`
for the poller; a walk of a poller that paces its requests does not pace
itself on top of it.

### Transport options

Every poller takes the same transport options:

```python
from ciaops import RetryPolicy, TIPoller

poller = TIPoller(
    username='...', api_key='...', api_url='...',
    timeout=(10, 120),                    # connect, read; seconds
    retry=RetryPolicy(retries=3, backoff_factor=2, max_retry_after=60),
    total_timeout=300,                    # seconds per request, repeats included
    error_body_in_message=True,           # quote what a 400 says, unredacted
    compression=False,                    # ask for uncompressed bodies
)
poller.set_retry_policy(RetryPolicy.none(), routes=['scoring/ip'])
poller.set_product('SIEM', 'Example', '1.0', 'example-ti', '2.0',
                   include_username=False)
```

`RetryPolicy` sets how many times a request is sent again in all and per
cause (`connect`, `read`, `status`), the backoff, the statuses repeated
(`status_forcelist`: only those are repeated, and a `Retry-After` sets the
pause, never whether to repeat), the longest `Retry-After` honored, the
least pause after a `429` without one (`pause_on_429`), and body
re-reads. `RetryPolicy.none()` sends every request once;
`RetryPolicy.connect_only()` repeats only a failed connect. A request
that changes state is sent once whatever the
policy says, except after a failed TCP connect. `total_timeout` bounds one
request with its repeats and pauses, every attempt included: an attempt
gets at most the time left, and a body that keeps arriving is stopped; on
a transport of your own (`mount_transport=False`) only the waits for the
server are held to it. One that runs out raises
`ConnectionException` with `kind="total_timeout"`. `send_request` takes
`timeout=` and `total_timeout=` for one request. `failure_log_level` sets
the level a failed request is logged at before it is raised
(`logging.ERROR` unless set).

**A response body that fails after the headers** (a gzip stream cut
short, a body shorter than its `Content-Length`, a connection dropped
while reading) is read again up to `RetryPolicy.body_retries` times; after
a body that cannot be decompressed, the repeat asks for it uncompressed
(`Accept-Encoding: identity`; `identity_on_decode_error=False` keeps
compression). `compression=False` on the poller asks for uncompressed
bodies from the first request. A walk built with `shrink_on_failure=True`
reads a page that keeps failing again with half the page size, down to
`min_page_size`, so a large page that will not arrive whole does not stop
the walk; once past the records of that page the size returns. A page
that fails at `min_page_size` ends the walk with `walk.stop_reason`
naming the cursor.

`session=` sends through a `requests.Session` the caller owns, such as a
platform's: the poller's credentials and headers go with its own requests
only, and its transport is mounted under the API URL;
`mount_transport=False` mounts nothing. A write is still sent once when
the session's adapter is an `HTTPAdapter`: when its urllib3 `Retry` could
repeat the write (a `Retry` of your own repeats any method after an error
other than a failed connect or read, unless its `total` or `other` is
`0` or `False`), the write goes out through a private copy of the session
that keeps its settings and the adapter's pools and TLS context, and the
session is left as it is.
`set_proxies` takes host, port and credentials, or a
`{"http": ..., "https": ...}` mapping; it warns on a partial configuration
and with `strict=True` raises instead.

**What failed.** A `ConnectionException` carries `status_code`,
`error_code`, `kind` (`status`, `timeout`, `connect`, `dropped`, `tls`,
`proxy`, `body`, `not_json`, `shape`, `total_timeout`, `other`), `transient`
(a later attempt can succeed), `server_message`, `body` (the start of the
response), `method`, `path`, `reached_server`, `may_have_applied` (for a
write) and `attempts`, so a caller decides without reading the message.
The message quotes only an explanation the body states as one (a JSON
`message`, `error`, `detail`, `messages` or `errors`, an HTML title), with
the values the request sent, and each term of a `q` search, replaced by
`***` (a number sent under `limit`, `count`, `offset` or `page` and a word
sent under `type`, `status`, `sort` or `order` stay); on `DRPV2Poller` the
error envelope's `message` is quoted as it came.
`error_body_in_message=True` quotes a `400`'s explanation, or the start of
its body, as they came, and the start of the body on another unexpected
status. Messages, and logs from `INFO` up, name a path with `<id>` in place
of a record id, an address or a domain; `path` keeps it whole.
`ciaops.transport.QueryFreeLogFilter` cuts query strings and URL
credentials out of the records of any logger it is added to.
An answer that is not the shape its route returns raises
`ResponseShapeError`, which is both a `ParserException` and a
`ConnectionException`.

```python
from ciaops import ConnectionException

try:
    page = poller.fetch_page('apt/threat', sequpdate=cursor)
except ConnectionException as error:
    if error.transient:
        ...                               # try again later from the same cursor
    elif error.status_code in (401, 403):
        ...                               # credentials or access list
```

### Collection constants

Use typed constants instead of bare strings to avoid typos and get IDE autocomplete:

```python
from ciaops.collections_meta import (
    TICollections, DRPCollections, DRPV2Collections, ASMCollections,
    IMCCollections, DRPV2Status, DRPV2ViolationType,
)

# TI examples
TICollections.APT_THREAT          # "apt/threat"
TICollections.COMPROMISED_ACCOUNT_GROUP  # "compromised/account_group"
TICollections.MALWARE_CNC         # "malware/cnc"

# DRP, legacy client API
DRPCollections.VIOLATION          # "violation"
DRPCollections.COMPROMISED_DARKWEB  # "compromised/darkweb"

# DRP client API v2: the logical collection you set keys for, and the
# vocabularies its filters and records share
DRPV2Collections.VIOLATIONS       # "drp/v2/violations"
DRPV2Status.LIVE                  # {"detected", "inResponse"}
DRPV2ViolationType.UPLOADABLE     # every type but "noViolation"

# ASM
ASMCollections.ASSETS_UPDATED     # "assets/updated"
ASMCollections.ISSUES_UPDATED     # "issues/updated"

# IMC: the two logical collections you set keys for
IMCCollections.INCIDENTS          # "imc/incidents"
IMCCollections.MATCHES            # "imc/matches"

# IMC: the match collections, in every spelling the API uses
IMCCollections.DARK_WEB                          # "darkWeb"      (byCollection key)
IMCCollections.get_match_segment('darkWeb')      # "dark-web"     (endpoint segment)
IMCCollections.get_collection_enum('darkWeb')    # "COLLECTION_DARK_WEB"  (filter enum)
IMCCollections.get_resolution_route('darkWeb')   # "darkweb/forums"       (TI by-id route)
IMCCollections.normalize_collection('dark-web')  # "darkWeb"      (accepts those three)
```

Look up the recommended TTL for any TI collection:

```python
TICollections.get_ttl(TICollections.MALWARE_CNC)          # 90  (days)
TICollections.get_ttl(TICollections.COMPROMISED_MESSENGER) # None  (no expiry)
```

Use constants anywhere a collection name string is expected:

```python
poller.set_keys(TICollections.APT_THREAT, keys)
generator = poller.create_update_generator(TICollections.MALWARE_CNC, sequpdate=...)
```

### Collections mapping

Method `set_keys()` sets **keys** to search in the selected **collection**. It should be a Python dict `mapping_keys = {key: value}` where \
**key** - result name \
**value** - dot-notation string with searchable keys

```python
mapping_keys = {"result_name": "searchable_key_1.searchable_key_2"}
```

Parser finds keys recursively in the API response, using dot-notation in **value**.
If you want to add your own data to the results start the **value** with star `*`.

```python
mapping_keys = {
	"network": "indicators.params.ip",
	"result_name": "*My_Value"
}
```

For `set_keys()` or `set_iocs_keys()` methods you can make a full template to get nested data in the way you want.

```python
mapping_keys = {
	'network': {
		'ips': 'indicators.params.ip'
	},
	'url': 'indicators.params.url',
	'type': '*network'
}
poller.set_keys(collection_name="apt/threat", keys=mapping_keys)
poller.set_iocs_keys(collection_name="apt/threat", keys={"ips": "indicators.params.ip"})
```

### Portions generator

Use `create_update_generator()` to create a generator that returns portions of feeds. \
**Update generator** - reads a feed in increasing `seqUpdate` order, from the cursor onward.

**Where a walk starts.** With neither `sequpdate` nor `date_from` the walk
starts at the beginning of the collection and reads its whole backlog, and
logs a warning saying so (a walk with a `query` is a search and is not
warned about). On a collection that does not select by `date_from`
(`TICollections.accepted_params`), a walk from a date reads the whole
backlog too, and says so; on `compromised/breacheddb`
(`TICollections.NO_DATE_FILTER`) a `date_from` raises `InputException`.
Seed it: `date_from` for a window, the start `start_cursor()` picks for a
day, or a stored cursor. On `ioc/primary`
seed `sequpdate=1` for a full walk: that feed answers a request without a
cursor with a page whose cursor does not move.

```python
start = poller.start_cursor('ioc/primary', '2026-10-01')
# TIStartPosition(collection='ioc/primary', sequpdate=17908020000000, source='computed', ...)
generator = poller.create_update_generator(
    'ioc/primary', **start.generator_kwargs(TIRequestParams(limit=500))
)
```

`start_cursor` asks `sequence_list` for the day, and again (`retries`,
two by default) while it answers `0`, `1` or nothing, which is the start
of the collection rather than the day. Then, on a collection whose cursor
is a time in a known unit (`TICollections.DATE_CURSOR_SCALE`), it computes
the cursor of the day's start: midnight UTC less `margin`. The server's
own day start is midnight UTC on some collections (`ioc/primary`) and
midnight UTC+3 on others, so the default of three hours starts at or
before it and reads up to three hours of the previous day again;
`margin=timedelta(0)` starts at midnight UTC. With `verify=True` (the
default) the first record that cursor selects is read back: its
`seqUpdate` must read as a time near the day, and a cursor that selects
nothing is checked on the collection's first record instead (a unit too
large selects nothing and reads that record decades early). A cursor the
records do not confirm is not used. Otherwise `on_degenerate`
decides: `"auto"` starts without a cursor and selects the day with
`date_from` (on a collection that does not select by `date_from` it
raises `DegenerateCursorError`, since the date would select nothing),
`"date_filter"` selects the day by `date_from` too but on such a
collection warns and reads it from the beginning instead of raising,
`"start"` starts at `1`, `"server"` takes the answer, `"raise"` raises.
`get_seq_update_dict()` replaces an answer of `0` or `1` with the computed
cursor where the unit is known and the read-back confirms it (one or two
requests per such collection; `verify=False` skips them,
`replace_degenerate=False` keeps the server's values) and logs a warning
naming each such collection.

**When a walk stops.** On the empty page that ends the feed, and after a
page whose cursor could not move the next request past it: a page with
records but no `seqUpdate`, with the `seqUpdate` the request or an earlier
request of the walk sent, or with `seqUpdate: 0` when the request sent
none. Such a page is yielded once, a warning names it, and the stored
cursor stays where it was.

**Note:** `compromised/breached` is a by-id route without an `/updated` feed, so
[sequence update logic](#sequence-update-logic) does not apply to it; its feed
counterpart is `compromised/breacheddb`. `TIPoller.find_records()` reads
the by-id route for `compromised/breacheddb`, and so does
`IMCPoller.resolve_match()`.

```python
from ciaops import TIRequestParams

generator = poller.create_update_generator(
    collection_name='compromised/account_group',
    request_params=TIRequestParams(
        date_from='2021-01-30',
        date_to='2021-02-03',
        query='192.0.2.8',
        limit=200,
    ),
    sequpdate=20000000,
)
```

The `compromised/spd` (Suspicious Payment Details) collection additionally
accepts a `type` filter that narrows results to a single payment-detail type.
Allowed values, matched without regard to case: `Cryptocurrency Wallet`,
`Bank Account Number`, `Mobile number`, `IBAN`, `Bank card`, `Email`,
`Unknown`, `QR payment string`.

```python
generator = poller.create_update_generator(
    collection_name='compromised/spd',
    request_params=TIRequestParams(type='IBAN'),
    sequpdate=20000000,
)
```

**Rate limiting:** the TI update generator throttles each of its requests,
a run read again or a page read smaller included, to **at most one
request a second** by default (elapsed-aware: it sleeps only the time
remaining since the previous request), the API's limit per route.
Override it with `rate_limit_delay` (seconds), or pass `0` to disable:

```python
generator = poller.create_update_generator(
    collection_name='compromised/account_group',
    request_params=TIRequestParams(date_from='2021-01-30'),
    rate_limit_delay=0,  # disable throttling
)
```

Each portion (iterable object) is a `Parser` object.
You can get **raw data** (in JSON format) or **parsed portion** (Python dictionary format),
using its methods and attributes.

```python
for portion in generator:
    parsed_json = portion.parse_portion(as_json=False)
    iocs = portion.get_iocs(as_json=False)
    sequpdate = portion.sequpdate
    count = portion.count
    raw_json = portion.raw_json
    raw_dict = portion.raw_dict
    new_parsed_json = portion.bulk_parse_portion(keys_list=[{"ips": "indicators.params.ip"}, {"url": 'indicators.params.url'}], as_json=False)
```

Attribute `sequpdate` of the generator iterable object is the cursor (`seqUpdate`) the walk continues after,
which you can save locally.

```python
sequpdate = portion.sequpdate
```

Attribute `count` of the generator iterable object shows you the number of records left in the queue.

```python
count = portion.count
```

Methods `parse_portion()` and `get_iocs()` of generator iterable objects use your
mapping keys (IoCs keys) to return parsed data.
You can override mapping keys using `keys` parameter in these functions.

```python
parsed_json = portion.parse_portion(as_json=False)
iocs = portion.get_iocs(as_json=False, keys=mapping_override_keys)
```

Also, you can use `bulk_parse_portion()` method to get multiple parsed dicts from every record.

```python
new_parsed_json = portion.bulk_parse_portion(keys_list=[{"ips": "indicators.params.ip"}, {"url": 'indicators.params.url'}], as_json=False)
```

**How a TI walk pages** follows its collection by default. `cursor_rule`
says where the next cursor comes from: `"auto"` (the default), the
collection's rule (`TICollections.cursor_rule`: the highest record
`seqUpdate` on `darkweb/forums`, the page's `seqUpdate` elsewhere);
`"response"`, the page's; `"max_item"`, the highest record's. A page's
`sequpdate` is the cursor the walk continues after, so a checkpoint taken
from it resumes there; on `darkweb/forums` that is the page's highest
record cursor, or just below it after a full page (`tie_safe`); either way
the next walk reads that record again, so de-duplicate on the record id.
`compromised/discord` without a cursor, `date_from` or query starts at its
first record (`seqUpdate=1`): without a cursor the server answers newest
first. On `ioc/primary` and `ioc/common` a `date_from` day goes out as its
first second and a `date_to` day as its last; `compromised/breacheddb`
takes no `date_from`.
`tie_safe` continues after a full page from just below its highest record
position and leaves out the records of that position already delivered, so
records that share one position across a page edge arrive; `"auto"`
(the default) turns it on for `TICollections.TIED_CURSOR_COLLECTIONS`. A
position is the record's `seqUpdate`, or its millisecond on the
collections in `TICollections.CURSOR_POSITION_SCALE` (`suspicious_ip/*`);
a page that is one position is read again larger, up to the collection's
limit (`TICollections.get_page_limit`; where it lists none, 1000 or the
page size when that is larger), and a run
wider than that is logged as records not delivered. A tie-safe walk sends a
page size (`limit`, the collection's recommended one, or 100) and gives
each page the cursor the walk resumes after as its `sequpdate`.
`cursor_rule="response", tie_safe=False` pages on the page cursor alone.

### Walk objects

`create_update_walk` (on `TIPoller`, `DRPPoller` and `ASMPoller`) takes the
generator's arguments and returns a `FeedWalk`. Iterate it for pages;
`walk.cursor` is the checkpoint, and it moves past a page only when the
loop asks for the next one, so a cursor saved after a failed sink reads
that page again. Delivery is at least once, except for the records of a
run of equal cursors beyond the largest page read, which are skipped with
a warning. A walk is single-use.

```python
from ciaops import JsonCheckpointStore, TIRecordFilter

store = JsonCheckpointStore('/var/lib/collector/checkpoints.json')
saved = store.load('apt/threat')
cursor = None if saved is None else saved.cursor
walk = poller.create_update_walk(
    'apt/threat',
    TIRequestParams(date_from='2026-10-01') if cursor is None else None,
    sequpdate=cursor,
    page_size='recommended',
    max_pages=50,                        # stop after 50 pages
    max_duration=600,                    # or before a page 10 minutes in
    record_filter=TIRecordFilter('apt/threat', min_severity='orange'),
    mask=True,                           # the recommended masking policy
    dedupe=True,                         # leave out records seen unchanged
)
try:
    for page in walk:
        sink(page.records)
finally:
    if walk.cursor is not None:          # nothing read yet: keep the bootstrap
        store.save('apt/threat', walk.cursor)
print(walk.stats, walk.stop_reason)
```

The options, each off unless set: `max_pages`, `max_records` (stops after
the page on which the count is reached), `max_duration` (seconds from the
start; checked before each page), `should_stop` (a callable asked
before each page), `record_filter` (a callable or an object with
`matches(record)`), `mask` (`True`, a `MaskPolicy`, or a callable on a
page), `dedupe` (`True` or a `SeenIds` to keep between runs; records are
keyed by `id`, by a digest of the record where it has no `id` or on
`suspicious_ip/open_proxy`, whose records share ids, or by `dedupe_key`
(`None` leaves a record out), and compared whole unless
`dedupe_fingerprint` says otherwise; a record counts as delivered once the
loop asks for the page after its own), `until` (a callable on each
record: the first it accepts and the rest are left out and the walk
stops, with the cursor before that page), `skip_failing_records` (leave
out a record a filter, `until`, `dedupe` or `mask` raises on; unset, such
a record stops the walk before its page; a failure that no single record
causes, an `InputException` from a callable, or a failure of every record
of a page of two or more is raised), and `shrink_on_failure` (after a
timeout, a dropped connection, a body that failed or is not JSON, a `500`
or a `504`, read the page again with half the size, down to
`min_page_size`, and back to full size once past that page; a tie-safe
walk reads a run at sizes below one that failed, and a run on which every
larger read fails stops the walk before it, with `stop_reason` saying so,
on every walk until the route serves it; `create_update_generator` takes
it too). `walk.stats` counts pages, records served, delivered, filtered,
duplicates, cut, skipped and shrinks; on ASM `walk.stats.complete` says
whether the server's `"N of M"` count was met. With a `ciaops.filters`
filter, `walk.stats.filter_fields` counts per criterion the records whose
field was read, absent or unreadable, and the walk warns once per
criterion whose field never read or held a value it cannot read: a
renamed field or a new date form shows up there instead of as records
silently left out. A page without records whose `count` says more remain
stops the walk with `walk.stop_reason`, the cursor where it was; on TI
with hunting rules off that `count` is an estimate, and the walk ends with
a warning instead.

### TIPoller extra methods

#### Available collections

Call `get_available_collections()` to discover which collections your API key can access before iterating.
`get_granted_collections()` returns the entries of `user/granted_collections` as the server serves them
(`collection`, `huntingRulesUsed` and the rest).

```python
collection_list = ti.get_available_collections()
seq_update_dict = ti.get_seq_update_dict(date='2020-12-12')
compromised_account_sequpdate = seq_update_dict.get('compromised/account_group')

# Check which collections have active hunting rules applied
hunting_collections = ti.get_hunting_rules_collections()
```

#### Find feed by ID

Returns a `Parser` object for a single feed by its ID.

```python
feed = ti.search_feed_by_id(collection_name='apt/threat', feed_id='abc123')
parsed = feed.parse_portion()
```

#### Download file

Download a binary file embedded inside a threat report.

```python
binary = ti.search_file_in_threats(
    collection_name='hi/threat',
    feed_id='feed_id',
    file_id='file_id_inside_feed',
)
```

#### Download PDF reports

```python
# Download a PDF for an HI or APT threat
pdf_bytes = ti.download_threat_pdf(threat_id='abc123')

# Download an HI analytic report PDF (use file.name field from hi/analytic record)
pdf_bytes = ti.download_analytic_report_pdf(file_name='/23ae4ab7.../file/450ffbd4...')

with open('report.pdf', 'wb') as f:
    f.write(pdf_bytes)
```

#### IP scoring

Score one or more IPs against the TI database via the `scoring/ip` endpoint.

```python
# Single IP
result = ti.get_ip_scoring('192.0.2.8')
# -> {"items": {"192.0.2.8": {"ip": "192.0.2.8", "riskScore": 0}}}   # riskScore is 0-100

# Multiple IPs
result = ti.get_ip_scoring(['192.0.2.8', '198.51.100.11'])
```

#### Domain scoring

Score one or more domains against the TI database via the `scoring/domain`
endpoint.

```python
# Single domain
result = ti.get_domain_scoring('example.com')
# -> {"items": {"example.com": {"domain": "example.com", "riskScore": 25}}}

# Multiple domains
result = ti.get_domain_scoring(['example.com', 'example.org'])
```

#### Scoring in batches

```python
scores = poller.score(['192.0.2.8', 'not-an-ip'], kind='ip')
scores['192.0.2.8']   # TIScore(..., risk_score=None, not_scored_reason='unscorable')
scores['not-an-ip']   # TIScore(..., risk_score=None, not_scored_reason='invalid')
```

`score` sends `batch_size` values per request (100 by default, at most
1,000) and returns one `TIScore` per distinct value, in input order. A
value the route would refuse is reported as `invalid` and not sent, since
one such value fails its whole request; an IPv6 address or an IPv4 address
that is not globally routable (private, loopback, link-local, shared,
reserved and documentation ranges), which the route answers `0` for
whatever it is, is reported as `unscorable` unless
`skip_unscorable=False`; a value the answer does not name is reported as
`missing`. Bands: `benign` (0), `low` (1-39), `suspicious` (40-59), `high`
(60-79), `malicious` (80-100).

#### One page, a search, a record by id

```python
page = poller.fetch_page('apt/threat', TIRequestParams(limit=10), sequpdate=cursor)
hits = poller.search('compromised/account_group', 'domain:example.com', limit=100)
records = poller.find_records('compromised/breacheddb', record_id)   # [] if unknown
```

`fetch_page` reads one page of `<collection>/updated` with the filters,
dates and cursor given; `search` reads the first page for a query.
`find_records` uses the by-id route, or `q=id:"<id>"` on a collection
without one (`TICollections.NOT_SERVED_BY_ID`; `compromised/breacheddb` is
read from `compromised/breached/<id>`). On a collection whose
record id is an IP address (`TICollections.IP_RECORD_IDS`), an id that is
no address is `[]` without a request. `search_feed_by_id`
raises `EmptyRecordError`, which is both a `NotFoundException` and a
`ParserException`, when the route answers an empty body.
`TIRequestParams` also takes `risk_score` (0-100; on `ioc/primary` the
server keeps a record whose highest score, its own or an element's,
reaches it, and leaves out a record without any score),
`with_description` and `extra_params` for a parameter it does not name;
`params.fingerprint(collection)` digests what a set of parameters
selects, for keeping a cursor with the view it belongs to.

#### The full text of a public leak

A record of the `osi/public_leak` feed carries the first 64 KiB of the
leak in `data`, `size` is the size of the whole text, and `dataTruncated`
says the text was cut; `size` and the length of `data` do not compare,
so read the flag. The whole record comes from the by-id route
(`search_feed_by_id`, `find_records`) or, for several, from `fetch-batch`:

```python
for page in poller.create_update_generator('osi/public_leak', sequpdate=cursor):
    for record in poller.iter_full_public_leaks(page.records):
        ...   # the text of each record is whole

for record in poller.iter_public_leaks(['<id>', '<id>'], batch_size=10):
    ...
```

A text can run to about 99 MiB and a batch is read whole, so `batch_size`
bounds the memory a batch takes. The server leaves out an id it does not
know, which is logged; `iter_full_public_leaks` then keeps the record as it
came. Both are paced like any TI walk, unless the poller paces its own
requests.

#### MITRE ATT&CK

Fetch the full MITRE ATT&CK technique vocabulary or a map of IDs to names.

```python
# Raw vocabulary (includes all AttackPattern details)
vocab = ti.get_mitre_techniques()

# ID-to-name dict
mitre_map = ti.get_mitre_attack_pattern_map()
# -> {"T1059": "Command and Scripting Interpreter", "T1078": "Valid Accounts", ...}

technique_name = mitre_map.get("T1059")
```

#### Global search

Search across all TI collections by query string.

```python
results = ti.global_search('192.0.2.8')
# -> [{"apiPath": "suspicious_ip/scanner", "count": 14, ...}, ...]
```

### DRPPoller methods

`DRPPoller` speaks the **legacy** DRP client API (`/client_api`). New
integrations should use the client API v2 and `DRPV2Poller` (next section);
the same credentials work for both.

```python
from ciaops import DRPPoller

drp = DRPPoller(username='...', api_key='...', api_url='https://drp.group-ib.com/client_api/')
```

**Update generator** to iterate violation feeds:

```python
generator = drp.create_update_generator(
    collection_name='violation/list',
    sequpdate=1700000000000000,   # or date_from='2024-01-15'; 1 walks the whole collection
    subtypes=[6],           # 1=counterfeit 2=piracy 3=partner_policy_compliance 4=trademark 5=malware 6=phishing 7=scam 8=no_violation
    section=1,              # one channel: 1=Web 2=Mobile 3=Marketplace 4=Social 5=Advertising 6=Messengers
    brands=['brand_id'],
    approve_states=['under_review'],
)
for portion in generator:
    data = portion.parse_portion()
    checkpoint = portion.sequpdate   # store after the page is handled
```

The walk starts after `sequpdate`; `date_from` is the same start given as a
date (the cursor `get_seq_update_dict()` computes for it, in microseconds).
Records before 2022-11-22 carry a `seqUpdate` in milliseconds, below every
microsecond value, so a `date_from` before that day starts the walk at the
first microsecond-cursor record and logs a warning; pass `sequpdate=1` to
read the older records too. With neither, the API answers only a recent
slice of the collection, and the walk says so in a warning.
`date_to` and `query` are refused: the route has no end bound and no text
search. Pages are requested in `seqUpdate` order, 500 records at a time
unless `limit` (a positive integer) says otherwise; records can share a
`seqUpdate`, so after a full page the walk continues from just below its
highest record cursor and leaves out the records of that value already
delivered; a page that is one run is read again with a larger page (up to
1000), and a run wider than that is logged as records not delivered. Each
page carries, as its `sequpdate`, the cursor the walk resumes after, so a
checkpoint taken from a page reads a split run whole. The walk ends on the empty
page, and after a page whose cursor could not move the next request past
it.

**Find feed by ID:**

```python
from ciaops import NotFoundException

try:
    feed = drp.search_feed_by_id(feed_id='violation_id')
except NotFoundException:
    ...                      # an unknown id: a 404, a 204, or a 200 with an empty body
raw = feed.raw_dict
```

**Change violation status** (only when status=`detected` and approveState=`under_review`):

```python
result = drp.change_status(feed_id='violation_id', status='approve')  # or 'reject'
result.applied, result.outcome      # True, 'OK'
```

`change_approve` sends one decision and says what it came to, read from
the per-id answer; a refusal the server answers with `400` is a result
too. An answer that carries neither says nothing: `result.applied` is
`None` and `result.may_have_applied` true, so read the violation back
before sending the decision again. `"official"` marks the resource as the
company's own, for the whole company, and cannot be undone, so it is sent
only with `allow_official=True`.

```python
from ciaops import DecisionRefusedError

result = drp.change_approve('violation_id', 'reject')
if not result:
    print(result.reason)            # e.g. "status=legal, approveState=not_required"

drp.change_approve('violation_id', 'official', allow_official=True,
                   raise_on_refusal=True)   # raises DecisionRefusedError when refused
```

**Upload violations** in batches the route takes (100 at most):

```python
result = drp.add_violations(items, batch_size=100, validate=True)
result["succeeded"], result["failed"]
```

`validate=True` refuses an item whose `violationSubtype` the subtype
vocabulary does not know, or whose `url` or `brandId` is blank, before
anything is sent. A record name, a short code, a filter id or a write name
in another case is sent as its write name either way (`piracy` as
`copyright`).

**Filter by status and crawler:** `statuses=['detected', 'in_response']`
(names or `statuses[]` ids, sent as ids) and `worker_codes=['domain']`.
`drp.cursor_for('2026-10-01')` is the cursor of a date or `datetime`.

**Brands and subscriptions:**

```python
brands = drp.get_brands()
# -> [{"name": "Brand A", "id": "id1"}, ...]

subscriptions = drp.get_subscriptions()
# -> ["scam", "phishing", ...]
```

**Typosquatting feed** (without a cursor or `date_from` the walk reads the
whole typosquatting feed, which can hold millions of records; pass
`date_from` to start at a day):

```python
generator = drp.create_update_generator(
    collection_name='violation/list',
    use_typo_squatting=True,
)
```

**seqUpdate by date:**

```python
seq_dict = drp.get_seq_update_dict(date='2024-01-15')
# -> {"violation": 1705276800000000, ...}
```

**A captured file by its hash**, such as a screenshot hash from a
violation's `images`:

```python
content = drp.download_file(sha256='<64 hex characters>')   # bytes
```

Store the bytes; never render a captured page.

### DRPV2Poller methods

**The DRP client API v2** (`/api/v2`) is the current Digital Risk Protection
API: one flat violation object, a cursor feed that delivers a violation
again when it changes, a `revision` per violation, counts in one call, bulk
writes, and one error envelope. It takes **the same credentials** as the
legacy client API (the portal email and the API key from the DRP profile)
against its own base URL. `DRPPoller` stays the client for the legacy
`/client_api`; the two APIs share no paths and no vocabulary, so each has its
own poller.

`DRPV2Poller` covers every operation of the contract (the feed, a single
violation, stats, both captures, companies and tags, upload, approve and
reject, comments, tag attach and detach), and its tests check it against a
copy of the vendor's OpenAPI document.

```python
from ciaops import DRPV2Poller

drp = DRPV2Poller(
    username='example@example.corp',
    api_key='API_KEY',
    api_url='https://drp.group-ib.com/api/v2/',
)
```

Walks are paced to **one request per second**, through one limiter per
poller; `rate_limit_delay=0` turns that off when an outer scheduler already
paces the calls. A single-request method sends at once; a repeat of its
request waits on the same limiter.

#### Syncing violations

The feed pages on an opaque cursor, `nextCursor`, present on **every**
response, the empty one that ends the feed included. Keep reading until a
page comes back empty; store that last cursor; next time pass it back **with
the same filter** and you receive only the violations that changed since. A
short page is not the end; only an empty one is.

```python
from ciaops import DRPV2ViolationFilter, DRPV2Status

criteria = DRPV2ViolationFilter(statuses=DRPV2Status.LIVE)   # detected, inResponse

walk = drp.create_violations_walk(criteria, cursor=load_checkpoint())
for page in walk:
    for violation in page.as_violations():
        upsert(violation.violation_id, violation)
    save_checkpoint(page.next_cursor)        # optional: checkpoint as you go
save_checkpoint(walk.cursor)                 # the caught-up checkpoint
```

`walk.cursor` moves past a page only when the loop asks for the next one.
While your code handles a page it still points at that page's start, so a
checkpoint saved from an `except` or `finally` block, or after a `break`,
delivers the page again next time instead of skipping what was not handled.

Or one page per poll, the shape a scheduled connector usually wants:

```python
page = drp.fetch_violations_page(criteria, cursor=load_checkpoint(), limit=500)
handle(page.as_violations())
save_checkpoint(page.next_cursor)            # also on an empty page
```

What to plan for:

- **The whole history by default.** When the API receives no `updatedFrom`
  it applies about the last month (now minus one calendar month) on every
  page, pages read from a stored cursor included, and the sync still ends on
  a normal empty page. `DRPV2Poller` therefore always sends a lower bound: the
  filter's `updated_from`, or `1970-01-01T00:00:00Z` when it is unset. Set
  `updated_from` to start a first sync later.
- **The filter goes out with every request.** The server applies it to each
  page, so a stored cursor must be read with the filter it was taken with.
  `DRPV2ViolationFilter` is frozen for that reason.
- **Upsert on `violation_id`.** A violation that changes is delivered again,
  later in the same walk too; keep the last delivery. `revision` is the
  number of history events, not a version of the content; diff the fields
  you use.
- **A newly matched signature does not move a violation in the feed.** Read
  the violation by id when its current state matters.
- **A violation that stops matching the filter does not come back** to say
  so. To track exits (a takedown that ended, say), compare snapshots by
  `violation_id`.
- `limit` (1-500, default 500) only changes how many requests a walk takes,
  never which violations come back.
- A page without its `items` list or its `nextCursor` raises
  `ParserException` and leaves the cursor where it was.

**Store the cursor as text, exactly as received.** The server compares
cursors as text and accepts any spelling of a UUID, so a copy that was
upper-cased, stripped of dashes or wrapped in braces (by a database column
type, for instance) resumes at another position without an error. Before
sending, a walk raises `InputException` for any string holding a UUID in a
form other than the issued one, whatever `ignore_validation` says. A cursor
the server cannot read at all raises `InvalidCursorException`:

```python
from ciaops import InvalidCursorException

try:
    walk = drp.create_violations_walk(criteria, cursor=load_checkpoint())
    for page in walk:
        ...
    save_checkpoint(walk.cursor)
except InvalidCursorException as exc:
    logger.warning("DRP rejected the stored cursor: %s", exc.server_message)
    drop_checkpoint()             # resync, bounded by criteria.updated_from
```

An empty first page from a stored cursor means caught up, or a cursor that
sorts after every position, such as a random UUID. To tell them apart,
compare what you hold with `get_violation_stats()` over the whole history,
with a `DRPV2StatsFilter` carrying the walk's `brand_ids`, `company_ids` and
`typosquatting`: `total`, or the `by_status` counts for the statuses you
filter on (the stats route does not apply the status filter).

Every page is a `Parser`, so `set_keys()` mapping works as for the other
feeds. A walk takes the mapping set when it is created:

```python
from ciaops import DRPV2Collections

drp.set_keys(DRPV2Collections.VIOLATIONS, {
    'id':     'violationId',
    'url':    'uri',
    'status': 'status',
    'brand':  'brand.brandId',
})
for page in drp.create_violations_walk(criteria, cursor=load_checkpoint()):
    rows = page.parse_portion()
```

#### Filtering violations

| Field | Parameter | Values |
|---|---|---|
| `updated_from`, `updated_to` | `updatedFrom`, `updatedTo` | `datetime` (an aware one is converted to UTC), `date`, `'YYYY-MM-DD'`, RFC 3339 with `Z` or an offset |
| `statuses` | `status[]` | `DRPV2Status`: `found`, `detected`, `inResponse`, `false`, `legal`, `onTracking`, `noContent`, `onParking`, `resolved` |
| `types` | `type[]` | `DRPV2ViolationType`: `phishing`, `counterfeit`, `copyright`, `partnerPolicyCompliance`, `trademark`, `malware`, `scam`, `noViolation` |
| `approve_states` | `approveState[]` | `DRPV2ApproveState`: `notRequired`, `underReview`, `approved`, `rejected` |
| `section` | `section` | `DRPV2Section`: `web`, `mobileApp`, `marketplace`, `socialNetwork`, `advertising`, `messenger` |
| `typosquatting` | `typosquatting` | `DRPV2Typosquatting`: `exclude` (sent when unset), `include`, `only` |
| `brand_ids`, `company_ids`, `tag_ids` | `brandIds[]`, `companyIds[]`, `tagIds[]` | ids from `get_companies()` and the records' `tag_ids` |

Different fields combine with AND, values of one field with OR. A repeated
field takes one value or any iterable; an empty one is refused rather than
read as "no filter", which would select everything. Values are checked
against the vocabulary before anything is sent (the server rejects an
unknown value with a `400` that does not say which), and a legacy client API
spelling is refused with the v2 token it maps to (`in_response` ->
`inResponse`, `under_review` -> `underReview`, `piracy` -> `copyright`, the
boolean typosquatting flag `True` -> `include`).

**How the bounds select.** The server reads a bound's date in UTC and
selects that whole day in the platform's time zone, which need not start at
midnight UTC; a time of day is dropped. By default (`exact_window=True`) the
filter treats the bounds as UTC moments instead (a date is its UTC midnight,
and an upper date includes its whole UTC day), and the walk asks the server
for a day more on each side: `updatedFrom` goes out as the day before the
lower bound's date (not before 1970-01-01, where the whole history starts)
and `updatedTo` as the day after the upper bound's. The
walk then returns every violation of the window, whatever time zone the
platform's days follow, and up to a day more on each side;
`DRPV2ViolationFilter.matches()` cuts a violation to the window, to the
second. It applies every other criterion to the violation's own fields too:

```python
criteria = DRPV2ViolationFilter(
    updated_from='2026-09-01T06:00:00Z', updated_to='2026-09-30'
)
in_window = [
    violation
    for page in drp.create_violations_walk(criteria)
    for violation in page.as_violations()
    if criteria.matches(violation)
]
```

Consecutive windows filtered this way (one UTC day each, say) deliver
every violation exactly once. With `exact_window=False` the bounds go out as
given and select the platform's own days, the ones `get_violation_stats()`
counts; consecutive date windows then tile without `matches()`, which
applies only a bound with a time of day. A bound with a time of day past the
edge of the platform's day does not bring back the violations beyond that
edge in that mode.

A violation can be present in several channels. `section` selects every
violation present in the channel named; each record lists its channels in
`sections`, and its own `section` is the primary one, which can be another.

A violation closed as `false` is never served, so filtering on that status
returns an empty page.

**An approval queue** is the `detected` violations whose `approve_state` is
`underReview`:

```python
from ciaops import DRPV2ApproveState

criteria = DRPV2ViolationFilter(
    statuses=DRPV2Status.DETECTED,
    approve_states=DRPV2ApproveState.UNDER_REVIEW,
    typosquatting='include',
)
queue = [
    violation
    for page in drp.create_violations_walk(criteria)
    for violation in page.as_violations()
]
```

**Scope ids come from `get_companies()`.** A brand outside the credential's
scope is a `403`; a company outside it returns an empty result, which reads
exactly like "no data".

#### Reading a violation

`DRPV2Violation` is a read view over the raw record (`raw_response`), with an
accessor for every field of the contract:

| Group | Accessors |
|---|---|
| identity | `violation_id`, `revision`, `created_at`, `updated_at`, `portal_link` |
| scope | `brand` (`brand_id`, `brand_name`), `company` (`company_id`, `company_name`), `brand_id`, `company_id` |
| verdict | `uri`, `type`, `section`, `sections`, `source`, `is_typosquatting`, `status`, `approve` (`state`, `is_required`), `approve_state` |
| detail | `scores`, `score('risk')` (`pick`: `'first'`, `'last'`, `'max'` or `'min'`), `hunting_rules`, `whois` (`domain`, `ip`), `title`, `description`, `tags`, `tag_ids`, `images`, `comments` |
| captures | `screenshot_url`, `html_url`, `has_screenshot`, `has_html`, `capture_hashes(kind)` |
| history | `violation_history` (as served), `timeline` (a stable order), `latest_status_change` |
| shortcuts | `is_live` (`detected` or `inResponse`), `is_under_review`, `is_uploaded` |

Every nested block reads as `None` or empty when the server sends `null`,
and a name served as `""` (tag and hunting-rule names usually are) reads as
`None`. Resolve tag names by id from stats over the whole history in the
`include` view (`get_violation_stats(DRPV2StatsFilter(typosquatting='include')).tag_names`),
since `get_tags()` lists only some of them. A transition is in a history
event's `change` (`field`, `from_`, `to`); `details` is the action's payload.

`brand` and `company` are the customer's own identity; `title`,
`description`, comments, the whois registrant and tag names (a `vip` tag
names a monitored person) can name people; hunting-rule names carry the
customer's own wording. None of them is an indicator, and an integration
may want to mask them before they leave the customer's systems:
`page.masked(DRPV2Collections.VIOLATIONS)` replaces the whois registrant
and masks the card numbers in the title, the description and the comment
texts; `MaskPolicy.strict()` replaces those texts by their length.

One violation by id, with its whole history:

```python
violation = drp.fetch_violation('9f2c...').violation      # NotFoundException if unknown
```

The parser returned by `fetch_violation()` honors the `set_keys()` mapping
too.

#### Counting violations

`get_violation_stats()` returns the total and its breakdowns (by status,
type, approve state, brand, company and tag) in one call. It honors five
filters (`updated_from`, `updated_to`, `brand_ids`, `company_ids` and
`typosquatting`), so it takes its own `DRPV2StatsFilter`:

```python
from ciaops import DRPV2StatsFilter

stats = drp.get_violation_stats(DRPV2StatsFilter(typosquatting='include'))
stats.total
stats.by_status['inResponse']      # every known status is a key, 0 if absent
stats.tag_names                    # tag_id -> name, for every named tag in by_tag
```

- It counts the violations the feed returns for the same window, brands,
  companies and view: its window selects on `updatedAt` too, and each
  breakdown matches the records' own fields. Each bound selects a whole
  day of the platform's calendar, as on the feed with `exact_window=False`;
  a time of day is ignored.
- To check what you hold against a count, walk the same bounds with
  `exact_window=False` to the empty page and call stats right after;
  violations that change in between move the two apart.
- `total` is the only grand total. `by_tag` counts attachments, so its rows
  overlap and do not sum to `total`.
- `typosquatting` is always 0 in the default `exclude` view.
- Like the feed, an unset `updated_from` counts the whole history.

#### Downloading captures

Most violations carry no capture, and the record says so: download only
when `has_screenshot` / `has_html` is true, and soon after first seeing the
violation, since a capture can disappear.

```python
if violation.has_screenshot:
    capture = drp.download_screenshot(violation.violation_id, missing_ok=True)
    if capture is not None:
        capture.media_type         # from the bytes: 'image/jpeg', 'image/png', ...
        save(f"{capture.sha256}.{capture.extension}.bin", capture.content)

if violation.has_html:
    page = drp.download_html(violation.violation_id, missing_ok=True)   # DRPV2Capture
```

A `200` that is not a capture (not `application/octet-stream`, empty, or
named by another hash than its own, such as a sign-in page from a proxy)
raises `ParserException`, and a redirect raises `ConnectionException`.
`capture.matches(violation)` tells whether the capture belongs to that
violation and its history names the capture. For the capture's own
violation, `False` is no sign of a wrong capture: a history can record a
capture without naming its file.

A captured page is the abusive page verbatim: store the bytes and **never
render it**, re-serve it or inline it into a ticket, and defang any URL
taken from it. `screenshot_url` and `html_url` work only with the API
credential, so they are no link for a ticket either. The media type comes
from the bytes, because the server sends `application/octet-stream` and its
file names can lack an extension.

These routes serve the **current** capture. The hashes an `enrich` event of
the history names (`DRPV2HistoryEvent.files`) identify captures; they are
not download addresses.

#### Companies, brands and tags

```python
for company in drp.get_companies():
    company.company_id, company.brand_ids
    for license_ in company.licenses:
        license_.type, license_.status, license_.expires_at
    tags = drp.get_tags(company_id=company.company_id)
```

`licenses` reports what a company subscribes to and when it expires; it is
not a complete list of what the company may see, so never switch a feature
off because a type is missing from it. The tag catalog lists a subset of
the tags attached in the requested scope and changes over time: read it again
before attaching tags, and resolve tag names from stats' `tag_names` in the
`include` view. Leave the system tags out of a tag picker: `Added by
customer` marks an uploaded violation, and `Reported by customer` one whose
URL was uploaded again. A
`403` from `get_tags()` means a company or brand id outside the credential's
scope, or mistyped, not a problem with the key.

#### Writing

Every write is **sent once** and never retried by the library, because a
second comment or upload is a second write. Any failure after a write was
sent (a timeout, a `5xx`, a dropped connection, an answer that cannot be
read) leaves its outcome unknown. A write that carried an
`idempotency_key` can be sent again under the same key, which the API
applies once; read the violations back before resending one without a key.
Each write returns one outcome per item, read from the response
body: `200`, `207` and, for an upload in which nothing succeeded, `400`
all come back as a result object, not as an exception.

A write takes seconds to minutes to show on `fetch_violation()`, which can
meanwhile return the previous state or, for a new upload, `404`.
`wait_for_violations()` re-reads with backoff (up to ten minutes) until a
condition holds for every id, and `wait_for_violation()` does it for one:

```python
from ciaops import DRPV2ApproveState, DRPV2Status

fresh = [drp.fetch_violation(vid).violation for vid in selected]   # right before
pending = [
    v.violation_id
    for v in fresh
    if v.status == DRPV2Status.DETECTED and v.is_under_review
]
if pending:
    result = drp.approve_violations(pending)
    confirmed = drp.wait_for_violations(          # id -> violation, or None
        result.succeeded_ids or pending,
        lambda v: v.approve_state == DRPV2ApproveState.APPROVED,
    )
```

`upload_violations()` registers 1-100 URLs or domains, each for one of
your brands. There is no delete: an upload is permanent. A new violation
starts as `found`, awaiting review, and becomes `detected` once confirmed.
A URL already known under the brand creates nothing: the violation keeps
its status, type and approval, and gains the system tag `Reported by
customer` once.

```python
from ciaops import DRPV2UploadItem

result = drp.upload_violations([
    DRPV2UploadItem(url='https://brand-lookalike.example.com', type='phishing', brand_id=brand_id),
])
result.violation_ids          # new and already known
result.errors                 # (url, brand_id) -> forbidden, invalidItem, ...
for row in result.succeeded:
    row.violation_id, row.existing, row.status    # status: a known one's
```

`type` is any violation type but `noViolation`. Two items naming the identical
URL and brand with different types are refused before sending. URLs are
compared as written: the server de-duplicates on a normalized URL, so two
spellings of one address can still name one violation.

A row's `existing` tells a new violation from a known one. For a known one,
`type` is the type sent, not the violation's, and `status` is its current
status when the API reports it. A row's `url` is the server's echo (a bare
domain comes back as `//domain`), not a key; to tie an id to an item for
certain, upload that item alone. The same items sent again under the same
`idempotency_key` within 24 hours return the first answer and create
nothing.

`approve_violations(ids)` and `reject_violations(ids)` take 1-100 ids. Both
act only on a violation whose `status` is `detected`; any other status
fails with `notUnderReview`. On a `detected` violation, by its
`approve_state`:

| `approve_state` | `approve_violations` | `reject_violations` |
|---|---|---|
| `underReview` | approved | rejected |
| `notRequired` | fails with `notUnderReview` | **rejected** |
| `rejected` | **reversed** to approved | no change |
| `approved` | no change | **reversed** to rejected |

A stale selection can reverse a decision: read the violations again just
before the call and send only the ones still awaiting a decision. Approving
does not change `status`.

`comment_violations(ids, comment=text)` appends the same text to each
violation. A comment cannot be edited or deleted, and a comment posted
through the API is `public`: every portal user of the tenant can read it.
Pass an `idempotency_key`, one fresh value per comment and the same value on
every retry of it: a repeat under the key posts nothing and reports the
first comment.

```python
import uuid

key = str(uuid.uuid4())                 # keep it with the pending comment
drp.comment_violations([violation_id], comment='Takedown requested', idempotency_key=key)
```

`attach_tags(ids, tag_ids)` refuses the whole request (`400 badRequest`,
nothing applied) for a tag id the server does not know at all; it does not
enforce the `get_tags()` list, so check against a fresh one yourself.
Attaching a tag a violation already carries, or detaching one it lacks,
changes nothing.
`detach_tags(ids, tag_ids)` takes the ids from the violations' own `tag_ids`,
since `get_tags()` omits tags that violations carry.

The violation records no author of a write, so log your own audit trail.
The library logs, at `INFO` under the `ciaops.pollers.drp_v2` logger
hierarchy, the ids each write
succeeded for (for an upload, the type and brand of a new violation and the
status of a known one), and at `WARNING` what
failed: for an upload the counts per code, the failed URLs only at `DEBUG`,
since a reported URL can carry a victim's address.

#### Errors

| Response | Raised |
|---|---|
| `400 invalidCursor` | `InvalidCursorException` (`cursor`, `server_message`) |
| `404 notFound` | `NotFoundException`: an unknown id, a violation the credential cannot see, or a missing capture |
| an answer of the wrong shape | `ParserException`: a page without `items` or `nextCursor`, stats without `total`, a write answer without its lists, a `200` that is not a capture |
| any other failure | `ConnectionException` |

A page or a write answer of the wrong shape raises `ResponseShapeError`,
which is also a `ConnectionException`; the other wrong shapes raise a plain
`ParserException`, which is not. After a write, treat both as "outcome
unknown". Every `ConnectionException` carries `status_code` (`None` when no
response arrived) and, when the API sent one, `error_code`, the stable code
from the error envelope (`DRPV2ErrorCode`: `badRequest`, `invalidCursor`,
`unauthenticated`, `forbidden`, `notFound`, `rateLimited`, `internal`).
Branch on `error_code`, never on the message text. A `403 forbidden` on a
request naming a brand or company id means that id is outside the
credential's scope or mistyped. A `404` without a code means the route does
not exist (usually an `api_url` that is not the `/api/v2/` base) and is a
plain `ConnectionException`, so `missing_ok=True` does not hide it.

#### Moving from DRPPoller

| `DRPPoller` (legacy `/client_api`) | `DRPV2Poller` (`/api/v2`) |
|---|---|
| `create_update_generator('violation/list', ...)` on `seqUpdate` | `create_violations_walk(criteria, cursor=...)` on `nextCursor` |
| `get_seq_update_dict(date)` | `DRPV2ViolationFilter(updated_from=date)` for the first run |
| `search_feed_by_id(id)` | `fetch_violation(id)` |
| `change_status(id, 'approve' / 'reject')` | `approve_violations([id])` / `reject_violations([id])` |
| `add_violations([{url, violationSubtype, brandId}])` | `upload_violations([DRPV2UploadItem(url, type, brand_id)])` |
| `get_brands()`, `get_subscriptions()` | `get_companies()`: brands and licenses with expiry |
| (none) | `get_violation_stats()`, `get_tags()`, `comment_violations()`, `attach_tags()` / `detach_tags()`, `download_screenshot()` / `download_html()` |

The vocabulary is camelCase and the same in filters and records:
`approve_states=['under_review']` becomes `approve_states=['underReview']`,
the numeric `subtypes` and `section` codes become `types` and `section`
tokens (`6` -> `'phishing'`, `1` -> `'web'`), and `use_typo_squatting=True`
becomes `typosquatting='include'`. The legacy `violationSubtype` is the v2
`type` (`piracy` reads as `copyright`); the legacy `violationType` has no v2
counterpart. A v2 cursor and a legacy `seqUpdate` are not interchangeable:
start the v2 sync with `updated_from`.

### ASMPoller methods

```python
from ciaops import ASMPoller

asm = ASMPoller(username='...', api_key='...', api_url='https://asm.group-ib.com/')
```

`api_url` is the host root: the library joins every route under `api/v1/`
itself, so a base that already ends in `/api/v1/` doubles the path. Every
request of a poller, feed pages and single calls alike, is paced to one
start per 1.05 seconds, the API's limit of one request per second; pass
`rate_limit_delay=0` when an outer scheduler paces the calls.

**List companies:**

```python
companies = asm.get_companies()          # all companies
active = asm.get_companies(status='active')
# -> [{"id": "uuid", "name": "Acme Corp"}, ...]
```

**Update generator** uses POST requests. Build the request body with
`ASMRequestParams` and pass it as `request_params`:

```python
from ciaops import ASMRequestParams

generator = asm.create_update_generator(
    collection_name='assets/updated',   # or 'leaks/updated', 'issues/updated'
    request_params=ASMRequestParams(
        company_id='company-uuid',      # one company per request
        date_from='2024-01-01',
        date_to='2024-06-01',           # optional
        count=500,                      # 1..5000; refused outside that range
        status=['new', 'confirmed'],    # optional filter
        type=['domain', 'ip'],          # optional filter (assets only)
        discover=['auto', 'cloud'],     # assets only: auto|enrich|manual|cloud|integration
        has_issues=['crit', 'high'],    # assets only: crit|high|medium|low|clean
    ),
)
for portion in generator:
    data = portion.parse_portion()
```

Fixed-vocabulary filters (`severity`, `asset_discovered`, `asset_status`,
`discover`, `has_issues`) and `count` are validated on construction and raise
`ValueError`; pass `ignore_validation=True` to send a value the library does
not know. `company_id` is one company: every feed takes one company per
request.

**What a portion holds.** The three feeds answer in one of two envelope
shapes: the flat `items: [...]` the API documents, or the recorded one where
`items` is an object keyed by company id (`items[companyId].items[type][status][]`
for assets, `items[companyId].items[status][]` for issues,
`items[companyId].items[]` for leaks). Each portion is an `ASMParser`, a
`Parser` that accepts both and flattens the nested form, so `parse_portion()`,
`get_iocs()` and `portion_size` see records, not company ids:

```python
for portion in generator:
    records = portion.records         # flat list of record dicts, server order
    for company_id, block in portion.by_company.items():
        # the company-keyed object as the server sent it ({} for the flat
        # form); the only place a leak record's company is available
        print(company_id, block.get('companyName'))
    if portion.skipped:
        pass  # entries that were not records were dropped; already logged
```

`portion.count` is the server's own top-level count and is not comparable
with `portion_size`: on the live API it is a cumulative string such as
`"10 of 46"` (records served so far of the total), and a recorded nested page
reports 30 against one record. A page
that yields no records while the server reports a positive count, or that
carried entries the parser had to skip, is logged at WARNING rather than
passed off as a normal end of feed.

**How ASM pages.** Iteration is driven by `seqUpdate`, an integer the API
returns on every response page; each page's value is sent on the next request
and the walk ends when a page comes back empty. `dateFrom`/`dateTo` are
**filters, not a starting offset**: they scope the result set, so they are
sent on *every* request alongside the cursor, not only on the first.

`seqUpdate` is the position of the oldest record served so far within the
window, running backwards in time; it is not a watermark of what changed
since. So `sequpdate=` continues an interrupted walk under the **same**
`date_from`/`date_to` (store `portion.sequpdate` as you go and pass it back
with the same window), and a walk started from a stored `seqUpdate` with a
later window collects nothing. For the next run, move the window instead:
set `date_from` a few minutes before the newest `lastSeen` (or `lastScan`,
for assets) you hold, walk without `sequpdate`, and de-duplicate on `id`.

```python
# Continue an interrupted walk of the same window:
sequpdate = None
for portion in generator:
    data = portion.parse_portion()
    sequpdate = portion.sequpdate   # pass back with the same date_from/date_to
```

**Dashboard scores:**

```python
scores = asm.get_dashboard_scores(company_id='company-uuid')

print(scores.current_score)          # 7.4
print(scores.score_trend)            # "improving" | "declining" | "stable"
print(scores.total_critical)         # 3
print(scores.severity_summary)       # {"critical": 3, "high": 12, ...}
print(scores.counters_summary)       # {"new_assets": 5, "new_issues": 2, ...}
print(scores.lowest_scoring_category)  # {"name": "Network Security", ...}

summary = scores.get_dashboard_summary()  # full dict for periodic updates
raw = asm.get_dashboard_scores(company_id='uuid', as_raw=True)  # plain dict
```

**Issue management:**

```python
evidence = asm.get_issue_evidence(issue_id='issue-uuid')

# Several issues in one call. Issue types the bulk endpoint does not serve
# come back with supported=false and are logged; fetch those one by one.
bulk = asm.get_issues_evidence_bulk(issue_ids=['issue-uuid-1', 'issue-uuid-2'])

asm.add_issue_comment(
    company_id='company-uuid',
    issue_id='issue-uuid',
    body='Investigating...',
)

asm.change_issue_status(
    issues_id=['issue-uuid-1', 'issue-uuid-2'],
    status='Under review',   # Detected | Under review | Solved | Ignored | False positive
)
```

`status` is matched against `ASMCollections.ISSUE_STATUS_OPTIONS` without
regard to case and sent as given, so the lowercase form the `issues/updated`
filter takes passes too. Pass `ignore_validation=True` to send a status the
library does not know. The five writes (comments, the two status changes
and the asset lists) are sent once: a failure after the request left
raises, and the library never repeats a write on its own.

**Asset management:**

```python
asm.add_assets(                 # each value creates a permanent asset
    company_id='company-uuid',
    confirmed_domain=['example.com'],
    confirmed_ip=['192.0.2.4'],
)

asm.remove_assets(              # takes the value off its list; the asset stays
    company_id='company-uuid',
    excluded_domain='old.example.com',
)

asm.change_asset_status(
    assets_ids=['asset-uuid'],
    status='confirmed',   # new | false | confirmed  ("false" is the string)
)

seed = asm.get_seed_assets(company_id='company-uuid')
# returns {"name": ..., "confirmedDomain": [...], "excludedDomain": [...],
#    "confirmedIP": [...], "excludedIP": [...]}: the curated lists that
#    add_assets/remove_assets edit, not the discovered assets
```

`add_assets` creates the assets: `remove_assets` takes a value off its list
and the asset stays in the inventory with status `new`, and no route deletes
it. Both take one text or a list and send each value as given, without
surrounding whitespace, so remove a value spelled as it was added. A domain
may start with `*.` and an IP list takes networks as `/` and a prefix length
(`192.0.2.0/24`); a URL, a host with a port or path, text with whitespace
inside, a netmask form, a `/0` network and an empty call are refused before
sending (`ignore_validation=True` skips the value checks; an empty call is
refused either way).
`change_asset_status` sends the body key the API takes, `assetsId`.

**Clients, companies, partners, logs, reports:** read-only, each returning
the response object as the API sends it:

```python
asm.get_clients()                      # {count, items: [{id, name, industry, country, status, managerEmail}]}
asm.get_client(client_id='...')        # one client object
asm.get_partners()                     # {count, items: [{id, name, subscribeStart, ...}]}
asm.get_companies(client_id='...')     # the companies list, narrowed to one client
asm.get_company(company_id='...')      # settings: name, website, branches, licenseType, activeScan, ...
asm.get_company_logs(company_id='...', date_from='2025-01-01', date_to='2025-01-31')
asm.get_user_logs(date_from='2025-01-01')   # the authenticating user's own log
asm.get_reports(company_id='...')      # {count, items: [{id, score, timestamp}]}
asm.get_last_report(company_id='...')  # the latest full report
asm.get_report(report_id='...')        # one full report, by *report* id
```

Report objects are camelCase at the top level (`companyId`, `scanDate`,
`rootIndicators`, `detailedList`, `totalChecks`) with snake_case keys inside
(`actual_score`, `first_seen`, `ssl_count`). In `get_company_logs` the
`items` value is an object keyed by company id, not a list.

Every id that goes into a URL path is validated and percent-encoded, and every
method raises `ResponseShapeError` (a `ParserException`) if the body is not
a JSON object, so a misrouted or malformed response is reported against the
endpoint that produced it rather than as an `AttributeError` later on.

**Options**, each off unless set:

```python
asm = ASMPoller(username='...', api_key='...', api_url='https://asm.group-ib.com/',
                read_only=True)                     # write routes refused before the wire
rows = asm.get_companies(status=['active'], full=True)   # the rows as served
page = asm.fetch_page('issues/updated', params, sequpdate=cursor)
page.served, page.total                             # from "N of M"
for company_id, record in page.company_records():
    ...
for issue_id, evidence in asm.iter_issue_evidence(issue_ids, batch_size=50):
    ...                                             # bulk route, one-by-one fallback
scores = asm.get_dashboard_scores(company_id, missing_score=float('nan'))
scores.reported('current')                          # None when the answer has no score
```

`create_update_walk(collection, params)` returns a walk object (see
[Walk objects](#walk-objects)); `walk.stats.complete` compares the
server's `"N of M"` count at the end.

### IMCPoller methods

**IMC (Incident Management Center)** is the incident layer on top of the TI
collections. Server-side **incident rules** match records across TI
collections; matches inside a time window are rolled up into an **incident**
with a status, priority, scoring, per-collection match counts and an optional
AI summary. Each match carries only a **pointer** into the source collection,
which you resolve to get the record itself.

IMC lives on the **TI gateway and uses the TI credentials**: one API key
covers both the incident feed and the by-id lookups that resolve its matches.

`IMCPoller` covers the whole public v2 surface: both `IncidentService`
operations and every `RuleMatchService` endpoint, and the implementation is
checked against the generated OpenAPI contract.

The API is **read-only**: no method on `IMCPoller` changes incident state.

```python
from ciaops import IMCPoller

imc = IMCPoller(username='user@example.com', api_key='API_KEY', api_url='TI_API_URL')
```

Requests are held to **one per second**. That rate is the TI gateway's,
inherited because IMC shares it; IMC's own limit is not published, and the live
runs at this rate never drew a `429`. Anything in this library that
makes more than one request paces itself to it (both walks and
`iter_resolved_matches`), and `rate_limit_delay=0` turns that off when an outer
scheduler already paces the calls.

The single-request methods (`search_updated_incidents`, `fetch_incident`,
`resolve_match`) make exactly one call and wait on the poller's limiter, which
never delays a first request. Calling them in a
loop is paced at the poller's rate; for another rate, give the poller a
`RateLimiter`:

```python
from ciaops import IMCPoller, RateLimiter

imc = IMCPoller(username='...', api_key='...', api_url='TI_API_URL',
                rate_limiter=RateLimiter(2.0))   # one request every two seconds
for incident_id in ids:
    portion = imc.fetch_incident(incident_id)
```

#### Consuming incidents

The incident feed is paged and delta in one mechanism, on an opaque `syncToken`
cursor: keep calling with the returned token until a page comes back with no
incidents; that empty page means you are caught up. Store the last token; pass
it back later and you get only what changed. It is the IMC equivalent of
`seqUpdate`.

The sync axis is the incident's **`updatedAt`**, so a status or assignee change
brings an old incident back into the feed. Ordering and page size are fixed by
the server (there is no `limit`), and **deletions are not tracked**: the feed
carries no tombstones.

Two consequences of syncing on `updatedAt` that a connector has to plan for,
both stated by the API's own documentation:

- **An incident shared with you after you synced past it never arrives.**
  Visibility is company-scoped; if an incident becomes visible later and its
  `updatedAt` did not move, no delta poll will return it. A periodic full
  re-sync (no `sync_token`, bounded by `updated_at_from`) is the only way to
  pick those up.
- **Editing a rule changes its incidents without moving their `updatedAt`.**
  See the rule-drift note below: name, priority, scoring and tags are served
  from the rule's current state, so a delta sync will not see the change.

> **A first poll returns the account's *oldest* incidents first.** The ordering
> is ascending by `updatedAt`, so the head of the first page is the oldest
> slice, not the newest. Which means:
>
> - To look at *recent* activity, filter by time rather than reading page one:
>   `IMCIncidentFilter(updated_at_from=...)`. Draining the whole feed also gets
>   you there, later.
> - A **filtered** query is ascending as well, so a wide window still returns
>   the oldest incidents *of that window*. Reaching "now" means a **narrow**
>   window. Measured on a live account, `updated_at_from = now - 1 day` put
>   today's incidents on the first page, while `now - 365 days` put
>   84-day-old ones there. Widen only until you get results, never past that.
> - `number` is a per-rule sequence, so it says nothing about age. Compare
>   `updatedAt`, not numbers.
>
> This matters in practice: **an old incident can report a large `matchCounts`
> whose match endpoint answers `200` with an empty page.** Measured on a live
> account: incidents a few **hours** old returned their matches in full (and
> resolved to their TI records), while incidents 84+ **days** old reported
> thousands of matches and returned none. No threshold is published, so treat
> evidence on an old incident as something that may be gone, and drill into
> recent ones. `iter_incident_matches` warns when a drained walk returns none
> of the reported matches, so this never passes as "no evidence".

One page per poll (what a scheduled connector usually wants):

```python
portion = imc.search_updated_incidents(sync_token=load_checkpoint())

for incident in portion.as_incidents():
    print(incident.number, incident.status, incident.rule_name)

save_checkpoint(portion.next_sync_token)
```

Or drain the whole backlog in one run. `create_incidents_walk` returns the
**walk object**, so the checkpoint is still reachable when the loop ends: the
last `nextSyncToken` arrives on the terminal empty page, which is never
yielded.

```python
walk = imc.create_incidents_walk(sync_token=load_checkpoint())
for portion in walk:
    for incident in portion.as_incidents():
        ...
save_checkpoint(walk.sync_token)     # the caught-up checkpoint
```

`walk.sync_token` moves past a page only when the loop asks for the next one.
While your code handles a page it still names the position that page was
requested from, so a checkpoint saved from an `except` or `finally` block
delivers the page again next time instead of skipping what was not handled.
Checkpointing `portion.next_sync_token` after each page is handled is
equally correct and costs one extra request on the next poll. A walk is
single-use: iterating one twice raises `ConsumedWalkError`, rather than
silently re-requesting and double-counting.

**When a stored checkpoint goes bad** (malformed, no longer decodable, or from
another context), the API answers `400` and the library raises
`InvalidCursorException` (a `ConnectionException` subclass), carrying the
rejected cursor and the server's own explanation. The recovery is specific, so
it is worth handling explicitly:

```python
from ciaops import InvalidCursorException

try:
    walk = imc.create_incidents_walk(sync_token=load_checkpoint())
    for portion in walk:
        ...
    save_checkpoint(walk.sync_token)
except InvalidCursorException as exc:
    logger.warning("IMC rejected %s: %s", exc.cursor_param, exc.server_message)
    drop_checkpoint()          # resync from scratch, optionally bounded by
                               # IMCIncidentFilter(updated_at_from=...)
```

Any other `400` keeps its type and carries the server's message, so a
rejected filter value says which one.

A corrupt **`pageToken`** behaves differently: the API answers `500` there
rather than `400`, so it is retried by the shared adapter and then surfaces as
a plain `ConnectionException` (about a minute of backoff). Only the sync cursor
(the one a connector persists) gets the clean `400` classification.

Omit `sync_token` for the first full pull, and use
`IMCIncidentFilter(updated_at_from=...)` to choose where that first sync starts.

Every page is also a `Parser`, so `set_keys()` mapping works exactly as for the
TI feeds:

```python
imc.set_keys(IMCCollections.INCIDENTS, {
    'number': 'number',
    'status': 'status',
    'rule':   'incidentRuleRevision.incidentRule.name',
    'score':  'incidentRuleRevision.incidentRule.scoring',
    'source': '*IMC',
})
portion = imc.search_updated_incidents(sync_token=load_checkpoint())
portion.parse_portion()
# returns [{"number": 42, "status": "INCIDENT_STATUS_TO_DO", "rule": "...", "score": 90, "source": "IMC"}]
```

#### Filtering incidents

Build the filter with `IMCIncidentFilter`. Repeated fields accept a single
value or a list (the API ORs a field's values). Enum fields take the value the
contract declares; use the constants:

```python
from ciaops import IMCIncidentFilter, IMCIncidentStatus

filters = IMCIncidentFilter(
    statuses=[IMCIncidentStatus.TO_DO, IMCIncidentStatus.PROCESSING],
    collections='darkWeb',                  # or IMCCollection.DARK_WEB, or 'dark-web'
    priorities=[1, 2],
    tags='vip',
    incident_rule_ids='22222222-2222-7222-8222-222200001234',
    assignee_user_ids=4242,
    scoring_from=70, scoring_to=100,        # 0-100
    updated_at_from='2026-06-26',           # promoted to 2026-06-26T00:00:00Z
)

portion = imc.search_updated_incidents(filters)
```

`IMCIncidentFilter` is **immutable**: frozen, with repeated fields held as
tuples. The API applies the filter on every request of a sync walk, cursor
requests included, so one that could change half-way through would silently
skip incidents that stopped matching. Build a new filter to change criteria.

Different fields combine with **AND**, values inside one field with **OR**, and
unset fields are not applied. The filter is flat even though the response
nests: `tags`, `priorities`, `incident_rule_ids`, `author_user_ids` and the
scoring bounds all match against the incident's **rule**.

The filter applies two wire rules for you: filter parameters are sent
with the required `filter.` prefix (an unprefixed one is **ignored** and
returns the full set), and enums are sent by name (the integer form is a
`400`).

Enum values are matched **exactly** against what the contract declares:
use the `IMCIncidentStatus.*` / `IMCCollection.*` constants. The API
answers a filter value outside the contract with every incident instead of
an error, so an invented value would read as "everything matches".
`collections` accepts all three spellings the contract itself declares
(`darkWeb`, `dark-web`, `COLLECTION_DARK_WEB`) because all three are the API's
own.

Values are validated on construction against the contract's own constraints;
pass `ignore_validation=True` to send them through as-is:

| Field | Constraint |
|---|---|
| `statuses`, `collections` | exactly a declared value: `IMCIncidentStatus.*`, `IMCCollection.*` (`collections` also takes `darkWeb` / `dark-web`); the `*_UNSPECIFIED` zero value is refused, since the API answers `400` for it (omit the filter to match everything) |
| `priorities` | integers **1-10** inclusive; **P1 is the highest** priority, P10 the lowest |
| `assignee_user_ids`, `author_user_ids` | **positive** integers |
| `incident_rule_ids` | canonical **UUID**s |
| `scoring_from` / `scoring_to` | **0-100**, closed range `[from, to]`, `from <= to` |
| `updated_at_from` / `updated_at_to` | RFC 3339, **half-open** range `[from, to)`, `from <= to` |

Because `updated_at_*` is half-open, adjacent windows never double-count, and
equal bounds select nothing.

> **One walk, one set of criteria.** The filter is applied on every request of
> a walk, the cursor ones included, and being frozen it cannot change under a
> walk in progress. What you must not
> do is *resume a stored cursor with different criteria*: the cursor only ever
> moves forward, so anything the old filter excluded stays excluded. New
> criteria mean a new sync without a cursor, bounded by `updated_at_from` if
> you do not want the whole backlog.

#### Reading an incident

```python
parser = imc.fetch_incident('11111111-....')     # the body *is* the incident
```

The id must be a canonical UUID, as the contract declares it, so a
malformed id is rejected before the request instead of coming back as a `400`.

Wrap any incident, from a page or from `fetch_incident`, in `IMCIncident`
for the fields an integration maps to a notable or a case:

```python
from ciaops import IMCIncident

incident = IMCIncident.from_parser(parser)       # or IMCIncident(raw_response=raw)

incident.id                        # UUID, the only global identifier
incident.number                    # 42     (sequence *within the rule*, from 1)
incident.status                    # "INCIDENT_STATUS_TO_DO"
incident.is_open                   # True   (to do / processing / on hold)
incident.window_start              # start of the aggregation window
incident.window_end                # end of the aggregation window

incident.total_matches             # 250
incident.match_counts              # {"vulnerability": 250, "darkWeb": 0, ...}
incident.collections_with_matches  # ["vulnerability"]  (drives the drill-down)

incident.rule_id                   # the rule behind the incident
incident.rule_name                 # "Monitored vendor CVEs"
incident.rule_version              # revision the incident matched
incident.rule_is_current           # is that still the rule's live revision?
incident.rule_revision_created_at  # when the revision was created
incident.rule_created_at           # when the rule was created
incident.rule_updated_at           # when the rule last changed
incident.collection_queries        # {"vulnerability": "cvss_score: >7"}  (Lucene)
incident.priority                  # 2      (1-10; 1 is the highest priority)
incident.scoring                   # 90     (0-100, set on the rule by its author)
incident.tags                      # ["vip"]

incident.author                    # {"id": "4243", "email": "..."}, the rule author
incident.author_email
incident.author_id
incident.rule_assignee_email       # the rule's *default* assignee
incident.rule_assignee_id
incident.assignee                  # {} when unassigned
incident.assignee_email            # this incident's assignee
incident.assignee_id

incident.has_ai_summary            # False when none was generated
incident.ai_summary_level          # "LEVEL_HIGH" | ... | None
incident.portal_link               # the incident's page in the portal
incident.as_summary_dict()         # flat, alert-shaped payload, link included
```

`aiSummary` is present only when its generation succeeded, so it is commonly
absent. `has_ai_summary` tells you which case you are in; report it as
unavailable rather than substituting a summary of your own. It carries three
fields: `title`, `description` and `level`.

> **Rule fields drift.** `rule_name`, `priority`, `scoring` and `tags` come
> from the rule's *current* state, not from a snapshot taken when the incident
> opened. Editing a rule changes them for all of its incidents **without
> moving those incidents' `updatedAt`**, so a delta sync will not see it. Only
> the incident's own fields (status, assignee) move the cursor.
> `rule_is_current` tells you whether the incident still points at the rule's
> live revision.

#### Drilling into the evidence

`iter_incident_matches` walks every collection that actually fired, driven by
`matchCounts.byCollection`; a collection with a zero count is skipped instead
of costing a request that returns an empty page:

```python
for collection, page in imc.iter_incident_matches(incident):
    print(collection, page.portion_size, page.next_page_token)
    for info in page.match_infos:
        print(info['idInIncident'], info['collectionItemId'],
              info['status'], info['matchedAt'])
```

`page.match_ids` gives the `idInIncident` values (a match's identity inside the
incident) and `page.collection_item_ids` the pointers into the source
collection.

For one collection at a time, use `create_matches_walk`; its walk object
exposes the resume point and the duplicate counter after iterating:

```python
walk = imc.create_matches_walk(
    incident_id=incident.id,
    collection='vulnerability',      # or 'vulnerabilities', or 'COLLECTION_VULNERABILITY'
)
for page in walk:
    ...
walk.page_token          # None once the last page has been read; otherwise the
                         # position the last yielded page was requested from
walk.duplicates_dropped  # matches skipped because they had already been seen
```

`max_pages_without_new_matches` is a hang guard: after that many pages in a
row that brought nothing new, the walk warns and stops instead of following
the cursor further. `walk.stopped_early` records the stop. The default is 2;
`1` stops at the first one. With `dedupe` on it never lets a duplicate
through; what it can do is stop ahead of a cursor that kept yielding nothing
new. `iter_incident_matches` passes it through and reports such a stop.
After an early stop `walk.page_token` is the cursor the server last answered
with, which the walk did not follow, not a resume point.

Three collections the contract reserves (`ddosAttack`, `openThreat`,
`telegram`) have no endpoint in public v2. Asking for one gives you that
answer explicitly rather than the generic "Invalid IMC collection" error.

`telegram` is not hypothetical: the portal offers Threats > Telegram as a rule
trigger, so a rule can raise incidents whose matches live in a collection this
API version cannot walk. Such a count is reported rather than dropped; see
`incident.unknown_collections` below.

`matchCounts.byCollection` and the match endpoints can disagree: an incident
can report matches whose endpoint answers `200` with an **empty page**. That is
observed on the live API, so `iter_incident_matches` compares a drained walk
with the reported count and warns rather than letting the empty result read as
"no evidence". Never infer that a walk is multi-page from a
count either; decide from `page.next_page_token`, because the page size is
server-controlled and not part of the contract.

`gitLeak` (Git leaks) is walkable like the other collections (`git-leaks`,
`COLLECTION_GIT_LEAK`, resolved through `osi/git_repository`).

A zero count is not evidence either way, so nothing warns and nothing changes;
a **non-zero** count in a collection this version cannot walk is reported
instead of dropped: the feed logs a warning once per unknown collection per
walk, `iter_incident_matches` logs one per incident, and
`incident.unknown_collections` exposes it as data (`{"telegram": 5}`). The
same goes for an incident reporting a non-zero `total` with no per-collection
breakdown to walk it by: the drill-down says so instead of returning an empty
result that looks like "no evidence".

> **Always page matches with `SORT_ORDER_DESC`** (the default).
> With `SORT_ORDER_ASC` the second page repeats the first and carries no
> cursor, so an ascending walk does not advance past the first page.
> The generator stops on a cursor that does not advance instead of looping,
> and keeps following one that does even when a page held nothing new, up to
> `max_pages_without_new_matches` such pages in a row. Duplicates it drops
> are always logged.

#### Resolving matches to TI records

A match tells you *which* record matched, not what is in it. Resolve the
pointer with its collection's **by-id** route:

```python
record = imc.resolve_match('threat', 'fake11111111111111111111111111110001')
# GET /api/v2/hi/threat/fake1111...  -> Parser (or None if the record is gone)
```

Or resolve a whole page, paced to the API limit:

```python
for collection, page in imc.iter_incident_matches(incident):
    for info, record in imc.iter_resolved_matches(collection, page.matches):
        if record is None:
            continue                       # the record aged out of its collection
        print(info['matchedAt'], record.raw_dict.get('title'))
```

**Resolution is the expensive step, and the cost is linear.** There is no batch
lookup, and lookups are paced to one request per second, so a full page of
about 100 matches takes about a minute and a 3,000-match incident is closer to
an hour; concurrency does not help, because the gateway's limit is per
account. Resolve what you will act on: filter the matches first, or pass
`limit`:

```python
for info, record in imc.iter_resolved_matches(collection, page.matches, limit=10):
    ...
```

When the input has a known size and the projected cost is a minute or more,
`iter_resolved_matches` logs that cost before it starts. It also logs what a
`limit` left untouched, so the count is never silently truncated.

`resolve_match` returns `None` for a record that no longer exists; pass
`missing_ok=False` to get a `NotFoundException` instead. The pointer is
percent-encoded before the request, since it is server data going into a URL
path, and a page entry that is not a match is reported and yielded as
`({}, None)` rather than dropped, so results stay aligned with the input. Keys
set for the target TI collection apply to the resolved record:

```python
imc.set_keys('hi/threat', {'title': 'title', 'countries': 'countries'})
record.parse_portion()   # -> [{"title": "...", "countries": ["US"]}]
```

Resolution routes per collection:

| Portal sub-section | IMC collection | Match path segment | Resolved with |
|---|---|---|---|
| Malware > Vulnerabilities | `vulnerability` | `vulnerabilities` | `osi/vulnerability/{id}` |
| Compromises > Accounts | `compromisedAccount` | `compromised-accounts` | `compromised/account_group/{id}` |
| Compromises > Bank cards | `compromisedCard` | `compromised-cards` | `compromised/bank_card_group/{id}` |
| Compromises > Masked bank cards | `compromisedMaskedCard` | `compromised-masked-cards` | `compromised/masked_card/{id}` |
| Compromises > Shops | `compromisedShop` | `compromised-shops` | `compromised/access/{id}` |
| Threats > Darkweb | `darkWeb` | `dark-web` | `darkweb/forums/{id}` |
| Compromises > Breached DB | `breachedDb` | `breached-db` | `compromised/breached/{id}` (singular) |
| Compromises > Suspicious payment details | `suspiciousPayment` | `suspicious-payments` | `compromised/spd/{id}` |
| Compromises > Public leaks | `publicLeak` | `public-leaks` | `osi/public_leak/{id}` |
| Threats > Last Threats | `threat` | `threats` | `hi/threat/{id}` |
| Git leaks | `gitLeak` | `git-leaks` | `osi/git_repository/{id}` |

The first column is what a rule author picks in the portal; the rest is what
the API calls the same thing. The pairing comes from the portal documentation's
sub-section names and the by-id routes above; the contract itself does not
carry the portal's labels.

`breachedDb` is the one collection whose feed and by-id route are spelled
differently: the feed is consumed as `compromised/breacheddb`, the newer
endpoint, which supports `/updated` and iterates on `seqUpdate`, while a single
record is read by id from singular `compromised/breached`. A resolved record is
parsed with the mapping set for the route it came from, so `set_keys` for one
of these does not apply to the other.

Resolved records inherit their collection's sensitivity: **mask passwords,
card numbers and leak payloads** before storing or displaying them.

### Close session

Always close the session in a `try`/`finally` block, or use the context manager:

```python
from ciaops import TIPoller
from ciaops.exception import InputException, ConnectionException

poller = TIPoller(username='example@example.corp', api_key='API_KEY', api_url='TI_API_URL')
try:
    feed = poller.search_feed_by_id('apt/threat', 'abc123')
except InputException as e:
    logger.error("Wrong input: %s", e)
except ConnectionException as e:
    logger.error("Connection error: %s", e)
finally:
    poller.close_session()
```

<br>

## Parsing

An example API response from a collection (received feeds):

```python
api_response = [
    {
        'iocs': {
            'network': [
                {
                    'ip': [1, 2],
                    'url': 'url.example.com'
                },
                {
                    'ip': [3],
                    'url': ''
                }
            ]
        }
    },
    {
        'iocs': {
            'network': [
                {
                    'ip': [4, 5],
                    'url': 'new.example.com'
                }
            ]
        }
    }
]
```

### Parse portion method

Your mapping dict for `parse_portion()` or `bulk_parse_portion()` methods:

```python
mapping_keys = {
    'network': {'ips': 'iocs.network.ip'},
    'url': 'iocs.network.url',
    'type': '*custom_network'
}
```

Result of `parse_portion()` output:

```python
parsing_result = [
    {
        'network': {'ips': [[1, 2], [3]]},
        'url': ['url.example.com', ''],
        'type': 'custom_network'
    },
    {
        'network': {'ips': [[4, 5]]},
        'url': ['new.example.com'],
        'type': 'custom_network'
    }
]
```

Result of `bulk_parse_portion()` output:

```python
parsing_result = [
    [
        {
            'network': {'ips': [[1, 2], [3]]},
            'url': ['url.example.com', ''],
            'type': 'custom_network'}
    ],
    [
        {
            'network': {'ips': [[4, 5]]},
            'url': ['new.example.com'],
            'type': 'custom_network'}
    ]
]
```

### Get IoCs method

Your mapping dict for `get_iocs()` method:

```python
mapping_keys = {
    'ips': 'iocs.network.ip',
    'url': 'iocs.network.url'
}
```

Result of `get_iocs()` output:

```python
parsing_result = {
    'ips': [1, 2, 3, 4, 5],
    'url': ['url.example.com', 'new.example.com']
}
```

<br>

## Filtering and masking records

Nothing here runs unless the caller builds it.

**Record filters** (`ciaops.filters`) have one contract per product:
`matches(record)`, `explain(record)` (the first criterion a record fails,
or `None`), `fingerprint()`, and what the server can apply:
`to_params()` on `TIRecordFilter` and `DRPRecordFilter`,
`to_request_params()` on `ASMRecordFilter`. Apply a filter to the record
as the API returns it, before masking.

```python
from ciaops import DRPRecordFilter, TIRecordFilter, TIRequestParams

ti_filter = TIRecordFilter('osi/vulnerability', types='cve', min_cvss=7)
params = ti_filter.to_params(TIRequestParams(limit=100))
kept = page.filtered(ti_filter)                   # a page of the records kept

drp_filter = DRPRecordFilter(statuses=['detected'], subtypes=['phishing'])
generator = drp_legacy.create_update_generator('violation/list', sequpdate=1,
                                               **drp_filter.to_params())
```

`TIRecordFilter.catalog(collection)` lists the filters a TI collection
takes; `TIRecordFilter.from_settings` reads them from integration settings,
`TIRecordFilter.from_lines` and `parse_filter_lines` from settings text, and
`TI_SETTINGS` names the settings.
`IMCIncidentFilter` and `DRPV2ViolationFilter` have `matches`, `explain`
and `fingerprint` too; `DRPV2StatsFilter`, which selects counts rather
than records, has `explain` and `fingerprint`.

**Masking** (`ciaops.masking`) masks the sensitive values of a record on
a copy, by the paths of its collection and by key in any record:

```python
from ciaops import MaskPolicy
from ciaops.masking import mask_record

masked = page.masked('compromised/account_group')              # recommended
strict = page.masked('compromised/account_group', MaskPolicy.strict())
result = mask_record('compromised/bank_card_group', record)
result.record, result.masked_paths
```

`MaskPolicy.recommended()` replaces the fields that hold passwords, card
secrets, personal data and secrets with a placeholder, masks card numbers
but for their first six and last four digits, masks card numbers in free
text, replaces download link lists with their item count, masks the logins
of ASM issues but for their first two and last two characters (at most half
of a short one) and keeps other logins. Free text keeps everything but card
numbers and the record's own passwords: a stealer log in
`events[].additionalData.raw` has the record's password masked where it
repeats it, while another password it states stays; a password shorter
than four characters (`MIN_TEXT_PASSWORD` in `ciaops.masking.record_pass`)
is masked in its own field only; `strict()` turns free text into a length
note and masks every login; `off()` keeps every value. A policy sets a
`MaskRule` per kind of value and can add paths and keys of its own.

The IMC and DRP v2 walks take `mask=` as the other walks do, and the ASM
evidence reads take `mask=True` or a `MaskPolicy`:

```python
walk = imc.create_incidents_walk(sync_token=token, mask=True)
walk = drp.create_violations_walk(criteria, mask=MaskPolicy.strict())
evidence = asm.get_issue_evidence(issue_id, mask=True)
```

**De-duplication, checkpoints, normalization.** `SeenIds` remembers what
was delivered (with a retention time, a size bound of 100,000 keys unless
set, and JSON state; `seen.changed` says whether there is anything new to
save) and
`record_fingerprint` digests a record or the parts that matter.
`MemoryCheckpointStore` and `JsonCheckpointStore` keep a cursor with the
fingerprint of what it was walked under; the JSON store replaces its file
atomically and locks it across processes. `ciaops.normalize` reads TLP,
severity, CVSS bands, API dates, refangs indicators and tells hash and
indicator kinds apart. `DRPViolationRecord`, `ASMIssue` and `ASMAsset`
read legacy DRP and ASM records with the vocabularies in
`DRPSubtype`, `DRPStatus`, `ASMSeverity` and their siblings.

## Utilities

`ParserHelper` and `Validator` also work outside the generator flow, for example on raw API responses.

```python
from ciaops.utils import ParserHelper, Validator
```

### ParserHelper

#### find_by_template

Parse a single feed `dict` against a key-mapping template. Returns a `dict` with the resolved values.

```python
feed = {
    "id": "abc123",
    "evaluation": {"severity": "high"},
    "indicators": [{"params": {"ip": "198.51.100.14"}}, {"params": {"ip": "198.51.100.58"}}]
}

keys = {
    "feed_id":  "id",
    "severity": "evaluation.severity",
    "ips":      "indicators.params.ip",
    "source":   "*Group-IB",
}

result = ParserHelper.find_by_template(feed, keys)
# {
#     "feed_id":  "abc123",
#     "severity": "high",
#     "ips":      ["198.51.100.14", "198.51.100.58"],
#     "source":   "Group-IB",
# }
```

Supported value directives:

| Directive                                                                    | Example                           | Result                                                                     |
| ---------------------------------------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------- |
| Dot-path string                                                              | `"evaluation.severity"`           | Value at that path                                                         |
| `"*literal"` (star prefix)                                                   | `"*Group-IB"`                     | The literal string `"Group-IB"`                                            |
| `"#field[N]"` (hash prefix)                                                  | `"#items[0]"`                     | Element at index N of the list found at `field`                            |
| Nested dict                                                                  | `{"ips": "indicators.params.ip"}` | Recursive template application                                             |
| `{"__nested_dot_path_to_list": "path", ...}`                                 | -                                 | Maps the inner template over each item in the list at `path`               |
| `{"__concatenate": {"static": "https://portal/?id=", "dynamic": "id"}}`      | -                                 | Concatenates a static prefix with a dynamic field value                    |
| `{"__concatenate": {"collection": "apt/threat", "dynamic": "id"}}`           | -                                 | Prefix auto-resolved from portal links for the given collection            |
| `{"__concatenate": {"parts": ["*https://portal/", "category", "*-", "id"]}}` | -                                 | Multi-part concatenation: `*` marks literals, bare strings are field paths |

Optional kwargs:

- `use_join_to_end_list=True`: joins list values into a single comma-separated string.
- `except_keys=["field"]`: excludes specific keys from the joining above.

#### find_element_by_key

Traverse any `dict` or `list` using a dot-notation path. Safe for nested lists and missing keys.

```python
from ciaops.utils import find_element_by_key

find_element_by_key({"a": {"b": 1}}, "a.b")
# -> 1

find_element_by_key({"items": [{"ip": "198.51.100.14"}, {"ip": "198.51.100.58"}]}, "items.ip")
# -> ["198.51.100.14", "198.51.100.58"]

find_element_by_key({"a": None}, "a.b")
# -> None
```

#### unpack_iocs

Recursively flattens a nested list of IoC values into a single deduplicated list. Filters out noise values (`""`, `None`, `"0.0.0.0"`, `"255.255.255.255"`). Deduplication is set-based, so the order of the result is not guaranteed.

```python
raw = [["198.51.100.14", "198.51.100.58"], ["198.51.100.14", None, "0.0.0.0"]]
ParserHelper.unpack_iocs(raw)
# -> ["198.51.100.14", "198.51.100.58"]
```

### Validator

`Validator` guards against invalid inputs before they reach the API.

```python
from ciaops.utils import Validator
```

**`validate_collection_name(collection_name, method=None)`** raises `InputException` for unknown or removed collection names. A removed collection with a replacement names it; `method` is accepted for backward compatibility and has no effect.

```python
Validator.validate_collection_name("apt/threat")        # OK
Validator.validate_collection_name("compromised/reaper")
# raises InputException: Collection 'compromised/reaper' has been removed. Use 'darkweb/forums' instead.
Validator.validate_collection_name("bp/phishing")
# raises InputException: Invalid collection name 'bp/phishing'.
```

**`validate_date_format(date, formats)`** raises `InputException` if the date string does not match any of the provided format strings.

```python
Validator.validate_date_format("2024-01-15", ("%Y-%m-%d",))   # OK
Validator.validate_date_format("15/01/2024", ("%Y-%m-%d",))   # raises InputException
```

**`validate_ips_argument(ips)`** normalizes and validates the `ips` argument for the `scoring/ip` endpoint. Accepts a single IP string or a list of IP strings; raises `InvalidIpsParameter` on invalid input. Returns a normalized list.

```python
Validator.validate_ips_argument("192.0.2.8")             # -> ["192.0.2.8"]
Validator.validate_ips_argument(["192.0.2.8", "198.51.100.11"]) # -> ["192.0.2.8", "198.51.100.11"]
Validator.validate_ips_argument("192.0.2.8,198.51.100.11")     # raises InvalidIpsParameter
```

**`validate_domains_argument(domains)`** normalizes and validates the `domains` argument for the `scoring/domain` endpoint. Accepts a single domain string or a list of domain strings; raises `InvalidDomainsParameter` on invalid input. Returns a normalized list.

```python
Validator.validate_domains_argument("example.com")               # -> ["example.com"]
Validator.validate_domains_argument(["example.com", "example.org"]) # -> ["example.com", "example.org"]
Validator.validate_domains_argument("example.com,example.org")      # raises InvalidDomainsParameter
```

<br>

## Portal Links

`TICollections.PORTAL_LINKS` and `generate_portal_link` map collection records
to their Group-IB Portal URLs.

```python
from ciaops import TICollections, generate_portal_link
```

### Simple collections (single ID in URL)

Most collections use a plain prefix + record ID pattern:

```python
link = generate_portal_link('apt/threat', record_id='abc123')
# -> "https://tap.group-ib.com/ta/last-threats?threat=abc123"

link = generate_portal_link('malware/config', record_id='def456')
# -> "https://tap.group-ib.com/malware/configs?id=def456"

link = generate_portal_link('compromised/account_group', record_id='ghi789')
# -> "https://tap.group-ib.com/cd/accounts?id=ghi789"

link = generate_portal_link('imc/incidents', record_id='11111111-1111-7111-8111-111100000701')
# -> "https://tap.group-ib.com/imc/incidents?id=11111111-1111-7111-8111-111100000701"
```

IMC incidents and DRP v2 violations have portal pages too; the prefixes are
in `IMCCollections.PORTAL_LINKS` and `DRPV2Collections.PORTAL_LINKS`, and
`generate_portal_link` reads every product's table. `IMCIncident.portal_link`
builds the link through `IMCCollections.incident_portal_link`, which
percent-encodes the id. For a portal on another host, pass `url_prefix` to
`generate_portal_link`.

Returns `None` when `record_id` is empty or the collection has no portal mapping.
The id is percent-encoded, a list id gives its first non-empty element, and
an `osi/vulnerability` id holding `:` is searched as `id:"<id>"`;
`encode=False` appends the id as given. `parse_portal_link(url)` goes the
other way: it returns the collections whose template the URL follows and the
record id in it, or `None`.

### Multi-part URL templates

Some collections require multiple fields from the feed record (e.g. `compromised/messenger`, `compromised/discord`). Pass all required field values via the `fields` dict:

```python
link = generate_portal_link(
    'compromised/messenger',
    fields={'chatStat.id': '1234', 'id': '5678'},
)
# -> "https://tap.group-ib.com/ta/im?chatId=1234&msg=5678"

link = generate_portal_link(
    'compromised/discord',
    fields={'channel.id': 'ch99', 'id': 'msg42'},
)
# -> "https://tap.group-ib.com/ta/im?collection=discord&chatId=ch99&msg=msg42"
```

Returns `None` if any required field is missing or empty.

### Custom prefix override

```python
link = generate_portal_link('my/collection', record_id='001', url_prefix='https://tap.group-ib.com/feed?id=')
# -> "https://tap.group-ib.com/feed?id=001"
```

### Embedding portal links in parsed output

Use the `__concatenate` directive in your mapping template so that `ParserHelper` resolves the URL automatically during parsing:

```python
keys = {
    'id':         'id',
    'title':      'title',
    'portal_url': {'__concatenate': {'collection': 'apt/threat', 'dynamic': 'id'}},
}
result = ParserHelper.find_by_template(feed, keys)
# result['portal_url'] -> "https://tap.group-ib.com/ta/last-threats?threat=<id>"
```

### Inspecting the TI URL map

```python
from ciaops import TICollections

for collection, template in TICollections.PORTAL_LINKS.items():
    print(collection, '->', template)
```

<br>

## Adapter utilities

`ConfigParser` and `FileHandler` are used by file-config based adapters such as the MISP adapter. They are not required for TI, DRP, ASM or IMC polling.

`FileHandler`'s YAML methods need PyYAML, an optional dependency that `pip install ciaops[misp]` installs. Without it, only the YAML methods raise `ImportError`; the JSON methods and `ConfigParser` work regardless. The `save_data_to_*` methods update an **existing** file and raise `FileNotFoundError` rather than creating one. They replace the file through a temporary file beside it, keep its permission bits, and write through a symbolic link to the file it points to.

```python
from ciaops.utils import ConfigParser, FileHandler
```

> **Note:** they live in `ciaops.utils` and are not re-exported from the
> top-level `ciaops` package. The adapters package holds `misp_adapter` and
> `opencti_adapter`.

### ConfigParser

Reads credentials and collection settings from a YAML config that `FileHandler` has already loaded into a dict.

```python
cp = ConfigParser()

# Extract credentials from a YAML config dict as a dynamic Enum
creds = cp.get_creds(yaml_config)          # reads yaml_config["creds"]
creds = cp.get_creds(yaml_config, key="auth")  # custom key

creds.USERNAME.value   # "user@example.com"
creds.API_KEY.value    # "abc123"
creds.API_URL.value    # "https://..."

# Get only enabled / disabled collections from YAML config
enabled  = ConfigParser.get_enabled_collections(yaml_config)   # ["apt/threat", ...]
disabled = ConfigParser.get_disabled_collections(yaml_config)

# Read a single collection's default_date
date = ConfigParser.get_collection_default_date(yaml_config, "apt/threat")
```

### FileHandler

A Borg-singleton file handler for reading and writing YAML and JSON config files. All instances share the same internal state, and reads and writes are serialized through a shared lock.

```python
fh = FileHandler()

# Check file existence / emptiness
fh.is_exist("/path/to/config.yml")   # True / False
fh.is_empty("/path/to/config.yml")   # True / False

# Read configs
yaml_config = fh.read_yaml_config("/path/to/config.yml")
json_config = fh.read_json_config("/path/to/mapping.json")

# Persist updated state of an enabled collection back to YAML
fh.save_collection_info(
    config="/path/to/config.yml",
    collection="apt/threat",
    seqUpdate=16172928022293,
    default_date="2024-01-15",
)

# Overwrite an entire config file
fh.save_data_to_yaml_config(data, "/path/to/config.yml")
fh.save_data_to_json_config(data, "/path/to/mapping.json")
```

<br>

## Examples

### Full program

```python
import logging
from ciaops import TIPoller
from ciaops.exception import InputException, ConnectionException, ParserException

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
...

poller = TIPoller(username=username, api_key=api_key, api_url=api_url)
try:
    poller.set_proxies(proxy_protocol=PROXY_PROTOCOL,
                       proxy_port=PROXY_PORT,
                       proxy_ip=PROXY_ADDRESS,
                       proxy_password=PROXY_PASSWORD,
                       proxy_username=PROXY_USERNAME)
    poller.set_verify(True)

    for collection, keys in keys_config.items():
        poller.set_keys(collection, keys)

    for collection, state in update_generator_config.items():
        if state.get("sequpdate"):
            generator = poller.create_update_generator(
                collection_name=collection,
                sequpdate=state.get("sequpdate"),
            )
        elif state.get("date_from"):
            sequpdate = poller.get_seq_update_dict(
                date=state.get("date_from"), collection_name=collection
            ).get(collection)
            generator = poller.create_update_generator(
                collection_name=collection, sequpdate=sequpdate
            )
        else:
            continue

        for portion in generator:
            save_portion(portion.parse_portion())
            update_generator_config[collection]["sequpdate"] = portion.sequpdate

except InputException as e:
    logging.exception("Wrong input: {0}".format(e))
except ConnectionException as e:
    logging.exception("Connection failed: {0}".format(e))
except ParserException as e:
    logging.exception("Exception occurred during parsing: {0}".format(e))
finally:
    poller.close_session()
```

<br>

## API logic

To page through a collection, use one of these two iteration methods:

- **Result ID iteration** - based on `resultId` parameter, which was retrieved from previous response.
  Uses common collection name endpoint (`apt/threat`) which is added to the base URL >>> `/api/v2/apt/threat`.
- **Sequence update iteration** - based on `seqUpdate` parameter, which was retrieved from previous response.
  Uses updated endpoint (`/updated`) after collection name (`/apt/threat`) >>> `/api/v2/apt/threat/updated`.

To search IPs, domains, hashes, emails, etc., you should follow the next logic:

- **Search logic** -
  First you should reach `/api/v2/search` endpoint with any `q` parameter >>> `/api/v2/search?q=192.0.2.8`.
  In the output response you will receive the collections that contain the search result (`192.0.2.8`).
  Use _Sequence update iteration_ as a next step to retrieve all events.

To get the latest updates on each collection events you should follow the next logic:

- **Sequence update logic** -
  first you should reach `/api/v2/sequence_list` endpoint with `date` and `collection` parameters (optional) >>> `/api/v2/sequence_list?date=2022-01-01&collection=apt/threat`.
  In the output response you will receive `seqUpdate` number, which you should use in the next request to collection `/updated` endpoint.
  Use _Sequence update iteration_ as a next step to retrieve all events.

<br>

### Sequence update logic

Most collections on the Threat Intelligence portal have an `/updated` endpoint.
And this endpoint uses updated logic based on `seqUpdate` key field, which comes from API JSON response.

The `seqUpdate` key is usually a time since the epoch as a big number, in a unit that differs by collection (`TICollections.DATE_CURSOR_SCALE` lists the measured units). On `apt/threat`, the collection in the examples below, the formula is:

```text
UTC timestamp * 10000
```

Do not compute a cursor from a date with this formula: get the `seqUpdate` for a date from the `/api/v2/sequence_list` endpoint.

#### API response

Each record carries a sequence update number; on some collections several records share one (see `tie_safe` above).
To check it you can explore JSON output and then explore each item in the `"items"` field.
Each item has a `seqUpdate` field, and the response carries a top-level `seqUpdate`, usually the last item's.
You can use it to get the next portion of feeds; on `darkweb/forums`, use the highest item `seqUpdate` instead.
Each collection has its own updated route, such as `/api/v2/apt/threat/updated`; the output below is an example.

```json
{
    "count": 1761,
    "items": [
        {"id": "fake286ca753feed3476649438e4e4488"...},
        {"id": "fake51d29357b22b80564a1d2f9fc8751"...},
        {
            "author": null,
            "companyId": [],
            "id": "fake4f16300296d20ef9b909dc0d354fb",
            ......,
            "indicators": [
                {
                    "dateFirstSeen": null,
                    "dateLastSeen": null,
                    "deleted": false,
                    "description": null,
                    "domain": "example.com",
                    "id": "fakebe483bb82759fbee7038235e0f52d0",
                    .....
                }
            ],
            "indicatorsIds": [
                "fakebe483bb82759fbee7038235e0f52d0"
            ],
            "isPublished": true,
            "isTailored": false,
            "labels": [],
            "langs": [
                "en"
            ],
            "malwareList": [],
            ......,
            "seqUpdate": 16172928022293
        },
    ],
    "seqUpdate": 16172928022293
}
```

#### Iteration steps

To iterate over `/api/v2/apt/threat/updated` endpoint data, you need to collect this
field number (`"seqUpdate": 16172928022293`) right at the top level of the JSON response,
received from previous request or from `/sequence_list` endpoint.

```console
curl -X 'GET' 'https://<base URL>/api/v2/sequence_list'
```

Add gathered `seqUpdate` in the next request, using endpoint params.

```console
curl -X 'GET' 'https://<base URL>/api/v2/apt/threat/updated?seqUpdate=16172928022293'
```

In the received JSON output check the `"count": 1751`. -> \
Gather `seqUpdate` from last feed or at top level -> \
Put it in next request ->

```console
curl -X 'GET' 'https://<base URL>/api/v2/apt/threat/updated?seqUpdate=16172928536227'
```

In the received JSON output, check the `"count": 1741` -> \
Gather `seqUpdate` from last feed or at top level -> \
Repeat till the end.

#### Stop the iteration

The "stop word" in that logic is items `"count"` or `"items"` list length.
For the collection `apt/threat` in the example above, the largest `limit` is 10;
most other collections take larger limits (see [Records limits](#records-limits)).
The limit depends on the amount of data to not overload the JSON output.
For example, you receive a portion of 10 feeds for the first iteration. ->
Then could be a portion of 3 feeds -> Then a portion of 0 feeds -> The end.

<br>

### Search logic

Search logic is used to find attribution to the search value in Threat Intelligence database.

#### Global search

To find events related to IP, domain, hash, email, etc., you should send request to the `/api/v2/search` endpoint
with any `q` parameter (`/api/v2/search?q=192.0.2.8`).
It returns a list of the collections that contain this value.
The next step is a _Sequence update iteration_ over all items in each collection.
You can specify the searchable type keyword to avoid side results by setting `q` parameter like `/api/v2/search?q=ip:192.0.2.8`.
The same can be done for domain, email, hash and other types (`/api/v2/search?q=domain:example.com`, `/api/v2/search?q=email:user@example.com`).

```json
[
    {
        "apiPath": "suspicious_ip/open_proxy",
        "label": "Suspicious IP :: Open Proxy",
        "link": "https://<base-url>/api/v2/suspicious_ip/open_proxy?q=ip:192.0.2.8",
        "count": 14,
        "time": 0.304644684,
        "detailedLinks": null
    },
    {
        "apiPath": "attacks/ddos",
        "label": "Attack :: DDoS",
        "link": "https://<base-url>/api/v2/attacks/ddos?q=ip:192.0.2.8",
        "count": 1490,
        "time": 0.389418291,
        "detailedLinks": null
    },
    {"apiPath": "attacks/deface"...},
    {"apiPath": "malware/config"...},
    {"apiPath": "suspicious_ip/scanner"...}
]

```

#### Iteration steps

The first search step reports that collection `attacks/ddos` contains 1490 items (`"count": 1490`).
To extract all of them, send a request to this collection with the `q` parameter (`?q=ip:192.0.2.8`).
Then take the top-level `"seqUpdate"` field of the JSON response and use it in the next request (`"seqUpdate": 1673373011294`).

```json
{
  "count": 1490,
  "items": [
    {
      "body": null,
      "cnc": {"cnc": "http://example.com/drv/"...},
      "company": null,
      "companyId": null,
      "dateBegin": null,
      "dateEnd": null,
      "dateReg": "2017-08-16T00:00:00+00:00",
      "evaluation": {},
      "favouriteForCompanies": [],
      "headers": [],
      "hideForCompanies": [],
      "id": "examplec58903baddc84b8c51eaef1f904374025d",
      "isFavourite": false,
      ...
    }
  ],
  ...,
  "seqUpdate": 1673373011294
}
```

So the next request should look like this `/api/v2/attacks/ddos/updated?q=ip:192.0.2.8&seqUpdate=1673373011294`.
The requests can also set the `limit` parameter, such as `limit=500`.
Explore the example below.

```console
curl -X 'GET' 'https://<base URL>/api/v2/search?q=ip:192.0.2.8'
```

Add gathered `seqUpdate` in the next request, using endpoint params.

```console
curl -X 'GET' 'https://<base URL>/api/v2/attacks/ddos/updated?q=ip:192.0.2.8&seqUpdate=1673373011294'
```

In the received JSON output check the `"count": 1390`. -> \
Gather `seqUpdate` from last feed or at top level -> \
Put it in next request ->

```console
curl -X 'GET' 'https://<base URL>/api/v2/attacks/ddos/updated?q=ip:192.0.2.8&seqUpdate=1673375930599'
```

In the received JSON output, check the `"count": 1290` -> \
Gather `seqUpdate` from last feed or at top level -> \
Repeat till the end.

#### Stop the iteration

The "stop word" in that logic is items `"count"` or `"items"` list length.
For the collection `attacks/ddos` in above example, the `limit` is set to 100 by default,
for other collections it may differ. The limit depends on the amount of data, to not overload the JSON output.
For example, usually you receive a portion of 100 feeds for the first iteration. ->
Then could be a portion of 23 feeds -> Then a portion of 0 feeds -> The end.

<br>

## Records limits

Default limit is 100 records per request. Each collection has its own largest limit, because record sizes differ.

To change the number of records in a response, add `limit` to the request,
up to the collection's limit from the Portal documentation, which
`TICollections.get_page_limit` returns: 10 on `apt/threat`, 500 on
`osi/vulnerability`, 5000 on `ioc/common`. A TI update walk asked for a
larger `limit` sends that limit instead.
`TICollections.get_recommended_page_size` gives the recommended page size of
a collection, never above that limit.

```console
curl -X 'GET' 'https://<base URL>/api/v2/apt/threat/updated?limit=10&seqUpdate=16172928022293'
```

<br>

## Recommended TTL

TTL (Time To Live) is the maximum length of time an indicator or dataset (package) can exist. Calculated in days: the period during which the data is expected to represent a valid, active IoC. Once the TTL expires the record should be considered stale and removed or re-evaluated. `None` means no expiry: the data does not have a defined lifetime and should be retained indefinitely.

| Endpoint                              | Recommended TTL (days) |
| ------------------------------------- | ---------------------- |
| **Threat Intelligence**               |                        |
| `apt/threat_actor/updated`            | 360                    |
| `darkweb/forums/updated`              | 90                     |
| `hi/threat_actor/updated`             | 360                    |
| `apt/threat/updated`                  | 360                    |
| `hi/threat/updated`                   | 360                    |
| `hi/open_threats/updated`             | None                   |
| `hi/analytic/updated`                 | None                   |
| **Malware**                           |                        |
| `malware/config/updated`              | 30                     |
| `malware/malware/updated`             | None                   |
| `malware/signature/updated`           | None                   |
| `malware/yara/updated`                | None                   |
| `malware/cnc/updated`                 | 90                     |
| **Attacks**                           |                        |
| `attacks/phishing_kit/updated`        | 30                     |
| `attacks/phishing_group/updated`      | 30                     |
| `attacks/ddos/updated`                | 30                     |
| `attacks/deface/updated`              | 30                     |
| **Vulnerabilities**                   |                        |
| `osi/vulnerability/updated`           | 30                     |
| **Compromised**                       |                        |
| `compromised/messenger/updated`       | None                   |
| `compromised/discord/updated`         | None                   |
| `compromised/access/updated`          | 90                     |
| `compromised/account_group/updated`   | 90                     |
| `compromised/breacheddb/updated`      | 90                     |
| `compromised/bank_card_group/updated` | 90                     |
| `compromised/masked_card/updated`     | 90                     |
| `compromised/spd/updated`             | 90                     |
| **OSI**                               |                        |
| `osi/public_leak/updated`             | 30                     |
| `osi/git_repository/updated`          | 30                     |
| **Suspicious IP**                     |                        |
| `suspicious_ip/tor_node/updated`      | 30                     |
| `suspicious_ip/open_proxy/updated`    | 15                     |
| `suspicious_ip/socks_proxy/updated`   | 2                      |
| `suspicious_ip/vpn/updated`           | 30                     |
| `suspicious_ip/scanner/updated`       | 15                     |
| **IoC**                               |                        |
| `ioc/common/updated`                  | 90                     |
| `ioc/primary/updated`                 | 90                     |

<br>

## Troubleshooting

### 401 response code

This code is returned when the credentials are missing or invalid. Make sure that you send the Authorization header with Basic auth, your username and an active API key.

### 403 response code

There are several possible reasons for it:

- IP limitation. Make sure that you request from an allowed IP address; the allowlist is managed on the Portal profile page, Security and Access.
- API key issue. Make sure that your API key is active and valid, or regenerate it on the Portal profile page.
- No access to the feed. Make sure that you have access to the requested feed. You can find the available feeds on the Portal profile page, Security and Access.

### 504 response code or timeout

Try a smaller `limit`, so each page is smaller. The library waits 120
seconds for a connection and, separately, for each piece of a response;
a poller takes `timeout=` (a number of seconds or a `(connect, read)`
pair) when a feed needs longer, and `send_request(timeout=...)` sets it for
one request.

## FAQ

Have a question? Open a support ticket on the Portal or write to integration@group-ib.com.
