Classifying with the cache#

Pipeline.classify is what fireman classify runs: it classifies every policy of a loaded inventory and returns a Classification with policies (one PolicyFindings(firewall, policy, findings) per policy, in inventory order, clean policies included) and cached (the firewalls reused from the cache). The report functions take result.policies. Unlike Compiling and classifying by hand, it compiles one firewall at a time and can skip firewalls whose findings are already cached.

The full script is below; it reads estate.yaml and branch.json from the current directory, so the estate has two firewalls, edge and branch.

classify_cache.py
"""Classify with the findings cache: a miss, a hit, a changed firewall and a forced rerun."""

import tempfile
from pathlib import Path

import click

from fireman import BDDManager, Pipeline, Store, file_source
from fireman.model import Firewall, Inventory, Policy


def run(title: str, inventory: Inventory, store: Store | None, *, reuse: bool = True) -> None:
    """Classify, then print which policies came from the cache and the findings per policy."""
    report = pipeline.classify(inventory, make_bdd=BDDManager, store=store, reuse=reuse).policies
    cached = ", ".join(f"{e.firewall}/{e.policy}" for e in report if e.cached) or "none"
    counts = ", ".join(f"{e.firewall}/{e.policy} {len(e.findings)}" for e in report)
    click.echo(f"{title}: cached {cached}; findings: {counts}")


pipeline = Pipeline()
inventory = pipeline.load(file_source(Path("estate.yaml")), file_source(Path("branch.json")))

# A throwaway folder keeps the demo repeatable; the CLI uses Store(), i.e. ./.fireman.
with tempfile.TemporaryDirectory() as folder:
    store = Store(Path(folder))

    for firewall in inventory.firewalls:
        digest = store.digest(inventory, firewall, implicit_deny=True)
        click.echo(f"{firewall.name}: cached findings {store.findings(digest)}")

    run("first run", inventory, store)
    run("second run", inventory, store)

    # The cache is readable directly: findings() returns what classify stored.
    branch = next(fw for fw in inventory.firewalls if fw.name == "branch")
    for entry in store.findings(store.digest(inventory, branch, implicit_deny=True)) or ():
        for finding in entry.findings:
            click.echo(f"  cached for branch: {finding.rule.name} {finding.anomaly.value}")

    # Drop the shadowed rule from branch. Only branch's digest changes, so edge stays cached.
    outbound = branch.policies[0]
    fixed = Policy(name=outbound.name, rules=tuple(r for r in outbound.rules if r.name != "block-test-net"))
    edited = Inventory(
        objects=inventory.objects,
        firewalls=tuple(
            Firewall(name=fw.name, objects=fw.objects, policies=(fixed,)) if fw.name == "branch" else fw
            for fw in inventory.firewalls
        ),
    )
    run("branch edited", edited, store)

    # reuse=False recomputes everything and refreshes the cache.
    run("reuse=False", edited, store, reuse=False)

    # Without a store nothing is cached or reused.
    run("no store", edited, store=None)

    # clear_all() deletes the database file, workspaces included; clear(name) drops one workspace.
    store.clear_all()
estate.yaml
# A small estate: one firewall, `edge`, between the internet, a DMZ and the LAN.
# The docs use it throughout. `inbound` is seeded with anomalies; `outbound` is
# clean.

addresses:
  - name: lan
    values: [10.1.0.0/16]
  - name: dmz
    values: [192.168.10.0/24]
  - name: web-servers
    values: [192.168.10.10, 192.168.10.11, 192.168.10.12]

fqdns:
  - name: update-server
    fqdn: updates.example.com
    addresses: [203.0.113.10]
    resolved_at: 2026-11-20T08:00:00Z
  - name: partner-api
    fqdn: api.partner.example
    addresses: [203.0.113.50]
    resolved_at: 2026-11-20T08:00:00Z

services:
  - name: web
    entries:
      - {protocol: 6, ports: [80, 80]}
      - {protocol: 6, ports: [443, 443]}
  - name: ssh
    entries:
      - {protocol: 6, ports: [22, 22]}
  - name: dns
    entries:
      - {protocol: 17, ports: [53, 53]}
      - {protocol: 6, ports: [53, 53]}

groups:
  # Every DMZ host except the web servers. A global group sees the global
  # `web-servers`, even inside `edge`, which has its own.
  - name: dmz-hosts
    kind: address
    include: [dmz]
    exclude: [web-servers]

firewalls:
  - name: edge
    addresses:
      # edge publishes only two of the three web servers.
      - name: web-servers
        values: [192.168.10.10, 192.168.10.11]
    policies:
      - name: inbound
        rules:
          - order_id: 10
            name: block-abusers
            action: deny
            sources: [198.51.100.0/24]
            destinations: [web-servers]
            services: [web]
          - order_id: 20
            name: allow-web
            action: accept
            sources: [any]
            destinations: [web-servers]
            services: [web]
          - order_id: 30
            name: allow-partner-https
            action: accept
            sources: [203.0.113.0/24]
            destinations: [web-servers]
            services:
              - {protocol: 6, ports: [443, 443]}
          - order_id: 40
            name: block-scanners
            action: deny
            sources: [192.0.2.0/24]
            destinations: [web-servers]
            services: [web]
          - order_id: 50
            name: allow-partner-api
            action: accept
            sources: [partner-api]
            destinations: [web-servers]
            services: [web]
          - order_id: 60
            name: allow-admin-ssh
            action: accept
            sources: [lan]
            destinations: [dmz-hosts]
            services: [ssh]
      - name: outbound
        rules:
          - order_id: 10
            name: allow-dns
            action: accept
            sources: [lan]
            destinations: [any]
            services: [dns]
          - order_id: 20
            name: allow-updates
            action: accept
            sources: [dmz-hosts]
            destinations: [update-server]
            services: [web]
          - order_id: 30
            name: allow-web-out
            action: accept
            sources: [lan]
            destinations: [lan, dmz]
            destination_negate: true
            services: [web]
          - order_id: 40
            name: allow-ping
            action: accept
            sources: [lan]
            destinations: [any]
            services:
              - {protocol: 1, icmp_type: 8}
branch.json
{
  "firewalls": [
    {
      "name": "branch",
      "addresses": [
        {"name": "branch-lan", "values": ["10.2.0.0/16"]}
      ],
      "policies": [
        {
          "name": "outbound",
          "rules": [
            {
              "order_id": 10,
              "name": "allow-dns",
              "action": "accept",
              "sources": ["branch-lan"],
              "destinations": ["any"],
              "services": ["dns"]
            },
            {
              "order_id": 20,
              "name": "allow-web",
              "action": "accept",
              "sources": ["branch-lan"],
              "destinations": ["any"],
              "services": ["web"]
            },
            {
              "order_id": 30,
              "name": "block-test-net",
              "action": "deny",
              "sources": ["branch-lan"],
              "destinations": ["192.0.2.0/24"],
              "services": ["web"]
            }
          ]
        }
      ]
    }
  ]
}

One manager per firewall#

pipeline.classify(inventory, make_bdd=make_bdd, implicit_deny=True, store=None, reuse=True)

make_bdd is a factory, not a manager: any callable that returns a fresh BDDManager: the class itself, or functools.partial(BDDManager, nodes=1 << 28) to size it. Each firewall that has to be compiled gets its own manager, built from an inventory of just the global objects and that firewall. Dead nodes are collected after compiling, the policies are classified, and the manager is dropped before the next firewall starts. Firewalls never share rules or objects with each other, so nothing is lost, and peak memory is that of the largest firewall rather than the whole estate.

Each PolicyFindings has a cached flag: True when its firewall’s findings were read from the store, False when they were just computed. The script prints it per policy:

def run(title: str, inventory: Inventory, store: Store | None, *, reuse: bool = True) -> None:
    """Classify, then print which policies came from the cache and the findings per policy."""
    report = pipeline.classify(inventory, make_bdd=BDDManager, store=store, reuse=reuse).policies
    cached = ", ".join(f"{e.firewall}/{e.policy}" for e in report if e.cached) or "none"
    counts = ", ".join(f"{e.firewall}/{e.policy} {len(e.findings)}" for e in report)
    click.echo(f"{title}: cached {cached}; findings: {counts}")


classify returns a Classification model: policies holds the PolicyFindings in inventory order, and cached names the firewalls read from the store, also in inventory order. A firewall without policies has no PolicyFindings to carry the flag, but it still shows up in cached. fireman classify uses it for its N of M firewalls from cache line.

result = pipeline.classify(inventory, make_bdd=make_bdd, store=store)
result.policies  # one PolicyFindings per policy
result.cached  # ("edge", "branch") on a second run

The store#

Store(root) is the SQLite findings cache, in root / "fireman.db". The default root is .fireman relative to the current directory, which is where the CLI keeps it; the database is created on first use. Like .venv, it belongs to the folder you work in, so each project folder has its own. The same database also holds the CLI’s workspaces.

The pipeline asks store.digests(inventory, implicit_deny) once for every firewall (store.digest(inventory, firewall, implicit_deny) gives one), each a SHA-256 over:

  • the Fireman version,

  • the implicit_deny setting,

  • the global objects,

  • that firewall: its own objects and every policy and rule.

Other firewalls are not part of it, so changing one firewall leaves the others cached. A digest already in the store is a hit and its findings are reused, marked cached=True; the rest are compiled, and only those are saved (never with cached=True, so the flag only says how a result reached you). A stored row that no longer fits the current models counts as a miss and is overwritten. Since the digest covers every input, the cache can’t go stale; deleting it is only housekeeping.

pipeline = Pipeline()
inventory = pipeline.load(file_source(Path("estate.yaml")), file_source(Path("branch.json")))

# A throwaway folder keeps the demo repeatable; the CLI uses Store(), i.e. ./.fireman.
with tempfile.TemporaryDirectory() as folder:
    store = Store(Path(folder))

    for firewall in inventory.firewalls:
        digest = store.digest(inventory, firewall, implicit_deny=True)
        click.echo(f"{firewall.name}: cached findings {store.findings(digest)}")

    run("first run", inventory, store)
    run("second run", inventory, store)

    # The cache is readable directly: findings() returns what classify stored.
    branch = next(fw for fw in inventory.firewalls if fw.name == "branch")
    for entry in store.findings(store.digest(inventory, branch, implicit_deny=True)) or ():
        for finding in entry.findings:
            click.echo(f"  cached for branch: {finding.rule.name} {finding.anomaly.value}")

The script keeps its store in a temporary folder, so every run starts empty. store.findings(digest) reads one firewall’s cached findings back, or None.

A changed firewall, and forcing a rerun#

The script then removes block-test-net from branch by building a new inventory from the models (constructing the Policy and Inventory models validates them again), and classifies that:

    # Drop the shadowed rule from branch. Only branch's digest changes, so edge stays cached.
    outbound = branch.policies[0]
    fixed = Policy(name=outbound.name, rules=tuple(r for r in outbound.rules if r.name != "block-test-net"))
    edited = Inventory(
        objects=inventory.objects,
        firewalls=tuple(
            Firewall(name=fw.name, objects=fw.objects, policies=(fixed,)) if fw.name == "branch" else fw
            for fw in inventory.firewalls
        ),
    )
    run("branch edited", edited, store)

    # reuse=False recomputes everything and refreshes the cache.
    run("reuse=False", edited, store, reuse=False)

    # Without a store nothing is cached or reused.
    run("no store", edited, store=None)

    # clear_all() deletes the database file, workspaces included; clear(name) drops one workspace.
    store.clear_all()

reuse=False skips the lookups, compiles every firewall and saves them all, refreshing the cache, as fireman classify --no-cache does. With store=None nothing is read or written. store.clear(name) deletes one workspace only and returns whether it existed; store.clear_all() deletes the database file, cached findings and every workspace.

Output#

edge: cached findings None
branch: cached findings None
first run: cached none; findings: edge/inbound 5, edge/outbound 0, branch/outbound 1
second run: cached edge/inbound, edge/outbound, branch/outbound; findings: edge/inbound 5, edge/outbound 0, branch/outbound 1
  cached for branch: block-test-net shadowed
branch edited: cached edge/inbound, edge/outbound; findings: edge/inbound 5, edge/outbound 0, branch/outbound 0
reuse=False: cached none; findings: edge/inbound 5, edge/outbound 0, branch/outbound 0
no store: cached none; findings: edge/inbound 5, edge/outbound 0, branch/outbound 0

The second run compiles nothing: every policy is cached. After the edit only branch is compiled, and its shadowed rule is gone.

Note

The digest includes the Fireman version, not the analysis code. If you change Fireman itself, use reuse=False or clear the store.

What classify does#

        sequenceDiagram
    participant You
    participant Pipeline
    participant Store
    participant Factory as make_bdd
    participant Core as compile_inventory

    You->>Pipeline: classify(inventory, make_bdd, store)
    Pipeline->>Store: digests(inventory, implicit_deny)
    loop each firewall
        Pipeline->>Store: findings(digest)
        alt hit
            Store-->>Pipeline: cached PolicyFindings
        else miss
            Store-->>Pipeline: None
            Note over Pipeline: firewall marked to compile
        end
    end
    loop each missed firewall, one at a time
        Pipeline->>Factory: make_bdd()
        Factory-->>Pipeline: fresh BDDManager
        Pipeline->>Core: compile_inventory(global objects + this firewall, bdd)
        Core-->>Pipeline: CompiledInventory
        Pipeline->>Pipeline: bdd.gc(), classify() each policy
        Note over Pipeline: manager dropped
    end
    Pipeline->>Store: save(missed digests → findings)
    Pipeline-->>You: Classification(policies, cached)
    

To print the findings as a table, JSON or YAML, see Usage and reports.