Files
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

259 lines
9.8 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.
//! Story 3.16 AC-7 (§5): bounded скан содержимого dynamic-зависимости на чтении.
//!
//! Вынесено отдельным модулем, чтобы каждый файл оставался в пределах rust-code-health.
use super::*;
// ---------------------------------------------------------------------------
// AC-7 §5: read-time скан содержимого dynamic-зависимости
// ---------------------------------------------------------------------------
/// Upstream, отдающий фиксированный текст документа (credential и `include:`-директива).
async fn spawn_text_upstream(value: &'static str) -> String {
use axum::{Router, routing::get};
let app = Router::new().route(
"/orders/{order_id}",
get(move || async move { axum::Json(json!({ "text": value })) }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("upstream bind");
let address = listener.local_addr().expect("upstream address");
tokio::spawn(async move {
axum::serve(listener, app).await.expect("upstream serves");
});
format!("http://{address}")
}
/// Published read Operation с текстовым выводом: `$.response.body.text` → `$.output`.
async fn published_text_read_operation(
stand: &Stand,
base: &str,
upstream: &str,
name: &str,
) -> String {
use super::super::common::{assert_success_json, operation_etag};
let payload = json!({
"name": name,
"display_name": name,
"category": "sales",
"protocol": "rest",
"security_level": "standard",
"target": {
"kind": "rest",
"base_url": upstream,
"method": "GET",
"path_template": "/orders/{order_id}"
},
"input_schema": {
"type": "object",
"required": true,
"fields": { "order_id": { "type": "string", "required": true } }
},
"output_schema": { "type": "string", "required": true },
"input_mapping": { "rules": [ {
"source": "$.mcp.order_id",
"target": "$.request.path.order_id",
"required": true
} ] },
"output_mapping": { "rules": [ {
"source": "$.response.body.text",
"target": "$.output",
"required": true
} ] },
"execution_config": { "timeout_ms": 1_000, "safety": { "class": "read" } },
"tool_description": { "title": name, "description": "Story 3.16 text dynamic dependency" }
});
let created = assert_success_json(
stand
.client
.post(format!("{base}/operations"))
.json(&payload)
.send()
.await
.expect("operation create request"),
)
.await;
let operation_id = created["operation_id"]
.as_str()
.expect("operation create returns an id")
.to_owned();
let etag = operation_etag(&stand.client, base, &operation_id).await;
assert_success_json(
stand
.client
.post(format!("{base}/operations/{operation_id}/publish"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({ "version": 1 }))
.send()
.await
.expect("operation publish request"),
)
.await;
operation_id
}
/// Published template Resource с текстовым kind и параметром по умолчанию.
async fn published_text_template_resource(
stand: &Stand,
base: &str,
operation_id: &str,
) -> ResourceFixture {
let name = unique("story316_dynamic_text");
let metadata = json!({
"uri": format!("crank://resources/{name}"),
"name": name,
"description": "",
"kind": "text",
"mime_type": "text/plain",
"sensitivity": "internal",
"source": {
"operation_id": operation_id,
"operation_version": 1,
"uri_template": "crank://orders/{order_id}",
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "default_value": "order-42" }
}],
"cache": { "ttl_ms": 60_000, "vary": ["order_id"], "max_bytes": 65_536 },
"failure": { "outcome": "error" }
}
});
let form = Form::new().part(
"metadata",
Part::bytes(serde_json::to_vec(&metadata).expect("metadata json"))
.file_name("metadata.json".to_owned())
.mime_str("application/json")
.expect("metadata mime"),
);
let response = stand
.client
.post(format!("{base}/resources"))
.multipart(form)
.send()
.await
.expect("template resource create request");
let status = response.status();
let body: Value = response.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::CREATED, "text template draft: {body}");
let id = body["resource"]["resource_id"]
.as_str()
.expect("template resource id")
.to_owned();
let updated_at = body["resource"]["updated_at"]
.as_str()
.expect("template updated_at")
.to_owned();
let published = stand
.client
.post(format!("{base}/resources/{id}/publish"))
.json(&json!({ "expected_updated_at": updated_at }))
.send()
.await
.expect("template publish request");
let status = published.status();
let body: Value = published.json().await.unwrap_or(Value::Null);
assert_eq!(status, StatusCode::OK, "text template publish: {body}");
ResourceFixture {
id,
version: body["published_version"]["version"]
.as_u64()
.expect("published_version.version") as u32,
digest: body["published_version"]["digest"]
.as_str()
.expect("published_version.digest")
.to_owned(),
}
}
/// AT-3.16-07 (§5): raw credential в выводе dynamic-шаблона отклоняется на чтении тем же
/// bounded-сканером, с кодом `prompt_dependency_credential_finding` и `dependencies[i]`.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn at_3_16_07_http_dynamic_credential_in_template_output_is_refused() {
const TOKEN: &str = "Authorization: Bearer sk-live-0123456789abcdef";
let stand = stand("story316_dynamic_credential").await;
let base = stand.base.clone();
let upstream = spawn_text_upstream(TOKEN).await;
let operation_id =
published_text_read_operation(&stand, &base, &upstream, &unique("story316_cred_read"))
.await;
let template = published_text_template_resource(&stand, &base, &operation_id).await;
let (status, created) = create_prompt(
&stand,
&base,
&composed_prompt("story316-dyn-cred", "internal", dependency(&template)),
)
.await;
assert_eq!(status, StatusCode::CREATED, "draft: {created}");
let prompt_id = created["prompt_id"].as_str().expect("prompt id").to_owned();
let (status, body) = preview_prompt(&stand, &base, &prompt_id, json!({"channel": "ops"})).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"a read-time credential finding blocks the composed prompt: {body}"
);
assert_eq!(error_code(&body), "prompt_dependency_credential_finding");
assert_eq!(
error_context(&body)["source_path"],
json!("dependencies[0]"),
"the refusal names the dependency that carried the finding: {body}"
);
assert!(
body.get("messages").is_none(),
"no partial prompt is produced: {body}"
);
assert!(
!serde_json::to_string(&body)
.unwrap_or_default()
.contains("sk-live-0123456789abcdef"),
"the matched text never leaves the server: {body}"
);
}
/// AT-3.16-07 (§5): explicit `include:` в выводе dynamic-шаблона отклоняется тем же сканером,
/// с кодом `prompt_dependency_access_bypass_finding` и `dependencies[i]`.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn at_3_16_07_http_dynamic_include_directive_is_refused() {
const DOCUMENT: &str = "include: crank://resources/private-notes";
let stand = stand("story316_dynamic_include").await;
let base = stand.base.clone();
let upstream = spawn_text_upstream(DOCUMENT).await;
let operation_id =
published_text_read_operation(&stand, &base, &upstream, &unique("story316_inc_read")).await;
let template = published_text_template_resource(&stand, &base, &operation_id).await;
let (status, created) = create_prompt(
&stand,
&base,
&composed_prompt("story316-dyn-include", "internal", dependency(&template)),
)
.await;
assert_eq!(status, StatusCode::CREATED, "draft: {created}");
let prompt_id = created["prompt_id"].as_str().expect("prompt id").to_owned();
let (status, body) = preview_prompt(&stand, &base, &prompt_id, json!({"channel": "ops"})).await;
assert_eq!(
status,
StatusCode::BAD_REQUEST,
"a read-time access-bypass finding blocks the composed prompt: {body}"
);
assert_eq!(error_code(&body), "prompt_dependency_access_bypass_finding");
assert_eq!(
error_context(&body)["source_path"],
json!("dependencies[0]"),
"the refusal names the dependency that carried the finding: {body}"
);
assert!(
body.get("messages").is_none(),
"no partial prompt is produced: {body}"
);
assert!(
!serde_json::to_string(&body)
.unwrap_or_default()
.contains("crank://resources/private-notes"),
"the directive target never leaves the server: {body}"
);
}