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