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

445 lines
15 KiB
Rust

//! AT-3.10-04 (AC4) — cache TTL/vary/size и safe failure outcome: typed,
//! bounded, fixed Agent/workspace/auth scope; widening блокируется.
//!
//! Границы зафиксированы в spec §2 (engineering caps): TTL 24 h, размер —
//! существующий `RESOURCE_STORAGE_CEILING`. UNIT-проверка exported constants —
//! build-only (честный NOT_RUN на этом этапе).
use super::*;
use crate::integration::resources::helpers::table_row_count;
use serde_json::Value as JsonValue;
const MAX_TTL_MS: u64 = 86_400_000;
const MAX_BYTES: u64 = 262_144;
fn big_number() -> JsonValue {
// 2^64 — не представимо в u64: структурный отказ, а не semantic bound.
serde_json::from_str("18446744073709551616").expect("big number literal")
}
async fn expect_source_invalid_containing(
client: &reqwest::Client,
server: &TestServer,
metadata: &Value,
expected_field_suffix: &str,
label: &str,
) {
let (status, text, body) = post_template_raw(client, server, metadata).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"structurally invalid policy must be a 400 ({label}); observed {} body={text}",
error_signature(status, &body)
);
assert_eq!(
body["error"]["code"],
json!("resource_source_invalid"),
"structural policy rejection must use the stable code ({label}): {body}"
);
let field = body["error"]["context"]["field"]
.as_str()
.unwrap_or("<absent>");
assert!(
field.ends_with(expected_field_suffix),
"the rejection must name `{expected_field_suffix}` ({label}), observed field={field}: {body}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at04_cache_and_failure_policy_bounds_block_publication() {
let (_registry, server, client, upstream) = spawn_stand("story310_at04_bounds").await;
let operation_id =
published_read_operation(&client, &server, &upstream, "story310_at04_read").await;
// Positive: ровно на границах политика принимается и публикуется.
let boundary_source = template_source(
&operation_id,
1,
"crank://orders/{order_id}",
json!([order_parameter(
"order_id",
"input.order_id",
json!({ "type": "string", "required": true, "format": "uuid" })
)]),
cache_policy(json!(MAX_TTL_MS), json!(["order_id"]), json!(MAX_BYTES)),
error_outcome(),
);
let metadata = template_metadata(
"crank://story310/policy-boundary",
"story310_policy_boundary",
boundary_source,
);
let created = create_template_draft(&client, &server, &metadata).await;
assert_eq!(
created["source"]["cache"]["ttl_ms"],
json!(MAX_TTL_MS),
"the accepted boundary TTL must be stored verbatim"
);
assert_eq!(created["source"]["cache"]["max_bytes"], json!(MAX_BYTES));
assert_eq!(
created["source"]["cache"]["scope"],
json!("workspace_agent_auth"),
"the normalized cache scope is fixed by the server, not by the payload"
);
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 boundary policy must publish; observed {} body={text}",
error_signature(status, &published)
);
// Semantic bounds: 0 и MAX+1 блокируют публикацию.
for (label, ttl, max_bytes, expected_code) in [
(
"ttl-zero",
json!(0),
json!(65_536),
"resource_source_cache_ttl_invalid",
),
(
"ttl-too-large",
json!(MAX_TTL_MS + 1),
json!(65_536),
"resource_source_cache_ttl_invalid",
),
(
"bytes-zero",
json!(60_000),
json!(0),
"resource_source_cache_size_invalid",
),
(
"bytes-too-large",
json!(60_000),
json!(MAX_BYTES + 1),
"resource_source_cache_size_invalid",
),
] {
let source = template_source(
&operation_id,
1,
"crank://orders/{order_id}",
json!([order_parameter(
"order_id",
"input.order_id",
json!({ "type": "string", "required": true, "format": "uuid" })
)]),
cache_policy(ttl, json!(["order_id"]), max_bytes),
error_outcome(),
);
let metadata = template_metadata(
&format!("crank://story310/policy-{label}"),
&format!("story310_policy_{label}"),
source,
);
expect_blocked(&client, &server, &metadata, expected_code, label).await;
}
// Structural policy errors: отсутствие/дробное/переполнение/строка.
let structural_cases: Vec<(&str, Value, &str)> = vec![
(
"ttl-absent",
{
let mut source = valid_source(&operation_id);
source["cache"]
.as_object_mut()
.expect("cache object")
.remove("ttl_ms");
source
},
"ttl_ms",
),
(
"ttl-fraction",
{
let mut source = valid_source(&operation_id);
source["cache"]["ttl_ms"] = json!(1.5);
source
},
"ttl_ms",
),
(
"ttl-negative",
{
let mut source = valid_source(&operation_id);
source["cache"]["ttl_ms"] = json!(-1);
source
},
"ttl_ms",
),
(
"ttl-overflow",
{
let mut source = valid_source(&operation_id);
source["cache"]["ttl_ms"] = big_number();
source
},
"ttl_ms",
),
(
"ttl-string",
{
let mut source = valid_source(&operation_id);
source["cache"]["ttl_ms"] = json!("60000");
source
},
"ttl_ms",
),
(
"bytes-absent",
{
let mut source = valid_source(&operation_id);
source["cache"]
.as_object_mut()
.expect("cache object")
.remove("max_bytes");
source
},
"max_bytes",
),
(
"bytes-fraction",
{
let mut source = valid_source(&operation_id);
source["cache"]["max_bytes"] = json!(10.5);
source
},
"max_bytes",
),
(
"bytes-overflow",
{
let mut source = valid_source(&operation_id);
source["cache"]["max_bytes"] = big_number();
source
},
"max_bytes",
),
(
"failure-empty",
{
let mut source = valid_source(&operation_id);
source["failure"] = json!({ "outcome": "empty" });
source
},
"failure.outcome",
),
(
"failure-fallback-body",
{
let mut source = valid_source(&operation_id);
source["failure"] = json!({ "outcome": "error", "body": "fallback text" });
source
},
"failure",
),
(
"failure-missing-outcome",
{
let mut source = valid_source(&operation_id);
source["failure"] = json!({});
source
},
"failure",
),
(
"failure-absent",
{
let mut source = valid_source(&operation_id);
source
.as_object_mut()
.expect("source object")
.remove("failure");
source
},
"failure",
),
];
for (label, source, field_suffix) in structural_cases {
let metadata = template_metadata(
&format!("crank://story310/policy-{label}"),
&format!("story310_policy_{label}"),
source,
);
expect_source_invalid_containing(&client, &server, &metadata, field_suffix, label).await;
}
// Widening scope запрещён: клиентский payload не расширяет workspace+Agent+auth.
let widening: Vec<(&str, Value, &str)> = vec![
("scope", json!("workspace"), "scope"),
("shared", json!(true), "shared"),
("cross_workspace", json!(true), "cross_workspace"),
("agent_scope", json!("any"), "agent_scope"),
("auth_independent", json!(true), "auth_independent"),
];
for (key, value, field_suffix) in widening {
let mut source = valid_source(&operation_id);
source["cache"][key] = value;
let metadata = template_metadata(
&format!("crank://story310/policy-widening-{key}"),
&format!("story310_policy_widening_{key}"),
source,
);
expect_source_invalid_containing(&client, &server, &metadata, field_suffix, key).await;
}
for (key, value) in [
("agent_scope", json!("any")),
("auth_independent", json!(true)),
] {
let mut source = valid_source(&operation_id);
source[key] = value;
let metadata = template_metadata(
&format!("crank://story310/policy-source-{key}"),
&format!("story310_policy_source_{key}"),
source,
);
expect_source_invalid_containing(&client, &server, &metadata, key, key).await;
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at04_vary_must_cover_every_template_parameter() {
let (_registry, server, client, upstream) = spawn_stand("story310_at04_vary").await;
let operation_id =
published_read_operation(&client, &server, &upstream, "story310_at04_vary_read").await;
let with_vary = |vary: Value| {
let mut source = valid_source(&operation_id);
source["cache"]["vary"] = vary;
source
};
// Full positive: каждый параметр объявлен в vary.
let metadata = template_metadata(
"crank://story310/vary-full",
"story310_vary_full",
with_vary(json!(["order_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();
let (status, text, published) = publish_with_card(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"a complete vary must publish; observed {} body={text}",
error_signature(status, &published)
);
for (label, vary, expected_code) in [
(
"unknown",
json!(["order_id", "tenant_id"]),
"resource_source_vary_unknown",
),
(
"duplicate",
json!(["order_id", "order_id"]),
"resource_source_vary_duplicate",
),
("incomplete", json!([]), "resource_source_vary_incomplete"),
] {
let metadata = template_metadata(
&format!("crank://story310/vary-{label}"),
&format!("story310_vary_{label}"),
with_vary(vary),
);
expect_blocked(&client, &server, &metadata, expected_code, label).await;
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at04_oversized_canonical_definition_is_client_error_without_resource() {
let (_registry, server, client, upstream) = spawn_stand("story310_at04_oversized").await;
let operation_id =
published_read_operation(&client, &server, &upstream, "story310_at04_oversized_read").await;
let mut source = valid_source(&operation_id);
source["parameters"][0]["schema"]["description"] = json!("x".repeat(70_000));
let metadata = template_metadata("crank://story310/oversized", "story310_oversized", source);
let (_, _, before) = list_resources(&client, &server).await;
let (status, text, body) = post_template_raw(&client, &server, &metadata).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"oversized source must be rejected before persistence: {text}"
);
assert_eq!(body["error"]["code"], json!("resource_source_invalid"));
let (_, _, after) = list_resources(&client, &server).await;
assert_eq!(
after["items"].as_array().map(Vec::len),
before["items"].as_array().map(Vec::len)
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at04_oversized_canonical_put_preserves_draft_and_allows_retry() {
let (registry, server, client, upstream) = spawn_stand("story310_at04_oversized_put").await;
let operation_id = published_read_operation(
&client,
&server,
&upstream,
"story310_at04_oversized_put_read",
)
.await;
let metadata = template_metadata(
"crank://story310/oversized-put",
"story310_oversized_put",
valid_source(&operation_id),
);
let created = create_template_draft(&client, &server, &metadata).await;
let resource_id = created["resource"]["resource_id"]
.as_str()
.expect("resource id")
.to_owned();
let before = get_card(&client, &server, &resource_id).await;
let updated_at = draft_updated_at(&before);
let versions_before = table_row_count(registry.pool(), "resource_versions").await;
let mut oversized = metadata.clone();
oversized["source"]["parameters"][0]["schema"]["description"] = json!("x".repeat(70_000));
oversized["expected_updated_at"] = json!(updated_at);
let (status, text, body) = put_template_raw(&client, &server, &resource_id, &oversized).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"oversized source PUT must fail: {text}"
);
assert_eq!(body["error"]["code"], json!("resource_source_invalid"));
let after_reject = get_card(&client, &server, &resource_id).await;
assert_eq!(
draft_updated_at(&after_reject),
updated_at,
"failed PUT must preserve draft CAS"
);
assert_eq!(
after_reject["source"], before["source"],
"failed PUT must preserve source"
);
assert_eq!(
table_row_count(registry.pool(), "resource_versions").await,
versions_before,
"failed PUT must not append a resource version"
);
let mut small = metadata;
small["description"] = json!("small retry");
small["expected_updated_at"] = json!(updated_at);
let (status, text, _) = put_template_raw(&client, &server, &resource_id, &small).await;
assert_eq!(
status,
StatusCode::OK,
"small retry with original CAS must succeed: {text}"
);
}