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    nexus_sdk::{
14        move_bindings::interface::meta_schema::MetaSchema,
15        types::{NexusData, OffchainToolOutput, OffchainToolOutputPort},
16    },
17    reqwest::Url,
18    serde_json::json,
19    std::sync::Arc,
20    warp::{
21        filters::{host::Authority, path::FullPath},
22        http::{HeaderMap, StatusCode},
23        Filter,
24        Rejection,
25        Reply,
26    },
27};
28
29/// Load toolkit configuration from environment.
30///
31/// **This is an internal function used by [bootstrap!] macro and should not be
32/// used directly.**
33#[doc(hidden)]
34pub fn load_config_() -> anyhow::Result<Arc<ToolkitRuntimeConfig>> {
35    ToolkitRuntimeConfig::from_env().map(Arc::new)
36}
37
38/// Build a placeholder URL for `--meta` output from a tool's [`NexusTool::path()`].
39///
40/// The URL is a `http://localhost`-based placeholder — the real URL is set
41/// during registration via `--url`. This function normalises the path so that
42/// a missing leading `/` does not corrupt the URL's authority component.
43///
44/// **This is an internal function used by [bootstrap!] macro and should not be
45/// used directly.**
46#[doc(hidden)]
47pub fn meta_placeholder_url_(path: &str) -> Url {
48    let base = if path.is_empty() {
49        "http://localhost/".to_string()
50    } else if path.starts_with('/') {
51        format!("http://localhost{path}")
52    } else {
53        format!("http://localhost/{path}")
54    };
55    Url::parse(&base).expect("placeholder URL must be valid")
56}
57
58fn json_bytes_or_fallback(status: StatusCode, value: serde_json::Value) -> (StatusCode, Vec<u8>) {
59    match serde_json::to_vec(&value) {
60        Ok(body) => (status, body),
61        Err(e) => {
62            let fallback = json!({
63                "error": "serialization_error",
64                "details": e.to_string(),
65            });
66            let body = serde_json::to_vec(&fallback)
67                .unwrap_or_else(|_| br#"{"error":"serialization_error"}"#.to_vec());
68            (StatusCode::INTERNAL_SERVER_ERROR, body)
69        }
70    }
71}
72
73/// Macro to bootstrap the runtime for a set of tools. The macro generates the
74/// necessary routes for each tool and serves them on the provided address.
75///
76/// # Signed HTTP (Leader <-> Tool authentication)
77/// The runtime can optionally require signed `/invoke` requests and sign the responses.
78///
79/// Configuration is file-based and loaded from [`crate::ENV_TOOLKIT_CONFIG_PATH`]. The file schema
80/// is documented on [`crate::ToolkitRuntimeConfig`].
81///
82/// When enabled (`signed_http.mode = "required"`), the runtime:
83/// - Rejects unsigned or invalidly signed `/invoke` requests (fail-closed).
84/// - Verifies the Leader signature against a local allowlist (`allowed_leaders` / `allowed_leaders_path`).
85/// - Caches completed responses by deterministic nonce and canonical input hash; in-flight nonce reuse is rejected.
86/// - Returns exact ordered BCS Tool output bytes and signs the nonce-bound v3 Tool response message.
87/// - Keeps nonce replay and cached-response handling entirely offchain.
88///
89/// Operational note: your gateway/proxy must forward the `X-Nexus-Sig-*` headers in both directions.
90/// The request body, nonce, and unsigned identity headers require authenticated HTTPS transport.
91/// Set both `NEXUS_TOOL_TLS_CERT_PATH` and `NEXUS_TOOL_TLS_KEY_PATH` to terminate TLS directly in
92/// the Toolkit server. If TLS terminates at a gateway, the gateway-to-Tool hop must provide an
93/// equivalently protected transport; signed HTTP does not make a plaintext hop safe.
94///
95/// ## Example config
96/// ```json
97/// {
98///   "invoke_max_body_bytes": 10485760,
99///   "signed_http": {
100///     "mode": "required",
101///     "allowed_leaders_path": "./allowed_leaders.json",
102///     "tools": {
103///       "xyz.dummy.tool@1": {
104///         "response_signing_key": "0000000000000000000000000000000000000000000000000000000000000000",
105///         "replay_cache_ttl_ms": 300000
106///       }
107///     }
108///   }
109/// }
110/// ```
111///
112/// ## `--meta` flag
113/// When the binary is invoked with `--meta`, the macro prints a JSON array of
114/// tool metadata (one entry per tool) to stdout and exits immediately — no HTTP
115/// server is started. This is used by CI pipelines to extract registration data
116/// from a Docker image without running the tool.
117///
118/// ```shell
119/// ./my-tool --meta   # prints JSON array and exits
120/// ```
121///
122/// ## Request body limits
123/// `/invoke` enforces a `Content-Length` limit via `warp::body::content_length_limit`.
124/// Requests without a `Content-Length` header are rejected.
125///
126/// # Examples
127///
128/// ### One tool running on `127.0.0.1:8080`
129///
130/// ```ignore
131/// use nexus_toolkit::bootstrap;
132///
133/// #[tokio::main]
134/// async fn main() {
135///     bootstrap!(YourTool);
136/// }
137/// ```
138///
139/// ### Multiple tools running on `127.0.0.1:8080`
140///
141/// ```ignore
142/// use nexus_toolkit::bootstrap;
143///
144/// #[tokio::main]
145/// async fn main() {
146///     bootstrap!([YourTool, AnotherTool]);
147/// }
148/// ```
149///
150/// ### One tool running on the provided address
151///
152/// ```ignore
153/// use nexus_toolkit::bootstrap;
154///
155/// #[tokio::main]
156/// async fn main() {
157///     bootstrap!(([127, 0, 0, 1], 8081), YourTool);
158/// }
159/// ```
160///
161/// ### Multiple tools running on the provided address
162///
163/// ```ignore
164/// use nexus_toolkit::bootstrap;
165///
166/// #[tokio::main]
167/// async fn main() {
168///     bootstrap!(([127, 0, 0, 1], 8081), [YourTool, AnotherTool]);
169/// }
170/// ```
171#[macro_export]
172macro_rules! bootstrap {
173    (@get_addr) => {{
174        let addr_str = std::env::var("BIND_ADDR")
175            .unwrap_or_else(|_| "127.0.0.1:8080".to_string());
176        addr_str
177            .parse::<std::net::SocketAddr>()
178            .expect("Invalid socket address in BIND_ADDR")
179    }};
180    ($addr:expr, [$tool:ty $(, $next_tool:ty)* $(,)?]) => {{
181        let _ = $crate::env_logger::try_init();
182
183        // Handle --meta: print tool metadata as a JSON array and exit
184        // without starting the HTTP server. Used by CI to extract
185        // registration data from a Docker image. Uses `return` to exit
186        // the enclosing function (typically `main`).
187        if ::std::env::args().any(|a| a == "--meta") {
188            let meta = $crate::serde_json::json!([
189                <$tool as $crate::NexusTool>::meta(
190                    $crate::runtime::meta_placeholder_url_(<$tool as $crate::NexusTool>::path())
191                )
192                $(
193                    , <$next_tool as $crate::NexusTool>::meta(
194                        $crate::runtime::meta_placeholder_url_(<$next_tool as $crate::NexusTool>::path())
195                    )
196                )*
197            ]);
198
199            println!("{}", $crate::serde_json::to_string_pretty(&meta)
200                .expect("meta serialization must not fail"));
201            return;
202        }
203
204        use {
205            ::std::sync::Arc,
206            $crate::warp::{http::StatusCode, Filter},
207        };
208
209        // Load toolkit config (shared across all tool routes).
210        let toolkit_cfg = $crate::runtime::load_config_()
211            .expect("Failed to load Nexus toolkit config");
212
213        // Create routes for each Tool in the bundle.
214        let routes = $crate::runtime::routes_for_with_config_::<$tool>(toolkit_cfg.clone());
215        $(
216            let routes = routes.or(
217                $crate::runtime::routes_for_with_config_::<$next_tool>(toolkit_cfg.clone())
218            );
219        )*
220
221        // Collect paths of all tools.
222        let mut paths = vec![<$tool as $crate::NexusTool>::path()];
223        $(
224            paths.push(<$next_tool as $crate::NexusTool>::path());
225        )*
226
227        // Add a default health route in case there is none in the root.
228        let default_health_route = $crate::warp::get()
229            .and($crate::warp::path("health"))
230            .map(|| {
231                $crate::warp::reply::with_status($crate::warp::reply(), StatusCode::OK)
232            });
233
234        // Add a default tools route to list all tools available at that webserver.
235        let default_tools_route = $crate::warp::get()
236            .and($crate::warp::path("tools"))
237            .map(move || $crate::warp::reply::json(&paths));
238
239        let routes = routes
240            .or(default_health_route)
241            .or(default_tools_route)
242            .boxed();
243        // Terminate TLS directly when both credential paths are configured.
244        match $crate::runtime::tls::Config::from_env()
245            .expect("Invalid Nexus Tool TLS configuration")
246        {
247            $crate::runtime::tls::Config::Disabled => {
248                $crate::warp::serve(routes).run($addr).await
249            }
250            $crate::runtime::tls::Config::Enabled { cert_path, key_path } => {
251                let (_, incoming) =
252                    $crate::runtime::tls::bind($addr.into(), cert_path, key_path)
253                        .await
254                        .expect("Failed to start Nexus Tool TLS server");
255                $crate::runtime::tls::serve(routes, incoming).await
256            }
257        }
258    }};
259    // Default address.
260    ([$($tool:ty),+ $(,)?]) => {{
261        let addr = bootstrap!(@get_addr);
262        bootstrap!(addr, [$($tool,)*])
263    }};
264    // Only 1 tool.
265    ($addr:expr, $tool:ty) => {{
266        bootstrap!($addr, [$tool])
267    }};
268    // Only 1 tool with default address.
269    ($tool:ty) => {{
270        let addr = bootstrap!(@get_addr);
271        bootstrap!(addr, [$tool])
272    }};
273}
274
275/// This function generates the necessary routes for a given [NexusTool] using an already-loaded
276/// [`ToolkitRuntimeConfig`].
277///
278/// This exists so callers (like [`bootstrap!`]) can load and validate config once per process and
279/// share it across multiple tool route bundles.
280#[doc(hidden)]
281pub fn routes_for_with_config_<T: NexusTool>(
282    toolkit_cfg: Arc<ToolkitRuntimeConfig>,
283) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
284    // Wrap config with file watching support
285    let config = Config::from_config(toolkit_cfg.clone());
286    // Force output schema to be an enum.
287    let output_schema = json!(schemars::schema_for!(T::Output));
288
289    if output_schema["oneOf"].is_null() {
290        panic!("The output type must be an enum to generate the correct output schema.");
291    }
292
293    let base_path = T::path()
294        .split("/")
295        .filter(|s| !s.is_empty())
296        .fold(warp::any().boxed(), |filter, segment| {
297            filter.and(warp::path(segment.to_string())).boxed()
298        });
299
300    let health_route = warp::get()
301        .and(base_path.clone())
302        .and(warp::path("health"))
303        .and_then(health_handler::<T>);
304
305    // Meta path is tool base URL path and `/meta`.
306    let meta_route = warp::get()
307        .and(base_path.clone())
308        .and(warp::path("meta"))
309        .and(warp::header::optional::<Authority>("X-Forwarded-Host"))
310        .and(warp::header::optional::<String>("X-Forwarded-Proto"))
311        .and(warp::filters::host::optional())
312        .and(warp::path::full())
313        .and_then(meta_handler::<T>);
314
315    let invoke_max_body_bytes = toolkit_cfg.invoke_max_body_bytes();
316
317    let tool_id = T::fqn().to_string();
318    let invoke_auth = InvokeAuth::new_sync(config, tool_id, T::timeout())
319        .expect("Failed to load signed HTTP configuration");
320
321    // Invoke path is tool base URL path and `/invoke`.
322    let invoke_route = warp::post()
323        .and(base_path)
324        .and(warp::path("invoke"))
325        .and(warp::header::headers_cloned())
326        .and(warp::body::content_length_limit(invoke_max_body_bytes))
327        .and(warp::body::bytes())
328        .and(warp::any().map(move || invoke_auth.clone()))
329        .and_then(invoke_handler::<T>);
330
331    health_route.or(meta_route).or(invoke_route)
332}
333
334async fn health_handler<T: NexusTool>() -> Result<impl Reply, Rejection> {
335    let tool = T::new().await;
336
337    let status = tool
338        .health()
339        .await
340        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
341
342    Ok(warp::reply::with_status(warp::reply(), status))
343}
344
345async fn meta_handler<T: NexusTool>(
346    x_forwarded_host: Option<Authority>,
347    x_forwarded_proto: Option<String>,
348    host: Option<Authority>,
349    path: FullPath,
350) -> Result<impl Reply, Rejection> {
351    // We always need the most "external" host, as this is what will be called by users.
352    let host = x_forwarded_host.or(host);
353
354    // If the host is malformed or not present, return a 400.
355    let host = match host {
356        Some(host) => host,
357        None => {
358            let reply = json!({
359                "error": "host_header_required",
360                "details": "Host header is required.",
361            });
362
363            return Ok(warp::reply::with_status(
364                warp::reply::json(&reply),
365                StatusCode::BAD_REQUEST,
366            ));
367        }
368    };
369
370    // Stripping 'meta' suffix from the path will give us the base path.
371    let base_path = match path.as_str().strip_suffix("meta") {
372        Some(base_path) => base_path,
373        None => {
374            // This is probably never reached as we create the endpoints
375            // ourselves.
376            let reply = json!({
377                "error": "invalid_path",
378                "details": "Meta path must end with '/meta'.",
379            });
380
381            return Ok(warp::reply::with_status(
382                warp::reply::json(&reply),
383                StatusCode::BAD_REQUEST,
384            ));
385        }
386    };
387
388    // As in the case of the host, we need to use the most "external" scheme,
389    // which is basically the scheme used by the client to access the tool.
390    // If the scheme is not present, we check the environment variable, which
391    // might have been set for operational purposes.
392    // As a last resort, we use http as the default scheme.
393    //
394    // Ref: https://github.com/Talus-Network/nexus-sdk/issues/77
395    let scheme = x_forwarded_proto.unwrap_or_else(|| "http".to_string());
396
397    // Validate scheme to prevent URL injection attacks
398    if scheme != "http" && scheme != "https" {
399        let reply = json!({
400            "error": "invalid_scheme",
401            "details": "Scheme must be either 'http' or 'https'.",
402        });
403
404        return Ok(warp::reply::with_status(
405            warp::reply::json(&reply),
406            StatusCode::BAD_REQUEST,
407        ));
408    }
409
410    let url = match Url::parse(&format!("{scheme}://{host}{base_path}")) {
411        Ok(url) => url,
412        Err(e) => {
413            let reply = json!({
414                "error": "url_parsing_error",
415                "details": e.to_string(),
416            });
417
418            return Ok(warp::reply::with_status(
419                warp::reply::json(&reply),
420                StatusCode::BAD_REQUEST,
421            ));
422        }
423    };
424
425    Ok(warp::reply::with_status(
426        warp::reply::json(&T::meta(url)),
427        StatusCode::OK,
428    ))
429}
430
431/// Result of the tool invocation pipeline before being turned into an HTTP response.
432struct InvokePipelineResponse {
433    status: StatusCode,
434    body: Vec<u8>,
435    is_result: bool,
436}
437
438impl InvokePipelineResponse {
439    fn json(status: StatusCode, value: serde_json::Value) -> Self {
440        let (status, body) = json_bytes_or_fallback(status, value);
441        Self {
442            status,
443            body,
444            is_result: false,
445        }
446    }
447}
448
449/// Tool invocation pipeline returning canonical BCS result bytes or a local JSON error.
450struct InvokePipeline;
451
452impl InvokePipeline {
453    async fn run<T: NexusTool>(
454        body_bytes: &[u8],
455        auth_ctx: Option<crate::AuthContext>,
456    ) -> InvokePipelineResponse {
457        let input = match decode_tool_input::<T>(body_bytes, auth_ctx.as_ref()) {
458            Ok(value) => value,
459            Err(ToolInputDecodeError::Integrity) => {
460                return InvokePipelineResponse::json(
461                    StatusCode::UNPROCESSABLE_ENTITY,
462                    json!({
463                        "error": "input_integrity_error",
464                        "details": "resolved Tool input does not match authenticated input hash",
465                    }),
466                );
467            }
468            Err(ToolInputDecodeError::Deserialization(e)) => {
469                return InvokePipelineResponse::json(
470                    StatusCode::UNPROCESSABLE_ENTITY,
471                    json!({
472                        "error": "input_deserialization_error",
473                        "details": e.to_string(),
474                    }),
475                );
476            }
477        };
478
479        let tool = T::new().await;
480
481        if let Some(ctx) = auth_ctx {
482            if let Err(e) = tool.authorize(ctx).await {
483                return InvokePipelineResponse::json(
484                    StatusCode::FORBIDDEN,
485                    json!({
486                        "error": "permission_denied",
487                        "details": e.to_string(),
488                    }),
489                );
490            }
491        }
492
493        let output = tool.invoke(input).await;
494
495        match encode_tagged_output(output) {
496            Ok(body) => InvokePipelineResponse {
497                status: StatusCode::OK,
498                body,
499                is_result: true,
500            },
501            Err(e) => InvokePipelineResponse::json(
502                StatusCode::INTERNAL_SERVER_ERROR,
503                json!({
504                    "error": "output_serialization_error",
505                    "details": e.to_string(),
506                }),
507            ),
508        }
509    }
510}
511
512enum ToolInputDecodeError {
513    Deserialization(anyhow::Error),
514    Integrity,
515}
516
517fn decode_tool_input<T: NexusTool>(
518    body_bytes: &[u8],
519    auth_ctx: Option<&crate::AuthContext>,
520) -> Result<T::Input, ToolInputDecodeError> {
521    if let Some(auth_ctx) = auth_ctx {
522        let schema = MetaSchema::from_offchain_json_schemas(
523            &serde_json::to_vec(&schemars::schema_for!(T::Input))
524                .map_err(anyhow::Error::from)
525                .map_err(ToolInputDecodeError::Deserialization)?,
526            &serde_json::to_vec(&schemars::schema_for!(T::Output))
527                .map_err(anyhow::Error::from)
528                .map_err(ToolInputDecodeError::Deserialization)?,
529        )
530        .map_err(ToolInputDecodeError::Deserialization)?;
531        let resolved_inputs = serde_json::from_slice::<serde_json::Value>(body_bytes)
532            .map_err(anyhow::Error::from)
533            .and_then(|value| schema.resolved_inputs_from_json(&value))
534            .map_err(ToolInputDecodeError::Deserialization)?;
535        if schema.resolved_inputs_sha256(&resolved_inputs).ok() != Some(auth_ctx.input_hash) {
536            return Err(ToolInputDecodeError::Integrity);
537        }
538        return serde_json::from_value::<crate::WithSerdeErrorPath<T::Input>>(
539            schema
540                .resolved_inputs_to_semantic_json(&resolved_inputs)
541                .map_err(ToolInputDecodeError::Deserialization)?,
542        )
543        .map(|value| value.0)
544        .map_err(|error| ToolInputDecodeError::Deserialization(error.into()));
545    }
546    serde_json::from_slice::<crate::WithSerdeErrorPath<T::Input>>(body_bytes)
547        .map(|value| value.0)
548        .map_err(|error| ToolInputDecodeError::Deserialization(error.into()))
549}
550
551fn encode_tagged_output<T: serde::Serialize>(output: T) -> anyhow::Result<Vec<u8>> {
552    let value = serde_json::to_value(crate::WithSerdeErrorPath(output))?;
553    let serde_json::Value::Object(variants) = value else {
554        anyhow::bail!("tool output must serialize as an externally tagged enum")
555    };
556    if variants.len() != 1 {
557        anyhow::bail!("tool output must contain exactly one variant")
558    }
559    let (tag, payload) = variants.into_iter().next().expect("length checked");
560    let serde_json::Value::Object(payload) = payload else {
561        anyhow::bail!("tool output variant payload must be an object")
562    };
563    let ports = payload
564        .into_iter()
565        .map(|(port_name, value)| {
566            Ok(OffchainToolOutputPort {
567                port_name: port_name.into_bytes(),
568                values: nexus_data(value)?.into_values()?,
569            })
570        })
571        .collect::<anyhow::Result<Vec<_>>>()?;
572    let output = OffchainToolOutput {
573        tag: tag.into_bytes(),
574        ports,
575    };
576    Ok(bcs::to_bytes(&output)?)
577}
578
579fn nexus_data(value: serde_json::Value) -> anyhow::Result<NexusData> {
580    if let serde_json::Value::Array(values) = value {
581        return NexusData::inline_data_many(
582            values
583                .iter()
584                .map(serde_json::to_vec)
585                .collect::<Result<Vec<_>, _>>()?,
586        );
587    }
588
589    NexusData::inline_data(serde_json::to_vec(&value)?)
590}
591
592async fn invoke_handler<T: NexusTool>(
593    headers: HeaderMap,
594    body: bytes::Bytes,
595    auth: InvokeAuth,
596) -> Result<warp::reply::Response, Rejection> {
597    let body_bytes = body.to_vec();
598
599    let auth_runtime = auth.current().await;
600    Ok(handle_invoke(
601        &auth_runtime,
602        auth.replay(),
603        headers,
604        body_bytes,
605        |auth_ctx, body_bytes| async move {
606            let pipeline = InvokePipeline::run::<T>(&body_bytes, auth_ctx).await;
607            (pipeline.status, pipeline.body, pipeline.is_result)
608        },
609    )
610    .await)
611}
612
613#[cfg(test)]
614mod tests {
615    use {
616        super::*,
617        nexus_sdk::{fqn, signed_http::v3::wire::AuthenticatedRequest, ToolFqn},
618        schemars::JsonSchema,
619        serde::{Deserialize, Serialize},
620        serde_json::json,
621    };
622
623    fn resolved_input(port_name: &str, value: serde_json::Value) -> serde_json::Value {
624        let value = NexusData::inline_data(serde_json::to_vec(&value).unwrap()).unwrap();
625        json!({
626            "ports": [{
627                "port_name": port_name,
628                "value": value.to_json_value().unwrap(),
629            }],
630        })
631    }
632
633    #[derive(Deserialize, JsonSchema)]
634    struct Input {
635        message: String,
636    }
637
638    #[derive(Serialize, JsonSchema)]
639    enum Output {
640        Ok {
641            message: String,
642            count: u64,
643            flags: Vec<bool>,
644            metadata: serde_json::Value,
645        },
646    }
647
648    #[derive(Serialize)]
649    enum DirectErrOutput {
650        #[serde(rename = "_err_eval")]
651        ErrEval { reason: String },
652    }
653
654    struct TestTool;
655
656    impl NexusTool for TestTool {
657        type Input = Input;
658        type Output = Output;
659
660        fn description() -> &'static str {
661            "Returns a structured test response."
662        }
663
664        fn fqn() -> ToolFqn {
665            fqn!("xyz.taluslabs.test@1")
666        }
667
668        async fn new() -> Self {
669            Self
670        }
671
672        async fn invoke(&self, input: Self::Input) -> Self::Output {
673            Output::Ok {
674                message: input.message,
675                count: 2,
676                flags: vec![true, false],
677                metadata: json!({"source": "test"}),
678            }
679        }
680
681        async fn health(&self) -> anyhow::Result<StatusCode> {
682            Ok(StatusCode::OK)
683        }
684    }
685
686    #[test]
687    fn tool_output_encodes_as_ordered_offchain_output() {
688        let bytes = encode_tagged_output(Output::Ok {
689            message: "hello".to_string(),
690            count: 2,
691            flags: vec![true, false],
692            metadata: json!({"source": "test"}),
693        })
694        .unwrap();
695        let output: OffchainToolOutput = bcs::from_bytes(&bytes).unwrap();
696
697        assert_eq!(bcs::to_bytes(&output).unwrap(), bytes);
698        assert_eq!(output.tag, b"Ok");
699        assert_eq!(
700            output
701                .ports
702                .iter()
703                .map(|port| port.port_name.as_slice())
704                .collect::<Vec<_>>(),
705            vec![
706                b"message".as_slice(),
707                b"count".as_slice(),
708                b"flags".as_slice(),
709                b"metadata".as_slice(),
710            ]
711        );
712
713        let message = NexusData::from_values(output.ports[0].values.clone(), false).unwrap();
714        assert_eq!(message.inline_data_bytes(), Some(br#""hello""#.to_vec()));
715
716        let flags = NexusData::from_values(output.ports[2].values.clone(), true).unwrap();
717        assert_eq!(
718            flags
719                .values()
720                .unwrap()
721                .into_iter()
722                .map(|value| match value {
723                    nexus_sdk::move_bindings::primitives::data::NexusValue::InlineData {
724                        bytes,
725                    } => bytes.clone(),
726                    _ => panic!("flags should be inline Data"),
727                })
728                .collect::<Vec<_>>(),
729            vec![b"true".to_vec(), b"false".to_vec()]
730        );
731
732        let metadata = NexusData::from_values(output.ports[3].values.clone(), false).unwrap();
733        assert_eq!(
734            metadata.inline_data_bytes(),
735            Some(br#"{"source":"test"}"#.to_vec())
736        );
737    }
738
739    #[test]
740    fn direct_err_eval_encodes_exact_named_signed_output() {
741        let bytes = encode_tagged_output(DirectErrOutput::ErrEval {
742            reason: "forced failure".to_string(),
743        })
744        .unwrap();
745        let output: OffchainToolOutput = bcs::from_bytes(&bytes).unwrap();
746
747        assert_eq!(output.tag, b"_err_eval");
748        assert_eq!(output.ports.len(), 1);
749        assert_eq!(output.ports[0].port_name, b"reason");
750        let reason = NexusData::from_values(output.ports[0].values.clone(), false).unwrap();
751        assert_eq!(
752            reason.inline_data_bytes(),
753            Some(br#""forced failure""#.to_vec())
754        );
755    }
756
757    #[test]
758    fn canonical_response_encoding_rejects_non_enum_shapes() {
759        assert!(encode_tagged_output(json!("plain value"))
760            .unwrap_err()
761            .to_string()
762            .contains("externally tagged enum"));
763        assert!(encode_tagged_output(json!({"Ok": {}, "Err": {}}))
764            .unwrap_err()
765            .to_string()
766            .contains("exactly one variant"));
767        assert!(encode_tagged_output(json!({"Ok": 1}))
768            .unwrap_err()
769            .to_string()
770            .contains("payload must be an object"));
771    }
772
773    #[test]
774    fn array_payloads_encode_each_json_value() {
775        let inline_values = |data: &NexusData| {
776            data.values()
777                .expect("encoded Toolkit output should decode")
778                .into_iter()
779                .map(|element| match element {
780                    nexus_sdk::move_bindings::primitives::data::NexusValue::InlineData {
781                        bytes,
782                    } => bytes.clone(),
783                    _ => panic!("array payload should contain inline Data"),
784                })
785                .collect::<Vec<_>>()
786        };
787        let homogeneous = nexus_data(json!(["a", "b"])).unwrap();
788        assert_eq!(
789            inline_values(&homogeneous),
790            vec![br#""a""#.to_vec(), br#""b""#.to_vec()]
791        );
792
793        let mixed = nexus_data(json!([1, true])).unwrap();
794        assert_eq!(inline_values(&mixed), vec![b"1".to_vec(), b"true".to_vec()]);
795
796        let empty = nexus_data(json!([])).expect_err("empty arrays must not produce Many values");
797        assert!(empty.to_string().contains("requires at least one value"));
798    }
799
800    #[tokio::test]
801    async fn invoke_pipeline_returns_exact_canonical_response_bytes() {
802        let body = serde_json::to_vec(&json!({"message": "hello"})).unwrap();
803        let response = InvokePipeline::run::<TestTool>(&body, None).await;
804        assert_eq!(response.status, StatusCode::OK);
805        assert!(response.is_result);
806        let output: OffchainToolOutput = bcs::from_bytes(&response.body).unwrap();
807        assert_eq!(bcs::to_bytes(&output).unwrap(), response.body);
808    }
809
810    #[tokio::test]
811    async fn invalid_input_remains_local_json_error() {
812        let response = InvokePipeline::run::<TestTool>(b"{}", None).await;
813        assert_eq!(response.status, StatusCode::UNPROCESSABLE_ENTITY);
814        assert!(!response.is_result);
815        assert!(serde_json::from_slice::<serde_json::Value>(&response.body).is_ok());
816    }
817
818    #[tokio::test]
819    async fn invoke_pipeline_rejects_authenticated_hash_mismatch() {
820        let transport = resolved_input("message", json!("hello"));
821        let body = serde_json::to_vec(&transport).unwrap();
822        let schema = MetaSchema::from_offchain_json_schemas(
823            &serde_json::to_vec(&schemars::schema_for!(Input)).unwrap(),
824            &serde_json::to_vec(&schemars::schema_for!(Output)).unwrap(),
825        )
826        .unwrap();
827        let resolved = schema.resolved_inputs_from_json(&transport).unwrap();
828        let actual_hash = schema.resolved_inputs_sha256(&resolved).unwrap();
829        let auth = |input_hash| AuthenticatedRequest {
830            leader_id: "leader".to_string(),
831            leader_key_id: 0,
832            input_hash,
833            leader_signature: [2; 64],
834            nonce: [3; 32],
835        };
836
837        let mismatch = InvokePipeline::run::<TestTool>(&body, Some(auth([9; 32]))).await;
838        assert_eq!(mismatch.status, StatusCode::UNPROCESSABLE_ENTITY);
839        assert_eq!(
840            serde_json::from_slice::<serde_json::Value>(&mismatch.body).unwrap()["error"],
841            "input_integrity_error"
842        );
843
844        let accepted = InvokePipeline::run::<TestTool>(&body, Some(auth(actual_hash))).await;
845        assert_eq!(accepted.status, StatusCode::OK);
846
847        let semantic_body = serde_json::to_vec(&json!({"message": "hello"})).unwrap();
848        let injected = InvokePipeline::run::<TestTool>(
849            &semantic_body,
850            Some(auth(nexus_sdk::signed_http::v3::wire::sha256(
851                &semantic_body,
852            ))),
853        )
854        .await;
855        assert_eq!(injected.status, StatusCode::UNPROCESSABLE_ENTITY);
856        assert!(!injected.is_result);
857        assert_eq!(
858            serde_json::from_slice::<serde_json::Value>(&injected.body).unwrap()["error"],
859            "input_deserialization_error"
860        );
861    }
862
863    #[test]
864    fn meta_placeholder_url_empty_path() {
865        let url = super::meta_placeholder_url_("");
866        assert_eq!(url.as_str(), "http://localhost/");
867    }
868
869    #[test]
870    fn meta_placeholder_url_no_leading_slash() {
871        let url = super::meta_placeholder_url_("path");
872        assert_eq!(url.host_str(), Some("localhost"));
873        assert_eq!(url.path(), "/path");
874    }
875
876    #[test]
877    fn meta_placeholder_url_with_leading_slash() {
878        let url = super::meta_placeholder_url_("/foo/");
879        assert_eq!(url.host_str(), Some("localhost"));
880        assert_eq!(url.path(), "/foo/");
881    }
882}