Files
crank/apps/admin-api/tests/integration/resources/template_boundaries.rs
T
Hermes DevOps 75fe5a123c [skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
2026-10-25 10:00:22 +00:00

474 lines
17 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.
//! AT-3.10-06 (AC6) + F2/F3 — immutable publication с точным source snapshot,
//! запрет host/scheme injection на definition boundary и definition-only
//! boundaries для export/content/import/preview.
//!
//! Cache key и runtime-подстановка значений — 3.11; здесь проверяется только
//! definition boundary. RED-состояние: template Draft ещё не создаётся.
use super::super::helpers::sha256_hex;
use super::*;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
fn text_metadata(uri: &str, name: &str) -> Value {
draft_metadata(uri, name, "text", "text/plain", "internal")
}
async fn read_body(client: &reqwest::Client, url: String) -> (StatusCode, String, Vec<u8>) {
let response = client
.get(url)
.send()
.await
.expect("read request must complete");
let status = response.status();
let bytes = response
.bytes()
.await
.map(|value| value.to_vec())
.unwrap_or_default();
let text = String::from_utf8_lossy(&bytes).into_owned();
(status, text, bytes)
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at06_publication_pins_exact_source_and_host_scheme_injection() {
let (_registry, server, client, upstream) = spawn_stand("story310_at06_pin").await;
let canary = "super-secret-story310-static-header";
let secret_headers = json!({ "authorization": canary });
let first_payload = read_operation_payload(
"story310_at06_first",
&upstream,
read_safety(),
Value::Null,
secret_headers.clone(),
);
let first_id = create_operation(&client, &server, &first_payload).await;
publish_operation(&client, &server, &first_id).await;
let second_id =
published_read_operation(&client, &server, &upstream, "story310_at06_second").await;
let metadata = template_metadata(
"crank://story310/pin",
"story310_pin",
valid_source(&first_id),
);
let (status, text, created) = post_template_raw(&client, &server, &metadata).await;
assert_eq!(
status,
StatusCode::CREATED,
"template Draft create is the premise of pinning; observed {} body={text}",
error_signature(status, &created)
);
assert!(
!text.contains(canary),
"create must not expose static_headers: {text}"
);
let resource_id = created["resource"]["resource_id"]
.as_str()
.expect("template Draft id")
.to_owned();
let (status, text, published) = publish_with_card(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"the first publication must succeed; observed {} body={text}",
error_signature(status, &published)
);
assert!(
!text.contains(canary),
"publish must not expose static_headers: {text}"
);
let published_at = draft_updated_at(&published["resource"]).to_string();
assert_eq!(
published["published_version"]["source"]["operation_id"],
json!(first_id)
);
assert_eq!(
published["published_version"]["source"]["operation_version"],
json!(1)
);
// PUT Draft на другую опубликованную операцию: published snapshot не меняется.
let mut update_metadata_value = text_metadata("crank://story310/pin", "story310_pin");
update_metadata_value["description"] = json!("pinned then retargeted");
update_metadata_value["expected_updated_at"] = json!(published_at);
update_metadata_value["source"] = valid_source(&second_id);
let (status, text, updated) =
put_template_raw(&client, &server, &resource_id, &update_metadata_value).await;
assert_eq!(
status,
StatusCode::OK,
"the Draft source is editable before the next publication; observed {} body={text}",
error_signature(status, &updated)
);
assert_eq!(updated["source"]["operation_id"], json!(second_id));
let (status, text, _) = read_body(
&client,
format!("{}/resources/{resource_id}/versions/1", server.as_ref()),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"published v1 must stay readable: {text}"
);
let version: Value = serde_json::from_str(&text).expect("published version is json");
assert_eq!(
version["source"]["operation_id"],
json!(first_id),
"editing the Draft must not mutate the published source snapshot: {version}"
);
assert!(
!text.contains(canary),
"published version must not expose static_headers: {text}"
);
// Повтор с устаревшим precondition — существующий 428, не новая публикация.
let (status, text, body) =
publish_raw(&client, &server, &resource_id, Some(published_at.as_str())).await;
assert_eq!(
status,
StatusCode::PRECONDITION_REQUIRED,
"a stale precondition must keep the existing lifecycle code; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_stale"));
// Новая публикация пинит новый source, история версии 1 остаётся прежней.
let (status, text, second_publication) =
publish_with_card(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"the retargeted Draft must publish as the next version; observed {} body={text}",
error_signature(status, &second_publication)
);
assert_eq!(
second_publication["published_version"]["source"]["operation_id"],
json!(second_id)
);
let (_, text_v1, _) = read_body(
&client,
format!("{}/resources/{resource_id}/versions/1", server.as_ref()),
)
.await;
let v1: Value = serde_json::from_str(&text_v1).expect("published version is json");
assert_eq!(v1["source"]["operation_id"], json!(first_id));
// Host/scheme injection внутри вложенных объектов source — definition boundary.
let injection_cases: Vec<(&str, Value)> = vec![
("parameter-url", {
let mut source = valid_source(&first_id);
source["parameters"][0]["url"] = json!("https://evil.example/{order_id}");
source
}),
("parameter-schema-host", {
let mut source = valid_source(&first_id);
source["parameters"][0]["schema"]["host"] = json!("evil.example");
source
}),
("cache-headers", {
let mut source = valid_source(&first_id);
source["cache"]["headers"] = json!({ "host": "evil.example" });
source
}),
("failure-url", {
let mut source = valid_source(&first_id);
source["failure"]["url"] = json!("https://evil.example/fallback");
source
}),
];
for (label, source) in injection_cases {
let metadata = template_metadata(
&format!("crank://story310/injection-{label}"),
&format!("story310_injection_{label}"),
source,
);
let (status, text, body) = post_template_raw(&client, &server, &metadata).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"nested injection `{label}` must be rejected; observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(body["error"]["code"], json!("resource_source_invalid"));
assert!(!text.contains(canary));
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at06_definition_only_boundaries_for_export_content_and_import() {
let (_registry, server, client, upstream) = spawn_stand("story310_at06_boundaries").await;
let read_id =
published_read_operation(&client, &server, &upstream, "story310_at06_export_read").await;
// Вторая операция публикуется как POST+write: публикация шаблона с ней блокируется.
let write_payload = order_operation_payload(
"story310_at06_blocked",
&upstream,
"POST",
json!({ "class": "write" }),
Value::Null,
Value::Null,
);
let blocked_id = create_operation(&client, &server, &write_payload).await;
publish_operation(&client, &server, &blocked_id).await;
// 1. Валидный шаблон: Draft export/content и Published export/content — 409.
let metadata = template_metadata(
"crank://story310/boundaries",
"story310_boundaries",
valid_source(&read_id),
);
let created = create_template_draft(&client, &server, &metadata).await;
let resource_id = created["resource"]["resource_id"]
.as_str()
.expect("template Draft id")
.to_owned();
for (label, url) in [
(
"draft-export",
format!("{}/resources/{resource_id}/export", server.as_ref()),
),
(
"draft-content",
format!("{}/resources/{resource_id}/content", server.as_ref()),
),
] {
let (status, text, _) = read_body(&client, url).await;
assert_eq!(
status,
StatusCode::CONFLICT,
"a source definition is not portable ({label}); observed {status} body={text}"
);
assert!(
text.contains("resource_source_not_portable"),
"the refusal must use the stable code ({label}): {text}"
);
assert!(
!text.contains(&read_id) && !text.contains("crank://orders/{order_id}"),
"the refusal must not leak the definition ({label}): {text}"
);
}
let (status, text, published) = publish_with_card(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"the valid template must publish before version boundaries; observed {} body={text}",
error_signature(status, &published)
);
for (label, url) in [
(
"version-export",
format!(
"{}/resources/{resource_id}/versions/1/export",
server.as_ref()
),
),
(
"version-content",
format!(
"{}/resources/{resource_id}/versions/1/content",
server.as_ref()
),
),
] {
let (status, text, _) = read_body(&client, url).await;
assert_eq!(
status,
StatusCode::CONFLICT,
"the published source definition is not downloadable ({label}); observed {status} body={text}"
);
assert!(text.contains("resource_source_not_portable"));
assert!(
!text.contains(&read_id) && !text.contains("crank://orders/{order_id}"),
"the refusal must not leak the definition ({label}): {text}"
);
}
// 2. Блокированный шаблон: preview отдаёт findings и null text, без исполнения REST.
let blocked_metadata = template_metadata(
"crank://story310/boundaries-blocked",
"story310_boundaries_blocked",
valid_source(&blocked_id),
);
let blocked_created = create_template_draft(&client, &server, &blocked_metadata).await;
let blocked_resource = blocked_created["resource"]["resource_id"]
.as_str()
.expect("blocked template Draft id")
.to_owned();
let (status, text, preview) = read_preview(&client, &server, &blocked_resource).await;
assert_eq!(
status,
StatusCode::OK,
"preview of a blocked template must answer 200: {text}"
);
assert_has_code(
&preview_codes(&preview),
"resource_source_not_read_safe",
"blocked template preview",
);
assert_eq!(
preview["preview"]["text"],
Value::Null,
"a template preview never renders content: {preview}"
);
assert!(!text.contains("http://127.0.0.1"));
// 3. Import не принимает dynamic envelope (definition не переносится).
let bytes = b"story310 static portable body\n";
let envelope = json!({
"format": "crank-resource-portability",
"version": 1,
"resource": {
"uri": "crank://story310/imported",
"name": "story310_imported",
"description": "",
"kind": "text",
"mime_type": "text/plain",
"sensitivity": "internal"
},
"source": { "kind": "draft", "version": 1 },
"content": {
"size_bytes": bytes.len(),
"digest": sha256_hex(bytes),
"base64": BASE64.encode(bytes)
}
});
let mut dynamic_in_resource = envelope.clone();
dynamic_in_resource["resource"]["source"] = valid_source(&read_id);
let mut dynamic_source = envelope.clone();
dynamic_source["source"] = json!({
"kind": "published",
"version": 1,
"operation_id": read_id,
"uri_template": "crank://orders/{order_id}"
});
let (_, _, listed_before) = list_resources(&client, &server).await;
let before = listed_before["items"].as_array().map(Vec::len).unwrap_or(0);
for (label, payload) in [
("dynamic-in-resource", dynamic_in_resource),
("dynamic-source", dynamic_source),
] {
let (status, text, body) = read_response(
client
.post(format!("{}/resources/import", server.as_ref()))
.json(&payload)
.send()
.await
.expect("import request must complete"),
)
.await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"a dynamic envelope must not import ({label}); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
json!("resource_portability_envelope_invalid")
);
assert!(
!text.contains(&read_id) && !text.contains("crank://orders/{operation_id}"),
"the import refusal must not leak the definition ({label}): {text}"
);
}
let (_, _, listed_after) = list_resources(&client, &server).await;
assert_eq!(
listed_after["items"].as_array().map(Vec::len),
Some(before),
"rejected dynamic imports must not create Resources: {listed_after}"
);
// 4. Positive static controls: download/export/import/preview не изменились.
let static_metadata = text_metadata(
"crank://story310/boundaries-static",
"story310_boundaries_static",
);
let (status, _traceable, text, static_card) =
post_draft_raw(&client, &server, &static_metadata, bytes, "text/plain").await;
assert_eq!(
status,
StatusCode::CREATED,
"static create must stay intact; observed {} body={text}",
error_signature(status, &static_card)
);
let static_id = static_card["resource"]["resource_id"]
.as_str()
.expect("static Draft id")
.to_owned();
let (status, _, downloaded) = read_body(
&client,
format!("{}/resources/{static_id}/content", server.as_ref()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
downloaded, bytes,
"static download must return the exact bytes"
);
let (status, text, _exported) = read_body(
&client,
format!("{}/resources/{static_id}/export", server.as_ref()),
)
.await;
assert_eq!(
status,
StatusCode::OK,
"static export must stay intact: {text}"
);
let exported: Value = serde_json::from_str(&text).expect("static export is json");
assert_eq!(exported["format"], json!("crank-resource-portability"));
assert_eq!(exported["source"]["kind"], json!("draft"));
let (status, text, static_preview) = read_preview(&client, &server, &static_id).await;
assert_eq!(
status,
StatusCode::OK,
"static preview must stay intact: {text}"
);
assert_eq!(
static_preview["preview"]["text"],
json!("story310 static portable body\n")
);
let import_payload = json!({
"format": "crank-resource-portability",
"version": 1,
"resource": {
"uri": "crank://story310/imported-static",
"name": "story310_imported_static",
"description": "",
"kind": "text",
"mime_type": "text/plain",
"sensitivity": "internal"
},
"source": { "kind": "draft", "version": 1 },
"content": {
"size_bytes": bytes.len(),
"digest": sha256_hex(bytes),
"base64": BASE64.encode(bytes)
}
});
let (status, text, imported) = read_response(
client
.post(format!("{}/resources/import", server.as_ref()))
.json(&import_payload)
.send()
.await
.expect("static import must complete"),
)
.await;
assert_eq!(
status,
StatusCode::CREATED,
"static import must stay intact; observed {} body={text}",
error_signature(status, &imported)
);
}