Skip to main content

lean_ctx/http_server/
config.rs

1use std::path::PathBuf;
2
3use anyhow::{Result, anyhow};
4use rmcp::transport::StreamableHttpServerConfig;
5
6use crate::core::a2a::relay::RelayPeerTableV1;
7use crate::core::a2a::task::TaskAuthorityConfigV1;
8
9const MAX_ID_LEN: usize = 64;
10
11pub(super) fn sanitize_id(raw: &str) -> String {
12    let trimmed = raw.trim();
13    if trimmed.is_empty() {
14        return "default".to_string();
15    }
16    let cleaned: String = trimmed
17        .chars()
18        .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
19        .take(MAX_ID_LEN)
20        .collect();
21    if cleaned.is_empty() {
22        "default".to_string()
23    } else {
24        cleaned
25    }
26}
27
28#[derive(Clone, Debug)]
29pub struct HttpServerConfig {
30    pub host: String,
31    pub port: u16,
32    pub project_root: PathBuf,
33    pub auth_token: Option<String>,
34    pub a2a_signing_key: Option<String>,
35    pub a2a_recipient_id: Option<String>,
36    pub a2a_tenant_id: Option<String>,
37    pub a2a_project_id: Option<String>,
38    pub a2a_peers: RelayPeerTableV1,
39    pub a2a_quotas: super::relay_rate::RelayQuotaConfig,
40    pub a2a_task_authority: TaskAuthorityConfigV1,
41    pub stateful_mode: bool,
42    pub json_response: bool,
43    pub disable_host_check: bool,
44    pub allowed_hosts: Vec<String>,
45    pub max_body_bytes: usize,
46    pub max_concurrency: usize,
47    pub max_rps: u32,
48    pub rate_burst: u32,
49    pub request_timeout_ms: u64,
50}
51
52impl Default for HttpServerConfig {
53    fn default() -> Self {
54        let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
55        Self {
56            host: "127.0.0.1".to_string(),
57            port: 8080,
58            project_root,
59            auth_token: None,
60            a2a_signing_key: None,
61            a2a_recipient_id: None,
62            a2a_tenant_id: None,
63            a2a_project_id: None,
64            a2a_peers: RelayPeerTableV1::default(),
65            a2a_quotas: super::relay_rate::RelayQuotaConfig::default(),
66            a2a_task_authority: TaskAuthorityConfigV1::default(),
67            stateful_mode: false,
68            json_response: true,
69            disable_host_check: false,
70            allowed_hosts: Vec::new(),
71            max_body_bytes: 2 * 1024 * 1024,
72            max_concurrency: 32,
73            max_rps: 50,
74            rate_burst: 100,
75            request_timeout_ms: 30_000,
76        }
77    }
78}
79
80impl HttpServerConfig {
81    pub(super) fn relay_quota_state(&self) -> Result<Option<super::relay_rate::RelayQuotaState>> {
82        self.a2a_quotas.validate().map_err(|error| anyhow!(error))?;
83        if self.a2a_peers.peers.is_empty() {
84            return Ok(None);
85        }
86        let peers = self
87            .a2a_peers
88            .peers
89            .iter()
90            .map(|peer| peer.peer_id.clone())
91            .collect::<Vec<_>>();
92        super::relay_rate::RelayQuotaState::new(
93            self.a2a_quotas,
94            &peers,
95            self.a2a_tenant_id.as_deref().unwrap_or(""),
96            self.a2a_project_id.as_deref().unwrap_or(""),
97            std::time::Instant::now(),
98        )
99        .map(Some)
100        .map_err(|error| anyhow!(error))
101    }
102
103    pub fn validate(&self) -> Result<()> {
104        self.relay_quota_state()?;
105        let host = self.host.trim().to_lowercase();
106        let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
107        if !is_loopback && self.auth_token.as_deref().unwrap_or("").is_empty() {
108            return Err(anyhow!(
109                "Refusing to bind to host='{host}' without auth. Provide --auth-token (or bind to 127.0.0.1)."
110            ));
111        }
112        if self.a2a_signing_key.as_ref().is_some_and(String::is_empty) {
113            return Err(anyhow!("a2a_signing_key must not be empty"));
114        }
115        self.a2a_peers
116            .validate(false)
117            .map_err(|error| anyhow!("invalid a2a peer table: {error}"))?;
118        self.a2a_peers
119            .reject_shared_secret()
120            .map_err(|error| anyhow!("invalid a2a peer credentials: {error}"))?;
121        if !self.a2a_peers.peers.is_empty() && self.a2a_recipient_id.is_none() {
122            return Err(anyhow!(
123                "a2a_recipient_id is required when relay peers are configured"
124            ));
125        }
126        if self.a2a_signing_key.is_some() && self.a2a_signing_key == self.auth_token {
127            return Err(anyhow!("a2a_signing_key must be distinct from auth_token"));
128        }
129        if self.a2a_signing_key.is_some() {
130            for (name, value) in [
131                ("a2a_recipient_id", self.a2a_recipient_id.as_deref()),
132                ("a2a_tenant_id", self.a2a_tenant_id.as_deref()),
133                ("a2a_project_id", self.a2a_project_id.as_deref()),
134            ] {
135                if value.is_none_or(str::is_empty) {
136                    return Err(anyhow!("{name} is required when A2A signing is enabled"));
137                }
138            }
139        }
140        // Trust policy is authority: a policy that does not fully validate is
141        // never served, and its Ed25519 material must not be the bearer token
142        // or the HMAC channel secret.
143        self.a2a_task_authority
144            .validate()
145            .map_err(|error| anyhow!("invalid a2a task authority policy: {error}"))?;
146        for secret in [self.auth_token.as_deref(), self.a2a_signing_key.as_deref()]
147            .into_iter()
148            .flatten()
149        {
150            self.a2a_task_authority
151                .reject_shared_secret(secret)
152                .map_err(|error| anyhow!(error.to_string()))?;
153        }
154        if !self.a2a_task_authority.peers.is_empty() && self.a2a_signing_key.is_none() {
155            return Err(anyhow!(
156                "a2a_signing_key is required when a task authority policy is configured"
157            ));
158        }
159        if !self.a2a_task_authority.peers.is_empty()
160            && (self.a2a_recipient_id.is_none()
161                || self.a2a_tenant_id.is_none()
162                || self.a2a_project_id.is_none())
163        {
164            return Err(anyhow!(
165                "a2a recipient, tenant, and project ids are required when a task authority policy is configured"
166            ));
167        }
168        match (
169            self.a2a_tenant_id.as_deref(),
170            self.a2a_project_id.as_deref(),
171        ) {
172            (Some(tenant_id), Some(project_id)) => {
173                crate::core::a2a::dlq::DlqScope::new(tenant_id, project_id)
174                    .map_err(|error| anyhow!(error.to_string()))?;
175            }
176            (None, None) => {}
177            _ => {
178                return Err(anyhow!(
179                    "a2a_tenant_id and a2a_project_id must be configured together"
180                ));
181            }
182        }
183        Ok(())
184    }
185
186    pub fn effective_auth_token(&self) -> Option<String> {
187        if let Some(ref token) = self.auth_token
188            && !token.is_empty()
189        {
190            return Some(token.clone());
191        }
192        let host = self.host.trim().to_lowercase();
193        let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
194        if is_loopback {
195            let auto_token = crate::core::session_token::generate_token();
196            eprintln!(
197                "[lean-ctx] Auto-generated auth token for loopback: {auto_token}\n\
198                 Pass as Bearer token or set --auth-token explicitly."
199            );
200            Some(auto_token)
201        } else {
202            None
203        }
204    }
205
206    pub(super) fn mcp_http_config(&self) -> StreamableHttpServerConfig {
207        let mut cfg = StreamableHttpServerConfig::default()
208            .with_stateful_mode(self.stateful_mode)
209            .with_json_response(self.json_response);
210
211        if self.disable_host_check {
212            tracing::warn!(
213                "⚠ --disable-host-check is active: DNS rebinding protection is OFF. \
214                 Do NOT use this in production or on non-loopback interfaces."
215            );
216            cfg = cfg.disable_allowed_hosts();
217            return cfg;
218        }
219
220        if !self.allowed_hosts.is_empty() {
221            cfg = cfg.with_allowed_hosts(self.allowed_hosts.clone());
222            return cfg;
223        }
224
225        // Keep rmcp's secure loopback defaults; also allow the configured host (if it's loopback).
226        let host = self.host.trim();
227        if host == "127.0.0.1" || host == "localhost" || host == "::1" {
228            cfg.allowed_hosts.push(host.to_string());
229        }
230
231        cfg
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::HttpServerConfig;
238
239    #[test]
240    fn a2a_signing_key_must_be_nonempty_and_distinct_from_bearer() {
241        let empty = HttpServerConfig {
242            a2a_signing_key: Some(String::new()),
243            ..HttpServerConfig::default()
244        };
245        assert!(empty.validate().is_err());
246
247        let reused = HttpServerConfig {
248            auth_token: Some("same-secret".to_string()),
249            a2a_signing_key: Some("same-secret".to_string()),
250            ..HttpServerConfig::default()
251        };
252        assert!(reused.validate().is_err());
253
254        let missing_scope = HttpServerConfig {
255            auth_token: Some("bearer-secret".to_string()),
256            a2a_signing_key: Some("signing-secret".to_string()),
257            ..HttpServerConfig::default()
258        };
259        assert!(missing_scope.validate().is_err());
260
261        let scoped = HttpServerConfig {
262            auth_token: Some("bearer-secret".to_string()),
263            a2a_signing_key: Some("signing-secret".to_string()),
264            a2a_recipient_id: Some("recipient".to_string()),
265            a2a_tenant_id: Some("tenant-a".to_string()),
266            a2a_project_id: Some("project-a".to_string()),
267            ..HttpServerConfig::default()
268        };
269        assert!(scoped.validate().is_ok());
270    }
271}