Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
605 lines
22 KiB
Rust
605 lines
22 KiB
Rust
//! AT-3.6-02: Draft flow, стабильные идентификаторы, приоритеты кодов (D-20) и
|
||
//! отсутствие раскрытия (D-18). Подмодуль `tests/integration/resources.rs`.
|
||
|
||
use super::helpers::{
|
||
CONTENT_LIMIT, DEFAULT_WORKSPACE_ID, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD,
|
||
assert_draft_identity, create_draft, create_owned_workspace, created_resource_id, draft_form,
|
||
draft_metadata, draft_updated_at, error_signature, file_part, get_card, login_client,
|
||
post_draft_raw, read_content, read_preview, read_response, run_grammar_matrix, sha256_hex,
|
||
spawn_authorized, table_row_count,
|
||
};
|
||
use super::observe_draft_state;
|
||
use reqwest::StatusCode;
|
||
use reqwest::multipart::Form;
|
||
use serde_json::json;
|
||
use serial_test::serial;
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Harness-контроль (существующее поведение, обязан остаться GREEN)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_control_existing_session_and_multipart_harness_are_functional() {
|
||
let (_registry, server, client) = spawn_authorized("story36_control").await;
|
||
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.get(format!("{server}/operations"))
|
||
.send()
|
||
.await
|
||
.expect("operations request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"existing GET /operations must stay GREEN; body={text}"
|
||
);
|
||
assert!(
|
||
body["items"].is_array(),
|
||
"existing list payload keeps its shape: {text}"
|
||
);
|
||
|
||
let document = "openapi: 3.0.3\ninfo: { title: Harness }\npaths:\n /ping:\n get:\n responses:\n '200': { description: ok }\n";
|
||
let form = Form::new().part(
|
||
"file",
|
||
file_part(document.as_bytes(), "openapi.yaml", "application/yaml"),
|
||
);
|
||
let (status, text, _) = read_response(
|
||
client
|
||
.post(format!("{server}/imports/openapi/preview"))
|
||
.multipart(form)
|
||
.send()
|
||
.await
|
||
.expect("multipart control request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"existing multipart preview must stay GREEN — session/CSRF/multipart harness works; body={text}"
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// AT-3.6-02: Draft flow и стабильные идентификаторы
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_text_json_binary_drafts_roundtrip_and_keep_stable_identifiers() {
|
||
let (registry, server, client) = spawn_authorized("story36_roundtrip").await;
|
||
|
||
let text_bytes = "Заголовок\nвторая строка\n".as_bytes();
|
||
let text_meta = draft_metadata(
|
||
"crank://docs/readme",
|
||
"readme_page",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
let created = create_draft(
|
||
&client,
|
||
&server,
|
||
&text_meta,
|
||
text_bytes,
|
||
"readme.txt",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
let text_id = created_resource_id(&created);
|
||
assert_draft_identity(&created, "crank://docs/readme", "readme_page", "text");
|
||
assert_eq!(created["resource"]["status"], json!("draft"));
|
||
assert_eq!(created["version"]["version"], json!(1));
|
||
assert_eq!(created["version"]["size_bytes"], json!(text_bytes.len()));
|
||
assert_eq!(created["findings"], json!([]));
|
||
|
||
let card = get_card(&client, &server, &text_id).await;
|
||
assert_draft_identity(&card, "crank://docs/readme", "readme_page", "text");
|
||
assert_eq!(card["version"]["mime_type"], json!("text/plain"));
|
||
assert_eq!(card["version"]["sensitivity"], json!("internal"));
|
||
assert_eq!(card["version"]["size_bytes"], json!(text_bytes.len()));
|
||
let digest = card["version"]["digest"]
|
||
.as_str()
|
||
.expect("Draft card must expose the exact content digest")
|
||
.to_owned();
|
||
// Независимый оракул: digest сверяется с SHA-256, посчитанным самим тестом (не с длиной).
|
||
assert_eq!(
|
||
digest,
|
||
sha256_hex(text_bytes),
|
||
"the Draft card must expose the digest of the stored bytes"
|
||
);
|
||
let updated_at = draft_updated_at(&card);
|
||
|
||
let (status, text, preview) = read_preview(&client, &server, &text_id).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"preview must exist; observed {} body={text}",
|
||
error_signature(status, &preview)
|
||
);
|
||
assert_eq!(
|
||
preview["preview"]["text"],
|
||
json!(String::from_utf8_lossy(text_bytes))
|
||
);
|
||
assert_eq!(
|
||
read_content(&client, &server, &text_id).await,
|
||
text_bytes.to_vec(),
|
||
"content must return the exact saved bytes"
|
||
);
|
||
|
||
let json_document =
|
||
"{\"b\":1,\"a\":[1,2,3],\"дубликат\":1,\"дубликат\":2,\"nested\":{\"n\":1e308}}";
|
||
let json_meta = draft_metadata(
|
||
"crank://docs/payload",
|
||
"payload_json",
|
||
"json",
|
||
"application/json",
|
||
"internal",
|
||
);
|
||
let created = create_draft(
|
||
&client,
|
||
&server,
|
||
&json_meta,
|
||
json_document.as_bytes(),
|
||
"payload.json",
|
||
"application/json",
|
||
)
|
||
.await;
|
||
assert_eq!(created["resource"]["kind"], json!("json"));
|
||
let json_id = created_resource_id(&created);
|
||
let json_card = get_card(&client, &server, &json_id).await;
|
||
assert_eq!(
|
||
json_card["version"]["digest"],
|
||
json!(sha256_hex(json_document.as_bytes())),
|
||
"JSON digest must be the SHA-256 of the stored bytes"
|
||
);
|
||
assert_eq!(
|
||
json_card["version"]["size_bytes"],
|
||
json!(json_document.len())
|
||
);
|
||
let (status, text, preview) = read_preview(&client, &server, &json_id).await;
|
||
assert_eq!(status, StatusCode::OK, "json preview must exist: {text}");
|
||
assert_eq!(
|
||
preview["preview"]["text"],
|
||
json!(json_document),
|
||
"JSON preview must return the exact stored bytes, not a re-serialized value (D-8): {text}"
|
||
);
|
||
assert_eq!(
|
||
read_content(&client, &server, &json_id).await,
|
||
json_document.as_bytes().to_vec(),
|
||
"byte-exact JSON readback: key order and duplicate keys preserved"
|
||
);
|
||
|
||
let binary_bytes: &[u8] = &[0x89, b'P', b'N', b'G', 0x00, 0xFF, 0x80, 0xC3, 0x28];
|
||
let binary_meta = draft_metadata(
|
||
"crank://img/logo",
|
||
"logo_png",
|
||
"binary",
|
||
"image/png",
|
||
"public",
|
||
);
|
||
let created = create_draft(
|
||
&client,
|
||
&server,
|
||
&binary_meta,
|
||
binary_bytes,
|
||
"logo.png",
|
||
"image/png",
|
||
)
|
||
.await;
|
||
let binary_id = created_resource_id(&created);
|
||
let binary_card = get_card(&client, &server, &binary_id).await;
|
||
assert_eq!(
|
||
binary_card["version"]["digest"],
|
||
json!(sha256_hex(binary_bytes)),
|
||
"binary digest must be the SHA-256 of the stored bytes"
|
||
);
|
||
assert_eq!(
|
||
binary_card["version"]["size_bytes"],
|
||
json!(binary_bytes.len())
|
||
);
|
||
assert_eq!(
|
||
read_content(&client, &server, &binary_id).await,
|
||
binary_bytes.to_vec(),
|
||
"binary bytes must round-trip unchanged"
|
||
);
|
||
let (status, text, preview) = read_preview(&client, &server, &binary_id).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"binary preview must exist; body={text}"
|
||
);
|
||
assert!(
|
||
preview["preview"]["text"].is_null(),
|
||
"binary kind must not return bytes as text (D-6): {text}"
|
||
);
|
||
|
||
// D-16: позитивный PUT не передаёт uri/name/kind вовсе; их присутствие — уже нарушение.
|
||
let positive_update = json!({
|
||
"description": "обновлённое описание",
|
||
"mime_type": "text/plain",
|
||
"sensitivity": "public",
|
||
"expected_updated_at": updated_at,
|
||
});
|
||
let new_text = "изменённый текст\n".as_bytes();
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.put(format!("{server}/resources/{text_id}"))
|
||
.multipart(draft_form(
|
||
&positive_update,
|
||
new_text,
|
||
"readme.txt",
|
||
"text/plain",
|
||
))
|
||
.send()
|
||
.await
|
||
.expect("update request must complete"),
|
||
)
|
||
.await;
|
||
assert!(
|
||
status.is_success(),
|
||
"PUT with a fresh precondition must succeed (SPEC pins only 428/400/404 here); observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["version"]["version"], json!(2));
|
||
|
||
let reloaded = get_card(&client, &server, &text_id).await;
|
||
assert_draft_identity(&reloaded, "crank://docs/readme", "readme_page", "text");
|
||
assert_eq!(reloaded["version"]["version"], json!(2));
|
||
let reloaded_digest = reloaded["version"]["digest"]
|
||
.as_str()
|
||
.expect("the updated card must expose its digest")
|
||
.to_owned();
|
||
assert_eq!(
|
||
reloaded_digest,
|
||
sha256_hex(new_text),
|
||
"the new bytes must be reflected in the digest (AT-3.6-03)"
|
||
);
|
||
assert_ne!(
|
||
reloaded_digest, digest,
|
||
"new bytes must produce a new digest (AT-3.6-03)"
|
||
);
|
||
assert_eq!(
|
||
read_content(&client, &server, &text_id).await,
|
||
new_text.to_vec(),
|
||
"the current version content must be returned"
|
||
);
|
||
|
||
assert_eq!(table_row_count(registry.pool(), "resources").await, 3);
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "resource_versions").await,
|
||
4
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_identifier_grammar_boundaries() {
|
||
let (_registry, server, client) = spawn_authorized("story36_grammar").await;
|
||
run_grammar_matrix(&client, &server).await;
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_uri_and_name_are_immutable_after_update() {
|
||
let (_registry, server, client) = spawn_authorized("story36_immutable").await;
|
||
|
||
let meta = draft_metadata(
|
||
"crank://immutable/draft",
|
||
"immutable_draft",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
let created = create_draft(
|
||
&client,
|
||
&server,
|
||
&meta,
|
||
b"first body",
|
||
"draft.txt",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
let id = created_resource_id(&created);
|
||
let updated_at = draft_updated_at(&get_card(&client, &server, &id).await);
|
||
|
||
let base = |field: &str, value: &str| {
|
||
let mut metadata = json!({
|
||
"description": "",
|
||
"mime_type": "text/plain",
|
||
"sensitivity": "internal",
|
||
"expected_updated_at": updated_at,
|
||
});
|
||
metadata[field] = json!(value);
|
||
metadata
|
||
};
|
||
|
||
for (field, value) in [
|
||
("uri", "crank://immutable/other"),
|
||
("name", "other_name"),
|
||
("kind", "json"),
|
||
] {
|
||
let metadata = base(field, value);
|
||
let mime = if field == "kind" {
|
||
"application/json"
|
||
} else {
|
||
"text/plain"
|
||
};
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.put(format!("{server}/resources/{id}"))
|
||
.multipart(draft_form(&metadata, b"second body", "draft.txt", mime))
|
||
.send()
|
||
.await
|
||
.expect("immutability request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::BAD_REQUEST,
|
||
"changing `{field}` must be rejected (D-16 `resource_field_immutable`); observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], json!("resource_field_immutable"));
|
||
assert_eq!(
|
||
body["error"]["context"]["field"],
|
||
json!(field),
|
||
"the offending field must be reported"
|
||
);
|
||
}
|
||
|
||
let reloaded = get_card(&client, &server, &id).await;
|
||
assert_draft_identity(
|
||
&reloaded,
|
||
"crank://immutable/draft",
|
||
"immutable_draft",
|
||
"text",
|
||
);
|
||
assert_eq!(
|
||
reloaded["version"]["version"],
|
||
json!(1),
|
||
"rejected updates must not create a version"
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_duplicate_identifier_conflict() {
|
||
let (registry, server, client) = spawn_authorized("story36_duplicate").await;
|
||
|
||
let meta = draft_metadata(
|
||
"crank://dup/draft",
|
||
"dup_draft",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
let accepted = create_draft(
|
||
&client,
|
||
&server,
|
||
&meta,
|
||
b"first payload",
|
||
"draft.txt",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
let accepted_id = created_resource_id(&accepted);
|
||
|
||
// F7 (TL run109): «до» — полное наблюдаемое состояние принятого Draft, а не
|
||
// только два счётчика: карточка (идентификаторы/указатель/версия/metadata/
|
||
// timestamps), точные bytes и итоги **всех четырёх** отношений V16.
|
||
let before = observe_draft_state(®istry, &client, &server, &accepted_id).await;
|
||
assert_draft_identity(&before.card, "crank://dup/draft", "dup_draft", "text");
|
||
assert_eq!(before.card["version"]["version"], json!(1));
|
||
assert_eq!(before.bytes, b"first payload".to_vec());
|
||
assert_eq!(before.versions, 1);
|
||
assert_eq!(before.owning_refs, 1);
|
||
assert_eq!(
|
||
before.blobs, 1,
|
||
"the accepted bytes own exactly one blob row"
|
||
);
|
||
|
||
let name_conflict = draft_metadata(
|
||
"crank://dup/other",
|
||
"dup_draft",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
// Однофакторность (D-14/D-20): у каждого конфликта нарушен ровно один uniqueness-фактор,
|
||
// поэтому ожидаемый код не зависит от порядка проверки двух constraints.
|
||
let uri_conflict = draft_metadata(
|
||
"crank://dup/draft",
|
||
"dup_draft_other",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
|
||
for (label, metadata, code, field) in [
|
||
("uri", &uri_conflict, "resource_uri_duplicate", "uri"),
|
||
("name", &name_conflict, "resource_name_duplicate", "name"),
|
||
] {
|
||
let (status, _, text, body) =
|
||
post_draft_raw(&client, &server, metadata, b"second payload", "text/plain").await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CONFLICT,
|
||
"duplicate {label} must be a conflict (D-14); observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], json!(code));
|
||
assert_eq!(body["error"]["context"]["field"], json!(field));
|
||
// R3 (TL run113 F7): полное состояние принятого Draft наблюдается **сразу**
|
||
// после каждого отказа, а не только после всей пары: иначе откат второго
|
||
// отказа маскировал бы изменение, оставленное первым.
|
||
let after_each = observe_draft_state(®istry, &client, &server, &accepted_id).await;
|
||
assert_eq!(
|
||
after_each, before,
|
||
"the duplicate {label} refusal must leave the whole accepted Draft — all four \
|
||
relations, the current pointer/version/metadata/timestamps and the readable old \
|
||
bytes — unchanged, observed right after that refusal (F7)"
|
||
);
|
||
}
|
||
|
||
// D-19 п.2/AD-10: у конфликта проверяется отсутствие принятых строк (orphan bytes
|
||
// в файловом store допустимы), поэтому сравнивается полное состояние: все четыре
|
||
// отношения, текущий указатель, версия, metadata, timestamps и старые bytes (F7).
|
||
let after = observe_draft_state(®istry, &client, &server, &accepted_id).await;
|
||
assert_eq!(
|
||
after, before,
|
||
"each duplicate refusal must leave the whole accepted Draft — all four relations, the \
|
||
current pointer/version/metadata/timestamps and the readable old bytes — unchanged (F7)"
|
||
);
|
||
assert_eq!(table_row_count(registry.pool(), "resources").await, 1);
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "resource_versions").await,
|
||
1
|
||
);
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "artifact_sources").await,
|
||
1,
|
||
"only the accepted draft keeps an owning reference"
|
||
);
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "artifact_blobs").await,
|
||
1,
|
||
"a rolled-back duplicate create must not add a blob row (F7)"
|
||
);
|
||
}
|
||
// ---------------------------------------------------------------------------
|
||
// AT-3.6-02: приоритет кодов (D-20) и отсутствие раскрытия (D-18)
|
||
// ---------------------------------------------------------------------------
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_metadata_rejection_precedes_content_rejection() {
|
||
let (_registry, server, client) = spawn_authorized("story36_precedence_metadata").await;
|
||
|
||
// E побеждает G: невалидное поле метаданных + превышающее содержимое → 400, не 413
|
||
let oversized = vec![b'a'; CONTENT_LIMIT + 1];
|
||
let meta = draft_metadata(
|
||
"crank://a",
|
||
"precedence_a",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
let (status, _, text, body) =
|
||
post_draft_raw(&client, &server, &meta, &oversized, "text/plain").await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::BAD_REQUEST,
|
||
"metadata rejection (E) must win over content rejection (G), D-20; observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], json!("resource_uri_invalid"));
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_missing_resource_is_not_found_before_content_validation() {
|
||
let (_registry, server, client) = spawn_authorized("story36_precedence_missing").await;
|
||
|
||
// C побеждает G: неизвестный resource_id + невалидное содержимое → 404, не 422
|
||
let metadata = json!({
|
||
"uri": "crank://precedence/missing",
|
||
"name": "precedence_missing",
|
||
"description": "",
|
||
"kind": "text",
|
||
"mime_type": "text/plain",
|
||
"sensitivity": "internal",
|
||
"expected_updated_at": "2026-01-01T00:00:00Z",
|
||
});
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.put(format!("{server}/resources/res_missing_story36"))
|
||
.multipart(draft_form(
|
||
&metadata,
|
||
&[0xC3, 0x28],
|
||
"draft.txt",
|
||
"text/plain",
|
||
))
|
||
.send()
|
||
.await
|
||
.expect("missing resource request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::NOT_FOUND,
|
||
"resolution (C) must win over content validation (G), D-20; observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], json!("resource_not_found"));
|
||
assert_eq!(body["error"]["context"]["field"], json!("resource_id"));
|
||
assert!(
|
||
!text.contains("uri") && !text.contains("name") && !text.contains("digest"),
|
||
"a missing Resource must not disclose any artifact metadata: {text}"
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story36_at02_foreign_resource_is_not_found_without_disclosure() {
|
||
let (registry, server, _client) = spawn_authorized("story36_foreign_resource").await;
|
||
// WorkspaceB принадлежит тому же аккаунту (Owner membership), поэтому доступ к workspace
|
||
// есть, а Resource — чужая сущность: негатив проверяет entity-level ownership (D-18),
|
||
// а не workspace-guard.
|
||
let owned_workspace = create_owned_workspace(®istry).await;
|
||
let workspace_b = server
|
||
.as_ref()
|
||
.replace(DEFAULT_WORKSPACE_ID, owned_workspace.as_str());
|
||
// Сессия логинится уже после выдачи membership.
|
||
let client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
|
||
|
||
let meta = draft_metadata(
|
||
"crank://foreign/draft",
|
||
"foreign_draft",
|
||
"text",
|
||
"text/plain",
|
||
"secret",
|
||
);
|
||
// Positive control: тот же аккаунт в своём WorkspaceB создаёт Resource (сущность существует).
|
||
let created = create_draft(
|
||
&client,
|
||
&workspace_b,
|
||
&meta,
|
||
b"foreign body",
|
||
"foreign.txt",
|
||
"text/plain",
|
||
)
|
||
.await;
|
||
let foreign_id = created_resource_id(&created);
|
||
|
||
// Чтение из WorkspaceA: Resource существует, но не здесь → 404 без раскрытия.
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.get(format!("{server}/resources/{foreign_id}"))
|
||
.send()
|
||
.await
|
||
.expect("foreign resource request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::NOT_FOUND,
|
||
"a Resource of another workspace must be 404 without disclosure (D-18); observed {} body={text}",
|
||
error_signature(status, &body)
|
||
);
|
||
assert_eq!(body["error"]["code"], json!("resource_not_found"));
|
||
assert_eq!(body["error"]["context"]["field"], json!("resource_id"));
|
||
assert!(
|
||
!text.contains("foreign_draft")
|
||
&& !text.contains("crank://foreign/draft")
|
||
&& !text.contains("text/plain"),
|
||
"the refusal must not disclose the foreign Resource metadata: {text}"
|
||
);
|
||
|
||
// Positive control: в своём WorkspaceB тот же Resource читается.
|
||
let own_card = get_card(&client, &workspace_b, &foreign_id).await;
|
||
assert_draft_identity(&own_card, "crank://foreign/draft", "foreign_draft", "text");
|
||
}
|