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

472 lines
18 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 (AT-3.6-05): настроенный предел содержимого на **реальном** HTTP-пути,
//! включая многобайтовую границу и фрагментированное тело без `Content-Length`.
//!
//! Источник: SPEC v4 D-3/D-9 (configured size, никакого «успешного префикса»),
//! TL review run103:35 (R-D: «configured small-L на реальном reader-е с
//! fragmentation/interruption/false-or-absent length и неизменным состоянием
//! отклонённого обновления»).
//!
//! Стенд настраивает `ResourceLimits::uniform(SMALL_LIMIT)` через настоящий билдер
//! сервиса (composition fixture), поэтому проверяется работающий сервис, а не
//! отдельная функция валидации. Фрагментированные запросы идут по реальному
//! loopback-сокету: `reqwest` всегда добавляет `Content-Length`, а здесь нужен
//! именно chunked-поток.
//!
//! Канонический прогон: `cargo test -p admin-api --lib
//! service::resources::tests::limits -- --test-threads=1`.
use reqwest::StatusCode;
use serial_test::serial;
use super::counters;
use crate::app::resource_test_support::{
GuardHarness, GuardOptions, LoginOptions, OWNER_EMAIL, OWNER_PASSWORD, created_resource_id,
draft_metadata, draft_updated_at, error_signature, get_raw, login_client, raw_session,
resource_row_counts, send_chunked_multipart,
};
/// Малое настроенное L: границы L−1/L/L+1 проверяются без 256 KiB payload.
const SMALL_LIMIT: usize = 16;
const BOUNDARY: &str = "story36limitsboundary";
enum Expectation {
Accepted,
TooLarge,
}
struct LimitCase {
label: &'static str,
kind: &'static str,
mime: &'static str,
bytes: Vec<u8>,
expectation: Expectation,
}
fn json_document(length: usize) -> Vec<u8> {
assert!(length >= 9, "a JSON envelope needs at least nine bytes");
format!("{{\"k\":\"{}\"}}", "a".repeat(length - 8)).into_bytes()
}
fn binary_document(length: usize) -> Vec<u8> {
// Произвольные байты, включая не-UTF8 последовательности и нули.
(0..length)
.map(|index| (index as u8).wrapping_mul(37).wrapping_add(0x80))
.collect()
}
fn limit_cases() -> Vec<LimitCase> {
let small = SMALL_LIMIT;
let mut cases = Vec::new();
for (label, length, expectation) in [
("text_l_minus_one", small - 1, Expectation::Accepted),
("text_l", small, Expectation::Accepted),
("text_l_plus_one", small + 1, Expectation::TooLarge),
] {
cases.push(LimitCase {
label,
kind: "text",
mime: "text/plain",
bytes: vec![b'a'; length],
expectation,
});
}
// Многобайтовый символ ровно на границе: не помещается — отвергается целиком.
let mut fits = vec![b'a'; small - 2];
fits.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(fits.len(), small);
let mut over = vec![b'a'; small - 1];
over.extend_from_slice("\u{e9}".as_bytes());
assert_eq!(over.len(), small + 1);
cases.push(LimitCase {
label: "text_multibyte_fits",
kind: "text",
mime: "text/plain",
bytes: fits,
expectation: Expectation::Accepted,
});
cases.push(LimitCase {
label: "text_multibyte_over",
kind: "text",
mime: "text/plain",
bytes: over,
expectation: Expectation::TooLarge,
});
for (label, length, expectation) in [
("json_l_minus_one", small - 1, Expectation::Accepted),
("json_l", small, Expectation::Accepted),
("json_l_plus_one", small + 1, Expectation::TooLarge),
] {
cases.push(LimitCase {
label,
kind: "json",
mime: "application/json",
bytes: json_document(length),
expectation,
});
}
for (label, length, expectation) in [
("binary_l_minus_one", small - 1, Expectation::Accepted),
("binary_l", small, Expectation::Accepted),
("binary_l_plus_one", small + 1, Expectation::TooLarge),
] {
cases.push(LimitCase {
label,
kind: "binary",
mime: "image/png",
bytes: binary_document(length),
expectation,
});
}
cases
}
async fn download_bytes(client: &reqwest::Client, url: &str) -> (StatusCode, Vec<u8>) {
let response = client
.get(url)
.send()
.await
.expect("the content request must complete");
let status = response.status();
let bytes = response
.bytes()
.await
.expect("the content body must be readable")
.to_vec();
(status, bytes)
}
async fn owner_client(harness: &GuardHarness) -> reqwest::Client {
login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await
}
fn raw_multipart(metadata: &serde_json::Value, content: &[u8], mime: &str) -> Vec<u8> {
let head = format!(
"--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"metadata\"; filename=\"metadata.json\"\r\n\
Content-Type: application/json\r\n\r\n{}\r\n\
--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"draft.bin\"\r\n\
Content-Type: {mime}\r\n\r\n",
serde_json::to_string(metadata).expect("metadata must serialize")
);
let mut body = head.into_bytes();
body.extend_from_slice(content);
body.extend_from_slice(format!("\r\n--{BOUNDARY}--\r\n").as_bytes());
body
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at05_configured_small_limit_boundaries_through_real_http() {
let harness = GuardHarness::spawn_with(
"limits",
GuardOptions {
resource_limit: Some(SMALL_LIMIT),
..GuardOptions::default()
},
)
.await;
let owner = owner_client(&harness).await;
let mut observations: Vec<String> = Vec::new();
let mut mismatches: Vec<String> = Vec::new();
let mut accepted = 0usize;
for case in limit_cases() {
let metadata = draft_metadata(
&format!("crank://limit/{}", case.label),
case.label,
case.kind,
case.mime,
"internal",
);
let (status, _traceable, text, body) = crate::app::resource_test_support::post_draft(
&owner,
&harness.resources_url(),
&metadata,
&case.bytes,
case.mime,
)
.await;
let code = body["error"]["code"]
.as_str()
.unwrap_or("<none>")
.to_owned();
match case.expectation {
Expectation::Accepted => {
accepted += 1;
let id = match (
status.is_success(),
body["resource"]["resource_id"].as_str(),
) {
(true, Some(id)) => id.to_owned(),
_ => {
mismatches.push(format!(
"{}: expected success, observed {}",
case.label,
error_signature(status, &body)
));
observations.push(format!("{}: {status} {code}", case.label));
continue;
}
};
let (content_status, bytes) =
download_bytes(&owner, &harness.nested_url(&id, "content")).await;
if content_status == StatusCode::OK && bytes == case.bytes {
observations.push(format!("{}: 201 + exact {} bytes", case.label, bytes.len()));
} else {
mismatches.push(format!(
"{}: content readback mismatch (status={content_status}, {} bytes)",
case.label,
bytes.len()
));
observations.push(format!("{}: content status={content_status}", case.label));
}
}
Expectation::TooLarge => {
if status == StatusCode::PAYLOAD_TOO_LARGE && code == "resource_content_too_large" {
observations.push(format!("{}: 413 {code}", case.label));
} else {
mismatches.push(format!(
"{}: expected 413 resource_content_too_large, observed {}",
case.label,
error_signature(status, &body)
));
observations.push(format!("{}: {status} {code} body={text}", case.label));
}
}
}
}
assert_eq!(
harness.accepted_drafts().await.len(),
accepted,
"a refused bounded body must not leave an accepted draft; observations: {observations:?}"
);
assert!(
mismatches.is_empty(),
"every configured-L boundary must be exact for text/JSON/binary, multibyte included; \
observations: {observations:?}; mismatches: {mismatches:?}"
);
// Фрагментированное тело (chunked, без `Content-Length`): тот же предел действует,
// «успешного префикса» не возникает.
let session = raw_session(&harness.root_url, OWNER_EMAIL, OWNER_PASSWORD).await;
let resources_url = harness.resources_url();
let path = resources_url[resources_url.find("/api").expect("admin prefix")..].to_owned();
let accepted_meta = draft_metadata(
"crank://limit/chunked_ok",
"chunked_ok",
"text",
"text/plain",
"internal",
);
let accepted_body = raw_multipart(&accepted_meta, &[b'c'; SMALL_LIMIT], "text/plain");
let chunks: Vec<Vec<u8>> = accepted_body
.chunks(23)
.map(|chunk| chunk.to_vec())
.collect();
assert!(
chunks.len() >= 3,
"the fragmented request must really be sent in several chunks"
);
let response = send_chunked_multipart(harness.addr, &path, &session, BOUNDARY, &chunks).await;
let accepted_fragmented_ok = response.status == 201 && response.write_error.is_none();
observations.push(format!(
"fragmented-L: expected 201, observed {}",
response.signature()
));
let over_meta = draft_metadata(
"crank://limit/chunked_over",
"chunked_over",
"text",
"text/plain",
"internal",
);
let over_body = raw_multipart(&over_meta, &[b'c'; SMALL_LIMIT + 1], "text/plain");
let over_chunks: Vec<Vec<u8>> = over_body.chunks(19).map(|chunk| chunk.to_vec()).collect();
let response =
send_chunked_multipart(harness.addr, &path, &session, BOUNDARY, &over_chunks).await;
let over_fragmented_ok =
response.status == 413 && response.body.contains("resource_content_too_large");
observations.push(format!(
"fragmented-L+1: expected 413 resource_content_too_large, observed {}",
response.signature()
));
// Прерванное тело (нет закрывающей границы): клиентский отказ, ничего принято не было.
let truncated_meta = draft_metadata(
"crank://limit/chunked_truncated",
"chunked_truncated",
"text",
"text/plain",
"internal",
);
let mut truncated_body = raw_multipart(&truncated_meta, b"short", "text/plain");
truncated_body.truncate(truncated_body.len() - 20);
let truncated_chunks: Vec<Vec<u8>> = truncated_body
.chunks(17)
.map(|chunk| chunk.to_vec())
.collect();
let response =
send_chunked_multipart(harness.addr, &path, &session, BOUNDARY, &truncated_chunks).await;
let interrupted_ok = response.status == 400;
observations.push(format!(
"interrupted-multipart: expected 400, observed {}",
response.signature()
));
let drafts = harness.accepted_drafts().await;
let only_accepted_fragmented_draft = drafts.len() == accepted + 1;
assert!(
only_accepted_fragmented_draft,
"only the accepted fragmented draft may be added; observations: {observations:?}"
);
assert!(
accepted_fragmented_ok && over_fragmented_ok,
"a fragmented body without Content-Length must obey the same limit (no prefix \
acceptance); observations: {observations:?}"
);
assert!(
interrupted_ok,
"an interrupted multipart body must be a client error (P2), not a limit refusal; \
observations: {observations:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at05_rejected_update_keeps_state_and_checksum() {
let harness = GuardHarness::spawn_with(
"limits_update",
GuardOptions {
resource_limit: Some(SMALL_LIMIT),
..GuardOptions::default()
},
)
.await;
let owner = owner_client(&harness).await;
let metadata = draft_metadata(
"crank://limit/update",
"limit_update",
"text",
"text/plain",
"internal",
);
let created = crate::app::resource_test_support::post_draft(
&owner,
&harness.resources_url(),
&metadata,
b"initial body",
"text/plain",
)
.await;
assert_eq!(
created.0,
StatusCode::CREATED,
"the seed draft must be created: {}",
created.2
);
let id = created_resource_id(&created.3);
let card = get_raw(&owner, &harness.resource_url(&id)).await.3;
let updated_at = draft_updated_at(&card);
let digest_before = card["version"]["digest"]
.as_str()
.unwrap_or_default()
.to_owned();
// Полное «до»: карточка целиком, точные bytes и итоги строк/ссылок V16. Отказ обязан
// оставить неизменным всё это, а не только версию/чек-сумму/описание (TL run105 F2).
let (content_status_before, bytes_before) =
download_bytes(&owner, &harness.nested_url(&id, "content")).await;
assert_eq!(content_status_before, StatusCode::OK);
let counts_before = resource_row_counts(harness.registry.pool()).await;
// Счётчики физических точек сбрасываются **после** собственного наблюдения, чтобы
// измерялся вклад самого отклонённого запроса, а не теста.
counters::reset();
// Отклонённое обновление: тело выше настроенного L.
let update = serde_json::json!({
"description": "should not apply",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": updated_at,
});
let (status, _headers, text, body) = crate::app::resource_test_support::put_draft(
&owner,
&harness.resource_url(&id),
&update,
&[b'z'; SMALL_LIMIT + 1],
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"L+1 on update must be a limit refusal: {}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
serde_json::json!("resource_content_too_large"),
"body={text}"
);
// Наблюдение физических точек сразу после отказа: измеряется вклад отклонённого запроса.
let puts_after_refusal = counters::artifact_puts();
let reads_after_refusal = counters::artifact_reads();
// Полное состояние после отказа: карточка целиком (включая `updated_at`, MIME и
// sensitivity), точные bytes и итоги строк/ссылок V16 не изменились.
let after = get_raw(&owner, &harness.resource_url(&id)).await.3;
assert_eq!(
after["version"]["version"],
serde_json::json!(1),
"a refused update must not create a version: {after}"
);
assert_eq!(
after["version"]["digest"].as_str().unwrap_or_default(),
digest_before,
"a refused update must not change the recorded checksum"
);
assert_eq!(
after["resource"]["description"],
serde_json::json!(""),
"a refused update must not apply the description: {after}"
);
assert_eq!(
after, card,
"a refused update must leave the whole card unchanged, including `updated_at`, \
`mime_type` and `sensitivity` (TL run105 F2)"
);
let counts_after = resource_row_counts(harness.registry.pool()).await;
assert_eq!(
counts_after, counts_before,
"a refused update must not add rows, owning references or blobs (TL run105 F2)"
);
let (content_status, bytes) = download_bytes(&owner, &harness.nested_url(&id, "content")).await;
assert_eq!(content_status, StatusCode::OK);
assert_eq!(
bytes, b"initial body",
"a refused update must keep the previously accepted bytes"
);
assert_eq!(
bytes, bytes_before,
"the pre-refusal read must be the same content"
);
assert_eq!(
puts_after_refusal, 0,
"an oversized update must be refused before any bytes are registered \
(D-20 ordering: limit check precedes the physical put)"
);
assert_eq!(
reads_after_refusal, 0,
"an oversized update must not read any stored bytes"
);
}