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
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.
386 lines
14 KiB
Rust
386 lines
14 KiB
Rust
//! Story 3.9 (BUILD): дополнительные обязательные проверки переноса, которые ранний RED
|
||
//! не доказывал — точный Published snapshot после изменения Draft и следующей публикации,
|
||
//! иной разрешённый `sensitivity`, заголовки экспорта, безопасные отказы и атрибуция.
|
||
//!
|
||
//! Файл — маленький sibling `portability.rs` (health-лимит 1000 строк на файл); фильтр тот же:
|
||
//! `cargo test -p admin-api --test integration story39_ -- --test-threads=1`.
|
||
|
||
use super::helpers::{
|
||
TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD, api_root, create_draft, create_owned_workspace,
|
||
created_resource_id, draft_metadata, draft_updated_at, error_signature, get_card, login_client,
|
||
read_response, sha256_hex, spawn_authorized, table_row_count,
|
||
};
|
||
use super::{put_draft_raw, update_metadata};
|
||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||
use reqwest::StatusCode;
|
||
use serde_json::{Value, json};
|
||
use serial_test::serial;
|
||
|
||
const ENVELOPE_FORMAT: &str = "crank-resource-portability";
|
||
|
||
/// Тот же предел тела импорта, что у маршрута: `MAX_ARTIFACT_BYTES / 3 * 4 + 64 KiB`.
|
||
const MAX_IMPORT_BODY_BYTES: usize = crank_artifacts::MAX_ARTIFACT_BYTES / 3 * 4 + 64 * 1024;
|
||
|
||
/// База workspace для существующих helpers (`{base}/resources`).
|
||
fn workspace_base(server: impl AsRef<str>, workspace_id: &str) -> String {
|
||
format!(
|
||
"{}/api/admin/workspaces/{workspace_id}",
|
||
api_root(server.as_ref())
|
||
)
|
||
}
|
||
|
||
async fn export_draft(
|
||
client: &reqwest::Client,
|
||
base: &str,
|
||
resource_id: &str,
|
||
) -> (StatusCode, String, Value) {
|
||
read_response(
|
||
client
|
||
.get(format!("{base}/resources/{resource_id}/export"))
|
||
.send()
|
||
.await
|
||
.expect("draft export request must complete"),
|
||
)
|
||
.await
|
||
}
|
||
|
||
async fn export_version(
|
||
client: &reqwest::Client,
|
||
base: &str,
|
||
resource_id: &str,
|
||
version: u32,
|
||
) -> (StatusCode, String, Value) {
|
||
read_response(
|
||
client
|
||
.get(format!(
|
||
"{base}/resources/{resource_id}/versions/{version}/export"
|
||
))
|
||
.send()
|
||
.await
|
||
.expect("published export request must complete"),
|
||
)
|
||
.await
|
||
}
|
||
|
||
async fn post_import(
|
||
client: &reqwest::Client,
|
||
base: &str,
|
||
envelope: &Value,
|
||
) -> (StatusCode, String, Value) {
|
||
read_response(
|
||
client
|
||
.post(format!("{base}/resources/import"))
|
||
.json(envelope)
|
||
.send()
|
||
.await
|
||
.expect("import request must complete"),
|
||
)
|
||
.await
|
||
}
|
||
|
||
async fn publish(client: &reqwest::Client, base: &str, resource_id: &str) -> Value {
|
||
let card = get_card(client, base, resource_id).await;
|
||
let (status, text, body) = read_response(
|
||
client
|
||
.post(format!("{base}/resources/{resource_id}/publish"))
|
||
.json(&json!({ "expected_updated_at": draft_updated_at(&card) }))
|
||
.send()
|
||
.await
|
||
.expect("publish fixture request must complete"),
|
||
)
|
||
.await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"accepted Story 3.7 publish contract must stay GREEN as the fixture: {text}"
|
||
);
|
||
body
|
||
}
|
||
|
||
fn envelope(resource: Value, source_version: u32, bytes: &[u8]) -> Value {
|
||
json!({
|
||
"format": ENVELOPE_FORMAT,
|
||
"version": 1,
|
||
"resource": resource,
|
||
"source": { "kind": "published", "version": source_version },
|
||
"content": {
|
||
"size_bytes": bytes.len(),
|
||
"digest": sha256_hex(bytes),
|
||
"base64": BASE64.encode(bytes),
|
||
},
|
||
})
|
||
}
|
||
|
||
fn resource_block(uri: &str, name: &str, sensitivity: &str) -> Value {
|
||
json!({
|
||
"uri": uri,
|
||
"name": name,
|
||
"description": "story39 extra fixture",
|
||
"kind": "text",
|
||
"mime_type": "text/plain",
|
||
"sensitivity": sensitivity,
|
||
})
|
||
}
|
||
|
||
// AT-3.9-01: экспорт точной Published Version не «плывёт» вслед за Draft.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story39_at01_published_export_stays_pinned_to_the_exact_version() {
|
||
let (registry, server, client) = spawn_authorized("story39_pinned_versions").await;
|
||
let base = workspace_base(&server, "ws_default");
|
||
|
||
let first = b"story39 pinned v1 body\n";
|
||
let metadata = draft_metadata(
|
||
"crank://e2e/story39-pinned",
|
||
"story39_pinned",
|
||
"text",
|
||
"text/plain",
|
||
"internal",
|
||
);
|
||
let created = create_draft(&client, &base, &metadata, first, "draft.txt", "text/plain").await;
|
||
let id = created_resource_id(&created);
|
||
let published_v1 = publish(&client, &base, &id).await;
|
||
|
||
// Draft изменён и опубликован заново: текущий Draft — v2.
|
||
let second = b"story39 pinned v2 body\n";
|
||
let card = get_card(&client, &base, &id).await;
|
||
let update = update_metadata(
|
||
"story39 pinned v2",
|
||
"text/plain",
|
||
"internal",
|
||
&draft_updated_at(&card),
|
||
);
|
||
let (status, text, _) = put_draft_raw(&client, &base, &id, &update, second, "text/plain").await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"the accepted Draft update contract must stay GREEN: {text}"
|
||
);
|
||
let published_v2 = publish(&client, &base, &id).await;
|
||
|
||
let (status, text, exported_v1) = export_version(&client, &base, &id, 1).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"versions/1 export must succeed: {text}"
|
||
);
|
||
let snapshot_v1 = &published_v1["published_version"];
|
||
assert_eq!(
|
||
exported_v1["resource"]["description"],
|
||
snapshot_v1["description"]
|
||
);
|
||
assert_eq!(exported_v1["content"]["digest"], json!(sha256_hex(first)));
|
||
assert_eq!(
|
||
BASE64
|
||
.decode(
|
||
exported_v1["content"]["base64"]
|
||
.as_str()
|
||
.unwrap_or_default()
|
||
)
|
||
.expect("exported base64 must decode"),
|
||
first.to_vec(),
|
||
"versions/1 must stay the exact first publication, not the current Draft"
|
||
);
|
||
assert_eq!(
|
||
exported_v1["source"],
|
||
json!({ "kind": "published", "version": 1 })
|
||
);
|
||
|
||
let (status, text, exported_v2) = export_version(&client, &base, &id, 2).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::OK,
|
||
"versions/2 export must succeed: {text}"
|
||
);
|
||
assert_eq!(
|
||
exported_v2["resource"]["description"],
|
||
published_v2["published_version"]["description"]
|
||
);
|
||
assert_eq!(exported_v2["content"]["digest"], json!(sha256_hex(second)));
|
||
assert_eq!(
|
||
exported_v2["source"],
|
||
json!({ "kind": "published", "version": 2 })
|
||
);
|
||
|
||
// Текущий Draft — v2; его экспорт тоже отдаёт v2 bytes.
|
||
let (status, text, exported_draft) = export_draft(&client, &base, &id).await;
|
||
assert_eq!(status, StatusCode::OK, "draft export must succeed: {text}");
|
||
assert_eq!(exported_draft["source"]["kind"], json!("draft"));
|
||
assert_eq!(exported_draft["source"]["version"], json!(2));
|
||
assert_eq!(
|
||
exported_draft["content"]["digest"],
|
||
json!(sha256_hex(second))
|
||
);
|
||
|
||
// Ни экспорт, ни публикации не создали новых строк.
|
||
assert_eq!(table_row_count(registry.pool(), "resources").await, 1);
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "resource_versions").await,
|
||
2
|
||
);
|
||
}
|
||
|
||
// AT-3.9-01/02: иной разрешённый sensitivity сохраняется, заголовки экспорта безопасны.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story39_at01_sensitivity_and_export_headers_are_preserved() {
|
||
let (registry, server, client) = spawn_authorized("story39_sensitivity").await;
|
||
let base = workspace_base(&server, "ws_default");
|
||
|
||
let bytes = b"story39 secret sensitivity body\n";
|
||
let metadata = draft_metadata(
|
||
"crank://e2e/story39-sensitivity",
|
||
"story39_sensitivity",
|
||
"text",
|
||
"text/plain",
|
||
"secret",
|
||
);
|
||
let created = create_draft(&client, &base, &metadata, bytes, "draft.txt", "text/plain").await;
|
||
let id = created_resource_id(&created);
|
||
|
||
let response = client
|
||
.get(format!("{base}/resources/{id}/export"))
|
||
.send()
|
||
.await
|
||
.expect("export request must complete");
|
||
let status = response.status();
|
||
let headers = response.headers().clone();
|
||
let content_type = headers
|
||
.get("content-type")
|
||
.and_then(|value| value.to_str().ok())
|
||
.unwrap_or_default()
|
||
.to_owned();
|
||
let disposition = headers
|
||
.get("content-disposition")
|
||
.and_then(|value| value.to_str().ok())
|
||
.unwrap_or_default()
|
||
.to_owned();
|
||
let nosniff = headers
|
||
.get("x-content-type-options")
|
||
.and_then(|value| value.to_str().ok())
|
||
.unwrap_or_default()
|
||
.to_owned();
|
||
let text = response.text().await.expect("export body must read");
|
||
assert_eq!(status, StatusCode::OK, "draft export must succeed: {text}");
|
||
assert_eq!(
|
||
content_type, "application/json",
|
||
"the export must stay inert JSON, never the declared Resource MIME"
|
||
);
|
||
assert_eq!(nosniff, "nosniff");
|
||
assert_eq!(
|
||
disposition, "attachment; filename=\"story39_sensitivity.crank-resource.json\"",
|
||
"the export filename must be derived and sanitized"
|
||
);
|
||
|
||
let exported: Value = serde_json::from_str(&text).expect("export must be JSON");
|
||
assert_eq!(exported["resource"]["sensitivity"], json!("secret"));
|
||
|
||
// Легальный перенос в другой workspace сохраняет sensitivity и создаёт Draft.
|
||
let target = create_owned_workspace(®istry).await;
|
||
let target_base = workspace_base(&server, target.as_str());
|
||
let target_client = login_client(&server, TEST_AUTH_EMAIL, TEST_AUTH_PASSWORD).await;
|
||
let (status, text, imported) = post_import(&target_client, &target_base, &exported).await;
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::CREATED,
|
||
"a legitimate transfer must create the target Draft: {text}"
|
||
);
|
||
assert_eq!(imported["version"]["sensitivity"], json!("secret"));
|
||
assert_eq!(imported["resource"]["status"], json!("draft"));
|
||
assert_eq!(
|
||
imported["resource"]["latest_published_version"],
|
||
Value::Null
|
||
);
|
||
}
|
||
|
||
// AT-3.9-03: отказы атрибутируемы и не несут содержимого/путей (безопасные errors/logs).
|
||
//
|
||
// Захват sink-ов логов в этом тестовом бинаре невозможен: единственный глобальный
|
||
// tracing-подписчик назначается принятым `integration::openapi_source::telemetry`, а второй
|
||
// `set_global_default` конфликтует. Поэтому проверяется наблюдаемая часть контракта тем же
|
||
// способом, что принятый `story36_at06`: отказ несёт `x-trace-id` и не содержит bytes/путей,
|
||
// а сам путь переноса не логирует содержимое (в portability/service нет tracing-вызовов).
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
#[serial]
|
||
async fn story39_at03_import_refusals_are_attributable_and_carry_no_content() {
|
||
const CANARY: &str = "C39-CONTENT-CANARY";
|
||
let (registry, server, client) = spawn_authorized("story39_canary").await;
|
||
let base = workspace_base(&server, "ws_default");
|
||
let before = table_row_count(registry.pool(), "resources").await;
|
||
|
||
// Digest mismatch: canary лежит в переданных bytes, ответ не должен их повторять.
|
||
let bytes = format!("{CANARY}\n").into_bytes();
|
||
let mut tampered = envelope(
|
||
resource_block("crank://e2e/story39-canary", "story39_canary", "internal"),
|
||
1,
|
||
&bytes,
|
||
);
|
||
tampered["content"]["digest"] = json!(sha256_hex(b"different body"));
|
||
let response = client
|
||
.post(format!("{base}/resources/import"))
|
||
.json(&tampered)
|
||
.send()
|
||
.await
|
||
.expect("import request must complete");
|
||
let status = response.status();
|
||
let traceable = response.headers().contains_key("x-trace-id");
|
||
let text = response.text().await.expect("refusal body must read");
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::UNPROCESSABLE_ENTITY,
|
||
"digest mismatch must stay 422: {text}"
|
||
);
|
||
assert!(
|
||
traceable,
|
||
"a refusal must carry `x-trace-id` so it is attributable"
|
||
);
|
||
for forbidden in [
|
||
CANARY,
|
||
"/home/",
|
||
".tmp/",
|
||
"artifact_blobs",
|
||
"postgres://",
|
||
"test-master-key",
|
||
] {
|
||
assert!(
|
||
!text.contains(forbidden),
|
||
"an import refusal must not expose `{forbidden}`: {text}"
|
||
);
|
||
}
|
||
let body: Value = serde_json::from_str(&text).expect("refusal must be JSON");
|
||
assert_eq!(body["error"]["code"], json!("resource_artifact_integrity"));
|
||
assert_eq!(body["error"]["context"]["field"], json!("content"));
|
||
|
||
// Тело больше лимита: безопасный JSON-конверт, а не пустой framework rejection.
|
||
let oversized = vec![b'a'; MAX_IMPORT_BODY_BYTES + 1];
|
||
let response = client
|
||
.post(format!("{base}/resources/import"))
|
||
.header(reqwest::header::CONTENT_TYPE, "application/json")
|
||
.body(oversized)
|
||
.send()
|
||
.await
|
||
.expect("oversized import request must complete");
|
||
let status = response.status();
|
||
let traceable = response.headers().contains_key("x-trace-id");
|
||
let text = response
|
||
.text()
|
||
.await
|
||
.expect("oversized refusal body must read");
|
||
assert_eq!(
|
||
status,
|
||
StatusCode::PAYLOAD_TOO_LARGE,
|
||
"a body above the envelope bound must be 413, not a generic rejection: {}",
|
||
error_signature(status, &Value::Null)
|
||
);
|
||
assert!(traceable, "the 413 refusal must stay attributable");
|
||
let body: Value = serde_json::from_str(&text).expect("413 must return the safe JSON envelope");
|
||
assert_eq!(body["error"]["code"], json!("resource_content_too_large"));
|
||
assert_eq!(body["error"]["context"]["field"], json!("content"));
|
||
|
||
assert_eq!(
|
||
table_row_count(registry.pool(), "resources").await,
|
||
before,
|
||
"rejected imports must not create Resources"
|
||
);
|
||
}
|