Skip to main content

subspace_core/config/
mcp.rs

1use std::collections::BTreeMap;
2use std::net::{IpAddr, Ipv4Addr, SocketAddr};
3
4use serde::{Deserialize, Serialize};
5
6/// Saved MCP policy. A missing group is served by default.
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(default, rename_all = "camelCase")]
9#[non_exhaustive]
10// qual:allow(srp, god_struct) reason: "Serialized MCP policy intentionally contains listener settings and its group choices in one config section."
11pub struct McpSettings {
12    pub enabled: bool,
13    pub bind: IpAddr,
14    pub port: u16,
15    pub require_token: bool,
16    pub groups: BTreeMap<String, bool>,
17}
18
19impl Default for McpSettings {
20    fn default() -> Self {
21        Self {
22            enabled: false,
23            bind: IpAddr::V4(Ipv4Addr::LOCALHOST),
24            port: 7331,
25            require_token: false,
26            groups: BTreeMap::new(),
27        }
28    }
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
32#[error("{field}: {reason}")]
33#[non_exhaustive]
34pub struct McpFieldError {
35    pub field: &'static str,
36    pub reason: &'static str,
37}
38
39impl McpSettings {
40    /// Validates saved policy, including the non-loopback authentication rule.
41    pub fn validate(&self) -> Result<(), McpFieldError> {
42        Self::validate_fields(
43            &self.bind.to_string(),
44            &self.port.to_string(),
45            self.require_token,
46        )
47        .map(|_| ())
48    }
49
50    /// Validates text fields before a Settings draft becomes typed policy.
51    pub fn validate_fields(
52        bind: &str,
53        port: &str,
54        require_token: bool,
55    ) -> Result<SocketAddr, McpFieldError> {
56        let bind: IpAddr = bind.trim().parse().map_err(|_| McpFieldError {
57            field: "mcp.bind",
58            reason: "must be an IPv4 or IPv6 address",
59        })?;
60        let port = port
61            .trim()
62            .parse::<u16>()
63            .ok()
64            .filter(|port| *port != 0)
65            .ok_or(McpFieldError {
66                field: "mcp.port",
67                reason: "must be an integer from 1 to 65535",
68            })?;
69        if !bind.is_loopback() && !require_token {
70            return Err(McpFieldError {
71                field: "mcp.requireToken",
72                reason: "a non-loopback address needs a token",
73            });
74        }
75        Ok(SocketAddr::new(bind, port))
76    }
77
78    pub fn group_enabled(&self, id: &str) -> bool {
79        self.groups.get(id).copied().unwrap_or(true)
80    }
81
82    pub fn address(&self) -> SocketAddr {
83        SocketAddr::new(self.bind, self.port)
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::McpSettings;
90
91    #[test]
92    fn parser_defaults_warns_and_keeps_safe_policy() {
93        let parse = |text| crate::config::parse(text, std::path::Path::new("config.json"));
94        assert_eq!(parse("{}").0.mcp, McpSettings::default());
95        let (config, notices) = parse(
96            r#"{"mcp":{"enabled":true,"bind":"::1","port":7400,"requireToken":true,"groups":{"application":false,"future":true}}}"#,
97        );
98        assert!(notices.is_empty());
99        assert!(config.mcp.enabled);
100        assert_eq!(config.mcp.address().to_string(), "[::1]:7400");
101        assert!(!config.mcp.group_enabled("application"));
102        for text in [
103            r#"{"mcp":{"bind":"localhost"}}"#,
104            r#"{"mcp":{"port":70000}}"#,
105            r#"{"mcp":{"port":0}}"#,
106            r#"{"mcp":{"bind":"0.0.0.0","enabled":true}}"#,
107        ] {
108            let (config, notices) = parse(text);
109            assert!(!notices.is_empty());
110            assert!(config.mcp.validate().is_ok());
111            assert!(!config.mcp.enabled);
112        }
113    }
114
115    #[test]
116    fn defaults_are_local_off_and_groups_are_on() {
117        let settings = McpSettings::default();
118        assert!(!settings.enabled);
119        assert!(!settings.require_token);
120        assert!(settings.group_enabled("application"));
121        assert_eq!(settings.address().to_string(), "127.0.0.1:7331");
122        assert!(settings.validate().is_ok());
123    }
124
125    #[test]
126    fn draft_fields_reject_bad_addresses_ports_and_unsafe_policy() {
127        for bind in ["127.0.0.1", "::1"] {
128            for port in ["1", "65535"] {
129                assert!(McpSettings::validate_fields(bind, port, false).is_ok());
130            }
131        }
132        for port in ["0", "65536", "70000", "-1", "1.5", ""] {
133            assert_eq!(
134                McpSettings::validate_fields("::1", port, false)
135                    .unwrap_err()
136                    .field,
137                "mcp.port"
138            );
139        }
140        assert_eq!(
141            McpSettings::validate_fields("localhost", "7331", true)
142                .unwrap_err()
143                .field,
144            "mcp.bind"
145        );
146        assert_eq!(
147            McpSettings::validate_fields("0.0.0.0", "7331", false)
148                .unwrap_err()
149                .field,
150            "mcp.requireToken"
151        );
152        assert!(McpSettings::validate_fields("0.0.0.0", "7331", true).is_ok());
153    }
154}