Files
crank/_bmad-output/implementation-artifacts/spec-2-5-openapi-upload-preview.md
T

7.5 KiB
Raw Blame History

title, type, created, status, baseline_commit, review_loop_iteration, context
title type created status baseline_commit review_loop_iteration context
2.5 — Ввести bounded multipart upload и verified OpenAPI preview feature 2026-08-28 done d2849ea3fe 0
_bmad-output/implementation-artifacts/epic-2-context.md

Intent

Problem: Production endpoint всё ещё принимает raw OpenAPI внутри JSON, доверяет сохранённому preview JSON при apply и не связывает import job с immutable workspace-scoped source. Это допускает unbounded/непроверенный ingress, TOCTOU и потерю source provenance.

Approach: Заменить production preview contract на один bounded multipart-файл и провести его через durable put → scoped source metadata → verified read → parser → import job; apply заново читает и парсит тот же source, а ошибки и expiry компенсируются только lifecycle detach/reconciliation.

Boundaries & Constraints

Always: auth/workspace/CSRF и вся multipart-форма валидируются до publish; ровно один file .yaml|.yml|.json, UTF-8, 1..256 KiB; YAML принимает application/yaml|x-yaml, text/yaml|x-yaml или application/octet-stream, JSON — application/json|openapi+json или octet-stream; blocking storage/parser идут вне async executor; source ID/digest хранятся в bounded job envelope; Accept-Language: ru* выбирает RU, иначе EN; ошибки содержат canonical Request ID/Trace ID без source.

Ask First: новая migration; изменение artifact root/permissions или reconciliation lifecycle; раскрытие digest, source ID, parser detail либо filename в публичной диагностике/telemetry; изменение create/apply conflict semantics.

Never: UI/E2E/docs из Story 2.6; NormalizedIR/support expansion из 2.7+; external $ref; Draft/Operation mutation во время preview; прямое удаление blob; production fallback на JSON {document} или построение Draft только из сохранённого preview JSON.

I/O & Edge-Case Matrix

Scenario Input / State Expected Output / Behavior Error Handling
Valid upload Один YAML/JSON file, ≤256 KiB, ≥1 method Durable source, verified parse, pending job и bounded preview 200 с job ID/expiry/preview без raw bytes/digest/source ID
Boundary reject Empty/oversized, malformed/duplicate/unknown part, bad name/MIME/UTF-8 Ни source metadata, ни job, ни Draft Stable 4xx/413 RU/EN envelope
Parse/failure/cancel Unsupported/no-methods либо storage/registry/parser/job failure Нет job/Draft; опубликованный blob остаётся orphan либо relation detach Safe code; lifecycle/reconciliation owns cleanup
Reuse/apply Job source foreign, detached, missing, corrupt или digest mismatch Preview JSON не считается authority; Draft не создаётся Stable not-found/integrity/unavailable outcome

Code Map

  • apps/admin-api/src/{app.rs,routes/imports.rs,dto.rs,error.rs} — текущий JSON route; добавить Axum multipart, envelope overhead limit и safe localized rejection mapping; reuse request correlation/error envelope.
  • apps/admin-api/src/{service.rs,main.rs,service/imports.rs} — передать уже открытый ArtifactStore; заменить raw parse на put/source/verified-read orchestration и re-verify/re-parse перед apply.
  • crates/crank-artifacts/src/{store.rs,model.rs} — read-only authority: put_registered, MAX_ARTIFACT_BYTES, verified bounded read; не добавлять path/digest accessors.
  • crates/crank-registry/src/{postgres/artifact_source.rs,postgres/import_job.rs,model.rs} — reuse scoped create/read/detach; сохранить source envelope в JSONB и атомарно detach при expiry без schema change.
  • apps/admin-api/tests/integration/{openapi_import.rs,openapi_source.rs,mod.rs,common.rs} — real router/PostgreSQL/filesystem matrix, scope/integrity/restart/cancel и anti-leak evidence.

Tasks & Acceptance

Execution:

  • Cargo.toml, apps/admin-api/Cargo.toml, src/{app.rs,routes/imports.rs,dto.rs,error.rs} — включить multipart и реализовать streaming one-file validation с отдельными file/envelope limits и стабильной локализацией.
  • apps/admin-api/src/{service.rs,main.rs,service/imports.rs} — разделить один production ArtifactStore между ingress/reconciliation; реализовать compensating detach guard, verified preview и source-authoritative apply.
  • crates/crank-registry/src/{postgres/import_job.rs,model.rs} — закрепить bounded source envelope и expiry cleanup relation без migration/raw source.
  • apps/admin-api/tests/integration/** — покрыть всю I/O matrix через реальный multipart router и доказать отсутствие Draft/job/telemetry leakage на отказах.

Acceptance Criteria:

  • Given valid или hostile multipart input, when preview проходит outer HTTP stack, then auth, exact 256 KiB limit, shape/MIME/UTF-8, safe RU/EN errors и Request ID/Trace ID доказаны без raw source в response/logs/traces/metrics.
  • Given successful preview, when job создаётся или позднее применяется, then parser получает только digest/size-verified bytes из workspace-scoped source, а absent/changed/foreign source блокирует Draft независимо от stored preview JSON.
  • Given failure, cancellation, disconnect, expiry или restart, when cleanup/retry выполняется, then нет частичных job/Draft entities, source становится безопасно detached либо blob остаётся reconciliation-owned orphan, без прямого unlink.

Spec Change Log

Design Notes

Import job хранит {source:{source_id,digest},preview} в существующем JSONB. Digest служит expected identity, но не возвращается клиенту. Созданная relation вооружает drop/expiry compensation; successful pending job сохраняет active relation до apply/expiry. Apply повторно выполняет scoped verified read и deterministic parse, а не десериализует preview как authority.

Verification

Commands:

  • cargo test -p admin-api --test integration openapi_source -- --test-threads=1 — outer multipart, auth/scope, limits, localization, cancellation/integrity и anti-leak matrix проходит.
  • cargo test -p admin-api --test integration openapi_import -- --test-threads=1 — verified-source apply/replay/no-Draft scenarios проходят.
  • cargo test -p crank-registry --test integration -- --test-threads=1 — source/job lifecycle и expiry compensation проходят.
  • cargo fmt --all --check && cargo clippy --workspace --all-targets --all-features -- -D warnings — форматирование и lint чисты.
  • just rust-boundaries && just rust-code-health && just verify — workspace contracts и полный regression gate проходят.