Loading an estate#

Pipeline.load turns one or more sources into a validated Inventory model, the same object fireman load stores as a workspace. Nothing is compiled yet, so loading is quick even for a large estate.

The full script is below; it reads estate.yaml and branch.json from the current directory.

loading.py
"""Load the sample estate as a library: one file, several sources, and a failed load."""

from collections.abc import Iterator
from pathlib import Path

import click
from pydantic import ValidationError

from fireman import LoadError, Pipeline, Source, file_source, json_file, resource, yaml_file
from fireman.model import Inventory


def summary(inventory: Inventory) -> None:
    """Print what an inventory holds, firewall by firewall."""
    objects = inventory.objects
    click.echo(
        f"global: {len(objects.addresses)} addresses, {len(objects.fqdns)} fqdns, "
        f"{len(objects.services)} services, {len(objects.groups)} groups"
    )
    for firewall in inventory.firewalls:
        own = sorted(firewall.objects.kinds)
        policies = ", ".join(f"{p.name} ({len(p.rules)} rules)" for p in firewall.policies)
        click.echo(f"firewall {firewall.name}: own objects {own}; policies {policies}")


@resource("rules", firewall="edge", policy="inbound")
def bad_rules() -> Iterator[dict[str, object]]:
    yield {
        "order_id": 70,
        "name": "drop-telnet",
        "action": "drop",
        "sources": ["any"],
        "destinations": ["dmz"],
        "services": [{"protocol": 6, "ports": [23, 23]}],
    }


@resource("rules", firewall="edge", policy="inbound")
def unknown_services() -> Iterator[dict[str, object]]:
    yield {
        "order_id": 70,
        "name": "allow-monitoring",
        "action": "accept",
        "sources": ["lan"],
        "destinations": ["dmz"],
        "services": ["ntp", "snmp"],
    }


def try_load(pipeline: Pipeline, *sources: Source) -> None:
    """Load, and on failure print each problem with its fields."""
    try:
        pipeline.load(*sources)
    except LoadError as exc:
        click.echo(f"LoadError with {len(exc.problems)} problem(s):")
        for problem in exc.problems:
            click.echo(f"  {problem}")
            click.echo(
                f"    resource={problem.resource!r} scope={problem.scope!r} index={problem.index} loc={problem.loc}"
            )


pipeline = Pipeline()

# One file. yaml_file and json_file read Fireman's own format; file_source picks by suffix.
inventory = pipeline.load(yaml_file(Path("estate.yaml")))
click.echo("== estate.yaml")
summary(inventory)

# Several sources are merged by scope before one validation, so branch.json may use
# the global objects that estate.yaml defines.
merged = pipeline.load(file_source(Path("estate.yaml")), json_file(Path("branch.json")))
click.echo("== estate.yaml + branch.json")
summary(merged)

# A bad field is reported per item, with the item's index in its resource.
click.echo("== a rule with a bad action")
try_load(pipeline, file_source(Path("estate.yaml")), Source((bad_rules(),)))

# Names are checked across the whole estate, once every item is valid.
click.echo("== a rule with unknown service names")
try_load(pipeline, file_source(Path("estate.yaml")), Source((unknown_services(),)))

# Models are frozen and model_copy skips validation, so edit a dump and validate it again.
click.echo("== editing an inventory")
data = inventory.model_dump(mode="json")
rule = data["firewalls"][0]["policies"][0]["rules"][0]
rule["action"] = "accept"
edited = Inventory.model_validate(data)
before, after = (inv.firewalls[0].policies[0].rules[0] for inv in (inventory, edited))
click.echo(f"{after.name}: {before.action} -> {after.action}")

rule["services"] = ["ntp"]
try:
    Inventory.model_validate(data)
except ValidationError as exc:
    click.echo(exc.errors()[0]["msg"])
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"]
            }
          ]
        }
      ]
    }
  ]
}

From files#

yaml_file and json_file read Fireman’s own format and return a Source. file_source picks one of them by suffix (.yaml, .yml or .json). Reading only splits the file into resources; the checks run in load.

from collections.abc import Iterator
from pathlib import Path

import click
from pydantic import ValidationError

from fireman import LoadError, Pipeline, Source, file_source, json_file, resource, yaml_file
from fireman.model import Inventory


def summary(inventory: Inventory) -> None:
    """Print what an inventory holds, firewall by firewall."""
    objects = inventory.objects
    click.echo(
        f"global: {len(objects.addresses)} addresses, {len(objects.fqdns)} fqdns, "
        f"{len(objects.services)} services, {len(objects.groups)} groups"
    )
    for firewall in inventory.firewalls:
        own = sorted(firewall.objects.kinds)
        policies = ", ".join(f"{p.name} ({len(p.rules)} rules)" for p in firewall.policies)
        click.echo(f"firewall {firewall.name}: own objects {own}; policies {policies}")


pipeline = Pipeline()

# One file. yaml_file and json_file read Fireman's own format; file_source picks by suffix.
inventory = pipeline.load(yaml_file(Path("estate.yaml")))
click.echo("== estate.yaml")
summary(inventory)

Pipeline() takes an optional name, the workspace name the CLI uses; it makes no difference to load. The result is a frozen pydantic model: global objects in inventory.objects, then inventory.firewalls, each with its own objects and policies.

Several sources at once#

Pass any number of sources. Their resources are merged by scope (global, a firewall, or a firewall’s policy) in the order given, then the whole estate is validated once. So a firewall in one file can use global objects from another. branch.json holds only a firewall branch, whose rules use dns and web from estate.yaml:

# Several sources are merged by scope before one validation, so branch.json may use
# the global objects that estate.yaml defines.
merged = pipeline.load(file_source(Path("estate.yaml")), json_file(Path("branch.json")))
click.echo("== estate.yaml + branch.json")
summary(merged)

Names must still be unique within a scope across all sources, and a firewall that appears in two sources is one firewall: its objects and policies are joined.

When loading fails#

load raises LoadError with every problem it found, not just the first. Its problems attribute is a tuple of Problem models:

Resource

The resource name (rules, addresses, …), a file path for a problem in the file’s structure, or inventory for a cross-check.

Scope

Where the resource lives: global, edge or edge/inbound. None for a problem in a file’s structure or a resource created with a bad scope.

Index

The item’s position in its resource, counted from 0, or None when the problem is not tied to one item.

Loc

The field path inside the item, as in pydantic’s errors().

Message

What is wrong, in words.

str(problem) joins them into one line, and str(exc) is every problem, one per line, the same lines fireman load prints.

The script adds a rule to edge/inbound from a small in-code resource (see Extending for writing your own) to show both kinds of failure:

@resource("rules", firewall="edge", policy="inbound")
def bad_rules() -> Iterator[dict[str, object]]:
    yield {
        "order_id": 70,
        "name": "drop-telnet",
        "action": "drop",
        "sources": ["any"],
        "destinations": ["dmz"],
        "services": [{"protocol": 6, "ports": [23, 23]}],
    }


@resource("rules", firewall="edge", policy="inbound")
def unknown_services() -> Iterator[dict[str, object]]:
    yield {
        "order_id": 70,
        "name": "allow-monitoring",
        "action": "accept",
        "sources": ["lan"],
        "destinations": ["dmz"],
        "services": ["ntp", "snmp"],
    }


def try_load(pipeline: Pipeline, *sources: Source) -> None:
    """Load, and on failure print each problem with its fields."""
    try:
        pipeline.load(*sources)
    except LoadError as exc:
        click.echo(f"LoadError with {len(exc.problems)} problem(s):")
        for problem in exc.problems:
            click.echo(f"  {problem}")
            click.echo(
                f"    resource={problem.resource!r} scope={problem.scope!r} index={problem.index} loc={problem.loc}"
            )


# A bad field is reported per item, with the item's index in its resource.
click.echo("== a rule with a bad action")
try_load(pipeline, file_source(Path("estate.yaml")), Source((bad_rules(),)))

# Names are checked across the whole estate, once every item is valid.
click.echo("== a rule with unknown service names")
try_load(pipeline, file_source(Path("estate.yaml")), Source((unknown_services(),)))

# Models are frozen and model_copy skips validation, so edit a dump and validate it again.
click.echo("== editing an inventory")
data = inventory.model_dump(mode="json")
rule = data["firewalls"][0]["policies"][0]["rules"][0]
rule["action"] = "accept"
edited = Inventory.model_validate(data)
before, after = (inv.firewalls[0].policies[0].rules[0] for inv in (inventory, edited))
click.echo(f"{after.name}: {before.action} -> {after.action}")

rule["services"] = ["ntp"]
try:
    Inventory.model_validate(data)
except ValidationError as exc:
    click.echo(exc.errors()[0]["msg"])

There are two passes. First every item is checked against its model on its own; a bad item is reported with its index and field, and the second pass does not run, since a skipped item would show up as an unknown name. Then the whole estate is cross-checked: names exist and have the right kind, groups have no cycles, and so on. Cross-check problems have no index; their scope is global, the firewall or firewall/policy, and the message names the rule or group and the field.

Reading a file can fail too: yaml_file, json_file and file_source raise LoadError straight away for a parse error, an unknown section or an unsupported suffix, with the file path as resource.

Output#

== estate.yaml
global: 3 addresses, 2 fqdns, 3 services, 1 groups
firewall edge: own objects ['web-servers']; policies inbound (6 rules), outbound (4 rules)
== estate.yaml + branch.json
global: 3 addresses, 2 fqdns, 3 services, 1 groups
firewall edge: own objects ['web-servers']; policies inbound (6 rules), outbound (4 rules)
firewall branch: own objects ['branch-lan']; policies outbound (3 rules)
== a rule with a bad action
LoadError with 1 problem(s):
  edge/inbound/rules[0].action: Input should be 'accept' or 'deny'
    resource='rules' scope='edge/inbound' index=0 loc=('action',)
== a rule with unknown service names
LoadError with 2 problem(s):
  edge/inbound/inventory: rule 'allow-monitoring' services: unknown service name 'ntp'
    resource='inventory' scope='edge/inbound' index=None loc=()
  edge/inbound/inventory: rule 'allow-monitoring' services: unknown service name 'snmp'
    resource='inventory' scope='edge/inbound' index=None loc=()

The bad rule is rules[0] because it is the first item of its own resource, not the seventh rule of the policy.

Editing an inventory#

The models are frozen, and model_copy(update=...) skips validation, so a copy can hold a rule that names a service that does not exist. To change an inventory, dump it, edit the plain data and validate it again: Inventory.model_validate runs every cross-check that load does.

# Models are frozen and model_copy skips validation, so edit a dump and validate it again.
click.echo("== editing an inventory")
data = inventory.model_dump(mode="json")
rule = data["firewalls"][0]["policies"][0]["rules"][0]
rule["action"] = "accept"
edited = Inventory.model_validate(data)
before, after = (inv.firewalls[0].policies[0].rules[0] for inv in (inventory, edited))
click.echo(f"{after.name}: {before.action} -> {after.action}")

rule["services"] = ["ntp"]
try:
    Inventory.model_validate(data)
except ValidationError as exc:
    click.echo(exc.errors()[0]["msg"])
== editing an inventory
block-abusers: deny -> accept
Value error, firewall 'edge' policy 'inbound' rule 'block-abusers' services: unknown service name 'ntp'

What load does#

        sequenceDiagram
    participant You
    participant Pipeline
    participant Resource
    participant Inventory

    You->>Pipeline: load(source, ...)
    loop each resource of each source
        Pipeline->>Resource: extract()
        Resource-->>Pipeline: items + problems (schema, converters)
        Pipeline->>Pipeline: validate each item (Rule, AddressObject, ...)
    end
    alt any item problem
        Pipeline-->>You: raise LoadError(problems)
    else all items valid
        Pipeline->>Pipeline: merge by scope, in source order
        Pipeline->>Inventory: model_validate(estate)
        alt cross-check fails
            Inventory-->>Pipeline: ValidationError
            Pipeline-->>You: raise LoadError(one problem per line)
        else valid
            Inventory-->>Pipeline: inventory
            Pipeline-->>You: Inventory
        end
    end