[skip ci] wip: preserve Hermes crank development checkpoint

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.
This commit is contained in:
Hermes DevOps committed 2026-10-25 08:05:37 +00:00
1 parent 1b6db09bd1
commit 301dce301a
357 files changed
+118831 -5113

No files matched your search

@@ -0,0 +1,991 @@
//! AT-3.6-02/06: guard-пути Resource Drafts на настоящем HTTP (TL review run101, R-A).
//!
//! Источник: SPEC v4 §2 (AT-3.6-02 guards), §6/§7 (AT-3.6-06 отказы без утечки),
//! TL review run101:39 (R-A) и FINAL-DISPOSITION run99:47 (разрешённая test-only
//! composition fixture). Проверяется то, что раньше было `BUILD-only GAP`: отказ,
//! выданный настоящим middleware-ом (`require_session`, `require_workspace_session`,
//! `require_csrf_for_browser_mutations`, `enforce_browser_security`), не доходит до
//! физических точек хранилища и не оставляет принятого состояния.
//!
//! Наблюдения: `crate::service::resources::counters` (реальные точки
//! `put_registered`/`load_content`) и публичное чтение реестра через composition fixture.
//! Ни один production API/проверка границ здесь не меняется: fixture собирается только
//! под `cfg(test)`.
//!
//! Канонический прогон: `cargo test -p admin-api --lib
//! service::resources::tests::guard_path::story36_ -- --test-threads=1`.
use reqwest::StatusCode;
use serial_test::serial;
use super::counters;
use crate::app::resource_test_support::{
FOREIGN_WORKSPACE_ID, GuardHarness, GuardOptions, LoginOptions, OWNER_EMAIL, OWNER_PASSWORD,
VIEWER_EMAIL, VIEWER_PASSWORD, anonymous_client, created_resource_id, draft_metadata,
draft_updated_at, error_signature, get_raw, login_client, post_draft, put_draft,
update_metadata,
};
/// Неизменяемая метафизика теста: содержимое, которое никогда не должно просочиться.
const SEED_CONTENT: &[u8] = b"guard-path-seed-payload";
fn seed_metadata(uri: &str, name: &str) -> serde_json::Value {
draft_metadata(uri, name, "text", "text/plain", "internal")
}
/// Session-клиент Owner `ws_default` с валидным CSRF.
async fn owner_client(harness: &GuardHarness) -> reqwest::Client {
login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await
}
/// Создаёт Draft через реальный HTTP и возвращает его идентификатор.
async fn seed_draft(
harness: &GuardHarness,
client: &reqwest::Client,
uri: &str,
name: &str,
) -> String {
let (status, _traceable, text, body) = post_draft(
client,
&harness.resources_url(),
&seed_metadata(uri, name),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"positive control: an authorized create must succeed ({}); observed {}",
uri,
error_signature(status, &body)
);
assert!(
!text.contains("guard-path-seed-payload"),
"a successful card response must not echo content bytes: {text}"
);
created_resource_id(&body)
}
/// Набор Resource-маршрутов, к которым применяется guard: card/preview/content.
fn read_routes(harness: &GuardHarness, resource_id: &str) -> [String; 3] {
[
harness.resource_url(resource_id),
harness.nested_url(resource_id, "preview"),
harness.nested_url(resource_id, "content"),
]
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_anonymous_refuses_every_resource_route() {
let harness = GuardHarness::spawn("anon").await;
let owner = owner_client(&harness).await;
let existing = seed_draft(&harness, &owner, "crank://guard/anon", "guard_anon").await;
// Метрика физических точек сбрасывается уже после сева: дальше считается только отказ.
counters::reset();
let anonymous = anonymous_client();
let (status, _traceable, _text, body) = post_draft(
&anonymous,
&harness.resources_url(),
&seed_metadata("crank://guard/anon/denied", "guard_anon_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"an anonymous create must be refused by the session guard; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
assert_eq!(
counters::artifact_puts(),
0,
"a session-guard refusal must not reach the byte-registration point"
);
let (status, _headers, _text, body) = put_draft(
&anonymous,
&harness.resource_url(&existing),
&seed_metadata("crank://guard/anon/denied", "guard_anon_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"an anonymous update must be refused before content work; observed {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 0);
let (status, _headers, _text, body) = get_raw(&anonymous, &harness.resources_url()).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"list: {}",
error_signature(status, &body)
);
for route in read_routes(&harness, &existing) {
let (status, _headers, text, body) = get_raw(&anonymous, &route).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"anonymous read of `{route}` must be refused; observed {}",
error_signature(status, &body)
);
assert!(
!text.contains("guard-path-seed-payload"),
"a refusal must never carry stored bytes: {text}"
);
}
assert_eq!(
counters::artifact_reads(),
0,
"a session-guard refusal must not reach the physical byte-read point"
);
assert_eq!(
counters::artifact_puts(),
0,
"no anonymous write may register bytes"
);
assert_eq!(
harness.accepted_drafts().await.len(),
1,
"only the seeded Draft may exist; the refused create must leave no accepted row"
);
// Положительный контроль: та же сущность и тот же маршрут с валидной сессией работают.
let (status, _headers, _text, body) = get_raw(&owner, &harness.resource_url(&existing)).await;
assert_eq!(
status,
StatusCode::OK,
"the same card must be readable by an authorized session: {}",
error_signature(status, &body)
);
assert_eq!(body["resource"]["name"], serde_json::json!("guard_anon"));
let (status, headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(
headers
.get("content-type")
.and_then(|value| value.to_str().ok()),
Some("application/octet-stream"),
"downloads keep the octet-stream policy (D-6)"
);
assert_eq!(
counters::artifact_reads(),
1,
"the authorized download is the positive control for the zero above"
);
let (status, _headers, _text, body) =
get_raw(&owner, &harness.nested_url(&existing, "preview")).await;
assert_eq!(status, StatusCode::OK);
// Для kind=text preview по D-6 отдаёт ровно сохранённые bytes как инертный `text`
// (положительный контроль: тот же payload наблюдается только на разрешённом чтении).
assert_eq!(
body["preview"]["text"],
serde_json::json!("guard-path-seed-payload"),
"a permitted preview of a text Resource returns the stored bytes as inert text"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_expired_session_cannot_reach_resource_routes() {
let expired = GuardHarness::spawn_with(
"expired",
GuardOptions {
session_ttl_hours: 0,
..GuardOptions::default()
},
)
.await;
let valid = GuardHarness::spawn_with("expired_control", GuardOptions::default()).await;
let valid_owner = owner_client(&valid).await;
let existing = seed_draft(
&valid,
&valid_owner,
"crank://guard/expired",
"guard_expired",
)
.await;
// Логин проходит (сессия выдаётся), но её срок жизни уже истёк.
let expired_client = login_client(
&expired.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await;
counters::reset();
let (status, _headers, _text, body) = get_raw(&expired_client, &expired.resources_url()).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"an expired session must be refused; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
for route in read_routes(&expired, &existing) {
let (status, _headers, _text, body) = get_raw(&expired_client, &route).await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"expired read `{route}`: {}",
error_signature(status, &body)
);
}
let (status, _t, _text, body) = post_draft(
&expired_client,
&expired.resources_url(),
&seed_metadata("crank://guard/expired/denied", "guard_expired_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"expired create: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
assert!(
expired.accepted_drafts().await.is_empty(),
"an expired session must not accept any Draft"
);
// PUT (мутация существующей сущности) обязан быть отвергнут тем же guard-ом ДО
// разрешения Resource и до любой работы с bytes (R-A: недостающий applicable PUT).
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
let (status, _headers, _text, body) = put_draft(
&expired_client,
&expired.resource_url(&existing),
&metadata,
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"an expired update must be refused by the session guard, not by entity resolution: {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("unauthorized"));
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
// Положительный контроль: та же последовательность при валидном сроке жизни.
let (status, _headers, _text, body) =
get_raw(&valid_owner, &valid.resource_url(&existing)).await;
assert_eq!(
status,
StatusCode::OK,
"the same request with a live session must succeed: {}",
error_signature(status, &body)
);
assert_eq!(
counters::artifact_reads(),
0,
"card reading must not touch bytes"
);
let (status, _headers, bytes, _body) =
get_raw(&valid_owner, &valid.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(counters::artifact_reads(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_workspace_without_access_cannot_read_existing_foreign_resource() {
let harness = GuardHarness::spawn_with(
"foreign",
GuardOptions {
foreign_workspace: true,
foreign_workspace_owner: true,
..GuardOptions::default()
},
)
.await;
let owner_a = owner_client(&harness).await;
let owner_b = login_client(
&harness.root_url,
crate::app::resource_test_support::FOREIGN_OWNER_EMAIL,
crate::app::resource_test_support::FOREIGN_OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await;
// Существующий ResourceB в чужом для A workspace: он реально создан и читается своим владельцем.
let foreign_base = harness.foreign_resources_url();
let (status, _t, _text, body) = post_draft(
&owner_b,
&foreign_base,
&seed_metadata("crank://guard/foreign", "guard_foreign"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the foreign workspace owner must create ResourceB: {}",
error_signature(status, &body)
);
let resource_b = created_resource_id(&body);
counters::reset();
let (status, _headers, _text, body) =
get_raw(&owner_a, &format!("{foreign_base}/{resource_b}")).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a workspace without access must be refused; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
for suffix in ["", "/preview", "/content"] {
let (status, _headers, text, _body) =
get_raw(&owner_a, &format!("{foreign_base}/{resource_b}{suffix}")).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"denied foreign read `{suffix}` must stay forbidden"
);
assert!(
!text.contains("guard-path-seed-payload"),
"a forbidden response must not carry foreign bytes: {text}"
);
}
let (status, _t, _text, body) = post_draft(
&owner_a,
&foreign_base,
&seed_metadata("crank://guard/foreign/denied", "guard_foreign_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a mutation in a workspace without access must be refused: {}",
error_signature(status, &body)
);
assert_eq!(
counters::artifact_puts(),
0,
"a workspace-guard refusal must not register bytes"
);
assert_eq!(
counters::artifact_reads(),
0,
"a workspace-guard refusal must not read bytes"
);
let (status, _headers, _text, body) = put_draft(
&owner_a,
&format!("{foreign_base}/{resource_b}"),
&seed_metadata("crank://guard/foreign", "guard_foreign"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a denied update must be refused before content work: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 0);
// Положительный контроль 1: ResourceB существует и читается в своём workspace.
let (status, _headers, bytes, _body) =
get_raw(&owner_b, &format!("{foreign_base}/{resource_b}/content")).await;
assert_eq!(
status,
StatusCode::OK,
"ResourceB must be readable inside its own workspace"
);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(counters::artifact_reads(), 1);
// Положительный контроль 2: та же самая отказанная сессия A работает в своём workspace.
let own = seed_draft(&harness, &owner_a, "crank://guard/own", "guard_own").await;
let (status, _headers, bytes, _body) =
get_raw(&owner_a, &harness.nested_url(&own, "content")).await;
assert_eq!(
status,
StatusCode::OK,
"the same denied session must still act in its own workspace"
);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(counters::artifact_reads(), 2);
assert_eq!(
harness
.registry
.list_resource_drafts(FOREIGN_WORKSPACE_ID, 100)
.await
.expect("foreign drafts must be readable")
.len(),
1,
"the refused create must leave exactly the seeded ResourceB in the foreign workspace"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_viewer_reads_but_never_mutates() {
let harness = GuardHarness::spawn_with(
"viewer",
GuardOptions {
viewer_membership: true,
..GuardOptions::default()
},
)
.await;
let owner = owner_client(&harness).await;
let existing = seed_draft(&harness, &owner, "crank://guard/viewer", "guard_viewer").await;
let viewer = login_client(
&harness.root_url,
VIEWER_EMAIL,
VIEWER_PASSWORD,
LoginOptions::with_csrf(),
)
.await;
counters::reset();
let (status, _t, _text, body) = post_draft(
&viewer,
&harness.resources_url(),
&seed_metadata("crank://guard/viewer/denied", "guard_viewer_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a non-Owner mutation must be refused; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
let (status, _headers, _text, body) = put_draft(
&viewer,
&harness.resource_url(&existing),
&seed_metadata("crank://guard/viewer", "guard_viewer"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a non-Owner update must be refused before content work: {}",
error_signature(status, &body)
);
assert_eq!(
counters::artifact_puts(),
0,
"an ownership refusal must not register bytes"
);
assert_eq!(
harness.accepted_drafts().await.len(),
1,
"a refused mutation must not add accepted rows"
);
// Положительный контроль: тот же Viewer на той же сессии читает разрешённые маршруты.
let (status, _headers, _text, body) = get_raw(&viewer, &harness.resource_url(&existing)).await;
assert_eq!(
status,
StatusCode::OK,
"a Viewer must be able to read the card: {}",
error_signature(status, &body)
);
let (status, _headers, bytes, _body) =
get_raw(&viewer, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(counters::artifact_reads(), 1);
let (status, _headers, _text, body) = get_raw(&viewer, &harness.resources_url()).await;
assert_eq!(
status,
StatusCode::OK,
"a Viewer must be able to list the workspace Resources: {}",
error_signature(status, &body)
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_missing_csrf_blocks_before_any_byte_work() {
let harness = GuardHarness::spawn("csrf").await;
let owner = owner_client(&harness).await;
let existing = seed_draft(&harness, &owner, "crank://guard/csrf", "guard_csrf").await;
// Тот же аккаунт, та же сессия, но без заголовка `x-csrf-token`.
let without_csrf = login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::default(),
)
.await;
counters::reset();
let (status, _t, _text, body) = post_draft(
&without_csrf,
&harness.resources_url(),
&seed_metadata("crank://guard/csrf/denied", "guard_csrf_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a browser mutation without CSRF must be refused; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
let (status, _headers, _text, body) = put_draft(
&without_csrf,
&harness.resource_url(&existing),
&seed_metadata("crank://guard/csrf", "guard_csrf"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a CSRF-less update must be refused: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
assert_eq!(
harness.accepted_drafts().await.len(),
1,
"no accepted row may appear without a valid CSRF token"
);
// Положительный контроль: тот же аккаунт с валидным CSRF проходит тот же POST.
let (status, _t, _text, body) = post_draft(
&owner,
&harness.resources_url(),
&seed_metadata("crank://guard/csrf/ok", "guard_csrf_ok"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the same request with a CSRF token must succeed: {}",
error_signature(status, &body)
);
assert_eq!(
counters::artifact_puts(),
1,
"the accepted create is the positive control for the zero above"
);
assert_eq!(harness.accepted_drafts().await.len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_cross_origin_blocks_mutation_and_read() {
let harness = GuardHarness::spawn("origin").await;
let owner = owner_client(&harness).await;
let existing = seed_draft(&harness, &owner, "crank://guard/origin", "guard_origin").await;
let cross_origin = login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::cross_origin(),
)
.await;
counters::reset();
let (status, _t, _text, body) = post_draft(
&cross_origin,
&harness.resources_url(),
&seed_metadata("crank://guard/origin/denied", "guard_origin_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a cross-origin browser mutation must be refused; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
for route in read_routes(&harness, &existing) {
let (status, _headers, text, _body) = get_raw(&cross_origin, &route).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a cross-origin admin request must be refused even on `{route}`"
);
assert!(!text.contains("guard-path-seed-payload"));
}
// PUT из чужого Origin: отказ браузерной защиты до любых bytes и без изменения состояния.
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
let (status, _headers, _text, body) = put_draft(
&cross_origin,
&harness.resource_url(&existing),
&metadata,
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a cross-origin update must be refused: {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
assert_eq!(harness.accepted_drafts().await.len(), 1);
// Положительный контроль: тот же аккаунт без чужого Origin проходит те же маршруты.
let (status, _t, _text, body) = post_draft(
&owner,
&harness.resources_url(),
&seed_metadata("crank://guard/origin/ok", "guard_origin_ok"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the same account without a foreign Origin must succeed: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 1);
let (status, _headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), SEED_CONTENT);
assert_eq!(counters::artifact_reads(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at04_stale_precondition_registers_no_bytes_through_real_http() {
let harness = GuardHarness::spawn("stale").await;
let owner = owner_client(&harness).await;
counters::reset();
let existing = seed_draft(&harness, &owner, "crank://guard/stale", "guard_stale").await;
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
assert_eq!(status, StatusCode::OK);
let first = draft_updated_at(&card);
// Положительный контроль 1: свежий precondition действительно регистрирует bytes через HTTP.
let (status, _headers, _text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &first),
b"second body",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::OK,
"a fresh precondition must update the Draft: {}",
error_signature(status, &body)
);
assert_eq!(
counters::artifact_puts(),
2,
"seed + accepted update must be the two real byte-registration points"
);
assert_eq!(counters::artifact_reads(), 0);
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
assert_eq!(status, StatusCode::OK);
let second = draft_updated_at(&card);
assert_ne!(
first, second,
"an accepted update must move the precondition"
);
// Отказ F: stale precondition. Принятый контракт P2 — «428 до put/read», поэтому сначала
// читается только счётчик, а состояние наблюдается после него.
counters::reset();
let (status, _headers, _text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &first),
b"third body",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a stale precondition must be refused: {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("resource_stale"));
let puts_after_stale = counters::artifact_puts();
let reads_after_stale = counters::artifact_reads();
// Состояние не изменилось: bytes победителя читаются, третьей версии нет.
let (status, _headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), b"second body");
assert_eq!(
harness.accepted_drafts().await[0].version.version,
2,
"a stale rejection must not create a version"
);
assert_eq!(
reads_after_stale, 0,
"a stale rejection must not perform a physical read"
);
assert_eq!(
puts_after_stale, 0,
"the accepted contract (P2) decides resource_stale before byte registration; \
the observed counter proves bytes were registered for a refused update"
);
// Положительный контроль 2: свежий precondition после отказов снова проходит.
counters::reset();
let (status, _headers, _text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &second),
b"third body",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::OK,
"a fresh precondition must still work after the stale refusals: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 1);
let (status, _headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), b"third body");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at04_stale_precondition_precedes_content_validation_through_http() {
let harness = GuardHarness::spawn("stale_utf8").await;
let owner = owner_client(&harness).await;
let existing = seed_draft(
&harness,
&owner,
"crank://guard/staleutf8",
"guard_staleutf8",
)
.await;
let (status, _headers, _text, card) = get_raw(&owner, &harness.resource_url(&existing)).await;
assert_eq!(status, StatusCode::OK);
let first = draft_updated_at(&card);
// Принятое обновление делает `first` настоящим (ранее валидным, теперь stale) precondition.
let (status, _headers, _text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &first),
b"second body",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::OK,
"the accepted update is the control for the stale case: {}",
error_signature(status, &body)
);
// F побеждает G: stale precondition + невалидная кодировка → 428 resource_stale, не 422.
let (status, _headers, text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &first),
&[0xC3, 0x28],
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"the stale precondition must win over content validation (D-20 F); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("resource_stale"));
assert_eq!(
body["error"]["context"]["field"],
serde_json::json!("expected_updated_at")
);
// Состояние не изменилось, свежий precondition продолжает работать.
let (status, _headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), b"second body");
let current = second_precondition(&owner, &harness, &existing).await;
let (status, _headers, _text, body) = put_draft(
&owner,
&harness.resource_url(&existing),
&update_metadata("", "text/plain", "internal", &current),
b"third body",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::OK,
"a fresh precondition must still work after the stale rejection: {}",
error_signature(status, &body)
);
let (status, _headers, bytes, _body) =
get_raw(&owner, &harness.nested_url(&existing, "content")).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(bytes.as_bytes(), b"third body");
}
/// Текущее значение precondition карточки Draft.
async fn second_precondition(
owner: &reqwest::Client,
harness: &GuardHarness,
resource_id: &str,
) -> String {
let (status, _headers, _text, card) = get_raw(owner, &harness.resource_url(resource_id)).await;
assert_eq!(status, StatusCode::OK);
draft_updated_at(&card)
}
// ---------------------------------------------------------------------------
// R-A (TL run103:47): чужой CSRF-токен — отдельный однофакторный негатив, а не
// повтор «отсутствующего» токена.
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_wrong_csrf_token_blocks_before_any_byte_work() {
let harness = GuardHarness::spawn("wrong_csrf").await;
let owner = owner_client(&harness).await;
let existing = seed_draft(
&harness,
&owner,
"crank://guard/wrongcsrf",
"guard_wrongcsrf",
)
.await;
// Та же валидная сессия и валидный Origin, но подпись CSRF-токена не совпадает.
let wrong_csrf = login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::with_wrong_csrf(),
)
.await;
counters::reset();
let (status, _t, _text, body) = post_draft(
&wrong_csrf,
&harness.resources_url(),
&seed_metadata("crank://guard/wrongcsrf/denied", "guard_wrongcsrf_denied"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a wrong CSRF token must be refused like a missing one; observed {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
let metadata = update_metadata("", "text/plain", "internal", "1970-01-01T00:00:00Z");
let (status, _headers, _text, body) = put_draft(
&wrong_csrf,
&harness.resource_url(&existing),
&metadata,
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a wrong CSRF token must also block the update path: {}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], serde_json::json!("forbidden"));
assert_eq!(counters::artifact_puts(), 0);
assert_eq!(counters::artifact_reads(), 0);
let drafts = harness.accepted_drafts().await;
assert_eq!(
drafts.len(),
1,
"a wrong CSRF token must not accept a draft or change state"
);
assert_eq!(drafts[0].version.version, 1);
// Положительный контроль: тот же аккаунт с настоящим токеном проходит тот же POST.
let (status, _t, _text, body) = post_draft(
&owner,
&harness.resources_url(),
&seed_metadata("crank://guard/wrongcsrf/ok", "guard_wrongcsrf_ok"),
SEED_CONTENT,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the same account with the real token must succeed: {}",
error_signature(status, &body)
);
assert_eq!(counters::artifact_puts(), 1);
assert_eq!(harness.accepted_drafts().await.len(), 2);
}
@@ -0,0 +1,625 @@
//! AT-3.6-06: изолированный захват журналов/спанов/метрик на реальном HTTP (TL run101, R-A).
//!
//! Источник: SPEC v4 §6/§7, QA test-design run77:117–119, TL review run101:39.
//! Проверяется то, что раньше было честным GAP: процессы-приёмники (`writer` fmt-слоя,
//! экспортируемые спаны, рекордер метрик) **реально существуют**, получают положительные
//! события от тех же Resource-отказов, и ни в одном из них не появляется содержимое.
//!
//! Изоляция: этот файл — единственная в бинаре `admin-api --lib` точка, которая ставит
//! глобальные подписчик/рекордер. Канонический прогон задаёт точный фильтр, поэтому в
//! процессе исполняется только этот тест:
//! `cargo test -p admin-api --lib
//! service::resources::tests::guard_telemetry::story36_ -- --test-threads=1`.
//! Существующий `integration::openapi_source::telemetry` живёт в другом тестовом бинаре
//! (integration-тесты), поэтому конфликта глобального default между ними нет.
use std::{
io,
sync::{Arc, Mutex},
};
use base64::Engine as _;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::{
error::OTelSdkResult,
trace::{SdkTracerProvider, SpanData, SpanExporter},
};
use reqwest::StatusCode;
use serde_json::{Value, json};
use serial_test::serial;
use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt};
use crate::app::resource_test_support::{
GuardHarness, GuardOptions, LoginOptions, OWNER_EMAIL, OWNER_PASSWORD, anonymous_client,
draft_metadata, error_signature, login_client, post_draft,
};
use crank_core::resource::{ResourceKind, ResourceLimits};
/// Test-only размещение рекордера метрик: файл лежит в тестовом пути
/// `apps/admin-api/tests/**`, поэтому прямой рекордер не объявляется в
/// production-исходниках (metrics boundary, TL run109). Захват и положительные
/// образцы остаются теми же.
#[path = "../metrics_capture.rs"]
mod metrics_capture;
/// Канарейка содержимого: одна и та же строка во всех кодировках.
const CANARY: &str = "C36-GUARD-CANARY-7f3a";
/// Тот же маркер, но с символами, которые JSON-сериализатор обязан экранировать.
const ESCAPED_CANARY: &str = "C36-GUARD-\"CANARY\"-\t-7f3a";
const ESCAPED_CANARY_JSON: &str = "C36-GUARD-\\\"CANARY\\\"-\\t-7f3a";
/// Отдельная канарейка существующего чужого Resource: её отсутствие во всех приёмниках
/// и ответах доказывает, что отказ доступа не раскрывает содержимое (R-A).
const FOREIGN_CANARY: &str = "C36-FOREIGN-CANARY-b41d";
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story36_at06_guard_refusals_never_reach_logs_spans_or_metrics() {
// (1) Приёмники в одном процессе: рекордер метрик, писатель журналов, экспортёр спанов.
let capture = metrics_capture::MetricsCapture::install();
// Story 3.6: recording-пути применяют ownership только к связанному сервису,
// поэтому фикстура обязана явно зафиксировать admin-api до первого запроса.
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
.expect("admin-api metrics binding for the guard telemetry fixture");
let writer = SharedLogWriter::default();
let exported = Arc::new(Mutex::new(Vec::new()));
let provider = SdkTracerProvider::builder()
.with_simple_exporter(CapturingExporter(Arc::clone(&exported)))
.build();
let tracer = provider.tracer("admin-resource-guard-test");
let subscriber = tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(writer.clone()),
)
.with(tracing_opentelemetry::layer().with_tracer(tracer));
tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber))
.expect("isolated Resource guard tracing subscriber");
let harness = GuardHarness::spawn_with(
"telemetry",
GuardOptions {
foreign_workspace: true,
foreign_workspace_owner: true,
..GuardOptions::default()
},
)
.await;
let owner = login_client(
&harness.root_url,
OWNER_EMAIL,
OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await;
let anonymous = anonymous_client();
let base64_canary = base64::engine::general_purpose::STANDARD.encode(CANARY);
let mut denial_traces = Vec::new();
// (2) guard-путь: анонимный create с канарейкой в содержимом.
let (status, traceable, text, body) = post_draft(
&anonymous,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/anon",
"tel_anon",
"text",
"text/plain",
"internal",
),
CANARY.as_bytes(),
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"anonymous create must be refused: {}",
error_signature(status, &body)
);
assert!(traceable, "a refusal must be attributable via x-trace-id");
assert!(!text.contains(CANARY), "the refusal must not echo content");
denial_traces.push(body);
// (3) malformed JSON: канарейка внутри отклоняемого содержимого.
let malformed = format!("{{\"leak\":\"{CANARY}\"");
let (status, _traceable, text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/json",
"tel_json",
"json",
"application/json",
"internal",
),
malformed.as_bytes(),
"application/json",
)
.await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"malformed JSON must be refused: {}",
error_signature(status, &body)
);
assert!(!text.contains(CANARY));
// Этот отказ используется ниже как коррелированное наблюдение named-события и спана.
let json_refusal = body.clone();
denial_traces.push(body);
// (4) non-UTF8: канарейка + повреждённая последовательность.
let invalid_utf8 = [CANARY.as_bytes(), &[0xC3, 0x28]].concat();
let (status, _traceable, text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/utf8",
"tel_utf8",
"text",
"text/plain",
"internal",
),
&invalid_utf8,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"invalid UTF-8 must be refused: {}",
error_signature(status, &body)
);
assert!(!text.contains(CANARY));
denial_traces.push(body);
// (5) base64-вариант канарейки в содержимом принятого Draft и в отклонённом повторе.
let accepted = format!("accepted-{base64_canary}");
let (status, _traceable, _text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/base64",
"tel_base64",
"text",
"text/plain",
"internal",
),
accepted.as_bytes(),
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the base64-carrying Draft must be accepted first: {}",
error_signature(status, &body)
);
let (status, _traceable, text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/base64",
"tel_base64_duplicate",
"text",
"text/plain",
"internal",
),
CANARY.as_bytes(),
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CONFLICT,
"a duplicate uri must be refused: {}",
error_signature(status, &body)
);
assert!(!text.contains(CANARY));
denial_traces.push(body);
// (6) oversized: реальное превышение предела содержимого, канарейка в начале bytes.
let limit = ResourceLimits::default().effective_limit(ResourceKind::Text);
let mut oversized = CANARY.as_bytes().to_vec();
oversized.resize(limit + 1, b'x');
let (status, _traceable, text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/oversized",
"tel_oversized",
"text",
"text/plain",
"internal",
),
&oversized,
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::PAYLOAD_TOO_LARGE,
"content beyond the limit must be refused: {}",
error_signature(status, &body)
);
assert!(!text.contains(CANARY));
denial_traces.push(body);
// (7) экранированный вариант канарейки внутри отклоняемого JSON-содержимого:
// незакрытая строка делает тело невалидным JSON, а оба представления маркера
// (с экранированием и без) остаются в отправленных байтах.
let escaped_body = format!("{{\"marker\":\"{ESCAPED_CANARY}\"");
let (status, _traceable, text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/escaped",
"tel_escaped",
"json",
"application/json",
"internal",
),
escaped_body.as_bytes(),
"application/json",
)
.await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"malformed JSON with an escaped marker must be refused: {}",
error_signature(status, &body)
);
assert!(!text.contains(ESCAPED_CANARY));
assert!(!text.contains(ESCAPED_CANARY_JSON));
denial_traces.push(body);
// (8) foreign existing Resource: отказ доступа не раскрывает ни metadata, ни bytes.
// Содержимое чужого Resource несёт проверяемую канарейку, поэтому «не раскрыто»
// наблюдается во всех приёмниках и ответах (R-A), а не только по метаданным.
let foreign_owner = login_client(
&harness.root_url,
crate::app::resource_test_support::FOREIGN_OWNER_EMAIL,
crate::app::resource_test_support::FOREIGN_OWNER_PASSWORD,
LoginOptions::with_csrf(),
)
.await;
let foreign_base = harness.foreign_resources_url();
let foreign_body = format!("foreign payload {FOREIGN_CANARY}");
let (status, _traceable, _text, body) = post_draft(
&foreign_owner,
&foreign_base,
&draft_metadata(
"crank://guard/tel/foreign",
"tel_foreign",
"text",
"text/plain",
"internal",
),
foreign_body.as_bytes(),
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"the foreign owner must seed ResourceB: {}",
error_signature(status, &body)
);
let resource_b = body["resource"]["resource_id"]
.as_str()
.expect("ResourceB id")
.to_owned();
let (status, _headers, text, body) =
crate::app::resource_test_support::get_raw(&owner, &format!("{foreign_base}/{resource_b}"))
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a foreign Resource must stay unreadable: {}",
error_signature(status, &body)
);
assert!(!text.contains(FOREIGN_CANARY));
assert!(!text.contains("foreign payload"));
denial_traces.push(body);
// Положительный контроль: разрешённое чтение того же ResourceB его владельцем —
// без него «канарейка не найдена» ничего не доказывала бы.
let (status, _headers, bytes, _body) = crate::app::resource_test_support::get_raw(
&foreign_owner,
&format!("{foreign_base}/{resource_b}/content"),
)
.await;
assert_eq!(status, StatusCode::OK, "the owner reads its own ResourceB");
assert_eq!(
bytes.as_bytes(),
foreign_body.as_bytes(),
"the foreign canary must really be the content of ResourceB"
);
let (status, _headers, _text, body) = post_draft(
&owner,
&harness.resources_url(),
&draft_metadata(
"crank://guard/tel/ok",
"tel_ok",
"text",
"text/plain",
"internal",
),
b"safe payload",
"text/plain",
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"a valid follow-up must succeed: {}",
error_signature(status, &body)
);
provider.force_flush().expect("span export flush");
// (9) Приёмники не пусты: положительные наблюдения, без которых «отсутствие» ничего не значит.
let logs = writer.output();
assert!(
logs.contains("admin request completed"),
"the log sink must receive the completed-request events"
);
assert!(
logs.contains("status=401"),
"the denied anonymous request must appear in the log sink with its outcome"
);
let rendered_spans = format!("{:?}", exported.lock().expect("exported spans"));
assert!(
rendered_spans.contains("http.request"),
"the span sink must receive the request spans"
);
let metrics_samples = capture.samples();
// Положительный контроль метрик: образец именно наших Resource-отказов.
// Story 3.6: четыре Resource-шаблона объявлены точными admin-идентичностями,
// поэтому `route` обязан нести **точный** template, а не `unmatched`.
let http_samples: Vec<_> = metrics_samples
.iter()
.filter(|(key, _, _, _)| key.key().name() == "crank_http_requests_total")
.collect();
assert!(
!http_samples.is_empty(),
"the metrics sink must receive HTTP request samples from the executed requests"
);
let denied_post_sample = http_samples.iter().find(|(key, _, _, _)| {
key.key()
.labels()
.any(|label| label.key() == "method" && label.value() == "POST")
&& key
.key()
.labels()
.any(|label| label.key() == "status_class" && label.value() == "4xx")
});
assert!(
denied_post_sample.is_some(),
"a refused Resource POST must be observable as a 4xx HTTP sample; observed keys: {:?}",
http_samples
.iter()
.map(|(key, _, _, _)| format!("{:?}", key.key()))
.collect::<Vec<_>>()
);
let resource_route_label = http_samples
.iter()
.flat_map(|(key, _, _, _)| key.key().labels())
.filter(|label| label.key() == "route")
.map(|label| label.value().to_owned())
.collect::<Vec<_>>();
assert!(
resource_route_label
.iter()
.any(|route| route == "/api/auth/login"),
"a known route must keep its own label: {resource_route_label:?}"
);
let resource_collection_template = "/api/admin/workspaces/{workspace_id}/resources";
assert!(
resource_route_label
.iter()
.any(|route| route == resource_collection_template),
"the refused Resource POST must keep its exact admin template \
`{resource_collection_template}`: {resource_route_label:?}"
);
assert!(
resource_route_label
.iter()
.all(|route| route != "unmatched"),
"no Resource request may stay `unmatched` now that the four templates are \
admin-owned: {resource_route_label:?}"
);
// (10) Ни в одном приёмнике нет содержимого — во всех кодировках и для чужого Resource.
for needle in [
CANARY,
ESCAPED_CANARY,
ESCAPED_CANARY_JSON,
&base64_canary,
FOREIGN_CANARY,
] {
assert!(
!logs.contains(needle),
"the log sink must not carry content bytes ({needle})"
);
assert!(
!rendered_spans.contains(needle),
"the span sink must not carry content bytes ({needle})"
);
for (key, _, _, _) in &metrics_samples {
assert!(
!key.key().name().contains(needle),
"a metric name must not carry content bytes ({needle})"
);
assert!(
!key.key().labels().any(|label| {
label.key().contains(needle) || label.value().contains(needle)
}),
"metric labels must not carry content bytes ({needle})"
);
}
for body in &denial_traces {
let rendered = body.to_string();
assert!(
!rendered.contains(needle),
"a refusal body must not carry content bytes ({needle})"
);
}
}
// Ответ отказа атрибутирован: trace_id присутствует в теле и в журнале.
let trace_id = denial_traces
.iter()
.find_map(|body| body["error"]["trace_id"].as_str())
.expect("a refusal body must expose its trace_id");
assert!(
logs.contains(trace_id),
"the attributed refusal must be observable in the log sink"
);
// (11) Коррелированный named-отказ (R-A): настоящее событие
// `admin.response.rejected` с точным `error_code`, тем же request_id/trace_id и
// соответствующим экспортированным span-ом запроса. Без этого «отказы видны в журнале»
// остаётся общим утверждением, а не наблюдением конкретного события.
let json_code = json_refusal["error"]["code"]
.as_str()
.expect("the malformed-JSON refusal must carry its stable code")
.to_owned();
assert_eq!(json_code, "resource_content_invalid_json");
let json_request_id = json_refusal["error"]["request_id"]
.as_str()
.expect("the refusal must expose its request_id")
.to_owned();
let json_trace_id = json_refusal["error"]["trace_id"]
.as_str()
.expect("the refusal must expose its trace_id")
.to_owned();
let rejected_line = logs
.lines()
.find(|line| {
// Наблюдение настоящего события отказа: имя объявлено как name-поле события,
// которое fmt-слой не печатает, поэтому корреляция идёт по телу события
// (`error_code`) вместе с request_id/trace_id отказа в одной строке.
line.contains("error_code")
&& line.contains(json_code.as_str())
&& line.contains(json_request_id.as_str())
&& line.contains(json_trace_id.as_str())
})
.unwrap_or_else(|| {
panic!(
"the named rejected event must be logged together with its error_code \
(`{json_code}`) and the correlated request_id/trace_id of the refusal \
(`{json_request_id}`/`{json_trace_id}`); log sink={logs}"
)
});
assert!(
rejected_line.contains("rejected") || rejected_line.contains("admin_api::error"),
"the correlated line must be the rejection event, not an unrelated record: {rejected_line}"
);
let spans = exported.lock().expect("exported spans");
let correlated = spans
.iter()
.find(|span| {
span.name.as_ref() == "http.request"
&& span.attributes.iter().any(|attribute| {
attribute.key.as_str() == "request_id"
&& attribute.value.as_str() == json_request_id.as_str()
})
})
.unwrap_or_else(|| {
let rendered: Vec<String> = spans
.iter()
.map(|span| {
let fields: Vec<String> = span
.attributes
.iter()
.map(|attribute| {
format!("{}={}", attribute.key.as_str(), attribute.value.as_str())
})
.collect();
format!("{}[{}]", span.name, fields.join(","))
})
.collect();
panic!(
"the refusal must have an exported http.request span carrying its request_id \
`{json_request_id}`; exported spans: {rendered:?}"
)
});
assert!(
correlated.attributes.iter().any(|attribute| {
attribute.key.as_str() == "trace_id"
&& attribute.value.as_str() == json_trace_id.as_str()
}),
"the exported span must carry the same trace_id as the refusal body"
);
drop(spans);
provider.shutdown().expect("tracer provider shutdown");
}
#[derive(Clone, Default)]
struct SharedLogWriter {
buffer: Arc<Mutex<Vec<u8>>>,
}
impl SharedLogWriter {
fn output(&self) -> String {
String::from_utf8(self.buffer.lock().expect("log buffer").clone()).unwrap_or_default()
}
}
impl<'a> MakeWriter<'a> for SharedLogWriter {
type Writer = SharedLogGuard;
fn make_writer(&'a self) -> Self::Writer {
SharedLogGuard {
buffer: Arc::clone(&self.buffer),
pending: Vec::new(),
}
}
}
struct SharedLogGuard {
buffer: Arc<Mutex<Vec<u8>>>,
pending: Vec<u8>,
}
impl io::Write for SharedLogGuard {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.pending.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
impl Drop for SharedLogGuard {
fn drop(&mut self) {
if let Ok(mut buffer) = self.buffer.lock() {
buffer.extend_from_slice(&self.pending);
}
}
}
#[derive(Clone, Debug)]
struct CapturingExporter(Arc<Mutex<Vec<SpanData>>>);
impl SpanExporter for CapturingExporter {
async fn export(&self, batch: Vec<SpanData>) -> OTelSdkResult {
if let Ok(mut spans) = self.0.lock() {
spans.extend(batch);
}
Ok(())
}
}
/// Компиляционная защита от «пустого» comparison: [Value] не должен молча терять поля.
#[test]
fn denial_body_rendering_keeps_error_fields() {
let body: Value = json!({ "error": { "code": "forbidden", "trace_id": "t-1" } });
assert!(body.to_string().contains("forbidden"));
}
@@ -0,0 +1,471 @@
//! 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"
);
}