Files
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

465 lines
18 KiB
Rust
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! ATDD (RED) Story 3.7 — «Публиковать и привязывать static Resource Versions»: первый срез.
//!
//! Источники: live Gitea #14 (`STORY37-SOURCE.md`, 6 AC), canonical `tickets.toml` entry 7
//! (lines 174–232), QA baseline `_bmad-output/test-artifacts/test-design-epic-3.md:97`
//! (3.7-INT-A/B, risk E3-R3), `docs/acceptance-test-plan.md:1032–1037` (AT-3.7-01…06) и
//! TL interface decisions (`.tmp/t_8c38b75f/STORY37-NEXT.md` §2–§5).
//!
//! Границы среза: AC01 (preview controls), AC02 (publication validation), AC03 (immutable
//! Published Version) и API/registry часть AC06. AC04 (typed Agent binding, atomic Agent
//! publication, `catalog_revision`), AC05 (lifecycle UI + RU/EN), archive и stale Agent
//! revision остаются обязательным остатком Story 3.7 и здесь не проверяются.
//!
//! Фаза ATDD, production-код не изменяется. Целевой контракт публикации пока отсутствует,
//! поэтому RED-тесты падают на реальном HTTP-ответе (404 fallback-роутера там, где контракт
//! требует 200/400/403/422/428), а не на ошибке компиляции, SQL-отношения или setup.
//! Позитивные контроли держат уже принятое поведение create/update/preview/download.
//!
//! Фильтр запуска: `cargo test -p admin-api --test integration --locked story37_ -- --test-threads=1`.
#![allow(dead_code)]
mod contract;
mod immutable_version;
mod policy;
mod preview_controls;
mod validation;
use std::path::{Path, PathBuf};
use crank_registry::PostgresRegistry;
use reqwest::StatusCode;
use serde_json::{Value, json};
use super::super::common::{
TestServer, authorized_client, build_test_app, spawn_admin_api, test_registry,
test_storage_root,
};
use super::helpers::{
create_draft, created_resource_id, draft_form, draft_updated_at, error_signature, get_card,
read_response,
};
// ---------------------------------------------------------------------------
// Стенд с наблюдаемым артефактным хранилищем
// ---------------------------------------------------------------------------
/// Тот же стенд, что `helpers::spawn_authorized`, но корень артефактного хранилища остаётся
/// известен тесту: AC02 требует независимой проверки artifact digest/integrity, а не доверия
/// ответу API.
pub(super) async fn spawn_with_storage(
storage_name: &str,
) -> (PostgresRegistry, TestServer, reqwest::Client, PathBuf) {
let registry = test_registry().await;
let storage_root = test_storage_root(storage_name);
let app = build_test_app(registry.clone(), storage_root.clone());
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
(registry, server, client, storage_root)
}
// ---------------------------------------------------------------------------
// Контракт публикации: publish и exact Published Version
// ---------------------------------------------------------------------------
/// Тело запроса публикации: `expected_updated_at` — точное значение карточки Draft
/// (TL interface decision 2), тот же CAS, что у существующего PUT.
pub(super) fn publish_body(expected_updated_at: &str) -> Value {
json!({ "expected_updated_at": expected_updated_at })
}
/// POST `.../resources/{resource_id}/publish` с произвольным телом (нужен для негатива
/// «precondition отсутствует»).
pub(super) async fn publish_raw(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
body: &Value,
) -> (StatusCode, String, Value) {
let server = server.as_ref();
read_response(
client
.post(format!("{server}/resources/{resource_id}/publish"))
.json(body)
.send()
.await
.expect("publish request must complete"),
)
.await
}
/// POST `.../resources/{resource_id}/publish` с точным precondition карточки.
pub(super) async fn publish(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
expected_updated_at: &str,
) -> (StatusCode, String, Value) {
publish_raw(
client,
server,
resource_id,
&publish_body(expected_updated_at),
)
.await
}
/// GET `.../resources/{resource_id}/versions/{version}`: метаданные immutable версии.
pub(super) async fn read_version(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
) -> (StatusCode, String, Value) {
let server = server.as_ref();
read_response(
client
.get(format!(
"{server}/resources/{resource_id}/versions/{version}"
))
.send()
.await
.expect("version metadata request must complete"),
)
.await
}
/// GET `.../resources/{resource_id}/versions/{version}/content`: ответ нужен целиком, потому
/// что проверяются и точные bytes, и inert download policy (TL decision 3).
pub(super) async fn read_version_content(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
) -> reqwest::Response {
let server = server.as_ref();
client
.get(format!(
"{server}/resources/{resource_id}/versions/{version}/content"
))
.send()
.await
.expect("version content request must complete")
}
/// `published_version` из успешного ответа публикации: отсутствие объекта — уже нарушение
/// контракта, поэтому паника называет фактическое тело.
pub(super) fn published_metadata(body: &Value) -> Value {
body.get("published_version")
.cloned()
.filter(Value::is_object)
.unwrap_or_else(|| {
panic!(
"a successful publish must answer `{{\"resource\": ..., \"published_version\": ...}}` \
(TL interface decision 2); body={body}"
)
})
}
/// Тот же immutable metadata object, возвращаемый `GET .../versions/{version}`: допускается
/// как верхнеуровневый объект, так и вложенный `published_version` (TL decision 2/3).
pub(super) fn version_metadata(body: &Value) -> Value {
for pointer in ["", "/published_version", "/version"] {
if let Some(value) = body.pointer(pointer)
&& value.get("digest").is_some()
{
return value.clone();
}
}
panic!("Published Version metadata object must expose `digest` (TL decision 3): {body}");
}
/// Идентификатор Resource внутри ответа публикации: сам resource card у вложенного
/// `resource` (existing card shape) либо на верхнем уровне.
pub(super) fn resource_card_id(body: &Value) -> Option<String> {
for pointer in [
"/resource/resource_id",
"/resource/resource/resource_id",
"/resource/id",
] {
if let Some(id) = body.pointer(pointer).and_then(Value::as_str) {
return Some(id.to_owned());
}
}
None
}
/// `published_version` (и тот же объект из `GET .../versions/{version}`) не должен раскрывать
/// storage/path/raw filename/artifact source (TL decision 2), при этом обязан нести
/// version/uri/name/description/kind/mime_type/size_bytes/digest/sensitivity (TL decision 3).
pub(super) fn assert_immutable_metadata(metadata: &Value, raw_upload_filename: &str) {
let object = metadata
.as_object()
.unwrap_or_else(|| panic!("published version metadata must be a JSON object: {metadata}"));
for key in [
"version",
"uri",
"name",
"description",
"kind",
"mime_type",
"size_bytes",
"digest",
"sensitivity",
] {
assert!(
object.contains_key(key),
"published version metadata must include `{key}` (TL decision 3): {metadata}"
);
}
for (key, value) in object {
let lowered = key.to_ascii_lowercase();
for forbidden in [
"path",
"storage",
"filename",
"file_name",
"source",
"blob",
"raw_upload",
"upload",
] {
assert!(
!lowered.contains(forbidden),
"published version metadata must not expose `{forbidden}` (key `{key}`): {metadata}"
);
}
if let Some(text) = value.as_str() {
assert!(
!text.starts_with('/'),
"published version metadata must not expose an absolute storage path (`{key}`): {metadata}"
);
assert!(
!text.contains("sha256/"),
"published version metadata must not expose the content-addressed store path (`{key}`): {metadata}"
);
assert!(
!text.starts_with("src_"),
"published version metadata must not expose the artifact source id (`{key}`): {metadata}"
);
assert!(
!text.contains(raw_upload_filename),
"published version metadata must not echo the raw upload filename (`{key}`): {metadata}"
);
}
}
}
// ---------------------------------------------------------------------------
// Фикстуры: Draft → публикация, наблюдение «не опубликовано»
// ---------------------------------------------------------------------------
pub(super) struct DraftFixture {
pub resource_id: String,
/// Точный CAS карточки Draft.
pub updated_at: String,
pub card: Value,
}
/// Создаёт Draft через существующий принятый контракт и читает карточку как источник
/// precondition и digest.
pub(super) async fn create_fixture(
client: &reqwest::Client,
server: impl AsRef<str>,
metadata: &Value,
bytes: &[u8],
filename: &str,
mime: &str,
) -> DraftFixture {
let server = server.as_ref();
let created = create_draft(client, server, metadata, bytes, filename, mime).await;
let resource_id = created_resource_id(&created);
let card = get_card(client, server, &resource_id).await;
let updated_at = draft_updated_at(&card);
DraftFixture {
resource_id,
updated_at,
card,
}
}
pub(super) struct PublishedFixture {
pub draft: DraftFixture,
pub bytes: Vec<u8>,
pub published_version: Value,
/// Полное тело успешного ответа: `resource` card + `published_version` (TL decision 2).
pub body: Value,
}
/// Полный позитивный цикл «валидный Draft → публикация»: успех обязан быть 200 и нести
/// immutable `published_version` (AT-3.7-03).
pub(super) async fn create_and_publish(
client: &reqwest::Client,
server: impl AsRef<str>,
metadata: &Value,
bytes: &[u8],
filename: &str,
mime: &str,
) -> PublishedFixture {
let server = server.as_ref();
let draft = create_fixture(client, server, metadata, bytes, filename, mime).await;
let (status, text, body) = publish(client, server, &draft.resource_id, &draft.updated_at).await;
assert_eq!(
status,
StatusCode::OK,
"POST .../publish must publish a valid Draft into an immutable Published Version \
(AT-3.7-03); observed {} body={text}",
error_signature(status, &body)
);
let published_version = published_metadata(&body);
assert_immutable_metadata(&published_version, filename);
PublishedFixture {
draft,
bytes: bytes.to_vec(),
published_version,
body,
}
}
/// Обновление Draft существующим PUT-контрактом: меняются только изменяемые поля.
pub(super) async fn update_draft_expect_success(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
metadata: &Value,
bytes: &[u8],
filename: &str,
mime: &str,
) -> Value {
let server = server.as_ref();
let (status, text, body) = read_response(
client
.put(format!("{server}/resources/{resource_id}"))
.multipart(draft_form(metadata, bytes, filename, mime))
.send()
.await
.expect("draft update request must complete"),
)
.await;
assert!(
status.is_success(),
"a valid Draft update must stay accepted (Story 3.6 contract); observed {} body={text}",
error_signature(status, &body)
);
body
}
/// «Точная версия не опубликована»: Draft/nonpublished/чужой version не выдаётся (TL decision 3).
pub(super) async fn assert_version_not_published(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
context: &str,
) {
let (status, text, body) = read_version(client, server, resource_id, version).await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"{context}: version {version} must not be readable as a Published Version; observed {} body={text}",
error_signature(status, &body)
);
}
/// «Ничего не опубликовано» для ресурса, который никогда не был опубликован: точная версия
/// недоступна и карточка остаётся Draft (refusal не создаёт Published metadata).
pub(super) async fn assert_nothing_published(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
context: &str,
) {
let server = server.as_ref();
assert_version_not_published(client, server, resource_id, version, context).await;
let card = get_card(client, server, resource_id).await;
assert_eq!(
card["resource"]["status"],
json!("draft"),
"{context}: the Resource must stay a Draft after a refusal; card={card}"
);
}
/// Публикация обязана отказать: точный статус, sanitized error envelope, сохранённый Draft и
/// отсутствие Published metadata. Возвращает тело отказа для дополнительных проверок.
pub(super) async fn publish_expect_refusal(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
expected_updated_at: &str,
expected_status: StatusCode,
context: &str,
) -> Value {
let server = server.as_ref();
let (status, text, body) = publish(client, server, resource_id, expected_updated_at).await;
assert_eq!(
status,
expected_status,
"{context}: publication must be refused with {expected_status}; observed {} body={text}",
error_signature(status, &body)
);
assert!(
body["error"]["code"].is_string(),
"{context}: a refusal must keep the existing sanitized error envelope; body={text}"
);
assert_nothing_published(client, server, resource_id, 1, context).await;
body
}
// ---------------------------------------------------------------------------
// Наблюдение сохранённого артефакта (AC02 artifact digest/integrity)
// ---------------------------------------------------------------------------
/// Физический путь blob по контракту content-addressed store: `sha256/<shard>/<digest>`
/// (`crates/crank-artifacts/src/store.rs`: `SHA_DIR`/`ArtifactRef::shard`).
pub(super) fn blob_path(storage_root: &Path, digest: &str) -> PathBuf {
storage_root.join("sha256").join(&digest[..2]).join(digest)
}
/// Заменяет сохранённые bytes артефакта другими, сохраняя контракт store: обычный файл,
/// одна ссылка, ноль write-бит. Поэтому отказ публикации обязан прийти из digest-проверки,
/// а не из проверки прав файла.
pub(super) fn replace_blob_with_tampered_bytes(storage_root: &Path, digest: &str, tampered: &[u8]) {
let path = blob_path(storage_root, digest);
assert!(
path.is_file(),
"the artifact blob must exist at the content-addressed path {path:?} (fixture premise)"
);
std::fs::remove_file(&path).expect("blob must be replaceable for the integrity fixture");
std::fs::write(&path, tampered).expect("tampered blob must be written");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444))
.expect("tampered blob keeps the read-only contract");
}
}
/// Тест-фикстура defense-in-depth: сохранённый URI больше не проходит грамматику D-10,
/// хотя ограничения БД (длина) соблюдены — значит проверять обязан publication validator.
pub(super) async fn overwrite_resource_uri(pool: &sqlx::PgPool, resource_id: &str, uri: &str) {
sqlx::query("update resources set uri = $1 where resource_id = $2")
.bind(uri)
.bind(resource_id)
.execute(pool)
.await
.expect("fixture must be able to persist a grammar-invalid uri");
}
/// Тест-фикстура defense-in-depth: сохранённый MIME текущей версии больше не входит в
/// allowlist kind, хотя синтаксис MIME и ограничения БД соблюдены.
pub(super) async fn overwrite_current_version_mime(
pool: &sqlx::PgPool,
resource_id: &str,
mime: &str,
) {
sqlx::query(
"update resource_versions set mime_type = $1 \
where resource_id = $2 and superseded_at is null",
)
.bind(mime)
.bind(resource_id)
.execute(pool)
.await
.expect("fixture must be able to persist a non-allowlisted mime type");
}