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

587 lines
21 KiB
Rust

//! AT-3.6-04/05/07 для содержимого: JSON, границы размера, форма запроса и
//! инертный ответ скачивания. Подмодуль `tests/integration/resources.rs`.
use super::helpers::{
CONTENT_LIMIT, create_draft, created_resource_id, draft_metadata, error_signature, get_card,
post_draft_raw, read_content, read_preview, read_response, run_inert_download_case,
run_malformed_json_matrix, sha256_hex, spawn_authorized, table_row_count,
};
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
// ---------------------------------------------------------------------------
// AT-3.6-04: JSON (семантика, точные границы парсера, oversized)
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at04_malformed_and_oversized_json_rejected() {
let (registry, server, client) = spawn_authorized("story36_json").await;
let (mismatches, total) = run_malformed_json_matrix(&client, &server).await;
assert!(
mismatches.is_empty(),
"AT-3.6-04 malformed JSON mismatches ({}/{total}):\n{}",
mismatches.len(),
mismatches.join("\n")
);
assert_eq!(table_row_count(registry.pool(), "resources").await, 0);
// L+1 отвергается до publication
let oversized = format!("{{\"pad\":\"{}\"}}", "a".repeat(CONTENT_LIMIT));
let meta = draft_metadata(
"crank://json/oversized",
"json_oversized",
"json",
"application/json",
"internal",
);
let (status, _, text, body) = post_draft_raw(
&client,
&server,
&meta,
oversized.as_bytes(),
"application/json",
)
.await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"oversized JSON must be rejected with 413 before publication (D-8); 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"));
// принятые числа и byte-exact семантика
let accepted = "{\"long\":18446744073709551616,\"small\":1e-400,\"big\":1e308,\"zero\":-0,\"dup\":1,\"dup\":2}";
let meta = draft_metadata(
"crank://json/accepted",
"json_accepted",
"json",
"application/json",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
accepted.as_bytes(),
"payload.json",
"application/json",
)
.await;
let id = created_resource_id(&created);
assert_eq!(
read_content(&client, &server, &id).await,
accepted.as_bytes().to_vec(),
"stored JSON must be byte-exact (key order, duplicate keys and numeric lexemes preserved)"
);
}
// ---------------------------------------------------------------------------
// AT-3.6-05: UTF-8 и границы размера
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at05_oversized_text_body_is_rejected_without_truncation() {
let (registry, server, client) = spawn_authorized("story36_size").await;
let meta = draft_metadata(
"crank://size/limit",
"size_limit",
"text",
"text/plain",
"internal",
);
let oversized = vec![b'a'; CONTENT_LIMIT + 1];
let (status, _, text, body) =
post_draft_raw(&client, &server, &meta, &oversized, "text/plain").await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"L+1 must be rejected as a whole (no unsafe truncation, D-9/D-20 G); 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_eq!(table_row_count(registry.pool(), "resources").await, 0);
assert_eq!(table_row_count(registry.pool(), "artifact_blobs").await, 0);
// L принимается включительно, байты не подменяются
let accepted = vec![b'b'; CONTENT_LIMIT];
let meta = draft_metadata(
"crank://size/exact",
"size_exact",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
&accepted,
"draft.txt",
"text/plain",
)
.await;
let id = created_resource_id(&created);
let bytes = read_content(&client, &server, &id).await;
assert_eq!(bytes.len(), CONTENT_LIMIT, "L must be accepted inclusively");
assert_eq!(bytes, accepted, "L bytes must round-trip unchanged");
}
// ---------------------------------------------------------------------------
// AT-3.6-07: скачивание инертно, заголовки content-части бессильны (D-6/D-16)
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at07_download_is_inert_octet_stream_attachment() {
let (_registry, server, client) = spawn_authorized("story36_download").await;
run_inert_download_case(&client, &server).await;
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at04_truncated_multipart_is_a_client_error() {
let (registry, server, client) = spawn_authorized("story36_truncated").await;
// Малый truncated multipart внутри body window: отказ формы запроса, не 413 (P2).
let metadata = serde_json::to_string(&draft_metadata(
"crank://truncated/draft",
"truncated_draft",
"text",
"text/plain",
"internal",
))
.expect("metadata must serialize");
let boundary = "story36truncatedboundary";
let truncated = format!(
"--{boundary}\r\nContent-Disposition: form-data; name=\"metadata\"\r\nContent-Type: application/json\r\n\r\n{metadata}\r\n--{boundary}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"draft.txt\"\r\nContent-Type: text/plain\r\n\r\npayload without a closing boundary"
);
let (status, text, body) = read_response(
client
.post(format!("{server}/resources"))
.header(
"content-type",
format!("multipart/form-data; boundary={boundary}"),
)
.body(truncated)
.send()
.await
.expect("truncated request must complete"),
)
.await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"a truncated multipart body inside the body window is a client error (P2), not 413; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(table_row_count(registry.pool(), "resources").await, 0);
// Контроль: действительное превышение configured L остаётся 413 с точным кодом.
let meta = draft_metadata(
"crank://truncated/oversized",
"truncated_oversized",
"text",
"text/plain",
"internal",
);
let oversized = vec![b'a'; CONTENT_LIMIT + 1];
let (status, _, text, body) =
post_draft_raw(&client, &server, &meta, &oversized, "text/plain").await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"a real limit violation must stay 413 (P2); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_content_too_large"));
}
// ---------------------------------------------------------------------------
// AT-3.6-04 (F2, TL run105): полная числовая/структурная политика D-8.1 на **реальном**
// пути сохранения и чтения — `POST` → `GET .../content` → `GET .../preview`.
//
// Домен уже проверяет политику на возвращённом `Vec` (`ResourceMetadata::validate_json`
// не читает физическое хранилище), поэтому здесь те же принятые/отвергнутые документы
// проходят настоящую запись, байтовое чтение и предпросмотр: точные digest/size, точные
// bytes и точный текст предпросмотра. Отвергнутый документ не должен ни создавать строк,
// ни менять уже принятое состояние.
// ---------------------------------------------------------------------------
/// Принятые числовые лексемы — тот же набор, что в locked-матрице домена
/// (`crates/crank-core/tests/unit/resource_drafts.rs`, D-8.1).
const NUMERIC_ACCEPTED: [&str; 16] = [
"0",
"-0",
"9007199254740993",
"18446744073709551615",
"18446744073709551616",
"-9223372036854775808",
"-9223372036854775809",
"0.1000000000000000000000001",
"1.000000000000000000000000000000001",
"123456789012345678901234567890",
"1e308",
"1.7e308",
"1e-309",
"1e-400",
"1e-1000000000000000000000",
"0e1000000000000000000000",
];
/// Принятые top-level значения и литеральный Unicode (D-8): bytes хранятся дословно.
const TOP_LEVEL_ACCEPTED: [&str; 15] = [
"null",
"true",
"false",
"0",
"-1",
"\"text\"",
"123",
"[]",
"{}",
"{\"ключ\":\"значение\"}",
"\"\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442\"",
"{\"привет\":\"мир\"}",
"{\"emoji\":\"🚀🦀\"}",
"\"e\\u0301\"",
"[\"Привет\",\"🚀\",null,false]",
];
/// Отвергнутые числовые лексемы: вне представимости f64 — невалидный JSON (D-8.1).
const NUMERIC_REJECTED: [&str; 5] = [
"1e309",
"-1e309",
"9e308",
"1.8e308",
"1e1000000000000000000000",
];
/// Якорный принятый Draft, состояние которого обязано пережить все отказы.
const ANCHOR_BYTES: &[u8] = b"{\"anchor\":\"kept\",\"n\":1}";
/// Один принятый JSON-документ на реальном пути: запись, точные bytes и предпросмотр.
///
/// Наблюдения агрегируются (не паникуют на первом расхождении), поэтому каждый документ
/// матрицы действительно исполняется и попадает в отчёт.
#[allow(clippy::too_many_arguments)]
async fn observe_accepted_json_document(
client: &reqwest::Client,
server: impl AsRef<str>,
index: usize,
label: &str,
document: &str,
observations: &mut Vec<String>,
mismatches: &mut Vec<String>,
) {
let server = server.as_ref();
let bytes = document.as_bytes();
let uri = format!("crank://json/policy/case{index}");
let name = format!("json_policy_case{index}");
let meta = draft_metadata(&uri, &name, "json", "application/json", "internal");
let (status, _traceable, text, body) =
post_draft_raw(client, server, &meta, bytes, "application/json").await;
if status != StatusCode::CREATED {
observations.push(format!("{label}: create status={status}"));
mismatches.push(format!(
"{label}: an accepted document must be stored; observed {} body={text}",
error_signature(status, &body)
));
return;
}
let Some(id) = body["resource"]["resource_id"]
.as_str()
.or_else(|| body["resource"]["id"].as_str())
else {
mismatches.push(format!(
"{label}: 201 without a Resource identifier: {text}"
));
return;
};
let card = get_card(client, server, id).await;
let stored = read_content(client, server, id).await;
let (preview_status, _preview_text, preview) = read_preview(client, server, id).await;
let digest = sha256_hex(bytes);
let expected_text = std::str::from_utf8(bytes)
.unwrap_or("<not-utf8>")
.to_owned();
let mut problems: Vec<String> = Vec::new();
if card["version"]["digest"] != json!(digest) {
problems.push(format!(
"card digest={} expected={digest}",
card["version"]["digest"]
));
}
if card["version"]["size_bytes"] != json!(bytes.len() as i64) {
problems.push(format!(
"card size={} expected={}",
card["version"]["size_bytes"],
bytes.len()
));
}
if stored != bytes {
problems.push(format!(
"content bytes differ: stored={} expected={} bytes=[{}]",
stored.len(),
bytes.len(),
String::from_utf8_lossy(&stored)
));
}
if preview_status != StatusCode::OK {
problems.push(format!("preview status={preview_status}"));
}
if preview["preview"]["text"].as_str() != Some(expected_text.as_str()) {
problems.push(format!(
"preview text differs: {}",
preview["preview"]["text"]
));
}
if preview["version"]["digest"] != card["version"]["digest"]
|| preview["version"]["size_bytes"] != card["version"]["size_bytes"]
{
problems.push("preview version metadata differs from the card".to_owned());
}
if preview["resource"]["kind"] != json!("json") {
problems.push(format!("preview kind={}", preview["resource"]["kind"]));
}
observations.push(format!(
"{label}: status={status} bytes={} digest={} size={} preview_status={preview_status}",
bytes.len(),
card["version"]["digest"],
card["version"]["size_bytes"]
));
if !problems.is_empty() {
mismatches.push(format!(
"{label} ({} bytes): {}",
bytes.len(),
problems.join("; ")
));
}
}
/// Неизменяемое окружение одного отвергнутого JSON-документа: реестр, HTTP-клиент, адрес
/// сервера и принятый (якорный) Draft, состояние которого обязано пережить отказ.
struct RejectedJsonContext<'a> {
registry: &'a crank_registry::PostgresRegistry,
client: &'a reqwest::Client,
server: &'a str,
anchor_id: &'a str,
anchor_card: &'a Value,
anchor_bytes: &'a [u8],
}
/// Один отвергнутый JSON-документ: клиентский отказ без последствий.
///
/// Наблюдаются все три требования сразу: точный статус/код/поле отказа, отсутствие новых
/// строк `resources` и неизменность уже принятого (якорного) Draft — карточки целиком и
/// точных bytes.
async fn observe_rejected_json_document(
context: &RejectedJsonContext<'_>,
index: usize,
label: &str,
document: &str,
observations: &mut Vec<String>,
mismatches: &mut Vec<String>,
) {
let registry = context.registry;
let client = context.client;
let server = context.server;
let anchor_id = context.anchor_id;
let anchor_card = context.anchor_card;
let anchor_bytes = context.anchor_bytes;
let uri = format!("crank://json/policy/rejected{index}");
let name = format!("json_policy_rejected{index}");
let meta = draft_metadata(&uri, &name, "json", "application/json", "internal");
let rows_before = table_row_count(registry.pool(), "resources").await;
let (status, _traceable, _text, body) = post_draft_raw(
client,
server,
&meta,
document.as_bytes(),
"application/json",
)
.await;
let rows_after = table_row_count(registry.pool(), "resources").await;
let anchor_card_after = get_card(client, server, anchor_id).await;
let anchor_bytes_after = read_content(client, server, anchor_id).await;
let code = body["error"]["code"].as_str().unwrap_or("<absent>");
let field = body["error"]["context"]["field"]
.as_str()
.unwrap_or("<absent>");
let mut problems: Vec<String> = Vec::new();
// D-14/D-16: невалидный JSON содержимого — 422 `resource_content_invalid_json`
// с точным полем `content` (тот же контракт проверяет матрица malformed JSON).
if status != StatusCode::UNPROCESSABLE_ENTITY {
problems.push(format!(
"status={status} ({})",
error_signature(status, &body)
));
}
if code != "resource_content_invalid_json" {
problems.push(format!("code={code}"));
}
if field != "content" {
problems.push(format!("field={field}"));
}
if rows_after != rows_before {
problems.push(format!("resources rows {rows_before} -> {rows_after}"));
}
if anchor_card_after != *anchor_card {
problems.push("the accepted anchor card changed".to_owned());
}
if anchor_bytes_after != anchor_bytes {
problems.push("the accepted anchor bytes changed".to_owned());
}
observations.push(format!(
"{label}: status={status} code={code} field={field} rows={rows_before}->{rows_after} \
anchor_unchanged={}",
anchor_card_after == *anchor_card && anchor_bytes_after == anchor_bytes
));
if !problems.is_empty() {
mismatches.push(format!("{label}: {}", problems.join("; ")));
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at04_full_json_policy_holds_through_storage_and_preview() {
let (registry, server, client) = spawn_authorized("story36_json_storage").await;
let mut observations: Vec<String> = Vec::new();
let mut mismatches: Vec<String> = Vec::new();
// Якорь: принятый Draft, который обязан остаться неизменным при последующих отказах.
let anchor = create_draft(
&client,
&server,
&draft_metadata(
"crank://json/policy/anchor",
"json_policy_anchor",
"json",
"application/json",
"internal",
),
ANCHOR_BYTES,
"payload.json",
"application/json",
)
.await;
let anchor_id = created_resource_id(&anchor);
let anchor_card = get_card(&client, &server, &anchor_id).await;
let anchor_bytes = read_content(&client, &server, &anchor_id).await;
assert_eq!(
anchor_bytes,
ANCHOR_BYTES.to_vec(),
"the anchor draft must itself be stored byte-exactly"
);
let mut index = 0;
for document in NUMERIC_ACCEPTED {
observe_accepted_json_document(
&client,
&server,
index,
&format!("numeric-accepted-{index}"),
document,
&mut observations,
&mut mismatches,
)
.await;
index += 1;
}
for document in TOP_LEVEL_ACCEPTED {
observe_accepted_json_document(
&client,
&server,
index,
&format!("top-level-accepted-{index}"),
document,
&mut observations,
&mut mismatches,
)
.await;
index += 1;
}
// Глубина ниже предела парсера принимается и читается обратно байт-в-байт.
let nested_ok = format!("{}1{}", "[".repeat(100), "]".repeat(100));
observe_accepted_json_document(
&client,
&server,
index,
"recursion-accepted-100",
&nested_ok,
&mut observations,
&mut mismatches,
)
.await;
index += 1;
// Отвергнутые документы: числа вне f64, длинное целое и глубина выше предела парсера.
let mut rejected: Vec<(String, String)> = NUMERIC_REJECTED
.iter()
.enumerate()
.map(|(position, document)| {
(
format!("rejected-number-{position}"),
(*document).to_owned(),
)
})
.collect();
rejected.push((
"rejected-long-integer".to_owned(),
format!("1{}", "0".repeat(400)),
));
rejected.push((
"rejected-recursion-300".to_owned(),
format!("{}1{}", "[".repeat(300), "]".repeat(300)),
));
let context = RejectedJsonContext {
registry: &registry,
client: &client,
server: server.as_ref(),
anchor_id: &anchor_id,
anchor_card: &anchor_card,
anchor_bytes: &anchor_bytes,
};
for (position, (label, document)) in rejected.iter().enumerate() {
observe_rejected_json_document(
&context,
position,
label,
document,
&mut observations,
&mut mismatches,
)
.await;
}
// Положительный контроль после отказов: тот же путь по-прежнему принимает документ.
observe_accepted_json_document(
&client,
&server,
index,
"accepted-after-rejections",
"{\"after\":\"rejections\"}",
&mut observations,
&mut mismatches,
)
.await;
assert!(
mismatches.is_empty(),
"the full D-8.1 policy must hold on the real storage/preview path; mismatches: \
{mismatches:?}; observations: {observations:?}"
);
}