Arodonata v2
Arodonata v2 (2.0.0) is an async-first Python 3.13+ library, declarative Policy-as-Code (CPCRUD) engine, auditable change report generator, and Streamable-HTTP Model Context Protocol (MCP) server for Check Point Security Management and Multi-Domain Security Management (MDSM).
Looking for Arodonata v1 (
1.16.0)? Legacy v1 remains frozen in this repository on branchmaster_v1and tagv1.16.0. All new projects and downstream integrations should target Arodonata v2.
Quickstart
import asyncio
from arodonata import ArodonataClient
async def main() -> None:
# Reads ARODONATA_* / MGMT_* environment variables and initializes SQLite/PostgreSQL cache
async with ArodonataClient() as client:
domains = await client.get_domains()
print(f"Discovered {len(domains)} domains: {[d.name for d in domains]}")
# Smart cache-first read across hosts in Domain4
hosts = await client.get_hosts(domain="Domain4", cache_mode="smart")
print(f"Domain4 has {len(hosts)} cached hosts")
# Multi-term search with recursive parent group resolution
search = await client.search_objects("10.1.10.50, *.internal.corp", max_depth=2)
for obj in search.objects:
print(f"Matched {obj.type} {obj.name} ({obj.uid}) in {obj.domain_name}")
asyncio.run(main())
Core Capability Matrix
| Capability | Primary Entry Point | Description |
|---|---|---|
| Unified Async Facade | ArodonataClient |
Single composition root wiring transport, SQL cache, distributed locks, rulebase numbering, CPCRUD, and change reports |
| Database-Backed Cache | DatabaseManager, SqlCacheAdapter |
17 arodonata_*-prefixed SQLModel tables on PostgreSQL (asyncpg) or SQLite (aiosqlite) with SHA-256 auto-migration and cross-process locks |
| Smart & Incremental Sync | refresh_objects, stream_refresh_* |
Four cache modes (cache, smart, smart-fast, force) with show-changes incremental diffs and parallel per-MDS-member execution |
| Search & Aggregation | search_objects, query_objects |
IP/CIDR/range/wildcard/exact search with recursive group membership traversal and SQL-free cross-domain aggregation (list, count, describe) |
| Rulebase Introspection | get_package_rulebase, filter_rulebase |
Normalized 6-table rulebase cache with exact SmartConsole hierarchical numbering (1, 2.1, 3), reverse UID lookup (locate_rules), and local filtering |
| Session Isolation & Overlay | client.write_session(...) |
Shared read-only arodonata_sid_cache sessions vs isolated WriteSession with contextvars-scoped SessionOverlay (read-your-own-writes before publish) |
| Declarative CPCRUD | client.cpcrud (CPCRUDService) |
Offline JSON Schema validation, HybridStateReader, two-axis conflict policies (on_name_conflict × on_ip_conflict), staleness guard (DomainStamp), and rollback (inverse) |
| Auditable Change Reports | build_change_report |
Collects object and rule diffs across sessions or date ranges (SessionScope, RangeScope) and renders self-contained HTML, Markdown, and JSON |
| Consolidated MCP Server | arodonata-mcp, create_mcp_server |
Streamable-HTTP MCP server exposing 13 cache-aligned core tools + 5 tamper-proof HMAC-signed CPCRUD tools for AI agents and FastAPI host apps |
| Observability & Security | @traced, redact_sid, TrustPolicy |
Provider-agnostic OpenTelemetry spans (arlogi[otel]), TOFU/pinned TLS fingerprint verification, and automatic sid/secret redaction everywhere |
Documentation Map
- Getting Started: Installation & Overview, Your First Script, and CPCRUD Quickstart.
- Downstream Integration Contract: Capabilities & Integration Guide (
CAPABILITIES.md) — mandatory reading for host applications (e.g., FPCR v2). - Architecture Deep Dives:
- User Guides & MCP:
- Configuration: Environment Variables & Settings, Multi-Server Topology, and TLS Verification (
pinned/tofu/lab-memory). - Examples (
01..12): Runnable Examples Catalog. - Development: Testing & Quality Gates (
./pytest.sh) and Changelog.
Arodonata v2: Capabilities & Downstream Integration Guide
Version: 2.0.0 · Status: Canonical Architecture Specification · Date: October 2026
1. Executive Summary & Architectural Role
Arodonata v2 is an async-first Python 3.13+ platform library, hexagonal SDK, Policy-as-Code (CPCRUD) engine, auditable change report generator, and Streamable-HTTP MCP server for Check Point Security Management and Multi-Domain Security Management (MDSM).
In the enterprise automation ecosystem (such as FPCR v2, web portals, CLIs, and AI agent platforms), Arodonata acts as the single authoritative engine for all Check Point interactions:
- Native
aiohttptransport, post-handshake SHA-256 certificate verification (pinned,tofu,lab-memory), per-MDS-member rate limiting, and70slogin throttle recovery (LoginGate). - Database-backed caching across 17
arodonata_*-prefixed SQLModel tables (PostgreSQLasyncpgand SQLiteaiosqlite) with SHA-256 schema hash auto-migration, naive UTC timestamp uniformity (tzinfo=None), and distributed locks (arodonata_distributed_locks). - Incremental (
show-changes) and full synchronization across domains, objects, services, assets (gateways/clusters/VSX), and rulebases with typed streaming progress events (SyncProgressEvent). - Isolated write sessions (
WriteSession) withcontextvars-boundSessionOverlayfor read-your-own-writes isolation prior topublish. - Declarative Policy-as-Code (
CPCRUDService): offline JSON Schema validation,HybridStateReader, two-axis conflict policies (NameConflictPolicy×IpConflictPolicy), pre-publish staleness verification (DomainStamp), staged session handoff (take-over-session), compensating rollback generation (inverse), and full lifecycle support for network objects, services,application-sitecustom URL/regex objects, groups, and rules. - Normalized 6-table rulebase cache with exact SmartConsole hierarchical rule numbering (
1,2.1,3), reverse UID lookup (locate_rules), and local rulebase filtering (filter_rulebase, includingoutput_format="cpcrud"). - Auditable change evidence collection and offline multi-format rendering (
HTML,Markdown,JSON). - Consolidated Model Context Protocol (
arodonata.mcp) server with 13 cache-aligned core tools and 5 tamper-proof HMAC-signed CPCRUD tools.
Core Architectural Principle for Downstream Consumers
"Delegate, Never Duplicate" Downstream applications MUST NOT implement custom Check Point HTTP callers, bespoke SQL cache tables for Check Point objects/rules, manual
sidsession pools, custom rulebase numbering parsers, or ad-hoc object naming algorithms. Consumer applications act strictly as business workflow orchestrators, state machines, user interfaces, and authorization/audit coordinators.
2. Capability Catalog & Consumer Contracts
| Capability Area | Canonical Arodonata v2 Module | Primary Classes / Functions | Configuration Source |
|---|---|---|---|
| Unified Facade | arodonata / arodonata.client |
ArodonataClient, ArodonataSettings |
ARODONATA_* / MGMT_* env vars |
| Storage & Locks | arodonata.adapters.storage |
DatabaseManager, SqlCacheAdapter, SqlLockAdapter, ARODONATA_TABLE_NAMES |
ARODONATA_DATABASE_URL |
| Transport & Sessions | arodonata.adapters.checkpoint |
AMgmtClient, TrustPolicy, RateLimiter, LoginGate, TaskWaiter |
ARODONATA_TLS_TRUST, ARODONATA_CONCURRENT_LIMIT |
| Contexts & Overlays | arodonata.core.context |
WriteSession, SessionOverlay, AuthContext, UserContext |
Python contextvars |
| Sync, Search & Query | arodonata.core.services |
DomainSyncCoordinator, ObjectService, ServiceCacheService, AssetRefreshService, SearchService |
CacheMode (cache, smart, smart-fast, force) |
| Rulebase & Numbering | arodonata.rulebase |
CachedRulebaseSource, RulebaseRefreshService, fetch_paged_rulebase, rule_to_cpcrud_operation |
RuleFormat (markdown, model_friendly, raw, cpcrud) |
| Declarative CPCRUD | arodonata.cpcrud |
CPCRUDService, Plan, ApplyReport, NamingPrefixes, StagedSessionInfo |
checkpoint_ops_schema.json |
| Evidence & Reports | arodonata.reports |
collect_change_report, render_change_report, build_change_report |
SessionScope, RangeScope, RenderOptions |
| MCP Integration | arodonata.mcp |
create_mcp_server, create_asgi_app, ArodonataMCPSettings |
ARODONATA_MCP_* env vars |
3. Deep-Dive: Host Application Integration Patterns
3.1 Shared AsyncEngine & Namespace Coexistence
Host applications (such as FastAPI backends using SQLAlchemy/SQLModel) can pass their existing AsyncEngine directly to ArodonataClient(engine=host_engine).
- Non-Destructive Ownership (
owns_engine=False): When an externalAsyncEngineis passed,await client.close()closes Arodonata's HTTP transport and background tasks without disposing the host application'sAsyncEngine. - Strict Table Namespace Isolation (
arodonata_*): All 17 Arodonata tables are prefixed witharodonata_(ARODONATA_TABLE_NAMES).DatabaseManager.initialize()inspects and migrates onlyarodonata_*tables, completely ignoring any host application tables registered inSQLModel.metadata(even if the host app has tables namedassets,domains, ordistributed_locks). - Naive UTC Timestamp Uniformity: All Arodonata models and database columns use naive UTC (
DateTime(timezone=False),tzinfo=Noneviato_naive_utc()andutc_now()), eliminatingasyncpgoffset-naive vs offset-awareDataErrorcrashes on PostgreSQL.
from sqlalchemy.ext.asyncio import create_async_engine
from arodonata import ArodonataClient, ArodonataSettings
engine = create_async_engine("postgresql+asyncpg://app:secret@db:5432/fpcr")
settings = ArodonataSettings()
client = ArodonataClient(settings, engine=engine)
await client.initialize()
# ... serve requests ...
await client.close() # Leaves `engine` open for the host application
3.2 Streaming Synchronization to Web UIs (SSE)
Every batch refresh method (refresh_objects, refresh_services, refresh_assets, refresh_rulebases) and CPCRUD execution (cpcrud.apply) has a paired async generator (stream_refresh_*, cpcrud.stream_apply, stream_publish_staged_session) yielding typed domain events (SyncProgressEvent, CPCRUDEvent).
To stream progress over HTTP Server-Sent Events (SSE), convert domain events at the HTTP boundary using arodonata.adapters.sse.to_sse_event:
from arodonata.adapters.sse import to_sse_event
async for event in client.stream_refresh_objects(domains=["Domain4"], mode="smart-fast"):
sse = to_sse_event(event)
yield sse.encode() # "event: ...\ndata: {...}\n\n"
3.3 Exact Search, Human-Readable Composite IDs, Cross-Domain Structured Queries, and Rule-to-CPCRUD Export
- Human-Readable Composite Identifiers (
object_id,service_id,asset_id) & Dual Topology Links:- Every cached entity carries both a collision-safe UID primary key (
id = "{mgmt_name}:{domain_name}:{uid}") and an indexed human-readable composite identifier (object_id,service_id, orasset_id = "{mgmt_name}:{domain_name}:{name}"). - Gateway, cluster, and VSX assets (
Asset/arodonata_assets) expose both UID and human-readable parent/child links (parent_uid,parent_name,parent_id,parent_asset_id,member_uids,member_asset_ids,virtual_system_uids,virtual_system_asset_ids), automatically resolving cross-domain VSX-to-Virtual-System relationships across domains on the same management server. find_object(),get_group_members(),search_objects(), andquery_objects()accept raw UIDs, object names, or composite identifiers (e.g.,"mds:Domain4:hWebHost"or"mds:VSX:VSX-Cluster-01").
- Every cached entity carries both a collision-safe UID primary key (
- Exact vs Substring Search: Pass
exact_match=Truetoawait client.search_objects(".example.com", exact_match=True)when validating whether an exact FQDN or object name exists without matching subdomains (sub.example.com). EachGroupMembershipNodeinSearchResult.membershipsincludesid,object_id,parent_uids, andparent_object_ids. - Cross-Domain Structured Queries (
query_objects): Useawait client.query_objects(types=["host", "network"], group_by=["domain_name", "type"], aggregate="count")to build dashboard summaries or filter across domains (scope_origin="local" | "global" | "all", plusobject_id,service_id,asset_id,parent_id,parent_asset_id) without writing raw SQL against cache tables. - Exporting Existing Rules to CPCRUD (
output_format="cpcrud"): Useawait client.filter_rulebase(mgmt, domain, layer="Standard Network", filter_query="10.1.10.50", output_format="cpcrud")orrule_to_cpcrud_operation(rule)to convert cached rules directly into schema-valid CPCRUD rule dicts for modification or migration.
3.4 Staged CPCRUD Sessions for Approval Workflows
When a workflow requires peer review before publishing to Check Point:
# Phase 1: Stage changes in a dedicated Check Point session without publishing
plan = await client.cpcrud.plan(template)
report = await client.cpcrud.apply(plan, no_publish=True, keep_session=True)
staged_uid = report.staged_sessions[0].session_uid
# Phase 2a: Collect a rich HTML/Markdown ChangeReport from the unpublished session!
evidence = await client.build_change_report(
[{"mgmt_name": mgmt, "domain": "Domain4", "session_uids": [staged_uid]}],
formats=["html", "markdown"],
)
# Phase 2b: After human approval, adopt via take-over-session and publish (or discard)
await client.publish_staged_session(mgmt, "Domain4", session_uid=staged_uid)
# Or on rejection:
# await client.discard_staged_session(mgmt, "Domain4", session_uid=staged_uid)
3.5 Universal Check Point Script Repository Facade
ArodonataClient exposes application-agnostic Script Repository management and execution via ScriptRepositoryService (client.script_service):
- Read-only inspection (
sid_cache):get_repository_script,list_repository_scripts, andcheck_repository_script(..., expected_body=...)inspect scripts without opening write sessions or callingpublish. - Idempotent provisioning (
WriteSession):ensure_repository_scriptnormalizes line endings (\r\n->\n), short-circuits withaction="unchanged"and zero publishes when the script body (and any explicitly suppliedcomments/color/tags) already matches, and otherwise creates/updates inside an isolatedWriteSession(or reuses an active matchingWriteSession) without pollutingSessionOverlay. - Execution (
script-type="repository"):run_repository_script(mgmt_name, script_name_or_uid, targets, *, domain=None, args=None, ...)forwards callerargsverbatim (str) or space-joined (Sequence[str]) over a dedicated non-read-only session (withoutpublishordiscard) and Base64-decodes per-targetshow-taskresults intoRepositoryScriptExecutionOutcome, mapping missing scripts or insufficient permissions toRepositoryScriptNotFoundError/RepositoryScriptPermissionError. - Route collection consumer:
TopologyService.collect_gateway_routes()consumes this layer whencprid_script_modeis"repository"or"auto", defaulting to"inline"for backward compatibility and providingcheck_route_collection_script/ensure_route_collection_script.
Database Schema Reference (17 arodonata_* Tables)
Arodonata v2 persists all cached topology, shared sessions, distributed locks, objects, services, gateway/VSX assets, gateway topology intervals, administrator topology annotations, and normalized policy rulebases across 17 SQLModel tables defined in src/arodonata/adapters/storage/tables.py (ARODONATA_TABLE_NAMES).
Both PostgreSQL (postgresql+asyncpg://) and SQLite (sqlite+aiosqlite://) are first-class supported backends.
1. Host Application Coexistence & Auto-Migration Design
Arodonata v2 is engineered to share a single database and SQLModel.metadata registry safely with host applications (such as FPCR v2):
- Strict
arodonata_Table Namespace (ARODONATA_TABLE_NAMES):- Every table owned by Arodonata is prefixed with
arodonata_(all 17 tables inARODONATA_TABLE_NAMES). DatabaseManager.initialize()inspects and migrates only tables inARODONATA_TABLE_NAMES. Any host application tables in the same database orSQLModel.metadata(such as a host app's ownassets,domains, orsid_cachetable) are never touched, altered, or dropped.
- Every table owned by Arodonata is prefixed with
- SHA-256 Schema Hash Auto-Migration (
arodonata_schema_version):DatabaseManagercomputes a deterministic SHA-256 digest (compute_schema_hash()) over the table names, column names, SQL types, primary keys, nullability, and indexes of all 17arodonata_*tables.- If the current
schema_hashis already recorded inarodonata_schema_versionand all 17 tables exist, startup skips column inspection and completes rapidly. - When the schema evolves,
_is_table_schema_incompatible()checks for breaking structural drift: primary key mismatch, orphanedNOT NULLcolumns lacking defaults, legacy timezone-awareTIMESTAMPTZcolumns, coarse column type family changes, or tightened/newly addedNOT NULLcolumns without defaults. Compatible additions use savepoint-protected (begin_nested())ALTER TABLEstatements; incompatible cache tables are dropped and recreated before recording the newschema_hash.
- Cross-Worker Migration Serialization:
- Multi-worker Uvicorn/Gunicorn startups are serialized using
SELECT pg_advisory_xact_lock(...)on PostgreSQL andBEGIN IMMEDIATEon SQLite, with a double-check ofarodonata_schema_versionafter acquiring the lock.
- Multi-worker Uvicorn/Gunicorn startups are serialized using
- Legacy v1 Table Fingerprint Cleanup:
- If upgrading an existing database from Arodonata v1,
DatabaseManagerdrops legacy unprefixeddomainsorsid_cachetables only if they contain positive v1 column fingerprints (mdm_dmnormgmt_dmn_key), guaranteeing zero risk to unprefixed host tables.
- If upgrading an existing database from Arodonata v1,
- Naive UTC Timestamp Uniformity (
DateTime(timezone=False)):- Every timestamp column in Arodonata uses
Column(DateTime(timezone=False))normalized viato_naive_utc()(tzinfo=Nonein UTC), preventingasyncpgoffset-naive vs offset-aware errors on PostgreSQL.
- Every timestamp column in Arodonata uses
- UID Primary Keys (
id) + Human-Readable Composite Identifiers (object_id,service_id,asset_id):- Check Point permits distinct objects in the same domain (or visible from
Global) to share the samenameacross different object classes (e.g., built-in objects namedemail) while having distinctuidvalues, and allows existing objects to be renamed across publishes. - Therefore,
arodonata_objects,arodonata_services, andarodonata_assetsretain a UID-based primary keyid = "{mgmt_name}:{domain_name}:{uid}"(preventing primary-key collisions and orphaned rows on rename duringsmart-fastincremental sync) while simultaneously exposing an indexed, non-unique human-readable composite identifier:CPObject.object_id(arodonata_objects.object_id):"{mgmt_name}:{domain_name}:{name}"CPService.service_id(arodonata_services.service_id):"{mgmt_name}:{domain_name}:{name}"Asset.asset_id(arodonata_assets.asset_id):"{mgmt_name}:{domain_name}:{name}"
- Rich
application-siteproperties (primary_category,url_list,urls_defined_as_regular_expression,description) are stored inarodonata_objects.raw_dataand hydrated ontoCPObjecton read. - In addition,
arodonata_assetsmaintains dual UID and human-readable parent/child topology links (parent_uid,parent_name,parent_id,parent_asset_id,member_uids,member_asset_ids,virtual_system_uids, andvirtual_system_asset_ids), supporting both intra-domain clusters and cross-domain VSX topology (where a physical VSX gateway/cluster resides in an infrastructure domain likeVSXand its Virtual Systems reside in tenant domains likeDomain4).
- Check Point permits distinct objects in the same domain (or visible from
2. Entity-Relationship Diagram (17 Tables)
3. Detailed Table Catalog
3.1 Infrastructure, Sessions & Synchronization Tables
1. arodonata_schema_version (SchemaVersionRecord)
Tracks applied SQLModel metadata SHA-256 hashes so workers skip redundant table migration inspections.
| Column | Type | Key / Index | Description |
|---|---|---|---|
schema_hash |
str |
PK |
64-char SHA-256 hex digest of the 17 arodonata_* table schemas |
applied_at |
datetime |
NOT NULL |
Naive UTC timestamp when the schema version was applied |
2. arodonata_distributed_locks (DistributedLockRecord)
Coordinates cross-process critical sections (per-domain cache refreshes, LoginGate serialization, and distributed RateLimiter slots).
| Column | Type | Key / Index | Description |
|---|---|---|---|
lock_key |
str |
PK |
Resource identifier (e.g., sync:mdsm-prod:Domain4:objects) |
owner_id |
str |
INDEX |
Unique holder token (uuid4) verified on renew() and release() |
acquired_at |
datetime |
NOT NULL |
Naive UTC acquisition timestamp |
expires_at |
datetime |
INDEX, NOT NULL |
Naive UTC expiration timestamp (periodically extended by background heartbeat) |
3. arodonata_sid_cache (SIDCacheRecord)
Persistent shared read-only Check Point session store. Strictly omits sid from __repr__ and __str__.
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
Composite key "{mgmt_name}:{domain_name}:{auth_identity}" (or "{mgmt_name}:{domain_name}" when auth_identity is None) |
mgmt_name |
str |
INDEX |
Management server logical name |
domain_name |
str |
INDEX |
Normalized domain name ("System Data" / SYSTEM_DOMAIN_KEY for SMS or MDS system domain) |
sid |
str |
repr=False |
Check Point session token (redacted in all representations) |
server_ip |
str |
NOT NULL |
Active CMA or MDS IP where this session resides |
session_uid |
str | None |
— | Check Point session UID from login response |
auth_identity |
str | None |
— | Non-secret AuthContext.identity_key ("{principal}:{24-char-hmac-sha256}") bound to the credential |
created_at |
datetime |
NOT NULL |
Naive UTC creation timestamp |
last_used_at |
datetime |
NOT NULL |
Naive UTC last API call timestamp |
expires_at |
datetime | None |
— | Naive UTC local expiry (last_used_at + session_expire_seconds) |
4. arodonata_domain_sync_state (DomainSyncStateRecord)
Unified synchronization state tracker per (mgmt_name, domain_name, scope, item_type). Updated atomically inside the same database transaction as cache data writes.
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
Composite key "{mgmt_name}:{domain_name}:{scope}:{item_type}" |
mgmt_name |
str |
INDEX |
Management server logical name |
domain_name |
str |
INDEX |
Domain name |
scope |
str |
INDEX |
"domains", "objects", "services", "assets", "rulebase", or "topology" |
item_type |
str |
INDEX |
Specific type (e.g., "host", "service-tcp") or "*" for whole-scope syncs |
last_published_at |
datetime | None |
— | Domain's show-last-published-session timestamp (None if never published) |
last_session_uid |
str | None |
— | Last published Check Point session UID (used for show-changes from-session and HybridStateReader) |
synced_at |
datetime | None |
— | Naive UTC timestamp of the last successful sync |
status |
str |
— | "idle", "syncing", "ok", or "failed" |
object_count |
int |
— | Count of cached rows for this (scope, item_type) slice |
last_error |
str | None |
— | Sanitized (redact_sid) error message if the last sync failed |
3.2 Topology, Objects, Services & Assets Tables
5. arodonata_domains (DomainRecord)
Cached MDSM/SMS domain topology discovered via show-domains (plus synthesized Global domain on MDSM).
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
"{mgmt_name}:{name}" |
mgmt_name |
str |
INDEX |
Management server logical name |
uid |
str |
INDEX |
Check Point domain UID |
name |
str |
INDEX |
Domain name (e.g., "Domain4", "Global", "System Data") |
domain_type |
str |
— | "domain", "global" / "global-domain" / "global domain", or "smc-user" |
active_ip |
str | None |
— | Active CMA IPv4/IPv6 address |
active_mds_ip |
str | None |
INDEX |
Hosting MDS member IP (used to group per-MDS-member sync concurrency) |
standby_ips |
list[str] (JSON) |
NOT NULL |
Standby CMA IPs for automatic failover |
servers |
list[dict] (JSON) |
NOT NULL |
Full CMA server entries from Check Point API |
is_global |
bool |
INDEX |
True for the MDSM Global domain |
raw_data |
dict (JSON) |
NOT NULL |
Full sanitized API payload |
updated_at |
datetime |
NOT NULL |
Naive UTC update timestamp |
6. arodonata_objects (CPObjectRecord)
Cached network objects (host, network, address-range, group, dns-domain, application-site, etc.).
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
"{mgmt_name}:{domain_name}:{uid}" |
object_id |
str |
INDEX |
Human-readable composite key "{mgmt_name}:{domain_name}:{name}" |
uid |
str |
INDEX |
Check Point object UID |
name |
str |
INDEX |
Object name |
type |
str |
INDEX |
Canonical object type ("host", "network", "address-range", "group", "dns-domain", "application-site") |
mgmt_name, domain_name |
str |
INDEX |
Server and domain context |
original_domain |
str | None |
INDEX |
Owning domain reported by Check Point (domain.name inside raw_data, distinguishing local vs Global objects) |
ipv4_address, ipv6_address |
str | None |
INDEX (ipv4) |
Host IPv4 / IPv6 address |
subnet4, mask_length4, subnet_mask |
str / int |
INDEX (subnet4) |
Network CIDR subnet and mask |
ipv4_address_first, ipv4_address_last |
str | None |
— | Address range bounds |
fqdn, is_sub_domain |
str / bool |
INDEX (fqdn) |
DNS domain FQDN and subdomain flag |
members |
list[str] (JSON) |
NOT NULL |
Member UIDs for group objects |
comments, color, tags, nat_settings |
str / JSON |
NOT NULL (comments, tags, nat_settings) |
Metadata, tag names, and automatic NAT settings |
raw_data, updated_at |
JSON / datetime |
NOT NULL |
Full API payload (hydrating application-site URLs/categories) and naive UTC timestamp |
7. arodonata_services (CPServiceRecord)
Dedicated cache table for service objects (service-tcp, service-udp, service-icmp, service-group, and on-demand service-other, service-sctp, service-dce-rpc, service-rpc, service-icmp6, service-citrix-tcp, service-compound-tcp, service-gtp).
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
"{mgmt_name}:{domain_name}:{uid}" |
service_id |
str |
INDEX |
Human-readable composite key "{mgmt_name}:{domain_name}:{name}" |
uid, name, type |
str |
INDEX |
Service UID, name, and canonical type |
mgmt_name, domain_name, original_domain |
str |
INDEX |
Server, domain, and owning domain |
port, protocol |
str | None |
INDEX |
Port/range string (e.g., "443", "8080-8090") and protocol |
icmp_type, icmp_code |
int | None |
— | ICMP type and code |
members |
list[str] (JSON) |
NOT NULL |
Member service UIDs for service-group |
session_timeout, match_for_any |
int / bool |
— | Service session timeout and match-for-any flag |
comments, tags, raw_data, updated_at |
str / JSON / datetime |
NOT NULL |
Metadata, tag names, raw payload, and naive UTC timestamp (color is nullable) |
8. arodonata_assets (AssetRecord)
Cached gateways, clusters, cluster members, VSX gateways/clusters/virtual systems, and management servers, enriched with parent/child topology links by ClusterRelationshipManager and VSXRelationshipManager.
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
"{mgmt_name}:{domain_name}:{uid}" |
asset_id |
str |
INDEX |
Human-readable composite key "{mgmt_name}:{domain_name}:{name}" |
uid, name, type |
str |
INDEX |
Asset UID, name, and type (simple-gateway, CpmiGatewayCluster, CpmiClusterMember, vsx-gateway, vsx-cluster-netobj, virtual-system, etc.) |
mgmt_name, domain_name |
str |
INDEX |
Server and domain context |
ipv4_address, ipv6_address |
str | None |
INDEX (ipv4) |
Management IPv4 / IPv6 address |
version, os_name, hardware, sic_status |
str | None |
— | Check Point version (e.g. "R82"), Gaia OS, appliance model, and SIC trust status |
parent_uid, parent_name |
str | None |
INDEX (parent_uid) |
Parent cluster or VSX container UID and name |
parent_id, parent_asset_id |
str | None |
INDEX |
Parent composite UID key ("{mgmt_name}:{parent_domain}:{parent_uid}") and human-readable key ("{mgmt_name}:{parent_domain}:{parent_name}") |
member_uids, member_asset_ids |
list[str] (JSON) |
NOT NULL |
Child cluster member UIDs and human-readable asset_id values |
virtual_system_uids, virtual_system_asset_ids |
list[str] (JSON) |
NOT NULL |
Child VSX virtual system UIDs and human-readable asset_id values |
interfaces |
list[dict] (JSON) |
NOT NULL |
Normalized network interfaces (name, ipv4-address, ipv4-network-mask, topology) |
network_security_blades |
dict (JSON) |
NOT NULL |
Enabled software blades (firewall, ips, url-filtering, anti-bot, etc.) |
comments, raw_data, updated_at |
str / JSON / datetime |
NOT NULL |
Metadata, raw payload, and naive UTC timestamp (color is nullable) |
3.3 Normalized Rulebase Cache Tables (SmartConsole-in-SQL)
Arodonata v2 normalizes policy packages, layers, section headers, and rules across 7 dedicated tables so SmartConsole hierarchical rule numbers (1, 2.1, 3), inline layers, and Global domain placeholders can be queried and filtered locally in milliseconds without hitting the Check Point API.
9. arodonata_rulebase_package_layer (RulebasePackageLayerRecord)
Links each policy package (package_uid, package_name) to its ordered access, HTTPS, threat, and NAT layers (layer_uid, layer_name, rulebase_type, position).
10. arodonata_rulebase_layer (RulebaseLayerRecord)
Stores every access, HTTPS, and threat layer (uid, name, rulebase_type), including inline layers (parent_layer_uid, parent_rule_uid), is_global, shared, and implicit_cleanup_action ("Drop" or "Accept").
11. arodonata_rulebase_section (RulebaseSectionRecord)
Stores rulebase section headers (layer_uid, uid, name, position, from_rule, to_rule, and ordered rule_uids list) stitched cleanly across 100-rule API pagination boundaries.
12. arodonata_rulebase_access (AccessRuleRecord)
Stores access-control rules (layer_uid, section_uid, uid, name, position, rule_number, enabled, action, inline_layer_uid, inline_layer_name, placeholder_domain_layer_uid, source, destination, service, source_negate, destination_negate, service_negate, track, install_on, comments, raw_data).
13. arodonata_rulebase_nat (NatRuleRecord)
Stores NAT rules (package_uid, package_name, section_uid, uid, name, position, rule_number, enabled, method, auto_generated, original_source, original_destination, original_service, translated_source, translated_destination, translated_service, install_on, comments, raw_data).
14. arodonata_rulebase_https (HttpsRuleRecord)
Stores HTTPS inspection rules (layer_uid, section_uid, uid, name, position, rule_number, enabled, action, inline_layer_uid, source, destination, service, site_category, certificate, track, install_on, comments, raw_data).
15. arodonata_rulebase_threat (ThreatRuleRecord)
Stores Threat Prevention rules (layer_uid, section_uid, uid, name, position, rule_number, enabled, action, protected_scope, source, destination, service, track, install_on, comments, raw_data).
3.4 Gateway Topology & Annotation Tables
16. arodonata_gateway_topology (GatewayTopologyRecord)
Stores pre-expanded 64-bit integer IPv4 topology intervals ([ip_first_int..ip_last_int]) behind gateway and Virtual System interfaces from static topology extraction, VPN encryption domains, VSX provisioning routes, and live CLI routing tables (21 columns, 11 indexes).
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
Composite key "{mgmt_name}:{domain_name}:{gateway_uid}:{interface_name}:{source_type}:{cidr_or_range}" |
mgmt_name, domain_name |
str |
INDEX |
Server and domain context |
gateway_id, gateway_asset_id |
str |
INDEX |
Gateway UID key ("{mgmt_name}:{domain_name}:{gateway_uid}") and human-readable key ("{mgmt_name}:{domain_name}:{gateway_name}") |
gateway_uid, gateway_name |
str |
INDEX |
Enforcing gateway/cluster/VS UID and name |
gateway_type |
str |
NOT NULL |
Gateway asset type (default "simple-gateway") |
interface_name |
str |
INDEX |
Gateway interface name (eth0, bond0.10, wrp128) |
interface_ipv4, interface_mask_length |
str | int | None |
— | Primary IPv4 and mask prefix length of the interface |
topology_zone |
str |
INDEX |
"internal", "external", or "dmz" |
leads_to_dmz |
bool |
NOT NULL |
Whether Check Point marks this interface as leading to a DMZ |
anti_spoofing_mode |
str |
NOT NULL |
"prevent", "detect", "off", or "unknown" |
source_type |
str |
INDEX |
"interface_connected", "interface_specific", "external_interface", "vpn_domain", "vs_static_route", "gaia_static_route", "bgp_route", "ospf_route", "kernel_route", or "manual" |
source_ref, cidr_or_range |
str |
NOT NULL |
Backing Check Point group/object/route reference and CIDR or IP range string |
ip_first_int, ip_last_int |
int (BigInteger) |
INDEX, NOT NULL |
Unsigned 32-bit IPv4 start/end stored as 64-bit integer for portable SQL interval queries |
prefix_len |
int |
NOT NULL |
Effective prefix specificity (/0../32) for longest-prefix matching |
updated_at |
datetime |
NOT NULL |
Naive UTC update timestamp |
17. arodonata_topology_annotations (TopologyAnnotationRecord)
Stores persistent administrator overrides (ignore, standby_dynamic), static-topology trust hints, and IPAM site/zone metadata preserved across full force topology refreshes (15 columns, 7 indexes).
| Column | Type | Key / Index | Description |
|---|---|---|---|
id |
str |
PK |
Composite annotation key scoped by server, domain, gateway, interface, and CIDR |
mgmt_name, domain_name |
str |
INDEX |
Server and domain context |
gateway_uid, gateway_name |
str |
INDEX |
Target gateway UID and optional name |
interface_name |
str |
INDEX |
Target interface name or "*" wildcard |
cidr_or_range |
str |
INDEX |
Target CIDR/IP range or "*" wildcard |
trust_static_topology |
bool | None |
— | Optional confidence override trusting static topology over live routing conflicts |
disposition |
str | None |
INDEX |
Optional "ignore" (suppresses interface from matching) or "standby_dynamic" |
topology_zone |
str | None |
— | Optional zone override ("internal", "external", "dmz") |
zone, site, comment |
str |
NOT NULL |
Organizational zone/site metadata and administrator note |
custom_metadata |
dict (JSON) |
NOT NULL |
Extensible JSON metadata exported alongside prefixes (export_topology_prefixes()) |
updated_at |
datetime |
NOT NULL |
Naive UTC update timestamp |
Model Context Protocol (MCP) Server & Consolidated Tool Surface
Arodonata v2 includes a production-hardened Streamable-HTTP Model Context Protocol (MCP) server (arodonata[mcp]) that can run either as a standalone CLI (arodonata-mcp) or embedded as an ASGI sub-application (create_mcp_server, create_asgi_app) inside a FastAPI or Starlette host.
1. Consolidated Tool Surface Optimization (v2 Architecture)
In Arodonata v2, the MCP tool surface was redesigned and consolidated into 13 cache-aligned core tools (plus 5 opt-in tamper-proof CPCRUD tools when ARODONATA_MCP_CPCRUD=true).
Why We Consolidated the MCP Tools
Early MCP servers often expose dozens of 1-to-1 wrappers over raw Check Point API endpoints (show-hosts, show-networks, show-access-layers, show-packages, etc.). That causes three major problems for LLM agents:
- Tool Selection Ambiguity & Context Bloat: Too many overlapping tool schemas consume thousands of prompt tokens and cause models to pick the wrong endpoint.
- Unbounded Output Overflow: Raw Check Point API calls or unanchored substring searches on large enterprise domains return thousands of objects and blow up the LLM context window.
- N+1 API Round-Trips: Answering questions like "How many hosts and networks exist per domain?" or "What packages and layers exist in Domain4?" previously required dozens of sequential tool calls.
Arodonata v2 solves all three problems with progressive disclosure, multi-table unified lookup, SQL-free cached aggregation, and hybrid cache/live execution:
| Tool Category | Tool Name | Optimization & Key Capabilities |
|---|---|---|
| Collection Listing | list_domains |
Lists discovered domains (arodonata_domains) with active_ip, active_mds_ip, standby_ips, is_global, source, and cache_age_seconds |
| Collection Listing | list_objects |
Lists cached network objects (host, network, address-range, group, dns-domain) with id, object_id, pagination (from, to, total), and type normalization |
| Collection Listing | list_services |
Lists cached services (arodonata_services with id and service_id), accepting both short ("tcp", "udp", "icmp", "group") and canonical ("service-tcp", etc.) types filters |
| Collection Listing | list_assets |
Lists cached gateways, clusters, cluster members, VSX gateways/virtual systems, and management servers (arodonata_assets with id, asset_id, parent_id, parent_asset_id, member_asset_ids, virtual_system_asset_ids), with optional parent UID/name/asset_id filtering |
| Multi-Table Entity Lookup | show_object |
Searches across arodonata_objects, arodonata_services, arodonata_assets (including gateway interfaces, network_security_blades, member_uids, member_asset_ids, virtual_system_asset_ids), and arodonata_rulebase_layer / package_layer by UID, exact name, or composite ID (object_id/service_id/asset_id) using 3-tier matching (exact, strict wildcard via fnmatchcase, and paginated substring_candidates fallback) |
| Structured Analytics | query_objects |
Executes cross-domain filtering (name_pattern, ip_subnet, port, protocol, tags, scope_origin="all"|"local"|"global", object_id, service_id, asset_id, parent_id, parent_asset_id), group_by, and aggregation (aggregate="list"|"count"|"describe") over cached SQL tables in a single tool call |
| Cache Management | cache_control |
Unified cache inspection (action="status", returning per-domain/per-type freshness from arodonata_domain_sync_state) and scoped refresh (action="refresh", scope="domains"|"objects"|"services"|"assets"|"rulebase") |
| Search & Membership | search_objects |
Multi-term IP/CIDR/range/wildcard/UID/composite-ID/name search with exact_match: bool = False and recursive parent group resolution (max_depth, including object_id and parent_object_ids) |
| Search & Membership | get_group_members |
Expands direct or recursive members of a network group, service-group, gateway cluster (member_uids / member_asset_ids), or VSX container (virtual_system_uids / virtual_system_asset_ids, including cross-domain Virtual Systems) by UID, name, or composite ID |
| Policy & Rulebase | show_rulebase |
Catalog + Rulebase Hybrid: when package and layer are omitted (or unmatched), returns the domain's cached packages and layers catalog! When specified, evaluates filter locally against cached rules/objects/services (markdown, model_friendly, raw, cpcrud) or switches to live API when show_hits / cache_mode="live" is used |
| Policy & Rulebase | locate_rules |
Resolves rule UIDs or layer UIDs into exact SmartConsole hierarchical rule numbers (1, 2.1) and package/layer paths across a domain |
| Audit & Compliance | change_report |
Collects and renders auditable session change reports (SessionScope or RangeScope) in markdown, json, or html with full sid redaction |
| Escape Hatch | api_call |
Executes direct Check Point Web API commands (where-used, show-sessions, verify-policy). Enforces a strict read-only command allowlist when ARODONATA_MCP_ALLOW_WRITE_API=false, and isolates allowed write calls in a dedicated session |
| Opt-in CPCRUD | cpcrud_validate |
Offline JSON Schema validation of declarative CPCRUD templates (ARODONATA_MCP_CPCRUD=true) |
| Opt-in CPCRUD | cpcrud_plan |
Generates a deterministic CPCRUD Plan signed with an in-memory HMAC-SHA256 key (plan_signature + plan_id) |
| Opt-in CPCRUD | cpcrud_apply |
Verifies the plan_id or HMAC plan_signature (rejecting model-forged or modified plans), executes inside an isolated WriteSession, and supports staging (no_publish=True, keep_session=True) |
| Opt-in CPCRUD | cpcrud_inverse |
Generates a compensating rollback template from a verified Plan and ApplyReport |
| Opt-in CPCRUD | cpcrud_staged_session |
Adopts a staged session (session_uid) via take-over-session and either publishes (action="publish", invalidating domain cache) or discards (action="discard") cleanly |
2. Deep-Dive into Key Tool Behaviors
2.1 Three-Tier Matching in show_object
When an LLM calls show_object(uid_or_name=..., mgmt_name=..., domain=..., obj_type=None, limit=20, offset=0):
- Tier 1 — Exact Match (
match_type="exact"):- If
uid_or_namecontains no*or?wildcards and matches an exact UID or case-insensitive name inarodonata_objects,arodonata_services,arodonata_assets, orarodonata_rulebase_layer/arodonata_rulebase_package_layer,show_objectreturns that single entity with full details (including gatewayinterfaces,network_security_blades,member_uids, andvirtual_system_uids).
- If
- Tier 2 — Strict Explicit Wildcard (
match_type="wildcard"):- If
uid_or_namecontains*or?(e.g."web-*-prod"or"*.example.com"), it evaluates anchoredfnmatchcasestrictly against the pattern without adding implicit leading/trailing wildcards. Iftotal == 1, it returns the full object; iftotal > 1, it returns a paginated candidate slice (limitdefault20, max500).
- If
- Tier 3 — Paginated Substring Candidate Fallback (
match_type="substring_candidates"):- If
uid_or_namehas no wildcard and no exact match exists in cache, instead of failing with a bare"not found"error or dumping thousands of objects,show_objectsearches for case-insensitive substring matches across cached names and returns up tolimit(20) compact candidate summaries (uid,name,type,domain_name,summary) withfrom,to, andtotalso the LLM can pick the exact object on the next turn.
- If
2.2 Progressive Disclosure via query_objects & show_rulebase
- Schema & Inventory Discovery (
query_objects(aggregate="describe")):- Calling
query_objects(mgmt_name="mdsm-prod", aggregate="describe")returns all available domains, per-type object/service/asset counts, and the exact list of filterable and groupable fields (domain_name,type,original_domain,color,protocol,port, etc.).
- Calling
- Cross-Domain Counting (
query_objects(aggregate="count", group_by=["domain_name", "type"])):- Counts objects and services across all domains in a single SQL query, supporting
scope_origin="local"(domain-owned only) vs"global"(original_domain == "Global").
- Counts objects and services across all domains in a single SQL query, supporting
- Guided Rulebase Discovery (
show_rulebase):- Calling
show_rulebase(mgmt_name="mdsm-prod", domain="Domain4")withoutpackageorlayer(or with a misspelled layer name) automatically returns"mode": "catalog"containing all cachedpackages(arodonata_rulebase_package_layer) andlayers(arodonata_rulebase_layer, including inline layers andimplicit_cleanup_action).
- Calling
2.3 Pre-Login Domain Validation & Actionable ToolFailure
Every domain-scoped MCP tool validates domain against the cached arodonata_domains table (triggering a single domain-list refresh on cache miss) before attempting any Check Point login. If an invalid domain name is passed, the tool returns an actionable error listing the valid domain names on that server instead of triggering unnecessary failed logins.
3. Running & Embedding the MCP Server
3.1 Standalone CLI (arodonata-mcp)
# Start with static bearer token authentication (default)
export ARODONATA_MCP_AUTH_MODE=static
export ARODONATA_MCP_TOKEN_VARS=TEAM_ALPHA_MCP_TOKEN
export TEAM_ALPHA_MCP_TOKEN="a-very-long-random-secret-token-at-least-32-chars"
uv run arodonata-mcp --host 127.0.0.1 --port 8000 --path /mcp
3.2 Embedding in FastAPI / Starlette (create_mcp_server & create_asgi_app)
See examples/12_mcp_embedded.py for a complete runnable example mounting Arodonata's MCP server inside a FastAPI application with custom host-level tools:
from contextlib import asynccontextmanager
from fastapi import FastAPI
from arodonata import ArodonataClient, ArodonataMCPSettings, create_asgi_app, create_mcp_server
client = ArodonataClient()
mcp_settings = ArodonataMCPSettings(auth_mode="host", path="/mcp")
mcp_server = create_mcp_server(client, mcp_settings=mcp_settings)
mcp_asgi = create_asgi_app(client, mcp_settings=mcp_settings, server=mcp_server)
@asynccontextmanager
async def lifespan(app: FastAPI):
async with client, mcp_asgi.lifespan(app):
yield
app = FastAPI(lifespan=lifespan)
app.mount("/mcp", mcp_asgi)
4. MCP Configuration & Security Reference (ArodonataMCPSettings)
| Env Variable | Type | Default | Description |
|---|---|---|---|
ARODONATA_MCP_HOST |
str |
"127.0.0.1" |
Bind address for standalone arodonata-mcp |
ARODONATA_MCP_PORT |
int |
8000 |
Bind TCP port (1..65535) |
ARODONATA_MCP_PATH |
str |
"/mcp" |
Streamable-HTTP mount path |
ARODONATA_MCP_AUTH_MODE |
"static" | "host" | "jwt" | "none" |
"static" |
Authentication mode ("host" and "jwt" are for embedded ASGI mode only; standalone CLI exits with code 2 if used) |
ARODONATA_MCP_TOKEN_VARS |
list[str] (CSV) |
[] |
Env var names holding bearer tokens (>= 32 chars); each var name becomes client_id in UserContext |
ARODONATA_MCP_TOKENS |
list[str] (CSV) |
[] |
Direct "client_id=secret", "client_id:secret", or bare base64 token secrets (>= 32 chars; safe with trailing = base64 padding) |
ARODONATA_MCP_ENABLE_DNS_REBINDING_PROTECTION |
bool |
True |
Enforces Host (HTTP 421) and Origin (HTTP 403) header allowlists |
ARODONATA_MCP_ALLOWED_HOSTS |
list[str] (CSV) |
127.0.0.1:*,localhost:*,[::1]:* |
Permitted Host headers (validates numeric ports on wildcard :port patterns) |
ARODONATA_MCP_ALLOWED_ORIGINS |
list[str] (CSV) |
http(s)://localhost:*, 127.0.0.1:* |
Permitted browser Origin headers |
ARODONATA_MCP_ALLOW_WRITE_API |
bool |
False |
When False, api_call permits only the explicit read-only allowlist (show-*, where-used, verify-policy); when True, mutating calls run in an isolated dedicated session |
ARODONATA_MCP_CPCRUD |
bool |
False |
Registers the 5 tamper-proof HMAC-signed CPCRUD tools (cpcrud_validate, cpcrud_plan, cpcrud_apply, cpcrud_inverse, cpcrud_staged_session) |
ARODONATA_MCP_ALLOW_INSECURE_UNAUTHENTICATED |
bool |
False |
Explicit opt-in required to pair ARODONATA_MCP_AUTH_MODE=none with non-loopback host, disabled DNS rebinding protection, wildcard or non-loopback allowlist entries, allow_write_api=true, or cpcrud=true (emits a SECURITY WARNING) |
ARODONATA_MCP_TOOL_RATE_LIMIT_PER_MINUTE |
int |
120 |
Sliding-window per-caller (client_id[:user_id]) tool invocation limit per minute across all MCP tools (0 disables enforcement) |
ARODONATA_MCP_LIVE_TOOL_RATE_LIMIT_PER_MINUTE |
int |
30 |
Stricter per-caller sliding-window limit per minute for live/mutating tools, cold/stale smart syncs, domain-miss refreshes, and show_object live fallbacks (0 disables enforcement) |
ARODONATA_MCP_JSON_RESPONSE |
bool |
False |
Return JSON responses instead of SSE streams on Streamable-HTTP POST |
ARODONATA_MCP_STATELESS_HTTP |
bool |
False |
Enable stateless Streamable-HTTP mode per request (recommended when serving multiple identities over one auth_mode="host" endpoint) |
ARODONATA_MCP_SERVER_NAME |
str |
"arodonata-mcp" |
Server identifier reported in MCP initialization |
4.1 Security, Multi-Tenant Isolation & Quota Semantics
- Service-Account Server-Wide Visibility Trust Boundary: The MCP server authenticates callers at the HTTP/ASGI boundary (
client_id[:user_id]), while backend Check Point queries execute using theArodonataClientservice account's configuredmgmt_namesand domain permissions. Do not expose a single shared MCP endpoint to mutually untrusted tenants expecting per-domain Check Point RBAC partitioning; run separate service-account-scoped MCP instances or enforce domain filtering in an enclosing host gateway. - Embedded
auth_mode="host"Middleware: When embedding viacreate_asgi_app(..., auth_mode="host"), the enclosing host ASGI middleware MUST bindUserContexton every incoming HTTP request. For multi-tenant hosts handling varying caller identities over one Streamable-HTTP mount, configurestateless_http=Trueso each request executes with its ownUserContextrather than inheriting the opening session's context. - Per-Caller CPCRUD Isolation:
cpcrud_plan,cpcrud_apply,cpcrud_inverse, andcpcrud_staged_sessionscope HMAC signatures,plan_store,last_report, andstaged_session_storestrictly by resolved caller identity (client_id[:user_id]). Ifstaged_session_storeexceedsMAX_STORED_PLANS, same-caller sessions are evicted before other callers' entries, cleanly discarded, and logged out with a SID-redactedWARNING. - Smart-Sync Live Quotas: Cached reads served from fresh warm cache (
cache_mode="cache"orcache_mode="smart"withincache_ttl) consume onlytool_rate_limit_per_minute, while cold/stalesmartsyncs, domain-list cache misses, multi-scope/composite-ID syncs, proportional domain/scope fan-out (cache_control,change_report), andshow_objectlive fallbacks chargelive_tool_rate_limit_per_minute.
Getting Started
Arodonata v2 requires Python 3.13+ and uses asynchronous I/O (asyncio, aiohttp, SQLAlchemy 2.0+ async engine) across all operations.
Installation
Install arodonata using uv (recommended) or pip:
# Core SDK (includes SQLite cache via aiosqlite, CPCRUD, rulebase, and change reports)
uv add arodonata
# Recommended: install with all optional extras (PostgreSQL asyncpg, MCP server, OpenTelemetry)
uv add "arodonata[all]"
Optional Extras
You can install individual extras depending on your deployment environment:
| Extra | Command | Installed Packages | Purpose |
|---|---|---|---|
postgres |
uv add "arodonata[postgres]" |
asyncpg>=0.30.0 |
PostgreSQL database cache & distributed locks |
mcp |
uv add "arodonata[mcp]" |
mcp>=1.2.0, starlette, uvicorn |
Standalone arodonata-mcp CLI and embeddable ASGI MCP server |
otel |
uv add "arodonata[otel]" |
arlogi[otel]>=0.1.0 |
OpenTelemetry span export and structured trace correlation |
all |
uv add "arodonata[all]" |
All of the above | Full production feature set |
Minimal Environment Configuration
Arodonata never loads .env files implicitly on import; your application (or CLI) loads environment variables explicitly (for example via python-dotenv or container orchestration) or passes typed arguments to ArodonataSettings.
Create a .env file for a single management server or MDSM server:
# Management server topology
ARODONATA_MGMT_NAMES=mdsm-prod
ARODONATA_MGMT_SERVERS=192.0.2.10:443
ARODONATA_API_KEYS=your-checkpoint-api-key
# Persistent cache (SQLite file or PostgreSQL URL)
ARODONATA_DATABASE_URL=sqlite+aiosqlite:///./arodonata_cache.db
# Or PostgreSQL:
# ARODONATA_DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/arodonata
# TLS certificate verification mode: pinned | tofu | lab-memory
ARODONATA_TLS_TRUST=tofu
Next Steps
- Your First Script — Initialize
ArodonataClient, query cached domains/objects/gateways, and useWriteSessionwithSessionOverlay. - CPCRUD Quickstart — Validate, plan, apply, and roll back declarative YAML/JSON policy templates.
- MCP Server Guide — Run
arodonata-mcpor mount the consolidated MCP tool surface inside FastAPI.
Your First Script
Every interaction in Arodonata v2 goes through ArodonataClient. It manages the database schema, connection pools, session lifecycle, rate limiting, and domain cache synchronization.
1. Read-Only Queries & Smart Caching
When you enter async with ArodonataClient() as client:, Arodonata automatically:
- Verifies and migrates the 17
arodonata_*tables in your SQLite or PostgreSQL database (DatabaseManager.initialize()). - Schedules non-blocking cleanup of any orphaned idle Arodonata read sessions (
changes == 0andlocks == 0). - Disposes owned connections cleanly on exit (preserving persistent
arodonata_sid_cacherows across CLI runs when using a file-backed SQLite or PostgreSQL database).
import asyncio
from dotenv import load_dotenv
from arodonata import ArodonataClient
async def main() -> None:
load_dotenv(".env")
async with ArodonataClient() as client:
# 1. Discover domains on all configured management servers
domains = await client.get_domains(include_global=True)
for dom in domains:
print(f"{dom.mgmt_name} / {dom.name} (active IP: {dom.active_ip}, global: {dom.is_global})")
# 2. Fetch hosts, networks, and services using smart cache synchronization
hosts = await client.get_hosts(domain="Domain4", cache_mode="smart")
networks = await client.get_networks(domain="Domain4", cache_mode="smart")
services = await client.get_services(domain="Domain4", types=["tcp", "udp"], cache_mode="smart")
print(f"Loaded {len(hosts)} hosts, {len(networks)} networks, {len(services)} services")
# 3. Inspect gateways, clusters, and VSX topology (with human-readable asset_id & parent_asset_id)
gateways = await client.get_gateways(domain="Domain4", cache_mode="smart")
for gw in gateways:
print(
f"Asset: {gw.asset_id} ({gw.type}) IP={gw.ipv4_address} "
f"parent={gw.parent_asset_id} members={gw.member_asset_ids}"
)
if __name__ == "__main__":
asyncio.run(main())
2. Understanding cache_mode
All read and refresh methods accept a CacheMode:
"cache": Read strictly from the local SQL database (0network calls)."smart"(default): Probesshow-last-published-sessionwhen the domain TTL (cache_ttl, default300s) expires; reloads from the API only if a newer publish occurred."smart-fast": Like"smart", but fetches only incremental deltas viashow-changes(preferringfrom-sessionover UTCfrom-date), falling back to a full type reload if changes exceedmax_incremental_changes(500)."force": Unconditionally reloads the requested scope from the Check Point API and atomically updates the SQL cache.
3. Isolated Writes & Read-Your-Own-Writes (SessionOverlay)
Never mutate objects on the shared read-only session. Instead, open an isolated client.write_session(mgmt_name, domain) or call high-level mutation helpers (add_object, set_object, delete_object):
async with ArodonataClient() as client:
mgmt = client.settings.mgmt_names[0]
# Opens a dedicated Check Point session outside arodonata_sid_cache
async with client.write_session(mgmt, "Domain4", publish_on_exit=False) as ws:
await client.add_object(
mgmt,
"host",
{"name": "h-temp-app", "ipv4-address": "198.51.100.42"},
domain="Domain4",
)
# SessionOverlay automatically merges uncommitted creates/updates/deletes into cache reads!
found = await client.find_object(mgmt, "Domain4", "h-temp-app")
assert found is not None and found.ipv4_address == "198.51.100.42"
# Explicitly discard so nothing is published to Domain4
await client.api_call(mgmt, "discard", {}, domain="Domain4", sid=ws.sid, server_ip=ws.server_ip)
ws.discarded = True
CPCRUD Quickstart
client.cpcrud (CPCRUDService) is Arodonata's declarative Policy-as-Code engine. It takes a YAML or JSON template describing desired objects, services, groups, sections, and rules, computes an idempotent execution plan against cached + live state, applies changes in an isolated session per domain, and can generate a compensating rollback template (inverse).
1. Define a Declarative Template
version: 1
mgmt_name: "mdsm-prod"
domain: "Domain4"
on_name_conflict: "update"
on_ip_conflict: "reuse"
objects:
- type: "host"
name: "web-srv-01"
ipv4-address: "198.51.100.10"
comments: "Managed by Arodonata CPCRUD"
color: "dark green"
services:
- type: "service-tcp"
name: "tcp-8443"
port: "8443"
groups:
- type: "group"
name: "grp-web-servers"
members:
- "web-srv-01"
rules:
- type: "access-rule"
layer: "Standard Network"
position: "bottom"
name: "allow-web-8443"
source: ["Any"]
destination: ["grp-web-servers"]
service: ["tcp-8443"]
rule_action: "Accept"
track: "Log"
2. Validate, Plan, Apply, and Roll Back
import asyncio
from pathlib import Path
from arodonata import ArodonataClient
async def main() -> None:
template_text = Path("examples/crud_example.yaml").read_text(encoding="utf-8")
async with ArodonataClient() as client:
# Step 1: Offline JSON Schema validation (zero network or DB calls)
errors = client.cpcrud.validate(template_text)
if errors:
raise ValueError(f"Invalid template: {errors}")
# Step 2: Plan (captures DomainStamp and resolves diffs via HybridStateReader)
plan = await client.cpcrud.plan(template_text)
for action in plan.actions:
print(f"[{action.outcome}] {action.object_type} {action.name} -> {action.command}")
# Step 3: Apply (verifies DomainStamp hasn't drifted, executes in isolated WriteSession, publishes)
report = await client.cpcrud.apply(plan)
print(f"Applied: success={report.success}, published={report.published}")
# Step 4: Generate a compensating rollback template from (plan, report)
rollback_template = client.cpcrud.inverse(plan, report)
rollback_plan = await client.cpcrud.plan(rollback_template)
rollback_report = await client.cpcrud.apply(rollback_plan)
print(f"Rolled back: success={rollback_report.success}")
if __name__ == "__main__":
asyncio.run(main())
3. Staged Sessions (Human-in-the-Loop Approval)
When integrating into approval workflows (or MCP agent workflows), pass no_publish=True, keep_session=True to apply(). This leaves the Check Point session open and returns StagedSessionInfo (session_uid) in report.staged_sessions.
Later, once approved or rejected, finalize the session by its session_uid:
# Approve and publish (adopts via take-over-session, publishes, logs out, and invalidates domain cache)
await client.publish_staged_session("mdsm-prod", "Domain4", session_uid=staged.session_uid)
# Or reject and discard cleanly
await client.discard_staged_session("mdsm-prod", "Domain4", session_uid=staged.session_uid)
Architecture Overview
Arodonata v2 is built on a strict Hexagonal (Ports & Adapters) architecture designed for high-concurrency asynchronous execution, multi-worker database safety, and zero-leak security hygiene.
System Context & Component Diagram
Key Architectural Invariants
- Pure Core Domain (
arodonata.core,arodonata.rulebase,arodonata.cpcrud,arodonata.reports,arodonata.api_reference):- Business logic depends exclusively on typed Python
Protocolinterfaces (ApiPort,CachePort,LockPort,AuthProvider,GatewayCliPort). - Core modules never import
aiohttp,asyncpg,aiosqlite, or HTTP transport primitives directly.
- Business logic depends exclusively on typed Python
- Database-First Synchronization & Multi-Worker Coordination:
- All cached state lives in 17
arodonata_*SQLModel tables (Database Schema Reference). - Schema initialization is serialized across worker processes (
pg_advisory_xact_lockon PostgreSQL,BEGIN IMMEDIATEon SQLite) and tracked by SHA-256 metadata digest inarodonata_schema_version. arodonata_distributed_lockscoordinates cross-process critical sections with automatic background heartbeat renewal across domain syncs, domain list discovery,LoginGateserialization, and distributedRateLimiterslots.
- All cached state lives in 17
- Strict Read vs Write Session Separation:
- Read operations share a persistent, credential-bound read-only session in
arodonata_sid_cache(system domain keyed as"System Data"). Mutating commands (add-*,set-*,delete-*,publish,discard,run-script) are rejected on the shared session. - Write operations open an isolated
WriteSession(create_dedicated_session) with an in-memorySessionOverlaybound viacontextvarsso callers immediately read their own uncommitted object/service writes beforepublish. CPCRUD also supports staged sessions (no_publish=True, keep_session=True, finalized viapublish_staged_session/discard_staged_session), whileScriptRepositoryServiceexecutes scripts inside dedicated non-read-only sessions withoutpublish/discard.
- Read operations share a persistent, credential-bound read-only session in
- Defense-in-Depth Security Hygiene:
- Session tokens (
sid), API keys, and passwords are redacted ("***REDACTED***") in allrepr(), logs, OpenTelemetry span attributes, exception messages, and MCP tool outputs (redact_sid(..., known_sids=...)). - TLS certificates are verified post-handshake and pre-request against SHA-256 DER fingerprints (
pinned,tofu, orlab-memory).
- Session tokens (
- Provider-Agnostic Observability:
- Functions decorated with
@traced(arodonata.core.telemetry) emit OpenTelemetry spans viaopentelemetry-api(arlogi.otel.traced) without ever owning or overriding the host application's globalTracerProvider.
- Functions decorated with
Subsystems & Package Map
| Package | Responsibility |
|---|---|
arodonata.client & arodonata.core |
Composition root (ArodonataClient), typed settings/contexts, error hierarchy, five core protocols, domain/object/service/asset/search/topology/script services, and background warm-up |
arodonata.rulebase |
Normalized policy package, inline layer, section, SmartConsole numbering, local filtering (RulebaseRefreshService, CachedRulebaseSource), and CPCRUD export |
arodonata.cpcrud |
Declarative Policy-as-Code engine: shorthand expression parser, draft-07 schema validator, HybridStateReader, differ, cleanup-aware planner, executor (retries + staged sessions), and inverse rollback builder |
arodonata.reports |
Auditable ChangeReport collector (session/range scopes + offline build_change_report_from_plan), live rule placement numbering, and self-contained HTML/Markdown/JSON renderer |
arodonata.api_reference |
Offline bundled cp_api_index.json.gz engine (ApiReferenceEngine) supporting version-filtered command search, payload schema description, and offline validation |
arodonata.mcp |
Streamable-HTTP MCP server (arodonata-mcp CLI + ArodonataASGIApp), static bearer / JWT / host auth, DNS-rebinding & Origin guards, HMAC-signed CPCRUD plans, and read/topology/API tools |
arodonata.testing |
Enterprise replay dataset generator, stateful in-process emulator (FileReplayApiMock, FileReplayCliMock), and standalone HTTPS mock server (CheckPointReplayHttpServer) |
Hexagonal Ports & Adapters
Arodonata v2 isolates all Check Point Management API, gateway CLI execution, and SQL database details behind five core Protocol interfaces defined in src/arodonata/core/ports/__init__.py.
Core Protocols (arodonata.core.ports)
1. ApiPort
Defines the asynchronous contract for communicating with Check Point Management and MDSM servers:
api_call(mgmt_name, command, payload=None, *, domain=None, sid=None, server_ip=None, wait_for_task=True, timeout=None) -> ApiCallResultapi_query(mgmt_name, command, *, domain=None, details_level="standard", payload=None, sid=None, server_ip=None, limit=300) -> ApiQueryResultcreate_dedicated_session(mgmt_name, domain=None, *, auth=None, session_name=None, session_description=None) -> tuple[str, str]logout_sid(mgmt_name, sid, *, server_ip=None) -> Awaitable[bool]close(*, logout=None) -> None(whenlogout=None, auto-logs out active sessions only if the client owns an auto-created ephemeral:memory:SQLite engine)
Default Adapter: AMgmtClient (src/arodonata/adapters/checkpoint/client.py), backed by:
ApiTransport(transport.py): Nativeaiohttpclient withallow_redirects=False,trust_env=False, post-handshake and pre-request SHA-256 certificate verification (TrustPolicy/TrustStoreintls.py), and phase-taggedTransportError(phase="connect" | "post-send") /ApiTimeoutError(phase="connect" | "read") carryingrequest_sent: boolso mutating calls are never re-sent after bytes leave the socket.VerifiedConnectionPool: Reuses verified keep-alive connections (<= 10sidle,< 95requests) for idempotentshow-*commands under shared scope AND for non-boundary commands within scoped dedicated sessions (s:<sha256_prefix>), whileNON_POOLABLE_SESSION_COMMANDS(login,logout,keepalive,publish,discard,continue-session,switch-session,take-over-session,disconnect) bypass pooling.LoginCoordinator&SessionCleaner(sessions.py): Credential-bound read-only session cache lookup, isolatedWriteSessionmanagement, coalesced keepalive sweeps, and startup cleanup of orphaned Arodonata sessions.RateLimiter&LoginGate(rate_limiter.py): Enforcesconcurrent_limitper MDS member IP and a70.0scooldown window on login throttling (err_too_many_requests).paginate_objects(pager.py) &TaskWaiter(task_waiter.py): Continuity-verified pagination (limit=300, clamped to500,±10boundary overlap recovery and single restart ontotalshift) plus exponential-backoffshow-taskpolling (2s..10sup totask_timeout).
2. CachePort
Defines the contract for reading and persisting cached Check Point topology, sessions, objects, services, assets, gateway topology intervals, annotations, rulebases, and sync states:
- Domain topology:
get_domains(),get_domain(),upsert_domains() - Shared sessions:
get_sid(),upsert_sid(),evict_sid(),list_sids() - Sync state:
get_sync_state(),list_sync_states(),upsert_sync_state() - Objects & Services:
get_objects(),get_object_by_uid(),replace_domain_objects(),upsert_objects(),delete_objects_by_uids(),get_services(),get_service_by_uid(),replace_domain_services(),upsert_services(),delete_services_by_uids() - Assets:
get_assets(),replace_domain_assets(),upsert_assets() - Gateway topology & annotations:
get_gateway_topology(),replace_domain_topology(),upsert_gateway_topology(),get_topology_annotations(),upsert_topology_annotations(),delete_topology_annotations() - Rulebase snapshots & slices:
replace_domain_rulebase(),replace_domain_package_catalog(),upsert_domain_rulebase_layers(),get_domain_rulebase(),get_domain_rulebase_packages()
(Note: Cross-domain filtering and aggregation methods describe_objects() and query_objects() live in SearchService and ArodonataClient, built on top of CachePort.)
Default Adapter: SqlCacheAdapter (src/arodonata/adapters/storage/cache_adapter.py), which executes atomic transactions, deduplicates primary keys before batched writes (_BATCH_ROWS = 500), and runs dialect-specific ON CONFLICT DO UPDATE upserts on PostgreSQL and SQLite.
3. LockPort
Coordinates distributed cross-process critical sections (per-domain cache refreshes, LoginGate serialization, and cross-worker RateLimiter slots):
acquire(lock_key, *, ttl_seconds=60.0, owner_id=None, wait_timeout=None, poll_interval=0.05) -> boolrenew(lock_key, *, ttl_seconds=60.0, owner_id=None) -> boolrelease(lock_key, *, owner_id=None) -> boollock(lock_key, *, ttl_seconds=60.0, owner_id=None, wait_timeout=None, poll_interval=0.05) -> AbstractAsyncContextManager[str](yieldsowner_id; raisesLockAcquisitionErroron contention/timeout)
Default Adapter: SqlLockAdapter (aliased as DatabaseLockManager, src/arodonata/adapters/storage/lock_adapter.py) backed by arodonata_distributed_locks, evaluating expiration against the database server's UTC clock.
4. AuthProvider
Optional pluggable protocol for resolving runtime credentials dynamically per (mgmt_name, domain) and receiving failure notifications when auth_mode="dynamic" is used without an explicit auth_context:
get_credentials(mgmt_name, domain=None, *, user=None) -> AuthContexton_auth_failed(mgmt_name, auth, exc) -> None
5. GatewayCliPort (& GatewayCliCallable)
Optional protocol for executing shell/clish diagnostics on Check Point gateways and VSX Virtual Systems (e.g., via SSH):
execute_command(target: GatewayCliTarget, command: str, *, timeout: float = 30.0) -> GatewayCliResult | strGatewayCliCallable = Callable[[GatewayCliTarget, str], Awaitable[GatewayCliResult | str]]
Injected via ArodonataClient(..., gateway_cli=...) or client.set_gateway_cli(...) for TopologyService.collect_gateway_routes(). When unavailable or failing, route collection falls back to Check Point cprid via AMgmtClient (run-script one-time or repository scripts managed by ScriptRepositoryService).
Boundary, Storage & Testing Adapters
DatabaseManager(src/arodonata/adapters/storage/database.py): Manages async SQLAlchemy engines (asyncpg/aiosqlite), cross-worker schema locks, and SHA-256 schema hash auto-migration restricted toARODONATA_TABLE_NAMES.SSEAdapter(src/arodonata/adapters/sse/__init__.py): Converts coreDomainEventstreams (SyncProgressEvent,CPCRUDEvent) into SID-redactedSSEEventframes viato_sse_event()andstream_as_sse().- Replay & Test Doubles (
arodonata.testing):FileReplayApiMock,FileReplayCliMock, andCheckPointReplayHttpServerimplementApiPortandGatewayCliPortagainst realistic MDSM/VSX fixture datasets with stateful session overlays and call auditing.
Dependency Injection in Tests & Custom Hosts
Because ArodonataClient accepts custom api: ApiPort, cache: CachePort, lock_port: LockPort, auth_provider: AuthProvider, and gateway_cli: GatewayCliPort | GatewayCliCallable instances in its constructor, unit tests and downstream applications can inject in-memory fakes or custom adapters without monkeypatching internal classes:
client = ArodonataClient(
settings,
api=custom_api_port,
cache=custom_cache_port,
lock_port=custom_lock_port,
auth_provider=custom_auth_provider,
gateway_cli=custom_gateway_cli,
)
Caching, Incremental Synchronization & Search
Arodonata v2 coordinates multi-domain synchronization through DomainSyncCoordinator (src/arodonata/core/services/sync_coordinator.py) and exposes four cache freshness modes (CacheMode).
1. The Four CacheMode Policies
| Mode | Staleness Probe (show-last-published-session) |
Data Fetch Strategy | Typical Use Case |
|---|---|---|---|
"cache" |
Never | Local SQLite/PostgreSQL query only (0 API calls) |
High-speed rulebase filtering, offline analysis, MCP query_objects |
"smart" (default) |
Only when synced_at is older than cache_ttl (or after invalidate_domain) |
Full atomic type-slice reload if (last_published_at, last_session_uid) changed |
Default SDK reads (get_hosts, get_services, get_gateways) |
"smart-fast" |
Same as "smart" |
Queries show-changes (from-session or UTC from-date), deletes removed UIDs, re-fetches added/modified UIDs via show-object, and applies dialect ON CONFLICT upserts; falls back to full reload if changes > max_incremental_changes (500) |
Rapid refresh after small publishes across large domains |
"force" |
Always probes current publish head | Unconditional atomic reload of all requested types | Initial cache build or forced recovery |
2. Synchronization Pipeline & Safeguards
Critical Invariants
- Dirty Shared Session Refusal (
DirtySessionError): Before syncing any domain into the shared cache,DomainSyncCoordinatorverifies viashow-sessionthatlocks == 0,changes == 0, andnumber-of-published-changes == 0(failing closed ifshow-sessionfails). Uncommitted changes are never written into shared SQL tables. - Process-Wide Concurrency & Single-Flight Coalescing (
_ProcessSyncRegistry): Coordinators sharing a database engine share event-loop-bound per-MDS-member semaphores and an_InFlightDomainSyncregistry so concurrent coroutines syncing the same domain coalesce without duplicate API probes or lock contention. Defaultdomain_sync_concurrencyismin(2, max(1, concurrent_limit - 1))unless overridden viaARODONATA_DOMAIN_SYNC_CONCURRENCY, and re-entrant nestedensurecalls reuse_HELD_MDS_PERMITSwithout deadlocking. - Lock Contention vs Genuine Failure: If another worker holds the per-domain lock (
LockAcquisitionError), the coordinator skips redundant work without markingarodonata_domain_sync_state.status = "failed". Genuine API or credential errors record a sanitized (redact_sid) error inlast_errorwhile preserving previously cached rows.
3. Search, Structured Queries & Recursive Group Membership (SearchService)
await client.search_objects(query, ..., exact_match=False, max_depth=2) classifies each comma-separated term via classify_search_term() into "ipv4", "cidr", "range", "wildcard", "uid", or "name" and searches across arodonata_objects (plus arodonata_assets including interface IPv4s when asset types are specified, and any active WriteSession overlay):
- IPv4 Address (
10.1.10.50): Matches hosts with that IPv4 address, networks whose CIDR subnet contains the IP, and address ranges whose[first..last]bounds include the IP. - CIDR Subnet (
10.1.10.0/24): Matches networks with that subnet/mask and hosts/subnets contained within it (with containment excluded whenexact_match=True). - IPv4 Range (
10.1.10.1-10.1.10.20): Matches overlappingaddress-rangeobjects and contained hosts. - Wildcard Pattern (
*.corp.example,web-*): Evaluates case-insensitive anchoredfnmatchcaseacrossname,uid,object_id,id,fqdn,ipv4_address,subnet4, andcomments. - UUID Identifier (
<uid>): MatchesCPObject.uidor compositeiddirectly. - Exact or Substring Name (
exact_match=TruevsFalse):- When
exact_match=False(default), matches case-insensitive substrings inname,fqdn,object_id,id, andcomments. - When
exact_match=True, matches only exact case-insensitivename,fqdn,object_id,id, oruid(e.g., searching".example.com"withexact_match=Truematches.example.comwithout matchingsub.example.com).
- When
- Recursive Group Resolution (
max_depth): Traversesgroup.membersupward up tomax_depthlevels, returningSearchResult(query=..., matches=[...], memberships=...)where eachGroupMembershipNodecarriesid,object_id,uid,name,mgmt_name,domain_name,depth,parent_uids, andparent_object_ids.
SearchService also provides:
describe_objects()andquery_objects()for cross-domain SQL-backed filtering (scope_origin="local"|"global"|"all",ip_subnet,port,protocol,tags),group_byaggregation with CPMI type aliases, andaggregate="count" | "list" | "describe".get_cache_status()inspectingarodonata_domain_sync_stateper(mgmt_name, domain_name, scope, item_type).get_group_members()/resolve_group_with_members()resolving recursive group, service-group, cluster, and cross-domain VSX members while raisingAmbiguousObjectErrorif an unqualified name matches multiple cached domains.
4. Cross-Domain Asset Topology & Composite Identifiers
During refresh_assets / stream_refresh_assets, AssetRefreshService runs ClusterRelationshipManager and VSXRelationshipManager across cached domain assets:
- Intra-Domain Cluster Members: Links each cluster (
CpmiGatewayCluster,vsx-cluster-netobj) and its members (CpmiClusterMember,vsx-cluster-member) with both UID references (parent_uid,member_uids) and composite identifiers (parent_id,parent_asset_id,member_asset_ids). - Cross-Domain VSX Virtual Systems: Reconciles VSX relationships across all domains on the same
mgmt_name(includingCpmiVsxSlotObj/CpmiVsSlotObjinterface and route inheritance), populatingparent_id("mds:VSX:<vsx-uid>"),parent_asset_id("mds:VSX:<vsx-name>"),virtual_system_uids, andvirtual_system_asset_ids(["mds:Domain4:<vs-name>"]).
5. Explicit Background Cache Warm-Up
client.start_object_cache_warmup(...) starts non-blocking background cache warming coalesced across callers via _WarmupFlightKey ((mgmt_name, domains, types, include_global, include_services, mode == "force")). get_domains() never triggers implicit warm-up, while client.get_warmup_status() reports SID-redacted per-server progress (WarmupStatusEntry). On client.close(), active warm-up tasks are cancelled cleanly.
6. Gateway Topology & Live Route Sync (TopologyService)
TopologyService combines Check Point static interface/VPN/VS-route extraction with live CLI routing diagnostics:
- Targeted On-Demand Extraction: Expands interface specific-network groups on demand via targeted
show-object/show-grouplookups rather than downloading every host/network object in a domain. - Live Route Collection: Executes route collection scripts bounded by
route_collect_concurrency(defaultmin(4, max(1, concurrent_limit // 2))) and serialized per VSX physical chassis node, tryingGatewayCliPort(SSH) first and falling back to Check Pointcpridrun-script(viaScriptRepositoryServicein"auto"or"repository"mode, or inline bash). - Reconciliation, Confidence & Matching: Persists 64-bit IPv4 intervals into
arodonata_gateway_topology, honors persistentarodonata_topology_annotations(ignore,standby_dynamic,trust_static_topology), computesConfidenceDeltascores usingTopologyConfidenceWeightsand policy rule evidence, and exposesreconcile_gateway_topology(),get_topology_diagnostics(),find_affected_gateways(), andexport_topology_prefixes().
7. Rulebase Snapshots & Selective Package Refresh
RulebaseRefreshService and CachedRulebaseSource maintain normalized SmartConsole-compatible rulebase caches across the 7 arodonata_rulebase_* tables:
refresh_policy_packages()populates the lightweightarodonata_rulebase_package_layercatalog without downloading all rule rows.refresh_package_rulebase()atomically updates only the target package's layers, inline layers, sections, and NAT package rows (upsert_domain_rulebase_layers) without overwriting other packages in the domain.RulebasePagerstitches sections split across 100-rule pagination boundaries and probes trailing empty sections;CachedRulebaseSourcesupports offline hierarchical numbering (1,2.1,3),locate_rules(), andfilter_rulebase()(output_format="objects" | "markdown" | "model_friendly" | "cpcrud").
Sessions, MDSM & SessionOverlay
Check Point Management servers tie every uncommitted change and object lock to a session identifier (sid). Sharing a single sid across concurrent tasks or mutating on a read session leads to accidental publishes of another user's changes or deadlocked objects.
Arodonata v2 enforces a strict architectural separation between shared read-only sessions and isolated write sessions.
1. Shared Read-Only Sessions (arodonata_sid_cache)
- Credential-Bound Pooling (
C4): All read commands (show-*,where-used,verify-policy) use a pooled session stored inarodonata_sid_cachekeyed by"{mgmt_name}:{domain_name}:{auth_identity}", wheredomain_namenormalizesNonetoSYSTEM_DOMAIN_KEY("System Data") andauth_identityis the non-secret HMAC-SHA256AuthContext.identity_key("{principal}:{digest}"). Distinct users or API keys in multi-tenant hosts never collide or share asid. - Hard Read-Only Guard:
AMgmtClientchecksis_readonly_command(command)before using a cachedsid. Attempting to runadd-*,set-*,delete-*,publish,discard, orrun-scripton the shared session raisesSessionStateErrorimmediately. - Persistent Reuse Across Invocations: When configured with PostgreSQL or file-backed SQLite,
await client.close()leaves validarodonata_sid_cachesessions alive so subsequent worker invocations reuse existing logins without triggering Check Point's login rate limiter (auto-logout on close runs only whenlogout=Trueor on an owned ephemeral:memory:SQLite DB). - Startup & Max-Sessions
SessionCleaner:SessionCleaner(src/arodonata/adapters/checkpoint/sessions.py) inspects open Web API sessions whereapplication == "arodonata"orsession-namestarts with"arodonata"withchanges == 0andlocks == 0. It discards orphaned sessions viadiscard {"uid": target_uid}(neverlogout, which cannot close foreign UIDs) while leavingSmartConsole, third-party, and dirty sessions untouched. Startup cleanup is also invoked on max-sessions errors and skips cleanly in cold"dynamic"mode with no active auth.
2. Isolated WriteSession & SessionOverlay
Whenever you open async with client.write_session(mgmt_name, domain) as ws:, Arodonata:
- Calls
create_dedicated_session()to open a fresh Check Point session outsidearodonata_sid_cache(applyingsession_name/session_descriptionfromUserContextif set). - Binds the
WriteSessionand itsSessionOverlayto Python'scontextvarsfor the current async task tree. - Intercepts every
add-<type>,set-<type>, anddelete-<type>call for cacheable objects and services and records them viaws.overlay.record_object_upsert(),record_object_delete(),record_service_upsert(), andrecord_service_delete(). Non-object/non-service commands (NON_OVERLAY_MUTATION_TARGETSsuch as rules, sections, layers, packages, domains, and repository scripts) bypassSessionOverlay. - Automatically merges
ws.overlay(apply_to_objects(),apply_to_services()) into cached read helpers (get_hosts,get_objects,get_services,find_object,search_objects,get_group_members) called within the same async context. - On normal block exit (
publish_on_exit=True), executespublish, waits for the task to complete, clears the overlay, invalidates the domain cache so the next read fetches the new published revision, and logs out the dedicatedsid. - On any
BaseException(includingasyncio.CancelledError), shieldsdiscardandlogout_sid()viaasyncio.shieldso no locks remain orphaned on Check Point.
3. Authentication Modes & Context Propagation
ArodonataSettings resolves credentials across three mutually validated modes (api_key, credential, and dynamic):
client.auth_context(AuthContext(...)): Scopes per-request credentials (api_keyorusername/password+ optionaluser_id) viacontextvarsfor multi-tenant APIs/MCP hosts.AuthProvider: Optional dynamic credential callback queried when no static or context-bound credential is present; notifieson_auth_failed()and fast-fails evicted identities across retries.client.user_context(UserContext(...)): Propagates operatoruser_id,username,session_name,session_description, andclient_idmetadata onto dedicated Check Point write sessions.
4. MDSM Discovery, Failover & Login Throttling Recovery
- Domain & Active CMA Failover:
DomainServicecachesshow-domains(falling back todetails-level="standard"if RBAC rejectsfullwhile preserving cached CMA IPs) with a1hTTL (domain_list_ttl). If a read-only call hits a stale standby CMA IP,LoginCoordinatorclears cached SIDs and re-resolves active CMA IPs viaDomainService/show-global-domain. Coalesced background keepalive sweeps (RateLimiter.run_coalesced_keepalive) keep long-lived sessions valid and evict expired SIDs immediately ("object not found"/ revision reverts). - Login Throttling Recovery (
LoginGate): Check Point R81.20 / R82 Management servers enforce a strict login rate limit returning HTTP400/429(err_too_many_requests/"Too many login attempts").LoginGate(src/arodonata/adapters/checkpoint/rate_limiter.py) serializes login attempts per MDS member IP with inter-login spacing and opens a sharedlogin_throttle_window(70.0sdefault) cooldown gate up tologin_max_wait(900.0s), while genuine auth failures (InvalidCredentialsError, e.g."Authentication to server failed.") fail fast with zero retries.
5. Staged CPCRUD Sessions & Repository Script Execution
- CPCRUD Staged Sessions:
cpcrud.apply(plan, no_publish=True, keep_session=True)retains the uncommitted write session cleanly and recordsStagedSessionInfo(sidredacted). Later calls topublish_staged_session()ordiscard_staged_session()validate session provenance and adopt the session viatake-over-session(withswitch-sessionfallback). ScriptRepositoryServiceExecution:run_repository_script()runsrun-scriptinside a dedicated non-read-only session (notarodonata_sid_cache) and closes cleanly without callingpublishordiscard.
CPCRUD Engine Architecture
arodonata.cpcrud (src/arodonata/cpcrud/) implements a deterministic, two-phase (plan → apply) Policy-as-Code engine for Check Point Security Management and MDSM.
Architecture & Data Flow
Core Components
1. Offline Schema & Semantic Validator (validator.py)
CPCRUDService.validate() validates YAML strings or Python dictionaries against src/arodonata/cpcrud/checkpoint_ops_schema.json (or cpcrud_schema_path, JSON Schema Draft-07) with zero network or database calls. Beyond JSON Schema, semantic checks enforce strict (object_type, operation) command allowlisting, reject add operations on application-site missing both url-list and application-signature, and validate incremental {add, remove} delta mappings.
2. DomainStamp & HybridStateReader (state_reader.py)
Before inspecting any objects or rules, Planner queries show-last-published-session for each target domain and records a DomainStamp(mgmt_name, domain, last_session_uid, last_published_at).
HybridStateReader serves object, service, and rule lookups using a tiered strategy:
- Cache Hit (Fast Path): If
arodonata_domain_sync_statefor(mgmt_name, domain, scope, item_type)matches the planner'sDomainStamp(last_published_atandlast_session_uid), lookups (host,network,address-range,group,dns-domain,application-site,service-tcp,service-udp,service-icmp, etc.) resolve directly fromarodonata_objectsandarodonata_servicesin local SQL. - Targeted Cold-Cache API Lookup: When local cache is cold or stale,
HybridStateReaderfirst issues targetedshow-objectsqueries (filter+ip-only=True)—withapplication-sitevalue-matching using normalizedurl-listkeys (normalize_app_site_url_key)—before falling back to full paginatedapi_query(show-hosts,show-services-tcp, etc.) only when necessary (e.g.,generic_err_command_not_recognizedor ICMP type/code lookups). - Intra-Plan Virtual State Overlay: Each
plan()call instantiates a freshHybridStateReaderwhose virtual overlay tracks objects, services, and groups planned earlier in the same template so downstream groups and rules see newly planned members immediately. - Fail-Closed Lookup Errors: Transport or API errors during state lookup raise
StateLookupErrorand produceOutcome.ERROR(plusOutcome.SKIPPED_DEPENDENCYon dependent groups/rules) rather than falsely assuming an object is missing and planning a duplicateCREATE.
3. Two-Axis Conflict Resolution (differ.py & planner.py)
When planning an object or service:
on_name_conflict: "update" | "error":- If an object with the same
nameexists with identical desired fields →Outcome.UNCHANGED(no-op). - If fields differ and
on_name_conflict="update"→Outcome.UPDATEwith field-levelFieldChangediffs. - If fields differ and
on_name_conflict="error"→Outcome.ERROR.
- If an object with the same
on_ip_conflict: "reuse" | "create_new" | "error":- Evaluated when no object has the requested
name, but an existing object in the domain already owns the same IPv4/IPv6 value, CIDR subnet, IP range, port/ICMP tuple, DNS FQDN, orapplication-siteURL set: "reuse"(default): PlansOutcome.REUSEand recordsrequested_name -> existing_nameinPlan.name_resolutions, automatically rewriting references in subsequent groups and rules."create_new": Generates a convention name viaNamingPrefixes(Host_<ip>,Net_<subnet>_<mask>,IPR_<first>-<last>or compressed same-/24,TCP_<port>,UDP_<port>,ICMP_<type>[_<code>],grp<name><suffix>,Site_[marker]<domain>) and plansOutcome.CREATE(or reuses if that canonical name already exists)."error": PlansOutcome.ERRORand skips dependent actions.
- Evaluated when no object has the requested
4. Rule Identity & Cleanup-Aware Positioning (rule_identity.py & position_helper.py)
- Access, HTTPS, and Threat Rules: Matched by
uid,name, or traffic tuple (source,destination,service,action). - NAT Rules: Matched by
uid,name, or original/translated traffic tuple, normalizing Check Point's built-in"Original"(NAT_ORIGINAL_OBJECT_UID) and"Any"(NAT_ANY_OBJECT_UID) sentinel UIDs so re-planning an applied NAT rule is idempotent (Outcome.UNCHANGED). - Cleanup Rule Anchoring:
is_cleanup_rule()identifies any rule with"cleanup"in its name or any trailingAny / Any / Anyrule at the end of a layer or section. Whenposition: "bottom"or{"bottom": "<section>"}is requested alongside a trailing cleanup rule,position_helperautomatically anchors the new rule{"above": "<cleanup_rule_uid>"}so traffic rules are never placed below the cleanup drop rule.
5. Dedicated-Session Executor & Compensating Rollback (executor.py, inverse.py)
When await client.cpcrud.apply(plan, force=False) runs:
- Pre-Session Staleness Check: Re-queries
show-last-published-sessionand compares againstplan.domain_stamps. If another admin published changes afterplan()was created andforce=False, execution aborts withOutcome.PLAN_STALEbefore opening a write session. - Pre-Publish Drift Re-Verification: Before calling
publish,Executorre-checksshow-last-published-session; if concurrent changes published during execution (force=False), it discards the session cleanly and reportsOutcome.PLAN_STALE. - Bounded Retries (
retry_remaining):Executor.stream_applycan re-run failed actions up toretry_remainingtimes, advancingDomainStamponly for domains published by the executor and folding retry results into a cumulativeApplyReport. - Compensating Rollback (
inverse.py):client.cpcrud.inverse(plan, report=None)supports both post-apply rollback (Outcome.CREATE,Outcome.UPDATE,Outcome.DELETEusingprior_state, requiring a concretetarget_uidonCREATE) and pre-apply dry-run inversion, emitting a schema-valid reverse template in reverse dependency order (rules → sections → groups → services/objects).
6. Shorthand Expression Parser (expressions.py)
arodonata.cpcrud.expressions parses concise operator strings into normalized Check Point object/service dictionaries using NamingPrefixes: parse_object_expression(), parse_service_expression(), parse_group_expression(), expand_group_expression(), parse_app_site_expression(), parse_range_token(), normalize_wildcard_domain(), and wildcard_domain_to_cp_regex_urls() (covering hosts, CIDRs, short IP ranges like 10.1.1.1-9, tcp/udp/icmp tokens, DNS sub-domains, wildcard application-site regex URLs, and nested group trees).
7. Incremental Group & Rule Cell Deltas (DiffSafetyError)
differ.py supports incremental {add, remove} dictionaries on group.members, service-group.members, application-site.url-list, and rule cells (source, destination, service, install-on, protected-scope, site-category), raising DiffSafetyError to prevent unsafe mutations (adding 'Any', narrowing an existing 'Any' cell without explicitly removing 'Any', or emptying a rule cell or url-list without application-signature). Missing named targets under "set" or incremental delta updates fail closed as Outcome.ERROR.
8. Staged Sessions & Offline Dry-Run ChangeReport
- Staged Sessions: Calling
apply(plan, no_publish=True, keep_session=True)leaves the dedicated write session uncommitted for external inspection (ApplyReport.staged_sessionswithStagedSessionInfo,sidredacted), emitsStagedSessionEvent, and supports later provenance-verified adoption (take-over-session/switch-session) viapublish_staged_session()anddiscard_staged_session(). - Offline Plan Reports:
build_change_report_from_plan(plan)(arodonata.reports.plan_report) converts anyPlandirectly into aChangeReportrenderable viarender_change_report()(html,markdown,json) without live API calls.
CPCRUD — Declarative Policy-as-Code Engine (client.cpcrud)
client.cpcrud (CPCRUDService) provides a deterministic, two-phase (plan -> apply) Policy-as-Code CRUD engine for Check Point Security Management and MDSM servers with offline JSON Schema validation, two-axis conflict resolution, staleness guards, and compensating rollback templates (inverse).
Quick Start
ARODONATA_LAB=home uv run examples/08_cpcrud_operations.py
ARODONATA_LAB=home uv run examples/09_cpcrud_inverse.py
08_cpcrud_operations.pyvalidatesexamples/crud_example.yamloffline, plans and applies it twice inDomain4, and verifies that Run 2 producesunchangedoutcomes with zerocreateactions.09_cpcrud_inverse.pyplans and applies a template, generates a compensating rollback template viaclient.cpcrud.inverse(plan, report), and applies the rollback.
Template Structure
Templates are validated offline against src/arodonata/cpcrud/checkpoint_ops_schema.json using client.cpcrud.validate(template) (zero network or database calls):
version: 1
mgmt_name: "10.192.15.140"
domain: "Domain4"
on_name_conflict: "update"
on_ip_conflict: "reuse"
objects:
- type: "host"
name: "cpcrud-example-host-1"
ipv4-address: "198.51.100.10"
comments: "CPCRUD example host"
color: "dark green"
- type: "network"
name: "cpcrud-example-net-1"
subnet4: "198.51.100.0"
mask-length4: 24
services:
- type: "service-tcp"
name: "cpcrud-example-tcp-8443"
port: "8443"
groups:
- type: "group"
name: "cpcrud-example-group"
members:
- "cpcrud-example-host-1"
- "cpcrud-example-net-1"
rules:
- type: "access-rule"
layer: "FPCR_UAT_Active Network"
position: "bottom"
name: "cpcrud-example-access-rule"
source: ["cpcrud-example-host-1"]
destination: ["Any"]
service: ["cpcrud-example-tcp-8443"]
rule_action: "Drop"
Multi-domain templates can also group operations under targets: (or domains:), where each item specifies its own mgmt_name, domain, and objects / services / groups / rules / operations.
Two-Axis Conflict Policies
on_name_conflict
Controls what happens when an object with the requested name already exists with different attributes:
| Value | Behavior |
|---|---|
update (default) |
Plans Outcome.UPDATE (set-<type>) with a field-level diff |
error |
Plans Outcome.ERROR and skips dependent groups/rules (Outcome.SKIPPED_DEPENDENCY) |
on_ip_conflict
Controls what happens when no object has the requested name, but another object already owns the same IPv4/subnet/range or service port:
| Value | Behavior |
|---|---|
reuse (default) |
Plans Outcome.REUSE and maps requested_name -> resolved_name in Plan.name_resolutions so downstream groups and rules reference the existing object |
create_new |
Plans Outcome.CREATE using convention-compliant NamingPrefixes (Host_<ip>, Net_<subnet>_<mask>, IPR_<first>-<last>, TCP_<port>, UDP_<port>) |
error |
Plans Outcome.ERROR and skips dependent actions |
Staleness Protection & Execution Options
- Pre-Lookup
DomainStamp:client.cpcrud.plan(template)capturesshow-last-published-session(last_session_uid,last_published_at) for every target domain BEFORE reading state. - Staleness Guard on
apply():await client.cpcrud.apply(plan, force=False)re-verifies each domain's published head before opening a write session. If another administrator published changes sinceplan(),apply(force=False)aborts that domain withOutcome.PLAN_STALE. Passforce=Trueto override. - Staged Sessions (
no_publish=True, keep_session=True): Leaves the dedicated write session open on the server and returnsStagedSessionInfoinApplyReport.staged_sessions(with.sidredacted inrepr()and logs). - Automatic Retries (
retry_remaining=N): Retries failed or locked actions up toNadditional passes.
Compensating Rollback (inverse)
Always pass the original Plan (captured before apply) and the resulting ApplyReport to client.cpcrud.inverse(plan, report):
plan = await client.cpcrud.plan(template)
report = await client.cpcrud.apply(plan)
inverse_template = client.cpcrud.inverse(plan, report)
inv_plan = await client.cpcrud.plan(inverse_template)
inv_report = await client.cpcrud.apply(inv_plan)
Auditable Change Reports (arodonata.reports)
Arodonata v2 provides a read-only change evidence collector and offline multi-format renderer (HTML, Markdown, JSON) in src/arodonata/reports/ and on ArodonataClient.
It is designed for change-management tickets, compliance audits, and human-in-the-loop review of both unpublished staged sessions and historical published sessions.
1. Scopes: SessionScope vs RangeScope
You can collect change reports across one or more management servers and domains in a single call by passing SessionScope or RangeScope items:
from datetime import datetime, UTC
from arodonata import ArodonataClient, RangeScope, RenderOptions, SessionScope
async with ArodonataClient() as client:
# Option A: Inspect specific session UIDs (published or currently open)
scope_sessions = SessionScope(
mgmt_name="mdsm-prod",
domain="Domain4",
session_uids=["4a8b9c10-..."],
)
# Option B: Inspect all published sessions within a UTC time window or session range
scope_range = RangeScope(
mgmt_name="mdsm-prod",
domain="Domain4",
from_date=datetime(2026, 10, 25, 0, 0, tzinfo=UTC),
to_date=datetime(2026, 10, 26, 0, 0, tzinfo=UTC),
)
bundle = await client.build_change_report(
[scope_sessions, scope_range],
formats=["html", "markdown", "json"],
options=RenderOptions(
title="Firewall Change Evidence — Ticket CHG-10492",
include_object_changes=True,
include_field_diffs=True,
include_warnings=True,
),
)
# Save rendered outputs
Path("report.html").write_bytes(bundle.html)
Path("report.md").write_text(bundle.markdown, encoding="utf-8")
Path("report.json").write_text(bundle.json_text, encoding="utf-8")
2. Unpublished Live Numbering vs Published Cached Numbering
A key capability in Arodonata v2 is accurate SmartConsole rule numbering (1, 2.1, 3) even for uncommitted rules inside an open WriteSession or staged CPCRUD session:
- Live Unpublished Session (
OwnedSession):- When you pass
owned_sessions=[OwnedSession(mgmt_name=..., domain=..., session_uid=..., sid=ws.sid, server_ip=ws.server_ip)]inRenderOptions, the collector reads the rulebase directly through that unpublishedsid(strictly read-onlyshow-*calls) so newly added or moved rules receive their exact post-change SmartConsole rule numbers beforepublish! - The
OwnedSession.sidis never stored inChangeReportand is redacted in__repr__and all rendered outputs.
- When you pass
- Published Session Fallback:
- For already-published sessions (or when no
OwnedSessionis provided), the collector resolves rule numbers and layer locations from the cached rulebase snapshot (arodonata_rulebase_*), complemented by bounded (MAX_UID_LOOKUPS = 200) liveshow-objectUID resolution for referenced objects.
- For already-published sessions (or when no
Configuration Overview
Arodonata v2 uses ArodonataSettings (src/arodonata/core/config.py) built on pydantic-settings for type-safe configuration resolution.
Core Design Principles
- No Implicit
.envLoading:ArodonataSettingsreads from explicit constructor keyword arguments andos.environ(env_file=None). Host applications and CLIs control when.envfiles are loaded. - Automatic Secret Redaction:
api_key,api_keys,password, anddatabase_urlpasswords are automatically masked ("***REDACTED***") in__repr__(),__str__(),model_dump(), andmodel_dump_json(). - Dual Alias Support: Every setting supports both prefixed
ARODONATA_*environment variables and legacyMGMT_*/ unprefixed aliases.
ArodonataSettings Reference
Server Topology & Authentication
| Field | Env Variable(s) | Type | Default | Description |
|---|---|---|---|---|
mgmt_names |
ARODONATA_MGMT_NAMES, MGMT_NAMES |
list[str] (CSV/JSON) |
[] |
Logical names of management servers (positional match with mgmt_servers) |
mgmt_servers |
ARODONATA_MGMT_SERVERS, MGMT_SERVERS |
list[str] (CSV/JSON) |
[] |
Target host, host:port, or [ipv6]:port addresses |
api_keys |
ARODONATA_API_KEYS, API_KEYS |
list[str] (CSV/JSON) |
[] |
Positional API keys for each server in mgmt_servers |
api_key_vars |
ARODONATA_API_KEY_VARS, API_KEY_VARS |
list[str] (CSV/JSON) |
[] |
Names of environment variables holding each server's API key |
mgmt_name |
ARODONATA_MGMT_NAME, MGMT_NAME |
str | None |
None |
Single-server logical name convenience fallback |
mgmt_ip |
ARODONATA_MGMT_IP, MGMT_IP |
str | None |
None |
Single-server IP/hostname convenience fallback |
mgmt_port |
ARODONATA_MGMT_PORT, MGMT_PORT |
int |
443 |
Default HTTPS port when omitted in mgmt_servers |
api_key |
ARODONATA_API_KEY, MGMT_API_KEY |
str | None |
None |
Single-server API key fallback |
username |
ARODONATA_USERNAME, MGMT_USER, MGMT_USERNAME |
str | None |
None |
Administrator username for "credential" auth mode |
password |
ARODONATA_PASSWORD, MGMT_PASSWORD |
str | None |
None |
Administrator password for "credential" auth mode |
auth_mode |
ARODONATA_AUTH_MODE |
"api_key" | "credential" | "dynamic" |
Auto-inferred | Inferred from configured keys/credentials (dynamic when neither is static) |
Timeouts, Concurrency & Rate Limiting
| Field | Env Variable | Type | Default | Description |
|---|---|---|---|---|
connect_timeout |
ARODONATA_CONNECT_TIMEOUT |
float |
30.0 |
TCP/TLS handshake timeout in seconds |
api_timeout |
ARODONATA_API_TIMEOUT |
float |
120.0 |
Per-request Management API timeout budget in seconds |
login_timeout |
ARODONATA_LOGIN_TIMEOUT |
float |
120.0 |
Timeout budget for login requests in seconds |
task_timeout |
ARODONATA_TASK_TIMEOUT |
float |
900.0 |
Maximum polling duration (TaskWaiter) for async tasks (publish, show-changes, revert-to-revision) |
rate_limit_slot_timeout |
ARODONATA_RATE_LIMIT_SLOT_TIMEOUT |
float |
90.0 |
Maximum wait time to acquire a per-MDS-member concurrency slot |
session_timeout |
ARODONATA_SESSION_TIMEOUT |
int |
600 |
Check Point server-side session-timeout requested on login (seconds) |
session_expire_seconds |
ARODONATA_SESSION_EXPIRE_SECONDS |
int |
540 |
Local TTL in arodonata_sid_cache before proactive keepalive/re-login |
concurrent_limit |
ARODONATA_CONCURRENT_LIMIT |
int (1..20) |
4 |
Max concurrent API requests per MDS member IP (domain_sync_concurrency = max(1, concurrent_limit - 1)) |
login_throttle_window |
ARODONATA_LOGIN_THROTTLE_WINDOW |
float |
70.0 |
Cooldown window (seconds) enforced by LoginGate when Check Point throttles logins |
login_max_wait |
ARODONATA_LOGIN_MAX_WAIT |
float |
900.0 |
Maximum total wait time across throttled login retries |
Storage, Cache & Telemetry
| Field | Env Variable | Type | Default | Description |
|---|---|---|---|---|
database_url |
ARODONATA_DATABASE_URL |
str |
"sqlite+aiosqlite:///:memory:" |
SQLAlchemy async database URL (sqlite+aiosqlite:///... or postgresql+asyncpg://...) |
sqlite_busy_timeout_ms |
ARODONATA_SQLITE_BUSY_TIMEOUT_MS |
int |
30000 |
SQLite PRAGMA busy_timeout in milliseconds (WAL mode enabled automatically on file DBs) |
cache_ttl |
ARODONATA_CACHE_TTL |
int |
300 |
Freshness window (seconds) before "smart" / "smart-fast" probes show-last-published-session |
domain_list_ttl |
ARODONATA_DOMAIN_LIST_TTL |
int |
3600 |
TTL (seconds) for cached MDSM show-domains topology (arodonata_domains) |
max_incremental_changes |
ARODONATA_MAX_INCREMENTAL_CHANGES |
int |
500 |
Threshold of show-changes entries above which "smart-fast" falls back to full type reload |
tls_trust |
ARODONATA_TLS_TRUST |
"pinned" | "tofu" | "lab-memory" |
"tofu" |
TLS peer certificate verification mode |
tls_known_hosts_path |
ARODONATA_TLS_KNOWN_HOSTS_PATH |
str |
~/.config/arodonata/tls_known_hosts.json |
Path to persistent 0600 JSON trust store |
tls_fingerprints |
ARODONATA_TLS_FINGERPRINTS |
str |
"" |
Comma-separated pinned SHA-256 certificate fingerprints (host:port=SHA256:... or bare hex) |
cpcrud_schema_path |
ARODONATA_CPCRUD_SCHEMA_PATH |
str | None |
None |
Optional path override for checkpoint_ops_schema.json |
trace_modules |
ARODONATA_TRACE_MODULES |
str |
"" |
OpenTelemetry module span gating rules (e.g. "+arodonata.core,-arodonata.adapters.storage") |
cprid_script_mode |
ARODONATA_CPRID_SCRIPT_MODE |
"inline" | "repository" | "auto" |
"inline" |
Execution mode for Management API cprid run-script route collection |
cprid_repository_script_name |
ARODONATA_CPRID_REPOSITORY_SCRIPT_NAME |
str |
"arodonata-collect-routes-v1" |
Default Check Point Script Repository entry used in "repository" and "auto" modes |
Multi-Server Topology & Authentication Modes
Arodonata v2 natively manages multiple Check Point Security Management Servers (SMS) and Multi-Domain Security Management (MDSM) clusters within a single ArodonataClient instance.
1. Positional Multi-Server Configuration
Configure multiple servers by providing comma-separated lists (or JSON arrays) in ARODONATA_MGMT_NAMES and ARODONATA_MGMT_SERVERS:
ARODONATA_MGMT_NAMES=mdsm-eu,mdsm-us,sms-dmz
ARODONATA_MGMT_SERVERS=10.10.1.10:443,10.20.1.10:443,[2001:db8::10]:443
ARODONATA_API_KEY_VARS=MDSM_EU_KEY,MDSM_US_KEY,SMS_DMZ_KEY
MDSM_EU_KEY=secret-api-key-eu
MDSM_US_KEY=secret-api-key-us
SMS_DMZ_KEY=secret-api-key-dmz
Indirect Secret References (ARODONATA_API_KEY_VARS)
Using ARODONATA_API_KEY_VARS is recommended for production deployments so each server's secret key resides in its own dedicated secret environment variable rather than a combined comma-separated string.
2. Authentication Modes (AuthMode)
ArodonataSettings automatically determines auth_mode using strict precedence:
"api_key"Mode: Active whenapi_keys,api_key, orapi_key_varsare provided. Counts ofmgmt_names,mgmt_servers, andapi_keysmust match exactly."credential"Mode: Active whenusernameandpasswordare provided (and no explicitapi_keysare set)."dynamic"Mode: Active when no static credentials or API keys are configured inArodonataSettings. Callers supply per-request credentials at runtime viawith client.auth_context(username=..., password=...):or an injectedAuthProviderport.
3. Runtime Credential & Attribution Contexts
In multi-tenant web backends (such as FPCR v2), a single long-lived ArodonataClient can execute operations under the logged-in administrator's identity using Python contextvars:
with (
client.auth_context(api_key=user_api_key),
client.user_context(
user_id="u-1042",
username="alice@corp.example",
session_name="fpcr-ticket-9812",
session_description="Automated firewall rule provisioning",
),
):
async with client.write_session("mdsm-eu", "Domain4") as ws:
await client.add_object("mdsm-eu", "host", {"name": "h-srv-99", "ipv4-address": "10.10.99.1"}, domain="Domain4")
- Credential Isolation in
arodonata_sid_cache: Shared read-only session keys incorporate an HMAC-SHA256 digest of the active credential (auth_identity), ensuring two different dynamic credentials never share a cachedsid.
TLS Certificate Verification (TrustPolicy & TrustStore)
Check Point Management and MDSM servers frequently use self-signed or internal CA certificates, and MDSM standby/member CMA IPs often present a certificate issued to the primary MDS hostname. Standard hostname-based TLS verification breaks on CMA IP routing, while disabling TLS verification (verify_ssl=False) exposes automation to man-in-the-middle attacks.
Arodonata v2 solves this with post-handshake, pre-request SHA-256 DER certificate fingerprint verification (src/arodonata/adapters/checkpoint/tls.py).
How Verification Works
- Before sending any HTTP request headers or Check Point credentials (
api-key/password/X-chkp-sid) over anaiohttpconnection,ApiTransportinspects the peer's raw DER certificate fromtransport.get_extra_info("ssl_object").getpeercert(binary_form=True). - It computes the uppercase SHA-256 hex digest and validates it against
TrustPolicybefore a single byte of HTTP payload leaves the socket. - If the certificate does not match, the connection is aborted immediately with
CertificateMismatchErrororUnknownServerCertificateError.
Trust Modes (ARODONATA_TLS_TRUST)
| Mode | Behavior | Recommended Use |
|---|---|---|
"pinned" |
Strictly requires the server's SHA-256 fingerprint to exist in ARODONATA_TLS_FINGERPRINTS or tls_known_hosts.json. Rejects unknown certificates with UnknownServerCertificateError. |
Production |
"tofu" (default) |
Trust On First Use: pins the certificate fingerprint to ~/.config/arodonata/tls_known_hosts.json (with 0600 permissions and fcntl.flock cross-process locking) on first contact, and raises CertificateMismatchError if it ever changes. |
Staging / CLI / Standard Deployments |
"lab-memory" |
Stores TOFU pins in memory for the lifetime of the process without writing to disk. Refuses to activate unless ARODONATA_LAB is set or explicitly configured for tests. |
CI / Ephemeral Lab Tests |
Cross-IP MDSM Member Recognition
On Multi-Domain servers, show-domains discovers domain CMA IPs and active MDS member IPs (active_mds_ip) that share the same physical server certificate as the primary mgmt_ip.
When TrustPolicy connects to an MDSM member IP whose certificate SHA-256 fingerprint matches an already-trusted entry in the same management cluster, it automatically recognizes and records that (host, port) endpoint without failing.
Configuring Pinned Fingerprints
You can supply pinned fingerprints via environment variable:
ARODONATA_TLS_TRUST=pinned
# Host-scoped or global comma-separated SHA-256 fingerprints:
ARODONATA_TLS_FINGERPRINTS="10.10.1.10:443=SHA256:A1B2C3...,10.20.1.10:443=SHA256:D4E5F6..."
Testing & Quality Gates
Arodonata v2 enforces strict offline unit test coverage, static typing, linting, OpenSpec specification validation, and a 7-bucket live Check Point MDSM integration suite.
1. Unified Test Runner (./pytest.sh)
All test execution goes through ./pytest.sh:
# Fast offline unit tests (mandatory pre-PR quality gate; zero network access)
./pytest.sh
./pytest.sh unit
# Pass extra pytest arguments (e.g. -k or specific test file)
./pytest.sh unit tests/unit/test_mcp_server.py
Live Check Point MDSM/SMS Integration Buckets (b1..b7)
Live integration tests require .env.test, .env.secrets, and an optional lab overlay .env.lab.<ARODONATA_LAB> (e.g., ARODONATA_LAB=home). They acquire a non-blocking process-wide lock (tests/integration/run_lock.py), probe server readiness (lab_ready.py), and automatically snapshot and restore mutated domains via revert-to-revision (cp_revision.py).
| Command | Bucket | Scope |
|---|---|---|
./pytest.sh int-1 |
bucket_1 |
Authentication, session lifecycle, rate limiter, cached reads, search, rulebase reads, change reports |
./pytest.sh int-2 |
bucket_2 |
Cache build, streaming sync events (SyncProgressEvent), live CPCRUD (plan / apply / inverse) |
./pytest.sh int-3 |
bucket_3 |
WriteSession + SessionOverlay, publish, discard, revert-to-revision, and 70s login throttle recovery |
./pytest.sh int-4 |
bucket_4 |
Multi-domain isolation (Domain4 vs Domain5 vs Global) and CacheMode matrix (cache, smart, smart-fast, force) |
./pytest.sh int-5 |
bucket_5 |
Full rebuilds, 120-rule layer pagination stitching, publish matrix, and session change reports |
./pytest.sh int-6 |
bucket_6 |
Bounded soak loop (repeated publish → smart-fast → revert stability cycles) |
./pytest.sh int-7 |
bucket_7 |
Live MCP server and consolidated tool surface verification |
./pytest.sh int-full |
b1..b7 |
Full sequential integration suite |
2. Mandatory Pre-Commit / Pre-PR Quality Gates
# 1. Python lint and formatting
uv run ruff check .
uv run ruff format --check .
# 2. Strict MyPy type checking (Python 3.13)
uv run mypy src
# 3. Offline unit test suite
./pytest.sh unit
# 4. Markdown linting
npx markdownlint-cli "**/*.md" --ignore node_modules --ignore .venv --fix
# 5. OpenSpec specification validation
openspec validate --specs --no-interactive
Changelog
All notable changes to this project will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
[Unreleased]
Security
- cpcrud,reports,rulebase,search: Redacted leaked SIDs and credentials via
redact_sid(..., known_sids=...)acrossActionResult,CPCRUDEvent,check_current_domain_head,_executor_pass, and recursiveFieldDiff(is_sensitive_key) /ChangeReport/reports/collectorsanitization (DA-001,DA-009), escaped[/],, backticks, newlines, and Markdown table pipes inrender_safe_inline_markdown_md,_esc_md,_esc_md_code, andformat_rules_markdown(DA-010,DA-015), enforced an explicitALLOWED_QUERY_GROUP_BY_FIELDSallowlist inquery_objects(DA-011), and propagatedServerIdentityErrorinresolve_implicit_domain_mode(DA-013). - transport,ssrf,storage,tls: Tightened
validate_explicit_server_ip()to require.issubset()across all resolved DNS answers and return canonical pinned IPs without host re-resolution (DA-001), defaultedRateLimitTimeoutErrortophase="connect"/request_sent=False, canonicalizedConnectionPoolIPv4/IPv6/DNS keys, enforced boundedmax_response_bytes(67_108_864default) streaming reads and valid TCP port bounds (1..65535), refused symlinked/group-writableTrustStorefiles and parent dirs while preserving0444/0644uid=0Kubernetes ConfigMap mounts (VVAH-CLAUDE-05), and created new file-backed SQLite parent directories (0700) and files (0600). - sessions,cleaner,scripts,routes: Enforced fail-closed
SessionCleanercleanup without seeding read-write SIDs intoarodonata_sid_cache(DA-042), respected explicitSIDCacheEntry.expires_atinis_sid_entry_fresh(), normalizeddomain_name=normalize_domain_key(...)unconditionally inget_write_session()(DA-003), passedcached.domain_nameinkeepalive_sideviction, caughtException(notBaseException) inlogout_sid(), and enforced SID redaction acrossScriptTargetExecutionResult,RepositoryScriptExecutionOutcome,GatewayCliResult,route_executor, and allScriptRepositoryService.run_repository_script()session exception branches (DA-011,VVAH-SID-01). - mcp,cpcrud: Rejected present-but-blank
Originheaders (origin_matches_allowed), boundplan_idinto_sign_plan(), blocked cross-callerplan_idoverwrites, prioritized same-callerstaged_session_storeeviction (VVAH-MCP-CPCRUD-01), registered per-call extra dedicated SIDs via_ACTIVE_MCP_EXTRA_SIDS+ shieldedlogout_sid+TaskPollError(..., known_sids=...)+json_tool_result(..., known_sids=...)(DA-037), and documented the service-account / server-wide domain visibility trust boundary indocs/mcp/index.md. - tls,sessions,testing: Failed closed with
ValidationErrorwhen an explicit hostname resolves to zero DNS A/AAAA records (REQ-SESS-010), enforced unconditional startup stale-session inspection despite cached read-only System Data SIDs (REQ-SESS-011), preserved hostname-boundTrustPolicypinned and TOFU fingerprint verification (identity_host/tls_identity_host) across canonical IP pinning and pooled socket reuse (REQ-SESS-012), and alignedFileReplayApiMockcommand-name validation withAMgmtClient(REQ-ITEST-007).
Fixed
wave-9-deep-audit: Remediated 34 Wave-9 deep-audit findings across CPCRUD (
StagedSessionInfo.baseline_readablefail-closed publish guard +allow_stalepropagation, single cancellation-safeasyncio.shield(logout_sid)cleanup,_resolve_domain_nameNonefallback,groupsdiffing, non-blank rule item safety, unsetinstall-onnormalization, cleancheckpoint_ops_schema.json), Rulebase (_service_matches_termstrictproto/portandsvc.typematching, cycle-safe_expand_parent_identifiers), Sessions/MDSM (WriteSessionexception preservation + shieldedlogout_sid, bounded stall-safe MDS pagination in_domain_discovery.py,cached_domainspreservation invalidate_explicit_server_ip,ServerIdentityError/TaskErrorpropagation in script/route execution), Cache/Search (SessionOverlay.apply_to_single_object/apply_to_single_serviceisolation, empty/foreigntypesearly short-circuits,vsx-reconcilewait_timeout=15.0and non-fatalLockAcquisitionErrorhandling,VSXRelationshipManager.enrichvsx_reffallback, lazy single-domain freshness checks infind_object,exact_match=TrueIP-range containment, sharedresolve_query_scopesskippingobjectsonport/protocolqueries, preservedSearchService.__module__ == "arodonata.core.services.search_service"), Emulator (groupsfilterseed_uids, gateway detailleads-to-specific-networkname resolution,delete-unused-objectscross-session lock preflight), and documentation sync (README.md,build_notebooklm_docs.pycovering 13 examples / 12 OpenSpec specs / 33 HTML pages).cpcrud,reports,rulebase,topology,assets,testing: Remediated Wave 8 policy-layer audit findings (
REQ-CPCRUD-014,REQ-CPCRUD-015,REQ-REPORT-006,REQ-RULE-007,REQ-TOPO-021,REQ-CACHE-017,REQ-ITEST-019) across CPCRUD (trackwire encoding per rulebase, fail-closed rule actions,install-onanti-Any and empty-list guards,is_cleanup_rulefix, offlinevalidate()parity,planned:UID stripping ininverse(), staged sessionlogout_sidshielding and domain-head staleness checks), Change Reports (fail-closedRangeScopeUIDs,OwnedSessionsid=Nonefallback, nestedold_rule_numberand dottedrule_numberpreservation, order-onlyFieldDiffsuppression, inline Markdown/_esc_mdsanitization), Rulebase (paginatedshow-*-layers, advancing zero-rule pages,< total_reportedtruncation error, empty/name-keyedLayerPrefixLocation), Topology (ServerIdentityErrorpropagation, full-domainroutessync state,(mgmt_name, domain_name, node_key)VSX coalescing, listnext-hopunwrapping, spaced_VS_ERROR_RE,manualexport parity), Assets ((mgmt_name, uid)VSX keying, per-management distributed lock,cache/no-op skip), andFileReplayApiMock(per-rulebasetrackwire validation, failedsetrollback,read_onlyswitch-session/discardguards, lazy in-memory baseline snapshots).cache,sync,rulebase,mcp: Preserved in-flight domain/wildcard invalidations across
probe_domain_staleness(REQ-CACHE-015) and slice sync handlers (REQ-CACHE-016— stampingDomainSyncState.synced_atatprobe.probe_started_atand guardingstream_ensure/ live route_record_slice_syncedoninvalidation_at_start), honoredcache_ttlon single-packagerefresh_package_rulebaseonce slice invalidation is satisfied (REQ-RULE-003), keptcache_mode="cache"domain pre-validation free of live refreshes and quota charges (REQ-MCP-013), capped implicit all-domaincache_control(action="refresh")atlive_tool_rate_limit_per_minuteon empty live buckets while rejecting oversize explicit fan-out calls upfront with zero leaked slots (REQ-MCP-014), and reportedmax(...)cache_age_secondsacross touched scopes inquery_objectsandsearch_objects(REQ-MCP-015).cache,sync,search,models: Replaced destructive
.discard()domain invalidation with timestamped + monotonic-sequence slice tracking inDomainSyncCoordinatorandDomainListRefreshTracker.invalidate(None), wiredWriteSessionpublish invalidation for externally injectedAMgmtClient(DA-002), committedsmart-fastincremental diffs atomically viaapply_object_diff()/apply_service_diff()aftershow-objecthydration (DA-004), normalized service type aliases/casing across SQL andSessionOverlay(DA-025), preservedmask-length4 == 0(0.0.0.0/0,DA-023), scopedSessionOverlaymerges acrossObjectService,ServiceCacheService, andSearchService(DA-024), fixedSearchService.find_object()non-defaultobj_typesync and single-passforcerefresh (DA-005), preserved multi-domainGlobalUID memberships (DA-030), prevented non-groupCPObject/CPServiceshadowing and cross-domainparent_namecluster leaks (DA-031), and clampedquery_objectslimit(1..1000),offset >= 0, andgroup_bypagination (VVAH-SEARCH-01).mcp,quota,apiref,docs: Honored
cache_mode="cache"and MDS downgrades inshow_object(DA-044), enforced multi-scope/composite-ID live quota and proportional bounded fan-out (cache_control,change_report,DA-016,VVAH-MCP-QUOTA-01), validated explicit domains whenmgmt_nameis omitted (DA-045), validatedvalid_valuesonlist[enum]payloads (DA-055) and capped deduplicateddescribe_commandbatches at<= 50(VVAH-APIREF-01), and synchronized docs/specs (arodonata_distributed_locks,17tables,SSEEvent.encode()).
Added
- topology,scripts,specs: Added zero-argument self-detecting VSX route collection bundle script (
build_route_collection_repository_script()) emitting multi-VS bundles (===ARODONATA_VSX_BUNDLE_START===...===ARODONATA_VSX_BUNDLE_END===) with per-VS error isolation (===ARODONATA_VS_ERROR...===), bundle parser and slice extractor (parse_vsx_bundle_output(),extract_vs_slice_from_bundle(),VsxBundleSlice), and per-physical-node zero-argument CPRID bundle coalescing ((mgmt_name, node_key)) traced toREQ-TOPO-008(SCN-TOPO-008-4). - scripts,models,specs: Added safe Base64
"script-body"decoding inRepositoryScript.from_cp_dict()with shared_try_decode_base64_text()heuristic, giving explicit precedence to"script-body-base64"over"script-body"and eliminating Check Point R82 false-positive outdated script drift traced toREQ-CLIENT-010(SCN-CLIENT-010-4). - testing,emulator,specs: Added Check Point R82 parity in
FileReplayApiMock(encode_repository_script_body_base64=True), rejection of non-empty"args"on repository scripts whenallow_one_time_script=False(HTTP 400 err_validation_failed), synthetic zero-argument VSX bundle generation on VSX chassis nodes, and field-order-independentlist_virtual_systems()parsing traced toREQ-TOPO-018(SCN-TOPO-018-2). - sessions,rate_limiter,specs: Added principal identity logging (
username,user-name, or non-secret static identifier) on login throttle cooldown events inLoginGateandLoginCoordinatortraced toREQ-SESS-006(SCN-SESS-006-1). - mcp,security,specs: Added
MCPToolQuotaManager(src/arodonata/mcp/quota.py,QuotaDecision) wired intomcp_tool_guard(src/arodonata/mcp/errors.py) enforcing independent per-client_idsliding-window quotas (tool_rate_limit_per_minute=120,live_tool_rate_limit_per_minute=30, defaulting unauthenticated callers to"anonymous", emittingarlogiWARNINGlogs andarodonata.mcp_rate_limited/arodonata.mcp_client_idspan attributes, and returning structuredrate_limit_exceededJSONToolFailureresponses; closes SAST #6), unifiedArodonataMCPSettings.validate_security_policy()withallow_insecure_unauthenticatedopt-in (ARODONATA_MCP_ALLOW_INSECURE_UNAUTHENTICATED/--allow-insecure-unauthenticated),LOOPBACK_HOSTS/is_loopback_host(),REQ-MCP-012(SCN-MCP-012-1) andSCN-MCP-001-6..7inopenspec/specs/mcp-server/spec.md, and"mcp"hexagonal import-boundary enforcement (arodonata.adapters,arodonata.testing) intests/unit/test_architecture_boundaries.py(SCN-CLIENT-018-1). - openspec,tests: Added
REQ-TOPO-020(SCN-TOPO-020-1..3) inopenspec/specs/gateway-topology/spec.mdand comprehensive regression coverage intests/unit/test_topology_compat_and_security.pyspecifying shim compatibility, boundary SID redaction, and fail-fastServerIdentityErrorpropagation across live route collection and targeted topology refresh. - core,ports,specs: Added
arodonata.core.models.sentinels(canonical Check Point built-in UIDs, token sets, and sentinel normalizers),arodonata.core.primitives(UUID_RE,is_uuid,format_composite_id,parse_composite_id,normalize_str_sequence,MAX_IPV4_INT,mask_to_prefix_len,prefix_len_to_mask,effective_range_prefix_len,object_ipv4_bounds,parse_cidr_or_range_bounds),RulebaseRefreshPort, and AST architectural boundary tests intests/unit/test_architecture_boundaries.pytraced toREQ-CLIENT-018(SCN-CLIENT-018-1..3). - ports: Decomposed
CachePortinto eight@runtime_checkableInterface Segregation sub-protocols (DomainCachePort,SidCachePort,SyncStatePort,ObjectCachePort,ServiceCachePort,AssetCachePort,TopologyCachePort,RulebaseCachePort) and narrowed all core, checkpoint, CPCRUD, rulebase, and report cache consumers to the exact sub-protocols they use while preservingCachePortas the composite protocol.
Changed
- wave-9,architecture,performance: Precomputed
_RulebaseFilterIndexonce perfilter_numbered_rulebasecall (REQ-RULE-008), replaced quadratic per-object emulator scans with single-passcollect_referenced_uids()(REQ-ITEST-020), unified canonical object summaries insrc/arodonata/reports/_object_summary.py(REQ-REPORT-007), extracted shared typed cache sync/overlay engine_typed_cache_sync.py(REQ-CACHE-018), decomposedsearch_service.pyinto acycliccore/services/search/and extracted_asset_linking.py+_domain_discovery.py(REQ-CACHE-018,REQ-SESS-013), unified canonicalparse_domain_entry/parse_domain_dictincore/models/domains.pyand sharedopen_api_write_sessionlifecycle incore/context.pyalongsidedetails-level="standard"MDS fallback (REQ-SESS-013), and consolidated_HybridStateReaderBase(fixingget_service_by_nameexact-name guard),_DomainPlanStatesingle-pass step caching,_run_on_adopted_staged_session,_copy_prior_fields, and split per-typediffer.pyhelpers (REQ-CPCRUD-016). - cpcrud,rulebase,reports: Decomposed all 6 oversized domain-engine modules into cohesive, acyclic submodules (
<= 677LOC each) while preserving exact backward-compatible imports,arlogi.get_logger(...)channel names, and@tracedspan parity (cpcrud:state_reader.py→_state_reader_common.py,_state_reader_objects.py,_state_reader_services.py;planner.py→_planner_helpers.py,_planner_diff.py,_planner_entity_steps.py,_planner_rule_steps.py;executor.py→_executor_helpers.py,_executor_pass.py,_executor_staged.py;rulebase:refresh.py→collector.py;reports:collector.py→_collector_diffs.py,_collector_changes.py;renderer.py→_renderer_formatting.py,_renderer_html.py,_renderer_markdown.py), unifiedcollect_package_rulebase_sliceandcollect_domain_rulebase_snapshotover shared_traverse_rulebase_layersBFS traversal and_fetch_nat_package_ruleswith single-pass_extract_package_layers_and_seeds, and unified group/member payload metadata helpers (_append_common_create_metadata,parse_existing_member_entries). - testing,emulator: Decomposed
replay_mock.py(3,737 LOC),_emulator_crud.py(2,581 LOC), anddataset_generator.py(2,817 LOC) into cohesive, acyclic_replay_*,_emulator_*, and_dataset_*submodules (<= 626LOC each), consolidated shared projection, pagination, object-inlining, and rulebase-slicing helpers in_emulator_projection(project_replay_details_level,project_details_level,paginate_items,inline_rule_objects,slice_rulebase_with_sections), preserved all public and backward-compatible re-exports (FileReplayApiMock,FileReplayCliMock,ReplayStateSnapshot,ensure_enterprise_raw_dataset,generate_enterprise_raw_dataset,_normalize_subnet_fields), and verified byte-for-byte deterministic dataset parity. - mcp,core,client: Decomposed monolithic
src/arodonata/mcp/tools.py(2,457 LOC) into the cohesive, acyclicsrc/arodonata/mcp/tools/package (__init__,_common,_show_object,objects,lookup,topology,rulebase,admin,cpcrud) with every file<= 477LOC, full legacy helper/constant re-exports, deduplicatedRULEBASE_TYPE_TO_COMMANDand live collection fetching, and zeroclient._*private accesses orarodonata.adaptersimports; movedREADONLY_EXACT_COMMANDS,is_readonly_command,validate_command_name, andformat_host_attr_for_urlintoarodonata.core.primitives(preserving exact identity re-exports inarodonata.adapters.checkpoint.*); and exposedbuild_validated_trust_policy/TrustPolicyviaarodonata.clientplus publicresolve_api_version,ensure_and_load_snapshot, andresolve_implicit_domain_modemethods. - client,search,config,boundaries: Replaced monolithic
src/arodonata/client.pywith the cohesive, acyclicsrc/arodonata/client/package (_base,warmup,lifecycle,inventory,rulebase_reports,topology,__init__), movedfind_objectresolution intoSearchService.find_object()with cache fallbacks when optional sub-services are omitted and concurrent cross-domain Pass-1/Pass-2 cache lookups, consolidated repeated database initialization checks into_ensure_initialized(), removed the dead_CaptureExplicitAuthModevalidator fromArodonataSettingsand unused internal facade aliases, added"adapters"hexagonal import-boundary enforcement intests/unit/test_architecture_boundaries.py(SCN-CLIENT-018-1), and preserved exact 61@tracedspans, service properties, and sharedloggeridentity. - adapters,storage,checkpoint: Decomposed
cache_adapter.pyintosrc/arodonata/adapters/storage/cache/(_base,mappers,rulebase_mappers,control,inventory,topology,rulebase,__init__) with unified dialect upserts and removed 5 unused*_to_recordhelpers; splitsessions.py(response_classifiers,target_resolver,session_cleaner,session_credentials,sessions) andtransport.py(connection_pool,connector,transport) withPolicyBoundSSLContextvalidation and cleanLoginCoordinatorhelper boundaries. - topology,services: Decomposed
topology_service.pyandroute_collector.pyinto the cohesive, acyclicsrc/arodonata/core/services/topology/package (_shared,normalizer,objects,scoring,policy_rules,extractor,flow_matching,policy_matcher,diagnostics,reconciler,refresh,route_scripts,route_parsers,route_executor,route_collection,service) while keepingtopology_service.pyandroute_collector.pyas import-compatible re-export shims for__all__, public helpers, formerly re-exported route helpers ontopology_service, and exact sharedloggeridentity supporting method-level monkeypatching (topology_service.logger.warning), removing internalcollect_gateway_routesfromarodonata.core.services.topology.__all__, and emitting structuredWARNINGlogs alongsideDomainSyncFailedEventwhen targeted gateway topology refresh fails. - core,cpcrud,rulebase,mcp,testing: Moved
parse_cp_publish_timestamptocore.models.common,SERVICE_COMMAND_TYPES/NON_OVERLAY_MUTATION_TARGETS/update_overlay_from_commandtocore.context, andPolicyPackageInfo/extract_policy_packagestocore.models.rulebasewith 100% backward-compatible re-exports; eliminated hexagonal violations acrosscore,cpcrud, andrulebase; decoupledTopologyServiceviaRulebaseRefreshPortDI (logging a warning when omitted during cold package refresh); and migrated duplicate UUID/CSV/IPv4 helpers anddataset_generator.pysentinel literals to the unified core modules.
Fixed
- testing,emulator: Remediated Wave 6 audit findings across
src/arodonata/testing/: fixed NAT rule lock preflight whenpackageis omitted (str(None) == "None"bypass), preserved constructorfail_ssh_nodesdefaults acrossreset(), rotated all active SID bindings ondiscardbyuidand rejected mutations on non-open sessions, separatedproject_replay_details_level()(REPLAY_STANDARD_SUMMARY_KEYSexcluding"groups") from deterministicproject_details_level()(CRUD_STANDARD_KEEP_KEYSordered tuple), restoredmin_limit=0pagination behavior across_paginate_listandhandle_show_repository_scripts(now reusingpaginate_items()), enforced MDS/Global domain binding onassign-global-policy/assign-global-assignment, and routed both live writes andrun-scripttasks throughmock._apply_domain_mutation()andmock._next_task_id(). - topology,executor,coalescing: Fixed
execute_gateway_cli()in repository mode to return extracted per-target Virtual System slices with attachedbundle_stdout(instead of raw chassis bundles), fail closed on missing bundle markers (vsx_bundle_missing) or truncated bundles (vsx_bundle_truncated), preserve run failure status without discarding error messages, and isolate coalesced leader cancellations via non-cancellation exceptions to protect sibling followers across independent gateways. - tls,platform: Added Windows cross-process file locking via
msvcrt.locking(lock_fd, msvcrt.LK_LOCK, 1)inTrustStore._save_atomic()and non-blockingmsvcrtlocks inIntegrationRunLock, resolving Windows platform compatibility and file contention races. - cpcrud,rulebase,reports: Fixed intra-plan virtual overlay coherency in
PlannerandHybridStateReadersogroupandservice-groupOutcome.UPDATEpaths record updated models (members,comments,color,tags,new-name,raw_data) in the virtual overlay, object/service updates,DELETEtombstones, fresh-cachedns-domainleading-dot lookups, andres_map/Plan.name_resolutionsstay coherent across subsequent template steps (including clearing stale rename aliases upon re-creation and pruning deleted targets), same-templateCREATE -> UPDATE/CREATE -> DELETElinkdepends_onand emit valid"name"wire identifiers instead of synthetic"planned:"UIDs (REQ-CPCRUD-003/SCN-CPCRUD-003-6),Executor._stream_single_passroutes head-freshness checks and invalidation throughExecutor._check_current_domain_head/Executor._invalidate_domain,_traverse_rulebase_layersbackfillsparent_layer_uid/parent_rule_uidonto queued pre-seeded inline/domain layers (SCN-RULE-001-2), and_discover_target_sessionsappliesredact_sid()/sanitize_mapping()across session listing errors andRawResponsepayloads. - mcp,security,server: Enforced
ArodonataMCPSettings.validate_security_policy()across all three MCP entry points (arodonata-mcpCLI,create_mcp_server(), andcreate_asgi_app()), failing closed on wildcardallowed_hosts/allowed_originswhile DNS rebinding protection is active and on unsafeauth_mode="none"configurations (non-loopbackhost, disabled DNS rebinding protection, non-loopbackallowed_hosts/allowed_origins, wildcards,allow_write_api, orcpcrud) unlessallow_insecure_unauthenticated=Trueis explicitly set (closing SAST #1, #2, and #5), bracketed IPv6 literals (::1,::,fe80::1) inAuthSettings.issuer_urlviaformat_host_attr_for_url(), eliminated split-brain drift increate_asgi_app(mcp_server=...)(allowing matchingsettingsparity while rejecting conflicts andtrust_policyoverrides), ensured CLI exits cleanly with code2on factory errors with singleSECURITY WARNINGemission and managed client disposal, fixedcollect_known_sids()to inspect active dedicated SIDs viaArodonataClient.get_active_dedicated_sids()and retained closed dedicated SIDs forapi_callredaction, isolated per-caller (client_id[:user_id]) CPCRUD plan signatures / stores / staged sessions with automatic discard+logout on eviction, charged cold/stalesmartsyncs, domain-miss refreshes, and live fallbacks tolivequota once per call viaMCPToolQuotaManager.check_and_consume_live_only(), mapped invalid ISO-8601 dates inchange_reportto actionableToolFailure, protected structuredToolFailurecore JSON keys, and restored forwarding_ensure_and_load_snapshot/_resolve_implicit_domain_modewrappers onCachedRulebaseSourceandSearchService. - tls,security: Bound
FingerprintTCPConnectorSSLContextcreation explicitly to validatedTrustPolicyviaPolicyBoundSSLContext(TrustPolicy.create_ssl_context(),create_verified_ssl_context(), and upfrontTrustPolicyvalidation inFingerprintTCPConnector, removing unreferenced_DEFAULT_CHECKPOINT_SSL_CONTEXT), prevented failed concurrent TOFU merges or disk write errors inTrustStore.record()/_save_atomic()from poisoning in-memory_entries, added structuredarlogiWARNINGaudit logs on first-contact TOFU andlab-memoryacceptance (event="tls_tofu_first_contact") plusERROR/WARNINGlogs on certificate mismatch/rejection/missing cert, and recordedarodonata.tls_decisionspan attributes (including"stored_match"for legacy known-hosts entries) viaspan_attrs()(SCN-TRANS-002-6, closing SAST #3 and #4). - sessions,client: Prevented unbounded recursion in
LoginCoordinatormax-sessions recovery (allow_max_sessions_cleanup=FalseonSessionCleanerlogins plus per-management_cleaning_max_sessionsguard), preserved live fresh cached SIDs across all principals and domains regardless ofseed_system_sidwhile logging out (logout_sid) and evicting only the active principal's expired cached SIDs, and eliminated the duplicateinvalidate_domain()call when publishing viaArodonataClient.api_call(). - topology,scripts,security: Enforced regex-based
redact_sid()at Pydantic model boundaries (GatewayCliResult,GatewayRouteCollectionStatus,DomainSyncState.last_error,RefreshOutcome.failed_domains,SyncProgressEvent.error,DomainSyncFailedEvent,ScriptTargetExecutionResult, andRepositoryScriptExecutionOutcome), threadedknown_sidsthroughScriptRepositoryService.run_repository_script()(covering internally openedarodonata-run-repo-scriptsessions as well as injected getters), scrubbed SSH-only and_vs_error=GatewayCliResultpaths, scrubbed targeted refreshWARNINGlogs, propagated fatalServerIdentityErrorfail-fast (withasyncio.TaskGroupsibling cancellation and clean dedicated-session logout, without downgrading domainroutessync states) across both targeted gateway topology refresh (_stream_targeted_gateway_refresh) and live route collection (execute_gateway_cli,collect_gateway_routes,AutoScriptModeResolver), and restored legacycpridfallback error formatting when an injectedgateway_clicallback returnsNone. - testing,sentinels: Resolved UID
6c488338-8eec-4103-ad21-cd461ac2c476misclassification in the replay emulator by removingDROP_UID_ALTand mapping it canonically toPolicy Targets(type="Global"), matching Check Point Management API semantics (6c488338-8eec-4103-ad21-cd461ac2c473remainsDrop), and switched_normalize_action/_normalize_trackto validate strictly againstACTION_UID_TO_NAME/TRACK_UID_TO_NAME. - cpcrud,primitives: Implemented single-pass contiguous netmask validation in
mask_to_prefix_len(supporting integral floats such as24.0and explicitallow_hostmask/allow_prefix_intflags) and addedstrict=Truevalidation innormalize_mask_lengthfor desired CPCRUD network specs so invalidmask_length4orsubnet_maskvalues raiseValidationErrorinstead of being silently dropped.
v2.6.6 (2026-11-19)
Fix
- core,cpcrud,mcp,reports,specs: adopt traceable OpenSpec schema, resolve Phase 1b audit findings, and achieve 100% spec coverage (#94)
Added
- openspec,tests: Forked minimal
arodonataOpenSpec schema (openspec/schemas/arodonata/) enforcingREQ-<DOM>-<NNN>andSCN-<DOM>-<NNN>-<K>scenario traceability across all 12 domain specifications (132requirements,284scenarios), registered@pytest.mark.spec(...)inpyproject.toml, addedscripts/check_spec_traceability.pywithtests/unit/test_check_spec_traceability.pyand.github/workflows/specs.yml, and achieved 100% scenario test coverage (0untested baseline scenarios) viatests/spec/. - reports: Added symmetric per-object
Field DiffsMarkdown column support alongside ruleField Diffsinrender_change_report(). - docs: Synchronized
docs/architecture/documentation withv2.6.5, addeddocs/examples/13-gateway-topology-matching.md, and documented Check Point Management Web API quirks and workarounds indocs/troubleshooting/checkpoint-api-quirks.md.
Fixed
- security,sessions,telemetry: Validated explicit
server_ipviaresolve_target_ips()and enforced resolved MDS rate-limit slots inLoginCoordinator.logout_sid()and cache-hitget_readonly_session()(FC-01), and added recursivesanitize_mapping/ sequence /bytesredaction incore/telemetry.py(span_attrs,_coerce_span_value) so credentials and session tokens never leak into OpenTelemetry spans (FC-02). - client,mcp,search,cpcrud,topology,testing: Determined ephemeral database cleanup on close from the actual SQLAlchemy engine URL in
ArodonataClient.close()andAMgmtClient.close()(FC-03), auto-upgraded coldlist_domains(cache_mode="cache")(FC-04), normalized mixed-case canonicalgroup_byfields inSearchService.query_objects()(FC-05), diffed existing auto-named entities underon_ip_conflict="create_new"inPlanner(FC-06), completed audit findingsFC-07–FC-12(including syntheticshow-tasklog status codes inFileReplayApiMock), and removed the deadlive_compatconfiguration flag.
v2.6.5 (2026-11-18)
Feat
- scripts,topology,testing: add Check Point Script Repository service, route modes, and emulator (#92)
- cpcrud,reports,config: add incremental rule/URL diffs, naming profiles, and dry-run plan reports (#91)
Added
- config,cpcrud: Extended
NamingPrefixes(src/arodonata/core/config.py, re-exported inarodonata.cpcrud.models) withrange_separator,compress_range_same_subnet,group_suffix,app_site,app_site_wildcard_marker,format_group(), andformat_app_site(), and wiredArodonataSettings.cpcrud_naming_prefixes(ARODONATA_CPCRUD_*and fallbackCPCRUD_*environment variables without implicit.envloading) as the default profile inCPCRUDServiceandPlanner. - cpcrud: Added
arodonata.cpcrud.expressions(parse_object_expression,parse_range_token,parse_app_site_expression,parse_service_expression,parse_group_expression,expand_group_expression,normalize_wildcard_domain,wildcard_domain_to_cp_regex_urls) for pure shorthand parsing of hosts, CIDRs, compressed same-/24ranges,.domainDNS objects,*domain/*.domainCheck Point regexapplication-sitespecs, services, and recursive nested inline groups. - cpcrud,testing: Added
{"add": [...], "remove": [...]}incremental patch support incheckpoint_ops_schema.json,FieldChange(added_items,removed_items),differ.py(application-site.url-listand Access/HTTPS/Threat/NAT rule cellssource,destination,service,protected-scope,site-category,install-on),Planner(depends_onordering, UID dereferencing in_build_prior_rule_state, case-folded non-regexurl-listvalue reuse vianormalize_app_site_url_key),inverse.pyrule rename rollback, andFileReplayApiMock(_emulator_crud.py,_emulator_changes.py). - reports,client: Added offline Dry-Run
ChangeReportsynthesis viabuild_change_report_from_plan()(src/arodonata/reports/plan_report.py, re-exported viaarodonata.reports,arodonata, andArodonataClient.build_change_report_from_plan) for pre-session HTML, Markdown, and JSON previews viarender_change_report(). - scripts,client: Added application-agnostic Check Point Script Repository support via
ScriptRepositoryService(src/arodonata/core/services/script_service.py), models and normalized body helpers (CpridScriptMode,RepositoryScript,RepositoryScriptStatus,EnsureRepositoryScriptResult,ScriptTargetExecutionResult,RepositoryScriptExecutionOutcomeinarodonata.core.models.scripts), typed SID-redacted exceptions and shared classifiers (RepositoryScriptError,RepositoryScriptNotFoundError,RepositoryScriptPermissionError,is_script_permission_error,is_unsupported_script_command_errorinarodonata.core.errors), and@tracedArodonataClientmethods (get_repository_script,list_repository_scripts,check_repository_script,ensure_repository_script,delete_repository_script,run_repository_script) with"repository-script","api-key","md-permissions-profile", and"domain-permissions-profile"excluded fromSessionOverlay(NON_OVERLAY_MUTATION_TARGETS). - config,topology,testing: Added
ArodonataSettings.cprid_script_mode("inline" | "repository" | "auto", default"inline", envARODONATA_CPRID_SCRIPT_MODE) andcprid_repository_script_name(ARODONATA_CPRID_REPOSITORY_SCRIPT_NAME, default"arodonata-collect-routes-v1"), canonical parameterized bash route-collection script (build_route_collection_repository_script(),format_route_collection_repository_args()), single-flightAutoScriptModeResolver"auto"probing without semaphore starvation,check_route_collection_script()/ensure_route_collection_script()helpers, fail-closedGatewayRouteCollectionStatus.error_codereporting, stateful per-domainrepository-scriptCRUD and permission emulation inFileReplayApiMock, and gated live lifecycle integration testtests/integration/b3/test_repository_scripts_live.py.
Fixed
- cpcrud: Enforced fail-closed
Outcome.ERROR/DiffSafetyErrorinvariants preventing unsafe"Any"widening (blocking removals that empty rule cells orapplication-site.url-listwithoutapplication-signature, requiring explicit"Any"removal when narrowing"Any"cells while stripping"Any"from Check Point wireremove, blocking incremental{"add": ["Any"]}, rejectingset/updatetargeting missing entities, rejecting unmatched rules carrying{add, remove}cell deltas under any verb, and preservingrule_numberpositional renames understrict_name). - context,scripts: Consolidated
SYSTEM_DOMAIN_KEY,normalize_domain_key(), and sharedopen_api_write_session()inarodonata.core.contextsoScriptRepositoryService,DomainService,LoginCoordinator, andArodonataClient.write_session()share identical"System Data"scoping without cross-domainWriteSessionbleed ondomain=None, and restored lenient UTF-8 / control-character Base64 task decoding (decode_base64_task_message).
v2.6.4 (2026-11-16)
Feat
- testing: expand replay dataset v1.2.0 with heterogeneous domain gateways (#88)
- testing,cpcrud: add replay policy verification, inline layers, and staged session discard (#87)
Added
- testing: Upgraded
dataset_generator.pyandtests/fixtures/enterprise_raw_dataset/toDATASET_VERSION = "1.2.0"(341total domain assets,315policy-enforcing gateways,325CLI routing targets), adding+7standalonesimple-gatewayappliances,+7CpmiGatewayClusterHA clusters (14cluster members),+4CpmiVsxNetobjVSX chassis hosts, and+25local and cross-domainCpmiVsNetobjVirtual Systems with unique per-domain gateway/interface IPs and Virtual System internal/24subnets and completeCpmiVsxSlotObj/CpmiVsSlotObjcoverage across all VSX chassis hosts so every user MDSM domain (Branch,Regional,WAN_Core,Perimeter,Transit,DC_Spine,DC_Pod,DB_Seg,Partner_DMZ) exercises heterogeneous appliance, cluster, Virtual System, and cross-domain VSX topologies. - testing: Extended
FileReplayApiMock(_emulator_crud.py,_emulator_models.py,replay_mock.py) withverify-policyandinstall-policytask simulation,access-layer/ inline-layer CRUD (add-access-layer,set-access-layer,delete-access-layer,show-access-layer), andshow-https-rulebase/show-threat-rulebase(https-rule,threat-rule) CRUD andwhere-usedresolution (#87).
Fixed
- cpcrud,client: Propagated
ArodonataClient.logout_sid()notifications throughCPCRUDService.notify_sid_logged_out()andExecutor.notify_sid_logged_out()soStagedSessionInfo.clear_sid()clears logged-out SIDs while preserving session provenance for externalpublishordiscardadoption (#87).
v2.6.3 (2026-11-14)
Feat
- testing,cpcrud: add stateful Check Point replay emulator and MDSM session lifecycle (#85)
Added
- testing: Extended
FileReplayApiMockandCheckPointReplayHttpServer(src/arodonata/testing/_emulator_models.py,_emulator_crud.py,_emulator_changes.py,replay_mock.py,mock_server.py) into a stateful Check Point Management and MDSM replay emulator supporting per-sidstaging overlays, read-your-own-writes isolation, read-only session enforcement, cross-session object locking (generic_err_object_locked),set-session,take-over-session,switch-session,publish,discard,logout, and structuredshow-changesdeltas. - testing: Implemented stateful CRUD, bidirectional group membership maintenance, Check Point uniqueness checks, and referential integrity validation (
generic_err_object_cannot_be_deleted) across hosts, networks, address ranges, DNS domains, application sites, groups, TCP/UDP/ICMP/ICMPv6/other services, service groups,show-unused-objects/delete-unused-objects, and Access/NAT rules and sections with automaticrule-number, section bounds,objects-dictionary, andwhere-usedrecomputation. - testing: Added MDSM
Globaldomain visibility for local reads, local write protection (generic_err_object_read_only), andassign-global-assignment/assign-global-policytask emulation, and upgradeddataset_generator.pytoDATASET_VERSION = "1.1.0"withmds/show-global-assignments.jsonand deterministicGlobalreferences in Access rule#104. - testing: Added fast in-memory state management (
ReplayStateSnapshot,snapshot_state(),restore_state(),reset()), SID-redactedcall_logrecords, and test assertion helpers (get_calls(),assert_no_global_mutations(),assert_no_full_object_scans(),assert_command_called(),assert_command_not_called()), plus comprehensive E2E test suites and updated documentation indocs/guides/enterprise-replay-mock-server.md.
Fixed
- cpcrud: Updated
Executor._extract_published_session_uid()and shared_resolve_session_uid()insrc/arodonata/cpcrud/executor.pyto extract published session UIDs fromshow-tasktask-details[].revisionandpublishResponsepayloads without redundant pre-publishshow-sessionround-trips.
Security
- testing: Gated
CheckPointReplayHttpServer/__testing__/*control endpoints behind opt-inenable_test_control=False(--enable-test-control) andX-Arodonata-Test-Token/ activeX-chkp-sidauthentication, enforced domain session pinning onFileReplayApiMock, and verified zero raw SID or credential leakage acrosscall_logentries and OpenTelemetry spans.
v2.6.2 (2026-11-14)
Fix
- search,mcp,testing: normalize Cpmi asset aliases, group_by aliases, and replay where-used (#83)
Added
- models,testing: Added
ASSET_TYPE_EQUIVALENTS,QUERY_GROUP_BY_ALIASES,expand_asset_type(), andexpand_asset_types()inarodonata.core.models, and implementedwhere-used(direct and indirect groups, access control rules, NAT rules viashow-packages, andSystem Datapackage metadata) plususe-object-dictionary=Falseinline object dictionary expansion and layer/package UID lookup inarodonata.testing.replay_mock.FileReplayApiMock.
Fixed
- search,assets,mcp: Expanded
Cpmi*internal Check Point asset type aliases (CpmiGatewayPlain<->simple-gateway,CpmiGatewayCluster<->simple-cluster,CpmiClusterMember/CpmiVsxClusterMember<->cluster-member/vsx-cluster-member,CpmiVsxNetobj/CpmiVsxClusterNetobj<->vsx-gateway/vsx-cluster,CpmiVsNetobj/CpmiVsClusterNetobj<->virtual-system/vs-netobj,CpmiHostCkp<->checkpoint-host) acrossSqlCacheAdapter.get_assets(),AssetRefreshService.get_assets(),SearchService.search_objects(),SearchService.query_objects(), and MCPlist_assets, and mappedquery_objectsgroup_byaliases (domain->domain_name,mgmt/server/management->mgmt_name,object_type/asset_type/service_type->type,orig_domain->original_domain) so grouped results preserve domain/server metadata and emit both requested alias keys and canonical column keys.
v2.6.1 (2026-11-13)
Fix
- transport,sessions: pool dedicated-session keep-alive sockets and harden lifecycle (#81)
Changed
- transport,sessions: Reuse fingerprint-verified keep-alive HTTPS connections across sequential non-boundary commands within dedicated sessions (
WriteSession/ explicitsid) via non-reversible SHA-256session_scope, while isolating shared read-onlyshow-*pooling and enforcingConnection: closeon session-boundary and un-scoped mutating commands. - transport: Use a pre-built lightweight TLS 1.2+
SSLContextwithout disk CA bundle loads for fingerprint-verified Check Point connections.
Fixed
- transport: Prevent
aiohttp.ServerDisconnectedError(0-byte EOF) caused by stale idle pooled sockets and Check Pointhttpd2MaxKeepAliveRequests(100) exhaustion by evicting matching idle sockets before non-pooled or fresh session handshakes, rotating pooled sockets at95requests inFingerprintTCPConnector, and closing session-scoped sockets onlogout_sid.
v2.6.0 (2026-11-13)
Feat
- sync,rulebase,topology,cpcrud: add lightweight package catalog, targeted lookups, and unreachable server resilience (#79)
Added
- Lightweight Policy Package Catalog & Targeted Single-Package Rulebase Synchronization (
RulebaseRefreshService,CachedRulebaseSource,CachePort,SqlCacheAdapter,ArodonataClient):- Added
RulebaseRefreshService.refresh_policy_packages()andArodonataClient.refresh_policy_packages()(scope="rulebase",item_type="packages"), synchronizingPolicyPackageInfometadata viashow-packagesandCachePort.replace_domain_rulebase_packages()without downloading NAT, HTTPS, threat-prevention, or access rulebases whenget_policy_packages(..., cache_mode="smart")runs on a cold domain. - Added
RulebaseRefreshService.refresh_package_rulebase()andArodonataClient.refresh_package_rulebase()(scope="rulebase",item_type="package:<rulebase_type>:<package_uid>"), synchronizing only the target package's catalog metadata, ordered layers for the requestedrulebase_type, Global placeholder expansions, and referenced inline sub-layers viaCachePort.upsert_domain_rulebase_layers()without stampingitem_type="*"or fetching sibling packages, while keepinglocate_rules()gated on a fullitem_type="*"domain snapshot.
- Added
- Single-Flight Background Cache Warm-Up Status & Static Topology Candidate Filtering (
ArodonataClient,WarmupStatusEntry,TopologyService,STATIC_TOPOLOGY_SOURCES):- Coalesced concurrent
ArodonataClient.start_object_cache_warmup()calls by(mgmt_name, domains, types, include_global, include_services, force), suppressed unretrievedasyncio.Taskexception warnings for fire-and-forget callers with SID-redacted structured warning logs, and addedArodonataClient.get_warmup_status()returningWarmupStatusEntry(running,completed,failed,cancelled). - Added
STATIC_TOPOLOGY_SOURCES,source_types: Sequence[TopologySourceType] | None = None, andinclude_annotations: bool = Trueparameters toTopologyService.find_affected_gateways()andArodonataClient.find_affected_gateways()so callers can restrict candidate matching to static SmartConsole topology intervals without mutating cached route or annotation rows.
- Coalesced concurrent
- Check Point
show-objectsReplay Support (FileReplayApiMock): Implementedshow-objects(type,filter,ip-only,details-level,limit,offset) acrossobjects_raw.json,services_raw.json, andgateways_and_servers.jsoninarodonata.testing.replay_mock.FileReplayApiMock.
Changed
- Replaced full-domain
DEFAULT_OBJECT_TYPES(show-hosts,show-dns-domains) refreshes during coldTopologyService.refresh_topology()andstream_refresh_topology()with targeted on-demandshow-objects/show-group/show-objectresolution across the target domain and"Global"persisted viaCachePort.upsert_objects()without stamping whole-domain"objects"sync slices, while re-validating cached groups/objects whenever"objects"sync states lag behind a newer domainpublish(src/arodonata/core/services/topology_service.py). - Switched cold-cache CPCRUD value-conflict lookups (
find_host_by_ip,find_network_by_subnet,find_range_by_bounds,find_tcp_udp_serviceinHybridStateReader) to targetedshow-objectsqueries with exact attribute verification, intra-plan virtual overlays, andgeneric_err_command_not_recognizedfallback instead of paginating full-domainshow-hosts,show-networks, orshow-services-tcp/show-services-udp, while retaining single-pageshow-services-icmp/show-services-icmp6listing forfind_icmp_service(src/arodonata/cpcrud/state_reader.py).
Fixed
- Hardened multi-server (
mgmt_name=None) domain discovery and scoped synchronization against unreachable management servers (DomainService.get_domains(),DomainSyncCoordinator,LoginCoordinator): caught transport/authentication errors duringshow-domainsdiscovery and pagination without redundant RBACdetails-level="standard"retries on transport failure or pointless MDS self-failover, continued syncing reachable management servers while recording unreachable servers inRefreshOutcome.failed_domains, and suppressed unrelated server failures when all explicitdomainsresolved on reachable servers. - Refined
SearchService.search_objects()andObjectServicesoexact_match=Trueexcludes wider containing supernets on IPv4/CIDR queries, mixedtypes=["host", "network", "gateway"]filters strip non-object types beforeObjectServiceAPI calls while refreshing and matching gateway/VSX assets fromarodonata_assets, and asset-onlysearch_objects(..., max_depth > 0)still loads group hierarchy nodes (src/arodonata/core/services/search_service.py,src/arodonata/core/services/object_service.py). - Updated MCP listing/search and
query_objects(..., aggregate="describe")cold-cache handling (src/arodonata/mcp/tools.py) to reportcache_age_seconds: nullwhen nosynced_attimestamp exists, search across all configuredmgmt_nameswhenmgmt_nameis omitted, and auto-upgradecache_mode="cache"to"smart"whenever a scope has0sync state stamps (including whenarodonata_objectsholds only partial topology-hydrated rows).
v2.5.0 (2026-11-11)
Feat
- testing,topology: add enterprise raw-replay scale suite and HTTPS mock server (#76)
- topology: add policy/NAT topology inference, VPN domain extraction, and policy reconciliation (#75)
- topology: add route collection, reconciliation, annotations, and confidence scoring (#73)
Fix
- sync,topology: batch Core cache writes, serialize VSX route CLI, and harden single-flight locks (#77)
- sessions: fail fast on unreachable login transport and suppress startup cleanup tracebacks (#74)
Added
- Gateway Topology Diagnostics, Live Route Collection via SSH Dependency Injection &
cpridFallback, Static-vs-Route Reconciliation, Persistent Administrator Annotations, IPAM Prefix Export, and Evidence Delta Confidence Scoring (arodonata.core.models.topology,arodonata.core.services.route_collector,arodonata.core.services.topology_service,arodonata.adapters.storage,ArodonataClient,arodonata.mcp.tools):- Static Topology Health Diagnostics (
get_topology_diagnostics()): Detects incomplete or untrustworthy SmartConsole interface topology settings (not_defined,routing_defined_without_routes,anti_spoofing_detect_or_off,unresolved_specific,empty_specific,missing_ip_mask,no_interfaces) while treating internal-only segmentation gateways as valid (zero warnings) and classifying single-interface or external-only service-graph gateways (e.g., Cisco ACI) asone_arm_topology(severity="info"). - Live OS/Clish Route Collection (
collect_gateway_routes(),GatewayCliPort,GatewayCliCallable): Collects live IPv4 routing tables (connected_route,gaia_static_route,clish_route,bgp_route,ospf_route, and0.0.0.0/0default routes) across simple gateways, cluster members (detecting cross-member route drift), and VSX Virtual Systems (viavsenvcontext switching on the physical VSX parent,$FWDIRCTX%05dverification, and dynamicvsx stat -lVSID lookup), invoking an injected SSH bash callback first and falling back to Check Point Management APIrun-script(cpridviaTaskWaiter). - Targeted Per-Gateway Refresh:
refresh_topology(..., gateways=..., collect_routes=...),stream_refresh_topology(..., gateways=..., collect_routes=...), andCachePort.replace_domain_topology(..., gateway_uids=..., source_types=..., active_gateway_uids=...)refresh and replace cached topology/route rows for specific gateways without re-downloading or deleting other gateways in the domain while pruning orphaned live routes on full domain refresh. - Static vs. Live Route Reconciliation (
reconcile_gateway_topology()): Compares SmartConsole static topology intervals against live CLI-collected routing intervals and across cluster members to reportTopologyReconciliationReportdiscrepancies (stale_in_topology,missing_in_topology,interface_mismatch,default_route_mismatch,cluster_member_drift,resolved_by_routing). - Persistent Administrator Annotations & IPAM Export (
arodonata_topology_annotations,upsert_topology_annotations(),get_topology_annotations(),delete_topology_annotations(),export_topology_prefixes()): Persists administrator dispositions (confirmed,standby_dynamic,ignore,manual),trust_static_topologyoverrides, and IPAM metadata (zone,site,comment,custom_metadata) across topology resyncs and exports consolidated prefix inventories. - Evidence Delta Confidence Scoring (
TopologyConfidenceWeights,ConfidenceDelta): Computes endpoint and flowconfidence(0.0..1.0),is_standby_path, andconfidence_factorsonTrafficFlowMatchandAffectedGatewayCandidate(withmin_confidenceandinclude_standbyfilters onfind_affected_gateways()and MCPlocate_gateways). - Stage 2 Policy & NAT Topology Inference, VPN Encryption Domain Extraction, and Policy-vs-Topology Reconciliation:
- Extracts gateway and cluster
vpn-domain(encryption-domain) references (honoringvpn-domain-type), recursively expands referenced network/group objects intoarodonata_gateway_topology(source_type="vpn_domain"), and appliesvpn_encryption_domain(+0.45) in confidence scoring. - Evaluates cached installed Access Control (
arodonata_rulebase_access_rule) and NAT (arodonata_rulebase_nat_ruleoriginalandtranslated) rules infind_affected_gateways(..., include_policy_inferred: bool = True)and MCPlocate_gateways(..., include_policy_inferred: bool = True), awarding+policy_rule_evidence(+0.25) to cross-interface L3 candidates and discovering one-arm (e.g., Cisco ACI service-graph) and incomplete-topology gateways withmatch_type="policy_inferred". - Adds
check_policy: bool = Falsetoreconcile_gateway_topology()(TopologyServiceandArodonataClient) to detectpolicy_topology_mismatchdiscrepancies when enabled Access or NAT rules explicitly targeting a gateway viainstall_onhave no explicit source or destination intervals overlapping that gateway's internal topology or routes.
- Extracts gateway and cluster
- Static Topology Health Diagnostics (
- Enterprise Raw-Replay Topology Scale Suite, File-Backed Check Point API/CLI Replay Doubles, and Standalone HTTPS Mock Server for Downstream Applications (
arodonata.testing,tests/fixtures/enterprise_raw_dataset/,tests/unit/test_topology_raw_replay_scale.py,docs/guides/enterprise-replay-mock-server.md):- Deterministic Enterprise Raw Dataset & Generator (
ensure_enterprise_raw_dataset(),generate_enterprise_raw_dataset()): Fixed-seed (20261108) generator producing raw Check Point Management API JSON files and gateway CLI routing outputs across 9 MDSM user domains (Branch,Regional,WAN_Core,Perimeter,Transit,DC_Spine,DC_Pod,DB_Seg,Partner_DMZ) plusGlobal(284 total assets / 276 policy-enforcing gateways, 2,951 network objects with 7-level nested groups, 210 services, 1,050 access rules, 120 NAT rules, and 279 CLI routing targets). - File-Backed Replay Adapters (
FileReplayApiMock,FileReplayCliMock): FullApiPortandGatewayCliPortimplementations reading raw fixtures from disk with pagination (limit,offset,from,to,total),details-level(uid,standard,full),uid/nameandclass-namefiltering,run-script+show-taskBase64 task execution, VSXvsenv/vsx stat -l/CTX%05dbash validation, per-domain/per-command/per-node call counters, and in-memory mutation helpers for targeted refresh testing. - Standalone & Embeddable Check Point HTTPS Mock Server (
CheckPointReplayHttpServer,python -m arodonata.testing.mock_server):aiohttp.webHTTPS server servingPOST /web_api/{command}with auto-generated self-signed TLS certificates,/web_api/logincredential validation, domain-boundX-chkp-sidsession tracking, and dynamic CMA/MDSipv4-addresshost rewriting in/web_api/show-domainsso external applications (MMP, FPCR) can pointArodonataClientatlocalhost:<port>(8443or443) without hardware appliances or artificial rate limits. - Smart Route Collection Caching & Per-Domain
cpridSession Reuse (TopologyService,execute_gateway_cli):refresh_topology(..., collect_routes=True, mode="smart")now skips redundant SSH/cpridroute collection for unchanged domains whoseDomainSyncState(scope="topology", item_type="routes", status="ok")is withincache_ttl(while retrying domains with partial gateway failures), andcollect_gateway_routes()reuses at most one dedicatedrun-scriptsession per(mgmt_name, domain_name).
- Deterministic Enterprise Raw Dataset & Generator (
- Configurable Domain Sync & Route Collection Concurrency Knobs and Lightweight Rulebase Package Queries (
ArodonataSettings,CachePort.get_domain_rulebase_packages,SqlCacheAdapter,CachedRulebaseSource):- Added
domain_sync_concurrency(ARODONATA_DOMAIN_SYNC_CONCURRENCY, auto-defaultmin(2, max(1, concurrent_limit - 1))),route_collect_concurrency(ARODONATA_ROUTE_COLLECT_CONCURRENCY, auto-defaultmin(4, max(1, concurrent_limit // 2))), andmax_routes_per_gateway(ARODONATA_MAX_ROUTES_PER_GATEWAY, default50000) onArodonataSettings. - Added
CachePort.get_domain_rulebase_packages()(SqlCacheAdapter.get_domain_rulebase_packages) to loadpackage_layersand distinct NAT package metadata without reading full rule tables during topology extraction, route collection, andCachedRulebaseSource.get_policy_packages().
- Added
Changed
- Replaced per-row SQLModel ORM
session.add()writes acrossSqlCacheAdapter.replace_domain_objects(),replace_domain_services(),replace_domain_assets(),replace_domain_topology(), and all sevenreplace_domain_rulebase()tables with chunked SQLAlchemy Core multi-rowINSERTbatches (_insert_rows_batched,_BATCH_ROWS = 500) and direct_*_to_rowdictionary builders to eliminate ORM identity-map memory spikes on large Check Point domains (src/arodonata/adapters/storage/cache_adapter.py). - Moved cross-domain VSX parent/child reconciliation (
AssetRefreshService._reconcile_cross_domain_vsx) from per-domain sync handlers to once per refresh run with afinally:fallback so earlystream_refresh_assets()disconnects or mid-run exceptions still reconcile committed domains (src/arodonata/core/services/asset_service.py).
Fixed
- Shared per-MDS domain sync semaphores and
(mgmt_name, domain_name, scope)single-flight coalescing process-wide across coordinators attached to the same database engine (weakly keyed perAbstractEventLoop), while reusing the caller's active MDS permit viaContextVaron nested re-entrantDomainSyncCoordinator.ensure()calls so empty-cache asset lookups insideTopologyService._sync_domain_topology()cannot deadlock (src/arodonata/core/services/sync_coordinator.py). - Serialized gateway CLI/
cpridroute collection per physicalnode_uidbefore acquiring the per-management concurrency slot so multiple VSX Virtual Systems sharing oneVS0chassis execute sequentially without starving independent gateways, coalesced identical concurrentrefresh_topology()andcollect_gateway_routes()calls while preserving waiterCancelledError(asyncio.timeout), capped collected routes in a singleip -4 route showawkpass (skippingclish -c "show route"above10,000kernel routes), and emitted truncation warnings strictly when routes are dropped beyondmax_routes_per_gateway(src/arodonata/core/services/topology_service.py,src/arodonata/core/services/route_collector.py). - Failed fast on unreachable management login transport errors without redundant retries and suppressed noisy startup session-cleanup tracebacks (
src/arodonata/adapters/checkpoint/sessions.py).
v2.4.1 (2026-11-05)
Added
- Streaming gateway topology refresh progress (
TopologyService.stream_refresh_topology()andArodonataClient.stream_refresh_topology()), yieldingDomainSyncProgressEventitems across"assets","objects", and"topology"phases along with per-gatewaygateway-topologyprogress events carryinggateway_uid,gateway_name,gateway_type,installed_access_policy, andinterval_count(src/arodonata/core/services/topology_service.py,src/arodonata/client.py).
Fixed
- Resolved each gateway's single active policy package (
installed_access_policyand single-elementpolicy_packages) inTopologyService._resolve_gateway_installed_policy()by explicitpolicy.access-policy-name(whenaccess-policy-installedis truthy), latest installation timestamp acrossinstallation-targets-revision/access-policy-installation-date, single-packageinstallation-targetsmembership, or single-package domain fallback rather than assigning all domain packages to every gateway in multi-package domains (src/arodonata/core/services/topology_service.py,src/arodonata/core/models/topology.py). - Parsed Check Point
"leads-to-specific-network"interface topology dictionaries (with inlinesubnet4/mask-length4fallback) in_normalize_interface()and CPMIdestination/nextHop/interfaceNamestatic route objects in_parse_route_destination()/_parse_route_nexthop_and_interface()(src/arodonata/core/services/topology_service.py). - Evicted cached read-only session SIDs (
arodonata_sid_cache) immediately uponApiTimeoutErrororTransportErrorinAMgmtClient.api_call(), and allowedDomainSyncCoordinator.probe_domain_staleness()to recover transiently failed sync state rows (status="failed"with matchinglast_published_at/last_session_uidandobject_count > 0) back tostatus="ok"without forcing a full domain re-download (src/arodonata/adapters/checkpoint/client.py,src/arodonata/core/services/sync_coordinator.py).
Fix
- topology: resolve single installed gateway policy, stream refresh progress, and parse leads-to-specific-network (#71)
- sync,sessions: evict cached SID on transport/read timeout and recover transient failed sync states (#70)
v2.4.0 (2026-11-04)
Feat
- topology,sync: add matched endpoints on gateway candidates and structured sync/session logging (#68)
Added
- Per-gateway filtered
matched_sourcesandmatched_destinationsonAffectedGatewayCandidate(arodonata.core.models.topology,arodonata.core.services.topology_service,ArodonataClient.find_affected_gateways, and MCPlocate_gateways):TopologyService.find_affected_gateways()now populatesmatched_sources: list[str]andmatched_destinations: list[str]on each returnedAffectedGatewayCandidatewith the deduplicated caller query strings from that gateway's cross-interfacematched_flows(src_interface != dst_interfaceand notexternal == external), strictly preserving the caller's input order fromsourcesanddestinations. - Structured
arlogioperational logging and RBACshow-domainsfallback (arodonata.core.services.sync_coordinator,arodonata.core.services.domain_service,arodonata.adapters.checkpoint.rate_limiter,arodonata.adapters.checkpoint.sessions):DomainSyncCoordinatoremits structuredDEBUGlogs on sync start, per-domain progress, and completion andWARNINGlogs on domain sync failure;DomainServiceemits structuredDEBUG/WARNINGlogs during domain discovery and retriesshow-domainswithdetails-level="standard"whendetails-level="full"is rejected by Check Point RBAC while preserving previously cached CMAactive_ip,active_mds_ip,standby_ips, andservers; andLoginGate,LoginCoordinator, andSessionCleaneremit structuredWARNINGlogs on login throttle/read-timeout cooldowns andDEBUGlogs on active CMA IP failover resolution, max-sessions cleanup triggers, and stale session discards.
v2.3.0 (2026-11-03)
Feat
- topology: add gateway interface topology cache and candidate matching (#65)
- cpcrud,cache: support Check Point application-site objects and access-rule negate flags (#62)
- api-reference,mcp: bundle multi-version API schema index and unified api_reference tool (#61)
Fix
- audit: remediate findings R1-R10 from audit 2611022007 (#64)
- cpcrud: allow same-creator WEB_API staged session adoption and discard adopt helper session (#63)
- reports: log system_objects_filtered at DEBUG instead of emitting ReportWarning (#60)
Added
- Gateway Interface Topology Cache & Candidate Policy-Enforcing Gateway Matching (
arodonata.core.models.topology,arodonata.core.services.topology_service,arodonata.core.services.asset_service,arodonata.adapters.storage,ArodonataClient,arodonata.mcp.tools,examples/13_gateway_topology_matching.py): SQL-backedarodonata_gateway_topologytable (GatewayTopologyRecord/GatewayTopologyEntrywith 64-bit integer IPv4 boundsip_first_int/ip_last_int), cross-domain VSX slot reconciliation (CpmiVsxSlotObjandCpmiVsSlotObjlinking tenantCpmiVsNetobjVirtual Systems viatargetCustomerto their physical VSX parent gateway/cluster and merginginterfaces_installedandroutes_installed),TopologyService(refresh_topology(),stream_refresh_topology(),get_gateway_topology(),summarize_gateway_interfaces(), andfind_affected_gateways()),ArodonataClientfacade methods, and MCPlocate_gatewaystool andcache_control(scope="topology")support — resolving IPv4 addresses, CIDRs, ranges, and domain-scoped Check Point object/group names across connected subnets, recursivespecific-networkgroups, VS static routes, and external interfaces while excluding physical cluster members, VS0 chassis, non-firewall hosts,external_to_externaltransits, and same-interface (src_interface == dst_interface) flows. - Check Point
application-site(application-site,application-site-category,application-site-group) support acrossServiceCacheService,HybridStateReader,SearchService,CachedRulebaseSource,CPCRUD, and MCP tools (arodonata.core.services.service_cache_service,arodonata.cpcrud,arodonata.rulebase,arodonata.mcp.tools), plussource-negate,destination-negate, andservice-negateboolean flags on CPCRUDaccess-ruleoperations (checkpoint_ops_schema.json,Planner,Differ,Executor,inverse()). - Bundled multi-version Check Point API Reference & Offline Payload Validation Engine (
arodonata.api_reference,ArodonataClient,arodonata.mcp.tools): packagedcp_api_index.json.gz(~395 KB compressed, covering 1,161 Managementv1.9..v2.2and Gaiav2.0.1commands, 724 shared nested objects, and 430 enums) with lazy in-memoryApiReferenceEngine(get_api_reference(),search_api_commands(),describe_api_command()for single or batch command names with dynamic version filtering, andvalidate_api_payload()checking unknown/version-unsupported commands and fields, required parameters, mutually exclusivefield_alternatives, types, and enumvalid_values),ArodonataClientfacade helpers with automaticapi_versioninference permgmt_name, and the unified MCPapi_reference(action="search" | "describe" | "validate")tool andlookup_api_commandprompt.
Changed
- Replaced the user-facing
system_objects_filteredReportWarningincollect_change_report()with a structuredDEBUG-level log entry viaarlogi(src/arodonata/reports/collector.py,openspec/specs/change-reports/spec.md) so routine filtering of background Check Point"System"maintenance objects does not clutter rendered HTML/Markdown evidence reports.
Fixed
- CPCRUD staged-session cross-process adoption provenance and detached
arodonata-cpcrud-adopthelper session cleanup (arodonata.cpcrud.executor,arodonata.cpcrud.service,arodonata.client):Executor._adopt_staged_session()now inspectsshow-session {}on the fresh helper session before takeover to obtain bothinitial_uidand the authenticated administrator'suser-name, permits adopting custom-namedWEB_APIstaged sessions (such as MMP[ant]-MMP_Rules-...) owned by the same administrator after a process restart or across workers/CLI while still refusing humanSmartConsoleGUI sessions and other administrators' sessions by default, accepts optionalexpected_session_name: str | None = None(403 session_name_mismatchon mismatch) andallow_foreign: bool = Falseacrosspublish_staged_session(),stream_publish_staged_session(), anddiscard_staged_session(), and immediately callsdiscard {"uid": initial_uid}aftertake-over-session/switch-sessionso no emptyarodonata-cpcrud-adopthelper session remains open on Check Point.
v2.2.0 (2026-10-31)
Feat
- reports: synthesize snapshot field diffs and style HTML evidence like SmartConsole (#58)
Added
- Snapshot-based
FieldDiffsynthesis, pre-change bare-UID resolution,"System"maintenance noise filtering, and SmartConsole-styled inline diff rendering (arodonata.reports,arodonata.mcp.tools):collect_change_report()now synthesizesFieldDiffentries (old_value,new_value,added_items,removed_items) directly fromold-objectandnew-objectsnapshots whenever explicitfield-changesare absent or partial (avoiding false-positive rule diffs when an unchanged referenced group has internal member edits), recursively harvests{uid, name}dictionaries acrossold-objectandnew-objectand resolves bare UUIDs appearing only inold-objectortrack(such as removedgroup.membersortrack.type) viaCachePortand boundedshow-objectlookups, populates structuredObjectChangeEntry.summary_fieldsand enrichedObjectChangeEntry.summary(ipv6-address,subnet4/mask-length4,subnet6/mask-length6,address-rangebounds,members,comments), and excludes non-deleted background Check Point"System"maintenance non-rule objects by default (RenderOptions.include_system_objects: bool = False, also exposed on thechange_reportMCP tool) while emitting asystem_objects_filteredReportWarning(details={"filtered_count": ...}) and preservingChangeReport.raw_responses;apply_session_rule_placement()groups rules by(package, rulebase_type, layer)before sorting in ascending SmartConsole order; andrender_change_report()renders SmartConsole-styled HTML tables (dark-blue#253245headers, full-width pale-yellow#eee8aaaccess section banner rows▾ <section_name> (<section_range>), shadedNo.column,Trackcolumn in both HTML and Markdown, andAccept/Dropaction indicators) with inline cell-level removed/added/before-after diffs (including compositesubnet4=net/maskandrange=first-lastdiffs) in both HTML and Markdown.
v2.1.1 (2026-10-30)
Fix
- reports: support post-publish OwnedSession placement, cold-cache fallback, and cross-domain lookups (#56)
Security
- Explicit
server_iptrust validation and MCP staged-session boundary hardening (arodonata.adapters.checkpoint.sessions,arodonata.cpcrud.executor,arodonata.mcp.tools):LoginCoordinator.resolve_target_ips()andLoginCoordinator.create_dedicated_session()now verify that any caller-suppliedserver_ipbelongs to the configured management host or cachedDomainInfoIPs (active_ip,active_mds_ip,standby_ips,servers) before opening a socket, raisingValidationErroron untrusted destinations; and MCPcpcrud_staged_sessionresolves target domain endpoints internally rather than accepting an unverifiedserver_ipargument.
Fixed
- Post-publish
OwnedSessionlive rulebase numbering, object-only session placement short-circuit, cold-cache live published rulebase fallback, and barelayer_uidresolution (arodonata.reports):apply_session_rule_placement()now accepts a clean post-publishOwnedSession(state == "published"orpublished_at is not Nonewithchanges == 0,locks == 0,number-of-published-changes == 0, and matching domain) to read the published rulebase live viasidwithout emittingowned_session_not_usedand best-effort warmCachePort.replace_domain_rulebase()alongsidearodonata_domain_sync_state(numbering_source = "live_published",numbering_basis = "Numbering read live after publish at <time> UTC"derived fromsession_report.publish_time, skipping cache overwrite if a concurrent refresh advancedarodonata_domain_sync_state); short-circuits immediately whensession_report.rule_changesis empty (numbering_source = "not_applicable",numbering_basis = "") while omitting.basis-bannerand- **Numbering Basis**:in HTML and Markdown renderers; falls back to a single-fetch read-onlycollect_domain_rulebase_snapshot()+ cache warm when the local SQL rulebase cache is cold (numbering_source = "live_published",numbering_basis = "Numbering read live from published rulebase at <time> UTC"); and resolves bare UUIDlayerreferences on rule changes via cache and boundedshow-objectlookups into top-levelRuleChangeEntry.layer_name. - Cross-domain cache-first
domain=Nonelookups and ambiguity detection (arodonata.core.errors,arodonata.client,arodonata.core.services.search_service,arodonata.mcp.tools):ArodonataClient.find_object(),SearchService.get_group_members(), and MCPshow_object/get_group_membersnow enforcecache_mode="cache"andinclude_global=Truewhendomainis omitted (preventing multi-domain network refresh storms), reject blank/whitespace targets withValidationError, raiseAmbiguousObjectErrorin the Python SDK when multiple domains match, and returnmatch_type="ambiguous"with candidate objects in MCP tools. LoginGateinter-login spacing without distributed lock starvation, post-revert read-only session recovery, and CPCRUD staged session takeover cleanup (arodonata.adapters.checkpoint.rate_limiter,arodonata.adapters.checkpoint.sessions,arodonata.adapters.checkpoint.client,arodonata.cpcrud.executor):LoginGate.acquire()now releases the cross-processlogin_gate:{mds_ip}distributed lock immediately after recordingmark_login_attemptand sleepslogin_attempt_spacingoutside the distributed lock;is_session_expired_result()classifiesshow-session(withoutuid) returninggeneric_err_object_not_foundafterrevert-to-revisionas an expired session soAMgmtClient.api_call()automatically evicts the wiped SID and re-authenticates; andExecutor._adopt_staged_session()passes{"uid": session_uid, "disconnect-active-session": True}totake-over-sessionwith fallback toswitch-session({"uid": session_uid}) while logging out the initial dedicated session on exit.
v2.1.0 (2026-10-26)
Feat
- cache,docs: add human-readable composite IDs and v2 documentation (#53)
Fix
- docs: fix pymdownx.snippets syntax across example pages (#54)
Added
- Human-readable composite identifiers (
object_id,service_id,asset_id) and dual UID/human-readable topology links (arodonata.core.models,arodonata.adapters.storage,arodonata.core.services,arodonata.client,arodonata.mcp): non-unique indexedobject_id = "{mgmt_name}:{domain_name}:{name}"onCPObject/CPObjectRecord(arodonata_objects),service_id = "{mgmt_name}:{domain_name}:{name}"onCPService/CPServiceRecord(arodonata_services), andasset_id = "{mgmt_name}:{domain_name}:{name}"onAsset/AssetRecord(arodonata_assets) alongside UID primary keysid = "{mgmt_name}:{domain_name}:{uid}";id,object_id, andparent_object_idsonGroupMembershipNodeinSearchResult.memberships;parent_id,parent_asset_id,member_asset_ids, andvirtual_system_asset_idsonAsset/AssetRecordwith cross-domain VSX gateway/cluster to Virtual System reconciliation across domains on the same management server; and composite identifier support acrossfind_object(),get_group_members(),search_objects(),query_objects(), and MCP tools (show_object,list_assets,get_group_members,query_objects). - Complete MkDocs Material documentation site (
docs/,mkdocs.yml,.github/workflows/docs.yml), portable standalone HTML guide (docs/_html/arodonata-v2-docs.html), and NotebookLM knowledge bundles (docs-notebooklm/01..04.md).
v2.0.0 (2026-10-26)
Feat
- mcp: consolidate MCP tool surface into cache-aligned catalog (#9)
- sdk: live integration tests (b1..b7), SDK examples (01..12), and host-app integration hardening (#8)
- mcp: implement Streamable-HTTP MCP server, CLI, security guards, and tool surface (Milestone 6) (#7)
- cpcrud: implement declarative Policy-as-Code CPCRUD engine (#6)
- rulebase,reports: implement rulebase introspection, numbering, and change reports (#5)
- sync: implement core sync/search services and ArodonataClient facade (#4)
- checkpoint: implement native aiohttp transport, TLS verification, and session lifecycle (#3)
- core,storage: implement milestone 1 core foundation and sql storage adapters (#2)
Security
- Comprehensive security and specification conformance remediation (
audit-remediation-261025acrossarodonata.adapters,arodonata.core,arodonata.cpcrud,arodonata.rulebase, andarodonata.mcp): strict Web API command-name validation (^[a-z0-9]+(-[a-z0-9]+)*$), disabled HTTP redirects (allow_redirects=False) and ambient proxies (trust_env=False), and phase-classifiedTransportError(connectvspost-send) preventing post-write request resends on failover; cross-processfcntl.flocklocking,0600permission enforcement, and IPv6[host]:portkey normalization inTrustStore; full secret anddatabase_urlpassword masking acrossArodonataSettings/ArodonataMCPSettingsand recursive secret/SID redaction across nested collections and exception chains;arodonata_prefix on all 15 SQLModel tables with positive v1 column fingerprint checks (mdm_dmn,mgmt_dmn_key), cross-worker serialized migration locks (pg_advisory_xact_lock/BEGIN IMMEDIATE), atomic single-transaction cache + sync-state commits, dialectON CONFLICTupserts, and owner-verified distributed lock renewal heartbeats; HMAC-SHA256 credential-boundarodonata_sid_cachekeys,LoginGateself-deadlock elimination and inter-login spacing, Arodonata-onlySessionCleanerfiltering (changes == 0andlocks == 0), and strict prohibition of mutating commands on the shared read-onlyarodonata_sid_cachesession; CPCRUD(object_type, operation)command allowlisting, per-planHybridStateReaderisolation, pre-publish head drift re-verification, and report-verifiedinverse()generation; and MCP read-only command allowlisting, HMAC-SHA256 signedcpcrud_planverification incpcrud_apply/cpcrud_inverse,cpcrud_staged_sessiontool, base64-safe 32-char minimum static token parsing with SHA-256hmac.compare_digest, and fail-closedjwtauthentication.
Added
- Consolidated cache-aligned MCP tool surface (
arodonata.mcp,arodonata.core.services,arodonata.client): 13 base tools (list_domains,list_objects,list_services,list_assets,show_objectwith 3-tier exact/anchored-wildcard/substring matching across objects, services, assets, and rulebase layers,search_objects,get_group_membersexpanding network groups, service groups, and cluster/VSX child assets,query_objectswithaggregate="list" | "count" | "describe",show_rulebase,locate_rules,change_report,cache_control, andapi_call) plus 5 opt-in CPCRUD tools (cpcrud_validate,cpcrud_plan,cpcrud_apply,cpcrud_inverse,cpcrud_staged_session) and multi-tableArodonataClient.find_object. - Host application integration hardening (
arodonata.adapters.storage,arodonata.core.services,arodonata.cpcrud,arodonata.rulebase):to_naive_utc()helper and uniform naive UTC timestamps (DateTime(timezone=False),tzinfo=None) across all database tables, domain models, and Check Point timestamp parsers;ARODONATA_TABLE_NAMESnamespace isolation andarodonata_assetstable rename (preventing collision with host applicationassetstables and ignoring non-Arodonata tables inSQLModel.metadata); savepoint-wrapped (begin_nested()) multi-worker schema evolution with automaticDROP+CREATErecovery for incompatible legacy v1 cache tables (domains,sid_cache,arodonata_schema_version);exact_match: bool = FalseinSearchService.search_objects(),ArodonataClient.search_objects(), and MCPsearch_objects; staged session finalization (publish_staged_session,stream_publish_staged_session,discard_staged_session) onCPCRUDServiceandArodonataClientviatake-over-session(uid=session_uid); andrule_to_cpcrud_operation()withoutput_format="cpcrud"support infilter_rulebase()for exporting cached rules into schema-valid CPCRUD operations. - Live Check Point MDSM/SMS integration test harness (
tests/integration/,openspec/specs/integration-testing-and-examples/spec.md),./pytest.shtest runner (unit,int-1..int-7,int-fullwith-venabled by default), and 12 progressive runnable SDK examples (examples/01..12,examples/_session_guard.py,examples/crud_example.yaml,examples/README.md,examples/README_CRUD.md): layered lab environment loader (tests/integration/lab_env.pysupportingARODONATA_LAB=<profile>), non-blocking process-widefcntl.flockrun lock (tests/integration/run_lock.py), live API readiness probe (tests/integration/lab_ready.py), crash-safe domain revision snapshot andrevert-to-revisionbaseline recovery (tests/integration/cp_revision.pyandrestore_baseline.py), standalone diagnostic utilities (probe_lab_domains.py,probe_login_throttle.py,lab_build.py), 60 live integration tests across 7 buckets (b1auth/sessions/reads/search/rate-limiting,b2cache build & CPCRUD live operations,b3publish/revert & 70s login throttle recovery,b4cache mode matrix & multi-domain isolation,b5full rebuild/120-rule pagination/rulebase session refresh/publish matrix/change reports,b6bounded soak loop,b7MCP server & tools), top-level re-exports (Asset,CPObject,CPService,DomainInfo,RefreshOutcome,SearchResult),ArodonataClient.cleanup_server_sessions(), andoteloptional dependency group (arodonata[otel]). - Streamable-HTTP MCP server and standalone CLI (
arodonata.mcp,arodonata[mcp],arodonata-mcp):ArodonataMCPSettings(ARODONATA_MCP_*configuration with secret-safe__repr__and standalone startup validation refusingauth_mode="host"or"jwt"and missingpinnedTLS trust material with exit code2),create_mcp_serverandcreate_asgi_app(ArodonataASGIAppfor Starlette/FastAPI embedding),StaticTokenVerifierandMCPBearerAuthMiddleware(constant-timehmac.compare_digestverification acrossARODONATA_MCP_TOKEN_VARSmapping variable names toclient_idin logs andUserContextwithout logging token values),MCPOriginHostGuardMiddleware(DNS rebinding protection returning HTTP421for unlistedHostand HTTP403for unlistedOrigin), pre-logindomainvalidation against the cachedarodonata_domainstable (with single domain-list refresh on miss) andInvalidCredentialsErrortranslation into actionableToolFailuremessages listing known domains, and MCP prompt templates (audit_session_changes,locate_ip_in_policy,plan_declarative_change). - Declarative Policy-as-Code CPCRUD engine (
arodonata.cpcrud) wired intoArodonataClient(client.cpcrud): offline JSON Schema Draft-07 template validator (CPCRUDService.validate/validate_templateovercheckpoint_ops_schema.jsonwith zero network or database calls),HybridStateReader(isolated per-plan state reader serving objects fromarodonata_objectsand services fromarodonata_servicesstrictly whenarodonata_domain_sync_statefor(scope, item_type)matches the planner'sDomainStamplast_published_atandlast_session_uid, with transparent live API fallback and intra-plan virtual state overlay),PlannerandDiffer(pre-lookupDomainStampcapture, two-axis conflict resolutionNameConflictPolicyxIpConflictPolicywithNamingPrefixesauto-naming,Outcome.ERRORandOutcome.SKIPPED_DEPENDENCYon lookup failures instead of falseCREATE, rule identity matching by key or traffic tuple with Check Point NAT"Original"/"Any"sentinel normalization, and cleanup-rule-aware"bottom"placement anchoring{"above": "<cleanup_rule_uid>"}), dedicated-sessionExecutor(applyandstream_applywithOutcome.PLAN_STALEsafeguard, per-domainWriteSession+SessionOverlayupdates,no_publish=True, keep_session=Truestaging withStagedSessionInfo/StagedSessionEventand SID redaction, post-publishinvalidate_domain, andretry_remainingfolding), and compensating rollback generator (CPCRUDService.inverse/build_inverse_template). - Rulebase introspection, SmartConsole hierarchical numbering (
arodonata.rulebase), and auditable session change reports (arodonata.reports) wired intoArodonataClient: section-stitching rulebase pager (fetch_paged_rulebasemerging splitrulebase-sectionheaders across 100-rule pages and recovering empty trailing sections),RulebaseRefreshService(refresh_rulebases/stream_refresh_rulebaseswith dirty-session refusal, full package/NAT/access/HTTPS/threat/inline/Global placeholder traversal, and atomicreplace_domain_rulebasereplacement),CachedRulebaseSource(get_policy_packages,get_package_rulebase,get_layer_rulebase,locate_rules, automatic domain resolution withAmbiguousLayerName, and localfilter_rulebaseevaluation over cached rules/objects/services), and change report pipeline (collect_change_reportwithSessionScope/RangeScopeUTC validation, deduplication,ReportWarningpartial-failure tracking, bounded 200-UIDshow-objectlookup, read-only liveOwnedSessionrule numbering with full SID redaction and cached snapshot fallback, and offlinerender_change_report/build_change_reportfor self-contained HTML, Markdown, and versioned JSON). - Core synchronization, search services (
arodonata.core.services), and unifiedArodonataClientfacade (arodonata.client):DomainServiceandDomainListRefreshTracker(MDSMshow-domainsdiscovery,Globaldomain synthesis,include_globalfiltering, active/standby failover IP re-resolution, and 1-hour TTL),DomainSyncCoordinator(parallel domain traversal peractive_mds_ipatmax(1, concurrent_limit - 1), per-domain distributed locks, dirty-session checks viashow-session,(last_published_at, last_session_uid)staleness comparison inarodonata_domain_sync_state, and probeInvalidCredentialsErrorfailure handling),ObjectService(pairedrefresh_objects/stream_refresh_objects,CacheMode"cache" | "smart" | "smart-fast" | "force","smart-fast"incremental diff viashow-changeswith fallback on> max_incremental_changes, default("host", "network", "address-range", "group", "dns-domain"), and type-scoped replacement),ServiceCacheService(arodonata_serviceswith default("service-tcp", "service-udp", "service-icmp", "service-group")and selective on-demandtypes=[...]),AssetRefreshService(ClusterRelationshipManagerandVSXRelationshipManagervia encapsulatedgeneric-objectqueries),SearchService(search_objectswith IP/CIDR/range/wildcard/UID/name classification and recursive group traversal up tomax_depth,describe_objects,query_objects, andget_cache_status), andArodonataClient(typed getters,WriteSessionoverlay merging,write_session,auth_context,add_object,set_object,delete_object,find_object,get_group_members,start_object_cache_warmup, andinvalidate_domain). - Check Point native
asynciotransport and session adapter (arodonata.adapters.checkpoint):TrustStoreandTrustPolicy(pinned,tofu,lab-memorywith atomic0600tls_known_hosts.jsonpersistence and cross-IP MDS member certificate recognition),ApiTransportoveraiohttp(post-handshake pre-request SHA-256 fingerprint verification, separateconnect_timeout/read_timeoutApiTimeoutErrorphases, no automatic re-send after socket write, andVerifiedConnectionPoolreusing keep-alive sockets up to 10s idle strictly forshow-*commands),TaskWaiter(exponential backoff2s..10spolling undertask_timeouttolerating up to 5 transient poll errors), continuity-verified object pager (pager.pywith±10boundary swap window recovery and single restart on discontinuity), per-MDS-memberRateLimiter(database slot locks + FIFO waiter queue + coalesced keepalive sweeps) andLoginGate(70sthrottle recovery and fast-failInvalidCredentialsError),LoginCoordinator,SessionCleaner, context-boundWriteSession(SessionOverlayupdates, auto-publish/discard), andAMgmtClientimplementingApiPort. - Core foundation (
arodonata.core) and SQL storage adapter (arodonata.adapters.storage):ArodonataSettings, exception hierarchy with SID/secret redaction,@tracedandspan_attrsinstrumentation, typed domain progress events (SyncProgressEvent,CPCRUDEvent),contextvars-boundAuthContext,UserContext, andWriteSessionwithSessionOverlay, Pydantic v2 domain models, hexagonal protocols (ApiPort,CachePort,LockPort,AuthProvider),DatabaseManager(SQLite + PostgreSQL with SHA-256 schema hash auto-migration viaarodonata_schema_version),SqlLockAdapter,SqlCacheAdapter, and SSE boundary adapter (arodonata.adapters.sse).
Changed
- Revised all OpenSpec capability specifications for Arodonata v2 clean-slate hexagonal architecture: native
aiohttptransport (replacingcpapi),SqlCacheAdapter(replacingPostgresCacheAdapter/CacheRepository), canonicalCacheModenames (cache,smart,smart-fast,force), paired coroutine andstream_*domain event APIs (removingSSEEventfrom core), and unifiedArodonataClientfacade (replacingarodonata.helpers).
Fixed
- Check Point R82 live compatibility and persistent cache/session reuse fixes:
ArodonataClientandAMgmtClientnow honorsettings.database_urlwhenengine=None, auto-create parent directories for file-backed SQLite URLs, preservearodonata_sid_cacheentries onclose()for persistent databases, and skip redundant startupSessionCleanerlogins when a valid system-domain SID is already cached;LoginCoordinatorclassifies generic R82"Authentication to server failed."(err_login_failed) as non-retryableInvalidCredentialsError;DomainSyncCoordinatorandObjectServiceextract"iso-8601"from dict-formattedpublish-timeand unwrap task-basedshow-changesoperationsarrays;Collectorpassesview-published-sessions=Truefor published session discovery; andPlanner._find_existing_nat_ruleresolves inline object/service names to UIDs for idempotent NAT rule re-planning.
Arodonata v2 Examples
Progressive runnable scripts demonstrating ArodonataClient usage from basic cache-backed queries to advanced multi-user session overlays, declarative Policy-as-Code (CPCRUD), auditable change reports, OpenTelemetry tracing, and embedded MCP servers.
Catalog Overview
| Script | Doc Page | Topic | Mutates Lab? |
|---|---|---|---|
01_basic_queries.py |
01 — Basic Queries | Discovers domains (get_domains) and queries cached hosts, networks, and services (get_hosts, get_networks, get_services) |
No |
02_search_and_query.py |
02 — Search & Structured Query | Multi-term object search with recursive group memberships (search_objects), progressive disclosure (describe_objects), structured cross-domain aggregation (query_objects), and cache freshness (get_cache_status) |
No |
03_gateway_relationships.py |
03 — Gateway & VSX Topology | Gateway, cluster, and VSX asset topology (get_gateways) linking cluster members and virtual systems via parent_uid and member_uids |
No |
04_smart_refresh.py |
04 — Smart & Streaming Refresh | Paired streaming (stream_refresh_*) and batch (refresh_*) cache synchronization across assets, objects, services, and rulebases — run this first to warm a persistent DB |
No |
05_rulebase_queries.py |
05 — Rulebase Queries | Policy package discovery (get_policy_packages), hierarchical SmartConsole numbering (get_package_rulebase), reverse UID lookup (locate_rules), and local rule filtering (filter_rulebase) |
No |
06_session_basics.py |
06 — Session Lifecycle Basics | Low-level session lifecycle: capture baseline (show-last-published-session), create_dedicated_session, add-host, publish, and revert-to-revision |
Yes (auto-reverted via _session_guard.py) |
07_context_and_overlay.py |
07 — Contexts & Session Overlay | Dynamic auth_context, user_context, and write_session with SessionOverlay read-your-own-writes isolation (discards on exit without publishing) |
No (discards uncommitted session) |
08_cpcrud_operations.py |
08 — CPCRUD Operations | Declarative Policy-as-Code (client.cpcrud.validate, plan, apply) applying crud_example.yaml twice to prove idempotency — see CPCRUD User Guide |
Yes (auto-reverted via _session_guard.py) |
09_cpcrud_inverse.py |
09 — CPCRUD Inverse Rollback | Compensating rollback workflow: plan -> apply -> inverse(plan, report) -> plan -> apply |
Yes (auto-reverted via _session_guard.py) |
10_change_report_evidence.py |
10 — Change Report Evidence | Auditable ChangeReport evidence: live unpublished numbering via OwnedSession vs published cached numbering rendered to HTML, Markdown, and JSON |
Yes (auto-reverted via _session_guard.py) |
11_otel_tracing.py |
11 — OpenTelemetry Tracing | Provider-agnostic OpenTelemetry instrumentation (arlogi.otel.setup_tracing) with a per-span timing breakdown from exported JSONL traces |
No |
12_mcp_embedded.py |
12 — Embedded FastAPI MCP | Embedding Arodonata's MCP server (create_mcp_server, create_asgi_app) inside a FastAPI application with custom tools |
No |
13_gateway_topology_matching.py |
13 — Gateway Topology Matching | Gateway topology sync, interface summaries, affected-gateway LPM matching, diagnostics, reconciliation, and annotations | No |
_session_guard.py |
— | Crash-safe baseline snapshot/restore context manager (guarded_session) and standalone CLI tool for manual testing |
Helper / CLI |
Setup & Execution
# 1. Install dependencies (including dev/example dependencies)
uv sync --all-extras
# 2. Configure environment files (.env.lib / .env.test / .env.secrets)
cp .env.example .env.lib
# 3. Warm the cache first (when using a persistent SQLite or PostgreSQL DATABASE_URL)
uv run examples/04_smart_refresh.py
# 4. Run read-only query, search, topology, rulebase, and overlay examples
uv run examples/01_basic_queries.py
uv run examples/02_search_and_query.py
uv run examples/03_gateway_relationships.py
uv run examples/05_rulebase_queries.py
uv run examples/07_context_and_overlay.py
uv run examples/11_otel_tracing.py
# 5. Run mutating lab examples (automatically snapshot and revert Domain4/Domain5 baseline)
ARODONATA_LAB=home uv run examples/06_session_basics.py
ARODONATA_LAB=home uv run examples/08_cpcrud_operations.py
ARODONATA_LAB=home uv run examples/09_cpcrud_inverse.py
ARODONATA_LAB=home uv run examples/10_change_report_evidence.py
# 6. Run the embedded FastAPI + MCP server on http://127.0.0.1:8000/mcp
uv run examples/12_mcp_embedded.py
# 7. Run gateway topology & affected-gateway candidate matching against replay fixtures
uv run examples/13_gateway_topology_matching.py
Crash-Safe Manual Testing with _session_guard.py
When experimenting manually in SmartConsole or with ad-hoc scripts against a lab domain:
# 1st invocation: snapshots and saves the current last-published session to examples/_tmp/session_guard_state.json
ARODONATA_LAB=home uv run examples/_session_guard.py 192.168.5.140 Domain4
# ... perform manual changes/publishes in Domain4 ...
# 2nd invocation: discards open sessions, reverts Domain4 to the saved baseline, and removes the state file
ARODONATA_LAB=home uv run examples/_session_guard.py 192.168.5.140 Domain4
01 — Basic Queries (01_basic_queries.py)
Demonstrates discovering domains (client.get_domains()) and querying cached hosts, networks, and services (client.get_hosts(), client.get_networks(), client.get_services()) using ArodonataClient.
Source Code (examples/01_basic_queries.py)
"""Example 01 — Basic typed queries (`get_domains`, `get_hosts`, `get_networks`, `get_services`).
Run:
uv run examples/01_basic_queries.py
Reads configuration from `.env.lib` and `.env.secrets` (or `.env`).
Demonstrates how `ArodonataClient` discovers domains and queries cached network and service
objects with `cache_mode="smart"`.
"""
from __future__ import annotations
import asyncio
import os
import time
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
async def main() -> None:
"""Query domains, hosts, networks, and services across configured management servers."""
settings = ArodonataSettings()
print(f"Using database: {settings.database_url or 'sqlite+aiosqlite:///:memory:'}")
print(f"Management servers: {settings.mgmt_names}")
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print("\n[Step 1/4] Discovering MDS domains (get_domains)...", flush=True)
s0 = time.perf_counter()
domains = await client.get_domains(include_global=True)
print(f"Discovered domains ({len(domains)}) in {time.perf_counter() - s0:.2f}s:")
for dom in domains[:10]:
print(f" - {dom.name} (mgmt={dom.mgmt_name}, active_ip={dom.active_ip}, global={dom.is_global})")
target_domain = os.getenv("EXAMPLE_DOMAIN") or (domains[0].name if domains else None)
if not target_domain:
print("No domains found.")
return
print(f"\n[Step 2/4] Querying hosts in domain {target_domain!r} (get_hosts, cache_mode='smart')...", flush=True)
s0 = time.perf_counter()
hosts = await client.get_hosts(domain=target_domain, cache_mode="smart")
print(f"Hosts ({len(hosts)}) in {time.perf_counter() - s0:.2f}s:")
for host in hosts[:5]:
print(f" - {host.name}: {host.ipv4_address} (uid={host.uid})")
print(
f"\n[Step 3/4] Querying networks in domain {target_domain!r} (get_networks, cache_mode='smart')...",
flush=True,
)
s0 = time.perf_counter()
networks = await client.get_networks(domain=target_domain, cache_mode="smart")
print(f"Networks ({len(networks)}) in {time.perf_counter() - s0:.2f}s:")
for net in networks[:5]:
print(f" - {net.name}: {net.subnet4}/{net.mask_length4}")
print(
f"\n[Step 4/4] Querying services in domain {target_domain!r} (get_services, cache_mode='smart')...",
flush=True,
)
s0 = time.perf_counter()
services = await client.get_services(domain=target_domain, cache_mode="smart")
print(f"Services ({len(services)}) in {time.perf_counter() - s0:.2f}s:")
for svc in services[:5]:
print(f" - {svc.name} ({svc.type}): port={svc.port} proto={svc.protocol}")
elapsed = time.perf_counter() - t0
print(f"\nCompleted in {elapsed:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
02 — Search & Structured Query (02_search_and_query.py)
Demonstrates multi-term object search with recursive parent group memberships (client.search_objects(), including exact_match=True), progressive-disclosure schema discovery (client.describe_objects()), SQL-free cross-domain aggregation (client.query_objects()), and cache freshness inspection (client.get_cache_status()).
Source Code (examples/02_search_and_query.py)
"""Example 02 — Object search, group membership resolution, and structured `query_objects`.
Run:
uv run examples/02_search_and_query.py
Demonstrates:
1. `client.search_objects(query, max_depth=2)` — classifies comma-separated search terms
(IPv4, CIDR, range, wildcard, UID, name) and resolves parent group memberships recursively.
2. `client.describe_objects()` — progressive-disclosure schema and type counts across domains.
3. `client.query_objects()` — cross-domain filtering, grouping (`group_by`), and aggregation
(`aggregate="count" | "list"`), including `scope_origin="local" | "global"`.
4. `client.get_cache_status()` — per-scope cache freshness and `cache_age_seconds`.
"""
from __future__ import annotations
import asyncio
import os
import time
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
async def main() -> None:
"""Run search_objects, describe_objects, query_objects, and get_cache_status."""
settings = ArodonataSettings()
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print("[Step 1/4] Resolving target domain (get_domains)...", flush=True)
domains = await client.get_domains()
target_domain = os.getenv("EXAMPLE_DOMAIN") or (domains[0].name if domains else None)
# 1. Search objects by wildcard and IPv4/CIDR with recursive parent group resolution
query_str = os.getenv("EXAMPLE_SEARCH_QUERY", "*host*, 10.0.0.0/8")
print(
f"\n[Step 2/4] Searching objects across all 5 types in {target_domain!r} "
f"(search_objects={query_str!r}, max_depth=2, cache_mode='smart')...",
flush=True,
)
s0 = time.perf_counter()
search_res = await client.search_objects(
query_str,
domains=[target_domain] if target_domain else None,
max_depth=2,
cache_mode="smart",
)
print(
f"Search query {query_str!r} matched {len(search_res.matches)} object(s) in {time.perf_counter() - s0:.2f}s:"
)
for match in search_res.matches[:5]:
groups = search_res.memberships.get(match.uid, [])
group_names = [f"{g.name} (depth={g.depth})" for g in groups]
print(f" - {match.name} ({match.type}, domain={match.domain_name}) -> groups={group_names}")
# 2. Progressive-disclosure metadata via describe_objects
print(
"\n[Step 3/4] Inspecting cached schema & aggregating objects (describe_objects / query_objects)...",
flush=True,
)
desc = await client.describe_objects(domain_name=target_domain)
print(f"Cached summary: {desc['total_objects']} objects, {desc['total_services']} services")
print(f" Object types: {desc['object_types']}")
print(f" Groupable fields: {desc['groupable_fields']}")
# 3. Structured cross-domain aggregation via query_objects
grouped = await client.query_objects(
domain_name=target_domain,
group_by=["domain_name", "type"],
aggregate="count",
)
print(f"\nGrouped counts (total={grouped['total']}):")
for row in grouped.get("groups", [])[:10]:
print(f" - {row['domain_name']} / {row['type']}: {row['count']}")
# 4. Inspect domain_sync_state freshness via get_cache_status
print("\n[Step 4/4] Checking cache freshness (get_cache_status)...", flush=True)
status = await client.get_cache_status(domain_name=target_domain)
print(f"Cache status entries ({status['total_entries']}):")
for entry in status["entries"][:5]:
print(
f" - [{entry['scope']}:{entry['item_type']}] {entry['mgmt_name']}:{entry['domain_name']} "
f"status={entry['status']} count={entry['object_count']} age={entry['cache_age_seconds']}s"
)
print(f"\nCompleted in {time.perf_counter() - t0:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
03 — Gateway & VSX Topology (03_gateway_relationships.py)
Demonstrates querying cached gateways, clusters, cluster members, and VSX virtual systems (client.get_gateways()) and traversing both UID (id, parent_uid, member_uids, virtual_system_uids) and human-readable composite identifiers (asset_id, parent_id, parent_asset_id, member_asset_ids, virtual_system_asset_ids, including cross-domain VSX links), along with interfaces and network_security_blades.
Source Code (examples/03_gateway_relationships.py)
"""Example 03 — Gateway, cluster, and VSX asset topology (`get_gateways`, `refresh_assets`).
Run:
uv run examples/03_gateway_relationships.py
Demonstrates how `AssetRefreshService` links cluster members and VSX virtual systems to their
parent cluster or VSX gateway via `parent_uid`, `parent_name`, `member_uids`, and
`virtual_system_uids`.
"""
from __future__ import annotations
import asyncio
import os
import time
from collections import defaultdict
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings, Asset # noqa: E402
async def main() -> None:
"""Inspect standalone gateways, clusters, cluster members, and VSX systems."""
settings = ArodonataSettings()
target_domain = os.getenv("EXAMPLE_DOMAIN")
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print(
f"[Step 1/2] Fetching gateway/cluster/VSX assets for domain={target_domain!r} (get_gateways)...", flush=True
)
gateways = await client.get_gateways(domain=target_domain, cache_mode="smart")
print("[Step 2/2] Resolving parent-child cluster & VSX topology...", flush=True)
by_uid: dict[str, Asset] = {gw.uid: gw for gw in gateways}
members_by_parent: dict[str, list[Asset]] = defaultdict(list)
standalone: list[Asset] = []
for gw in gateways:
if gw.parent_uid:
members_by_parent[gw.parent_uid].append(gw)
elif not gw.member_uids and not gw.virtual_system_uids:
standalone.append(gw)
print(f"Total cached gateway/server assets: {len(gateways)}")
print(f"Standalone gateways/servers: {len(standalone)}")
for gw in standalone[:5]:
print(f" - {gw.name} ({gw.type}, ip={gw.ipv4_address}, domain={gw.domain_name})")
print(f"\nClusters / VSX parents with linked members: {len(members_by_parent)}")
for parent_uid, members in list(members_by_parent.items())[:5]:
parent = by_uid.get(parent_uid)
parent_label = f"{parent.name} ({parent.type})" if parent else parent_uid
member_names = ", ".join(f"{m.name} ({m.ipv4_address or 'no-ip'})" for m in members)
print(f" - {parent_label}: {member_names}")
print(f"\nCompleted in {time.perf_counter() - t0:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
04 — Smart & Streaming Refresh (04_smart_refresh.py)
Demonstrates paired streaming (stream_refresh_*) and batch (refresh_*) cache synchronization across assets, objects, services, and rulebases, including SSE conversion via arodonata.adapters.sse.to_sse_event.
Source Code (examples/04_smart_refresh.py)
"""Example 04 — Paired batch & streaming cache synchronization (`refresh_*` and `stream_refresh_*`).
Run:
uv run examples/04_smart_refresh.py
Run this script first against a persistent SQLite or PostgreSQL database (`DATABASE_URL`) to
warm the cache across all discovered domains. Demonstrates both streaming (`stream_refresh_*`)
and awaitable (`refresh_*`) synchronization methods and optional SSE wire formatting.
"""
from __future__ import annotations
import asyncio
import os
import time
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
from arodonata.adapters.sse import to_sse_event # noqa: E402
async def main() -> None:
"""Stream progress events while refreshing assets, objects, services, and rulebases."""
settings = ArodonataSettings()
target_domains = [os.environ["EXAMPLE_DOMAIN"]] if os.getenv("EXAMPLE_DOMAIN") else None
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print("[Step 1/5] Streaming asset synchronization (gateways, clusters, VSX)...", flush=True)
async for ev in client.stream_refresh_assets(domains=target_domains, mode="smart"):
if ev.phase in ("started", "completed", "skipped", "failed"):
print(f" [{ev.phase}] {ev.message or f'{ev.mgmt_name}:{ev.domain} ({ev.item_type})'}")
print("\n[Step 2/5] Streaming network object synchronization (hosts, networks, ranges, groups)...", flush=True)
async for ev in client.stream_refresh_objects(domains=target_domains, mode="smart"):
if ev.phase in ("started", "completed", "skipped", "failed"):
print(f" [{ev.phase}] {ev.message or f'{ev.mgmt_name}:{ev.domain} ({ev.item_type})'}")
# Example of converting a domain event to an SSE frame for web endpoints:
_sse_frame = to_sse_event(ev).encode()
print("\n[Step 3/5] Batch refreshing services...", flush=True)
svc_outcome = await client.refresh_services(domains=target_domains, mode="smart")
print(
f" Services sync: refreshed={len(svc_outcome.refreshed_domains)}, "
f"skipped={len(svc_outcome.skipped_domains)}, items={svc_outcome.total_items}"
)
print("\n[Step 4/5] Batch refreshing policy rulebases...", flush=True)
rb_outcome = await client.refresh_rulebases(domains=target_domains, mode="smart")
print(
f" Rulebases sync: refreshed={len(rb_outcome.refreshed_domains)}, "
f"skipped={len(rb_outcome.skipped_domains)}, items={rb_outcome.total_items}"
)
print("\n[Step 5/5] Batch refreshing gateway interface topology...", flush=True)
topo_outcome = await client.refresh_topology(domains=target_domains, mode="smart")
print(
f" Topology sync: refreshed={len(topo_outcome.refreshed_domains)}, "
f"skipped={len(topo_outcome.skipped_domains)}, items={topo_outcome.total_items}"
)
print(f"\nCache warm-up completed in {time.perf_counter() - t0:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
05 — Rulebase Queries (05_rulebase_queries.py)
Demonstrates policy package discovery (client.get_policy_packages()), hierarchical SmartConsole numbering (client.get_package_rulebase(), client.get_layer_rulebase()), reverse UID lookup (client.locate_rules()), and local rulebase filtering (client.filter_rulebase(), including output_format="cpcrud").
Source Code (examples/05_rulebase_queries.py)
"""Example 05 — Rulebase introspection, hierarchical SmartConsole numbering, and local filtering.
Run:
uv run examples/05_rulebase_queries.py
Demonstrates:
1. `client.get_policy_packages(mgmt_name, domain)` — list cached policy packages and layers.
2. `client.get_package_rulebase(mgmt_name, domain, package)` — hierarchical SmartConsole rule
numbers (`1`, `2.1`, `2.2.1`) across ordered Global/Domain layers and inline sub-layers.
3. `client.locate_rules(mgmt_name, domain, rule_uids=[...])` — reverse lookup from rule UID to
SmartConsole rule numbers across packages.
4. `client.filter_rulebase(...)` — local rulebase query evaluation (`src:`, `dst:`, `svc:`,
`action:`, free text, CIDR containment) rendered in `markdown` or `model_friendly` format.
"""
from __future__ import annotations
import asyncio
import os
import time
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
async def main() -> None:
"""Inspect policy packages, numbered rulebases, rule locations, and local rule filtering."""
settings = ArodonataSettings()
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print("[Step 1/5] Resolving target domain (get_domains)...", flush=True)
domains = await client.get_domains()
if not domains:
print("No domains discovered.")
return
dom = next((d for d in domains if d.name == os.getenv("EXAMPLE_DOMAIN")), domains[0])
mgmt_name = dom.mgmt_name
domain_name = dom.name
print(f"[Step 2/5] Ensuring rulebase cache for {mgmt_name}:{domain_name} (refresh_rulebases)...", flush=True)
await client.refresh_rulebases(mgmt_name=mgmt_name, domains=[domain_name], mode="smart")
print(f"[Step 3/5] Listing policy packages in {domain_name} (get_policy_packages)...", flush=True)
packages = await client.get_policy_packages(mgmt_name, domain_name, cache_mode="cache")
if not packages:
print(f"No policy packages cached in {domain_name}.")
return
pkg = packages[0]
print(f"\nPolicy Package: {pkg.name} (uid={pkg.uid})")
print(f" Access layers: {[lay.layer_name for lay in pkg.access_layers]}")
print(
f"\n[Step 4/5] Computing hierarchical SmartConsole rule numbers for {pkg.name!r} (get_package_rulebase)...",
flush=True,
)
pkg_rb = await client.get_package_rulebase(
mgmt_name,
domain_name,
pkg.name,
rulebase_type="access",
cache_mode="cache",
)
for layer in pkg_rb.layers:
print(f"\nLayer {layer.layer_name!r} (prefix={layer.prefix!r}, rules={len(layer.rules)}):")
for nr in layer.rules[:5]:
print(f" #{nr.rule_number:<6} {nr.name or '(unnamed)':<28} action={nr.action} enabled={nr.enabled}")
access_rules = await client.get_access_rules(mgmt_name, domain_name)
if access_rules:
sample = access_rules[0]
locs = await client.locate_rules(
mgmt_name,
domain_name,
rule_uids=[sample.uid],
cache_mode="cache",
)
print(f"\nLocated rule UID {sample.uid}: {locs.rule_locations.get(sample.uid)}")
print("\n[Step 5/5] Filtering rulebase locally (filter_rulebase)...", flush=True)
filtered = await client.filter_rulebase(
mgmt_name,
domain_name,
package=pkg.name,
rulebase_type="access",
filter_query=os.getenv("EXAMPLE_RULE_FILTER", "action:Accept"),
output_format="markdown",
cache_mode="cache",
)
print(f"\nFiltered rulebase ({filtered.matched_count}/{filtered.total_rules} matching rules):")
print("\n".join(filtered.rendered_text.splitlines()[:15]))
print(f"\nCompleted in {time.perf_counter() - t0:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
06 — Session Lifecycle Basics (06_session_basics.py)
Demonstrates low-level Check Point session lifecycle operations (create_dedicated_session, add-host, publish, and crash-safe revert-to-revision via _session_guard.py).
Source Code (examples/06_session_basics.py)
"""Example 06 — Check Point session lifecycle basics: baseline, dedicated session, publish, and revert.
Run:
uv run examples/06_session_basics.py
Demonstrates:
1. Reading the domain's current baseline revision (`show-last-published-session`).
2. Opening an isolated write session via `client.create_dedicated_session(mgmt_name, domain)`.
3. Creating a test host (`add-host`) and publishing (`publish` with `wait_for_task=True`).
4. Verifying that `show-last-published-session` moved to the newly published session UID.
5. Reverting the domain back to the saved baseline revision (`revert-to-revision`) via
`_session_guard.guarded_session`.
"""
from __future__ import annotations
import asyncio
import os
import sys
import uuid
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
load_dotenv(".env.test", override=True)
load_dotenv(".env.lib", override=True)
load_dotenv(".env.secrets", override=True)
sys.path.insert(0, str(Path(__file__).parent))
from _session_guard import guarded_session # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
def _extract_iso_time(time_field: Any) -> str:
if isinstance(time_field, dict):
return str(time_field.get("iso-8601") or time_field)
return str(time_field or "unknown")
async def main() -> None:
"""Run the baseline -> create_dedicated_session -> add-host -> publish -> revert cycle."""
settings = ArodonataSettings()
mgmt_name = settings.mgmt_names[0]
domain = os.getenv("EXAMPLE_DOMAIN") or os.getenv("TEST_DOMAIN_A", "Domain4")
host_name = f"example-session-host-{uuid.uuid4().hex[:6]}"
async with ArodonataClient(settings=settings) as client:
async with guarded_session(client, mgmt_name, domains=[domain]) as baseline:
base_rev = baseline[domain]
print(f"Step 1: Captured baseline on {mgmt_name}:{domain}:")
print(f" UID: {base_rev['uid']}")
print(f" Name: {base_rev['name']}")
print(f" Time: {_extract_iso_time(base_rev['publish_time'])}")
print(f"\nStep 2: Opening dedicated write session and creating host {host_name!r}...")
sid, server_ip = await client.create_dedicated_session(
mgmt_name,
domain,
session_name=f"example-06-{host_name[-6:]}",
session_description="Example 06 dedicated write session",
)
try:
add_res = await client.api_call(
mgmt_name,
"add-host",
{
"name": host_name,
"ipv4-address": "198.51.100.240",
"comments": "Created by examples/06_session_basics.py",
},
domain=domain,
sid=sid,
server_ip=server_ip,
)
assert add_res.success, f"add-host failed: {add_res.error_message}"
print(f" Created host {host_name} (uid={add_res.data.get('uid')})")
print("\nStep 3: Publishing session...")
pub_res = await client.api_call(
mgmt_name,
"publish",
{},
domain=domain,
sid=sid,
server_ip=server_ip,
wait_for_task=True,
)
assert pub_res.success, f"publish failed: {pub_res.error_message}"
print(" Published successfully.")
finally:
await client.logout_sid(mgmt_name, sid, server_ip=server_ip)
print("\nStep 4: Verifying show-last-published-session advanced...")
after_res = await client.api_call(mgmt_name, "show-last-published-session", {}, domain=domain)
assert after_res.success
new_uid = after_res.data.get("uid")
print(f" Previous UID: {base_rev['uid']}")
print(f" Current UID: {new_uid}")
assert new_uid != base_rev["uid"]
print("\nStep 5: Exiting guarded_session will automatically revert domain to baseline...")
final_res = await client.api_call(mgmt_name, "show-last-published-session", {}, domain=domain)
print(f"Step 6: Verified post-revert UID: {final_res.data.get('uid')}")
if __name__ == "__main__":
asyncio.run(main())
07 — Contexts & Session Overlay (07_context_and_overlay.py)
Demonstrates runtime auth_context, user_context, and isolated write_session with SessionOverlay read-your-own-writes isolation (verifying that uncommitted objects appear immediately in get_hosts(), find_object(), and search_objects() before discarding cleanly on exit).
Source Code (examples/07_context_and_overlay.py)
"""Example 07 — Dynamic `auth_context`, `user_context`, and `write_session` with `SessionOverlay`.
Run:
uv run examples/07_context_and_overlay.py
Demonstrates Arodonata v2's context-aware multi-user and transactional features:
1. `with client.auth_context(username=..., password=...)` — dynamically overrides credentials
per asyncio task without mutating client settings.
2. `with client.user_context(username=..., session_name=..., session_description=...)` —
propagates operator attribution and Check Point session naming into `write_session` and logs.
3. `async with client.write_session(mgmt_name, domain, publish_on_exit=False)` — opens an
isolated `WriteSession` backed by `SessionOverlay` so uncommitted `add_object` / `set_object` /
`delete_object` mutations are immediately visible to `get_hosts`, `find_object`, and
`search_objects` inside the context ("read-your-own-writes") while remaining invisible to
other readers and the shared SQLite cache until published.
"""
from __future__ import annotations
import asyncio
import os
import uuid
from dotenv import load_dotenv
load_dotenv(".env.test", override=True)
load_dotenv(".env.lib", override=True)
load_dotenv(".env.secrets", override=True)
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
async def main() -> None:
"""Demonstrate auth_context, user_context, and WriteSession SessionOverlay isolation."""
settings = ArodonataSettings()
mgmt_name = settings.mgmt_names[0]
domain = os.getenv("EXAMPLE_DOMAIN") or os.getenv("TEST_DOMAIN_A", "Domain4")
tag = uuid.uuid4().hex[:6]
temp_host = f"overlay-demo-host-{tag}"
async with ArodonataClient(settings=settings) as client:
# Warm the host cache for the target domain
await client.refresh_objects(mgmt_name=mgmt_name, domains=[domain], types=["host"], mode="smart")
eng_password = os.getenv("USER_eng1") or os.getenv("USER_Eng1") or os.getenv("USER_admin", "") # noqa: SIM112
eng_user = "eng1" if (os.getenv("USER_eng1") or os.getenv("USER_Eng1")) else "admin" # noqa: SIM112
print(f"1. Entering auth_context(username={eng_user!r}) + user_context(session_name=' Ticket-700 ')...")
with (
client.auth_context(username=eng_user, password=eng_password),
client.user_context(
user_id=eng_user,
username=eng_user,
session_name=f"CHG-Overlay-{tag}",
session_description="Read-your-own-writes SessionOverlay demo",
),
):
# Use publish_on_exit=False and discard explicitly so the lab is never mutated
async with client.write_session(
mgmt_name,
domain,
publish_on_exit=False,
) as ws:
print(f"2. Opened WriteSession (session_name={ws.session_name!r}, server_ip={ws.server_ip})")
add_res = await client.add_object(
mgmt_name,
"host",
{
"name": temp_host,
"ipv4-address": "198.51.100.241",
"comments": "Uncommitted host in SessionOverlay",
},
domain=domain,
)
assert add_res.success, add_res.error_message
print(f"3. Added uncommitted host {temp_host!r} inside WriteSession.")
# Read-your-own-writes: find_object and search_objects see the uncommitted host!
found = await client.find_object(mgmt_name, domain, temp_host, obj_type="host", cache_mode="cache")
assert found is not None
print(f"4. Inside WriteSession, find_object({temp_host!r}) -> {found.name} ({found.ipv4_address})")
search_res = await client.search_objects(
"198.51.100.241",
mgmt_name=mgmt_name,
domains=[domain],
cache_mode="cache",
)
print(
f"5. Inside WriteSession, search_objects('198.51.100.241') matched: {[m.name for m in search_res.matches]}"
)
# Discard uncommitted changes before exiting so nothing is published
disc = await client.api_call(
mgmt_name,
"discard",
{},
domain=domain,
sid=ws.sid,
server_ip=ws.server_ip,
)
assert disc.success
ws.discarded = True
print("6. Discarded WriteSession cleanly without publishing.")
# Outside the WriteSession, the discarded host is not in the cache
outside = await client.find_object(mgmt_name, domain, temp_host, obj_type="host", cache_mode="cache")
print(f"7. Outside WriteSession, find_object({temp_host!r}) -> {outside}")
if __name__ == "__main__":
asyncio.run(main())
08 — CPCRUD Operations (08_cpcrud_operations.py)
Demonstrates offline JSON Schema validation (client.cpcrud.validate()), deterministic planning (client.cpcrud.plan()), and idempotent execution (client.cpcrud.apply()) using examples/crud_example.yaml.
Declarative Template (examples/crud_example.yaml)
# CPCRUD v2 example template: hosts, networks, TCP service, group, access rule, and NAT rule.
#
# Validated offline against `checkpoint_ops_schema.json` via `client.cpcrud.validate()`.
# Adjust `mgmt_name`, `domain`, `layer`, and `package` to match your target environment.
version: 1
mgmt_name: "mdsH5b"
domain: "Domain4"
on_name_conflict: "update"
on_ip_conflict: "reuse"
objects:
- type: "host"
name: "cpcrud-example-host-1"
ipv4-address: "198.51.100.10"
comments: "CPCRUD example host"
color: "dark green"
- type: "network"
name: "cpcrud-example-net-1"
subnet4: "198.51.100.0"
mask-length4: 24
comments: "CPCRUD example network"
color: "blue"
services:
- type: "service-tcp"
name: "cpcrud-example-tcp-8443"
port: "8443"
comments: "CPCRUD example custom HTTPS port"
groups:
- type: "group"
name: "cpcrud-example-group"
members:
- "cpcrud-example-host-1"
- "cpcrud-example-net-1"
comments: "CPCRUD example group"
rules:
- type: "access-rule"
layer: "FPCR_UAT_Active Network"
position: "bottom"
name: "cpcrud-example-access-rule"
source:
- "cpcrud-example-host-1"
destination:
- "Any"
service:
- "cpcrud-example-tcp-8443"
rule_action: "Drop"
comments: "CPCRUD example access rule"
- type: "nat-rule"
package: "FPCR_UAT_Active"
position: "top"
name: "cpcrud-example-nat-rule"
method: "hide"
original-source: "cpcrud-example-host-1"
original-destination: "Any"
original-service: "Any"
translated-source: "cpcrud-example-host-1"
translated-destination: "Original"
translated-service: "Original"
comments: "CPCRUD example NAT rule"
Source Code (examples/08_cpcrud_operations.py)
"""Example 08 — Declarative CPCRUD operations (`validate`, `plan`, `apply`, and idempotency).
Run:
uv run examples/08_cpcrud_operations.py
Demonstrates:
1. Loading `examples/crud_example.yaml` and validating it offline (`client.cpcrud.validate`).
2. Planning (`await client.cpcrud.plan`) and applying (`await client.cpcrud.apply`) the template.
3. Re-planning and re-applying the exact same template to prove idempotency (Pass 2 produces
`unchanged` / `reuse` outcomes and zero `create` actions).
4. Wrapping execution in `_session_guard.guarded_session` so the lab domain is automatically
reverted to its pre-run baseline revision on exit.
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
from pathlib import Path
import yaml
from dotenv import load_dotenv
load_dotenv(".env.test", override=True)
load_dotenv(".env.lib", override=True)
load_dotenv(".env.secrets", override=True)
logging.basicConfig(level=logging.WARNING)
sys.path.insert(0, str(Path(__file__).parent))
from _session_guard import guarded_session # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
YAML_FILE = Path(__file__).parent / "crud_example.yaml"
async def main() -> None:
"""Validate, plan, and apply `examples/crud_example.yaml` twice to demonstrate idempotency."""
settings = ArodonataSettings()
mgmt_name = settings.mgmt_names[0]
domain = os.getenv("EXAMPLE_DOMAIN") or os.getenv("TEST_DOMAIN_A", "Domain4")
raw_template = yaml.safe_load(YAML_FILE.read_text(encoding="utf-8"))
raw_template["mgmt_name"] = mgmt_name
raw_template["domain"] = domain
async with ArodonataClient(settings=settings) as client:
# 1. Offline JSON Schema validation (zero network calls)
print("[Step 1/4] Validating template against offline CPCRUD JSON Schema...", flush=True)
errors = client.cpcrud.validate(raw_template)
assert not errors, f"Template validation failed: {errors}"
print("Template passed offline JSON Schema validation.")
print(f"[Step 2/4] Capturing baseline revision on {mgmt_name}:{domain}...", flush=True)
async with guarded_session(client, mgmt_name, domains=[domain]):
for run in (1, 2):
step_num = run + 1
print(
f"[Step {step_num}/4] Planning and applying CPCRUD template (Run {run}/2)...",
flush=True,
)
plan = await client.cpcrud.plan(raw_template)
print(f"\n--- Run {run}: Planned {len(plan.actions)} action(s) ---")
for act in plan.actions:
print(
f" plan: [{act.mgmt_name}:{act.domain_name}] {act.outcome.value:9} {act.object_type} {act.name}"
)
report = await client.cpcrud.apply(
plan,
session_name=f"cpcrud-example-run-{run}",
)
print(
f"Run {run} apply report: success={report.success} "
f"created={report.created_count} updated={report.updated_count} "
f"unchanged={report.unchanged_count} failed={report.failed_count}"
)
for res in report.results:
print(
f" apply: [{res.mgmt_name}:{res.domain_name}] {res.outcome.value:9} {res.object_type} {res.name}"
)
print(f"\nReverting {mgmt_name}:{domain} to baseline revision...", flush=True)
if __name__ == "__main__":
asyncio.run(main())
09 — CPCRUD Inverse Rollback (09_cpcrud_inverse.py)
Demonstrates generating a compensating rollback template via client.cpcrud.inverse(plan, report) and applying it to restore the domain state.
Source Code (examples/09_cpcrud_inverse.py)
"""Example 09 — CPCRUD compensating rollback template (`plan` -> `apply` -> `inverse` -> `apply`).
Run:
uv run examples/09_cpcrud_inverse.py
Demonstrates how `client.cpcrud.inverse(plan, report)` builds a schema-valid compensating
template from the original `Plan` and `ApplyReport`:
- Created objects/services/groups/rules become `delete` operations keyed by `uid`.
- Updated objects/rules roll back to their captured `prior_state`.
- Deleted objects/rules are re-created from their captured `prior_state`.
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
load_dotenv(".env.test", override=True)
load_dotenv(".env.lib", override=True)
load_dotenv(".env.secrets", override=True)
logging.basicConfig(level=logging.WARNING)
sys.path.insert(0, str(Path(__file__).parent))
from _session_guard import guarded_session # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
async def main() -> None:
"""Plan, apply, generate an inverse rollback template, and apply the rollback."""
settings = ArodonataSettings()
mgmt_name = settings.mgmt_names[0]
domain = os.getenv("EXAMPLE_DOMAIN") or os.getenv("TEST_DOMAIN_A", "Domain4")
template: dict[str, Any] = {
"version": 1,
"mgmt_name": mgmt_name,
"domain": domain,
"objects": [
{
"type": "host",
"name": "cpcrud-example-inverse-host",
"ipv4-address": "198.51.100.19",
"comments": "Created for CPCRUD inverse rollback demo",
}
],
}
print(f"[Step 1/4] Capturing baseline revision on {mgmt_name}:{domain}...", flush=True)
async with ArodonataClient(settings=settings) as client, guarded_session(client, mgmt_name, domains=[domain]):
# 1. Plan ONCE and keep the Plan instance for inverse()
print("[Step 2/4] Planning and applying forward CPCRUD template...", flush=True)
plan = await client.cpcrud.plan(template)
report = await client.cpcrud.apply(plan, session_name="cpcrud-inverse-forward")
print(f"Forward apply: success={report.success} created={report.created_count}")
for r in report.results:
print(f" forward: [{r.mgmt_name}:{r.domain_name}] {r.outcome.value:9} {r.object_type} {r.name}")
# 2. Generate compensating inverse template from (plan, report)
print("\n[Step 3/4] Generating and validating compensating inverse template...", flush=True)
inverse_template = client.cpcrud.inverse(plan, report)
val_errors = client.cpcrud.validate(inverse_template)
assert not val_errors, f"Inverse template failed schema validation: {val_errors}"
# 3. Plan and apply the compensating template
print("[Step 4/4] Planning and applying inverse rollback template...", flush=True)
inv_plan = await client.cpcrud.plan(inverse_template)
inv_report = await client.cpcrud.apply(inv_plan, session_name="cpcrud-inverse-rollback")
print(f"\nInverse rollback: success={inv_report.success} deleted={inv_report.deleted_count}")
for r in inv_report.results:
print(f" inverse: [{r.mgmt_name}:{r.domain_name}] {r.outcome.value:9} {r.object_type} {r.name}")
print(f"\nVerifying/reverting {mgmt_name}:{domain} baseline on exit...", flush=True)
if __name__ == "__main__":
asyncio.run(main())
10 — Change Report Evidence (10_change_report_evidence.py)
Demonstrates collecting and rendering auditable ChangeReport evidence (HTML, Markdown, JSON), comparing live unpublished rulebase numbering (OwnedSession) against published cached numbering.
Source Code (examples/10_change_report_evidence.py)
"""Example 10 — Auditable change report evidence (`OwnedSession` pending vs published HTML/Markdown/JSON).
Run:
ARODONATA_LAB=home uv run examples/10_change_report_evidence.py
Demonstrates:
1. Creating a baseline setup session and a change session in a lab domain (`Domain5` by default).
2. Collecting and rendering a `ChangeReport` while the session is still unpublished using
`OwnedSession(sid=..., server_ip=...)` (`numbering_source == "owned_session"`).
3. Publishing the session and rendering the final auditable bundle (`html`, `markdown`, `json`)
to `examples/_tmp/`.
4. Reverting the domain to its original baseline via `_session_guard.guarded_session`.
"""
from __future__ import annotations
import asyncio
import logging
import os
import sys
import uuid
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(".env.test", override=True)
load_dotenv(".env.lib", override=True)
load_dotenv(".env.secrets", override=True)
logging.basicConfig(level=logging.WARNING)
sys.path.insert(0, str(Path(__file__).parent))
from _session_guard import guarded_session # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
from arodonata.reports import ( # noqa: E402
OwnedSession,
RenderedReportBundle,
RenderOptions,
SessionScope,
)
OUT_DIR = Path(__file__).parent / "_tmp"
def _write_bundle(bundle: RenderedReportBundle, prefix: str) -> None:
OUT_DIR.mkdir(parents=True, exist_ok=True)
if bundle.html is not None:
(OUT_DIR / f"{prefix}.html").write_bytes(bundle.html)
if bundle.markdown is not None:
(OUT_DIR / f"{prefix}.md").write_text(bundle.markdown, encoding="utf-8")
if bundle.json_text is not None:
(OUT_DIR / f"{prefix}.json").write_text(bundle.json_text, encoding="utf-8")
for sess in bundle.report.sessions:
print(
f"{prefix}: session={sess.session_name!r} state={sess.state} "
f"numbering_source={sess.numbering_source} "
f"rules={len(sess.rule_changes)} objects={len(sess.object_changes)}"
)
print(f" -> wrote {OUT_DIR / prefix}.{{html,md,json}}")
async def main() -> None:
"""Create a sample firewall change, generate pending and published evidence reports, and revert."""
settings = ArodonataSettings()
mgmt_name = settings.mgmt_names[0]
domain = os.getenv("TEST_DOMAIN_B", "Domain5")
tag = uuid.uuid4().hex[:6]
options = RenderOptions(
title="Evidence: **RITM-EXAMPLE** — *Firewall Policy Change*",
header_fields={"RITM": "RITM-EXAMPLE", "Requester": "secops"},
)
print(f"[Step 1/5] Capturing baseline revision on {mgmt_name}:{domain}...", flush=True)
async with ArodonataClient(settings=settings) as client, guarded_session(client, mgmt_name, domains=[domain]):
print(f"[Step 2/5] Refreshing rulebase cache for {mgmt_name}:{domain}...", flush=True)
await client.refresh_rulebases(mgmt_name=mgmt_name, domains=[domain], mode="force")
packages = await client.get_policy_packages(mgmt_name, domain, cache_mode="cache")
if not packages or not packages[0].access_layers:
print(f"No policy package/access layer found in {domain}.")
return
layer_name = next(
(lay.layer_name for lay in packages[0].access_layers if lay.layer_name != "Global"),
packages[0].access_layers[0].layer_name,
)
print(
f"[Step 3/5] Opening dedicated session on {mgmt_name}:{domain} and staging host + rule in {layer_name!r}...",
flush=True,
)
sid, server_ip = await client.create_dedicated_session(
mgmt_name,
domain,
session_name=f"ritm-example-{tag}",
session_description="Change report evidence example",
)
try:
s_info = await client.api_call(
mgmt_name,
"show-session",
{},
domain=domain,
sid=sid,
server_ip=server_ip,
)
session_uid = str(s_info.data["uid"])
host_name = f"cr-web-{tag}"
rule_name = f"cr-allow-web-{tag}"
await client.api_call(
mgmt_name,
"add-host",
{"name": host_name, "ipv4-address": "198.51.100.245", "comments": "DMZ web server"},
domain=domain,
sid=sid,
server_ip=server_ip,
)
await client.api_call(
mgmt_name,
"add-access-rule",
{
"layer": layer_name,
"position": "top",
"name": rule_name,
"source": "Any",
"destination": host_name,
"service": "https",
"action": "Accept",
},
domain=domain,
sid=sid,
server_ip=server_ip,
)
# 1. Pending session evidence numbered live via OwnedSession
print("[Step 4/5] Building pending change report via OwnedSession...", flush=True)
owned = OwnedSession(
sid=sid,
server_ip=server_ip,
session_uid=session_uid,
mgmt_name=mgmt_name,
domain=domain,
)
pending_scope = SessionScope(
mgmt_name=mgmt_name,
domain=domain,
session_uids=[session_uid],
owned_sessions=owned,
)
pending_bundle = await client.build_change_report(
[pending_scope],
formats=("html", "markdown", "json"),
options=options,
)
_write_bundle(pending_bundle, "evidence-1-pending")
# 2. Publish the session and refresh rulebase cache
print("[Step 5/5] Publishing session and building published change report...", flush=True)
await client.api_call(
mgmt_name,
"publish",
{},
domain=domain,
sid=sid,
server_ip=server_ip,
wait_for_task=True,
)
finally:
await client.logout_sid(mgmt_name, sid, server_ip=server_ip)
await client.refresh_rulebases(mgmt_name=mgmt_name, domains=[domain], mode="force")
pub_scope = SessionScope(
mgmt_name=mgmt_name,
domain=domain,
session_uids=[session_uid],
)
pub_bundle = await client.build_change_report(
[pub_scope],
formats=("html", "markdown", "json"),
options=options,
)
_write_bundle(pub_bundle, "evidence-2-published")
print(f"Reverting {mgmt_name}:{domain} to baseline revision...", flush=True)
if __name__ == "__main__":
asyncio.run(main())
11 — OpenTelemetry Tracing (11_otel_tracing.py)
Demonstrates provider-agnostic OpenTelemetry span instrumentation (arlogi.otel.setup_tracing + ARODONATA_TRACE_MODULES) and per-span latency analysis from exported JSONL traces.
Source Code (examples/11_otel_tracing.py)
"""Example 11 — Provider-agnostic OpenTelemetry tracing with per-span timing breakdown.
Run:
uv run examples/11_otel_tracing.py
Arodonata v2 is a provider-agnostic OpenTelemetry span producer (`opentelemetry-api` +
`arlogi.otel.traced`) and never owns or configures a global `TracerProvider`. When an application
or script configures tracing via `arlogi.otel.setup_tracing()`, all `@traced` methods across
`ArodonataClient`, `DomainSyncCoordinator`, `ObjectService`, `AMgmtClient`, and `ApiTransport`
automatically emit nested spans with sanitized attributes (never leaking SIDs or secrets).
"""
from __future__ import annotations
import asyncio
import json
import os
import shutil
import time
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arlogi.otel import setup_tracing, shutdown_tracing # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings # noqa: E402
from arodonata.core.telemetry import set_trace_modules # noqa: E402
TRACE_DIR = Path(__file__).parent / "_tmp" / "otel_traces"
def _iter_spans(trace_dir: Path) -> Iterator[dict[str, Any]]:
"""Yield every exported span dict across rotated JSONL trace files."""
for file_path in sorted(trace_dir.glob("*.jsonl")):
for line in file_path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
payload = json.loads(line)
for resource_span in payload.get("resourceSpans", []):
for scope_span in resource_span.get("scopeSpans", []):
yield from scope_span.get("spans", [])
def _print_span_summary(trace_dir: Path) -> None:
durations_ms: dict[str, list[float]] = {}
for span in _iter_spans(trace_dir):
start = int(span.get("startTimeUnixNano", 0))
end = int(span.get("endTimeUnixNano", 0))
durations_ms.setdefault(span.get("name", "?"), []).append(max(end - start, 0) / 1e6)
if not durations_ms:
print(" (no spans exported in TRACE_DIR)")
return
print(f"\n{'Span Name':<65} {'Count':>6} {'Total ms':>10} {'Avg ms':>10}")
print("-" * 95)
for name, values in sorted(durations_ms.items(), key=lambda kv: -sum(kv[1])):
print(f" {name:<63} {len(values):>6} {sum(values):>10.1f} {sum(values) / len(values):>10.1f}")
async def main() -> None:
"""Run asset and object refresh with OpenTelemetry JSONL trace export and summarize spans."""
shutil.rmtree(TRACE_DIR, ignore_errors=True)
TRACE_DIR.mkdir(parents=True, exist_ok=True)
setup_tracing(service_name="arodonata-example-11", file_dir=TRACE_DIR)
set_trace_modules({"arodonata": True})
settings = ArodonataSettings(trace_modules="arodonata:on")
target_domains = [os.environ["EXAMPLE_DOMAIN"]] if os.getenv("EXAMPLE_DOMAIN") else None
t0 = time.perf_counter()
try:
async with ArodonataClient(settings=settings) as client:
print("[Step 1/2] Refreshing assets with OpenTelemetry tracing active...", flush=True)
await client.refresh_assets(domains=target_domains, mode="smart")
print("[Step 2/2] Refreshing network objects with OpenTelemetry tracing active...", flush=True)
await client.refresh_objects(domains=target_domains, types=["host", "network"], mode="smart")
finally:
shutdown_tracing()
print(f"\nTotal wall time: {time.perf_counter() - t0:.2f}s")
_print_span_summary(TRACE_DIR)
if __name__ == "__main__":
asyncio.run(main())
12 — Embedded FastAPI MCP Server (12_mcp_embedded.py)
Demonstrates embedding Arodonata's Streamable-HTTP MCP server (create_mcp_server, create_asgi_app) inside a FastAPI application alongside custom host-defined MCP tools.
Source Code (examples/12_mcp_embedded.py)
"""Example 12 — Embedding Arodonata's MCP server inside a FastAPI application (`create_asgi_app`).
Run:
uv run examples/12_mcp_embedded.py
Then connect an MCP client to `http://127.0.0.1:8000/mcp`.
Demonstrates:
1. Creating an `ArodonataClient` and wiring it into `create_mcp_server(client, auth_mode="host")`.
2. Registering custom application-specific tools alongside Arodonata's built-in Check Point tools.
3. Wrapping the MCP server in `create_asgi_app` and mounting it inside a FastAPI lifespan.
"""
from __future__ import annotations
import os
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import asynccontextmanager
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
import uvicorn # noqa: E402
from fastapi import FastAPI, Request, Response # noqa: E402
from fastapi.responses import JSONResponse # noqa: E402
from arodonata import ArodonataClient, ArodonataSettings, user_context # noqa: E402
from arodonata.mcp import ArodonataMCPSettings, create_asgi_app, create_mcp_server # noqa: E402
settings = ArodonataSettings()
client = ArodonataClient(settings=settings)
mcp_settings = ArodonataMCPSettings(
server_name="acme-firewall-assistant",
auth_mode="host",
port=8000,
path="/mcp",
cpcrud=True,
)
mcp_server = create_mcp_server(client, mcp_settings=mcp_settings)
@mcp_server.tool(
name="acme_change_ticket",
description="Look up the ACME change ticket that introduced a firewall rule (demo stub).",
)
async def acme_change_ticket(rule_uid: str) -> dict[str, str]:
"""Return a demo change ticket reference for `rule_uid`."""
return {"rule_uid": rule_uid, "ticket": "CHG-2026-0001"}
mcp_app = create_asgi_app(client, mcp_server=mcp_server, mcp_settings=mcp_settings)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
"""Initialize ArodonataClient and the Streamable-HTTP MCP router lifespan."""
async with client, mcp_app.router.lifespan_context(mcp_app.starlette_app):
yield
app = FastAPI(title="ACME Firewall Assistant (Arodonata v2 MCP)", lifespan=lifespan)
EXPECTED_HOST_API_KEY = os.environ.get("ACME_HOST_API_KEY", "acme-host-demo-token-0123456789abcdef")
@app.middleware("http")
async def host_authentication_middleware(
request: Request,
call_next: Callable[[Request], Awaitable[Response]],
) -> Response:
"""Enclosing ASGI host authentication middleware required when `auth_mode='host'` (`I18`)."""
if request.url.path == "/healthz":
return await call_next(request)
auth_header = request.headers.get("Authorization", "")
if auth_header != f"Bearer {EXPECTED_HOST_API_KEY}":
return JSONResponse({"detail": "Unauthorized"}, status_code=401)
caller_id = request.headers.get("X-Client-ID", "acme-portal-user")
with user_context(user_id=caller_id, client_id=caller_id):
return await call_next(request)
@app.get("/healthz")
async def healthz() -> dict[str, str]:
"""Health check endpoint."""
return {"status": "ok"}
app.mount("/", mcp_app)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
13 — Gateway Topology Matching (13_gateway_topology_matching.py)
Demonstrates offline and live gateway topology workflows (refresh_topology, get_gateway_topology, summarize_gateway_interfaces, find_affected_gateways, get_topology_diagnostics, reconcile_gateway_topology, and upsert_topology_annotations) using replay fixtures.
Source Code (examples/13_gateway_topology_matching.py)
"""Example 13 — Gateway interface topology caching & affected gateway candidate matching (`get_gateway_topology`, `find_affected_gateways`).
Run:
uv run examples/13_gateway_topology_matching.py
Demonstrates:
1. Synchronizing and querying the gateway interface topology cache (`arodonata_gateway_topology`) via
`client.get_gateway_topology(...)`.
2. Summarizing flat topology intervals per gateway interface (`TopologyService.summarize_gateway_interfaces`).
3. Discovering which policy-enforcing gateways (simple gateways, clusters, and VSX Virtual Systems),
domains, policy packages, and access layers are affected by traffic between `sources` and `destinations`
via `client.find_affected_gateways(sources, destinations, ...)`, excluding gateways where both endpoints
reside behind the same interface (`src_interface == dst_interface`).
"""
from __future__ import annotations
import asyncio
import os
import time
from dotenv import load_dotenv
load_dotenv(".env.lib", override=False)
load_dotenv(".env.secrets", override=False)
from arodonata import ArodonataClient, ArodonataSettings, TopologyService # noqa: E402
async def main() -> None:
"""Inspect cached gateway interface topology and locate candidate gateways for sample traffic flows."""
settings = ArodonataSettings()
raw_domain = os.getenv("EXAMPLE_DOMAIN")
target_domain = raw_domain.strip() if raw_domain and raw_domain.strip() else None
sample_sources = [
s.strip() for s in os.getenv("EXAMPLE_FLOW_SOURCES", "10.0.0.0/8, 192.168.0.0/16").split(",") if s.strip()
]
sample_destinations = [
d.strip() for d in os.getenv("EXAMPLE_FLOW_DESTINATIONS", "172.16.0.0/12, 8.8.8.8").split(",") if d.strip()
]
t0 = time.perf_counter()
async with ArodonataClient(settings=settings) as client:
print(
f"[Step 1/3] Fetching gateway topology entries for domain={target_domain!r} (get_gateway_topology)...",
flush=True,
)
entries = await client.get_gateway_topology(domain=target_domain, cache_mode="smart")
print(f" Cached topology intervals: {len(entries)}")
print("\n[Step 2/3] Summarizing topology per gateway interface...", flush=True)
summaries = TopologyService.summarize_gateway_interfaces(entries)
print(f" Policy-enforcing gateway interfaces: {len(summaries)}")
for summary in summaries[:10]:
cidrs_preview = ", ".join(summary.cidrs_and_ranges[:4])
if len(summary.cidrs_and_ranges) > 4:
cidrs_preview += f", ... (+{len(summary.cidrs_and_ranges) - 4} more)"
dmz_tag = " [DMZ]" if summary.leads_to_dmz else ""
print(
f" - {summary.gateway_asset_id} :: {summary.interface_name} "
f"({summary.topology_zone}{dmz_tag}, sources={summary.source_types}): {cidrs_preview}"
)
print(
f"\n[Step 3/3] Finding affected gateways for sources={sample_sources} -> destinations={sample_destinations}...",
flush=True,
)
candidates = await client.find_affected_gateways(
sources=sample_sources,
destinations=sample_destinations,
domain=target_domain,
cache_mode="cache",
)
print(f" Affected policy-enforcing gateways found: {len(candidates)}")
for cand in candidates:
print(
f" * {cand.gateway_asset_id} ({cand.gateway_type}, ip={cand.ipv4_address}) "
f"policy={cand.installed_access_policy!r} packages={cand.policy_packages} layers={cand.access_layers}"
)
for flow in cand.matched_flows[:5]:
print(
f" {flow.source_query} ({flow.src_interface} [{flow.src_topology_zone}: {flow.src_matched_cidr}]) "
f"-> {flow.destination_query} ({flow.dst_interface} [{flow.dst_topology_zone}: {flow.dst_matched_cidr}]) "
f"[{flow.match_type}]"
)
print(f"\nCompleted in {time.perf_counter() - t0:.2f}s")
if __name__ == "__main__":
asyncio.run(main())