[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,393 @@
//! API/registry часть AC06 / AT-3.7-06 для первого среза публикации.
//!
//! Проверяется: недоступная (отсутствующая/чужая) сущность — 404 без раскрытия; ответы
//! публикации и точной версии не раскрывают storage/path/raw filename; новые мутирующие
//! маршруты публикации подчиняются существующим guard-ам (сессия, CSRF, origin, роль), а
//! владелец тем же путём публикует успешно.
//!
//! Остаток AC06 (archive, stale Agent revision, Playwright/browser) остаётся обязательным
//! остатком Story 3.7 и здесь не проверяется.
use super::super::helpers::{
DEFAULT_WORKSPACE_ID, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, assert_download_policy,
create_draft, create_owned_workspace, created_resource_id, draft_metadata, draft_updated_at,
ensure_viewer_membership, error_signature, get_card, header_value, login_client,
login_client_with_foreign_origin, login_client_without_csrf, spawn_authorized,
};
use super::{
assert_immutable_metadata, assert_nothing_published, assert_version_not_published,
create_and_publish, create_fixture, publish, published_metadata, read_version,
read_version_content, version_metadata,
};
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_missing_and_foreign_resources_are_not_found_without_disclosure() {
let (registry, server, _client) = spawn_authorized("story37_at06_not_found").await;
// (a) несуществующая сущность: разрешение (C) важнее precondition (F), как в существующем
// PUT-контракте.
let (status, text, body) = publish(
&_client,
&server,
"res_story37_missing",
"2026-01-01T00:00:00Z",
)
.await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"publishing an unavailable Resource must be 404 (TL decision 2); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
json!("resource_not_found"),
"a publish of an unavailable Resource must keep the existing sanitized Resource envelope \
(`error.code`=resource_not_found); observed status={status} body={text}"
);
assert_eq!(
body["error"]["context"]["field"],
json!("resource_id"),
"the refusal must name the offending field; observed body={text}"
);
assert!(
!text.contains("uri") && !text.contains("digest") && !text.contains("mime"),
"a missing Resource refusal must not disclose artifact metadata: {text}"
);
assert_version_not_published(
&_client,
&server,
"res_story37_missing",
1,
"AT-3.7-06 missing resource",
)
.await;
// (b) чужая сущность: Resource существует в другом workspace того же аккаунта
// (Owner membership выдан), поэтому проверяется entity-level scoping, а не workspace-guard.
let owned_workspace = create_owned_workspace(&registry).await;
let workspace_b = server
.as_ref()
.replace(DEFAULT_WORKSPACE_ID, owned_workspace.as_str());
// Сессия логинится уже после выдачи membership.
let client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let foreign_meta = draft_metadata(
"crank://story37/foreign",
"foreign_doc",
"text",
"text/plain",
"secret",
);
let foreign = create_draft(
&client,
&workspace_b,
&foreign_meta,
b"foreign secret body",
"story37-foreign-raw.txt",
"text/plain",
)
.await;
let foreign_id = created_resource_id(&foreign);
let (status, text, body) = publish(&client, &server, &foreign_id, "2026-01-01T00:00:00Z").await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"a Resource of another workspace must be 404 without disclosure; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_not_found"));
assert!(
!text.contains("foreign_doc")
&& !text.contains("crank://story37/foreign")
&& !text.contains("text/plain"),
"the refusal must not disclose the foreign Resource metadata: {text}"
);
assert_version_not_published(&client, &server, &foreign_id, 1, "AT-3.7-06 foreign").await;
// Positive control: в своём workspace тот же Resource публикуется тем же маршрутом.
let foreign_card = get_card(&client, &workspace_b, &foreign_id).await;
let (status, text, body) = publish(
&client,
&workspace_b,
&foreign_id,
&draft_updated_at(&foreign_card),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"the same Resource must publish inside its own workspace; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(published_metadata(&body)["version"], json!(1));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_published_reads_do_not_disclose_storage_reference() {
let (_registry, server, client) = spawn_authorized("story37_at06_no_disclosure").await;
let bytes = "опубликованный документ\n".as_bytes();
let raw_upload_filename = "story37-raw-upload-secret-name.bin";
let mut meta = draft_metadata(
"crank://story37/disclosure",
"public_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("описание опубликованного документа");
let published = create_and_publish(
&client,
&server,
&meta,
bytes,
raw_upload_filename,
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
assert!(
!published.body.to_string().contains(raw_upload_filename),
"the publish response must not echo the raw upload filename: {}",
published.body
);
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the exact Version metadata must be readable; observed {} body={text}",
error_signature(status, &body)
);
assert_immutable_metadata(&version_metadata(&body), raw_upload_filename);
assert!(
!text.contains(raw_upload_filename) && !text.contains("src_") && !text.contains("/sha256/"),
"the Version metadata response must not disclose a storage reference: {text}"
);
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
let disposition = header_value(response.headers(), "content-disposition");
assert!(
disposition.contains("public_doc.txt"),
"the published download must keep the filename derived from `name`: {disposition}"
);
assert!(
!disposition.contains(raw_upload_filename),
"the published download must not leak the raw upload filename: {disposition}"
);
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
bytes.to_vec()
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_guard_negatives_protect_publish_route() {
let (_registry, server, client) = spawn_authorized("story37_at06_guards").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/guard",
"guard_doc",
"text",
"text/plain",
"internal",
),
b"guard body",
"story37-guard.txt",
"text/plain",
)
.await;
// (a) без сессии guard обязан отказать до маршрутизации и до чтения тела.
let anonymous = reqwest::Client::new();
let (status, text, _) = publish(
&anonymous,
&server,
&fixture.resource_id,
&fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::UNAUTHORIZED,
"a publish without a session must be refused: {text}"
);
// (b) сессия без CSRF (browser mutation).
let without_csrf =
login_client_without_csrf(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = publish(
&without_csrf,
&server,
&fixture.resource_id,
&fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a publish without the CSRF token must be refused: {text}"
);
// (c) cross-origin запрос.
let foreign_origin =
login_client_with_foreign_origin(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let (status, text, _) = publish(
&foreign_origin,
&server,
&fixture.resource_id,
&fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a cross-origin publish must be refused: {text}"
);
// Ни один негатив не создал Published Version и не сдвинул карточку Draft.
assert_nothing_published(
&client,
&server,
&fixture.resource_id,
1,
"AT-3.7-06 guards",
)
.await;
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_viewer_cannot_publish_but_owner_can() {
let (registry, server, client) = spawn_authorized("story37_at06_roles").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/roles",
"roles_doc",
"text",
"text/plain",
"internal",
),
b"roles body",
"story37-roles.txt",
"text/plain",
)
.await;
let (viewer_email, viewer_password) = ensure_viewer_membership(&registry).await;
let viewer = login_client(&server, viewer_email, viewer_password).await;
let (status, text, body) =
publish(&viewer, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::FORBIDDEN,
"a Viewer must not publish a Resource — the existing mutation guard covers the new route; \
observed {} body={text}",
error_signature(status, &body)
);
assert_nothing_published(
&client,
&server,
&fixture.resource_id,
1,
"AT-3.7-06 viewer",
)
.await;
// Positive control: владелец публикует тот же Draft (отказ Viewer не оставил side effects).
let (status, text, body) =
publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::OK,
"the owner must publish the same Draft; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(published_metadata(&body)["version"], json!(1));
}
/// F4 (TL CODE-REVIEW): `version` — публичный `u32`-path, но версия вне представимого
/// БД диапазона не может существовать. Оба exact-read маршрута авторизованного
/// workspace обязаны дать sanitized 404, а не storage-500.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at06_unrepresentable_version_is_not_found() {
let (_registry, server, client) = spawn_authorized("story37_at06_version_bounds").await;
// Положительный контроль: реальная Published Version 1 доступна обоими маршрутами.
let published = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/version-bounds",
"version_bounds",
"text",
"text/plain",
"internal",
),
b"version bounds body\n",
"story37-version-bounds.txt",
"text/plain",
)
.await;
let resource_id = published.draft.resource_id.clone();
let (status, text, body) = read_version(&client, &server, &resource_id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the existing version must stay readable; observed {} body={text}",
error_signature(status, &body)
);
// Версия вне i32-диапазона: metadata и content — sanitized 404.
let impossible: u32 = 2_147_483_648;
let (status, text, body) = read_version(&client, &server, &resource_id, impossible).await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"an unrepresentable version must be a sanitized 404, not a storage failure; observed {} \
body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_not_found"));
assert!(
!text.to_ascii_lowercase().contains("storage")
&& !text.contains("internal server error")
&& !text.contains(&impossible.to_string()),
"the refusal must stay sanitized: {text}"
);
let response = read_version_content(&client, &server, &resource_id, impossible).await;
let content_status = response.status();
let content_text = response.text().await.unwrap_or_default();
assert_eq!(
content_status,
StatusCode::NOT_FOUND,
"the content route must mirror the sanitized 404; observed body={content_text}"
);
assert!(
!content_text.to_ascii_lowercase().contains("storage")
&& !content_text.contains("internal server error"),
"the content refusal must stay sanitized: {content_text}"
);
}
@@ -0,0 +1,361 @@
//! AC03 / AT-3.7-03: immutable Published Resource Version.
//!
//! Публикация создаёт неизменяемую версию; последующее редактирование Draft создаёт новый
//! Draft, но не меняет опубликованные bytes/metadata (TL interface decisions 2–3, risk E3-R3:
//! «concurrent edit/archive/publish ... cannot mutate a published snapshot»). Точное значение
//! версии читается через `GET .../resources/{id}/versions/{version}` и `.../versions/{v}/content`;
//! зависший precondition повторной публикации остаётся 428 `resource_stale`/`recovery=reload`
//! и не создаёт duplicate/partial writes.
use super::super::helpers::{
assert_download_policy, draft_metadata, draft_updated_at, error_signature, get_card,
header_value, read_content, sha256_hex, spawn_authorized, table_row_count,
};
use super::{
assert_immutable_metadata, assert_version_not_published, create_and_publish, publish,
publish_raw, published_metadata, read_version, read_version_content, resource_card_id,
update_draft_expect_success, version_metadata,
};
use crank_registry::PostgresRegistry;
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
/// Итоги существующих реестровых отношений: нужны как наблюдение «duplicate/partial writes
/// не появилось». Схема публикации ещё не выбрана (TL decision 5), поэтому тест не опирается на
/// новые отношения — только на уже принятые.
async fn relation_counts(registry: &PostgresRegistry) -> (i64, i64, i64, i64) {
(
table_row_count(registry.pool(), "resources").await,
table_row_count(registry.pool(), "resource_versions").await,
table_row_count(registry.pool(), "artifact_sources").await,
table_row_count(registry.pool(), "artifact_blobs").await,
)
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_publish_creates_immutable_version_readable_exactly() {
let (_registry, server, client) = spawn_authorized("story37_at03_immutable").await;
let bytes = "опубликованное содержимое\nвторая строка\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/published",
"published_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание");
let raw_upload_filename = "story37-published-raw.bin";
let published = create_and_publish(
&client,
&server,
&meta,
bytes,
raw_upload_filename,
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
// Тело успешного ответа несёт и карточку Resource, и immutable metadata (TL decision 2).
assert_eq!(
resource_card_id(&published.body).as_deref(),
Some(id.as_str()),
"a successful publish must answer the Resource card too: {}",
published.body
);
// Точные поля Published Version: независимый оракул digest считается тестом.
assert_eq!(snapshot["version"], json!(1));
assert_eq!(snapshot["uri"], json!("crank://story37/published"));
assert_eq!(snapshot["name"], json!("published_doc"));
assert_eq!(snapshot["description"], json!("опубликованное описание"));
assert_eq!(snapshot["kind"], json!("text"));
assert_eq!(snapshot["mime_type"], json!("text/plain"));
assert_eq!(snapshot["size_bytes"], json!(bytes.len()));
assert_eq!(snapshot["digest"], json!(sha256_hex(bytes)));
assert_eq!(snapshot["sensitivity"], json!("internal"));
// GET .../versions/{version} возвращает тот же immutable object.
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the exact Published Version metadata must be readable (TL decision 3); observed {} body={text}",
error_signature(status, &body)
);
let observed = version_metadata(&body);
assert_eq!(
observed, snapshot,
"GET versions/1 must return the same immutable metadata object that publish returned"
);
assert_immutable_metadata(&observed, raw_upload_filename);
// GET .../versions/{version}/content отдаёт точные опубликованные bytes и остаётся инертным.
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
let disposition = header_value(response.headers(), "content-disposition");
assert!(
!disposition.contains(raw_upload_filename),
"the raw upload filename must not reach the published download header: {disposition}"
);
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
bytes.to_vec(),
"GET versions/1/content must return the exact published bytes"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_draft_edit_does_not_change_published_bytes_or_metadata() {
let (_registry, server, client) = spawn_authorized("story37_at03_pinned").await;
let first_bytes = "published body v1\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/pinned",
"pinned_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание");
let published = create_and_publish(
&client,
&server,
&meta,
first_bytes,
"story37-pinned-raw.bin",
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
let card_before_edit = get_card(&client, &server, &id).await;
let second_bytes = "draft body v2\n".as_bytes();
let updated = update_draft_expect_success(
&client,
&server,
&id,
&json!({
"description": "изменённое описание черновика",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": draft_updated_at(&card_before_edit),
}),
second_bytes,
"story37-pinned-raw.bin",
"text/plain",
)
.await;
assert_eq!(
updated["version"]["version"],
json!(2),
"editing after publication must create a new Draft version (AT-3.7-03)"
);
// Черновик изменился по всем наблюдаемым полям.
let card = get_card(&client, &server, &id).await;
assert_eq!(card["version"]["version"], json!(2));
assert_eq!(card["version"]["digest"], json!(sha256_hex(second_bytes)));
assert_eq!(card["version"]["sensitivity"], json!("public"));
assert_eq!(
card["resource"]["description"],
json!("изменённое описание черновика")
);
assert_eq!(
read_content(&client, &server, &id).await,
second_bytes.to_vec(),
"the current Draft content must be the edited bytes"
);
// Опубликованный snapshot не изменился ни в metadata, ни в bytes.
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must stay readable after a Draft edit; observed {} body={text}",
error_signature(status, &body)
);
let observed = version_metadata(&body);
assert_eq!(
observed, snapshot,
"a Draft edit must not change the Published Version metadata (AT-3.7-03)"
);
assert_eq!(
observed["description"],
json!("опубликованное описание"),
"the published description must stay pinned"
);
assert_eq!(
observed["sensitivity"],
json!("internal"),
"the published sensitivity must stay pinned even when the Draft raises it"
);
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_download_policy(response.headers());
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
first_bytes.to_vec(),
"the published bytes must stay pinned after a Draft edit"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at03_stale_and_repeated_publish_never_mutate_published_snapshot() {
let (registry, server, client) = spawn_authorized("story37_at03_stale").await;
let first_bytes = "published v1 bytes\n".as_bytes();
let mut meta = draft_metadata(
"crank://story37/stale",
"stale_doc",
"text",
"text/plain",
"internal",
);
meta["description"] = json!("опубликованное описание v1");
let published = create_and_publish(
&client,
&server,
&meta,
first_bytes,
"story37-stale-v1.txt",
"text/plain",
)
.await;
let id = published.draft.resource_id.clone();
let snapshot = published.published_version.clone();
let counts_after_publish = relation_counts(&registry).await;
// Повтор той же публикации: precondition прежней карточки уже stale (TL decision 2/3).
let (status, text, body) = publish(&client, &server, &id, &published.draft.updated_at).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"repeating the same publish must be 428; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
assert_eq!(body["error"]["context"]["recovery"], json!("reload"));
// Отсутствующий precondition — тот же 428 без публикации.
let (status, text, body) = publish_raw(&client, &server, &id, &json!({})).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a publish without precondition must be 428 (TL decision 2); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
// Ни duplicate publication, ни partial writes: отношения и снапшот не изменились.
assert_eq!(
relation_counts(&registry).await,
counts_after_publish,
"a stale/repeated publish must not write any row"
);
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must stay readable; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
version_metadata(&body),
snapshot,
"a stale publish must not mutate the published snapshot"
);
// Редактирование Draft: publish с прежним (теперь stale) precondition снова 428.
let card = get_card(&client, &server, &id).await;
let second_bytes = "draft v2 bytes\n".as_bytes();
update_draft_expect_success(
&client,
&server,
&id,
&json!({
"description": "черновик v2",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": draft_updated_at(&card),
}),
second_bytes,
"story37-stale-v2.txt",
"text/plain",
)
.await;
let (status, text, body) = publish(&client, &server, &id, &published.draft.updated_at).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a publish racing a Draft edit must be 428; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
assert_version_not_published(&client, &server, &id, 2, "AT-3.7-03 stale publish").await;
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the published snapshot must survive the racing publish; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(version_metadata(&body), snapshot);
// Публикация актуального Draft создаёт новую Published Version, прежняя остаётся точной.
let card = get_card(&client, &server, &id).await;
let (status, text, body) = publish(&client, &server, &id, &draft_updated_at(&card)).await;
assert_eq!(
status,
StatusCode::OK,
"the current Draft must be publishable with a fresh precondition; observed {} body={text}",
error_signature(status, &body)
);
let second_published = published_metadata(&body);
assert_immutable_metadata(&second_published, "story37-stale-v2.txt");
assert_eq!(second_published["version"], json!(2));
assert_eq!(second_published["digest"], json!(sha256_hex(second_bytes)));
assert_eq!(second_published["sensitivity"], json!("public"));
let (status, text, body) = read_version(&client, &server, &id, 1).await;
assert_eq!(
status,
StatusCode::OK,
"the earlier Published Version must stay readable; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
version_metadata(&body),
snapshot,
"publishing a newer version must not rewrite the earlier Published Version"
);
let response = read_version_content(&client, &server, &id, 1).await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response
.bytes()
.await
.expect("published content must be readable")
.to_vec(),
first_bytes.to_vec(),
"the earlier Published Version bytes must stay exact"
);
}
@@ -0,0 +1,241 @@
//! AC02 positive/negative controls для publication policy (Story 3.7).
//!
//! TL decision 4: explicit `include: crank://...` — это директива, а не обычное
//! упоминание. Она разрешается только workspace-local по уже опубликованной metadata;
//! понижение sensitivity запрещено. Обычные ссылки, проза и сами слова категорий
//! публикуются. Все контроля используют синтетические значения, без реальных секретов.
use super::super::helpers::{
create_draft, created_resource_id, draft_metadata, error_signature, get_card, spawn_authorized,
};
use super::{create_and_publish, create_fixture, publish, published_metadata};
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
/// Локальная опубликованная цель + обычная ссылка в том же Draft: обе ситуации
/// разрешены и дают immutable Published Version.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_ordinary_link_and_local_published_include_are_publishable() {
let (_registry, server, client) = spawn_authorized("story37_policy_positive").await;
// Цель — exact Published Version в этом же workspace со sensitivity internal.
let target = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/policy-target",
"policy_target",
"text",
"text/plain",
"internal",
),
b"target reference body\n",
"story37-policy-target.txt",
"text/plain",
)
.await;
assert_eq!(target.published_version["version"], json!(1));
// Обычная ссылка + упоминания категорий: не директива и не секрет.
let ordinary = "См. https://example.com/spec; private keys и tokens описаны в prose.\n";
let ordinary_fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/policy-ordinary",
"policy_ordinary",
"text",
"text/plain",
"internal",
),
ordinary.as_bytes(),
"story37-policy-ordinary.txt",
"text/plain",
)
.await;
let (status, text, body) = publish(
&client,
&server,
&ordinary_fixture.resource_id,
&ordinary_fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::OK,
"an ordinary link must stay publishable; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(published_metadata(&body)["version"], json!(1));
// Explicit include на exact published version того же workspace с совместимой
// sensitivity публикуется; текст остаётся статическим (без expansion).
let include = "include: crank://story37/policy-target\n";
let include_fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/policy-include",
"policy_include",
"text",
"text/plain",
"internal",
),
include.as_bytes(),
"story37-policy-include.txt",
"text/plain",
)
.await;
let (status, text, body) = publish(
&client,
&server,
&include_fixture.resource_id,
&include_fixture.updated_at,
)
.await;
assert_eq!(
status,
StatusCode::OK,
"an explicit include of a published local Resource must publish; observed {} body={text}",
error_signature(status, &body)
);
let published = published_metadata(&body);
assert_eq!(published["version"], json!(1));
assert_eq!(published["kind"], json!("text"));
assert!(
!published.to_string().contains("target reference body"),
"publication must not expand the included content: {published}"
);
}
/// Include на published Resource с более высокой sensitivity — access-bypassing
/// reference: тот же generic 422, без раскрытия цели и без side effects.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_include_must_not_lower_published_sensitivity() {
let (_registry, server, client) = spawn_authorized("story37_policy_lowering").await;
// Публикуем секретную цель (sensitivity=secret сама по себе публикуема).
let secret_target = create_and_publish(
&client,
&server,
&draft_metadata(
"crank://story37/policy-secret-target",
"policy_secret_target",
"text",
"text/plain",
"secret",
),
b"synthetic secret target body\n",
"story37-policy-secret-target.txt",
"text/plain",
)
.await;
assert_eq!(secret_target.published_version["version"], json!(1));
// Внутренний Draft включает секретную цель -> понижение sensitivity, отказ.
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/policy-lowering",
"policy_lowering",
"text",
"text/plain",
"internal",
),
b"include: crank://story37/policy-secret-target\n",
"story37-policy-lowering.txt",
"text/plain",
)
.await;
let (status, text, body) =
publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"a sensitivity-lowering include must be refused with 422; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_secret_findings"));
assert_eq!(body["error"]["context"]["field"], json!("content"));
assert!(
!text.contains("policy-secret-target") && !text.contains("policy_secret_target"),
"the refusal must not disclose the referenced target: {text}"
);
// Отказ не опубликовал включающий Draft и не изменил цель.
let card = get_card(&client, &server, &fixture.resource_id).await;
assert_eq!(card["resource"]["status"], json!("draft"));
let (status, _, _) = super::read_version(&client, &server, &fixture.resource_id, 1).await;
assert_eq!(
status,
StatusCode::NOT_FOUND,
"a refused publication must not expose a Published Version"
);
}
/// `include:` на неопубликованную (но существующую) сущность того же workspace —
/// тот же generic отказ; существование/метаданные цели не раскрываются.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_include_requires_published_target_without_disclosure() {
let (_registry, server, client) = spawn_authorized("story37_policy_unpublished").await;
let unpublished_meta = draft_metadata(
"crank://story37/policy-draft-target",
"policy_draft_target",
"text",
"text/plain",
"internal",
);
let unpublished = create_draft(
&client,
&server,
&unpublished_meta,
b"draft-only target body\n",
"story37-policy-draft-target.txt",
"text/plain",
)
.await;
let unpublished_id = created_resource_id(&unpublished);
assert!(!unpublished_id.is_empty());
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/policy-unpublished",
"policy_unpublished",
"text",
"text/plain",
"internal",
),
b"include: crank://story37/policy-draft-target\n",
"story37-policy-unpublished.txt",
"text/plain",
)
.await;
let (status, text, body) =
publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"an include of an unpublished target must be refused; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_secret_findings"));
assert!(
!text.contains("policy-draft-target") && !text.contains("draft-only target body"),
"the refusal must not disclose the unpublished target: {text}"
);
// Цель остаётся Draft и не получила Published Version.
let target_card = get_card(&client, &server, &unpublished_id).await;
assert_eq!(target_card["resource"]["status"], json!("draft"));
let (target_version_status, _, _) =
super::read_version(&client, &server, &unpublished_id, 1).await;
assert_eq!(target_version_status, StatusCode::NOT_FOUND);
}
@@ -0,0 +1,292 @@
//! 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}"
);
}
@@ -0,0 +1,616 @@
//! AC02 / AT-3.7-02: publication validator.
//!
//! Проверяется, что публикация повторно проверяет сохранённые URI/MIME и целостность
//! артефакта (defense-in-depth: строки БД могут пережить более строгую грамматику), а
//! secret-bearing content (raw credential, private key, access-bypassing reference) блокирует
//! публикацию. Любой отказ сохраняет Draft и не создаёт Published metadata.
//!
//! TL interface decision 4: синтетические канарейки, никаких реальных credentials; при
//! отсутствии конкретного secret-policy входа точный пробел возвращается TL вместе с готовым
//! RED (см. `.tmp/t_b132062a/STORY37-ATDD-REPORT.md`).
use super::super::helpers::{
DEFAULT_WORKSPACE_ID, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, create_draft, draft_metadata,
login_client, spawn_authorized, table_row_count,
};
use super::{
create_fixture, overwrite_current_version_mime, overwrite_resource_uri, publish_expect_refusal,
replace_blob_with_tampered_bytes, spawn_with_storage, update_draft_expect_success,
};
use reqwest::StatusCode;
use serde_json::json;
use serial_test::serial;
// ---------------------------------------------------------------------------
// Defense-in-depth: сохранённые метаданные проверяются заново
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_publish_revalidates_stored_uri_and_mime_grammar() {
let (registry, server, client) = spawn_authorized("story37_publish_stored_grammar").await;
// (a) сохранённый URI больше не удовлетворяет грамматике D-10 (верхний регистр схемы),
// хотя ограничение длины и уникальность БД соблюдены.
let uri_fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/stored-uri",
"stored_uri",
"text",
"text/plain",
"internal",
),
b"stored uri body",
"story37-stored-uri.txt",
"text/plain",
)
.await;
overwrite_resource_uri(
registry.pool(),
&uri_fixture.resource_id,
"CRANK://story37/stored-uri",
)
.await;
let refusal = publish_expect_refusal(
&client,
&server,
&uri_fixture.resource_id,
&uri_fixture.updated_at,
StatusCode::BAD_REQUEST,
"AT-3.7-02 stored uri re-validation",
)
.await;
assert_eq!(
refusal["error"]["code"],
json!("resource_uri_invalid"),
"the stored uri grammar failure must keep the existing Resource code: {refusal}"
);
assert_eq!(refusal["error"]["context"]["field"], json!("uri"));
// (b) сохранённый MIME текущей версии больше не входит в allowlist kind.
let mime_fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/stored-mime",
"stored_mime",
"text",
"text/plain",
"internal",
),
b"stored mime body",
"story37-stored-mime.txt",
"text/plain",
)
.await;
overwrite_current_version_mime(
registry.pool(),
&mime_fixture.resource_id,
"application/zip",
)
.await;
let refusal = publish_expect_refusal(
&client,
&server,
&mime_fixture.resource_id,
&mime_fixture.updated_at,
StatusCode::BAD_REQUEST,
"AT-3.7-02 stored mime re-validation",
)
.await;
assert_eq!(
refusal["error"]["code"],
json!("resource_mime_not_allowed"),
"the stored mime allowlist failure must keep the existing Resource code: {refusal}"
);
assert_eq!(refusal["error"]["context"]["field"], json!("mime_type"));
// Оба Draft сохранены и остаются читаемыми: отказ не удалил и не переписал состояние.
assert_eq!(
table_row_count(registry.pool(), "resources").await,
2,
"both refused Drafts must still exist"
);
}
// ---------------------------------------------------------------------------
// Defense-in-depth: целостность сохранённого артефакта
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_publish_refuses_tampered_artifact_integrity() {
let (registry, server, client, storage_root) =
spawn_with_storage("story37_publish_integrity").await;
let bytes = b"integrity fixture body\n";
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/integrity",
"integrity_doc",
"text",
"text/plain",
"internal",
),
bytes,
"story37-integrity.txt",
"text/plain",
)
.await;
let digest = fixture.card["version"]["digest"]
.as_str()
.expect("Draft card must expose the stored digest")
.to_owned();
assert_eq!(
digest,
super::super::helpers::sha256_hex(bytes),
"the fixture digest must match the stored bytes"
);
let versions_before = table_row_count(registry.pool(), "resource_versions").await;
// Store-контракт сохраняется (обычный read-only файл с одной ссылкой), поэтому отказ
// обязан прийти именно из digest/размерной проверки.
replace_blob_with_tampered_bytes(&storage_root, &digest, b"story37-tampered-payload");
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 artifact integrity",
)
.await;
assert!(
!refusal
.to_string()
.contains(storage_root.to_str().unwrap_or_default()),
"an integrity refusal must not disclose the storage path: {refusal}"
);
assert_eq!(
table_row_count(registry.pool(), "resource_versions").await,
versions_before,
"a refused publication must not register a new version row"
);
}
// ---------------------------------------------------------------------------
// Secret-bearing content блокирует публикацию
// ---------------------------------------------------------------------------
/// Синтетический PEM-блок: заголовки реального формата, тело — очевидно неправдоподобная
/// строка, поэтому ни один настоящий ключ не используется (TL decision 4).
const SYNTHETIC_PRIVATE_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\n\
c3ludGhldGljLXN0b3J5MzctcHJpdmF0ZS1rZXktYm9keS1ub3QtYS1yZWFsLWtleQ==\n\
-----END PRIVATE KEY-----\n";
/// Синтетическая raw credential: документированный AWS-пример (публичные, учебные значения),
/// а не рабочий секрет.
const SYNTHETIC_RAW_CREDENTIAL: &str = "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n\
aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n";
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_publish_refuses_private_key_content() {
let (_registry, server, client) = spawn_authorized("story37_secret_private_key").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/private-key",
"private_key_doc",
"text",
"text/plain",
"internal",
),
SYNTHETIC_PRIVATE_KEY_PEM.as_bytes(),
"story37-private-key.txt",
"text/plain",
)
.await;
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 private key publication refusal",
)
.await;
assert!(
!refusal.to_string().contains("BEGIN PRIVATE KEY")
&& !refusal.to_string().contains("c3ludGhldGlj"),
"the refusal must stay sanitized and must not echo the secret-bearing content: {refusal}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_publish_refuses_raw_credential_content() {
let (_registry, server, client) = spawn_authorized("story37_secret_raw_credential").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/raw-credential",
"raw_credential_doc",
"text",
"text/plain",
"internal",
),
SYNTHETIC_RAW_CREDENTIAL.as_bytes(),
"story37-raw-credential.txt",
"text/plain",
)
.await;
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 raw credential publication refusal",
)
.await;
assert!(
!refusal.to_string().contains("AKIAIOSFODNN7EXAMPLE")
&& !refusal.to_string().contains("wJalrXUtnFEMI"),
"the refusal must stay sanitized and must not echo the credential: {refusal}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_publish_refuses_access_bypassing_reference() {
let (registry, server, _client) = spawn_authorized("story37_secret_bypass").await;
// WorkspaceB принадлежит тому же аккаунту (Owner membership), поэтому обе сущности
// доступны одной авторизации, но это разные workspace-скоупы: ссылка из WorkspaceA на
// секретную сущность WorkspaceB обошла бы scope публикуемого ресурса.
let owned_workspace = super::super::helpers::create_owned_workspace(&registry).await;
let workspace_b = server
.as_ref()
.replace(DEFAULT_WORKSPACE_ID, owned_workspace.as_str());
// Сессия логинится уже после выдачи membership.
let client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
let secret_meta = draft_metadata(
"crank://story37/secret-source",
"secret_source",
"text",
"text/plain",
"secret",
);
create_draft(
&client,
&workspace_b,
&secret_meta,
b"secret payload of another workspace",
"story37-secret-source.txt",
"text/plain",
)
.await;
let referencing_content = "include: crank://story37/secret-source\n";
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/bypassing-ref",
"bypassing_ref",
"text",
"text/plain",
"internal",
),
referencing_content.as_bytes(),
"story37-bypassing-ref.txt",
"text/plain",
)
.await;
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 access-bypassing reference refusal",
)
.await;
assert!(
!refusal.to_string().contains("secret_source")
&& !refusal
.to_string()
.contains("crank://story37/secret-source"),
"the refusal must not disclose the referenced secret entity: {refusal}"
);
}
/// Точность детектора: обычный текст, который лишь упоминает категории, не является секретом
/// и обязан публиковаться (TL decision 4: не считать любую ссылку secret, не вводить
/// universal scanner).
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_benign_mentions_are_not_treated_as_secrets() {
let (_registry, server, client) = spawn_authorized("story37_secret_precision").await;
let benign = "Инструкция: не коммитьте private key в репозиторий, \
используйте secret manager и переменные окружения.\n";
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/benign-mentions",
"benign_mentions",
"text",
"text/plain",
"internal",
),
benign.as_bytes(),
"story37-benign.txt",
"text/plain",
)
.await;
let (status, text, body) =
super::publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::OK,
"a merely descriptive text must stay publishable; observed {} body={text}",
super::super::helpers::error_signature(status, &body)
);
assert_eq!(super::published_metadata(&body)["version"], json!(1));
}
// ---------------------------------------------------------------------------
// Позитивный контроль: отказ не ломает существующий контракт обновления Draft
// ---------------------------------------------------------------------------
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_refusal_keeps_existing_draft_update_contract_intact() {
let (registry, server, client) = spawn_authorized("story37_refusal_then_update").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/refusal-update",
"refusal_update",
"text",
"text/plain",
"internal",
),
b"first body",
"story37-refusal-update.txt",
"text/plain",
)
.await;
overwrite_current_version_mime(registry.pool(), &fixture.resource_id, "application/zip").await;
publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::BAD_REQUEST,
"AT-3.7-02 refusal has no side effects",
)
.await;
// Существующий PUT-контракт после отказа продолжает работать: precondition карточки
// не сдвинулся, обычное редактирование принимается и возвращает состояние Draft.
let updated = update_draft_expect_success(
&client,
&server,
&fixture.resource_id,
&json!({
"description": "правка после отказа",
"mime_type": "text/plain",
"sensitivity": "public",
"expected_updated_at": fixture.updated_at,
}),
b"second body",
"story37-refusal-update.txt",
"text/plain",
)
.await;
assert_eq!(updated["version"]["version"], json!(2));
assert_eq!(updated["version"]["mime_type"], json!("text/plain"));
}
// ---------------------------------------------------------------------------
// F2/F3/F1 (TL CODE-REVIEW): семантические raw credentials, реальные
// placeholders и безопасная инспекция malformed содержимого
// ---------------------------------------------------------------------------
/// F2: JSON-credential распознаётся независимо от позиции ключа и от JSON-экранирования;
/// отказ — тот же generic 422 `field=content` без новых строк публикации/source.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_json_credentials_are_detected_semantically() {
let (registry, server, client) = spawn_authorized("story37_secret_json").await;
for (uri, name, content) in [
(
"crank://story37/json-later-key",
"json_later_key",
br#"{"name":"config","password":"synthetic-password-42"}"#.as_slice(),
),
(
"crank://story37/json-escaped-key",
"json_escaped_key",
br#"{"pass\u0077ord":"synthetic-password-42"}"#.as_slice(),
),
] {
let fixture = create_fixture(
&client,
&server,
&draft_metadata(uri, name, "json", "application/json", "internal"),
content,
"story37-secret.json",
"application/json",
)
.await;
// Счётчики берутся после создания Draft: сам Draft владеет одной active-ссылкой.
let publications_before = table_row_count(registry.pool(), "resource_publications").await;
let sources_before = table_row_count(registry.pool(), "artifact_sources").await;
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 JSON raw credential refusal",
)
.await;
assert_eq!(refusal["error"]["code"], json!("resource_secret_findings"));
assert_eq!(refusal["error"]["context"]["field"], json!("content"));
assert!(
!refusal.to_string().contains("synthetic-password-42"),
"the refusal must not echo the credential: {refusal}"
);
assert_eq!(
table_row_count(registry.pool(), "resource_publications").await,
publications_before,
"a refused JSON credential must not insert a publication row ({content:?})"
);
assert_eq!(
table_row_count(registry.pool(), "artifact_sources").await,
sources_before,
"a refused JSON credential must not insert an owning source ({content:?})"
);
}
}
/// F2: обычные text-assignment формы (bare `token`, произвольный размер значения) и
/// Bearer без цифр — те же raw credentials; ни одна не публикуется.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_text_assignments_and_digit_free_bearer_are_refused() {
let (registry, server, client) = spawn_authorized("story37_secret_assignments").await;
for (index, content) in [
"token = synthetic-value-42\n",
"password = abc123\n",
"Bearer abcdefghijklmnopqrstuvwx\n",
]
.into_iter()
.enumerate()
{
let uri = format!("crank://story37/assignment-{index}");
let name = format!("assignment_{index}");
let fixture = create_fixture(
&client,
&server,
&draft_metadata(&uri, &name, "text", "text/plain", "internal"),
content.as_bytes(),
"story37-assignment.txt",
"text/plain",
)
.await;
// Счётчики берутся после создания Draft: сам Draft владеет одной active-ссылкой.
let publications_before = table_row_count(registry.pool(), "resource_publications").await;
let sources_before = table_row_count(registry.pool(), "artifact_sources").await;
let refusal = publish_expect_refusal(
&client,
&server,
&fixture.resource_id,
&fixture.updated_at,
StatusCode::UNPROCESSABLE_ENTITY,
"AT-3.7-02 text raw credential refusal",
)
.await;
assert_eq!(refusal["error"]["code"], json!("resource_secret_findings"));
assert_eq!(refusal["error"]["context"]["field"], json!("content"));
assert_eq!(
table_row_count(registry.pool(), "resource_publications").await,
publications_before,
"a refused raw credential must not insert a publication row ({content:?})"
);
assert_eq!(
table_row_count(registry.pool(), "artifact_sources").await,
sources_before,
"a refused raw credential must not insert an owning source ({content:?})"
);
}
}
/// F3: полная заглушка в реальной assignment-форме (`Authorization: Bearer ***`)
/// публикуется; положительный контроль — настоящий синтетический token по-прежнему
/// блокируется (`story37_at02_text_assignments_and_digit_free_bearer_are_refused`).
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_authorization_placeholder_is_publishable() {
let (_registry, server, client) = spawn_authorized("story37_secret_placeholder").await;
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/auth-placeholder",
"auth_placeholder",
"text",
"text/plain",
"internal",
),
b"Authorization: Bearer ***\n",
"story37-auth-placeholder.txt",
"text/plain",
)
.await;
let (status, text, body) =
super::publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::OK,
"a documented placeholder must stay publishable; observed {} body={text}",
super::super::helpers::error_signature(status, &body)
);
assert_eq!(super::published_metadata(&body)["version"], json!(1));
}
/// F1: malformed PEM-подобный префикс с многобайтовыми символами — обычный bounded
/// ответ (публикация проходит как обычный текст), а не паника/обрыв соединения.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn story37_at02_malformed_key_prefix_is_a_normal_bounded_response() {
let (_registry, server, client) = spawn_authorized("story37_secret_malformed").await;
let content = format!("-----BEGIN a{}", "я".repeat(60));
let fixture = create_fixture(
&client,
&server,
&draft_metadata(
"crank://story37/malformed-key",
"malformed_key",
"text",
"text/plain",
"internal",
),
content.as_bytes(),
"story37-malformed-key.txt",
"text/plain",
)
.await;
let (status, text, body) =
super::publish(&client, &server, &fixture.resource_id, &fixture.updated_at).await;
assert_eq!(
status,
StatusCode::OK,
"a malformed non-key prefix must produce a normal bounded response; observed {} body={text}",
super::super::helpers::error_signature(status, &body)
);
assert_eq!(super::published_metadata(&body)["version"], json!(1));
}