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