CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 27m19s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
321 lines
11 KiB
Rust
321 lines
11 KiB
Rust
//! Unit contract of Story 3.18: the pinned level vocabulary, the bounded input contract of
|
|
//! `logging/setLevel`, the request-scoped bounded event buffer and the closed safe notification
|
|
//! shape.
|
|
|
|
use serde_json::json;
|
|
|
|
use super::*;
|
|
|
|
/// Parse one `logging/setLevel` params object and validate its level, or `None` when the shape itself
|
|
/// is malformed (which the adapter answers with the same safe detail).
|
|
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
|
|
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
|
|
#[allow(deprecated)]
|
|
Some(command.validate().map(|request| request.level.into()))
|
|
}
|
|
|
|
#[test]
|
|
fn every_pinned_level_is_accepted_exactly_once_and_in_severity_order() {
|
|
// The pinned `LoggingLevel` union of both revisions, most verbose first.
|
|
let pinned = [
|
|
("debug", LogLevel::Debug),
|
|
("info", LogLevel::Info),
|
|
("notice", LogLevel::Notice),
|
|
("warning", LogLevel::Warning),
|
|
("error", LogLevel::Error),
|
|
("critical", LogLevel::Critical),
|
|
("alert", LogLevel::Alert),
|
|
("emergency", LogLevel::Emergency),
|
|
];
|
|
for (index, (literal, expected)) in pinned.iter().enumerate() {
|
|
assert_eq!(
|
|
LogLevel::parse(literal),
|
|
Some(*expected),
|
|
"{literal} is a pinned level"
|
|
);
|
|
assert_eq!(
|
|
expected.as_str(),
|
|
*literal,
|
|
"the wire literal of a level is exactly the pinned string"
|
|
);
|
|
assert_eq!(
|
|
*expected as usize, index,
|
|
"the severity ordering of {literal} must follow the RFC 5424 order"
|
|
);
|
|
assert_eq!(
|
|
validate(literal),
|
|
Some(Ok(*expected)),
|
|
"{literal} must be accepted through the wire shape too"
|
|
);
|
|
}
|
|
assert!(
|
|
pinned.windows(2).all(|pair| pair[0].1 < pair[1].1),
|
|
"severity must be strictly increasing so the filter is `event >= level`"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn nothing_outside_the_pinned_union_is_a_level() {
|
|
for value in [
|
|
"",
|
|
"warn",
|
|
"WARN",
|
|
"Info",
|
|
"information",
|
|
" debug",
|
|
"debug ",
|
|
"0",
|
|
"7",
|
|
"emergency!",
|
|
"debug\u{0}",
|
|
"информация",
|
|
] {
|
|
assert_eq!(
|
|
LogLevel::parse(value),
|
|
None,
|
|
"{value:?} is not one of the pinned literals and must never be coerced into one"
|
|
);
|
|
assert_eq!(
|
|
validate(value),
|
|
Some(Err(INVALID_LEVEL)),
|
|
"a value outside the union is a bounded invalid-params detail, got {value:?}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn malformed_level_shapes_share_one_safe_detail() {
|
|
// A `level` the schema types as a string, sent as something else: a deserialization error that the
|
|
// adapter answers with the same safe detail. It never echoes what the client sent.
|
|
for value in [json!(7), json!(1.5), json!(0)] {
|
|
assert!(
|
|
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
|
"a numeric level is not a pinned LoggingLevel"
|
|
);
|
|
}
|
|
for value in [json!(null), json!({}), json!(["info"]), json!(true)] {
|
|
assert!(
|
|
serde_json::from_value::<SetLevelCommand>(json!({ "level": value })).is_err(),
|
|
"a non-string level is not a pinned LoggingLevel"
|
|
);
|
|
}
|
|
assert!(
|
|
serde_json::from_value::<SetLevelCommand>(json!({})).is_err(),
|
|
"the pinned request requires `level`"
|
|
);
|
|
// Control: the same safe detail is what an unknown string produces, so both malformed shapes are
|
|
// indistinguishable on the wire and neither discloses what was sent.
|
|
assert_eq!(validate("verbose"), Some(Err(INVALID_LEVEL)));
|
|
assert!(
|
|
INVALID_LEVEL.len() < 64,
|
|
"the detail stays a fixed short text"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn an_oversized_level_is_refused_before_any_comparison() {
|
|
let oversized = "i".repeat(MAX_LEVEL_BYTES + 1);
|
|
assert_eq!(validate(&oversized), Some(Err(INVALID_LEVEL)));
|
|
// Positive control: the bound is not so tight that a pinned literal is refused.
|
|
assert_eq!(validate("emergency"), Some(Ok(LogLevel::Emergency)));
|
|
}
|
|
|
|
#[test]
|
|
fn the_session_opt_in_is_per_session_and_bounded() {
|
|
let store = LogLevelStore::new();
|
|
store.set("session-a", LogLevel::Error);
|
|
store.set("session-b", LogLevel::Debug);
|
|
assert_eq!(store.get("session-a"), Some(LogLevel::Error));
|
|
assert_eq!(store.get("session-b"), Some(LogLevel::Debug));
|
|
assert_eq!(
|
|
store.get("session-c"),
|
|
None,
|
|
"a session that never opted in must not inherit another session's level"
|
|
);
|
|
|
|
// The table stays bounded: filling it past the cap drops the previous opt-ins instead of growing.
|
|
for index in 0..MAX_TRACKED_SESSIONS {
|
|
store.set(&format!("filler-{index}"), LogLevel::Info);
|
|
}
|
|
store.set("session-after-cap", LogLevel::Alert);
|
|
assert_eq!(store.get("session-after-cap"), Some(LogLevel::Alert));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn an_event_is_delivered_only_at_or_above_the_opted_in_level() {
|
|
// One closed-vocabulary event per severity, recorded inside a request scope that offered SSE.
|
|
for (active, expected) in [
|
|
(LogLevel::Debug, 4usize),
|
|
(LogLevel::Info, 4),
|
|
(LogLevel::Notice, 3),
|
|
(LogLevel::Warning, 2),
|
|
(LogLevel::Error, 1),
|
|
(LogLevel::Critical, 0),
|
|
(LogLevel::Alert, 0),
|
|
(LogLevel::Emergency, 0),
|
|
] {
|
|
let delivered = scoped(async move {
|
|
set_active_level(Some(active));
|
|
set_sse_acceptable();
|
|
note(LogLevel::Info, EVENT_SERVED, "ok");
|
|
note(LogLevel::Notice, EVENT_LEVEL_APPLIED, "applied");
|
|
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
|
note(LogLevel::Error, EVENT_FAILED, "internal");
|
|
take_notifications()
|
|
})
|
|
.await;
|
|
assert_eq!(
|
|
delivered.len(),
|
|
expected,
|
|
"level {} must deliver exactly the events at or above it",
|
|
active.as_str()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn without_an_opt_in_nothing_is_even_recorded() {
|
|
// Outside a scope (no request, e.g. a background worker): a no-op.
|
|
note(LogLevel::Info, EVENT_SERVED, "ok");
|
|
assert!(take_notifications().is_empty());
|
|
|
|
// Inside a scope without an opted-in level.
|
|
let no_level = scoped(async {
|
|
set_sse_acceptable();
|
|
note(LogLevel::Error, EVENT_FAILED, "internal");
|
|
take_notifications()
|
|
})
|
|
.await;
|
|
assert!(
|
|
no_level.is_empty(),
|
|
"the pinned modern schema forbids notifications for a client that did not opt in"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_level_is_present_but_the_client_offered_no_stream() {
|
|
let delivered = scoped(async {
|
|
set_active_level(Some(LogLevel::Debug));
|
|
note(LogLevel::Error, EVENT_FAILED, "internal");
|
|
take_notifications()
|
|
})
|
|
.await;
|
|
assert!(
|
|
delivered.is_empty(),
|
|
"a JSON body has no carrier for notifications/message; the event is dropped, not smuggled in"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_buffer_is_bounded_and_drains_once() {
|
|
let (first, second) = scoped(async {
|
|
set_active_level(Some(LogLevel::Debug));
|
|
set_sse_acceptable();
|
|
for _ in 0..(MAX_PENDING_NOTIFICATIONS * 4) {
|
|
note(LogLevel::Info, EVENT_SERVED, "ok");
|
|
}
|
|
let first = take_notifications();
|
|
let second = take_notifications();
|
|
(first, second)
|
|
})
|
|
.await;
|
|
assert_eq!(
|
|
first.len(),
|
|
MAX_PENDING_NOTIFICATIONS,
|
|
"the per-response frequency bound"
|
|
);
|
|
assert!(
|
|
second.is_empty(),
|
|
"a delivered event must not survive into a later response"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn the_notification_body_is_exactly_the_closed_safe_shape() {
|
|
let delivered = scoped(async {
|
|
set_active_level(Some(LogLevel::Debug));
|
|
set_sse_acceptable();
|
|
note(LogLevel::Warning, EVENT_REJECTED, "invalid_params");
|
|
take_notifications()
|
|
})
|
|
.await;
|
|
assert_eq!(
|
|
delivered,
|
|
vec![json!({
|
|
"jsonrpc": "2.0",
|
|
"method": "notifications/message",
|
|
"params": {
|
|
"level": "warning",
|
|
"logger": "crank-mcp-server",
|
|
"data": {"event": "mcp.request.rejected", "outcome": "invalid_params"}
|
|
}
|
|
})],
|
|
"`params` carries only the severity, the fixed logger name and the closed data object"
|
|
);
|
|
// A notification has no `id`, so it can never be mistaken for a response.
|
|
assert!(delivered[0].get("id").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
|
|
let modern = |meta: Value| json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {"_meta": meta}});
|
|
assert_eq!(
|
|
modern_request_level(&modern(
|
|
json!({ "io.modelcontextprotocol/logLevel": "error" })
|
|
)),
|
|
Some(LogLevel::Error)
|
|
);
|
|
// Not opted in: an absent key, a non-string value and an unknown literal are all "no level".
|
|
assert_eq!(modern_request_level(&modern(json!({}))), None);
|
|
assert_eq!(
|
|
modern_request_level(&modern(json!({ "io.modelcontextprotocol/logLevel": 7 }))),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
modern_request_level(&modern(
|
|
json!({ "io.modelcontextprotocol/logLevel": "verbose" })
|
|
)),
|
|
None
|
|
);
|
|
// A level under another key is not the pinned carrier.
|
|
assert_eq!(
|
|
modern_request_level(&modern(json!({ "logLevel": "error" }))),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
modern_request_level(&json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})),
|
|
None
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_command_records_the_level_of_its_own_session_only() {
|
|
let store = LogLevelStore::new();
|
|
store.set("other-session", LogLevel::Debug);
|
|
// Unknown members were ignored by the legacy command; SDK metadata must not narrow that wire.
|
|
let command: SetLevelCommand = serde_json::from_value(json!({
|
|
"level": "critical", "_meta": 7, "unknown": {"private": "ignored"}
|
|
}))
|
|
.expect("a pinned level parses regardless of unknown members");
|
|
let outcome = handle_logging_command(&store, "this-session", command);
|
|
assert!(matches!(
|
|
outcome,
|
|
LoggingOutcome::Applied(LogLevel::Critical)
|
|
));
|
|
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
|
assert_eq!(
|
|
store.get("other-session"),
|
|
Some(LogLevel::Debug),
|
|
"setting one session's level must never change another client's level"
|
|
);
|
|
|
|
// A malformed level changes nothing.
|
|
let malformed: SetLevelCommand =
|
|
serde_json::from_value(json!({ "level": "verbose" })).expect("the shape parses");
|
|
assert!(matches!(
|
|
handle_logging_command(&store, "this-session", malformed),
|
|
LoggingOutcome::InvalidParams(INVALID_LEVEL)
|
|
));
|
|
assert_eq!(store.get("this-session"), Some(LogLevel::Critical));
|
|
}
|