Files
crank/apps/admin-api/tests/integration/resources/template_policy.rs
bsodfather 54ce770682
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
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
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.
2026-10-25 09:08: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}"
);
}