Files
crank/apps/admin-api/tests/integration/resources/publication/preview_controls.rs
T
Hermes DevOps 75fe5a123c [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.
2026-10-25 10:00:22 +00:00

293 lines
11 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.
//! AC01 / AT-3.7-01: safe preview не публикует ничего и не раскрывает unbounded bytes.
//!
//! Контроль держит уже принятое и GREEN поведение Story 3.6 (preview/download существуют) и
//! одновременно фиксирует часть контракта 3.7: preview/test read не создаёт Published Version,
//! показывает точный content type/size/findings, а binary preview не отдаёт bytes.
use super::super::helpers::{
CONTENT_LIMIT, assert_download_policy, create_draft, created_resource_id, draft_metadata,
get_card, read_content, read_preview, sha256_hex, spawn_authorized, table_row_count,
};
use super::{assert_nothing_published, assert_version_not_published};
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at01_preview_control_shows_exact_metadata_and_publishes_nothing() {
let (registry, server, client) = spawn_authorized("story37_preview_text").await;
let bytes = "безопасный предпросмотр\nвторая строка\n".as_bytes();
let meta = draft_metadata(
"crank://story37/preview",
"preview_page",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
bytes,
"story37-preview.txt",
"text/plain",
)
.await;
let id = created_resource_id(&created);
let card = get_card(&client, &server, &id).await;
assert_eq!(card["version"]["mime_type"], json!("text/plain"));
assert_eq!(card["version"]["size_bytes"], json!(bytes.len()));
assert_eq!(card["version"]["digest"], json!(sha256_hex(bytes)));
let versions_before_preview = table_row_count(registry.pool(), "resource_versions").await;
let (status, text, preview) = read_preview(&client, &server, &id).await;
assert_eq!(
status,
StatusCode::OK,
"existing Resource preview must stay GREEN (AT-3.7-01); body={text}"
);
assert_eq!(
preview["preview"]["text"],
json!(String::from_utf8_lossy(bytes)),
"safe preview must show the exact stored content for kind=text"
);
assert_eq!(
preview["version"]["mime_type"],
json!("text/plain"),
"preview must show the exact content type"
);
assert_eq!(
preview["version"]["size_bytes"],
json!(bytes.len()),
"preview must show the exact size"
);
assert!(
preview["findings"].is_array(),
"preview must expose findings without publishing (AT-3.7-01): {text}"
);
// «без публикации»: точная версия недоступна, карточка остаётся Draft и число версий
// в существующем реестровом отношении не изменилось.
assert_nothing_published(&client, &server, &id, 1, "AT-3.7-01 text preview").await;
assert_eq!(
table_row_count(registry.pool(), "resource_versions").await,
versions_before_preview,
"a preview must not register a new (published) version row"
);
// download того же Draft остаётся точным и не создаёт публикации
assert_eq!(
read_content(&client, &server, &id).await,
bytes.to_vec(),
"draft download must return the exact bytes"
);
assert_version_not_published(&client, &server, &id, 1, "AT-3.7-01 download").await;
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at01_binary_preview_never_serves_unbounded_bytes() {
let (_registry, server, client) = spawn_authorized("story37_preview_binary").await;
// Детерминированные 64 KiB с явной канарейкой: появление этих bytes в preview-body
// (или его сериализации в DOM/telemetry) сделало бы ответ неограниченным.
const CANARY: &str = "STORY37-BINARY-CANARY-0001";
let mut bytes: Vec<u8> = Vec::with_capacity(64 * 1024);
while bytes.len() < 64 * 1024 {
bytes.extend_from_slice(CANARY.as_bytes());
}
assert!(bytes.len() <= CONTENT_LIMIT);
let meta = draft_metadata(
"crank://story37/preview-binary",
"preview_binary",
"binary",
"image/png",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
&bytes,
"story37-binary.png",
"image/png",
)
.await;
let id = created_resource_id(&created);
let card = get_card(&client, &server, &id).await;
assert_eq!(card["version"]["size_bytes"], json!(bytes.len()));
assert_eq!(card["version"]["digest"], json!(sha256_hex(&bytes)));
let (status, text, preview) = read_preview(&client, &server, &id).await;
assert_eq!(
status,
StatusCode::OK,
"binary preview must exist; body={text}"
);
assert!(
preview["preview"]["text"].is_null(),
"kind=binary must not be served as text (D-6): {text}"
);
assert!(
!text.contains(CANARY),
"binary preview must not embed the stored bytes"
);
assert!(
text.len() < 4 * 1024,
"binary preview payload must stay bounded (declared size {} bytes); observed {} bytes",
bytes.len(),
text.len()
);
assert_nothing_published(&client, &server, &id, 1, "AT-3.7-01 binary preview").await;
let response = client
.get(format!("{server}/resources/{id}/content"))
.send()
.await
.expect("binary download request must complete");
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
assert_eq!(
response
.bytes()
.await
.expect("binary body must be readable")
.to_vec(),
bytes,
"binary bytes must round-trip unchanged"
);
}
// ---------------------------------------------------------------------------
// D2 (TL review R1): findings preview — реальные коды publication-scanner
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at01_preview_findings_expose_stable_codes_without_bytes_or_publication() {
let (registry, server, client) = spawn_authorized("story37_preview_findings").await;
// Синтетическая raw-credential канарейка: тот же scanner обязан отказать публикации
// (AC02) и показать нарушение в preview (AC01), не раскрывая совпавший текст.
const CANARY: &str = "story37-preview-canary-5c1d";
let secret = format!("password = {CANARY}\n");
let meta = draft_metadata(
"crank://story37/preview-findings",
"preview_findings",
"text",
"text/plain",
"internal",
);
let created = create_draft(
&client,
&server,
&meta,
secret.as_bytes(),
"story37-preview-findings.txt",
"text/plain",
)
.await;
let id = created_resource_id(&created);
let publications_before = table_row_count(registry.pool(), "resource_publications").await;
let (status, text, preview) = read_preview(&client, &server, &id).await;
assert_eq!(
status,
StatusCode::OK,
"preview must stay readable for content that publication refuses; body={text}"
);
// Preview остаётся инертным: текст показывается, но findings не содержат его bytes.
assert_eq!(preview["preview"]["text"], json!(secret));
let findings = preview["findings"]
.as_array()
.unwrap_or_else(|| panic!("preview must carry a findings array: {text}"));
assert!(
!findings.is_empty(),
"preview must surface the real publication finding instead of an empty list: {text}"
);
assert_eq!(
findings[0]["code"],
json!("resource_secret_findings"),
"the finding must reuse the stable publication domain code: {text}"
);
assert_eq!(
findings[0]["field"],
json!("content"),
"the finding must point at the stable field, not at the matched text: {text}"
);
for finding in findings {
let object = finding
.as_object()
.unwrap_or_else(|| panic!("a finding must be an object: {text}"));
assert_eq!(
object.len(),
2,
"a finding exposes exactly stable code/field, no extra bytes: {finding}"
);
}
assert!(
!preview["findings"].to_string().contains(CANARY),
"findings must never embed the matched secret bytes: {text}"
);
// Clean control: обычный текст не даёт findings, то есть непустой ответ не ложный.
let clean_bytes = b"ordinary preview body\n";
let clean = create_draft(
&client,
&server,
&draft_metadata(
"crank://story37/preview-findings-clean",
"preview_findings_clean",
"text",
"text/plain",
"internal",
),
clean_bytes,
"story37-preview-findings-clean.txt",
"text/plain",
)
.await;
let clean_id = created_resource_id(&clean);
let (status, text, clean_preview) = read_preview(&client, &server, &clean_id).await;
assert_eq!(status, StatusCode::OK, "clean preview must succeed: {text}");
assert_eq!(
clean_preview["findings"],
json!([]),
"clean content must report no findings: {text}"
);
// Никакой побочной публикации: findings — только чтение.
assert_nothing_published(&client, &server, &id, 1, "D2 preview findings").await;
assert_eq!(
table_row_count(registry.pool(), "resource_publications").await,
publications_before,
"a findings preview must not create publication rows"
);
// Тот же scanner по-прежнему отказывает публикации этого Draft.
let card = get_card(&client, &server, &id).await;
let (status, text, body) = super::publish(
&client,
&server,
&id,
card["resource"]["updated_at"].as_str().unwrap_or_default(),
)
.await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"publication of the same bytes must stay refused; observed body={text}"
);
assert_eq!(body["error"]["code"], json!("resource_secret_findings"));
assert!(
!text.contains(CANARY),
"the publication refusal must not disclose the matched bytes: {text}"
);
}