mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
Support explicit JSON-RPC ID policies
This commit is contained in:
1 parent
6d1c6188f3
commit
576fdd5e1a
3 files changed
+41
-15
No files matched your search
@@ -12,8 +12,12 @@ For newline-delimited transports, `read_line` bounds memory while reading; after
|
||||
line, the caller must close the stream or discard the rest of that line.
|
||||
`serde_json`'s nesting limit remains in effect. Response sizes are the caller's responsibility.
|
||||
|
||||
A valid request receives the handler's result or error with its original string, integer, or null
|
||||
ID. An omitted ID is a notification: it calls the separate notification handler and gets no reply.
|
||||
A valid request receives the handler's result or error with its original string, numeric, or null
|
||||
ID. The default accepts numeric IDs as required by [JSON-RPC 2.0](https://www.jsonrpc.org/specification#request_object),
|
||||
which discourages fractional values. Set `integer_ids_only` and clear `allow_null_ids` for
|
||||
protocols such as MCP that require integer or string IDs. A legacy server can retain its previous
|
||||
null-ID behavior independently. An omitted ID is a notification: it calls the separate notification
|
||||
handler and gets no reply.
|
||||
Malformed batch entries receive an invalid-request error; an empty batch gets one error response;
|
||||
a batch containing only notifications has no response. Invalid parameter shapes receive an
|
||||
invalid-params error for requests and no reply for notifications. The handler decides whether
|
||||
|
||||
@@ -16,11 +16,15 @@ use std::io::BufRead;
|
||||
pub struct Limits {
|
||||
pub max_message_bytes: usize,
|
||||
pub max_batch_items: usize,
|
||||
/// Reject fractional JSON numbers as IDs for protocols that require integer IDs.
|
||||
pub integer_ids_only: bool,
|
||||
/// Permit an explicit null request ID, as JSON-RPC does; some protocols prohibit it.
|
||||
pub allow_null_ids: bool,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self { max_message_bytes: 64 * 1024 * 1024, max_batch_items: 4096 }
|
||||
Self { max_message_bytes: 64 * 1024 * 1024, max_batch_items: 4096, integer_ids_only: false, allow_null_ids: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,10 +113,13 @@ pub struct Request<'a> {
|
||||
|
||||
/// Inspect a single request envelope. This validates its JSON-RPC version, method and ID;
|
||||
/// [`process`] additionally validates parameter shape before dispatching it.
|
||||
pub fn request(value: &Value) -> Option<Request<'_>> {
|
||||
pub fn request(value: &Value, limits: Limits) -> Option<Request<'_>> {
|
||||
let object = value.as_object()?;
|
||||
let id = object.get("id");
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || !id.is_none_or(|v| v.is_null() || v.is_string() || v.is_i64() || v.is_u64()) {
|
||||
let valid_id = id.is_none_or(|v| {
|
||||
(v.is_null() && limits.allow_null_ids) || v.is_string() || if limits.integer_ids_only { v.is_i64() || v.is_u64() } else { v.is_number() }
|
||||
});
|
||||
if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") || !valid_id {
|
||||
return None;
|
||||
}
|
||||
Some(Request { id, method: object.get("method")?.as_str()?, params: object.get("params") })
|
||||
@@ -150,12 +157,12 @@ fn invalid_request() -> Value {
|
||||
error_response(Value::Null, RpcError::new(-32600, "Invalid Request"))
|
||||
}
|
||||
|
||||
fn one<F, N>(value: &Value, on_request: &mut F, on_notification: &mut N) -> Option<Value>
|
||||
fn one<F, N>(value: &Value, limits: Limits, on_request: &mut F, on_notification: &mut N) -> Option<Value>
|
||||
where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
N: FnMut(Request<'_>),
|
||||
{
|
||||
let Some(request) = request(value) else { return Some(invalid_request()) };
|
||||
let Some(request) = request(value, limits) else { return Some(invalid_request()) };
|
||||
let id = request.id;
|
||||
if request.params.is_some_and(|v| !v.is_object() && !v.is_array()) {
|
||||
return id.map(|id| error_response(id.clone(), RpcError::new(-32602, "Invalid params")));
|
||||
@@ -178,13 +185,13 @@ where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
N: FnMut(Request<'_>),
|
||||
{
|
||||
let Some(batch) = value.as_array() else { return Ok(one(value, &mut on_request, &mut on_notification)) };
|
||||
let Some(batch) = value.as_array() else { return Ok(one(value, limits, &mut on_request, &mut on_notification)) };
|
||||
if batch.len() > limits.max_batch_items {
|
||||
return Err(ParseError::BatchTooLarge);
|
||||
}
|
||||
if batch.is_empty() {
|
||||
return Ok(Some(invalid_request()));
|
||||
}
|
||||
let responses: Vec<_> = batch.iter().filter_map(|v| one(v, &mut on_request, &mut on_notification)).collect();
|
||||
let responses: Vec<_> = batch.iter().filter_map(|v| one(v, limits, &mut on_request, &mut on_notification)).collect();
|
||||
Ok((!responses.is_empty()).then_some(Value::Array(responses)))
|
||||
}
|
||||
@@ -59,7 +59,7 @@ fn notifications_never_receive_responses_including_all_notification_batches() {
|
||||
|
||||
#[test]
|
||||
fn invalid_envelopes_and_params_return_standard_errors() {
|
||||
for id in [json!(1.5), json!(true), json!([]), json!({})] {
|
||||
for id in [json!(true), json!([]), json!({})] {
|
||||
let input = json!({"jsonrpc":"2.0", "id":id, "method":"ping"});
|
||||
let reply = process(&input, Limits::default(), |_| panic!("invalid id dispatched"), |_| panic!("invalid id notified")).unwrap().unwrap();
|
||||
assert_eq!(reply["id"], Value::Null);
|
||||
@@ -99,7 +99,7 @@ fn arrays_are_valid_params_and_errors_can_include_data() {
|
||||
|
||||
#[test]
|
||||
fn parse_and_batch_limits_apply_before_dispatch() {
|
||||
let limits = Limits { max_message_bytes: 3, max_batch_items: 1 };
|
||||
let limits = Limits { max_message_bytes: 3, max_batch_items: 1, ..Limits::default() };
|
||||
assert_eq!(parse_json(b"null", limits), Err(ParseError::MessageTooLarge));
|
||||
assert_eq!(parse_json(b"123", limits).unwrap(), json!(123));
|
||||
assert_eq!(parse_json(b"{", limits), Err(ParseError::InvalidJson));
|
||||
@@ -147,11 +147,26 @@ fn bounded_line_read_propagates_io_errors() {
|
||||
#[test]
|
||||
fn inspect_single_request_distinguishes_null_ids_and_invalid_envelopes() {
|
||||
let request = json!({"jsonrpc":"2.0", "id":null, "method":"ping"});
|
||||
let parsed = craft_jsonrpc::request(&request).unwrap();
|
||||
let parsed = craft_jsonrpc::request(&request, Limits::default()).unwrap();
|
||||
assert_eq!(parsed.id, Some(&Value::Null));
|
||||
assert_eq!(parsed.method, "ping");
|
||||
let notification = json!({"jsonrpc":"2.0", "method":"ping"});
|
||||
assert!(craft_jsonrpc::request(¬ification).unwrap().id.is_none());
|
||||
assert!(craft_jsonrpc::request(&json!({"jsonrpc":"2.0", "id":false, "method":"ping"})).is_none());
|
||||
assert!(craft_jsonrpc::request(&json!({"method":"ping"})).is_none());
|
||||
assert!(craft_jsonrpc::request(¬ification, Limits::default()).unwrap().id.is_none());
|
||||
assert!(craft_jsonrpc::request(&json!({"jsonrpc":"2.0", "id":false, "method":"ping"}), Limits::default()).is_none());
|
||||
assert!(craft_jsonrpc::request(&json!({"method":"ping"}), Limits::default()).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_ids_follow_the_selected_protocol_policy() {
|
||||
let input = json!({"jsonrpc":"2.0", "id":1.5, "method":"ping"});
|
||||
let reply = process(&input, Limits::default(), |_| Ok(json!({})), |_| {}).unwrap().unwrap();
|
||||
assert_eq!(reply["id"], json!(1.5));
|
||||
let strict = Limits { integer_ids_only: true, ..Limits::default() };
|
||||
let reply = process(&input, strict, |_| panic!("fractional ID dispatched"), |_| {}).unwrap().unwrap();
|
||||
assert_eq!(reply["id"], Value::Null);
|
||||
assert_eq!(reply["error"]["code"], -32600);
|
||||
let no_null = Limits { allow_null_ids: false, ..strict };
|
||||
let null_id = json!({"jsonrpc":"2.0", "id":null, "method":"ping"});
|
||||
let reply = process(&null_id, no_null, |_| panic!("null ID dispatched"), |_| {}).unwrap().unwrap();
|
||||
assert_eq!(reply["error"]["code"], -32600);
|
||||
}
|
||||
Reference in new issue
Block a user