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

242 lines
10 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.
//! R-D (P5): где именно срабатывает защита чтения Resource и как это наблюдается
//! счётчиками физических точек (AT-3.6-03/05).
//!
//! Источник: FINAL-DISPOSITION run99 (P5), TL review run103:35 (R-D): «однофакторная
//! integrity-матрица на durable seed-ах, metadata-denial до чтения против физического
//! отказа, который чтение уже выполнил».
//!
//! Наблюдения: `counters::artifact_reads` (реальная точка физического чтения) и точные
//! bytes/идентичность артефакта. SQL-мутации и файловые наблюдения живут в composition
//! fixture `crate::app::resource_test_support`, а не в сервисном коде.
//!
//! Канонический прогон: `cargo test -p admin-api --lib
//! service::resources::tests::read_integrity -- --test-threads=1`.
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
use crank_core::WorkspaceId;
use crank_registry::PostgresRegistry;
use serial_test::serial;
use super::super::{DraftMetadata, NewDraft, ResourcesService};
use super::counters;
use crate::app::resource_test_support::{
ArtifactIdentity, ArtifactMutation, ResourceServiceHarness, apply_artifact_mutation,
artifact_files, observe_artifact_identity, restore_artifact_identity,
};
const LIMIT: usize = 256 * 1024;
const WORKSPACE_ID: &str = "ws_default";
const CONTENT: &[u8] = b"integrity payload";
struct Harness {
service: ResourcesService,
registry: PostgresRegistry,
root: PathBuf,
}
/// Стенд с **известным** приватным artifact root: физический отказ можно наблюдать
/// только там, где тест владеет корнем хранилища (production-конструктор его скрывает).
///
/// Драйвер, миграция и сборка store/service выполняются в composition fixture
/// `crate::app::resource_test_support::ResourceServiceHarness` — сервисный тест-модуль
/// не создаёт SQL-адаптер и не держит raw pool (TL review run105 F3).
async fn harness(name: &str) -> Harness {
let ResourceServiceHarness {
service,
registry,
root,
} = ResourceServiceHarness::spawn(name, LIMIT).await;
Harness {
service,
registry,
root,
}
}
async fn seed(harness: &Harness, suffix: &str) -> crank_core::ids::ResourceId {
harness
.service
.create_draft(NewDraft {
workspace_id: WorkspaceId::new(WORKSPACE_ID),
metadata: DraftMetadata {
uri: format!("crank://integrity/{suffix}"),
name: format!("integrity_{suffix}"),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
},
bytes: CONTENT.to_vec(),
})
.await
.expect("the durable seed draft must be created")
.resource_id
}
/// Физические файлы содержимого (один blob на seed).
fn blob_files(harness: &Harness) -> Vec<PathBuf> {
let files = artifact_files(&harness.root);
assert_eq!(
files.len(),
1,
"exactly one durable blob is expected under the private root: {files:?}"
);
files
}
/// Запись файла содержимого в форме, которую принимает store (регулярный файл
/// владельца, одна ссылка, без прав записи) — создаёт файл заново при необходимости.
fn install_blob(path: &PathBuf, bytes: &[u8]) {
if path.exists() {
fs::remove_file(path).expect("the durable blob must be removable for the fault case");
}
fs::write(path, bytes).expect("the replacement blob must be writable");
fs::set_permissions(path, fs::Permissions::from_mode(0o444))
.expect("the replacement blob must lose its write bits");
}
#[tokio::test]
#[serial]
async fn story36_at03_metadata_denial_refuses_before_any_physical_read() {
let harness = harness("metadata_denial").await;
let resource_id = seed(&harness, "metadata").await;
// Позитивный контроль: durable seed действительно читается точными bytes.
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.expect("the durable seed must be readable"),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
let identity: ArtifactIdentity =
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await;
let mut observations: Vec<String> = Vec::new();
let mut mismatches: Vec<String> = Vec::new();
for mutation in ArtifactMutation::ALL {
let label = mutation.label();
apply_artifact_mutation(harness.registry.pool(), mutation)
.await
.unwrap_or_else(|error| panic!("mutation `{label}` must apply: {error}"));
assert_ne!(
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
identity,
"mutation `{label}` must really change the observed identity"
);
counters::reset();
let refusal = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let reads = counters::artifact_reads();
let observed = match &refusal {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// Metadata-сверка обязана отсечь рассинхронизацию ДО физического чтения.
if refusal.is_err() && observed == "resource_artifact_integrity" && reads == 0 {
observations.push(format!("{label}: {observed}, physical reads={reads}"));
} else {
mismatches.push(format!(
"{label}: expected resource_artifact_integrity with reads=0, observed \
{observed} with reads={reads}"
));
observations.push(format!("{label}: {observed}, physical reads={reads}"));
}
restore_artifact_identity(harness.registry.pool(), WORKSPACE_ID, &identity)
.await
.unwrap_or_else(|error| panic!("restoration after `{label}` must apply: {error}"));
assert_eq!(
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
identity,
"mutation `{label}` must be restored byte-exactly"
);
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.unwrap_or_else(|error| panic!("restore after `{label}` must resolve: {error:?}")),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
}
assert!(
mismatches.is_empty(),
"every metadata mismatch must be refused before the physical read point; observations: \
{observations:?}; mismatches: {mismatches:?}"
);
}
#[tokio::test]
#[serial]
async fn story36_at03_physical_failure_reads_once_and_returns_no_bytes() {
let harness = harness("physical_failure").await;
let resource_id = seed(&harness, "physical").await;
let mut files = blob_files(&harness);
let blob = files.remove(0);
// (1) Содержимое физически отсутствует: metadata-сверка проходит, чтение выполняется
// и падает — счётчик чтения равен 1, bytes не возвращаются.
fs::remove_file(&blob).expect("the durable blob must be removable");
counters::reset();
let missing = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let missing_reads = counters::artifact_reads();
let missing_code = match &missing {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// (2) Содержимое подменено на другую строку той же длины: чтение тоже выполняется,
// но расхождение digest обязано быть отказом без bytes.
install_blob(&blob, b"integrity payloaX");
counters::reset();
let corrupted = harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await;
let corrupted_reads = counters::artifact_reads();
let corrupted_code = match &corrupted {
Err(error) => error.code().to_owned(),
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
};
// (3) Положительный контроль: возврат точных bytes восстанавливает чтение.
install_blob(&blob, CONTENT);
counters::reset();
assert_eq!(
harness
.service
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
.await
.expect("the restored blob must be readable again"),
CONTENT.to_vec()
);
assert_eq!(counters::artifact_reads(), 1);
assert!(
missing.is_err() && missing_code == "resource_artifact_integrity" && missing_reads == 1,
"a physically missing blob must fail after the read point with no bytes; observed \
{missing_code} with reads={missing_reads}"
);
assert!(
corrupted.is_err()
&& corrupted_code == "resource_artifact_integrity"
&& corrupted_reads == 1,
"a physically corrupted blob must fail closed after the read point with no bytes; \
observed {corrupted_code} with reads={corrupted_reads}"
);
}