diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index c8e7a0c..39cff26 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,8 +1,9 @@ # Workflow state -Updated: 2026-11-24. -Repository: VoidLibrary; active branch `feat/roadmap-p2-wave6a` (from `main` -at `4479960`, merged Waves 1–5 and pushed to `origin/main`). +Updated: 2026-11-25. +Repository: VoidLibrary; active branch `feat/roadmap-p2-wave6b` (from `main` +at `acd77ee`, merged Waves 1–6A plus RFC 8259 decimal `StrictJson` and pushed +to `origin/main`). ## Completed objective @@ -251,9 +252,60 @@ while leaving local untracked files untouched. `binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 311.16 ns, `data_json_serialize_small_object` 162.52 ns. +## Verification already observed (StrictJson RFC 8259 decimals — `acd77ee`, on `main`) + +- Added `ParseOptions{maximumDepth, allowDecimals = true}` and `double` variant + alternative to `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`) for LSP + messages while preserving exact `int64_t` integer semantics and `allowDecimals = false` + opt-out (`tests/standalone/Data/StrictJson.cpp` 6/6 tests). +- Verified in RelWithDebInfo `-Werror` (`49/49`, `ctest` 2/2) and Debug ASan+UBSan + `-Werror` (`/tmp/void-strictjson-asan`, `49/49` in 7.0 ms, 0 leaks, 0 UB); pushed to + `origin/main`. + +## Verification already observed (Wave 6B — P2 Crypto, Security, Archive, Update) + +- Wave 6B task specs (`8a1c15f`): added `M-CRYPTO-01-05.md`, `M-SECURITY-01-04.md`, + `M-ARCHIVE-01-05.md`, and `M-UPDATE-01-06.md`. +- `Crypto` & `CryptoAsync` (`eb42228`): `Crypto;CryptoAsync;Testing` (`/tmp/void-w6b-crypto`, + `-Werror`, `-p openssl`, 10 modules) `Crypto*|crypto_*` 8/8 (`Crypto` 3, + `CryptoHardening` 3, `CryptoAsync` 2); `ctest` 2/2 (`7.22 s`, including `CryptoOnly` & + `CryptoAsyncOnly`). +- `Security` & `SecurityAsync` (`713d2dc`): `Security;SecurityAsync;Testing` + (`/tmp/void-w6b-security`, `-Werror`, `-p libsodium`, 10 modules) `Security*|security_*` + 14/14 (`720.7 ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2); + `ctest` 2/2 (`8.46 s`, including `SecurityOnly` & `SecurityAsyncOnly`). +- `Archive` (`00d7478`): `Archive;Testing` (`/tmp/void-w6b-archive`, `-Werror`, + `-p libarchive`, 7 modules) `Archive*|archive_*` 9/9 (`259.0 ms`: `Archive` 6, + `ArchiveHardening` 3); `ctest` 2/2 (`5.76 s`, including `ArchiveOnly`). +- `Update` (`47736cb`): `Update;Testing` (`/tmp/void-w6b-update`, `-Werror`, + `-p libarchive -p openssl`, 12 modules) `Update*|update_*|component_feed_*|readable_component_*|version_store_*` + 25/25 (`1.91 s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 (`10.64 s`, including + `UpdateOnly`). +- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-full`, 41 modules, + `47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 intentional skips + (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed + (`6.26 s`); `ctest` 2/2 passed (`VoidTests` 7.34 s, `VoidInstalledComponentConsumers` + all 25 consumers incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`, + `SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`, + `RelocatedExternal`, 40.73 s, total 48.07 s). +- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w6b-asan`, 41 + modules, `47736cb`): `VoidTests` 1,406 tests — 1,403 passed, 3 skipped, 0 failed + (`21.78 s`), 0 ASan/LSan leaks, 0 UBSan errors. +- Wave 6B Debug TSan subset (`CryptoAsync;SecurityAsync;Update;Testing`, + `/tmp/void-w6b-tsan`, 20 modules, `47736cb`): 56/56 passed (`4.86 s`), 0 TSan data races. +- `VoidFoundationBench` post-W6B (`rev=47736cb6ce2f`, `/tmp/void-w6b-full/post-w6b.json`): + `harness_empty_loop` 0.38 ns, `core_uuid_parse_hyphenated` 24.52 ns, + `core_uuid_to_string` 16.53 ns, `core_hash_fnv1a64_256b` 179.95 ns, + `core_hash_murmur3_256b` 67.37 ns, `functional_result_ok_chain` 1.12 ns, + `functional_error_with_context` 58.37 ns, `math_checked_add_loop` 0.47 ns, + `containers_spsc_ring_push_pop` 8.76 ns, `containers_lru_get_put` 21.02 ns, + `binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 333.32 ns, + `data_json_serialize_small_object` 165.99 ns. + ## Ownership and next step -Waves 1–6A (`P0`, `P1`, `P2` Operations Foundations, `System`, `SystemAsync`, and `IPC`) -are complete and verified on `feat/roadmap-p2-wave6a`, ready to merge into `main`, push to -`origin`, and proceed continuously to **Wave 6B (`Crypto`, `Security`, `Archive`, -`Update`)**. +Waves 1–6B (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, and +`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`) are complete and +verified on `feat/roadmap-p2-wave6b`, ready to merge into `main`, push to `origin`, and +proceed continuously to **Wave 7 (`Sqlite`, `SqliteAsync`, and NEW original `Storage` +engine — `G-STORE` gate)**. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 5aa78af..956dc47 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -79,6 +79,21 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | M-SYSTEM-06 | Split async `SystemAsync` (`INTERNAL_DEPS System Async IO Time Functional LogState`, `EXTRA_HEADERS` `AsyncProcess.hpp`/`AsyncWatcher.hpp`), `ProcessManager`, `ManagedChild`, async `communicate`/`wait`/`close_and_join`, `WatcherService`/`WatchSubscription`, `SystemAsync.cpp`, `SystemAsyncOnly` consumer (`9a3c5d8`) | [M-SYSTEM-01-05](tasks/M-SYSTEM-01-05.md) | VERIFIED | `SystemAsync*` 2/2 (`211.5ms`), `ctest` 2/2 (`SystemAsyncOnly` `9.43s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `2/2` (0 races) | | S-IPC-01..03 | New `IPC` module (`src/IPC/module.cmake`, `Types.hpp`, `Codec.hpp`, `Transport.hpp`, `Session.hpp`, `IPC.hpp`), V1 `VDIP` 24B big-endian framing & pre-alloc `BufferQuota`/`QuotaPermit`, `LocalListener`/`connect_local` (`O_NOFOLLOW`, `0700`/`0600`, `flock`, `SO_PEERCRED` fail-closed), `adopt_pipe_pair`/`create_socket_pair_transports`, full-duplex `Session` with control lane/tombstones/token-bucket/graceful drain, `Ipc.cpp`, `IPCOnly` consumer (`39a48d5`) | [S-IPC-01-03](tasks/S-IPC-01-03.md) | VERIFIED | `Ipc*` 3/3 (`8.8ms`), `ctest` 2/2 (`IPCOnly` `12.20s`), full RelWithDebInfo (`1,383 ✔`), ASan+UBSan (0 leaks/UB), TSan `3/3` (0 races) | +## Out-of-band Priority Fix (`main`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| StrictJson decimals | RFC 8259 decimal numbers (`double` variant alternative + `ParseOptions::allowDecimals = true`) in `Void::Json::Strict` (`include/Void/Data/StrictJson.hpp`, `tests/standalone/Data/StrictJson.cpp`) (`acd77ee`) | — | VERIFIED | `StrictJson` 6/6 (`49/49` Data suite, `ctest` 2/2), Debug ASan+UBSan `49/49` (0 leaks/UB); pushed to `origin/main` | + +## Wave 6B — P2 Crypto, Security, Archive, Update (`feat/roadmap-p2-wave6b`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| M-CRYPTO-01..05 | Hardened `Crypto` (OpenSSL 3.5.9 non-deprecated `EVP_MD`/`EVP_MAC`/`EVP_KDF`/`EVP_PKEY`, poisoned `Hasher`, 16 MiB Ed25519 cap, 4 KiB HKDF cap & overlap/wipe guards, `constant_time_equal`, `secure_wipe`, `kCryptoErrorDomain = 18`) + optional `CryptoAsync` (`hash_stream`, `AsyncFileHasher` 8/32/8 MiB budget, `close_and_join`), `CryptoOnly` & `CryptoAsyncOnly` consumers (`8a1c15f`, `eb42228`) | [M-CRYPTO-01-05](tasks/M-CRYPTO-01-05.md) | VERIFIED | `Crypto` 3 + `CryptoHardening` 3 + `CryptoAsync` 2 = 8/8, `ctest` 2/2 (`7.22s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 8/8 (0 races) | +| M-SECURITY-01..04 | Hardened `Security` (`kSecurityErrorDomain = 19`, `SecureBuffer` with lock policies & wipe counter, input caps, `parse_argon2id_cost`, `verify_password_budgeted`, `VSEC` v1 `xchacha20poly1305_ietf` `Envelope`/`SecretKeyRing` without legacy fallback, bounded default-deny `Authorization`) + `SecurityAsync` (`Authenticator`, `AccountSessionPort`, fail-closed `AuditSink`, `PasswordJobBudget`, `SessionPolicy`, dummy-hash parity, version CAS, `close_and_join`), `SecurityOnly` & `SecurityAsyncOnly` consumers (`713d2dc`) | [M-SECURITY-01-04](tasks/M-SECURITY-01-04.md) | VERIFIED | `SecurityTests` 8 + `SecurityHardening` 4 + `SecurityAsync` 2 = 14/14 (`720.7ms`), `ctest` 2/2 (`8.46s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 14/14 (0 races) | +| M-ARCHIVE-01..05 | Hardened `Archive` (`kArchiveErrorDomain = 17`, streaming `Reader` + forensic listing, file-as-parent conflict rejection, exclusive `0700` `StagedTree` + bottom-up `fsync` + Linux `SYS_renameat2(RENAME_NOREPLACE)` atomic `publish()` with `PublicationOutcome::Unknown`, `cleanup_stale_staging`, reproducible `O_NOFOLLOW` `create_archive`, isolated `VoidArchiveWorker` extraction with rlimits + RSS check + parent inventory verification), `ArchiveOnly` consumer (`00d7478`) | [M-ARCHIVE-01-05](tasks/M-ARCHIVE-01-05.md) | VERIFIED | `Archive` 6 + `ArchiveHardening` 3 = 9/9 (`259.0ms`), `ctest` 2/2 (`5.76s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 9/9 (0 races) | +| M-UPDATE-01..06 | Hardened `Update` (`kUpdateErrorDomain = 20`, schema-3 verify-before-payload-parse fix, `StrictJsonProfile` integer-only option, non-forgeable `VerifiedSelection`, `VersionStore::pruneWithPins`, atomic checksummed `ReplayFloorStore`, Ed25519 `TrustStore` rotation/revocation, `ArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` halting with `RecoveryRequired`, `InstallCoordinator` with staged archive + `CleanupPending` + idempotent `reconcile`/`retry_cleanup`), `UpdateOnly` consumer (`47736cb`) | [M-UPDATE-01-06](tasks/M-UPDATE-01-06.md) | VERIFIED | `Update` 22 + `UpdateHardening` 3 = 25/25 (`1.91s`), `ctest` 2/2 (`10.64s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 25/25 (0 races) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index a3f6f59..fcb3bd3 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -244,3 +244,26 @@ Branch: `feat/roadmap-p2-wave6a` (branched from `main` at `4479960`, which was p | Full Integrated ASan+UBSan (`39a48d5`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6a-asan`, 39 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-asan/tests/VoidTests` | 1,386 tests — 1,383 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (19.34s), 0 ASan/LSan leaks, 0 UBSan errors | | Wave 6A TSan Subset (`39a48d5`) | `dev cpp-gcc -c` Debug (`SystemAsync;IPC;IO;Async;Resilience;Testing`, `/tmp/void-w6a-tsan`, 14 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6a-tsan/tests/VoidTests --filter "Process*\|SystemHardening*\|SystemAsync*\|Ipc*\|FileWatcher*\|IoDriver*\|OperationScope*"` | 35/35 passed (609.4ms: `OperationScope` 5, `IoDriver` 4, `Ipc` 3, `FileWatcher` 5, `Process` 10, `ProcessStream` 3, `SystemHardening` 3, `SystemAsync` 2), 0 TSan data races | | Post-W6A Benchmark (`39a48d5`, `rev=39a48d5c0a72`) | `/tmp/void-w6a-full/benchmarks/VoidFoundationBench --json /tmp/void-w6a-full/post-w6a.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.92ns, `core_uuid_to_string` 17.45ns, `core_hash_fnv1a64_256b` 181.41ns, `core_hash_murmur3_256b` 67.93ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.77ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.61ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 311.16ns, `data_json_serialize_small_object` 162.52ns | + +## StrictJson RFC 8259 Decimal Verification (2026-11-25) + +Branch: `main` (`acd77ee`, pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2. + +| Scope | Command & configuration | Observed outcome | +| --- | --- | --- | +| StrictJson decimals (`acd77ee`) | RelWithDebInfo `-Werror` Data suite & `ctest`, plus Debug ASan+UBSan `-Werror` (`/tmp/void-strictjson-asan`) | RelWithDebInfo: `49/49` (`StrictJson` 6/6), `ctest` 2/2 passed; Debug ASan+UBSan: `49/49` (7.0ms), 0 leaks, 0 UB | + +## Wave 6B / P2 Crypto, Security, Archive, Update Verification (2026-11-25) + +Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2, OpenSSL 3.5.9, libsodium 1.0.22, libarchive 3.8.10, SQLite 3.54.0. + +| Scope | Command & configuration | Observed outcome | +| --- | --- | --- | +| M-CRYPTO-01..05 (`8a1c15f`, `eb42228`) | `Crypto;CryptoAsync;Testing` RelWithDebInfo `-Werror` `-p openssl` `/tmp/void-w6b-crypto` (10 modules, `VoidTests`, `ctest`) | `CryptoHardening` 3 + `CryptoAsync` 2 (+ `Crypto` 3) passed; `ctest` 2/2 passed (`7.22s`, incl. `CryptoOnly` & `CryptoAsyncOnly`) | +| M-SECURITY-01..04 (`713d2dc`) | `Security;SecurityAsync;Testing` RelWithDebInfo `-Werror` `-p libsodium` `/tmp/void-w6b-security` (10 modules, `VoidTests`, `ctest`) | `Security*\|security_*` 14/14 passed (`720.7ms`: `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2); `ctest` 2/2 passed (`8.46s`, incl. `SecurityOnly` & `SecurityAsyncOnly`) | +| M-ARCHIVE-01..05 (`00d7478`) | `Archive;Testing` RelWithDebInfo `-Werror` `-p libarchive` `/tmp/void-w6b-archive` (7 modules, `VoidTests`, `ctest`) | `Archive*\|archive_*` 9/9 passed (`259.0ms`: `Archive` 6, `ArchiveHardening` 3); `ctest` 2/2 passed (`5.76s`, incl. `ArchiveOnly`) | +| M-UPDATE-01..06 (`47736cb`) | `Update;Testing` RelWithDebInfo `-Werror` `-p libarchive -p openssl` `/tmp/void-w6b-update` (12 modules, `VoidTests`, `ctest`) | `Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*` 25/25 passed (`1.91s`: `Update` 22, `UpdateHardening` 3); `ctest` 2/2 passed (`10.64s`, incl. `UpdateOnly`) | +| Full Integrated RelWithDebInfo (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w6b-full`, 41 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w6b-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w6b-full --output-on-failure --timeout 300` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`6.26s`); `ctest`: 2/2 passed (`VoidTests` 7.34s + `VoidInstalledComponentConsumers` 40.73s across 25 consumer runs incl. `CryptoOnly`, `CryptoAsyncOnly`, `SecurityOnly`, `SecurityAsyncOnly`, `ArchiveOnly`, `UpdateOnly`, `RelocatedFoundation`, `RelocatedExternal`, total `48.07s`) | +| Full Integrated ASan+UBSan (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6b-asan`, 41 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w6b-asan/tests/VoidTests` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`21.78s`), 0 ASan/LSan leaks, 0 UBSan errors | +| Wave 6B TSan Subset (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p libsodium` Debug (`CryptoAsync;SecurityAsync;Update;Testing`, `/tmp/void-w6b-tsan`, 20 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6b-tsan/tests/VoidTests --filter "Crypto*\|crypto_*\|Security*\|security_*\|Archive*\|archive_*\|Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*"` | 56/56 passed (`4.86s`: `Archive` 6, `ArchiveHardening` 3, `Crypto` 3, `CryptoHardening` 3, `CryptoAsync` 2, `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2, `Update` 22, `UpdateHardening` 3), 0 TSan data races | +| Post-W6B Benchmark (`47736cb`, `rev=47736cb6ce2f`) | `/tmp/void-w6b-full/benchmarks/VoidFoundationBench --json /tmp/void-w6b-full/post-w6b.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.52ns, `core_uuid_to_string` 16.53ns, `core_hash_fnv1a64_256b` 179.95ns, `core_hash_murmur3_256b` 67.37ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 58.37ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.76ns, `containers_lru_get_put` 21.02ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 333.32ns, `data_json_serialize_small_object` 165.99ns | diff --git a/docs/agent-workflow/tasks/M-ARCHIVE-01-05.md b/docs/agent-workflow/tasks/M-ARCHIVE-01-05.md new file mode 100644 index 0000000..6890dfb --- /dev/null +++ b/docs/agent-workflow/tasks/M-ARCHIVE-01-05.md @@ -0,0 +1,26 @@ +# Archive Streaming Reader, Atomic Staged Publication, Reproducible Creation & Child Isolation +Task ID: M-ARCHIVE-01..05 +Phase: P2 (Wave 6B) +Status: APPROVED +Contracts: C-02, C-03, C-04, C-05, C-06, C-07 + +## 1. Context and baseline +`Void::Archive` preserves the existing incremental `extract(path, destination, ExtractionOptions)` API and anti-traversal/symlink-swap/size-limit tests while adding typed error reporting (`kArchiveErrorDomain = 17`), bounded streaming `Reader` (`open_reader`, `next_entry`, `read_chunk`, `skip_entry`, normal/forensic `list_entries`), atomic staged extraction and no-replace directory publication (`StagedTree`, `extract_staged`, `publish`, `cleanup_stale_staging`), reproducible tar/tar.zstd creation (`create_archive`), and hardened child-process isolated extraction (`extract_staged_isolated`, `run_isolated_worker_main`). + +## 2. Deliverables +- `src/Archive/module.cmake` (`INTERNAL_DEPS Functional Time System`, `EXTERNAL_DEPS LibArchive::LibArchive`). +- `include/Void/Archive/Types.hpp`: `kArchiveErrorDomain = 17`, `ArchiveErrorCode`, `make_archive_error`, `ReadLimits` (10,000 entries, 512 MiB file, 2 GiB total, 1 GiB compressed, 8 MiB metadata, 64 KiB transfer chunk, 4 KiB path, 255B component, 64 components), `EntryInfo`, `ProgressEvent`, `PublicationOutcome`, `PublicationReceipt`, `CreationOptions`, `IsolationOptions` (128 MiB RSS, 60s timeout), `ByteSource`/`ByteSink` + span/vector/file adapters. +- `include/Void/Archive/Archive.hpp`, `src/Archive/Archive.cpp`, `src/Archive/StagedArchive.cpp`: preserve `extract()`; add `Reader`, `list_entries` (normal + opt-in forensic), `StagedTree`, `extract_staged` (exclusive `0700` dir, `O_NOFOLLOW`, `0644`/`0755`, bottom-up dir `fsync`, completion inventory, no-follow cleanup), `publish` via Linux `renameat2(..., RENAME_NOREPLACE)` (`unsupported_capability` on `ENOSYS`/`EINVAL`, `PublicationOutcome::Unknown` on post-rename parent `fsync` failure), `cleanup_stale_staging`, reproducible `create_archive`, and `extract_staged_isolated` / `run_isolated_worker_main` via `Void::Process::spawn` (ASan-safe rlimits + parent verification of staged inventory). +- `tests/helpers/ArchiveWorker.cpp` wired as `VoidArchiveWorker` in `tests/CMakeLists.txt`, `tests/standalone/Archive/ArchiveHardening.cpp`, `tests/package/ArchiveOnly/*`, registered in `tests/package/InstalledComponents.cmake`. + +## 3. Edge cases +- `skip_entry` still decodes and accounts for actual decompressed bytes against per-entry and total limits. +- File-as-parent path conflicts (e.g. file `a` followed by `a/b`, or `a/b` followed by file `a`) and non-zero/zero invalid limits are rejected cleanly. +- Diagnostics cap path rendering at 4 KiB and escape control characters / attacker newlines. +- Post-rename parent `fsync` failure reports `PublicationOutcome::Unknown` without falsely claiming rollback; pre-publish failure cleans only the owned staging descriptor and preserves primary error + staging id if cleanup fails. +- Under `__SANITIZE_ADDRESS__`, child worker avoids fatal `RLIMIT_AS` and enforces `RLIMIT_CPU`/`RLIMIT_FSIZE`/`RLIMIT_NOFILE` + `/proc/self/statm` RSS enforcement. + +## 4. Verification commands +```sh +dev cpp-gcc -p libarchive -c bash -lc 'cmake -S . -B /tmp/void-w6b-archive -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Archive;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-archive && /tmp/void-w6b-archive/tests/VoidTests --filter "Archive*|archive_*" && ctest --test-dir /tmp/void-w6b-archive --output-on-failure --timeout 120' +``` diff --git a/docs/agent-workflow/tasks/M-CRYPTO-01-05.md b/docs/agent-workflow/tasks/M-CRYPTO-01-05.md new file mode 100644 index 0000000..29f2161 --- /dev/null +++ b/docs/agent-workflow/tasks/M-CRYPTO-01-05.md @@ -0,0 +1,26 @@ +# Crypto Hardening, Signing, MAC/KDF & Optional Async Hash Adapter +Task ID: M-CRYPTO-01..05 +Phase: P2 (Wave 6B) +Status: APPROVED +Contracts: C-02, C-03, C-07, C-13 + +## 1. Context and baseline +`Void::Crypto` preserves all 1.x APIs (`Hasher`, `Digest`, `HashAlgorithm`, `hash`, `hashFile`, `sha1`/`sha256`/`sha512`, `sha*File`, `verifyEd25519` exact-byte false-vs-error semantics) while hardening `Hasher` state poisoning (`Ready -> Updating -> Finalized | Failed`), adding per-context OpenSSL 3 `ProviderOptions` (no process-wide provider mutation), typed Ed25519 wrappers (`Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed`, move-only `Ed25519PrivateKey`), `sign_ed25519`, `hmac_sha256`/`hmac_sha256_into`, `hkdf_sha256`, `constant_time_equal`, backend fault injection, and a separate optional `CryptoAsync` module (`hash_stream`, `AsyncFileHasher`) so `Crypto` remains runtime-free. + +## 2. Deliverables +- `src/Crypto/module.cmake` (`INTERNAL_DEPS Functional`, `EXTERNAL_DEPS OpenSSL::Crypto`, `EXCLUDE_HEADERS Void/Crypto/AsyncHash.hpp`) & `src/CryptoAsync/module.cmake` (`INTERNAL_DEPS Crypto IO Async Time Functional`, `EXTRA_HEADERS Void/Crypto/AsyncHash.hpp`). +- `include/Void/Crypto/Types.hpp`: `kCryptoErrorDomain = 18`, `CryptoErrorCode`, `make_crypto_error`, `HasherState`, `ProviderOptions`, `CryptoLimits` (`kMaxOneShotMessageBytes = 16 MiB`, `kMaxHkdfOutputBytes = 4 KiB`, `kStreamChunkBytes = 64 KiB`, `kDefaultMaxConcurrentFileHashes = 8`, `kDefaultMaxWaitingFileHashes = 32`, `kDefaultAsyncBufferBudgetBytes = 8 MiB`), `Ed25519PublicKey`, `Ed25519Signature`, `Ed25519Seed` (with explicit wipe). +- `include/Void/Crypto/Crypto.hpp` & `src/Crypto/Crypto.cpp`: OpenSSL 3 non-deprecated EVP APIs (`EVP_MD_fetch`, `EVP_MAC_fetch`, `EVP_KDF_fetch`, `EVP_PKEY_new_raw_*_ex`, `EVP_DigestSignInit_ex`, `EVP_DigestVerifyInit_ex`, `CRYPTO_memcmp`, `OPENSSL_cleanse`), poisoned `Hasher` + `state()`, `Ed25519PrivateKey` (`generate`, `from_raw_seed`, `public_key`, `export_raw_seed`), `sign_ed25519`, typed `verify_ed25519`, `hmac_sha256`, `hmac_sha256_into`, `hkdf_sha256` (4 KiB cap, overlap rejection, wipe-on-error), `constant_time_equal`, and thread-local/scoped backend fault hook. +- `include/Void/Crypto/AsyncHash.hpp` & `src/CryptoAsync/AsyncHash.cpp`: `hash_stream` (64 KiB `BufferLease` chunks, stop/deadline checks between chunks, clean-EOF-only finalize) and `AsyncFileHasher` (8 concurrent / 32 waiters / 8 MiB buffer budget, `close_and_join`). +- `tests/standalone/Crypto/CryptoHardening.cpp`, `tests/standalone/CryptoAsync/CryptoAsync.cpp`, `tests/package/{CryptoOnly,CryptoAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`. + +## 3. Edge cases +- Invalid key/signature sizes return `invalid_argument` before touching OpenSSL; well-formed invalid Ed25519 signatures return `true`/`false` (not error). +- One-shot `sign_ed25519`/`verify_ed25519` enforce `16 MiB` limit; `hkdf_sha256` rejects zero/oversized (`> 4 KiB`) output and overlapping input/salt/context/output spans, wiping output on failure. +- Backend error during `Hasher::update`/`finalize` transitions state to `Failed`, rejecting further `update`/`finalize` calls. +- `hash_stream` never returns a digest on partial read + error or stop/EOF cancellation race; `AsyncFileHasher::close_and_join` stops admission and drains in-flight work before returning. + +## 4. Verification commands +```sh +dev cpp-gcc -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-crypto -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Crypto;CryptoAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-crypto && /tmp/void-w6b-crypto/tests/VoidTests --filter "Crypto*|crypto_*" && ctest --test-dir /tmp/void-w6b-crypto --output-on-failure --timeout 120' +``` diff --git a/docs/agent-workflow/tasks/M-SECURITY-01-04.md b/docs/agent-workflow/tasks/M-SECURITY-01-04.md new file mode 100644 index 0000000..c048738 --- /dev/null +++ b/docs/agent-workflow/tasks/M-SECURITY-01-04.md @@ -0,0 +1,29 @@ +# Security Hardening, SecureBuffer, Versioned Envelopes, Authorization & Authenticator +Task ID: M-SECURITY-01..04 +Phase: P2 (Wave 6B) +Status: APPROVED +Contracts: C-02, C-03, C-04, C-05, C-07, C-09, C-13 + +## 1. Context and baseline +`Void::Security` preserves all 1.x APIs (`generateToken`, `hashToken`, `verifyToken`, `hashPassword`, `verifyPassword`, `generateSecretKey`, `sealSecret`, `openSecret`) and the exact legacy secret envelope format (`24B nonce || secretbox_easy(16B MAC + ciphertext)`), while adding `SecureBuffer`, input/cost validation (`parse_argon2id_cost`, `verify_password_budgeted`), versioned `VSEC` v1 AEAD envelopes + `SecretKeyRing` rotation, typed default-deny `Authorization`, and a separate `SecurityAsync` module (`Authenticator`, `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget`, `AuditSink`) so primitive `Security` remains free of Async/Resilience/Storage dependencies. + +## 2. Deliverables +- `src/Security/module.cmake` (`INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS Sodium::Sodium`, `EXCLUDE_HEADERS Void/Security/Authenticator.hpp`) & `src/SecurityAsync/module.cmake` (`INTERNAL_DEPS Security Async Time Resilience Functional`, `EXTRA_HEADERS Void/Security/Authenticator.hpp`). +- `include/Void/Security/Types.hpp`: `kSecurityErrorDomain = 19`, `SecurityErrorCode`, `make_security_error`, `SecurityLimits` (1 KiB password/hash, 512 B token, 16 MiB plaintext, 64 roles, 4096 rules, 16 predicate depth), `PasswordVerifyBudget`, `Argon2idCost`. +- `include/Void/Security/SecureBuffer.hpp` & `src/Security/SecureBuffer.cpp`: move-only `SecureBuffer` with `LockPolicy::{StandardWiped, LockedOptional, LockedRequired}` (fail-closed if locked allocation fails), `sodium_memzero` wipe on release/move, optional fault hook. +- `include/Void/Security/Security.hpp` & `src/Security/Security.cpp`: preserve 1.x surface + enforce input caps, `parse_argon2id_cost`, `verify_password_budgeted` rejecting excessive `m`/`t` before Argon2id allocation, backend init/randomness fault seam. +- `include/Void/Security/Envelope.hpp` & `src/Security/Envelope.cpp`: versioned `VSEC` v1 `crypto_aead_xchacha20poly1305_ietf` envelope authenticating header + `key_id` + `aad`, `SecretKeyRing` (active-key writes, multi-key reads, checked retirement), zero silent legacy fallback. +- `include/Void/Security/Authorization.hpp` & `src/Security/Authorization.cpp`: `Principal` (<=64 roles), typed `Predicate` (depth <=16), `PolicySnapshot` (<=4096 rules, default-deny, deny-overrides-allow, `authorize`). +- `include/Void/Security/Authenticator.hpp` & `src/SecurityAsync/Authenticator.cpp`: `AccountSessionPort`, `InMemoryAccountSessionStore`, `PasswordJobBudget` (512 MiB / 2 active / 32 waiters), `SessionPolicy` (10,000 total / 16 per subject / 1h TTL / 60s civil-clock rollback check / 256 cleanup batch), mandatory `AuditSink`, `Authenticator` (dummy-hash timing-work parity, credential-version CAS, non-interruptible drain-on-stop, zero positive session cache, `close_and_join`). +- `tests/standalone/Security/SecurityHardening.cpp`, `tests/standalone/SecurityAsync/SecurityAsync.cpp`, `tests/package/{SecurityOnly,SecurityAsyncOnly}/*`, registered in `tests/package/InstalledComponents.cmake`. + +## 3. Edge cases +- Legacy `sealSecret`/`openSecret` bytes remain bit-for-bit compatible; `Envelope` never guesses legacy decoding after AEAD failure. +- Unknown account and wrong password execute comparable Argon2id work via a precomputed dummy hash and return identical public denial while recording distinct internal audit reasons. +- Cancelling during password verification returns cancelled, retains budget/buffers until the Argon2id job completes, discards output, and never writes a session. +- Civil-clock rollback exceeding configured tolerance (default 60s) fails session admission until reconciled. + +## 4. Verification commands +```sh +dev cpp-gcc -p libsodium -c bash -lc 'cmake -S . -B /tmp/void-w6b-security -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Security;SecurityAsync;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-security && /tmp/void-w6b-security/tests/VoidTests --filter "Security*|security_*" && ctest --test-dir /tmp/void-w6b-security --output-on-failure --timeout 120' +``` diff --git a/docs/agent-workflow/tasks/M-UPDATE-01-06.md b/docs/agent-workflow/tasks/M-UPDATE-01-06.md new file mode 100644 index 0000000..2468563 --- /dev/null +++ b/docs/agent-workflow/tasks/M-UPDATE-01-06.md @@ -0,0 +1,28 @@ +# Update Verify-Before-Parse, Replay Floor, Trust Store, Pinned Pruning & Recoverable Install Coordinator +Task ID: M-UPDATE-01..06 +Phase: P2 (Wave 6B) +Status: APPROVED +Contracts: C-02, C-03, C-04, C-05, C-06, C-07, C-09, C-10 + +## 1. Context and baseline +`Void::Update` preserves existing feed/component verification, readable envelopes, greatest-compatible-version selection, and `VersionStore` durable activation/commit/rollback/reconcile/external-health semantics while fixing the schema-3 verify-before-payload-parse bug in `src/Update/Feed.cpp`, introducing explicit `SchemaParsePolicy` (`LegacyGeneralJson` vs `StrictJsonProfile`), non-forgeable `VerifiedSelection`, durable monotonic `ReplayFloorStore`, explicit `TrustStore` rotation/revocation, pin-aware bounded `VersionStore::pruneWithPins`, checksummed `OperationJournal`, and `InstallCoordinator` integrating `Archive`'s staged atomic publication and `VersionStore`'s single commit boundary. + +## 2. Deliverables +- `src/Update/module.cmake` (`INTERNAL_DEPS Archive Crypto Data Functional System Text Time`). +- `include/Void/Update/Types.hpp`: `kUpdateErrorDomain = 20`, `UpdateErrorCode`, `make_update_error`, `SchemaParsePolicy`, `InstallState`, `ActivationMode`, `ReleaseIdentity`, `InstallReceipt`, `InstallOptions` (1 active, 8 queued, 2 concurrent downloads, 512 MiB artifact, 2 GiB staging quota, 32 components, 256 edges, 10m deadline, 30s readiness, 1s probe interval, 3 consecutive healthy, 2 retained previous, 16 prune batch). +- `include/Void/Update/Feed.hpp` & `src/Update/Feed.cpp`: move `Crypto::verifyEd25519` strictly BEFORE payload JSON parsing/comparison in schema-3 `verifyEnvelope`, support `SchemaParsePolicy::StrictJsonProfile` (integer-only strict JSON via `Void::Json::Strict::ParseOptions{.allowDecimals = false}`), add non-forgeable `VerifiedSelection` + `verify_and_select_release` / `verify_and_select_component_set`. +- `include/Void/Update/VersionStore.hpp` & `src/Update/VersionStore.cpp`: add `PruneReport` and `pruneWithPins(retainedPreviousVersions, pinnedVersions, batchLimit = 16)`. +- `include/Void/Update/Install.hpp` & `src/Update/Install.cpp` (included from `Update.hpp`): `ReplayFloorStore` (atomic via `Void::FileSystem::replace_file`, monotonic across restarts/key rotations/clock rollback), `TrustStore` (bootstrap, authenticated rotation, revocation), `ArtifactTransport` + `LocalFileArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` (`RecoveryRequired` on unknown/corrupt), and `InstallCoordinator` (`install`, idempotent `reconcile`, `retry_cleanup`, `shutdown`). +- `tests/standalone/Update/UpdateHardening.cpp`, `tests/package/UpdateOnly/*`, registered in `tests/package/InstalledComponents.cmake`. + +## 3. Edge cases +- Invalid signature over malformed JSON payload in schema-3 envelopes fails at signature verification without ever invoking payload JSON parsing. +- Replay floor never decreases on restart, key rotation, or civil-clock rollback. +- Post-commit cleanup/prune failures transition receipt to `CleanupPending` with retryable diagnostics and NEVER trigger rollback; calling `rollback` after durable healthy marker preserves the committed candidate. +- Unknown/corrupt operation journal entries halt automation with `RecoveryRequired` without discarding evidence. +- Pinned versions cannot be pruned; prune reports skipped-pin pressure rather than breaking live pins. + +## 4. Verification commands +```sh +dev cpp-gcc -p libarchive -p openssl -c bash -lc 'cmake -S . -B /tmp/void-w6b-update -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DVOID_ENABLED_MODULES="Update;Testing" -DVOID_WARNINGS_AS_ERRORS=ON && cmake --build /tmp/void-w6b-update && /tmp/void-w6b-update/tests/VoidTests --filter "Update*|update_*|component_feed_*|readable_component_*|version_store_*" && ctest --test-dir /tmp/void-w6b-update --output-on-failure --timeout 120' +``` diff --git a/include/Void/Archive/Archive.hpp b/include/Void/Archive/Archive.hpp index f708045..22b4318 100644 --- a/include/Void/Archive/Archive.hpp +++ b/include/Void/Archive/Archive.hpp @@ -1,11 +1,19 @@ #pragma once +#include #include #include +#include #include #include #include +#include +#include +#include +#include +#include +#include namespace Void::Archive { @@ -21,12 +29,176 @@ namespace Void::Archive std::uint64_t bytes{0}; }; - /// Extract a tar/tar.zst archive without invoking an external process. - /// Only regular files and directories are accepted. Absolute/traversal - /// paths, links, special files, duplicates and configured size/count - /// overages fail the whole operation. + /// Extract a tar/tar.zst archive incrementally into `destination` without + /// invoking an external process. Preserved 1.x incremental API; callers + /// requiring all-or-nothing directory visibility should use + /// `extract_staged` + `StagedTree::publish`. [[nodiscard]] Void::Result::Result extract(const std::filesystem::path& archivePath, const std::filesystem::path& destination, const ExtractionOptions& options = {}); + + /// Caller-driven bounded tar/tar.zst reader. Maintains one active entry at + /// a time; callers must drain (`read_chunk` returning 0) or call + /// `skip_entry()` before advancing with `next_entry()`. + class Reader + { + public: + + ~Reader(); + Reader(Reader&&) noexcept; + Reader& operator=(Reader&&) noexcept; + Reader(const Reader&) = delete; + Reader& operator=(const Reader&) = delete; + + [[nodiscard]] static Void::Result::Result open( + ByteSource& source, ReadLimits limits = {}, + std::stop_token stop = {}, + std::optional deadline = + std::nullopt, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + [[nodiscard]] static Void::Result::Result open_file( + const std::filesystem::path& archive_path, + ReadLimits limits = {}, std::stop_token stop = {}, + std::optional deadline = + std::nullopt, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + + /// Advance to the next archive entry. Returns std::nullopt on clean + /// EOF. + [[nodiscard]] Void::Result::Result> + next_entry(); + + /// Read up to dst.size() decompressed bytes of the active regular + /// file entry. Returns 0 on entry EOF. + [[nodiscard]] Void::Result::Result + read_chunk(std::span dst); + + /// Drain and discard remaining bytes of the active entry while + /// still accounting decompressed bytes against policy limits. + [[nodiscard]] Void::Result::Result skip_entry(); + + [[nodiscard]] std::size_t entries_seen() const noexcept; + [[nodiscard]] std::uint64_t total_decompressed_bytes() const noexcept; + [[nodiscard]] std::uint64_t total_compressed_bytes() const noexcept; + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit Reader(std::unique_ptr impl) noexcept; + }; + + /// Bounded metadata listing of archive entries. Normal mode (`forensic = + /// false`) rejects unsafe/duplicate/conflicting entries. Opt-in forensic + /// mode reports rejected entries without writing to disk. + [[nodiscard]] Void::Result::Result> + list_entries(ByteSource& source, ReadLimits limits = {}, + bool forensic = false); + + [[nodiscard]] Void::Result::Result> + list_entries(const std::filesystem::path& archive_path, + ReadLimits limits = {}, bool forensic = false); + + /// Move-only handle owning an unpublished private staging directory beneath + /// a pinned parent directory. Unlinks only names under its staging + /// descriptor without following links if destroyed before publication. + class StagedTree + { + public: + + StagedTree() noexcept = default; + ~StagedTree() noexcept; + StagedTree(StagedTree&&) noexcept; + StagedTree& operator=(StagedTree&&) noexcept; + StagedTree(const StagedTree&) = delete; + StagedTree& operator=(const StagedTree&) = delete; + + [[nodiscard]] bool valid() const noexcept; + [[nodiscard]] bool published() const noexcept; + [[nodiscard]] std::string_view staging_id() const noexcept; + [[nodiscard]] const std::filesystem::path& + staging_root() const noexcept; + [[nodiscard]] const std::filesystem::path& + tree_path() const noexcept; + [[nodiscard]] std::size_t entries() const noexcept; + [[nodiscard]] std::uint64_t bytes() const noexcept; + [[nodiscard]] const std::vector& + inventory() const noexcept; + + /// Publish the staged tree into a previously absent immediate child + /// of the pinned parent directory using atomic no-replace rename + /// (`renameat2(..., RENAME_NOREPLACE)`). Never overwrites existing + /// directories or falls back to a racy existence check. + [[nodiscard]] Void::Result::Result + publish(std::string_view new_child_name); + + /// Explicitly discard an unpublished staging tree. + [[nodiscard]] Void::Result::Result discard(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit StagedTree(std::unique_ptr impl) noexcept; + + friend Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options); + friend Void::Result::Result + extract_staged_isolated( + const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options); + }; + + /// Extract a tar/tar.zst stream into an exclusive 0700 staging directory + /// beneath `parent_directory`, fsync files and directories bottom-up, write + /// a bounded completion inventory, and return an unpublished StagedTree. + [[nodiscard]] Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options = {}); + + [[nodiscard]] Void::Result::Result + extract_staged(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options = {}); + + /// Remove abandoned staging directories under `parent_directory` that carry + /// a valid exclusive operation marker owned by the current user and are at + /// least `min_age` old. Never touches directories without a valid marker. + [[nodiscard]] Void::Result::Result + cleanup_stale_staging(const std::filesystem::path& parent_directory, + std::chrono::seconds min_age = + std::chrono::seconds{300}); + + /// Create a bounded, optionally reproducible tar or tar.zst archive from + /// regular file and directory entries. Sorts normalized paths, rejects + /// duplicates/conflicts, and opens source files with O_NOFOLLOW. + [[nodiscard]] Void::Result::Result + create_archive(ByteSink& sink, std::span entries, + const CreationOptions& options = {}); + + [[nodiscard]] Void::Result::Result + create_archive(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options = {}); + + /// Hardened untrusted-input profile: extracts the archive in an isolated + /// System child process with bounded execution time and RSS checks, then + /// independently verifies the staged tree and inventory in the parent + /// before returning StagedTree. + [[nodiscard]] Void::Result::Result + extract_staged_isolated(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options); + + /// Entry point invoked by the isolated archive decoder worker binary. + [[nodiscard]] int run_isolated_worker_main(int argc, char** argv); + } // namespace Void::Archive diff --git a/include/Void/Archive/Types.hpp b/include/Void/Archive/Types.hpp new file mode 100644 index 0000000..44de549 --- /dev/null +++ b/include/Void/Archive/Types.hpp @@ -0,0 +1,342 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Archive +{ + enum class ArchiveErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + unsafe_entry = 2, + unsupported_format = 3, + corrupt_archive = 4, + limit_exceeded = 5, + permission_denied = 6, + no_space = 7, + io_error = 8, + cancelled = 9, + timeout = 10, + unknown_publication = 11, + unsupported_capability = 12, + already_exists = 13, + conflict = 14, + isolation_failed = 15 + }; + + [[nodiscard]] inline Void::Result::Error + make_archive_error(ArchiveErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case ArchiveErrorCode::none: + kind = ErrorKind::internal; + break; + case ArchiveErrorCode::invalid_argument: + case ArchiveErrorCode::unsafe_entry: + kind = ErrorKind::invalid_argument; + break; + case ArchiveErrorCode::unsupported_format: + case ArchiveErrorCode::unsupported_capability: + kind = ErrorKind::unsupported; + break; + case ArchiveErrorCode::corrupt_archive: + kind = ErrorKind::corrupt; + break; + case ArchiveErrorCode::limit_exceeded: + case ArchiveErrorCode::no_space: + kind = ErrorKind::exhausted; + break; + case ArchiveErrorCode::permission_denied: + case ArchiveErrorCode::io_error: + kind = ErrorKind::io; + break; + case ArchiveErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case ArchiveErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case ArchiveErrorCode::already_exists: + case ArchiveErrorCode::conflict: + kind = ErrorKind::conflict; + break; + case ArchiveErrorCode::unknown_publication: + case ArchiveErrorCode::isolation_failed: + kind = ErrorKind::internal; + break; + } + + const ErrorCode domain_code{Void::Result::kArchiveErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; + } + + /// Render an untrusted archive entry path safely for diagnostics: capped at + /// 4 KiB with control characters and newlines escaped. + [[nodiscard]] std::string + sanitize_diagnostic_path(std::string_view raw) noexcept; + + struct ReadLimits { + std::size_t max_entries{10'000}; + bool allow_zero_entries{false}; + std::uint64_t max_file_bytes{512ULL * 1024 * 1024}; + std::uint64_t max_total_bytes{2ULL * 1024 * 1024 * 1024}; + std::uint64_t max_compressed_bytes{1ULL * 1024 * 1024 * 1024}; + std::size_t max_metadata_bytes{8ULL * 1024 * 1024}; + std::size_t transfer_buffer_bytes{64ULL * 1024}; + std::size_t max_path_bytes{4096}; + std::size_t max_component_bytes{255}; + std::size_t max_path_components{64}; + + [[nodiscard]] Void::Result::Result validate() const + { + if ((max_entries == 0 && !allow_zero_entries) || + max_file_bytes == 0 || max_total_bytes == 0 || + max_compressed_bytes == 0 || max_metadata_bytes == 0 || + transfer_buffer_bytes == 0 || max_path_bytes == 0 || + max_component_bytes == 0 || max_path_components == 0) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::ReadLimits: limits must be non-zero unless " + "allow_zero_entries is explicitly enabled")}; + } + return {}; + } + }; + + enum class EntryType : std::uint8_t { + RegularFile = 0, + Directory, + Symlink, + Hardlink, + Other + }; + + struct EntryInfo { + std::string path{}; + EntryType type{EntryType::RegularFile}; + std::uint64_t declared_size{0}; + std::uint32_t safe_mode{0644}; + bool executable{false}; + bool accepted{true}; + std::string rejection_reason{}; + }; + + struct ProgressEvent { + std::size_t entries_processed{0}; + std::uint64_t bytes_extracted{0}; + std::string current_path{}; + }; + + using ProgressCallback = std::function; + + enum class PublicationOutcome : std::uint8_t { + Published = 0, + NotPublished, + Unknown + }; + + struct PublicationReceipt { + PublicationOutcome outcome{PublicationOutcome::NotPublished}; + std::filesystem::path destination_path{}; + std::string staging_id{}; + std::size_t entries{0}; + std::uint64_t bytes{0}; + std::string diagnostic{}; + }; + + struct StagedExtractionOptions { + ReadLimits limits{}; + bool preserve_executable_bit{true}; + std::stop_token stop{}; + std::optional deadline{}; + const Void::Time::MonotonicClock* clock{nullptr}; + ProgressCallback on_progress{}; + }; + + enum class ArchiveCompression : std::uint8_t { None = 0, Zstd }; + + struct CreationOptions { + ArchiveCompression compression{ArchiveCompression::Zstd}; + bool reproducible{true}; + ReadLimits limits{}; + std::stop_token stop{}; + }; + + struct CreateEntry { + std::string path{}; + EntryType type{EntryType::RegularFile}; + bool executable{false}; + std::vector content{}; + std::optional source_file{}; + }; + + struct IsolationOptions { + std::filesystem::path worker_executable{}; + std::uint64_t max_rss_bytes{128ULL * 1024 * 1024}; + std::chrono::milliseconds timeout{std::chrono::seconds{60}}; + StagedExtractionOptions extraction{}; + }; + + /// Synchronous byte source interface borrowed through completion. + class ByteSource + { + public: + + virtual ~ByteSource() = default; + /// Read up to dst.size() bytes. Returns 0 on clean EOF. + [[nodiscard]] virtual Void::Result::Result + read(std::span dst) = 0; + }; + + /// Synchronous byte sink interface borrowed through completion. + class ByteSink + { + public: + + virtual ~ByteSink() = default; + [[nodiscard]] virtual Void::Result::Result + write(std::span src) = 0; + }; + + class SpanByteSource final : public ByteSource + { + public: + + explicit SpanByteSource(std::span data) noexcept + : m_data(data) + { + } + + [[nodiscard]] Void::Result::Result + read(std::span dst) override; + + private: + + std::span m_data{}; + std::size_t m_offset{0}; + }; + + class FileByteSource final : public ByteSource + { + public: + + [[nodiscard]] static Void::Result::Result + open(const std::filesystem::path& path); + + FileByteSource(FileByteSource&&) noexcept; + FileByteSource& operator=(FileByteSource&&) noexcept; + ~FileByteSource() override; + + FileByteSource(const FileByteSource&) = delete; + FileByteSource& operator=(const FileByteSource&) = delete; + + [[nodiscard]] Void::Result::Result + read(std::span dst) override; + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit FileByteSource(std::unique_ptr impl) noexcept; + }; + + class VectorByteSink final : public ByteSink + { + public: + + explicit VectorByteSink( + std::size_t max_bytes = 256ULL * 1024 * 1024) noexcept + : m_max_bytes(max_bytes) + { + } + + [[nodiscard]] Void::Result::Result + write(std::span src) override; + + [[nodiscard]] const std::vector& bytes() const noexcept + { + return m_bytes; + } + [[nodiscard]] std::vector take_bytes() noexcept + { + return std::move(m_bytes); + } + + private: + + std::size_t m_max_bytes{256ULL * 1024 * 1024}; + std::vector m_bytes{}; + }; + + class FileByteSink final : public ByteSink + { + public: + + [[nodiscard]] static Void::Result::Result + create(const std::filesystem::path& path); + + FileByteSink(FileByteSink&&) noexcept; + FileByteSink& operator=(FileByteSink&&) noexcept; + ~FileByteSink() override; + + FileByteSink(const FileByteSink&) = delete; + FileByteSink& operator=(const FileByteSink&) = delete; + + [[nodiscard]] Void::Result::Result + write(std::span src) override; + [[nodiscard]] Void::Result::Result sync_and_close(); + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit FileByteSink(std::unique_ptr impl) noexcept; + }; + + enum class FaultPoint : std::uint8_t { + none = 0, + rename_enosys, + post_rename_parent_sync, + staging_cleanup_fail + }; + + class ScopedFaultGuard + { + public: + + explicit ScopedFaultGuard(FaultPoint point) noexcept; + ~ScopedFaultGuard() noexcept; + + ScopedFaultGuard(const ScopedFaultGuard&) = delete; + ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete; + ScopedFaultGuard(ScopedFaultGuard&&) = delete; + ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete; + + private: + + FaultPoint m_previous{FaultPoint::none}; + }; + +} // namespace Void::Archive diff --git a/include/Void/Crypto/AsyncHash.hpp b/include/Void/Crypto/AsyncHash.hpp new file mode 100644 index 0000000..5632b3e --- /dev/null +++ b/include/Void/Crypto/AsyncHash.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::CryptoAsync +{ + struct StreamHashOptions { + std::size_t chunk_bytes{ + Void::Crypto::CryptoLimits::kStreamChunkBytes}; + Void::Crypto::ProviderOptions provider{}; + }; + + /// Incrementally hash an IO::ByteStream using a Driver-owned BufferLease + /// (default 64 KiB). Checks stop/deadline between chunks and finalizes only + /// on clean EOF without cancellation. + [[nodiscard]] Void::Coro::Task> + hash_stream(Void::Crypto::HashAlgorithm algorithm, + Void::IO::Driver& driver, Void::IO::ByteStream& stream, + Void::Async::OperationOptions options = {}, + StreamHashOptions hash_options = {}); + + struct FileHasherOptions { + std::size_t max_concurrent{ + Void::Crypto::CryptoLimits::kDefaultMaxConcurrentFileHashes}; + std::size_t max_waiting{ + Void::Crypto::CryptoLimits::kDefaultMaxWaitingFileHashes}; + std::size_t buffer_budget_bytes{ + Void::Crypto::CryptoLimits::kDefaultAsyncBufferBudgetBytes}; + std::size_t chunk_bytes{ + Void::Crypto::CryptoLimits::kStreamChunkBytes}; + Void::Crypto::ProviderOptions provider{}; + }; + + struct FileHasherStats { + std::size_t active{0}; + std::size_t waiting{0}; + std::size_t reserved_buffer_bytes{0}; + std::uint64_t completed{0}; + std::uint64_t rejected{0}; + bool closing{false}; + }; + + /// Bounded asynchronous file-hashing service with concurrency, queue, and + /// owned buffer-budget limits plus explicit stop/join shutdown. + class AsyncFileHasher + { + public: + + explicit AsyncFileHasher( + Void::Async::Executor& executor, + FileHasherOptions options = {}, + const Void::Time::MonotonicClock& clock = + Void::Time::SystemMonotonicClock::instance()); + ~AsyncFileHasher(); + + AsyncFileHasher(const AsyncFileHasher&) = delete; + AsyncFileHasher& operator=(const AsyncFileHasher&) = delete; + AsyncFileHasher(AsyncFileHasher&&) = delete; + AsyncFileHasher& operator=(AsyncFileHasher&&) = delete; + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + hash_file(Void::Crypto::HashAlgorithm algorithm, + std::filesystem::path path, + Void::Async::OperationOptions options = {}); + + void request_stop() noexcept; + + [[nodiscard]] Void::Result::Result close_and_join(); + + [[nodiscard]] FileHasherStats stats() const noexcept; + + private: + + struct State; + std::shared_ptr m_state; + }; + +} // namespace Void::CryptoAsync diff --git a/include/Void/Crypto/Crypto.hpp b/include/Void/Crypto/Crypto.hpp index 9fa0658..caecfbc 100644 --- a/include/Void/Crypto/Crypto.hpp +++ b/include/Void/Crypto/Crypto.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -21,18 +22,23 @@ namespace Void::Crypto [[nodiscard]] static Void::Result::Result create(HashAlgorithm algorithm); + [[nodiscard]] static Void::Result::Result + create(HashAlgorithm algorithm, + const ProviderOptions& provider); ~Hasher(); Hasher(Hasher&&) noexcept; Hasher& operator=(Hasher&&) noexcept; Hasher(const Hasher&) = delete; Hasher& operator=(const Hasher&) = delete; + [[nodiscard]] HasherState state() const noexcept; + [[nodiscard]] Void::Result::Result update(std::span data); [[nodiscard]] Void::Result::Result update(std::string_view data); /// Finalize this hash. Calling finalize or update again is an - /// error. + /// error. Backend update/finalize failures poison the hasher. [[nodiscard]] Void::Result::Result finalize(); private: @@ -44,10 +50,16 @@ namespace Void::Crypto [[nodiscard]] Void::Result::Result hash(HashAlgorithm algorithm, std::span data); + [[nodiscard]] Void::Result::Result + hash(HashAlgorithm algorithm, std::span data, + const ProviderOptions& provider); [[nodiscard]] Void::Result::Result hash(HashAlgorithm algorithm, std::string_view data); [[nodiscard]] Void::Result::Result hashFile(HashAlgorithm algorithm, const std::filesystem::path& path); + [[nodiscard]] Void::Result::Result + hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, + const ProviderOptions& provider); [[nodiscard]] Void::Result::Result sha1(std::span data); @@ -65,14 +77,89 @@ namespace Void::Crypto [[nodiscard]] Void::Result::Result sha512File(const std::filesystem::path& path); - inline constexpr std::size_t Ed25519PublicKeySize = 32; - inline constexpr std::size_t Ed25519SignatureSize = 64; + /// Move-only owning Ed25519 private key handle. Has no implicit copy, + /// string conversion, or secret formatting. + class Ed25519PrivateKey + { + public: + + Ed25519PrivateKey() noexcept = default; + ~Ed25519PrivateKey(); + Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept; + Ed25519PrivateKey& operator=(Ed25519PrivateKey&&) noexcept; + Ed25519PrivateKey(const Ed25519PrivateKey&) = delete; + Ed25519PrivateKey& operator=(const Ed25519PrivateKey&) = delete; + + [[nodiscard]] static Void::Result::Result + generate(const ProviderOptions& provider = {}); + + [[nodiscard]] static Void::Result::Result + from_raw_seed(std::span seed, + const ProviderOptions& provider = {}); + + [[nodiscard]] bool valid() const noexcept; + + [[nodiscard]] Void::Result::Result + public_key() const; + + /// Explicit secret export into a move-only self-wiping seed handle. + [[nodiscard]] Void::Result::Result + export_raw_seed() const; + + private: + + struct Impl; + std::unique_ptr m_impl; + explicit Ed25519PrivateKey(std::unique_ptr impl) noexcept; + + friend Void::Result::Result + sign_ed25519(std::span message, + const Ed25519PrivateKey& private_key, + const ProviderOptions& provider); + }; + + /// Sign exact message bytes (up to CryptoLimits::kMaxOneShotMessageBytes) + /// with an owning Ed25519 private key. + [[nodiscard]] Void::Result::Result + sign_ed25519(std::span message, + const Ed25519PrivateKey& private_key, + const ProviderOptions& provider = {}); /// Verify an Ed25519 detached signature over the exact message bytes. - /// Invalid key/signature sizes are errors; a well-formed but invalid - /// signature returns false. + /// Invalid key/signature sizes or oversized messages are errors; a + /// well-formed but invalid signature returns false. [[nodiscard]] Void::Result::Result verifyEd25519(std::span message, std::span signature, std::span publicKey); + + [[nodiscard]] Void::Result::Result + verify_ed25519(std::span message, + const Ed25519Signature& signature, + const Ed25519PublicKey& public_key, + const ProviderOptions& provider = {}); + + /// Compute HMAC-SHA-256 into a caller-owned 32-byte buffer. + /// Wipes output on backend failure and rejects overlapping buffers. + [[nodiscard]] Void::Result::Result + hmac_sha256_into(std::span secret_key, + std::span message, + std::span output, + const ProviderOptions& provider = {}); + + [[nodiscard]] Void::Result::Result + hmac_sha256(std::span secret_key, + std::span message, + const ProviderOptions& provider = {}); + + /// Derive key material with RFC 5869 HKDF-SHA-256 into a caller-owned + /// buffer (1..CryptoLimits::kMaxHkdfOutputBytes). Rejects overlapping + /// buffers and wipes secret_output on any failure after validation. + [[nodiscard]] Void::Result::Result + hkdf_sha256(std::span secret_input, + std::span salt, + std::span context, + std::span secret_output, + const ProviderOptions& provider = {}); + } // namespace Void::Crypto diff --git a/include/Void/Crypto/Types.hpp b/include/Void/Crypto/Types.hpp new file mode 100644 index 0000000..cd205a4 --- /dev/null +++ b/include/Void/Crypto/Types.hpp @@ -0,0 +1,287 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Crypto +{ + inline constexpr std::size_t Ed25519PublicKeySize = 32; + inline constexpr std::size_t Ed25519SignatureSize = 64; + inline constexpr std::size_t Ed25519SeedSize = 32; + inline constexpr std::size_t HmacSha256Size = 32; + + struct CryptoLimits { + static constexpr std::size_t kMaxOneShotMessageBytes = + 16ULL * 1024ULL * 1024ULL; + static constexpr std::size_t kMaxHkdfOutputBytes = 4ULL * 1024ULL; + static constexpr std::size_t kStreamChunkBytes = 64ULL * 1024ULL; + static constexpr std::size_t kDefaultMaxConcurrentFileHashes = 8; + static constexpr std::size_t kDefaultMaxWaitingFileHashes = 32; + static constexpr std::size_t kDefaultAsyncBufferBudgetBytes = + 8ULL * 1024ULL * 1024ULL; + }; + + enum class CryptoErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + invalid_key_size = 2, + invalid_signature_size = 3, + message_too_large = 4, + output_too_large = 5, + overlapping_buffers = 6, + invalid_state = 7, + unsupported_algorithm = 8, + provider_error = 9, + backend_error = 10, + io_error = 11, + cancelled = 12, + timeout = 13, + overloaded = 14, + resource_exhausted = 15, + closed = 16 + }; + + [[nodiscard]] inline Void::Result::Error + make_crypto_error(CryptoErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case CryptoErrorCode::none: + kind = ErrorKind::internal; + break; + case CryptoErrorCode::invalid_argument: + case CryptoErrorCode::invalid_key_size: + case CryptoErrorCode::invalid_signature_size: + case CryptoErrorCode::message_too_large: + case CryptoErrorCode::output_too_large: + case CryptoErrorCode::overlapping_buffers: + kind = ErrorKind::invalid_argument; + break; + case CryptoErrorCode::invalid_state: + kind = ErrorKind::conflict; + break; + case CryptoErrorCode::unsupported_algorithm: + kind = ErrorKind::unsupported; + break; + case CryptoErrorCode::provider_error: + case CryptoErrorCode::backend_error: + kind = ErrorKind::internal; + break; + case CryptoErrorCode::io_error: + kind = ErrorKind::io; + break; + case CryptoErrorCode::cancelled: + case CryptoErrorCode::closed: + kind = ErrorKind::cancelled; + break; + case CryptoErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case CryptoErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case CryptoErrorCode::resource_exhausted: + kind = ErrorKind::exhausted; + break; + } + + const ErrorCode domain_code{Void::Result::kCryptoErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; + } + + enum class HasherState : std::uint8_t { + Ready = 0, + Updating, + Finalized, + Failed, + MovedFrom + }; + + /// Per-operation OpenSSL 3 provider selection. Never mutates process-wide + /// provider state. + struct ProviderOptions { + std::string property_query{}; + }; + + struct Ed25519PublicKey { + std::array bytes{}; + + [[nodiscard]] std::span view() const noexcept + { + return bytes; + } + + [[nodiscard]] static Void::Result::Result + from_bytes(std::span raw) + { + if (raw.size() != Ed25519PublicKeySize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_key_size, + "Ed25519PublicKey requires exactly 32 bytes")}; + } + Ed25519PublicKey key; + for (std::size_t i = 0; i < Ed25519PublicKeySize; ++i) { + key.bytes[i] = raw[i]; + } + return key; + } + + [[nodiscard]] constexpr bool + operator==(const Ed25519PublicKey&) const noexcept = default; + }; + + struct Ed25519Signature { + std::array bytes{}; + + [[nodiscard]] std::span view() const noexcept + { + return bytes; + } + + [[nodiscard]] static Void::Result::Result + from_bytes(std::span raw) + { + if (raw.size() != Ed25519SignatureSize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_signature_size, + "Ed25519Signature requires exactly 64 bytes")}; + } + Ed25519Signature sig; + for (std::size_t i = 0; i < Ed25519SignatureSize; ++i) { + sig.bytes[i] = raw[i]; + } + return sig; + } + + [[nodiscard]] constexpr bool + operator==(const Ed25519Signature&) const noexcept = default; + }; + + /// Securely wipe a mutable byte buffer using the crypto backend's + /// non-elidable cleanse routine. + void secure_wipe(std::span buffer) noexcept; + + /// Constant-time equality comparison for equal-length digests/MACs. + [[nodiscard]] bool + constant_time_equal(std::span lhs, + std::span rhs) noexcept; + + /// Move-only 32-byte Ed25519 raw seed cleared on release. + class Ed25519Seed + { + public: + + Ed25519Seed() noexcept = default; + ~Ed25519Seed() noexcept { clear(); } + + Ed25519Seed(Ed25519Seed&& other) noexcept + : m_bytes(other.m_bytes), m_valid(other.m_valid) + { + other.clear(); + } + + Ed25519Seed& operator=(Ed25519Seed&& other) noexcept + { + if (this != &other) { + clear(); + m_bytes = other.m_bytes; + m_valid = other.m_valid; + other.clear(); + } + return *this; + } + + Ed25519Seed(const Ed25519Seed&) = delete; + Ed25519Seed& operator=(const Ed25519Seed&) = delete; + + [[nodiscard]] static Void::Result::Result + from_bytes(std::span raw) + { + if (raw.size() != Ed25519SeedSize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_key_size, + "Ed25519Seed requires exactly 32 bytes")}; + } + Ed25519Seed seed; + for (std::size_t i = 0; i < Ed25519SeedSize; ++i) { + seed.m_bytes[i] = raw[i]; + } + seed.m_valid = true; + return seed; + } + + [[nodiscard]] bool valid() const noexcept { return m_valid; } + + [[nodiscard]] std::span view() const noexcept + { + return m_valid ? std::span{m_bytes} + : std::span{}; + } + + void clear() noexcept + { + secure_wipe(m_bytes); + m_valid = false; + } + + private: + + std::array m_bytes{}; + bool m_valid{false}; + }; + + enum class FaultOperation : std::uint8_t { + none = 0, + any, + hash_create, + hash_update, + hash_finalize, + ed25519_keygen, + ed25519_import, + ed25519_sign, + ed25519_verify, + hmac, + hkdf + }; + + struct FaultConfig { + FaultOperation op{FaultOperation::none}; + CryptoErrorCode code{CryptoErrorCode::provider_error}; + std::size_t fail_after{0}; + }; + + /// RAII thread-local backend fault injection guard for deterministic + /// provider/backend failure testing. + class ScopedFaultGuard + { + public: + + explicit ScopedFaultGuard(FaultConfig config) noexcept; + ~ScopedFaultGuard() noexcept; + + ScopedFaultGuard(const ScopedFaultGuard&) = delete; + ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete; + ScopedFaultGuard(ScopedFaultGuard&&) = delete; + ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete; + + private: + + FaultConfig m_previous{}; + std::size_t m_previous_hits{0}; + }; + +} // namespace Void::Crypto diff --git a/include/Void/Security/Authenticator.hpp b/include/Void/Security/Authenticator.hpp new file mode 100644 index 0000000..0efe617 --- /dev/null +++ b/include/Void/Security/Authenticator.hpp @@ -0,0 +1,353 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SecurityAsync +{ + struct AccountRecord { + std::string subject{}; + std::string normalized_username{}; + std::string password_hash{}; + std::vector roles{}; + std::uint64_t credential_version{1}; + std::uint64_t revocation_generation{1}; + std::uint64_t policy_generation{1}; + bool enabled{true}; + }; + + struct SessionRecord { + std::string session_id{}; + std::string token_digest{}; + std::string subject{}; + std::vector roles{}; + std::uint64_t credential_version{1}; + std::uint64_t revocation_generation{1}; + std::uint64_t policy_generation{1}; + Void::Time::CivilClock::time_point created_at{}; + Void::Time::CivilClock::time_point expires_at{}; + bool revoked{false}; + }; + + class AccountSessionPort + { + public: + + virtual ~AccountSessionPort() = default; + + [[nodiscard]] virtual Void::Result::Result< + std::optional> + find_account_by_username( + std::string_view normalized_username) = 0; + + [[nodiscard]] virtual Void::Result::Result< + std::optional> + find_account_by_subject(std::string_view subject) = 0; + + [[nodiscard]] virtual Void::Result::Result + update_password_hash_if_version( + std::string_view subject, + std::uint64_t expected_credential_version, + std::string new_password_hash) = 0; + + [[nodiscard]] virtual Void::Result::Result + create_session_if_version( + const SessionRecord& session, + std::uint64_t expected_credential_version, + std::size_t max_total_sessions, + std::size_t max_per_subject, + Void::Time::CivilClock::time_point now) = 0; + + [[nodiscard]] virtual Void::Result::Result< + std::optional> + find_session_by_token_digest(std::string_view token_digest) = 0; + + [[nodiscard]] virtual Void::Result::Result + revoke_session(std::string_view session_id) = 0; + + [[nodiscard]] virtual Void::Result::Result + cleanup_expired_sessions( + Void::Time::CivilClock::time_point now, + std::size_t batch_limit) = 0; + }; + + class InMemoryAccountSessionStore final : public AccountSessionPort + { + public: + + [[nodiscard]] Void::Result::Result + upsert_account(AccountRecord account); + + [[nodiscard]] Void::Result::Result + bump_credential_version(std::string_view subject, + std::string new_password_hash = {}); + + [[nodiscard]] Void::Result::Result + set_account_enabled(std::string_view subject, bool enabled); + + [[nodiscard]] Void::Result::Result + bump_revocation_generation(std::string_view subject); + + void set_available(bool available) noexcept; + [[nodiscard]] std::size_t session_count() const; + + [[nodiscard]] Void::Result::Result> + find_account_by_username( + std::string_view normalized_username) override; + + [[nodiscard]] Void::Result::Result> + find_account_by_subject(std::string_view subject) override; + + [[nodiscard]] Void::Result::Result + update_password_hash_if_version( + std::string_view subject, + std::uint64_t expected_credential_version, + std::string new_password_hash) override; + + [[nodiscard]] Void::Result::Result create_session_if_version( + const SessionRecord& session, + std::uint64_t expected_credential_version, + std::size_t max_total_sessions, std::size_t max_per_subject, + Void::Time::CivilClock::time_point now) override; + + [[nodiscard]] Void::Result::Result> + find_session_by_token_digest( + std::string_view token_digest) override; + + [[nodiscard]] Void::Result::Result + revoke_session(std::string_view session_id) override; + + [[nodiscard]] Void::Result::Result + cleanup_expired_sessions(Void::Time::CivilClock::time_point now, + std::size_t batch_limit) override; + + private: + + mutable std::mutex m_mu{}; + bool m_available{true}; + std::map> + m_accounts_by_subject{}; + std::map> + m_subject_by_username{}; + std::map> + m_sessions_by_id{}; + std::map> + m_session_id_by_digest{}; + }; + + struct AuditEvent { + std::string event_type{}; + std::string subject{}; + std::string internal_reason{}; + bool success{false}; + Void::Time::CivilClock::time_point timestamp{}; + }; + + class AuditSink + { + public: + + virtual ~AuditSink() = default; + [[nodiscard]] virtual Void::Result::Result + record(const AuditEvent& event) = 0; + }; + + class InMemoryAuditSink final : public AuditSink + { + public: + + explicit InMemoryAuditSink(std::size_t max_events = 1024) noexcept + : m_max_events(max_events) + { + } + + [[nodiscard]] Void::Result::Result + record(const AuditEvent& event) override; + + [[nodiscard]] std::vector snapshot() const; + void clear(); + + private: + + std::size_t m_max_events{1024}; + mutable std::mutex m_mu{}; + std::vector m_events{}; + }; + + enum class AuditFailurePolicy : std::uint8_t { + FailClosed = 0, + BestEffort + }; + + struct PasswordJobBudget { + std::size_t max_memory_bytes{ + Void::Security::SecurityLimits:: + kDefaultPasswordJobMemoryBudgetBytes}; + std::size_t max_concurrent_jobs{ + Void::Security::SecurityLimits:: + kDefaultMaxConcurrentPasswordJobs}; + std::size_t max_waiters{ + Void::Security::SecurityLimits::kDefaultMaxWaitingPasswordJobs}; + }; + + struct SessionPolicy { + std::chrono::seconds ttl{ + Void::Security::SecurityLimits::kDefaultSessionTtl}; + std::size_t max_total_sessions{ + Void::Security::SecurityLimits::kDefaultMaxTotalSessions}; + std::size_t max_per_subject{ + Void::Security::SecurityLimits::kDefaultMaxSessionsPerSubject}; + std::chrono::seconds clock_rollback_tolerance{ + Void::Security::SecurityLimits:: + kDefaultClockRollbackTolerance}; + std::size_t expiry_cleanup_batch{ + Void::Security::SecurityLimits::kDefaultExpiryCleanupBatch}; + }; + + struct AuthenticatorOptions { + SessionPolicy session{}; + PasswordJobBudget password_budget{}; + Void::Security::PasswordVerifyBudget verify_budget{}; + Void::Security::PasswordHashStrength dummy_hash_strength{ + Void::Security::PasswordHashStrength::Moderate}; + std::string precomputed_dummy_hash{}; + AuditFailurePolicy audit_policy{AuditFailurePolicy::FailClosed}; + Void::Resilience::KeyedBucketConfig rate_limit{ + .capacity = 20.0, + .refill_per_second = 5.0, + .max_keys = 4096, + .max_key_bytes = 256, + }; + std::optional + last_known_civil_time{}; + Void::Security::LockPolicy secret_lock_policy{ + Void::Security::LockPolicy::StandardWiped}; + std::function before_password_verify_hook{}; + }; + + class BearerToken + { + public: + + BearerToken() noexcept = default; + BearerToken(BearerToken&&) noexcept = default; + BearerToken& operator=(BearerToken&&) noexcept = default; + BearerToken(const BearerToken&) = delete; + BearerToken& operator=(const BearerToken&) = delete; + + [[nodiscard]] static Void::Result::Result + from_string(std::string_view raw, + Void::Security::LockPolicy policy = + Void::Security::LockPolicy::StandardWiped); + + [[nodiscard]] std::string_view expose_secret() const noexcept + { + return m_buf.string_view(); + } + + [[nodiscard]] bool empty() const noexcept { return m_buf.empty(); } + void clear() noexcept { m_buf.clear(); } + + private: + + explicit BearerToken(Void::Security::SecureBuffer buf) noexcept + : m_buf(std::move(buf)) + { + } + + Void::Security::SecureBuffer m_buf{}; + friend class Authenticator; + }; + + struct LoginInput { + std::string username{}; + std::string password{}; + }; + + struct SessionGrant { + std::string session_id{}; + BearerToken bearer_token{}; + Void::Time::CivilClock::time_point expires_at{}; + Void::Security::Principal principal{}; + }; + + struct AuthenticatorStats { + std::size_t active_password_jobs{0}; + std::size_t waiting_password_jobs{0}; + std::size_t reserved_password_memory_bytes{0}; + bool closing{false}; + }; + + class Authenticator + { + public: + + [[nodiscard]] static Void::Result::Result< + std::unique_ptr> + create(std::shared_ptr port, + Void::Async::Executor& executor, + AuthenticatorOptions options = {}, + std::shared_ptr audit_sink = {}, + const Void::Time::MonotonicClock& monotonic_clock = + Void::Time::SystemMonotonicClock::instance(), + const Void::Time::CivilClock& civil_clock = + Void::Time::SystemCivilClock::instance()); + + ~Authenticator(); + Authenticator(const Authenticator&) = delete; + Authenticator& operator=(const Authenticator&) = delete; + Authenticator(Authenticator&&) = delete; + Authenticator& operator=(Authenticator&&) = delete; + + [[nodiscard]] Void::Coro::Task> + login(LoginInput input, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task< + Void::Result::Result> + authenticate(const BearerToken& token, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Coro::Task> + revoke(std::string session_id, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + cleanup_expired_step(); + + void reconcile_clock( + Void::Time::CivilClock::time_point new_watermark) noexcept; + + void request_stop() noexcept; + [[nodiscard]] Void::Result::Result close_and_join(); + + [[nodiscard]] AuthenticatorStats stats() const noexcept; + + private: + + struct State; + explicit Authenticator(std::shared_ptr state) noexcept; + std::shared_ptr m_state; + }; + +} // namespace Void::SecurityAsync diff --git a/include/Void/Security/Authorization.hpp b/include/Void/Security/Authorization.hpp new file mode 100644 index 0000000..8dd22e4 --- /dev/null +++ b/include/Void/Security/Authorization.hpp @@ -0,0 +1,170 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Security +{ + struct Principal { + std::string subject{}; + std::vector roles{}; + std::uint64_t policy_generation{0}; + std::map> attributes{}; + }; + + struct ResourceAttributes { + std::string resource_type{}; + std::string resource_id{}; + std::map> attributes{}; + }; + + enum class Effect : std::uint8_t { Deny = 0, Allow = 1 }; + + /// Native typed policy predicate AST with bounded depth (<= 16) and zero + /// script/filesystem/network side effects. + struct Predicate { + enum class Kind : std::uint8_t { + AlwaysTrue = 0, + AlwaysFalse, + HasRole, + SubjectEquals, + ResourceTypeEquals, + ResourceIdEquals, + ResourceAttrEquals, + PrincipalAttrEquals, + ResourceOwnerMatchesSubject, + AllOf, + AnyOf, + Not + }; + + Kind kind{Kind::AlwaysFalse}; + std::string key{}; + std::string value{}; + std::vector children{}; + + [[nodiscard]] static Predicate always_true() + { + return Predicate{.kind = Kind::AlwaysTrue}; + } + [[nodiscard]] static Predicate always_false() + { + return Predicate{.kind = Kind::AlwaysFalse}; + } + [[nodiscard]] static Predicate has_role(std::string role) + { + return Predicate{.kind = Kind::HasRole, + .value = std::move(role)}; + } + [[nodiscard]] static Predicate subject_equals(std::string subject) + { + return Predicate{.kind = Kind::SubjectEquals, + .value = std::move(subject)}; + } + [[nodiscard]] static Predicate resource_type(std::string type) + { + return Predicate{.kind = Kind::ResourceTypeEquals, + .value = std::move(type)}; + } + [[nodiscard]] static Predicate resource_id(std::string id) + { + return Predicate{.kind = Kind::ResourceIdEquals, + .value = std::move(id)}; + } + [[nodiscard]] static Predicate resource_attr(std::string k, + std::string v) + { + return Predicate{.kind = Kind::ResourceAttrEquals, + .key = std::move(k), + .value = std::move(v)}; + } + [[nodiscard]] static Predicate principal_attr(std::string k, + std::string v) + { + return Predicate{.kind = Kind::PrincipalAttrEquals, + .key = std::move(k), + .value = std::move(v)}; + } + [[nodiscard]] static Predicate + owner_is_subject(std::string owner_attr = "owner") + { + return Predicate{.kind = Kind::ResourceOwnerMatchesSubject, + .key = std::move(owner_attr)}; + } + [[nodiscard]] static Predicate all_of(std::vector items) + { + return Predicate{.kind = Kind::AllOf, + .children = std::move(items)}; + } + [[nodiscard]] static Predicate any_of(std::vector items) + { + return Predicate{.kind = Kind::AnyOf, + .children = std::move(items)}; + } + [[nodiscard]] static Predicate negate(Predicate child) + { + Predicate p{.kind = Kind::Not}; + p.children.push_back(std::move(child)); + return p; + } + }; + + struct PolicyRule { + std::string id{}; + Effect effect{Effect::Deny}; + std::string action{}; + Predicate condition{Predicate::always_false()}; + }; + + struct Decision { + bool allowed{false}; + std::string matched_rule_id{}; + std::string reason{}; + std::uint64_t policy_generation{0}; + }; + + /// Immutable validated authorization policy snapshot. + /// Enforces default-deny and deny-overrides-allow with bounded rules + /// (<= 4096), roles (<= 64), and predicate nesting depth (<= 16). + class PolicySnapshot + { + public: + + [[nodiscard]] static Void::Result::Result + create(std::uint64_t generation, std::vector rules); + + [[nodiscard]] std::uint64_t generation() const noexcept + { + return m_generation; + } + + [[nodiscard]] std::size_t rule_count() const noexcept + { + return m_rules.size(); + } + + [[nodiscard]] Decision + authorize(const Principal& principal, std::string_view action, + const ResourceAttributes& resource) const; + + private: + + PolicySnapshot(std::uint64_t generation, + std::vector rules) noexcept + : m_generation(generation), m_rules(std::move(rules)) + { + } + + std::uint64_t m_generation{0}; + std::vector m_rules{}; + }; + +} // namespace Void::Security diff --git a/include/Void/Security/Envelope.hpp b/include/Void/Security/Envelope.hpp new file mode 100644 index 0000000..834ea01 --- /dev/null +++ b/include/Void/Security/Envelope.hpp @@ -0,0 +1,90 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Security +{ + inline constexpr std::uint8_t kEnvelopeVersionV1 = 1; + inline constexpr std::uint8_t kEnvelopeAlgXChaCha20Poly1305Ietf = 1; + inline constexpr std::size_t kEnvelopeKeyBytes = 32; + inline constexpr std::size_t kEnvelopeNonceBytes = 24; + inline constexpr std::size_t kEnvelopeTagBytes = 16; + + struct EnvelopeHeader { + std::uint8_t version{kEnvelopeVersionV1}; + std::uint8_t algorithm{kEnvelopeAlgXChaCha20Poly1305Ietf}; + std::string key_id{}; + std::uint32_t plaintext_size{0}; + }; + + /// Parse and validate a versioned VSEC envelope header without decrypting. + /// Never falls back to legacy seal_secret framing. + [[nodiscard]] Void::Result::Result + inspect_envelope(std::span envelope); + + /// Versioned AEAD key ring supporting key rotation: writes use the single + /// active key ID, reads resolve the key ID authenticated in the header, and + /// retirement requires proving no ciphertext still depends on that key ID. + class SecretKeyRing + { + public: + + SecretKeyRing() = default; + SecretKeyRing(SecretKeyRing&&) noexcept = default; + SecretKeyRing& operator=(SecretKeyRing&&) noexcept = default; + SecretKeyRing(const SecretKeyRing&) = delete; + SecretKeyRing& operator=(const SecretKeyRing&) = delete; + + [[nodiscard]] Void::Result::Result + add_key(std::string key_id, + std::span raw_key, + bool make_active = false, + LockPolicy lock_policy = LockPolicy::StandardWiped); + + [[nodiscard]] Void::Result::Result generate_and_add_key( + std::string key_id, bool make_active = true, + LockPolicy lock_policy = LockPolicy::StandardWiped); + + [[nodiscard]] Void::Result::Result + set_active_key(std::string_view key_id); + + /// Retire a non-active key only after the caller supplies an + /// inventory of remaining ciphertext key IDs proving none reference + /// `key_id`. + [[nodiscard]] Void::Result::Result + retire_key(std::string_view key_id, + std::span + remaining_ciphertext_key_ids); + + [[nodiscard]] std::optional + active_key_id() const; + [[nodiscard]] bool has_key(std::string_view key_id) const; + [[nodiscard]] std::vector key_ids() const; + + [[nodiscard]] Void::Result::Result> + seal(std::span plaintext, + std::span aad = {}) const; + + [[nodiscard]] Void::Result::Result + open(std::span envelope, + std::span aad = {}, + LockPolicy out_policy = LockPolicy::StandardWiped) const; + + private: + + std::map> m_keys{}; + std::string m_active_key_id{}; + }; + +} // namespace Void::Security diff --git a/include/Void/Security/SecureBuffer.hpp b/include/Void/Security/SecureBuffer.hpp new file mode 100644 index 0000000..81b1dae --- /dev/null +++ b/include/Void/Security/SecureBuffer.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Security +{ + enum class LockPolicy : std::uint8_t { + StandardWiped = 0, + LockedOptional, + LockedRequired + }; + + /// Move-only secret byte buffer wiped with sodium_memzero on release. + /// Supports optional or required libsodium locked allocation without + /// silently downgrading a LockedRequired policy. + class SecureBuffer + { + public: + + SecureBuffer() noexcept = default; + ~SecureBuffer() noexcept; + + SecureBuffer(SecureBuffer&& other) noexcept; + SecureBuffer& operator=(SecureBuffer&& other) noexcept; + + SecureBuffer(const SecureBuffer&) = delete; + SecureBuffer& operator=(const SecureBuffer&) = delete; + + [[nodiscard]] static Void::Result::Result + allocate(std::size_t size, + LockPolicy policy = LockPolicy::StandardWiped); + + [[nodiscard]] static Void::Result::Result + from_bytes(std::span data, + LockPolicy policy = LockPolicy::StandardWiped); + + [[nodiscard]] static Void::Result::Result + from_string(std::string_view text, + LockPolicy policy = LockPolicy::StandardWiped); + + [[nodiscard]] std::span view() const noexcept + { + return m_data ? std::span{m_data, m_size} + : std::span{}; + } + + [[nodiscard]] std::span writable() noexcept + { + return m_data ? std::span{m_data, m_size} + : std::span{}; + } + + [[nodiscard]] std::string_view string_view() const noexcept + { + return m_data ? std::string_view{ + reinterpret_cast(m_data), + m_size} + : std::string_view{}; + } + + [[nodiscard]] std::size_t size() const noexcept { return m_size; } + [[nodiscard]] bool empty() const noexcept { return m_size == 0; } + [[nodiscard]] bool is_locked() const noexcept { return m_locked; } + + void clear() noexcept; + + /// Total bytes wiped across SecureBuffer lifetimes (for + /// sanitizer-safe wipe verification in tests). + [[nodiscard]] static std::uint64_t total_wiped_bytes() noexcept; + + private: + + unsigned char* m_data{nullptr}; + std::size_t m_size{0}; + bool m_locked{false}; + }; + +} // namespace Void::Security diff --git a/include/Void/Security/Security.hpp b/include/Void/Security/Security.hpp index bc6ee22..bfe159f 100644 --- a/include/Void/Security/Security.hpp +++ b/include/Void/Security/Security.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -23,6 +24,14 @@ namespace Void::Security inline constexpr std::size_t secret_authentication_bytes = 16; using SecretKey = std::array; + /// Wipe a mutable byte buffer with sodium_memzero. + void wipe_bytes(std::span buffer) noexcept; + + /// Constant-time comparison using sodium_memcmp. + [[nodiscard]] bool + constant_time_equal(std::span lhs, + std::span rhs) noexcept; + /// Generate a URL-safe, unpadded token containing `entropy_bytes` of /// cryptographically secure randomness. [[nodiscard]] Void::Result::Result @@ -44,6 +53,18 @@ namespace Void::Security std::string_view password, PasswordHashStrength strength = PasswordHashStrength::Moderate); + /// Parse Argon2id cost parameters (`$argon2id$v=19$m=...,t=...,p=...$...`) + /// without executing Argon2id or allocating memory. + [[nodiscard]] Void::Result::Result + parse_argon2id_cost(std::string_view encoded_hash); + + /// Verify a password against an encoded Argon2id hash after enforcing input + /// caps and operator-approved memory/iteration/parallelism cost budgets. + [[nodiscard]] Void::Result::Result + verify_password_budgeted(std::string_view password, + std::string_view encoded_hash, + const PasswordVerifyBudget& budget = {}); + /// Verify a password against a libsodium Argon2id encoded hash. /// Malformed hashes are treated as a non-match. [[nodiscard]] Void::Result::Result @@ -53,8 +74,8 @@ namespace Void::Security /// Generate a cryptographically random key for local secret encryption. [[nodiscard]] Void::Result::Result random_secret_key(); - /// Encrypt and authenticate bytes. The returned portable envelope is - /// nonce || ciphertext || authentication tag. + /// Encrypt and authenticate bytes using the legacy local secret format + /// (24-byte nonce || crypto_secretbox_easy combined MAC + ciphertext). [[nodiscard]] Void::Result::Result> seal_secret(std::span plaintext, const SecretKey& key); diff --git a/include/Void/Security/Types.hpp b/include/Void/Security/Types.hpp new file mode 100644 index 0000000..d1c56f1 --- /dev/null +++ b/include/Void/Security/Types.hpp @@ -0,0 +1,197 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Security +{ + struct SecurityLimits { + static constexpr std::size_t kMaxPasswordBytes = 1024; + static constexpr std::size_t kMaxEncodedHashBytes = 1024; + static constexpr std::size_t kMaxTokenBytes = 512; + static constexpr std::size_t kMaxSecretPlaintextBytes = + 16ULL * 1024ULL * 1024ULL; + static constexpr std::size_t kMaxKeyIdBytes = 128; + static constexpr std::size_t kMaxAadBytes = 64ULL * 1024ULL; + static constexpr std::size_t kMaxRolesPerPrincipal = 64; + static constexpr std::size_t kMaxPolicyRules = 4096; + static constexpr std::size_t kMaxPredicateDepth = 16; + static constexpr std::size_t kDefaultPasswordJobMemoryBudgetBytes = + 512ULL * 1024ULL * 1024ULL; + static constexpr std::size_t kDefaultMaxConcurrentPasswordJobs = 2; + static constexpr std::size_t kDefaultMaxWaitingPasswordJobs = 32; + static constexpr std::size_t kDefaultMaxTotalSessions = 10000; + static constexpr std::size_t kDefaultMaxSessionsPerSubject = 16; + static constexpr std::chrono::seconds kDefaultSessionTtl{3600}; + static constexpr std::chrono::seconds + kDefaultClockRollbackTolerance{60}; + static constexpr std::size_t kDefaultExpiryCleanupBatch = 256; + }; + + enum class SecurityErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + input_too_large = 2, + malformed_hash = 3, + cost_budget_exceeded = 4, + authentication_failed = 5, + denied = 6, + rate_limited = 7, + session_expired = 8, + session_revoked = 9, + session_capacity_exceeded = 10, + clock_rollback = 11, + conflict = 12, + key_not_found = 13, + key_in_use = 14, + unsupported_version = 15, + policy_invalid = 16, + audit_failed = 17, + locked_memory_unavailable = 18, + backend_error = 19, + store_unavailable = 20, + cancelled = 21, + timeout = 22, + overloaded = 23, + closed = 24 + }; + + [[nodiscard]] inline Void::Result::Error + make_security_error(SecurityErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case SecurityErrorCode::none: + kind = ErrorKind::internal; + break; + case SecurityErrorCode::invalid_argument: + case SecurityErrorCode::input_too_large: + case SecurityErrorCode::policy_invalid: + kind = ErrorKind::invalid_argument; + break; + case SecurityErrorCode::malformed_hash: + case SecurityErrorCode::authentication_failed: + kind = ErrorKind::corrupt; + break; + case SecurityErrorCode::cost_budget_exceeded: + case SecurityErrorCode::session_capacity_exceeded: + case SecurityErrorCode::locked_memory_unavailable: + kind = ErrorKind::exhausted; + break; + case SecurityErrorCode::denied: + case SecurityErrorCode::session_expired: + case SecurityErrorCode::session_revoked: + case SecurityErrorCode::clock_rollback: + case SecurityErrorCode::conflict: + case SecurityErrorCode::key_in_use: + kind = ErrorKind::conflict; + break; + case SecurityErrorCode::rate_limited: + case SecurityErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case SecurityErrorCode::key_not_found: + kind = ErrorKind::not_found; + break; + case SecurityErrorCode::unsupported_version: + kind = ErrorKind::unsupported; + break; + case SecurityErrorCode::audit_failed: + case SecurityErrorCode::backend_error: + case SecurityErrorCode::store_unavailable: + kind = ErrorKind::internal; + break; + case SecurityErrorCode::cancelled: + case SecurityErrorCode::closed: + kind = ErrorKind::cancelled; + break; + case SecurityErrorCode::timeout: + kind = ErrorKind::timeout; + break; + } + + const ErrorCode domain_code{Void::Result::kSecurityErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; + } + + struct Argon2idCost { + std::uint32_t version{19}; + std::uint64_t memory_kib{0}; + std::uint64_t iterations{0}; + std::uint32_t parallelism{0}; + + [[nodiscard]] std::optional + memory_bytes() const noexcept + { + if (memory_kib > + std::numeric_limits::max() / 1024ULL) { + return std::nullopt; + } + return memory_kib * 1024ULL; + } + }; + + struct PasswordVerifyBudget { + std::uint64_t max_memory_bytes{256ULL * 1024ULL * 1024ULL}; + std::uint64_t max_iterations{16}; + std::uint32_t max_parallelism{4}; + }; + + enum class FaultOperation : std::uint8_t { + none = 0, + any, + sodium_init, + random_bytes, + locked_alloc, + password_hash, + secret_seal, + secret_open + }; + + struct FaultConfig { + FaultOperation op{FaultOperation::none}; + SecurityErrorCode code{SecurityErrorCode::backend_error}; + std::size_t fail_after{0}; + }; + + class ScopedFaultGuard + { + public: + + explicit ScopedFaultGuard(FaultConfig config) noexcept; + ~ScopedFaultGuard() noexcept; + + ScopedFaultGuard(const ScopedFaultGuard&) = delete; + ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete; + ScopedFaultGuard(ScopedFaultGuard&&) = delete; + ScopedFaultGuard& operator=(ScopedFaultGuard&&) = delete; + + private: + + FaultConfig m_previous{}; + std::size_t m_previous_hits{0}; + }; + + namespace Detail + { + [[nodiscard]] std::optional + maybe_inject_fault(FaultOperation op, std::string_view operation); + } // namespace Detail + +} // namespace Void::Security diff --git a/include/Void/Update/Feed.hpp b/include/Void/Update/Feed.hpp index 6016714..0014fde 100644 --- a/include/Void/Update/Feed.hpp +++ b/include/Void/Update/Feed.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -68,6 +69,8 @@ namespace Void::Update std::chrono::system_clock::time_point now{ std::chrono::system_clock::now()}; bool requireUnexpired{true}; + SchemaParsePolicy parsePolicy{SchemaParsePolicy::LegacyGeneralJson}; + std::size_t maxJsonDepth{64}; }; struct VerifiedFeed { @@ -193,4 +196,108 @@ namespace Void::Update /// Select the greatest compatible version, independent of feed order. [[nodiscard]] std::optional selectRelease(const Feed& feed, const SelectionRequest& request); + + /// Non-forgeable signature-verified release selection retaining the exact + /// verified envelope bytes, signer key ID, policy decision, and selected + /// release/component metadata. Can only be constructed by verified factory + /// functions. + class VerifiedSelection + { + public: + + VerifiedSelection(const VerifiedSelection&) = default; + VerifiedSelection(VerifiedSelection&&) noexcept = default; + VerifiedSelection& operator=(const VerifiedSelection&) = default; + VerifiedSelection& operator=(VerifiedSelection&&) noexcept = default; + + [[nodiscard]] const std::string& + signed_envelope_bytes() const noexcept + { + return m_signed_envelope; + } + [[nodiscard]] const std::string& + signed_payload_bytes() const noexcept + { + return m_signed_payload; + } + [[nodiscard]] const std::string& signer_key_id() const noexcept + { + return m_signer_key_id; + } + [[nodiscard]] const std::string& feed_id() const noexcept + { + return m_feed_id; + } + [[nodiscard]] std::uint64_t sequence() const noexcept + { + return m_sequence; + } + [[nodiscard]] std::chrono::system_clock::time_point + expires_at() const noexcept + { + return m_expires_at; + } + [[nodiscard]] SchemaParsePolicy parse_policy() const noexcept + { + return m_parse_policy; + } + [[nodiscard]] const ReleaseIdentity& release() const noexcept + { + return m_release; + } + [[nodiscard]] const std::map& + component_releases() const noexcept + { + return m_components; + } + + private: + + VerifiedSelection() = default; + + std::string m_signed_envelope{}; + std::string m_signed_payload{}; + std::string m_signer_key_id{}; + std::string m_feed_id{}; + std::uint64_t m_sequence{0}; + std::chrono::system_clock::time_point m_expires_at{}; + SchemaParsePolicy m_parse_policy{ + SchemaParsePolicy::LegacyGeneralJson}; + ReleaseIdentity m_release{}; + std::map m_components{}; + + friend Void::Result::Result + verify_and_select_release(std::string_view envelopeJson, + const Keyring& keys, + const SelectionRequest& request, + const VerificationPolicy& policy); + + friend Void::Result::Result + verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& + releaseEnvelopeJsons, + const Keyring& keys, std::string_view primaryComponentId, + const VerificationPolicy& policy); + }; + + /// Verify an aggregate feed envelope (verify-before-parse), validate + /// policy, and produce a non-forgeable VerifiedSelection for the best + /// compatible release. + [[nodiscard]] Void::Result::Result + verify_and_select_release(std::string_view envelopeJson, + const Keyring& keys, + const SelectionRequest& request, + const VerificationPolicy& policy = {}); + + /// Verify a signed component catalog envelope and signed per-component + /// release envelopes, validate dependency closure and transaction limits + /// (<= 32 components, <= 256 dependency edges), and return a non-forgeable + /// VerifiedSelection. + [[nodiscard]] Void::Result::Result + verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& releaseEnvelopeJsons, + const Keyring& keys, std::string_view primaryComponentId, + const VerificationPolicy& policy = {}); } // namespace Void::Update diff --git a/include/Void/Update/Install.hpp b/include/Void/Update/Install.hpp new file mode 100644 index 0000000..278a1d1 --- /dev/null +++ b/include/Void/Update/Install.hpp @@ -0,0 +1,228 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + /// Durable high-water sequence floor per (feed_id, channel) persisted via + /// atomic file replacement + directory sync. Monotonic across restarts, key + /// rotations, and civil-clock rollbacks; corrupt floor files fail with + /// RecoveryRequired instead of resetting to zero. + class ReplayFloorStore + { + public: + + explicit ReplayFloorStore(std::filesystem::path file_path); + + [[nodiscard]] Void::Result::Result load(); + + [[nodiscard]] std::optional + floor(std::string_view feed_id, + std::string_view channel) const; + + /// Validate `sequence >= stored_floor` (or strictly `>` when + /// `require_strictly_greater` is true) and durably persist the new + /// high-water mark before returning. + [[nodiscard]] Void::Result::Result + advance(std::string_view feed_id, std::string_view channel, + std::uint64_t sequence, + bool require_strictly_greater = false); + + private: + + std::filesystem::path m_path{}; + mutable std::mutex m_mu{}; + std::map> m_floors{}; + bool m_loaded{false}; + }; + + /// Explicit trust-root store supporting application bootstrap, + /// authenticated old-trust key rotation, operator-approved rotation, and + /// key revocation without rewriting historical signed bytes. + class TrustStore + { + public: + + [[nodiscard]] static std::string + rotation_statement(std::string_view new_key_id, + const Ed25519PublicKey& new_public_key); + + [[nodiscard]] Void::Result::Result bootstrap(Keyring keys); + + /// Rotate in `new_key_id` using an Ed25519 signature produced by an + /// active trusted key (`authorizing_key_id`) over + /// `rotation_statement(new_key_id, new_public_key)`. + [[nodiscard]] Void::Result::Result + rotate_key_authenticated( + std::string new_key_id, + const Ed25519PublicKey& new_public_key, + std::span signature, + std::string_view authorizing_key_id); + + [[nodiscard]] Void::Result::Result + rotate_key_operator(std::string new_key_id, + const Ed25519PublicKey& new_public_key); + + [[nodiscard]] Void::Result::Result + revoke_key(std::string_view key_id); + + [[nodiscard]] Keyring snapshot() const; + [[nodiscard]] bool is_revoked(std::string_view key_id) const; + + private: + + mutable std::mutex m_mu{}; + Keyring m_active{}; + std::set> m_revoked{}; + }; + + struct DownloadRequest { + std::string url{}; + std::string expected_sha256{}; + std::uint64_t expected_size{0}; + std::uint64_t max_bytes{0}; + std::optional resume_validator{}; + std::uint64_t resume_offset{0}; + std::stop_token stop{}; + }; + + struct DownloadMetadata { + std::string validator{}; + bool resumed{false}; + }; + + /// Abstract bounded artifact download transport. Concrete Net/HTTP + /// transports implement this interface without coupling Update to Net. + class ArtifactTransport + { + public: + + virtual ~ArtifactTransport() = default; + + [[nodiscard]] virtual Void::Result::Result + download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& + on_chunk) = 0; + }; + + /// Offline local-file transport for deterministic update workflow and + /// installed-consumer testing. + class LocalFileArtifactTransport final : public ArtifactTransport + { + public: + + void map_url(std::string url, std::filesystem::path file_path, + std::string validator = "v1"); + void set_fail_next(bool fail) noexcept; + void set_truncate_bytes(std::optional bytes) noexcept; + + [[nodiscard]] Void::Result::Result download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& + on_chunk) override; + + private: + + struct Entry { + std::filesystem::path path{}; + std::string validator{}; + }; + mutable std::mutex m_mu{}; + std::map> m_entries{}; + bool m_fail_next{false}; + std::optional m_truncate_bytes{}; + }; + + struct LifecycleHooks { + /// Required when ActivationMode::ExternalLifecycle is selected. + std::function( + const Semver::Version&, const std::filesystem::path&)> + activate_external{}; + /// Cooperative health probe executed outside coordinator locks. + /// Defaults to immediately healthy if unset. + std::function( + const Semver::Version&, const std::filesystem::path&)> + health_probe{}; + /// Invoked before rollback on readiness failure to stop/join the + /// candidate cleanly. + std::function stop_candidate{}; + /// Returns currently pinned live generations (e.g. loaded plugins) + /// that pruning must not delete. + std::function()> live_pinned_versions{}; + /// Owning progress event snapshot invoked outside coordinator locks. + std::function on_progress{}; + /// Optional post-commit cleanup hook (also usable to inject cleanup + /// failures in tests to verify CleanupPending without rollback). + std::function()> + post_commit_cleanup_hook{}; + }; + + /// Serialized per-store installation orchestrator combining verified + /// selections, monotonic replay floors, exact-digest streaming downloads, + /// Archive atomic staging, VersionStore single-commit activation, + /// checksummed operation journaling, and pin-aware bounded pruning. + class InstallCoordinator + { + public: + + InstallCoordinator(VersionStore& store, + ReplayFloorStore& floor_store, + std::shared_ptr transport, + LifecycleHooks hooks = {}); + + InstallCoordinator(const InstallCoordinator&) = delete; + InstallCoordinator& operator=(const InstallCoordinator&) = delete; + + [[nodiscard]] Void::Result::Result + install(const VerifiedSelection& selection, + const InstallOptions& options = {}); + + /// Idempotent recovery pass inspecting both the checksummed + /// operation journal and VersionStore's durable activation/health + /// evidence. Corrupt or unknown journal records halt with + /// RecoveryRequired without discarding evidence. + [[nodiscard]] Void::Result::Result reconcile(); + + /// Retry post-commit cleanup/pruning after a CleanupPending + /// outcome. Never rolls back a committed version. + [[nodiscard]] Void::Result::Result + retry_cleanup(const InstallOptions& options = {}); + + void shutdown() noexcept; + [[nodiscard]] bool is_shutdown() const noexcept; + + [[nodiscard]] std::filesystem::path + operation_journal_path() const; + + private: + + VersionStore& m_store; + ReplayFloorStore& m_floor_store; + std::shared_ptr m_transport; + LifecycleHooks m_hooks{}; + mutable std::mutex m_state_mu{}; + bool m_active{false}; + bool m_shutdown{false}; + }; + +} // namespace Void::Update diff --git a/include/Void/Update/Types.hpp b/include/Void/Update/Types.hpp new file mode 100644 index 0000000..ddb67d2 --- /dev/null +++ b/include/Void/Update/Types.hpp @@ -0,0 +1,209 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + enum class UpdateErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + signature_failed = 2, + untrusted_key = 3, + replay_rejected = 4, + expired = 5, + schema_error = 6, + mirror_mismatch = 7, + digest_mismatch = 8, + size_mismatch = 9, + limit_exceeded = 10, + transport_error = 11, + staging_error = 12, + activation_failed = 13, + health_check_failed = 14, + recovery_required = 15, + cleanup_pending = 16, + unknown_outcome = 17, + conflict = 18, + cancelled = 19, + timeout = 20, + closed = 21, + io_error = 22 + }; + + [[nodiscard]] inline Void::Result::Error + make_update_error(UpdateErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case UpdateErrorCode::none: + kind = ErrorKind::internal; + break; + case UpdateErrorCode::invalid_argument: + case UpdateErrorCode::schema_error: + kind = ErrorKind::invalid_argument; + break; + case UpdateErrorCode::signature_failed: + case UpdateErrorCode::untrusted_key: + case UpdateErrorCode::mirror_mismatch: + case UpdateErrorCode::digest_mismatch: + case UpdateErrorCode::size_mismatch: + case UpdateErrorCode::recovery_required: + kind = ErrorKind::corrupt; + break; + case UpdateErrorCode::replay_rejected: + case UpdateErrorCode::expired: + case UpdateErrorCode::conflict: + case UpdateErrorCode::cleanup_pending: + kind = ErrorKind::conflict; + break; + case UpdateErrorCode::limit_exceeded: + kind = ErrorKind::exhausted; + break; + case UpdateErrorCode::transport_error: + case UpdateErrorCode::staging_error: + case UpdateErrorCode::io_error: + kind = ErrorKind::io; + break; + case UpdateErrorCode::activation_failed: + case UpdateErrorCode::health_check_failed: + case UpdateErrorCode::unknown_outcome: + kind = ErrorKind::internal; + break; + case UpdateErrorCode::cancelled: + case UpdateErrorCode::closed: + kind = ErrorKind::cancelled; + break; + case UpdateErrorCode::timeout: + kind = ErrorKind::timeout; + break; + } + + const ErrorCode domain_code{Void::Result::kUpdateErrorDomain, + static_cast(code)}; + return Error{kind, std::move(message), domain_code, sys_err}; + } + + /// Explicit JSON parsing policy for signed payloads (C-07). + /// LegacyGeneralJson preserves existing accepted documents; + /// StrictJsonProfile additionally enforces Void::Json::Strict rules + /// (no duplicate keys, integer-only strict numbers, bounded nesting depth). + enum class SchemaParsePolicy : std::uint8_t { + LegacyGeneralJson = 0, + StrictJsonProfile = 1 + }; + + enum class InstallState : std::uint8_t { + Verified = 0, + Downloading, + Staged, + Published, + Activated, + HealthyCommitted, + CleanupPending, + RolledBack, + RecoveryRequired + }; + + enum class ActivationMode : std::uint8_t { + InternalVersionStore = 0, + ExternalLifecycle = 1 + }; + + struct UpdateLimits { + static constexpr std::size_t kDefaultMaxActiveInstalls = 1; + static constexpr std::size_t kDefaultMaxQueuedSelections = 8; + static constexpr std::size_t kDefaultMaxConcurrentDownloads = 2; + static constexpr std::uint64_t kDefaultMaxArtifactBytes = + 512ULL * 1024 * 1024; + static constexpr std::uint64_t kDefaultStagingQuotaBytes = + 2ULL * 1024 * 1024 * 1024; + static constexpr std::size_t kDefaultMaxComponentsPerTransaction = + 32; + static constexpr std::size_t kDefaultMaxDependencyEdges = 256; + static constexpr std::chrono::milliseconds kDefaultInstallDeadline{ + std::chrono::minutes{10}}; + static constexpr std::chrono::milliseconds kDefaultReadinessTimeout{ + std::chrono::seconds{30}}; + static constexpr std::chrono::milliseconds + kDefaultHealthProbeInterval{std::chrono::seconds{1}}; + static constexpr std::size_t kDefaultConsecutiveHealthyRequired = 3; + static constexpr std::size_t kDefaultRetainedPreviousVersions = 2; + static constexpr std::size_t kDefaultPruneBatchLimit = 16; + }; + + struct ReleaseIdentity { + std::string component{}; + std::string artifact_id{}; + std::string channel{}; + Semver::Version version{}; + std::uint64_t sequence{0}; + std::string sha256{}; + std::uint64_t size{0}; + std::string url{}; + std::string package_type{}; + }; + + struct InstallReceipt { + std::string install_id{}; + InstallState state{InstallState::Verified}; + ReleaseIdentity release{}; + std::string signer_key_id{}; + std::string diagnostic{}; + bool cleanup_retryable{false}; + }; + + struct InstallOptions { + ActivationMode activation_mode{ + ActivationMode::InternalVersionStore}; + std::size_t max_active_installs{ + UpdateLimits::kDefaultMaxActiveInstalls}; + std::size_t max_queued_selections{ + UpdateLimits::kDefaultMaxQueuedSelections}; + std::size_t max_concurrent_downloads{ + UpdateLimits::kDefaultMaxConcurrentDownloads}; + std::uint64_t max_artifact_bytes{ + UpdateLimits::kDefaultMaxArtifactBytes}; + std::uint64_t staging_quota_bytes{ + UpdateLimits::kDefaultStagingQuotaBytes}; + std::size_t max_components{ + UpdateLimits::kDefaultMaxComponentsPerTransaction}; + std::size_t max_dependency_edges{ + UpdateLimits::kDefaultMaxDependencyEdges}; + std::chrono::milliseconds install_deadline{ + UpdateLimits::kDefaultInstallDeadline}; + std::chrono::milliseconds readiness_timeout{ + UpdateLimits::kDefaultReadinessTimeout}; + std::chrono::milliseconds health_probe_interval{ + UpdateLimits::kDefaultHealthProbeInterval}; + std::size_t consecutive_healthy_required{ + UpdateLimits::kDefaultConsecutiveHealthyRequired}; + std::size_t retained_previous_versions{ + UpdateLimits::kDefaultRetainedPreviousVersions}; + std::size_t prune_batch_limit{ + UpdateLimits::kDefaultPruneBatchLimit}; + bool allow_resumable_download{false}; + std::optional isolated_archive_worker{}; + std::stop_token stop{}; + const Void::Time::MonotonicClock* monotonic_clock{nullptr}; + const Void::Time::CivilClock* civil_clock{nullptr}; + }; + +} // namespace Void::Update diff --git a/include/Void/Update/Update.hpp b/include/Void/Update/Update.hpp index a495265..753b755 100644 --- a/include/Void/Update/Update.hpp +++ b/include/Void/Update/Update.hpp @@ -1,4 +1,6 @@ #pragma once #include +#include +#include #include diff --git a/include/Void/Update/VersionStore.hpp b/include/Void/Update/VersionStore.hpp index cef46f2..e1e604e 100644 --- a/include/Void/Update/VersionStore.hpp +++ b/include/Void/Update/VersionStore.hpp @@ -8,10 +8,16 @@ #include #include #include +#include #include namespace Void::Update { + struct PruneReport { + std::vector removed{}; + std::vector skipped_due_to_pins{}; + bool batch_limit_reached{false}; + }; struct PendingActivation { std::optional previousVersion; Semver::Version candidateVersion; @@ -86,6 +92,16 @@ namespace Void::Update Void::Result::Result> prune(std::size_t retainedPreviousVersions); + /// Pin-aware bounded pruning pass. Never deletes the active + /// version, pending activation candidate/previous, top + /// `retainedPreviousVersions` healthy versions, or any version in + /// `pinnedVersions`. Reports pin-blocked candidates and honors + /// `batchLimit` (default 16 publications per pass). + [[nodiscard]] Void::Result::Result + pruneWithPins(std::size_t retainedPreviousVersions, + std::span pinnedVersions, + std::size_t batchLimit = 16); + [[nodiscard]] Void::Result::Result> currentVersion() const; [[nodiscard]] Void::Result::Result> diff --git a/src/Archive/StagedArchive.cpp b/src/Archive/StagedArchive.cpp new file mode 100644 index 0000000..c0da04c --- /dev/null +++ b/src/Archive/StagedArchive.cpp @@ -0,0 +1,2804 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#include +#ifdef __linux__ +#include +#endif +#ifndef RENAME_NOREPLACE +#define RENAME_NOREPLACE (1U << 0) +#endif +#endif + +namespace Void::Archive +{ + namespace + { + thread_local FaultPoint g_fault_point{FaultPoint::none}; + std::atomic g_stage_counter{0}; + + constexpr int kDirOpenFlags = + O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW; + constexpr std::size_t kMaxDiagnosticPathBytes = 4096; + constexpr std::string_view kStagePrefix = ".void-stage-"; + constexpr std::string_view kMarkerFilename = ".void-stage.marker"; + constexpr std::string_view kInventoryFilename = "inventory.txt"; + constexpr std::string_view kTreeSubdir = "tree"; + + using ArchiveReadPtr = + std::unique_ptr; + using ArchiveWritePtr = + std::unique_ptr; + using ArchiveEntryPtr = + std::unique_ptr; + + class OwnedFd + { + public: + + explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {} + ~OwnedFd() noexcept { reset(); } + OwnedFd(OwnedFd&& other) noexcept + : m_fd(std::exchange(other.m_fd, -1)) + { + } + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(std::exchange(other.m_fd, -1)); + } + return *this; + } + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + [[nodiscard]] int get() const noexcept { return m_fd; } + [[nodiscard]] explicit operator bool() const noexcept + { + return m_fd >= 0; + } + [[nodiscard]] int release() noexcept + { + return std::exchange(m_fd, -1); + } + void reset(int fd = -1) noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + } + m_fd = fd; + } + + private: + + int m_fd{-1}; + }; + + [[nodiscard]] ArchiveErrorCode errno_to_archive_code(int err) noexcept + { + switch (err) { + case EACCES: + case EPERM: + return ArchiveErrorCode::permission_denied; + case ENOSPC: + case EDQUOT: + return ArchiveErrorCode::no_space; + case EEXIST: + case ENOTEMPTY: + return ArchiveErrorCode::already_exists; + case ENOSYS: + case EINVAL: + return ArchiveErrorCode::unsupported_capability; + default: + return ArchiveErrorCode::io_error; + } + } + + [[nodiscard]] Void::Result::Error + make_errno_error(int err, std::string message) + { + return make_archive_error( + errno_to_archive_code(err), + std::format("{}: {}", message, std::strerror(err)), + std::error_code{err, std::generic_category()}); + } + + [[nodiscard]] Void::Result::Error + make_libarchive_error(archive* a, std::string_view op, + ArchiveErrorCode fallback = + ArchiveErrorCode::corrupt_archive) + { + const char* raw = a ? archive_error_string(a) : nullptr; + const std::string detail = + raw ? sanitize_diagnostic_path(raw) : "unknown archive error"; + return make_archive_error(fallback, + std::format("Archive: {}: {}", op, detail)); + } + + [[nodiscard]] bool is_safe_single_component( + std::string_view name, std::size_t max_bytes = 255) noexcept + { + if (name.empty() || name.size() > max_bytes || name == "." || + name == "..") { + return false; + } + for (const unsigned char ch : name) { + if (ch == '/' || ch == '\\' || ch == '\0') { + return false; + } + } + return true; + } + + struct ValidatedPath { + std::string normalized{}; + std::vector components{}; + }; + + [[nodiscard]] Void::Result::Result + validate_archive_path(std::string_view raw, bool is_directory, + const ReadLimits& limits) + { + if (raw.empty()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: entry path is empty")}; + } + if (raw.size() > limits.max_path_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + std::format("Archive: entry path exceeds {} byte cap: '{}'", + limits.max_path_bytes, + sanitize_diagnostic_path(raw)))}; + } + if (raw.find('\0') != std::string_view::npos || + raw.find('\\') != std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unsafe characters in path '{}'", + sanitize_diagnostic_path(raw)))}; + } + + std::string_view trimmed = raw; + if (trimmed.back() == '/') { + if (!is_directory) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: regular file path ends with '/': " + "'{}'", + sanitize_diagnostic_path(raw)))}; + } + trimmed.remove_suffix(1); + if (trimmed.empty() || trimmed.back() == '/') { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: invalid directory path '{}'", + sanitize_diagnostic_path(raw)))}; + } + } + if (trimmed.front() == '/' || + trimmed.find("//") != std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: absolute or non-normal path '{}'", + sanitize_diagnostic_path(raw)))}; + } + + ValidatedPath out; + std::size_t pos = 0; + while (pos < trimmed.size()) { + const std::size_t slash = trimmed.find('/', pos); + const std::string_view comp = + slash == std::string_view::npos + ? trimmed.substr(pos) + : trimmed.substr(pos, slash - pos); + if (!is_safe_single_component(comp, + limits.max_component_bytes)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unsafe path component in '{}'", + sanitize_diagnostic_path(raw)))}; + } + if (out.components.size() >= limits.max_path_components) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + std::format( + "Archive: path exceeds {} components: '{}'", + limits.max_path_components, + sanitize_diagnostic_path(raw)))}; + } + out.components.emplace_back(comp); + if (slash == std::string_view::npos) { + break; + } + pos = slash + 1; + } + + const std::filesystem::path fspath{trimmed}; + if (fspath.empty() || fspath.is_absolute() || + fspath.has_root_name() || fspath.lexically_normal() != fspath) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: non-normalized path '{}'", + sanitize_diagnostic_path(raw)))}; + } + out.normalized.assign(trimmed); + return out; + } + + class PathTracker + { + public: + + explicit PathTracker(std::size_t max_metadata_bytes) noexcept + : m_max_metadata_bytes(max_metadata_bytes) + { + } + + [[nodiscard]] Void::Result::Result + record(const ValidatedPath& vp, bool is_directory) + { + const std::size_t cost = vp.normalized.size() + 64U; + if (cost > m_max_metadata_bytes || + m_metadata_bytes > m_max_metadata_bytes - cost) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: aggregate path/inventory metadata " + "exceeds limit")}; + } + + // Check exact duplicate. + if (m_files.contains(vp.normalized) || + m_explicit_dirs.contains(vp.normalized)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: duplicate entry path '{}'", + sanitize_diagnostic_path( + vp.normalized)))}; + } + + // If registering a file, ensure no implicit/explicit dir + // already owns this path as a parent. + if (!is_directory && m_all_dirs.contains(vp.normalized)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: file conflicts with existing " + "directory '{}'", + sanitize_diagnostic_path( + vp.normalized)))}; + } + + // Every parent prefix must not already be a regular file. + std::string prefix; + for (std::size_t i = 0; i + 1 < vp.components.size(); ++i) { + if (i > 0) { + prefix.push_back('/'); + } + prefix.append(vp.components[i]); + if (m_files.contains(prefix)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: file-as-parent conflict " + "at '{}'", + sanitize_diagnostic_path(prefix)))}; + } + if (m_all_dirs.insert(prefix).second) { + const std::size_t pcost = prefix.size() + 32U; + if (pcost > m_max_metadata_bytes || + m_metadata_bytes > + m_max_metadata_bytes - pcost) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: aggregate metadata exceeds " + "limit")}; + } + m_metadata_bytes += pcost; + } + } + + m_metadata_bytes += cost; + if (is_directory) { + m_explicit_dirs.insert(vp.normalized); + m_all_dirs.insert(vp.normalized); + } else { + m_files.insert(vp.normalized); + } + return {}; + } + + [[nodiscard]] const std::set& + all_dirs() const noexcept + { + return m_all_dirs; + } + + private: + + std::size_t m_max_metadata_bytes{0}; + std::size_t m_metadata_bytes{0}; + std::set m_files{}; + std::set m_explicit_dirs{}; + std::set m_all_dirs{}; + }; + + [[nodiscard]] Void::Result::Result + write_all_fd(int fd, std::span data) + { + std::size_t written = 0; + while (written < data.size()) { + const ssize_t n = ::write( + fd, + reinterpret_cast(data.data()) + written, + data.size() - written); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return std::unexpected{ + make_errno_error(errno, "Archive: write failed")}; + } + written += static_cast(n); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + write_file_at(int dir_fd, const char* filename, + std::string_view content, mode_t mode) + { + OwnedFd fd{::openat(dir_fd, filename, + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | + O_NOFOLLOW, + mode)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: create '{}'", filename))}; + } + const auto bytes = + std::as_bytes(std::span{content.data(), content.size()}); + if (auto w = write_all_fd(fd.get(), bytes); !w.has_value()) { + fd.reset(); + (void)::unlinkat(dir_fd, filename, 0); + return w; + } + if (::fsync(fd.get()) != 0) { + const int err = errno; + fd.reset(); + (void)::unlinkat(dir_fd, filename, 0); + return std::unexpected{make_errno_error( + err, std::format("Archive: fsync '{}'", filename))}; + } + const int raw = fd.release(); + if (::close(raw) != 0) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: close '{}'", filename))}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result + remove_directory_contents_nofollow(int dir_fd) + { + OwnedFd dup_fd{::openat(dir_fd, ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate dir fd for cleanup")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{ + make_errno_error(errno, "Archive: fdopendir failed")}; + } + (void)dup_fd.release(); // owned by dir now + + Void::Result::Result first_err{}; + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + if (errno != 0 && first_err.has_value()) { + first_err = std::unexpected{ + make_errno_error(errno, "Archive: readdir failed")}; + } + break; + } + const std::string_view name{ent->d_name}; + if (name == "." || name == "..") { + continue; + } + struct stat st{}; + if (::fstatat(dir_fd, ent->d_name, &st, AT_SYMLINK_NOFOLLOW) != + 0) { + if (errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: fstatat during cleanup")}; + } + continue; + } + if (S_ISDIR(st.st_mode)) { + OwnedFd sub{::openat(dir_fd, ent->d_name, kDirOpenFlags)}; + if (!sub) { + if (first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, + "Archive: openat subdir during cleanup")}; + } + continue; + } + if (auto sub_res = remove_directory_contents_nofollow( + sub.get()); + !sub_res.has_value() && first_err.has_value()) { + first_err = std::move(sub_res); + } + sub.reset(); + if (::unlinkat(dir_fd, ent->d_name, AT_REMOVEDIR) != 0 && + errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: unlinkat subdir")}; + } + } else { + if (::unlinkat(dir_fd, ent->d_name, 0) != 0 && + errno != ENOENT && first_err.has_value()) { + first_err = std::unexpected{make_errno_error( + errno, "Archive: unlinkat entry")}; + } + } + } + (void)::closedir(dir); + return first_err; + } + + [[nodiscard]] Void::Result::Result + remove_stage_dir(int parent_fd, std::string_view stage_name) + { + if (g_fault_point == FaultPoint::staging_cleanup_fail) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive: injected staging cleanup failure")}; + } + const std::string name_str{stage_name}; + OwnedFd stage_fd{::openat(parent_fd, name_str.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + if (errno == ENOENT) { + return {}; + } + return std::unexpected{make_errno_error( + errno, "Archive: open staging root for cleanup")}; + } + auto content_res = remove_directory_contents_nofollow(stage_fd.get()); + stage_fd.reset(); + if (::unlinkat(parent_fd, name_str.c_str(), AT_REMOVEDIR) != 0 && + errno != ENOENT) { + if (content_res.has_value()) { + return std::unexpected{make_errno_error( + errno, "Archive: remove staging root")}; + } + } + return content_res; + } + + [[nodiscard]] Void::Result::Result + open_or_create_relative_dir(int root_fd, + const std::vector& comps, + std::size_t count) + { + OwnedFd cur{::openat(root_fd, ".", kDirOpenFlags)}; + if (!cur) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate staging tree fd")}; + } + for (std::size_t i = 0; i < count; ++i) { + const char* part = comps[i].c_str(); + int fd = ::openat(cur.get(), part, kDirOpenFlags); + if (fd < 0 && errno == ENOENT) { + if (::mkdirat(cur.get(), part, 0755) != 0 && + errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: mkdirat in staging tree")}; + } + fd = ::openat(cur.get(), part, kDirOpenFlags); + } + if (fd < 0) { + return std::unexpected{make_errno_error( + errno, "Archive: unsafe parent in staging tree")}; + } + cur = OwnedFd{fd}; + } + return cur; + } + + [[nodiscard]] Void::Result::Result + fsync_directories_bottom_up(int tree_fd, + const std::set& dirs) + { + std::vector sorted(dirs.begin(), dirs.end()); + std::sort(sorted.begin(), sorted.end(), + [](const std::string& a, const std::string& b) { + const auto da = + std::count(a.begin(), a.end(), '/'); + const auto db = + std::count(b.begin(), b.end(), '/'); + if (da != db) { + return da > db; + } + return a.size() > b.size(); + }); + + for (const auto& dir_rel : sorted) { + OwnedFd cur{::openat(tree_fd, ".", kDirOpenFlags)}; + if (!cur) { + return std::unexpected{make_errno_error( + errno, "Archive: duplicate tree fd for fsync")}; + } + std::size_t pos = 0; + while (pos < dir_rel.size()) { + const std::size_t slash = dir_rel.find('/', pos); + const std::string comp = + slash == std::string::npos + ? dir_rel.substr(pos) + : dir_rel.substr(pos, slash - pos); + OwnedFd next{::openat(cur.get(), comp.c_str(), kDirOpenFlags)}; + if (!next) { + return std::unexpected{make_errno_error( + errno, "Archive: open dir for fsync")}; + } + cur = std::move(next); + if (slash == std::string::npos) { + break; + } + pos = slash + 1; + } + if (::fsync(cur.get()) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged subdirectory")}; + } + } + if (::fsync(tree_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged tree root")}; + } + return {}; + } + + [[nodiscard]] std::optional current_rss_bytes() noexcept + { + std::ifstream statm{"/proc/self/statm"}; + if (!statm.is_open()) { + return std::nullopt; + } + std::uint64_t total_pages = 0; + std::uint64_t resident_pages = 0; + if (!(statm >> total_pages >> resident_pages)) { + return std::nullopt; + } + const long page_size = ::sysconf(_SC_PAGESIZE); + if (page_size <= 0) { + return std::nullopt; + } + return resident_pages * static_cast(page_size); + } + + [[nodiscard]] std::string + serialize_inventory(const std::vector& inventory) + { + std::string out; + out += "VOID_ARCHIVE_INVENTORY_V1\n"; + for (const auto& entry : inventory) { + const char tag = + entry.type == EntryType::Directory ? 'D' : 'F'; + out += std::format("{} {} {:o} {}\n", tag, entry.declared_size, + entry.safe_mode, entry.path); + } + return out; + } + + [[nodiscard]] Void::Result::Result> + parse_inventory(std::string_view text, const ReadLimits& limits) + { + if (text.size() > limits.max_metadata_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory exceeds metadata limit")}; + } + std::vector out; + std::size_t pos = 0; + const auto next_line = [&](std::string_view& line) -> bool { + if (pos >= text.size()) { + return false; + } + const std::size_t nl = text.find('\n', pos); + if (nl == std::string_view::npos) { + line = text.substr(pos); + pos = text.size(); + } else { + line = text.substr(pos, nl - pos); + pos = nl + 1; + } + return true; + }; + + std::string_view header; + if (!next_line(header) || header != "VOID_ARCHIVE_INVENTORY_V1") { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid completion inventory header")}; + } + + PathTracker tracker{limits.max_metadata_bytes}; + std::uint64_t total_bytes = 0; + std::string_view line; + while (next_line(line)) { + if (line.empty()) { + continue; + } + if (out.size() >= limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory entry count exceeds limit")}; + } + if (line.size() < 6 || (line[0] != 'F' && line[0] != 'D') || + line[1] != ' ') { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory line")}; + } + const bool is_dir = line[0] == 'D'; + const std::size_t sp2 = line.find(' ', 2); + if (sp2 == std::string_view::npos) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory size field")}; + } + const std::size_t sp3 = line.find(' ', sp2 + 1); + if (sp3 == std::string_view::npos || sp3 + 1 >= line.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: malformed inventory mode/path field")}; + } + + std::uint64_t size = 0; + const auto sres = std::from_chars(line.data() + 2, + line.data() + sp2, size); + if (sres.ec != std::errc{} || sres.ptr != line.data() + sp2) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid inventory size")}; + } + std::uint32_t mode = 0; + const auto mres = std::from_chars( + line.data() + sp2 + 1, line.data() + sp3, mode, 8); + if (mres.ec != std::errc{} || mres.ptr != line.data() + sp3) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: invalid inventory mode")}; + } + const std::string_view path_view = line.substr(sp3 + 1); + auto vp = validate_archive_path(path_view, is_dir, limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = tracker.record(*vp, is_dir); !rec.has_value()) { + return std::unexpected{std::move(rec.error())}; + } + if (!is_dir) { + if (size > limits.max_file_bytes || + size > limits.max_total_bytes - total_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: inventory byte totals exceed limit")}; + } + total_bytes += size; + } + out.push_back(EntryInfo{ + .path = std::move(vp->normalized), + .type = is_dir ? EntryType::Directory + : EntryType::RegularFile, + .declared_size = size, + .safe_mode = mode, + .executable = !is_dir && ((mode & 0111U) != 0U), + .accepted = true, + }); + } + return out; + } + + [[nodiscard]] Void::Result::Result + verify_staged_tree_on_disk(int tree_fd, + const std::vector& inventory, + const ReadLimits& limits, + std::uint64_t& out_verified_bytes) + { + std::map expected_files; + std::set expected_dirs; + for (const auto& e : inventory) { + if (e.type == EntryType::Directory) { + expected_dirs.insert(e.path); + } else { + expected_files[e.path] = &e; + } + // Add all parent prefixes as expected directories. + std::size_t pos = 0; + while ((pos = e.path.find('/', pos)) != std::string::npos) { + expected_dirs.insert(e.path.substr(0, pos)); + ++pos; + } + } + + std::set seen_files; + std::set seen_dirs; + out_verified_bytes = 0; + + std::function(int, const std::string&, + std::size_t)> + walk = [&](int dir_fd, const std::string& prefix, + std::size_t depth) -> Void::Result::Result { + if (depth > limits.max_path_components) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: staged directory depth exceeds limit")}; + } + OwnedFd dup_fd{::openat(dir_fd, ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: verify openat dir")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{make_errno_error( + errno, "Archive: verify fdopendir")}; + } + (void)dup_fd.release(); + + Void::Result::Result status{}; + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + if (errno != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify readdir")}; + } + break; + } + const std::string_view name{ent->d_name}; + if (name == "." || name == "..") { + continue; + } + const std::string rel = + prefix.empty() ? std::string{name} + : (prefix + "/" + std::string{name}); + struct stat st{}; + if (::fstatat(dir_fd, ent->d_name, &st, + AT_SYMLINK_NOFOLLOW) != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify fstatat")}; + break; + } + if (S_ISLNK(st.st_mode)) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected symlink in " + "staged tree")}; + break; + } + if (S_ISDIR(st.st_mode)) { + if (!expected_dirs.contains(rel)) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unexpected directory in " + "staged tree '{}'", + sanitize_diagnostic_path(rel)))}; + break; + } + seen_dirs.insert(rel); + OwnedFd sub{ + ::openat(dir_fd, ent->d_name, kDirOpenFlags)}; + if (!sub) { + status = std::unexpected{make_errno_error( + errno, "Archive: verify openat subdir")}; + break; + } + if (auto sr = walk(sub.get(), rel, depth + 1U); + !sr.has_value()) { + status = std::move(sr); + break; + } + } else if (S_ISREG(st.st_mode)) { + if (st.st_nlink > 1) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected " + "hardlink in staged tree")}; + break; + } + auto it = expected_files.find(rel); + if (it == expected_files.end()) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive: unexpected file in " + "staged tree '{}'", + sanitize_diagnostic_path(rel)))}; + break; + } + const auto actual_size = + static_cast(st.st_size); + if (actual_size != it->second->declared_size || + actual_size > limits.max_file_bytes || + actual_size > + limits.max_total_bytes - out_verified_bytes) { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: staged file size disagrees with " + "inventory or exceeds limit")}; + break; + } + out_verified_bytes += actual_size; + seen_files.insert(rel); + OwnedFd rfd{::openat(dir_fd, ent->d_name, + O_RDONLY | O_CLOEXEC | + O_NOFOLLOW)}; + if (!rfd || ::fsync(rfd.get()) != 0) { + status = std::unexpected{make_errno_error( + errno, "Archive: parent verify fsync file")}; + break; + } + } else { + status = std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive: parent verification rejected special " + "file in staged tree")}; + break; + } + } + (void)::closedir(dir); + return status; + }; + + if (auto wr = walk(tree_fd, "", 0); !wr.has_value()) { + return wr; + } + if (seen_files.size() != expected_files.size() || + seen_dirs.size() != expected_dirs.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive: staged tree missing entries declared in " + "inventory")}; + } + return fsync_directories_bottom_up(tree_fd, expected_dirs); + } + } // namespace + + std::string sanitize_diagnostic_path(std::string_view raw) noexcept + { + std::string out; + const std::size_t cap = std::min(raw.size(), kMaxDiagnosticPathBytes); + out.reserve(cap); + for (std::size_t i = 0; i < raw.size(); ++i) { + if (out.size() >= kMaxDiagnosticPathBytes) { + break; + } + const unsigned char ch = static_cast(raw[i]); + if (ch == '\n') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\n"; + } else if (ch == '\r') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\r"; + } else if (ch == '\t') { + if (out.size() + 2 > kMaxDiagnosticPathBytes) { + break; + } + out += "\\t"; + } else if (ch < 0x20U || ch == 0x7FU) { + if (out.size() + 4 > kMaxDiagnosticPathBytes) { + break; + } + static constexpr char kHex[] = "0123456789abcdef"; + out += "\\x"; + out.push_back(kHex[ch >> 4U]); + out.push_back(kHex[ch & 0x0FU]); + } else { + out.push_back(static_cast(ch)); + } + } + return out; + } + + ScopedFaultGuard::ScopedFaultGuard(FaultPoint point) noexcept + : m_previous(g_fault_point) + { + g_fault_point = point; + } + + ScopedFaultGuard::~ScopedFaultGuard() noexcept + { + g_fault_point = m_previous; + } + + // ── ByteSource & ByteSink Adapters ─────────────────────────────────────── + + Void::Result::Result + SpanByteSource::read(std::span dst) + { + if (m_offset >= m_data.size() || dst.empty()) { + return std::size_t{0}; + } + const std::size_t n = std::min(dst.size(), m_data.size() - m_offset); + std::memcpy(dst.data(), m_data.data() + m_offset, n); + m_offset += n; + return n; + } + + struct FileByteSource::Impl { + OwnedFd fd{}; + }; + + FileByteSource::FileByteSource(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + FileByteSource::FileByteSource(FileByteSource&&) noexcept = default; + FileByteSource& + FileByteSource::operator=(FileByteSource&&) noexcept = default; + FileByteSource::~FileByteSource() = default; + + Void::Result::Result + FileByteSource::open(const std::filesystem::path& path) + { + OwnedFd fd{::open(path.c_str(), O_RDONLY | O_CLOEXEC)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: open '{}'", + sanitize_diagnostic_path(path.string())))}; + } + auto impl = std::make_unique(); + impl->fd = std::move(fd); + return FileByteSource{std::move(impl)}; + } + + Void::Result::Result + FileByteSource::read(std::span dst) + { + if (!m_impl || !m_impl->fd) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::FileByteSource: source is closed")}; + } + if (dst.empty()) { + return std::size_t{0}; + } + for (;;) { + const ssize_t n = + ::read(m_impl->fd.get(), dst.data(), dst.size()); + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSource: read")}; + } + return static_cast(n); + } + } + + Void::Result::Result + VectorByteSink::write(std::span src) + { + if (src.size() > m_max_bytes || m_bytes.size() > m_max_bytes - src.size()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::VectorByteSink: output exceeds buffer limit")}; + } + m_bytes.insert(m_bytes.end(), src.begin(), src.end()); + return {}; + } + + struct FileByteSink::Impl { + OwnedFd fd{}; + }; + + FileByteSink::FileByteSink(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + FileByteSink::FileByteSink(FileByteSink&&) noexcept = default; + FileByteSink& FileByteSink::operator=(FileByteSink&&) noexcept = default; + FileByteSink::~FileByteSink() = default; + + Void::Result::Result + FileByteSink::create(const std::filesystem::path& path) + { + OwnedFd fd{::open(path.c_str(), + O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, std::format("Archive: create '{}'", + sanitize_diagnostic_path(path.string())))}; + } + auto impl = std::make_unique(); + impl->fd = std::move(fd); + return FileByteSink{std::move(impl)}; + } + + Void::Result::Result + FileByteSink::write(std::span src) + { + if (!m_impl || !m_impl->fd) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::FileByteSink: sink is closed")}; + } + return write_all_fd(m_impl->fd.get(), src); + } + + Void::Result::Result FileByteSink::sync_and_close() + { + if (!m_impl || !m_impl->fd) { + return {}; + } + if (::fsync(m_impl->fd.get()) != 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSink: fsync")}; + } + const int raw = m_impl->fd.release(); + if (::close(raw) != 0) { + return std::unexpected{ + make_errno_error(errno, "Archive::FileByteSink: close")}; + } + return {}; + } + + // ── Reader ─────────────────────────────────────────────────────────────── + + struct Reader::Impl { + std::unique_ptr owned_source{}; + ByteSource* source{nullptr}; + ReadLimits limits{}; + std::stop_token stop{}; + std::optional deadline{}; + const Void::Time::MonotonicClock* clock{ + &Void::Time::SystemMonotonicClock::instance()}; + ArchiveReadPtr handle{nullptr, &archive_read_free}; + std::vector read_buf{}; + PathTracker tracker; + std::optional source_error{}; + bool has_active_file{false}; + bool reached_eof{false}; + bool poisoned{false}; + std::size_t entries_seen{0}; + std::uint64_t entry_bytes_read{0}; + std::uint64_t total_decompressed{0}; + std::uint64_t total_compressed{0}; + + explicit Impl(const ReadLimits& lim) + : limits(lim), read_buf(lim.transfer_buffer_bytes), + tracker(lim.max_metadata_bytes) + { + } + + [[nodiscard]] Void::Result::Result check_stop_deadline() const + { + if (stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::Reader: operation cancelled")}; + } + if (deadline.has_value() && clock->now() >= *deadline) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::timeout, + "Archive::Reader: deadline expired")}; + } + return {}; + } + + static la_ssize_t libarchive_read_cb(archive* a, void* client_data, + const void** buffer) + { + auto* self = static_cast(client_data); + if (auto chk = self->check_stop_deadline(); !chk.has_value()) { + self->source_error = std::move(chk.error()); + archive_set_error(a, ECANCELED, "cancelled or timed out"); + return -1; + } + auto res = self->source->read(self->read_buf); + if (!res.has_value()) { + self->source_error = std::move(res.error()); + archive_set_error(a, EIO, "source read failed"); + return -1; + } + const std::uint64_t n = static_cast(*res); + if (n > self->limits.max_compressed_bytes - + self->total_compressed) { + self->source_error = make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: compressed input exceeds limit"); + archive_set_error(a, EFBIG, + "compressed input exceeds limit"); + return -1; + } + self->total_compressed += n; + *buffer = self->read_buf.data(); + return static_cast(n); + } + }; + + Reader::Reader(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + Reader::~Reader() = default; + Reader::Reader(Reader&&) noexcept = default; + Reader& Reader::operator=(Reader&&) noexcept = default; + + Void::Result::Result Reader::open( + ByteSource& source, ReadLimits limits, std::stop_token stop, + std::optional deadline, + const Void::Time::MonotonicClock& clock) + { + if (auto valid = limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + auto impl = std::make_unique(limits); + impl->source = &source; + impl->stop = stop; + impl->deadline = deadline; + impl->clock = &clock; + + if (auto chk = impl->check_stop_deadline(); !chk.has_value()) { + return std::unexpected{std::move(chk.error())}; + } + + impl->handle = + ArchiveReadPtr{archive_read_new(), &archive_read_free}; + if (!impl->handle) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::Reader: cannot allocate libarchive reader")}; + } + (void)archive_read_support_filter_zstd(impl->handle.get()); + (void)archive_read_support_filter_none(impl->handle.get()); + (void)archive_read_support_format_tar(impl->handle.get()); + + if (archive_read_open2(impl->handle.get(), impl.get(), nullptr, + &Impl::libarchive_read_cb, nullptr, + nullptr) != ARCHIVE_OK) { + if (impl->source_error.has_value()) { + return std::unexpected{std::move(*impl->source_error)}; + } + return std::unexpected{make_libarchive_error( + impl->handle.get(), "open archive", + ArchiveErrorCode::unsupported_format)}; + } + return Reader{std::move(impl)}; + } + + Void::Result::Result Reader::open_file( + const std::filesystem::path& archive_path, ReadLimits limits, + std::stop_token stop, + std::optional deadline, + const Void::Time::MonotonicClock& clock) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + auto owned = std::make_unique(std::move(*file)); + auto reader = open(*owned, limits, stop, deadline, clock); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + reader->m_impl->owned_source = std::move(owned); + return reader; + } + + Void::Result::Result> Reader::next_entry() + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (m_impl->has_active_file) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: active entry must be drained or skipped " + "before advancing")}; + } + if (m_impl->reached_eof) { + return std::optional{std::nullopt}; + } + if (auto chk = m_impl->check_stop_deadline(); !chk.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(chk.error())}; + } + + archive_entry* entry = nullptr; + const int status = + archive_read_next_header(m_impl->handle.get(), &entry); + if (status == ARCHIVE_EOF) { + m_impl->reached_eof = true; + return std::optional{std::nullopt}; + } + if (status != ARCHIVE_OK) { + m_impl->poisoned = true; + if (m_impl->source_error.has_value()) { + return std::unexpected{std::move(*m_impl->source_error)}; + } + return std::unexpected{ + make_libarchive_error(m_impl->handle.get(), "read header")}; + } + + if (m_impl->entries_seen >= m_impl->limits.max_entries) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: entry count exceeds limit")}; + } + ++m_impl->entries_seen; + + const char* raw_path = archive_entry_pathname(entry); + if (raw_path == nullptr) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::Reader: entry has no pathname")}; + } + if (archive_entry_hardlink(entry) != nullptr || + archive_entry_symlink(entry) != nullptr) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive::Reader: links are not allowed ('{}')", + sanitize_diagnostic_path(raw_path)))}; + } + + const auto ftype = archive_entry_filetype(entry); + if (ftype != AE_IFDIR && ftype != AE_IFREG) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + std::format("Archive::Reader: special files are not allowed " + "('{}')", + sanitize_diagnostic_path(raw_path)))}; + } + + const bool is_dir = (ftype == AE_IFDIR); + auto vp = validate_archive_path(raw_path, is_dir, m_impl->limits); + if (!vp.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = m_impl->tracker.record(*vp, is_dir); !rec.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(rec.error())}; + } + + std::uint64_t declared_size = 0; + bool executable = false; + if (!is_dir) { + const auto raw_size = archive_entry_size(entry); + if (raw_size < 0) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::corrupt_archive, + "Archive::Reader: negative entry size")}; + } + declared_size = static_cast(raw_size); + if (declared_size > m_impl->limits.max_file_bytes || + declared_size > m_impl->limits.max_total_bytes - + m_impl->total_decompressed) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: declared entry size exceeds policy")}; + } + executable = (archive_entry_perm(entry) & 0111) != 0; + m_impl->has_active_file = true; + m_impl->entry_bytes_read = 0; + } + + return std::optional{EntryInfo{ + .path = std::move(vp->normalized), + .type = is_dir ? EntryType::Directory : EntryType::RegularFile, + .declared_size = declared_size, + .safe_mode = is_dir ? 0755U : (executable ? 0755U : 0644U), + .executable = executable, + .accepted = true, + }}; + } + + Void::Result::Result + Reader::read_chunk(std::span dst) + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (!m_impl->has_active_file) { + return std::size_t{0}; + } + if (dst.empty()) { + return std::size_t{0}; + } + if (auto chk = m_impl->check_stop_deadline(); !chk.has_value()) { + m_impl->poisoned = true; + return std::unexpected{std::move(chk.error())}; + } + + const std::size_t to_read = + std::min(dst.size(), m_impl->limits.transfer_buffer_bytes); + const la_ssize_t n = + archive_read_data(m_impl->handle.get(), dst.data(), to_read); + if (n == 0) { + m_impl->has_active_file = false; + return std::size_t{0}; + } + if (n < 0) { + m_impl->poisoned = true; + if (m_impl->source_error.has_value()) { + return std::unexpected{std::move(*m_impl->source_error)}; + } + return std::unexpected{ + make_libarchive_error(m_impl->handle.get(), "read entry data")}; + } + const auto amount = static_cast(n); + if (amount > m_impl->limits.max_file_bytes - m_impl->entry_bytes_read || + amount > m_impl->limits.max_total_bytes - + m_impl->total_decompressed) { + m_impl->poisoned = true; + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::Reader: actual decompressed bytes exceed limit")}; + } + m_impl->entry_bytes_read += amount; + m_impl->total_decompressed += amount; + return static_cast(n); + } + + Void::Result::Result Reader::skip_entry() + { + if (!m_impl || m_impl->poisoned) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::Reader: reader is moved-from or failed")}; + } + if (!m_impl->has_active_file) { + return std::uint64_t{0}; + } + // Explicitly decompress and account every byte so skipping cannot + // bypass file/total decompression limits. + std::vector scratch(m_impl->limits.transfer_buffer_bytes); + std::uint64_t skipped = 0; + for (;;) { + auto n = read_chunk(scratch); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + break; + } + skipped += static_cast(*n); + } + return skipped; + } + + std::size_t Reader::entries_seen() const noexcept + { + return m_impl ? m_impl->entries_seen : 0; + } + + std::uint64_t Reader::total_decompressed_bytes() const noexcept + { + return m_impl ? m_impl->total_decompressed : 0; + } + + std::uint64_t Reader::total_compressed_bytes() const noexcept + { + return m_impl ? m_impl->total_compressed : 0; + } + + // ── Listing ────────────────────────────────────────────────────────────── + + Void::Result::Result> + list_entries(ByteSource& source, ReadLimits limits, bool forensic) + { + if (auto valid = limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + + if (!forensic) { + auto reader = Reader::open(source, limits); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + std::vector out; + for (;;) { + auto next = reader->next_entry(); + if (!next.has_value()) { + return std::unexpected{std::move(next.error())}; + } + if (!next->has_value()) { + break; + } + if ((*next)->type == EntryType::RegularFile) { + if (auto skip = reader->skip_entry(); !skip.has_value()) { + return std::unexpected{std::move(skip.error())}; + } + } + out.push_back(std::move(**next)); + } + return out; + } + + // Opt-in forensic listing: reports rejected entries without writing. + struct ForensicState { + ByteSource* source{nullptr}; + ReadLimits limits{}; + std::vector buf{}; + std::uint64_t compressed{0}; + std::optional err{}; + }; + ForensicState st{&source, limits, + std::vector(limits.transfer_buffer_bytes)}; + ArchiveReadPtr handle{archive_read_new(), &archive_read_free}; + if (!handle) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::list_entries: cannot allocate reader")}; + } + (void)archive_read_support_filter_zstd(handle.get()); + (void)archive_read_support_filter_none(handle.get()); + (void)archive_read_support_format_tar(handle.get()); + + auto cb = [](archive* a, void* data, + const void** out_buf) -> la_ssize_t { + auto* s = static_cast(data); + auto r = s->source->read(s->buf); + if (!r.has_value()) { + s->err = std::move(r.error()); + archive_set_error(a, EIO, "read error"); + return -1; + } + const auto n = static_cast(*r); + if (n > s->limits.max_compressed_bytes - s->compressed) { + s->err = make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: compressed limit exceeded"); + archive_set_error(a, EFBIG, "compressed limit exceeded"); + return -1; + } + s->compressed += n; + *out_buf = s->buf.data(); + return static_cast(n); + }; + if (archive_read_open2(handle.get(), &st, nullptr, cb, nullptr, + nullptr) != ARCHIVE_OK) { + if (st.err.has_value()) { + return std::unexpected{std::move(*st.err)}; + } + return std::unexpected{make_libarchive_error( + handle.get(), "forensic open", + ArchiveErrorCode::unsupported_format)}; + } + + std::vector out; + PathTracker tracker{limits.max_metadata_bytes}; + std::size_t metadata_bytes = 0; + archive_entry* entry = nullptr; + for (;;) { + const int status = archive_read_next_header(handle.get(), &entry); + if (status == ARCHIVE_EOF) { + break; + } + if (status != ARCHIVE_OK) { + if (st.err.has_value()) { + return std::unexpected{std::move(*st.err)}; + } + return std::unexpected{ + make_libarchive_error(handle.get(), "forensic header")}; + } + if (out.size() >= limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: entry count exceeds limit")}; + } + + const char* raw_path = archive_entry_pathname(entry); + const std::string sanitized = + raw_path ? sanitize_diagnostic_path(raw_path) : ""; + if (sanitized.size() + 64U > limits.max_metadata_bytes || + metadata_bytes > + limits.max_metadata_bytes - (sanitized.size() + 64U)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::list_entries: metadata limit exceeded")}; + } + metadata_bytes += sanitized.size() + 64U; + + EntryInfo info; + info.path = sanitized; + const auto ftype = archive_entry_filetype(entry); + if (archive_entry_hardlink(entry) != nullptr) { + info.type = EntryType::Hardlink; + info.accepted = false; + info.rejection_reason = "hardlink disallowed"; + } else if (archive_entry_symlink(entry) != nullptr || + ftype == AE_IFLNK) { + info.type = EntryType::Symlink; + info.accepted = false; + info.rejection_reason = "symlink disallowed"; + } else if (ftype != AE_IFDIR && ftype != AE_IFREG) { + info.type = EntryType::Other; + info.accepted = false; + info.rejection_reason = "special file disallowed"; + } else { + const bool is_dir = (ftype == AE_IFDIR); + info.type = + is_dir ? EntryType::Directory : EntryType::RegularFile; + info.declared_size = + archive_entry_size(entry) > 0 + ? static_cast(archive_entry_size(entry)) + : 0; + info.executable = + !is_dir && ((archive_entry_perm(entry) & 0111) != 0); + info.safe_mode = + is_dir ? 0755U : (info.executable ? 0755U : 0644U); + auto vp = validate_archive_path(raw_path ? raw_path : "", + is_dir, limits); + if (!vp.has_value()) { + info.accepted = false; + info.rejection_reason = vp.error().message(); + } else if (auto rec = tracker.record(*vp, is_dir); + !rec.has_value()) { + info.accepted = false; + info.rejection_reason = rec.error().message(); + } else { + info.path = std::move(vp->normalized); + info.accepted = true; + } + } + out.push_back(std::move(info)); + (void)archive_read_data_skip(handle.get()); + } + return out; + } + + Void::Result::Result> + list_entries(const std::filesystem::path& archive_path, + ReadLimits limits, bool forensic) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + return list_entries(*file, limits, forensic); + } + + // ── StagedTree & Atomic Publication ────────────────────────────────────── + + struct StagedTree::Impl { + OwnedFd parent_fd{}; + OwnedFd stage_fd{}; + std::filesystem::path parent_path{}; + std::filesystem::path staging_root{}; + std::filesystem::path tree_path{}; + std::string staging_id{}; + std::size_t entries{0}; + std::uint64_t bytes{0}; + std::vector inventory{}; + bool published{false}; + bool discarded{false}; + + ~Impl() noexcept + { + if (!published && !discarded && parent_fd && !staging_id.empty()) { + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), staging_id); + } + } + }; + + StagedTree::StagedTree(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + StagedTree::~StagedTree() noexcept = default; + StagedTree::StagedTree(StagedTree&&) noexcept = default; + StagedTree& StagedTree::operator=(StagedTree&&) noexcept = default; + + bool StagedTree::valid() const noexcept + { + return m_impl != nullptr && !m_impl->discarded; + } + bool StagedTree::published() const noexcept + { + return m_impl != nullptr && m_impl->published; + } + std::string_view StagedTree::staging_id() const noexcept + { + return m_impl ? std::string_view{m_impl->staging_id} + : std::string_view{}; + } + const std::filesystem::path& StagedTree::staging_root() const noexcept + { + static const std::filesystem::path kEmpty; + return m_impl ? m_impl->staging_root : kEmpty; + } + const std::filesystem::path& StagedTree::tree_path() const noexcept + { + static const std::filesystem::path kEmpty; + return m_impl ? m_impl->tree_path : kEmpty; + } + std::size_t StagedTree::entries() const noexcept + { + return m_impl ? m_impl->entries : 0; + } + std::uint64_t StagedTree::bytes() const noexcept + { + return m_impl ? m_impl->bytes : 0; + } + const std::vector& StagedTree::inventory() const noexcept + { + static const std::vector kEmpty; + return m_impl ? m_impl->inventory : kEmpty; + } + + Void::Result::Result StagedTree::discard() + { + if (!m_impl || m_impl->discarded) { + return {}; + } + if (m_impl->published) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::StagedTree::discard: tree is already published")}; + } + m_impl->stage_fd.reset(); + auto res = remove_stage_dir(m_impl->parent_fd.get(), m_impl->staging_id); + if (!res.has_value()) { + return std::unexpected{res.error().with_context(std::format( + "retryable staging_id={}", m_impl->staging_id))}; + } + m_impl->discarded = true; + return {}; + } + + Void::Result::Result + StagedTree::publish(std::string_view new_child_name) + { + if (!m_impl || m_impl->discarded || m_impl->published) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive::StagedTree::publish: invalid or already published " + "tree")}; + } + if (!is_safe_single_component(new_child_name)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::StagedTree::publish: new_child_name must be a safe " + "immediate directory name")}; + } + + const std::string target_name{new_child_name}; + const auto dest_path = m_impl->parent_path / target_name; + + int rc = -1; + int err = 0; + if (g_fault_point == FaultPoint::rename_enosys) { + errno = ENOSYS; + rc = -1; + err = ENOSYS; + } else { +#if defined(__linux__) && defined(SYS_renameat2) + rc = static_cast(::syscall( + SYS_renameat2, m_impl->stage_fd.get(), "tree", + m_impl->parent_fd.get(), target_name.c_str(), + static_cast(RENAME_NOREPLACE))); + err = errno; +#else + rc = -1; + err = ENOSYS; +#endif + } + + if (rc != 0) { + if (err == ENOSYS || err == EINVAL) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsupported_capability, + "Archive::StagedTree::publish: atomic no-replace rename " + "is unsupported on this filesystem", + std::error_code{err, std::generic_category()})}; + } + return std::unexpected{make_errno_error( + err, std::format("Archive::StagedTree::publish '{}'", + sanitize_diagnostic_path(target_name)))}; + } + + // Rename succeeded; publication is no longer reversible as staging. + m_impl->published = true; + + bool sync_failed = false; + int sync_err = 0; + if (g_fault_point == FaultPoint::post_rename_parent_sync) { + sync_failed = true; + sync_err = EIO; + } else if (::fsync(m_impl->parent_fd.get()) != 0) { + sync_failed = true; + sync_err = errno; + } + + // Best-effort cleanup of now-empty staging wrapper metadata. + m_impl->stage_fd.reset(); + (void)remove_stage_dir(m_impl->parent_fd.get(), m_impl->staging_id); + + if (sync_failed) { + return PublicationReceipt{ + .outcome = PublicationOutcome::Unknown, + .destination_path = dest_path, + .staging_id = m_impl->staging_id, + .entries = m_impl->entries, + .bytes = m_impl->bytes, + .diagnostic = std::format( + "parent directory fsync failed after atomic rename ({}): " + "publication durability is unknown; inspect destination " + "rather than assuming rollback", + std::strerror(sync_err)), + }; + } + + return PublicationReceipt{ + .outcome = PublicationOutcome::Published, + .destination_path = dest_path, + .staging_id = m_impl->staging_id, + .entries = m_impl->entries, + .bytes = m_impl->bytes, + .diagnostic = {}, + }; + } + + namespace + { + [[nodiscard]] Void::Result::Result extract_into_pinned_stage( + ByteSource& source, int stage_fd, int tree_fd, + const StagedExtractionOptions& options, std::uint64_t max_rss_bytes, + std::vector& out_inventory, std::uint64_t& out_bytes) + { + const auto& clock = + options.clock ? *options.clock + : Void::Time::SystemMonotonicClock::instance(); + auto reader = Reader::open(source, options.limits, options.stop, + options.deadline, clock); + if (!reader.has_value()) { + return std::unexpected{std::move(reader.error())}; + } + + out_inventory.clear(); + out_bytes = 0; + std::set created_dirs; + std::vector chunk(options.limits.transfer_buffer_bytes); + auto last_progress = clock.now() - std::chrono::seconds{1}; + + auto emit_progress = [&](const std::string& path, bool force) { + if (!options.on_progress) { + return; + } + const auto now = clock.now(); + if (!force && now - last_progress < + std::chrono::milliseconds{100}) { + return; + } + last_progress = now; + try { + options.on_progress(ProgressEvent{ + .entries_processed = out_inventory.size(), + .bytes_extracted = out_bytes, + .current_path = sanitize_diagnostic_path(path), + }); + } catch (...) { + // Progress failure never changes extraction success. + } + }; + + auto check_rss = [&]() -> Void::Result::Result { + if (max_rss_bytes == 0) { + return {}; + } + if (auto rss = current_rss_bytes(); + rss.has_value() && *rss > max_rss_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: decoder exceeded configured RSS limit")}; + } + return {}; + }; + + for (;;) { + if (auto r = check_rss(); !r.has_value()) { + return r; + } + auto next = reader->next_entry(); + if (!next.has_value()) { + return std::unexpected{std::move(next.error())}; + } + if (!next->has_value()) { + break; + } + EntryInfo info = std::move(**next); + auto vp = validate_archive_path( + info.path, info.type == EntryType::Directory, + options.limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + + // Record every implicit parent dir for bottom-up fsync. + std::string prefix; + for (std::size_t i = 0; i + 1 < vp->components.size(); ++i) { + if (i > 0) { + prefix.push_back('/'); + } + prefix.append(vp->components[i]); + created_dirs.insert(prefix); + } + + auto parent_dir = open_or_create_relative_dir( + tree_fd, vp->components, vp->components.size() - 1U); + if (!parent_dir.has_value()) { + return std::unexpected{std::move(parent_dir.error())}; + } + const std::string& leaf = vp->components.back(); + + if (info.type == EntryType::Directory) { + if (::mkdirat(parent_dir->get(), leaf.c_str(), 0755) != 0 && + errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: mkdirat staged directory")}; + } + created_dirs.insert(info.path); + info.declared_size = 0; + info.safe_mode = 0755U; + out_inventory.push_back(std::move(info)); + emit_progress(out_inventory.back().path, false); + continue; + } + + const mode_t mode = + (options.preserve_executable_bit && info.executable) ? 0755 + : 0644; + OwnedFd out_fd{::openat( + parent_dir->get(), leaf.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, mode)}; + if (!out_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: openat staged file")}; + } + + std::uint64_t actual_file_bytes = 0; + for (;;) { + if (auto r = check_rss(); !r.has_value()) { + return r; + } + auto n = reader->read_chunk(chunk); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + break; + } + if (auto w = write_all_fd( + out_fd.get(), + std::span{chunk.data(), *n}); + !w.has_value()) { + return w; + } + actual_file_bytes += static_cast(*n); + out_bytes += static_cast(*n); + } + if (::fsync(out_fd.get()) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staged regular file")}; + } + const int raw_fd = out_fd.release(); + if (::close(raw_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: close staged regular file")}; + } + info.declared_size = actual_file_bytes; + info.safe_mode = static_cast(mode); + out_inventory.push_back(std::move(info)); + emit_progress(out_inventory.back().path, false); + } + + if (auto synced = + fsync_directories_bottom_up(tree_fd, created_dirs); + !synced.has_value()) { + return synced; + } + + const std::string inv_text = serialize_inventory(out_inventory); + if (inv_text.size() > options.limits.max_metadata_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive: completion inventory exceeds metadata limit")}; + } + if (auto inv_w = write_file_at(stage_fd, "inventory.txt", inv_text, + 0600); + !inv_w.has_value()) { + return inv_w; + } + if (::fsync(stage_fd) != 0) { + return std::unexpected{make_errno_error( + errno, "Archive: fsync staging root")}; + } + emit_progress("", true); + return {}; + } + + struct AllocatedStage { + OwnedFd parent_fd{}; + OwnedFd stage_fd{}; + OwnedFd tree_fd{}; + std::string stage_name{}; + std::filesystem::path stage_path{}; + std::filesystem::path tree_path{}; + }; + + [[nodiscard]] Void::Result::Result + allocate_stage(const std::filesystem::path& parent_directory) + { + std::error_code ec; + std::filesystem::create_directories(parent_directory, ec); + if (ec) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + std::format("Archive: cannot create parent directory: {}", + ec.message()), + ec)}; + } + OwnedFd parent_fd{::open(parent_directory.c_str(), kDirOpenFlags)}; + if (!parent_fd) { + return std::unexpected{make_errno_error( + errno, "Archive: open parent directory")}; + } + + AllocatedStage allocated; + for (std::size_t attempt = 0; attempt < 128; ++attempt) { + const auto seq = + g_stage_counter.fetch_add(1, std::memory_order_relaxed); + const std::string name = + std::format("{}{}-{}", kStagePrefix, + static_cast(::getpid()), seq); + if (::mkdirat(parent_fd.get(), name.c_str(), 0700) == 0) { + OwnedFd stage_fd{ + ::openat(parent_fd.get(), name.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + const int err = errno; + (void)::unlinkat(parent_fd.get(), name.c_str(), + AT_REMOVEDIR); + return std::unexpected{make_errno_error( + err, "Archive: open created staging dir")}; + } + const auto epoch_s = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + const std::string marker = std::format( + "VOID_STAGE_MARKER_V1\npid={}\nuid={}\ncreated={}\n", + static_cast(::getpid()), + static_cast(::geteuid()), epoch_s); + if (auto mw = write_file_at( + stage_fd.get(), std::string{kMarkerFilename}.c_str(), + marker, 0600); + !mw.has_value()) { + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{std::move(mw.error())}; + } + if (::mkdirat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + 0755) != 0) { + const int err = errno; + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{make_errno_error( + err, "Archive: mkdirat staging tree")}; + } + OwnedFd tree_fd{::openat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + kDirOpenFlags)}; + if (!tree_fd) { + const int err = errno; + stage_fd.reset(); + (void)remove_stage_dir(parent_fd.get(), name); + return std::unexpected{make_errno_error( + err, "Archive: open staging tree")}; + } + allocated.parent_fd = std::move(parent_fd); + allocated.stage_fd = std::move(stage_fd); + allocated.tree_fd = std::move(tree_fd); + allocated.stage_name = name; + allocated.stage_path = parent_directory / name; + allocated.tree_path = allocated.stage_path / kTreeSubdir; + return allocated; + } + if (errno != EEXIST) { + return std::unexpected{make_errno_error( + errno, "Archive: create exclusive staging dir")}; + } + } + return std::unexpected{make_archive_error( + ArchiveErrorCode::conflict, + "Archive: exhausted attempts to create exclusive staging dir")}; + } + } // namespace + + Void::Result::Result + extract_staged(ByteSource& source, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options) + { + if (auto valid = options.limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + + auto stage = allocate_stage(parent_directory); + if (!stage.has_value()) { + return std::unexpected{std::move(stage.error())}; + } + + std::vector inventory; + std::uint64_t total_bytes = 0; + auto extracted = extract_into_pinned_stage( + source, stage->stage_fd.get(), stage->tree_fd.get(), options, 0, + inventory, total_bytes); + if (!extracted.has_value()) { + auto primary_err = std::move(extracted.error()); + stage->tree_fd.reset(); + stage->stage_fd.reset(); + if (auto clean = remove_stage_dir(stage->parent_fd.get(), + stage->stage_name); + !clean.has_value()) { + primary_err = primary_err.with_context(std::format( + "staging cleanup also failed (retryable staging_id={}): {}", + stage->stage_name, clean.error().message())); + } + return std::unexpected{std::move(primary_err)}; + } + + auto impl = std::make_unique(); + impl->parent_fd = std::move(stage->parent_fd); + impl->stage_fd = std::move(stage->stage_fd); + impl->parent_path = parent_directory; + impl->staging_root = std::move(stage->stage_path); + impl->tree_path = std::move(stage->tree_path); + impl->staging_id = std::move(stage->stage_name); + impl->entries = inventory.size(); + impl->bytes = total_bytes; + impl->inventory = std::move(inventory); + return StagedTree{std::move(impl)}; + } + + Void::Result::Result + extract_staged(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const StagedExtractionOptions& options) + { + auto file = FileByteSource::open(archive_path); + if (!file.has_value()) { + return std::unexpected{std::move(file.error())}; + } + return extract_staged(*file, parent_directory, options); + } + + Void::Result::Result + cleanup_stale_staging(const std::filesystem::path& parent_directory, + std::chrono::seconds min_age) + { + OwnedFd parent_fd{::open(parent_directory.c_str(), kDirOpenFlags)}; + if (!parent_fd) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: open parent")}; + } + OwnedFd dup_fd{::openat(parent_fd.get(), ".", kDirOpenFlags)}; + if (!dup_fd) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: dup parent")}; + } + DIR* dir = ::fdopendir(dup_fd.get()); + if (dir == nullptr) { + return std::unexpected{make_errno_error( + errno, "Archive::cleanup_stale_staging: fdopendir")}; + } + (void)dup_fd.release(); + + const uid_t my_uid = ::geteuid(); + const auto now_s = + std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()) + .count(); + std::size_t removed = 0; + + for (;;) { + errno = 0; + struct dirent* ent = ::readdir(dir); + if (ent == nullptr) { + break; + } + const std::string_view name{ent->d_name}; + if (!name.starts_with(kStagePrefix)) { + continue; + } + struct stat st{}; + if (::fstatat(parent_fd.get(), ent->d_name, &st, + AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISDIR(st.st_mode) || st.st_uid != my_uid) { + continue; + } + OwnedFd stage_fd{ + ::openat(parent_fd.get(), ent->d_name, kDirOpenFlags)}; + if (!stage_fd) { + continue; + } + // Require exclusive operation marker owned by current user. + struct stat mst{}; + if (::fstatat(stage_fd.get(), std::string{kMarkerFilename}.c_str(), + &mst, AT_SYMLINK_NOFOLLOW) != 0 || + !S_ISREG(mst.st_mode) || mst.st_uid != my_uid) { + continue; + } + OwnedFd mfd{::openat(stage_fd.get(), + std::string{kMarkerFilename}.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!mfd) { + continue; + } + std::array mbuf{}; + const ssize_t mlen = ::read(mfd.get(), mbuf.data(), mbuf.size()); + mfd.reset(); + stage_fd.reset(); + if (mlen <= 0) { + continue; + } + const std::string_view mtext{mbuf.data(), + static_cast(mlen)}; + if (!mtext.starts_with("VOID_STAGE_MARKER_V1\n")) { + continue; + } + const auto created_pos = mtext.find("created="); + if (created_pos == std::string_view::npos) { + continue; + } + const auto created_end = mtext.find('\n', created_pos); + const std::string_view ts_view = mtext.substr( + created_pos + 8U, + created_end == std::string_view::npos + ? std::string_view::npos + : created_end - (created_pos + 8U)); + std::int64_t created_s = 0; + const auto tres = std::from_chars( + ts_view.data(), ts_view.data() + ts_view.size(), created_s); + if (tres.ec != std::errc{} || + tres.ptr != ts_view.data() + ts_view.size()) { + continue; + } + if (now_s - created_s < min_age.count()) { + continue; + } + if (auto rr = remove_stage_dir(parent_fd.get(), name); + rr.has_value()) { + ++removed; + } + } + (void)::closedir(dir); + return removed; + } + + // ── Reproducible Archive Creation ──────────────────────────────────────── + + Void::Result::Result + create_archive(ByteSink& sink, std::span entries, + const CreationOptions& options) + { + if (auto valid = options.limits.validate(); !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + if (entries.size() > options.limits.max_entries) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::create_archive: entry count exceeds limit")}; + } + + struct NormalizedCreate { + std::string path{}; + const CreateEntry* src{nullptr}; + std::uint64_t size{0}; + OwnedFd file_fd{}; + }; + + PathTracker tracker{options.limits.max_metadata_bytes}; + std::vector normalized; + normalized.reserve(entries.size()); + std::uint64_t total_bytes = 0; + + for (const auto& entry : entries) { + if (options.stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::create_archive: cancelled")}; + } + if (entry.type != EntryType::RegularFile && + entry.type != EntryType::Directory) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::create_archive: only regular files and " + "directories are allowed")}; + } + const bool is_dir = (entry.type == EntryType::Directory); + auto vp = validate_archive_path(entry.path, is_dir, options.limits); + if (!vp.has_value()) { + return std::unexpected{std::move(vp.error())}; + } + if (auto rec = tracker.record(*vp, is_dir); !rec.has_value()) { + return std::unexpected{std::move(rec.error())}; + } + + NormalizedCreate item; + item.path = std::move(vp->normalized); + item.src = &entry; + if (!is_dir) { + if (entry.source_file.has_value()) { + OwnedFd fd{::open(entry.source_file->c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!fd) { + return std::unexpected{make_errno_error( + errno, "Archive::create_archive: open source file " + "(links disallowed)")}; + } + struct stat st{}; + if (::fstat(fd.get(), &st) != 0 || !S_ISREG(st.st_mode)) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::unsafe_entry, + "Archive::create_archive: source_file is not a " + "regular file")}; + } + item.size = static_cast(st.st_size); + item.file_fd = std::move(fd); + } else { + item.size = static_cast(entry.content.size()); + } + if (item.size > options.limits.max_file_bytes || + item.size > options.limits.max_total_bytes - total_bytes) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::create_archive: content size exceeds limit")}; + } + total_bytes += item.size; + } + normalized.push_back(std::move(item)); + } + + // Sort lexicographically for reproducible archives. + std::sort(normalized.begin(), normalized.end(), + [](const NormalizedCreate& a, const NormalizedCreate& b) { + return a.path < b.path; + }); + + struct SinkBridge { + ByteSink* sink{nullptr}; + std::optional err{}; + }; + SinkBridge bridge{&sink}; + + ArchiveWritePtr writer{archive_write_new(), &archive_write_free}; + if (!writer) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::create_archive: cannot allocate writer")}; + } + if (options.compression == ArchiveCompression::Zstd) { + if (archive_write_add_filter_zstd(writer.get()) != ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "add zstd filter")}; + } + } else { + if (archive_write_add_filter_none(writer.get()) != ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "add none filter")}; + } + } + if (archive_write_set_format_pax_restricted(writer.get()) != + ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "set pax_restricted")}; + } + if (archive_write_set_bytes_in_last_block(writer.get(), 1) != + ARCHIVE_OK) { + return std::unexpected{ + make_libarchive_error(writer.get(), "set bytes_in_last_block")}; + } + + auto write_cb = [](archive* a, void* data, const void* buf, + std::size_t len) -> la_ssize_t { + auto* b = static_cast(data); + auto res = b->sink->write(std::span{ + static_cast(buf), len}); + if (!res.has_value()) { + b->err = std::move(res.error()); + archive_set_error(a, EIO, "sink write failed"); + return -1; + } + return static_cast(len); + }; + if (archive_write_open2(writer.get(), &bridge, nullptr, write_cb, + nullptr, nullptr) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "open archive writer")}; + } + + std::vector io_buf(options.limits.transfer_buffer_bytes); + for (auto& item : normalized) { + if (options.stop.stop_requested()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::create_archive: cancelled")}; + } + ArchiveEntryPtr ae{archive_entry_new(), &archive_entry_free}; + const bool is_dir = (item.src->type == EntryType::Directory); + const std::string wire_path = + is_dir ? (item.path + "/") : item.path; + archive_entry_set_pathname(ae.get(), wire_path.c_str()); + archive_entry_set_filetype(ae.get(), is_dir ? AE_IFDIR : AE_IFREG); + archive_entry_set_perm( + ae.get(), is_dir ? 0755 : (item.src->executable ? 0755 : 0644)); + if (options.reproducible) { + archive_entry_set_mtime(ae.get(), 0, 0); + archive_entry_set_uid(ae.get(), 0); + archive_entry_set_gid(ae.get(), 0); + archive_entry_set_uname(ae.get(), ""); + archive_entry_set_gname(ae.get(), ""); + } + if (!is_dir) { + archive_entry_set_size(ae.get(), + static_cast(item.size)); + } + + if (archive_write_header(writer.get(), ae.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "write header")}; + } + + if (!is_dir) { + if (item.file_fd) { + std::uint64_t remaining = item.size; + while (remaining > 0) { + const std::size_t want = static_cast( + std::min(remaining, io_buf.size())); + const ssize_t r = + ::read(item.file_fd.get(), io_buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::io_error, + "Archive::create_archive: source file shrunk " + "or read failed")}; + } + std::size_t off = 0; + while (off < static_cast(r)) { + const la_ssize_t w = archive_write_data( + writer.get(), io_buf.data() + off, + static_cast(r) - off); + if (w < 0) { + if (bridge.err.has_value()) { + return std::unexpected{ + std::move(*bridge.err)}; + } + return std::unexpected{make_libarchive_error( + writer.get(), "write data")}; + } + off += static_cast(w); + } + remaining -= static_cast(r); + } + } else { + std::size_t off = 0; + while (off < item.src->content.size()) { + const la_ssize_t w = archive_write_data( + writer.get(), item.src->content.data() + off, + item.src->content.size() - off); + if (w < 0) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{make_libarchive_error( + writer.get(), "write data")}; + } + off += static_cast(w); + } + } + } + + if (archive_write_finish_entry(writer.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "finish entry")}; + } + } + + if (archive_write_close(writer.get()) != ARCHIVE_OK) { + if (bridge.err.has_value()) { + return std::unexpected{std::move(*bridge.err)}; + } + return std::unexpected{ + make_libarchive_error(writer.get(), "close archive writer")}; + } + return {}; + } + + Void::Result::Result + create_archive(const std::filesystem::path& output_path, + std::span entries, + const CreationOptions& options) + { + auto sink = FileByteSink::create(output_path); + if (!sink.has_value()) { + return std::unexpected{std::move(sink.error())}; + } + if (auto res = create_archive(*sink, entries, options); + !res.has_value()) { + return res; + } + return sink->sync_and_close(); + } + + // ── Isolated Child Decoder Profile ─────────────────────────────────────── + + Void::Result::Result + extract_staged_isolated(const std::filesystem::path& archive_path, + const std::filesystem::path& parent_directory, + const IsolationOptions& options) + { + if (options.worker_executable.empty()) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::extract_staged_isolated: worker_executable is " + "required")}; + } + if (auto valid = options.extraction.limits.validate(); + !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + if (options.timeout <= std::chrono::milliseconds{0}) { + return std::unexpected{make_archive_error( + ArchiveErrorCode::invalid_argument, + "Archive::extract_staged_isolated: timeout must be positive")}; + } + + auto stage = allocate_stage(parent_directory); + if (!stage.has_value()) { + return std::unexpected{std::move(stage.error())}; + } + + auto cleanup_on_fail = [&](Void::Result::Error primary) + -> Void::Result::Result { + stage->tree_fd.reset(); + stage->stage_fd.reset(); + if (auto clean = remove_stage_dir(stage->parent_fd.get(), + stage->stage_name); + !clean.has_value()) { + primary = primary.with_context(std::format( + "staging cleanup failed (retryable staging_id={})", + stage->stage_name)); + } + return std::unexpected{std::move(primary)}; + }; + + const auto& lim = options.extraction.limits; + Void::Process::SpawnOptions spawn_opts{}; + spawn_opts.executable = options.worker_executable; + spawn_opts.arguments = { + "--archive", + archive_path.string(), + "--stage", + stage->stage_path.string(), + "--max-entries", + std::to_string(lim.max_entries), + "--max-file", + std::to_string(lim.max_file_bytes), + "--max-total", + std::to_string(lim.max_total_bytes), + "--max-compressed", + std::to_string(lim.max_compressed_bytes), + "--max-metadata", + std::to_string(lim.max_metadata_bytes), + "--max-rss", + std::to_string(options.max_rss_bytes), + "--timeout-ms", + std::to_string(options.timeout.count()), + "--preserve-exec", + options.extraction.preserve_executable_bit ? "1" : "0", + "--allow-zero", + lim.allow_zero_entries ? "1" : "0", + }; + spawn_opts.stdin_pipe = false; + spawn_opts.stdout_pipe = true; + spawn_opts.stderr_pipe = true; + spawn_opts.search_path = false; + spawn_opts.new_process_group = true; + + auto child = Void::Process::spawn(spawn_opts); + if (!child.has_value()) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::isolation_failed, + std::format("Archive::extract_staged_isolated: spawn failed: " + "{}", + child.error().message()))); + } + + Void::Process::CaptureLimits cap{}; + cap.max_stdout_bytes = 64 * 1024; + cap.max_stderr_bytes = 64 * 1024; + cap.overflow_policy = Void::Process::OverflowPolicy::drain_and_truncate; + + auto comm = Void::Process::communicate_blocking( + *child, {}, cap, options.timeout, options.extraction.stop); + if (!comm.has_value()) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::isolation_failed, + std::format("Archive::extract_staged_isolated: communicate " + "failed: {}", + comm.error().message()))); + } + if (comm->cancelled) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::cancelled, + "Archive::extract_staged_isolated: cancelled")); + } + if (comm->timed_out) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::timeout, + "Archive::extract_staged_isolated: worker timed out")); + } + if (!comm->status.exited || comm->status.code != 0) { + const auto code = comm->status.exited && comm->status.code == 42 + ? ArchiveErrorCode::limit_exceeded + : ArchiveErrorCode::isolation_failed; + return cleanup_on_fail(make_archive_error( + code, + std::format("Archive::extract_staged_isolated: worker failed " + "(exited={}, code={}, signal={}): {}", + comm->status.exited, comm->status.code, + comm->status.signal, + sanitize_diagnostic_path(comm->err)))); + } + + // Parent independently verifies inventory & staged tree before + // granting publication authority. + OwnedFd inv_fd{::openat(stage->stage_fd.get(), + std::string{kInventoryFilename}.c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!inv_fd) { + return cleanup_on_fail(make_errno_error( + errno, "Archive::extract_staged_isolated: missing inventory")); + } + std::string inv_text; + std::array rbuf{}; + for (;;) { + const ssize_t n = ::read(inv_fd.get(), rbuf.data(), rbuf.size()); + if (n < 0 && errno == EINTR) { + continue; + } + if (n < 0) { + return cleanup_on_fail(make_errno_error( + errno, + "Archive::extract_staged_isolated: read inventory")); + } + if (n == 0) { + break; + } + if (inv_text.size() + static_cast(n) > + lim.max_metadata_bytes) { + return cleanup_on_fail(make_archive_error( + ArchiveErrorCode::limit_exceeded, + "Archive::extract_staged_isolated: inventory exceeds " + "metadata limit")); + } + inv_text.append(rbuf.data(), static_cast(n)); + } + inv_fd.reset(); + + auto parsed_inv = parse_inventory(inv_text, lim); + if (!parsed_inv.has_value()) { + return cleanup_on_fail(std::move(parsed_inv.error())); + } + + std::uint64_t verified_bytes = 0; + if (auto vr = verify_staged_tree_on_disk( + stage->tree_fd.get(), *parsed_inv, lim, verified_bytes); + !vr.has_value()) { + return cleanup_on_fail(std::move(vr.error())); + } + if (::fsync(stage->stage_fd.get()) != 0) { + return cleanup_on_fail(make_errno_error( + errno, "Archive::extract_staged_isolated: fsync staging root")); + } + + auto impl = std::make_unique(); + impl->parent_fd = std::move(stage->parent_fd); + impl->stage_fd = std::move(stage->stage_fd); + impl->parent_path = parent_directory; + impl->staging_root = std::move(stage->stage_path); + impl->tree_path = std::move(stage->tree_path); + impl->staging_id = std::move(stage->stage_name); + impl->entries = parsed_inv->size(); + impl->bytes = verified_bytes; + impl->inventory = std::move(*parsed_inv); + return StagedTree{std::move(impl)}; + } + + int run_isolated_worker_main(int argc, char** argv) + { + std::filesystem::path archive_path; + std::filesystem::path stage_path; + StagedExtractionOptions opts{}; + std::uint64_t max_rss_bytes = 128ULL * 1024 * 1024; + std::uint64_t timeout_ms = 60'000; + + auto parse_u64 = [](const char* s, std::uint64_t& out) -> bool { + if (s == nullptr) { + return false; + } + const std::string_view sv{s}; + auto res = + std::from_chars(sv.data(), sv.data() + sv.size(), out); + return res.ec == std::errc{} && res.ptr == sv.data() + sv.size(); + }; + + for (int i = 1; i < argc; ++i) { + const std::string_view arg{argv[i]}; + auto next_val = [&]() -> const char* { + return (i + 1 < argc) ? argv[++i] : nullptr; + }; + std::uint64_t v = 0; + if (arg == "--archive") { + if (const char* p = next_val()) { + archive_path = p; + } + } else if (arg == "--stage") { + if (const char* p = next_val()) { + stage_path = p; + } + } else if (arg == "--max-entries" && parse_u64(next_val(), v)) { + opts.limits.max_entries = static_cast(v); + } else if (arg == "--max-file" && parse_u64(next_val(), v)) { + opts.limits.max_file_bytes = v; + } else if (arg == "--max-total" && parse_u64(next_val(), v)) { + opts.limits.max_total_bytes = v; + } else if (arg == "--max-compressed" && parse_u64(next_val(), v)) { + opts.limits.max_compressed_bytes = v; + } else if (arg == "--max-metadata" && parse_u64(next_val(), v)) { + opts.limits.max_metadata_bytes = static_cast(v); + } else if (arg == "--max-rss" && parse_u64(next_val(), v)) { + max_rss_bytes = v; + } else if (arg == "--timeout-ms" && parse_u64(next_val(), v)) { + timeout_ms = v; + } else if (arg == "--preserve-exec" && parse_u64(next_val(), v)) { + opts.preserve_executable_bit = (v != 0); + } else if (arg == "--allow-zero" && parse_u64(next_val(), v)) { + opts.limits.allow_zero_entries = (v != 0); + } else { + const std::string msg = "unknown worker argument\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 2; + } + } + + if (archive_path.empty() || stage_path.empty()) { + const std::string msg = "missing --archive or --stage\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 2; + } + + // Apply safe OS resource limits (guard RLIMIT_AS under ASan; RSS is + // enforced via /proc/self/statm directly). + { + const rlim_t cpu_secs = + static_cast(std::max( + 1, (timeout_ms + 999ULL) / 1000ULL + 1ULL)); + struct rlimit rl_cpu{cpu_secs, cpu_secs}; + (void)::setrlimit(RLIMIT_CPU, &rl_cpu); + + const rlim_t fsize_cap = static_cast( + std::max(opts.limits.max_file_bytes, + opts.limits.max_metadata_bytes) + + 1024ULL * 1024ULL); + struct rlimit rl_fsize{fsize_cap, fsize_cap}; + (void)::setrlimit(RLIMIT_FSIZE, &rl_fsize); + + struct rlimit rl_nofile{128, 128}; + (void)::setrlimit(RLIMIT_NOFILE, &rl_nofile); + } + + opts.deadline = Void::Time::SystemMonotonicClock::instance().now() + + std::chrono::milliseconds{timeout_ms}; + + OwnedFd stage_fd{::open(stage_path.c_str(), kDirOpenFlags)}; + if (!stage_fd) { + const std::string msg = "cannot open stage dir\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 3; + } + OwnedFd tree_fd{::openat(stage_fd.get(), + std::string{kTreeSubdir}.c_str(), + kDirOpenFlags)}; + if (!tree_fd) { + const std::string msg = "cannot open stage tree dir\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 3; + } + + auto source = FileByteSource::open(archive_path); + if (!source.has_value()) { + const std::string msg = source.error().message() + "\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + return 4; + } + + std::vector inventory; + std::uint64_t bytes = 0; + auto res = extract_into_pinned_stage( + *source, stage_fd.get(), tree_fd.get(), opts, max_rss_bytes, + inventory, bytes); + if (!res.has_value()) { + const std::string msg = res.error().message() + "\n"; + (void)::write(STDERR_FILENO, msg.data(), msg.size()); + if (res.error().code().value == + static_cast(ArchiveErrorCode::limit_exceeded)) { + return 42; + } + return 5; + } + return 0; + } + +} // namespace Void::Archive diff --git a/src/Archive/module.cmake b/src/Archive/module.cmake index b2b2c52..824c085 100644 --- a/src/Archive/module.cmake +++ b/src/Archive/module.cmake @@ -1,4 +1,4 @@ void_add_module(Archive - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Time System EXTERNAL_DEPS LibArchive::LibArchive ) diff --git a/src/Crypto/Crypto.cpp b/src/Crypto/Crypto.cpp index cbbb3b6..a00c02e 100644 --- a/src/Crypto/Crypto.cpp +++ b/src/Crypto/Crypto.cpp @@ -1,48 +1,226 @@ #include #include +#include +#include #include #include +#include #include +#include +#include #include #include +#include +#include namespace Void::Crypto { namespace { - [[nodiscard]] const EVP_MD* - algorithm_impl(HashAlgorithm algorithm) noexcept + thread_local FaultConfig g_fault_config{}; + thread_local std::size_t g_fault_hits{0}; + + [[nodiscard]] std::optional + maybe_inject_fault(FaultOperation op, std::string_view operation) + { + if (g_fault_config.op == FaultOperation::none) { + return std::nullopt; + } + if (g_fault_config.op != FaultOperation::any && + g_fault_config.op != op) { + return std::nullopt; + } + if (g_fault_hits < g_fault_config.fail_after) { + ++g_fault_hits; + return std::nullopt; + } + ++g_fault_hits; + return make_crypto_error( + g_fault_config.code, + std::format("{}: injected crypto backend fault", operation)); + } + + [[nodiscard]] const char* + algorithm_name(HashAlgorithm algorithm) noexcept { switch (algorithm) { case HashAlgorithm::Sha1: - return EVP_sha1(); + return "SHA1"; case HashAlgorithm::Sha256: - return EVP_sha256(); + return "SHA256"; case HashAlgorithm::Sha512: - return EVP_sha512(); + return "SHA512"; } return nullptr; } - [[nodiscard]] std::string openssl_error(std::string_view operation) + [[nodiscard]] const char* + propq_or_null(const ProviderOptions& provider) noexcept { - const unsigned long code = ERR_get_error(); - if (code == 0) { - return std::string{operation}; + return provider.property_query.empty() + ? nullptr + : provider.property_query.c_str(); + } + + [[nodiscard]] Void::Result::Error + make_openssl_error(CryptoErrorCode code, std::string_view operation) + { + const unsigned long err_code = ERR_get_error(); + ERR_clear_error(); + if (err_code == 0) { + return make_crypto_error(code, std::string{operation}); } std::array buffer{}; - ERR_error_string_n(code, buffer.data(), buffer.size()); - return std::format("{}: {}", operation, buffer.data()); + ERR_error_string_n(err_code, buffer.data(), buffer.size()); + return make_crypto_error( + code, std::format("{}: {}", operation, buffer.data())); + } + + [[nodiscard]] bool spans_overlap(std::span a, + std::span b) noexcept + { + if (a.empty() || b.empty()) { + return false; + } + const auto a_begin = reinterpret_cast(a.data()); + const auto a_end = a_begin + a.size(); + const auto b_begin = reinterpret_cast(b.data()); + const auto b_end = b_begin + b.size(); + return a_begin < b_end && b_begin < a_end; + } + + using EvpMdPtr = std::unique_ptr; + using EvpMdCtxPtr = + std::unique_ptr; + using EvpPkeyPtr = std::unique_ptr; + using EvpMacPtr = std::unique_ptr; + using EvpMacCtxPtr = + std::unique_ptr; + using EvpKdfPtr = std::unique_ptr; + using EvpKdfCtxPtr = + std::unique_ptr; + + [[nodiscard]] const unsigned char* + non_null_bytes(std::span span) noexcept + { + static constexpr unsigned char kEmptyByte = 0; + return span.empty() + ? &kEmptyByte + : reinterpret_cast(span.data()); + } + + [[nodiscard]] Void::Result::Result + verify_ed25519_impl(std::span message, + std::span signature, + std::span public_key, + const ProviderOptions& provider) + { + if (signature.size() != Ed25519SignatureSize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_signature_size, + std::format("Crypto::verifyEd25519: signature must be {} " + "bytes", + Ed25519SignatureSize))}; + } + if (public_key.size() != Ed25519PublicKeySize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_key_size, + std::format("Crypto::verifyEd25519: public key must be {} " + "bytes", + Ed25519PublicKeySize))}; + } + if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::message_too_large, + std::format("Crypto::verifyEd25519: message exceeds {} " + "byte one-shot limit", + CryptoLimits::kMaxOneShotMessageBytes))}; + } + if (auto fault = maybe_inject_fault(FaultOperation::ed25519_verify, + "Crypto::verifyEd25519"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + + ERR_clear_error(); + const char* propq = propq_or_null(provider); + EvpPkeyPtr key{EVP_PKEY_new_raw_public_key_ex( + nullptr, "ED25519", propq, + non_null_bytes(public_key), public_key.size()), + &EVP_PKEY_free}; + if (!key) { + const auto code = + provider.property_query.empty() + ? CryptoErrorCode::backend_error + : CryptoErrorCode::provider_error; + return std::unexpected{make_openssl_error( + code, "Crypto::verifyEd25519: invalid public key or " + "unavailable provider")}; + } + EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!context) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::verifyEd25519: EVP_MD_CTX_new failed")}; + } + if (EVP_DigestVerifyInit_ex(context.get(), nullptr, nullptr, + nullptr, propq, key.get(), + nullptr) != 1) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::verifyEd25519: initialization failed")}; + } + const int result = EVP_DigestVerify( + context.get(), non_null_bytes(signature), signature.size(), + non_null_bytes(message), message.size()); + if (result < 0) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::verifyEd25519 failed")}; + } + ERR_clear_error(); + return result == 1; } } // namespace + void secure_wipe(std::span buffer) noexcept + { + if (!buffer.empty()) { + OPENSSL_cleanse(buffer.data(), buffer.size()); + } + } + + bool constant_time_equal(std::span lhs, + std::span rhs) noexcept + { + if (lhs.size() != rhs.size()) { + return false; + } + if (lhs.empty()) { + return true; + } + return CRYPTO_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; + } + + ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept + : m_previous(g_fault_config), m_previous_hits(g_fault_hits) + { + g_fault_config = config; + g_fault_hits = 0; + } + + ScopedFaultGuard::~ScopedFaultGuard() noexcept + { + g_fault_config = m_previous; + g_fault_hits = m_previous_hits; + } + struct Hasher::Impl { - EVP_MD_CTX* context{nullptr}; - const EVP_MD* algorithm{nullptr}; - bool finalized{false}; - ~Impl() { EVP_MD_CTX_free(context); } + EvpMdCtxPtr context{nullptr, &EVP_MD_CTX_free}; + EvpMdPtr algorithm{nullptr, &EVP_MD_free}; + HasherState state{HasherState::Ready}; }; Hasher::Hasher(std::unique_ptr impl) noexcept @@ -53,36 +231,85 @@ namespace Void::Crypto Hasher::Hasher(Hasher&&) noexcept = default; Hasher& Hasher::operator=(Hasher&&) noexcept = default; + HasherState Hasher::state() const noexcept + { + return m_impl ? m_impl->state : HasherState::MovedFrom; + } + Void::Result::Result Hasher::create(HashAlgorithm algorithm) { + return create(algorithm, ProviderOptions{}); + } + + Void::Result::Result + Hasher::create(HashAlgorithm algorithm, const ProviderOptions& provider) + { + const char* md_name = algorithm_name(algorithm); + if (md_name == nullptr) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::unsupported_algorithm, + "Crypto::Hasher: unsupported algorithm")}; + } + if (auto fault = maybe_inject_fault(FaultOperation::hash_create, + "Crypto::Hasher::create"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + + ERR_clear_error(); auto impl = std::make_unique(); - impl->algorithm = algorithm_impl(algorithm); - if (impl->algorithm == nullptr) { - return Void::Result::fail("Crypto::Hasher: unsupported algorithm"); + impl->algorithm = EvpMdPtr{ + EVP_MD_fetch(nullptr, md_name, propq_or_null(provider)), + &EVP_MD_free}; + if (!impl->algorithm) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::Hasher: EVP_MD_fetch failed")}; } - impl->context = EVP_MD_CTX_new(); - if (impl->context == nullptr) { - return Void::Result::fail( - openssl_error("Crypto::Hasher: EVP_MD_CTX_new failed")); + impl->context = EvpMdCtxPtr{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!impl->context) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::Hasher: EVP_MD_CTX_new failed")}; } - if (EVP_DigestInit_ex(impl->context, impl->algorithm, nullptr) != 1) { - return Void::Result::fail( - openssl_error("Crypto::Hasher: digest initialization failed")); + if (EVP_DigestInit_ex2(impl->context.get(), impl->algorithm.get(), + nullptr) != 1) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::Hasher: digest initialization failed")}; } + impl->state = HasherState::Ready; return Hasher{std::move(impl)}; } Void::Result::Result Hasher::update(std::span data) { - if (!m_impl || m_impl->finalized) { - return Void::Result::fail( - "Crypto::Hasher::update: hasher is finalized or moved-from"); + if (!m_impl) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Hasher::update: hasher is moved-from")}; + } + if (m_impl->state == HasherState::Finalized || + m_impl->state == HasherState::Failed) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Hasher::update: hasher is finalized or failed")}; + } + if (auto fault = maybe_inject_fault(FaultOperation::hash_update, + "Crypto::Hasher::update"); + fault.has_value()) { + m_impl->state = HasherState::Failed; + return std::unexpected{std::move(*fault)}; } if (!data.empty() && - EVP_DigestUpdate(m_impl->context, data.data(), data.size()) != 1) { - return Void::Result::fail( - openssl_error("Crypto::Hasher::update failed")); + EVP_DigestUpdate(m_impl->context.get(), data.data(), + data.size()) != 1) { + m_impl->state = HasherState::Failed; + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::Hasher::update failed")}; } + m_impl->state = HasherState::Updating; return {}; } @@ -93,24 +320,41 @@ namespace Void::Crypto Void::Result::Result Hasher::finalize() { - if (!m_impl || m_impl->finalized) { - return Void::Result::fail( - "Crypto::Hasher::finalize: hasher is finalized or moved-from"); + if (!m_impl) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Hasher::finalize: hasher is moved-from")}; } - const int digest_size = EVP_MD_get_size(m_impl->algorithm); + if (m_impl->state == HasherState::Finalized || + m_impl->state == HasherState::Failed) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Hasher::finalize: hasher is finalized or failed")}; + } + if (auto fault = maybe_inject_fault(FaultOperation::hash_finalize, + "Crypto::Hasher::finalize"); + fault.has_value()) { + m_impl->state = HasherState::Failed; + return std::unexpected{std::move(*fault)}; + } + const int digest_size = EVP_MD_get_size(m_impl->algorithm.get()); if (digest_size <= 0) { - return Void::Result::fail( - "Crypto::Hasher::finalize: invalid digest size"); + m_impl->state = HasherState::Failed; + return std::unexpected{make_crypto_error( + CryptoErrorCode::backend_error, + "Crypto::Hasher::finalize: invalid digest size")}; } Digest digest(static_cast(digest_size)); unsigned int written = 0; - if (EVP_DigestFinal_ex(m_impl->context, + if (EVP_DigestFinal_ex(m_impl->context.get(), reinterpret_cast(digest.data()), &written) != 1) { - return Void::Result::fail( - openssl_error("Crypto::Hasher::finalize failed")); + m_impl->state = HasherState::Failed; + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::Hasher::finalize failed")}; } - m_impl->finalized = true; + m_impl->state = HasherState::Finalized; digest.resize(written); return digest; } @@ -118,7 +362,13 @@ namespace Void::Crypto auto hash(HashAlgorithm algorithm, std::span data) -> Void::Result::Result { - auto hasher = Hasher::create(algorithm); + return hash(algorithm, data, ProviderOptions{}); + } + + auto hash(HashAlgorithm algorithm, std::span data, + const ProviderOptions& provider) -> Void::Result::Result + { + auto hasher = Hasher::create(algorithm, provider); if (!hasher) { return std::unexpected{hasher.error()}; } @@ -137,17 +387,26 @@ namespace Void::Crypto auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path) -> Void::Result::Result + { + return hashFile(algorithm, path, ProviderOptions{}); + } + + auto hashFile(HashAlgorithm algorithm, const std::filesystem::path& path, + const ProviderOptions& provider) + -> Void::Result::Result { std::ifstream input{path, std::ios::binary}; if (!input.is_open()) { - return Void::Result::fail(std::format( - "Crypto::hashFile: cannot open '{}'", path.string())); + return std::unexpected{make_crypto_error( + CryptoErrorCode::io_error, + std::format("Crypto::hashFile: cannot open '{}'", + path.string()))}; } - auto hasher = Hasher::create(algorithm); + auto hasher = Hasher::create(algorithm, provider); if (!hasher) { return std::unexpected{hasher.error()}; } - std::array buffer{}; + std::array buffer{}; while (input) { input.read(buffer.data(), static_cast(buffer.size())); @@ -160,9 +419,11 @@ namespace Void::Crypto } } } - if (input.bad()) { - return Void::Result::fail(std::format( - "Crypto::hashFile: I/O error reading '{}'", path.string())); + if (input.bad() || (!input.eof() && input.fail())) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::io_error, + std::format("Crypto::hashFile: I/O error reading '{}'", + path.string()))}; } return hasher->finalize(); } @@ -204,54 +465,366 @@ namespace Void::Crypto return hashFile(HashAlgorithm::Sha512, path); } + struct Ed25519PrivateKey::Impl { + EvpPkeyPtr pkey{nullptr, &EVP_PKEY_free}; + }; + + Ed25519PrivateKey::Ed25519PrivateKey(std::unique_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + Ed25519PrivateKey::~Ed25519PrivateKey() = default; + Ed25519PrivateKey::Ed25519PrivateKey(Ed25519PrivateKey&&) noexcept = + default; + Ed25519PrivateKey& + Ed25519PrivateKey::operator=(Ed25519PrivateKey&&) noexcept = default; + + bool Ed25519PrivateKey::valid() const noexcept + { + return m_impl != nullptr && m_impl->pkey != nullptr; + } + + Void::Result::Result + Ed25519PrivateKey::generate(const ProviderOptions& provider) + { + if (auto fault = maybe_inject_fault(FaultOperation::ed25519_keygen, + "Crypto::Ed25519PrivateKey::generate"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + ERR_clear_error(); + EvpPkeyPtr key{ + EVP_PKEY_Q_keygen(nullptr, propq_or_null(provider), "ED25519"), + &EVP_PKEY_free}; + if (!key) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::Ed25519PrivateKey::generate failed")}; + } + auto impl = std::make_unique(); + impl->pkey = std::move(key); + return Ed25519PrivateKey{std::move(impl)}; + } + + Void::Result::Result + Ed25519PrivateKey::from_raw_seed(std::span seed, + const ProviderOptions& provider) + { + if (seed.size() != Ed25519SeedSize) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_key_size, + std::format("Crypto::Ed25519PrivateKey::from_raw_seed: seed " + "must be {} bytes", + Ed25519SeedSize))}; + } + if (auto fault = maybe_inject_fault( + FaultOperation::ed25519_import, + "Crypto::Ed25519PrivateKey::from_raw_seed"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + ERR_clear_error(); + EvpPkeyPtr key{EVP_PKEY_new_raw_private_key_ex( + nullptr, "ED25519", propq_or_null(provider), + non_null_bytes(seed), seed.size()), + &EVP_PKEY_free}; + if (!key) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::Ed25519PrivateKey::from_raw_seed failed")}; + } + auto impl = std::make_unique(); + impl->pkey = std::move(key); + return Ed25519PrivateKey{std::move(impl)}; + } + + Void::Result::Result Ed25519PrivateKey::public_key() const + { + if (!valid()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Ed25519PrivateKey::public_key: invalid or moved-from " + "key")}; + } + Ed25519PublicKey pub; + std::size_t len = pub.bytes.size(); + if (EVP_PKEY_get_raw_public_key( + m_impl->pkey.get(), + reinterpret_cast(pub.bytes.data()), + &len) != 1 || + len != Ed25519PublicKeySize) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::Ed25519PrivateKey::public_key failed")}; + } + return pub; + } + + Void::Result::Result Ed25519PrivateKey::export_raw_seed() const + { + if (!valid()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::Ed25519PrivateKey::export_raw_seed: invalid or " + "moved-from key")}; + } + std::array raw{}; + std::size_t len = raw.size(); + if (EVP_PKEY_get_raw_private_key( + m_impl->pkey.get(), + reinterpret_cast(raw.data()), &len) != 1 || + len != Ed25519SeedSize) { + secure_wipe(raw); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::Ed25519PrivateKey::export_raw_seed failed")}; + } + auto result = Ed25519Seed::from_bytes(raw); + secure_wipe(raw); + return result; + } + + Void::Result::Result + sign_ed25519(std::span message, + const Ed25519PrivateKey& private_key, + const ProviderOptions& provider) + { + if (!private_key.valid()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_state, + "Crypto::sign_ed25519: private key is invalid or moved-from")}; + } + if (message.size() > CryptoLimits::kMaxOneShotMessageBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::message_too_large, + std::format("Crypto::sign_ed25519: message exceeds {} byte " + "one-shot limit", + CryptoLimits::kMaxOneShotMessageBytes))}; + } + if (auto fault = maybe_inject_fault(FaultOperation::ed25519_sign, + "Crypto::sign_ed25519"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + + ERR_clear_error(); + EvpMdCtxPtr context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; + if (!context) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::sign_ed25519: EVP_MD_CTX_new failed")}; + } + if (EVP_DigestSignInit_ex(context.get(), nullptr, nullptr, nullptr, + propq_or_null(provider), + private_key.m_impl->pkey.get(), + nullptr) != 1) { + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::sign_ed25519: initialization failed")}; + } + Ed25519Signature signature; + std::size_t sig_len = signature.bytes.size(); + if (EVP_DigestSign( + context.get(), + reinterpret_cast(signature.bytes.data()), + &sig_len, non_null_bytes(message), message.size()) != 1 || + sig_len != Ed25519SignatureSize) { + secure_wipe(signature.bytes); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::sign_ed25519 failed")}; + } + return signature; + } + Void::Result::Result verifyEd25519(std::span message, std::span signature, std::span publicKey) { - if (signature.size() != Ed25519SignatureSize) { - return Void::Result::fail( - std::format("Crypto::verifyEd25519: signature must be {} bytes", - Ed25519SignatureSize)); + return verify_ed25519_impl(message, signature, publicKey, + ProviderOptions{}); + } + + Void::Result::Result + verify_ed25519(std::span message, + const Ed25519Signature& signature, + const Ed25519PublicKey& public_key, + const ProviderOptions& provider) + { + return verify_ed25519_impl(message, signature.view(), public_key.view(), + provider); + } + + Void::Result::Result + hmac_sha256_into(std::span secret_key, + std::span message, + std::span output, + const ProviderOptions& provider) + { + if (output.size() != HmacSha256Size) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_argument, + std::format("Crypto::hmac_sha256_into: output must be {} bytes", + HmacSha256Size))}; } - if (publicKey.size() != Ed25519PublicKeySize) { - return Void::Result::fail(std::format( - "Crypto::verifyEd25519: public key must be {} bytes", - Ed25519PublicKeySize)); + if (spans_overlap(secret_key, output) || + spans_overlap(message, output)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::overlapping_buffers, + "Crypto::hmac_sha256_into: output buffer overlaps input")}; + } + if (auto fault = maybe_inject_fault(FaultOperation::hmac, + "Crypto::hmac_sha256_into"); + fault.has_value()) { + secure_wipe(output); + return std::unexpected{std::move(*fault)}; } - using Key = std::unique_ptr; - using Context = std::unique_ptr; - Key key{EVP_PKEY_new_raw_public_key( - EVP_PKEY_ED25519, nullptr, - reinterpret_cast(publicKey.data()), - publicKey.size()), - &EVP_PKEY_free}; - if (!key) { - return Void::Result::fail( - openssl_error("Crypto::verifyEd25519: invalid public key")); + ERR_clear_error(); + EvpMacPtr mac{EVP_MAC_fetch(nullptr, "HMAC", propq_or_null(provider)), + &EVP_MAC_free}; + if (!mac) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::hmac_sha256_into: EVP_MAC_fetch failed")}; } - Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free}; - if (!context) { - return Void::Result::fail( - openssl_error("Crypto::verifyEd25519: EVP_MD_CTX_new failed")); + EvpMacCtxPtr ctx{EVP_MAC_CTX_new(mac.get()), &EVP_MAC_CTX_free}; + if (!ctx) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::hmac_sha256_into: EVP_MAC_CTX_new failed")}; } - if (EVP_DigestVerifyInit(context.get(), nullptr, nullptr, nullptr, - key.get()) != 1) { - return Void::Result::fail( - openssl_error("Crypto::verifyEd25519: initialization failed")); + + char digest_name[] = "SHA256"; + std::array params = { + OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name, + 0), + OSSL_PARAM_construct_end(), + }; + + if (EVP_MAC_init(ctx.get(), non_null_bytes(secret_key), + secret_key.size(), params.data()) != 1) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::hmac_sha256_into: EVP_MAC_init failed")}; } - const int result = EVP_DigestVerify( - context.get(), - reinterpret_cast(signature.data()), - signature.size(), - reinterpret_cast(message.data()), - message.size()); - if (result < 0) { - return Void::Result::fail( - openssl_error("Crypto::verifyEd25519 failed")); + if (!message.empty() && + EVP_MAC_update(ctx.get(), non_null_bytes(message), + message.size()) != 1) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::hmac_sha256_into: EVP_MAC_update failed")}; } - return result == 1; + std::size_t out_len = 0; + if (EVP_MAC_final(ctx.get(), + reinterpret_cast(output.data()), + &out_len, output.size()) != 1 || + out_len != HmacSha256Size) { + secure_wipe(output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::hmac_sha256_into: EVP_MAC_final failed")}; + } + return {}; } + + Void::Result::Result hmac_sha256(std::span secret_key, + std::span message, + const ProviderOptions& provider) + { + Digest out(HmacSha256Size); + if (auto res = hmac_sha256_into(secret_key, message, out, provider); + !res.has_value()) { + secure_wipe(out); + return std::unexpected{std::move(res.error())}; + } + return out; + } + + Void::Result::Result + hkdf_sha256(std::span secret_input, + std::span salt, + std::span context, + std::span secret_output, + const ProviderOptions& provider) + { + if (secret_output.empty()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_argument, + "Crypto::hkdf_sha256: output buffer must be non-empty")}; + } + if (secret_output.size() > CryptoLimits::kMaxHkdfOutputBytes) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::output_too_large, + std::format("Crypto::hkdf_sha256: output size exceeds {} byte " + "cap", + CryptoLimits::kMaxHkdfOutputBytes))}; + } + if (spans_overlap(secret_input, secret_output) || + spans_overlap(salt, secret_output) || + spans_overlap(context, secret_output)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::overlapping_buffers, + "Crypto::hkdf_sha256: output buffer overlaps input")}; + } + if (auto fault = maybe_inject_fault(FaultOperation::hkdf, + "Crypto::hkdf_sha256"); + fault.has_value()) { + secure_wipe(secret_output); + return std::unexpected{std::move(*fault)}; + } + + ERR_clear_error(); + EvpKdfPtr kdf{EVP_KDF_fetch(nullptr, "HKDF", propq_or_null(provider)), + &EVP_KDF_free}; + if (!kdf) { + secure_wipe(secret_output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::provider_error, + "Crypto::hkdf_sha256: EVP_KDF_fetch failed")}; + } + EvpKdfCtxPtr ctx{EVP_KDF_CTX_new(kdf.get()), &EVP_KDF_CTX_free}; + if (!ctx) { + secure_wipe(secret_output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::hkdf_sha256: EVP_KDF_CTX_new failed")}; + } + + char digest_name[] = "SHA256"; + std::array params = { + OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, digest_name, + 0), + OSSL_PARAM_construct_octet_string( + OSSL_KDF_PARAM_KEY, + const_cast(non_null_bytes(secret_input)), + secret_input.size()), + OSSL_PARAM_construct_octet_string( + OSSL_KDF_PARAM_SALT, + const_cast(non_null_bytes(salt)), salt.size()), + OSSL_PARAM_construct_octet_string( + OSSL_KDF_PARAM_INFO, + const_cast(non_null_bytes(context)), + context.size()), + OSSL_PARAM_construct_end(), + }; + + if (EVP_KDF_derive( + ctx.get(), + reinterpret_cast(secret_output.data()), + secret_output.size(), params.data()) != 1) { + secure_wipe(secret_output); + return std::unexpected{make_openssl_error( + CryptoErrorCode::backend_error, + "Crypto::hkdf_sha256: EVP_KDF_derive failed")}; + } + return {}; + } + } // namespace Void::Crypto diff --git a/src/Crypto/module.cmake b/src/Crypto/module.cmake index 200a64f..0fb20a7 100644 --- a/src/Crypto/module.cmake +++ b/src/Crypto/module.cmake @@ -1,4 +1,6 @@ void_add_module(Crypto INTERNAL_DEPS Functional EXTERNAL_DEPS OpenSSL::Crypto + EXCLUDE_HEADERS + Void/Crypto/AsyncHash.hpp ) diff --git a/src/CryptoAsync/AsyncHash.cpp b/src/CryptoAsync/AsyncHash.cpp new file mode 100644 index 0000000..e92f210 --- /dev/null +++ b/src/CryptoAsync/AsyncHash.cpp @@ -0,0 +1,522 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::CryptoAsync +{ + namespace + { + [[nodiscard]] Void::Result::Error + map_io_error(const Void::Result::Error& err) + { + if (err.kind() == Void::Result::ErrorKind::cancelled) { + return Void::Crypto::make_crypto_error( + Void::Crypto::CryptoErrorCode::cancelled, err.message(), + err.system_code()); + } + if (err.kind() == Void::Result::ErrorKind::timeout) { + return Void::Crypto::make_crypto_error( + Void::Crypto::CryptoErrorCode::timeout, err.message(), + err.system_code()); + } + if (err.kind() == Void::Result::ErrorKind::exhausted) { + return Void::Crypto::make_crypto_error( + Void::Crypto::CryptoErrorCode::resource_exhausted, + err.message(), err.system_code()); + } + return Void::Crypto::make_crypto_error( + Void::Crypto::CryptoErrorCode::io_error, err.message(), + err.system_code()); + } + } // namespace + + Void::Coro::Task> + hash_stream(Void::Crypto::HashAlgorithm algorithm, + Void::IO::Driver& driver, Void::IO::ByteStream& stream, + Void::Async::OperationOptions options, + StreamHashOptions hash_options) + { + using namespace Void::Crypto; + + if (hash_options.chunk_bytes == 0 || + hash_options.chunk_bytes > CryptoLimits::kStreamChunkBytes) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_argument, + "CryptoAsync::hash_stream: chunk_bytes must be in [1, 64 KiB]")}; + } + if (!stream.valid()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::closed, + "CryptoAsync::hash_stream: stream is invalid or closed")}; + } + if (options.stop.stop_requested()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::hash_stream: operation stopped before start")}; + } + if (Void::Async::is_deadline_expired(options, driver.clock())) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::hash_stream: deadline expired before start")}; + } + + auto hasher = Hasher::create(algorithm, hash_options.provider); + if (!hasher.has_value()) { + co_return std::unexpected{std::move(hasher.error())}; + } + + auto lease = driver.allocate_buffer(hash_options.chunk_bytes); + if (!lease.has_value()) { + co_return std::unexpected{map_io_error(lease.error())}; + } + + for (;;) { + if (options.stop.stop_requested()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::hash_stream: stopped between chunks")}; + } + if (Void::Async::is_deadline_expired(options, driver.clock())) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::hash_stream: deadline expired between chunks")}; + } + + auto transfer = co_await stream.read_some_owned(*lease, options); + if (!transfer.has_value()) { + co_return std::unexpected{map_io_error(transfer.error())}; + } + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::hash_stream: stopped during stream read")}; + } + if (Void::Async::is_deadline_expired(options, driver.clock())) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::hash_stream: deadline expired after read")}; + } + + if (transfer->bytes > 0) { + if (auto upd = hasher->update(lease->readable()); + !upd.has_value()) { + co_return std::unexpected{std::move(upd.error())}; + } + } + if (transfer->eof) { + break; + } + } + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::hash_stream: stopped before finalize")}; + } + + co_return hasher->finalize(); + } + + struct AsyncFileHasher::State : std::enable_shared_from_this { + struct Job { + Job(Void::Crypto::HashAlgorithm alg, + std::filesystem::path p, + std::shared_ptr< + Void::Async::OperationState> + o) + : algorithm(alg), path(std::move(p)), op(std::move(o)) + { + } + Void::Crypto::HashAlgorithm algorithm; + std::filesystem::path path; + std::shared_ptr< + Void::Async::OperationState> + op; + std::optional>> + cancel_cb{}; + }; + + State(Void::Async::Executor& exec, FileHasherOptions opts, + const Void::Time::MonotonicClock& clk) + : executor(exec), options(std::move(opts)), clock(clk) + { + } + + void start_workers_locked() + { + if (workers_started || options.max_concurrent == 0) { + return; + } + workers_started = true; + const std::size_t count = + std::max(1, options.max_concurrent); + workers.reserve(count); + auto self = shared_from_this(); + for (std::size_t i = 0; i < count; ++i) { + workers.emplace_back([self] { self->worker_loop(); }); + } + } + + void worker_loop() + { + for (;;) { + std::shared_ptr job; + { + std::unique_lock lk{mu}; + cv.wait(lk, [this] { + if (closing) { + return true; + } + if (queue.empty()) { + return false; + } + if (active < options.max_concurrent && + reserved_bytes + options.chunk_bytes <= + options.buffer_budget_bytes) { + return true; + } + return std::any_of( + queue.begin(), queue.end(), + [this](const auto& j) { + return j->op->stop_requested() || + j->op->is_deadline_expired(clock); + }); + }); + + // Purge any already-cancelled or expired jobs in queue. + std::vector, + Void::Result::Error>> + dropped_jobs; + for (auto it = queue.begin(); it != queue.end();) { + auto& item = *it; + if (closing || item->op->stop_requested()) { + dropped_jobs.emplace_back( + std::move(item), + Void::Crypto::make_crypto_error( + closing + ? Void::Crypto::CryptoErrorCode::closed + : Void::Crypto::CryptoErrorCode::cancelled, + "CryptoAsync::AsyncFileHasher: job cancelled while queued")); + it = queue.erase(it); + } else if (item->op->is_deadline_expired(clock)) { + dropped_jobs.emplace_back( + std::move(item), + Void::Crypto::make_crypto_error( + Void::Crypto::CryptoErrorCode::timeout, + "CryptoAsync::AsyncFileHasher: deadline expired while queued")); + it = queue.erase(it); + } else { + ++it; + } + } + if (!dropped_jobs.empty()) { + lk.unlock(); + for (auto& [dropped, err] : dropped_jobs) { + dropped->cancel_cb.reset(); + const auto kind = + (err.kind() == + Void::Result::ErrorKind::cancelled) + ? Void::Async::DomainOutcomeKind::cancelled + : Void::Async::DomainOutcomeKind::failed; + auto ticket = dropped->op->try_commit_error( + std::move(err), kind); + if (ticket.has_value()) { + ticket->dispatch(); + } + dropped->op->release_backend_ref_and_dispatch(); + } + lk.lock(); + } + + if (closing && queue.empty()) { + return; + } + if (queue.empty() || active >= options.max_concurrent || + reserved_bytes + options.chunk_bytes > + options.buffer_budget_bytes) { + continue; + } + + job = std::move(queue.front()); + queue.pop_front(); + ++active; + reserved_bytes += options.chunk_bytes; + in_flight.push_back(job->op); + } + + job->cancel_cb.reset(); + auto result = run_job(*job); + + { + std::lock_guard lk{mu}; + --active; + reserved_bytes -= options.chunk_bytes; + ++completed; + std::erase_if(in_flight, [&](const auto& weak_op) { + auto sp = weak_op.lock(); + return !sp || sp == job->op; + }); + } + cv.notify_all(); + + std::optional ticket; + if (result.has_value()) { + ticket = job->op->try_commit_value(std::move(*result)); + } else { + const auto kind = + (result.error().kind() == + Void::Result::ErrorKind::cancelled) + ? Void::Async::DomainOutcomeKind::cancelled + : Void::Async::DomainOutcomeKind::failed; + ticket = job->op->try_commit_error( + std::move(result.error()), kind); + } + if (ticket.has_value()) { + ticket->dispatch(); + } + job->op->release_backend_ref_and_dispatch(); + } + } + + [[nodiscard]] Void::Result::Result + run_job(const Job& job) const + { + using namespace Void::Crypto; + + if (job.op->stop_requested()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::AsyncFileHasher: cancelled before open")}; + } + if (job.op->is_deadline_expired(clock)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::AsyncFileHasher: deadline expired before open")}; + } + + std::ifstream input{job.path, std::ios::binary}; + if (!input.is_open()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::io_error, + std::format( + "CryptoAsync::AsyncFileHasher: cannot open '{}'", + job.path.string()))}; + } + + auto hasher = Hasher::create(job.algorithm, options.provider); + if (!hasher.has_value()) { + return std::unexpected{std::move(hasher.error())}; + } + + std::vector buffer(options.chunk_bytes); + while (input) { + if (job.op->stop_requested()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::AsyncFileHasher: stopped during file read")}; + } + if (job.op->is_deadline_expired(clock)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::AsyncFileHasher: deadline expired during read")}; + } + input.read(buffer.data(), + static_cast(buffer.size())); + const auto count = input.gcount(); + if (count > 0) { + const auto bytes = std::as_bytes(std::span{ + buffer.data(), static_cast(count)}); + if (auto upd = hasher->update(bytes); + !upd.has_value()) { + return std::unexpected{std::move(upd.error())}; + } + } + } + if (input.bad() || (!input.eof() && input.fail())) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::io_error, + std::format( + "CryptoAsync::AsyncFileHasher: I/O error reading '{}'", + job.path.string()))}; + } + if (job.op->stop_requested()) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::AsyncFileHasher: stopped before finalize")}; + } + if (job.op->is_deadline_expired(clock)) { + return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::AsyncFileHasher: deadline expired before finalize")}; + } + return hasher->finalize(); + } + + Void::Async::Executor& executor; + FileHasherOptions options; + const Void::Time::MonotonicClock& clock; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::deque> queue{}; + std::vector>> + in_flight{}; + std::vector workers{}; + bool workers_started{false}; + bool closing{false}; + bool joined{false}; + std::size_t active{0}; + std::size_t reserved_bytes{0}; + std::uint64_t completed{0}; + std::uint64_t rejected{0}; + }; + + AsyncFileHasher::AsyncFileHasher(Void::Async::Executor& executor, + FileHasherOptions options, + const Void::Time::MonotonicClock& clock) + : m_state(std::make_shared(executor, std::move(options), clock)) + { + } + + AsyncFileHasher::~AsyncFileHasher() { (void)close_and_join(); } + + Void::Coro::Task> + AsyncFileHasher::hash_file(Void::Crypto::HashAlgorithm algorithm, + std::filesystem::path path, + Void::Async::OperationOptions options) + { + using namespace Void::Crypto; + auto state = m_state; + + if (state->options.max_concurrent == 0 || + state->options.chunk_bytes == 0 || + state->options.chunk_bytes > CryptoLimits::kStreamChunkBytes) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::invalid_argument, + "CryptoAsync::AsyncFileHasher: invalid options")}; + } + if (state->options.chunk_bytes > state->options.buffer_budget_bytes) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::resource_exhausted, + "CryptoAsync::AsyncFileHasher: chunk_bytes exceeds buffer budget")}; + } + if (options.stop.stop_requested()) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::cancelled, + "CryptoAsync::AsyncFileHasher: stopped before admission")}; + } + if (Void::Async::is_deadline_expired(options, state->clock)) { + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::timeout, + "CryptoAsync::AsyncFileHasher: deadline expired before admission")}; + } + + auto op = Void::Async::OperationState::create( + options, &state->executor, Void::Async::StopBehavior::notify_only); + auto job = std::make_shared(algorithm, std::move(path), op); + + { + std::lock_guard lk{state->mu}; + if (state->closing) { + ++state->rejected; + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::closed, + "CryptoAsync::AsyncFileHasher: service is closing")}; + } + const std::size_t max_effective_concurrent = std::min( + state->options.max_concurrent, + state->options.buffer_budget_bytes / state->options.chunk_bytes); + const std::size_t capacity = + max_effective_concurrent + state->options.max_waiting; + if (state->active + state->queue.size() >= capacity) { + ++state->rejected; + co_return std::unexpected{make_crypto_error( + CryptoErrorCode::overloaded, + "CryptoAsync::AsyncFileHasher: wait queue is full")}; + } + + op->acquire_backend_ref(); + state->start_workers_locked(); + if (options.stop.stop_possible()) { + std::weak_ptr weak_state = state; + job->cancel_cb.emplace(options.stop, [weak_state]() { + if (auto s = weak_state.lock()) { + s->cv.notify_all(); + } + }); + } + state->queue.push_back(std::move(job)); + } + state->cv.notify_one(); + + co_return co_await op->awaitable(&state->executor); + } + + void AsyncFileHasher::request_stop() noexcept + { + std::vector< + std::shared_ptr>> + ops; + { + std::lock_guard lk{m_state->mu}; + m_state->closing = true; + for (const auto& j : m_state->queue) { + ops.push_back(j->op); + } + for (const auto& weak_op : m_state->in_flight) { + if (auto sp = weak_op.lock()) { + ops.push_back(std::move(sp)); + } + } + } + for (auto& op : ops) { + op->request_stop(); + } + m_state->cv.notify_all(); + } + + Void::Result::Result AsyncFileHasher::close_and_join() + { + request_stop(); + std::vector threads; + { + std::lock_guard lk{m_state->mu}; + if (m_state->joined) { + return {}; + } + m_state->joined = true; + threads.swap(m_state->workers); + } + for (auto& t : threads) { + if (t.joinable()) { + t.join(); + } + } + return {}; + } + + FileHasherStats AsyncFileHasher::stats() const noexcept + { + std::lock_guard lk{m_state->mu}; + return FileHasherStats{ + .active = m_state->active, + .waiting = m_state->queue.size(), + .reserved_buffer_bytes = m_state->reserved_bytes, + .completed = m_state->completed, + .rejected = m_state->rejected, + .closing = m_state->closing, + }; + } + +} // namespace Void::CryptoAsync diff --git a/src/CryptoAsync/module.cmake b/src/CryptoAsync/module.cmake new file mode 100644 index 0000000..eecac88 --- /dev/null +++ b/src/CryptoAsync/module.cmake @@ -0,0 +1,6 @@ +void_add_module(CryptoAsync + INTERNAL_DEPS Crypto IO Async Time Functional + EXTERNAL_DEPS Threads::Threads + EXTRA_HEADERS + Void/Crypto/AsyncHash.hpp +) diff --git a/src/Security/Authorization.cpp b/src/Security/Authorization.cpp new file mode 100644 index 0000000..86193d8 --- /dev/null +++ b/src/Security/Authorization.cpp @@ -0,0 +1,203 @@ +#include + +#include + +namespace Void::Security +{ + namespace + { + [[nodiscard]] Void::Result::Result + validate_predicate(const Predicate& pred, std::size_t depth) + { + if (depth > SecurityLimits::kMaxPredicateDepth) { + return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Security::PolicySnapshot: predicate nesting exceeds max " + "depth 16")}; + } + switch (pred.kind) { + case Predicate::Kind::AlwaysTrue: + case Predicate::Kind::AlwaysFalse: + case Predicate::Kind::HasRole: + case Predicate::Kind::SubjectEquals: + case Predicate::Kind::ResourceTypeEquals: + case Predicate::Kind::ResourceIdEquals: + case Predicate::Kind::ResourceAttrEquals: + case Predicate::Kind::PrincipalAttrEquals: + case Predicate::Kind::ResourceOwnerMatchesSubject: + return {}; + case Predicate::Kind::AllOf: + case Predicate::Kind::AnyOf: + for (const auto& child : pred.children) { + if (auto res = validate_predicate(child, depth + 1U); + !res.has_value()) { + return res; + } + } + return {}; + case Predicate::Kind::Not: + if (pred.children.size() != 1U) { + return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Security::PolicySnapshot: Not predicate requires " + "exactly 1 child")}; + } + return validate_predicate(pred.children.front(), + depth + 1U); + } + return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Security::PolicySnapshot: unknown predicate kind")}; + } + + [[nodiscard]] bool eval_predicate(const Predicate& pred, + const Principal& principal, + const ResourceAttributes& resource, + std::size_t depth) + { + if (depth > SecurityLimits::kMaxPredicateDepth) { + return false; + } + switch (pred.kind) { + case Predicate::Kind::AlwaysTrue: + return true; + case Predicate::Kind::AlwaysFalse: + return false; + case Predicate::Kind::HasRole: + return std::find(principal.roles.begin(), + principal.roles.end(), + pred.value) != principal.roles.end(); + case Predicate::Kind::SubjectEquals: + return !principal.subject.empty() && + principal.subject == pred.value; + case Predicate::Kind::ResourceTypeEquals: + return resource.resource_type == pred.value; + case Predicate::Kind::ResourceIdEquals: + return resource.resource_id == pred.value; + case Predicate::Kind::ResourceAttrEquals: + { + auto it = resource.attributes.find(pred.key); + return it != resource.attributes.end() && + it->second == pred.value; + } + case Predicate::Kind::PrincipalAttrEquals: + { + auto it = principal.attributes.find(pred.key); + return it != principal.attributes.end() && + it->second == pred.value; + } + case Predicate::Kind::ResourceOwnerMatchesSubject: + { + if (principal.subject.empty()) { + return false; + } + const std::string_view attr_key = + pred.key.empty() ? std::string_view{"owner"} + : std::string_view{pred.key}; + auto it = resource.attributes.find(attr_key); + return it != resource.attributes.end() && + it->second == principal.subject; + } + case Predicate::Kind::AllOf: + if (pred.children.empty()) { + return false; + } + for (const auto& child : pred.children) { + if (!eval_predicate(child, principal, resource, + depth + 1U)) { + return false; + } + } + return true; + case Predicate::Kind::AnyOf: + for (const auto& child : pred.children) { + if (eval_predicate(child, principal, resource, + depth + 1U)) { + return true; + } + } + return false; + case Predicate::Kind::Not: + if (pred.children.size() != 1U) { + return false; + } + return !eval_predicate(pred.children.front(), principal, + resource, depth + 1U); + } + return false; + } + } // namespace + + Void::Result::Result + PolicySnapshot::create(std::uint64_t generation, + std::vector rules) + { + if (rules.size() > SecurityLimits::kMaxPolicyRules) { + return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Security::PolicySnapshot: rule count exceeds 4096 cap")}; + } + for (const auto& rule : rules) { + if (rule.action.empty()) { + return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Security::PolicySnapshot: rule action must be non-empty")}; + } + if (auto res = validate_predicate(rule.condition, 1U); + !res.has_value()) { + return std::unexpected{std::move(res.error())}; + } + } + return PolicySnapshot{generation, std::move(rules)}; + } + + Decision PolicySnapshot::authorize(const Principal& principal, + std::string_view action, + const ResourceAttributes& resource) const + { + if (action.empty()) { + return Decision{.allowed = false, + .reason = "empty action denied", + .policy_generation = m_generation}; + } + if (principal.roles.size() > SecurityLimits::kMaxRolesPerPrincipal) { + return Decision{.allowed = false, + .reason = "principal exceeds 64-role cap", + .policy_generation = m_generation}; + } + + std::string allow_rule_id; + bool matched_allow = false; + + for (const auto& rule : m_rules) { + if (rule.action != "*" && rule.action != action) { + continue; + } + if (!eval_predicate(rule.condition, principal, resource, 1U)) { + continue; + } + if (rule.effect == Effect::Deny) { + return Decision{.allowed = false, + .matched_rule_id = rule.id, + .reason = "explicit deny", + .policy_generation = m_generation}; + } + if (!matched_allow) { + matched_allow = true; + allow_rule_id = rule.id; + } + } + + if (matched_allow) { + return Decision{.allowed = true, + .matched_rule_id = std::move(allow_rule_id), + .reason = "explicit allow", + .policy_generation = m_generation}; + } + + return Decision{.allowed = false, + .reason = "default deny", + .policy_generation = m_generation}; + } + +} // namespace Void::Security diff --git a/src/Security/Envelope.cpp b/src/Security/Envelope.cpp new file mode 100644 index 0000000..05b3f8b --- /dev/null +++ b/src/Security/Envelope.cpp @@ -0,0 +1,433 @@ +#include + +#include + +#include +#include +#include +#include + +namespace Void::Security +{ + namespace + { + constexpr std::array kMagic{'V', 'S', 'E', 'C'}; + constexpr std::size_t kFixedPrefixBytes = 4 + 1 + 1 + 2 + 4; // 12 + + [[nodiscard]] Void::Result::Result ensure_sodium_env() + { + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::sodium_init, "Security::Envelope"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + static const bool ok = sodium_init() >= 0; + if (!ok) { + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::Envelope: libsodium initialization failed")}; + } + return {}; + } + + void append_u16_be(std::vector& out, std::uint16_t v) + { + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(v & 0xFFU)); + } + + void append_u32_be(std::vector& out, std::uint32_t v) + { + out.push_back(static_cast((v >> 24U) & 0xFFU)); + out.push_back(static_cast((v >> 16U) & 0xFFU)); + out.push_back(static_cast((v >> 8U) & 0xFFU)); + out.push_back(static_cast(v & 0xFFU)); + } + + void append_u64_be(std::vector& out, std::uint64_t v) + { + for (int shift = 56; shift >= 0; shift -= 8) { + out.push_back(static_cast((v >> shift) & 0xFFU)); + } + } + + [[nodiscard]] std::uint16_t read_u16_be(const unsigned char* p) noexcept + { + return static_cast( + (static_cast(p[0]) << 8U) | + static_cast(p[1])); + } + + [[nodiscard]] std::uint32_t read_u32_be(const unsigned char* p) noexcept + { + return (static_cast(p[0]) << 24U) | + (static_cast(p[1]) << 16U) | + (static_cast(p[2]) << 8U) | + static_cast(p[3]); + } + + [[nodiscard]] bool valid_key_id(std::string_view key_id) noexcept + { + if (key_id.empty() || key_id.size() > SecurityLimits::kMaxKeyIdBytes) { + return false; + } + for (const unsigned char ch : key_id) { + if (ch < 0x20U || ch == 0x7FU) { + return false; + } + } + return true; + } + + [[nodiscard]] std::vector + build_aead_aad(std::span header_and_nonce, + std::span caller_aad) + { + std::vector combined; + combined.reserve(header_and_nonce.size() + 8 + caller_aad.size()); + combined.insert(combined.end(), header_and_nonce.begin(), + header_and_nonce.end()); + append_u64_be(combined, static_cast(caller_aad.size())); + combined.insert(combined.end(), caller_aad.begin(), + caller_aad.end()); + return combined; + } + } // namespace + + Void::Result::Result + inspect_envelope(std::span envelope) + { + if (envelope.size() < + kFixedPrefixBytes + kEnvelopeNonceBytes + kEnvelopeTagBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::unsupported_version, + "Security::inspect_envelope: truncated or non-VSEC envelope")}; + } + if (!std::equal(kMagic.begin(), kMagic.end(), envelope.begin())) { + return std::unexpected{make_security_error( + SecurityErrorCode::unsupported_version, + "Security::inspect_envelope: invalid magic (legacy fallback " + "disabled)")}; + } + + const std::uint8_t version = envelope[4]; + const std::uint8_t algorithm = envelope[5]; + if (version != kEnvelopeVersionV1) { + return std::unexpected{make_security_error( + SecurityErrorCode::unsupported_version, + "Security::inspect_envelope: unsupported envelope version")}; + } + if (algorithm != kEnvelopeAlgXChaCha20Poly1305Ietf) { + return std::unexpected{make_security_error( + SecurityErrorCode::unsupported_version, + "Security::inspect_envelope: unsupported envelope algorithm")}; + } + + const std::uint16_t key_id_len = read_u16_be(envelope.data() + 6); + const std::uint32_t plaintext_size = read_u32_be(envelope.data() + 8); + if (key_id_len == 0 || key_id_len > SecurityLimits::kMaxKeyIdBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::inspect_envelope: invalid key_id length")}; + } + if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::inspect_envelope: declared plaintext exceeds 16 MiB " + "cap")}; + } + + const std::size_t expected_size = + kFixedPrefixBytes + static_cast(key_id_len) + + kEnvelopeNonceBytes + static_cast(plaintext_size) + + kEnvelopeTagBytes; + if (envelope.size() != expected_size) { + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::inspect_envelope: envelope length mismatch")}; + } + + std::string key_id( + reinterpret_cast(envelope.data() + kFixedPrefixBytes), + key_id_len); + if (!valid_key_id(key_id)) { + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::inspect_envelope: invalid characters in key_id")}; + } + + return EnvelopeHeader{ + .version = version, + .algorithm = algorithm, + .key_id = std::move(key_id), + .plaintext_size = plaintext_size, + }; + } + + Void::Result::Result + SecretKeyRing::add_key(std::string key_id, + std::span raw_key, + bool make_active, LockPolicy lock_policy) + { + if (!valid_key_id(key_id)) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Security::SecretKeyRing::add_key: invalid key_id")}; + } + if (raw_key.size() != kEnvelopeKeyBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Security::SecretKeyRing::add_key: key must be 32 bytes")}; + } + if (m_keys.contains(key_id)) { + return std::unexpected{make_security_error( + SecurityErrorCode::conflict, + "Security::SecretKeyRing::add_key: duplicate key_id")}; + } + auto stored = SecureBuffer::from_bytes(raw_key, lock_policy); + if (!stored.has_value()) { + return std::unexpected{std::move(stored.error())}; + } + const std::string id_copy = key_id; + m_keys.emplace(std::move(key_id), std::move(*stored)); + if (make_active || m_active_key_id.empty()) { + m_active_key_id = id_copy; + } + return {}; + } + + Void::Result::Result + SecretKeyRing::generate_and_add_key(std::string key_id, + bool make_active, + LockPolicy lock_policy) + { + if (auto init = ensure_sodium_env(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::random_bytes, + "Security::SecretKeyRing::generate_and_add_key"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + auto key_buf = SecureBuffer::allocate(kEnvelopeKeyBytes, lock_policy); + if (!key_buf.has_value()) { + return std::unexpected{std::move(key_buf.error())}; + } + static_assert(kEnvelopeKeyBytes == + crypto_aead_xchacha20poly1305_ietf_KEYBYTES); + crypto_aead_xchacha20poly1305_ietf_keygen(key_buf->writable().data()); + return add_key(std::move(key_id), key_buf->view(), make_active, + lock_policy); + } + + Void::Result::Result + SecretKeyRing::set_active_key(std::string_view key_id) + { + auto it = m_keys.find(key_id); + if (it == m_keys.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "Security::SecretKeyRing::set_active_key: unknown key_id")}; + } + m_active_key_id = it->first; + return {}; + } + + Void::Result::Result SecretKeyRing::retire_key( + std::string_view key_id, + std::span remaining_ciphertext_key_ids) + { + auto it = m_keys.find(key_id); + if (it == m_keys.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "Security::SecretKeyRing::retire_key: unknown key_id")}; + } + if (it->first == m_active_key_id) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_in_use, + "Security::SecretKeyRing::retire_key: cannot retire active " + "key")}; + } + for (const auto& referenced : remaining_ciphertext_key_ids) { + if (referenced == key_id) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_in_use, + "Security::SecretKeyRing::retire_key: ciphertext inventory " + "still references key_id")}; + } + } + m_keys.erase(it); + return {}; + } + + std::optional SecretKeyRing::active_key_id() const + { + if (m_active_key_id.empty()) { + return std::nullopt; + } + return m_active_key_id; + } + + bool SecretKeyRing::has_key(std::string_view key_id) const + { + return m_keys.find(key_id) != m_keys.end(); + } + + std::vector SecretKeyRing::key_ids() const + { + std::vector ids; + ids.reserve(m_keys.size()); + for (const auto& [id, _] : m_keys) { + ids.push_back(id); + } + return ids; + } + + Void::Result::Result> + SecretKeyRing::seal(std::span plaintext, + std::span aad) const + { + if (auto init = ensure_sodium_env(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + if (m_active_key_id.empty()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "Security::SecretKeyRing::seal: no active key configured")}; + } + if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::SecretKeyRing::seal: plaintext exceeds 16 MiB cap")}; + } + if (aad.size() > SecurityLimits::kMaxAadBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::SecretKeyRing::seal: AAD exceeds 64 KiB cap")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::secret_seal, "Security::SecretKeyRing::seal"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + + auto it = m_keys.find(m_active_key_id); + if (it == m_keys.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "Security::SecretKeyRing::seal: active key missing")}; + } + + static_assert(kEnvelopeNonceBytes == + crypto_aead_xchacha20poly1305_ietf_NPUBBYTES); + static_assert(kEnvelopeTagBytes == + crypto_aead_xchacha20poly1305_ietf_ABYTES); + + const std::size_t header_size = + kFixedPrefixBytes + m_active_key_id.size() + kEnvelopeNonceBytes; + std::vector out; + out.reserve(header_size + plaintext.size() + kEnvelopeTagBytes); + + out.insert(out.end(), kMagic.begin(), kMagic.end()); + out.push_back(kEnvelopeVersionV1); + out.push_back(kEnvelopeAlgXChaCha20Poly1305Ietf); + append_u16_be(out, static_cast(m_active_key_id.size())); + append_u32_be(out, static_cast(plaintext.size())); + for (const char ch : m_active_key_id) { + out.push_back(static_cast(ch)); + } + + const std::size_t nonce_offset = out.size(); + out.resize(nonce_offset + kEnvelopeNonceBytes); + randombytes_buf(out.data() + nonce_offset, kEnvelopeNonceBytes); + + const auto combined_aad = + build_aead_aad(std::span{out}, aad); + + const std::size_t ct_offset = out.size(); + out.resize(ct_offset + plaintext.size() + kEnvelopeTagBytes); + unsigned long long ct_len = 0; + + static constexpr unsigned char kEmptyByte = 0; + const unsigned char* pt_ptr = + plaintext.empty() ? &kEmptyByte : plaintext.data(); + if (crypto_aead_xchacha20poly1305_ietf_encrypt( + out.data() + ct_offset, &ct_len, pt_ptr, + static_cast(plaintext.size()), + combined_aad.data(), + static_cast(combined_aad.size()), nullptr, + out.data() + nonce_offset, it->second.view().data()) != 0 || + ct_len != plaintext.size() + kEnvelopeTagBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::SecretKeyRing::seal: AEAD encryption failed")}; + } + return out; + } + + Void::Result::Result + SecretKeyRing::open(std::span envelope, + std::span aad, + LockPolicy out_policy) const + { + if (auto init = ensure_sodium_env(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + if (aad.size() > SecurityLimits::kMaxAadBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::SecretKeyRing::open: AAD exceeds 64 KiB cap")}; + } + auto header = inspect_envelope(envelope); + if (!header.has_value()) { + return std::unexpected{std::move(header.error())}; + } + auto it = m_keys.find(header->key_id); + if (it == m_keys.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "Security::SecretKeyRing::open: unknown key_id in envelope")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::secret_open, "Security::SecretKeyRing::open"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + + const std::size_t nonce_offset = + kFixedPrefixBytes + header->key_id.size(); + const std::size_t header_and_nonce_len = + nonce_offset + kEnvelopeNonceBytes; + const auto combined_aad = + build_aead_aad(envelope.subspan(0, header_and_nonce_len), aad); + + auto plaintext = + SecureBuffer::allocate(header->plaintext_size, out_policy); + if (!plaintext.has_value()) { + return std::unexpected{std::move(plaintext.error())}; + } + + unsigned char dummy_out = 0; + unsigned char* out_ptr = + plaintext->empty() ? &dummy_out : plaintext->writable().data(); + unsigned long long pt_len = 0; + const std::size_t ct_size = envelope.size() - header_and_nonce_len; + if (crypto_aead_xchacha20poly1305_ietf_decrypt( + out_ptr, &pt_len, nullptr, + envelope.data() + header_and_nonce_len, + static_cast(ct_size), combined_aad.data(), + static_cast(combined_aad.size()), + envelope.data() + nonce_offset, + it->second.view().data()) != 0 || + pt_len != header->plaintext_size) { + plaintext->clear(); + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::SecretKeyRing::open: AEAD authentication failed")}; + } + return plaintext; + } + +} // namespace Void::Security diff --git a/src/Security/SecureBuffer.cpp b/src/Security/SecureBuffer.cpp new file mode 100644 index 0000000..f289006 --- /dev/null +++ b/src/Security/SecureBuffer.cpp @@ -0,0 +1,152 @@ +#include + +#include + +#include +#include +#include +#include + +namespace Void::Security +{ + namespace + { + std::atomic g_total_wiped_bytes{0}; + + [[nodiscard]] Void::Result::Result ensure_sodium_buf() + { + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::sodium_init, "Security::SecureBuffer"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } + static const bool ok = sodium_init() >= 0; + if (!ok) { + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::SecureBuffer: libsodium initialization failed")}; + } + return {}; + } + } // namespace + + SecureBuffer::~SecureBuffer() noexcept { clear(); } + + SecureBuffer::SecureBuffer(SecureBuffer&& other) noexcept + : m_data(std::exchange(other.m_data, nullptr)), + m_size(std::exchange(other.m_size, 0)), + m_locked(std::exchange(other.m_locked, false)) + { + } + + SecureBuffer& SecureBuffer::operator=(SecureBuffer&& other) noexcept + { + if (this != &other) { + clear(); + m_data = std::exchange(other.m_data, nullptr); + m_size = std::exchange(other.m_size, 0); + m_locked = std::exchange(other.m_locked, false); + } + return *this; + } + + void SecureBuffer::clear() noexcept + { + if (m_data != nullptr) { + if (m_size > 0) { + sodium_memzero(m_data, m_size); + g_total_wiped_bytes.fetch_add(m_size, + std::memory_order_relaxed); + } + if (m_locked) { + sodium_free(m_data); + } else { + delete[] m_data; + } + m_data = nullptr; + m_size = 0; + m_locked = false; + } + } + + std::uint64_t SecureBuffer::total_wiped_bytes() noexcept + { + return g_total_wiped_bytes.load(std::memory_order_relaxed); + } + + Void::Result::Result + SecureBuffer::allocate(std::size_t size, LockPolicy policy) + { + if (size > SecurityLimits::kMaxSecretPlaintextBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::SecureBuffer: allocation exceeds 16 MiB cap")}; + } + if (auto init = ensure_sodium_buf(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + if (size == 0) { + return SecureBuffer{}; + } + + if (policy == LockPolicy::LockedRequired || + policy == LockPolicy::LockedOptional) { + auto fault = Detail::maybe_inject_fault( + FaultOperation::locked_alloc, + "Security::SecureBuffer::allocate"); + void* raw = fault.has_value() ? nullptr : sodium_malloc(size); + if (raw != nullptr) { + sodium_memzero(raw, size); + SecureBuffer buf; + buf.m_data = static_cast(raw); + buf.m_size = size; + buf.m_locked = true; + return buf; + } + if (policy == LockPolicy::LockedRequired) { + return std::unexpected{make_security_error( + SecurityErrorCode::locked_memory_unavailable, + "Security::SecureBuffer: required locked allocation " + "failed")}; + } + } + + unsigned char* raw = new (std::nothrow) unsigned char[size]; + if (raw == nullptr) { + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::SecureBuffer: allocation failed")}; + } + sodium_memzero(raw, size); + SecureBuffer buf; + buf.m_data = raw; + buf.m_size = size; + buf.m_locked = false; + return buf; + } + + Void::Result::Result + SecureBuffer::from_bytes(std::span data, + LockPolicy policy) + { + auto buf = allocate(data.size(), policy); + if (!buf.has_value()) { + return std::unexpected{std::move(buf.error())}; + } + if (!data.empty()) { + std::memcpy(buf->m_data, data.data(), data.size()); + } + return buf; + } + + Void::Result::Result + SecureBuffer::from_string(std::string_view text, LockPolicy policy) + { + return from_bytes( + std::span{ + reinterpret_cast(text.data()), + text.size()}, + policy); + } + +} // namespace Void::Security diff --git a/src/Security/Security.cpp b/src/Security/Security.cpp index 2ee26d7..065268a 100644 --- a/src/Security/Security.cpp +++ b/src/Security/Security.cpp @@ -3,7 +3,9 @@ #include #include +#include #include +#include #include #include #include @@ -12,6 +14,9 @@ namespace Void::Security { namespace { + thread_local FaultConfig g_fault_config{}; + thread_local std::size_t g_fault_hits{0}; + struct PasswordLimits { unsigned long long operations; std::size_t memory; @@ -19,10 +24,16 @@ namespace Void::Security [[nodiscard]] Void::Result::Result ensure_sodium() { + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::sodium_init, "Security::ensure_sodium"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; + } static const bool initialized = sodium_init() >= 0; if (!initialized) { - return Void::Result::fail( - "Security: libsodium initialization failed"); + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security: libsodium initialization failed")}; } return {}; } @@ -54,21 +65,106 @@ namespace Void::Security token.size(), nullptr, 0); return digest; } + + [[nodiscard]] std::optional + parse_u64_strict(std::string_view text) noexcept + { + if (text.empty()) { + return std::nullopt; + } + for (const char ch : text) { + if (ch < '0' || ch > '9') { + return std::nullopt; + } + } + std::uint64_t value = 0; + const auto res = std::from_chars( + text.data(), text.data() + text.size(), value); + if (res.ec != std::errc{} || + res.ptr != text.data() + text.size()) { + return std::nullopt; + } + return value; + } } // namespace + ScopedFaultGuard::ScopedFaultGuard(FaultConfig config) noexcept + : m_previous(g_fault_config), m_previous_hits(g_fault_hits) + { + g_fault_config = config; + g_fault_hits = 0; + } + + ScopedFaultGuard::~ScopedFaultGuard() noexcept + { + g_fault_config = m_previous; + g_fault_hits = m_previous_hits; + } + + namespace Detail + { + std::optional + maybe_inject_fault(FaultOperation op, std::string_view operation) + { + if (g_fault_config.op == FaultOperation::none) { + return std::nullopt; + } + if (g_fault_config.op != FaultOperation::any && + g_fault_config.op != op) { + return std::nullopt; + } + if (g_fault_hits < g_fault_config.fail_after) { + ++g_fault_hits; + return std::nullopt; + } + ++g_fault_hits; + return make_security_error( + g_fault_config.code, + std::format("{}: injected security backend fault", operation)); + } + } // namespace Detail + + void wipe_bytes(std::span buffer) noexcept + { + if (!buffer.empty()) { + sodium_memzero(buffer.data(), buffer.size()); + } + } + + bool constant_time_equal(std::span lhs, + std::span rhs) noexcept + { + if (lhs.size() != rhs.size()) { + return false; + } + if (lhs.empty()) { + return true; + } + return sodium_memcmp(lhs.data(), rhs.data(), lhs.size()) == 0; + } + Void::Result::Result random_token(std::size_t entropy_bytes) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; } if (entropy_bytes == 0) { - return Void::Result::fail( - "Security::random_token: entropy must be greater than zero"); + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Security::random_token: entropy must be greater than zero")}; } - if (entropy_bytes > - (std::numeric_limits::max() - 2) / 4 * 3) { - return Void::Result::fail( - "Security::random_token: entropy size is too large"); + // 384 bytes base64url encodes to 512 chars (SecurityLimits::kMaxTokenBytes). + constexpr std::size_t kMaxEntropyBytes = + (SecurityLimits::kMaxTokenBytes / 4U) * 3U; + if (entropy_bytes > kMaxEntropyBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::random_token: entropy exceeds 512-byte token cap")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::random_bytes, "Security::random_token"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; } std::vector random(entropy_bytes); @@ -82,8 +178,9 @@ namespace Void::Security sodium_base64_VARIANT_URLSAFE_NO_PADDING); sodium_memzero(random.data(), random.size()); if (result == nullptr) { - return Void::Result::fail( - "Security::random_token: base64 encoding failed"); + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::random_token: base64 encoding failed")}; } encoded.resize(std::strlen(encoded.c_str())); return encoded; @@ -92,7 +189,12 @@ namespace Void::Security Void::Result::Result hash_token(std::string_view token) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; + } + if (token.size() > SecurityLimits::kMaxTokenBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::hash_token: token exceeds 512-byte cap")}; } const auto digest = token_digest(token); @@ -106,7 +208,12 @@ namespace Void::Security std::string_view encoded_hash) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; + } + if (token.size() > SecurityLimits::kMaxTokenBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::verify_token: token exceeds 512-byte cap")}; } constexpr auto encoded_length = crypto_generichash_BYTES * 2; @@ -132,17 +239,24 @@ namespace Void::Security hash_password(std::string_view password, PasswordHashStrength strength) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; } - if (password.size() > crypto_pwhash_PASSWD_MAX) { - return Void::Result::fail( - "Security::hash_password: password is too long"); + if (password.size() > SecurityLimits::kMaxPasswordBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::hash_password: password exceeds 1 KiB cap")}; } const auto limits = password_limits(strength); if (!limits) { - return Void::Result::fail( - "Security::hash_password: invalid strength"); + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Security::hash_password: invalid strength")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::password_hash, "Security::hash_password"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; } std::array encoded{}; @@ -151,23 +265,183 @@ namespace Void::Security static_cast(password.size()), limits->operations, limits->memory, crypto_pwhash_ALG_ARGON2ID13) != 0) { - return Void::Result::fail( - "Security::hash_password: Argon2id hashing failed"); + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::hash_password: Argon2id hashing failed")}; } return std::string{encoded.data()}; } + Void::Result::Result + parse_argon2id_cost(std::string_view encoded_hash) + { + if (encoded_hash.empty() || + encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes || + encoded_hash.find('\0') != std::string_view::npos) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: invalid hash length or NUL")}; + } + + // Format: $argon2id$v=19$m=,t=,p=$$ + constexpr std::string_view kPrefix = "$argon2id$"; + if (!encoded_hash.starts_with(kPrefix)) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: unsupported algorithm prefix")}; + } + + std::string_view rest = encoded_hash.substr(kPrefix.size()); + const auto next_field = [&](std::string_view& field) -> bool { + const auto sep = rest.find('$'); + if (sep == std::string_view::npos) { + return false; + } + field = rest.substr(0, sep); + rest = rest.substr(sep + 1); + return true; + }; + + std::string_view ver_field; + std::string_view params_field; + std::string_view salt_field; + if (!next_field(ver_field) || !next_field(params_field) || + !next_field(salt_field) || salt_field.empty() || rest.empty() || + rest.find('$') != std::string_view::npos) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: malformed PHC structure")}; + } + + if (!ver_field.starts_with("v=")) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: missing version field")}; + } + const auto ver = parse_u64_strict(ver_field.substr(2)); + if (!ver.has_value() || *ver != 19ULL) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: unsupported Argon2 version")}; + } + + const auto c1 = params_field.find(','); + if (c1 == std::string_view::npos) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: missing parameter separators")}; + } + const auto c2 = params_field.find(',', c1 + 1); + if (c2 == std::string_view::npos || + params_field.find(',', c2 + 1) != std::string_view::npos) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: invalid parameter list")}; + } + + const std::string_view m_part = params_field.substr(0, c1); + const std::string_view t_part = params_field.substr(c1 + 1, c2 - c1 - 1); + const std::string_view p_part = params_field.substr(c2 + 1); + if (!m_part.starts_with("m=") || !t_part.starts_with("t=") || + !p_part.starts_with("p=")) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: expected m=,t=,p= fields")}; + } + + const auto m_val = parse_u64_strict(m_part.substr(2)); + const auto t_val = parse_u64_strict(t_part.substr(2)); + const auto p_val = parse_u64_strict(p_part.substr(2)); + if (!m_val.has_value() || !t_val.has_value() || !p_val.has_value() || + *m_val == 0 || *t_val == 0 || *p_val == 0 || + *p_val > std::numeric_limits::max()) { + return std::unexpected{make_security_error( + SecurityErrorCode::malformed_hash, + "Security::parse_argon2id_cost: invalid m/t/p values")}; + } + + Argon2idCost cost{ + .version = static_cast(*ver), + .memory_kib = *m_val, + .iterations = *t_val, + .parallelism = static_cast(*p_val), + }; + if (!cost.memory_bytes().has_value()) { + return std::unexpected{make_security_error( + SecurityErrorCode::cost_budget_exceeded, + "Security::parse_argon2id_cost: memory cost overflows")}; + } + return cost; + } + + Void::Result::Result + verify_password_budgeted(std::string_view password, + std::string_view encoded_hash, + const PasswordVerifyBudget& budget) + { + if (const auto initialized = ensure_sodium(); !initialized) { + return std::unexpected{initialized.error()}; + } + if (password.size() > SecurityLimits::kMaxPasswordBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::verify_password_budgeted: password exceeds 1 KiB " + "cap")}; + } + if (encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::verify_password_budgeted: encoded hash exceeds 1 " + "KiB cap")}; + } + + auto cost = parse_argon2id_cost(encoded_hash); + if (!cost.has_value()) { + return std::unexpected{std::move(cost.error())}; + } + const auto mem_bytes = cost->memory_bytes(); + if (!mem_bytes.has_value() || *mem_bytes > budget.max_memory_bytes || + cost->iterations > budget.max_iterations || + cost->parallelism > budget.max_parallelism) { + return std::unexpected{make_security_error( + SecurityErrorCode::cost_budget_exceeded, + "Security::verify_password_budgeted: encoded Argon2id cost " + "exceeds approved verification budget")}; + } + + const std::string terminated_hash{encoded_hash}; + return crypto_pwhash_str_verify( + terminated_hash.c_str(), password.data(), + static_cast(password.size())) == 0; + } + Void::Result::Result verify_password(std::string_view password, std::string_view encoded_hash) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; } - if (password.size() > crypto_pwhash_PASSWD_MAX || + if (password.size() > SecurityLimits::kMaxPasswordBytes || encoded_hash.empty() || + encoded_hash.size() > SecurityLimits::kMaxEncodedHashBytes || encoded_hash.find('\0') != std::string_view::npos) { return false; } + auto cost = parse_argon2id_cost(encoded_hash); + if (!cost.has_value()) { + return false; + } + // Prevent DoS from malicious encoded costs even through the legacy + // helper while allowing all built-in libsodium presets up to Sensitive. + const auto mem_bytes = cost->memory_bytes(); + if (!mem_bytes.has_value() || + *mem_bytes > crypto_pwhash_MEMLIMIT_SENSITIVE || + cost->iterations > 32ULL || cost->parallelism > 8U) { + return std::unexpected{make_security_error( + SecurityErrorCode::cost_budget_exceeded, + "Security::verify_password: encoded Argon2id cost exceeds " + "safety ceiling")}; + } const std::string terminated_hash{encoded_hash}; return crypto_pwhash_str_verify( @@ -178,7 +452,12 @@ namespace Void::Security Void::Result::Result random_secret_key() { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::random_bytes, "Security::random_secret_key"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; } static_assert(secret_key_bytes == crypto_secretbox_KEYBYTES); @@ -192,15 +471,19 @@ namespace Void::Security const SecretKey& key) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; } static_assert(secret_nonce_bytes == crypto_secretbox_NONCEBYTES); static_assert(secret_authentication_bytes == crypto_secretbox_MACBYTES); - if (plaintext.size() > std::numeric_limits::max() - - secret_nonce_bytes - - secret_authentication_bytes) { - return Void::Result::fail( - "Security::seal_secret: plaintext is too large"); + if (plaintext.size() > SecurityLimits::kMaxSecretPlaintextBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::seal_secret: plaintext exceeds 16 MiB cap")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::secret_seal, "Security::seal_secret"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; } std::vector envelope(secret_nonce_bytes + @@ -213,8 +496,9 @@ namespace Void::Security ciphertext, plaintext.data(), static_cast(plaintext.size()), nonce, key.data()) != 0) { - return Void::Result::fail( - "Security::seal_secret: encryption failed"); + return std::unexpected{make_security_error( + SecurityErrorCode::backend_error, + "Security::seal_secret: encryption failed")}; } return envelope; } @@ -224,25 +508,39 @@ namespace Void::Security const SecretKey& key) { if (const auto initialized = ensure_sodium(); !initialized) { - return Void::Result::fail(std::move(initialized).error()); + return std::unexpected{initialized.error()}; } if (envelope.size() < secret_nonce_bytes + secret_authentication_bytes) { - return Void::Result::fail( - "Security::open_secret: envelope is truncated"); + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::open_secret: envelope is truncated")}; + } + const auto ciphertext_size = envelope.size() - secret_nonce_bytes; + const auto plaintext_size = + ciphertext_size - secret_authentication_bytes; + if (plaintext_size > SecurityLimits::kMaxSecretPlaintextBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::input_too_large, + "Security::open_secret: envelope exceeds 16 MiB cap")}; + } + if (auto fault = Detail::maybe_inject_fault( + FaultOperation::secret_open, "Security::open_secret"); + fault.has_value()) { + return std::unexpected{std::move(*fault)}; } const auto* nonce = envelope.data(); const auto* ciphertext = nonce + secret_nonce_bytes; - const auto ciphertext_size = envelope.size() - secret_nonce_bytes; - std::vector plaintext(ciphertext_size - - secret_authentication_bytes); + std::vector plaintext(plaintext_size); if (crypto_secretbox_open_easy( plaintext.data(), ciphertext, static_cast(ciphertext_size), nonce, key.data()) != 0) { - return Void::Result::fail( - "Security::open_secret: authentication failed"); + wipe_bytes(plaintext); + return std::unexpected{make_security_error( + SecurityErrorCode::authentication_failed, + "Security::open_secret: authentication failed")}; } return plaintext; } diff --git a/src/Security/module.cmake b/src/Security/module.cmake index 86b2be2..f076d09 100644 --- a/src/Security/module.cmake +++ b/src/Security/module.cmake @@ -1,4 +1,6 @@ void_add_module(Security - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Time EXTERNAL_DEPS Sodium::Sodium + EXCLUDE_HEADERS + Void/Security/Authenticator.hpp ) diff --git a/src/SecurityAsync/Authenticator.cpp b/src/SecurityAsync/Authenticator.cpp new file mode 100644 index 0000000..818b81f --- /dev/null +++ b/src/SecurityAsync/Authenticator.cpp @@ -0,0 +1,1163 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::SecurityAsync +{ + namespace + { + using namespace Void::Security; + + [[nodiscard]] std::optional + normalize_username(std::string_view raw) + { + while (!raw.empty() && + std::isspace(static_cast(raw.front()))) { + raw.remove_prefix(1); + } + while (!raw.empty() && + std::isspace(static_cast(raw.back()))) { + raw.remove_suffix(1); + } + if (raw.empty() || raw.size() > 256U) { + return std::nullopt; + } + std::string out; + out.reserve(raw.size()); + for (const unsigned char ch : raw) { + if (ch < 0x20U || ch == 0x7FU) { + return std::nullopt; + } + if (ch >= 'A' && ch <= 'Z') { + out.push_back(static_cast(ch - 'A' + 'a')); + } else { + out.push_back(static_cast(ch)); + } + } + return out; + } + + void wipe_string(std::string& s) noexcept + { + if (!s.empty()) { + wipe_bytes(std::span{ + reinterpret_cast(s.data()), s.size()}); + s.clear(); + } + } + } // namespace + + // ── InMemoryAccountSessionStore ────────────────────────────────────────── + + Void::Result::Result + InMemoryAccountSessionStore::upsert_account(AccountRecord account) + { + if (account.subject.empty() || account.normalized_username.empty()) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "InMemoryAccountSessionStore: subject and normalized_username " + "are required")}; + } + if (account.roles.size() > SecurityLimits::kMaxRolesPerPrincipal) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "InMemoryAccountSessionStore: account exceeds 64-role cap")}; + } + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + m_subject_by_username[account.normalized_username] = account.subject; + m_accounts_by_subject[account.subject] = std::move(account); + return {}; + } + + Void::Result::Result + InMemoryAccountSessionStore::bump_credential_version( + std::string_view subject, std::string new_password_hash) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto it = m_accounts_by_subject.find(subject); + if (it == m_accounts_by_subject.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "InMemoryAccountSessionStore: unknown subject")}; + } + ++it->second.credential_version; + if (!new_password_hash.empty()) { + it->second.password_hash = std::move(new_password_hash); + } + return {}; + } + + Void::Result::Result + InMemoryAccountSessionStore::set_account_enabled( + std::string_view subject, bool enabled) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto it = m_accounts_by_subject.find(subject); + if (it == m_accounts_by_subject.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "InMemoryAccountSessionStore: unknown subject")}; + } + it->second.enabled = enabled; + ++it->second.credential_version; + return {}; + } + + Void::Result::Result + InMemoryAccountSessionStore::bump_revocation_generation( + std::string_view subject) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto it = m_accounts_by_subject.find(subject); + if (it == m_accounts_by_subject.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "InMemoryAccountSessionStore: unknown subject")}; + } + ++it->second.revocation_generation; + return {}; + } + + void InMemoryAccountSessionStore::set_available(bool available) noexcept + { + std::lock_guard lk{m_mu}; + m_available = available; + } + + std::size_t InMemoryAccountSessionStore::session_count() const + { + std::lock_guard lk{m_mu}; + return m_sessions_by_id.size(); + } + + Void::Result::Result> + InMemoryAccountSessionStore::find_account_by_username( + std::string_view normalized_username) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto uit = m_subject_by_username.find(normalized_username); + if (uit == m_subject_by_username.end()) { + return std::optional{std::nullopt}; + } + auto ait = m_accounts_by_subject.find(uit->second); + if (ait == m_accounts_by_subject.end()) { + return std::optional{std::nullopt}; + } + return std::optional{ait->second}; + } + + Void::Result::Result> + InMemoryAccountSessionStore::find_account_by_subject( + std::string_view subject) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto ait = m_accounts_by_subject.find(subject); + if (ait == m_accounts_by_subject.end()) { + return std::optional{std::nullopt}; + } + return std::optional{ait->second}; + } + + Void::Result::Result + InMemoryAccountSessionStore::update_password_hash_if_version( + std::string_view subject, + std::uint64_t expected_credential_version, + std::string new_password_hash) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto it = m_accounts_by_subject.find(subject); + if (it == m_accounts_by_subject.end() || !it->second.enabled) { + return std::unexpected{make_security_error( + SecurityErrorCode::conflict, + "InMemoryAccountSessionStore: account missing or disabled")}; + } + if (it->second.credential_version != expected_credential_version) { + return std::unexpected{make_security_error( + SecurityErrorCode::conflict, + "InMemoryAccountSessionStore: credential version mismatch")}; + } + it->second.password_hash = std::move(new_password_hash); + ++it->second.credential_version; + return {}; + } + + Void::Result::Result + InMemoryAccountSessionStore::create_session_if_version( + const SessionRecord& session, + std::uint64_t expected_credential_version, + std::size_t max_total_sessions, std::size_t max_per_subject, + Void::Time::CivilClock::time_point now) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto ait = m_accounts_by_subject.find(session.subject); + if (ait == m_accounts_by_subject.end() || !ait->second.enabled) { + return std::unexpected{make_security_error( + SecurityErrorCode::conflict, + "InMemoryAccountSessionStore: account missing or disabled")}; + } + if (ait->second.credential_version != expected_credential_version) { + return std::unexpected{make_security_error( + SecurityErrorCode::conflict, + "InMemoryAccountSessionStore: credential changed during " + "login")}; + } + + std::size_t active_total = 0; + std::size_t active_subject = 0; + for (const auto& [_, rec] : m_sessions_by_id) { + if (!rec.revoked && now < rec.expires_at) { + ++active_total; + if (rec.subject == session.subject) { + ++active_subject; + } + } + } + if (active_total >= max_total_sessions || + active_subject >= max_per_subject) { + return std::unexpected{make_security_error( + SecurityErrorCode::session_capacity_exceeded, + "InMemoryAccountSessionStore: session capacity limit " + "reached")}; + } + + m_session_id_by_digest[session.token_digest] = session.session_id; + m_sessions_by_id[session.session_id] = session; + return {}; + } + + Void::Result::Result> + InMemoryAccountSessionStore::find_session_by_token_digest( + std::string_view token_digest) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto dit = m_session_id_by_digest.find(token_digest); + if (dit == m_session_id_by_digest.end()) { + return std::optional{std::nullopt}; + } + auto sit = m_sessions_by_id.find(dit->second); + if (sit == m_sessions_by_id.end()) { + return std::optional{std::nullopt}; + } + return std::optional{sit->second}; + } + + Void::Result::Result + InMemoryAccountSessionStore::revoke_session(std::string_view session_id) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + auto sit = m_sessions_by_id.find(session_id); + if (sit == m_sessions_by_id.end()) { + return std::unexpected{make_security_error( + SecurityErrorCode::key_not_found, + "InMemoryAccountSessionStore: session not found")}; + } + sit->second.revoked = true; + return {}; + } + + Void::Result::Result + InMemoryAccountSessionStore::cleanup_expired_sessions( + Void::Time::CivilClock::time_point now, std::size_t batch_limit) + { + std::lock_guard lk{m_mu}; + if (!m_available) { + return std::unexpected{make_security_error( + SecurityErrorCode::store_unavailable, + "InMemoryAccountSessionStore: store unavailable")}; + } + std::size_t removed = 0; + for (auto it = m_sessions_by_id.begin(); + it != m_sessions_by_id.end() && removed < batch_limit;) { + if (it->second.revoked || now >= it->second.expires_at) { + m_session_id_by_digest.erase(it->second.token_digest); + it = m_sessions_by_id.erase(it); + ++removed; + } else { + ++it; + } + } + return removed; + } + + // ── InMemoryAuditSink ──────────────────────────────────────────────────── + + Void::Result::Result + InMemoryAuditSink::record(const AuditEvent& event) + { + std::lock_guard lk{m_mu}; + if (m_events.size() >= m_max_events) { + return std::unexpected{make_security_error( + SecurityErrorCode::audit_failed, + "InMemoryAuditSink: audit queue is full")}; + } + m_events.push_back(event); + return {}; + } + + std::vector InMemoryAuditSink::snapshot() const + { + std::lock_guard lk{m_mu}; + return m_events; + } + + void InMemoryAuditSink::clear() + { + std::lock_guard lk{m_mu}; + m_events.clear(); + } + + // ── BearerToken ────────────────────────────────────────────────────────── + + Void::Result::Result + BearerToken::from_string(std::string_view raw, LockPolicy policy) + { + if (raw.empty() || raw.size() > SecurityLimits::kMaxTokenBytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "BearerToken: invalid token length")}; + } + auto buf = SecureBuffer::from_string(raw, policy); + if (!buf.has_value()) { + return std::unexpected{std::move(buf.error())}; + } + return BearerToken{std::move(*buf)}; + } + + // ── Authenticator ──────────────────────────────────────────────────────── + + struct Authenticator::State : std::enable_shared_from_this { + struct PasswordJob { + PasswordJob( + SecureBuffer pwd, std::string hash, + std::size_t req_mem, + std::shared_ptr> o) + : password(std::move(pwd)), + encoded_hash(std::move(hash)), + required_memory(req_mem), op(std::move(o)) + { + } + + SecureBuffer password; + std::string encoded_hash; + std::size_t required_memory{0}; + std::shared_ptr> op; + std::optional>> + cancel_cb{}; + }; + + State(std::shared_ptr p, + Void::Async::Executor& exec, AuthenticatorOptions opts, + std::string dummy, + Void::Resilience::BoundedKeyedRateLimiter rl, + std::shared_ptr sink, + const Void::Time::MonotonicClock& mono, + const Void::Time::CivilClock& civ, + Void::Time::CivilClock::time_point initial_watermark) + : port(std::move(p)), executor(exec), options(std::move(opts)), + dummy_hash(std::move(dummy)), rate_limiter(std::move(rl)), + audit_sink(std::move(sink)), monotonic_clock(mono), + civil_clock(civ), civil_watermark(initial_watermark) + { + } + + [[nodiscard]] Void::Result::Result< + Void::Time::CivilClock::time_point> + check_civil_clock() + { + const auto now = civil_clock.now(); + std::lock_guard lk{clock_mu}; + if (clock_halted) { + return std::unexpected{make_security_error( + SecurityErrorCode::clock_rollback, + "Authenticator: civil clock rollback requires " + "reconciliation")}; + } + if (now + options.session.clock_rollback_tolerance < + civil_watermark) { + clock_halted = true; + return std::unexpected{make_security_error( + SecurityErrorCode::clock_rollback, + "Authenticator: civil clock rolled back beyond " + "configured tolerance")}; + } + if (now > civil_watermark) { + civil_watermark = now; + } + return now; + } + + [[nodiscard]] Void::Result::Result + emit_audit(const AuditEvent& ev) + { + if (!audit_sink) { + return {}; + } + auto res = audit_sink->record(ev); + if (!res.has_value() && + options.audit_policy == AuditFailurePolicy::FailClosed) { + return std::unexpected{make_security_error( + SecurityErrorCode::audit_failed, + "Authenticator: mandatory audit sink rejected event")}; + } + return {}; + } + + void start_workers_locked() + { + if (workers_started) { + return; + } + workers_started = true; + const std::size_t count = std::max( + 1, options.password_budget.max_concurrent_jobs); + workers.reserve(count); + auto self = shared_from_this(); + for (std::size_t i = 0; i < count; ++i) { + workers.emplace_back([self] { self->worker_loop(); }); + } + } + + void worker_loop() + { + for (;;) { + std::shared_ptr job; + { + std::unique_lock lk{mu}; + cv.wait(lk, [this] { + if (closing) { + return true; + } + if (queue.empty()) { + return false; + } + if (active_jobs < + options.password_budget + .max_concurrent_jobs && + reserved_memory + + queue.front()->required_memory <= + options.password_budget.max_memory_bytes) { + return true; + } + return std::any_of( + queue.begin(), queue.end(), + [this](const auto& j) { + return j->op->stop_requested() || + j->op->is_deadline_expired( + monotonic_clock); + }); + }); + + std::vector, + Void::Result::Error>> + dropped; + for (auto it = queue.begin(); it != queue.end();) { + auto& item = *it; + if (closing || item->op->stop_requested()) { + dropped.emplace_back( + std::move(item), + make_security_error( + closing ? SecurityErrorCode::closed + : SecurityErrorCode::cancelled, + "Authenticator: password job cancelled " + "while queued")); + it = queue.erase(it); + } else if (item->op->is_deadline_expired( + monotonic_clock)) { + dropped.emplace_back( + std::move(item), + make_security_error( + SecurityErrorCode::timeout, + "Authenticator: password job deadline " + "expired while queued")); + it = queue.erase(it); + } else { + ++it; + } + } + if (!dropped.empty()) { + lk.unlock(); + for (auto& [d, err] : dropped) { + d->cancel_cb.reset(); + d->password.clear(); + const auto kind = + (err.kind() == + Void::Result::ErrorKind::cancelled) + ? Void::Async::DomainOutcomeKind:: + cancelled + : Void::Async::DomainOutcomeKind:: + failed; + if (auto t = d->op->try_commit_error( + std::move(err), kind); + t.has_value()) { + t->dispatch(); + } + d->op->release_backend_ref_and_dispatch(); + } + lk.lock(); + } + + if (closing && queue.empty()) { + return; + } + if (queue.empty() || + active_jobs >= + options.password_budget.max_concurrent_jobs || + reserved_memory + queue.front()->required_memory > + options.password_budget.max_memory_bytes) { + continue; + } + + job = std::move(queue.front()); + queue.pop_front(); + ++active_jobs; + reserved_memory += job->required_memory; + in_flight.push_back(job->op); + } + + job->cancel_cb.reset(); + + if (options.before_password_verify_hook) { + options.before_password_verify_hook(); + } + + // Non-interruptible password computation: retains buffers & + // memory budget until completion even if stopped mid-flight. + auto verified = verify_password_budgeted( + job->password.string_view(), job->encoded_hash, + options.verify_budget); + job->password.clear(); + + { + std::lock_guard lk{mu}; + --active_jobs; + reserved_memory -= job->required_memory; + std::erase_if(in_flight, [&](const auto& weak_op) { + auto sp = weak_op.lock(); + return !sp || sp == job->op; + }); + } + cv.notify_all(); + + std::optional ticket; + if (job->op->stop_requested()) { + // Discard verification result on cancellation. + ticket = job->op->try_commit_error( + make_security_error( + SecurityErrorCode::cancelled, + "Authenticator: login cancelled during " + "password verification"), + Void::Async::DomainOutcomeKind::cancelled); + } else if (job->op->is_deadline_expired(monotonic_clock)) { + ticket = job->op->try_commit_error( + make_security_error( + SecurityErrorCode::timeout, + "Authenticator: login deadline expired during " + "password verification"), + Void::Async::DomainOutcomeKind::failed); + } else if (verified.has_value()) { + ticket = job->op->try_commit_value(*verified); + } else { + ticket = job->op->try_commit_error( + std::move(verified.error()), + Void::Async::DomainOutcomeKind::failed); + } + if (ticket.has_value()) { + ticket->dispatch(); + } + job->op->release_backend_ref_and_dispatch(); + } + } + + std::shared_ptr port; + Void::Async::Executor& executor; + AuthenticatorOptions options; + std::string dummy_hash; + Void::Resilience::BoundedKeyedRateLimiter rate_limiter; + std::shared_ptr audit_sink; + const Void::Time::MonotonicClock& monotonic_clock; + const Void::Time::CivilClock& civil_clock; + + mutable std::mutex clock_mu{}; + Void::Time::CivilClock::time_point civil_watermark{}; + bool clock_halted{false}; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::deque> queue{}; + std::vector>> + in_flight{}; + std::vector workers{}; + bool workers_started{false}; + bool closing{false}; + bool joined{false}; + std::size_t active_jobs{0}; + std::size_t reserved_memory{0}; + }; + + Authenticator::Authenticator(std::shared_ptr state) noexcept + : m_state(std::move(state)) + { + } + + Authenticator::~Authenticator() { (void)close_and_join(); } + + Void::Result::Result> + Authenticator::create(std::shared_ptr port, + Void::Async::Executor& executor, + AuthenticatorOptions options, + std::shared_ptr audit_sink, + const Void::Time::MonotonicClock& monotonic_clock, + const Void::Time::CivilClock& civil_clock) + { + if (!port) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Authenticator::create: AccountSessionPort is required")}; + } + if (options.session.ttl <= std::chrono::seconds{0} || + options.session.max_total_sessions == 0 || + options.session.max_per_subject == 0 || + options.session.expiry_cleanup_batch == 0 || + options.session.clock_rollback_tolerance < + std::chrono::seconds{0}) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Authenticator::create: invalid SessionPolicy")}; + } + if (options.password_budget.max_concurrent_jobs == 0 || + options.password_budget.max_memory_bytes == 0) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Authenticator::create: invalid PasswordJobBudget")}; + } + + std::string dummy = options.precomputed_dummy_hash; + if (dummy.empty()) { + auto hashed = hash_password("void-authenticator-dummy-parity", + options.dummy_hash_strength); + if (!hashed.has_value()) { + return std::unexpected{std::move(hashed.error())}; + } + dummy = std::move(*hashed); + } + auto dummy_cost = parse_argon2id_cost(dummy); + if (!dummy_cost.has_value()) { + return std::unexpected{std::move(dummy_cost.error())}; + } + const auto dummy_mem = dummy_cost->memory_bytes(); + if (!dummy_mem.has_value() || + *dummy_mem > options.verify_budget.max_memory_bytes || + *dummy_mem > options.password_budget.max_memory_bytes) { + return std::unexpected{make_security_error( + SecurityErrorCode::cost_budget_exceeded, + "Authenticator::create: dummy password preset exceeds " + "configured password memory budget")}; + } + + auto rl = Void::Resilience::BoundedKeyedRateLimiter::create( + options.rate_limit, monotonic_clock); + if (!rl.has_value()) { + return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Authenticator::create: invalid rate_limit configuration")}; + } + + const auto now = civil_clock.now(); + const auto watermark = options.last_known_civil_time.value_or(now); + + auto state = std::make_shared( + std::move(port), executor, std::move(options), std::move(dummy), + std::move(*rl), std::move(audit_sink), monotonic_clock, civil_clock, + watermark); + return std::unique_ptr( + new Authenticator(std::move(state))); + } + + Void::Coro::Task> + Authenticator::login(LoginInput input, + Void::Async::OperationOptions options) + { + auto state = m_state; + + struct PasswordWiper { + std::string& ref; + ~PasswordWiper() noexcept { wipe_string(ref); } + } input_wiper{input.password}; + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::cancelled, + "Authenticator::login: stopped before admission")}; + } + if (Void::Async::is_deadline_expired(options, state->monotonic_clock)) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::timeout, + "Authenticator::login: deadline expired before admission")}; + } + + auto now = state->check_civil_clock(); + if (!now.has_value()) { + co_return std::unexpected{std::move(now.error())}; + } + + auto normalized = normalize_username(input.username); + if (!normalized.has_value() || input.password.empty() || + input.password.size() > SecurityLimits::kMaxPasswordBytes) { + if (auto a = state->emit_audit(AuditEvent{ + .event_type = "login", + .subject = "", + .internal_reason = "malformed_credentials", + .success = false, + .timestamp = *now}); + !a.has_value()) { + co_return std::unexpected{std::move(a.error())}; + } + co_return std::unexpected{make_security_error( + SecurityErrorCode::denied, "Authentication failed")}; + } + + auto adm = state->rate_limiter.admit(*normalized); + if (!adm.has_value() || !adm->allowed) { + (void)state->emit_audit(AuditEvent{ + .event_type = "login", + .subject = "", + .internal_reason = "rate_limited", + .success = false, + .timestamp = *now}); + co_return std::unexpected{make_security_error( + SecurityErrorCode::rate_limited, + "Authenticator::login: rate limit exceeded")}; + } + + auto acct_res = state->port->find_account_by_username(*normalized); + if (!acct_res.has_value()) { + co_return std::unexpected{std::move(acct_res.error())}; + } + + const bool account_present = acct_res->has_value(); + const bool account_enabled = account_present && (*acct_res)->enabled; + const std::string target_hash = + account_enabled ? (*acct_res)->password_hash : state->dummy_hash; + + auto cost = parse_argon2id_cost(target_hash); + if (!cost.has_value()) { + co_return std::unexpected{std::move(cost.error())}; + } + const auto mem_bytes = cost->memory_bytes(); + if (!mem_bytes.has_value() || + *mem_bytes > state->options.verify_budget.max_memory_bytes || + *mem_bytes > state->options.password_budget.max_memory_bytes || + cost->iterations > state->options.verify_budget.max_iterations || + cost->parallelism > state->options.verify_budget.max_parallelism) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::cost_budget_exceeded, + "Authenticator::login: stored password hash exceeds budget")}; + } + + auto pwd_buf = SecureBuffer::from_string( + input.password, state->options.secret_lock_policy); + wipe_string(input.password); + if (!pwd_buf.has_value()) { + co_return std::unexpected{std::move(pwd_buf.error())}; + } + + auto op = Void::Async::OperationState::create( + options, &state->executor, Void::Async::StopBehavior::notify_only); + auto job = std::make_shared( + std::move(*pwd_buf), target_hash, + static_cast(*mem_bytes), op); + + { + std::lock_guard lk{state->mu}; + if (state->closing) { + job->password.clear(); + co_return std::unexpected{make_security_error( + SecurityErrorCode::closed, + "Authenticator::login: service is closing")}; + } + const std::size_t max_capacity = + state->options.password_budget.max_concurrent_jobs + + state->options.password_budget.max_waiters; + if (state->active_jobs + state->queue.size() >= max_capacity) { + job->password.clear(); + co_return std::unexpected{make_security_error( + SecurityErrorCode::overloaded, + "Authenticator::login: password verification queue full")}; + } + op->acquire_backend_ref(); + state->start_workers_locked(); + if (options.stop.stop_possible()) { + std::weak_ptr weak_state = state; + job->cancel_cb.emplace(options.stop, [weak_state]() { + if (auto s = weak_state.lock()) { + s->cv.notify_all(); + } + }); + } + state->queue.push_back(std::move(job)); + } + state->cv.notify_one(); + + auto verify_res = co_await op->awaitable(&state->executor); + if (!verify_res.has_value()) { + co_return std::unexpected{std::move(verify_res.error())}; + } + + auto post_now = state->check_civil_clock(); + if (!post_now.has_value()) { + co_return std::unexpected{std::move(post_now.error())}; + } + + if (!account_present || !account_enabled || !*verify_res) { + const std::string reason = + !account_present + ? "account_not_found" + : (!account_enabled ? "account_disabled" + : "invalid_password"); + if (auto a = state->emit_audit(AuditEvent{ + .event_type = "login", + .subject = account_present ? (*acct_res)->subject : "", + .internal_reason = reason, + .success = false, + .timestamp = *post_now}); + !a.has_value()) { + co_return std::unexpected{std::move(a.error())}; + } + co_return std::unexpected{make_security_error( + SecurityErrorCode::denied, "Authentication failed")}; + } + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::cancelled, + "Authenticator::login: stopped before session write")}; + } + + const auto& account = **acct_res; + if (account.roles.size() > SecurityLimits::kMaxRolesPerPrincipal) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::policy_invalid, + "Authenticator::login: account exceeds 64-role cap")}; + } + + auto raw_token = random_token(default_token_entropy_bytes); + if (!raw_token.has_value()) { + co_return std::unexpected{std::move(raw_token.error())}; + } + auto token_holder = BearerToken::from_string( + *raw_token, state->options.secret_lock_policy); + auto token_digest = hash_token(*raw_token); + wipe_string(*raw_token); + if (!token_holder.has_value()) { + co_return std::unexpected{std::move(token_holder.error())}; + } + if (!token_digest.has_value()) { + co_return std::unexpected{std::move(token_digest.error())}; + } + + auto session_id = random_token(16); + if (!session_id.has_value()) { + co_return std::unexpected{std::move(session_id.error())}; + } + + const auto expires_at = *post_now + state->options.session.ttl; + SessionRecord record{ + .session_id = *session_id, + .token_digest = std::move(*token_digest), + .subject = account.subject, + .roles = account.roles, + .credential_version = account.credential_version, + .revocation_generation = account.revocation_generation, + .policy_generation = account.policy_generation, + .created_at = *post_now, + .expires_at = expires_at, + .revoked = false, + }; + + auto created = state->port->create_session_if_version( + record, account.credential_version, + state->options.session.max_total_sessions, + state->options.session.max_per_subject, *post_now); + if (!created.has_value()) { + const bool is_conflict = + created.error().code().value == + static_cast(SecurityErrorCode::conflict); + (void)state->emit_audit(AuditEvent{ + .event_type = "login", + .subject = account.subject, + .internal_reason = is_conflict ? "credential_version_conflict" + : "session_write_failed", + .success = false, + .timestamp = *post_now}); + co_return std::unexpected{std::move(created.error())}; + } + + if (auto a = state->emit_audit(AuditEvent{ + .event_type = "login", + .subject = account.subject, + .internal_reason = "login_success", + .success = true, + .timestamp = *post_now}); + !a.has_value()) { + // Mandatory audit failed: undo session grant and wipe bearer token. + (void)state->port->revoke_session(record.session_id); + token_holder->clear(); + co_return std::unexpected{std::move(a.error())}; + } + + Principal principal{ + .subject = account.subject, + .roles = account.roles, + .policy_generation = account.policy_generation, + }; + + co_return SessionGrant{ + .session_id = std::move(record.session_id), + .bearer_token = std::move(*token_holder), + .expires_at = expires_at, + .principal = std::move(principal), + }; + } + + Void::Coro::Task> + Authenticator::authenticate(const BearerToken& token, + Void::Async::OperationOptions options) + { + auto state = m_state; + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::cancelled, + "Authenticator::authenticate: stopped")}; + } + if (Void::Async::is_deadline_expired(options, state->monotonic_clock)) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::timeout, + "Authenticator::authenticate: deadline expired")}; + } + { + std::lock_guard lk{state->mu}; + if (state->closing) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::closed, + "Authenticator::authenticate: service is closing")}; + } + } + + auto now = state->check_civil_clock(); + if (!now.has_value()) { + co_return std::unexpected{std::move(now.error())}; + } + + if (token.empty() || + token.expose_secret().size() > SecurityLimits::kMaxTokenBytes) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::denied, "Invalid bearer token")}; + } + + auto digest = hash_token(token.expose_secret()); + if (!digest.has_value()) { + co_return std::unexpected{std::move(digest.error())}; + } + + // Authoritative lookup every call; zero positive session cache. + auto session_res = state->port->find_session_by_token_digest(*digest); + if (!session_res.has_value()) { + co_return std::unexpected{std::move(session_res.error())}; + } + if (!session_res->has_value()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::denied, "Session not found")}; + } + + const auto& session = **session_res; + if (session.revoked) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::session_revoked, "Session revoked")}; + } + if (*now >= session.expires_at) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::session_expired, "Session expired")}; + } + + auto acct_res = state->port->find_account_by_subject(session.subject); + if (!acct_res.has_value()) { + co_return std::unexpected{std::move(acct_res.error())}; + } + if (!acct_res->has_value() || !(*acct_res)->enabled || + (*acct_res)->revocation_generation != + session.revocation_generation) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::session_revoked, + "Account disabled or revocation generation advanced")}; + } + + co_return Principal{ + .subject = session.subject, + .roles = session.roles, + .policy_generation = session.policy_generation, + }; + } + + Void::Coro::Task> + Authenticator::revoke(std::string session_id, + Void::Async::OperationOptions options) + { + auto state = m_state; + + if (options.stop.stop_requested()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::cancelled, + "Authenticator::revoke: stopped")}; + } + if (Void::Async::is_deadline_expired(options, state->monotonic_clock)) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::timeout, + "Authenticator::revoke: deadline expired")}; + } + if (session_id.empty()) { + co_return std::unexpected{make_security_error( + SecurityErrorCode::invalid_argument, + "Authenticator::revoke: session_id must be non-empty")}; + } + + auto res = state->port->revoke_session(session_id); + if (!res.has_value()) { + co_return std::unexpected{std::move(res.error())}; + } + + (void)state->emit_audit(AuditEvent{ + .event_type = "revoke", + .subject = "", + .internal_reason = "session_revoked", + .success = true, + .timestamp = state->civil_clock.now()}); + co_return Void::Result::Result{}; + } + + Void::Result::Result Authenticator::cleanup_expired_step() + { + return m_state->port->cleanup_expired_sessions( + m_state->civil_clock.now(), + m_state->options.session.expiry_cleanup_batch); + } + + void Authenticator::reconcile_clock( + Void::Time::CivilClock::time_point new_watermark) noexcept + { + std::lock_guard lk{m_state->clock_mu}; + m_state->civil_watermark = new_watermark; + m_state->clock_halted = false; + } + + void Authenticator::request_stop() noexcept + { + std::vector>> ops; + { + std::lock_guard lk{m_state->mu}; + m_state->closing = true; + for (const auto& j : m_state->queue) { + ops.push_back(j->op); + } + for (const auto& weak_op : m_state->in_flight) { + if (auto sp = weak_op.lock()) { + ops.push_back(std::move(sp)); + } + } + } + for (auto& op : ops) { + op->request_stop(); + } + m_state->cv.notify_all(); + } + + Void::Result::Result Authenticator::close_and_join() + { + request_stop(); + std::vector threads; + { + std::lock_guard lk{m_state->mu}; + if (m_state->joined) { + return {}; + } + m_state->joined = true; + threads.swap(m_state->workers); + } + for (auto& t : threads) { + if (t.joinable()) { + t.join(); + } + } + return {}; + } + + AuthenticatorStats Authenticator::stats() const noexcept + { + std::lock_guard lk{m_state->mu}; + return AuthenticatorStats{ + .active_password_jobs = m_state->active_jobs, + .waiting_password_jobs = m_state->queue.size(), + .reserved_password_memory_bytes = m_state->reserved_memory, + .closing = m_state->closing, + }; + } + +} // namespace Void::SecurityAsync diff --git a/src/SecurityAsync/module.cmake b/src/SecurityAsync/module.cmake new file mode 100644 index 0000000..a435cd7 --- /dev/null +++ b/src/SecurityAsync/module.cmake @@ -0,0 +1,6 @@ +void_add_module(SecurityAsync + INTERNAL_DEPS Security Async Time Resilience Functional + EXTERNAL_DEPS Threads::Threads + EXTRA_HEADERS + Void/Security/Authenticator.hpp +) diff --git a/src/Update/Feed.cpp b/src/Update/Feed.cpp index 1950e17..76a8ed2 100644 --- a/src/Update/Feed.cpp +++ b/src/Update/Feed.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -592,6 +593,26 @@ namespace Void::Update } return true; } + [[nodiscard]] Void::Result::Result + enforce_parse_policy(std::string_view payload, + const VerificationPolicy& policy) + { + if (policy.parsePolicy == SchemaParsePolicy::StrictJsonProfile) { + auto strict = Json::Strict::parse( + payload, Json::Strict::ParseOptions{ + .maximumDepth = policy.maxJsonDepth, + .allowDecimals = false, + }); + if (!strict.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::schema_error, + std::format("Update feed: StrictJsonProfile rejected " + "payload: {}", + strict.error().message))}; + } + } + return {}; + } } // namespace Void::Result::Result @@ -599,8 +620,13 @@ namespace Void::Update const VerificationPolicy& policy) { if (payload.size() > policy.maxPayloadBytes) { - return Void::Result::fail( - "Update feed: payload exceeds policy size"); + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "Update feed: payload exceeds policy size")}; + } + if (auto strict = enforce_parse_policy(payload, policy); + !strict.has_value()) { + return std::unexpected{std::move(strict.error())}; } return parse_feed(payload, policy); } @@ -665,25 +691,21 @@ namespace Void::Update } const auto key = keys.find(*keyId); if (key == keys.end()) { - return Void::Result::fail( - "Update feed: envelope key is not trusted"); + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "Update feed: envelope key is not trusted")}; } auto payload = Encoding::Base64::decode_url(*payloadText); auto signature = Encoding::Base64::decode_url(*signatureText); if (!payload || !signature || payload->size() > policy.maxPayloadBytes) { - return Void::Result::fail( - "Update feed: invalid or oversized envelope encoding"); - } - if (*schema == 3) { - auto signedDocument = Json::parse(*payload); - if (!signedDocument || !signedDocument->is_object() || - displayedDocument == nullptr || - *displayedDocument != *signedDocument) { - return Void::Result::fail("Update feed: readable document " - "differs from signed payload"); - } + return std::unexpected{make_update_error( + UpdateErrorCode::schema_error, + "Update feed: invalid or oversized envelope encoding")}; } + + // Verify exact signed payload bytes BEFORE any payload JSON parsing or + // schema-3 readable-document mirror comparison. const auto signatureBytes = std::as_bytes(std::span{signature->data(), signature->size()}); const auto payloadBytes = @@ -691,11 +713,30 @@ namespace Void::Update auto valid = Crypto::verifyEd25519(payloadBytes, signatureBytes, key->second); if (!valid) { - return std::unexpected{valid.error()}; + return std::unexpected{make_update_error( + UpdateErrorCode::signature_failed, valid.error().message())}; } if (!*valid) { - return Void::Result::fail( - "Update feed: signature verification failed"); + return std::unexpected{make_update_error( + UpdateErrorCode::signature_failed, + "Update feed: signature verification failed")}; + } + + if (auto strict = enforce_parse_policy(*payload, policy); + !strict.has_value()) { + return std::unexpected{std::move(strict.error())}; + } + + if (*schema == 3) { + auto signedDocument = Json::parse(*payload); + if (!signedDocument || !signedDocument->is_object() || + displayedDocument == nullptr || + *displayedDocument != *signedDocument) { + return std::unexpected{make_update_error( + UpdateErrorCode::mirror_mismatch, + "Update feed: readable document differs from signed " + "payload")}; + } } return VerifiedEnvelope{.schemaVersion = *schema, .keyId = std::move(*keyId), @@ -707,8 +748,13 @@ namespace Void::Update const VerificationPolicy& policy) { if (payload.size() > policy.maxPayloadBytes) { - return Void::Result::fail( - "Component feed: payload exceeds policy size"); + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "Component feed: payload exceeds policy size")}; + } + if (auto strict = enforce_parse_policy(payload, policy); + !strict.has_value()) { + return std::unexpected{std::move(strict.error())}; } auto document = Json::parse(payload); if (!document || !document->is_object()) { @@ -754,8 +800,13 @@ namespace Void::Update const VerificationPolicy& policy) { if (payload.size() > policy.maxPayloadBytes) { - return Void::Result::fail( - "Component feed: payload exceeds policy size"); + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "Component feed: payload exceeds policy size")}; + } + if (auto strict = enforce_parse_policy(payload, policy); + !strict.has_value()) { + return std::unexpected{std::move(strict.error())}; } auto document = Json::parse(payload); if (!document || !document->is_object()) { @@ -919,4 +970,124 @@ namespace Void::Update } return *selected; } + + Void::Result::Result + verify_and_select_release(std::string_view envelopeJson, + const Keyring& keys, + const SelectionRequest& request, + const VerificationPolicy& policy) + { + auto verified = verifyFeedEnvelope(envelopeJson, keys, policy); + if (!verified.has_value()) { + return std::unexpected{std::move(verified.error())}; + } + auto selected = selectRelease(verified->feed, request); + if (!selected.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::schema_error, + "Update feed: no compatible release matched selection " + "request")}; + } + + VerifiedSelection out; + out.m_signed_envelope.assign(envelopeJson); + out.m_signed_payload = std::move(verified->signedPayload); + out.m_signer_key_id = std::move(verified->keyId); + out.m_feed_id = verified->feed.feedId; + out.m_sequence = verified->feed.sequence; + out.m_expires_at = verified->feed.expiresAt; + out.m_parse_policy = policy.parsePolicy; + out.m_release = ReleaseIdentity{ + .component = std::move(selected->component), + .artifact_id = std::move(selected->artifactId), + .channel = std::move(selected->channel), + .version = std::move(selected->version), + .sequence = verified->feed.sequence, + .sha256 = std::move(selected->sha256), + .size = selected->size, + .url = std::move(selected->url), + .package_type = std::move(selected->packageType), + }; + return out; + } + + Void::Result::Result verify_and_select_component_set( + std::string_view catalogEnvelopeJson, + const std::map& releaseEnvelopeJsons, + const Keyring& keys, std::string_view primaryComponentId, + const VerificationPolicy& policy) + { + auto cat_env = verifyEnvelope(catalogEnvelopeJson, keys, policy); + if (!cat_env.has_value()) { + return std::unexpected{std::move(cat_env.error())}; + } + auto catalog = + parseComponentCatalogPayload(cat_env->signedPayload, policy); + if (!catalog.has_value()) { + return std::unexpected{std::move(catalog.error())}; + } + if (catalog->components.size() > + UpdateLimits::kDefaultMaxComponentsPerTransaction) { + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "Component set: exceeds 32-component transaction limit")}; + } + + std::map releases; + std::size_t edge_count = 0; + for (const auto& [comp_id, env_json] : releaseEnvelopeJsons) { + auto rel_env = verifyEnvelope(env_json, keys, policy); + if (!rel_env.has_value()) { + return std::unexpected{std::move(rel_env.error())}; + } + auto rel = + parseComponentReleasePayload(rel_env->signedPayload, policy); + if (!rel.has_value()) { + return std::unexpected{std::move(rel.error())}; + } + edge_count += rel->dependencies.size(); + if (edge_count > UpdateLimits::kDefaultMaxDependencyEdges) { + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "Component set: exceeds 256 dependency-edge limit")}; + } + releases.emplace(comp_id, std::move(*rel)); + } + + if (auto valid = validateComponentSet(*catalog, releases); + !valid.has_value()) { + return std::unexpected{std::move(valid.error())}; + } + + auto primary_it = releases.find(std::string{primaryComponentId}); + if (primary_it == releases.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "Component set: primaryComponentId not present in verified " + "set")}; + } + + const auto& primary = primary_it->second; + VerifiedSelection out; + out.m_signed_envelope.assign(catalogEnvelopeJson); + out.m_signed_payload = std::move(cat_env->signedPayload); + out.m_signer_key_id = std::move(cat_env->keyId); + out.m_feed_id = "component-catalog"; + out.m_sequence = catalog->sequence; + out.m_expires_at = catalog->expiresAt; + out.m_parse_policy = policy.parsePolicy; + out.m_release = ReleaseIdentity{ + .component = primary.componentId, + .artifact_id = primary.artifactIdentity, + .channel = primary.channel, + .version = primary.componentVersion, + .sequence = primary.sequence, + .sha256 = primary.artifact.sha256, + .size = primary.artifact.size, + .url = primary.artifact.url, + .package_type = primary.artifact.packageType, + }; + out.m_components = std::move(releases); + return out; + } } // namespace Void::Update diff --git a/src/Update/Install.cpp b/src/Update/Install.cpp new file mode 100644 index 0000000..098ddd2 --- /dev/null +++ b/src/Update/Install.cpp @@ -0,0 +1,1292 @@ +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Update +{ + namespace + { + std::atomic g_install_seq{0}; + + [[nodiscard]] std::string sha256_hex(std::string_view data) + { + auto d = Crypto::sha256(data); + if (!d.has_value()) { + return {}; + } + return Encoding::Hex::encode(*d); + } + + [[nodiscard]] std::string + state_to_string(InstallState state) noexcept + { + switch (state) { + case InstallState::Verified: + return "Verified"; + case InstallState::Downloading: + return "Downloading"; + case InstallState::Staged: + return "Staged"; + case InstallState::Published: + return "Published"; + case InstallState::Activated: + return "Activated"; + case InstallState::HealthyCommitted: + return "HealthyCommitted"; + case InstallState::CleanupPending: + return "CleanupPending"; + case InstallState::RolledBack: + return "RolledBack"; + case InstallState::RecoveryRequired: + return "RecoveryRequired"; + } + return "RecoveryRequired"; + } + + [[nodiscard]] std::optional + parse_state(std::string_view text) noexcept + { + if (text == "Verified") { + return InstallState::Verified; + } + if (text == "Downloading") { + return InstallState::Downloading; + } + if (text == "Staged") { + return InstallState::Staged; + } + if (text == "Published") { + return InstallState::Published; + } + if (text == "Activated") { + return InstallState::Activated; + } + if (text == "HealthyCommitted") { + return InstallState::HealthyCommitted; + } + if (text == "CleanupPending") { + return InstallState::CleanupPending; + } + if (text == "RolledBack") { + return InstallState::RolledBack; + } + if (text == "RecoveryRequired") { + return InstallState::RecoveryRequired; + } + return std::nullopt; + } + + [[nodiscard]] std::string floor_key(std::string_view feed_id, + std::string_view channel) + { + return std::format("{}\x1f{}", feed_id, channel); + } + + struct JournalRecord { + std::string install_id{}; + InstallState state{InstallState::Verified}; + ActivationMode activation_mode{ + ActivationMode::InternalVersionStore}; + std::string component{}; + std::string channel{}; + std::string version{}; + std::string signer_key_id{}; + std::uint64_t sequence{0}; + std::string diagnostic{}; + }; + + [[nodiscard]] std::string + serialize_journal_payload(const JournalRecord& rec) + { + Json::Value::Object_t obj; + obj.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + obj.emplace_back("installId", Json::Value{rec.install_id}); + obj.emplace_back("state", Json::Value{state_to_string(rec.state)}); + obj.emplace_back( + "activationMode", + Json::Value{ + rec.activation_mode == ActivationMode::ExternalLifecycle + ? std::string{"external"} + : std::string{"internal"}}); + obj.emplace_back("component", Json::Value{rec.component}); + obj.emplace_back("channel", Json::Value{rec.channel}); + obj.emplace_back("version", Json::Value{rec.version}); + obj.emplace_back("signerKeyId", Json::Value{rec.signer_key_id}); + obj.emplace_back( + "sequence", Json::Value{static_cast(rec.sequence)}); + obj.emplace_back("diagnostic", Json::Value{rec.diagnostic}); + return Json::serialize(Json::Value{std::move(obj)}); + } + + [[nodiscard]] Void::Result::Result + write_operation_journal(const std::filesystem::path& path, + const JournalRecord& rec) + { + const std::string payload = serialize_journal_payload(rec); + const std::string checksum = sha256_hex(payload); + if (checksum.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "Update: failed to checksum operation journal")}; + } + Json::Value::Object_t wrapper; + wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + wrapper.emplace_back("sha256", Json::Value{checksum}); + wrapper.emplace_back("payload", Json::Value{payload}); + const std::string serialized = + Json::serialize(Json::Value{std::move(wrapper)}); + auto res = Void::FileSystem::replace_file( + path, serialized, + Void::FileSystem::ReplaceOptions{ + .durability = + Void::FileSystem::ReplaceDurability::durable_sync, + .mode = 0600}); + if (!res.has_value()) { + return std::unexpected{make_update_error( + res.error().durability_unknown + ? UpdateErrorCode::unknown_outcome + : UpdateErrorCode::io_error, + std::format("Update: write operation journal failed: {}", + res.error().error.message()))}; + } + return {}; + } + + [[nodiscard]] Void::Result::Result> + read_operation_journal(const std::filesystem::path& path) + { + std::error_code ec; + if (!std::filesystem::exists(path, ec)) { + if (ec) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("Update: inspect journal failed: {}", + ec.message()), + ec)}; + } + return std::optional{std::nullopt}; + } + + auto content = Void::FileSystem::read_file_bounded( + path, Void::FileSystem::ReadFileOptions{.max_bytes = 256 * 1024}); + if (!content.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("Update: unreadable operation journal: {}", + content.error().message()))}; + } + + auto wrapper = Json::parse(*content); + if (!wrapper.has_value() || !wrapper->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal is not valid JSON")}; + } + const auto* ver = wrapper->find("schemaVersion"); + const auto* sha = wrapper->find("sha256"); + const auto* pay = wrapper->find("payload"); + if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || + !sha || !sha->is_string() || !pay || !pay->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal has unknown schema or missing " + "checksum")}; + } + const std::string actual_sha = sha256_hex(pay->as_string()); + if (actual_sha != sha->as_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal checksum mismatch")}; + } + + auto doc = Json::parse(pay->as_string()); + if (!doc.has_value() || !doc->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal payload is corrupt")}; + } + const auto* state_val = doc->find("state"); + const auto* id_val = doc->find("installId"); + const auto* ver_val = doc->find("version"); + if (!state_val || !state_val->is_string() || !id_val || + !id_val->is_string() || !ver_val || !ver_val->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: operation journal missing required fields")}; + } + const auto parsed_state = parse_state(state_val->as_string()); + if (!parsed_state.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "Update: unknown state in operation journal")}; + } + + JournalRecord rec; + rec.install_id = id_val->as_string(); + rec.state = *parsed_state; + if (const auto* m = doc->find("activationMode"); + m && m->is_string() && m->as_string() == "external") { + rec.activation_mode = ActivationMode::ExternalLifecycle; + } + if (const auto* c = doc->find("component"); c && c->is_string()) { + rec.component = c->as_string(); + } + if (const auto* ch = doc->find("channel"); ch && ch->is_string()) { + rec.channel = ch->as_string(); + } + rec.version = ver_val->as_string(); + if (const auto* k = doc->find("signerKeyId"); k && k->is_string()) { + rec.signer_key_id = k->as_string(); + } + if (const auto* s = doc->find("sequence"); s && s->is_number()) { + rec.sequence = s->get_uint().value_or(0); + } + if (const auto* d = doc->find("diagnostic"); d && d->is_string()) { + rec.diagnostic = d->as_string(); + } + return std::optional{std::move(rec)}; + } + + void remove_journal_best_effort(const std::filesystem::path& path) + { + std::error_code ec; + (void)std::filesystem::remove(path, ec); + } + } // namespace + + // ── ReplayFloorStore ───────────────────────────────────────────────────── + + ReplayFloorStore::ReplayFloorStore(std::filesystem::path file_path) + : m_path(std::move(file_path)) + { + } + + Void::Result::Result ReplayFloorStore::load() + { + std::lock_guard lk{m_mu}; + std::error_code ec; + if (!std::filesystem::exists(m_path, ec)) { + if (ec) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("ReplayFloorStore: inspect failed: {}", + ec.message()), + ec)}; + } + m_floors.clear(); + m_loaded = true; + return {}; + } + + auto text = Void::FileSystem::read_file_bounded( + m_path, Void::FileSystem::ReadFileOptions{.max_bytes = 1024 * 1024}); + if (!text.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("ReplayFloorStore: cannot read floor file: {}", + text.error().message()))}; + } + + auto wrapper = Json::parse(*text); + if (!wrapper.has_value() || !wrapper->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: corrupt floor file JSON")}; + } + const auto* ver = wrapper->find("schemaVersion"); + const auto* sha = wrapper->find("sha256"); + const auto* pay = wrapper->find("payload"); + if (!ver || !ver->is_number() || ver->get_int().value_or(0) != 1 || + !sha || !sha->is_string() || !pay || !pay->is_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: unknown schema or missing checksum")}; + } + if (sha256_hex(pay->as_string()) != sha->as_string()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: floor file checksum mismatch")}; + } + + auto doc = Json::parse(pay->as_string()); + if (!doc.has_value() || !doc->is_object()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: floor payload is not an object")}; + } + + std::map> loaded; + for (const auto& [k, v] : doc->as_object()) { + auto seq = v.get_uint(); + if (!seq.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "ReplayFloorStore: invalid sequence value")}; + } + loaded.emplace(k, *seq); + } + m_floors = std::move(loaded); + m_loaded = true; + return {}; + } + + std::optional + ReplayFloorStore::floor(std::string_view feed_id, + std::string_view channel) const + { + std::lock_guard lk{m_mu}; + const std::string key = floor_key(feed_id, channel); + auto it = m_floors.find(key); + if (it == m_floors.end()) { + return std::nullopt; + } + return it->second; + } + + Void::Result::Result + ReplayFloorStore::advance(std::string_view feed_id, + std::string_view channel, + std::uint64_t sequence, + bool require_strictly_greater) + { + if (feed_id.empty() || channel.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "ReplayFloorStore: feed_id and channel are required")}; + } + { + std::lock_guard lk{m_mu}; + if (!m_loaded) { + // Load before mutating to never clobber an existing persisted + // floor. + } + } + if (!m_loaded) { + if (auto ld = load(); !ld.has_value()) { + return ld; + } + } + + std::lock_guard lk{m_mu}; + const std::string key = floor_key(feed_id, channel); + auto it = m_floors.find(key); + if (it != m_floors.end()) { + if (sequence < it->second || + (require_strictly_greater && sequence == it->second)) { + return std::unexpected{make_update_error( + UpdateErrorCode::replay_rejected, + std::format("ReplayFloorStore: sequence {} rejected below " + "floor {}", + sequence, it->second))}; + } + if (sequence == it->second) { + return {}; + } + } + + auto next_map = m_floors; + next_map[key] = sequence; + + Json::Value::Object_t payload_obj; + for (const auto& [k, v] : next_map) { + payload_obj.emplace_back(k, Json::Value{v}); + } + const std::string payload = + Json::serialize(Json::Value{std::move(payload_obj)}); + const std::string checksum = sha256_hex(payload); + + Json::Value::Object_t wrapper; + wrapper.emplace_back("schemaVersion", Json::Value{std::int64_t{1}}); + wrapper.emplace_back("sha256", Json::Value{checksum}); + wrapper.emplace_back("payload", Json::Value{payload}); + const std::string serialized = + Json::serialize(Json::Value{std::move(wrapper)}); + + if (m_path.has_parent_path()) { + std::error_code ec; + std::filesystem::create_directories(m_path.parent_path(), ec); + } + auto written = Void::FileSystem::replace_file( + m_path, serialized, + Void::FileSystem::ReplaceOptions{ + .durability = Void::FileSystem::ReplaceDurability::durable_sync, + .mode = 0600}); + if (!written.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + std::format("ReplayFloorStore: persist failed: {}", + written.error().error.message()))}; + } + m_floors = std::move(next_map); + return {}; + } + + // ── TrustStore ─────────────────────────────────────────────────────────── + + std::string + TrustStore::rotation_statement(std::string_view new_key_id, + const Ed25519PublicKey& new_public_key) + { + return std::format("VOID_TRUST_ROTATE_V1:{}:{}", new_key_id, + Encoding::Hex::encode(new_public_key)); + } + + Void::Result::Result TrustStore::bootstrap(Keyring keys) + { + if (keys.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore::bootstrap: at least one trust key is required")}; + } + std::lock_guard lk{m_mu}; + m_active = std::move(keys); + return {}; + } + + Void::Result::Result TrustStore::rotate_key_authenticated( + std::string new_key_id, const Ed25519PublicKey& new_public_key, + std::span signature, + std::string_view authorizing_key_id) + { + if (new_key_id.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore: new_key_id must be non-empty")}; + } + std::lock_guard lk{m_mu}; + if (m_revoked.contains(new_key_id)) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: cannot re-admit revoked key_id")}; + } + auto auth_it = m_active.find(std::string{authorizing_key_id}); + if (auth_it == m_active.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: authorizing key is not active")}; + } + const std::string stmt = rotation_statement(new_key_id, new_public_key); + auto ok = Crypto::verifyEd25519( + std::as_bytes(std::span{stmt.data(), stmt.size()}), signature, + auth_it->second); + if (!ok.has_value() || !*ok) { + return std::unexpected{make_update_error( + UpdateErrorCode::signature_failed, + "TrustStore: authenticated key rotation signature failed")}; + } + m_active[std::move(new_key_id)] = new_public_key; + return {}; + } + + Void::Result::Result + TrustStore::rotate_key_operator(std::string new_key_id, + const Ed25519PublicKey& new_public_key) + { + if (new_key_id.empty()) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "TrustStore: new_key_id must be non-empty")}; + } + std::lock_guard lk{m_mu}; + if (m_revoked.contains(new_key_id)) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: cannot re-admit revoked key_id")}; + } + m_active[std::move(new_key_id)] = new_public_key; + return {}; + } + + Void::Result::Result TrustStore::revoke_key(std::string_view key_id) + { + std::lock_guard lk{m_mu}; + auto it = m_active.find(std::string{key_id}); + if (it == m_active.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::untrusted_key, + "TrustStore: key_id not found in active keyring")}; + } + m_active.erase(it); + m_revoked.emplace(key_id); + return {}; + } + + Keyring TrustStore::snapshot() const + { + std::lock_guard lk{m_mu}; + return m_active; + } + + bool TrustStore::is_revoked(std::string_view key_id) const + { + std::lock_guard lk{m_mu}; + return m_revoked.contains(key_id); + } + + // ── LocalFileArtifactTransport ─────────────────────────────────────────── + + void LocalFileArtifactTransport::map_url(std::string url, + std::filesystem::path file_path, + std::string validator) + { + std::lock_guard lk{m_mu}; + m_entries[std::move(url)] = + Entry{.path = std::move(file_path), + .validator = std::move(validator)}; + } + + void LocalFileArtifactTransport::set_fail_next(bool fail) noexcept + { + std::lock_guard lk{m_mu}; + m_fail_next = fail; + } + + void LocalFileArtifactTransport::set_truncate_bytes( + std::optional bytes) noexcept + { + std::lock_guard lk{m_mu}; + m_truncate_bytes = bytes; + } + + Void::Result::Result LocalFileArtifactTransport::download( + const DownloadRequest& request, + const std::function< + Void::Result::Result(std::span)>& on_chunk) + { + Entry entry; + std::optional truncate_limit; + { + std::lock_guard lk{m_mu}; + if (m_fail_next) { + m_fail_next = false; + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + "LocalFileArtifactTransport: injected transport error")}; + } + auto it = m_entries.find(request.url); + if (it == m_entries.end()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + std::format("LocalFileArtifactTransport: unknown URL '{}'", + request.url))}; + } + entry = it->second; + truncate_limit = m_truncate_bytes; + } + + std::ifstream in{entry.path, std::ios::binary}; + if (!in.is_open()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + std::format("LocalFileArtifactTransport: cannot open '{}'", + entry.path.string()))}; + } + + bool resumed = false; + if (request.resume_offset > 0 && request.resume_validator.has_value() && + *request.resume_validator == entry.validator) { + in.seekg(static_cast(request.resume_offset)); + resumed = static_cast(in); + } + + std::array buf{}; + std::size_t sent = 0; + while (in) { + if (request.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "LocalFileArtifactTransport: cancelled")}; + } + std::size_t want = buf.size(); + if (truncate_limit.has_value()) { + if (sent >= *truncate_limit) { + break; + } + want = std::min(want, *truncate_limit - sent); + } + in.read(reinterpret_cast(buf.data()), + static_cast(want)); + const auto n = static_cast(in.gcount()); + if (n > 0) { + if (auto cb = on_chunk(std::span{buf.data(), n}); + !cb.has_value()) { + return std::unexpected{std::move(cb.error())}; + } + sent += n; + } + } + if (in.bad()) { + return std::unexpected{make_update_error( + UpdateErrorCode::transport_error, + "LocalFileArtifactTransport: I/O error reading artifact")}; + } + return DownloadMetadata{.validator = entry.validator, + .resumed = resumed}; + } + + // ── InstallCoordinator ─────────────────────────────────────────────────── + + InstallCoordinator::InstallCoordinator( + VersionStore& store, ReplayFloorStore& floor_store, + std::shared_ptr transport, LifecycleHooks hooks) + : m_store(store), m_floor_store(floor_store), + m_transport(std::move(transport)), m_hooks(std::move(hooks)) + { + } + + std::filesystem::path InstallCoordinator::operation_journal_path() const + { + return m_store.root() / ".update.op_journal.json"; + } + + void InstallCoordinator::shutdown() noexcept + { + std::lock_guard lk{m_state_mu}; + m_shutdown = true; + } + + bool InstallCoordinator::is_shutdown() const noexcept + { + std::lock_guard lk{m_state_mu}; + return m_shutdown; + } + + Void::Result::Result + InstallCoordinator::install(const VerifiedSelection& selection, + const InstallOptions& options) + { + if (!m_transport) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "InstallCoordinator: ArtifactTransport is required")}; + } + if (options.activation_mode == ActivationMode::ExternalLifecycle && + !m_hooks.activate_external) { + return std::unexpected{make_update_error( + UpdateErrorCode::invalid_argument, + "InstallCoordinator: ExternalLifecycle requires " + "activate_external hook")}; + } + + // Serialize one active install per store while keeping transport & + // lifecycle callbacks outside the coordinator state lock. + { + std::lock_guard lk{m_state_mu}; + if (m_shutdown) { + return std::unexpected{make_update_error( + UpdateErrorCode::closed, + "InstallCoordinator: coordinator is shut down")}; + } + if (m_active) { + return std::unexpected{make_update_error( + UpdateErrorCode::conflict, + "InstallCoordinator: another install is already active")}; + } + m_active = true; + } + struct ActiveGuard { + std::mutex& mu; + bool& active; + ~ActiveGuard() noexcept + { + std::lock_guard lk{mu}; + active = false; + } + } active_guard{m_state_mu, m_active}; + + const auto& mono_clock = + options.monotonic_clock + ? *options.monotonic_clock + : Void::Time::SystemMonotonicClock::instance(); + const auto& civil_clock = options.civil_clock + ? *options.civil_clock + : Void::Time::SystemCivilClock::instance(); + const auto deadline = mono_clock.now() + options.install_deadline; + + if (options.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "InstallCoordinator: cancelled before admission")}; + } + if (civil_clock.now() >= selection.expires_at()) { + return std::unexpected{make_update_error( + UpdateErrorCode::expired, + "InstallCoordinator: verified selection is expired")}; + } + if (selection.release().size == 0 || + selection.release().size > options.max_artifact_bytes) { + return std::unexpected{make_update_error( + UpdateErrorCode::limit_exceeded, + "InstallCoordinator: artifact size exceeds policy")}; + } + + if (auto init = m_store.initialize(); !init.has_value()) { + return std::unexpected{std::move(init.error())}; + } + + // Check whether an unrecovered journal exists before admitting new + // work. + auto existing_j = read_operation_journal(operation_journal_path()); + if (!existing_j.has_value()) { + return std::unexpected{std::move(existing_j.error())}; + } + if (existing_j->has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + "InstallCoordinator: prior operation journal present; run " + "reconcile() first")}; + } + + // Advance durable replay floor before download/install. + if (auto fl = m_floor_store.advance(selection.feed_id(), + selection.release().channel, + selection.sequence()); + !fl.has_value()) { + return std::unexpected{std::move(fl.error())}; + } + + const std::string install_id = + std::format("inst-{}-{}", static_cast(::getpid()), + g_install_seq.fetch_add(1, std::memory_order_relaxed)); + + InstallReceipt receipt{ + .install_id = install_id, + .state = InstallState::Verified, + .release = selection.release(), + .signer_key_id = selection.signer_key_id(), + }; + + auto emit_progress = [&]() { + if (m_hooks.on_progress) { + try { + m_hooks.on_progress(receipt); + } catch (...) { + } + } + }; + + auto persist_state = [&](InstallState st, + std::string diag = {}) -> Void::Result::Result { + receipt.state = st; + receipt.diagnostic = std::move(diag); + JournalRecord rec{ + .install_id = receipt.install_id, + .state = receipt.state, + .activation_mode = options.activation_mode, + .component = receipt.release.component, + .channel = receipt.release.channel, + .version = receipt.release.version.to_string(), + .signer_key_id = receipt.signer_key_id, + .sequence = receipt.release.sequence, + .diagnostic = receipt.diagnostic, + }; + auto w = write_operation_journal(operation_journal_path(), rec); + emit_progress(); + return w; + }; + + // 1. Download artifact to exclusive staging file while checking exact + // size and incremental SHA-256. + if (auto ps = persist_state(InstallState::Downloading); + !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + const auto staging_root = m_store.root() / "staging"; + const auto download_path = + staging_root / std::format(".dl-{}.tar.zst", install_id); + struct FileCleanup { + std::filesystem::path p{}; + ~FileCleanup() noexcept + { + if (!p.empty()) { + std::error_code ec; + (void)std::filesystem::remove(p, ec); + } + } + } dl_cleanup{download_path}; + + auto hasher = Crypto::Hasher::create(Crypto::HashAlgorithm::Sha256); + if (!hasher.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(hasher.error())}; + } + + int dl_fd = ::open(download_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + 0600); + if (dl_fd < 0) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + "InstallCoordinator: cannot create staging download file")}; + } + + std::uint64_t downloaded_bytes = 0; + DownloadRequest dreq{ + .url = receipt.release.url, + .expected_sha256 = receipt.release.sha256, + .expected_size = receipt.release.size, + .max_bytes = std::min(options.max_artifact_bytes, + options.staging_quota_bytes), + .stop = options.stop, + }; + + auto dl_res = m_transport->download( + dreq, + [&](std::span chunk) -> Void::Result::Result { + if (options.stop.stop_requested()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cancelled, + "InstallCoordinator: cancelled during download")}; + } + if (mono_clock.now() >= deadline) { + return std::unexpected{make_update_error( + UpdateErrorCode::timeout, + "InstallCoordinator: install deadline expired during " + "download")}; + } + const auto n = static_cast(chunk.size()); + if (n > dreq.max_bytes - downloaded_bytes || + n > receipt.release.size - downloaded_bytes) { + return std::unexpected{make_update_error( + UpdateErrorCode::size_mismatch, + "InstallCoordinator: downloaded bytes exceed declared " + "artifact size")}; + } + if (auto u = hasher->update(chunk); !u.has_value()) { + return std::unexpected{std::move(u.error())}; + } + std::size_t off = 0; + while (off < chunk.size()) { + const ssize_t w = ::write( + dl_fd, + reinterpret_cast(chunk.data()) + off, + chunk.size() - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "InstallCoordinator: write staging artifact " + "failed")}; + } + off += static_cast(w); + } + downloaded_bytes += n; + return {}; + }); + + const bool sync_ok = (::fsync(dl_fd) == 0); + (void)::close(dl_fd); + if (!dl_res.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(dl_res.error())}; + } + if (!sync_ok) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::io_error, + "InstallCoordinator: fsync staging artifact failed")}; + } + if (downloaded_bytes != receipt.release.size) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::size_mismatch, + std::format("InstallCoordinator: downloaded {} bytes != " + "expected {}", + downloaded_bytes, receipt.release.size))}; + } + auto digest = hasher->finalize(); + if (!digest.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{std::move(digest.error())}; + } + const std::string actual_sha = Encoding::Hex::encode(*digest); + if (actual_sha != receipt.release.sha256) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::digest_mismatch, + "InstallCoordinator: artifact SHA-256 mismatch")}; + } + + // 2. Safe staged extraction via Archive + atomic publication into + // VersionStore. + Archive::StagedExtractionOptions ext_opts{}; + ext_opts.limits.max_total_bytes = + std::min(ext_opts.limits.max_total_bytes, + options.staging_quota_bytes); + ext_opts.limits.max_file_bytes = + std::min(ext_opts.limits.max_file_bytes, + options.staging_quota_bytes); + ext_opts.stop = options.stop; + ext_opts.deadline = deadline; + ext_opts.clock = &mono_clock; + + Void::Result::Result staged = + options.isolated_archive_worker.has_value() + ? Archive::extract_staged_isolated( + download_path, staging_root, + Archive::IsolationOptions{ + .worker_executable = *options.isolated_archive_worker, + .timeout = options.install_deadline, + .extraction = ext_opts}) + : Archive::extract_staged(download_path, staging_root, ext_opts); + if (!staged.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: archive extraction failed: {}", + staged.error().message()))}; + } + if (auto ps = persist_state(InstallState::Staged); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // Publish staged tree as an immediate child of store/staging, then hand + // off to VersionStore::publish(). + const std::string ready_name = + std::format("{}.ready.{}", receipt.release.version.to_string(), + install_id); + auto stage_pub = staged->publish(ready_name); + if (!stage_pub.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: staging handoff failed: {}", + stage_pub.error().message()))}; + } + if (stage_pub->outcome == Archive::PublicationOutcome::Unknown) { + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, stage_pub->diagnostic)}; + } + + struct ReadyDirCleanup { + std::filesystem::path p{}; + ~ReadyDirCleanup() noexcept + { + if (!p.empty()) { + std::error_code ec; + (void)std::filesystem::remove_all(p, ec); + } + } + } ready_cleanup{stage_pub->destination_path}; + + if (auto pub = + m_store.publish(receipt.release.version, + stage_pub->destination_path); + !pub.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::staging_error, + std::format("InstallCoordinator: VersionStore::publish failed: " + "{}", + pub.error().message()))}; + } + ready_cleanup.p.clear(); // moved into versions/ + + if (auto ps = persist_state(InstallState::Published); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 3. Activation (InternalVersionStore vs ExternalLifecycle — strictly + // separate!). + const auto published_dir = m_store.versionPath(receipt.release.version); + if (options.activation_mode == ActivationMode::InternalVersionStore) { + if (auto act = m_store.activate(receipt.release.version); + !act.has_value()) { + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::activation_failed, act.error().message())}; + } + } else { + if (auto act = m_hooks.activate_external(receipt.release.version, + published_dir); + !act.has_value()) { + (void)m_store.recordFailed(receipt.release.version); + remove_journal_best_effort(operation_journal_path()); + return std::unexpected{make_update_error( + UpdateErrorCode::activation_failed, act.error().message())}; + } + } + if (auto ps = persist_state(InstallState::Activated); !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 4. Bounded cooperative health/readiness probes outside locks. + const auto readiness_deadline = + std::min(deadline, mono_clock.now() + options.readiness_timeout); + const std::size_t required_healthy = + std::max(1, options.consecutive_healthy_required); + std::size_t consecutive_ok = 0; + bool ready = false; + std::string readiness_diag; + + if (!m_hooks.health_probe) { + ready = true; + } else { + for (;;) { + if (options.stop.stop_requested()) { + readiness_diag = "cancelled before durable commit"; + break; + } + if (mono_clock.now() > readiness_deadline) { + readiness_diag = "readiness timeout expired"; + break; + } + auto probe = + m_hooks.health_probe(receipt.release.version, published_dir); + if (!probe.has_value()) { + readiness_diag = probe.error().message(); + break; + } + if (*probe) { + ++consecutive_ok; + if (consecutive_ok >= required_healthy) { + ready = true; + break; + } + } else { + consecutive_ok = 0; + } + if (mono_clock.now() >= readiness_deadline) { + readiness_diag = "candidate did not reach readiness"; + break; + } + if (!*probe && (options.monotonic_clock != nullptr || + options.health_probe_interval <= + std::chrono::milliseconds{0})) { + readiness_diag = "candidate health probe returned unhealthy"; + break; + } + if (options.health_probe_interval > + std::chrono::milliseconds{0} && + options.monotonic_clock == nullptr) { + std::this_thread::sleep_for(options.health_probe_interval); + } + } + } + + if (!ready) { + if (m_hooks.stop_candidate) { + m_hooks.stop_candidate(receipt.release.version); + } + if (options.activation_mode == + ActivationMode::InternalVersionStore) { + if (auto rb = m_store.rollback(); !rb.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + rb.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("InstallCoordinator: rollback failed: {}", + rb.error().message()))}; + } + } else { + (void)m_store.recordFailed(receipt.release.version); + } + (void)persist_state(InstallState::RolledBack, readiness_diag); + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + // 5. Durable commit via VersionStore's single commit marker. + if (options.activation_mode == ActivationMode::InternalVersionStore) { + if (auto cm = m_store.commit(); !cm.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + cm.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, + std::format("InstallCoordinator: commit outcome uncertain: " + "{}", + cm.error().message()))}; + } + } else { + if (auto rh = m_store.recordHealthy(receipt.release.version); + !rh.has_value()) { + (void)persist_state(InstallState::RecoveryRequired, + rh.error().message()); + return std::unexpected{make_update_error( + UpdateErrorCode::unknown_outcome, + std::format("InstallCoordinator: recordHealthy failed: {}", + rh.error().message()))}; + } + } + + if (auto ps = persist_state(InstallState::HealthyCommitted); + !ps.has_value()) { + return std::unexpected{std::move(ps.error())}; + } + + // 6. Post-commit cleanup/pruning: failures become CleanupPending and + // NEVER trigger rollback of the committed version. + std::vector pins; + if (m_hooks.live_pinned_versions) { + pins = m_hooks.live_pinned_versions(); + } + std::string cleanup_diag; + if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, + pins, options.prune_batch_limit); + !pr.has_value()) { + cleanup_diag = pr.error().message(); + } else if (m_hooks.post_commit_cleanup_hook) { + if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { + cleanup_diag = hk.error().message(); + } + } + + if (!cleanup_diag.empty()) { + receipt.cleanup_retryable = true; + (void)persist_state(InstallState::CleanupPending, cleanup_diag); + return receipt; + } + + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + Void::Result::Result InstallCoordinator::reconcile() + { + auto journal = read_operation_journal(operation_journal_path()); + if (!journal.has_value()) { + return std::unexpected{std::move(journal.error())}; + } + + if (auto rec = m_store.reconcile(); !rec.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, + std::format("InstallCoordinator::reconcile: VersionStore " + "reconcile failed: {}", + rec.error().message()))}; + } + + auto current = m_store.currentVersion(); + if (!current.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::recovery_required, current.error().message())}; + } + + InstallReceipt receipt{}; + if (!journal->has_value()) { + receipt.state = InstallState::HealthyCommitted; + if (current->has_value()) { + receipt.release.version = **current; + } + return receipt; + } + + const auto& j = **journal; + receipt.install_id = j.install_id; + receipt.signer_key_id = j.signer_key_id; + receipt.release.component = j.component; + receipt.release.channel = j.channel; + receipt.release.sequence = j.sequence; + if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { + receipt.release.version = *pv; + } + + if (j.state == InstallState::RecoveryRequired) { + receipt.state = InstallState::RecoveryRequired; + receipt.diagnostic = j.diagnostic; + return receipt; + } + if (j.state == InstallState::CleanupPending) { + receipt.state = InstallState::CleanupPending; + receipt.diagnostic = j.diagnostic; + receipt.cleanup_retryable = true; + return receipt; + } + + // Determine outcome from VersionStore's authoritative durable evidence. + auto healthy = m_store.healthyPublishedVersions(); + bool candidate_healthy = false; + if (healthy.has_value()) { + for (const auto& hv : *healthy) { + if (hv.to_string() == j.version) { + candidate_healthy = true; + break; + } + } + } + + const bool is_current = + current->has_value() && (*current)->to_string() == j.version; + if (candidate_healthy && + (is_current || + j.activation_mode == ActivationMode::ExternalLifecycle)) { + receipt.state = InstallState::HealthyCommitted; + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + // Candidate was not committed; VersionStore::reconcile() restored the + // previous version if activation had started. + receipt.state = InstallState::RolledBack; + receipt.diagnostic = "reconciled uncommitted operation"; + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + + Void::Result::Result + InstallCoordinator::retry_cleanup(const InstallOptions& options) + { + auto journal = read_operation_journal(operation_journal_path()); + if (!journal.has_value()) { + return std::unexpected{std::move(journal.error())}; + } + if (!journal->has_value()) { + return InstallReceipt{.state = InstallState::HealthyCommitted}; + } + const auto& j = **journal; + if (j.state != InstallState::CleanupPending && + j.state != InstallState::HealthyCommitted) { + return std::unexpected{make_update_error( + UpdateErrorCode::conflict, + "InstallCoordinator::retry_cleanup: journal is not in " + "CleanupPending state")}; + } + + std::vector pins; + if (m_hooks.live_pinned_versions) { + pins = m_hooks.live_pinned_versions(); + } + if (auto pr = m_store.pruneWithPins(options.retained_previous_versions, + pins, options.prune_batch_limit); + !pr.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cleanup_pending, pr.error().message())}; + } + if (m_hooks.post_commit_cleanup_hook) { + if (auto hk = m_hooks.post_commit_cleanup_hook(); !hk.has_value()) { + return std::unexpected{make_update_error( + UpdateErrorCode::cleanup_pending, hk.error().message())}; + } + } + + InstallReceipt receipt{ + .install_id = j.install_id, + .state = InstallState::HealthyCommitted, + .signer_key_id = j.signer_key_id, + .cleanup_retryable = false, + }; + if (auto pv = Semver::parse_strict(j.version); pv.has_value()) { + receipt.release.version = *pv; + } + remove_journal_best_effort(operation_journal_path()); + return receipt; + } + +} // namespace Void::Update diff --git a/src/Update/VersionStore.cpp b/src/Update/VersionStore.cpp index fe67952..836349d 100644 --- a/src/Update/VersionStore.cpp +++ b/src/Update/VersionStore.cpp @@ -1721,6 +1721,124 @@ namespace Void::Update return removed; } + Void::Result::Result + VersionStore::pruneWithPins(std::size_t retainedPreviousVersions, + std::span + pinnedVersions, + std::size_t batchLimit) + { + if (batchLimit == 0) { + return Void::Result::fail( + "VersionStore::pruneWithPins: batchLimit must be positive"); + } + for (const auto& path : {m_root, m_root / "versions"}) { + if (auto checked = require_real_directory(path); !checked) { + return std::unexpected{checked.error()}; + } + } + auto lock = FileLock::acquire(m_root / ".update.lock"); + if (!lock) { + return std::unexpected{lock.error()}; + } + if (auto cleaned = cleanup_pruning_entries(m_root / "versions"); + !cleaned) { + return std::unexpected{cleaned.error()}; + } + + auto current = currentVersion(); + if (!current) { + return std::unexpected{current.error()}; + } + auto pending = pendingActivation(); + if (!pending) { + return std::unexpected{pending.error()}; + } + auto history = read_health_history(m_root); + if (!history) { + return std::unexpected{history.error()}; + } + auto published = published_versions(m_root / "versions"); + if (!published) { + return std::unexpected{published.error()}; + } + + std::sort(published->begin(), published->end(), + std::greater{}); + std::set> publishedNames; + for (const auto& version : *published) { + publishedNames.insert(version.to_string()); + } + + std::set> retained; + std::optional currentName; + if (*current) { + currentName = (**current).to_string(); + retained.insert(*currentName); + } + if (*pending) { + retained.insert((*pending)->candidateVersion.to_string()); + if ((*pending)->previousVersion) { + retained.insert((*pending)->previousVersion->to_string()); + } + } + + std::size_t retainedPrevious = 0; + for (auto iterator = history->committedOrder.rbegin(); + iterator != history->committedOrder.rend() && + retainedPrevious < retainedPreviousVersions; + ++iterator) { + const auto state = history->states.find(*iterator); + if (publishedNames.contains(*iterator) && + state != history->states.end() && + state->second == HealthState::healthy && + (!currentName || *iterator != *currentName) && + !retained.contains(*iterator)) { + retained.insert(*iterator); + ++retainedPrevious; + } + } + + std::set> pinnedNames; + for (const auto& v : pinnedVersions) { + pinnedNames.insert(v.to_string()); + } + + PruneReport report; + for (const auto& version : *published) { + const auto name = version.to_string(); + if (retained.contains(name)) { + continue; + } + const auto state = history->states.find(name); + if (state == history->states.end() || + (state->second != HealthState::healthy && + state->second != HealthState::failed && + state->second != HealthState::retired)) { + continue; + } + if (pinnedNames.contains(name)) { + report.skipped_due_to_pins.push_back(version); + continue; + } + if (report.removed.size() >= batchLimit) { + report.batch_limit_reached = true; + break; + } + if (state->second != HealthState::retired) { + if (auto recorded = append_health_event(m_root, 'D', name); + !recorded) { + return std::unexpected{recorded.error()}; + } + } + if (auto pruned = quarantine_and_remove(m_root / "versions", name); + !pruned) { + return std::unexpected{pruned.error()}; + } + report.removed.push_back(version); + } + return report; + } + Void::Result::Result> VersionStore::currentVersion() const { diff --git a/src/Update/module.cmake b/src/Update/module.cmake index 0fac0c3..183c9ce 100644 --- a/src/Update/module.cmake +++ b/src/Update/module.cmake @@ -1,3 +1,3 @@ void_add_module(Update - INTERNAL_DEPS Crypto Data Functional System Text + INTERNAL_DEPS Archive Crypto Data Functional System Text Time ) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1f5520e..8d6e724 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -170,6 +170,20 @@ if(TARGET VoidTests AND (TARGET Void::System OR TARGET Void::IPC)) add_dependencies(VoidTests VoidProcessHelper) endif() +if(TARGET VoidTests AND TARGET Void::Archive) + add_executable(VoidArchiveWorker + "${CMAKE_CURRENT_SOURCE_DIR}/helpers/ArchiveWorker.cpp") + target_link_libraries(VoidArchiveWorker PRIVATE Void::Archive) + set_target_properties(VoidArchiveWorker PROPERTIES + CXX_STANDARD 26 + CXX_STANDARD_REQUIRED ON + CXX_EXTENSIONS OFF + VOID_TESTING_NO_AUTO_SCAN TRUE) + target_compile_definitions(VoidTests PRIVATE + "VOID_ARCHIVE_WORKER_PATH=\"$\"") + add_dependencies(VoidTests VoidArchiveWorker) +endif() + if(TARGET VoidTests AND TARGET Void::Plugin) set(_test_plugin_src "${CMAKE_CURRENT_SOURCE_DIR}/plugins/TestPlugin.cpp") if(EXISTS "${_test_plugin_src}") diff --git a/tests/helpers/ArchiveWorker.cpp b/tests/helpers/ArchiveWorker.cpp new file mode 100644 index 0000000..bd1d613 --- /dev/null +++ b/tests/helpers/ArchiveWorker.cpp @@ -0,0 +1,6 @@ +#include + +int main(int argc, char** argv) +{ + return Void::Archive::run_isolated_worker_main(argc, argv); +} diff --git a/tests/package/ArchiveOnly/CMakeLists.txt b/tests/package/ArchiveOnly/CMakeLists.txt new file mode 100644 index 0000000..f21c093 --- /dev/null +++ b/tests/package/ArchiveOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidArchiveOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Archive) + +add_executable(void_archive_only_consumer main.cpp) +target_link_libraries(void_archive_only_consumer PRIVATE Void::Archive) +target_compile_features(void_archive_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME ArchiveOnlyConsumer COMMAND void_archive_only_consumer) diff --git a/tests/package/ArchiveOnly/main.cpp b/tests/package/ArchiveOnly/main.cpp new file mode 100644 index 0000000..ef36ad9 --- /dev/null +++ b/tests/package/ArchiveOnly/main.cpp @@ -0,0 +1,26 @@ +#include + +#include +#include + +int main() +{ + const std::array entries{{ + Void::Archive::CreateEntry{ + .path = "hello.txt", + .type = Void::Archive::EntryType::RegularFile, + .content = {std::byte{'h'}, std::byte{'i'}}, + }, + }}; + Void::Archive::VectorByteSink sink; + if (!Void::Archive::create_archive(sink, entries).has_value()) { + return 1; + } + Void::Archive::SpanByteSource src{sink.bytes()}; + auto listed = Void::Archive::list_entries(src); + if (!listed.has_value() || listed->size() != 1U || + (*listed)[0].path != "hello.txt") { + return 2; + } + return 0; +} diff --git a/tests/package/CryptoAsyncOnly/CMakeLists.txt b/tests/package/CryptoAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..8b3a7ea --- /dev/null +++ b/tests/package/CryptoAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidCryptoAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS CryptoAsync) + +add_executable(void_crypto_async_only_consumer main.cpp) +target_link_libraries(void_crypto_async_only_consumer PRIVATE Void::CryptoAsync) +target_compile_features(void_crypto_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME CryptoAsyncOnlyConsumer COMMAND void_crypto_async_only_consumer) diff --git a/tests/package/CryptoAsyncOnly/main.cpp b/tests/package/CryptoAsyncOnly/main.cpp new file mode 100644 index 0000000..c692e7f --- /dev/null +++ b/tests/package/CryptoAsyncOnly/main.cpp @@ -0,0 +1,19 @@ +#include +#include +#include + +int main() +{ + Void::Async::ManualExecutor exec; + auto drv = Void::IO::Driver::create(exec); + if (!drv.has_value()) { + return 1; + } + Void::CryptoAsync::AsyncFileHasher hasher{exec}; + if (hasher.stats().active != 0) { + return 2; + } + (void)hasher.close_and_join(); + (void)(*drv)->shutdown_and_join(); + return 0; +} diff --git a/tests/package/CryptoOnly/CMakeLists.txt b/tests/package/CryptoOnly/CMakeLists.txt new file mode 100644 index 0000000..b8db969 --- /dev/null +++ b/tests/package/CryptoOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidCryptoOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Crypto) + +add_executable(void_crypto_only_consumer main.cpp) +target_link_libraries(void_crypto_only_consumer PRIVATE Void::Crypto) +target_compile_features(void_crypto_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME CryptoOnlyConsumer COMMAND void_crypto_only_consumer) diff --git a/tests/package/CryptoOnly/main.cpp b/tests/package/CryptoOnly/main.cpp new file mode 100644 index 0000000..97b2726 --- /dev/null +++ b/tests/package/CryptoOnly/main.cpp @@ -0,0 +1,31 @@ +#include + +#include +#include + +int main() +{ + auto digest = Void::Crypto::sha256("abc"); + if (!digest.has_value() || digest->size() != 32) { + return 1; + } + auto key = Void::Crypto::Ed25519PrivateKey::generate(); + if (!key.has_value()) { + return 2; + } + auto pub = key->public_key(); + if (!pub.has_value()) { + return 3; + } + const std::array msg{std::byte{1}, std::byte{2}, std::byte{3}, + std::byte{4}}; + auto sig = Void::Crypto::sign_ed25519(msg, *key); + if (!sig.has_value()) { + return 4; + } + auto ok = Void::Crypto::verify_ed25519(msg, *sig, *pub); + if (!ok.has_value() || !*ok) { + return 5; + } + return 0; +} diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 71012e5..dc26c00 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -161,6 +161,59 @@ if(_has_log) run_consumer(LogOnly "${install_prefix}" "LogOnly" ${_no_external_deps}) endif() +has_modules(_has_crypto Crypto Functional) +if(_has_crypto) + run_consumer(CryptoOnly "${install_prefix}" "CryptoOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_crypto_async CryptoAsync Crypto IO Async Time Functional) +if(_has_crypto_async) + run_consumer(CryptoAsyncOnly "${install_prefix}" "CryptoAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_security Security Time Functional) +if(_has_security) + run_consumer(SecurityOnly "${install_prefix}" "SecurityOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_security_async SecurityAsync Security Async Time Resilience Functional) +if(_has_security_async) + run_consumer(SecurityAsyncOnly "${install_prefix}" "SecurityAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_archive Archive System Time Functional) +if(_has_archive) + run_consumer(ArchiveOnly "${install_prefix}" "ArchiveOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + +has_modules(_has_update Update Archive Crypto Data Functional System Text Time) +if(_has_update) + run_consumer(UpdateOnly "${install_prefix}" "UpdateOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/SecurityAsyncOnly/CMakeLists.txt b/tests/package/SecurityAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..58ef598 --- /dev/null +++ b/tests/package/SecurityAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSecurityAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS SecurityAsync) + +add_executable(void_security_async_only_consumer main.cpp) +target_link_libraries(void_security_async_only_consumer PRIVATE Void::SecurityAsync) +target_compile_features(void_security_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SecurityAsyncOnlyConsumer COMMAND void_security_async_only_consumer) diff --git a/tests/package/SecurityAsyncOnly/main.cpp b/tests/package/SecurityAsyncOnly/main.cpp new file mode 100644 index 0000000..fb0f323 --- /dev/null +++ b/tests/package/SecurityAsyncOnly/main.cpp @@ -0,0 +1,21 @@ +#include +#include + +#include + +int main() +{ + auto store = std::make_shared(); + Void::Async::ManualExecutor exec; + Void::SecurityAsync::AuthenticatorOptions opts{}; + opts.dummy_hash_strength = Void::Security::PasswordHashStrength::Interactive; + auto auth = Void::SecurityAsync::Authenticator::create(store, exec, opts); + if (!auth.has_value()) { + return 1; + } + if ((*auth)->stats().active_password_jobs != 0) { + return 2; + } + (void)(*auth)->close_and_join(); + return 0; +} diff --git a/tests/package/SecurityOnly/CMakeLists.txt b/tests/package/SecurityOnly/CMakeLists.txt new file mode 100644 index 0000000..157cfcd --- /dev/null +++ b/tests/package/SecurityOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSecurityOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Security) + +add_executable(void_security_only_consumer main.cpp) +target_link_libraries(void_security_only_consumer PRIVATE Void::Security) +target_compile_features(void_security_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SecurityOnlyConsumer COMMAND void_security_only_consumer) diff --git a/tests/package/SecurityOnly/main.cpp b/tests/package/SecurityOnly/main.cpp new file mode 100644 index 0000000..08304b3 --- /dev/null +++ b/tests/package/SecurityOnly/main.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +#include + +#include + +int main() +{ + Void::Security::SecretKeyRing ring; + if (!ring.generate_and_add_key("v1", true).has_value()) { + return 1; + } + const std::vector pt{'o', 'k'}; + auto env = ring.seal(pt); + if (!env.has_value()) { + return 2; + } + auto dec = ring.open(*env); + if (!dec.has_value() || dec->size() != pt.size()) { + return 3; + } + auto policy = Void::Security::PolicySnapshot::create(1, {}); + if (!policy.has_value()) { + return 4; + } + const Void::Security::Principal p{.subject = "u1"}; + const Void::Security::ResourceAttributes r{.resource_type = "doc"}; + if (policy->authorize(p, "read", r).allowed) { + return 5; + } + return 0; +} diff --git a/tests/package/UpdateOnly/CMakeLists.txt b/tests/package/UpdateOnly/CMakeLists.txt new file mode 100644 index 0000000..56102e7 --- /dev/null +++ b/tests/package/UpdateOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidUpdateOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Update) + +add_executable(void_update_only_consumer main.cpp) +target_link_libraries(void_update_only_consumer PRIVATE Void::Update) +target_compile_features(void_update_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME UpdateOnlyConsumer COMMAND void_update_only_consumer) diff --git a/tests/package/UpdateOnly/main.cpp b/tests/package/UpdateOnly/main.cpp new file mode 100644 index 0000000..d8657a2 --- /dev/null +++ b/tests/package/UpdateOnly/main.cpp @@ -0,0 +1,22 @@ +#include +#include + +int main() +{ + auto k = Void::Crypto::Ed25519PrivateKey::generate(); + if (!k.has_value()) { + return 1; + } + auto pub = k->public_key(); + if (!pub.has_value()) { + return 2; + } + Void::Update::TrustStore trust; + if (!trust.bootstrap({{"k1", pub->bytes}}).has_value()) { + return 3; + } + if (!trust.snapshot().contains("k1")) { + return 4; + } + return 0; +} diff --git a/tests/standalone/Archive/ArchiveHardening.cpp b/tests/standalone/Archive/ArchiveHardening.cpp new file mode 100644 index 0000000..9c2754a --- /dev/null +++ b/tests/standalone/Archive/ArchiveHardening.cpp @@ -0,0 +1,392 @@ +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Archive; + + std::vector to_bytes(std::string_view s) + { + std::vector out(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(static_cast(s[i])); + } + return out; + } + + std::string read_file_str(const std::filesystem::path& p) + { + std::ifstream in{p, std::ios::binary}; + Void::Testing::require(in.is_open()); + return std::string{std::istreambuf_iterator{in}, + std::istreambuf_iterator{}}; + } + + std::vector make_raw_tar( + std::span> + entries) + { + using W = std::unique_ptr; + using E = + std::unique_ptr; + std::vector out; + W writer{archive_write_new(), &archive_write_free}; + Void::Testing::require(static_cast(writer)); + Void::Testing::require(archive_write_add_filter_zstd(writer.get()) == + ARCHIVE_OK); + Void::Testing::require(archive_write_set_format_pax_restricted( + writer.get()) == ARCHIVE_OK); + Void::Testing::require( + archive_write_set_bytes_in_last_block(writer.get(), 1) == + ARCHIVE_OK); + auto cb = [](archive*, void* data, const void* buf, + std::size_t len) -> la_ssize_t { + auto* vec = static_cast*>(data); + const auto* p = static_cast(buf); + vec->insert(vec->end(), p, p + len); + return static_cast(len); + }; + Void::Testing::require(archive_write_open2(writer.get(), &out, nullptr, + cb, nullptr, nullptr) == + ARCHIVE_OK); + for (const auto& [path, content, type, link] : entries) { + E ae{archive_entry_new(), &archive_entry_free}; + const std::string p{path}; + archive_entry_set_pathname(ae.get(), p.c_str()); + archive_entry_set_filetype(ae.get(), type); + archive_entry_set_perm(ae.get(), type == AE_IFDIR ? 0755 : 0644); + if (type == AE_IFREG) { + archive_entry_set_size(ae.get(), + static_cast(content.size())); + } + if (!link.empty()) { + const std::string l{link}; + archive_entry_set_symlink(ae.get(), l.c_str()); + } + Void::Testing::require(archive_write_header(writer.get(), ae.get()) == + ARCHIVE_OK); + if (!content.empty()) { + Void::Testing::require( + archive_write_data(writer.get(), content.data(), + content.size()) == + static_cast(content.size())); + } + Void::Testing::require(archive_write_finish_entry(writer.get()) == + ARCHIVE_OK); + } + Void::Testing::require(archive_write_close(writer.get()) == ARCHIVE_OK); + return out; + } +} // namespace + +Void::Testing::Test archive_reader_reproducible_skip_and_forensic_listing() +{ + // 1. Reproducible creation produces identical bytes regardless of entry + // ordering. + const std::array order_a{{ + CreateEntry{.path = "bin/run", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("#!/bin/sh\necho hi\n")}, + CreateEntry{.path = "docs/readme.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("hello archive")}, + CreateEntry{.path = "bin/", .type = EntryType::Directory}, + }}; + const std::array order_b{order_a[2], order_a[1], order_a[0]}; + + VectorByteSink sink_a; + VectorByteSink sink_b; + CreationOptions copts{.compression = ArchiveCompression::Zstd, + .reproducible = true}; + Void::Testing::require(create_archive(sink_a, order_a, copts).has_value()); + Void::Testing::require(create_archive(sink_b, order_b, copts).has_value()); + Void::Testing::expect_eq(sink_a.bytes(), sink_b.bytes()); + + // 2. Caller-driven Reader enforces drain/skip before next_entry and + // accounts skipped decompressed bytes against max_total_bytes. + { + SpanByteSource src{sink_a.bytes()}; + auto reader = Reader::open(src); + Void::Testing::require(reader.has_value()); + + auto e1 = reader->next_entry(); + Void::Testing::require(e1.has_value() && e1->has_value()); + Void::Testing::expect_eq((*e1)->path, std::string{"bin"}); + Void::Testing::expect_eq(static_cast((*e1)->type), + static_cast(EntryType::Directory)); + + auto e2 = reader->next_entry(); + Void::Testing::require(e2.has_value() && e2->has_value()); + Void::Testing::expect_eq((*e2)->path, std::string{"bin/run"}); + Void::Testing::expect((*e2)->executable); + + // Calling next_entry before draining/skipping active file fails. + auto premature = reader->next_entry(); + Void::Testing::require(!premature.has_value()); + } + + // Skip accounting catches total limit even when caller skips data! + { + SpanByteSource src{sink_a.bytes()}; + ReadLimits tight{}; + tight.max_total_bytes = 20; // bin/run (18B) + readme (13B) = 31B > 20B + auto reader = Reader::open(src, tight); + Void::Testing::require(reader.has_value()); + Void::Testing::require(reader->next_entry().has_value()); // bin/ + Void::Testing::require(reader->next_entry().has_value()); // bin/run + auto skipped = reader->skip_entry(); + Void::Testing::require(skipped.has_value()); + Void::Testing::expect_eq(*skipped, 18ULL); + auto e3 = reader->next_entry(); // docs/readme.txt declared 13B > 2B rem + Void::Testing::require(!e3.has_value()); + Void::Testing::expect_eq( + e3.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); + } + + // 3. Zero limits rejected unless allow_zero_entries is explicitly set. + { + ReadLimits zero_entries{}; + zero_entries.max_entries = 0; + Void::Testing::expect(!zero_entries.validate().has_value()); + zero_entries.allow_zero_entries = true; + Void::Testing::expect(zero_entries.validate().has_value()); + } + + // 4. File-as-parent conflict rejected cleanly (both orderings). + { + const std::array< + std::tuple, + 2> + conflict_entries{{ + {"foo", "file-bytes", AE_IFREG, ""}, + {"foo/child", "nested", AE_IFREG, ""}, + }}; + const auto raw = make_raw_tar(conflict_entries); + SpanByteSource src{raw}; + auto listed = list_entries(src, {}, false); + Void::Testing::require(!listed.has_value()); + Void::Testing::expect_eq( + listed.error().code().value, + static_cast(ArchiveErrorCode::unsafe_entry)); + } + + // 5. Normal vs forensic listing + sanitized diagnostics. + { + const std::array< + std::tuple, + 3> + mixed{{ + {"safe.txt", "ok", AE_IFREG, ""}, + {"bad\nlink", "", AE_IFLNK, "/etc/passwd"}, + {"../escape", "nope", AE_IFREG, ""}, + }}; + const auto raw = make_raw_tar(mixed); + + SpanByteSource src1{raw}; + Void::Testing::expect(!list_entries(src1, {}, false).has_value()); + + SpanByteSource src2{raw}; + auto forensic = list_entries(src2, {}, true); + Void::Testing::require(forensic.has_value()); + Void::Testing::expect_eq(forensic->size(), 3U); + Void::Testing::expect((*forensic)[0].accepted); + Void::Testing::expect(!(*forensic)[1].accepted); + Void::Testing::expect((*forensic)[1].path.find('\n') == + std::string::npos); + Void::Testing::expect(!(*forensic)[2].accepted); + } + + // Diagnostic sanitizer caps at 4 KiB and escapes newlines. + const std::string huge_diag(6000, 'a'); + Void::Testing::expect_eq(sanitize_diagnostic_path(huge_diag).size(), 4096U); + Void::Testing::expect_eq(sanitize_diagnostic_path("a\nb\rc"), + std::string{"a\\nb\\rc"}); +} + +Void::Testing::Test archive_staged_extraction_atomic_publish_unknown_and_cleanup() +{ + Void::FileSystem::TempDir tmp{"void_archive_staged_"}; + const auto archive_path = tmp / "pkg.tar.zst"; + const auto parent_dir = tmp / "versions"; + std::filesystem::create_directories(parent_dir); + + const std::array entries{{ + CreateEntry{.path = "bin/app", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("binary-payload")}, + CreateEntry{.path = "etc/config.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("key=val")}, + }}; + Void::Testing::require(create_archive(archive_path, entries).has_value()); + + // 1. Staged extraction + atomic no-replace publication + safe modes. + std::size_t progress_calls = 0; + StagedExtractionOptions sopts{}; + sopts.on_progress = [&](const ProgressEvent&) { ++progress_calls; }; + auto staged = extract_staged(archive_path, parent_dir, sopts); + Void::Testing::require(staged.has_value()); + Void::Testing::expect(staged->valid()); + Void::Testing::expect(!staged->published()); + Void::Testing::expect_eq(staged->entries(), 2U); + Void::Testing::expect(progress_calls >= 1U); + + // Unsupported renameat2 ENOSYS returns unsupported_capability without + // fallback or consuming the staging tree. + { + ScopedFaultGuard fault{FaultPoint::rename_enosys}; + auto unsupported = staged->publish("v1"); + Void::Testing::require(!unsupported.has_value()); + Void::Testing::expect_eq( + unsupported.error().code().value, + static_cast(ArchiveErrorCode::unsupported_capability)); + Void::Testing::expect(!staged->published()); + Void::Testing::expect(!std::filesystem::exists(parent_dir / "v1")); + } + + // Atomic publish succeeds. + auto receipt = staged->publish("v1"); + Void::Testing::require(receipt.has_value()); + Void::Testing::expect_eq(static_cast(receipt->outcome), + static_cast(PublicationOutcome::Published)); + Void::Testing::expect(staged->published()); + Void::Testing::expect_eq(read_file_str(parent_dir / "v1/bin/app"), + std::string{"binary-payload"}); + Void::Testing::expect_eq(read_file_str(parent_dir / "v1/etc/config.txt"), + std::string{"key=val"}); + + struct stat st_exec{}; + struct stat st_reg{}; + Void::Testing::require(::stat((parent_dir / "v1/bin/app").c_str(), &st_exec) == + 0); + Void::Testing::require( + ::stat((parent_dir / "v1/etc/config.txt").c_str(), &st_reg) == 0); + Void::Testing::expect_eq(st_exec.st_mode & 0777, mode_t{0755}); + Void::Testing::expect_eq(st_reg.st_mode & 0777, mode_t{0644}); + + // 2. Never overwrites an existing child directory. + auto staged2 = extract_staged(archive_path, parent_dir); + Void::Testing::require(staged2.has_value()); + auto conflict = staged2->publish("v1"); + Void::Testing::require(!conflict.has_value()); + Void::Testing::expect_eq( + conflict.error().code().value, + static_cast(ArchiveErrorCode::already_exists)); + const auto stage2_root = staged2->staging_root(); + Void::Testing::expect(std::filesystem::exists(stage2_root)); + // Destroying unpublished StagedTree cleans up its staging directory. + staged2 = std::unexpected{make_archive_error(ArchiveErrorCode::none)}; + Void::Testing::expect(!std::filesystem::exists(stage2_root)); + + // 3. Post-rename parent fsync failure reports Unknown outcome with identity + // and does NOT claim rollback. + auto staged3 = extract_staged(archive_path, parent_dir); + Void::Testing::require(staged3.has_value()); + { + ScopedFaultGuard fault{FaultPoint::post_rename_parent_sync}; + auto unknown = staged3->publish("v2"); + Void::Testing::require(unknown.has_value()); + Void::Testing::expect_eq(static_cast(unknown->outcome), + static_cast(PublicationOutcome::Unknown)); + Void::Testing::expect_eq(unknown->destination_path, parent_dir / "v2"); + Void::Testing::expect(!unknown->staging_id.empty()); + Void::Testing::expect(std::filesystem::exists(parent_dir / "v2/bin/app")); + } + + // 4. Failed extraction with cleanup fault preserves primary error + + // retryable staging_id; cleanup_stale_staging cleans only valid marked dirs. + const auto foreign_dir = parent_dir / ".void-stage-foreign"; + std::filesystem::create_directories(foreign_dir); + { + ScopedFaultGuard fault{FaultPoint::staging_cleanup_fail}; + StagedExtractionOptions tight{}; + tight.limits.max_file_bytes = 4; + auto failed = extract_staged(archive_path, parent_dir, tight); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect_eq( + failed.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); + Void::Testing::expect(failed.error().message().find("staging_id=") != + std::string::npos); + } + auto cleaned = cleanup_stale_staging(parent_dir, std::chrono::seconds{0}); + Void::Testing::require(cleaned.has_value()); + Void::Testing::expect_eq(*cleaned, 1U); + Void::Testing::expect(std::filesystem::exists(foreign_dir)); +} + +Void::Testing::Test archive_isolated_worker_extracts_verifies_and_publishes() +{ +#ifdef VOID_ARCHIVE_WORKER_PATH + Void::FileSystem::TempDir tmp{"void_archive_iso_"}; + const auto archive_path = tmp / "untrusted.tar.zst"; + const auto parent_dir = tmp / "out"; + std::filesystem::create_directories(parent_dir); + + const std::array entries{{ + CreateEntry{.path = "bin/tool", + .type = EntryType::RegularFile, + .executable = true, + .content = to_bytes("isolated-ok")}, + CreateEntry{.path = "data/info.txt", + .type = EntryType::RegularFile, + .executable = false, + .content = to_bytes("verified-by-parent")}, + }}; + Void::Testing::require(create_archive(archive_path, entries).has_value()); + + IsolationOptions iso{}; + iso.worker_executable = VOID_ARCHIVE_WORKER_PATH; + iso.timeout = std::chrono::seconds{30}; + iso.max_rss_bytes = 256ULL * 1024 * 1024; + + auto staged = extract_staged_isolated(archive_path, parent_dir, iso); + Void::Testing::require(staged.has_value()); + Void::Testing::expect_eq(staged->entries(), 2U); + + auto published = staged->publish("rel-1"); + Void::Testing::require(published.has_value()); + Void::Testing::expect_eq(static_cast(published->outcome), + static_cast(PublicationOutcome::Published)); + Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/bin/tool"), + std::string{"isolated-ok"}); + Void::Testing::expect_eq(read_file_str(parent_dir / "rel-1/data/info.txt"), + std::string{"verified-by-parent"}); + + // Worker limit violation returns limit_exceeded and cleans staging. + IsolationOptions tight = iso; + tight.extraction.limits.max_file_bytes = 4; + auto failed = extract_staged_isolated(archive_path, parent_dir, tight); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect_eq( + failed.error().code().value, + static_cast(ArchiveErrorCode::limit_exceeded)); +#else + Void::Testing::expect(true); +#endif +} diff --git a/tests/standalone/Crypto/CryptoHardening.cpp b/tests/standalone/Crypto/CryptoHardening.cpp new file mode 100644 index 0000000..12a090c --- /dev/null +++ b/tests/standalone/Crypto/CryptoHardening.cpp @@ -0,0 +1,368 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + int hex_nibble(char c) + { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; + } + + std::vector from_hex(std::string_view hex) + { + Void::Testing::require(hex.size() % 2 == 0); + std::vector out; + out.reserve(hex.size() / 2); + for (std::size_t i = 0; i < hex.size(); i += 2) { + const int hi = hex_nibble(hex[i]); + const int lo = hex_nibble(hex[i + 1]); + Void::Testing::require(hi >= 0 && lo >= 0); + out.push_back(static_cast((hi << 4) | lo)); + } + return out; + } + + std::string to_hex(std::span data) + { + static constexpr char kHex[] = "0123456789abcdef"; + std::string out; + out.reserve(data.size() * 2); + for (const std::byte b : data) { + const auto v = static_cast(b); + out.push_back(kHex[v >> 4]); + out.push_back(kHex[v & 0x0F]); + } + return out; + } + + std::span as_bytes(std::string_view text) + { + return std::as_bytes(std::span{text.data(), text.size()}); + } +} // namespace + +Void::Testing::Test crypto_hasher_state_poisoning_and_provider_isolation() +{ + using namespace Void::Crypto; + + auto h = Hasher::create(HashAlgorithm::Sha256); + Void::Testing::require(h.has_value()); + Void::Testing::expect_eq(static_cast(h->state()), + static_cast(HasherState::Ready)); + Void::Testing::require(h->update("ab").has_value()); + Void::Testing::expect_eq(static_cast(h->state()), + static_cast(HasherState::Updating)); + + // Inject mid-stream update failure -> hasher is permanently poisoned. + { + ScopedFaultGuard fault{FaultConfig{FaultOperation::hash_update, + CryptoErrorCode::backend_error, 0}}; + auto bad = h->update("c"); + Void::Testing::require(!bad.has_value()); + Void::Testing::expect_eq(bad.error().code().domain, + Void::Result::kCryptoErrorDomain); + Void::Testing::expect_eq( + bad.error().code().value, + static_cast(CryptoErrorCode::backend_error)); + } + Void::Testing::expect_eq(static_cast(h->state()), + static_cast(HasherState::Failed)); + auto retry_update = h->update("d"); + Void::Testing::require(!retry_update.has_value()); + Void::Testing::expect_eq( + retry_update.error().code().value, + static_cast(CryptoErrorCode::invalid_state)); + auto retry_finalize = h->finalize(); + Void::Testing::require(!retry_finalize.has_value()); + Void::Testing::expect_eq( + retry_finalize.error().code().value, + static_cast(CryptoErrorCode::invalid_state)); + + // Moved-from state reports MovedFrom and fails cleanly. + Hasher moved = std::move(*h); + Void::Testing::expect_eq(static_cast(h->state()), + static_cast(HasherState::MovedFrom)); + Void::Testing::expect(!h->update("x").has_value()); + Void::Testing::expect(!moved.finalize().has_value()); + + // Per-context unavailable provider fails without breaking subsequent + // default-provider operations. + ProviderOptions bad_provider{.property_query = "provider=nonexistent_void"}; + auto unavailable = Hasher::create(HashAlgorithm::Sha256, bad_provider); + Void::Testing::require(!unavailable.has_value()); + Void::Testing::expect_eq( + unavailable.error().code().value, + static_cast(CryptoErrorCode::provider_error)); + + auto good = sha256("abc"); + Void::Testing::require(good.has_value()); + Void::Testing::expect_eq( + to_hex(*good), + std::string{"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f" + "20015ad"}); +} + +Void::Testing::Test crypto_ed25519_signing_vectors_and_boundaries() +{ + using namespace Void::Crypto; + + struct Rfc8032Vector { + std::string_view seed_hex; + std::string_view pub_hex; + std::string_view msg_hex; + std::string_view sig_hex; + }; + + const std::array vectors = {{ + {"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + "", + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155" + "5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"}, + {"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + "72", + "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da" + "085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"}, + {"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + "af82", + "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac" + "18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"}, + }}; + + for (const auto& vec : vectors) { + const auto seed = from_hex(vec.seed_hex); + const auto expected_pub = from_hex(vec.pub_hex); + const auto msg = from_hex(vec.msg_hex); + const auto expected_sig = from_hex(vec.sig_hex); + + auto key = Ed25519PrivateKey::from_raw_seed(seed); + Void::Testing::require(key.has_value()); + auto pub = key->public_key(); + Void::Testing::require(pub.has_value()); + Void::Testing::expect_eq(to_hex(pub->view()), std::string{vec.pub_hex}); + + auto exported = key->export_raw_seed(); + Void::Testing::require(exported.has_value()); + Void::Testing::expect(constant_time_equal(exported->view(), seed)); + exported->clear(); + Void::Testing::expect(!exported->valid()); + Void::Testing::expect(exported->view().empty()); + + auto sig = sign_ed25519(msg, *key); + Void::Testing::require(sig.has_value()); + Void::Testing::expect_eq(to_hex(sig->view()), std::string{vec.sig_hex}); + + auto verified = verify_ed25519(msg, *sig, *pub); + Void::Testing::require(verified.has_value()); + Void::Testing::expect(*verified); + + // Flipping a single signature bit yields false, NOT an error. + auto tampered_sig = *sig; + tampered_sig.bytes[0] ^= std::byte{0x01}; + auto bad_verify = verify_ed25519(msg, tampered_sig, *pub); + Void::Testing::require(bad_verify.has_value()); + Void::Testing::expect(!*bad_verify); + } + + // Key generation round-trip. + auto generated = Ed25519PrivateKey::generate(); + Void::Testing::require(generated.has_value()); + auto gen_pub = generated->public_key(); + Void::Testing::require(gen_pub.has_value()); + auto gen_sig = sign_ed25519(as_bytes("hello ed25519"), *generated); + Void::Testing::require(gen_sig.has_value()); + auto gen_ok = + verify_ed25519(as_bytes("hello ed25519"), *gen_sig, *gen_pub); + Void::Testing::require(gen_ok.has_value()); + Void::Testing::expect(*gen_ok); + + // Invalid sizes near boundaries must fail with typed invalid_argument. + for (const std::size_t bad_key_len : {0U, 1U, 31U, 33U, 64U}) { + std::vector bad_key(bad_key_len, std::byte{0x11}); + auto r = verifyEd25519({}, gen_sig->view(), bad_key); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(CryptoErrorCode::invalid_key_size)); + auto import_r = Ed25519PrivateKey::from_raw_seed(bad_key); + Void::Testing::require(!import_r.has_value()); + Void::Testing::expect_eq( + import_r.error().code().value, + static_cast(CryptoErrorCode::invalid_key_size)); + } + for (const std::size_t bad_sig_len : {0U, 1U, 63U, 65U}) { + std::vector bad_sig(bad_sig_len, std::byte{0x22}); + auto r = verifyEd25519({}, bad_sig, gen_pub->view()); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(CryptoErrorCode::invalid_signature_size)); + } + + // Oversized message (>16 MiB) rejected before OpenSSL call. + std::vector huge(CryptoLimits::kMaxOneShotMessageBytes + 1U, + std::byte{0}); + auto huge_sign = sign_ed25519(huge, *generated); + Void::Testing::require(!huge_sign.has_value()); + Void::Testing::expect_eq( + huge_sign.error().code().value, + static_cast(CryptoErrorCode::message_too_large)); + auto huge_verify = verify_ed25519(huge, *gen_sig, *gen_pub); + Void::Testing::require(!huge_verify.has_value()); + Void::Testing::expect_eq( + huge_verify.error().code().value, + static_cast(CryptoErrorCode::message_too_large)); + + // Provider fault returns error without leaking secret key material. + { + ScopedFaultGuard fault{FaultConfig{FaultOperation::ed25519_sign, + CryptoErrorCode::provider_error, 0}}; + auto failed = sign_ed25519(as_bytes("secret-free"), *generated); + Void::Testing::require(!failed.has_value()); + Void::Testing::expect_eq( + failed.error().code().value, + static_cast(CryptoErrorCode::provider_error)); + } +} + +Void::Testing::Test crypto_hmac_sha256_and_hkdf_sha256_vectors_and_guards() +{ + using namespace Void::Crypto; + + // RFC 4231 Case 1 + { + const std::vector key(20, std::byte{0x0b}); + auto mac = hmac_sha256(key, as_bytes("Hi There")); + Void::Testing::require(mac.has_value()); + Void::Testing::expect_eq( + to_hex(*mac), + std::string{"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e93" + "76c2e32cff7"}); + } + // RFC 4231 Case 2 + { + auto mac = hmac_sha256(as_bytes("Jefe"), + as_bytes("what do ya want for nothing?")); + Void::Testing::require(mac.has_value()); + Void::Testing::expect_eq( + to_hex(*mac), + std::string{"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec5" + "8b964ec3843"}); + } + // RFC 4231 Case 3 + { + const std::vector key(20, std::byte{0xaa}); + const std::vector msg(50, std::byte{0xdd}); + auto mac = hmac_sha256(key, msg); + Void::Testing::require(mac.has_value()); + Void::Testing::expect_eq( + to_hex(*mac), + std::string{"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635" + "514ced565fe"}); + } + // Empty key and empty message work cleanly. + { + auto mac = hmac_sha256({}, {}); + Void::Testing::require(mac.has_value()); + Void::Testing::expect_eq(mac->size(), HmacSha256Size); + } + + // RFC 5869 Appendix A Case 1 + { + const std::vector ikm(22, std::byte{0x0b}); + const auto salt = from_hex("000102030405060708090a0b0c"); + const auto info = from_hex("f0f1f2f3f4f5f6f7f8f9"); + std::array okm{}; + auto r = hkdf_sha256(ikm, salt, info, okm); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq( + to_hex(okm), + std::string{"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02" + "d56ecc4c5bf34007208d5b887185865"}); + } + // RFC 5869 Appendix A Case 3 (empty salt & info) + { + const std::vector ikm(22, std::byte{0x0b}); + std::array okm{}; + auto r = hkdf_sha256(ikm, {}, {}, okm); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq( + to_hex(okm), + std::string{"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454" + "e5f3c738d2d9d201395faa4b61a96c8"}); + } + + // HKDF guards: empty output, oversized (>4 KiB) without mutating buffer, + // overlapping spans rejected, fault wipes destination. + { + const std::vector ikm(16, std::byte{0x42}); + std::vector empty_out; + auto r_empty = hkdf_sha256(ikm, {}, {}, empty_out); + Void::Testing::require(!r_empty.has_value()); + Void::Testing::expect_eq( + r_empty.error().code().value, + static_cast(CryptoErrorCode::invalid_argument)); + + std::vector too_large(CryptoLimits::kMaxHkdfOutputBytes + 1U, + std::byte{0x7A}); + auto r_large = hkdf_sha256(ikm, {}, {}, too_large); + Void::Testing::require(!r_large.has_value()); + Void::Testing::expect_eq( + r_large.error().code().value, + static_cast(CryptoErrorCode::output_too_large)); + Void::Testing::expect( + std::all_of(too_large.begin(), too_large.end(), + [](std::byte b) { return b == std::byte{0x7A}; })); + + std::array shared{}; + shared.fill(std::byte{0x55}); + auto r_overlap = + hkdf_sha256(std::span{shared}.subspan(0, 32), {}, {}, + std::span{shared}.subspan(16, 32)); + Void::Testing::require(!r_overlap.has_value()); + Void::Testing::expect_eq( + r_overlap.error().code().value, + static_cast(CryptoErrorCode::overlapping_buffers)); + + std::array wiped{}; + wiped.fill(std::byte{0xCC}); + { + ScopedFaultGuard fault{ + FaultConfig{FaultOperation::hkdf, + CryptoErrorCode::provider_error, 0}}; + auto r_fault = hkdf_sha256(ikm, {}, {}, wiped); + Void::Testing::require(!r_fault.has_value()); + } + Void::Testing::expect( + std::all_of(wiped.begin(), wiped.end(), + [](std::byte b) { return b == std::byte{0x00}; })); + } + + // constant_time_equal checks + const auto a = from_hex("01020304"); + const auto b = from_hex("01020304"); + const auto c = from_hex("01020305"); + const auto d = from_hex("010203"); + Void::Testing::expect(constant_time_equal(a, b)); + Void::Testing::expect(!constant_time_equal(a, c)); + Void::Testing::expect(!constant_time_equal(a, d)); +} diff --git a/tests/standalone/CryptoAsync/CryptoAsync.cpp b/tests/standalone/CryptoAsync/CryptoAsync.cpp new file mode 100644 index 0000000..5b6998a --- /dev/null +++ b/tests/standalone/CryptoAsync/CryptoAsync.cpp @@ -0,0 +1,333 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + std::span as_bytes(std::string_view text) + { + return std::as_bytes(std::span{text.data(), text.size()}); + } + + struct ScopedTempDir { + std::filesystem::path path; + + ScopedTempDir() + { + static std::atomic seq{0}; + const auto id = seq.fetch_add(1, std::memory_order_relaxed); + const auto ts = + std::chrono::steady_clock::now().time_since_epoch().count(); + path = std::filesystem::temp_directory_path() / + ("void_crypto_async_" + std::to_string(ts) + "_" + + std::to_string(id)); + std::filesystem::create_directories(path); + } + + ~ScopedTempDir() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + }; + + Void::Coro::Task run_hash_stream( + Void::Crypto::HashAlgorithm alg, Void::IO::Driver& driver, + Void::IO::ByteStream& stream, Void::Async::OperationOptions op, + Void::CryptoAsync::StreamHashOptions hash_opts, + std::optional>& out) + { + out = co_await Void::CryptoAsync::hash_stream( + alg, driver, stream, std::move(op), std::move(hash_opts)); + } + + Void::Coro::Task run_hash_file( + Void::CryptoAsync::AsyncFileHasher& hasher, + Void::Crypto::HashAlgorithm alg, std::filesystem::path path, + Void::Async::OperationOptions op, + std::optional>& out, + std::atomic* done_counter = nullptr) + { + out = co_await hasher.hash_file(alg, std::move(path), std::move(op)); + if (done_counter != nullptr) { + done_counter->fetch_add(1, std::memory_order_release); + } + } +} // namespace + +Void::Testing::Test crypto_async_hash_stream_eof_errors_and_cancellation() +{ + using namespace Void::Crypto; + using namespace Void::CryptoAsync; + + Void::Async::ManualExecutor exec; + Void::Time::ManualClock clock; + + Void::IO::BackendOptions opts{}; + opts.preference = Void::IO::BackendPreference::mock; + opts.limits.max_owned_buffer_bytes = 128 * 1024; + auto drv = Void::IO::Driver::create(exec, opts, clock); + Void::Testing::require(drv.has_value()); + auto* mock = (*drv)->mock_controller(); + Void::Testing::require(mock != nullptr); + + // 1. Multi-chunk stream matches sha256("hello async world"). + { + auto stream = (*drv)->create_mock_stream(); + Void::Testing::require(stream.has_value()); + + std::optional> outcome; + Void::Async::TaskScope scope{exec}; + auto handle = scope.spawn( + run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {}, + StreamHashOptions{.chunk_bytes = 8}, outcome)); + Void::Testing::require(handle.has_value()); + (void)exec.drain(); + + Void::Testing::require( + mock->complete_read(*stream, as_bytes("hello "), false)); + (void)exec.drain(); + Void::Testing::require( + mock->complete_read(*stream, as_bytes("async "), false)); + (void)exec.drain(); + Void::Testing::require( + mock->complete_read(*stream, as_bytes("world"), true)); + (void)exec.drain(); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outcome.has_value() && outcome->has_value()); + + auto expected = sha256("hello async world"); + Void::Testing::require(expected.has_value()); + Void::Testing::expect_eq(**outcome, *expected); + } + + // 2. Partial read then error must never produce a digest. + { + auto stream = (*drv)->create_mock_stream(); + Void::Testing::require(stream.has_value()); + + std::optional> outcome; + Void::Async::TaskScope scope{exec}; + auto handle = scope.spawn( + run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {}, + StreamHashOptions{.chunk_bytes = 16}, outcome)); + Void::Testing::require(handle.has_value()); + (void)exec.drain(); + + Void::Testing::require( + mock->complete_read(*stream, as_bytes("partial"), false)); + (void)exec.drain(); + Void::Testing::require(mock->fail_read( + *stream, Void::IO::make_io_error(Void::IO::IoErrorCode::os_error, + "injected read failure"))); + (void)exec.drain(); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outcome.has_value() && !outcome->has_value()); + Void::Testing::expect_eq( + outcome->error().code().value, + static_cast(CryptoErrorCode::io_error)); + } + + // 3. Stop requested racing with EOF completion must not return a digest. + { + auto stream = (*drv)->create_mock_stream(); + Void::Testing::require(stream.has_value()); + + std::stop_source stop_src; + std::optional> outcome; + Void::Async::TaskScope scope{exec}; + auto handle = scope.spawn(run_hash_stream( + HashAlgorithm::Sha256, **drv, *stream, + Void::Async::OperationOptions{.stop = stop_src.get_token()}, + StreamHashOptions{.chunk_bytes = 16}, outcome)); + Void::Testing::require(handle.has_value()); + (void)exec.drain(); + + auto tok = mock->try_acquire_read(*stream); + Void::Testing::require(tok.has_value()); + stop_src.request_stop(); + (void)mock->finish_read_data(*tok, as_bytes("done"), true); + (void)exec.drain(); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outcome.has_value() && !outcome->has_value()); + Void::Testing::expect_eq( + outcome->error().code().value, + static_cast(CryptoErrorCode::cancelled)); + } + + // 4. Deadline expiry between chunks returns timeout. + { + auto stream = (*drv)->create_mock_stream(); + Void::Testing::require(stream.has_value()); + + const auto deadline = clock.now() + std::chrono::seconds{5}; + std::optional> outcome; + Void::Async::TaskScope scope{exec}; + auto handle = scope.spawn(run_hash_stream( + HashAlgorithm::Sha256, **drv, *stream, + Void::Async::OperationOptions{.deadline = deadline}, + StreamHashOptions{.chunk_bytes = 16}, outcome)); + Void::Testing::require(handle.has_value()); + (void)exec.drain(); + + Void::Testing::require( + clock.advance(std::chrono::seconds{10}).has_value()); + Void::Testing::require( + mock->complete_read(*stream, as_bytes("chunk1"), false)); + (void)exec.drain(); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outcome.has_value() && !outcome->has_value()); + Void::Testing::expect_eq( + outcome->error().code().value, + static_cast(CryptoErrorCode::timeout)); + } + + // 5. Buffer budget exhaustion returns resource_exhausted before reading. + { + auto hold = (*drv)->allocate_buffer(128 * 1024); + Void::Testing::require(hold.has_value()); + auto stream = (*drv)->create_mock_stream(); + Void::Testing::require(stream.has_value()); + + std::optional> outcome; + Void::Async::TaskScope scope{exec}; + auto handle = scope.spawn( + run_hash_stream(HashAlgorithm::Sha256, **drv, *stream, {}, + StreamHashOptions{.chunk_bytes = 1024}, outcome)); + Void::Testing::require(handle.has_value()); + (void)exec.drain(); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outcome.has_value() && !outcome->has_value()); + Void::Testing::expect_eq( + outcome->error().code().value, + static_cast(CryptoErrorCode::resource_exhausted)); + } + + Void::Testing::require((*drv)->shutdown_and_join().has_value()); +} + +Void::Testing::Test crypto_async_file_hasher_bounds_and_shutdown() +{ + using namespace Void::Crypto; + using namespace Void::CryptoAsync; + + ScopedTempDir tmp; + const auto file_path = tmp.path / "sample.bin"; + { + std::ofstream out{file_path, std::ios::binary}; + std::string payload(200 * 1024, 'V'); + out.write(payload.data(), static_cast(payload.size())); + } + auto sync_digest = sha256File(file_path); + Void::Testing::require(sync_digest.has_value()); + + Void::Async::ManualExecutor exec; + AsyncFileHasher hasher{ + exec, + FileHasherOptions{.max_concurrent = 2, + .max_waiting = 4, + .buffer_budget_bytes = 256 * 1024, + .chunk_bytes = 16 * 1024}}; + + std::array>, 4> results{}; + std::atomic done_count{0}; + { + Void::Async::TaskScope scope{exec}; + for (std::size_t i = 0; i < results.size(); ++i) { + auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256, + file_path, {}, results[i], + &done_count)); + Void::Testing::require(h.has_value()); + } + + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds{10}; + while (done_count.load(std::memory_order_acquire) < 4 && + std::chrono::steady_clock::now() < deadline) { + if (exec.drain() == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + Void::Testing::require(scope.join_pumping(exec).has_value()); + } + + for (const auto& r : results) { + Void::Testing::require(r.has_value() && r->has_value()); + Void::Testing::expect_eq(**r, *sync_digest); + } + + // Pre-cancelled admission returns cancelled without starting. + { + std::stop_source ss; + ss.request_stop(); + std::optional> cancelled; + Void::Async::TaskScope scope{exec}; + auto h = scope.spawn(run_hash_file( + hasher, HashAlgorithm::Sha256, file_path, + Void::Async::OperationOptions{.stop = ss.get_token()}, cancelled)); + Void::Testing::require(h.has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(cancelled.has_value() && !cancelled->has_value()); + Void::Testing::expect_eq( + cancelled->error().code().value, + static_cast(CryptoErrorCode::cancelled)); + } + + // Shutdown stops admission cleanly and leaves zero active/reserved budget. + Void::Testing::require(hasher.close_and_join().has_value()); + const auto st = hasher.stats(); + Void::Testing::expect(st.closing); + Void::Testing::expect_eq(st.active, 0U); + Void::Testing::expect_eq(st.reserved_buffer_bytes, 0U); + + { + std::optional> after_close; + Void::Async::TaskScope scope{exec}; + auto h = scope.spawn(run_hash_file(hasher, HashAlgorithm::Sha256, + file_path, {}, after_close)); + Void::Testing::require(h.has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(after_close.has_value() && + !after_close->has_value()); + Void::Testing::expect_eq( + after_close->error().code().value, + static_cast(CryptoErrorCode::closed)); + } + + // Budget smaller than chunk_bytes fails with resource_exhausted. + AsyncFileHasher tiny{ + exec, + FileHasherOptions{.max_concurrent = 1, + .max_waiting = 1, + .buffer_budget_bytes = 1024, + .chunk_bytes = 4096}}; + { + std::optional> budget_err; + Void::Async::TaskScope scope{exec}; + auto h = scope.spawn(run_hash_file(tiny, HashAlgorithm::Sha256, + file_path, {}, budget_err)); + Void::Testing::require(h.has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(budget_err.has_value() && + !budget_err->has_value()); + Void::Testing::expect_eq( + budget_err->error().code().value, + static_cast(CryptoErrorCode::resource_exhausted)); + } + Void::Testing::require(tiny.close_and_join().has_value()); +} diff --git a/tests/standalone/Security/SecurityHardening.cpp b/tests/standalone/Security/SecurityHardening.cpp new file mode 100644 index 0000000..515a7d0 --- /dev/null +++ b/tests/standalone/Security/SecurityHardening.cpp @@ -0,0 +1,322 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +Void::Testing::Test security_secure_buffer_wipe_and_lock_policies() +{ + using namespace Void::Security; + + const auto wiped_before = SecureBuffer::total_wiped_bytes(); + { + auto buf = SecureBuffer::from_string("top-secret-key-material"); + Void::Testing::require(buf.has_value()); + Void::Testing::expect_eq(buf->string_view(), + std::string_view{"top-secret-key-material"}); + Void::Testing::expect(!buf->is_locked()); + + auto moved = std::move(*buf); + Void::Testing::expect(buf->empty()); + Void::Testing::expect_eq(moved.size(), 23U); + } + Void::Testing::expect(SecureBuffer::total_wiped_bytes() >= + wiped_before + 23U); + + // LockedRequired fails closed on locked allocation failure (no downgrade). + { + ScopedFaultGuard fault{ + FaultConfig{FaultOperation::locked_alloc, + SecurityErrorCode::locked_memory_unavailable, 0}}; + auto required = SecureBuffer::allocate(64, LockPolicy::LockedRequired); + Void::Testing::require(!required.has_value()); + Void::Testing::expect_eq( + required.error().code().value, + static_cast( + SecurityErrorCode::locked_memory_unavailable)); + + auto optional = SecureBuffer::allocate(64, LockPolicy::LockedOptional); + Void::Testing::require(optional.has_value()); + Void::Testing::expect(!optional->is_locked()); + } + + // Oversized allocation rejected before touching backend. + auto huge = + SecureBuffer::allocate(SecurityLimits::kMaxSecretPlaintextBytes + 1U); + Void::Testing::require(!huge.has_value()); + Void::Testing::expect_eq( + huge.error().code().value, + static_cast(SecurityErrorCode::input_too_large)); +} + +Void::Testing::Test security_input_caps_cost_budget_and_fault_seams() +{ + using namespace Void::Security; + + // Excessive Argon2id memory/iteration cost rejected BEFORE allocation. + const std::string malicious_mem = + "$argon2id$v=19$m=4194304,t=3,p=1$AAAAAAAAAAAAAAAAAAAAAA$" + "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; + auto parsed = parse_argon2id_cost(malicious_mem); + Void::Testing::require(parsed.has_value()); + Void::Testing::expect_eq(parsed->memory_kib, 4194304ULL); + + PasswordVerifyBudget tight_budget{ + .max_memory_bytes = 64ULL * 1024ULL * 1024ULL, + .max_iterations = 4, + .max_parallelism = 2, + }; + auto rejected = verify_password_budgeted("pw", malicious_mem, tight_budget); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect_eq( + rejected.error().code().value, + static_cast(SecurityErrorCode::cost_budget_exceeded)); + + // Malformed hash corpus rejected cleanly. + for (const std::string_view bad : { + "", + "$argon2i$v=19$m=65536,t=2,p=1$aaaa$bbbb", + "$argon2id$v=18$m=65536,t=2,p=1$aaaa$bbbb", + "$argon2id$v=19$m=0,t=2,p=1$aaaa$bbbb", + "$argon2id$v=19$m=99999999999999999999,t=2,p=1$aaaa$bbbb", + "$argon2id$v=19$m=65536,t=2$aaaa$bbbb", + "$argon2id$v=19$m=65536,t=2,p=1$aaaa$", + }) { + Void::Testing::expect(!parse_argon2id_cost(bad).has_value()); + } + + // Input length caps: >1 KiB password, >512 B token. + const std::string long_pw(SecurityLimits::kMaxPasswordBytes + 1U, 'p'); + auto pw_err = hash_password(long_pw, PasswordHashStrength::Interactive); + Void::Testing::require(!pw_err.has_value()); + Void::Testing::expect_eq( + pw_err.error().code().value, + static_cast(SecurityErrorCode::input_too_large)); + + const std::string long_tok(SecurityLimits::kMaxTokenBytes + 1U, 't'); + auto tok_err = hash_token(long_tok); + Void::Testing::require(!tok_err.has_value()); + Void::Testing::expect_eq( + tok_err.error().code().value, + static_cast(SecurityErrorCode::input_too_large)); + + // Sodium init / randomness failure publishes no token or key. + { + ScopedFaultGuard fault{FaultConfig{FaultOperation::sodium_init, + SecurityErrorCode::backend_error, 0}}; + Void::Testing::expect(!random_token().has_value()); + Void::Testing::expect(!random_secret_key().has_value()); + } + { + ScopedFaultGuard fault{FaultConfig{FaultOperation::random_bytes, + SecurityErrorCode::backend_error, 0}}; + Void::Testing::expect(!random_token().has_value()); + Void::Testing::expect(!random_secret_key().has_value()); + } + + // Legacy envelope exact byte layout preserved: 24B nonce + 16B MAC + pt. + auto key = random_secret_key(); + Void::Testing::require(key.has_value()); + const std::vector pt{'v', 'o', 'i', 'd'}; + auto legacy = seal_secret(pt, *key); + Void::Testing::require(legacy.has_value()); + Void::Testing::expect_eq(legacy->size(), + secret_nonce_bytes + secret_authentication_bytes + + pt.size()); + auto opened = open_secret(*legacy, *key); + Void::Testing::require(opened.has_value()); + Void::Testing::expect_eq(*opened, pt); +} + +Void::Testing::Test security_versioned_envelope_rotation_and_no_legacy_fallback() +{ + using namespace Void::Security; + + SecretKeyRing ring; + Void::Testing::require(ring.generate_and_add_key("k1", true).has_value()); + Void::Testing::expect_eq(ring.active_key_id().value_or(""), + std::string{"k1"}); + + const std::vector pt{'a', 'p', 'i', '-', 'k', 'e', 'y'}; + const std::vector aad{'t', 'e', 'n', 'a', 'n', 't', ':', '1'}; + const std::vector wrong_aad{'t', 'e', 'n', 'a', + 'n', 't', ':', '2'}; + + auto env_k1 = ring.seal(pt, aad); + Void::Testing::require(env_k1.has_value()); + + auto hdr = inspect_envelope(*env_k1); + Void::Testing::require(hdr.has_value()); + Void::Testing::expect_eq(hdr->version, kEnvelopeVersionV1); + Void::Testing::expect_eq(hdr->algorithm, kEnvelopeAlgXChaCha20Poly1305Ietf); + Void::Testing::expect_eq(hdr->key_id, std::string{"k1"}); + Void::Testing::expect_eq(hdr->plaintext_size, + static_cast(pt.size())); + + // Rotate to k2: new writes use k2, old k1 envelopes still decrypt. + Void::Testing::require(ring.generate_and_add_key("k2", true).has_value()); + Void::Testing::expect_eq(ring.active_key_id().value_or(""), + std::string{"k2"}); + + auto env_k2 = ring.seal(pt, aad); + Void::Testing::require(env_k2.has_value()); + auto hdr2 = inspect_envelope(*env_k2); + Void::Testing::require(hdr2.has_value()); + Void::Testing::expect_eq(hdr2->key_id, std::string{"k2"}); + + auto dec1 = ring.open(*env_k1, aad); + auto dec2 = ring.open(*env_k2, aad); + Void::Testing::require(dec1.has_value() && dec2.has_value()); + Void::Testing::expect(constant_time_equal(dec1->view(), pt)); + Void::Testing::expect(constant_time_equal(dec2->view(), pt)); + + // Wrong AAD fails authentication. + auto bad_aad = ring.open(*env_k1, wrong_aad); + Void::Testing::require(!bad_aad.has_value()); + Void::Testing::expect_eq( + bad_aad.error().code().value, + static_cast(SecurityErrorCode::authentication_failed)); + + // Tampering any header/key_id/ciphertext byte fails authentication. + auto tampered = *env_k1; + tampered.back() ^= 0x80U; + Void::Testing::expect(!ring.open(tampered, aad).has_value()); + + auto bad_ver = *env_k1; + bad_ver[4] = 99U; + auto ver_res = ring.open(bad_ver, aad); + Void::Testing::require(!ver_res.has_value()); + Void::Testing::expect_eq( + ver_res.error().code().value, + static_cast(SecurityErrorCode::unsupported_version)); + + // Legacy secretbox envelope MUST NOT silently fall back in SecretKeyRing. + auto legacy_key = random_secret_key(); + Void::Testing::require(legacy_key.has_value()); + auto legacy_env = seal_secret(pt, *legacy_key); + Void::Testing::require(legacy_env.has_value()); + auto no_fallback = ring.open(*legacy_env, {}); + Void::Testing::require(!no_fallback.has_value()); + Void::Testing::expect_eq( + no_fallback.error().code().value, + static_cast(SecurityErrorCode::unsupported_version)); + + // Key retirement guards: cannot retire active key or key still in inventory. + const std::vector empty_inv{}; + auto retire_active = ring.retire_key("k2", empty_inv); + Void::Testing::require(!retire_active.has_value()); + Void::Testing::expect_eq( + retire_active.error().code().value, + static_cast(SecurityErrorCode::key_in_use)); + + const std::vector still_used{"k1", "k2"}; + auto retire_in_use = ring.retire_key("k1", still_used); + Void::Testing::require(!retire_in_use.has_value()); + Void::Testing::expect_eq( + retire_in_use.error().code().value, + static_cast(SecurityErrorCode::key_in_use)); + + const std::vector migrated_inv{"k2"}; + Void::Testing::require(ring.retire_key("k1", migrated_inv).has_value()); + Void::Testing::expect(!ring.has_key("k1")); + auto retired_open = ring.open(*env_k1, aad); + Void::Testing::require(!retired_open.has_value()); + Void::Testing::expect_eq( + retired_open.error().code().value, + static_cast(SecurityErrorCode::key_not_found)); +} + +Void::Testing::Test security_authorization_default_deny_and_limits() +{ + using namespace Void::Security; + + auto policy = PolicySnapshot::create( + 7, + { + PolicyRule{ + .id = "allow-owner-read", + .effect = Effect::Allow, + .action = "doc:read", + .condition = Predicate::all_of( + {Predicate::resource_type("document"), + Predicate::owner_is_subject()}), + }, + PolicyRule{ + .id = "allow-admin-all", + .effect = Effect::Allow, + .action = "*", + .condition = Predicate::has_role("admin"), + }, + PolicyRule{ + .id = "deny-classified", + .effect = Effect::Deny, + .action = "*", + .condition = Predicate::resource_attr("tier", "classified"), + }, + }); + Void::Testing::require(policy.has_value()); + + Principal alice{ + .subject = "alice", .roles = {"editor"}, .policy_generation = 7}; + Principal admin{ + .subject = "root", .roles = {"admin"}, .policy_generation = 7}; + ResourceAttributes doc{ + .resource_type = "document", + .resource_id = "d1", + .attributes = {{"owner", "alice"}, {"tier", "standard"}}, + }; + ResourceAttributes secret_doc{ + .resource_type = "document", + .resource_id = "d2", + .attributes = {{"owner", "alice"}, {"tier", "classified"}}, + }; + + // Explicit allow for owner. + auto d1 = policy->authorize(alice, "doc:read", doc); + Void::Testing::expect(d1.allowed); + Void::Testing::expect_eq(d1.matched_rule_id, + std::string{"allow-owner-read"}); + + // Default deny for unmatched action. + auto d2 = policy->authorize(alice, "doc:delete", doc); + Void::Testing::expect(!d2.allowed); + + // Deny overrides allow even for admin. + auto d3 = policy->authorize(admin, "doc:read", secret_doc); + Void::Testing::expect(!d3.allowed); + Void::Testing::expect_eq(d3.matched_rule_id, + std::string{"deny-classified"}); + + // Principal exceeding 64 roles fails closed. + Principal bloated{.subject = "bob"}; + bloated.roles.assign(SecurityLimits::kMaxRolesPerPrincipal + 1U, "admin"); + Void::Testing::expect(!policy->authorize(bloated, "doc:read", doc).allowed); + + // Rule count > 4096 rejected. + std::vector too_many( + SecurityLimits::kMaxPolicyRules + 1U, + PolicyRule{.id = "r", + .effect = Effect::Allow, + .action = "x", + .condition = Predicate::always_true()}); + Void::Testing::expect(!PolicySnapshot::create(1, std::move(too_many)).has_value()); + + // Predicate depth > 16 rejected. + Predicate deep = Predicate::always_true(); + for (std::size_t i = 0; i < SecurityLimits::kMaxPredicateDepth + 1U; ++i) { + deep = Predicate::negate(std::move(deep)); + } + Void::Testing::expect( + !PolicySnapshot::create( + 1, {PolicyRule{.id = "deep", + .effect = Effect::Allow, + .action = "x", + .condition = std::move(deep)}}) + .has_value()); +} diff --git a/tests/standalone/SecurityAsync/SecurityAsync.cpp b/tests/standalone/SecurityAsync/SecurityAsync.cpp new file mode 100644 index 0000000..0acbbcb --- /dev/null +++ b/tests/standalone/SecurityAsync/SecurityAsync.cpp @@ -0,0 +1,439 @@ +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Security; + using namespace Void::SecurityAsync; + + Void::Coro::Task run_login( + Authenticator& auth, LoginInput input, + Void::Async::OperationOptions opts, + std::optional>& out, + std::atomic* done = nullptr) + { + out = co_await auth.login(std::move(input), std::move(opts)); + if (done != nullptr) { + done->fetch_add(1, std::memory_order_release); + } + } + + Void::Coro::Task run_authenticate( + Authenticator& auth, const BearerToken& token, + Void::Async::OperationOptions opts, + std::optional>& out) + { + out = co_await auth.authenticate(token, std::move(opts)); + } + + Void::Coro::Task run_revoke( + Authenticator& auth, std::string session_id, + Void::Async::OperationOptions opts, + std::optional>& out) + { + out = co_await auth.revoke(std::move(session_id), std::move(opts)); + } + + void pump_until(Void::Async::ManualExecutor& exec, + const std::atomic& counter, int target) + { + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds{15}; + while (counter.load(std::memory_order_acquire) < target && + std::chrono::steady_clock::now() < deadline) { + if (exec.drain() == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + } +} // namespace + +Void::Testing::Test security_async_login_auth_revoke_expiry_and_clock_rollback() +{ + auto store = std::make_shared(); + auto audit = std::make_shared(64); + Void::Async::ManualExecutor exec; + Void::Time::ManualClock mono_clock; + Void::Time::ManualCivilClock civil_clock{ + std::chrono::system_clock::time_point{std::chrono::seconds{1000000}}}; + + auto alice_hash = + hash_password("correct-pw", PasswordHashStrength::Interactive); + Void::Testing::require(alice_hash.has_value()); + Void::Testing::require( + store + ->upsert_account(AccountRecord{ + .subject = "sub-alice", + .normalized_username = "alice", + .password_hash = *alice_hash, + .roles = {"user"}, + .credential_version = 1, + .revocation_generation = 1, + .policy_generation = 3, + .enabled = true, + }) + .has_value()); + + AuthenticatorOptions opts{}; + opts.dummy_hash_strength = PasswordHashStrength::Interactive; + opts.precomputed_dummy_hash = *alice_hash; + opts.session.ttl = std::chrono::seconds{3600}; + opts.session.max_total_sessions = 4; + opts.session.max_per_subject = 2; + opts.session.clock_rollback_tolerance = std::chrono::seconds{60}; + + auto auth = Authenticator::create(store, exec, opts, audit, mono_clock, + civil_clock); + Void::Testing::require(auth.has_value()); + + // 1. Unknown account and wrong password produce identical public denial but + // distinct internal audit reasons. + { + std::optional> unknown_res; + std::optional> wrong_pw_res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"ghost", "any"}, {}, unknown_res, + &done)) + .has_value()); + Void::Testing::require( + scope + .spawn(run_login(**auth, {"ALICE", "wrong-pw"}, {}, + wrong_pw_res, &done)) + .has_value()); + pump_until(exec, done, 2); + Void::Testing::require(scope.join_pumping(exec).has_value()); + + Void::Testing::require(unknown_res.has_value() && + !unknown_res->has_value()); + Void::Testing::require(wrong_pw_res.has_value() && + !wrong_pw_res->has_value()); + Void::Testing::expect_eq(unknown_res->error().code().value, + wrong_pw_res->error().code().value); + Void::Testing::expect_eq(unknown_res->error().message(), + wrong_pw_res->error().message()); + + const auto events = audit->snapshot(); + bool saw_not_found = false; + bool saw_invalid_pw = false; + for (const auto& ev : events) { + if (ev.internal_reason == "account_not_found") { + saw_not_found = true; + } + if (ev.internal_reason == "invalid_password") { + saw_invalid_pw = true; + } + } + Void::Testing::expect(saw_not_found); + Void::Testing::expect(saw_invalid_pw); + } + + // 2. Successful login (case-insensitive username) + authoritative + // authenticate + immediate revocation (zero positive cache). + std::optional grant1; + { + std::optional> res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {" Alice ", "correct-pw"}, {}, res, + &done)) + .has_value()); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(res.has_value() && res->has_value()); + grant1.emplace(std::move(**res)); + } + + { + std::optional> principal; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_authenticate(**auth, grant1->bearer_token, {}, + principal)) + .has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(principal.has_value() && principal->has_value()); + Void::Testing::expect_eq((*principal)->subject, + std::string{"sub-alice"}); + Void::Testing::expect_eq((*principal)->policy_generation, 3ULL); + } + + // Revoke takes effect immediately on next authenticate call. + { + std::optional> rev_res; + std::optional> after_rev; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_revoke(**auth, grant1->session_id, {}, rev_res)) + .has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(rev_res.has_value() && rev_res->has_value()); + + Void::Async::TaskScope scope2{exec}; + Void::Testing::require( + scope2 + .spawn(run_authenticate(**auth, grant1->bearer_token, {}, + after_rev)) + .has_value()); + Void::Testing::require(scope2.join_pumping(exec).has_value()); + Void::Testing::require(after_rev.has_value() && !after_rev->has_value()); + Void::Testing::expect_eq( + after_rev->error().code().value, + static_cast(SecurityErrorCode::session_revoked)); + } + + // 3. Per-subject session capacity (max_per_subject = 2) enforced, and + // expiry + bounded cleanup reclaims slots. + std::optional g2; + std::optional g3; + for (auto* target : {&g2, &g3}) { + std::optional> res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"alice", "correct-pw"}, {}, res, &done)) + .has_value()); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(res.has_value() && res->has_value()); + target->emplace(std::move(**res)); + } + { + std::optional> over_cap; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"alice", "correct-pw"}, {}, over_cap, + &done)) + .has_value()); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(over_cap.has_value() && !over_cap->has_value()); + Void::Testing::expect_eq( + over_cap->error().code().value, + static_cast( + SecurityErrorCode::session_capacity_exceeded)); + } + + // Advance civil clock past TTL -> authenticate denies expired, cleanup + // removes sessions. + Void::Testing::require( + civil_clock.advance(std::chrono::seconds{3601}).has_value()); + { + std::optional> expired; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_authenticate(**auth, g2->bearer_token, {}, expired)) + .has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(expired.has_value() && !expired->has_value()); + Void::Testing::expect_eq( + expired->error().code().value, + static_cast(SecurityErrorCode::session_expired)); + } + auto cleaned = (*auth)->cleanup_expired_step(); + Void::Testing::require(cleaned.has_value()); + Void::Testing::expect_eq(*cleaned, 3U); + + // 4. Civil-clock rollback beyond 60s tolerance halts admission until + // explicitly reconciled. + civil_clock.set(civil_clock.now() - std::chrono::seconds{120}); + { + std::optional> halted; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"alice", "correct-pw"}, {}, halted)) + .has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(halted.has_value() && !halted->has_value()); + Void::Testing::expect_eq( + halted->error().code().value, + static_cast(SecurityErrorCode::clock_rollback)); + } + (*auth)->reconcile_clock(civil_clock.now()); + + // 5. Store outage fails closed. + store->set_available(false); + { + std::optional> outage; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"alice", "correct-pw"}, {}, outage)) + .has_value()); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(outage.has_value() && !outage->has_value()); + Void::Testing::expect_eq( + outage->error().code().value, + static_cast(SecurityErrorCode::store_unavailable)); + } + store->set_available(true); + + Void::Testing::require((*auth)->close_and_join().has_value()); +} + +Void::Testing::Test security_async_version_race_hash_stop_and_mandatory_audit() +{ + auto store = std::make_shared(); + auto audit = std::make_shared(1); // capacity 1! + Void::Async::ManualExecutor exec; + Void::Time::ManualClock mono_clock; + Void::Time::ManualCivilClock civil_clock{ + std::chrono::system_clock::time_point{std::chrono::seconds{2000000}}}; + + auto pw_hash = + hash_password("hunter2", PasswordHashStrength::Interactive); + Void::Testing::require(pw_hash.has_value()); + Void::Testing::require( + store + ->upsert_account(AccountRecord{ + .subject = "sub-bob", + .normalized_username = "bob", + .password_hash = *pw_hash, + .roles = {"member"}, + .credential_version = 1, + .revocation_generation = 1, + .policy_generation = 1, + .enabled = true, + }) + .has_value()); + + // 1. Stop during in-flight password hash: worker drains to completion, + // releases memory budget, discards outcome, and creates zero sessions. + { + std::promise entered_hash; + std::promise release_hash; + auto entered_fut = entered_hash.get_future(); + auto release_fut = release_hash.get_future().share(); + + AuthenticatorOptions opts{}; + opts.dummy_hash_strength = PasswordHashStrength::Interactive; + opts.precomputed_dummy_hash = *pw_hash; + opts.before_password_verify_hook = [&]() { + entered_hash.set_value(); + release_fut.wait(); + }; + + auto auth = Authenticator::create(store, exec, opts, nullptr, + mono_clock, civil_clock); + Void::Testing::require(auth.has_value()); + + std::stop_source ss; + std::optional> res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"bob", "hunter2"}, + Void::Async::OperationOptions{ + .stop = ss.get_token()}, + res, &done)) + .has_value()); + (void)exec.drain(); + + // Wait until worker actually holds password job budget. + entered_fut.wait(); + Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 1U); + Void::Testing::expect((*auth)->stats().reserved_password_memory_bytes > + 0U); + + ss.request_stop(); + release_hash.set_value(); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + + Void::Testing::require(res.has_value() && !res->has_value()); + Void::Testing::expect_eq( + res->error().code().value, + static_cast(SecurityErrorCode::cancelled)); + Void::Testing::expect_eq(store->session_count(), 0U); + Void::Testing::expect_eq((*auth)->stats().active_password_jobs, 0U); + Void::Testing::expect_eq( + (*auth)->stats().reserved_password_memory_bytes, 0U); + Void::Testing::require((*auth)->close_and_join().has_value()); + } + + // 2. Credential version change racing with login invalidates session write. + { + AuthenticatorOptions opts{}; + opts.dummy_hash_strength = PasswordHashStrength::Interactive; + opts.precomputed_dummy_hash = *pw_hash; + opts.before_password_verify_hook = [&]() { + (void)store->bump_credential_version("sub-bob"); + }; + + auto auth = Authenticator::create(store, exec, opts, nullptr, + mono_clock, civil_clock); + Void::Testing::require(auth.has_value()); + + std::optional> res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done)) + .has_value()); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(res.has_value() && !res->has_value()); + Void::Testing::expect_eq( + res->error().code().value, + static_cast(SecurityErrorCode::conflict)); + Void::Testing::expect_eq(store->session_count(), 0U); + Void::Testing::require((*auth)->close_and_join().has_value()); + } + + // 3. Mandatory fail-closed audit queue full revokes session and fails login. + { + // Pre-fill the 1-slot audit sink. + Void::Testing::require( + audit->record(AuditEvent{.event_type = "fill"}).has_value()); + + AuthenticatorOptions opts{}; + opts.dummy_hash_strength = PasswordHashStrength::Interactive; + opts.precomputed_dummy_hash = *pw_hash; + opts.audit_policy = AuditFailurePolicy::FailClosed; + + auto auth = Authenticator::create(store, exec, opts, audit, mono_clock, + civil_clock); + Void::Testing::require(auth.has_value()); + + std::optional> res; + std::atomic done{0}; + Void::Async::TaskScope scope{exec}; + Void::Testing::require( + scope + .spawn(run_login(**auth, {"bob", "hunter2"}, {}, res, &done)) + .has_value()); + pump_until(exec, done, 1); + Void::Testing::require(scope.join_pumping(exec).has_value()); + Void::Testing::require(res.has_value() && !res->has_value()); + Void::Testing::expect_eq( + res->error().code().value, + static_cast(SecurityErrorCode::audit_failed)); + Void::Testing::require((*auth)->close_and_join().has_value()); + } +} diff --git a/tests/standalone/Update/UpdateHardening.cpp b/tests/standalone/Update/UpdateHardening.cpp new file mode 100644 index 0000000..7e497c7 --- /dev/null +++ b/tests/standalone/Update/UpdateHardening.cpp @@ -0,0 +1,456 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Update; + + std::span as_bytes(std::string_view s) + { + return std::as_bytes(std::span{s.data(), s.size()}); + } + + std::vector to_vec(std::string_view s) + { + std::vector out(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(static_cast(s[i])); + } + return out; + } + + std::string sign_b64url(std::string_view payload, + const Void::Crypto::Ed25519PrivateKey& key) + { + auto sig = Void::Crypto::sign_ed25519(as_bytes(payload), key); + Void::Testing::require(sig.has_value()); + return Void::Encoding::Base64::encode_url( + std::string_view{reinterpret_cast(sig->bytes.data()), + sig->bytes.size()}); + } + + std::string make_feed_payload(std::string_view version, + std::uint64_t sequence, std::string_view url, + std::uint64_t size, std::string_view sha256) + { + return std::format( + R"json({{ + "schemaVersion": 1, + "feedId": "vendor-main", + "sequence": {}, + "generatedAt": "2026-01-01T00:00:00Z", + "expiresAt": "2099-01-01T00:00:00Z", + "releases": [{{ + "component": "service", + "artifactId": "main", + "channel": "stable", + "version": "{}", + "cohort": "linux-abi-2", + "platform": "linux", + "arch": "x86_64", + "url": "{}", + "size": {}, + "sha256": "{}", + "packageType": "tar.zst", + "compatibility": {{ + "versionContracts": {{}}, + "exactContracts": {{}} + }}, + "releaseManifestSha256": "2222222222222222222222222222222222222222222222222222222222222222" + }}] +}})json", + sequence, version, url, size, sha256); + } + + std::string make_envelope_v1(std::string_view key_id, + std::string_view payload, + const Void::Crypto::Ed25519PrivateKey& key) + { + return std::format( + R"json({{"schemaVersion":1,"keyId":"{}","payload":"{}","signature":"{}"}})json", + key_id, Void::Encoding::Base64::encode_url(payload), + sign_b64url(payload, key)); + } + + struct BuiltPackage { + std::filesystem::path path{}; + std::uint64_t size{0}; + std::string sha256{}; + }; + + BuiltPackage build_test_package(const std::filesystem::path& dir, + std::string_view version) + { + const auto pkg_path = dir / std::format("service-{}.tar.zst", version); + const std::array entries{{ + Void::Archive::CreateEntry{ + .path = "version.txt", + .type = Void::Archive::EntryType::RegularFile, + .executable = false, + .content = to_vec(version), + }, + }}; + Void::Testing::require( + Void::Archive::create_archive(pkg_path, entries).has_value()); + auto digest = Void::Crypto::sha256File(pkg_path); + Void::Testing::require(digest.has_value()); + return BuiltPackage{ + .path = pkg_path, + .size = std::filesystem::file_size(pkg_path), + .sha256 = Void::Encoding::Hex::encode(*digest), + }; + } +} // namespace + +Void::Testing::Test update_schema3_verify_before_parse_and_strict_json_profile() +{ + auto priv = Void::Crypto::Ed25519PrivateKey::generate(); + Void::Testing::require(priv.has_value()); + auto pub = priv->public_key(); + Void::Testing::require(pub.has_value()); + Keyring keys{{"k1", pub->bytes}}; + + // 1. Schema-3 envelope with INVALID signature AND MALFORMED non-JSON + // payload must fail at signature verification (NOT JSON parse / mirror + // mismatch!). + { + constexpr std::string_view corrupt_payload = "{not valid json!!!"; + const std::array bad_sig{}; + const std::string env = std::format( + R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":1}},"signedPayload":"{}","signature":"{}"}})json", + Void::Encoding::Base64::encode_url(corrupt_payload), + Void::Encoding::Base64::encode_url(std::string_view{ + reinterpret_cast(bad_sig.data()), + bad_sig.size()})); + auto res = verifyEnvelope(env, keys); + Void::Testing::require(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(UpdateErrorCode::signature_failed)); + } + + // 2. Schema-3 envelope with VALID signature and mismatched display mirror + // fails with mirror_mismatch AFTER signature passes. + { + constexpr std::string_view signed_doc = R"json({"ok":1})json"; + const std::string env = std::format( + R"json({{"schemaVersion":3,"keyId":"k1","document":{{"ok":2}},"signedPayload":"{}","signature":"{}"}})json", + Void::Encoding::Base64::encode_url(signed_doc), + sign_b64url(signed_doc, *priv)); + auto res = verifyEnvelope(env, keys); + Void::Testing::require(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(UpdateErrorCode::mirror_mismatch)); + } + + // 3. Mutating whitespace of signed bytes breaks signature verification. + { + constexpr std::string_view signed_doc = R"json({"ok":1})json"; + constexpr std::string_view mutated_doc = R"json({ "ok": 1 })json"; + const std::string env = std::format( + R"json({{"schemaVersion":1,"keyId":"k1","payload":"{}","signature":"{}"}})json", + Void::Encoding::Base64::encode_url(mutated_doc), + sign_b64url(signed_doc, *priv)); + auto res = verifyEnvelope(env, keys); + Void::Testing::require(!res.has_value()); + Void::Testing::expect_eq( + res.error().code().value, + static_cast(UpdateErrorCode::signature_failed)); + } + + // 4. SchemaParsePolicy::StrictJsonProfile rejects duplicate keys and + // decimals while LegacyGeneralJson retains legacy acceptance. + { + constexpr std::string_view dup_payload = + R"json({"a":1,"a":2})json"; + const std::string env = make_envelope_v1("k1", dup_payload, *priv); + + VerificationPolicy legacy{}; + legacy.parsePolicy = SchemaParsePolicy::LegacyGeneralJson; + Void::Testing::expect(verifyEnvelope(env, keys, legacy).has_value()); + + VerificationPolicy strict{}; + strict.parsePolicy = SchemaParsePolicy::StrictJsonProfile; + auto strict_res = verifyEnvelope(env, keys, strict); + Void::Testing::require(!strict_res.has_value()); + Void::Testing::expect_eq( + strict_res.error().code().value, + static_cast(UpdateErrorCode::schema_error)); + } +} + +Void::Testing::Test update_replay_floor_and_trust_store_rotation_revocation() +{ + Void::FileSystem::TempDir tmp{"void_update_floor_"}; + const auto floor_path = tmp / "replay_floor.json"; + + // 1. Durable monotonic floor survives restart & rejects replay. + { + ReplayFloorStore store{floor_path}; + Void::Testing::require(store.load().has_value()); + Void::Testing::require(store.advance("vendor-main", "stable", 10).has_value()); + Void::Testing::expect_eq( + store.floor("vendor-main", "stable").value_or(0), 10ULL); + } + { + ReplayFloorStore reloaded{floor_path}; + Void::Testing::require(reloaded.load().has_value()); + Void::Testing::expect_eq( + reloaded.floor("vendor-main", "stable").value_or(0), 10ULL); + + auto replay = reloaded.advance("vendor-main", "stable", 9); + Void::Testing::require(!replay.has_value()); + Void::Testing::expect_eq( + replay.error().code().value, + static_cast(UpdateErrorCode::replay_rejected)); + Void::Testing::require( + reloaded.advance("vendor-main", "stable", 11).has_value()); + } + + // Corrupt floor file triggers RecoveryRequired (never resets to 0). + { + std::ofstream corrupt{floor_path, std::ios::binary | std::ios::trunc}; + corrupt << R"({"schemaVersion":1,"sha256":"0000","payload":"{}"})"; + } + { + ReplayFloorStore broken{floor_path}; + auto r = broken.load(); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(UpdateErrorCode::recovery_required)); + } + + // 2. TrustStore bootstrap, authenticated rotation, and revocation. + auto k1 = Void::Crypto::Ed25519PrivateKey::generate(); + auto k2 = Void::Crypto::Ed25519PrivateKey::generate(); + Void::Testing::require(k1.has_value() && k2.has_value()); + auto pub1 = k1->public_key(); + auto pub2 = k2->public_key(); + Void::Testing::require(pub1.has_value() && pub2.has_value()); + + TrustStore trust; + Void::Testing::require(trust.bootstrap({{"k1", pub1->bytes}}).has_value()); + + const std::string stmt = TrustStore::rotation_statement("k2", pub2->bytes); + auto rot_sig = Void::Crypto::sign_ed25519(as_bytes(stmt), *k1); + Void::Testing::require(rot_sig.has_value()); + + // Bad signature rejected. + auto bad_sig = *rot_sig; + bad_sig.bytes[0] ^= std::byte{0xFF}; + Void::Testing::expect(!trust + .rotate_key_authenticated("k2", pub2->bytes, + bad_sig.view(), "k1") + .has_value()); + + // Valid authenticated rotation succeeds. + Void::Testing::require( + trust + .rotate_key_authenticated("k2", pub2->bytes, rot_sig->view(), "k1") + .has_value()); + Void::Testing::expect(trust.snapshot().contains("k2")); + + // Revoking k1 removes it and forbids silent re-admission. + Void::Testing::require(trust.revoke_key("k1").has_value()); + Void::Testing::expect(trust.is_revoked("k1")); + Void::Testing::expect(!trust.snapshot().contains("k1")); + Void::Testing::expect( + !trust.rotate_key_operator("k1", pub1->bytes).has_value()); +} + +Void::Testing::Test update_coordinator_install_rollback_pins_cleanup_pending_and_reconcile() +{ + Void::FileSystem::TempDir tmp{"void_update_coord_"}; + const auto pkg_dir = tmp / "packages"; + const auto store_dir = tmp / "store"; + const auto floor_path = tmp / "floor.json"; + std::filesystem::create_directories(pkg_dir); + + auto priv = Void::Crypto::Ed25519PrivateKey::generate(); + Void::Testing::require(priv.has_value()); + auto pub = priv->public_key(); + Void::Testing::require(pub.has_value()); + Keyring keys{{"k1", pub->bytes}}; + + auto transport = std::make_shared(); + VersionStore vstore{store_dir}; + ReplayFloorStore floors{floor_path}; + Void::Testing::require(floors.load().has_value()); + + const SelectionRequest sel_req{ + .component = "service", + .artifactId = "main", + .channel = "stable", + .environment = {.platform = "linux", .architecture = "x86_64"}, + }; + + auto make_verified_pkg = [&](std::string_view ver, std::uint64_t seq) { + auto pkg = build_test_package(pkg_dir, ver); + const std::string url = + std::format("https://updates.invalid/service-{}.tar.zst", ver); + transport->map_url(url, pkg.path); + const std::string payload = + make_feed_payload(ver, seq, url, pkg.size, pkg.sha256); + const std::string env = make_envelope_v1("k1", payload, *priv); + auto sel = verify_and_select_release(env, keys, sel_req); + Void::Testing::require(sel.has_value()); + return *sel; + }; + + // 1. Install v1.0.0 cleanly (internal activation + 3 consecutive probes). + std::size_t probe_calls = 0; + bool fail_cleanup = false; + std::vector pinned; + LifecycleHooks hooks{ + .health_probe = [&](const Void::Semver::Version&, + const std::filesystem::path&) { + ++probe_calls; + return Void::Result::Result{true}; + }, + .live_pinned_versions = [&]() { return pinned; }, + .post_commit_cleanup_hook = [&]() -> Void::Result::Result { + if (fail_cleanup) { + return std::unexpected{make_update_error( + UpdateErrorCode::cleanup_pending, + "injected post-commit cleanup failure")}; + } + return {}; + }, + }; + + InstallCoordinator coord{vstore, floors, transport, hooks}; + Void::Time::ManualClock mono; + InstallOptions iopts{}; + iopts.health_probe_interval = std::chrono::milliseconds{0}; + iopts.consecutive_healthy_required = 3; + iopts.retained_previous_versions = 1; + iopts.monotonic_clock = &mono; + + auto sel_100 = make_verified_pkg("1.0.0", 1); + auto r1 = coord.install(sel_100, iopts); + Void::Testing::require(r1.has_value()); + Void::Testing::expect_eq(static_cast(r1->state), + static_cast(InstallState::HealthyCommitted)); + Void::Testing::expect_eq(probe_calls, 3U); + auto cur = vstore.currentVersion(); + Void::Testing::require(cur.has_value() && cur->has_value()); + Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"}); + + // 2. Truncated / bad-digest download fails before activation, leaving 1.0.0 + // active. + auto sel_110 = make_verified_pkg("1.1.0", 2); + transport->set_truncate_bytes(4); + auto bad_dl = coord.install(sel_110, iopts); + transport->set_truncate_bytes(std::nullopt); + Void::Testing::require(!bad_dl.has_value()); + Void::Testing::expect_eq( + bad_dl.error().code().value, + static_cast(UpdateErrorCode::size_mismatch)); + cur = vstore.currentVersion(); + Void::Testing::require(cur.has_value() && cur->has_value()); + Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"}); + + // 3. Unhealthy candidate rolls back cleanly via VersionStore. + bool stopped_candidate = false; + { + LifecycleHooks unhealthy_hooks{ + .health_probe = [](const Void::Semver::Version&, + const std::filesystem::path&) { + return Void::Result::Result{false}; + }, + .stop_candidate = [&](const Void::Semver::Version&) { + stopped_candidate = true; + }, + }; + InstallCoordinator bad_coord{vstore, floors, transport, unhealthy_hooks}; + auto rb = bad_coord.install(sel_110, iopts); + Void::Testing::require(rb.has_value()); + Void::Testing::expect_eq(static_cast(rb->state), + static_cast(InstallState::RolledBack)); + Void::Testing::expect(stopped_candidate); + cur = vstore.currentVersion(); + Void::Testing::require(cur.has_value() && cur->has_value()); + Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.0.0"}); + } + + // 4. Post-commit cleanup failure reports CleanupPending WITHOUT rolling + // back committed candidate, and retry_cleanup resolves it. + auto sel_120 = make_verified_pkg("1.2.0", 3); + fail_cleanup = true; + auto cp = coord.install(sel_120, iopts); + Void::Testing::require(cp.has_value()); + Void::Testing::expect_eq(static_cast(cp->state), + static_cast(InstallState::CleanupPending)); + Void::Testing::expect(cp->cleanup_retryable); + cur = vstore.currentVersion(); + Void::Testing::require(cur.has_value() && cur->has_value()); + Void::Testing::expect_eq((*cur)->to_string(), std::string{"1.2.0"}); + + // Reconcile is idempotent and preserves CleanupPending until retried. + auto rec1 = coord.reconcile(); + auto rec2 = coord.reconcile(); + Void::Testing::require(rec1.has_value() && rec2.has_value()); + Void::Testing::expect_eq(static_cast(rec1->state), + static_cast(InstallState::CleanupPending)); + Void::Testing::expect_eq(static_cast(rec2->state), + static_cast(InstallState::CleanupPending)); + + fail_cleanup = false; + auto retried = coord.retry_cleanup(iopts); + Void::Testing::require(retried.has_value()); + Void::Testing::expect_eq(static_cast(retried->state), + static_cast(InstallState::HealthyCommitted)); + + // 5. Pin-aware pruning protects pinned live generation 1.0.0 while pruning + // unpinned old versions. + auto v100 = Void::Semver::parse_strict("1.0.0"); + Void::Testing::require(v100.has_value()); + pinned = {*v100}; + auto sel_130 = make_verified_pkg("1.3.0", 4); + auto r3 = coord.install(sel_130, iopts); + Void::Testing::require(r3.has_value()); + Void::Testing::expect_eq(static_cast(r3->state), + static_cast(InstallState::HealthyCommitted)); + Void::Testing::expect(std::filesystem::exists(vstore.versionPath(*v100))); + + auto prune_rep = vstore.pruneWithPins(1, pinned, 16); + Void::Testing::require(prune_rep.has_value()); + Void::Testing::expect_eq(prune_rep->skipped_due_to_pins.size(), 1U); + Void::Testing::expect_eq(prune_rep->skipped_due_to_pins[0].to_string(), + std::string{"1.0.0"}); + + // 6. Corrupt operation journal halts reconcile with RecoveryRequired + // without deleting the journal file. + { + std::ofstream bad_j{coord.operation_journal_path(), + std::ios::binary | std::ios::trunc}; + bad_j << R"({"schemaVersion":99,"sha256":"dead","payload":"{}"})"; + } + auto rec_err = coord.reconcile(); + Void::Testing::require(!rec_err.has_value()); + Void::Testing::expect_eq( + rec_err.error().code().value, + static_cast(UpdateErrorCode::recovery_required)); + Void::Testing::expect( + std::filesystem::exists(coord.operation_journal_path())); +}