Files
bsodfather a438c1df42
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
feat(epic3): безопасное structured logging MCP (Story 3.18)
Story 3.18 (#25) surface: клиент получает только закрытые structured
`notifications/message` выбранного уровня, без запросов, секретов и
internal causes.

- `logging` capability advertising в обеих поддерживаемых revisions;
  `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request);
- закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним
  safe detail; закрытый набор safe events, task-local request scope;
  bounded in-memory opt-in, без миграций;
- `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт;
- ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3),
  protocol::logging unit (12);
- проекция capability inventory/frozen oracle переведена на `logging`.

Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy,
python oracle 56 OK, capability inventory valid). Полный `just verify` —
NOT_RUN на story по validation-policy, остаётся на собранной фиче.
2026-10-25 12:50:00 +00:00

281 lines
9.6 KiB
Rust

#![allow(dead_code, unused_imports)]
//! Story 3.1 ATDD (AT-13): per-era advertisement compared against an *independent*, pre-frozen,
//! inventory-derived oracle.
//!
//! Oracle: `tests/fixtures/mcp-revisions/<revision>-advertised-capabilities.frozen.json`, produced by
//! the server-only projection of the reviewed inventory (spec section 5, rules 1-4) - never from a
//! captured server response, never era-vs-era. Each era is compared **on its own**: the parsed
//! `result.capabilities` is re-serialized with the workspace's actual deterministic `serde_json`
//! serialization (default map order, no `preserve_order`) and compared byte-for-byte.
//!
//! The sidecar `<revision>-advertised-capabilities.provenance.json` is audit-only: it is never
//! byte-compared with the endpoint and carries the participating identity triples instead.
use super::common::*;
use std::path::PathBuf;
use std::time::Duration;
use axum::http::header;
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
const MODERN_REVISION: &str = "2026-07-28";
const LEGACY_REVISION: &str = "2025-11-25";
const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
fn fixture_path(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/mcp-revisions")
.join(name)
}
fn frozen_capabilities(revision: &str) -> Vec<u8> {
let path = fixture_path(&format!("{revision}-advertised-capabilities.frozen.json"));
std::fs::read(&path).unwrap_or_else(|error| {
panic!(
"the pre-frozen per-era oracle must be readable at {}: {error}",
path.display()
)
})
}
fn provenance_sidecar(revision: &str) -> Value {
let path = fixture_path(&format!(
"{revision}-advertised-capabilities.provenance.json"
));
let raw = std::fs::read_to_string(&path).unwrap_or_else(|error| {
panic!(
"the projection provenance sidecar must be readable at {}: {error}",
path.display()
)
});
serde_json::from_str(&raw).unwrap()
}
/// The same deterministic serialization the test compares against: compact, and (because this
/// workspace does not enable `serde_json`'s `preserve_order`) object keys follow the default map
/// order rather than insertion order.
fn canonical(component: &Value) -> Vec<u8> {
serde_json::to_vec(component).expect("a parsed capability object is always serializable")
}
fn modern_meta(revision: &str) -> Value {
json!({
META_PROTOCOL_VERSION: revision,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: { "name": "crank-atdd-inventory-client", "version": "0.1.0" }
})
}
struct Endpoint {
client: reqwest::Client,
mcp_url: String,
api_key: String,
}
async fn endpoint() -> Endpoint {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let operation = test_operation(&upstream_base_url, "crm_create_lead");
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "sales-inventory").await;
let api_key = create_platform_api_key(
&registry,
"sales-inventory",
"mcp-inventory",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
))
.await;
Endpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, "sales-inventory"),
api_key,
}
}
async fn json_body(response: reqwest::Response) -> Value {
let status = response.status();
let body = response.text().await.unwrap();
serde_json::from_str(&body).unwrap_or_else(|error| {
panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}")
})
}
/// AT-13 / AT-05: the legacy `initialize` advertisement equals the frozen legacy-era oracle.
#[tokio::test]
async fn inventory_projection_legacy_initialize_matches_the_frozen_oracle() {
let endpoint = endpoint().await;
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.json(&json!({
"jsonrpc": "2.0",
"id": 101,
"method": "initialize",
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
}))
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"legacy initialize must be served"
);
let body = json_body(response).await;
let capabilities = body["result"]["capabilities"]
.as_object()
.unwrap_or_else(|| {
panic!("legacy initialize must return a capabilities object, got {body}")
});
assert_eq!(
canonical(&Value::Object(capabilities.clone())),
frozen_capabilities(LEGACY_REVISION),
"the served legacy capabilities must be byte-equal to the independent frozen oracle, got {body}"
);
}
/// AT-13 / AT-04: the modern `server/discover` advertisement equals the frozen modern-era oracle.
#[tokio::test]
async fn inventory_projection_modern_discover_matches_the_frozen_oracle() {
let endpoint = endpoint().await;
let response = endpoint
.client
.post(&endpoint.mcp_url)
.header(header::ACCEPT, "application/json, text/event-stream")
.header(
header::AUTHORIZATION,
format!("Bearer {}", endpoint.api_key),
)
.header("MCP-Protocol-Version", MODERN_REVISION)
.header("Mcp-Method", "server/discover")
.json(&json!({
"jsonrpc": "2.0",
"id": 102,
"method": "server/discover",
"params": { "_meta": modern_meta(MODERN_REVISION) }
}))
.send()
.await
.unwrap();
assert_eq!(
response.status().as_u16(),
200,
"modern discover must be served"
);
let body = json_body(response).await;
let capabilities = body["result"]["capabilities"]
.as_object()
.unwrap_or_else(|| panic!("modern discover must return a capabilities object, got {body}"));
assert_eq!(
canonical(&Value::Object(capabilities.clone())),
frozen_capabilities(MODERN_REVISION),
"the served modern capabilities must be byte-equal to the independent frozen oracle, got {body}"
);
}
/// AT-13: both eras are compared against their own oracle, and the provenance sidecar is an audit
/// document (inventory digest + participating triples), never another copy of the endpoint answer.
#[tokio::test]
async fn inventory_projection_sidecar_is_provenance_only_and_names_the_projection_inputs() {
for revision in [MODERN_REVISION, LEGACY_REVISION] {
let frozen = frozen_capabilities(revision);
let sidecar = provenance_sidecar(revision);
assert!(
sidecar["rule"].is_string() && sidecar["inventory_sha256"].is_string(),
"{revision} sidecar must record the projection rule and the inventory digest"
);
let triples: Vec<(String, String, String)> = sidecar["projection_inputs"]
.as_array()
.unwrap_or_else(|| panic!("{revision} sidecar must list the projection inputs"))
.iter()
.map(|item| {
(
item["role"].as_str().unwrap().to_owned(),
item["kind"].as_str().unwrap().to_owned(),
item["surface"].as_str().unwrap().to_owned(),
)
})
.collect();
assert_eq!(
triples,
vec![
(
"server".to_owned(),
"capability".to_owned(),
"logging".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"completions".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"prompts".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"resources".to_owned()
),
(
"server".to_owned(),
"capability".to_owned(),
"tools".to_owned()
)
],
"the advertised server capabilities of the current scope are `logging`, `completions`, `prompts`, `resources` and `tools`"
);
// The sidecar is not the payload: byte comparison is against the frozen file only.
assert_ne!(
serde_json::to_vec(&sidecar).unwrap(),
frozen,
"the provenance sidecar must never be the byte oracle"
);
}
}