--- title: '2.1 — Реализовать безопасное immutable artifact storage' type: 'feature' created: '2026-08-25' status: 'done' baseline_revision: '182bde8ac0709709be849f5ab51d2ce02aa5410b' review_loop_iteration: 1 followup_review_recommended: false context: - '_bmad-output/implementation-artifacts/epic-2-context.md' - '_bmad-output/planning-artifacts/architecture/architecture-crank-2026-08-03/ARCHITECTURE-SPINE.md' warnings: [oversized] deferred: [] --- ## Intent **Problem:** Загруженные bytes пока не имеют отдельной immutable filesystem boundary: существующий `LocalArtifactStorage` формирует mutable `file://` paths и не защищает source от подмены, corruption и path races. **Approach:** Добавить leaf-crate `crank-artifacts`, который хранит bounded bytes по opaque SHA-256 reference, публикует их атомарно и durable, проверяет digest при каждом чтении и предоставляет только безопасные низкоуровневые housekeeping/legacy-read primitives. ## Boundaries & Constraints **Always:** считать authority открытый directory FD, а не `PathBuf`; выполнять blob I/O относительно закреплённых root/shard FDs без следования symlink; использовать private same-directory temp, file fsync, atomic no-clobber publish и directory fsync; проверять размер до/во время записи и digest до возврата; возвращать bounded typed errors без raw bytes, caller path или IO details; оставлять crate независимым от workspace crates. **Block If:** Linux reference deployment не предоставляет безопасный no-clobber/dirfd contract (`openat2`/`renameat2`) и его нельзя реализовать без ослабляющего fallback; требования вынуждают принять policy о registry ownership/orphan status внутри filesystem crate. **Never:** не менять `sprint-status.yaml`; не добавлять PostgreSQL metadata, workspace ownership, reconciliation policy, Admin API, multipart/parser flow, UI или deployment configuration; не принимать filename/path/new `file://` как physical reference; не расширять path-based `apps/admin-api/src/storage.rs`; не cherry-pick исторический WIP без устранения его TOCTOU и recovery gaps. ## I/O & Edge-Case Matrix | Scenario | Input / State | Expected Output / Behavior | Error Handling | |----------|--------------|---------------------------|----------------| | Store/read | Bounded bytes | `sha256:<64 lowercase hex>`, durable single blob, byte-identical verified read | No error expected | | Duplicate race | Повторные/конкурентные одинаковые bytes | Один immutable blob; каждый caller получает тот же ref | Existing blob отдельно verified; mismatch — integrity error | | Invalid or damaged | Empty/oversized input, malformed ref, missing/truncated/corrupt/non-regular blob | Никаких partial final blobs и непроверенных bytes | Stable typed size/reference/integrity/storage error без path/source | | Hostile filesystem | Traversal, absolute path, symlink или configured-root replacement | I/O остаётся внутри pinned root и не затрагивает replacement target | Fail closed typed unsafe-root/reference error | | Interrupted write | Disk-full/fault до или после publish; fresh/stale temp | Final blob полностью опубликован либо отсутствует; retry безопасен; cleanup bounded | Temp распознаётся по внутреннему формату; referenced policy не принимается | | Legacy read | Explicit legacy root, absolute `file://`, expected digest | Только fd-relative read внутри pinned root; original ref/file не меняется | Escape/symlink/wrong digest/disabled reader отклоняются | ## Code Map - `Cargo.toml:1-55` — зарегистрировать workspace member и общие `rustix`/test dependencies; сохранить Rust 2024 / 1.96 conventions. - `crates/crank-artifacts/Cargo.toml` — новый leaf manifest; production dependencies только для Linux filesystem boundary, hashing, URL parsing и typed errors. - `crates/crank-artifacts/src/lib.rs` — минимальный public API и точечные re-exports по conventions `crank-schema`/`crank-mapping`. - `crates/crank-artifacts/src/model.rs` — strict `ArtifactRef`, limits, candidate/temp value types; ref принимает только canonical lowercase SHA-256 form. - `crates/crank-artifacts/src/error.rs` — path-free typed public errors без transparent IO sources. - `crates/crank-artifacts/src/store.rs` — bounded write, verified read, pinned-FD layout `sha256/<2>/`, dedupe и fault/recovery seams. - `crates/crank-artifacts/src/housekeeping.rs` — streaming scan с отдельными scan/result budgets; stale-temp capability привязана к root и inode, а cooperative root lock исключает live/replacement/cross-store deletion races. - `crates/crank-artifacts/src/legacy.rs` — opt-in digest-verified `file://` compatibility read внутри pinned legacy root; никакого rewrite/delete. - `crates/crank-artifacts/tests/` — filesystem/security/recovery matrix; tests используют isolated temp roots, реальный fork/abrupt-exit на syscall checkpoints и проверяют отсутствие outside-root effects. - `scripts/check-rust-boundaries.py:31-140` и `tests/unit/test_check_rust_boundaries.py` — закрепить `crank-artifacts` как leaf category, запрещённую от workspace dependencies. - `apps/admin-api/src/storage.rs:9-84` — read-only evidence: существующий path-based sample store не переиспользовать и не менять в 2.1. - `_bmad-output/implementation-artifacts/spec-2-1-openapi-source.md` — read-only superseded audit artifact; не использовать как active scope. ## Tasks & Acceptance **Execution:** - `Cargo.toml`, `Cargo.lock`, `crates/crank-artifacts/Cargo.toml` — зарегистрировать изолированный crate и минимальные pinned capabilities — сделать boundary сборочной и воспроизводимой. - `crates/crank-artifacts/src/{lib.rs,model.rs,error.rs,store.rs}` — реализовать strict refs, fd-anchored durable CAS, trusted-owner/inode invariants, корректную errno classification и syscall-coupled fault checkpoints — закрыть integrity, no-clobber и root-race contract. - `crates/crank-artifacts/src/{housekeeping.rs,legacy.rs}` — реализовать streaming bounded primitives с cooperative lock/capability revalidation и opt-in legacy reader — поддержать recovery/migration без ownership policy, live-temp deletion или mutable paths. - `crates/crank-artifacts/tests/**` — покрыть всю I/O matrix, concurrency и fault windows — доказать outer filesystem behavior, а не внутренние proxy. - `scripts/check-rust-boundaries.py`, `tests/unit/test_check_rust_boundaries.py` — запретить production workspace dependencies у `crank-artifacts` — сохранить hexagonal leaf invariant. **Acceptance Criteria:** - Given bounded source bytes, when несколько writers сохраняют их одновременно, then все получают один canonical SHA-256 ref, final blob публикуется no-clobber после file fsync и shard directory fsync, а повторный read возвращает только digest-verified bytes. - Given missing, truncated, corrupt, symlink или non-regular blob, when caller читает canonical ref, then bytes не возвращаются и typed diagnostics не раскрывает source, filesystem path или low-level IO detail. - Given traversal/path/file-URL input либо symlink/root-replacement race, when выполняется write/read/list/delete, then операция остаётся fd-anchored внутри исходного configured root и outside/replacement target не затрагивается. - Given configured root или existing final blob, when store открывает authority либо принимает deduplicated blob, then root принадлежит effective service identity и не writable для group/world, а final — owned regular single-link inode без write bits и с verified digest; иначе операция fail closed. - Given disk-full seam или abrupt child-process exit на write/file-fsync/publish/directory-fsync checkpoints, when store открывается в новом process и retry выполняется, then final blob целиком verified либо отсутствует, syscall checkpoints нельзя сохранить при удалении соответствующего sync/publish operation. - Given live, fresh, stale, replaced или cross-store temp и каталог с произвольным числом entries, when housekeeping получает scan/result budgets и удаляет candidate, then scan аллоцирует/просматривает не больше budget, live/replaced/foreign candidate не удаляется, successful unlink fsync-ится, а registry ownership policy не принимается. - Given explicit legacy root и expected digest, when читается legacy absolute `file://`, then только contained regular file возвращается после digest verification, а escape/symlink/mismatch отклоняются без rewrite/delete. - Given public parsing/streaming/limits API, when canonical ref round-trips, reader отдаёт short chunks/`Interrupted`, либо payload/legacy file равен exact maximum, then полный digest/bytes сохраняются; overflow limits отклоняются и operational IO не маскируется как integrity. - Given изменённый workspace, when запускаются crate tests и boundary/format/lint gates, then exhaustive artifact suite проходит и executable rule отклоняет production workspace dependency из `crank-artifacts`, не запрещая dev-only test support. ## Spec Change Log ### 2026-08-25 — Review repair loop 1 - Trigger: review обнаружил, что общие слова `bounded`, `immutable`, `safe stale temp` и `fault seams` допускают unbounded `readdir`, trusted-root/inode gaps, live/replacement/cross-root temp deletion и in-process-only crash proxy. - Amended: Code Map, Execution, AC и Design Notes теперь требуют streaming scan/result budgets; euid/root и final inode invariants; cooperative root lock плюс root/inode/age revalidation; process-unique temp nonce; errno-aware operations; syscall-coupled fork/abrupt-exit/disk-full evidence и точные public API boundary tests. - Avoids: green tests при удалённых fsync, partial-success `readdir`, cleanup активного/reused temp, принятие writable/hard-linked final, untrusted root и ошибки на exact max/short reads. - KEEP: pinned directory FDs как authority; strict lowercase SHA-256 refs; same-shard private temp; `renameat2(RENAME_NOREPLACE)` без fallback; file/directory fsync; verified reads; path/source-free typed errors; legacy no-rewrite/no-delete; leaf-crate и separation от registry policy. ## Review Triage Log ### 2026-08-25 — Review pass - intent_gap: 0 - bad_spec: 0 - patch: 15: (high 8, medium 5, low 2) - defer: 0 - reject: 3: (high 0, medium 3, low 0) - addressed_findings: - `[high]` `[patch]` `RootLock` переведён на independently-opened directory FD; regression без `clone` доказывает, что cleanup не удаляет live temp. - `[high]` `[patch]` Все преобразования FD в `File` используют checked `F_DUPFD_CLOEXEC` и возвращают `Storage` при отказе duplicate. - `[high]` `[patch]` Verified и legacy reads ограничены фактическим `MAX_ARTIFACT_BYTES + 1`, поэтому рост файла не создаёт unbounded allocation. - `[high]` `[patch]` Создание `sha256` и shard namespace edges теперь fsync-ит parent directory и покрыто fault-checkpoint regression для обоих уровней. - `[high]` `[patch]` Housekeeping обходит только canonical `00..ff` shards и расходует `scan_budget` только на их entries без лишнего `readdir` после exhaustion. - `[high]` `[patch]` Ошибки `readdir`, открытия canonical shard и `fstatat` больше не маскируются как успешный неполный scan. - `[high]` `[patch]` Stale capability сохраняет и повторно проверяет seconds+nanos mtime и subsecond grace перед unlink. - `[high]` `[patch]` Crash/fault test state сериализован, а default-parallel crate suite повторно проходит без checkpoint races. - `[medium]` `[patch]` `result_limit` применяется после stale validation; `omitted` считает только подтверждённые stale candidates, включая limits 1 и 0. - `[medium]` `[patch]` Relative legacy root теперь отклоняется fail closed вместо несовместимого сравнения с absolute `file://`. - `[medium]` `[patch]` Integration test fault hooks закрыты `debug_assertions`; release test build компилируется без production export hooks. - `[medium]` `[patch]` Oversized legacy file `MAX_ARTIFACT_BYTES + 1` явно отклоняется regression test. - `[medium]` `[patch]` Non-regular directory на final digest явно возвращает integrity failure. - `[low]` `[patch]` Каноничность ref закреплена отдельной проверкой 64 lowercase против same-length uppercase digest. - `[low]` `[patch]` Неиспользуемая production dependency `rustix` удалена из crate, workspace и lockfile. ### 2026-08-25 — Review pass - intent_gap: 0 - bad_spec: 6: (high 5, medium 1, low 0) - patch: 12: (high 0, medium 6, low 6) - defer: 0 - reject: 0 - addressed_findings: - `[high]` `[bad_spec]` Закреплены trusted euid ownership/mode требования к root и созданным directories. - `[high]` `[bad_spec]` Закреплены owner/regular/single-link/read-only/digest invariants для existing final blob. - `[high]` `[bad_spec]` Stale-temp cleanup получил root/inode/age capability revalidation и cooperative lock против live/replacement/cross-store races. - `[high]` `[bad_spec]` Housekeeping обязан stream-ить каталог и соблюдать отдельные scan/result budgets вместо полного `Vec`. - `[high]` `[bad_spec]` Crash/disk-full verification перенесена на abrupt child-process и syscall-coupled checkpoints, а не только in-process return hooks. - `[medium]` `[bad_spec]` Temp naming требует process-unique random nonce, чтобы crash/PID reuse не исчерпывали фиксированное окно имён. ## Design Notes Pinned directory FDs являются authority на весь lifetime store. Path root нужен только для безопасного initial open; root/created directories проверяются на euid ownership и private mode. После открытия operations используют `*at`/`openat2` с no-symlink constraints. Temp получает random process nonce, держит shared cooperative root lock до publish и находится с final в одном shard; cleanup берёт exclusive lock и повторно проверяет root identity, inode и age перед unlink+fsync. Existing final принимается только как owned, regular, single-link, non-writable inode с верным digest. Publish не имеет replacing fallback; retry после rename повторно verified-read и directory fsync. Listing stream-ит не более `scan_budget` entries и возвращает не более `result_limit`. Test checkpoints оборачивают реальные write/fsync/rename operations; forked child завершается через `_exit`, parent открывает новый store. Решение «orphan или referenced» остаётся в Story 2.2. ## Verification **Commands:** - `cargo test -p crank-artifacts` — весь filesystem/security/recovery contract проходит. - `cargo clippy -p crank-artifacts --all-targets --all-features -- -D warnings` — crate без lint warnings. - `python3 -m unittest tests.unit.test_check_rust_boundaries` — leaf boundary regression проходит. - `cargo fmt --all --check && just rust-boundaries && just rust-code-health` — workspace conventions и executable architecture проходят. - `just verify` — полный workspace regression gate проходит. ## Completion Evidence ### 2026-08-25 — Независимое follow-up review и закрытие - Три независимых слоя проверили полный tracked/untracked diff: blind hunter, edge-case hunter и verification-gap reviewer. - Исправлены production gaps: dev-only boundary semantics, blocking FIFO opens, user-reader self-deadlock, namespace fsync retry, pre-syscall fault injection, disappearing-temp race, single-use cleanup capability, future mtime и lexical legacy root. - Усилена evidence matrix: same-size corruption, digest-matching symlinks, exact maximum round-trip, positive grace, initial-root symlink, multi-process dedupe и bounded child-process FIFO scenarios. - `cargo test -p crank-artifacts -- --test-threads=1` — 28/28 тестов прошли. - Targeted format/clippy/release/boundary/code-health gates прошли без ошибок; Python boundary suite — 16/16. - Полный `just verify` прошёл до конца: workspace clippy и все non-ignored workspace tests зелёные. - Финальный post-fix security audit не нашёл high/medium блокеров. ## Suggested Review Order **Storage authority и durable publish** - Public boundary закрепляет root FD, bounded ingress и verified reads. [`store.rs:71`](../../crates/crank-artifacts/src/store.rs#L71) - Publication связывает fault semantics с write/fsync/no-clobber namespace operations. [`store.rs:209`](../../crates/crank-artifacts/src/store.rs#L209) - Canonical opaque reference исключает filesystem path из public contract. [`model.rs:12`](../../crates/crank-artifacts/src/model.rs#L12) **Recovery и compatibility** - Single-use stale capability повторно проверяется под exclusive root lock. [`housekeeping.rs:11`](../../crates/crank-artifacts/src/housekeeping.rs#L11) - Legacy `file://` остаётся digest-verified и привязанным к pinned root. [`store.rs:168`](../../crates/crank-artifacts/src/store.rs#L168) **Architecture и доказательства** - Executable boundary разрешает test-only support, сохраняя production leaf invariant. [`check-rust-boundaries.py:91`](../../scripts/check-rust-boundaries.py#L91) - Filesystem matrix покрывает process races, crash recovery, corruption и blocking entries. [`artifact_store.rs:65`](../../crates/crank-artifacts/tests/artifact_store.rs#L65) - Boundary regressions различают dev, build и mixed dependency declarations. [`test_check_rust_boundaries.py:203`](../../tests/unit/test_check_rust_boundaries.py#L203)