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

352 lines
14 KiB
Rust
Raw Permalink 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-02 (AC2) — publication validator разрешает только read-safe GET/HEAD
//! без destructive semantics и без approval-required side effects.
//!
//! RED-состояние: `metadata.source` пока игнорируется, multipart требует `content`,
//! поэтому create template Draft падает на реальном отсутствии поведения
//! (`400 validation_error` malformed multipart), а не на setup.
use super::super::helpers::sha256_hex;
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
#[allow(clippy::type_complexity)]
async fn story310_at02_read_safety_matrix_blocks_every_non_read_variant() {
let (_registry, server, client, upstream) = spawn_stand("story310_at02_safety").await;
// Два разных реальных канала заголовков: target.static_headers и
// execution_config.headers. Оба обязаны быть в pinned fixture и отсутствовать
// в ответах Resource.
let static_canary = "super-secret-story310-static-header";
let execution_canary = "super-secret-story310-execution-header";
let secret_headers = json!({ "authorization": execution_canary });
let approval = approval_required();
// (метка, method, safety, approval, публикация разрешена)
let matrix: [(&str, &str, Option<Value>, Option<Value>, bool); 11] = [
("get_read", "GET", Some(read_safety()), None, true),
("head_read", "HEAD", Some(read_safety()), None, true),
("post_read", "POST", Some(read_safety()), None, false),
("put_read", "PUT", Some(read_safety()), None, false),
("patch_read", "PATCH", Some(read_safety()), None, false),
("delete_read", "DELETE", Some(read_safety()), None, false),
("options_read", "OPTIONS", Some(read_safety()), None, false),
(
"get_write",
"GET",
Some(json!({ "class": "write" })),
None,
false,
),
(
"get_destructive",
"GET",
Some(json!({ "class": "destructive" })),
None,
false,
),
(
"get_external_message",
"GET",
Some(json!({ "class": "external_message" })),
None,
false,
),
(
"get_financial",
"GET",
Some(json!({ "class": "financial_or_irreversible" })),
None,
false,
),
];
let mut accepted_publications = 0;
for (label, method, safety, approval_policy, publishable) in matrix {
let name = format!("story310_at02_{label}");
let mut payload = order_operation_payload(
&name,
&upstream,
method,
safety.clone().unwrap_or(Value::Null),
approval_policy.clone().unwrap_or(Value::Null),
secret_headers.clone(),
);
payload["target"]["static_headers"] = json!({ "x-static-canary": static_canary });
let operation_id = create_operation(&client, &server, &payload).await;
publish_operation(&client, &server, &operation_id).await;
// Positive control: pinned fixture действительно содержит оба маркера.
let (status, fixture, _) = read_response(
client
.get(format!(
"{}/operations/{operation_id}/versions/1",
server.as_ref()
))
.send()
.await
.expect("version fixture request must complete"),
)
.await;
assert_eq!(status, StatusCode::OK, "pinned fixture must be readable");
assert!(
fixture.contains(static_canary) && fixture.contains(execution_canary),
"the pinned fixture must carry both header canaries: {fixture}"
);
let metadata = template_metadata(
&format!("crank://story310/safety-{label}"),
&name,
valid_source(&operation_id),
);
let (status, text, created) = post_template_raw(&client, &server, &metadata).await;
assert_eq!(
status,
StatusCode::CREATED,
"a structurally valid source with an exact Published version must create a Draft ({label}); observed {} body={text}",
error_signature(status, &created)
);
assert!(
!text.contains(static_canary) && !text.contains(execution_canary),
"the Draft card must not expose operation headers ({label}): {text}"
);
let resource_id = created["resource"]["resource_id"]
.as_str()
.expect("template Draft id")
.to_owned();
let (status, text, preview) = read_preview(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"preview must answer 200 ({label}): {text}"
);
assert!(
!text.contains(static_canary) && !text.contains(execution_canary),
"preview must not expose operation headers ({label}): {text}"
);
let (status, text, published) = publish_with_card(&client, &server, &resource_id).await;
if publishable {
assert_eq!(
status,
StatusCode::OK,
"`{method}` with confirmed read safety must publish ({label}); observed {} body={text}",
error_signature(status, &published)
);
assert!(
!text.contains(static_canary) && !text.contains(execution_canary),
"the published snapshot must not expose headers ({label}): {text}"
);
accepted_publications += 1;
} else {
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"`{method}` with {safety:?} must block publication ({label}); observed {} body={text}",
error_signature(status, &published)
);
assert_eq!(
published["error"]["code"],
json!("resource_source_blocked"),
"blocked publication must use the stable code ({label}): {published}"
);
assert_has_code(
&blocked_codes(&published),
"resource_source_not_read_safe",
&format!("publication blocker ({label})"),
);
assert!(
!text.contains(static_canary) && !text.contains(execution_canary),
"the publication blocker must not expose headers ({label}): {text}"
);
let card = get_card(&client, &server, &resource_id).await;
assert_eq!(card["resource"]["latest_published_version"], Value::Null);
assert_has_code(
&preview_codes(&preview),
"resource_source_not_read_safe",
&format!("preview finding ({label})"),
);
}
}
assert_eq!(
accepted_publications, 2,
"GET+read and HEAD+read must be the only publishable rows (guards 'everything blocks')"
);
// Approval-required при GET+read блокирует публикацию отдельным гейтом.
let approval_payload = read_operation_payload(
"story310_at02_get_approval",
&upstream,
read_safety(),
approval,
Value::Null,
);
let approval_id = create_operation(&client, &server, &approval_payload).await;
publish_operation(&client, &server, &approval_id).await;
let metadata = template_metadata(
"crank://story310/safety-approval",
"story310_safety_approval",
valid_source(&approval_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::UNPROCESSABLE_ENTITY,
"approval-required side effects must block publication; observed {} body={text}",
error_signature(status, &published)
);
assert_has_code(
&blocked_codes(&published),
"resource_source_not_read_safe",
"approval-required blocker",
);
// Неподтверждённая read-safety (`safety` отсутствует) — тоже блокер, не «default read».
let unconfirmed_payload = read_operation_payload(
"story310_at02_get_unconfirmed",
&upstream,
Value::Null,
Value::Null,
Value::Null,
);
let unconfirmed_id = create_operation(&client, &server, &unconfirmed_payload).await;
publish_operation(&client, &server, &unconfirmed_id).await;
let metadata = template_metadata(
"crank://story310/safety-unconfirmed",
"story310_safety_unconfirmed",
valid_source(&unconfirmed_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::UNPROCESSABLE_ENTITY,
"an absent safety class is unconfirmed and must block; observed {} body={text}",
error_signature(status, &published)
);
assert_has_code(
&blocked_codes(&published),
"resource_source_not_read_safe",
"unconfirmed safety blocker",
);
}
/// Story 3.10 / TL amendment: публикация перепроверяет **сохранённое** определение,
/// а не последний preview. Единственный валидный tamper-канал — прямая запись в
/// version-keyed строку (immutable Operation Version менять нельзя).
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
async fn story310_at02_publish_revalidates_stored_draft_source() {
let (registry, server, client, upstream) = spawn_stand("story310_at02_stored").await;
let read_id =
published_read_operation(&client, &server, &upstream, "story310_at02_stored_read").await;
let unsafe_payload = order_operation_payload(
"story310_at02_stored_unsafe",
&upstream,
"POST",
json!({ "class": "write" }),
Value::Null,
Value::Null,
);
let unsafe_id = create_operation(&client, &server, &unsafe_payload).await;
publish_operation(&client, &server, &unsafe_id).await;
let metadata = template_metadata(
"crank://story310/stored",
"story310_stored",
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();
// До tampering сохранённый Draft чист.
let (status, text, preview) = read_preview(&client, &server, &resource_id).await;
assert_eq!(status, StatusCode::OK, "clean preview must succeed: {text}");
assert!(preview_codes(&preview).is_empty());
// Переписываем сохранённую ссылку на Published, но небезопасную операцию.
let typed_id = crank_core::ids::ResourceId::new(resource_id.clone());
let stored = registry
.get_resource_template_source(DEFAULT_WORKSPACE_ID, &typed_id, 1)
.await
.expect("stored definition must be readable");
let mut value: Value =
serde_json::from_str(&stored.definition_json).expect("stored definition is json");
value["operation_id"] = json!(unsafe_id);
let typed: crank_core::resource::template::TemplateSource =
serde_json::from_value(value).expect("stored definition keeps the template shape");
let tampered = serde_json::to_string(&typed).expect("definition must serialize");
let digest = sha256_hex(tampered.as_bytes());
sqlx::query(
"alter table resource_template_sources
disable trigger crank_guard_resource_template_source_immutable",
)
.execute(registry.pool())
.await
.expect("the immutable guard is reversible for the tamper fixture");
sqlx::query(
"update resource_template_sources
set definition_json = $1, definition_digest = $2
where workspace_id = $3 and resource_id = $4 and version = 1",
)
.bind(&tampered)
.bind(&digest)
.bind(DEFAULT_WORKSPACE_ID)
.bind(&resource_id)
.execute(registry.pool())
.await
.expect("the tamper fixture must rewrite the stored reference");
sqlx::query(
"alter table resource_template_sources
enable trigger crank_guard_resource_template_source_immutable",
)
.execute(registry.pool())
.await
.expect("the immutable guard must be restored");
// Preview и publish читают сохранённое определение и видят небезопасную ссылку.
let (status, text, preview) = read_preview(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::OK,
"tampered preview must answer 200: {text}"
);
assert_has_code(
&preview_codes(&preview),
"resource_source_not_read_safe",
"tampered stored definition",
);
let (status, text, published) = publish_with_card(&client, &server, &resource_id).await;
assert_eq!(
status,
StatusCode::UNPROCESSABLE_ENTITY,
"a tampered stored source must not publish; observed {} body={text}",
error_signature(status, &published)
);
assert_eq!(published["error"]["code"], json!("resource_source_blocked"));
assert_has_code(
&blocked_codes(&published),
"resource_source_not_read_safe",
"stored source revalidation",
);
let card = get_card(&client, &server, &resource_id).await;
assert_eq!(
card["resource"]["latest_published_version"],
Value::Null,
"a blocked publication must not create a version"
);
}