7 Commits

Author SHA1 Message Date
founder 431732396b fix: apply nft batches in the selected namespace, complete the swap rollback [P0]
Two release blockers, the first a regression introduced by dd5be47.

1. The anti-torrent batch was applied on the host.

   Making the rebuild atomic moved it from run_step(transport, ..) to run_nft_batch(script),
   and run_nft_batch spawned `nft` directly with Command::new. An nft transaction belongs to
   the network namespace of the process that runs nft, so with the production default
   apply_in_amnezia_netns = true the sequence became: inspect inside the container, install
   the table on the host, verify inside the container, fail. The guard was silently
   ineffective, a stray table accumulated on the host, and the next reconcile could fail on
   `add table` because the host copy already existed.

   NsTransport gains run_with_stdin, implemented for all three transports - host, nsenter,
   and docker exec with -i, which is required or the child sees EOF immediately.
   run_nft_batch now takes the transport, and both callers pass the one they inspected
   with. A recording fake transport asserts the script goes through the transport rather
   than to a host process, which is the regression this could not previously catch.

2. Swap replacement rolled back with the wrong priority and not from every branch.

   The rollback reactivated with desired.priority - the value that may be exactly what the
   kernel had just rejected - because the previously active priority was dropped at the
   match arm and never passed in. The active entry's priority is now carried into
   replace_active_swapfile and used by the rollback.

   Three early failure branches also returned without undoing anything: a failed swapoff of
   the original, a failed rename to .previous, and a failed swapoff of the staging file all
   left the staging swap active and the transition half-applied, after which the next
   reconcile tried to unlink a file that was still active and could not proceed.

   The transition now records what it completed - staging_active, original_active,
   original_moved, new_installed - and one rollback undoes exactly that much, in an order
   that never leaves the host without swap: restore the original file, reactivate it at its
   previous priority, confirm it, and only then release and remove the staging swap. The
   returned error carries the original cause plus what the recovery achieved.

   Leftovers from a killed process are no longer removed blindly. A .new or .previous that
   is still active cannot be unlinked, so it is reported with the swapoff command that
   clears it instead of failing the same way on every reconcile.

Also in this commit, from the same audit:

- Requires=docker.service dropped in favour of Wants=. The daemon is built to outlive
  Docker being down, but Requires= had systemd stop the harness whenever Docker stopped,
  and Restart=on-failure does not cover a dependency-ordered stop - so the reconnect loop
  never got to run.
- apply_antitorrent_disabled swallowed every discover_target error, not just "no container
  running". Docker being unreachable or a permission error on the socket reported success
  for a cleanup that never happened. Only AppError::NotFound is tolerated now.
- FstabTransaction::begin asserts /etc/fstab is a regular non-symlink file. read_to_string
  and metadata both follow links, so a symlinked fstab would be read through and then
  replaced by the rename, detaching the real file from the path the system boots from.
- append_event serialises its read-modify-write behind a mutex; the reconcile loop and the
  Docker events thread both append and could drop an entry.
- tool_exists loses the fallocate, chmod and dd arms, dead since mkswap --file replaced the
  allocation chain.

Docs corrected where they no longer matched the code: findmnt is described as mandatory
rather than skippable, the swap creation wording is mkswap --file, and the README package
examples use 0.1.6 to match Cargo.toml. Remaining fallocate mentions are explicitly
historical ("the previous chain"), which is accurate.

Seven tests added: batch routed through the given transport, batch failure reported as
such, rollback state defaults and previous-priority carry, active leftovers reported rather
than deleted, inactive leftovers cleared.

cargo fmt --check, clippy -D warnings, cargo test --locked --workspace --release: 188 + 4
passed.
2026-08-07 05:08:20 +05:00
founder fa44ffbb24 fix: verify the state directory before use, keep fstab copies at the original mode [P1]
1. The state directory was created too late and never verified.

   ensure_state_dir only ran when the ownership record was written, well after
   assert_swap_path_is_safe had already required every parent of swap.path to exist. On a
   clean host that meant a perfectly legal /var/lib/awg2-harness/swapfile was rejected
   because the directory this package is supposed to create did not exist yet.

   Worse, when the directory did exist the check only confirmed it was a directory. A
   pre-existing /var/lib/awg2-harness that was group- or world-writable defeated the whole
   point of restricting swap.path to root-owned roots: another user could still swap the
   swapfile out from under a root-owned fallocate or mkswap.

   ensure_state_dir now runs first in ensure_swap and asserts what the restriction actually
   depends on: the parent is a real directory and not a symlink, the state directory itself
   is not a symlink, it is owned by uid 0, and it is not writable by group or others. A
   mode that is merely narrower than 0700 is tightened rather than rejected; anything
   group- or world-writable is a hard error, because the safety argument for the whole
   allow-list rests on it.

   The units also declare StateDirectory=awg2-harness with mode 0700 and
   RuntimeDirectory=awg2-harness, so in the common case systemd creates and owns both and
   the binary only has to verify. The runtime checks stay regardless: the CLI subcommands
   run outside the service lifecycle.

2. The fstab copies could be more permissive than the file they mirror.

   The backup and pristine copies were written at a hardcoded 0644 with a comment claiming
   they must not be wider than the original. On a host where /etc/fstab is 0600 they were,
   and the rollback then handed that wider mode to the live file too. FstabTransaction now
   captures the live mode when it opens and uses it for the backup, the pristine copy, the
   candidate and the rollback.

One test added, unix-only since it asserts a mode: a 0600 fstab produces 0600 copies and
stays 0600 after the commit.

cargo test --workspace: 180 + 4 passed. clippy -D warnings clean. Unit files not verified
here - no systemd on this host; tools/build.sh runs systemd-analyze verify on the build
machine.
2026-08-07 04:44:35 +05:00
founder a9b6e3c15d fix(systemd): drop the duplicate ensure-swap, use Type=exec and stepped restart backoff [P1]
awg2-harness.service ran ensure-swap from ExecStartPre while the daemon runs it again as
the first step of its own startup. Idempotency kept it harmless, but it cost two locks,
two reads of /proc/swaps, two persistence checks, and split the startup failure path
across two units so an operator reading systemctl status could not tell which invocation
failed. The daemon owns the startup sequence, its error contract and its log stream, so
the ExecStartPre is removed. The standalone ensure-swap subcommand is unaffected.

Type=simple reports a unit as started the moment systemd forks, before the binary is
known to be executable. Type=exec waits for the exec to succeed, so a missing or
non-executable /usr/sbin/awg2-harness fails the unit instead of appearing to start.

Restart policy: the daemon moves from Restart=always to on-failure, matching the
scheduler. A clean exit is deliberate and should not be respawned. For the scheduler this
was already load-bearing and is now documented - it exits 0 both when reboot.enabled is
false and after systemd accepts the reboot request, so Restart=always would have spun it
in a loop on any host with scheduled reboots disabled.

RestartSec=10s with StartLimitBurst=5 over StartLimitIntervalSec=60 could exhaust the
limit in about 50 seconds, which is easy to hit when the daemon is failing because Docker
or the container is still coming up - the restarts burn the budget before the dependency
can recover. Replaced with a stepped backoff, 10 -> 20 -> 40 -> 80 -> 160s via
RestartSteps=4 and RestartMaxDelaySec=160s, and the limit window widened to 15 minutes
with a burst of 10 so a full backoff sequence fits inside it. Both directives require
systemd 254+; Debian 13 ships 257.

Documented alongside, because it is the same lifecycle contract and had no home in the
docs: configuration is read once at process start and a config edit needs a restart of the
affected service. daemon-reload is not involved - it applies to unit files, not to the
application config. ExecReload is deliberately absent, since adding it without real SIGHUP
handling would imply a reload path that does not exist.

Unit files are installed from the repo root by tools/build.sh, which already runs
systemd-analyze verify on the build host when it is available, so these changes are
verified there. Not verifiable in this environment: no Debian, no systemd.

Acceptance checklist gained five checks covering unit verification, the restart-required
contract, single ensure-swap per start, growing backoff, and the scheduler not looping
when reboots are disabled.
2026-08-06 22:54:11 +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 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 9d2d2bc0c2 Сборка: добавить production packaging flow через .deb
Добавлен package-режим в tools/build.sh: --package, --dist-dir, --version. Реализована сборка Debian-пакета, metadata/control, postinst/postrm и SHA256SUMS. Установочные пути унифицированы под /usr/sbin и /lib/systemd/system для production-модели.
2026-05-10 17:26:11 +05:00
founder d937f816bf feat: bootstrap awg2 harness rust workspace and docs 2026-05-09 02:17:25 +05:00