Skip to main content

nexus_toolkit/
runtime.rs

1//! See <https://github.com/Talus-Network/gitbook-docs/blob/production/nexus-sdk/toolkit-rust.md>
2
3#[doc(hidden)]
4pub mod tls;
5
6use {
7    crate::{
8        config::Config,
9        signed_http_warp::{handle_invoke, InvokeAuth},
10        NexusTool,
11        ToolkitRuntimeConfig,
12    },
13    futures::FutureExt,
14    nexus_sdk::move_bindings::interface::meta_schema::MetaSchema,
15    reqwest::Url,
16    serde_json::json,
17    std::{panic::AssertUnwindSafe, sync::Arc},
18    warp::{
19        filters::{host::Authority, path::FullPath},
20        http::{HeaderMap, StatusCode},
21        Filter,
22        Rejection,
23        Reply,
24    },
25};
26
27/// Load toolkit configuration from environment.
28///
29/// **This is an internal function used by [bootstrap!] macro and should not be
30/// used directly.**
31#[doc(hidden)]
32pub fn load_config_() -> anyhow::Result<Arc<ToolkitRuntimeConfig>> {
33    ToolkitRuntimeConfig::from_env().map(Arc::new)
34}
35
36/// Build a placeholder URL for `--meta` output from a tool's [`NexusTool::path()`].
37///
38/// The URL is a `http://localhost`-based placeholder — the real URL is set
39/// during registration via `--url`. This function normalises the path so that
40/// a missing leading `/` does not corrupt the URL's authority component.
41///
42/// **This is an internal function used by [bootstrap!] macro and should not be
43/// used directly.**
44#[doc(hidden)]
45pub fn meta_placeholder_url_(path: &str) -> Url {
46    let base = if path.is_empty() {
47        "http://localhost/".to_string()
48    } else if path.starts_with('/') {
49        format!("http://localhost{path}")
50    } else {
51        format!("http://localhost/{path}")
52    };
53    Url::parse(&base).expect("placeholder URL must be valid")
54}
55
56fn json_bytes_or_fallback(status: StatusCode, value: serde_json::Value) -> (StatusCode, Vec<u8>) {
57    match serde_json::to_vec(&value) {
58        Ok(body) => (status, body),
59        Err(e) => {
60            let fallback = json!({
61                "error": "serialization_error",
62                "details": e.to_string(),
63            });
64            let body = serde_json::to_vec(&fallback)
65                .unwrap_or_else(|_| br#"{"error":"serialization_error"}"#.to_vec());
66            (StatusCode::INTERNAL_SERVER_ERROR, body)
67        }
68    }
69}
70
71/// Macro to bootstrap the runtime for a set of tools. The macro generates the
72/// necessary routes for each tool and serves them on the provided address.
73///
74/// # Signed HTTP (Leader <-> Tool authentication)
75/// The runtime can optionally require signed `/invoke` requests and sign the responses.
76///
77/// Configuration is file-based and loaded from [`crate::ENV_TOOLKIT_CONFIG_PATH`]. The file schema
78/// is documented on [`crate::ToolkitRuntimeConfig`].
79///
80/// When enabled (`signed_http.mode = "required"`), the runtime:
81/// - Rejects unsigned or invalidly signed `/invoke` requests (fail-closed).
82/// - Verifies the Leader signature against a local allowlist (`allowed_leaders` / `allowed_leaders_path`).
83/// - Optionally requires each Tool's directly observed TLS peer key to match the allowlisted Leader key.
84/// - Caches completed responses by deterministic nonce and canonical input hash; in-flight nonce reuse is rejected.
85/// - Returns exact ordered BCS Tool output bytes and signs the nonce-bound v3 Tool response message.
86/// - Keeps nonce replay and cached-response handling entirely offchain.
87///
88/// Operational note: your gateway/proxy must forward the `X-Nexus-Sig-*` headers in both directions.
89/// The request body, nonce, and unsigned identity headers require authenticated HTTPS transport.
90/// Set both `NEXUS_TOOL_TLS_CERT_PATH` and `NEXUS_TOOL_TLS_KEY_PATH` to terminate TLS in the
91/// Toolkit; setting only one, or invalid TLS credentials, prevents startup. Plain HTTP is served
92/// only when neither is set, which is intended solely for hosts that terminate HTTPS in front of
93/// the Toolkit (e.g. Cloud Run or a load balancer). The Leader only calls `https://` Tool URLs,
94/// so a Tool exposed directly over plain HTTP is never invoked.
95/// If a Tool enables `require_client_certificate`, TLS must terminate in Toolkit or pass through
96/// the gateway; forwarded certificate headers do not establish identity. With that option disabled,
97/// a gateway may terminate the Leader's TLS connection and use HTTPS to connect to the Toolkit.
98///
99/// ## Example config
100/// ```json
101/// {
102///   "signed_http": {
103///     "mode": "required",
104///     "allowed_leaders_path": "./allowed_leaders.json",
105///     "tools": {
106///       "xyz.dummy.tool@1": {
107///         "response_signing_key": "0000000000000000000000000000000000000000000000000000000000000000",
108///         "replay_cache_ttl_ms": 300000
109///       }
110///     }
111///   }
112/// }
113/// ```
114///
115/// ## `--meta` flag
116/// When the binary is invoked with `--meta`, the macro prints a JSON array of
117/// tool metadata (one entry per tool) to stdout and exits immediately — no HTTP
118/// server is started. This is used by CI pipelines to extract registration data
119/// from a Docker image without running the tool.
120///
121/// ```shell
122/// ./my-tool --meta   # prints JSON array and exits
123/// ```
124///
125/// ## Request body limits
126/// `/invoke` enforces a `Content-Length` limit via `warp::body::content_length_limit`.
127/// Requests without a `Content-Length` header are rejected.
128///
129/// # Invocation errors and timeouts
130///
131/// The runtime catches unwinding panics during input decoding, tool construction,
132/// authorization, invocation, and output serialization. It returns a generic
133/// HTTP 500 response without the panic payload or a tool result signature.
134///
135/// Recovery requires `panic = "unwind"` (Cargo's default). The final application's
136/// workspace controls this setting; with `panic = "abort"`, a panic terminates the process.
137///
138/// Invocation deadlines follow [`NexusTool::timeout()`].
139///
140/// # Examples
141///
142/// ### One tool running on `127.0.0.1:8080`
143///
144/// ```ignore
145/// use nexus_toolkit::bootstrap;
146///
147/// #[tokio::main]
148/// async fn main() {
149///     bootstrap!(YourTool);
150/// }
151/// ```
152///
153/// ### Multiple tools running on `127.0.0.1:8080`
154///
155/// ```ignore
156/// use nexus_toolkit::bootstrap;
157///
158/// #[tokio::main]
159/// async fn main() {
160///     bootstrap!([YourTool, AnotherTool]);
161/// }
162/// ```
163///
164/// ### One tool running on the provided address
165///
166/// ```ignore
167/// use nexus_toolkit::bootstrap;
168///
169/// #[tokio::main]
170/// async fn main() {
171///     bootstrap!(([127, 0, 0, 1], 8081), YourTool);
172/// }
173/// ```
174///
175/// ### Multiple tools running on the provided address
176///
177/// ```ignore
178/// use nexus_toolkit::bootstrap;
179///
180/// #[tokio::main]
181/// async fn main() {
182///     bootstrap!(([127, 0, 0, 1], 8081), [YourTool, AnotherTool]);
183/// }
184/// ```
185#[macro_export]
186macro_rules! bootstrap {
187    (@get_addr) => {{
188        let addr_str = std::env::var("BIND_ADDR")
189            .unwrap_or_else(|_| "127.0.0.1:8080".to_string());
190        addr_str
191            .parse::<std::net::SocketAddr>()
192            .expect("Invalid socket address in BIND_ADDR")
193    }};
194    ($addr:expr, [$tool:ty $(, $next_tool:ty)* $(,)?]) => {{
195        let _ = $crate::env_logger::try_init();
196
197        // Handle --meta: print tool metadata as a JSON array and exit
198        // without starting the HTTP server. Used by CI to extract
199        // registration data from a Docker image. Uses `return` to exit
200        // the enclosing function (typically `main`).
201        if ::std::env::args().any(|a| a == "--meta") {
202            let meta = $crate::serde_json::json!([
203                <$tool as $crate::NexusTool>::meta(
204                    $crate::runtime::meta_placeholder_url_(<$tool as $crate::NexusTool>::path())
205                )
206                $(
207                    , <$next_tool as $crate::NexusTool>::meta(
208                        $crate::runtime::meta_placeholder_url_(<$next_tool as $crate::NexusTool>::path())
209                    )
210                )*
211            ]);
212
213            println!("{}", $crate::serde_json::to_string_pretty(&meta)
214                .expect("meta serialization must not fail"));
215            return;
216        }
217
218        use {
219            ::std::sync::Arc,
220            $crate::warp::{http::StatusCode, Filter},
221        };
222
223        // Load toolkit config (shared across all tool routes).
224        let toolkit_cfg = $crate::runtime::load_config_()
225            .expect("Failed to load Nexus toolkit config");
226
227        // Create routes for each Tool in the bundle.
228        let routes = $crate::runtime::routes_for_with_config_::<$tool>(toolkit_cfg.clone());
229        $(
230            let routes = routes.or(
231                $crate::runtime::routes_for_with_config_::<$next_tool>(toolkit_cfg.clone())
232            );
233        )*
234
235        // Collect paths of all tools.
236        let mut paths = vec![<$tool as $crate::NexusTool>::path()];
237        $(
238            paths.push(<$next_tool as $crate::NexusTool>::path());
239        )*
240
241        // Add a default health route in case there is none in the root.
242        let default_health_route = $crate::warp::get()
243            .and($crate::warp::path("health"))
244            .map(|| {
245                $crate::warp::reply::with_status($crate::warp::reply(), StatusCode::OK)
246            });
247
248        // Add a default tools route to list all tools available at that webserver.
249        let default_tools_route = $crate::warp::get()
250            .and($crate::warp::path("tools"))
251            .map(move || $crate::warp::reply::json(&paths));
252
253        let routes = routes
254            .or(default_health_route)
255            .or(default_tools_route)
256            .boxed();
257        match $crate::runtime::tls::Config::from_env()
258            .expect("Invalid Nexus Tool TLS configuration")
259        {
260            // Plaintext is only valid behind an external HTTPS terminator; the
261            // Leader never calls http:// Tool URLs.
262            $crate::runtime::tls::Config::Disabled => {
263                $crate::log::warn!(
264                    "Nexus Tool TLS is disabled; the Tool must sit behind an external HTTPS terminator"
265                );
266                $crate::warp::serve(routes).run($addr).await
267            }
268            $crate::runtime::tls::Config::Enabled { cert_path, key_path } => {
269                let (_, incoming) =
270                    $crate::runtime::tls::bind($addr.into(), cert_path, key_path)
271                        .await
272                        .expect("Failed to start Nexus Tool TLS server");
273                $crate::runtime::tls::serve(routes, incoming).await
274            }
275        }
276    }};
277    // Default address.
278    ([$($tool:ty),+ $(,)?]) => {{
279        let addr = bootstrap!(@get_addr);
280        bootstrap!(addr, [$($tool,)*])
281    }};
282    // Only 1 tool.
283    ($addr:expr, $tool:ty) => {{
284        bootstrap!($addr, [$tool])
285    }};
286    // Only 1 tool with default address.
287    ($tool:ty) => {{
288        let addr = bootstrap!(@get_addr);
289        bootstrap!(addr, [$tool])
290    }};
291}
292
293/// This function generates the necessary routes for a given [NexusTool] using an already-loaded
294/// [`ToolkitRuntimeConfig`].
295///
296/// This exists so callers (like [`bootstrap!`]) can load and validate config once per process and
297/// share it across multiple tool route bundles.
298#[doc(hidden)]
299pub fn routes_for_with_config_<T: NexusTool>(
300    toolkit_cfg: Arc<ToolkitRuntimeConfig>,
301) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
302    // Wrap config with file watching support
303    let config = Config::from_config(toolkit_cfg.clone());
304    // Force output schema to be an enum.
305    let output_schema = json!(schemars::schema_for!(T::Output));
306
307    if output_schema["oneOf"].is_null() {
308        panic!("The output type must be an enum to generate the correct output schema.");
309    }
310
311    let base_path = T::path()
312        .split("/")
313        .filter(|s| !s.is_empty())
314        .fold(warp::any().boxed(), |filter, segment| {
315            filter.and(warp::path(segment.to_string())).boxed()
316        });
317
318    let health_route = warp::get()
319        .and(base_path.clone())
320        .and(warp::path("health"))
321        .and_then(health_handler::<T>);
322
323    // Meta path is tool base URL path and `/meta`.
324    let meta_route = warp::get()
325        .and(base_path.clone())
326        .and(warp::path("meta"))
327        .and(warp::header::optional::<Authority>("X-Forwarded-Host"))
328        .and(warp::filters::host::optional())
329        .and(warp::path::full())
330        .and_then(meta_handler::<T>);
331
332    let invoke_max_body_bytes = toolkit_cfg.invoke_max_body_bytes();
333
334    let tool_id = T::fqn().to_string();
335    let invoke_auth = InvokeAuth::new_sync(config, tool_id, T::timeout())
336        .expect("Failed to load signed HTTP configuration");
337
338    // Invoke path is tool base URL path and `/invoke`.
339    let invoke_route = warp::post()
340        .and(base_path)
341        .and(warp::path("invoke"))
342        .and(warp::filters::ext::optional::<tls::TlsPeerIdentity>())
343        .and(warp::header::headers_cloned())
344        .and(warp::body::content_length_limit(invoke_max_body_bytes))
345        .and(warp::body::bytes())
346        .and(warp::any().map(move || invoke_auth.clone()))
347        .and_then(invoke_handler::<T>);
348
349    health_route.or(meta_route).or(invoke_route)
350}
351
352async fn health_handler<T: NexusTool>() -> Result<impl Reply, Rejection> {
353    let tool = T::new().await;
354
355    let status = tool
356        .health()
357        .await
358        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
359
360    Ok(warp::reply::with_status(warp::reply(), status))
361}
362
363async fn meta_handler<T: NexusTool>(
364    x_forwarded_host: Option<Authority>,
365    host: Option<Authority>,
366    path: FullPath,
367) -> Result<impl Reply, Rejection> {
368    // We always need the most "external" host, as this is what will be called by users.
369    let host = x_forwarded_host.or(host);
370
371    // If the host is malformed or not present, return a 400.
372    let host = match host {
373        Some(host) => host,
374        None => {
375            let reply = json!({
376                "error": "host_header_required",
377                "details": "Host header is required.",
378            });
379
380            return Ok(warp::reply::with_status(
381                warp::reply::json(&reply),
382                StatusCode::BAD_REQUEST,
383            ));
384        }
385    };
386
387    // Stripping 'meta' suffix from the path will give us the base path.
388    let base_path = match path.as_str().strip_suffix("meta") {
389        Some(base_path) => base_path,
390        None => {
391            // This is probably never reached as we create the endpoints
392            // ourselves.
393            let reply = json!({
394                "error": "invalid_path",
395                "details": "Meta path must end with '/meta'.",
396            });
397
398            return Ok(warp::reply::with_status(
399                warp::reply::json(&reply),
400                StatusCode::BAD_REQUEST,
401            ));
402        }
403    };
404
405    // Metadata always advertises the external HTTPS endpoint.
406    let url = match Url::parse(&format!("https://{host}{base_path}")) {
407        Ok(url) => url,
408        Err(e) => {
409            let reply = json!({
410                "error": "url_parsing_error",
411                "details": e.to_string(),
412            });
413
414            return Ok(warp::reply::with_status(
415                warp::reply::json(&reply),
416                StatusCode::BAD_REQUEST,
417            ));
418        }
419    };
420
421    Ok(warp::reply::with_status(
422        warp::reply::json(&T::meta(url)),
423        StatusCode::OK,
424    ))
425}
426
427/// Result of the tool invocation pipeline before being turned into an HTTP response.
428struct InvokePipelineResponse {
429    status: StatusCode,
430    body: Vec<u8>,
431    is_result: bool,
432}
433
434impl InvokePipelineResponse {
435    fn json(status: StatusCode, value: serde_json::Value) -> Self {
436        let (status, body) = json_bytes_or_fallback(status, value);
437        Self {
438            status,
439            body,
440            is_result: false,
441        }
442    }
443}
444
445/// Tool invocation pipeline returning canonical BCS result bytes or a local JSON error.
446struct InvokePipeline;
447
448impl InvokePipeline {
449    async fn run<T: NexusTool>(
450        body_bytes: &[u8],
451        auth_ctx: Option<crate::AuthContext>,
452    ) -> InvokePipelineResponse {
453        let invocation =
454            AssertUnwindSafe(Self::run_inner::<T>(body_bytes, auth_ctx)).catch_unwind();
455        match tokio::time::timeout(T::timeout(), invocation).await {
456            Ok(Ok(response)) => response,
457            Ok(Err(_)) => {
458                log::error!("Tool invocation panicked");
459                InvokePipelineResponse::json(
460                    StatusCode::INTERNAL_SERVER_ERROR,
461                    json!({"error": "tool_invocation_failed"}),
462                )
463            }
464            Err(_) => InvokePipelineResponse::json(
465                StatusCode::GATEWAY_TIMEOUT,
466                json!({"error": "tool_invocation_timeout"}),
467            ),
468        }
469    }
470
471    async fn run_inner<T: NexusTool>(
472        body_bytes: &[u8],
473        auth_ctx: Option<crate::AuthContext>,
474    ) -> InvokePipelineResponse {
475        let input = match decode_tool_input::<T>(body_bytes, auth_ctx.as_ref()) {
476            Ok(value) => value,
477            Err(ToolInputDecodeError::Integrity) => {
478                return InvokePipelineResponse::json(
479                    StatusCode::UNPROCESSABLE_ENTITY,
480                    json!({
481                        "error": "input_integrity_error",
482                        "details": "resolved Tool input does not match authenticated input hash",
483                    }),
484                );
485            }
486            Err(ToolInputDecodeError::Deserialization(e)) => {
487                return InvokePipelineResponse::json(
488                    StatusCode::UNPROCESSABLE_ENTITY,
489                    json!({
490                        "error": "input_deserialization_error",
491                        "details": e.to_string(),
492                    }),
493                );
494            }
495        };
496
497        let tool = T::new().await;
498
499        if let Some(ctx) = auth_ctx {
500            if let Err(e) = tool.authorize(ctx).await {
501                return InvokePipelineResponse::json(
502                    StatusCode::FORBIDDEN,
503                    json!({
504                        "error": "permission_denied",
505                        "details": e.to_string(),
506                    }),
507                );
508            }
509        }
510
511        let output = tool.invoke(input).await;
512
513        match T::encode_output(output).and_then(|output| {
514            let schema = MetaSchema::from_offchain_json_schemas(
515                &serde_json::to_vec(&schemars::schema_for!(T::Input))?,
516                &serde_json::to_vec(&schemars::schema_for!(T::Output))?,
517            )?;
518            schema.canonical_output_ports(&output)?;
519            Ok(bcs::to_bytes(&output)?)
520        }) {
521            Ok(body) => InvokePipelineResponse {
522                status: StatusCode::OK,
523                body,
524                is_result: true,
525            },
526            Err(e) => InvokePipelineResponse::json(
527                StatusCode::INTERNAL_SERVER_ERROR,
528                json!({
529                    "error": "output_serialization_error",
530                    "details": e.to_string(),
531                }),
532            ),
533        }
534    }
535}
536
537enum ToolInputDecodeError {
538    Deserialization(anyhow::Error),
539    Integrity,
540}
541
542fn decode_tool_input<T: NexusTool>(
543    body_bytes: &[u8],
544    auth_ctx: Option<&crate::AuthContext>,
545) -> Result<T::Input, ToolInputDecodeError> {
546    let schema = MetaSchema::from_offchain_json_schemas(
547        &serde_json::to_vec(&schemars::schema_for!(T::Input))
548            .map_err(anyhow::Error::from)
549            .map_err(ToolInputDecodeError::Deserialization)?,
550        &serde_json::to_vec(&schemars::schema_for!(T::Output))
551            .map_err(anyhow::Error::from)
552            .map_err(ToolInputDecodeError::Deserialization)?,
553    )
554    .map_err(ToolInputDecodeError::Deserialization)?;
555    let resolved_inputs = serde_json::from_slice::<serde_json::Value>(body_bytes)
556        .map_err(anyhow::Error::from)
557        .and_then(|value| schema.resolved_inputs_from_json(&value))
558        .map_err(ToolInputDecodeError::Deserialization)?;
559    if let Some(auth_ctx) = auth_ctx {
560        if schema.resolved_inputs_sha256(&resolved_inputs).ok() != Some(auth_ctx.input_hash) {
561            return Err(ToolInputDecodeError::Integrity);
562        }
563    }
564    serde_json::from_value::<crate::WithSerdeErrorPath<T::Input>>(
565        schema
566            .resolved_inputs_to_semantic_json(&resolved_inputs)
567            .map_err(ToolInputDecodeError::Deserialization)?,
568    )
569    .map(|value| value.0)
570    .map_err(|error| ToolInputDecodeError::Deserialization(error.into()))
571}
572
573#[cfg(test)]
574fn encode_tagged_output<T: serde::Serialize>(output: T) -> anyhow::Result<Vec<u8>> {
575    Ok(bcs::to_bytes(
576        &nexus_sdk::types::OffchainToolOutput::from_json(serde_json::to_value(
577            crate::WithSerdeErrorPath(output),
578        )?)?,
579    )?)
580}
581
582async fn invoke_handler<T: NexusTool>(
583    tls_peer: Option<tls::TlsPeerIdentity>,
584    headers: HeaderMap,
585    body: bytes::Bytes,
586    auth: InvokeAuth,
587) -> Result<warp::reply::Response, Rejection> {
588    let body_bytes = body.to_vec();
589
590    let auth_runtime = auth.current().await;
591    Ok(handle_invoke(
592        &auth_runtime,
593        auth.replay(),
594        &T::fqn().to_string(),
595        headers,
596        body_bytes,
597        tls_peer.and_then(|peer| peer.public_key()),
598        |auth_ctx, body_bytes| async move {
599            let pipeline = InvokePipeline::run::<T>(&body_bytes, auth_ctx).await;
600            (pipeline.status, pipeline.body, pipeline.is_result)
601        },
602    )
603    .await)
604}
605
606#[cfg(test)]
607mod tests {
608    use {
609        super::*,
610        nexus_sdk::{
611            fqn,
612            signed_http::v3::wire::AuthenticatedRequest,
613            types::{NexusData, OffchainToolOutput},
614            ToolFqn,
615        },
616        schemars::JsonSchema,
617        serde::{Deserialize, Serialize},
618        serde_json::json,
619    };
620
621    #[test]
622    fn signed_http_configuration_is_independent_of_listener_tls_configuration() {
623        let required = ToolkitRuntimeConfig::from_json_str(
624            r#"{
625                "signed_http": {
626                    "mode": "required",
627                    "allowed_leaders": {
628                        "version": 1,
629                        "leaders": [{
630                            "leader_id": "leader",
631                            "keys": [{"kid": 0, "public_key": "0000000000000000000000000000000000000000000000000000000000000000"}]
632                        }]
633                    },
634                    "tools": {"xyz.test@1": {}}
635                }
636            }"#,
637        )
638        .unwrap();
639        assert!(required.signed_http_is_required());
640
641        let unsigned = ToolkitRuntimeConfig::from_json_str("{}").unwrap();
642        assert!(!unsigned.signed_http_is_required());
643    }
644
645    fn resolved_input(port_name: &str, value: serde_json::Value) -> serde_json::Value {
646        let value = NexusData::inline_data(serde_json::to_vec(&value).unwrap()).unwrap();
647        json!({
648            "ports": [{
649                "port_name": port_name,
650                "value": value.to_json_value().unwrap(),
651            }],
652        })
653    }
654
655    #[derive(Deserialize, JsonSchema)]
656    struct Input {
657        message: String,
658    }
659
660    #[derive(Serialize, JsonSchema)]
661    enum Output {
662        Ok {
663            message: String,
664            count: u64,
665            flags: Vec<bool>,
666            metadata: serde_json::Value,
667        },
668    }
669
670    #[derive(Serialize)]
671    enum DirectErrOutput {
672        #[serde(rename = "_err_eval")]
673        ErrEval { reason: String },
674    }
675
676    struct TestTool;
677
678    impl NexusTool for TestTool {
679        type Input = Input;
680        type Output = Output;
681
682        fn description() -> &'static str {
683            "Returns a structured test response."
684        }
685
686        fn fqn() -> ToolFqn {
687            fqn!("xyz.taluslabs.test@1")
688        }
689
690        async fn new() -> Self {
691            Self
692        }
693
694        async fn invoke(&self, input: Self::Input) -> Self::Output {
695            Output::Ok {
696                message: input.message,
697                count: 2,
698                flags: vec![true, false],
699                metadata: json!({"source": "test"}),
700            }
701        }
702
703        async fn health(&self) -> anyhow::Result<StatusCode> {
704            Ok(StatusCode::OK)
705        }
706    }
707
708    #[test]
709    fn tool_output_encodes_as_ordered_offchain_output() {
710        let bytes = encode_tagged_output(Output::Ok {
711            message: "hello".to_string(),
712            count: 2,
713            flags: vec![true, false],
714            metadata: json!({"source": "test"}),
715        })
716        .unwrap();
717        let output: OffchainToolOutput = bcs::from_bytes(&bytes).unwrap();
718
719        assert_eq!(bcs::to_bytes(&output).unwrap(), bytes);
720        assert_eq!(output.tag, b"Ok");
721        assert_eq!(
722            output
723                .ports
724                .iter()
725                .map(|port| port.port_name.as_slice())
726                .collect::<Vec<_>>(),
727            vec![
728                b"message".as_slice(),
729                b"count".as_slice(),
730                b"flags".as_slice(),
731                b"metadata".as_slice(),
732            ]
733        );
734
735        let message = NexusData::from_values(output.ports[0].values.clone(), false).unwrap();
736        assert_eq!(message.inline_data_bytes(), Some(br#""hello""#.to_vec()));
737
738        let flags = NexusData::from_values(output.ports[2].values.clone(), true).unwrap();
739        assert_eq!(
740            flags
741                .values()
742                .unwrap()
743                .into_iter()
744                .map(|value| match value {
745                    nexus_sdk::move_bindings::primitives::data::NexusValue::InlineData {
746                        bytes,
747                    } => bytes.clone(),
748                    _ => panic!("flags should be inline Data"),
749                })
750                .collect::<Vec<_>>(),
751            vec![b"true".to_vec(), b"false".to_vec()]
752        );
753
754        let metadata = NexusData::from_values(output.ports[3].values.clone(), false).unwrap();
755        assert_eq!(
756            metadata.inline_data_bytes(),
757            Some(br#"{"source":"test"}"#.to_vec())
758        );
759    }
760
761    #[test]
762    fn direct_err_eval_encodes_exact_named_signed_output() {
763        let bytes = encode_tagged_output(DirectErrOutput::ErrEval {
764            reason: "forced failure".to_string(),
765        })
766        .unwrap();
767        let output: OffchainToolOutput = bcs::from_bytes(&bytes).unwrap();
768
769        assert_eq!(output.tag, b"_err_eval");
770        assert_eq!(output.ports.len(), 1);
771        assert_eq!(output.ports[0].port_name, b"reason");
772        let reason = NexusData::from_values(output.ports[0].values.clone(), false).unwrap();
773        assert_eq!(
774            reason.inline_data_bytes(),
775            Some(br#""forced failure""#.to_vec())
776        );
777    }
778
779    #[test]
780    fn canonical_response_encoding_rejects_non_enum_shapes() {
781        assert!(encode_tagged_output(json!("plain value"))
782            .unwrap_err()
783            .to_string()
784            .contains("externally tagged enum"));
785        assert!(encode_tagged_output(json!({"Ok": {}, "Err": {}}))
786            .unwrap_err()
787            .to_string()
788            .contains("exactly one variant"));
789        assert!(encode_tagged_output(json!({"Ok": 1}))
790            .unwrap_err()
791            .to_string()
792            .contains("payload must be an object"));
793    }
794
795    #[test]
796    fn array_payloads_encode_each_json_value() {
797        let port_data = |value| -> anyhow::Result<NexusData> {
798            let output = OffchainToolOutput::from_json(json!({"ok":{"items":value}}))?;
799            NexusData::from_values(output.ports[0].values.clone(), true)
800        };
801        let inline_values = |data: &NexusData| {
802            data.values()
803                .expect("encoded Toolkit output should decode")
804                .into_iter()
805                .map(|element| match element {
806                    nexus_sdk::move_bindings::primitives::data::NexusValue::InlineData {
807                        bytes,
808                    } => bytes.clone(),
809                    _ => panic!("array payload should contain inline Data"),
810                })
811                .collect::<Vec<_>>()
812        };
813        let homogeneous = port_data(json!(["a", "b"])).unwrap();
814        assert_eq!(
815            inline_values(&homogeneous),
816            vec![br#""a""#.to_vec(), br#""b""#.to_vec()]
817        );
818
819        let mixed = port_data(json!([1, true])).unwrap();
820        assert_eq!(inline_values(&mixed), vec![b"1".to_vec(), b"true".to_vec()]);
821
822        let empty = port_data(json!([])).expect_err("empty arrays must not produce Many values");
823        assert!(empty.to_string().contains("requires at least one value"));
824    }
825
826    #[tokio::test]
827    async fn invoke_pipeline_returns_exact_canonical_response_bytes() {
828        let body = serde_json::to_vec(&resolved_input("message", json!("hello"))).unwrap();
829        let response = InvokePipeline::run::<TestTool>(&body, None).await;
830        assert_eq!(response.status, StatusCode::OK);
831        assert!(response.is_result);
832        let output: OffchainToolOutput = bcs::from_bytes(&response.body).unwrap();
833        assert_eq!(bcs::to_bytes(&output).unwrap(), response.body);
834    }
835
836    #[tokio::test]
837    async fn unsigned_routes_decode_leader_inputs_without_an_allowlist() {
838        for config in ["{}", r#"{"signed_http":{"mode":"disabled"}}"#] {
839            let routes = routes_for_with_config_::<TestTool>(std::sync::Arc::new(
840                ToolkitRuntimeConfig::from_json_str(config).unwrap(),
841            ));
842            let response = warp::test::request()
843                .method("POST")
844                .path("/invoke")
845                .json(&resolved_input("message", json!("hello")))
846                .reply(&routes)
847                .await;
848            assert_eq!(response.status(), StatusCode::OK);
849            assert!(response.headers().get("X-Nexus-Tool-Signature").is_none());
850            let output: OffchainToolOutput = bcs::from_bytes(response.body()).unwrap();
851            let message = output
852                .ports
853                .iter()
854                .find(|port| port.port_name == b"message")
855                .unwrap();
856            assert_eq!(
857                NexusData::from_values(message.values.clone(), false)
858                    .unwrap()
859                    .inline_data_bytes(),
860                Some(br#""hello""#.to_vec())
861            );
862
863            for invalid in [json!({"message":"hello"}), json!({"ports": []})] {
864                let response = warp::test::request()
865                    .method("POST")
866                    .path("/invoke")
867                    .json(&invalid)
868                    .reply(&routes)
869                    .await;
870                assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
871            }
872        }
873    }
874
875    #[tokio::test]
876    async fn invalid_input_remains_local_json_error() {
877        let response = InvokePipeline::run::<TestTool>(b"{}", None).await;
878        assert_eq!(response.status, StatusCode::UNPROCESSABLE_ENTITY);
879        assert!(!response.is_result);
880        assert!(serde_json::from_slice::<serde_json::Value>(&response.body).is_ok());
881    }
882
883    #[derive(JsonSchema)]
884    enum PanickingOutput {
885        Ok { message: String },
886    }
887
888    impl Serialize for PanickingOutput {
889        fn serialize<S: serde::Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
890            match self {
891                Self::Ok { message } => panic!("PRIVATE_SERIALIZATION_MARKER {message}"),
892            }
893        }
894    }
895
896    struct FailingTool<const PHASE: u8>;
897
898    impl<const PHASE: u8> NexusTool for FailingTool<PHASE> {
899        type Input = Input;
900        type Output = PanickingOutput;
901
902        fn fqn() -> ToolFqn {
903            fqn!("xyz.taluslabs.failure.test@1")
904        }
905
906        fn description() -> &'static str {
907            "Exercise invocation failure isolation."
908        }
909
910        fn timeout() -> std::time::Duration {
911            std::time::Duration::from_millis(10)
912        }
913
914        async fn new() -> Self {
915            assert!(PHASE != 0, "PRIVATE_CONSTRUCTOR_MARKER");
916            Self
917        }
918
919        async fn authorize(&self, _: crate::AuthContext) -> anyhow::Result<()> {
920            assert!(PHASE != 1, "PRIVATE_AUTHORIZATION_MARKER");
921            Ok(())
922        }
923
924        async fn invoke(&self, _: Input) -> PanickingOutput {
925            if PHASE == 4 {
926                std::future::pending::<()>().await;
927            }
928            assert!(PHASE != 2, "PRIVATE_INVOCATION_MARKER");
929            PanickingOutput::Ok {
930                message: "hello".into(),
931            }
932        }
933
934        async fn health(&self) -> anyhow::Result<StatusCode> {
935            Ok(StatusCode::OK)
936        }
937    }
938
939    #[tokio::test]
940    async fn panics_are_local_errors_and_later_requests_succeed() {
941        let body = serde_json::to_vec(&resolved_input("message", json!("hello"))).unwrap();
942        let responses = [
943            InvokePipeline::run::<FailingTool<0>>(&body, None).await,
944            InvokePipeline::run::<FailingTool<2>>(&body, None).await,
945            InvokePipeline::run::<FailingTool<3>>(&body, None).await,
946        ];
947        for response in responses {
948            assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
949            assert!(!response.is_result);
950            assert_eq!(
951                serde_json::from_slice::<serde_json::Value>(&response.body).unwrap(),
952                json!({"error": "tool_invocation_failed"})
953            );
954        }
955        assert_eq!(
956            InvokePipeline::run::<TestTool>(&body, None).await.status,
957            StatusCode::OK
958        );
959    }
960
961    #[tokio::test]
962    async fn authorization_panics_do_not_escape_or_become_tool_results() {
963        let transport = resolved_input("message", json!("hello"));
964        let schema = MetaSchema::from_offchain_json_schemas(
965            &serde_json::to_vec(&schemars::schema_for!(Input)).unwrap(),
966            &serde_json::to_vec(&schemars::schema_for!(PanickingOutput)).unwrap(),
967        )
968        .unwrap();
969        let resolved = schema.resolved_inputs_from_json(&transport).unwrap();
970        let auth = AuthenticatedRequest {
971            leader_id: "leader".into(),
972            leader_key_id: 0,
973            input_hash: schema.resolved_inputs_sha256(&resolved).unwrap(),
974            leader_signature: [2; 64],
975            nonce: [3; 32],
976            context_timestamp_ms: 0,
977        };
978        let response = InvokePipeline::run::<FailingTool<1>>(
979            &serde_json::to_vec(&transport).unwrap(),
980            Some(auth),
981        )
982        .await;
983        assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
984        assert!(!response.is_result);
985        assert!(!String::from_utf8(response.body)
986            .unwrap()
987            .contains("PRIVATE"));
988    }
989
990    #[tokio::test]
991    async fn asynchronous_work_obeys_the_tool_deadline() {
992        let body = serde_json::to_vec(&resolved_input("message", json!("hello"))).unwrap();
993        let response = InvokePipeline::run::<FailingTool<4>>(&body, None).await;
994        assert_eq!(response.status, StatusCode::GATEWAY_TIMEOUT);
995        assert!(!response.is_result);
996        assert_eq!(
997            serde_json::from_slice::<serde_json::Value>(&response.body).unwrap(),
998            json!({"error": "tool_invocation_timeout"})
999        );
1000    }
1001
1002    #[tokio::test]
1003    async fn invoke_pipeline_rejects_authenticated_hash_mismatch() {
1004        let transport = resolved_input("message", json!("hello"));
1005        let body = serde_json::to_vec(&transport).unwrap();
1006        let schema = MetaSchema::from_offchain_json_schemas(
1007            &serde_json::to_vec(&schemars::schema_for!(Input)).unwrap(),
1008            &serde_json::to_vec(&schemars::schema_for!(Output)).unwrap(),
1009        )
1010        .unwrap();
1011        let resolved = schema.resolved_inputs_from_json(&transport).unwrap();
1012        let actual_hash = schema.resolved_inputs_sha256(&resolved).unwrap();
1013        let auth = |input_hash| AuthenticatedRequest {
1014            leader_id: "leader".to_string(),
1015            leader_key_id: 0,
1016            input_hash,
1017            leader_signature: [2; 64],
1018            nonce: [3; 32],
1019            context_timestamp_ms: 0,
1020        };
1021
1022        let mismatch = InvokePipeline::run::<TestTool>(&body, Some(auth([9; 32]))).await;
1023        assert_eq!(mismatch.status, StatusCode::UNPROCESSABLE_ENTITY);
1024        assert_eq!(
1025            serde_json::from_slice::<serde_json::Value>(&mismatch.body).unwrap()["error"],
1026            "input_integrity_error"
1027        );
1028
1029        let accepted = InvokePipeline::run::<TestTool>(&body, Some(auth(actual_hash))).await;
1030        assert_eq!(accepted.status, StatusCode::OK);
1031
1032        let semantic_body = serde_json::to_vec(&json!({"message": "hello"})).unwrap();
1033        let injected = InvokePipeline::run::<TestTool>(
1034            &semantic_body,
1035            Some(auth(nexus_sdk::signed_http::v3::wire::sha256(
1036                &semantic_body,
1037            ))),
1038        )
1039        .await;
1040        assert_eq!(injected.status, StatusCode::UNPROCESSABLE_ENTITY);
1041        assert!(!injected.is_result);
1042        assert_eq!(
1043            serde_json::from_slice::<serde_json::Value>(&injected.body).unwrap()["error"],
1044            "input_deserialization_error"
1045        );
1046    }
1047
1048    #[test]
1049    fn meta_placeholder_url_empty_path() {
1050        let url = super::meta_placeholder_url_("");
1051        assert_eq!(url.as_str(), "http://localhost/");
1052    }
1053
1054    #[test]
1055    fn meta_placeholder_url_no_leading_slash() {
1056        let url = super::meta_placeholder_url_("path");
1057        assert_eq!(url.host_str(), Some("localhost"));
1058        assert_eq!(url.path(), "/path");
1059    }
1060
1061    #[derive(Serialize, JsonSchema)]
1062    enum ExplicitOutput {
1063        Ok {
1064            #[schemars(with = "String")]
1065            message: NexusData,
1066        },
1067    }
1068
1069    struct ExplicitTool<const INVALID: bool>;
1070    impl<const INVALID: bool> NexusTool for ExplicitTool<INVALID> {
1071        type Input = Input;
1072        type Output = ExplicitOutput;
1073
1074        fn fqn() -> ToolFqn {
1075            fqn!("xyz.taluslabs.explicit@1")
1076        }
1077
1078        fn description() -> &'static str {
1079            "Returns explicit protocol data."
1080        }
1081
1082        async fn new() -> Self {
1083            Self
1084        }
1085
1086        async fn health(&self) -> anyhow::Result<StatusCode> {
1087            Ok(StatusCode::OK)
1088        }
1089
1090        async fn invoke(&self, _: Input) -> ExplicitOutput {
1091            ExplicitOutput::Ok {
1092                message: NexusData::walrus_data(
1093                    b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1094                    [1; 32],
1095                )
1096                .unwrap(),
1097            }
1098        }
1099
1100        fn encode_output(output: ExplicitOutput) -> anyhow::Result<OffchainToolOutput> {
1101            let ExplicitOutput::Ok { message } = output;
1102            OffchainToolOutput::from_ports(
1103                if INVALID {
1104                    b"Unknown".to_vec()
1105                } else {
1106                    b"Ok".to_vec()
1107                },
1108                [("message".into(), message)],
1109            )
1110        }
1111    }
1112
1113    #[tokio::test]
1114    async fn explicit_references_remain_canonical_and_invalid_outputs_are_unsigned() {
1115        let input = serde_json::to_vec(&resolved_input("message", json!("input"))).unwrap();
1116        let response = InvokePipeline::run::<ExplicitTool<false>>(&input, None).await;
1117        assert_eq!(response.status, StatusCode::OK);
1118        assert!(response.is_result);
1119        let output: OffchainToolOutput = bcs::from_bytes(&response.body).unwrap();
1120        assert!(matches!(
1121            output.ports[0].values[0],
1122            nexus_sdk::types::NexusValue::WalrusData { .. }
1123        ));
1124        let response = InvokePipeline::run::<ExplicitTool<true>>(&input, None).await;
1125        assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
1126        assert!(!response.is_result);
1127    }
1128
1129    #[test]
1130    fn meta_placeholder_url_with_leading_slash() {
1131        let url = super::meta_placeholder_url_("/foo/");
1132        assert_eq!(url.host_str(), Some("localhost"));
1133        assert_eq!(url.path(), "/foo/");
1134    }
1135}