[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.
This commit is contained in:
1 parent
1b6db09bd1
commit
75fe5a123c
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,617 @@
|
||||
//! Story 3.8 · NFR-P4 diagnostics: real `resources/list` latency for both supported MCP revisions.
|
||||
//!
|
||||
//! This is an **opt-in local diagnostic**, not a default-suite gate and not Reference evidence.
|
||||
//! It drives the same real loopback HTTP endpoint, real PostgreSQL registry and real artifact store
|
||||
//! the accepted AT-3.8-01..05 suite uses (`standard_endpoint`), measures `resources/list` until the
|
||||
//! complete response body is consumed on a monotonic clock, validates every wire result against the
|
||||
//! exact bound Resource snapshot, and writes raw samples plus nearest-rank percentiles under
|
||||
//! `W/.tmp/t_b5624309` (override with `CRANK_DISCOVERY_DIAGNOSTIC_DIR`).
|
||||
//!
|
||||
//! Run explicitly:
|
||||
//!
|
||||
//! ```text
|
||||
//! SQLX_OFFLINE=true CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 \
|
||||
//! cargo test -p mcp-server --test integration \
|
||||
//! integration::static_resources::discovery_diagnostic -- --ignored --nocapture --test-threads=1
|
||||
//! ```
|
||||
//!
|
||||
//! It never asserts a latency threshold: the accepted ≤150 ms p95 NFR-P4 limit is reported as a
|
||||
//! comparison only, because the dataset here is the bounded existing fixture (see `dataset` in the
|
||||
//! summary), not the PRD Reference dataset, and the host is a shared 4 GiB test server. It does
|
||||
//! assert protocol correctness (exactly the bound snapshot, correct per-revision result shape) so a
|
||||
//! broken wire response can never be reported as a latency sample.
|
||||
|
||||
use std::{
|
||||
fs,
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use reqwest::header;
|
||||
use serde_json::{Value, json};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
|
||||
use super::super::common::initialize_session;
|
||||
use super::fixtures::*;
|
||||
|
||||
/// Hard run bounds agreed for this bounded diagnostic.
|
||||
const WARMUP_REQUESTS_PER_REVISION: usize = 20;
|
||||
const MEASURED_REQUESTS_PER_REVISION: usize = 200;
|
||||
/// At most 5 MCP requests/second with one request in flight: 250 ms between request starts.
|
||||
const MIN_REQUEST_INTERVAL: Duration = Duration::from_millis(250);
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const NFR_P4_P95_LIMIT_MS: f64 = 150.0;
|
||||
const JSONRPC_LIST_ID: u64 = 41;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Phase {
|
||||
Warmup,
|
||||
Measured,
|
||||
}
|
||||
|
||||
impl Phase {
|
||||
fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Phase::Warmup => "warmup",
|
||||
Phase::Measured => "measured",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One HTTP attempt: latency to the fully consumed body, plus whatever failed.
|
||||
struct WireCall {
|
||||
latency_ms: f64,
|
||||
http_status: Option<u16>,
|
||||
body_bytes: Option<usize>,
|
||||
body: Option<String>,
|
||||
transport_error: Option<String>,
|
||||
}
|
||||
|
||||
impl WireCall {
|
||||
fn failure(&self, outcome: &'static str, detail: impl Into<String>) -> Sample {
|
||||
Sample {
|
||||
revision: "",
|
||||
phase: Phase::Measured,
|
||||
index: 0,
|
||||
latency_ms: self.latency_ms,
|
||||
http_status: self.http_status,
|
||||
body_bytes: self.body_bytes,
|
||||
outcome,
|
||||
detail: detail.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Sample {
|
||||
revision: &'static str,
|
||||
phase: Phase,
|
||||
index: usize,
|
||||
latency_ms: f64,
|
||||
http_status: Option<u16>,
|
||||
body_bytes: Option<usize>,
|
||||
outcome: &'static str,
|
||||
detail: String,
|
||||
}
|
||||
|
||||
impl Sample {
|
||||
fn as_json(&self) -> Value {
|
||||
json!({
|
||||
"revision": self.revision,
|
||||
"phase": self.phase.as_str(),
|
||||
"index": self.index,
|
||||
"latency_ms": self.latency_ms,
|
||||
"http_status": self.http_status,
|
||||
"body_bytes": self.body_bytes,
|
||||
"outcome": self.outcome,
|
||||
"detail": self.detail,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn now_rfc3339() -> String {
|
||||
OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.unwrap_or_else(|error| format!("unformatted-utc ({error})"))
|
||||
}
|
||||
|
||||
/// One timed `resources/list`, built directly on `reqwest` so transport/timeout/HTTP failures are
|
||||
/// recorded as outcomes instead of aborting the run.
|
||||
async fn timed_list(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &'static str,
|
||||
session: Option<&str>,
|
||||
) -> WireCall {
|
||||
let payload = if revision == LEGACY_REVISION {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": JSONRPC_LIST_ID,
|
||||
"method": "resources/list",
|
||||
"params": {}
|
||||
})
|
||||
} else {
|
||||
let mut params = json!({});
|
||||
params["_meta"] = modern_meta(revision);
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": JSONRPC_LIST_ID,
|
||||
"method": "resources/list",
|
||||
"params": params
|
||||
})
|
||||
};
|
||||
|
||||
let mut request = endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(header::ACCEPT, "application/json, text/event-stream")
|
||||
.header(
|
||||
header::AUTHORIZATION,
|
||||
format!("Bearer {}", endpoint.api_key),
|
||||
);
|
||||
if revision == LEGACY_REVISION {
|
||||
request = request
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session.unwrap_or_default());
|
||||
} else {
|
||||
request = request
|
||||
.header("MCP-Protocol-Version", revision)
|
||||
.header("Mcp-Method", "resources/list");
|
||||
}
|
||||
|
||||
let started = Instant::now();
|
||||
let response = match request.json(&payload).send().await {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
return WireCall {
|
||||
latency_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
http_status: None,
|
||||
body_bytes: None,
|
||||
body: None,
|
||||
transport_error: Some(error.to_string()),
|
||||
};
|
||||
}
|
||||
};
|
||||
let status = response.status().as_u16();
|
||||
match response.text().await {
|
||||
Ok(body) => {
|
||||
let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
let body_bytes = body.len();
|
||||
WireCall {
|
||||
latency_ms,
|
||||
http_status: Some(status),
|
||||
body_bytes: Some(body_bytes),
|
||||
body: Some(body),
|
||||
transport_error: None,
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let latency_ms = started.elapsed().as_secs_f64() * 1000.0;
|
||||
WireCall {
|
||||
latency_ms,
|
||||
http_status: Some(status),
|
||||
body_bytes: None,
|
||||
body: None,
|
||||
transport_error: Some(format!("reading the response body failed: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate one wire result against the exact bound snapshot and the pinned per-revision shape.
|
||||
/// Returns the number of listed Resources on success.
|
||||
fn validate_list_body(
|
||||
body: &str,
|
||||
revision: &'static str,
|
||||
endpoint: &ResourceEndpoint,
|
||||
) -> Result<usize, String> {
|
||||
let parsed: Value = serde_json::from_str(body)
|
||||
.map_err(|error| format!("response body is not JSON ({error}): {body:.400}"))?;
|
||||
let result = parsed
|
||||
.get("result")
|
||||
.ok_or_else(|| format!("no JSON-RPC result: {body:.400}"))?;
|
||||
let resources = result
|
||||
.get("resources")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| format!("result carries no resources array: {result}"))?;
|
||||
|
||||
if revision == LEGACY_REVISION {
|
||||
for field in ["resultType", "ttlMs", "cacheScope"] {
|
||||
if result.get(field).is_some() {
|
||||
return Err(format!("legacy result must not carry {field}: {result}"));
|
||||
}
|
||||
}
|
||||
} else if result.get("resultType").and_then(Value::as_str) != Some("complete") {
|
||||
return Err(format!(
|
||||
"modern result must carry resultType=complete: {result}"
|
||||
));
|
||||
}
|
||||
if result.get("nextCursor").is_some() {
|
||||
return Err(format!(
|
||||
"a 3-Resource snapshot must not advertise a continuation: {result}"
|
||||
));
|
||||
}
|
||||
|
||||
let expected: Vec<(&str, &str)> = [&endpoint.text, &endpoint.json, &endpoint.binary]
|
||||
.into_iter()
|
||||
.map(|bound| (bound.uri.as_str(), bound.name.as_str()))
|
||||
.collect();
|
||||
if resources.len() != expected.len() {
|
||||
return Err(format!(
|
||||
"expected exactly {} bound Resources, got {}: {result}",
|
||||
expected.len(),
|
||||
resources.len()
|
||||
));
|
||||
}
|
||||
for resource in resources {
|
||||
let uri = resource
|
||||
.get("uri")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| format!("listed Resource without uri: {resource}"))?;
|
||||
let Some((_, name)) = expected
|
||||
.iter()
|
||||
.find(|(expected_uri, _)| *expected_uri == uri)
|
||||
else {
|
||||
return Err(format!("unexpected listed Resource {uri}: {result}"));
|
||||
};
|
||||
if resource.get("name").and_then(Value::as_str) != Some(*name) {
|
||||
return Err(format!(
|
||||
"listed Resource {uri} must carry the published name {name}: {resource}"
|
||||
));
|
||||
}
|
||||
if resource
|
||||
.get("mimeType")
|
||||
.and_then(Value::as_str)
|
||||
.is_none_or(|mime| mime.is_empty())
|
||||
{
|
||||
return Err(format!(
|
||||
"listed Resource {uri} must carry a MIME type: {resource}"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(resources.len())
|
||||
}
|
||||
|
||||
fn evaluate(call: WireCall, revision: &'static str, endpoint: &ResourceEndpoint) -> Sample {
|
||||
let Some(body) = call.body.as_deref() else {
|
||||
return call.failure(
|
||||
"transport-error",
|
||||
call.transport_error.clone().unwrap_or_default(),
|
||||
);
|
||||
};
|
||||
if call.http_status != Some(200) {
|
||||
return call.failure(
|
||||
"http-status",
|
||||
format!("HTTP {}: {body:.400}", call.http_status.unwrap_or(0)),
|
||||
);
|
||||
}
|
||||
match validate_list_body(body, revision, endpoint) {
|
||||
Ok(_) => Sample {
|
||||
revision,
|
||||
phase: Phase::Measured,
|
||||
index: 0,
|
||||
latency_ms: call.latency_ms,
|
||||
http_status: call.http_status,
|
||||
body_bytes: call.body_bytes,
|
||||
outcome: "ok",
|
||||
detail: String::new(),
|
||||
},
|
||||
Err(detail) => call.failure("wire-invalid", detail),
|
||||
}
|
||||
}
|
||||
|
||||
fn percentile_nearest_rank(sorted: &[f64], fraction: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let rank = (fraction * sorted.len() as f64).ceil() as usize;
|
||||
sorted[rank.saturating_sub(1).min(sorted.len() - 1)]
|
||||
}
|
||||
|
||||
fn summarize(
|
||||
revision: &'static str,
|
||||
samples: &[Sample],
|
||||
wall: Duration,
|
||||
init_ms: Option<f64>,
|
||||
) -> Value {
|
||||
let mut latencies: Vec<f64> = samples
|
||||
.iter()
|
||||
.filter(|sample| sample.outcome == "ok")
|
||||
.map(|sample| sample.latency_ms)
|
||||
.collect();
|
||||
latencies.sort_by(f64::total_cmp);
|
||||
let mut error_counts: std::collections::BTreeMap<&'static str, usize> =
|
||||
std::collections::BTreeMap::new();
|
||||
for sample in samples.iter().filter(|sample| sample.outcome != "ok") {
|
||||
*error_counts.entry(sample.outcome).or_default() += 1;
|
||||
}
|
||||
let mean = if latencies.is_empty() {
|
||||
f64::NAN
|
||||
} else {
|
||||
latencies.iter().sum::<f64>() / latencies.len() as f64
|
||||
};
|
||||
let p95 = percentile_nearest_rank(&latencies, 0.95);
|
||||
let wall_seconds = wall.as_secs_f64();
|
||||
json!({
|
||||
"revision": revision,
|
||||
"measured_requests": samples.len(),
|
||||
"ok": latencies.len(),
|
||||
"errors": error_counts,
|
||||
"p50_ms": percentile_nearest_rank(&latencies, 0.50),
|
||||
"p95_ms": p95,
|
||||
"max_ms": latencies.last().copied().unwrap_or(f64::NAN),
|
||||
"min_ms": latencies.first().copied().unwrap_or(f64::NAN),
|
||||
"mean_ms": mean,
|
||||
"wall_seconds": wall_seconds,
|
||||
"achieved_requests_per_second": if wall_seconds > 0.0 {
|
||||
samples.len() as f64 / wall_seconds
|
||||
} else {
|
||||
f64::NAN
|
||||
},
|
||||
"body_bytes_min": samples.iter().filter_map(|s| s.body_bytes).min(),
|
||||
"body_bytes_max": samples.iter().filter_map(|s| s.body_bytes).max(),
|
||||
"session_init_ms": init_ms,
|
||||
"nfr_p4_p95_limit_ms": NFR_P4_P95_LIMIT_MS,
|
||||
"p95_within_150ms_local_comparison_only": p95.is_finite() && p95 <= NFR_P4_P95_LIMIT_MS,
|
||||
})
|
||||
}
|
||||
|
||||
fn git(workdir: &str, args: &[&str]) -> String {
|
||||
std::process::Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(workdir)
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|output| output.status.success())
|
||||
.and_then(|output| String::from_utf8(output.stdout).ok())
|
||||
.map(|stdout| stdout.trim().to_owned())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn environment_snapshot() -> Value {
|
||||
let loadavg = fs::read_to_string("/proc/loadavg").unwrap_or_default();
|
||||
let meminfo = fs::read_to_string("/proc/meminfo").unwrap_or_default();
|
||||
let mem_available_kib = meminfo
|
||||
.lines()
|
||||
.find(|line| line.starts_with("MemAvailable:"))
|
||||
.and_then(|line| line.split_whitespace().nth(1))
|
||||
.and_then(|value| value.parse::<u64>().ok());
|
||||
json!({
|
||||
"os": std::env::consts::OS,
|
||||
"arch": std::env::consts::ARCH,
|
||||
"logical_cpus": std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),
|
||||
"loadavg": loadavg.trim(),
|
||||
"mem_available_kib": mem_available_kib,
|
||||
"build_profile": if cfg!(debug_assertions) { "debug" } else { "release" },
|
||||
"clock": "std::time::Instant (monotonic)",
|
||||
"shared_host_note": "shared 4 vCPU / 4 GiB test server; loadavg recorded at measurement start and end",
|
||||
})
|
||||
}
|
||||
|
||||
async fn db_counts(registry: &crank_registry::PostgresRegistry) -> Value {
|
||||
let pool = registry.pool();
|
||||
let mut counts = serde_json::Map::new();
|
||||
for (label, sql) in [
|
||||
("agents", "select count(*) from agents"),
|
||||
("published_agents", "select count(*) from published_agents"),
|
||||
("operations", "select count(*) from operations"),
|
||||
("resources", "select count(*) from resources"),
|
||||
(
|
||||
"resource_publications",
|
||||
"select count(*) from resource_publications",
|
||||
),
|
||||
(
|
||||
"agent_resource_bindings",
|
||||
"select count(*) from agent_resource_bindings",
|
||||
),
|
||||
] {
|
||||
let value = sqlx::query_scalar::<_, i64>(sql)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|error| format!("{label}: {error}"));
|
||||
match value {
|
||||
Ok(count) => {
|
||||
counts.insert(label.to_owned(), json!(count));
|
||||
}
|
||||
Err(detail) => {
|
||||
counts.insert(label.to_owned(), json!({ "error": detail }));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(counts)
|
||||
}
|
||||
|
||||
fn output_dir() -> PathBuf {
|
||||
std::env::var_os("CRANK_DISCOVERY_DIAGNOSTIC_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../.tmp/t_b5624309"))
|
||||
}
|
||||
|
||||
/// Opt-in: `#[ignore]` keeps an unproven timing diagnostic out of the default suite. The console
|
||||
/// `test result: ignored` line is the visible signal that this measurement did not run.
|
||||
#[tokio::test]
|
||||
#[ignore = "opt-in NFR-P4 discovery latency diagnostic (real HTTP + PostgreSQL), not a default-suite gate"]
|
||||
async fn discovery_latency_diagnostic_p50_p95_both_revisions() {
|
||||
let mut endpoint = standard_endpoint("nfr_p4_discovery").await;
|
||||
// The accepted fixture resyncs the published catalog on every request (`refresh_interval` = 0),
|
||||
// so each sample measures a cold-catalog discovery request: the production read path over HTTP.
|
||||
endpoint.client = reqwest::Client::builder()
|
||||
.timeout(REQUEST_TIMEOUT)
|
||||
.build()
|
||||
.expect("diagnostic HTTP client must build");
|
||||
|
||||
let revisions = supported_revisions();
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
assert!(
|
||||
revisions.iter().any(|supported| supported == revision),
|
||||
"the checked-in revision oracle must contain {revision}: {revisions:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let worktree = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let worktree = worktree.display().to_string();
|
||||
let environment_start = environment_snapshot();
|
||||
let counts = db_counts(&endpoint.registry).await;
|
||||
let started_at = now_rfc3339();
|
||||
let run_started = Instant::now();
|
||||
let mut all_samples: Vec<Value> = Vec::new();
|
||||
let mut summaries = serde_json::Map::new();
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
// Session setup is deliberately outside the timed list span: legacy only.
|
||||
let (init_ms, session) = if revision == LEGACY_REVISION {
|
||||
let init_started = Instant::now();
|
||||
let session =
|
||||
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
|
||||
(
|
||||
Some(init_started.elapsed().as_secs_f64() * 1000.0),
|
||||
Some(session),
|
||||
)
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let mut measured: Vec<Sample> = Vec::new();
|
||||
let total = WARMUP_REQUESTS_PER_REVISION + MEASURED_REQUESTS_PER_REVISION;
|
||||
let measured_started = Instant::now();
|
||||
for index in 0..total {
|
||||
let phase = if index < WARMUP_REQUESTS_PER_REVISION {
|
||||
Phase::Warmup
|
||||
} else {
|
||||
Phase::Measured
|
||||
};
|
||||
let request_started = Instant::now();
|
||||
let call = timed_list(&endpoint, revision, session.as_deref()).await;
|
||||
let mut sample = evaluate(call, revision, &endpoint);
|
||||
sample.revision = revision;
|
||||
sample.phase = phase;
|
||||
sample.index = index;
|
||||
all_samples.push(sample.as_json());
|
||||
if phase == Phase::Measured {
|
||||
measured.push(sample);
|
||||
}
|
||||
let elapsed = request_started.elapsed();
|
||||
if elapsed < MIN_REQUEST_INTERVAL {
|
||||
tokio::time::sleep(MIN_REQUEST_INTERVAL - elapsed).await;
|
||||
}
|
||||
}
|
||||
let wall = measured_started.elapsed();
|
||||
let summary = summarize(revision, &measured, wall, init_ms);
|
||||
println!(
|
||||
"[discovery-diagnostic] revision={revision} samples={} ok={} errors={} p50={:.3}ms p95={:.3}ms max={:.3}ms wall={:.2}s",
|
||||
summary["measured_requests"],
|
||||
summary["ok"],
|
||||
summary["errors"],
|
||||
summary["p50_ms"].as_f64().unwrap_or(f64::NAN),
|
||||
summary["p95_ms"].as_f64().unwrap_or(f64::NAN),
|
||||
summary["max_ms"].as_f64().unwrap_or(f64::NAN),
|
||||
summary["wall_seconds"].as_f64().unwrap_or(f64::NAN),
|
||||
);
|
||||
summaries.insert(revision.to_owned(), summary);
|
||||
}
|
||||
|
||||
let out_dir = output_dir();
|
||||
fs::create_dir_all(&out_dir).expect("diagnostic output directory must be creatable");
|
||||
let raw_path = out_dir.join("discovery-samples.jsonl");
|
||||
let mut raw = String::new();
|
||||
for sample in &all_samples {
|
||||
raw.push_str(&sample.to_string());
|
||||
raw.push('\n');
|
||||
}
|
||||
fs::write(&raw_path, raw).expect("raw samples must be written");
|
||||
|
||||
let max_payload_bytes = [&endpoint.text, &endpoint.json, &endpoint.binary]
|
||||
.into_iter()
|
||||
.map(|bound| bound.bytes.len())
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
let summary = json!({
|
||||
"diagnostic": "story38_nfr_p4_resource_discovery_latency",
|
||||
"generated_at_utc": now_rfc3339(),
|
||||
"started_at_utc": started_at,
|
||||
"candidate": {
|
||||
"head": git(&worktree, &["rev-parse", "HEAD"]),
|
||||
"branch": git(&worktree, &["rev-parse", "--abbrev-ref", "HEAD"]),
|
||||
"worktree": worktree,
|
||||
"dirty_tree": !git(&worktree, &["status", "--porcelain"]).is_empty(),
|
||||
"note": "HEAD alone is insufficient in this dirty worktree; source identity is recorded in .tmp/t_b5624309/identity-*.json",
|
||||
},
|
||||
"scope": {
|
||||
"measures": "MCP resources/list response latency over the real HTTP endpoint",
|
||||
"does_not_measure": [
|
||||
"resources/read latency",
|
||||
"tools/call or platform execution overhead",
|
||||
"mixed load, soak, burst or release Reference workload",
|
||||
"representative real MCP client applications (none used; reqwest is not a client application)",
|
||||
],
|
||||
"nfr_p4_p95_limit_ms": NFR_P4_P95_LIMIT_MS,
|
||||
"qualifies_nfr_p4": false,
|
||||
"qualification_reason": "bounded existing fixture dataset on a shared 4 GiB host, single in-process test, not the PRD Reference Deployment dataset/load generator",
|
||||
},
|
||||
"method": {
|
||||
"transport": "loopback HTTP (127.0.0.1, ephemeral port) served by the production axum router",
|
||||
"registry": "real PostgreSQL 16 (testcontainers, own schema) with the real migration authority",
|
||||
"artifact_store": "real immutable test-owned ArtifactStore root",
|
||||
"revisions": [MODERN_REVISION, LEGACY_REVISION],
|
||||
"warmup_requests_per_revision": WARMUP_REQUESTS_PER_REVISION,
|
||||
"measured_requests_per_revision": MEASURED_REQUESTS_PER_REVISION,
|
||||
"concurrency": 1,
|
||||
"min_request_interval_ms": MIN_REQUEST_INTERVAL.as_millis(),
|
||||
"request_timeout_ms": REQUEST_TIMEOUT.as_millis(),
|
||||
"timed_span": "request start → complete response body consumed",
|
||||
"percentile": "nearest-rank",
|
||||
"warm_cold_policy": "process and fixtures warm after construction; first measured revision runs after its own 20-request warmup; catalog refresh interval is 0 ms, so every request reloads the published catalog from PostgreSQL (cold-catalog path)",
|
||||
"session_policy": "legacy 2025-11-25: one initialize/initialized handshake before warmup, timed separately; modern 2026-07-28: stateless per request",
|
||||
"error_policy": "transport, timeout, HTTP-status and wire-validation failures are counted per revision and excluded from percentiles; any error fails the test",
|
||||
},
|
||||
"dataset": {
|
||||
"fixture": "static_resources::fixtures::standard_endpoint (accepted AT-3.8 suite)",
|
||||
"bound_resources": 3,
|
||||
"resource_kinds": ["text", "json", "binary"],
|
||||
"max_resource_payload_bytes": max_payload_bytes,
|
||||
"page": "no limit parameter: all 3 bound Resources in one page (server max page 100)",
|
||||
"published_agents_in_request_scope": 1,
|
||||
"published_operations_in_request_scope": 1,
|
||||
"seeded_but_not_in_scope": "1 additional draft Agent, 1 published-but-unbound Resource, 1 draft Resource, 1 foreign-workspace Resource",
|
||||
"db_row_counts": counts,
|
||||
"dataset_gap": "PRD Reference dataset (200 Agents / 2 000 Operations, 32 static Resources of ≤4 KiB) is NOT seeded: the accepted fixture capabilities cannot seed it without a larger new harness, so this run measures the minimal existing set",
|
||||
},
|
||||
"environment": environment_start,
|
||||
"environment_at_end": environment_snapshot(),
|
||||
"run_wall_seconds": run_started.elapsed().as_secs_f64(),
|
||||
"revisions": summaries,
|
||||
"raw_samples_file": raw_path.display().to_string(),
|
||||
"total_requests": all_samples.len(),
|
||||
});
|
||||
let summary_path = out_dir.join("discovery-summary.json");
|
||||
fs::write(
|
||||
&summary_path,
|
||||
format!(
|
||||
"{}\n",
|
||||
serde_json::to_string_pretty(&summary).expect("summary serializes")
|
||||
),
|
||||
)
|
||||
.expect("summary must be written");
|
||||
println!("[discovery-diagnostic] summary: {}", summary_path.display());
|
||||
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
let entry = &summaries[revision];
|
||||
let errors = entry["errors"]
|
||||
.as_object()
|
||||
.map(|map| map.len())
|
||||
.unwrap_or(0);
|
||||
assert_eq!(
|
||||
entry["measured_requests"].as_u64(),
|
||||
Some(MEASURED_REQUESTS_PER_REVISION as u64),
|
||||
"every revision must produce the planned measured sample count: {entry}"
|
||||
);
|
||||
assert_eq!(
|
||||
errors, 0,
|
||||
"a working local endpoint must not answer transport/HTTP/wire failures on {revision}: {entry}"
|
||||
);
|
||||
assert_eq!(
|
||||
entry["ok"].as_u64(),
|
||||
Some(MEASURED_REQUESTS_PER_REVISION as u64),
|
||||
"every measured response must validate against the bound snapshot on {revision}: {entry}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,998 @@
|
||||
//! Story 3.8 (AT-3.8-01..05): real MCP endpoint fixtures for published static Resources.
|
||||
//!
|
||||
//! Everything here uses the existing loopback MCP server, the real PostgreSQL registry and the
|
||||
//! sanctioned `CommunityMachineCredentialVerifier` — no `route.fulfill`, no stubbed backend, no fake
|
||||
//! service. Fixture data is bounded and test-owned.
|
||||
//!
|
||||
//! Resource fixture rows are seeded with SQL and exact published bytes written through the real
|
||||
//! `ArtifactStore` (the same `put`/content-addressed contract the admin-api publishes with) into a
|
||||
//! test-owned root. The row shapes are exactly the V16/V17 contracts (`resources`,
|
||||
//! `resource_versions`, `resource_publications`, `artifact_*`).
|
||||
//!
|
||||
//! BUILD SEAM (Story 3.8): `build_app_with_artifacts` gives the MCP app the artifact store of its
|
||||
//! root (the same seam the admin-api already has via `storage_root`); the existing constructors keep
|
||||
//! working and fail `resources/read` closed. The production read path
|
||||
//! (`resolve_resource_publication` + `resource_wire`) is the same code the endpoint runs.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::{
|
||||
fs, io,
|
||||
os::unix::fs::PermissionsExt,
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_community_mcp::{
|
||||
auth::CommunityMachineCredentialVerifier, build_app_with_artifacts,
|
||||
session::InMemorySessionStore,
|
||||
};
|
||||
use crank_core::ResponseCacheStore;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, PlatformApiKeyScope, ToolSelectionPolicy, Workspace,
|
||||
WorkspaceId, WorkspaceStatus,
|
||||
};
|
||||
use crank_registry::model::resource::ArchiveResourceRequest;
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, CreateWorkspaceRequest, PostgresRegistry,
|
||||
PublishAgentRequest, PublishRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use crank_runtime::{
|
||||
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
use tracing_subscriber::{filter::LevelFilter, fmt::MakeWriter};
|
||||
|
||||
use super::super::common::*;
|
||||
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) 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";
|
||||
|
||||
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Private, test-owned artifact root (0700) removed on drop.
|
||||
pub(super) struct TestRoot(PathBuf);
|
||||
|
||||
impl TestRoot {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"crank-mcp-static-resources-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).expect("artifact root must be creatable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
|
||||
.expect("artifact root must be private");
|
||||
Self(path)
|
||||
}
|
||||
|
||||
pub(super) fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestRoot {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One seeded static Resource. `kind` is the typed kind, never sniffed from bytes.
|
||||
pub(super) struct SeedResource {
|
||||
pub(super) resource_id: ResourceId,
|
||||
pub(super) uri: String,
|
||||
pub(super) name: String,
|
||||
pub(super) kind: &'static str,
|
||||
pub(super) mime_type: &'static str,
|
||||
pub(super) sensitivity: &'static str,
|
||||
pub(super) bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl SeedResource {
|
||||
pub(super) fn text(id: &str, uri: &str, name: &str, body: &str) -> Self {
|
||||
Self::new(id, uri, name, "text", "text/plain", body.as_bytes())
|
||||
}
|
||||
|
||||
pub(super) fn json(id: &str, uri: &str, name: &str, body: &str) -> Self {
|
||||
Self::new(id, uri, name, "json", "application/json", body.as_bytes())
|
||||
}
|
||||
|
||||
/// `image/png` bytes that are *valid UTF-8*: a text/JSON conversion would silently succeed, so
|
||||
/// the read result proves the typed kind decides `blob` vs `text` (no content sniffing).
|
||||
pub(super) fn binary(id: &str, uri: &str, name: &str, bytes: &[u8]) -> Self {
|
||||
Self::new(id, uri, name, "binary", "image/png", bytes)
|
||||
}
|
||||
|
||||
fn new(
|
||||
id: &str,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
kind: &'static str,
|
||||
mime_type: &'static str,
|
||||
bytes: &[u8],
|
||||
) -> Self {
|
||||
Self {
|
||||
resource_id: ResourceId::new(id),
|
||||
uri: uri.to_owned(),
|
||||
name: name.to_owned(),
|
||||
kind,
|
||||
mime_type,
|
||||
sensitivity: "internal",
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct BoundResource {
|
||||
pub(super) id: ResourceId,
|
||||
pub(super) uri: String,
|
||||
pub(super) name: String,
|
||||
pub(super) bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl BoundResource {
|
||||
fn from_seed(seed: &SeedResource) -> Self {
|
||||
Self {
|
||||
id: seed.resource_id.clone(),
|
||||
uri: seed.uri.clone(),
|
||||
name: seed.name.clone(),
|
||||
bytes: seed.bytes.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct ResourceEndpoint {
|
||||
pub(super) registry: PostgresRegistry,
|
||||
pub(super) client: reqwest::Client,
|
||||
pub(super) mcp_url: String,
|
||||
pub(super) api_key: String,
|
||||
pub(super) tool_name: String,
|
||||
pub(super) agent_id: AgentId,
|
||||
pub(super) draft_agent_id: AgentId,
|
||||
pub(super) root: TestRoot,
|
||||
pub(super) artifact_store: ArtifactStore,
|
||||
pub(super) text: BoundResource,
|
||||
pub(super) json: BoundResource,
|
||||
pub(super) binary: BoundResource,
|
||||
pub(super) unbound_uri: String,
|
||||
pub(super) unbound_name: String,
|
||||
pub(super) draft_uri: String,
|
||||
pub(super) draft_name: String,
|
||||
pub(super) foreign_uri: String,
|
||||
}
|
||||
|
||||
impl ResourceEndpoint {
|
||||
pub(super) fn bound_uris(&self) -> Vec<String> {
|
||||
vec![
|
||||
self.text.uri.clone(),
|
||||
self.json.uri.clone(),
|
||||
self.binary.uri.clone(),
|
||||
]
|
||||
}
|
||||
|
||||
/// Digest-derived physical blob path of exact published bytes.
|
||||
pub(super) fn blob_path(&self, bytes: &[u8]) -> PathBuf {
|
||||
let digest = digest_hex(bytes);
|
||||
self.root
|
||||
.path()
|
||||
.join("sha256")
|
||||
.join(&digest[..2])
|
||||
.join(&digest)
|
||||
}
|
||||
|
||||
/// Replace the published binary blob with different bytes of the same length (corruption).
|
||||
pub(super) fn corrupt_binary_blob(&self) {
|
||||
let path = self.blob_path(&self.binary.bytes);
|
||||
fs::remove_file(&path).expect("published blob must be removable in a test-owned root");
|
||||
fs::write(&path, vec![b'x'; self.binary.bytes.len()])
|
||||
.expect("corrupt blob must be writable");
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o444))
|
||||
.expect("corrupt blob must stay read-only like a published blob");
|
||||
}
|
||||
|
||||
/// Remove the published binary blob entirely (a missing artifact, not a corrupt one).
|
||||
pub(super) fn delete_binary_blob(&self) {
|
||||
fs::remove_file(self.blob_path(&self.binary.bytes))
|
||||
.expect("a test-owned published blob must be removable");
|
||||
}
|
||||
|
||||
/// Make the publication size claim inconsistent with the stored blob, modelling tampered
|
||||
/// metadata that must be denied before any byte is read. The table check constraint already
|
||||
/// forbids a claim above the artifact-store ceiling, so an oversize row cannot be created at all;
|
||||
/// this exercises the same pre-read integrity decision with a valid-but-wrong size.
|
||||
pub(super) async fn inconsistent_text_publication_size(&self) {
|
||||
sqlx::query(
|
||||
"update resource_publications
|
||||
set size_bytes = $4
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3",
|
||||
)
|
||||
.bind(test_workspace_id().as_str())
|
||||
.bind(self.text.id.as_str())
|
||||
.bind(1_i32)
|
||||
.bind(1_i64)
|
||||
.execute(self.registry.pool())
|
||||
.await
|
||||
.expect("publication size metadata must be updatable in a test-owned fixture");
|
||||
}
|
||||
|
||||
/// Archive the bound text Resource through the accepted Story 3.7 registry transition.
|
||||
pub(super) async fn archive_text(&self) {
|
||||
let current = self
|
||||
.registry
|
||||
.get_resource_draft(test_workspace_id().as_str(), &self.text.id)
|
||||
.await
|
||||
.expect("bound Resource must be readable before archive");
|
||||
self.registry
|
||||
.archive_resource(ArchiveResourceRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: self.text.id.clone(),
|
||||
expected_updated_at: current.resource.updated_at,
|
||||
archived_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("an active published Resource must archive");
|
||||
}
|
||||
}
|
||||
|
||||
/// Local constructor seam for tests that need to observe the real runtime cache. It deliberately
|
||||
/// mirrors the production constructor arguments without changing the shared integration harness.
|
||||
fn build_resource_test_app(
|
||||
registry: PostgresRegistry,
|
||||
artifact_store: ArtifactStore,
|
||||
cache: Option<Arc<dyn ResponseCacheStore>>,
|
||||
) -> axum::Router {
|
||||
let runtime = crank_runtime::community_with_outbound_policy(
|
||||
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||
)
|
||||
.build();
|
||||
let runtime = cache.map_or(runtime.clone(), |cache| {
|
||||
runtime.with_response_cache_store(cache)
|
||||
});
|
||||
build_app_with_artifacts(
|
||||
registry,
|
||||
Duration::from_millis(0),
|
||||
None,
|
||||
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
|
||||
runtime,
|
||||
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
|
||||
Arc::new(InMemoryCoordinationStateStore::default()),
|
||||
Arc::new(InMemorySessionStore::default()),
|
||||
Arc::new(CommunityMachineCredentialVerifier),
|
||||
16,
|
||||
artifact_store,
|
||||
)
|
||||
}
|
||||
|
||||
/// Standard fixture without response caching, retaining the historical behavior of existing tests.
|
||||
pub(super) async fn standard_endpoint(name: &str) -> ResourceEndpoint {
|
||||
standard_endpoint_with_cache(name, None).await
|
||||
}
|
||||
|
||||
/// Standard real-registry fixture with an explicitly injected response cache when requested.
|
||||
pub(super) async fn standard_endpoint_with_cache(
|
||||
name: &str,
|
||||
cache: Option<Arc<dyn ResponseCacheStore>>,
|
||||
) -> ResourceEndpoint {
|
||||
let registry = test_registry().await;
|
||||
let root = TestRoot::new(name);
|
||||
let artifact_store =
|
||||
ArtifactStore::open(root.path()).expect("the test artifact root must open");
|
||||
|
||||
// A published tool keeps the tools/list positive control meaningful on this exact endpoint.
|
||||
let upstream = spawn_upstream_server().await;
|
||||
let operation = test_operation(&upstream, "crm_resources_probe");
|
||||
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::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let text = SeedResource::text(
|
||||
"res_bound_text",
|
||||
"crank://resources/bound-text",
|
||||
"bound_text",
|
||||
"bound text v1\n",
|
||||
);
|
||||
let json = SeedResource::json(
|
||||
"res_bound_json",
|
||||
"crank://resources/bound-json",
|
||||
"bound_json",
|
||||
r#"{"kind":"bound","version":1}"#,
|
||||
);
|
||||
let binary = SeedResource::binary(
|
||||
"res_bound_binary",
|
||||
"crank://resources/bound-binary",
|
||||
"bound_binary",
|
||||
b"PNG-but-valid-utf8-bytes",
|
||||
);
|
||||
let unbound = SeedResource::text(
|
||||
"res_unbound_text",
|
||||
"crank://resources/unbound-text",
|
||||
"unbound_text",
|
||||
"unbound text v1\n",
|
||||
);
|
||||
let draft = SeedResource::text(
|
||||
"res_draft_text",
|
||||
"crank://resources/draft-text",
|
||||
"draft_text",
|
||||
"draft text v1\n",
|
||||
);
|
||||
let foreign = SeedResource::text(
|
||||
"res_foreign_text",
|
||||
"crank://resources/foreign-text",
|
||||
"foreign_text",
|
||||
"foreign text v1\n",
|
||||
);
|
||||
|
||||
seed_workspace(®istry).await;
|
||||
for (seed, status) in [
|
||||
(&text, "published"),
|
||||
(&json, "published"),
|
||||
(&binary, "published"),
|
||||
(&unbound, "published"),
|
||||
(&draft, "draft"),
|
||||
] {
|
||||
seed_resource(
|
||||
®istry,
|
||||
&artifact_store,
|
||||
test_workspace_id().as_str(),
|
||||
seed,
|
||||
status,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
seed_resource(
|
||||
®istry,
|
||||
&artifact_store,
|
||||
"ws_other",
|
||||
&foreign,
|
||||
"published",
|
||||
)
|
||||
.await;
|
||||
|
||||
let agent_slug = name;
|
||||
let agent_id = AgentId::new(format!("agent_{agent_slug}"));
|
||||
let draft_agent_slug = format!("{name}-draft");
|
||||
let draft_agent_id = AgentId::new(format!("agent_{draft_agent_slug}"));
|
||||
|
||||
create_draft_agent(®istry, agent_slug).await;
|
||||
create_draft_agent(®istry, &draft_agent_slug).await;
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[binding_for_operation(&operation)],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: text.resource_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: json.resource_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: binary.resource_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("draft Resource bindings must be saved");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the Resource-bound Agent must publish");
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
agent_slug,
|
||||
"mcp-resources",
|
||||
&[PlatformApiKeyScope::Read],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_resource_test_app(
|
||||
registry.clone(),
|
||||
artifact_store.clone(),
|
||||
cache,
|
||||
))
|
||||
.await;
|
||||
|
||||
ResourceEndpoint {
|
||||
registry,
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, agent_slug),
|
||||
api_key,
|
||||
tool_name: operation.name.clone(),
|
||||
agent_id,
|
||||
draft_agent_id,
|
||||
root,
|
||||
artifact_store,
|
||||
text: BoundResource::from_seed(&text),
|
||||
json: BoundResource::from_seed(&json),
|
||||
binary: BoundResource::from_seed(&binary),
|
||||
unbound_uri: unbound.uri,
|
||||
unbound_name: unbound.name,
|
||||
draft_uri: draft.uri,
|
||||
draft_name: draft.name,
|
||||
foreign_uri: foreign.uri,
|
||||
}
|
||||
}
|
||||
|
||||
/// A published Agent with no Resource bindings at all: the empty `resources/list` page control.
|
||||
/// The endpoint is otherwise the same real loopback MCP server + real registry + artifact root.
|
||||
pub(super) struct EmptyResourceEndpoint {
|
||||
pub(super) client: reqwest::Client,
|
||||
pub(super) mcp_url: String,
|
||||
pub(super) api_key: String,
|
||||
_root: TestRoot,
|
||||
_artifact_store: ArtifactStore,
|
||||
}
|
||||
|
||||
pub(super) async fn empty_resource_endpoint(name: &str) -> EmptyResourceEndpoint {
|
||||
let registry = test_registry().await;
|
||||
let root = TestRoot::new(name);
|
||||
let artifact_store =
|
||||
ArtifactStore::open(root.path()).expect("the test artifact root must open");
|
||||
create_draft_agent(®istry, name).await;
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &test_agent_id(name),
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("a Resource-free Agent must publish at registry level");
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
name,
|
||||
"mcp-resources-empty",
|
||||
&[PlatformApiKeyScope::Read],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
|
||||
registry,
|
||||
Duration::from_millis(0),
|
||||
None,
|
||||
artifact_store.clone(),
|
||||
))
|
||||
.await;
|
||||
EmptyResourceEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, name),
|
||||
api_key,
|
||||
_root: root,
|
||||
_artifact_store: artifact_store,
|
||||
}
|
||||
}
|
||||
|
||||
async fn seed_workspace(registry: &PostgresRegistry) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: WorkspaceId::new("ws_other"),
|
||||
slug: "other".to_owned(),
|
||||
display_name: "other".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("foreign workspace must be created");
|
||||
}
|
||||
|
||||
async fn create_draft_agent(registry: &PostgresRegistry, slug: &str) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let agent_id = AgentId::new(format!("agent_{slug}"));
|
||||
let agent = Agent {
|
||||
id: agent_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
slug: slug.to_owned(),
|
||||
display_name: slug.to_owned(),
|
||||
description: "Story 3.8 static Resource fixture".to_owned(),
|
||||
status: AgentStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
latest_published_version: None,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
published_at: None,
|
||||
};
|
||||
let version = AgentVersion {
|
||||
agent_id,
|
||||
version: 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: json!({}),
|
||||
tool_selection_policy: ToolSelectionPolicy::default(),
|
||||
created_at: now,
|
||||
};
|
||||
registry
|
||||
.create_agent(CreateAgentRequest {
|
||||
agent: &agent,
|
||||
version: &version,
|
||||
bindings: &[],
|
||||
})
|
||||
.await
|
||||
.expect("draft Agent must be created");
|
||||
}
|
||||
|
||||
/// Seed one exact Resource row set (`resources` + current `resource_versions` + owning blob/source and,
|
||||
/// for `published`, the immutable `resource_publications` snapshot). The bytes are written through the
|
||||
/// real `ArtifactStore`, so the fixture never re-implements the storage layout.
|
||||
async fn seed_resource(
|
||||
registry: &PostgresRegistry,
|
||||
artifact_store: &ArtifactStore,
|
||||
workspace: &str,
|
||||
seed: &SeedResource,
|
||||
status: &str,
|
||||
) {
|
||||
let stored = artifact_store
|
||||
.put(&seed.bytes)
|
||||
.expect("fixture bytes must be published into the test artifact root");
|
||||
let digest = stored.artifact_ref.digest_hex().to_owned();
|
||||
let source_id = format!("src_{}", seed.resource_id.as_str());
|
||||
let size = i64::try_from(stored.size_bytes).expect("bounded fixture bytes");
|
||||
let pool = registry.pool();
|
||||
|
||||
sqlx::query(
|
||||
"insert into artifact_blobs
|
||||
(digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at)
|
||||
values ($1, $2, $3, 'available', now(), now())",
|
||||
)
|
||||
.bind(&digest)
|
||||
.bind(format!("sha256:{digest}"))
|
||||
.bind(size)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("fixture blob metadata must insert");
|
||||
|
||||
sqlx::query(
|
||||
"insert into artifact_sources
|
||||
(workspace_id, source_id, blob_digest, mime_type, sensitivity, lifecycle, created_at, updated_at)
|
||||
values ($1, $2, $3, $4, $5, 'active', now(), now())",
|
||||
)
|
||||
.bind(workspace)
|
||||
.bind(&source_id)
|
||||
.bind(&digest)
|
||||
.bind(seed.mime_type)
|
||||
.bind(seed.sensitivity)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("fixture artifact source must insert");
|
||||
|
||||
sqlx::query(
|
||||
"insert into resources
|
||||
(workspace_id, resource_id, uri, name, description, status, kind, current_draft_version, created_at, updated_at)
|
||||
values ($1, $2, $3, $4, '', $5, $6, 1, now(), now())",
|
||||
)
|
||||
.bind(workspace)
|
||||
.bind(seed.resource_id.as_str())
|
||||
.bind(&seed.uri)
|
||||
.bind(&seed.name)
|
||||
.bind(status)
|
||||
.bind(seed.kind)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("fixture Resource row must insert");
|
||||
|
||||
sqlx::query(
|
||||
"insert into resource_versions
|
||||
(workspace_id, resource_id, version, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, created_at, superseded_at)
|
||||
values ($1, $2, 1, $3, $4, $5, $6, $7, $8, now(), null)",
|
||||
)
|
||||
.bind(workspace)
|
||||
.bind(seed.resource_id.as_str())
|
||||
.bind(seed.kind)
|
||||
.bind(seed.mime_type)
|
||||
.bind(size)
|
||||
.bind(&digest)
|
||||
.bind(seed.sensitivity)
|
||||
.bind(&source_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("fixture Resource version must insert");
|
||||
|
||||
if status == "published" {
|
||||
sqlx::query(
|
||||
"insert into resource_publications
|
||||
(workspace_id, resource_id, version, uri, name, description, kind, mime_type, size_bytes, digest, sensitivity, artifact_source_id, published_at)
|
||||
values ($1, $2, 1, $3, $4, '', $5, $6, $7, $8, $9, $10, now())",
|
||||
)
|
||||
.bind(workspace)
|
||||
.bind(seed.resource_id.as_str())
|
||||
.bind(&seed.uri)
|
||||
.bind(&seed.name)
|
||||
.bind(seed.kind)
|
||||
.bind(seed.mime_type)
|
||||
.bind(size)
|
||||
.bind(&digest)
|
||||
.bind(seed.sensitivity)
|
||||
.bind(&source_id)
|
||||
.execute(pool)
|
||||
.await
|
||||
.expect("fixture Resource publication must insert");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn digest_hex(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
/// Revisions come from the checked-in oracle, never from memory.
|
||||
pub(super) fn supported_revisions() -> Vec<String> {
|
||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/fixtures/mcp-revisions/supported-revisions.json");
|
||||
let raw = fs::read_to_string(&path).unwrap_or_else(|error| {
|
||||
panic!(
|
||||
"revision oracle must be readable at {}: {error}",
|
||||
path.display()
|
||||
)
|
||||
});
|
||||
serde_json::from_str::<Value>(&raw).expect("revision oracle must be JSON")["revisions"]
|
||||
.as_array()
|
||||
.expect("revision oracle must list revisions")
|
||||
.iter()
|
||||
.map(|entry| {
|
||||
entry["revision"]
|
||||
.as_str()
|
||||
.expect("revision string")
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn modern_meta(revision: &str) -> Value {
|
||||
json!({
|
||||
META_PROTOCOL_VERSION: revision,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: { "name": "crank-atdd-resources", "version": "0.1.0" }
|
||||
})
|
||||
}
|
||||
|
||||
/// `resources/list` over one supported revision on the standard fixture endpoint.
|
||||
pub(super) async fn list_resources(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &str,
|
||||
params: Value,
|
||||
) -> reqwest::Response {
|
||||
list_resources_at(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
revision,
|
||||
params,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// `resources/list` over one supported revision: modern is stateless (identity in headers + `_meta`),
|
||||
/// legacy goes through the accepted initialize/session handshake.
|
||||
pub(super) async fn list_resources_at(
|
||||
client: &reqwest::Client,
|
||||
mcp_url: &str,
|
||||
api_key: &str,
|
||||
revision: &str,
|
||||
params: Value,
|
||||
) -> reqwest::Response {
|
||||
if revision == LEGACY_REVISION {
|
||||
let session = initialize_session(client, mcp_url, api_key).await;
|
||||
post_jsonrpc_response(
|
||||
client,
|
||||
mcp_url,
|
||||
api_key,
|
||||
Some(&session),
|
||||
None,
|
||||
json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
let mut params = params;
|
||||
params["_meta"] = modern_meta(revision);
|
||||
let headers = [
|
||||
("MCP-Protocol-Version", revision),
|
||||
("Mcp-Method", "resources/list"),
|
||||
];
|
||||
post_jsonrpc_with_headers(
|
||||
client,
|
||||
mcp_url,
|
||||
api_key,
|
||||
&headers,
|
||||
json!({ "jsonrpc": "2.0", "id": 11, "method": "resources/list", "params": params }),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// `resources/templates/list` over one supported revision on the standard fixture endpoint.
|
||||
pub(super) async fn list_resource_templates(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &str,
|
||||
) -> reqwest::Response {
|
||||
list_resource_templates_with_params(endpoint, revision, json!({})).await
|
||||
}
|
||||
|
||||
pub(super) async fn list_resource_templates_with_params(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &str,
|
||||
mut params: Value,
|
||||
) -> reqwest::Response {
|
||||
if !params.is_object() {
|
||||
params = json!({});
|
||||
}
|
||||
if revision == LEGACY_REVISION {
|
||||
let session =
|
||||
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
|
||||
post_jsonrpc_response(
|
||||
&endpoint.client, &endpoint.mcp_url, &endpoint.api_key, Some(&session), None,
|
||||
json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }),
|
||||
).await
|
||||
} else {
|
||||
params
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.insert("_meta".to_owned(), modern_meta(revision));
|
||||
let headers = [
|
||||
("MCP-Protocol-Version", revision),
|
||||
("Mcp-Method", "resources/templates/list"),
|
||||
];
|
||||
post_jsonrpc_with_headers(
|
||||
&endpoint.client, &endpoint.mcp_url, &endpoint.api_key, &headers,
|
||||
json!({ "jsonrpc": "2.0", "id": 31, "method": "resources/templates/list", "params": params }),
|
||||
).await
|
||||
}
|
||||
}
|
||||
|
||||
/// `resources/read` over one supported revision, with the required modern `Mcp-Name` equal to the URI.
|
||||
pub(super) async fn read_resource(
|
||||
endpoint: &ResourceEndpoint,
|
||||
revision: &str,
|
||||
uri: &str,
|
||||
request_id: Option<&str>,
|
||||
) -> reqwest::Response {
|
||||
if revision == LEGACY_REVISION {
|
||||
let session =
|
||||
initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
|
||||
post_jsonrpc_response(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
Some(&session),
|
||||
request_id,
|
||||
json!({ "jsonrpc": "2.0", "id": 21, "method": "resources/read", "params": { "uri": uri } }),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
let mut headers = vec![
|
||||
("MCP-Protocol-Version", revision),
|
||||
("Mcp-Method", "resources/read"),
|
||||
("Mcp-Name", uri),
|
||||
];
|
||||
if let Some(request_id) = request_id {
|
||||
headers.push(("x-request-id", request_id));
|
||||
}
|
||||
post_jsonrpc_with_headers(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
&headers,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 21,
|
||||
"method": "resources/read",
|
||||
"params": { "uri": uri, "_meta": modern_meta(revision) }
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Same modern read without any credential: authorization must reject before any Resource lookup.
|
||||
pub(super) async fn read_resource_without_credentials(
|
||||
endpoint: &ResourceEndpoint,
|
||||
uri: &str,
|
||||
) -> reqwest::Response {
|
||||
endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "resources/read")
|
||||
.header("Mcp-Name", uri)
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 31,
|
||||
"method": "resources/read",
|
||||
"params": { "uri": uri, "_meta": modern_meta(MODERN_REVISION) }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("unauthenticated request must reach the server")
|
||||
}
|
||||
|
||||
/// The same credential-less read in the legacy era: the session-based revision must reject it at the
|
||||
/// transport authorization stage as well.
|
||||
pub(super) async fn read_resource_without_credentials_legacy(
|
||||
endpoint: &ResourceEndpoint,
|
||||
uri: &str,
|
||||
) -> reqwest::Response {
|
||||
endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 32,
|
||||
"method": "resources/read",
|
||||
"params": { "uri": uri }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("unauthenticated request must reach the server")
|
||||
}
|
||||
|
||||
pub(super) 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}")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn result_of<'a>(body: &'a Value, what: &str) -> &'a Value {
|
||||
body.get("result").unwrap_or_else(|| {
|
||||
panic!("{what} must return a JSON-RPC result (missing product capability?), got {body}")
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn error_code(body: &Value) -> i64 {
|
||||
body["error"]["code"]
|
||||
.as_i64()
|
||||
.unwrap_or_else(|| panic!("expected a JSON-RPC error, got {body}"))
|
||||
}
|
||||
|
||||
pub(super) fn listed_uris(result: &Value) -> Vec<String> {
|
||||
result["resources"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| {
|
||||
panic!("resources/list result must carry a resources array, got {result}")
|
||||
})
|
||||
.iter()
|
||||
.map(|resource| {
|
||||
resource["uri"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| panic!("listed resource must carry a uri, got {resource}"))
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn base64_of(bytes: &[u8]) -> String {
|
||||
STANDARD.encode(bytes)
|
||||
}
|
||||
|
||||
/// Collects per-revision failures so one run proves the RED/GREEN state for *every* supported MCP
|
||||
/// revision instead of stopping at the first one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct RevisionChecks {
|
||||
failures: Vec<String>,
|
||||
}
|
||||
|
||||
impl RevisionChecks {
|
||||
pub(super) fn require(&mut self, condition: bool, message: impl FnOnce() -> String) {
|
||||
if !condition {
|
||||
self.failures.push(message());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn result<'a>(
|
||||
&mut self,
|
||||
body: &'a Value,
|
||||
revision: &str,
|
||||
what: &str,
|
||||
) -> Option<&'a Value> {
|
||||
match body.get("result") {
|
||||
Some(result) => Some(result),
|
||||
None => {
|
||||
self.failures.push(format!(
|
||||
"{what} on {revision} must return a JSON-RPC result, got {body}"
|
||||
));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish(self) {
|
||||
assert!(
|
||||
self.failures.is_empty(),
|
||||
"failures:\n---\n{}",
|
||||
self.failures.join("\n---\n")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// In-process log capture: proves the read telemetry keeps identity and carries no Resource content.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct CapturedLogs {
|
||||
buffer: Arc<Mutex<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl CapturedLogs {
|
||||
pub(super) fn install(&self) -> tracing::subscriber::DefaultGuard {
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_max_level(LevelFilter::INFO)
|
||||
.with_ansi(false)
|
||||
.with_writer(LogWriter(Arc::clone(&self.buffer)))
|
||||
.finish();
|
||||
tracing::subscriber::set_default(subscriber)
|
||||
}
|
||||
|
||||
pub(super) fn output(&self) -> String {
|
||||
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
struct LogWriter(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl<'a> MakeWriter<'a> for LogWriter {
|
||||
type Writer = LogGuard;
|
||||
|
||||
fn make_writer(&'a self) -> Self::Writer {
|
||||
LogGuard(Arc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
struct LogGuard(Arc<Mutex<Vec<u8>>>);
|
||||
|
||||
impl io::Write for LogGuard {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Story 3.8 AC04 / AT-3.8-04: archiving a Published Resource Version after the Agent snapshot is
|
||||
//! fixed must not break reproducible reads of the exact immutable snapshot, while archive refuses new
|
||||
//! bindings. Explicit security revocation stays a separate audited transition and is NOT aliased to
|
||||
//! archive here — its API does not exist yet (reported as a gap, not invented).
|
||||
|
||||
use super::super::common::test_workspace_id;
|
||||
use super::fixtures::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn archive_keeps_the_exact_published_snapshot_readable_for_the_bound_agent() {
|
||||
let endpoint = standard_endpoint("archive_read").await;
|
||||
endpoint.archive_text().await;
|
||||
|
||||
// The immutable publication row itself is untouched by archive.
|
||||
let publication = endpoint
|
||||
.registry
|
||||
.resolve_resource_publication(test_workspace_id().as_str(), &endpoint.text.id, 1)
|
||||
.await
|
||||
.expect("archiving must not remove the exact published version");
|
||||
assert_eq!(
|
||||
publication.publication.digest,
|
||||
digest_hex(&endpoint.text.bytes),
|
||||
"archive must not rewrite the published digest"
|
||||
);
|
||||
|
||||
let expected = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
|
||||
for revision in supported_revisions() {
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
|
||||
let result = result_of(&body, &format!("post-archive resources/read on {revision}"));
|
||||
let contents = result["contents"].as_array().unwrap_or_else(|| {
|
||||
panic!("post-archive read must return contents on {revision}: {body}")
|
||||
});
|
||||
assert_eq!(
|
||||
contents.len(),
|
||||
1,
|
||||
"post-archive read must return one content entry on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
contents[0]["text"].as_str(),
|
||||
Some(expected.as_str()),
|
||||
"post-archive read must return the exact immutable snapshot on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Archive refuses new bindings, including for a still-mutable Draft Agent version.
|
||||
#[tokio::test]
|
||||
async fn archive_refuses_new_resource_bindings() {
|
||||
let endpoint = standard_endpoint("archive_binding_guard").await;
|
||||
let binding = crank_registry::AgentResourceBinding {
|
||||
resource_id: endpoint.text.id.clone(),
|
||||
resource_version: 1,
|
||||
};
|
||||
|
||||
// Positive control: while the Resource is published and active, a Draft Agent accepts the binding.
|
||||
endpoint
|
||||
.registry
|
||||
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.draft_agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
||||
resource_bindings: std::slice::from_ref(&binding),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("an active published Resource must be bindable");
|
||||
// Drop the control binding again so the post-archive attempt is a genuinely new binding.
|
||||
endpoint
|
||||
.registry
|
||||
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.draft_agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("a Draft Agent must stay mutable");
|
||||
|
||||
endpoint.archive_text().await;
|
||||
|
||||
let denied = endpoint
|
||||
.registry
|
||||
.save_agent_catalog_config(crank_registry::SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.draft_agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
||||
resource_bindings: &[binding],
|
||||
expected_state: None,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
denied.is_err(),
|
||||
"an archived Resource must not be accepted as a new Agent binding, got {denied:?}"
|
||||
);
|
||||
|
||||
let rows: i64 = sqlx::query_scalar(
|
||||
"select count(*) from agent_resource_bindings where agent_id = $1 and agent_version = 1",
|
||||
)
|
||||
.bind(endpoint.draft_agent_id.as_str())
|
||||
.fetch_one(endpoint.registry.pool())
|
||||
.await
|
||||
.expect("binding rows must be queryable");
|
||||
assert_eq!(rows, 0, "a refused binding must not persist any row");
|
||||
|
||||
// Sanity: the refused attempt must not have been a no-op for another reason.
|
||||
let published = endpoint
|
||||
.registry
|
||||
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
|
||||
.await
|
||||
.expect("the bound Agent version must be readable")
|
||||
.expect("the bound Agent version must exist");
|
||||
assert_eq!(
|
||||
published.resource_bindings.len(),
|
||||
3,
|
||||
"the published Agent snapshot must keep its three exact Resource bindings: {published:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,819 @@
|
||||
//! Story 3.8 AC01 / AT-3.8-01: authorized discovery returns only the Published Resources bound to the
|
||||
//! exact published Agent snapshot, with an opaque continuation. Draft, foreign and unbound Resources
|
||||
//! never appear.
|
||||
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
sync::atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
use axum::{
|
||||
Json as AxumJson,
|
||||
body::Body,
|
||||
extract::{Path, State},
|
||||
response::Response,
|
||||
routing::{get, head},
|
||||
};
|
||||
use crank_core::resource::template::TemplateSource;
|
||||
use crank_core::{
|
||||
AgentStatus, HttpMethod, OperationId, OperationSafetyClass, OperationSafetyPolicy,
|
||||
RestResponseDescriptor, RestTarget, Target, ids::ResourceId,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::model::CreateAgentDraftVersionRequest;
|
||||
use crank_registry::model::resource::{
|
||||
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, PostgresRegistry, PublishAgentRequest, PublishRequest,
|
||||
SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use crank_schema::SchemaKind;
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::super::common::{
|
||||
object_schema, post_jsonrpc_response, post_jsonrpc_with_headers, test_operation,
|
||||
test_workspace_id,
|
||||
};
|
||||
use super::fixtures::*;
|
||||
|
||||
#[path = "list/template_discovery.rs"]
|
||||
mod template_discovery;
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_serves_every_supported_revision_with_only_bound_published_resources() {
|
||||
let endpoint = standard_endpoint("list_matrix").await;
|
||||
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
|
||||
let revisions = supported_revisions();
|
||||
assert!(
|
||||
revisions.contains(&MODERN_REVISION.to_owned())
|
||||
&& revisions.contains(&LEGACY_REVISION.to_owned()),
|
||||
"the protocol matrix must be driven by the checked-in revision oracle: {revisions:?}"
|
||||
);
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in revisions {
|
||||
let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
|
||||
let Some(result) = checks.result(&body, &revision, "resources/list") else {
|
||||
continue;
|
||||
};
|
||||
if revision != LEGACY_REVISION {
|
||||
checks.require(result["resultType"].as_str() == Some("complete"), || {
|
||||
format!(
|
||||
"a modern resources/list result must carry Result.resultType=\"complete\" on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
let Some(listed_array) = result["resources"].as_array() else {
|
||||
checks.require(false, || {
|
||||
format!("resources/list must carry a resources array on {revision}: {body}")
|
||||
});
|
||||
continue;
|
||||
};
|
||||
let listed: BTreeSet<String> = listed_array
|
||||
.iter()
|
||||
.filter_map(|resource| resource["uri"].as_str().map(str::to_owned))
|
||||
.collect();
|
||||
checks.require(listed == expected, || {
|
||||
format!(
|
||||
"revision {revision} must list exactly the bound Published Resources, got {body}"
|
||||
)
|
||||
});
|
||||
for excluded in [
|
||||
&endpoint.draft_uri,
|
||||
&endpoint.unbound_uri,
|
||||
&endpoint.foreign_uri,
|
||||
] {
|
||||
checks.require(!listed.contains(excluded), || {
|
||||
format!(
|
||||
"a Draft, foreign or unbound Resource ({excluded}) must not be discoverable on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
for resource in listed_array {
|
||||
let uri = resource["uri"].as_str().unwrap_or_default();
|
||||
match [&endpoint.text, &endpoint.json, &endpoint.binary]
|
||||
.into_iter()
|
||||
.find(|bound| bound.uri == uri)
|
||||
{
|
||||
None => checks.require(false, || {
|
||||
format!("unexpected listed Resource {uri} on {revision}: {body}")
|
||||
}),
|
||||
Some(bound) => {
|
||||
checks.require(
|
||||
resource["name"].as_str() == Some(bound.name.as_str()),
|
||||
|| {
|
||||
format!(
|
||||
"the listed Resource must expose the published name for {uri} on {revision}: {resource}"
|
||||
)
|
||||
},
|
||||
);
|
||||
checks.require(resource["mimeType"].as_str().is_some(), || {
|
||||
format!(
|
||||
"the listed Resource must expose the published MIME type for {uri} on {revision}: {resource}"
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
checks.finish();
|
||||
}
|
||||
|
||||
/// The pinned 2026-07-28 `ListResourcesResult extends PaginatedResult, CacheableResult`: every modern
|
||||
/// list result — an empty page, a populated page and a continued page — must carry `resultType`,
|
||||
/// `ttlMs` and `cacheScope`. The legacy revision keeps its earlier shape without those members.
|
||||
#[tokio::test]
|
||||
async fn list_modern_results_carry_the_required_cacheable_result_fields() {
|
||||
let populated = standard_endpoint("list_cacheable_populated").await;
|
||||
let empty = empty_resource_endpoint("list_cacheable_empty").await;
|
||||
let bound = populated.bound_uris().len();
|
||||
assert!(
|
||||
bound > 1,
|
||||
"the fixture must paginate more than one Resource"
|
||||
);
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let first =
|
||||
json_body(list_resources(&populated, &revision, json!({ "limit": 1 })).await).await;
|
||||
let cursor = result_of(&first, "bounded resources/list")["nextCursor"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| {
|
||||
panic!("a bounded page must advertise a cursor on {revision}: {first}")
|
||||
})
|
||||
.to_owned();
|
||||
let second = json_body(
|
||||
list_resources(
|
||||
&populated,
|
||||
&revision,
|
||||
json!({ "limit": 1, "cursor": cursor }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
let empty_page = json_body(
|
||||
list_resources_at(
|
||||
&empty.client,
|
||||
&empty.mcp_url,
|
||||
&empty.api_key,
|
||||
&revision,
|
||||
json!({}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
|
||||
for (what, body, expected) in [
|
||||
("populated resources/list", &first, 1usize),
|
||||
("continued resources/list", &second, 1usize),
|
||||
("empty resources/list", &empty_page, 0usize),
|
||||
] {
|
||||
require_list_result_shape(&mut checks, body, &revision, what);
|
||||
let Some(result) = body.get("result") else {
|
||||
continue;
|
||||
};
|
||||
let listed = listed_uris(result);
|
||||
checks.require(listed.len() == expected, || {
|
||||
format!("{what} must carry {expected} Resource(s) on {revision}: {body}")
|
||||
});
|
||||
}
|
||||
}
|
||||
checks.finish();
|
||||
}
|
||||
|
||||
/// Story 3.8 correction (Cherry Studio 2.1.7): the client requests `resources/templates/list`
|
||||
/// together with `resources/list` and drops the whole resource browser when that call fails, even
|
||||
/// though the second call succeeds. This server has no dynamic Resource template, so both supported
|
||||
/// revisions must answer the authenticated request with an empty `resourceTemplates` array in their
|
||||
/// own result envelope instead of an era-correct "method not found".
|
||||
#[tokio::test]
|
||||
async fn list_resource_templates_answers_an_empty_page_on_every_revision() {
|
||||
let endpoint = standard_endpoint("list_templates").await;
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let response = list_resource_templates(&endpoint, &revision).await;
|
||||
let status = response.status();
|
||||
let body = json_body(response).await;
|
||||
checks.require(status == reqwest::StatusCode::OK, || {
|
||||
format!(
|
||||
"resources/templates/list must be served on {revision}, got HTTP {status}: {body}"
|
||||
)
|
||||
});
|
||||
let Some(result) = checks.result(&body, &revision, "resources/templates/list") else {
|
||||
continue;
|
||||
};
|
||||
checks.require(body["id"].as_i64() == Some(31), || {
|
||||
format!("resources/templates/list must preserve the request id on {revision}: {body}")
|
||||
});
|
||||
checks.require(
|
||||
result
|
||||
.get("resourceTemplates")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(Vec::is_empty),
|
||||
|| {
|
||||
format!(
|
||||
"resources/templates/list must answer exactly an empty resourceTemplates array on {revision}: {body}"
|
||||
)
|
||||
},
|
||||
);
|
||||
checks.require(result.get("nextCursor").is_none(), || {
|
||||
format!("an empty template page must not advertise nextCursor on {revision}: {body}")
|
||||
});
|
||||
|
||||
if revision == LEGACY_REVISION {
|
||||
for field in ["resultType", "ttlMs", "cacheScope"] {
|
||||
checks.require(result.get(field).is_none(), || {
|
||||
format!(
|
||||
"the legacy resources/templates/list must keep its earlier shape without {field} on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
checks.require(result["resultType"].as_str() == Some("complete"), || {
|
||||
format!(
|
||||
"a modern resources/templates/list must carry Result.resultType=\"complete\" on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
checks.require(
|
||||
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|
||||
|| {
|
||||
format!(
|
||||
"a modern resources/templates/list must carry CacheableResult.ttlMs on {revision}: {body}"
|
||||
)
|
||||
},
|
||||
);
|
||||
checks.require(
|
||||
matches!(
|
||||
result.get("cacheScope").and_then(Value::as_str),
|
||||
Some("public" | "private")
|
||||
),
|
||||
|| {
|
||||
format!(
|
||||
"a modern resources/templates/list must carry CacheableResult.cacheScope on {revision}: {body}"
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
checks.finish();
|
||||
}
|
||||
|
||||
/// The new method is not an escape hatch: the shared modern header rule, the transport
|
||||
/// authorization and the legacy initialized-session guard still decide before its handler runs.
|
||||
#[tokio::test]
|
||||
async fn list_resource_templates_keeps_the_existing_guards() {
|
||||
let endpoint = standard_endpoint("list_templates_guards").await;
|
||||
let payload = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 41,
|
||||
"method": "resources/templates/list",
|
||||
"params": { "_meta": modern_meta(MODERN_REVISION) }
|
||||
});
|
||||
|
||||
for headers in [
|
||||
vec![("MCP-Protocol-Version", MODERN_REVISION)],
|
||||
vec![
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "resources/list"),
|
||||
],
|
||||
] {
|
||||
let body = json_body(
|
||||
post_jsonrpc_with_headers(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
&headers,
|
||||
payload.clone(),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a modern resources/templates/list without its own Mcp-Method must not reach the handler ({headers:?}): {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32020,
|
||||
"a missing or mismatched Mcp-Method stays a header mismatch ({headers:?}): {body}"
|
||||
);
|
||||
}
|
||||
|
||||
// No credential: the transport authorization still answers first.
|
||||
let unauthenticated = endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header("MCP-Protocol-Version", MODERN_REVISION)
|
||||
.header("Mcp-Method", "resources/templates/list")
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("unauthenticated request must reach the server");
|
||||
assert_eq!(
|
||||
unauthenticated.status().as_u16(),
|
||||
401,
|
||||
"an unauthenticated resources/templates/list must be rejected before dispatch"
|
||||
);
|
||||
|
||||
// A legacy session that never completed `notifications/initialized` is still refused.
|
||||
let initialized = endpoint
|
||||
.client
|
||||
.post(&endpoint.mcp_url)
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header("Authorization", format!("Bearer {}", endpoint.api_key))
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "initialize",
|
||||
"params": { "protocolVersion": LEGACY_REVISION, "capabilities": {} }
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.expect("the legacy initialize must reach the server");
|
||||
let session_id = initialized
|
||||
.headers()
|
||||
.get("MCP-Session-Id")
|
||||
.expect("initialize must mint a session")
|
||||
.to_str()
|
||||
.expect("session id is ASCII")
|
||||
.to_owned();
|
||||
let body = json_body(
|
||||
post_jsonrpc_response(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
Some(&session_id),
|
||||
None,
|
||||
json!({ "jsonrpc": "2.0", "id": 42, "method": "resources/templates/list", "params": {} }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a legacy resources/templates/list on an uninitialized session must not be served: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32002,
|
||||
"the legacy initialized-session guard keeps its answer: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
fn require_list_result_shape(
|
||||
checks: &mut RevisionChecks,
|
||||
body: &Value,
|
||||
revision: &str,
|
||||
what: &str,
|
||||
) {
|
||||
let Some(result) = checks.result(body, revision, what) else {
|
||||
return;
|
||||
};
|
||||
if revision == LEGACY_REVISION {
|
||||
for field in ["resultType", "ttlMs", "cacheScope"] {
|
||||
checks.require(result.get(field).is_none(), || {
|
||||
format!(
|
||||
"the legacy {what} must keep its earlier shape without {field} on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
checks.require(result["resultType"].as_str() == Some("complete"), || {
|
||||
format!("a modern {what} must carry Result.resultType=\"complete\" on {revision}: {body}")
|
||||
});
|
||||
checks.require(
|
||||
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|
||||
|| format!("a modern {what} must carry CacheableResult.ttlMs on {revision}: {body}"),
|
||||
);
|
||||
checks.require(
|
||||
matches!(
|
||||
result.get("cacheScope").and_then(Value::as_str),
|
||||
Some("public" | "private")
|
||||
),
|
||||
|| format!("a modern {what} must carry CacheableResult.cacheScope on {revision}: {body}"),
|
||||
);
|
||||
}
|
||||
|
||||
/// Opacity is not enough: a continuation is bound to this workspace+Agent+catalog revision+MCP
|
||||
/// revision, so a malformed, cross-revision or cross-agent cursor is a safe invalid-params answer and
|
||||
/// never mixes two pages.
|
||||
#[tokio::test]
|
||||
async fn list_rejects_malformed_cross_revision_and_cross_agent_cursors() {
|
||||
let endpoint = standard_endpoint("list_cursor_scope").await;
|
||||
let other = standard_endpoint("list_cursor_other_agent").await;
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let first =
|
||||
json_body(list_resources(&endpoint, &revision, json!({ "limit": 1 })).await).await;
|
||||
let cursor = result_of(&first, "bounded resources/list")["nextCursor"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| panic!("a bounded page must advertise a cursor: {first}"))
|
||||
.to_owned();
|
||||
|
||||
let rejected = [
|
||||
("malformed", "not-a-cursor".to_owned(), &revision),
|
||||
("not base64", "%%%".to_owned(), &revision),
|
||||
(
|
||||
"forged scope",
|
||||
forge_cursor_for_other_scope(&endpoint, &revision),
|
||||
&revision,
|
||||
),
|
||||
];
|
||||
for (what, cursor_value, requested_revision) in rejected {
|
||||
let body = json_body(
|
||||
list_resources(
|
||||
&endpoint,
|
||||
requested_revision,
|
||||
json!({ "limit": 1, "cursor": cursor_value }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a {what} cursor must not be served a page on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32602,
|
||||
"a {what} cursor must be safe invalid params on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
// A cursor minted for another MCP revision is a different scope.
|
||||
let cross_revision = if revision == LEGACY_REVISION {
|
||||
MODERN_REVISION
|
||||
} else {
|
||||
LEGACY_REVISION
|
||||
};
|
||||
let body = json_body(
|
||||
list_resources(
|
||||
&endpoint,
|
||||
cross_revision,
|
||||
json!({ "limit": 1, "cursor": cursor.clone() }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a cursor minted for {revision} must not page the {cross_revision} revision: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32602,
|
||||
"a cross-revision cursor must be safe invalid params: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
// A cursor of another Agent is a different scope as well.
|
||||
let foreign_cursor = {
|
||||
let first =
|
||||
json_body(list_resources(&other, MODERN_REVISION, json!({ "limit": 1 })).await).await;
|
||||
result_of(&first, "other Agent bounded resources/list")["nextCursor"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| panic!("the other Agent must advertise a cursor: {first}"))
|
||||
.to_owned()
|
||||
};
|
||||
let body = json_body(
|
||||
list_resources(
|
||||
&endpoint,
|
||||
MODERN_REVISION,
|
||||
json!({ "limit": 1, "cursor": foreign_cursor }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a cursor of another Agent must never page this Agent's snapshot: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32602,
|
||||
"a cross-agent cursor must be safe invalid params: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A cursor whose scope fields are well-formed but name another catalog revision: the minimal opaque
|
||||
/// continuation contract binds the catalog identity, so this is a stale continuation, not a page.
|
||||
fn forge_cursor_for_other_scope(endpoint: &ResourceEndpoint, revision: &str) -> String {
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
let payload = json!({
|
||||
"v": 1u8,
|
||||
"w": "default",
|
||||
"a": endpoint.agent_id.as_str(),
|
||||
"c": "agent-version-1-catalog-revision-0",
|
||||
"r": revision,
|
||||
"o": 1usize,
|
||||
});
|
||||
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&payload).expect("cursor payload is serializable"))
|
||||
}
|
||||
|
||||
/// Opacity + no duplicates + one catalog revision: the cursor is an opaque continuation, not a
|
||||
/// Resource URI/id, and a bounded page never mixes or repeats entries.
|
||||
#[tokio::test]
|
||||
async fn list_pagination_is_an_opaque_continuation_over_the_same_catalog_revision() {
|
||||
let endpoint = standard_endpoint("list_pagination").await;
|
||||
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let first =
|
||||
json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await;
|
||||
let first_result = result_of(&first, &format!("bounded resources/list on {revision}"));
|
||||
let first_uris = listed_uris(first_result);
|
||||
assert_eq!(
|
||||
first_uris.len(),
|
||||
2,
|
||||
"resources/list limit=2 must bound the page on {revision}, got {first}"
|
||||
);
|
||||
let cursor = first_result["nextCursor"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| {
|
||||
panic!("a page with more bounded Resources must advertise nextCursor on {revision}: {first}")
|
||||
})
|
||||
.to_owned();
|
||||
for opaque in expected.iter().map(String::as_str).chain([
|
||||
endpoint.text.id.as_str(),
|
||||
endpoint.json.id.as_str(),
|
||||
endpoint.binary.id.as_str(),
|
||||
]) {
|
||||
assert!(
|
||||
!cursor.contains(opaque),
|
||||
"the pagination cursor must be opaque, not a Resource URI/id ({opaque}): {cursor}"
|
||||
);
|
||||
}
|
||||
|
||||
let second = json_body(
|
||||
list_resources(
|
||||
&endpoint,
|
||||
&revision,
|
||||
json!({ "limit": 2, "cursor": cursor }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
let second_result = result_of(&second, &format!("continued resources/list on {revision}"));
|
||||
let mut all = first_uris;
|
||||
all.extend(listed_uris(second_result));
|
||||
assert_eq!(
|
||||
all.len(),
|
||||
expected.len(),
|
||||
"the continuation must not repeat or skip Resources on {revision}: {all:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
all.into_iter().collect::<BTreeSet<_>>(),
|
||||
expected,
|
||||
"the union of both pages must be the bound snapshot on {revision}: {second}"
|
||||
);
|
||||
assert!(
|
||||
second_result.get("nextCursor").is_none(),
|
||||
"the last page must not advertise another cursor on {revision}: {second}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression for the defect the Story 3.17 real-client smoke reproduced: with a *valid* published
|
||||
/// Resource template bound to the exact published Agent snapshot, `resources/list` answered
|
||||
/// `-32603`/HTTP 500 for the whole page, so no client could open the template parameter form.
|
||||
///
|
||||
/// A template is not an artifact-backed concrete Resource — its publication has no blob and its
|
||||
/// concrete URIs are the expanded ones. So the page keeps answering exactly the earlier entries,
|
||||
/// while the template stays discoverable through `resources/templates/list` with its typed
|
||||
/// parameters, and it is never advertised as a downloadable Resource.
|
||||
#[tokio::test]
|
||||
async fn list_stays_available_when_a_published_template_is_bound() {
|
||||
let endpoint = standard_endpoint("list_bound_template").await;
|
||||
let registry = &endpoint.registry;
|
||||
let published = registry
|
||||
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
|
||||
.await
|
||||
.expect("published Agent snapshot must be readable")
|
||||
.expect("published Agent version 1 must exist");
|
||||
|
||||
// A published Resource template (Story 3.10) pointing at the already published test Operation.
|
||||
let template_id = ResourceId::new("res_list_bound_template");
|
||||
let template_uri = "crank://templates/regions";
|
||||
let template_source = TemplateSource::parse(&json!({
|
||||
"operation_id": "op_crm_resources_probe",
|
||||
"operation_version": 1,
|
||||
"uri_template": "crank://regions/{region}",
|
||||
"parameters": [{
|
||||
"name": "region",
|
||||
"input_path": "input.region",
|
||||
"schema": { "type": "string", "required": true }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["region"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
}))
|
||||
.expect("template fixture must satisfy the Story 3.10 source contract");
|
||||
let definition =
|
||||
serde_json::to_string(&template_source).expect("normalized definition must serialize");
|
||||
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: template_id.clone(),
|
||||
uri: template_uri.to_owned(),
|
||||
name: "regions".to_owned(),
|
||||
description: "Published regions template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition,
|
||||
definition_digest: digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template Draft must be created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: template_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template exact version must publish");
|
||||
|
||||
// Mixed Agent snapshot: the three artifact-backed Resources plus the one template binding.
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut agent_draft = published.snapshot.clone();
|
||||
agent_draft.version = 2;
|
||||
agent_draft.status = AgentStatus::Draft;
|
||||
agent_draft.created_at = now;
|
||||
registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: &agent_draft,
|
||||
bindings: &published.bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.expect("a new Agent Draft must be created for the mixed Resource bindings");
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
agent_version: 2,
|
||||
bindings: &published.bindings,
|
||||
tool_selection_policy: &published.snapshot.tool_selection_policy,
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: endpoint.text.id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: endpoint.json.id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: endpoint.binary.id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: template_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the template binding must be saved next to the artifact-backed Resources");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: 2,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the mixed Agent snapshot must publish");
|
||||
|
||||
let expected: BTreeSet<String> = endpoint.bound_uris().into_iter().collect();
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let body = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
|
||||
if let Some(result) = checks.result(&body, &revision, "resources/list") {
|
||||
let listed: BTreeSet<String> = listed_uris(result).into_iter().collect();
|
||||
checks.require(listed == expected, || {
|
||||
format!(
|
||||
"a bound published template must not break or change resources/list on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
checks.require(!listed.contains(template_uri), || {
|
||||
format!(
|
||||
"a template must not be advertised as a concrete Resource on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
let templates = json_body(list_resource_templates(&endpoint, &revision).await).await;
|
||||
if let Some(result) = checks.result(&templates, &revision, "resources/templates/list") {
|
||||
let advertised = result["resourceTemplates"]
|
||||
.as_array()
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.find(|item| {
|
||||
item["uriTemplate"].as_str() == Some("crank://regions/{region}")
|
||||
})
|
||||
.cloned()
|
||||
})
|
||||
.unwrap_or(None);
|
||||
match advertised {
|
||||
Some(template) => checks.require(
|
||||
template["parameters"][0]["name"].as_str() == Some("region")
|
||||
&& template["mimeType"].as_str() == Some("application/json"),
|
||||
|| {
|
||||
format!(
|
||||
"template discovery must keep its typed parameters on {revision}: {template}"
|
||||
)
|
||||
},
|
||||
),
|
||||
None => checks.require(false, || {
|
||||
format!(
|
||||
"the bound template must stay discoverable on {revision}: {templates}"
|
||||
)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
// Mixed pagination: the template binding must neither fail a page nor duplicate/skip entries.
|
||||
let first =
|
||||
json_body(list_resources(&endpoint, &revision, json!({ "limit": 2 })).await).await;
|
||||
let Some(first_result) = checks.result(&first, &revision, "bounded resources/list") else {
|
||||
continue;
|
||||
};
|
||||
let mut union: Vec<String> = listed_uris(first_result);
|
||||
let mut next = first_result["nextCursor"].as_str().map(str::to_owned);
|
||||
while let Some(cursor) = next {
|
||||
let page = json_body(
|
||||
list_resources(
|
||||
&endpoint,
|
||||
&revision,
|
||||
json!({ "limit": 2, "cursor": cursor }),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
let Some(page_result) = checks.result(&page, &revision, "continued resources/list")
|
||||
else {
|
||||
break;
|
||||
};
|
||||
union.extend(listed_uris(page_result));
|
||||
next = page_result["nextCursor"].as_str().map(str::to_owned);
|
||||
}
|
||||
checks.require(
|
||||
union.iter().cloned().collect::<BTreeSet<_>>() == expected
|
||||
&& union.len() == expected.len(),
|
||||
|| {
|
||||
format!(
|
||||
"mixed pagination must neither skip nor repeat Resources on {revision}: {union:?}"
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
checks.finish();
|
||||
|
||||
// Integrity is still enforced for a template admission: a publication whose digest no longer
|
||||
// matches its own definition must fail the page instead of silently dropping the entry.
|
||||
sqlx::query(
|
||||
"update resource_publications set digest = $4
|
||||
where workspace_id = $1 and resource_id = $2 and version = $3",
|
||||
)
|
||||
.bind(test_workspace_id().as_str())
|
||||
.bind(template_id.as_str())
|
||||
.bind(1_i32)
|
||||
.bind("0".repeat(64))
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.expect("test-owned template publication metadata must be corruptible");
|
||||
let corrupted = json_body(list_resources(&endpoint, MODERN_REVISION, json!({})).await).await;
|
||||
assert!(
|
||||
corrupted.get("result").is_none(),
|
||||
"a corrupt template publication must fail the page, not answer a partial success: {corrupted}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&corrupted),
|
||||
-32603,
|
||||
"a corrupt template publication must stay an internal error: {corrupted}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,939 @@
|
||||
use super::*;
|
||||
use base64::Engine as _;
|
||||
use std::sync::Arc;
|
||||
#[path = "template_discovery_binary.rs"]
|
||||
mod binary_fixture;
|
||||
use binary_fixture::{TestValkey, publish_binary_template};
|
||||
|
||||
async fn template_order_lookup(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Path(order_id): Path<String>,
|
||||
) -> AxumJson<Value> {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
if order_id == "00000000-0000-4000-8000-000000000001" {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(600)).await;
|
||||
}
|
||||
AxumJson(json!({ "id": order_id, "order_id": order_id, "status": "found" }))
|
||||
}
|
||||
|
||||
async fn template_binary_lookup(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Path(order_id): Path<String>,
|
||||
headers: axum::http::HeaderMap,
|
||||
) -> Response<Body> {
|
||||
use base64::Engine as _;
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
if headers
|
||||
.get("authorization")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
!= Some("Bearer story311-test-token")
|
||||
{
|
||||
return Response::builder()
|
||||
.status(401)
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"error":"unauthorized"}"#))
|
||||
.unwrap();
|
||||
}
|
||||
let payload = if order_id.ends_with("d481") {
|
||||
json!({ "data_base64": "not-base64" })
|
||||
} else if order_id.ends_with("d482") {
|
||||
json!({ "data_base64": "AA==", "extra": "not-allowed" })
|
||||
} else if order_id.ends_with("d484") {
|
||||
json!({
|
||||
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_537])
|
||||
})
|
||||
} else if order_id.ends_with("d485") {
|
||||
json!({
|
||||
"data_base64": base64::engine::general_purpose::STANDARD.encode(vec![0_u8; 65_536])
|
||||
})
|
||||
} else {
|
||||
json!({
|
||||
"data_base64": base64::engine::general_purpose::STANDARD.encode([0_u8, 255, 1, 253, 254, 255])
|
||||
})
|
||||
};
|
||||
let mime = if order_id.ends_with("d483") {
|
||||
"text/plain"
|
||||
} else {
|
||||
"application/json"
|
||||
};
|
||||
Response::builder()
|
||||
.status(200)
|
||||
.header("content-type", mime)
|
||||
.body(Body::from(serde_json::to_vec(&payload).unwrap()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn template_order_head(
|
||||
State(calls): State<Arc<AtomicUsize>>,
|
||||
Path(order_id): Path<String>,
|
||||
) -> Response<Body> {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
Response::builder()
|
||||
.status(200)
|
||||
.header("x_order_id", order_id)
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[path = "template_discovery_cache_loss.rs"]
|
||||
mod cache_loss;
|
||||
|
||||
/// Regression oracle for Story 3.11: a real, exact-version template bound to the published Agent
|
||||
/// must be discoverable, rather than being confused with the empty-template positive control.
|
||||
#[tokio::test]
|
||||
async fn published_agent_discovers_its_bound_template_on_supported_revisions() {
|
||||
let (valkey, port) = TestValkey::start();
|
||||
let cache = Arc::new(
|
||||
crank_runtime::RedisCacheStore::connect(
|
||||
crank_core::CacheBackend::Valkey,
|
||||
&format!("redis://127.0.0.1:{port}/0"),
|
||||
)
|
||||
.await
|
||||
.expect("runtime must connect to test-owned Valkey"),
|
||||
);
|
||||
let endpoint = standard_endpoint_with_cache("bound_template_discovery", Some(cache)).await;
|
||||
let registry: &PostgresRegistry = &endpoint.registry;
|
||||
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("test upstream must bind a loopback port");
|
||||
let upstream_address = upstream_listener.local_addr().unwrap();
|
||||
let upstream_calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = axum::Router::new()
|
||||
.route("/orders/{order_id}", get(template_order_lookup))
|
||||
.route("/orders-binary/{order_id}", get(template_binary_lookup))
|
||||
.route("/order-metadata/{order_id}", head(template_order_head))
|
||||
.with_state(Arc::clone(&upstream_calls));
|
||||
tokio::spawn(async move {
|
||||
axum::serve(upstream_listener, upstream)
|
||||
.await
|
||||
.expect("test upstream must serve");
|
||||
});
|
||||
let mut operation = test_operation(&format!("http://{upstream_address}"), "bound_order_lookup");
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: format!("http://{upstream_address}"),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/orders/{order_id}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("order_id");
|
||||
operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("order_id")
|
||||
.unwrap()
|
||||
.format = Some("uuid".to_owned());
|
||||
operation.execution_config.timeout_ms = 300;
|
||||
operation.execution_config.safety = Some(OperationSafetyPolicy {
|
||||
class: OperationSafetyClass::Read,
|
||||
confirmation: None,
|
||||
});
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.order_id".to_owned(),
|
||||
target: "$.request.path.order_id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("GET Read operation must be created through registry API");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("GET Read operation exact version must publish");
|
||||
let published = registry
|
||||
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
|
||||
.await
|
||||
.expect("published Agent snapshot must be readable")
|
||||
.expect("published Agent version 1 must exist");
|
||||
let operation_id = operation.id.to_string();
|
||||
let resource_id = ResourceId::new("res_bound_template_discovery");
|
||||
let uri = "crank://orders/{order_id}";
|
||||
let head_uri = "crank://orders-metadata/{order_id}";
|
||||
let definition_value = json!({
|
||||
"operation_id": operation_id,
|
||||
"operation_version": 1,
|
||||
"uri_template": uri,
|
||||
"parameters": [{
|
||||
"name": "order_id",
|
||||
"input_path": "input.order_id",
|
||||
"schema": { "type": "string", "required": true, "format": "uuid" }
|
||||
}],
|
||||
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
|
||||
"failure": { "outcome": "error" }
|
||||
});
|
||||
let normalized_source = TemplateSource::parse(&definition_value)
|
||||
.expect("template fixture must satisfy the Story 3.10 source contract");
|
||||
let definition = serde_json::to_string(&normalized_source)
|
||||
.expect("normalized definition must serialize canonically");
|
||||
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: "crank://templates/order-lookup".to_owned(),
|
||||
name: "order_lookup".to_owned(),
|
||||
description: "Published order lookup template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition.clone(),
|
||||
definition_digest: digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template Draft must be created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest.clone(),
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("template exact version must publish");
|
||||
|
||||
let mut head_operation = test_operation(
|
||||
&format!("http://{upstream_address}"),
|
||||
"bound_order_metadata",
|
||||
);
|
||||
head_operation.id = OperationId::new("op_bound_order_metadata");
|
||||
head_operation.target = Target::Rest(RestTarget {
|
||||
base_url: format!("http://{upstream_address}"),
|
||||
method: HttpMethod::Head,
|
||||
path_template: "/order-metadata/{order_id}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: vec![RestResponseDescriptor {
|
||||
status_code: 200,
|
||||
media_type: None,
|
||||
schema_variant: 0,
|
||||
}],
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
head_operation.input_schema = object_schema("order_id");
|
||||
head_operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("order_id")
|
||||
.unwrap()
|
||||
.format = Some("uuid".to_owned());
|
||||
head_operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.order_id".to_owned(),
|
||||
target: "$.request.path.order_id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
head_operation
|
||||
.output_schema
|
||||
.fields
|
||||
.get_mut("id")
|
||||
.unwrap()
|
||||
.kind = SchemaKind::Number;
|
||||
head_operation.output_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.response.data.status".to_owned(),
|
||||
target: "$.output.id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
head_operation.execution_config.timeout_ms = 300;
|
||||
head_operation.execution_config.safety = Some(OperationSafetyPolicy {
|
||||
class: OperationSafetyClass::Read,
|
||||
confirmation: None,
|
||||
});
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &head_operation, Some("alice"))
|
||||
.await
|
||||
.expect("HEAD Read operation must be created");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &head_operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("HEAD Read operation must publish");
|
||||
let head_resource_id = ResourceId::new("res_bound_template_head");
|
||||
let head_definition_value = json!({
|
||||
"operation_id": head_operation.id.as_str(), "operation_version": 1,
|
||||
"uri_template": head_uri,
|
||||
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
|
||||
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536}, "failure":{"outcome":"error"}
|
||||
});
|
||||
let head_source = TemplateSource::parse(&head_definition_value)
|
||||
.expect("HEAD metadata definition must be valid");
|
||||
let head_definition = serde_json::to_string(&head_source).unwrap();
|
||||
let head_digest = format!("{:x}", Sha256::digest(head_definition.as_bytes()));
|
||||
let head_draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: head_resource_id.clone(),
|
||||
uri: "crank://templates/order-metadata".to_owned(),
|
||||
name: "order_metadata".to_owned(),
|
||||
description: "Published order metadata template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: head_definition,
|
||||
definition_digest: head_digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("HEAD template Draft must be created");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: head_resource_id.clone(),
|
||||
expected_updated_at: head_draft.snapshot.resource.updated_at,
|
||||
expected_version: head_draft.snapshot.version.version,
|
||||
expected_digest: head_digest,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("HEAD template must be published");
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut agent_draft = published.snapshot.clone();
|
||||
agent_draft.version = 2;
|
||||
agent_draft.status = AgentStatus::Draft;
|
||||
agent_draft.created_at = now;
|
||||
registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: &agent_draft,
|
||||
bindings: &published.bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.expect("a new Agent Draft must be created for the exact template binding");
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
agent_version: 2,
|
||||
bindings: &published.bindings,
|
||||
tool_selection_policy: &published.snapshot.tool_selection_policy,
|
||||
resource_bindings: &[
|
||||
AgentResourceBinding {
|
||||
resource_id: resource_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: head_resource_id.clone(),
|
||||
resource_version: 1,
|
||||
},
|
||||
],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("exact template version must be bound to the Agent Draft");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: 2,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent snapshot with the exact template binding must publish");
|
||||
|
||||
let unbound_id = ResourceId::new("res_unbound_template");
|
||||
let mut unbound_json = definition_value.clone();
|
||||
unbound_json["uri_template"] = json!("crank://other-orders/{order_id}");
|
||||
let unbound_source =
|
||||
TemplateSource::parse(&unbound_json).expect("unbound template definition remains valid");
|
||||
let unbound_definition = serde_json::to_string(&unbound_source).unwrap();
|
||||
let unbound_digest = format!("{:x}", Sha256::digest(unbound_definition.as_bytes()));
|
||||
let unbound_draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: unbound_id.clone(),
|
||||
uri: "crank://templates/unbound-order".to_owned(),
|
||||
name: "unbound_order".to_owned(),
|
||||
description: "Published but not bound".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: unbound_definition.clone(),
|
||||
definition_digest: unbound_digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("unbound template Draft must be created through the registry API");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: unbound_id,
|
||||
expected_updated_at: unbound_draft.snapshot.resource.updated_at,
|
||||
expected_version: unbound_draft.snapshot.version.version,
|
||||
expected_digest: unbound_digest,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("unbound template must be published without an Agent binding");
|
||||
|
||||
// Prove the fixture is a real exact-version Published template binding before MCP is called.
|
||||
let (publication, stored_definition) = registry
|
||||
.resolve_resource_template_publication(test_workspace_id().as_str(), &resource_id, 1)
|
||||
.await
|
||||
.expect("the exact Published template source must resolve");
|
||||
assert_eq!(publication.source_kind, "template");
|
||||
assert_eq!(publication.version, 1);
|
||||
assert_eq!(stored_definition.definition_json, definition);
|
||||
assert_eq!(stored_definition.definition_digest, digest);
|
||||
assert_eq!(
|
||||
TemplateSource::parse(
|
||||
&serde_json::from_str(&stored_definition.definition_json)
|
||||
.expect("stored definition must remain JSON")
|
||||
)
|
||||
.expect("stored definition must remain normalized and valid"),
|
||||
normalized_source
|
||||
);
|
||||
let published_operation = registry
|
||||
.get_operation_version(&test_workspace_id(), &operation.id, 1)
|
||||
.await
|
||||
.expect("the exact Published Read Operation must be readable")
|
||||
.expect("the exact operation version must exist");
|
||||
assert_eq!(
|
||||
published_operation.status,
|
||||
crank_core::OperationStatus::Published
|
||||
);
|
||||
assert_eq!(published_operation.version, 1);
|
||||
assert!(matches!(
|
||||
&published_operation.snapshot.target,
|
||||
Target::Rest(target)
|
||||
if target.method == HttpMethod::Get
|
||||
&& target.path_template == "/orders/{order_id}"
|
||||
));
|
||||
assert_eq!(
|
||||
published_operation
|
||||
.snapshot
|
||||
.execution_config
|
||||
.safety
|
||||
.as_ref()
|
||||
.map(|policy| policy.class),
|
||||
Some(OperationSafetyClass::Read),
|
||||
"the pinned operation must be explicitly classified as Read"
|
||||
);
|
||||
assert!(
|
||||
published_operation
|
||||
.snapshot
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.is_none(),
|
||||
"the pinned Read operation must not require approval"
|
||||
);
|
||||
assert_eq!(
|
||||
published_operation.snapshot.input_schema.fields["order_id"]
|
||||
.format
|
||||
.as_deref(),
|
||||
Some("uuid"),
|
||||
"the published input schema must match the template parameter"
|
||||
);
|
||||
let exact_published_agent = registry
|
||||
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 2)
|
||||
.await
|
||||
.expect("published Agent snapshot must be readable")
|
||||
.expect("the bound Agent version must exist");
|
||||
assert_eq!(
|
||||
exact_published_agent.snapshot.status,
|
||||
AgentStatus::Published,
|
||||
"the binding must belong to a Published Agent snapshot"
|
||||
);
|
||||
assert_eq!(exact_published_agent.snapshot.version, 2);
|
||||
assert_eq!(
|
||||
exact_published_agent.resource_bindings,
|
||||
vec![
|
||||
AgentResourceBinding {
|
||||
resource_id: resource_id.clone(),
|
||||
resource_version: 1
|
||||
},
|
||||
AgentResourceBinding {
|
||||
resource_id: head_resource_id.clone(),
|
||||
resource_version: 1
|
||||
},
|
||||
],
|
||||
"the fixture must bind the exact template version"
|
||||
);
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let response = list_resource_templates(&endpoint, &revision).await;
|
||||
let status = response.status();
|
||||
let body = json_body(response).await;
|
||||
println!("template discovery {revision}: HTTP {status} {body}");
|
||||
checks.require(status == reqwest::StatusCode::OK, || {
|
||||
format!("template discovery HTTP status on {revision}: HTTP {status} {body}")
|
||||
});
|
||||
let Some(result) = checks.result(&body, &revision, "resources/templates/list") else {
|
||||
continue;
|
||||
};
|
||||
require_list_result_shape(&mut checks, &body, &revision, "resources/templates/list");
|
||||
let Some(templates) = result.get("resourceTemplates").and_then(Value::as_array) else {
|
||||
checks.require(false, || {
|
||||
format!(
|
||||
"resources/templates/list must return resourceTemplates on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
continue;
|
||||
};
|
||||
checks.require(templates.len() == 2, || {
|
||||
format!("the exact bound Published templates must be listed on {revision}: {body}")
|
||||
});
|
||||
checks.require(
|
||||
templates
|
||||
.iter()
|
||||
.any(|template| template["uriTemplate"] == head_uri),
|
||||
|| format!("the bound HEAD metadata template must be listed on {revision}: {body}"),
|
||||
);
|
||||
checks.require(result.get("nextCursor").is_none(), || {
|
||||
format!("a complete template page must not advertise nextCursor on {revision}: {body}")
|
||||
});
|
||||
if let Some(template) = templates.first() {
|
||||
for (field, expected) in [
|
||||
("uriTemplate", json!(uri)),
|
||||
("name", json!("order_lookup")),
|
||||
("mimeType", json!("application/json")),
|
||||
("description", json!("Published order lookup template")),
|
||||
] {
|
||||
checks.require(template.get(field) == Some(&expected), || {
|
||||
format!(
|
||||
"template {field} must match the published definition on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
let mut cursor: Option<String> = None;
|
||||
let mut paged_templates = Vec::new();
|
||||
for _ in 0..10 {
|
||||
let params = cursor.as_ref().map_or_else(
|
||||
|| json!({ "limit": 1 }),
|
||||
|cursor| json!({ "limit": 1, "cursor": cursor }),
|
||||
);
|
||||
let body =
|
||||
json_body(list_resource_templates_with_params(&endpoint, &revision, params).await)
|
||||
.await;
|
||||
let Some(result) = body.get("result") else {
|
||||
panic!("template page failed on {revision}: {body}");
|
||||
};
|
||||
paged_templates.extend(result["resourceTemplates"].as_array().unwrap().clone());
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
if cursor.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
paged_templates.len(),
|
||||
2,
|
||||
"pagination must eventually yield both bound templates on {revision}: {paged_templates:?}"
|
||||
);
|
||||
let paged_uris: BTreeSet<String> = paged_templates
|
||||
.iter()
|
||||
.filter_map(|item| item["uriTemplate"].as_str().map(str::to_owned))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
paged_uris,
|
||||
BTreeSet::from([uri.to_owned(), head_uri.to_owned()])
|
||||
);
|
||||
|
||||
let invalid_cursor = json_body(
|
||||
list_resource_templates_with_params(
|
||||
&endpoint,
|
||||
&revision,
|
||||
json!({"cursor":"not-a-valid-cursor"}),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
checks.require(invalid_cursor.get("result").is_none() && invalid_cursor["error"]["code"].as_i64() == Some(-32602), || {
|
||||
format!("template list must reject a malformed scoped cursor on {revision}: {invalid_cursor}")
|
||||
});
|
||||
}
|
||||
|
||||
let (binary_template, auth_profile_id) = publish_binary_template(
|
||||
registry,
|
||||
&endpoint.agent_id,
|
||||
&format!("http://{upstream_address}"),
|
||||
)
|
||||
.await;
|
||||
let binary_bytes = [0_u8, 255, 1, 253, 254, 255];
|
||||
let mut binary_cache_warmed = false;
|
||||
for revision in supported_revisions() {
|
||||
let exact_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
|
||||
let binary_calls_before = upstream_calls.load(Ordering::SeqCst);
|
||||
let body = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
|
||||
assert!(
|
||||
body.get("error").is_none(),
|
||||
"declared binary runtime read failed on {revision}: {body}"
|
||||
);
|
||||
let content = &body["result"]["contents"][0];
|
||||
assert_eq!(content["uri"], exact_uri);
|
||||
assert_eq!(content["mimeType"], "application/pdf");
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(content["blob"].as_str().unwrap())
|
||||
.unwrap(),
|
||||
binary_bytes,
|
||||
"binary Resource wire bytes must exactly match the REST output on {revision}"
|
||||
);
|
||||
assert!(
|
||||
content.get("text").is_none(),
|
||||
"binary content must not be represented as text"
|
||||
);
|
||||
let expected_calls = binary_calls_before + usize::from(!binary_cache_warmed);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
expected_calls,
|
||||
"the binary read must be fetched once, then served from cache across revisions"
|
||||
);
|
||||
binary_cache_warmed = true;
|
||||
let cached = json_body(read_resource(&endpoint, &revision, exact_uri, None).await).await;
|
||||
assert_eq!(cached["result"]["contents"][0]["blob"], content["blob"]);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
expected_calls,
|
||||
"the authenticated binary read must hit its own cache on {revision}"
|
||||
);
|
||||
|
||||
let boundary_uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d485";
|
||||
let boundary =
|
||||
json_body(read_resource(&endpoint, &revision, boundary_uri, None).await).await;
|
||||
let boundary_bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(boundary["result"]["contents"][0]["blob"].as_str().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
boundary_bytes.len(),
|
||||
65_536,
|
||||
"max_bytes boundary is inclusive on {revision}"
|
||||
);
|
||||
|
||||
for (case, uri) in [
|
||||
(
|
||||
"malformed base64",
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d481",
|
||||
),
|
||||
(
|
||||
"unexpected field",
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d482",
|
||||
),
|
||||
(
|
||||
"wrong MIME",
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d483",
|
||||
),
|
||||
(
|
||||
"oversize body",
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d484",
|
||||
),
|
||||
] {
|
||||
let uri = if revision == MODERN_REVISION {
|
||||
uri.to_owned()
|
||||
} else {
|
||||
uri.replace("4372", "4373")
|
||||
};
|
||||
let calls_before_negative = upstream_calls.load(Ordering::SeqCst);
|
||||
let rejected = json_body(read_resource(&endpoint, &revision, &uri, None).await).await;
|
||||
assert!(
|
||||
rejected.get("result").is_none() && rejected.get("error").is_some(),
|
||||
"{case} binary result must fail closed on {revision}: {rejected}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_negative + 1,
|
||||
"{case} case must reach the REST response mapper on {revision}: {uri}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let calls_before_auth_profile_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
|
||||
for revision in supported_revisions() {
|
||||
let cached = json_body(
|
||||
read_resource(
|
||||
&endpoint,
|
||||
&revision,
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
|
||||
None,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
cached.get("result").is_some(),
|
||||
"the exact AuthProfile-backed response must be cached before revoke on {revision}: {cached}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_auth_profile_cache_confirmation,
|
||||
"the pre-revoke control must hit the live AuthProfile-backed cache on {revision}"
|
||||
);
|
||||
}
|
||||
let calls_before_auth_profile_revoke = upstream_calls.load(Ordering::SeqCst);
|
||||
sqlx::query("delete from auth_profiles where id = $1")
|
||||
.bind(auth_profile_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.expect("the test-owned pinned AuthProfile is revoked");
|
||||
for revision in supported_revisions() {
|
||||
let uri = "crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480";
|
||||
let revoked = json_body(read_resource(&endpoint, &revision, uri, None).await).await;
|
||||
assert!(
|
||||
revoked.get("result").is_none(),
|
||||
"a missing pinned AuthProfile must fail closed before returning cache on {revision}: {revoked}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_auth_profile_revoke,
|
||||
"revoking the pinned AuthProfile must prevent both cached return and REST dispatch"
|
||||
);
|
||||
}
|
||||
assert_eq!(binary_template, "crank://orders-binary/{order_id}");
|
||||
|
||||
let order_id = "f47ac10b-58cc-4372-a567-0e02b2c3d479";
|
||||
let expanded_uri = format!("crank://orders/{order_id}");
|
||||
let mut successful_reads = upstream_calls.load(Ordering::SeqCst);
|
||||
let mut text_cache_filled = false;
|
||||
for revision in supported_revisions() {
|
||||
let response = read_resource(&endpoint, &revision, &expanded_uri, None).await;
|
||||
let status = response.status();
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"dynamic template read failed on {revision}: {body}"
|
||||
);
|
||||
let contents = body["result"]["contents"][0]["text"]
|
||||
.as_str()
|
||||
.expect("JSON result must be returned as text content");
|
||||
let output: Value =
|
||||
serde_json::from_str(contents).expect("the upstream JSON must remain JSON content");
|
||||
assert_eq!(output["id"], order_id);
|
||||
assert_eq!(body["result"]["contents"][0]["uri"], expanded_uri);
|
||||
if !text_cache_filled {
|
||||
successful_reads += 1;
|
||||
text_cache_filled = true;
|
||||
}
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
successful_reads,
|
||||
"the second protocol revision must return the populated cache entry without another REST call"
|
||||
);
|
||||
|
||||
let expanded_head_uri = format!("crank://orders-metadata/{order_id}");
|
||||
let response = read_resource(&endpoint, &revision, &expanded_head_uri, None).await;
|
||||
let status = response.status();
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"HEAD metadata mapping failed on {revision}: {body}"
|
||||
);
|
||||
let contents = body["result"]["contents"][0]["text"]
|
||||
.as_str()
|
||||
.unwrap_or_else(|| {
|
||||
panic!("explicit HEAD metadata response must contain JSON text: {body}")
|
||||
});
|
||||
let metadata: Value =
|
||||
serde_json::from_str(contents).expect("the explicit metadata mapping remains JSON");
|
||||
assert_eq!(metadata["id"], 200);
|
||||
successful_reads += 1;
|
||||
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads);
|
||||
|
||||
let traversal = "crank://orders/%2e%2e";
|
||||
let body = json_body(read_resource(&endpoint, &revision, traversal, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"traversal-shaped template URI must not be served on {revision}: {body}"
|
||||
);
|
||||
let host_injection = format!("crank://127.0.0.1/orders/{order_id}");
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &host_injection, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"URI authority must remain fixed on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
successful_reads,
|
||||
"host injection must be rejected before REST dispatch"
|
||||
);
|
||||
|
||||
let invalid_uuid = "crank://orders/not-a-uuid";
|
||||
let body = json_body(read_resource(&endpoint, &revision, invalid_uuid, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"URI parameters must satisfy the exact published input schema on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
successful_reads,
|
||||
"invalid URI values must be rejected before REST dispatch"
|
||||
);
|
||||
}
|
||||
|
||||
let timeout_uuid = "00000000-0000-4000-8000-000000000001";
|
||||
let timeout_uri = format!("crank://orders/{timeout_uuid}");
|
||||
let response = read_resource(&endpoint, MODERN_REVISION, &timeout_uri, None).await;
|
||||
let status = response.status();
|
||||
let body = json_body(response).await;
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"runtime failures must use an MCP error response: {body}"
|
||||
);
|
||||
assert!(body.get("result").is_none());
|
||||
assert!(
|
||||
body["error"]["data"]["request_id"]
|
||||
.as_str()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
);
|
||||
assert!(
|
||||
body["error"]["data"]["trace_id"]
|
||||
.as_str()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
);
|
||||
for field in ["error_code", "stage", "retryability", "outcome_certainty"] {
|
||||
assert!(
|
||||
body["error"]["data"][field]
|
||||
.as_str()
|
||||
.is_some_and(|value| !value.is_empty()),
|
||||
"structured runtime error must include {field}: {body}"
|
||||
);
|
||||
}
|
||||
assert_eq!(upstream_calls.load(Ordering::SeqCst), successful_reads + 1);
|
||||
assert!(!body.to_string().contains(timeout_uuid));
|
||||
assert!(!body.to_string().contains("127.0.0.1"));
|
||||
|
||||
let calls_before_operation_cache_confirmation = upstream_calls.load(Ordering::SeqCst);
|
||||
for revision in supported_revisions() {
|
||||
let cached =
|
||||
json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
|
||||
assert!(
|
||||
cached.get("result").is_some(),
|
||||
"the exact Operation response must be available from cache before archive on {revision}: {cached}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_operation_cache_confirmation,
|
||||
"the pre-archive control must hit the existing cache on {revision}"
|
||||
);
|
||||
}
|
||||
|
||||
let calls_before_operation_archive = upstream_calls.load(Ordering::SeqCst);
|
||||
registry
|
||||
.archive_operation(
|
||||
&test_workspace_id(),
|
||||
&operation.id,
|
||||
&OffsetDateTime::now_utc(),
|
||||
)
|
||||
.await
|
||||
.expect("the exact pinned Operation must be archivable for the stale-snapshot regression");
|
||||
for revision in supported_revisions() {
|
||||
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"an archived source Operation must fail closed on {revision}: {body}"
|
||||
);
|
||||
assert!(
|
||||
body["error"]["data"]["request_id"]
|
||||
.as_str()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
);
|
||||
assert!(
|
||||
body["error"]["data"]["trace_id"]
|
||||
.as_str()
|
||||
.is_some_and(|id| !id.is_empty())
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_operation_archive,
|
||||
"an archived Operation must not return its live Valkey cache entry or dispatch"
|
||||
);
|
||||
}
|
||||
// Keep an independent published HEAD Operation eligible to verify real Valkey-loss fallback.
|
||||
let calls_before_valkey_loss = upstream_calls.load(Ordering::SeqCst);
|
||||
valkey.stop();
|
||||
let fallback_uri = format!("crank://orders-metadata/{order_id}");
|
||||
let fallback =
|
||||
json_body(read_resource(&endpoint, MODERN_REVISION, &fallback_uri, None).await).await;
|
||||
let fallback_text = fallback["result"]["contents"][0]["text"]
|
||||
.as_str()
|
||||
.expect("cache-loss fallback must preserve the declared HEAD metadata representation");
|
||||
let fallback_output: Value = serde_json::from_str(fallback_text).unwrap();
|
||||
assert_eq!(fallback_output["id"], 200);
|
||||
assert_eq!(fallback["result"]["contents"][0]["uri"], fallback_uri);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_before_valkey_loss + 1,
|
||||
"Valkey loss must use the eligible HEAD Operation's uncached REST path"
|
||||
);
|
||||
checks.finish();
|
||||
|
||||
// A live revoke must remove the exact template binding from future discovery.
|
||||
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-list', 'story311-list')")
|
||||
.bind(resource_id.as_str()).execute(registry.pool()).await
|
||||
.expect("the fixture revoke must be persisted");
|
||||
sqlx::query("insert into resource_security_revocations (workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id) values ('ws_default', $1, now(), 'user_default_owner', 'story311-head-list', 'story311-head-list')")
|
||||
.bind(head_resource_id.as_str()).execute(registry.pool()).await
|
||||
.expect("the HEAD template revoke must be persisted");
|
||||
let calls_after_revoke = upstream_calls.load(Ordering::SeqCst);
|
||||
for revision in supported_revisions() {
|
||||
let body = json_body(list_resource_templates(&endpoint, &revision).await).await;
|
||||
assert!(
|
||||
body["result"]["resourceTemplates"]
|
||||
.as_array()
|
||||
.is_some_and(|items| {
|
||||
items.len() == 1 && items[0]["uriTemplate"] == binary_template
|
||||
}),
|
||||
"revoked text templates must disappear while the independent binary template remains on {revision}: {body}"
|
||||
);
|
||||
let body = json_body(read_resource(&endpoint, &revision, &expanded_uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a revoked template must not be read on {revision}: {body}"
|
||||
);
|
||||
let revoked_head_uri = format!("crank://orders-metadata/{order_id}");
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &revoked_head_uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"revoked HEAD metadata must not be read on {revision}: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
calls_after_revoke,
|
||||
"revoked template read must not dispatch"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
pub(super) struct TestValkey(String);
|
||||
|
||||
impl TestValkey {
|
||||
pub(super) fn start() -> (Self, u16) {
|
||||
let output = Command::new("docker")
|
||||
.args([
|
||||
"run",
|
||||
"--detach",
|
||||
"--publish",
|
||||
"127.0.0.1::6379",
|
||||
"valkey/valkey:8-alpine",
|
||||
])
|
||||
.output()
|
||||
.expect("Docker CLI must start the test-owned Valkey container");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"test-owned Valkey must start: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let id = String::from_utf8(output.stdout)
|
||||
.expect("Docker container id must be UTF-8")
|
||||
.trim()
|
||||
.to_owned();
|
||||
let valkey = Self(id);
|
||||
let port_output = Command::new("docker")
|
||||
.args(["port", &valkey.0, "6379/tcp"])
|
||||
.output()
|
||||
.expect("Docker CLI must report the test-owned port");
|
||||
assert!(
|
||||
port_output.status.success(),
|
||||
"test-owned Valkey port must be available"
|
||||
);
|
||||
let address = String::from_utf8(port_output.stdout).expect("Docker port must be UTF-8");
|
||||
let port = address
|
||||
.trim()
|
||||
.rsplit(':')
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("Docker mapped port must be numeric");
|
||||
(valkey, port)
|
||||
}
|
||||
|
||||
pub(super) fn stop(&self) {
|
||||
let output = Command::new("docker")
|
||||
.args(["stop", &self.0])
|
||||
.output()
|
||||
.expect("Docker CLI must stop the test-owned Valkey");
|
||||
assert!(output.status.success(), "test-owned Valkey must stop");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestValkey {
|
||||
fn drop(&mut self) {
|
||||
let _ = Command::new("docker").args(["rm", "-f", &self.0]).output();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn publish_binary_template(
|
||||
registry: &PostgresRegistry,
|
||||
agent_id: &crank_core::AgentId,
|
||||
base_url: &str,
|
||||
) -> (String, crank_core::AuthProfileId) {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let secret_id = crank_core::SecretId::new("secret_story311_binary_test");
|
||||
let secret = crank_core::Secret {
|
||||
id: secret_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
name: "story311 binary test credential".to_owned(),
|
||||
kind: crank_core::SecretKind::Token,
|
||||
status: crank_core::SecretStatus::Active,
|
||||
current_version: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
last_used_at: None,
|
||||
};
|
||||
let crypto =
|
||||
crank_runtime::SecretCrypto::new("test-master-key-00000000000000000000000000000000")
|
||||
.unwrap();
|
||||
registry
|
||||
.verify_or_register_master_key_identity(crank_registry::MasterKeyIdentityCandidate {
|
||||
epoch: crypto.master_key_epoch(),
|
||||
fingerprint: crypto.master_key_fingerprint(),
|
||||
cipher_contract: crank_registry::MASTER_KEY_CIPHER_CONTRACT,
|
||||
observed_at: &now,
|
||||
})
|
||||
.await
|
||||
.expect("the test runtime master-key identity must be registered");
|
||||
let ciphertext = crypto
|
||||
.encrypt(&json!({"token":"story311-test-token"}))
|
||||
.unwrap();
|
||||
registry
|
||||
.create_secret(crank_registry::CreateSecretRequest {
|
||||
secret: &secret,
|
||||
ciphertext: &ciphertext,
|
||||
key_version: crypto.key_version(),
|
||||
master_key_epoch: crypto.master_key_epoch(),
|
||||
created_by: None,
|
||||
})
|
||||
.await
|
||||
.expect("test-owned binary auth secret must be persisted encrypted");
|
||||
let auth_profile_id = crank_core::AuthProfileId::new("auth_story311_binary_test");
|
||||
let auth_profile = crank_core::AuthProfile {
|
||||
id: auth_profile_id.clone(),
|
||||
workspace_id: test_workspace_id(),
|
||||
name: "story311 binary test auth".to_owned(),
|
||||
kind: crank_core::AuthKind::Bearer,
|
||||
config: crank_core::AuthConfig::Bearer(crank_core::BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id,
|
||||
}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
registry
|
||||
.save_auth_profile(crank_registry::SaveAuthProfileRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
profile: &auth_profile,
|
||||
})
|
||||
.await
|
||||
.expect("test auth profile must be saved in its workspace");
|
||||
|
||||
let mut operation = test_operation(base_url, "bound_order_binary");
|
||||
operation.id = OperationId::new("op_bound_order_binary");
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: base_url.to_owned(),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/orders-binary/{order_id}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: vec![RestResponseDescriptor {
|
||||
status_code: 200,
|
||||
media_type: Some("application/json".to_owned()),
|
||||
schema_variant: 0,
|
||||
}],
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("order_id");
|
||||
operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("order_id")
|
||||
.unwrap()
|
||||
.format = Some("uuid".to_owned());
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.order_id".to_owned(),
|
||||
target: "$.request.path.order_id".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
let mut output_schema = object_schema("data_base64");
|
||||
output_schema.fields.insert(
|
||||
"extra".to_owned(),
|
||||
output_schema.fields["data_base64"].clone(),
|
||||
);
|
||||
output_schema.fields.get_mut("extra").unwrap().required = false;
|
||||
operation.output_schema = output_schema;
|
||||
operation.output_mapping = MappingSet {
|
||||
rules: vec![
|
||||
MappingRule {
|
||||
source: "$.response.body.data_base64".to_owned(),
|
||||
target: "$.output.data_base64".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
},
|
||||
MappingRule {
|
||||
source: "$.response.body.extra".to_owned(),
|
||||
target: "$.output.extra".to_owned(),
|
||||
required: false,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
operation.execution_config.timeout_ms = 1_000;
|
||||
operation.execution_config.auth_profile_ref = Some(auth_profile_id.clone());
|
||||
operation.execution_config.safety = Some(OperationSafetyPolicy {
|
||||
class: OperationSafetyClass::Read,
|
||||
confirmation: None,
|
||||
});
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("binary GET Read operation must be created");
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.expect("binary operation must publish");
|
||||
|
||||
let uri_template = "crank://orders-binary/{order_id}";
|
||||
let definition_value = json!({
|
||||
"operation_id": operation.id.as_str(),
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{"name":"order_id","input_path":"input.order_id","schema":{"type":"string","required":true,"format":"uuid"}}],
|
||||
"cache": {"ttl_ms":60000,"vary":["order_id"],"max_bytes":65536},
|
||||
"failure": {"outcome":"error"}
|
||||
});
|
||||
let source = TemplateSource::parse(&definition_value).expect("binary template source is valid");
|
||||
let definition = serde_json::to_string(&source).unwrap();
|
||||
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
|
||||
let resource_id = ResourceId::new("res_bound_template_binary");
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: "crank://templates/order-binary".to_owned(),
|
||||
name: "order_binary".to_owned(),
|
||||
description: "Published binary order representation".to_owned(),
|
||||
kind: "binary".to_owned(),
|
||||
mime_type: "application/pdf".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition,
|
||||
definition_digest: digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("binary template Draft must be created");
|
||||
registry
|
||||
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: draft.snapshot.resource.updated_at,
|
||||
expected_version: draft.snapshot.version.version,
|
||||
expected_digest: digest,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("binary template must publish");
|
||||
|
||||
let published = registry
|
||||
.get_agent_version(&test_workspace_id(), agent_id, 2)
|
||||
.await
|
||||
.expect("version two agent must remain readable")
|
||||
.expect("version two agent must be published");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut agent_draft = published.snapshot.clone();
|
||||
agent_draft.version = 3;
|
||||
agent_draft.status = AgentStatus::Draft;
|
||||
agent_draft.created_at = now;
|
||||
registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
version: &agent_draft,
|
||||
bindings: &published.bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.expect("binary binding draft version must create");
|
||||
let existing_publications: Vec<(String, i32)> = sqlx::query_as(
|
||||
"select resource_id, version from resource_publications where workspace_id = $1 and resource_id in ('res_bound_template_discovery', 'res_bound_template_head', 'res_bound_template_binary')",
|
||||
)
|
||||
.bind(test_workspace_id().as_str())
|
||||
.fetch_all(registry.pool())
|
||||
.await
|
||||
.expect("published Resource versions must be discoverable for the Agent fixture");
|
||||
let resource_bindings: Vec<AgentResourceBinding> = existing_publications
|
||||
.into_iter()
|
||||
.map(|(resource_id, resource_version)| AgentResourceBinding {
|
||||
resource_id: ResourceId::new(resource_id),
|
||||
resource_version: resource_version as u32,
|
||||
})
|
||||
.collect();
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
agent_version: 3,
|
||||
bindings: &published.bindings,
|
||||
tool_selection_policy: &published.snapshot.tool_selection_policy,
|
||||
resource_bindings: &resource_bindings,
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("exact binary template version must bind to the Agent draft");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
version: 3,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent snapshot with binary binding must publish");
|
||||
(uri_template.to_owned(), auth_profile_id)
|
||||
}
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
use super::*;
|
||||
|
||||
/// A live cache hit must fall back to the exact REST read when the test-owned Valkey is lost.
|
||||
#[tokio::test]
|
||||
async fn eligible_get_resource_reads_uncached_after_valkey_loss() {
|
||||
let (valkey, port) = TestValkey::start();
|
||||
let cache = Arc::new(
|
||||
crank_runtime::RedisCacheStore::connect(
|
||||
crank_core::CacheBackend::Valkey,
|
||||
&format!("redis://127.0.0.1:{port}/0"),
|
||||
)
|
||||
.await
|
||||
.expect("runtime must connect to test-owned Valkey"),
|
||||
);
|
||||
let endpoint = standard_endpoint_with_cache("uncached_after_valkey_loss", Some(cache)).await;
|
||||
let registry = &endpoint.registry;
|
||||
let published = registry
|
||||
.get_agent_version(&test_workspace_id(), &endpoint.agent_id, 1)
|
||||
.await
|
||||
.expect("published Agent snapshot must be readable")
|
||||
.expect("published Agent version 1 must exist");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let mut agent_draft = published.snapshot.clone();
|
||||
agent_draft.version = 2;
|
||||
agent_draft.status = AgentStatus::Draft;
|
||||
agent_draft.created_at = now;
|
||||
registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: &agent_draft,
|
||||
bindings: &published.bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.expect("Agent version two Draft must be created for the template fixture");
|
||||
registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
agent_version: 2,
|
||||
bindings: &published.bindings,
|
||||
tool_selection_policy: &published.snapshot.tool_selection_policy,
|
||||
resource_bindings: &[],
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent version two catalog must be saved");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id: &endpoint.agent_id,
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("Agent version two must be published for the template fixture");
|
||||
let upstream_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
||||
.await
|
||||
.expect("test upstream must bind a loopback port");
|
||||
let upstream_address = upstream_listener.local_addr().unwrap();
|
||||
let upstream_calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = axum::Router::new()
|
||||
.route("/orders-binary/{order_id}", get(template_binary_lookup))
|
||||
.with_state(Arc::clone(&upstream_calls));
|
||||
tokio::spawn(async move {
|
||||
axum::serve(upstream_listener, upstream)
|
||||
.await
|
||||
.expect("test upstream must serve");
|
||||
});
|
||||
let (template, _auth_profile_id) = publish_binary_template(
|
||||
&endpoint.registry,
|
||||
&endpoint.agent_id,
|
||||
&format!("http://{upstream_address}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(template, "crank://orders-binary/{order_id}");
|
||||
|
||||
let expected_bytes = [0_u8, 255, 1, 253, 254, 255];
|
||||
let revision_uris = [
|
||||
(
|
||||
MODERN_REVISION,
|
||||
"crank://orders-binary/f47ac10b-58cc-4372-a567-0e02b2c3d480",
|
||||
),
|
||||
(
|
||||
LEGACY_REVISION,
|
||||
"crank://orders-binary/f47ac10b-58cc-4373-a567-0e02b2c3d480",
|
||||
),
|
||||
];
|
||||
for (revision, uri) in revision_uris {
|
||||
let before_first_read = upstream_calls.load(Ordering::SeqCst);
|
||||
for expected_calls in [before_first_read + 1, before_first_read + 1] {
|
||||
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
|
||||
assert!(
|
||||
body.get("error").is_none(),
|
||||
"eligible GET failed on {revision}: {body}"
|
||||
);
|
||||
let content = &body["result"]["contents"][0];
|
||||
assert_eq!(content["uri"], uri);
|
||||
assert_eq!(content["mimeType"], "application/pdf");
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(
|
||||
content["blob"]
|
||||
.as_str()
|
||||
.expect("binary response must carry a blob")
|
||||
)
|
||||
.expect("binary response must be valid base64"),
|
||||
expected_bytes,
|
||||
"REST bytes must remain exact on {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
expected_calls,
|
||||
"the initial REST read increments once and its live-Valkey repeat is a hit on {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
valkey.stop();
|
||||
for (revision, uri) in revision_uris {
|
||||
let before_read = upstream_calls.load(Ordering::SeqCst);
|
||||
let body = json_body(read_resource(&endpoint, revision, uri, None).await).await;
|
||||
assert!(
|
||||
body.get("error").is_none(),
|
||||
"eligible uncached GET failed on {revision}: {body}"
|
||||
);
|
||||
let content = &body["result"]["contents"][0];
|
||||
assert_eq!(content["uri"], uri);
|
||||
assert_eq!(content["mimeType"], "application/pdf");
|
||||
assert_eq!(
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(
|
||||
content["blob"]
|
||||
.as_str()
|
||||
.expect("binary response must carry a blob")
|
||||
)
|
||||
.expect("binary response must be valid base64"),
|
||||
expected_bytes,
|
||||
"REST bytes must remain exact after Valkey loss on {revision}"
|
||||
);
|
||||
assert_eq!(
|
||||
upstream_calls.load(Ordering::SeqCst),
|
||||
before_read + 1,
|
||||
"the exact eligible URI must use REST when Valkey is unavailable on {revision}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Story 3.8 AC02 / AT-3.8-02: `resources/read` returns the exact published text/JSON/binary content
|
||||
//! and MIME in the negotiated shape, with Request ID/Trace ID preserved and no content capture in
|
||||
//! telemetry.
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn check_content(
|
||||
checks: &mut RevisionChecks,
|
||||
body: &Value,
|
||||
revision: &str,
|
||||
uri: &str,
|
||||
expected_text: Option<&str>,
|
||||
expected_blob: Option<&str>,
|
||||
mime: &str,
|
||||
) {
|
||||
let Some(result) = checks.result(body, revision, "resources/read") else {
|
||||
return;
|
||||
};
|
||||
if revision != LEGACY_REVISION {
|
||||
// The pinned 2026-07-28 schema: `ReadResourceResult extends CacheableResult`.
|
||||
checks.require(result["resultType"].as_str() == Some("complete"), || {
|
||||
format!("a modern read result must carry Result.resultType=\"complete\" on {revision}: {body}")
|
||||
});
|
||||
checks.require(
|
||||
result.get("ttlMs").and_then(Value::as_u64).is_some(),
|
||||
|| {
|
||||
format!(
|
||||
"a modern read result must carry CacheableResult.ttlMs on {revision}: {body}"
|
||||
)
|
||||
},
|
||||
);
|
||||
checks.require(
|
||||
matches!(result.get("cacheScope").and_then(Value::as_str), Some("public" | "private")),
|
||||
|| format!("a modern read result must carry CacheableResult.cacheScope on {revision}: {body}"),
|
||||
);
|
||||
}
|
||||
let Some(contents) = result["contents"].as_array() else {
|
||||
checks.require(false, || {
|
||||
format!("resources/read must return contents[] on {revision}: {body}")
|
||||
});
|
||||
return;
|
||||
};
|
||||
checks.require(contents.len() == 1, || {
|
||||
format!("an exact published static version must yield exactly one content entry on {revision}: {body}")
|
||||
});
|
||||
let Some(content) = contents.first() else {
|
||||
return;
|
||||
};
|
||||
checks.require(content["uri"].as_str() == Some(uri), || {
|
||||
format!("the read content must address the requested published URI on {revision}: {body}")
|
||||
});
|
||||
checks.require(content["mimeType"].as_str() == Some(mime), || {
|
||||
format!("the read must return the published MIME type {mime} on {revision}: {body}")
|
||||
});
|
||||
if let Some(expected_text) = expected_text {
|
||||
checks.require(content["text"].as_str() == Some(expected_text), || {
|
||||
format!("the read must return the exact published text bytes on {revision}: {body}")
|
||||
});
|
||||
checks.require(content.get("blob").is_none(), || {
|
||||
format!(
|
||||
"a text/JSON Resource must not be converted to a base64 blob on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
if let Some(expected_blob) = expected_blob {
|
||||
checks.require(content["blob"].as_str() == Some(expected_blob), || {
|
||||
format!(
|
||||
"a binary Resource must be returned as the exact base64 blob on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
checks.require(content.get("text").is_none(), || {
|
||||
format!(
|
||||
"binary bytes that happen to be valid UTF-8 must still be a blob (no sniffing) on {revision}: {body}"
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_serves_the_exact_published_text_for_every_supported_revision() {
|
||||
let endpoint = standard_endpoint("read_text").await;
|
||||
let expected = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
|
||||
check_content(
|
||||
&mut checks,
|
||||
&body,
|
||||
&revision,
|
||||
&endpoint.text.uri,
|
||||
Some(&expected),
|
||||
None,
|
||||
"text/plain",
|
||||
);
|
||||
}
|
||||
checks.finish();
|
||||
}
|
||||
|
||||
/// The typed kind decides the wire conversion: text/JSON => `text`, binary => `blob` base64, with no
|
||||
/// content sniffing (the binary fixture bytes are valid UTF-8 on purpose).
|
||||
#[tokio::test]
|
||||
async fn read_converts_json_to_text_and_binary_to_base64_without_sniffing() {
|
||||
let endpoint = standard_endpoint("read_kinds").await;
|
||||
let json_text = String::from_utf8(endpoint.json.bytes.clone()).expect("JSON fixture is UTF-8");
|
||||
let json_blob = base64_of(&endpoint.json.bytes);
|
||||
let binary_blob = base64_of(&endpoint.binary.bytes);
|
||||
assert_ne!(
|
||||
json_blob, binary_blob,
|
||||
"the two fixtures must differ so a wrong content cannot pass"
|
||||
);
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
for revision in supported_revisions() {
|
||||
let json_wire =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.json.uri, None).await).await;
|
||||
check_content(
|
||||
&mut checks,
|
||||
&json_wire,
|
||||
&revision,
|
||||
&endpoint.json.uri,
|
||||
Some(&json_text),
|
||||
None,
|
||||
"application/json",
|
||||
);
|
||||
|
||||
let binary_body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
|
||||
check_content(
|
||||
&mut checks,
|
||||
&binary_body,
|
||||
&revision,
|
||||
&endpoint.binary.uri,
|
||||
None,
|
||||
Some(&binary_blob),
|
||||
"image/png",
|
||||
);
|
||||
}
|
||||
checks.finish();
|
||||
}
|
||||
|
||||
/// Request/Trace identity is preserved and the Resource content is never captured into telemetry.
|
||||
#[tokio::test]
|
||||
async fn read_preserves_request_identity_without_capturing_content_in_telemetry() {
|
||||
let endpoint = standard_endpoint("read_telemetry").await;
|
||||
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
|
||||
assert!(
|
||||
!canary.trim().is_empty(),
|
||||
"the content canary must be non-empty"
|
||||
);
|
||||
let logs = CapturedLogs::default();
|
||||
|
||||
let (body, request_id, trace_id) = {
|
||||
let _capture = logs.install();
|
||||
let response = read_resource(
|
||||
&endpoint,
|
||||
MODERN_REVISION,
|
||||
&endpoint.text.uri,
|
||||
Some("story38-read-corr"),
|
||||
)
|
||||
.await;
|
||||
let request_id = response.headers()["x-request-id"]
|
||||
.to_str()
|
||||
.expect("x-request-id header")
|
||||
.to_owned();
|
||||
let trace_id = response.headers()["x-trace-id"]
|
||||
.to_str()
|
||||
.expect("x-trace-id header")
|
||||
.to_owned();
|
||||
(json_body(response).await, request_id, trace_id)
|
||||
};
|
||||
|
||||
let mut checks = RevisionChecks::default();
|
||||
check_content(
|
||||
&mut checks,
|
||||
&body,
|
||||
MODERN_REVISION,
|
||||
&endpoint.text.uri,
|
||||
Some(&canary),
|
||||
None,
|
||||
"text/plain",
|
||||
);
|
||||
checks.require(request_id == "story38-read-corr", || {
|
||||
format!("the read response must preserve the request id, got {request_id}")
|
||||
});
|
||||
checks.require(!trace_id.is_empty(), || {
|
||||
"the read response must carry a trace id, got an empty header".to_owned()
|
||||
});
|
||||
|
||||
let captured = logs.output();
|
||||
checks.require(captured.contains("story38-read-corr"), || {
|
||||
format!("the read telemetry must keep the Request ID, captured logs: {captured}")
|
||||
});
|
||||
checks.require(captured.contains("resource read outcome"), || {
|
||||
format!("the read telemetry must record the read outcome event, captured logs: {captured}")
|
||||
});
|
||||
checks.require(
|
||||
captured.contains("outcome=\"ok\"") && captured.contains("content_bytes="),
|
||||
|| {
|
||||
format!(
|
||||
"the read telemetry must record a successful read outcome without content, captured logs: {captured}"
|
||||
)
|
||||
},
|
||||
);
|
||||
checks.require(!captured.contains(canary.trim()), || {
|
||||
format!("the read telemetry must not capture Resource content, captured logs: {captured}")
|
||||
});
|
||||
checks.finish();
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! Story 3.8 / AT-3.8-05: a revoked Resource is denied on both supported revisions, and the
|
||||
//! denial telemetry carries the correlation identity but never the Resource URI/name/MIME/digest
|
||||
//! or any content. The positive control proves the capture sink really records an allowed read.
|
||||
//!
|
||||
//! The tombstone is written with SQL into the same real schema the endpoint reads (the Admin revoke
|
||||
//! path is exercised by `admin-api`); everything else here is the unchanged production MCP path.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
async fn seed_tombstone(endpoint: &ResourceEndpoint) {
|
||||
sqlx::query(
|
||||
"insert into resource_security_revocations (
|
||||
workspace_id, resource_id, revoked_at, actor_user_id, request_id, trace_id
|
||||
) values ('ws_default', $1, now(), 'user_default_owner', 'story38-fixture', 'story38-fixture')",
|
||||
)
|
||||
.bind(endpoint.text.id.as_str())
|
||||
.execute(endpoint.registry.pool())
|
||||
.await
|
||||
.expect("the fixture tombstone must be written into the live schema");
|
||||
}
|
||||
|
||||
/// The revoked read is denied on both revisions; the captured telemetry keeps the Request ID and
|
||||
/// the safe outcome only, while the allowed read is captured as a successful outcome.
|
||||
#[tokio::test]
|
||||
async fn story38_revoked_read_and_list_telemetry_are_content_free_on_both_revisions() {
|
||||
let endpoint = standard_endpoint("revocation_telemetry").await;
|
||||
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
|
||||
seed_tombstone(&endpoint).await;
|
||||
|
||||
let denied_logs = CapturedLogs::default();
|
||||
let mut denied_bodies = Vec::new();
|
||||
{
|
||||
let _capture = denied_logs.install();
|
||||
for revision in supported_revisions() {
|
||||
let response = read_resource(
|
||||
&endpoint,
|
||||
&revision,
|
||||
&endpoint.text.uri,
|
||||
Some("story38-denied-corr"),
|
||||
)
|
||||
.await;
|
||||
denied_bodies.push((revision.clone(), json_body(response).await));
|
||||
}
|
||||
// The page must keep the other bound Resources while omitting the revoked one.
|
||||
for revision in supported_revisions() {
|
||||
let listed = json_body(list_resources(&endpoint, &revision, json!({})).await).await;
|
||||
let uris = listed["result"]["resources"]
|
||||
.as_array()
|
||||
.expect("resources/list must still return a page")
|
||||
.iter()
|
||||
.map(|resource| resource["uri"].as_str().unwrap_or_default().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(
|
||||
!uris.contains(&endpoint.text.uri),
|
||||
"{revision}: a revoked Resource must disappear from list: {uris:?}"
|
||||
);
|
||||
assert!(
|
||||
uris.contains(&endpoint.json.uri),
|
||||
"{revision}: the control Resource must stay listed: {uris:?}"
|
||||
);
|
||||
let text = listed.to_string();
|
||||
assert!(
|
||||
!text.contains(&endpoint.text.name),
|
||||
"{revision}: no revoked metadata may be listed: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (revision, body) in denied_bodies {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"{revision}: a revoked read must not return content: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["code"].as_i64(),
|
||||
Some(-32602),
|
||||
"{revision}: the pinned safe NotAvailable code must be reused: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
body["error"]["message"].as_str(),
|
||||
Some("the requested resource is not available"),
|
||||
"{revision}: the pinned safe NotAvailable message must be reused: {body}"
|
||||
);
|
||||
let text = body.to_string();
|
||||
for leak in [
|
||||
canary.trim(),
|
||||
&endpoint.text.name,
|
||||
&endpoint.text.uri,
|
||||
"text/plain",
|
||||
] {
|
||||
assert!(
|
||||
!text.contains(leak),
|
||||
"{revision}: the denial must not disclose Resource data ({leak}): {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let captured = denied_logs.output();
|
||||
assert!(
|
||||
captured.contains("story38-denied-corr"),
|
||||
"the denied read telemetry must keep the Request ID, captured: {captured}"
|
||||
);
|
||||
assert!(
|
||||
captured.contains("resource read outcome") && captured.contains("outcome=\"denied\""),
|
||||
"the denied read must record a safe denied outcome, captured: {captured}"
|
||||
);
|
||||
assert!(
|
||||
captured.contains("resource list page omitted revoked resources")
|
||||
&& captured.contains("outcome=\"filtered\"")
|
||||
&& captured.contains("revoked_omitted=1"),
|
||||
"the list page must record that one revoked entry was omitted, captured: {captured}"
|
||||
);
|
||||
for leak in [
|
||||
canary.trim(),
|
||||
endpoint.text.name.as_str(),
|
||||
endpoint.text.uri.as_str(),
|
||||
"text/plain",
|
||||
] {
|
||||
assert!(
|
||||
!captured.contains(leak),
|
||||
"the denial telemetry must not capture Resource data ({leak}), captured: {captured}"
|
||||
);
|
||||
}
|
||||
|
||||
// Positive control: the same sink records an allowed read as a successful outcome.
|
||||
let allowed_logs = CapturedLogs::default();
|
||||
let allowed = {
|
||||
let _capture = allowed_logs.install();
|
||||
json_body(
|
||||
read_resource(
|
||||
&endpoint,
|
||||
MODERN_REVISION,
|
||||
&endpoint.json.uri,
|
||||
Some("story38-allowed-corr"),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await
|
||||
};
|
||||
assert!(
|
||||
allowed.get("result").is_some(),
|
||||
"the control Resource must stay readable: {allowed}"
|
||||
);
|
||||
let allowed_captured = allowed_logs.output();
|
||||
assert!(
|
||||
allowed_captured.contains("story38-allowed-corr")
|
||||
&& allowed_captured.contains("outcome=\"ok\"")
|
||||
&& allowed_captured.contains("content_bytes="),
|
||||
"the same sink must capture an allowed read outcome, captured: {allowed_captured}"
|
||||
);
|
||||
assert!(
|
||||
!allowed_captured.contains(endpoint.text.uri.as_str()),
|
||||
"an allowed read telemetry must not capture the URI either, captured: {allowed_captured}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
//! Story 3.8 AC03 / AT-3.8-03 and AC05 safe-error cases: unknown, Draft and unbound URIs stay
|
||||
//! indistinguishable and leak no metadata, authorization rejects before any Resource lookup, the
|
||||
//! required modern name header keeps its existing validation, and a corrupt published blob fails
|
||||
//! safely instead of returning bytes.
|
||||
//!
|
||||
//! Both controls (`tools/list` on the same endpoint identity, modern `Mcp-Name` validation) are GREEN
|
||||
//! before the build: they prove the fixture's auth and dispatch are real, so a failing Resource case
|
||||
//! is a missing product capability, not a broken setup.
|
||||
//!
|
||||
//! NOT PROVEN HERE (needs a build seam, reported to TL): "artifact bytes are not read before
|
||||
//! authorization" needs an observable artifact-read hook in the MCP app. The app currently has no
|
||||
//! artifact store at all, so the suite proves the 401 happens before any Resource result but cannot
|
||||
//! observe the absence of a byte read.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use super::super::common::{initialize_session, post_jsonrpc, post_jsonrpc_with_headers};
|
||||
use super::fixtures::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_unknown_draft_and_unbound_uris_share_one_safe_outcome() {
|
||||
let endpoint = standard_endpoint("read_safe_errors").await;
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let bodies = [
|
||||
json_body(
|
||||
read_resource(
|
||||
&endpoint,
|
||||
&revision,
|
||||
"crank://resources/does-not-exist",
|
||||
None,
|
||||
)
|
||||
.await,
|
||||
)
|
||||
.await,
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.draft_uri, None).await).await,
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.unbound_uri, None).await).await,
|
||||
// A Published Resource of another workspace is not part of this Agent snapshot either.
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.foreign_uri, None).await).await,
|
||||
];
|
||||
let codes: Vec<i64> = bodies.iter().map(error_code).collect();
|
||||
assert_ne!(
|
||||
codes[0], -32601,
|
||||
"the read must be handled by the Resource product, not the unsupported-method answer on {revision}: {bodies:?}"
|
||||
);
|
||||
assert!(
|
||||
codes.iter().all(|code| *code == codes[0]),
|
||||
"unknown, Draft and unbound URIs must not be distinguishable by protocol outcome on {revision}: {:?} / {bodies:?}",
|
||||
codes
|
||||
);
|
||||
for body in &bodies {
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a denied read must not return Resource contents on {revision}: {body}"
|
||||
);
|
||||
let text = body.to_string();
|
||||
for leak in [
|
||||
endpoint.draft_name.as_str(),
|
||||
endpoint.unbound_name.as_str(),
|
||||
"draft text v1",
|
||||
"unbound text v1",
|
||||
"sha256:",
|
||||
"text/plain",
|
||||
] {
|
||||
assert!(
|
||||
!text.contains(leak),
|
||||
"the safe error must not disclose Resource metadata ({leak}) on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unauthenticated_read_is_rejected_before_any_resource_result() {
|
||||
let endpoint = standard_endpoint("read_unauthorized").await;
|
||||
let response = read_resource_without_credentials(&endpoint, &endpoint.text.uri).await;
|
||||
let status = response.status().as_u16();
|
||||
let body = response.text().await.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
status, 401,
|
||||
"an unauthenticated resources/read must be rejected with 401 before any Resource lookup: {body}"
|
||||
);
|
||||
let canary = String::from_utf8(endpoint.text.bytes.clone()).expect("text fixture is UTF-8");
|
||||
assert!(
|
||||
!body.contains(canary.trim()),
|
||||
"a rejected read must not disclose published bytes: {body}"
|
||||
);
|
||||
assert!(
|
||||
!body.contains(endpoint.text.name.as_str()),
|
||||
"a rejected read must not disclose published metadata: {body}"
|
||||
);
|
||||
|
||||
let legacy = read_resource_without_credentials_legacy(&endpoint, &endpoint.text.uri).await;
|
||||
let legacy_status = legacy.status().as_u16();
|
||||
let legacy_body = legacy.text().await.unwrap();
|
||||
assert_eq!(
|
||||
legacy_status, 401,
|
||||
"an unauthenticated legacy resources/read must be rejected with 401 as well: {legacy_body}"
|
||||
);
|
||||
assert!(
|
||||
!legacy_body.contains(canary.trim()) && !legacy_body.contains(endpoint.text.name.as_str()),
|
||||
"a rejected legacy read must not disclose published bytes or metadata: {legacy_body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// AC03: no artifact byte is opened before authorization, scope, binding or size is decided. The
|
||||
/// success at the end is the positive control that proves the counter actually observes reads.
|
||||
#[tokio::test]
|
||||
async fn read_never_touches_artifact_bytes_before_authorization_scope_or_size_denial() {
|
||||
let endpoint = standard_endpoint("read_byte_ordering").await;
|
||||
crank_artifacts::test_support::reset_artifact_reads();
|
||||
|
||||
for denied in [
|
||||
read_resource_without_credentials(&endpoint, &endpoint.text.uri).await,
|
||||
read_resource_without_credentials_legacy(&endpoint, &endpoint.text.uri).await,
|
||||
] {
|
||||
assert_eq!(
|
||||
denied.status().as_u16(),
|
||||
401,
|
||||
"a credential-less read must be denied at the transport stage"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
crank_artifacts::test_support::artifact_reads(),
|
||||
0,
|
||||
"an unauthenticated read must not touch artifact bytes"
|
||||
);
|
||||
|
||||
for revision in supported_revisions() {
|
||||
for uri in [
|
||||
"crank://resources/does-not-exist".to_owned(),
|
||||
endpoint.draft_uri.clone(),
|
||||
endpoint.unbound_uri.clone(),
|
||||
endpoint.foreign_uri.clone(),
|
||||
] {
|
||||
let body = json_body(read_resource(&endpoint, &revision, &uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a denied Resource read must not return contents on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
crank_artifacts::test_support::artifact_reads(),
|
||||
0,
|
||||
"unknown/Draft/unbound/foreign reads must not touch artifact bytes"
|
||||
);
|
||||
|
||||
// Positive control: the authorized bound read does open the published bytes.
|
||||
let allowed =
|
||||
json_body(read_resource(&endpoint, MODERN_REVISION, &endpoint.text.uri, None).await).await;
|
||||
assert!(
|
||||
allowed.get("result").is_some(),
|
||||
"the bound Resource must be served: {allowed}"
|
||||
);
|
||||
assert!(
|
||||
crank_artifacts::test_support::artifact_reads() >= 1,
|
||||
"the authorized read must be observable as an artifact read"
|
||||
);
|
||||
}
|
||||
|
||||
/// AC05 integrity: publication metadata that disagrees with the stored blob is denied from metadata
|
||||
/// alone, before any artifact byte is opened, and discloses nothing.
|
||||
///
|
||||
/// The table check constraint forbids a size claim above the artifact-store ceiling, so the in-process
|
||||
/// size ceiling is defense-in-depth and cannot be reproduced as an end-to-end oversize fixture.
|
||||
#[tokio::test]
|
||||
async fn inconsistent_publication_metadata_is_denied_before_any_artifact_read() {
|
||||
let endpoint = standard_endpoint("read_oversize").await;
|
||||
endpoint.inconsistent_text_publication_size().await;
|
||||
crank_artifacts::test_support::reset_artifact_reads();
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.text.uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"an inconsistent publication must not return contents on {revision}: {body}"
|
||||
);
|
||||
assert_ne!(
|
||||
error_code(&body),
|
||||
-32601,
|
||||
"the read must reach the Resource handler on {revision}: {body}"
|
||||
);
|
||||
let text = body.to_string();
|
||||
assert!(
|
||||
!text.contains(&endpoint.root.path().display().to_string()),
|
||||
"the safe failure must not disclose the artifact root on {revision}: {body}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains("bound text v1"),
|
||||
"the safe failure must not disclose published bytes on {revision}: {body}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains(&digest_hex(&endpoint.text.bytes)),
|
||||
"the safe failure must not disclose the published digest on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
crank_artifacts::test_support::artifact_reads(),
|
||||
0,
|
||||
"a size/integrity denial must happen before any artifact byte is read"
|
||||
);
|
||||
}
|
||||
|
||||
/// AC05 missing artifact: the read fails safely instead of serving bytes or a path.
|
||||
#[tokio::test]
|
||||
async fn missing_published_artifact_fails_safely() {
|
||||
let endpoint = standard_endpoint("read_missing").await;
|
||||
endpoint.delete_binary_blob();
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a missing published artifact must not return contents on {revision}: {body}"
|
||||
);
|
||||
assert_ne!(
|
||||
error_code(&body),
|
||||
-32601,
|
||||
"the read must reach the Resource handler on {revision}: {body}"
|
||||
);
|
||||
let text = body.to_string();
|
||||
assert!(
|
||||
!text.contains(&endpoint.root.path().display().to_string()),
|
||||
"the safe failure must not disclose the artifact root on {revision}: {body}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains(&base64_of(&endpoint.binary.bytes)),
|
||||
"the safe failure must not disclose the artifact reference on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Existing modern protocol contract: `Mcp-Name` must match `params.uri` and is validated before any
|
||||
/// handler. This control must stay GREEN after Resource registration (no handler may bypass it).
|
||||
#[tokio::test]
|
||||
async fn modern_read_name_header_is_still_validated_before_any_resource_handler() {
|
||||
let endpoint = standard_endpoint("read_name_validation").await;
|
||||
let headers = [
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "resources/read"),
|
||||
("Mcp-Name", "crank://resources/some-other-uri"),
|
||||
];
|
||||
let response = post_jsonrpc_with_headers(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
&headers,
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 41,
|
||||
"method": "resources/read",
|
||||
"params": { "uri": endpoint.text.uri, "_meta": modern_meta(MODERN_REVISION) }
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
let status = response.status().as_u16();
|
||||
let body = json_body(response).await;
|
||||
|
||||
assert_eq!(
|
||||
status, 400,
|
||||
"a mismatched Mcp-Name must be a header-validation failure: {body}"
|
||||
);
|
||||
assert_eq!(
|
||||
error_code(&body),
|
||||
-32020,
|
||||
"a mismatched Mcp-Name must keep the existing -32020 diagnostic: {body}"
|
||||
);
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a mismatched Mcp-Name must never serve Resource contents: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Same-endpoint positive control: the published tool catalog still works for the fixture Agent.
|
||||
#[tokio::test]
|
||||
async fn published_tool_listing_remains_green_on_the_same_endpoint() {
|
||||
let endpoint = standard_endpoint("read_tools_control").await;
|
||||
let session = initialize_session(&endpoint.client, &endpoint.mcp_url, &endpoint.api_key).await;
|
||||
let body = post_jsonrpc(
|
||||
&endpoint.client,
|
||||
&endpoint.mcp_url,
|
||||
&endpoint.api_key,
|
||||
Some(&session),
|
||||
json!({ "jsonrpc": "2.0", "id": 51, "method": "tools/list", "params": {} }),
|
||||
)
|
||||
.await;
|
||||
let tools = body["result"]["tools"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("tools/list must return the published catalog: {body}"));
|
||||
|
||||
assert!(
|
||||
tools
|
||||
.iter()
|
||||
.any(|tool| tool["name"].as_str() == Some(endpoint.tool_name.as_str())),
|
||||
"the fixture Agent must expose its published tool {}: {body}",
|
||||
endpoint.tool_name
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn corrupt_published_artifact_fails_safely_without_bytes_or_paths() {
|
||||
let endpoint = standard_endpoint("read_corrupt").await;
|
||||
endpoint.corrupt_binary_blob();
|
||||
|
||||
for revision in supported_revisions() {
|
||||
let body =
|
||||
json_body(read_resource(&endpoint, &revision, &endpoint.binary.uri, None).await).await;
|
||||
assert!(
|
||||
body.get("result").is_none(),
|
||||
"a corrupt published artifact must not return contents on {revision}: {body}"
|
||||
);
|
||||
let code = error_code(&body);
|
||||
assert_ne!(
|
||||
code, -32601,
|
||||
"the read must reach the Resource handler instead of the unsupported-method answer on {revision}: {body}"
|
||||
);
|
||||
let text = body.to_string();
|
||||
let root = endpoint.root.path().display().to_string();
|
||||
assert!(
|
||||
!text.contains(&root),
|
||||
"the safe failure must not disclose the artifact root on {revision}: {body}"
|
||||
);
|
||||
assert!(
|
||||
!text.contains("PNG-but-valid-utf8-bytes"),
|
||||
"the safe failure must not disclose blob bytes on {revision}: {body}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user