--- title: '2.1 — Безопасно сохранять загруженный OpenAPI source' type: 'feature' created: '2026-08-25' status: 'superseded' baseline_revision: '182bde8ac0709709be849f5ab51d2ce02aa5410b' baseline_commit: '182bde8ac0709709be849f5ab51d2ce02aa5410b' review_loop_iteration: 0 followup_review_recommended: false context: - '_bmad-output/implementation-artifacts/epic-2-context.md' warnings: [oversized, superseded-by-split] deferred: [] --- > Историческая спецификация остановленной попытки. После timeout и проверки scope заменена Stories 2.1a–2.1d; не использовать как вход для нового запуска. ## Intent **Problem:** Текущий OpenAPI preview принимает неограниченную JSON-строку, сразу парсит её и не сохраняет исходные bytes. Поэтому preview и последующий import не имеют общего immutable source, а upload, целостность, isolation и recovery не защищены. **Approach:** Добавить самостоятельный `crank-artifacts` с content-addressed immutable storage, PostgreSQL metadata и reconciliation; перевести Admin API/UI на bounded multipart upload, после сохранения читать source только с проверкой digest и лишь затем передавать parser’у. ## Boundaries & Constraints **Always:** принимать один UTF-8 файл `.yaml`/`.yml`/`.json` размером не более 256 KiB; определять путь только из opaque SHA-256 ref; выполнять temp write → file fsync → atomic no-clobber publish → directory fsync; разделять физическую дедупликацию и workspace-scoped metadata; не возвращать и не логировать raw source, реальные пути или cross-scope existence; проверять digest при каждом read; сохранять compatibility read только для absolute `file://` под явно configured legacy root. **Block If:** безопасная реализация требует platform contract за пределами Linux reference deployment либо существующая migration authority не позволяет добавить forward-only v12 без изменения уже применённых миграций. **Never:** не менять и не откатывать `sprint-status.yaml`; не создавать Draft Operations в story 2.1; не использовать filename/document path для filesystem path; не принимать `file://` при новом upload; не следовать symlink; не перечитывать mutable external source; не включать raw bytes/examples/descriptions в ошибки, logs, traces, metrics или browser telemetry; не переписывать legacy ref и не удалять legacy file до успешной verification. ## I/O & Edge-Case Matrix | Scenario | Input / State | Expected Output / Behavior | Error Handling | |----------|--------------|---------------------------|----------------| | Valid upload | Один multipart file, supported name/MIME, UTF-8, 1..262144 bytes | Opaque artifact ref и bounded safe metadata; bytes durable; parser получает verified bytes | No error expected | | Invalid upload | Empty, oversized, malformed multipart, unsupported extension/MIME/encoding | Ни metadata, ни Draft, ни final artifact | Stable localized 400/413 code + Request/Trace ID, без source/parser text | | Duplicate/race | Одинаковые bytes в одном или разных workspace, конкурентные writers | Один immutable blob, независимые scoped metadata; чужой scope неразличим | Idempotent success без existence oracle | | Integrity failure | Metadata есть, blob missing/corrupt | Parsing не запускается | Typed integrity error, без fallback | | Recovery | Orphan старше grace period либо concurrent referenced blob | Удаляется только подтверждённый orphan; referenced blob сохраняется | Bounded sweep report | | Hostile/legacy path | Traversal, symlink, absolute path; либо existing legacy `file://` | New refs rejected; legacy read только под configured root и с digest verification | Typed path/integrity error; source не меняется | ## Code Map - `Cargo.toml` — workspace members/dependencies; зарегистрировать новый `crank-artifacts`. - `crates/crank-artifacts/src/lib.rs` — новый pure filesystem boundary: opaque refs, bounded atomic writes, verified reads, legacy-root compatibility и orphan sweep; fault-injection/clock seams нужны recovery tests. - `crates/crank-artifacts/tests/` — known-digest, concurrent dedupe, crash/disk-full, corruption, traversal/symlink, legacy и sweep tests. - `crates/crank-registry/src/migrations/authority.rs:18` и новый `artifact_sources_v12.{rs,sql}`/`schema_guard_v12.rs` — forward-only metadata schema и migration contract; прошлые migration sources read-only. - `crates/crank-registry/src/model.rs`, `src/postgres/artifact_source.rs`, `src/postgres/mod.rs`, `src/lib.rs` — typed metadata/repository API с workspace-scoped lookup и safe sweep claim/delete. - `apps/admin-api/src/service.rs:52` и `src/storage.rs:9` — подключить artifact store к `AdminService`; существующий sample `file://` path не расширять на OpenAPI. - `apps/admin-api/src/routes/imports.rs:25`, `src/app.rs:51`, `src/dto.rs:527` — заменить preview upload на bounded multipart contract и stable localized outcomes. - `apps/admin-api/src/service/imports.rs:32` — upload → durable bytes → metadata commit → verified read → parser; сохранить artifact identity в import job и не создавать Operations. - `apps/admin-api/src/error.rs:39` — переиспользовать 413/envelope, добавить bounded artifact error mapping без IO/path/parser details. - `apps/ui/js/api.js:412`, `apps/ui/js/openapi-import.js:342`, `apps/ui/index.html:395` — отправлять `FormData`, реализовать RU/EN idle/validating/uploading/error/success/cancel и monotonic request token/abort против stale response. - `apps/admin-api/tests/integration/openapi_source.rs`, `crates/crank-registry/tests/integration/`, `apps/ui/tests/e2e/operations.spec.js` — outer-surface regression matrix; текущие JSON preview tests обновить без ослабления apply assertions. ## Tasks & Acceptance **Execution:** - `crates/crank-artifacts/**`, `Cargo.toml`, `Cargo.lock` — реализовать bounded content-addressed store и exhaustive negative/recovery tests — изолировать filesystem security/durability от Admin API. - `crates/crank-registry/src/{migrations,postgres,model.rs,lib.rs}` — добавить v12 metadata (`workspace`, digest/ref, size, MIME, sensitivity, lifecycle, timestamps), scoped CRUD и sweep coordination — сделать ownership и recovery транзакционными. - `apps/admin-api/src/{app.rs,dto.rs,error.rs,routes/imports.rs,service.rs,service/imports.rs}` — внедрить multipart upload, stable errors, metadata commit и verified source read до parsing — обеспечить единые bytes preview/import. - `apps/ui/{index.html,js/api.js,js/openapi-import.js}` — заменить textarea transport на file upload и локализованные race-safe состояния — покрыть пользовательскую поверхность AC. - `apps/admin-api/tests/integration/openapi_source.rs`, `apps/admin-api/tests/integration/openapi_import.rs`, `crates/crank-registry/tests/integration/**`, `apps/ui/tests/e2e/operations.spec.js` — проверить всю матрицу, restart durability, scope isolation и отсутствие source canary в diagnostics. - `docs/admin-api.md`, `docs/runtime-config.md`, `docs/openapi-import.md` — зафиксировать multipart/bounds, opaque ref, lifecycle/sweeper и legacy-root compatibility contract. **Acceptance Criteria:** - Given authenticated Admin API, when `.yaml`/`.yml`/`.json` загружается multipart, then validation filename/MIME/size/UTF-8 происходит до parsing, invalid inputs дают stable RU/EN error и не создают artifact metadata, import job или Draft. - Given valid bytes, when upload завершается и сервис перезапускается, then SHA-256 ref, fsync/atomic persistence и workspace metadata сохраняются, а verified read возвращает byte-identical source. - Given duplicate/concurrent uploads and two workspaces, when refs читаются/listed, then physical bytes deduplicated, scoped metadata independent, а foreign ref выглядит как обычный not-found без утечки свойств. - Given crash windows, corruption, disk-full and orphan sweep, when recovery runs after grace period, then only confirmed unreferenced blobs удаляются, referenced/concurrently-committed blobs survive, and missing/corrupt bytes block parsing with typed integrity error. - Given traversal, symlink, absolute/file URL inputs and legacy refs, when storage reads/writes/deletes, then operations remain under roots; new file URLs are rejected; verified legacy reads preserve original ref/file. - Given source canary and UI file replacement/cancel/racing responses, when upload succeeds or fails, then raw canary is absent from telemetry/DOM diagnostics, RU/EN state is correct, and stale response cannot replace the newest file state. ## Spec Change Log ## Review Triage Log ### Review Findings — 2026-08-28, aggregate Story 2.1 review - [x] [Review][Patch][high] Подготовить private artifact root в reference Docker deployment: новый named volume сейчас имеет mode `0755`, а `ArtifactStore::open` требует ровно `0700`, поэтому чистая Community-установка не стартует [apps/admin-api/Dockerfile:17] - [x] [Review][Patch][high] Сделать cleanup expired import jobs и dangling sources исчерпывающим и периодическим: одна пачка `128` при startup/preview/apply оставляет backlog и не обслуживает тихий долгоживущий процесс [crates/crank-registry/src/postgres/import_job.rs:146] - [x] [Review][Patch][high] Изолировать повреждённые `preview_payload.source`: одна malformed row не должна откатывать всю cleanup-транзакцию и блокировать startup/новые imports [crates/crank-registry/src/postgres/import_job.rs:163] - [x] [Review][Patch][high] Устранить race `Pending`/concurrent apply: запрос, прочитавший старый Pending, должен получить canonical replay завершённой job, а не `source_unavailable` [apps/admin-api/src/service/imports.rs:179] - [x] [Review][Patch][high] Зафиксировать parser contract между preview и apply: rolling upgrade не должен молча применить иной набор операций или пропустить выбранные keys после повторного parse [apps/admin-api/src/service/imports.rs:203] - [x] [Review][Patch][high] Сделать отмену/закрытие UI во время mutating apply outcome-aware: browser abort не отменяет серверный commit и не должен терять job authority либо провоцировать duplicate renamed drafts [apps/ui/js/openapi-import.js:442] - [x] [Review][Patch][medium] Подключить production cleanup stale temp files с bounded continuation, чтобы crash leftovers не накапливались и ранние shards не создавали starvation [crates/crank-artifacts/src/housekeeping.rs:321] - [x] [Review][Patch][medium] Сделать аварийный detach source надёжным при cancellation/shutdown вместо fire-and-forget `Drop`, результат которого теряется [apps/admin-api/src/service/imports.rs:420] - [x] [Review][Patch][medium] Добавить bounded deadlines для startup/periodic reconciliation и parsing, чтобы зависший DB/FS/parser вызов не блокировал startup либо worker навсегда [apps/admin-api/src/reconciliation.rs:729] - [x] [Review][Patch][medium] Перенести `ArtifactStore::clone`/FD duplication внутрь `spawn_blocking`, соблюдая контракт отсутствия filesystem syscalls на async executor [apps/admin-api/src/reconciliation.rs:248] - [x] [Review][Patch][medium] Нормализовать MIME через parsed essence перед validation и persistence; корректные типы с parameters/case не должны расходиться между route и service [apps/admin-api/src/routes/imports.rs:71] - [x] [Review][Patch][medium] Учитывать quality weights/order в `Accept-Language` и передавать locale в create/apply API, включая reparse и diagnostics [apps/admin-api/src/routes/imports.rs:125] - [x] [Review][Patch][medium] Сохранять unknown-operation skips в canonical `ImportJobApplyResult`, чтобы idempotent replay был идентичен первому ответу [apps/admin-api/src/service/imports.rs:211] - [x] [Review][Patch][medium] Добавить `operation_key` в created response и сопоставлять UI result с preview по стабильному key, а не по имени после rename [apps/admin-api/src/service/imports.rs:272] - [x] [Review][Patch][medium] Отделить успешный server commit от ошибки `onImported()`/refresh, чтобы UI не сообщал о неуспешном создании уже созданных drafts [apps/ui/js/openapi-import.js:719] - [x] [Review][Patch][medium] Устранить противоречие `Specify later`/обязательный Base URL и очищать server selection при `pagehide` согласно UX contract [apps/ui/js/openapi-import.js:273] - [x] [Review][Patch][medium] Расширить readiness проверкой доступности artifact subsystem, а не только PostgreSQL [apps/admin-api/src/service.rs:127] - [x] [Review][Patch][medium] Добавить индексы для expired jobs, JSON source lookup, expired claims и reconciliation/source lookup через новую forward-only migration [crates/crank-registry/src/migrations/artifact_metadata_v12.sql:60] - [x] [Review][Patch][medium] Исправить idempotency detach с `expected_updated_at: None`: точный replay уже выполненного unconditional detach не должен конфликтовать [crates/crank-registry/src/postgres/artifact_source.rs:504] - [x] [Review][Patch][medium] Изолировать process-global fault seams/counters, чтобы обычный default-parallel `crank-artifacts` test run был стабильным, а CI не скрывал гонку `--test-threads=1` [crates/crank-artifacts/tests/reconciliation.rs:1] - [x] [Review][Patch][medium] Убрать календарную зависимость из claim-revival regression test и использовать согласованный database clock [crates/crank-registry/tests/integration/artifact_reconciliation.rs:1] - [x] [Review][Patch][medium] Усилить fail-closed evidence validator: `accepted=true` допустим только для automated/pass evidence, а не произвольного schema-valid кандидата [scripts/validate-capability-run.py:125] - [x] [Review][Patch][medium] Добавить изолированный lifecycle regression для `no_methods`, проверяющий отсутствие active source, а не наличие любого detached source после нескольких ошибок [apps/admin-api/tests/integration/openapi_source.rs:350] - [x] [Review][Patch][medium] Проверять смену языка реальным `window.setLang()`/`crank:langchange`, а не только вручную созданным `StorageEvent` [apps/ui/tests/e2e/operations.spec.js:449] - [x] [Review][Patch][medium] Добавить process-level startup test, который доказывает вызов immediate reconciliation и lifecycle cleanup из реальной composition root [apps/admin-api/src/main.rs:206] ### Дополнительный независимый проход — 2026-08-29 - [x] [Review][Patch][high] Сохранять authority mutating apply в `sessionStorage` и восстанавливать ту же job после close/pagehide/reload, блокируя изменение inputs до canonical replay. - [x] [Review][Patch][medium] Сделать V13 schema guard точным для всех пяти cleanup/reconciliation indexes, включая key order, predicate, uniqueness и validity/readiness. - [x] [Review][Patch][medium] Ограничить одновременно живущие blocking parser tasks глобальным semaphore и общим 30-секундным deadline. - [x] [Review][Patch][medium] Продолжать stale-temp scan за omitted entry и исчерпывать страницы в пределах bounded deadline без starvation. - [x] [Review][Patch][medium] Ограничить все три startup maintenance phase одним внешним 30-секундным deadline. - [x] [Review][Patch][medium] Считать HTTP 4xx, кроме 408, definitive apply outcome: очищать replay authority и разблокировать UI. - [x] [Review][Dismissed][medium] Не восстанавливать прежний публичный Rust-конструктор с owned `ArtifactStore`: Community API ещё pre-release, а `Arc` исключает FD duplication и blocking syscall на async executor; breaking cleanup ранее явно принят владельцем продукта. ## Design Notes Physical blob identity is global SHA-256, but authorization is exclusively a PostgreSQL workspace metadata relation. Sweeper uses a two-phase candidate/recheck protocol after grace period; deletion never follows caller paths. Import jobs refer to the scoped source metadata id plus digest, so subsequent stories can reverify the same bytes without embedding source in preview JSON. ## Verification **Commands:** - `cargo test -p crank-artifacts` — all storage failure/race/path tests pass. - `cargo test -p crank-registry --test integration -- --test-threads=1` — v12 metadata, isolation and migration tests pass. - `cargo test -p admin-api --test integration -- --test-threads=1` — multipart and preview integration tests pass. - `cd apps/ui && npm run e2e -- operations.spec.js` — RU/EN upload states and stale-response tests pass. - `just verify` — full Rust/config/migration/lint/test gate passes. - `just verify-ui` — production UI bundle builds. ### Aggregate review verification — 2026-08-29 - `cargo check -p crank-artifacts -p crank-registry -p admin-api --all-targets` — pass. - `cargo clippy -p crank-artifacts -p crank-registry -p admin-api --all-targets -- -D warnings` — pass. - `cargo test -p crank-artifacts --all-targets` — 57 tests pass при default parallelism. - `cargo test -p crank-registry --test integration -- --test-threads=1` — 82 pass, 1 documented production-scale query-plan test ignored. - `cargo test -p admin-api --lib` — 37 pass; `config_startup` — 6 pass; Admin integration — 66 pass. - `npm run build`, OpenAPI Playwright E2E и `python3 -m unittest tests.unit.test_validate_capability_run` — pass. - `docker buildx build --load -f apps/admin-api/Dockerfile -t crank/admin-api:story-2-1-review .` — pass; fresh named volume provisioned as `0700`, relative storage root rejected with exit 64. - `cargo fmt --all -- --check`, `git diff --check`, JS/shell syntax и все три `docker compose config` — pass. **Verdict:** все подтверждённые high/medium findings устранены; Story 2.1 и её части 2.1a–2.1d приняты. Один compatibility warning отклонён как осознанный pre-release API cleanup. Production-scale million-row query-plan evidence остаётся отдельным тяжёлым CI/release gate, а не блокером корректности Story.