nexus-toolkit 2.0.0

Rust framework for building and serving Nexus Tools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! Toolkit runtime configuration.
//!
//! This module defines the single JSON config file consumed by the
//! `nexus-toolkit` HTTP runtime (see [`crate::bootstrap!`]).
//!
//! The goals are:
//! - Keep configuration deployment-friendly (one file mounted into the tool container/VM).
//! - Avoid per-tool env var naming schemes (like `NEXUS_TOOL_SIGNING_KEY_<SUFFIX>`).
//! - Tools need a local allowlist of permitted Leaders. A response signing key is optional.
//!
//! # Loading
//! The runtime loads this config from the path stored in [`ENV_TOOLKIT_CONFIG_PATH`].
//! If the env var is not set, safe defaults are used (signed HTTP disabled).
//!
//! # DoS protection: request body size
//! `/invoke` requests MUST include a `Content-Length` header and it MUST be less than or equal to
//! [`ToolkitRuntimeConfig::invoke_max_body_bytes`]. This is enforced using
//! `warp::body::content_length_limit`, which rejects requests without `Content-Length`.
//!
//! # Signed HTTP (application-layer signatures)
//! If the config includes a `signed_http` section in `required` mode, the runtime:
//! - Rejects any `/invoke` request that does not carry valid signature headers.
//! - Rejects any request signed by a Leader not present in the local allowlist.
//! - Signs the exact ordered BCS Tool output bytes when a response signing key is configured.
//!
//! Operational note: if you run tools behind a gateway/proxy, ensure it forwards the `X-Nexus-Sig-*`
//! headers. If these headers are stripped, signed HTTP will fail closed.
//!
//! The signature protocol itself lives in `nexus-sdk` under
//! [`nexus_sdk::signed_http::v3`](nexus_sdk::signed_http::v3).
//!
//! # Example config
//! ```json
//! {
//!   "invoke_max_body_bytes": 10485760,
//!   "signed_http": {
//!     "mode": "required",
//!     "allowed_leaders_path": "./allowed_leaders.json",
//!     "tools": {
//!       "xyz.dummy.tool@1": {
//!         "response_signing_key": "0000000000000000000000000000000000000000000000000000000000000000"
//!       }
//!     }
//!   }
//! }
//! ```
//!
//! # Example (Rust)
//! This example parses a config from JSON (no filesystem required) by embedding the
//! allowlist inline.
//!
//! ```
//! use {
//!     ed25519_dalek::SigningKey,
//!     nexus_toolkit::ToolkitRuntimeConfig,
//!     serde_json::{json, Map},
//! };
//!
//! let tool_id = "xyz.dummy.tool@1";
//! let tool_sk_hex = hex::encode([7u8; 32]);
//! let leader_sk = SigningKey::from_bytes(&[9u8; 32]);
//! let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
//!
//! let mut tools = Map::new();
//! tools.insert(
//!     tool_id.to_string(),
//!     json!({
//!         "response_signing_key": tool_sk_hex,
//!     }),
//! );
//!
//! let cfg_json = serde_json::to_string_pretty(&json!({
//!     "invoke_max_body_bytes": 123,
//!     "signed_http": {
//!         "mode": "required",
//!         "allowed_leaders": {
//!             "version": 1,
//!             "leaders": [{
//!                 "leader_id": "0x1111",
//!                 "keys": [{
//!                     "kid": 0,
//!                     "public_key": leader_pk_hex,
//!                 }],
//!             }],
//!         },
//!         "tools": tools,
//!     },
//! }))
//! .unwrap();
//!
//! let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
//! assert_eq!(cfg.invoke_max_body_bytes(), 123);
//! assert!(cfg.signed_http_is_required());
//! assert!(cfg.has_tool(tool_id));
//! ```

use {
    anyhow::Context as _,
    ed25519_dalek::SigningKey,
    nexus_sdk::signed_http::{
        keys::parse_ed25519_signing_key,
        v3::wire::{AllowedLeaders, AllowedLeadersFileV1},
    },
    notify::{Event, RecommendedWatcher, RecursiveMode, Watcher},
    serde::Deserialize,
    std::{
        collections::BTreeMap,
        fs,
        path::{Path, PathBuf},
        sync::{Arc, RwLock},
        time::Duration,
    },
};

/// Env var read by the toolkit runtime to locate its JSON config file.
pub const ENV_TOOLKIT_CONFIG_PATH: &str = "NEXUS_TOOLKIT_CONFIG_PATH";

const DEFAULT_INVOKE_MAX_BODY_BYTES: u64 = 10 * 1024 * 1024; // 10 MiB

/// Signed HTTP mode for the toolkit runtime.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SignedHttpMode {
    /// Do not require signature headers.
    Disabled,
    /// Reject any request missing/invalid signature headers.
    #[default]
    Required,
}

/// Fully loaded toolkit runtime config (validated + ready to use).
///
/// This type is primarily used internally by the runtime; it is public so the
/// config format can be documented and unit-tested.
#[derive(Clone)]
pub struct ToolkitRuntimeConfig {
    invoke_max_body_bytes: u64,
    signed_http: Option<SignedHttpRuntimeConfig>,
    source_path: Option<PathBuf>,
}

#[derive(Clone)]
pub(crate) struct SignedHttpRuntimeConfig {
    pub(crate) allowed_leaders: Arc<AllowedLeaders>,
    pub(crate) tools: BTreeMap<String, SignedHttpToolRuntimeConfig>,
}

#[derive(Clone)]
pub(crate) struct SignedHttpToolRuntimeConfig {
    /// Key used to attest successful Tool results.
    ///
    /// Request authentication does not depend on this key. When it is absent,
    /// the runtime still requires a valid signature from an allowed Leader and
    /// returns the successful result without a Tool signature.
    pub(crate) response_signing_key: Option<SigningKey>,
    pub(crate) replay_cache_ttl_ms: u64,
}

pub(crate) const DEFAULT_REPLAY_CACHE_TTL_MS: u64 = 300_000;

impl ToolkitRuntimeConfig {
    /// Load config from [`ENV_TOOLKIT_CONFIG_PATH`] if set, otherwise return defaults.
    pub fn from_env() -> anyhow::Result<Self> {
        let Some(path) = std::env::var(ENV_TOOLKIT_CONFIG_PATH).ok() else {
            return Ok(Self::default_for_runtime());
        };
        Self::from_path(path)
    }

    /// Parse config from a JSON file.
    pub fn from_path(path: impl AsRef<Path>) -> anyhow::Result<Self> {
        let path = path.as_ref();
        let bytes = fs::read(path).with_context(|| format!("failed to read {}", path.display()))?;
        let mut cfg = Self::from_json_bytes(&bytes).with_context(|| {
            format!(
                "failed to parse toolkit runtime config at {}",
                path.display()
            )
        })?;
        cfg.source_path = Some(path.to_path_buf());
        Ok(cfg)
    }

    /// Parse config from JSON bytes.
    pub fn from_json_bytes(bytes: &[u8]) -> anyhow::Result<Self> {
        let file: ToolkitRuntimeConfigFile =
            serde_json::from_slice(bytes).context("invalid JSON")?;
        Self::try_from(file)
    }

    /// Parse config from a JSON string.
    pub fn from_json_str(json: &str) -> anyhow::Result<Self> {
        Self::from_json_bytes(json.as_bytes())
    }

    /// Maximum allowed `/invoke` request body size in bytes.
    pub fn invoke_max_body_bytes(&self) -> u64 {
        self.invoke_max_body_bytes
    }

    /// True if the runtime requires signed HTTP requests.
    pub fn signed_http_is_required(&self) -> bool {
        self.signed_http.is_some()
    }

    /// Returns whether signed HTTP configuration exists for `tool_id`.
    pub fn has_tool(&self, tool_id: &str) -> bool {
        self.signed_http
            .as_ref()
            .is_some_and(|s| s.tools.contains_key(tool_id))
    }

    pub(crate) fn signed_http(&self) -> Option<&SignedHttpRuntimeConfig> {
        self.signed_http.as_ref()
    }

    fn default_for_runtime() -> Self {
        Self {
            invoke_max_body_bytes: DEFAULT_INVOKE_MAX_BODY_BYTES,
            signed_http: None,
            source_path: None,
        }
    }

    pub(crate) fn source_path(&self) -> Option<&Path> {
        self.source_path.as_deref()
    }
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ToolkitRuntimeConfigFile {
    #[serde(default)]
    pub invoke_max_body_bytes: Option<u64>,
    #[serde(default)]
    pub signed_http: Option<SignedHttpConfigFile>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SignedHttpConfigFile {
    /// Defaults to `required` when omitted.
    #[serde(default)]
    pub mode: SignedHttpMode,

    /// Path to an allowlist file (same schema as `AllowedLeadersFileV1`).
    #[serde(default)]
    pub allowed_leaders_path: Option<String>,

    /// Inline allowlist (useful for tests and simple deployments).
    #[serde(default)]
    pub allowed_leaders: Option<AllowedLeadersFileV1>,

    /// Per Tool authentication and response configuration, keyed by Tool id.
    #[serde(default)]
    pub tools: BTreeMap<String, SignedHttpToolConfigFile>,
}

#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct SignedHttpToolConfigFile {
    /// Optional hex or base64 encoding of a 32 byte Ed25519 private key.
    ///
    /// This also accepts Sui keytool encoding: base64 of `0x00 || sk32`.
    #[serde(default)]
    pub response_signing_key: Option<String>,

    /// Completed replay-entry lifetime in milliseconds. Defaults to five minutes.
    #[serde(default)]
    pub replay_cache_ttl_ms: Option<u64>,
}

impl TryFrom<ToolkitRuntimeConfigFile> for ToolkitRuntimeConfig {
    type Error = anyhow::Error;

    fn try_from(file: ToolkitRuntimeConfigFile) -> Result<Self, Self::Error> {
        let invoke_max_body_bytes = file
            .invoke_max_body_bytes
            .unwrap_or(DEFAULT_INVOKE_MAX_BODY_BYTES);

        let signed_http = match file.signed_http {
            None => None,
            Some(s) if s.mode == SignedHttpMode::Disabled => None,
            Some(s) => Some(load_signed_http_config(s)?),
        };

        Ok(Self {
            invoke_max_body_bytes,
            signed_http,
            source_path: None,
        })
    }
}

fn load_signed_http_config(file: SignedHttpConfigFile) -> anyhow::Result<SignedHttpRuntimeConfig> {
    let allowed_leaders = match (file.allowed_leaders, file.allowed_leaders_path) {
        (Some(inline), _) => AllowedLeaders::try_from(inline).map_err(anyhow::Error::new)?,
        (None, Some(path)) => AllowedLeaders::from_path(path).map_err(anyhow::Error::new)?,
        (None, None) => {
            anyhow::bail!("signed_http requires either allowed_leaders or allowed_leaders_path")
        }
    };
    let allowed_leaders = Arc::new(allowed_leaders);

    if file.tools.is_empty() {
        anyhow::bail!("signed_http.tools must contain at least one tool entry");
    }

    let mut tools: BTreeMap<String, SignedHttpToolRuntimeConfig> = BTreeMap::new();
    for (tool_id, tool) in file.tools {
        let replay_cache_ttl_ms = tool
            .replay_cache_ttl_ms
            .unwrap_or(DEFAULT_REPLAY_CACHE_TTL_MS);
        if replay_cache_ttl_ms == 0 {
            anyhow::bail!(
                "invalid signed_http.tools[\"{tool_id}\"].replay_cache_ttl_ms: must be greater than zero"
            );
        }
        let response_signing_key = tool
            .response_signing_key
            .as_deref()
            .map(parse_ed25519_signing_key)
            .transpose()
            .map_err(|e| {
                anyhow::anyhow!(
                    "invalid signed_http.tools[\"{tool_id}\"].response_signing_key: {e}"
                )
            })?;
        tools.insert(
            tool_id,
            SignedHttpToolRuntimeConfig {
                response_signing_key,
                replay_cache_ttl_ms,
            },
        );
    }

    Ok(SignedHttpRuntimeConfig {
        allowed_leaders,
        tools,
    })
}

/// Internal config holder with automatic file watching.
///
/// This is used internally by the runtime to enable hot-reload of configuration
/// without requiring a process restart. When the config file changes, the new
/// configuration is automatically loaded.
#[doc(hidden)]
pub struct Config {
    config: Arc<RwLock<Arc<ToolkitRuntimeConfig>>>,
    _watcher: Option<RecommendedWatcher>,
}

impl Config {
    /// Create a new config watcher from the environment.
    ///
    /// If [`ENV_TOOLKIT_CONFIG_PATH`] is set, starts a file watcher that reloads
    /// config on changes automatically.
    #[doc(hidden)]
    #[cfg(test)]
    pub async fn from_env() -> anyhow::Result<Arc<Self>> {
        let path = std::env::var(ENV_TOOLKIT_CONFIG_PATH)
            .ok()
            .map(PathBuf::from);

        let initial_config = match &path {
            Some(p) => ToolkitRuntimeConfig::from_path(p)?,
            None => ToolkitRuntimeConfig::default_for_runtime(),
        };

        let config = Arc::new(RwLock::new(Arc::new(initial_config)));

        let watcher = if let Some(ref p) = path {
            Some(Self::start_watcher(p.clone(), Arc::clone(&config))?)
        } else {
            None
        };

        Ok(Arc::new(Self {
            config,
            _watcher: watcher,
        }))
    }

    /// Wrap an existing config, watching its source file if it has one.
    ///
    /// If the config was loaded from a file (has a `source_path`), a file watcher
    /// is set up for automatic hot-reload. Otherwise, the config is wrapped without
    /// file watching.
    #[doc(hidden)]
    pub fn from_config(config: Arc<ToolkitRuntimeConfig>) -> Arc<Self> {
        let path = config.source_path().map(|p| p.to_path_buf());
        let config_holder = Arc::new(RwLock::new(config));

        let watcher = path.and_then(|p| {
            Self::start_watcher(p, Arc::clone(&config_holder))
                .map_err(|e| {
                    tracing::warn!("Failed to start config file watcher: {e}");
                    e
                })
                .ok()
        });

        Arc::new(Self {
            config: config_holder,
            _watcher: watcher,
        })
    }

    /// Get the current configuration.
    #[doc(hidden)]
    pub fn current(&self) -> Arc<ToolkitRuntimeConfig> {
        self.config.read().unwrap().clone()
    }

    fn start_watcher(
        path: PathBuf,
        config: Arc<RwLock<Arc<ToolkitRuntimeConfig>>>,
    ) -> anyhow::Result<RecommendedWatcher> {
        let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(1);

        let mut watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
            if let Ok(event) = res {
                if event.kind.is_modify() || event.kind.is_create() {
                    // Non-blocking send - if channel is full, we'll catch the next event
                    let _ = tx.try_send(());
                }
            }
        })?;

        // Watch the parent directory for ConfigMap atomic updates
        let watch_path = path.parent().unwrap_or(&path);
        watcher.watch(watch_path, RecursiveMode::NonRecursive)?;

        tracing::info!("Started config file watcher for {}", path.display());

        // Spawn reload task
        let reload_path = path.clone();
        tokio::spawn(async move {
            let debounce_duration = Duration::from_millis(500);
            let poll_interval = Duration::from_secs(2);
            let mut poll_tick = tokio::time::interval(poll_interval);
            let mut last_modified = file_modified(reload_path.clone()).await;

            loop {
                tokio::select! {
                    maybe_event = rx.recv() => {
                        if maybe_event.is_none() {
                            break;
                        }

                        // Debounce writes that arrive in a burst.
                        tokio::time::sleep(debounce_duration).await;
                        while rx.try_recv().is_ok() {}
                    }
                    _ = poll_tick.tick() => {
                        let current_modified = file_modified(reload_path.clone()).await;

                        if current_modified == last_modified {
                            continue;
                        }
                    }
                }

                match reload_config(reload_path.clone()).await {
                    Ok((new_config, current_modified)) => {
                        last_modified = current_modified;
                        let mut guard = config.write().unwrap();
                        *guard = Arc::new(new_config);
                        tracing::info!("Reloaded toolkit config from {}", reload_path.display());
                    }
                    Err(e) => {
                        tracing::error!(
                            "Failed to reload toolkit config from {}: {e}",
                            reload_path.display()
                        );
                        // Keep using old config
                    }
                }
            }
        });

        Ok(watcher)
    }
}

async fn file_modified(path: PathBuf) -> Option<std::time::SystemTime> {
    tokio::task::spawn_blocking(move || fs::metadata(path).and_then(|meta| meta.modified()).ok())
        .await
        .unwrap_or(None)
}

async fn reload_config(
    path: PathBuf,
) -> anyhow::Result<(ToolkitRuntimeConfig, Option<std::time::SystemTime>)> {
    tokio::task::spawn_blocking(move || {
        let config = ToolkitRuntimeConfig::from_path(&path)?;
        let modified = fs::metadata(&path).and_then(|meta| meta.modified()).ok();
        Ok((config, modified))
    })
    .await
    .context("config reload task failed")?
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::test_utils::ENV_VAR_LOCK,
        serde_json::{json, Map},
    };

    fn make_config_json(
        tool_id: &str,
        tool_sk_hex: &str,
        leader_id: &str,
        leader_pk_hex: &str,
    ) -> String {
        let mut tools = Map::new();
        tools.insert(
            tool_id.to_string(),
            json!({
                "response_signing_key": tool_sk_hex,
            }),
        );

        serde_json::to_string(&json!({
            "invoke_max_body_bytes": 123,
            "signed_http": {
                "mode": "required",
                "allowed_leaders": {
                    "version": 1,
                    "leaders": [{
                        "leader_id": leader_id,
                        "keys": [{
                            "kid": 0,
                            "public_key": leader_pk_hex,
                        }],
                    }],
                },
                "tools": tools,
            },
        }))
        .unwrap()
    }

    #[test]
    fn parse_signed_http_inline_config() {
        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let tool_sk_hex = hex::encode([9u8; 32]);

        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();

        assert_eq!(cfg.invoke_max_body_bytes(), 123);
        assert!(cfg.signed_http_is_required());
        assert!(cfg.has_tool(tool_id));
        assert!(cfg.signed_http().unwrap().tools[tool_id]
            .response_signing_key
            .is_some());

        assert!(cfg
            .signed_http()
            .unwrap()
            .allowed_leaders
            .source_path()
            .is_none());
    }

    #[test]
    fn parse_verification_only_tool_config() {
        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "required",
                "allowed_leaders": {
                    "version": 1,
                    "leaders": [{
                        "leader_id": "0x1111",
                        "keys": [{
                            "kid": 0,
                            "public_key": leader_pk_hex,
                        }],
                    }],
                },
                "tools": {
                    tool_id: {
                        "replay_cache_ttl_ms": 60_000,
                    },
                },
            },
        }))
        .unwrap();

        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
        let tool = &cfg.signed_http().unwrap().tools[tool_id];

        assert!(tool.response_signing_key.is_none());
        assert_eq!(tool.replay_cache_ttl_ms, 60_000);
    }

    #[test]
    fn parse_signed_http_from_path() {
        let leader_sk = SigningKey::from_bytes(&[5u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_sk_hex = hex::encode([6u8; 32]);

        let allowlist_json = serde_json::to_string(&json!({
            "version": 1,
            "leaders": [{
                "leader_id": "0x9999",
                "keys": [{
                    "kid": 0,
                    "public_key": leader_pk_hex,
                }],
            }],
        }))
        .unwrap();

        let file_name = format!(
            "nexus-allowlist-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(file_name);
        fs::write(&path, allowlist_json).unwrap();

        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "required",
                "allowed_leaders_path": path.display().to_string(),
                "tools": {
                    "xyz.demo.tool@1": {
                        "response_signing_key": tool_sk_hex,
                    },
                },
            },
        }))
        .unwrap();

        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
        assert!(cfg.signed_http_is_required());
        assert!(cfg.has_tool("xyz.demo.tool@1"));
        assert_eq!(
            cfg.signed_http().unwrap().allowed_leaders.source_path(),
            Some(path.as_path())
        );
    }

    #[test]
    fn signed_http_disabled_is_ignored() {
        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "disabled",
            },
        }))
        .unwrap();
        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();
        assert!(!cfg.signed_http_is_required());
    }

    #[test]
    fn signed_http_requires_allowlist() {
        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "required",
                "tools": {
                    "demo": {},
                },
            },
        }))
        .unwrap();
        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
    }

    #[test]
    fn signed_http_requires_tool_entries() {
        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "required",
                "allowed_leaders": {
                    "version": 1,
                    "leaders": [],
                },
            },
        }))
        .unwrap();
        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
    }

    #[test]
    fn removed_signed_http_claim_fields_are_rejected() {
        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "disabled",
                "max_clock_skew_ms": 10,
            },
        }))
        .unwrap();
        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());

        let cfg_json = serde_json::to_string(&json!({
            "signed_http": {
                "mode": "required",
                "allowed_leaders": { "version": 1, "leaders": [] },
                "tools": {
                    "demo": {
                        "tool_kid": 0,
                        "response_signing_key": hex::encode([7; 32]),
                    },
                },
            },
        }))
        .unwrap();
        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
    }

    #[test]
    fn rejects_obsolete_top_level_version() {
        let cfg_json = serde_json::to_string(&json!({
            "version": 1,
        }))
        .unwrap();
        assert!(ToolkitRuntimeConfig::from_json_str(&cfg_json).is_err());
    }

    #[test]
    fn from_path_sets_source_path() {
        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let tool_sk_hex = hex::encode([9u8; 32]);

        let file_name = format!(
            "nexus-source-path-test-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(&file_name);

        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
        fs::write(&path, &cfg_json).unwrap();

        let cfg = ToolkitRuntimeConfig::from_path(&path).unwrap();

        // Verify source_path is set correctly
        assert_eq!(cfg.source_path(), Some(path.as_path()));

        // Cleanup
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn from_path_error_on_missing_file() {
        let result = ToolkitRuntimeConfig::from_path("/nonexistent/path/config.json");
        assert!(result.is_err());
        let err = format!("{:?}", result.err().unwrap());
        assert!(err.contains("failed to read"));
    }

    #[test]
    fn from_path_error_on_invalid_json() {
        let file_name = format!(
            "nexus-invalid-json-test-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(&file_name);

        fs::write(&path, "{ not valid json }").unwrap();

        let result = ToolkitRuntimeConfig::from_path(&path);
        assert!(result.is_err());
        let err = format!("{:?}", result.err().unwrap());
        assert!(err.contains("failed to parse"));

        // Cleanup
        let _ = fs::remove_file(&path);
    }

    #[test]
    fn from_json_str_has_no_source_path() {
        let cfg_json = serde_json::to_string(&json!({})).unwrap();
        let cfg = ToolkitRuntimeConfig::from_json_str(&cfg_json).unwrap();

        // Config loaded from string has no source path
        assert!(cfg.source_path().is_none());
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn config_watcher_loads_default_without_env_var() {
        let _guard = ENV_VAR_LOCK.lock().unwrap();

        // Ensure env var is not set
        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);

        let watcher = Config::from_env().await.unwrap();
        let config = watcher.current();

        // Default config has no signed HTTP
        assert!(!config.signed_http_is_required());
        assert_eq!(config.invoke_max_body_bytes(), 10 * 1024 * 1024);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn config_watcher_loads_from_file() {
        let _guard = ENV_VAR_LOCK.lock().unwrap();

        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let tool_sk_hex = hex::encode([9u8; 32]);

        // Create config file
        let file_name = format!(
            "nexus-watcher-test-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(&file_name);

        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
        fs::write(&path, &cfg_json).unwrap();

        // Set env var and create watcher
        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());

        let watcher = Config::from_env().await.unwrap();
        let config = watcher.current();

        // Verify config loaded correctly
        assert_eq!(config.invoke_max_body_bytes(), 123);
        assert!(config.signed_http_is_required());
        assert!(config.has_tool(tool_id));

        // Cleanup
        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
        let _ = fs::remove_file(&path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn config_watcher_reloads_on_file_change() {
        let _guard = ENV_VAR_LOCK.lock().unwrap();

        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let tool_sk_hex = hex::encode([9u8; 32]);

        // Create initial config file
        let file_name = format!(
            "nexus-watcher-reload-test-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(&file_name);

        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
        fs::write(&path, &cfg_json).unwrap();

        // Set env var and create watcher
        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());

        let watcher = Config::from_env().await.unwrap();

        // Verify initial config
        let config = watcher.current();
        assert_eq!(config.invoke_max_body_bytes(), 123);

        // Update the config file with new values
        let new_cfg_json = serde_json::to_string(&json!({
            "invoke_max_body_bytes": 456,
            "signed_http": {
                "mode": "required",
                "allowed_leaders": {
                    "version": 1,
                    "leaders": [{
                        "leader_id": "0x1111",
                        "keys": [{
                            "kid": 0,
                            "public_key": leader_pk_hex,
                        }],
                    }],
                },
                "tools": {
                    "xyz.demo.tool@1": {
                        "response_signing_key": tool_sk_hex,
                    },
                },
            },
        }))
        .unwrap();
        fs::write(&path, &new_cfg_json).unwrap();

        // Wait for debounce (500ms) + some buffer
        tokio::time::sleep(std::time::Duration::from_millis(700)).await;

        // Verify config was reloaded
        let config = watcher.current();
        assert_eq!(config.invoke_max_body_bytes(), 456);

        // Cleanup
        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
        let _ = fs::remove_file(&path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn config_watcher_keeps_old_on_invalid_update() {
        let _guard = ENV_VAR_LOCK.lock().unwrap();

        let leader_sk = SigningKey::from_bytes(&[7u8; 32]);
        let leader_pk_hex = hex::encode(leader_sk.verifying_key().to_bytes());
        let tool_id = "xyz.demo.tool@1";
        let tool_sk_hex = hex::encode([9u8; 32]);

        // Create initial config file
        let file_name = format!(
            "nexus-watcher-invalid-test-{}.json",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let path = std::env::temp_dir().join(&file_name);

        let cfg_json = make_config_json(tool_id, &tool_sk_hex, "0x1111", &leader_pk_hex);
        fs::write(&path, &cfg_json).unwrap();

        // Set env var and create watcher
        std::env::set_var(ENV_TOOLKIT_CONFIG_PATH, path.display().to_string());

        let watcher = Config::from_env().await.unwrap();

        // Verify initial config
        let config = watcher.current();
        assert_eq!(config.invoke_max_body_bytes(), 123);

        // Write invalid JSON to config file
        fs::write(&path, "{ invalid json }").unwrap();

        // Wait for debounce + buffer
        tokio::time::sleep(std::time::Duration::from_millis(700)).await;

        // Config should still be the old one (invalid reload is ignored)
        let config = watcher.current();
        assert_eq!(config.invoke_max_body_bytes(), 123);

        // Cleanup
        std::env::remove_var(ENV_TOOLKIT_CONFIG_PATH);
        let _ = fs::remove_file(&path);
    }
}