//! 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(®istry).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(®istry).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}" ); }