pyinfra-cargowall-kit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ build/
5
+ dist/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ node_modules/
11
+ htmlcov/
12
+ .coverage
13
+
14
+ # Local caches
15
+ .uv-cache/
16
+ .prek-cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Simon Maillard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.5
2
+ Name: pyinfra-cargowall-kit
3
+ Version: 0.1.0
4
+ Summary: Reusable pyinfra helpers to manage the CargoWall eBPF egress firewall
5
+ Project-URL: Homepage, https://github.com/maisim/pyinfra-cargowall-kit
6
+ Project-URL: Repository, https://github.com/maisim/pyinfra-cargowall-kit
7
+ Project-URL: Issues, https://github.com/maisim/pyinfra-cargowall-kit/issues
8
+ Project-URL: Changelog, https://github.com/maisim/pyinfra-cargowall-kit/releases
9
+ Author-email: Simon Maillard <simon@ogesta.fr>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: cargowall,ebpf,egress,firewall,infrastructure-as-code,pyinfra
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: System Administrators
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: System :: Systems Administration
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: <4.0,>=3.11
27
+ Requires-Dist: pyinfra<4,>=3.11
28
+ Description-Content-Type: text/markdown
29
+
30
+ # pyinfra-cargowall-kit
31
+
32
+ > **⚠️ ALPHA RELEASE**: This project is currently in the **Alpha** stage. The API, operation arguments, and features are subject to change at any time without backward compatibility. Do not use in production environments.
33
+
34
+ > **Packaging status**: this repository is the source of truth and is public. Install the latest
35
+ > release from PyPI; while the project is alpha, pin the version you use.
36
+
37
+ [![CI](https://github.com/maisim/pyinfra-cargowall-kit/actions/workflows/python-publish.yml/badge.svg)](https://github.com/maisim/pyinfra-cargowall-kit/actions/workflows/python-publish.yml)
38
+ [![PyPI](https://img.shields.io/pypi/v/pyinfra-cargowall-kit)](https://pypi.org/project/pyinfra-cargowall-kit/)
39
+ [![Python versions](https://img.shields.io/pypi/pyversions/pyinfra-cargowall-kit)](https://pypi.org/project/pyinfra-cargowall-kit/)
40
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
41
+
42
+ Reusable [pyinfra](https://pyinfra.com/) operations and facts for managing
43
+ [CargoWall](https://github.com/code-cargo/cargowall), an eBPF-based network egress firewall, on
44
+ Linux hosts.
45
+
46
+ ## Requirements
47
+
48
+ **Target host:**
49
+
50
+ - Linux kernel 5.8 or newer. CargoWall uses a BPF ring buffer, which landed in 5.8; the TC attach
51
+ path falls back to the legacy `clsact` qdisc below 6.6.
52
+ - The `bpf` syscall (`CONFIG_BPF_SYSCALL`) and permission to load `SCHED_CLS` programs: root, or
53
+ `CAP_BPF` + `CAP_NET_ADMIN`.
54
+ - Kernel lockdown must be `none`; `integrity` and `confidentiality` block unauthenticated eBPF.
55
+ - `python3` for the eBPF probe, plus `curl`, `mktemp` and systemd.
56
+ - An `amd64` or `arm64` host; the matching release asset is downloaded automatically.
57
+
58
+ **Controller:** Python 3.11+ and `pyinfra` 3.11+.
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install pyinfra-cargowall-kit
64
+ uv add pyinfra-cargowall-kit
65
+ ```
66
+
67
+ ## Usage
68
+
69
+ The deploy helpers install the binary, write the config and start the service:
70
+
71
+ ```python
72
+ from pyinfra_cargowall_kit import configure, teardown
73
+
74
+ configure(
75
+ instance_name="myapp",
76
+ config={
77
+ "defaultAction": "deny",
78
+ "rules": [
79
+ {"type": "hostname", "value": "github.com", "action": "allow"},
80
+ {"type": "cidr", "value": "1.1.1.1/32", "action": "allow"},
81
+ ],
82
+ },
83
+ )
84
+
85
+ # Stop the service and remove the unit, config and binary
86
+ teardown(instance_name="myapp")
87
+ ```
88
+
89
+ The underlying operation accepts the same arguments plus the layout and lifecycle options:
90
+
91
+ ```python
92
+ from pyinfra_cargowall_kit import cargowall
93
+
94
+ cargowall(
95
+ instance_name="myapp",
96
+ config={"defaultAction": "deny", "rules": []},
97
+ version="v1.3.0",
98
+ audit_mode=False,
99
+ dns_upstream="1.1.1.1:53",
100
+ binary_path="/usr/local/bin/cargowall",
101
+ ebpf_preflight=True,
102
+ arch=None,
103
+ )
104
+ ```
105
+
106
+ | Argument | Default | Description |
107
+ |---|---|---|
108
+ | `instance_name` | required | Unit and config name; letters, digits, `.`, `_` and `-` only |
109
+ | `config` | required | CargoWall config (`defaultAction`, `rules`) |
110
+ | `version` | `v1.3.0` | Release tag; compared in canonical `vX.Y.Z` form |
111
+ | `binary_path` | `/usr/local/bin/cargowall` | Where the binary is installed |
112
+ | `audit_mode` | `False` | Add `--audit-mode --audit-log` to the service |
113
+ | `dns_upstream` | `1.1.1.1:53` | Upstream DNS used by the proxy |
114
+ | `present` | `True` | `False` stops the service and removes the unit, config and binary |
115
+ | `ebpf_preflight` | `True` | Probe eBPF before staging anything |
116
+ | `arch` | host architecture | Force `amd64` or `arm64` |
117
+
118
+ The operation is idempotent: the installed version is read through `cargowall --version`, the
119
+ config is written through pyinfra's checksummed `files.put`, and the service is only restarted when
120
+ its unit changes.
121
+
122
+ ## eBPF preflight
123
+
124
+ Before staging an install, the operation mirrors CargoWall's own `pkg/ebpf/detect.go`: it checks
125
+ the kernel version, the `bpf` syscall and the ability to load a minimal `SCHED_CLS` program, and it
126
+ parses the active kernel lockdown mode. A definitive refusal raises `OperationError` with the
127
+ reason (kernel too old, `ENOSYS`, `EPERM`/`EACCES`, lockdown) and changes nothing on the host.
128
+
129
+ An inconclusive probe (missing `python3`, unsupported architecture, `EINVAL`) only emits a noop
130
+ warning and continues. Set `ebpf_preflight=False` to skip the probe entirely. The probe proves the
131
+ program-load path, not TC attach or map creation beyond the kernel floor.
132
+
133
+ ## Facts
134
+
135
+ | Fact | Returns |
136
+ |---|---|
137
+ | `CargoWallVersion` | Installed release as `vX.Y.Z`, or `None` |
138
+ | `CargoWallRunning` | `True` when `cargowall@<instance>.service` is active |
139
+ | `CargoWallConfigHash` | The config file's MD5, or `None` |
140
+ | `EbpfAvailable` | Diagnostics dict: `kernel_version`, `kernel_supported`, `bpf_syscall`, `can_create_programs`, `blocked`, `lockdown`, `unprivileged_bpf_disabled`, `arch`, `probe`, `errno`, `detail` |
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ git clone https://github.com/maisim/pyinfra-cargowall-kit.git
146
+ cd pyinfra-cargowall-kit
147
+ uv sync --group dev
148
+ uv run pytest -q
149
+ uv run prek run --all-files
150
+ ```
151
+
152
+ The CI runs the same checks on Python 3.11 through 3.14, then builds and checks the distributions.
153
+
154
+ ## License
155
+
156
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,127 @@
1
+ # pyinfra-cargowall-kit
2
+
3
+ > **⚠️ ALPHA RELEASE**: This project is currently in the **Alpha** stage. The API, operation arguments, and features are subject to change at any time without backward compatibility. Do not use in production environments.
4
+
5
+ > **Packaging status**: this repository is the source of truth and is public. Install the latest
6
+ > release from PyPI; while the project is alpha, pin the version you use.
7
+
8
+ [![CI](https://github.com/maisim/pyinfra-cargowall-kit/actions/workflows/python-publish.yml/badge.svg)](https://github.com/maisim/pyinfra-cargowall-kit/actions/workflows/python-publish.yml)
9
+ [![PyPI](https://img.shields.io/pypi/v/pyinfra-cargowall-kit)](https://pypi.org/project/pyinfra-cargowall-kit/)
10
+ [![Python versions](https://img.shields.io/pypi/pyversions/pyinfra-cargowall-kit)](https://pypi.org/project/pyinfra-cargowall-kit/)
11
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
12
+
13
+ Reusable [pyinfra](https://pyinfra.com/) operations and facts for managing
14
+ [CargoWall](https://github.com/code-cargo/cargowall), an eBPF-based network egress firewall, on
15
+ Linux hosts.
16
+
17
+ ## Requirements
18
+
19
+ **Target host:**
20
+
21
+ - Linux kernel 5.8 or newer. CargoWall uses a BPF ring buffer, which landed in 5.8; the TC attach
22
+ path falls back to the legacy `clsact` qdisc below 6.6.
23
+ - The `bpf` syscall (`CONFIG_BPF_SYSCALL`) and permission to load `SCHED_CLS` programs: root, or
24
+ `CAP_BPF` + `CAP_NET_ADMIN`.
25
+ - Kernel lockdown must be `none`; `integrity` and `confidentiality` block unauthenticated eBPF.
26
+ - `python3` for the eBPF probe, plus `curl`, `mktemp` and systemd.
27
+ - An `amd64` or `arm64` host; the matching release asset is downloaded automatically.
28
+
29
+ **Controller:** Python 3.11+ and `pyinfra` 3.11+.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install pyinfra-cargowall-kit
35
+ uv add pyinfra-cargowall-kit
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ The deploy helpers install the binary, write the config and start the service:
41
+
42
+ ```python
43
+ from pyinfra_cargowall_kit import configure, teardown
44
+
45
+ configure(
46
+ instance_name="myapp",
47
+ config={
48
+ "defaultAction": "deny",
49
+ "rules": [
50
+ {"type": "hostname", "value": "github.com", "action": "allow"},
51
+ {"type": "cidr", "value": "1.1.1.1/32", "action": "allow"},
52
+ ],
53
+ },
54
+ )
55
+
56
+ # Stop the service and remove the unit, config and binary
57
+ teardown(instance_name="myapp")
58
+ ```
59
+
60
+ The underlying operation accepts the same arguments plus the layout and lifecycle options:
61
+
62
+ ```python
63
+ from pyinfra_cargowall_kit import cargowall
64
+
65
+ cargowall(
66
+ instance_name="myapp",
67
+ config={"defaultAction": "deny", "rules": []},
68
+ version="v1.3.0",
69
+ audit_mode=False,
70
+ dns_upstream="1.1.1.1:53",
71
+ binary_path="/usr/local/bin/cargowall",
72
+ ebpf_preflight=True,
73
+ arch=None,
74
+ )
75
+ ```
76
+
77
+ | Argument | Default | Description |
78
+ |---|---|---|
79
+ | `instance_name` | required | Unit and config name; letters, digits, `.`, `_` and `-` only |
80
+ | `config` | required | CargoWall config (`defaultAction`, `rules`) |
81
+ | `version` | `v1.3.0` | Release tag; compared in canonical `vX.Y.Z` form |
82
+ | `binary_path` | `/usr/local/bin/cargowall` | Where the binary is installed |
83
+ | `audit_mode` | `False` | Add `--audit-mode --audit-log` to the service |
84
+ | `dns_upstream` | `1.1.1.1:53` | Upstream DNS used by the proxy |
85
+ | `present` | `True` | `False` stops the service and removes the unit, config and binary |
86
+ | `ebpf_preflight` | `True` | Probe eBPF before staging anything |
87
+ | `arch` | host architecture | Force `amd64` or `arm64` |
88
+
89
+ The operation is idempotent: the installed version is read through `cargowall --version`, the
90
+ config is written through pyinfra's checksummed `files.put`, and the service is only restarted when
91
+ its unit changes.
92
+
93
+ ## eBPF preflight
94
+
95
+ Before staging an install, the operation mirrors CargoWall's own `pkg/ebpf/detect.go`: it checks
96
+ the kernel version, the `bpf` syscall and the ability to load a minimal `SCHED_CLS` program, and it
97
+ parses the active kernel lockdown mode. A definitive refusal raises `OperationError` with the
98
+ reason (kernel too old, `ENOSYS`, `EPERM`/`EACCES`, lockdown) and changes nothing on the host.
99
+
100
+ An inconclusive probe (missing `python3`, unsupported architecture, `EINVAL`) only emits a noop
101
+ warning and continues. Set `ebpf_preflight=False` to skip the probe entirely. The probe proves the
102
+ program-load path, not TC attach or map creation beyond the kernel floor.
103
+
104
+ ## Facts
105
+
106
+ | Fact | Returns |
107
+ |---|---|
108
+ | `CargoWallVersion` | Installed release as `vX.Y.Z`, or `None` |
109
+ | `CargoWallRunning` | `True` when `cargowall@<instance>.service` is active |
110
+ | `CargoWallConfigHash` | The config file's MD5, or `None` |
111
+ | `EbpfAvailable` | Diagnostics dict: `kernel_version`, `kernel_supported`, `bpf_syscall`, `can_create_programs`, `blocked`, `lockdown`, `unprivileged_bpf_disabled`, `arch`, `probe`, `errno`, `detail` |
112
+
113
+ ## Development
114
+
115
+ ```bash
116
+ git clone https://github.com/maisim/pyinfra-cargowall-kit.git
117
+ cd pyinfra-cargowall-kit
118
+ uv sync --group dev
119
+ uv run pytest -q
120
+ uv run prek run --all-files
121
+ ```
122
+
123
+ The CI runs the same checks on Python 3.11 through 3.14, then builds and checks the distributions.
124
+
125
+ ## License
126
+
127
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "pyinfra-cargowall-kit"
3
+ version = "0.1.0"
4
+ description = "Reusable pyinfra helpers to manage the CargoWall eBPF egress firewall"
5
+ authors = [
6
+ { name = "Simon Maillard", email = "simon@ogesta.fr" }
7
+ ]
8
+ license = { text = "MIT" }
9
+ keywords = [
10
+ "pyinfra",
11
+ "cargowall",
12
+ "ebpf",
13
+ "firewall",
14
+ "egress",
15
+ "infrastructure-as-code",
16
+ ]
17
+ classifiers = [
18
+ "Development Status :: 3 - Alpha",
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: System Administrators",
22
+ "License :: OSI Approved :: MIT License",
23
+ "Operating System :: POSIX :: Linux",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Topic :: System :: Systems Administration",
30
+ "Typing :: Typed",
31
+ ]
32
+ dependencies = [
33
+ "pyinfra>=3.11,<4",
34
+ ]
35
+ readme = "README.md"
36
+ requires-python = ">=3.11,<4.0"
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/maisim/pyinfra-cargowall-kit"
40
+ Repository = "https://github.com/maisim/pyinfra-cargowall-kit"
41
+ Issues = "https://github.com/maisim/pyinfra-cargowall-kit/issues"
42
+ Changelog = "https://github.com/maisim/pyinfra-cargowall-kit/releases"
43
+
44
+ [build-system]
45
+ requires = ["hatchling"]
46
+ build-backend = "hatchling.build"
47
+
48
+ [tool.hatch.build.targets.wheel]
49
+ packages = ["src/pyinfra_cargowall_kit"]
50
+
51
+ [tool.hatch.build.targets.sdist]
52
+ include = ["src/pyinfra_cargowall_kit", "README.md", "pyproject.toml", "LICENSE"]
53
+
54
+ [dependency-groups]
55
+ dev = [
56
+ "coverage>=7.16.2",
57
+ "detect-secrets>=1.4.0",
58
+ "docformatter==1.7.8",
59
+ "mypy>=2.3.1",
60
+ "prek>=0.5.4",
61
+ "pytest>=9.1.1",
62
+ "pytest-cov>=7.1.0",
63
+ "ruff>=0.16.9",
64
+ ]
65
+
66
+ [tool.pytest.ini_options]
67
+ testpaths = ["tests"]
68
+
69
+ [tool.coverage.run]
70
+ branch = true
71
+ omit = ["*/tests/*"]
72
+
73
+ [tool.ruff]
74
+ line-length = 100
75
+ target-version = "py311"
76
+
77
+ [tool.ruff.lint]
78
+ select = ["E", "F", "W", "I", "N"]
79
+
80
+ [tool.mypy]
81
+ python_version = "3.11"
82
+ ignore_missing_imports = true
83
+ check_untyped_defs = true
@@ -0,0 +1,34 @@
1
+ """
2
+ Pyinfra-cargowall-kit — reusable pyinfra operations and facts for CargoWall egress
3
+ firewall.
4
+
5
+ CargoWall is an eBPF-based network egress firewall that filters outbound
6
+ traffic at the kernel level using a DNS proxy + TC eBPF program.
7
+
8
+ This package provides:
9
+ - :func:`cargowall` operation — declarative install/config/start/stop
10
+ - :class:`CargoWallVersion`, :class:`CargoWallRunning`, :class:`CargoWallConfigHash` and
11
+ :class:`EbpfAvailable` facts
12
+ - :func:`configure` / :func:`teardown` deploy scripts
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from pyinfra_cargowall_kit.deploy import configure, teardown
18
+ from pyinfra_cargowall_kit.facts import (
19
+ CargoWallConfigHash,
20
+ CargoWallRunning,
21
+ CargoWallVersion,
22
+ EbpfAvailable,
23
+ )
24
+ from pyinfra_cargowall_kit.operations import cargowall
25
+
26
+ __all__ = [
27
+ "CargoWallConfigHash",
28
+ "CargoWallRunning",
29
+ "CargoWallVersion",
30
+ "EbpfAvailable",
31
+ "cargowall",
32
+ "configure",
33
+ "teardown",
34
+ ]
@@ -0,0 +1,52 @@
1
+ """
2
+ CargoWall deploy scripts.
3
+
4
+ These are importable from pyinfra deploy files (``pyinfra -y deploy.py``) or called
5
+ programmatically from odoo-foundry recipes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pyinfra_cargowall_kit.operations import cargowall
11
+
12
+
13
+ def configure(
14
+ instance_name: str,
15
+ config: dict,
16
+ version: str = "v1.3.0",
17
+ *,
18
+ audit_mode: bool = False,
19
+ dns_upstream: str = "1.1.1.1:53",
20
+ ) -> None:
21
+ """
22
+ Deploy script: install CargoWall, write config, start service.
23
+
24
+ Usage in a pyinfra deploy file::
25
+
26
+ from pyinfra_cargowall_kit.deploy import configure
27
+ configure(instance_name="myapp", config={"defaultAction": "deny", "rules": [...]})
28
+ """
29
+ cargowall(
30
+ instance_name=instance_name,
31
+ config=config,
32
+ version=version,
33
+ audit_mode=audit_mode,
34
+ dns_upstream=dns_upstream,
35
+ present=True,
36
+ )
37
+
38
+
39
+ def teardown(instance_name: str) -> None:
40
+ """
41
+ Deploy script: stop CargoWall service and remove all files.
42
+
43
+ Usage in a pyinfra deploy file::
44
+
45
+ from pyinfra_cargowall_kit.deploy import teardown
46
+ teardown(instance_name="myapp")
47
+ """
48
+ cargowall(
49
+ instance_name=instance_name,
50
+ config={},
51
+ present=False,
52
+ )
@@ -0,0 +1,347 @@
1
+ """
2
+ CargoWall facts for pyinfra.
3
+
4
+ Facts query the remote host state and return typed results that pyinfra operations can use
5
+ for idempotency checks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ import shlex
13
+ from collections.abc import Iterable
14
+
15
+ from pyinfra.api import FactBase
16
+
17
+ # ``cargowall --version`` prints the release, and older banners prefix it with the binary name
18
+ # (``cargowall v1.3.0``). Normalising to the tag form lets the operation compare values that
19
+ # differ only by the leading ``v`` or by a prefix.
20
+ _VERSION_RE = re.compile(r"(?<![\w.])v?(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)(?![\w.])")
21
+
22
+
23
+ def normalize_cargowall_version(value: str | None) -> str | None:
24
+ """
25
+ Return ``vX.Y.Z`` for a version banner, or ``None`` when no version is present.
26
+
27
+ + value: raw output such as ``"cargowall v1.3.0"``, ``"1.3.0"`` or ``"v1.3.0-rc.1"``
28
+ """
29
+ if not value:
30
+ return None
31
+ match = _VERSION_RE.search(value)
32
+ if match is None:
33
+ return None
34
+ return f"v{match.group(1)}"
35
+
36
+
37
+ class CargoWallVersion(FactBase):
38
+ """
39
+ Return the installed CargoWall version string (e.g. ``"v1.3.0"``), or ``None`` when
40
+ the binary is absent.
41
+ """
42
+
43
+ default = staticmethod(lambda: None)
44
+
45
+ def command(
46
+ self,
47
+ binary_path: str = "/usr/local/bin/cargowall",
48
+ ) -> str:
49
+ quoted = shlex.quote(binary_path)
50
+ return (
51
+ f"if [ -x {quoted} ]; then "
52
+ f"{quoted} --version 2>/dev/null || echo absent; "
53
+ "else echo absent; fi"
54
+ )
55
+
56
+ def process(self, output: Iterable[str]) -> str | None:
57
+ rendered = "".join(output).strip()
58
+ if not rendered or rendered == "absent":
59
+ return None
60
+ return normalize_cargowall_version(rendered)
61
+
62
+
63
+ class CargoWallRunning(FactBase):
64
+ """
65
+ Return ``True`` when the CargoWall systemd service is active.
66
+ """
67
+
68
+ default = staticmethod(lambda: False)
69
+
70
+ def command(self, service_name: str) -> str:
71
+ quoted = shlex.quote(f"cargowall@{service_name}.service")
72
+ return f"systemctl is-active --quiet {quoted} && echo running || echo stopped"
73
+
74
+ def process(self, output: Iterable[str]) -> bool:
75
+ return "".join(output).strip() == "running"
76
+
77
+
78
+ # The syscall number is architecture-specific. CargoWall publishes amd64 and arm64 binaries; the
79
+ # other entries keep the probe honest on hosts where it can still run.
80
+ _NR_BPF_BY_ARCH = {
81
+ "x86_64": 321,
82
+ "amd64": 321,
83
+ "aarch64": 280,
84
+ "arm64": 280,
85
+ "riscv64": 280,
86
+ "loongarch64": 280,
87
+ "i386": 357,
88
+ "i486": 357,
89
+ "i586": 357,
90
+ "i686": 357,
91
+ "armv6l": 386,
92
+ "armv7l": 386,
93
+ "armv8l": 386,
94
+ "ppc64": 361,
95
+ "ppc64le": 361,
96
+ "s390x": 351,
97
+ }
98
+
99
+ _EBPF_DEFAULT: dict = {
100
+ "kernel_version": None,
101
+ "kernel_supported": False,
102
+ "bpf_syscall": False,
103
+ "can_create_programs": False,
104
+ "blocked": False,
105
+ "lockdown": None,
106
+ "unprivileged_bpf_disabled": None,
107
+ "arch": None,
108
+ "probe": "not_run",
109
+ "errno": None,
110
+ "detail": None,
111
+ }
112
+
113
+ # Mirrors CargoWall's own pkg/ebpf/detect.go: the ring buffer requires kernel 5.8, the bpf syscall
114
+ # must exist, and loading a minimal SCHED_CLS program proves the CAP_BPF/CAP_NET_ADMIN path. A
115
+ # probe that cannot answer (missing python3, unsupported arch, EINVAL) is inconclusive, not a
116
+ # denial; only a definitive refusal sets ``blocked``.
117
+ _EBPF_PROBE_SCRIPT = r"""
118
+ import ctypes
119
+ import errno as errno_module
120
+ import json
121
+ import os
122
+ import platform
123
+ import re
124
+ import struct
125
+ import sys
126
+
127
+ BPF_PROG_LOAD = 5
128
+ BPF_PROG_GET_FD_BY_ID = 23
129
+ BPF_PROG_TYPE_SCHED_CLS = 3
130
+ BPF_MOV64_IMM = 0xB7
131
+ BPF_EXIT = 0x95
132
+
133
+ NR_BPF = __NR_BPF_BY_ARCH__
134
+
135
+ result = {
136
+ "kernel_version": platform.release(),
137
+ "kernel_supported": False,
138
+ "bpf_syscall": False,
139
+ "can_create_programs": False,
140
+ "blocked": False,
141
+ "lockdown": None,
142
+ "unprivileged_bpf_disabled": None,
143
+ "arch": platform.machine().lower(),
144
+ "probe": "error",
145
+ "errno": None,
146
+ "detail": None,
147
+ }
148
+
149
+
150
+ def finish(probe, errno_name=None, detail=None, blocked=False):
151
+ result["probe"] = probe
152
+ result["errno"] = errno_name
153
+ result["detail"] = detail
154
+ result["blocked"] = blocked
155
+ print(json.dumps(result))
156
+ sys.exit(0)
157
+
158
+
159
+ def kernel_at_least(release, major, minor):
160
+ match = re.match(r"(\d+)\.(\d+)", release)
161
+ if not match:
162
+ return False
163
+ return (int(match.group(1)), int(match.group(2))) >= (major, minor)
164
+
165
+
166
+ def lockdown_mode():
167
+ try:
168
+ with open("/sys/kernel/security/lockdown") as handle:
169
+ raw = handle.read().strip()
170
+ except OSError:
171
+ return None
172
+ for token in raw.split():
173
+ if token.startswith("[") and token.endswith("]"):
174
+ return token[1:-1]
175
+ return "none" if "none" in raw.split() else raw or None
176
+
177
+
178
+ def unprivileged_bpf_disabled():
179
+ try:
180
+ with open("/proc/sys/kernel/unprivileged_bpf_disabled") as handle:
181
+ return int(handle.read().strip())
182
+ except (OSError, ValueError):
183
+ return None
184
+
185
+
186
+ result["lockdown"] = lockdown_mode()
187
+ result["unprivileged_bpf_disabled"] = unprivileged_bpf_disabled()
188
+ result["kernel_supported"] = kernel_at_least(result["kernel_version"], 5, 8)
189
+
190
+ nr = NR_BPF.get(result["arch"])
191
+ if nr is None:
192
+ finish("unsupported_arch", detail="no __NR_bpf for architecture " + result["arch"])
193
+
194
+ libc = ctypes.CDLL(None, use_errno=True)
195
+ libc.syscall.restype = ctypes.c_long
196
+
197
+ # A known-invalid request: ENOENT/EINVAL proves the syscall exists, ENOSYS means it does not.
198
+ ctypes.set_errno(0)
199
+ libc.syscall(nr, BPF_PROG_GET_FD_BY_ID, 0, 0)
200
+ syscall_errno = ctypes.get_errno()
201
+ result["bpf_syscall"] = syscall_errno != errno_module.ENOSYS
202
+ if not result["bpf_syscall"]:
203
+ finish("enosys", errno_name="ENOSYS", detail="the bpf syscall is unavailable", blocked=True)
204
+
205
+ # A minimal SCHED_CLS program: r0 = 0; exit.
206
+ insns = (ctypes.c_ubyte * 16)()
207
+ insns[0] = BPF_MOV64_IMM
208
+ insns[8] = BPF_EXIT
209
+ license_buffer = ctypes.create_string_buffer(b"GPL")
210
+ attr = ctypes.create_string_buffer(72)
211
+ struct.pack_into(
212
+ "=IIQQIIQII16sII",
213
+ attr,
214
+ 0,
215
+ BPF_PROG_TYPE_SCHED_CLS,
216
+ 2,
217
+ ctypes.addressof(insns),
218
+ ctypes.addressof(license_buffer),
219
+ 0,
220
+ 0,
221
+ 0,
222
+ 0,
223
+ 0,
224
+ b"",
225
+ 0,
226
+ 0,
227
+ )
228
+
229
+ ctypes.set_errno(0)
230
+ fd = libc.syscall(nr, BPF_PROG_LOAD, ctypes.byref(attr), ctypes.sizeof(attr))
231
+ load_errno = ctypes.get_errno()
232
+ if fd >= 0:
233
+ os.close(fd)
234
+ result["can_create_programs"] = True
235
+
236
+ if not result["kernel_supported"]:
237
+ finish(
238
+ "unsupported_kernel",
239
+ detail="kernel " + result["kernel_version"] + " is below the 5.8 ring-buffer floor",
240
+ blocked=True,
241
+ )
242
+
243
+ if fd >= 0:
244
+ finish("ok")
245
+
246
+ errno_name = errno_module.errorcode.get(load_errno, str(load_errno))
247
+ if load_errno in (errno_module.EPERM, errno_module.EACCES):
248
+ detail = "cannot load a SCHED_CLS program: " + errno_name
249
+ if result["lockdown"] in ("integrity", "confidentiality"):
250
+ detail += " (kernel lockdown is " + result["lockdown"] + ")"
251
+ probe = "eperm" if load_errno == errno_module.EPERM else "eacces"
252
+ finish(probe, errno_name=errno_name, detail=detail, blocked=True)
253
+ if load_errno == errno_module.ENOSYS:
254
+ finish("enosys", errno_name=errno_name, detail="the bpf syscall is unavailable", blocked=True)
255
+ if load_errno == errno_module.EINVAL:
256
+ finish(
257
+ "einval",
258
+ errno_name=errno_name,
259
+ detail="the probe program was rejected; eBPF support is inconclusive",
260
+ )
261
+ finish("error", errno_name=errno_name, detail="unexpected bpf() failure")
262
+ """
263
+
264
+
265
+ class EbpfAvailable(FactBase):
266
+ """
267
+ Return a dict describing eBPF availability on the host.
268
+
269
+ The probe mirrors CargoWall's own detection: kernel 5.8 or newer (the ring-buffer
270
+ floor), the bpf syscall, and loading a minimal SCHED_CLS program. Keys:
271
+ ``kernel_version``, ``kernel_supported``, ``bpf_syscall``, ``can_create_programs``,
272
+ ``blocked``, ``lockdown``, ``unprivileged_bpf_disabled``, ``arch``, ``probe``,
273
+ ``errno`` and ``detail``.
274
+
275
+ ``blocked`` is true only for a definitive refusal (kernel too old, ENOSYS,
276
+ EPERM/EACCES, or an active lockdown with the program load unproven). An inconclusive
277
+ probe (missing python3, unsupported architecture, EINVAL) leaves ``blocked`` false and
278
+ explains itself in ``probe`` and ``detail``.
279
+ """
280
+
281
+ default = staticmethod(lambda: dict(_EBPF_DEFAULT))
282
+
283
+ def command(self) -> str:
284
+ script = _EBPF_PROBE_SCRIPT.replace("__NR_BPF_BY_ARCH__", repr(_NR_BPF_BY_ARCH))
285
+ quoted = shlex.quote(script)
286
+ missing = shlex.quote(json.dumps({"probe": "python_missing"}))
287
+ return (
288
+ "if command -v python3 >/dev/null 2>&1; "
289
+ f"then python3 -c {quoted}; "
290
+ f"else echo {missing}; fi"
291
+ )
292
+
293
+ def process(self, output: Iterable[str]) -> dict:
294
+ rendered = "".join(output).strip()
295
+ result = dict(_EBPF_DEFAULT)
296
+ if not rendered:
297
+ result["probe"] = "invalid_output"
298
+ return result
299
+ payload = None
300
+ for line in reversed(rendered.splitlines()):
301
+ try:
302
+ candidate = json.loads(line)
303
+ except json.JSONDecodeError:
304
+ continue
305
+ if isinstance(candidate, dict):
306
+ payload = candidate
307
+ break
308
+ if payload is None:
309
+ result["probe"] = "invalid_output"
310
+ return result
311
+ for key in ("kernel_version", "arch", "probe", "errno", "detail"):
312
+ value = payload.get(key)
313
+ if isinstance(value, str) or value is None:
314
+ result[key] = value
315
+ for key in ("kernel_supported", "bpf_syscall", "can_create_programs", "blocked"):
316
+ result[key] = bool(payload.get(key, False))
317
+ lockdown = payload.get("lockdown")
318
+ result["lockdown"] = lockdown if isinstance(lockdown, str) or lockdown is None else None
319
+ disabled = payload.get("unprivileged_bpf_disabled")
320
+ result["unprivileged_bpf_disabled"] = disabled if isinstance(disabled, int) else None
321
+ if not result["probe"]:
322
+ result["probe"] = "error"
323
+ return result
324
+
325
+
326
+ class CargoWallConfigHash(FactBase):
327
+ """
328
+ Return the MD5 hash of the current CargoWall config file, or ``None`` if absent.
329
+
330
+ Used to decide whether the config needs to be rewritten.
331
+ """
332
+
333
+ default = staticmethod(lambda: None)
334
+
335
+ def command(self, config_name: str) -> str:
336
+ config_path = shlex.quote(f"/etc/cargowall/{config_name}.json")
337
+ return (
338
+ f"if [ -f {config_path} ]; then "
339
+ f"md5sum {config_path} | cut -d' ' -f1; "
340
+ "else echo absent; fi"
341
+ )
342
+
343
+ def process(self, output: Iterable[str]) -> str | None:
344
+ rendered = "".join(output).strip()
345
+ if not rendered or rendered == "absent":
346
+ return None
347
+ return rendered
@@ -0,0 +1,360 @@
1
+ """
2
+ CargoWall pyinfra operations and deploy scripts.
3
+
4
+ Declarative, idempotent: install binary, write config, manage systemd service.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import shlex
12
+ from io import StringIO
13
+
14
+ from pyinfra import host
15
+ from pyinfra.api import deploy
16
+ from pyinfra.api.exceptions import OperationError
17
+ from pyinfra.facts.server import Arch
18
+ from pyinfra.operations import files, server, systemd
19
+
20
+ from pyinfra_cargowall_kit.facts import (
21
+ CargoWallRunning,
22
+ CargoWallVersion,
23
+ EbpfAvailable,
24
+ normalize_cargowall_version,
25
+ )
26
+
27
+ DEFAULT_BINARY_PATH = "/usr/local/bin/cargowall"
28
+ DEFAULT_CONFIG_DIR = "/etc/cargowall"
29
+ DEFAULT_DNS_UPSTREAM = "1.1.1.1:53"
30
+ DEFAULT_VERSION = "v1.3.0"
31
+
32
+ _INSTANCE_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
33
+ _DOWNLOAD_ARCH = {
34
+ "x86_64": "amd64",
35
+ "amd64": "amd64",
36
+ "aarch64": "arm64",
37
+ "arm64": "arm64",
38
+ }
39
+
40
+
41
+ def _validate_instance_name(instance_name: str) -> str:
42
+ """
43
+ Reject names that would produce an invalid systemd unit, config path or pidfile.
44
+ """
45
+ if not _INSTANCE_NAME_RE.fullmatch(instance_name):
46
+ raise ValueError(
47
+ f"invalid CargoWall instance name {instance_name!r}: use letters, digits, '.', '_' or "
48
+ "'-' (1-64 characters, starting with a letter or digit)"
49
+ )
50
+ return instance_name
51
+
52
+
53
+ def _validate_path(path: str, *, label: str) -> str:
54
+ """
55
+ Reject paths that systemd or the shell cannot represent safely.
56
+ """
57
+ if not path.startswith("/") or any(char in path for char in "\n\r\0"):
58
+ raise ValueError(f"{label} must be an absolute path without control characters: {path!r}")
59
+ return path
60
+
61
+
62
+ def _quote_systemd_arg(value: str) -> str:
63
+ """
64
+ Quote one ExecStart/ExecStop argument for systemd.
65
+
66
+ ``%`` and ``$`` are expanded even inside quotes, so both are escaped, and a literal
67
+ backslash or double quote needs its own escape.
68
+ """
69
+ if any(char in value for char in "\n\r\0"):
70
+ raise ValueError(f"systemd arguments cannot contain control characters: {value!r}")
71
+ escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%").replace("$", "$$")
72
+ return f'"{escaped}"'
73
+
74
+
75
+ def _unit_name(instance_name: str) -> str:
76
+ """
77
+ Return the systemd unit name for an already validated instance name.
78
+ """
79
+ return f"cargowall@{instance_name}.service"
80
+
81
+
82
+ def _download_arch(host_arch: str) -> str:
83
+ """
84
+ Map a host architecture to the asset name used by CargoWall releases.
85
+ """
86
+ arch = _DOWNLOAD_ARCH.get(host_arch.lower())
87
+ if arch is None:
88
+ raise OperationError(
89
+ f"CargoWall has no prebuilt binary for architecture {host_arch!r} "
90
+ "(supported: x86_64/amd64, aarch64/arm64)"
91
+ )
92
+ return arch
93
+
94
+
95
+ def _build_install_script(
96
+ *, version: str, binary_path: str = DEFAULT_BINARY_PATH, arch: str = "amd64"
97
+ ) -> str:
98
+ """
99
+ Return a shell script that downloads and installs the CargoWall binary.
100
+ """
101
+ canonical = normalize_cargowall_version(version)
102
+ if canonical is None:
103
+ raise ValueError(f"invalid CargoWall version {version!r}: expected a tag like 'v1.3.0'")
104
+ if arch not in {"amd64", "arm64"}:
105
+ raise ValueError(f"unsupported CargoWall binary architecture {arch!r}")
106
+ binary = _validate_path(binary_path, label="binary_path")
107
+ url = (
108
+ "https://github.com/code-cargo/cargowall/releases/download/"
109
+ f"{canonical}/cargowall-linux-{arch}"
110
+ )
111
+ return f"""
112
+ set -eu
113
+ tmp="$(mktemp)"
114
+ trap 'rm -f "$tmp"' EXIT
115
+ curl -fsSL -o "$tmp" {shlex.quote(url)}
116
+ install -m 0755 "$tmp" {shlex.quote(binary)}
117
+ """
118
+
119
+
120
+ def _build_config_json(config: dict) -> str:
121
+ """
122
+ Serialize the CargoWall config dict to a deterministic JSON string.
123
+ """
124
+ return json.dumps(config, sort_keys=True, indent=2)
125
+
126
+
127
+ def _build_systemd_unit(
128
+ instance_name: str,
129
+ *,
130
+ audit_mode: bool = False,
131
+ dns_upstream: str = DEFAULT_DNS_UPSTREAM,
132
+ binary_path: str = DEFAULT_BINARY_PATH,
133
+ ) -> str:
134
+ """
135
+ Return the content of a systemd service unit for CargoWall.
136
+ """
137
+ name = _validate_instance_name(instance_name)
138
+ binary = _validate_path(binary_path, label="binary_path")
139
+ if not dns_upstream or any(char in dns_upstream for char in "\n\r\0"):
140
+ raise ValueError(f"invalid dns_upstream {dns_upstream!r}")
141
+ config_path = f"{DEFAULT_CONFIG_DIR}/{name}.json"
142
+ pidfile = f"/run/cargowall-{name}.pid"
143
+ exec_start = [
144
+ binary,
145
+ "start",
146
+ "--config",
147
+ config_path,
148
+ "--dns-upstream",
149
+ dns_upstream,
150
+ "--pidfile",
151
+ pidfile,
152
+ ]
153
+ if audit_mode:
154
+ exec_start.extend(["--audit-mode", "--audit-log", f"/var/log/cargowall/{name}.ndjson"])
155
+ exec_stop = [binary, "stop", "--pidfile", pidfile]
156
+ return (
157
+ "[Unit]\n"
158
+ f"Description=CargoWall egress firewall ({name})\n"
159
+ "After=network-online.target\n"
160
+ "Wants=network-online.target\n"
161
+ "\n"
162
+ "[Service]\n"
163
+ "Type=forking\n"
164
+ "ExecStart=" + " ".join(_quote_systemd_arg(argument) for argument in exec_start) + "\n"
165
+ "ExecStop=" + " ".join(_quote_systemd_arg(argument) for argument in exec_stop) + "\n"
166
+ f"PIDFile={pidfile}\n"
167
+ "Restart=on-failure\n"
168
+ "RestartSec=5\n"
169
+ "\n"
170
+ "[Install]\n"
171
+ "WantedBy=multi-user.target\n"
172
+ )
173
+
174
+
175
+ def _ebpf_blocked_message(ebpf: dict) -> str:
176
+ """
177
+ Build an actionable error for a definitive eBPF refusal.
178
+ """
179
+ probe = ebpf.get("probe") or "unknown"
180
+ lockdown = ebpf.get("lockdown")
181
+ kernel = ebpf.get("kernel_version") or "unknown"
182
+ arch = ebpf.get("arch") or "unknown"
183
+ errno_name = ebpf.get("errno") or "unknown"
184
+ reasons = {
185
+ "unsupported_kernel": f"kernel {kernel} is below the 5.8 ring-buffer floor",
186
+ "enosys": "the kernel has no bpf syscall (CONFIG_BPF_SYSCALL off, or seccomp blocks it)",
187
+ "eperm": "loading the probe program was denied; run as root with CAP_BPF and CAP_NET_ADMIN",
188
+ "eacces": "loading the probe program was denied; CAP_BPF and CAP_NET_ADMIN are required",
189
+ }
190
+ reason = reasons.get(probe, "eBPF program loading failed")
191
+ message = (
192
+ f"CargoWall cannot load eBPF programs on this host: {reason} "
193
+ f"(probe={probe}, errno={errno_name}, kernel={kernel}, arch={arch}, "
194
+ f"lockdown={lockdown!r}). Nothing on the host was changed. "
195
+ "Check with `bpftool feature probe`, or set ebpf_preflight=False to skip this check."
196
+ )
197
+ if lockdown in ("integrity", "confidentiality"):
198
+ message += f" The kernel is in {lockdown} lockdown; boot with lockdown=none to allow eBPF."
199
+ return message
200
+
201
+
202
+ @deploy("Ensure CargoWall egress firewall")
203
+ def cargowall(
204
+ instance_name: str,
205
+ config: dict,
206
+ version: str = DEFAULT_VERSION,
207
+ *,
208
+ binary_path: str = DEFAULT_BINARY_PATH,
209
+ audit_mode: bool = False,
210
+ dns_upstream: str = DEFAULT_DNS_UPSTREAM,
211
+ present: bool = True,
212
+ ebpf_preflight: bool = True,
213
+ arch: str | None = None,
214
+ ):
215
+ """
216
+ Ensure CargoWall egress firewall is present or absent on the target host.
217
+
218
+ Idempotent: checks the installed version, skips if already in the desired state.
219
+
220
+ + instance_name: unique name for this CargoWall instance (used for config
221
+ path and systemd service name)
222
+ + config: CargoWall config dict with ``defaultAction``, ``rules``
223
+ + version: CargoWall release tag (e.g. ``"v1.3.0"``); compared in canonical form
224
+ + binary_path: where to install the binary
225
+ + audit_mode: when True, run in audit (log-only) mode
226
+ + dns_upstream: upstream DNS server (e.g. ``"1.1.1.1:53"``)
227
+ + present: when False, stop the service and remove config + binary
228
+ + ebpf_preflight: when True (default), probe eBPF before staging anything and fail with an
229
+ actionable error when the host definitively cannot load programs
230
+ + arch: force the binary architecture (``amd64`` or ``arm64``); by default it follows the host
231
+ """
232
+ name = _validate_instance_name(instance_name)
233
+ desired_version = normalize_cargowall_version(version)
234
+ if desired_version is None:
235
+ raise ValueError(f"invalid CargoWall version {version!r}: expected a tag like 'v1.3.0'")
236
+ binary = _validate_path(binary_path, label="binary_path")
237
+ config_path = f"{DEFAULT_CONFIG_DIR}/{name}.json"
238
+ unit_name = _unit_name(name)
239
+
240
+ if present:
241
+ # 1. Preflight: fail before staging an install/config when the host cannot load eBPF.
242
+ # Facts run during assembly, so nothing has been executed when this raises.
243
+ if ebpf_preflight:
244
+ running = host.get_fact(CargoWallRunning, service_name=name)
245
+ if not running:
246
+ ebpf = host.get_fact(EbpfAvailable)
247
+ if ebpf.get("blocked"):
248
+ raise OperationError(_ebpf_blocked_message(ebpf))
249
+ if not ebpf.get("can_create_programs"):
250
+ host.noop(
251
+ f"CargoWall eBPF probe inconclusive ({ebpf.get('probe')}): "
252
+ f"{ebpf.get('detail') or 'no detail'}; continuing"
253
+ )
254
+
255
+ if arch is not None:
256
+ if arch not in {"amd64", "arm64"}:
257
+ raise OperationError(
258
+ f"unsupported CargoWall binary architecture {arch!r} (supported: amd64, arm64)"
259
+ )
260
+ download_arch = arch
261
+ else:
262
+ download_arch = _download_arch(str(host.get_fact(Arch)))
263
+
264
+ # 2. Install or upgrade the binary
265
+ current_version = host.get_fact(CargoWallVersion, binary_path=binary)
266
+ if current_version is None:
267
+ server.shell(
268
+ name=f"Install CargoWall {desired_version}",
269
+ commands=[
270
+ _build_install_script(
271
+ version=desired_version, binary_path=binary, arch=download_arch
272
+ )
273
+ ],
274
+ )
275
+ elif current_version != desired_version:
276
+ server.shell(
277
+ name=f"Upgrade CargoWall {current_version} -> {desired_version}",
278
+ commands=[
279
+ _build_install_script(
280
+ version=desired_version, binary_path=binary, arch=download_arch
281
+ )
282
+ ],
283
+ )
284
+ else:
285
+ host.noop(f"CargoWall {desired_version} already installed at {binary}")
286
+
287
+ # 3. Ensure config and audit-log directories
288
+ files.directory(
289
+ name=f"Ensure CargoWall config dir for {name}",
290
+ path=DEFAULT_CONFIG_DIR,
291
+ mode="0750",
292
+ )
293
+ if audit_mode:
294
+ files.directory(
295
+ name=f"Ensure CargoWall audit log dir for {name}",
296
+ path="/var/log/cargowall",
297
+ mode="0750",
298
+ )
299
+
300
+ # 4. Write config file
301
+ config_json = _build_config_json(config)
302
+ files.put(
303
+ name=f"Write CargoWall config for {name}",
304
+ src=StringIO(config_json),
305
+ dest=config_path,
306
+ mode="0600",
307
+ )
308
+
309
+ # 5. Write systemd unit
310
+ unit_content = _build_systemd_unit(
311
+ name,
312
+ audit_mode=audit_mode,
313
+ dns_upstream=dns_upstream,
314
+ binary_path=binary,
315
+ )
316
+ files.put(
317
+ name=f"Write CargoWall systemd unit for {name}",
318
+ src=StringIO(unit_content),
319
+ dest=f"/etc/systemd/system/{unit_name}",
320
+ mode="0644",
321
+ )
322
+
323
+ # 6. Enable and start service
324
+ systemd.service(
325
+ name=f"Enable and start CargoWall {name}",
326
+ service=unit_name,
327
+ running=True,
328
+ enabled=True,
329
+ daemon_reload=True,
330
+ )
331
+
332
+ else:
333
+ # Teardown: stop service, remove files
334
+ if host.get_fact(CargoWallVersion, binary_path=binary) is not None:
335
+ systemd.service(
336
+ name=f"Stop and disable CargoWall {name}",
337
+ service=unit_name,
338
+ running=False,
339
+ enabled=False,
340
+ )
341
+
342
+ files.file(
343
+ name=f"Remove CargoWall systemd unit for {name}",
344
+ path=f"/etc/systemd/system/{unit_name}",
345
+ present=False,
346
+ )
347
+
348
+ files.file(
349
+ name=f"Remove CargoWall config for {name}",
350
+ path=config_path,
351
+ present=False,
352
+ )
353
+
354
+ files.file(
355
+ name="Remove CargoWall binary",
356
+ path=binary,
357
+ present=False,
358
+ )
359
+ else:
360
+ host.noop("CargoWall already absent")