Commit Graph

60 Commits

Author SHA1 Message Date
founder 549fbcae31 fix(swap): make the /etc/fstab rewrite transactional [P0]
Two release blockers, both in the most destructive operation the package performs.

1. An unreadable /etc/fstab was treated as an empty one.

   let content = fs::read_to_string(fstab_path).unwrap_or_default();

   PermissionDenied, an I/O error, a damaged filesystem and "file absent" all collapsed
   into an empty string. The rewrite then emitted a fstab containing only the managed swap
   line and installed it atomically and successfully, dropping the root and boot mounts.
   Consequence: a host that does not boot, guarded by one unwrap_or_default. The same
   masking was present in read_fstab_swap_entries, so an unreadable fstab was reported by
   status as "no swap entries", which reads as healthy drift-free state.

2. The backup was best-effort.

   let _ = fs::write(bak_path, &content);

   If it failed, the rewrite proceeded anyway. IMPLEMENTATION_SPEC and the acceptance
   checklist both asserted the backup exists. The scenario where the backup fails is
   exactly the scenario where it is needed.

New module fstab.rs owns the operation:

- read_required distinguishes NotFound from every other error and fails on both. A
  missing /etc/fstab on Debian is an anomaly, not a blank slate, so it is never created;
- a blank candidate is refused outright;
- the backup is mandatory and flushed before the temp file is created, so there is no
  window where the target is about to be replaced and no recovery copy exists;
- two copies are kept: .awg2-harness.bak is the state before the current rewrite,
  .awg2-harness.original is written once with create_new and holds the host as it was
  before this package first touched it;
- the temp file is a sibling of the target, created with create_new, sync_all'd, and
  inherits the original permissions; a stale temp from a killed run is removed explicitly
  rather than reused;
- the candidate is validated with findmnt --verify --tab-file before the swap. The step is
  skipped when findmnt cannot be spawned; a rejection is fatal;
- commit is an atomic rename followed by a directory fsync;
- after the rename the target is re-read and compared to what was written. A mismatch
  restores the backup and fails.

Also fixed: render_fstab_line interpolated the path raw. fstab fields are
whitespace-separated, so a space or tab in swap.path would shift every following column.
Paths now go through octal escaping (\040, \011, \012, \134).

Ten tests, all portable - the "unreadable but present" case is exercised by pointing the
reader at a directory, which fails as a non-NotFound error on every platform. Covered:
unreadable target is an error rather than an empty file, missing target is an error,
backup failure leaves the target byte-identical, blank candidate refused, unchanged
candidate is a no-op that writes no backup, the pristine copy survives repeated rewrites,
a stale temp does not block commit, and field escaping.

Docs updated: IMPLEMENTATION_SPEC section 17 gained the full rewrite contract, the
acceptance checklist gained seven checks including the two failure modes above.

cargo test --workspace: 124 + 4 passed, ten new. clippy -D warnings clean.
2026-08-06 21:02:38 +05:00
founder 7254ebe9e4 traffic: make apply and verify share one class-id assignment
apply_full_topology computed peer class ids inline while inspect_and_diff computed them
through expected_peer_class_map. Two implementations of the same contract, and
apply_full_topology ends by calling inspect_and_diff to verify its own work - so a
divergence between them would surface as verify-after-apply failing on a topology that had
just been applied correctly, with a reason pointing at class mapping rather than at the
real cause. Apply now uses expected_peer_class_map, which makes it structurally impossible
for the two sides to disagree.

Behaviour is identical. Both paths assign class_start_id + index over peers in slice order,
and discover_peers hands them over sorted lexicographically and deduplicated. Iterating the
resulting BTreeMap walks the same keys in the same order, so the emitted tc commands and
their class ids are unchanged; only the loop source moved.

expected_peer_class_map is now the single source of truth for the class-id contract and
gained the tests it never had: lexicographic ordering (10.8.1.10 before 10.8.1.2, the
production contract that must not silently become numeric), a non-default class_start_id,
u16 overflow, and the empty peer list.

Found while splitting traffic.rs; kept out of that commit to keep the move reviewable.

cargo test --workspace: 114 + 4 passed, four new. clippy -D warnings clean.
2026-08-06 18:53:24 +05:00
founder dbceda5c13 refactor(firewall): split firewall.rs by subsystem, collapse duplicated test fixtures
firewall.rs held two subsystems that share nothing but the nft command layer: the host
INPUT firewall, applied in the host namespace and owning inet awg2_host_firewall, and the
anti-torrent guard, applied in the namespace chosen by config and owning inet
awg2_harness. The split follows that boundary rather than an inspect/apply one:

  firewall/mod.rs          apply_firewall, namespace selection, shared table constants
  firewall/nft.rs          text normalization and the nft command wrappers
  firewall/host.rs         host INPUT firewall and its 5 tests
  firewall/antitorrent.rs  connection-count guard and its 6 tests

Production logic is unchanged. Function sets before and after are identical: 25 against
25, verified by extracting names from the old blob and the four new files and diffing.

Not a pure move in one respect, stated here so it is not a surprise in review: the test
module contained four near-identical 45-line Config literals, about 180 lines of
copy-paste, differing only in the single field each test actually cared about. Carrying
four copies into the new files would have knowingly propagated the duplication, so they
collapse into one test_config() helper in firewall/mod.rs that tests mutate. This is why
the four files total 875 lines against the old 890 despite gaining doc comments.

Doc comments now record the reasoning that was only implicit before: why nft output is
compared after normalization (rendering differs across versions - quoting, comma-separated
ct state lists, brace layout), why the host firewall batch never contains a delete (a
partially applied INPUT chain could lock out SSH), why ct state new is load-bearing in the
anti-torrent rule, why connlimit_state_present accepts two renderings, and why the
anti-torrent rule defaults to the container namespace.

IMPLEMENTATION_SPEC section 3 is updated: it described the old flat layout and carried the
split as an unfulfilled intention. Both traffic and firewall now match what it documents.

cargo test --workspace: 110 + 4 passed, unchanged count. clippy -D warnings clean.
2026-08-06 18:51:31 +05:00
founder b42d99068b refactor(traffic): split traffic.rs into a module directory, code move only
traffic.rs was 1026 lines of production code, by far the largest module. The split the
spec has described since the beginning is now done, along the responsibility boundaries
that already existed inside the file:

  traffic/mod.rs       shared models and the three entry points
                       (inspect_drift_summary, reconcile_traffic, peer_status_table)
  traffic/parse_tc.rs  pure parsers for tc/ip output, plus all 16 existing tests
  traffic/inspect.rs   inspect_and_diff and the class-id contract
  traffic/apply.rs     teardown, full rebuild, and the tolerated-error wrappers

No logic changed. The function set before and after the move is identical - verified by
extracting function names from the old blob and the four new files and diffing them: 26
against 26, no additions, no removals. Bodies moved verbatim; the only edits are module
paths, pub(super) markers on the items that cross a file boundary, and doc comments on
the non-obvious parts (why filter parsing is block-based, why the class-id sort is
textual, what each tolerated-error wrapper is allowed to swallow).

Note on visibility: the shared models stay private in mod.rs. Rust makes private items
visible to descendant modules, so the submodules can construct TrafficDrift and
FilterInspect without widening anything to pub(crate).

Splitting the tests out with their parsers is the practical win: parse_tc.rs is 100% pure
functions and now reads as the tested surface of the module, rather than 16 tests sitting
at the bottom of a thousand-line file next to code that needs a live container.

cargo test --workspace: 110 + 4 passed, same count as before the move, all 16 traffic
tests now reporting under traffic::parse_tc. clippy -D warnings clean.
2026-08-06 18:46:52 +05:00
founder 84275d0fe4 status: deduplicate the healthy and degraded paths, keep the System block contiguous
print_status and print_degraded_sections carried four byte-identical blocks - host
firewall (25 lines), anti-torrent (24), last actions (9) and recent events (10) - plus a
Conntrack block that was the same logic assembled differently and a Traffic desired block
of four printlns. Roughly 80 lines of copy-paste with no test covering either copy, so a
format change applied to one path would have silently diverged from the other. The
divergence would only ever be visible while the container is down, which is the worst
moment to discover the diagnostic output is wrong.

Every shared section is now one function called from both paths:
print_traffic_desired_section, print_host_firewall_section, print_antitorrent_section,
print_conntrack_section, print_last_actions_section, print_recent_events_section. The file
already had this shape for print_swap_status and print_reboot_section; the pattern is now
followed consistently. The Docker/Amnezia port path block keeps two variants because they
genuinely differ - real values against unknown - but the shared FORWARD ownership note is
a single constant.

The runtime state paths were also duplicated across modules: status.rs re-declared the
literals that daemon.rs already owns. daemon::LAST_STATE_FILE and daemon::EVENTS_FILE are
now pub and reused, and the recent-events window is a named constant instead of a bare 10.

Ordering fix in the same function: print_network_tuning_status ran between the service
line and the container lines, so container/container_id/pid/netns/interface appeared under
the "Network tuning:" header at the same two-space indent as its fields. Container
identity is now printed inside the discovery match, before any other section opens, in
both the healthy and degraded paths. Field names are unchanged; only the order of two
blocks moved. IMPLEMENTATION_SPEC section 15 documented the old order and is updated.

print_degraded_sections returned anyhow::Result<()> while never failing; it returns unit
now.

status.rs: 645 -> 602 lines. cargo test --workspace: 110 + 4 passed. clippy -D warnings
clean.
2026-08-06 18:41:39 +05:00
founder d98ade42ce docs: unify language contract to Russian and reconcile the spec with the code
The docs folder had drifted into a mixed-language contract: IMPLEMENTATION_SPEC.md was
entirely in English while the rest was Russian with English headings. Prose is now
Russian throughout; English is kept only where it is technically load-bearing (commands,
tool output, config keys, file/module/table names, tc handles) and for terms with no
settled Russian equivalent in this context (drift, reconcile, peer, namespace, handshake).
docs/README.md now states that contract explicitly.

Rewriting the spec surfaced several places where it described intent rather than the
code. Corrected against traffic_core/src:

- module layout: the spec showed traffic/ and firewall/ as directories with
  model/inspect/apply submodules. They are single files, and sysctl_tuning.rs was
  missing from the tree entirely.
- data model: Peer was documented as carrying public key, handshake and counters. It
  carries only ipv4; runtime state lives in a separate PeerRuntime, and there is no
  desired-state struct at all - it is derived inline from config plus sorted peers.
  RuntimeTarget.netns_path is a String, not a PathBuf.
- interface detection: the spec listed a third step taking the first non-loopback
  interface with an IPv4 address. No such fallback exists; detection bails with an
  explicit error, which is safer and is now documented as deliberate.
- reconcile: the pseudo-flow folded firewall into reconcile_traffic. They are two
  independent reconciles with separate locks.
- locking: only traffic.lock was documented. There are three locks, and
  sysctl_tuning.lock has a 30s timeout rather than 10s. Stale-lock recovery via
  /proc/<pid> was undocumented.
- sysctl_tuning: the module also manages /etc/modules-load.d/90-awg2-harness-bbr.conf
  when BBR is active, and refuses to touch either managed file without its marker.
  Both docs and the acceptance checklist claimed only the sysctl.d file was written.
- status contract: the documented output was outdated. All 15 printed sections are now
  listed in the order status.rs emits them, including the degraded path when no container
  is found, and the fact that the Network tuning block is printed between the System
  service line and the container lines.
- swap: size was documented as a constant 2048 MB instead of swap.size_mb, and the
  /etc/fstab.awg2-harness.bak backup was undocumented.
- apply/verify: the tolerated-error lists are now the actual closed sets from the code.

Acceptance checklist gained checks for the daemon startup failure policy (sysctl/swap
fatal, traffic/firewall not), lock contention and stale-lock recovery, degraded status,
the modules-load file, and the marker guard. The stale host wg requirement was dropped
from its host-tools item.

Every path, table, counter and log string quoted in the docs was verified to exist in
the source. cargo test --workspace: 110 + 4 passed.
2026-08-06 16:45:00 +05:00
founder 16214f3c66 AmneziaWG 3.0 readiness: centralize wg CLI contract, drop dead host-side fallback
Peer discovery is now the single owner of how wg is invoked and parsed.

wg.rs:
- resolve the binary through ordered amnezia.wg_binaries (default [awg, wg]);
  awg is the real binary in the official image and wg is a symlink to it, so awg is
  tried first and wg stays for plain WireGuard containers. No probe call: resolution
  is a property of the command being run anyway.
- drop the nsenter fallback. AmneziaWG is userspace and its UAPI socket lives under
  RUNSTATEDIR/amneziawg/ in the container mount namespace, while host wireguard-tools
  looks under /var/run/wireguard/. nsenter -n enters only the network namespace, so
  that path could never return peers.
- classify dump lines structurally instead of by column count. The AWG interface line
  is longer than a peer line (14 columns on AWG 2.0, 28 on AWG 3.0) and its
  handshake/rx/tx positions hold junk-packet sizes that parse as integers, so only the
  allowed-ips column discriminates. Column 1 of an interface line is the device private
  key, which the previous heuristic rejected only incidentally.
- fix allowed-ips parsing: `show all allowed-ips` separates a peer's addresses with
  spaces, not commas, so peers with more than one allowed IP were shaped on their first
  address only and the rest ran unlimited.
- collapse the three duplicated /32-in-CIDR filters into one tokenizer shared by the
  allowed-ips, dump and pretty-print parsers.

config.rs:
- add amnezia.wg_binaries with serde default, validated as bare command names
  (non-empty, no whitespace, no path separators) since they execute inside the
  container. Existing deployed configs keep parsing unchanged.
- remove host wg from the required-tool preflight. It gated daemon startup on
  wireguard-tools for a code path that produced nothing.

status.rs:
- discover peers once instead of twice per status call and degrade gracefully like the
  neighbouring sections instead of aborting the whole output.

Tests: real AWG 3.0 / AWG 2.0 / plain WireGuard interface-line fixtures, AWG 3.0 range
keepalive, space-separated allowed-ips, binary resolution order, and a test that parses
and validates the shipped config.example.toml.
2026-08-06 15:32:26 +05:00
Crimson 5edefa74b1 Обновить README.md 2026-06-23 03:03:55 +00:00
Crimson 9a80afdb9e Обновить README.md main_v0.2.6 2026-06-21 17:34:01 +00:00
founder 0d0b1c006b fix(sysctl_tuning): complete fix36 production reconcile and bbr modules-load lifecycle 2026-05-28 20:04:08 +05:00
founder 4f384bcff0 Decouple sysctl runtime validation and modprobe dependencies 2026-05-28 12:12:42 +05:00
founder 10b2d0aefb Production sysctl_tuning hardening and upgrade-safe defaults 2026-05-28 12:01:08 +05:00
founder 2c27bff800 Реализован production-модуль sysctl_tuning и полная интеграция fix33
Добавлен отдельный host-level модуль sysctl_tuning без легаси-подходов: managed sysctl файл, точечный reconcile через sysctl -w только для drifted ключей, режимы tcp_bbr off/auto/require, безопасное удаление только managed-файла и атомарная запись конфигурации.

Интегрированы новые CLI-команды apply-network-tuning/inspect-network-tuning, startup reconcile в daemon и секция Network tuning в status. Расширены config/defaults/валидация, обновлен пример конфига и документация. Добавлены unit-тесты для config и sysctl_tuning.
2026-05-28 11:31:13 +05:00
founder 4ff2bb2c30 Документация: унификация проверок для amnezia-awg2 и amnezia-awg 2026-05-12 21:19:08 +05:00
founder c7b5da98f4 Документация DNS: динамический deep-check и уточнение критериев 2026-05-12 21:12:15 +05:00
founder 8e3e924952 Документация и postinst UX: безопасная проверка checksum и preflight-first 2026-05-12 20:46:57 +05:00
founder c78015f76e Конфиг: переведены комментарии в config.example.toml на русский 2026-05-12 20:37:52 +05:00
founder 4757799f04 Документация: обязательный production-профиль AmneziaDNS и правила DNS/53 2026-05-12 20:36:17 +05:00
founder b3d274f89d Документация и UX установки: полный production-fix по fix32 2026-05-12 20:16:56 +05:00
founder 2ee50bfa8e docs: уточнён формат SSH-ключа для установки через Amnezia main_v0.1.6 2026-05-12 18:41:23 +05:00
founder d1d919a615 fix31: финальный polish формулировок без исторических отсылок 2026-05-12 18:05:27 +05:00
founder bb37da72c0 fix30: очищены old-bash формулировки и уточнён class-id контракт 2026-05-12 17:50:15 +05:00
founder b493c9df3b chore: удалить временный fix29.txt из репозитория 2026-05-12 17:28:48 +05:00
founder 44a62cf634 fix29: удалён legacy, введён Debian 13-only и обновлён rollback 2026-05-12 17:26:41 +05:00
founder 69c737bcf4 fix28: обновлена production-документация и упаковка docs в deb 2026-05-12 16:56:36 +05:00
founder a9bac8fdad fix27: исправлен парсер root-класса tc без ложных совпадений 2026-05-12 14:34:28 +05:00
founder ead1130e5f fix25: исправлена идемпотентность swap и удаления default qdisc 2026-05-12 14:24:02 +05:00
founder a64fae7fe6 fix24: исправлен production-парсинг версии пакета в build.sh 2026-05-12 14:12:51 +05:00
founder c10fb775e9 Fix23: вернуть production ssh_port 2323 в конфиге и документации
- config.example: host_firewall.ssh_port=2323

- docs: синхронизированы CONFIGURATION/MIGRATION/ACCEPTANCE_CHECKLIST
2026-05-12 14:02:12 +05:00
founder 6e586c7af9 Fix23: финализация production-сборки 0.1.4
- Swap: сузил tolerance usable size до 64 KiB

- Cargo.lock: синхронизирована версия awg2-harness = 0.1.4

- Example/docs: ssh_port default приведен к 22

- Обновлен acceptance checklist по SSH default
2026-05-12 14:00:54 +05:00
founder 44d3593944 Fix22: подготовка production 0.1.4 и стабилизация сервиса
- Поднята версия awg2-harness до 0.1.4

- Обновлены production defaults: peer_limit=50mbit, root_rate=500mbit

- Добавлен systemd anti-flapping rate-limit и увеличен RestartSec

- Синхронизирована документация CONFIGURATION/MIGRATION
2026-05-12 13:47:37 +05:00
founder ff2ae98d30 Fix21: прод-фиксы swap/firewall/wg без легаси
- Swap: допуск небольшой дельты usable size при verify/compare

- Firewall: поддержка Debian 13 dynamic set/add @set вместо только literal meter

- WG: приоритет docker exec для peer/runtime discovery с безопасным fallback
2026-05-12 13:37:37 +05:00
founder c463e64205 Исправлены runtime-баги firewall policy и парсера swapon для Debian 13 2026-05-12 13:15:14 +05:00
founder bbefd299fd Исправлен packaging-gate для build-host без runtime-зависимостей 2026-05-12 12:46:06 +05:00
founder 5800b6c874 Исправлен парсер tc-хитов для строк match+success 2026-05-12 12:34:37 +05:00
founder bff9c50a6b Исправлены clippy-замечания под gate -D warnings 2026-05-12 12:19:47 +05:00
founder d114784d7d Убраны дубли проверок в build gate и package выводе 2026-05-12 11:54:28 +05:00
founder 1e2a3b5b67 Добавлен fallback диагностики FORWARD через nft и расширен вывод status 2026-05-12 11:48:18 +05:00
founder ed786f165f Исправлен сломанный unit-тест docker parser в docker.rs 2026-05-12 11:33:32 +05:00
founder f8c6f2e92d Уточнена диагностика UDP port mapping для Docker и обновлены checklist/docs 2026-05-11 19:30:25 +05:00
founder adc244daa7 Добавлена диагностика Docker/Amnezia port path в status и уточнена документация host firewall 2026-05-11 19:22:39 +05:00
founder 640178a592 Исправлен drift-check host firewall для established/related, добавлены тесты и trim policy в status 2026-05-11 18:54:15 +05:00
founder 36600c0a5a fix10: стабилизация host firewall first-run и no-op reconcile
- исправлен first-run дефект: delete table вынесен из nft batch\n- добавлен no-op путь при отсутствии host firewall drift\n- исправлен trim для default_input_policy в drift-check\n- добавлены тесты для batch script и policy trim\n- уточнен release-gate в acceptance checklist по INPUT/FORWARD
2026-05-11 18:45:17 +05:00
founder ed4a571d71 fix9: безопасный host firewall apply и строгий конфиг
- host_firewall секция стала обязательной (убран silent enable)\n- host firewall применяется атомарным nft batch\n- добавлен verify-after-apply с hard-fail при drift\n- усилен tolerant parser drift (кавычки, ipv6-icmp alias)\n- расширены unit-тесты config/firewall\n- дополнен acceptance checklist блоком host firewall
2026-05-11 18:33:46 +05:00
founder 3d5bec424c chore: форматирование тестов wg и reboot module 2026-05-11 18:16:26 +05:00
founder 381c106f9d fix8: продакшн host firewall + dual reconcile firewall
- добавлена секция host_firewall в конфиг и defaults\n- реализован host firewall reconcile в отдельной таблице\n- apply-firewall теперь делает host firewall + anti-torrent\n- убрана JSON-инспекция из full-table drift для anti-torrent\n- расширен status вывод drift по host firewall/anti-torrent
2026-05-11 18:14:46 +05:00
founder 7a4e9764b1 fix7: продакшен-реализация полного reconcile swap и интеграций
- Полностью переписан swap-модуль в режиме exclusive ownership\n- Добавлены verify/checks, статус фактического swap-state и drift\n- Интегрирован ensure-swap в daemon и systemd ExecStartPre\n- Усилен lock API (таймауты) и применение в traffic/firewall/swap\n- Усилен parser firewall (JSON-first + устойчивый text fallback)\n- Обновлены config validation, runtime tools и default priority\n- Синхронизированы docs и build/package hygiene\n- Удалены member Cargo.lock в пользу корневого lockfile
2026-05-11 17:30:15 +05:00
founder 819cc9c308 Документация и runtime: полный production-fix по fix6 без legacy 2026-05-10 22:58:59 +05:00
founder 83c4e3ba05 workspace и reboot-модуль: второй продакшн бинарь и упаковка 2026-05-10 21:30:06 +05:00
founder d4cd6a4e43 traffic_core: продакшн-фиксы runtime и валидации 2026-05-10 21:29:52 +05:00