1mod http_error;
9
10use std::net::SocketAddr;
11use std::sync::Arc;
12
13use axum::body::Bytes;
14use axum::extract::FromRequest;
15use axum::extract::Query;
16use axum::extract::Request;
17use axum::extract::State;
18use axum::http::header::CONTENT_TYPE;
19use axum::http::header::WWW_AUTHENTICATE;
20use axum::http::HeaderValue;
21use axum::http::Method;
22use axum::http::StatusCode;
23use axum::response::IntoResponse;
24use axum::response::Response;
25use axum::routing::get;
26use axum::routing::post;
27use axum::Extension;
28use axum::Router;
29use jsonrpc_core::ErrorCode;
30use jsonrpc_core::MetaIoHandler;
31use jsonrpc_core::Version;
32use rings_gateway::GatewayStatus;
33use rings_gateway::GatewayStatusHandle;
34use rings_rpc::method::AuthorizationClass;
35use serde::Deserialize;
36use serde::Serialize;
37use tokio::net::TcpListener;
38
39use self::http_error::HttpError;
40use crate::native::api_auth::ApiListener;
41use crate::native::api_auth::ApiSecurity;
42use crate::native::api_auth::NODE_VERSION_HEADER;
43use crate::observability::OperatorSnapshot;
44use crate::processor::Processor;
45
46#[derive(Clone)]
48pub struct JsonRpcState<M>
49where M: jsonrpc_core::Middleware<Arc<Processor>>
50{
51 processor: Arc<Processor>,
52 io_handler: MetaIoHandler<Arc<Processor>, M>,
53}
54
55#[derive(Clone)]
57pub struct StatusState {
58 processor: Arc<Processor>,
59}
60
61#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
63#[serde(rename_all = "snake_case")]
64enum StatusView {
65 #[default]
67 Full,
68 Observability,
70}
71
72#[derive(Debug, Default, Deserialize)]
74struct StatusQuery {
75 #[serde(default)]
77 view: StatusView,
78}
79
80#[derive(Serialize)]
82struct ObservabilityStatusResponse {
83 version: String,
85 observability: OperatorSnapshot,
87}
88
89#[derive(Clone)]
91pub struct GatewayStatusState {
92 status: GatewayStatusHandle,
93}
94
95#[derive(Clone)]
97struct ListenerSecurity {
98 policy: Arc<ApiSecurity>,
99 listener: ApiListener,
100}
101
102#[derive(Clone)]
111pub(crate) struct DecodedJsonRpc(Result<jsonrpc_core::Request, jsonrpc_core::Error>);
112
113impl DecodedJsonRpc {
114 pub(crate) fn decode(bytes: &[u8]) -> Self {
116 Self(
117 serde_json::from_slice(bytes)
118 .map_err(|_| jsonrpc_core::Error::new(ErrorCode::ParseError)),
119 )
120 }
121
122 pub(crate) fn request(&self) -> Option<&jsonrpc_core::Request> {
124 self.0.as_ref().ok()
125 }
126}
127
128struct ExternalRpcMiddleware;
129struct InternalRpcMiddleware;
130
131pub async fn run_internal_api_with_gateway(
133 port: u16,
134 processor: Arc<Processor>,
135 gateway: Option<GatewayStatusHandle>,
136 security: Arc<ApiSecurity>,
137) -> anyhow::Result<()> {
138 let gateway_configured = gateway.is_some();
139 let binding_addr = SocketAddr::from(([127, 0, 0, 1], port));
140 let axum_make_service = internal_router(processor, gateway, security)
141 .into_make_service_with_connect_info::<SocketAddr>();
142
143 println!("JSON-RPC endpoint: http://{binding_addr}");
144 if gateway_configured {
145 println!("Gateway status endpoint: http://{binding_addr}/gateway/status");
146 }
147 let listener = TcpListener::bind(binding_addr).await?;
148 axum::serve(listener, axum_make_service).await?;
149 Ok(())
150}
151
152pub async fn run_external_api(
154 addr: String,
155 processor: Arc<Processor>,
156 security: Arc<ApiSecurity>,
157) -> anyhow::Result<()> {
158 let binding_addr: SocketAddr = addr.parse()?;
159 security.validate_external_listener(binding_addr)?;
160 let axum_make_service =
161 external_router(processor, security).into_make_service_with_connect_info::<SocketAddr>();
162
163 println!("JSON-RPC endpoint: http://{addr}");
164 let listener = TcpListener::bind(binding_addr).await?;
165 axum::serve(listener, axum_make_service).await?;
166 Ok(())
167}
168
169fn internal_router(
171 processor: Arc<Processor>,
172 gateway: Option<GatewayStatusHandle>,
173 security: Arc<ApiSecurity>,
174) -> Router {
175 let jsonrpc_state = Arc::new(JsonRpcState {
176 processor: processor.clone(),
177 io_handler: MetaIoHandler::with_middleware(InternalRpcMiddleware),
178 });
179 let status_state = Arc::new(StatusState { processor });
180
181 let mut router = Router::new()
182 .route("/", post(jsonrpc_io_handler).with_state(jsonrpc_state))
183 .route("/status", get(status_handler).with_state(status_state));
184 if let Some(status) = gateway {
185 router = router.route(
186 "/gateway/status",
187 get(gateway_status_handler).with_state(Arc::new(GatewayStatusState { status })),
188 );
189 }
190 secure_router(router, security, ApiListener::Internal)
191}
192
193fn external_router(processor: Arc<Processor>, security: Arc<ApiSecurity>) -> Router {
195 let jsonrpc_state = Arc::new(JsonRpcState {
196 processor: processor.clone(),
197 io_handler: MetaIoHandler::with_middleware(ExternalRpcMiddleware),
198 });
199 let status_state = Arc::new(StatusState { processor });
200
201 let router = Router::new()
202 .route("/", post(jsonrpc_io_handler).with_state(jsonrpc_state))
203 .route("/status", get(status_handler).with_state(status_state));
204 secure_router(router, security, ApiListener::External)
205}
206
207fn secure_router(router: Router, policy: Arc<ApiSecurity>, listener: ApiListener) -> Router {
208 let cors = match listener {
209 ApiListener::Internal => policy.cors_layer(),
210 ApiListener::External => policy.external_cors_layer(),
211 };
212 router
213 .layer(axum::middleware::from_fn_with_state(
214 ListenerSecurity { policy, listener },
215 enforce_api_security,
216 ))
217 .layer(cors)
218 .layer(axum::middleware::map_response(stamp_node_version))
219}
220
221async fn stamp_node_version(mut response: Response) -> Response {
224 response.headers_mut().insert(
225 NODE_VERSION_HEADER,
226 HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
227 );
228 response
229}
230
231async fn enforce_api_security(
241 State(security): State<ListenerSecurity>,
242 mut req: Request,
243 next: axum::middleware::Next,
244) -> Response {
245 let authenticated = security.policy.authorizes(req.headers());
246 let jsonrpc = is_jsonrpc_post(&req);
247 let floor = if jsonrpc {
248 security.listener.authorization_floor()
249 } else {
250 AuthorizationClass::Gated
251 };
252 if !floor.satisfied_by(authenticated) {
253 return unauthorized();
254 }
255 if !jsonrpc {
256 return next.run(req).await;
257 }
258 if !has_json_content_type(&req) {
259 return (
260 StatusCode::UNSUPPORTED_MEDIA_TYPE,
261 "application/json required",
262 )
263 .into_response();
264 }
265 let body = std::mem::take(req.body_mut());
266 let decoded = match Bytes::from_request(Request::new(body), &()).await {
267 Ok(bytes) => DecodedJsonRpc::decode(bytes.as_ref()),
268 Err(rejection) => return rejection.into_response(),
269 };
270 let required = security.listener.required_authorization(decoded.request());
271 if !required.satisfied_by(authenticated) {
272 return unauthorized();
273 }
274 req.extensions_mut().insert(decoded);
275 next.run(req).await
276}
277
278fn unauthorized() -> Response {
279 (
280 StatusCode::UNAUTHORIZED,
281 [(WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"))],
282 "authentication required",
283 )
284 .into_response()
285}
286
287fn is_jsonrpc_post(req: &Request) -> bool {
288 req.method() == Method::POST && req.uri().path() == "/"
289}
290
291fn has_json_content_type(req: &Request) -> bool {
292 req.headers()
293 .get(CONTENT_TYPE)
294 .and_then(|value| value.to_str().ok())
295 .and_then(|value| value.split(';').next())
296 .is_some_and(|media_type| media_type.trim().eq_ignore_ascii_case("application/json"))
297}
298
299async fn jsonrpc_io_handler<M>(
300 State(state): State<Arc<JsonRpcState<M>>>,
301 Extension(DecodedJsonRpc(request)): Extension<DecodedJsonRpc>,
302) -> Result<JsonResponse, HttpError>
303where
304 M: jsonrpc_core::Middleware<Arc<Processor>>,
305{
306 let response = match request {
307 Ok(request) => {
308 if let jsonrpc_core::Request::Batch(calls) = &request {
309 if calls.len() > rings_rpc::method::MAX_JSONRPC_BATCH_CALLS {
310 return Err(HttpError::BadRequest);
311 }
312 }
313 state
314 .io_handler
315 .handle_rpc_request(request, state.processor.clone())
316 .await
317 }
318 Err(error) => Some(jsonrpc_core::Response::from(error, Some(Version::V2))),
320 };
321 let response = response.ok_or(HttpError::BadRequest)?;
322 let body = serde_json::to_string(&response).map_err(|_| HttpError::Internal)?;
323 Ok(JsonResponse(body))
324}
325
326async fn status_handler(
327 Query(query): Query<StatusQuery>,
328 State(state): State<Arc<StatusState>>,
329) -> Result<Response, HttpError> {
330 match query.view {
331 StatusView::Full => {
332 let response = state
333 .processor
334 .get_node_info()
335 .await
336 .map_err(|_| HttpError::Internal)?;
337 Ok(axum::Json(response).into_response())
338 }
339 StatusView::Observability => {
340 let observability = state
341 .processor
342 .operator_snapshot()
343 .await
344 .map_err(|_| HttpError::Internal)?;
345 let response = ObservabilityStatusResponse {
346 version: crate::util::build_version(),
347 observability,
348 };
349 Ok(axum::Json(response).into_response())
350 }
351 }
352}
353
354async fn gateway_status_handler(
355 State(state): State<Arc<GatewayStatusState>>,
356) -> axum::Json<GatewayStatus> {
357 axum::Json(state.status.snapshot())
358}
359
360#[derive(Debug, Clone)]
362pub struct JsonResponse(String);
363
364impl IntoResponse for JsonResponse {
365 fn into_response(self) -> axum::response::Response {
366 ([("content-type", "application/json")], self.0).into_response()
367 }
368}
369
370mod jsonrpc_middleware_impl {
371 use std::future::Future;
372
373 use jsonrpc_core::futures_util::future;
374 use jsonrpc_core::futures_util::future::Either;
375 use jsonrpc_core::futures_util::FutureExt;
376 use jsonrpc_core::middleware::NoopCallFuture;
377 use jsonrpc_core::middleware::NoopFuture;
378 use jsonrpc_core::*;
379 use rings_rpc::protos::rings_node_handler::ExternalRpcHandler;
380 use rings_rpc::protos::rings_node_handler::InternalRpcHandler;
381
382 use super::*;
383
384 impl Middleware<Arc<Processor>> for InternalRpcMiddleware {
385 type Future = NoopFuture;
386 type CallFuture = NoopCallFuture;
387
388 fn on_call<F, X>(
389 &self,
390 call: Call,
391 meta: Arc<Processor>,
392 next: F,
393 ) -> Either<Self::CallFuture, X>
394 where
395 F: Fn(Call, Arc<Processor>) -> X + Send + Sync,
396 X: Future<Output = Option<Output>> + Send + 'static,
397 {
398 match call {
399 Call::MethodCall(req) => {
400 let fut = InternalRpcHandler
401 .handle_request(meta, req.method, req.params.into())
402 .then(move |res| {
403 future::ready(Some(Output::from(res, req.id, req.jsonrpc)))
404 });
405 Either::Left(Box::pin(fut))
406 }
407 _ => Either::Left(Box::pin(next(call, meta))),
408 }
409 }
410 }
411
412 impl Middleware<Arc<Processor>> for ExternalRpcMiddleware {
413 type Future = NoopFuture;
414 type CallFuture = NoopCallFuture;
415
416 fn on_call<F, X>(
417 &self,
418 call: Call,
419 meta: Arc<Processor>,
420 next: F,
421 ) -> Either<Self::CallFuture, X>
422 where
423 F: Fn(Call, Arc<Processor>) -> X + Send + Sync,
424 X: Future<Output = Option<Output>> + Send + 'static,
425 {
426 match call {
427 Call::MethodCall(req) => {
428 let fut = ExternalRpcHandler
429 .handle_request(meta, req.method, req.params.into())
430 .then(move |res| {
431 future::ready(Some(Output::from(res, req.id, req.jsonrpc)))
432 });
433 Either::Left(Box::pin(fut))
434 }
435 _ => Either::Left(Box::pin(next(call, meta))),
436 }
437 }
438 }
439}
440
441#[cfg(test)]
442mod security_tests {
443 use axum::body::Body;
444 use axum::http::header::ACCESS_CONTROL_ALLOW_ORIGIN;
445 use axum::http::header::AUTHORIZATION;
446 use axum::http::header::ORIGIN;
447 use tower::ServiceExt;
448
449 use super::*;
450 use crate::tests::native::prepare_processor;
451
452 macro_rules! token {
453 () => {
454 "0123456789abcdef0123456789abcdef"
455 };
456 }
457
458 const TOKEN: &str = token!();
459 const ORIGIN_ALLOWED: &str = "https://app.example.com";
460
461 #[test]
462 fn jsonrpc_content_type_rejects_simple_cross_origin_posts() {
463 let plain = Request::builder()
464 .method(Method::POST)
465 .uri("/")
466 .header(CONTENT_TYPE, "text/plain")
467 .body(Body::empty());
468 let json = Request::builder()
469 .method(Method::POST)
470 .uri("/")
471 .header(CONTENT_TYPE, "application/json; charset=utf-8")
472 .body(Body::empty());
473 assert!(matches!(plain, Ok(request) if !has_json_content_type(&request)));
474 assert!(matches!(json, Ok(request) if has_json_content_type(&request)));
475 }
476
477 fn security() -> Option<Arc<ApiSecurity>> {
478 let origins = [ORIGIN_ALLOWED.to_string()];
479 ApiSecurity::new(TOKEN.to_string(), &origins, false)
480 .ok()
481 .map(Arc::new)
482 }
483
484 fn stub_router(listener: ApiListener) -> Router {
486 let Some(security) = security() else {
487 return Router::new();
488 };
489 let router = Router::new()
490 .route("/", post(|| async { "accepted" }))
491 .route("/status", get(|| async { "status" }))
492 .route("/gateway/status", get(|| async { "gateway status" }));
493 secure_router(router, security, listener)
494 }
495
496 fn call(method: &str) -> String {
497 format!(r#"{{"jsonrpc":"2.0","id":1,"method":"{method}","params":{{}}}}"#)
498 }
499
500 fn batch(methods: &[&str]) -> String {
501 let calls = methods.iter().copied().map(call).collect::<Vec<_>>();
502 format!("[{}]", calls.join(","))
503 }
504
505 fn jsonrpc_request(body: String) -> std::result::Result<Request, axum::http::Error> {
506 Request::builder()
507 .method(Method::POST)
508 .uri("/")
509 .header(CONTENT_TYPE, "application/json")
510 .body(Body::from(body))
511 }
512
513 fn bearer(
514 request: std::result::Result<Request, axum::http::Error>,
515 ) -> std::result::Result<Request, axum::http::Error> {
516 request.map(|mut request| {
517 request.headers_mut().insert(
518 AUTHORIZATION,
519 HeaderValue::from_static(concat!("Bearer ", token!())),
520 );
521 request
522 })
523 }
524
525 fn authorized_request(content_type: &str) -> std::result::Result<Request, axum::http::Error> {
526 bearer(
527 Request::builder()
528 .method(Method::POST)
529 .uri("/")
530 .header(CONTENT_TYPE, content_type)
531 .body(Body::from(call("nodeInfo"))),
532 )
533 }
534
535 async fn status_of(
536 router: Router,
537 request: std::result::Result<Request, axum::http::Error>,
538 ) -> Option<StatusCode> {
539 let request = request.ok()?;
540 router
541 .oneshot(request)
542 .await
543 .ok()
544 .map(|response| response.status())
545 }
546
547 #[tokio::test]
548 async fn every_listener_requires_auth_before_every_control_route() {
549 for listener in [ApiListener::Internal, ApiListener::External] {
550 for (method, path) in [
551 (Method::POST, "/"),
552 (Method::GET, "/status"),
553 (Method::GET, "/gateway/status"),
554 ] {
555 let request = Request::builder()
556 .method(method)
557 .uri(path)
558 .header(CONTENT_TYPE, "application/json")
559 .body(Body::from(call("nodeInfo")));
560 assert_eq!(
561 status_of(stub_router(listener), request).await,
562 Some(StatusCode::UNAUTHORIZED),
563 "{listener:?} route {path} was not protected"
564 );
565 }
566 }
567 }
568
569 #[tokio::test]
570 async fn external_listener_serves_the_handshake_without_a_token() {
571 for method in ["nodeDid", "answerOffer", "acceptAnswer"] {
572 assert_eq!(
573 status_of(
574 stub_router(ApiListener::External),
575 jsonrpc_request(call(method))
576 )
577 .await,
578 Some(StatusCode::OK),
579 "{method} must be public on the external listener"
580 );
581 }
582 let handshake = batch(&["nodeDid", "answerOffer", "acceptAnswer"]);
583 assert_eq!(
584 status_of(
585 stub_router(ApiListener::External),
586 jsonrpc_request(handshake)
587 )
588 .await,
589 Some(StatusCode::OK)
590 );
591 let oversized_public: Vec<&str> = (0..=rings_rpc::method::MAX_PUBLIC_BATCH_CALLS)
592 .map(|_| "nodeDid")
593 .collect();
594 assert_eq!(
595 status_of(
596 stub_router(ApiListener::External),
597 jsonrpc_request(batch(&oversized_public))
598 )
599 .await,
600 Some(StatusCode::UNAUTHORIZED),
601 "unauthenticated batch exceeding MAX_PUBLIC_BATCH_CALLS must be gated"
602 );
603 }
604
605 #[tokio::test]
606 async fn external_listener_gates_status_and_registry_reads() {
607 for method in [
608 "nodeInfo",
609 "lookupOnlineNodes",
610 "lookupOnionExits",
611 "listPeers",
612 ] {
613 assert_eq!(
614 status_of(
615 stub_router(ApiListener::External),
616 jsonrpc_request(call(method))
617 )
618 .await,
619 Some(StatusCode::UNAUTHORIZED),
620 "{method} must be gated on the external listener"
621 );
622 }
623 }
624
625 #[tokio::test]
626 async fn internal_listener_gates_every_method_including_the_handshake() {
627 for method in ["nodeDid", "answerOffer", "acceptAnswer", "nodeInfo"] {
628 assert_eq!(
629 status_of(
630 stub_router(ApiListener::Internal),
631 jsonrpc_request(call(method))
632 )
633 .await,
634 Some(StatusCode::UNAUTHORIZED),
635 "{method} must be gated on the internal listener"
636 );
637 }
638 }
639
640 #[tokio::test]
641 async fn a_batch_is_gated_by_its_strictest_member() {
642 let mixed = batch(&["nodeDid", "nodeInfo"]);
643 assert_eq!(
644 status_of(
645 stub_router(ApiListener::External),
646 jsonrpc_request(mixed.clone())
647 )
648 .await,
649 Some(StatusCode::UNAUTHORIZED)
650 );
651 assert_eq!(
652 status_of(
653 stub_router(ApiListener::External),
654 bearer(jsonrpc_request(mixed))
655 )
656 .await,
657 Some(StatusCode::OK)
658 );
659 }
660
661 #[tokio::test]
662 async fn undecodable_and_unknown_bodies_are_gated() {
663 for body in ["{}", "not json", "[]{", &call("notAMethod")] {
664 assert_eq!(
665 status_of(
666 stub_router(ApiListener::External),
667 jsonrpc_request(body.to_string())
668 )
669 .await,
670 Some(StatusCode::UNAUTHORIZED),
671 "body {body:?} must not be served without a token"
672 );
673 }
674 }
675
676 #[tokio::test]
677 async fn a_public_call_still_requires_json_content_type() {
678 let request = Request::builder()
679 .method(Method::POST)
680 .uri("/")
681 .header(CONTENT_TYPE, "text/plain")
682 .body(Body::from(call("nodeDid")));
683 assert_eq!(
684 status_of(stub_router(ApiListener::External), request).await,
685 Some(StatusCode::UNSUPPORTED_MEDIA_TYPE)
686 );
687 }
688
689 #[tokio::test]
690 async fn router_rejects_simple_content_type_and_accepts_authenticated_json() {
691 for listener in [ApiListener::Internal, ApiListener::External] {
692 assert_eq!(
693 status_of(stub_router(listener), authorized_request("text/plain")).await,
694 Some(StatusCode::UNSUPPORTED_MEDIA_TYPE)
695 );
696 assert_eq!(
697 status_of(
698 stub_router(listener),
699 authorized_request("application/json")
700 )
701 .await,
702 Some(StatusCode::OK)
703 );
704 }
705 }
706
707 #[tokio::test]
708 async fn router_emits_cors_only_for_the_configured_exact_origin() {
709 let with_origin = |origin: &'static str| {
710 authorized_request("application/json").map(|mut request| {
711 request
712 .headers_mut()
713 .insert(ORIGIN, HeaderValue::from_static(origin));
714 request
715 })
716 };
717 let allowed = stub_router(ApiListener::Internal)
718 .oneshot(with_origin(ORIGIN_ALLOWED).expect("test request must build"))
719 .await;
720 let denied = stub_router(ApiListener::Internal)
721 .oneshot(with_origin("https://attacker.example").expect("test request must build"))
722 .await;
723 assert!(matches!(
724 allowed,
725 Ok(response)
726 if response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN)
727 == Some(&HeaderValue::from_static(ORIGIN_ALLOWED))
728 ));
729 assert!(matches!(
730 denied,
731 Ok(response) if response.headers().get(ACCESS_CONTROL_ALLOW_ORIGIN).is_none()
732 ));
733
734 let preflight = Request::builder()
735 .method(Method::OPTIONS)
736 .uri("/")
737 .header(ORIGIN, "https://dapp.example")
738 .header("access-control-request-method", "POST")
739 .header("access-control-request-headers", "content-type")
740 .body(Body::empty())
741 .expect("preflight request must build");
742 let external_preflight = stub_router(ApiListener::External)
743 .oneshot(preflight)
744 .await
745 .expect("external preflight response");
746 assert!(external_preflight.status().is_success());
747 assert_eq!(
748 external_preflight
749 .headers()
750 .get(ACCESS_CONTROL_ALLOW_ORIGIN),
751 Some(&HeaderValue::from_static("*"))
752 );
753 }
754
755 async fn json_reply(
756 router: Router,
757 request: std::result::Result<Request, axum::http::Error>,
758 ) -> Option<(StatusCode, serde_json::Value)> {
759 let response = router.oneshot(request.ok()?).await.ok()?;
760 let status = response.status();
761 let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
762 .await
763 .ok()?;
764 let reply = serde_json::from_slice(bytes.as_ref()).ok()?;
765 Some((status, reply))
766 }
767
768 #[tokio::test]
772 async fn external_router_dispatches_the_decoded_public_call() {
773 let Some(security) = security() else {
774 return;
775 };
776 let processor = Arc::new(prepare_processor().await);
777 let did = processor.did().to_string();
778 let router = external_router(processor, security);
779
780 let served = json_reply(router.clone(), jsonrpc_request(call("nodeDid"))).await;
781 assert_eq!(
782 served
783 .as_ref()
784 .map(|(status, reply)| (*status, reply.pointer("/result/did"))),
785 Some((StatusCode::OK, Some(&serde_json::Value::String(did))))
786 );
787
788 let malformed = json_reply(router, bearer(jsonrpc_request("not json".to_string()))).await;
789 assert_eq!(
790 malformed
791 .as_ref()
792 .map(|(status, reply)| (*status, reply.pointer("/error/code"))),
793 Some((StatusCode::OK, Some(&serde_json::Value::from(-32700))))
794 );
795 }
796
797 #[tokio::test]
801 async fn test_the_public_node_did_call_names_the_wire_and_crate_versions() {
802 let Some(security) = security() else {
803 return;
804 };
805 let router = external_router(Arc::new(prepare_processor().await), security);
806 let crate_version = HeaderValue::from_static(env!("CARGO_PKG_VERSION"));
807
808 let served = router
809 .clone()
810 .oneshot(jsonrpc_request(call("nodeDid")).expect("test request must build"))
811 .await;
812 assert!(matches!(
813 served,
814 Ok(response) if response.headers().get(NODE_VERSION_HEADER) == Some(&crate_version)
815 ));
816 let reply = json_reply(router.clone(), jsonrpc_request(call("nodeDid"))).await;
817 assert_eq!(
818 reply
819 .as_ref()
820 .and_then(|(_, reply)| reply.pointer("/result/wire_version")),
821 Some(&serde_json::Value::from(rings_core::message::WIRE_VERSION))
822 );
823
824 let refused = router
825 .oneshot(jsonrpc_request(call("nodeInfo")).expect("test request must build"))
826 .await;
827 assert!(matches!(
828 refused,
829 Ok(response) if response.status() == StatusCode::UNAUTHORIZED
830 && response.headers().get(NODE_VERSION_HEADER) == Some(&crate_version)
831 ));
832 }
833
834 #[tokio::test]
835 async fn status_preserves_full_response_and_offers_compact_observability() {
836 let Some(security) = security() else {
837 return;
838 };
839 let processor = Arc::new(prepare_processor().await);
840 let routers = [
841 internal_router(processor.clone(), None, security.clone()),
842 external_router(processor, security),
843 ];
844 for router in &routers {
845 let response = json_reply(
846 router.clone(),
847 bearer(
848 Request::builder()
849 .method(Method::GET)
850 .uri("/status")
851 .body(Body::empty()),
852 ),
853 )
854 .await;
855 assert_eq!(
856 response.as_ref().map(|(status, _)| *status),
857 Some(StatusCode::OK)
858 );
859 assert!(response
860 .as_ref()
861 .and_then(|(_, body)| body.pointer("/version"))
862 .is_some());
863 assert!(response
864 .as_ref()
865 .and_then(|(_, body)| body.pointer("/swarm"))
866 .is_some());
867 assert!(response
868 .as_ref()
869 .and_then(|(_, body)| body.pointer("/observability"))
870 .is_none());
871 }
872
873 for router in routers {
874 let response = json_reply(
875 router,
876 bearer(
877 Request::builder()
878 .method(Method::GET)
879 .uri("/status?view=observability")
880 .body(Body::empty()),
881 ),
882 )
883 .await;
884 assert_eq!(
885 response.as_ref().map(|(status, _)| *status),
886 Some(StatusCode::OK)
887 );
888 assert!(matches!(
889 response
890 .as_ref()
891 .and_then(|(_, body)| body.pointer("/observability/schema_version")),
892 Some(serde_json::Value::Number(version)) if version.as_u64() == Some(1)
893 ));
894 assert!(response
895 .as_ref()
896 .and_then(|(_, body)| body.pointer("/version"))
897 .is_some());
898 assert!(response
899 .as_ref()
900 .and_then(|(_, body)| body.pointer("/swarm"))
901 .is_none());
902 }
903
904 for path in ["/operator/v1/observability", "/operator/v1/metrics"] {
905 let removed = bearer(
906 Request::builder()
907 .method(Method::GET)
908 .uri(path)
909 .body(Body::empty()),
910 );
911 assert_eq!(
912 status_of(stub_router(ApiListener::Internal), removed).await,
913 Some(StatusCode::NOT_FOUND)
914 );
915 }
916 }
917}