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

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}"
);
}