Files
crank/apps/admin-api/tests/integration/resources/portability.rs
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

984 lines
34 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.9 — серверная часть переноса Resource: bounded envelope,
//! export Draft/точной Published Version, импорт нового owned Draft.
//!
//! Источники: `epics.md`:2614–2645, `docs/acceptance-test-plan.md`:1054–1065 (AT-3.9-01..03),
//! `test-design-epic-3.md`:74–86,116,176–180 и принятый spec `spec-resource-portability/spec.md`.
//! Маршрутов `.../export` и `.../import` ещё нет, поэтому каждый RED ниже — расхождение на
//! реальном HTTP-ответе (404/405 вместо 200/201/400/409/413/422), а не ошибка компиляции.
//! Существующие create/publish/list/content контракты Story 3.6–3.8 — позитивный контроль.
//!
//! Фильтр запуска: `cargo test -p admin-api --test integration story39_ -- --test-threads=1`.
use super::helpers::{
CONTENT_LIMIT, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, api_root, create_draft,
create_owned_workspace, created_resource_id, draft_metadata, draft_updated_at,
ensure_viewer_membership, error_signature, get_card, list_resources, login_client,
login_client_with_foreign_origin, login_client_without_csrf, read_content, read_response,
sha256_hex, spawn_authorized, table_row_count,
};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
const ENVELOPE_FORMAT: &str = "crank-resource-portability";
const ENVELOPE_VERSION: u64 = 1;
/// Ключи, которых не должно быть ни в экспортируемом manifest, ни в ошибках импорта:
/// внутренние owning-ссылки, пути хранилища, lifecycle/ownership-подмена.
const FORBIDDEN_KEYS: &[&str] = &[
"artifact",
"artifact_id",
"artifact_ref",
"artifact_sources",
"blob",
"blob_path",
"storage",
"storage_root",
"owner",
"owner_user_id",
"workspace",
"workspace_id",
"resource_id",
"status",
"published_at",
"credential",
"credentials",
"secret",
"filename",
"created_at",
"updated_at",
];
/// Значения, доказывающие утечку внутреннего состояния (пути/БД/ключи/хранилище).
const FORBIDDEN_VALUE_MARKERS: &[&str] = &[
"/home/",
"/tmp/",
".tmp/",
"artifact_blobs",
"artifact_sources",
"postgres://",
"test-master-key",
];
// Envelope: независимый оракул теста (digest/base64 считает тест, а не API).
fn encode(bytes: &[u8]) -> String {
BASE64.encode(bytes)
}
fn decode(value: &str) -> Vec<u8> {
BASE64
.decode(value)
.unwrap_or_else(|error| panic!("exported content.base64 must be valid base64: {error}"))
}
fn resource_block(uri: &str, name: &str, description: &str, kind: &str, mime: &str) -> Value {
json!({
"uri": uri,
"name": name,
"description": description,
"kind": kind,
"mime_type": mime,
"sensitivity": "internal",
})
}
fn content_block(bytes: &[u8]) -> Value {
json!({
"size_bytes": bytes.len(),
"digest": sha256_hex(bytes),
"base64": encode(bytes),
})
}
fn envelope(resource: Value, source_kind: &str, source_version: u32, bytes: &[u8]) -> Value {
json!({
"format": ENVELOPE_FORMAT,
"version": ENVELOPE_VERSION,
"resource": resource,
"source": { "kind": source_kind, "version": source_version },
"content": content_block(bytes),
})
}
/// Ожидаемый envelope Draft: поля карточки + bytes, которые тест знает независимо.
fn draft_envelope(card: &Value, bytes: &[u8]) -> Value {
let resource = resource_block(
card["resource"]["uri"]
.as_str()
.expect("card must expose uri"),
card["resource"]["name"]
.as_str()
.expect("card must expose name"),
card["resource"]["description"]
.as_str()
.expect("card must expose description"),
card["resource"]["kind"]
.as_str()
.expect("card must expose kind"),
card["version"]["mime_type"]
.as_str()
.expect("card must expose mime_type"),
);
let version = card["resource"]["current_draft_version"]
.as_u64()
.expect("card must expose current_draft_version") as u32;
envelope(resource, "draft", version, bytes)
}
/// Ожидаемый envelope точной Published Version (snapshot из publish-ответа).
fn published_envelope(published: &Value, bytes: &[u8]) -> Value {
let snapshot = &published["published_version"];
let resource = resource_block(
snapshot["uri"].as_str().expect("published must expose uri"),
snapshot["name"]
.as_str()
.expect("published must expose name"),
snapshot["description"]
.as_str()
.expect("published must expose description"),
snapshot["kind"]
.as_str()
.expect("published must expose kind"),
snapshot["mime_type"]
.as_str()
.expect("published must expose mime_type"),
);
let version = snapshot["version"]
.as_u64()
.expect("published must expose version") as u32;
envelope(resource, "published", version, bytes)
}
fn collect_keys(value: &Value, keys: &mut Vec<String>) {
match value {
Value::Object(map) => {
for (key, nested) in map {
keys.push(key.clone());
collect_keys(nested, keys);
}
}
Value::Array(items) => {
for item in items {
collect_keys(item, keys);
}
}
_ => {}
}
}
/// Manifest/ошибка без утечек: запрещённые ключи и внутренние значения. Base64-содержимое
/// не сканируется на подстроки (это пользовательские bytes), но сами bytes проверяются
/// отдельно точным сравнением.
fn assert_safe_wire_value(value: &Value, context: &str) {
let mut redacted = value.clone();
if let Some(content) = redacted.get_mut("content").and_then(Value::as_object_mut) {
content.insert("base64".to_owned(), Value::String(String::new()));
}
let mut keys = Vec::new();
collect_keys(&redacted, &mut keys);
for forbidden in FORBIDDEN_KEYS {
assert!(
!keys.iter().any(|key| key == forbidden),
"{context}: wire value must not expose internal/ownership key `{forbidden}`: {redacted}"
);
}
let text = redacted.to_string();
for marker in FORBIDDEN_VALUE_MARKERS {
assert!(
!text.contains(marker),
"{context}: wire value must not expose internal value `{marker}`: {redacted}"
);
}
}
// HTTP-обёртки новых контрактов.
fn workspace_base(server: &str, workspace_id: &str) -> String {
format!("{}/api/admin/workspaces/{workspace_id}", api_root(server))
}
async fn export_draft(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
) -> (StatusCode, String, Value) {
read_response(
client
.get(format!(
"{}/resources/{resource_id}/export",
server.as_ref()
))
.send()
.await
.expect("draft export request must complete"),
)
.await
}
async fn export_version(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
version: u32,
) -> (StatusCode, String, Value) {
read_response(
client
.get(format!(
"{}/resources/{resource_id}/versions/{version}/export",
server.as_ref()
))
.send()
.await
.expect("published export request must complete"),
)
.await
}
async fn post_import(
client: &reqwest::Client,
server: impl AsRef<str>,
envelope: &Value,
) -> (StatusCode, String, Value) {
read_response(
client
.post(format!("{}/resources/import", server.as_ref()))
.json(envelope)
.send()
.await
.expect("import request must complete"),
)
.await
}
async fn post_import_raw(
client: &reqwest::Client,
server: impl AsRef<str>,
body: Vec<u8>,
) -> (StatusCode, String, Value) {
read_response(
client
.post(format!("{}/resources/import", server.as_ref()))
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body)
.send()
.await
.expect("raw import request must complete"),
)
.await
}
/// Публикация Draft существующим принятым контрактом Story 3.7 (фикстура, не предмет проверки).
async fn publish_draft(
client: &reqwest::Client,
server: impl AsRef<str>,
resource_id: &str,
) -> Value {
let card = get_card(client, server.as_ref(), resource_id).await;
let (status, text, body) = read_response(
client
.post(format!(
"{}/resources/{resource_id}/publish",
server.as_ref()
))
.json(&json!({ "expected_updated_at": draft_updated_at(&card) }))
.send()
.await
.expect("publish fixture request must complete"),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"accepted Story 3.7 publish contract must stay GREEN as the fixture: {text}"
);
body
}
async fn assert_import_ok(
client: &reqwest::Client,
server: impl AsRef<str>,
envelope: &Value,
) -> (String, Value) {
let (status, text, imported) = post_import(client, server, envelope).await;
assert_eq!(
status,
StatusCode::CREATED,
"POST .../resources/import must create a new Draft (AT-3.9-01); observed {} body={text}",
error_signature(status, &imported)
);
(created_resource_id(&imported), imported)
}
// AT-3.9-01: экспорт/импорт Draft и точной Published Version.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at01_export_draft_roundtrip_preserves_metadata_digest_bytes() {
let (registry, server, client) = spawn_authorized("story39_export_draft").await;
let bytes = b"story39 draft roundtrip body\n";
let metadata = draft_metadata(
"crank://e2e/story39-export-draft",
"story39_export_draft",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&metadata,
bytes,
"draft.txt",
"text/plain",
)
.await;
let source_id = created_resource_id(&created);
let card = get_card(&client, &server, &source_id).await;
let expected = draft_envelope(&card, bytes);
let (status, text, exported) = export_draft(&client, &server, &source_id).await;
assert_eq!(
status,
StatusCode::OK,
"GET .../resources/{{id}}/export must return the bounded envelope (AT-3.9-01); observed {} body={text}",
error_signature(status, &exported)
);
assert_safe_wire_value(&exported, "draft export");
assert_eq!(
exported, expected,
"export must preserve wire metadata, size, digest and bytes and contain only allowlisted fields"
);
assert_eq!(
decode(exported["content"]["base64"].as_str().unwrap_or_default()),
bytes.to_vec(),
"exported base64 must decode to the exact stored bytes"
);
// Реальный roundtrip в другую установку/workspace: новый owned Draft, без публикации.
let target = create_owned_workspace(&registry).await;
let target_base = workspace_base(server.as_ref(), target.as_str());
let target_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (imported_id, imported) = assert_import_ok(&target_client, &target_base, &exported).await;
assert_ne!(
imported_id, source_id,
"import must create a new Resource identity, never reuse or upsert the source"
);
assert_eq!(imported["resource"]["status"], json!("draft"));
assert_eq!(
imported["resource"]["latest_published_version"],
Value::Null,
"import must never auto-publish"
);
assert_eq!(imported["resource"]["current_draft_version"], json!(1));
assert_eq!(imported["resource"]["uri"], exported["resource"]["uri"]);
assert_eq!(imported["resource"]["name"], exported["resource"]["name"]);
assert_eq!(
imported["resource"]["description"],
exported["resource"]["description"]
);
assert_eq!(imported["resource"]["kind"], exported["resource"]["kind"]);
assert_eq!(
imported["version"]["mime_type"],
exported["resource"]["mime_type"]
);
assert_eq!(imported["version"]["size_bytes"], json!(bytes.len() as i64));
assert_eq!(imported["version"]["digest"], json!(sha256_hex(bytes)));
assert_eq!(
read_content(&target_client, &target_base, &imported_id).await,
bytes.to_vec(),
"imported bytes must be byte-identical to the exported content"
);
// Импортированный Draft не опубликован: точной версии нет.
let (status, text, published) = read_response(
target_client
.get(format!("{target_base}/resources/{imported_id}/versions/1"))
.send()
.await
.expect("published version request must complete"),
)
.await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"an imported Draft must not own a Published Version: {text} body={published}"
);
// Источник неизменён: ни карточка, ни lifecycle.
assert_eq!(
get_card(&client, &server, &source_id).await,
card,
"export must not change the source Resource"
);
assert_eq!(
table_row_count(registry.pool(), "resources").await,
2,
"exactly the source and the imported Draft must exist"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at01_export_published_version_imports_as_new_draft() {
let (registry, server, client) = spawn_authorized("story39_export_published").await;
let bytes = b"story39 published snapshot\n";
let metadata = draft_metadata(
"crank://e2e/story39-published",
"story39_published",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&metadata,
bytes,
"draft.txt",
"text/plain",
)
.await;
let source_id = created_resource_id(&created);
let published = publish_draft(&client, &server, &source_id).await;
let expected = published_envelope(&published, bytes);
let (status, text, exported) = export_version(&client, &server, &source_id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"GET .../versions/{{n}}/export must return the exact Published Version (AT-3.9-01); observed {} body={text}",
error_signature(status, &exported)
);
assert_safe_wire_value(&exported, "published export");
assert_eq!(
exported, expected,
"published export must keep the exact snapshot metadata, digest and bytes"
);
assert_eq!(exported["source"]["kind"], json!("published"));
assert_eq!(exported["source"]["version"], json!(1));
let target = create_owned_workspace(&registry).await;
let target_base = workspace_base(server.as_ref(), target.as_str());
let target_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (imported_id, imported) = assert_import_ok(&target_client, &target_base, &exported).await;
assert_ne!(imported_id, source_id);
assert_eq!(
imported["resource"]["status"],
json!("draft"),
"import of a Published Version must create a Draft, not a Published Resource"
);
assert_eq!(
imported["resource"]["latest_published_version"],
Value::Null,
"a transferred Published Version must not be published in the target workspace"
);
assert_eq!(
read_content(&target_client, &target_base, &imported_id).await,
bytes.to_vec()
);
assert_eq!(
table_row_count(registry.pool(), "resource_versions").await,
2,
"target must have its own draft revision only; source publication is not copied"
);
}
// AT-3.9-03: roundtrip text/JSON/binary.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at03_text_json_binary_roundtrip_preserves_exact_bytes() {
let (registry, server, client) = spawn_authorized("story39_roundtrip").await;
let target = create_owned_workspace(&registry).await;
let target_base = workspace_base(server.as_ref(), target.as_str());
let target_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let text = "Привет, Crank!\nline two\n".as_bytes().to_vec();
let json_bytes = "{ \"z\": 1, \"a\": [true, null, \"строка\"] }"
.as_bytes()
.to_vec();
let binary: Vec<u8> = (0u8..=255).cycle().take(1024).collect();
let fixtures: [(&str, &str, &str, &[u8]); 3] = [
("crank://e2e/story39-text", "story39_text", "text", &text),
(
"crank://e2e/story39-json",
"story39_json",
"json",
&json_bytes,
),
(
"crank://e2e/story39-binary",
"story39_binary",
"binary",
&binary,
),
];
for (uri, name, kind, bytes) in fixtures {
let mime = match kind {
"text" => "text/plain",
"json" => "application/json",
_ => "application/pdf",
};
let metadata = draft_metadata(uri, name, kind, mime, "internal");
let created = create_draft(&client, &server, &metadata, bytes, "payload.bin", mime).await;
let source_id = created_resource_id(&created);
let card = get_card(&client, &server, &source_id).await;
let expected = draft_envelope(&card, bytes);
let (status, text_body, exported) = export_draft(&client, &server, &source_id).await;
assert_eq!(
status,
StatusCode::OK,
"export of kind={kind} must return the envelope (AT-3.9-03); observed {} body={text_body}",
error_signature(status, &exported)
);
assert_eq!(exported, expected, "exported envelope for kind={kind}");
assert_eq!(
decode(exported["content"]["base64"].as_str().unwrap_or_default()),
bytes.to_vec(),
"kind={kind}: base64 must round-trip the exact bytes"
);
let (imported_id, imported) =
assert_import_ok(&target_client, &target_base, &exported).await;
assert_eq!(
imported["resource"]["kind"],
json!(kind),
"kind must be preserved for {name}"
);
assert_eq!(imported["version"]["mime_type"], json!(mime));
assert_eq!(imported["version"]["digest"], json!(sha256_hex(bytes)));
assert_eq!(
read_content(&target_client, &target_base, &imported_id).await,
bytes.to_vec(),
"kind={kind}: imported bytes must stay exact"
);
}
}
// AT-3.9-03: malformed/oversized/foreign envelope → отказ без изменения состояния.
struct ImportCase {
label: &'static str,
body: Vec<u8>,
expected_status: StatusCode,
expected_code: &'static str,
expected_field: &'static str,
}
fn case(
label: &'static str,
body: Vec<u8>,
status: StatusCode,
code: &'static str,
field: &'static str,
) -> ImportCase {
ImportCase {
label,
body,
expected_status: status,
expected_code: code,
expected_field: field,
}
}
fn valid_import_envelope() -> Value {
envelope(
resource_block(
"crank://e2e/story39-import",
"story39_import",
"story39 import fixture",
"text",
"text/plain",
),
"draft",
1,
b"story39 import body\n",
)
}
fn serialized(value: &Value) -> Vec<u8> {
serde_json::to_vec(value).expect("case envelope must serialize")
}
fn mutated(label: &'static str, mutate: impl FnOnce(&mut Value)) -> ImportCase {
let mut value = valid_import_envelope();
mutate(&mut value);
let body = serialized(&value);
case(
label,
body,
StatusCode::BAD_REQUEST,
"resource_portability_envelope_invalid",
"envelope",
)
}
fn malformed_cases() -> Vec<ImportCase> {
vec![
case(
"not-json",
b"{".to_vec(),
StatusCode::BAD_REQUEST,
"resource_portability_envelope_invalid",
"envelope",
),
case(
"trailing-garbage",
[serialized(&valid_import_envelope()), b"trailing".to_vec()].concat(),
StatusCode::BAD_REQUEST,
"resource_portability_envelope_invalid",
"envelope",
),
mutated("wrong-format", |v| v["format"] = json!("crank-resource")),
mutated("unsupported-version-2", |v| v["version"] = json!(2)),
mutated("unknown-artifact-key", |v| {
v["artifact_ref"] = json!("blobs/aa/bb")
}),
mutated("foreign-owner-key", |v| {
v["owner_user_id"] = json!("user_other")
}),
mutated("auto-published-status", |v| {
v["status"] = json!("published")
}),
mutated("workspace-injection", |v| {
v["workspace_id"] = json!("ws_other")
}),
mutated("resource-id-injection", |v| {
v["resource_id"] = json!("res_existing")
}),
mutated("missing-content", |v| {
v.as_object_mut()
.expect("envelope object")
.remove("content");
}),
mutated("resource-block-missing", |v| {
v.as_object_mut()
.expect("envelope object")
.remove("resource");
}),
mutated("content-not-object", |v| v["content"] = json!("crank://x")),
mutated("nested-unknown-key", |v| {
v["content"]["artifact"] = json!("blobs/aa/bb")
}),
mutated("invalid-base64", |v| {
v["content"]["base64"] = json!("not base64!")
}),
mutated("digest-not-hex", |v| {
v["content"]["digest"] = json!("z".repeat(64))
}),
mutated("source-kind-invalid", |v| {
v["source"]["kind"] = json!("archive")
}),
mutated("source-version-zero", |v| v["source"]["version"] = json!(0)),
case(
"uri-invalid",
serialized(&{
let mut value = valid_import_envelope();
value["resource"]["uri"] = json!("crank://a");
value
}),
StatusCode::BAD_REQUEST,
"resource_uri_invalid",
"uri",
),
case(
"mime-not-allowed",
serialized(&{
let mut value = valid_import_envelope();
value["resource"]["mime_type"] = json!("application/zip");
value
}),
StatusCode::BAD_REQUEST,
"resource_mime_not_allowed",
"mime_type",
),
]
}
async fn resource_counts(registry: &crank_registry::PostgresRegistry) -> (i64, i64, i64) {
(
table_row_count(registry.pool(), "resources").await,
table_row_count(registry.pool(), "resource_versions").await,
table_row_count(registry.pool(), "artifact_blobs").await,
)
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at03_malformed_envelopes_are_rejected_without_state_change() {
let (registry, server, client) = spawn_authorized("story39_malformed").await;
// Позитивный контроль: без него «ничего не создано» ничего не доказывает.
let (baseline_status, baseline_text, _) = list_resources(&client, &server).await;
assert_eq!(
baseline_status,
StatusCode::OK,
"existing list contract must stay GREEN: {baseline_text}"
);
let before = resource_counts(&registry).await;
let mut mismatches = Vec::new();
let cases = malformed_cases();
for case in &cases {
let (status, text, body) = post_import_raw(&client, &server, case.body.clone()).await;
let code = body["error"]["code"].as_str().unwrap_or("<absent>");
let field = body["error"]["context"]["field"]
.as_str()
.unwrap_or("<absent>");
if status != case.expected_status
|| code != case.expected_code
|| field != case.expected_field
{
mismatches.push(format!(
"{}: expected {}/{}/{}, observed {} (body={text})",
case.label,
case.expected_status,
case.expected_code,
case.expected_field,
error_signature(status, &body)
));
continue;
}
assert_safe_wire_value(&body, case.label);
}
assert!(
mismatches.is_empty(),
"AT-3.9-03 malformed import envelopes ({}/{}):\n{}",
mismatches.len(),
cases.len(),
mismatches.join("\n")
);
assert_eq!(
resource_counts(&registry).await,
before,
"a rejected envelope must not create resources, versions or artifacts"
);
let (_, _, items) = list_resources(&client, &server).await;
assert_eq!(
items["items"].as_array().map(Vec::len),
Some(0),
"a rejected envelope must not add a Draft to the list: {items}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at03_digest_size_and_oversize_envelopes_are_rejected() {
let (registry, server, client) = spawn_authorized("story39_bounds").await;
let before = resource_counts(&registry).await;
let bytes = b"story39 integrity body\n";
let base = valid_import_envelope();
let mut tampered_digest = base.clone();
tampered_digest["content"]["digest"] = json!(sha256_hex(b"different body"));
let (status, text, body) = post_import(&client, &server, &tampered_digest).await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"digest mismatch must be rejected (AT-3.9-03); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_artifact_integrity"));
assert_eq!(body["error"]["context"]["field"], json!("content"));
assert_safe_wire_value(&body, "digest mismatch");
let mut tampered_size = base.clone();
tampered_size["content"]["size_bytes"] = json!(bytes.len() as i64 + 1);
let (status, text, body) = post_import(&client, &server, &tampered_size).await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"size mismatch must be rejected (AT-3.9-03); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_artifact_integrity"));
assert_safe_wire_value(&body, "size mismatch");
let oversized = vec![b'a'; CONTENT_LIMIT + 1];
let oversized_envelope = envelope(
resource_block(
"crank://e2e/story39-oversized",
"story39_oversized",
"",
"text",
"text/plain",
),
"draft",
1,
&oversized,
);
let (status, text, body) = post_import(&client, &server, &oversized_envelope).await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"content above the storage limit must be rejected with 413 (AT-3.9-03); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_content_too_large"));
assert_eq!(body["error"]["context"]["field"], json!("content"));
assert_safe_wire_value(&body, "oversized envelope");
assert_eq!(
resource_counts(&registry).await,
before,
"rejected digest/size/oversized envelopes must not change any stored state"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at03_cross_workspace_export_denied_import_allowed() {
let (registry, server, client) = spawn_authorized("story39_cross_workspace").await;
let bytes = b"story39 cross workspace body\n";
let metadata = draft_metadata(
"crank://e2e/story39-cross",
"story39_cross",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&metadata,
bytes,
"draft.txt",
"text/plain",
)
.await;
let source_id = created_resource_id(&created);
// WorkspaceB доступен той же сессии (Owner-membership), но Resource принадлежит WorkspaceA.
let other = create_owned_workspace(&registry).await;
let other_base = workspace_base(server.as_ref(), other.as_str());
let other_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, body) = export_draft(&other_client, &other_base, &source_id).await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"a foreign-workspace Resource must not be exportable (AT-3.9-03); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
json!("resource_not_found"),
"a foreign-workspace export must return the stable not-found code"
);
assert!(
!text.contains("crank://e2e/story39-cross") && !text.contains(&sha256_hex(bytes)),
"a denied export must not leak foreign uri/digest: {text}"
);
// Свой workspace экспортируется, чужой target принимает envelope как новый Draft.
let (status, text, exported) = export_draft(&client, &server, &source_id).await;
assert_eq!(
status,
StatusCode::OK,
"own workspace export must succeed: {text}"
);
let (imported_id, imported) = assert_import_ok(&other_client, &other_base, &exported).await;
assert_ne!(imported_id, source_id);
assert_eq!(imported["resource"]["status"], json!("draft"));
assert_eq!(
imported["resource"]["latest_published_version"],
Value::Null
);
let (_, _, other_list) = list_resources(&other_client, &other_base).await;
assert_eq!(
other_list["items"].as_array().map(Vec::len),
Some(1),
"the target workspace owns exactly the imported Draft: {other_list}"
);
let (_, _, source_list) = list_resources(&client, &server).await;
assert_eq!(
source_list["items"].as_array().map(Vec::len),
Some(1),
"the source workspace must not gain a copy: {source_list}"
);
// Никакого upsert: повторный импорт того же envelope в тот же workspace — конфликт.
let (status, text, body) = post_import(&other_client, &other_base, &exported).await;
assert_eq!(
status,
StatusCode::CONFLICT,
"re-importing the same identity must conflict, not upsert (AT-3.9-01); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_uri_duplicate"));
}
// AT-3.9-01: существующие guard-слои не обходятся импортом.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story39_at01_guards_are_not_bypassed() {
let (registry, server, client) = spawn_authorized("story39_guards").await;
let envelope_value = valid_import_envelope();
let anonymous = reqwest::Client::new();
let (status, text, body) = post_import(&anonymous, &server, &envelope_value).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"import requires an authenticated session: {text}"
);
assert_eq!(body["error"]["code"], json!("unauthorized"));
assert_safe_wire_value(&body, "anonymous import");
let without_csrf =
login_client_without_csrf(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = post_import(&without_csrf, &server, &envelope_value).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"import must keep the CSRF guard: {text}"
);
let foreign_origin =
login_client_with_foreign_origin(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = post_import(&foreign_origin, &server, &envelope_value).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"import must keep the origin guard: {text}"
);
let (viewer_email, viewer_password) = ensure_viewer_membership(&registry).await;
let viewer = login_client(&server, viewer_email, viewer_password).await;
let (status, text, _) = post_import(&viewer, &server, &envelope_value).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a Viewer must not import Resources: {text}"
);
// Ни один отказ не создал Draft.
let (_, _, items) = list_resources(&viewer, &server).await;
assert_eq!(
items["items"].as_array().map(Vec::len),
Some(0),
"guarded import attempts must not create a Draft: {items}"
);
// Позитивный контроль: тот же endpoint с валидной сессией Owner создаёт Draft,
// поэтому разрешения выше действительно относятся к работающему импорту.
let (imported_id, imported) = assert_import_ok(&client, &server, &envelope_value).await;
assert_eq!(imported["resource"]["status"], json!("draft"));
assert_eq!(
imported["resource"]["latest_published_version"],
Value::Null
);
let (_, _, items) = list_resources(&viewer, &server).await;
assert_eq!(
items["items"].as_array().map(Vec::len),
Some(1),
"the positive control must create exactly one Draft: {imported_id} {items}"
);
}