Skip to main content

lean_ctx_cli/http_server/
config.rs

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