Files
crank/apps/admin-api/src/service/resources/tests.rs
T
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

404 lines
18 KiB
Rust
Raw 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.
//! BUILD-ONLY: in-crate counter harness Story 3.6 (D-19, пять именованных проверок).
//!
//! Статус на стадии Dev ATDD: **не зарегистрирован**. Файл лежит по пути, который BUILD
//! объявит из production-модуля:
//! ```text
//! // apps/admin-api/src/service/resources.rs
//! #[cfg(test)] pub(crate) mod counters { /* inline: note_artifact_put/read, artifact_puts/reads, reset */ }
//! #[cfg(test)] #[path = "resources/tests.rs"] mod tests;
//! ```
//! Сегодня `apps/admin-api/src/service/resources.rs` не существует, поэтому файл не компилируется
//! и не исполняется (нулевая коллекция — не PASS). Ранняя регистрация запрещена: счётчики живут
//! внутри production-модуля, а production-код на стадии ATDD не пишется.
//!
//! Минимальный будущий интерфейс, на который опираются тесты (объявляется в
//! `service/resources.rs`, отдельного production `tests_support`-модуля не требуется):
//! ```text
//! pub(crate) struct DraftMetadata { pub uri: String, pub name: String, pub description: String,
//! pub kind: String, pub mime_type: String, pub sensitivity: String }
//! pub(crate) struct NewDraft { pub workspace_id: WorkspaceId, pub metadata: DraftMetadata,
//! pub bytes: Vec<u8> }
//! pub(crate) struct CreatedDraft { pub resource_id: ResourceId }
//! impl ResourcesService {
//! pub(crate) fn for_tests(registry: PostgresRegistry, limit: usize) -> Self;
//! pub(crate) async fn create_draft(&self, draft: NewDraft) -> Result<CreatedDraft, ResourceError>;
//! pub(crate) async fn read_content(&self, workspace_id: &WorkspaceId, resource_id: &ResourceId)
//! -> Result<Vec<u8>, ResourceError>;
//! }
//! ```
//! Фикстуры собираются локально в этом файле (`text_draft`/`text_draft_in`), поэтому production
//! обязан остаться без тестового `tests_support`-модуля и без публичного API ради тестов.
//!
//! Что именно должен доказать harness (D-19): счётчики стоят на реальных точках —
//! `ArtifactStore::put_registered` (перед регистрацией bytes) и физического чтения байт в
//! приватном `read_resource_content()`. «0» доказывается только вместе с положительным
//! контролем, а duplicate/DB-rollback проверяются по отсутствию принятых строк, а не по put.
//! Запуск после BUILD (фильтр обязан содержать сегмент `tests::`):
//! `cargo test -p admin-api --lib service::resources::tests::story36_ -- --list`
//! и затем `... -- --test-threads=1` (каждый тест предваряется `counters::reset()`).
use super::ResourcesService;
use super::counters;
use crate::app::resource_test_support::ResourceServiceHarness;
use crank_core::WorkspaceId;
use crank_registry::model::resource::ResourceDraftRecord;
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery, PostgresRegistry};
use serial_test::serial;
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const FOREIGN_WORKSPACE_ID: &str = "ws_story36_counters_other";
struct Harness {
service: ResourcesService,
registry: PostgresRegistry,
}
/// Изолированный стенд: своя PG-схема на каждый тест (иначе счётчики делят строки между тестами).
///
/// Драйвер, миграция и сборка store/service выполняются composition-фикстурой
/// `crate::app::resource_test_support::ResourceServiceHarness`: сервисный тест-модуль
/// получает готовый сервис и реестр, а не сырой pool (TL run105 F3, Q1).
async fn harness(name: &str) -> Harness {
let ResourceServiceHarness {
service, registry, ..
} = ResourceServiceHarness::spawn(name, LIMIT).await;
Harness { service, registry }
}
/// Принятые черновики workspace через продуктовое чтение: raw SQL в
/// `apps/admin-api/src/service/**` запрещён execution-boundary правилом, поэтому
/// «0 принятых строк» наблюдается на том же публичном чтении, что и UI.
async fn accepted_drafts(harness: &Harness) -> Vec<ResourceDraftRecord> {
harness
.registry
.list_resource_drafts(WORKSPACE_ID, 100)
.await
.expect("accepted resource drafts must be readable")
}
/// Активные owning-ссылки workspace (учёт владения bytes, AD-10).
async fn active_owning_refs(harness: &Harness) -> usize {
let workspace_id = WorkspaceId::new(WORKSPACE_ID);
let page = harness
.registry
.list_artifact_sources(ListArtifactSourcesQuery {
workspace_id: &workspace_id,
cursor: None,
limit: 100,
})
.await
.expect("artifact sources must be readable");
page.items
.iter()
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
.count()
}
/// Локальная фикстура: Draft в `ws_default` (никакого production `tests_support`).
fn text_draft(uri: &str, name: &str, bytes: &[u8]) -> NewDraftFixture {
text_draft_in(&WorkspaceId::new(WORKSPACE_ID), uri, name, bytes)
}
/// Та же фикстура с явным workspace (нужна для «чужого» Resource).
fn text_draft_in(
workspace_id: &WorkspaceId,
uri: &str,
name: &str,
bytes: &[u8],
) -> NewDraftFixture {
super::NewDraft {
workspace_id: workspace_id.clone(),
metadata: super::DraftMetadata {
uri: uri.to_owned(),
name: name.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: bytes.to_vec(),
}
}
type NewDraftFixture = super::NewDraft;
/// Второй workspace (никаких прав/членства у него нет: здесь проверяется только адресация).
async fn create_other_workspace(registry: &PostgresRegistry) -> WorkspaceId {
use crank_core::{Workspace, WorkspaceStatus};
use crank_registry::CreateWorkspaceRequest;
use serde_json::json;
let now = time::OffsetDateTime::now_utc();
let workspace_id = WorkspaceId::new(FOREIGN_WORKSPACE_ID);
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: "story36-counters-other".to_owned(),
display_name: "Story 3.6 Counters Other".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.expect("the second workspace must be created");
workspace_id
}
// Детерминизм счётчиков: счётчики D-19 — процессные статики, поэтому все проверки,
// которые их наблюдают (включая guard-пути), сериализуются атрибутом планировщика.
// Сами ассерты и тела тестов не изменены.
#[tokio::test]
#[serial]
async fn story36_counter_authorized_create_puts_once() {
let harness = harness("create_puts").await;
counters::reset();
let created = harness
.service
.create_draft(text_draft("crank://counter/put", "counter_put", b"payload"))
.await
.expect("authorized create must succeed");
assert_eq!(
counters::artifact_puts(),
1,
"an authorized create must hit the real byte-registration point exactly once"
);
assert_eq!(counters::artifact_reads(), 0);
// Положительный контроль: счётчик отражает настоящую запись, а не переменную теста.
let stored = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("stored content must be readable");
assert_eq!(stored.as_slice(), b"payload");
}
#[tokio::test]
#[serial]
async fn story36_counter_authorized_read_reads_once() {
let harness = harness("read_reads").await;
let created = harness
.service
.create_draft(text_draft(
"crank://counter/read",
"counter_read",
b"payload",
))
.await
.expect("authorized create must succeed");
counters::reset();
let stored = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("authorized read must succeed");
assert_eq!(stored.as_slice(), b"payload");
assert_eq!(
counters::artifact_reads(),
1,
"an authorized read must hit the real byte-read point exactly once"
);
}
#[tokio::test]
#[serial]
async fn story36_counter_denied_create_puts_zero() {
let harness = harness("denied_create").await;
counters::reset();
// Конкретный доменный отказ до регистрации bytes: kind=text + text/plain + C3 28.
let draft = text_draft("crank://counter/denied", "counter_denied", &[0xC3, 0x28]);
let error = harness
.service
.create_draft(draft)
.await
.expect_err("invalid UTF-8 must be rejected before bytes are registered");
assert_eq!(error.code(), "resource_content_invalid_utf8");
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
assert!(
accepted_drafts(&harness).await.is_empty(),
"a refused create must not accept any resource row"
);
}
#[tokio::test]
#[serial]
async fn story36_counter_denied_foreign_resource_reads_zero() {
let harness = harness("foreign_read").await;
let foreign_workspace = create_other_workspace(&harness.registry).await;
// Реальный Resource в другом workspace: он существует, но не в ws_default.
let created = harness
.service
.create_draft(text_draft_in(
&foreign_workspace,
"crank://counter/foreign",
"counter_foreign",
b"foreign payload",
))
.await
.expect("create in the owning workspace must succeed");
counters::reset();
let error = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect_err("a Resource of another workspace must not be readable here");
assert_eq!(error.code(), "resource_not_found");
assert_eq!(counters::artifact_reads(), 0);
assert_eq!(counters::artifact_puts(), 0);
// Положительный контроль: тот же существующий Resource читается в своём workspace,
// поэтому «0» выше — наблюдение, а не отсутствие реализации.
let stored = harness
.service
.read_content(&foreign_workspace, &created.resource_id)
.await
.expect("the owning workspace must read its own Resource");
assert_eq!(stored.as_slice(), b"foreign payload");
assert_eq!(counters::artifact_reads(), 1);
}
#[tokio::test]
#[serial]
async fn story36_counter_duplicate_conflict_accepted_rows_zero() {
let harness = harness("duplicate").await;
counters::reset();
harness
.service
.create_draft(text_draft("crank://counter/dup", "counter_dup", b"payload"))
.await
.expect("first create must succeed");
let duplicate = text_draft("crank://counter/dup", "counter_other", b"payload");
let error = harness
.service
.create_draft(duplicate)
.await
.expect_err("duplicate uri must be rejected");
assert_eq!(error.code(), "resource_uri_duplicate");
// Значение put здесь НЕ утверждается: bytes регистрируются до конфликта, осиротевшие
// bytes допустимы (AD-10). Доказывается отсутствие принятых строк: у принятого
// черновика ровно одна текущая версия, а живая owning-ссылка ровно одна.
let accepted = accepted_drafts(&harness).await;
assert_eq!(accepted.len(), 1, "only the first create is accepted");
assert_eq!(
accepted[0].version.version, 1,
"the accepted draft keeps exactly one current version"
);
harness
.registry
.resolve_current_resource_version(WORKSPACE_ID, &accepted[0].resource.resource_id)
.await
.expect("the accepted draft must expose its current version");
assert_eq!(
active_owning_refs(&harness).await,
1,
"only the accepted draft keeps an active owning reference"
);
}
// Регистрация подмодулей guard-путей (TL review run101, R-A): тот же in-crate набор,
// отдельные файлы, потому что inline-модуль такого объёма запрещён health-правилом.
//
// Три HTTP-модуля лежат в тестовом пути `tests/integration/resources/in_crate/`
// (TL run111): их содержимое использует прямой HTTP-клиент, а `apps/admin-api/src/service/**`
// по execution-boundary правилу не может содержать такую зависимость даже в тестах.
// Модули остаются in-crate тестами библиотеки — import-путь `service::resources::tests::<модуль>`
// и все test IDs сохраняются, внешний integration-бинарь их не регистрирует.
#[path = "../../../tests/integration/resources/in_crate/guard_path.rs"]
mod guard_path;
#[path = "../../../tests/integration/resources/in_crate/guard_telemetry.rs"]
mod guard_telemetry;
#[path = "../../../tests/integration/resources/in_crate/limits.rs"]
mod limits;
#[path = "tests/read_integrity.rs"]
mod read_integrity;
// P3 (TL F05): детерминированная проверка единого снимка версии и bytes.
#[path = "tests/snapshot.rs"]
mod snapshot;
#[path = "tests/snapshot_after_resolve.rs"]
mod snapshot_after_resolve;
// F5 (TL run105): контроль редактирования чувствительных заголовков в диагностике
// рукописного запроса — отдельный файл по тому же health-правилу.
#[path = "tests/diagnostics.rs"]
mod diagnostics;
// Story 3.7 / AC03 (TL CODE-REVIEW): детерминированный race «публикация vs Draft
// update» через уже принятый BUILD-only шов `interleave`.
#[path = "tests/publication_race.rs"]
mod publication_race;
// BUILD obligations, которые этот harness НЕ подтверждает:
// - session/Owner/CSRF/origin guard-ы (это HTTP-уровень, таргет A);
// - DB-rollback при update после шага пометки (таргет P, `story36_at03_update_rollback_*`);
// - захват logs/spans/metrics (см. `apps/admin-api/tests/integration/resources/telemetry.rs`).
// Измерение принятых строк идёт через публичное чтение реестра (`list_resource_drafts`,
// `list_artifact_sources`), а не через прямой SQL-драйвер: execution-boundary запрещает
// зависимость от драйвера хранилища в `apps/admin-api/src/service/**`. Поведенческое
// ожидание сохранено: на отказе не появляется ни принятый черновик, ни его текущая версия,
// ни активная owning-ссылка.
// ---------------------------------------------------------------------------
// Story 3.7 / AC02: configure lower limit демонстрирует 413-путь публикации,
// недостижимый через persisted state (DB CHECK = storage ceiling).
// ---------------------------------------------------------------------------
#[tokio::test]
async fn story37_at02_configured_lower_limit_refuses_publication_before_writes() {
use std::sync::Arc;
use crank_artifacts::ArtifactStore;
use crank_core::resource::{ResourceError, ResourceLimits};
let wide = ResourceServiceHarness::spawn("story37_publish_limit", LIMIT).await;
let bytes = b"0123456789abcdef0123456789abcdef";
let created = wide
.service
.create_draft(text_draft("crank://story37/limit", "limit_doc", bytes))
.await
.expect("draft must be created under the default limit");
let card = wide
.service
.card(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
.await
.expect("draft card must be readable");
// Тот же registry/store, но сконфигурированный ниже сохранённого размера: публикация
// обязана отказать до любых записей (413-путь).
let store = Arc::new(ArtifactStore::open(&wide.root).expect("shared store must open"));
let narrow = ResourcesService::new(
wide.registry.clone(),
store,
ResourceLimits::uniform(8).expect("lower limit must stay inside the ceiling"),
);
let error = narrow
.publish(super::PublishResource {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
resource_id: created.resource_id.clone(),
expected_updated_at: Some(card.resource.updated_at),
})
.await
.expect_err("a stored content above the configured limit must be refused");
assert_eq!(error, ResourceError::ContentTooLarge);
let drafts = accepted_drafts(&Harness {
service: wide.service,
registry: wide.registry,
})
.await;
assert_eq!(drafts.len(), 1, "a refused publication must keep the Draft");
assert_eq!(
drafts[0].resource.status,
crank_core::resource::ResourceStatus::Draft
);
}