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

605 lines
22 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.
//! 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(&registry, &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(&registry, &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(&registry, &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(&registry).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");
}