Skip to main content

nexus_toolkit/
config.rs

1//! Toolkit runtime configuration.
2//!
3//! This module defines the single JSON config file consumed by the
4//! `nexus-toolkit` HTTP runtime (see [`crate::bootstrap!`]).
5//!
6//! The goals are:
7//! - Keep configuration deployment-friendly (one file mounted into the tool container/VM).
8//! - Avoid per-tool env var naming schemes (like `NEXUS_TOOL_SIGNING_KEY_<SUFFIX>`).
9//! - Tools need a local allowlist of permitted Leaders. A response signing key is optional.
10//!
11//! # Loading
12//! The runtime loads this config from the path stored in [`ENV_TOOLKIT_CONFIG_PATH`].
13//! If the env var is not set, safe defaults are used (signed HTTP disabled).
14//!
15//! # DoS protection: request body size
16//! `/invoke` requests MUST include a `Content-Length` header and it MUST be less than or equal to
17//! [`ToolkitRuntimeConfig::invoke_max_body_bytes`]. This is enforced using
18//! `warp::body::content_length_limit`, which rejects requests without `Content-Length`.
19//! The default accommodates the SDK execution envelope. Operators may override
20//! `invoke_max_body_bytes` to set their HTTP admission limit. This does not change
21//! the separate SDK budget for resolved input and output data.
22//!
23//! # Signed HTTP (application-layer signatures)
24//! If the config includes a `signed_http` section in `required` mode, the runtime:
25//! - Rejects any `/invoke` request that does not carry valid signature headers.
26//! - Rejects any request signed by a Leader not present in the local allowlist.
27//! - Signs the exact ordered BCS Tool output bytes when a response signing key is configured.
28//!
29//! Operational note: if you run tools behind a gateway/proxy, ensure it forwards the `X-Nexus-Sig-*`
30//! headers. If these headers are stripped, signed HTTP will fail closed.
31//!
32//! The signature protocol itself lives in `nexus-sdk` under
33//! [`nexus_sdk::signed_http::v3`](nexus_sdk::signed_http::v3).
34//!
35//! # Example config
36//! ```json
37//! {
38//!   "signed_http": {
39//!     "mode": "required",
40//!     "allowed_leaders_path": "./allowed_leaders.json",
41//!     "tools": {
42//!       "xyz.dummy.tool@1": {
43//!         "response_signing_key": "0000000000000000000000000000000000000000000000000000000000000000"
44//!       }
45//!     }
46//!   }
47//! }
48//! ```
49//!
50//! # Example (Rust)
51//! This example parses a config from JSON (no filesystem required) by embedding the
52//! allowlist inline.
53//!
54//! ```
55//! use {
56//!     ed25519_dalek::SigningKey,
57//!     nexus_toolkit::ToolkitRuntimeConfig,
58//!     serde_json::{json, Map},
59//! };
60//!
61//! let tool_id = "xyz.dummy.tool@1";
62//! let tool_sk_hex = hex::encode([7u8; 32]);
63//! let leader_sk = SigningKey::from_bytes(&[9u8; 32]);
64//! let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
65//!
66//! let mut tools = Map::new();
67//! tools.insert(
68//!     tool_id.to_string(),
69//!     json!({
70//!         "response_signing_key": tool_sk_hex,
71//!     }),
72//! );
73//!
74//! let cfg_json = serde_json::to_string_pretty(&json!({
75//!     "signed_http": {
76//!         "mode": "required",
77//!         "allowed_leaders": {
78//!             "version": 1,
79//!             "leaders": [{
80//!                 "leader_id": "0x1111",
81//!                 "keys": [{
82//!                     "kid": 0,
83//!                     "public_key": leader_pk_hex,
84//!                 }],
85//!             }],
86//!         },
87//!         "tools": tools,
88//!     },
89//! }))
90//! .unwrap();
91//!
92//! let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
93//! assert_eq!(cfg.invoke_max_body_bytes(), nexus_sdk::execution_limits::MAX_INVOKE_BODY_BYTES);
94//! assert!(cfg.signed_http_is_required());
95//! assert!(cfg.has_tool(tool_id));
96//! ```
97
98use {
99    anyhow::Context as _,
100    ed25519_dalek::SigningKey,
101    nexus_sdk::{
102        execution_limits::MAX_INVOKE_BODY_BYTES,
103        signed_http::{
104            keys::parse_ed25519_signing_key,
105            v3::wire::{AllowedLeaders, AllowedLeadersFileV1},
106        },
107    },
108    notify::{Event, RecommendedWatcher, RecursiveMode, Watcher},
109    serde::Deserialize,
110    std::{
111        collections::BTreeMap,
112        fs,
113        path::{Path, PathBuf},
114        sync::{Arc, RwLock},
115        time::Duration,
116    },
117};
118
119/// Env var read by the toolkit runtime to locate its JSON config file.
120pub const ENV_TOOLKIT_CONFIG_PATH: &str = "NEXUS_TOOLKIT_CONFIG_PATH";
121
122/// Signed HTTP mode for the toolkit runtime.
123#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
124#[serde(rename_all = "snake_case")]
125pub enum SignedHttpMode {
126    /// Do not require signature headers.
127    Disabled,
128    /// Reject any request missing/invalid signature headers.
129    #[default]
130    Required,
131}
132
133/// Fully loaded toolkit runtime config (validated + ready to use).
134///
135/// This type is primarily used internally by the runtime; it is public so the
136/// config format can be documented and unit-tested.
137#[derive(Clone)]
138pub struct ToolkitRuntimeConfig {
139    invoke_max_body_bytes: u64,
140    signed_http: Option<SignedHttpRuntimeConfig>,
141    source_path: Option<PathBuf>,
142}
143
144#[derive(Clone)]
145pub(crate) struct SignedHttpRuntimeConfig {
146    pub(crate) allowed_leaders: Arc<AllowedLeaders>,
147    pub(crate) tools: BTreeMap<String, SignedHttpToolRuntimeConfig>,
148}
149
150#[derive(Clone)]
151pub(crate) struct SignedHttpToolRuntimeConfig {
152    /// Key used to attest successful Tool results.
153    ///
154    /// Request authentication does not depend on this key. When it is absent,
155    /// the runtime still requires a valid signature from an allowed Leader and
156    /// returns the successful result without a Tool signature.
157    pub(crate) response_signing_key: Option<SigningKey>,
158    pub(crate) require_client_certificate: bool,
159    pub(crate) context_timestamp_window_ms: u64,
160    pub(crate) replay_cache_ttl_ms: u64,
161}
162
163pub(crate) const DEFAULT_REPLAY_CACHE_TTL_MS: u64 = 300_000;
164pub(crate) const DEFAULT_CONTEXT_TIMESTAMP_WINDOW_MS: u64 = 30_000;
165
166impl ToolkitRuntimeConfig {
167    /// Load config from [`ENV_TOOLKIT_CONFIG_PATH`] if set, otherwise return defaults.
168    pub fn from_env() -> anyhow::Result<Self> {
169        let Some(path) = std::env::var(ENV_TOOLKIT_CONFIG_PATH).ok() else {
170            return Ok(Self::default_for_runtime());
171        };
172        Self::from_path(path)
173    }
174
175    /// Parse config from a JSON file.
176    pub fn from_path(path: impl AsRef<Path>) -> anyhow::Result<Self> {
177        let path = path.as_ref();
178        let bytes = fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
179        let mut cfg = Self::from_json_bytes(&bytes).with_context(|| {
180            format!(
181                "failed to parse toolkit runtime config at {}",
182                path.display()
183            )
184        })?;
185        cfg.source_path = Some(path.to_path_buf());
186        Ok(cfg)
187    }
188
189    /// Parse config from JSON bytes.
190    pub fn from_json_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
191        let file: ToolkitRuntimeConfigFile =
192            serde_json::from_slice(bytes).context("invalid JSON")?;
193        Self::try_from(file)
194    }
195
196    /// Parse config from a JSON string.
197    pub fn from_json_str(json: &str) -> anyhow::Result<Self> {
198        Self::from_json_bytes(json.as_bytes())
199    }
200
201    /// Maximum admitted `/invoke` request body size, independent of the resolved data budget.
202    pub fn invoke_max_body_bytes(&self) -> u64 {
203        self.invoke_max_body_bytes
204    }
205
206    /// True if the runtime requires signed HTTP requests.
207    pub fn signed_http_is_required(&self) -> bool {
208        self.signed_http.is_some()
209    }
210
211    /// Returns whether signed HTTP configuration exists for `tool_id`.
212    pub fn has_tool(&self, tool_id: &str) -> bool {
213        self.signed_http
214            .as_ref()
215            .is_some_and(|s| s.tools.contains_key(tool_id))
216    }
217
218    pub(crate) fn signed_http(&self) -> Option<&SignedHttpRuntimeConfig> {
219        self.signed_http.as_ref()
220    }
221
222    fn default_for_runtime() -> Self {
223        Self {
224            invoke_max_body_bytes: MAX_INVOKE_BODY_BYTES,
225            signed_http: None,
226            source_path: None,
227        }
228    }
229
230    pub(crate) fn source_path(&self) -> Option<&Path> {
231        self.source_path.as_deref()
232    }
233}
234
235#[derive(Clone, Debug, Deserialize)]
236#[serde(deny_unknown_fields)]
237struct ToolkitRuntimeConfigFile {
238    /// HTTP admission limit, defaulting to the SDK execution envelope.
239    #[serde(default)]
240    pub invoke_max_body_bytes: Option<u64>,
241    #[serde(default)]
242    pub signed_http: Option<SignedHttpConfigFile>,
243}
244
245#[derive(Clone, Debug, Deserialize)]
246#[serde(deny_unknown_fields)]
247struct SignedHttpConfigFile {
248    /// Defaults to `required` when omitted.
249    #[serde(default)]
250    pub mode: SignedHttpMode,
251
252    /// Path to an allowlist file (same schema as `AllowedLeadersFileV1`).
253    #[serde(default)]
254    pub allowed_leaders_path: Option<String>,
255
256    /// Inline allowlist (useful for tests and simple deployments).
257    #[serde(default)]
258    pub allowed_leaders: Option<AllowedLeadersFileV1>,
259
260    /// Per Tool authentication and response configuration, keyed by Tool id.
261    #[serde(default)]
262    pub tools: BTreeMap<String, SignedHttpToolConfigFile>,
263}
264
265#[derive(Clone, Debug, Deserialize)]
266#[serde(deny_unknown_fields)]
267struct SignedHttpToolConfigFile {
268    /// Optional hex or base64 encoding of a 32 byte Ed25519 private key.
269    ///
270    /// This also accepts Sui keytool encoding: base64 of `0x00 || sk32`.
271    #[serde(default)]
272    pub response_signing_key: Option<String>,
273    /// Require the TLS peer key to match the allowlisted Leader key for each signed invocation.
274    #[serde(default)]
275    pub require_client_certificate: bool,
276    /// Symmetric context timestamp freshness window in milliseconds. Defaults to 30 seconds.
277    #[serde(default)]
278    pub context_timestamp_window_ms: Option<u64>,
279
280    /// Completed replay-entry lifetime in milliseconds. Defaults to five minutes.
281    #[serde(default)]
282    pub replay_cache_ttl_ms: Option<u64>,
283}
284
285impl TryFrom<ToolkitRuntimeConfigFile> for ToolkitRuntimeConfig {
286    type Error = anyhow::Error;
287
288    fn try_from(file: ToolkitRuntimeConfigFile) -> Result<Self, Self::Error> {
289        let signed_http = match file.signed_http {
290            None => None,
291            Some(s) if s.mode == SignedHttpMode::Disabled => None,
292            Some(s) => Some(load_signed_http_config(s)?),
293        };
294
295        Ok(Self {
296            invoke_max_body_bytes: file.invoke_max_body_bytes.unwrap_or(MAX_INVOKE_BODY_BYTES),
297            signed_http,
298            source_path: None,
299        })
300    }
301}
302
303fn load_signed_http_config(file: SignedHttpConfigFile) -> anyhow::Result<SignedHttpRuntimeConfig> {
304    let allowed_leaders = match (file.allowed_leaders, file.allowed_leaders_path) {
305        (Some(inline), _) => AllowedLeaders::try_from(inline).map_err(anyhow::Error::new)?,
306        (None, Some(path)) => AllowedLeaders::from_path(path).map_err(anyhow::Error::new)?,
307        (None, None) => {
308            anyhow::bail!("signed_http requires either allowed_leaders or allowed_leaders_path")
309        }
310    };
311    let allowed_leaders = Arc::new(allowed_leaders);
312
313    if file.tools.is_empty() {
314        anyhow::bail!("signed_http.tools must contain at least one tool entry");
315    }
316
317    let mut tools: BTreeMap<String, SignedHttpToolRuntimeConfig> = BTreeMap::new();
318    for (tool_id, tool) in file.tools {
319        let context_timestamp_window_ms = tool
320            .context_timestamp_window_ms
321            .unwrap_or(DEFAULT_CONTEXT_TIMESTAMP_WINDOW_MS);
322        let replay_cache_ttl_ms = tool
323            .replay_cache_ttl_ms
324            .unwrap_or(DEFAULT_REPLAY_CACHE_TTL_MS);
325        if replay_cache_ttl_ms == 0 {
326            anyhow::bail!(
327                "invalid signed_http.tools[\"{tool_id}\"].replay_cache_ttl_ms: must be greater than zero"
328            );
329        }
330        let response_signing_key = tool
331            .response_signing_key
332            .as_deref()
333            .map(parse_ed25519_signing_key)
334            .transpose()
335            .map_err(|e| {
336                anyhow::anyhow!(
337                    "invalid signed_http.tools[\"{tool_id}\"].response_signing_key: {e}"
338                )
339            })?;
340        tools.insert(
341            tool_id,
342            SignedHttpToolRuntimeConfig {
343                response_signing_key,
344                require_client_certificate: tool.require_client_certificate,
345                context_timestamp_window_ms,
346                replay_cache_ttl_ms,
347            },
348        );
349    }
350
351    Ok(SignedHttpRuntimeConfig {
352        allowed_leaders,
353        tools,
354    })
355}
356
357/// Internal config holder with automatic file watching.
358///
359/// This is used internally by the runtime to enable hot-reload of configuration
360/// without requiring a process restart. When the config file changes, the new
361/// configuration is automatically loaded.
362#[doc(hidden)]
363pub struct Config {
364    config: Arc<RwLock<Arc<ToolkitRuntimeConfig>>>,
365    _watcher: Option<RecommendedWatcher>,
366}
367
368impl Config {
369    /// Create a new config watcher from the environment.
370    ///
371    /// If [`ENV_TOOLKIT_CONFIG_PATH`] is set, starts a file watcher that reloads
372    /// config on changes automatically.
373    #[doc(hidden)]
374    #[cfg(test)]
375    pub async fn from_env() -> anyhow::Result<Arc<Self>> {
376        let path = std::env::var(ENV_TOOLKIT_CONFIG_PATH)
377            .ok()
378            .map(PathBuf::from);
379
380        let initial_config = match &path {
381            Some(p) => ToolkitRuntimeConfig::from_path(p)?,
382            None => ToolkitRuntimeConfig::default_for_runtime(),
383        };
384
385        let config = Arc::new(RwLock::new(Arc::new(initial_config)));
386
387        let watcher = if let Some(ref p) = path {
388            Some(Self::start_watcher(p.clone(), Arc::clone(&config))?)
389        } else {
390            None
391        };
392
393        Ok(Arc::new(Self {
394            config,
395            _watcher: watcher,
396        }))
397    }
398
399    /// Wrap an existing config, watching its source file if it has one.
400    ///
401    /// If the config was loaded from a file (has a `source_path`), a file watcher
402    /// is set up for automatic hot-reload. Otherwise, the config is wrapped without
403    /// file watching.
404    #[doc(hidden)]
405    pub fn from_config(config: Arc<ToolkitRuntimeConfig>) -> Arc<Self> {
406        let path = config.source_path().map(|p| p.to_path_buf());
407        let config_holder = Arc::new(RwLock::new(config));
408
409        let watcher = path.and_then(|p| {
410            Self::start_watcher(p, Arc::clone(&config_holder))
411                .map_err(|e| {
412                    tracing::warn!("Failed to start config file watcher: {e}");
413                    e
414                })
415                .ok()
416        });
417
418        Arc::new(Self {
419            config: config_holder,
420            _watcher: watcher,
421        })
422    }
423
424    /// Get the current configuration.
425    #[doc(hidden)]
426    pub fn current(&self) -> Arc<ToolkitRuntimeConfig> {
427        self.config.read().unwrap().clone()
428    }
429
430    fn start_watcher(
431        path: PathBuf,
432        config: Arc<RwLock<Arc<ToolkitRuntimeConfig>>>,
433    ) -> anyhow::Result<RecommendedWatcher> {
434        let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(1);
435
436        let mut watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
437            if let Ok(event) = res {
438                if event.kind.is_modify() || event.kind.is_create() {
439                    // Non-blocking send - if channel is full, we'll catch the next event
440                    let _ = tx.try_send(());
441                }
442            }
443        })?;
444
445        // Watch the parent directory for ConfigMap atomic updates
446        let watch_path = path.parent().unwrap_or(&path);
447        watcher.watch(watch_path, RecursiveMode::NonRecursive)?;
448
449        tracing::info!("Started config file watcher for {}", path.display());
450
451        // Spawn reload task
452        let reload_path = path.clone();
453        tokio::spawn(async move {
454            let debounce_duration = Duration::from_millis(500);
455            let poll_interval = Duration::from_secs(2);
456            let mut poll_tick = tokio::time::interval(poll_interval);
457            let mut last_modified = file_modified(reload_path.clone()).await;
458
459            loop {
460                tokio::select! {
461                    maybe_event = rx.recv() => {
462                        if maybe_event.is_none() {
463                            break;
464                        }
465
466                        // Debounce writes that arrive in a burst.
467                        tokio::time::sleep(debounce_duration).await;
468                        while rx.try_recv().is_ok() {}
469                    }
470                    _ = poll_tick.tick() => {
471                        let current_modified = file_modified(reload_path.clone()).await;
472
473                        if current_modified == last_modified {
474                            continue;
475                        }
476                    }
477                }
478
479                match reload_config(reload_path.clone()).await {
480                    Ok((new_config, current_modified)) => {
481                        last_modified = current_modified;
482                        let mut guard = config.write().unwrap();
483                        *guard = Arc::new(new_config);
484                        tracing::info!("Reloaded toolkit config from {}", reload_path.display());
485                    }
486                    Err(e) => {
487                        tracing::error!(
488                            "Failed to reload toolkit config from {}: {e}",
489                            reload_path.display()
490                        );
491                        // Keep using old config
492                    }
493                }
494            }
495        });
496
497        Ok(watcher)
498    }
499}
500
501async fn file_modified(path: PathBuf) -> Option<std::time::SystemTime> {
502    tokio::task::spawn_blocking(move || fs::metadata(path).and_then(|meta| meta.modified()).ok())
503        .await
504        .unwrap_or(None)
505}
506
507async fn reload_config(
508    path: PathBuf,
509) -> anyhow::Result<(ToolkitRuntimeConfig, Option<std::time::SystemTime>)> {
510    tokio::task::spawn_blocking(move || {
511        let config = ToolkitRuntimeConfig::from_path(&path)?;
512        let modified = fs::metadata(&path).and_then(|meta| meta.modified()).ok();
513        Ok((config, modified))
514    })
515    .await
516    .context("config reload task failed")?
517}
518
519#[cfg(test)]
520mod tests {
521    use {
522        super::*,
523        crate::test_utils::ENV_VAR_LOCK,
524        serde_json::{json, Map},
525    };
526
527    #[test]
528    fn invocation_body_limit_preserves_existing_operator_settings() {
529        let defaults = ToolkitRuntimeConfig::from_json_str("{}").unwrap();
530        assert_eq!(defaults.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
531        for limit in [
532            0,
533            10 * 1024 * 1024,
534            MAX_INVOKE_BODY_BYTES - 1,
535            MAX_INVOKE_BODY_BYTES,
536            MAX_INVOKE_BODY_BYTES + 1,
537            u64::MAX,
538        ] {
539            let config = ToolkitRuntimeConfig::from_json_str(
540                &json!({"invoke_max_body_bytes": limit}).to_string(),
541            )
542            .unwrap();
543            assert_eq!(config.invoke_max_body_bytes(), limit);
544        }
545    }
546
547    fn make_config_json(
548        tool_id: &str,
549        tool_sk_hex: &str,
550        leader_id: &str,
551        leader_pk_hex: &str,
552    ) -> String {
553        let mut tools = Map::new();
554        tools.insert(
555            tool_id.to_string(),
556            json!({
557                "response_signing_key": tool_sk_hex,
558            }),
559        );
560
561        serde_json::to_string(&json!({
562            "signed_http": {
563                "mode": "required",
564                "allowed_leaders": {
565                    "version": 1,
566                    "leaders": [{
567                        "leader_id": leader_id,
568                        "keys": [{
569                            "kid": 0,
570                            "public_key": leader_pk_hex,
571                        }],
572                    }],
573                },
574                "tools": tools,
575            },
576        }))
577        .unwrap()
578    }
579
580    #[test]
581    fn parse_signed_http_inline_config() {
582        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
583        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
584        let tool_id = "xyz.demo.tool@1";
585        let tool_sk_hex = hex::encode([9u8; 32]);
586
587        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
588        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
589
590        assert_eq!(cfg.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
591        assert!(cfg.signed_http_is_required());
592        assert!(cfg.has_tool(tool_id));
593        assert!(!cfg.signed_http().unwrap().tools[tool_id].require_client_certificate);
594        assert_eq!(
595            cfg.signed_http().unwrap().tools[tool_id].context_timestamp_window_ms,
596            DEFAULT_CONTEXT_TIMESTAMP_WINDOW_MS
597        );
598        assert!(cfg.signed_http().unwrap().tools[tool_id]
599            .response_signing_key
600            .is_some());
601
602        assert!(cfg
603            .signed_http()
604            .unwrap()
605            .allowed_leaders
606            .source_path()
607            .is_none());
608    }
609
610    #[test]
611    fn parse_verification_only_tool_config() {
612        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
613        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
614        let tool_id = "xyz.demo.tool@1";
615        let cfg_json = serde_json::to_string(&json!({
616            "signed_http": {
617                "mode": "required",
618                "allowed_leaders": {
619                    "version": 1,
620                    "leaders": [{
621                        "leader_id": "0x1111",
622                        "keys": [{
623                            "kid": 0,
624                            "public_key": leader_pk_hex,
625                        }],
626                    }],
627                },
628                "tools": {
629                    tool_id: {
630                "context_timestamp_window_ms": 9_000,
631                "replay_cache_ttl_ms": 60_000,
632                    },
633                },
634            },
635        }))
636        .unwrap();
637
638        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
639        let tool = &cfg.signed_http().unwrap().tools[tool_id];
640
641        assert!(tool.response_signing_key.is_none());
642        assert!(!tool.require_client_certificate);
643        assert_eq!(tool.context_timestamp_window_ms, 9_000);
644        assert_eq!(tool.replay_cache_ttl_ms, 60_000);
645    }
646
647    #[test]
648    fn client_certificate_requirement_is_default_off_and_per_tool() {
649        let leader = SigningKey::from_bytes(&[7u8; 32]);
650        let cfg_json = serde_json::to_string(&json!({
651            "signed_http": {
652                "mode": "required",
653                "allowed_leaders": {
654                    "version": 1,
655                    "leaders": [{
656                        "leader_id": "leader",
657                        "keys": [{
658                            "kid": 0,
659                            "public_key": hex::encode(leader.verifying_key().to_bytes()),
660                        }],
661                    }],
662                },
663                "tools": {
664                    "xyz.required@1": { "require_client_certificate": true },
665                    "xyz.default@1": {},
666                },
667            },
668        }))
669        .unwrap();
670        let config = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
671        let tools = &config.signed_http().unwrap().tools;
672
673        assert!(tools["xyz.required@1"].require_client_certificate);
674        assert!(!tools["xyz.default@1"].require_client_certificate);
675    }
676
677    #[test]
678    fn parse_signed_http_from_path() {
679        let leader_sk = SigningKey::from_bytes(&[5u8; 32]);
680        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
681        let tool_sk_hex = hex::encode([6u8; 32]);
682
683        let allowlist_json = serde_json::to_string(&json!({
684            "version": 1,
685            "leaders": [{
686                "leader_id": "0x9999",
687                "keys": [{
688                    "kid": 0,
689                    "public_key": leader_pk_hex,
690                }],
691            }],
692        }))
693        .unwrap();
694
695        let file_name = format!(
696            "nexus-allowlist-{}.json",
697            std::time::SystemTime::now()
698                .duration_since(std::time::UNIX_EPOCH)
699                .unwrap()
700                .as_nanos()
701        );
702        let path = std::env::temp_dir().join(file_name);
703        fs::write(&path, allowlist_json).unwrap();
704
705        let cfg_json = serde_json::to_string(&json!({
706            "signed_http": {
707                "mode": "required",
708                "allowed_leaders_path": path.display().to_string(),
709                "tools": {
710                    "xyz.demo.tool@1": {
711                        "response_signing_key": tool_sk_hex,
712                    },
713                },
714            },
715        }))
716        .unwrap();
717
718        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
719        assert!(cfg.signed_http_is_required());
720        assert!(cfg.has_tool("xyz.demo.tool@1"));
721        assert_eq!(
722            cfg.signed_http().unwrap().allowed_leaders.source_path(),
723            Some(path.as_path())
724        );
725    }
726
727    #[test]
728    fn signed_http_disabled_is_ignored() {
729        let cfg_json = serde_json::to_string(&json!({
730            "signed_http": {
731                "mode": "disabled",
732                "tools": {
733                    "demo": { "require_client_certificate": true },
734                },
735            },
736        }))
737        .unwrap();
738        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
739        assert!(!cfg.signed_http_is_required());
740    }
741
742    #[test]
743    fn signed_http_requires_allowlist() {
744        let cfg_json = serde_json::to_string(&json!({
745            "signed_http": {
746                "mode": "required",
747                "tools": {
748                    "demo": {},
749                },
750            },
751        }))
752        .unwrap();
753        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
754    }
755
756    #[test]
757    fn signed_http_requires_tool_entries() {
758        let cfg_json = serde_json::to_string(&json!({
759            "signed_http": {
760                "mode": "required",
761                "allowed_leaders": {
762                    "version": 1,
763                    "leaders": [],
764                },
765            },
766        }))
767        .unwrap();
768        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
769    }
770
771    #[test]
772    fn removed_signed_http_claim_fields_are_rejected() {
773        let cfg_json = serde_json::to_string(&json!({
774            "signed_http": {
775                "mode": "disabled",
776                "max_clock_skew_ms": 10,
777            },
778        }))
779        .unwrap();
780        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
781
782        let cfg_json = serde_json::to_string(&json!({
783            "signed_http": {
784                "mode": "required",
785                "allowed_leaders": { "version": 1, "leaders": [] },
786                "tools": {
787                    "demo": {
788                        "tool_kid": 0,
789                        "response_signing_key": hex::encode([7; 32]),
790                    },
791                },
792            },
793        }))
794        .unwrap();
795        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
796    }
797
798    #[test]
799    fn rejects_obsolete_top_level_version() {
800        let cfg_json = serde_json::to_string(&json!({
801            "version": 1,
802        }))
803        .unwrap();
804        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
805    }
806
807    #[test]
808    fn from_path_sets_source_path() {
809        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
810        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
811        let tool_id = "xyz.demo.tool@1";
812        let tool_sk_hex = hex::encode([9u8; 32]);
813
814        let file_name = format!(
815            "nexus-source-path-test-{}.json",
816            std::time::SystemTime::now()
817                .duration_since(std::time::UNIX_EPOCH)
818                .unwrap()
819                .as_nanos()
820        );
821        let path = std::env::temp_dir().join(&file_name);
822
823        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
824        fs::write(&path, &cfg_json).unwrap();
825
826        let cfg = ToolkitRuntimeConfig::from_path(&path).unwrap();
827
828        // Verify source_path is set correctly
829        assert_eq!(cfg.source_path(), Some(path.as_path()));
830
831        // Cleanup
832        let _ = fs::remove_file(&path);
833    }
834
835    #[test]
836    fn from_path_error_on_missing_file() {
837        let result = ToolkitRuntimeConfig::from_path("/nonexistent/path/config.json");
838        assert!(result.is_err());
839        let err = format!("{:?}", result.err().unwrap());
840        assert!(err.contains("failed to read"));
841    }
842
843    #[test]
844    fn from_path_error_on_invalid_json() {
845        let file_name = format!(
846            "nexus-invalid-json-test-{}.json",
847            std::time::SystemTime::now()
848                .duration_since(std::time::UNIX_EPOCH)
849                .unwrap()
850                .as_nanos()
851        );
852        let path = std::env::temp_dir().join(&file_name);
853
854        fs::write(&path, "{ not valid json }").unwrap();
855
856        let result = ToolkitRuntimeConfig::from_path(&path);
857        assert!(result.is_err());
858        let err = format!("{:?}", result.err().unwrap());
859        assert!(err.contains("failed to parse"));
860
861        // Cleanup
862        let _ = fs::remove_file(&path);
863    }
864
865    #[test]
866    fn from_json_str_has_no_source_path() {
867        let cfg_json = serde_json::to_string(&json!({})).unwrap();
868        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
869
870        // Config loaded from string has no source path
871        assert!(cfg.source_path().is_none());
872    }
873
874    #[allow(clippy::await_holding_lock)]
875    #[tokio::test]
876    async fn config_watcher_loads_default_without_env_var() {
877        let _guard = ENV_VAR_LOCK.lock().unwrap();
878
879        // Ensure env var is not set
880        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
881
882        let watcher = Config::from_env().await.unwrap();
883        let config = watcher.current();
884
885        // Default config has no signed HTTP
886        assert!(!config.signed_http_is_required());
887        assert_eq!(config.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
888    }
889
890    #[allow(clippy::await_holding_lock)]
891    #[tokio::test]
892    async fn config_watcher_loads_from_file() {
893        let _guard = ENV_VAR_LOCK.lock().unwrap();
894
895        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
896        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
897        let tool_id = "xyz.demo.tool@1";
898        let tool_sk_hex = hex::encode([9u8; 32]);
899
900        // Create config file
901        let file_name = format!(
902            "nexus-watcher-test-{}.json",
903            std::time::SystemTime::now()
904                .duration_since(std::time::UNIX_EPOCH)
905                .unwrap()
906                .as_nanos()
907        );
908        let path = std::env::temp_dir().join(&file_name);
909
910        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
911        fs::write(&path, &cfg_json).unwrap();
912
913        // Set env var and create watcher
914        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());
915
916        let watcher = Config::from_env().await.unwrap();
917        let config = watcher.current();
918
919        // Verify config loaded correctly
920        assert_eq!(config.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
921        assert!(config.signed_http_is_required());
922        assert!(config.has_tool(tool_id));
923
924        // Cleanup
925        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
926        let _ = fs::remove_file(&path);
927    }
928
929    #[allow(clippy::await_holding_lock)]
930    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
931    async fn config_watcher_reloads_on_file_change() {
932        let _guard = ENV_VAR_LOCK.lock().unwrap();
933
934        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
935        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
936        let tool_id = "xyz.demo.tool@1";
937        let tool_sk_hex = hex::encode([9u8; 32]);
938
939        // Create initial config file
940        let file_name = format!(
941            "nexus-watcher-reload-test-{}.json",
942            std::time::SystemTime::now()
943                .duration_since(std::time::UNIX_EPOCH)
944                .unwrap()
945                .as_nanos()
946        );
947        let path = std::env::temp_dir().join(&file_name);
948
949        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
950        fs::write(&path, &cfg_json).unwrap();
951
952        // Set env var and create watcher
953        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());
954
955        let watcher = Config::from_env().await.unwrap();
956
957        // Verify initial config
958        let config = watcher.current();
959        assert_eq!(config.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
960
961        assert_eq!(
962            config.signed_http().unwrap().tools[tool_id].replay_cache_ttl_ms,
963            DEFAULT_REPLAY_CACHE_TTL_MS
964        );
965
966        // Update the config file with new values
967        let new_cfg_json = serde_json::to_string(&json!({
968            "signed_http": {
969                "mode": "required",
970                "allowed_leaders": {
971                    "version": 1,
972                    "leaders": [{
973                        "leader_id": "0x1111",
974                        "keys": [{
975                            "kid": 0,
976                            "public_key": leader_pk_hex,
977                        }],
978                    }],
979                },
980                "tools": {
981                    "xyz.demo.tool@1": {
982                        "response_signing_key": tool_sk_hex,
983                        "replay_cache_ttl_ms": DEFAULT_REPLAY_CACHE_TTL_MS + 1,
984                    },
985                },
986            },
987        }))
988        .unwrap();
989        fs::write(&path, &new_cfg_json).unwrap();
990
991        // Wait for debounce (500ms) + some buffer
992        tokio::time::sleep(std::time::Duration::from_millis(700)).await;
993
994        // Verify config was reloaded
995        let config = watcher.current();
996        assert_eq!(config.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
997
998        assert_eq!(
999            config.signed_http().unwrap().tools[tool_id].replay_cache_ttl_ms,
1000            DEFAULT_REPLAY_CACHE_TTL_MS + 1
1001        );
1002
1003        // Cleanup
1004        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
1005        let _ = fs::remove_file(&path);
1006    }
1007
1008    #[allow(clippy::await_holding_lock)]
1009    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1010    async fn config_watcher_keeps_old_on_invalid_update() {
1011        let _guard = ENV_VAR_LOCK.lock().unwrap();
1012
1013        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
1014        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
1015        let tool_id = "xyz.demo.tool@1";
1016        let tool_sk_hex = hex::encode([9u8; 32]);
1017
1018        // Create initial config file
1019        let file_name = format!(
1020            "nexus-watcher-invalid-test-{}.json",
1021            std::time::SystemTime::now()
1022                .duration_since(std::time::UNIX_EPOCH)
1023                .unwrap()
1024                .as_nanos()
1025        );
1026        let path = std::env::temp_dir().join(&file_name);
1027
1028        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
1029        fs::write(&path, &cfg_json).unwrap();
1030
1031        // Set env var and create watcher
1032        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());
1033
1034        let watcher = Config::from_env().await.unwrap();
1035
1036        // Verify initial config
1037        let config = watcher.current();
1038        assert_eq!(config.invoke_max_body_bytes(), MAX_INVOKE_BODY_BYTES);
1039
1040        // Write invalid JSON to config file
1041        let previous_config = config;
1042        fs::write(&path, "{ invalid json }").unwrap();
1043
1044        // Wait for debounce + buffer
1045        tokio::time::sleep(std::time::Duration::from_millis(700)).await;
1046
1047        // Config should still be the old one (invalid reload is ignored)
1048        let config = watcher.current();
1049        assert!(Arc::ptr_eq(&previous_config, &config));
1050
1051        // Cleanup
1052        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
1053        let _ = fs::remove_file(&path);
1054    }
1055}