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