lean_ctx_cli/http_server/
config.rs1use 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 pub oauth: bool,
53 pub oauth_issuer: Option<String>,
55 pub oauth_state_dir: Option<PathBuf>,
57}
58
59impl Default for HttpServerConfig {
60 fn default() -> Self {
61 let project_root = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
62 Self {
63 host: "127.0.0.1".to_string(),
64 port: 8080,
65 project_root,
66 auth_token: None,
67 a2a_signing_key: None,
68 a2a_recipient_id: None,
69 a2a_tenant_id: None,
70 a2a_project_id: None,
71 a2a_peers: RelayPeerTableV1::default(),
72 a2a_quotas: super::relay_rate::RelayQuotaConfig::default(),
73 a2a_task_authority: TaskAuthorityConfigV1::default(),
74 stateful_mode: false,
75 json_response: true,
76 disable_host_check: false,
77 allowed_hosts: Vec::new(),
78 max_body_bytes: 2 * 1024 * 1024,
79 max_concurrency: 32,
80 max_rps: 50,
81 rate_burst: 100,
82 request_timeout_ms: 30_000,
83 oauth: false,
84 oauth_issuer: None,
85 oauth_state_dir: None,
86 }
87 }
88}
89
90impl HttpServerConfig {
91 pub(super) fn relay_quota_state(&self) -> Result<Option<super::relay_rate::RelayQuotaState>> {
92 self.a2a_quotas.validate().map_err(|error| anyhow!(error))?;
93 if self.a2a_peers.peers.is_empty() {
94 return Ok(None);
95 }
96 let peers = self
97 .a2a_peers
98 .peers
99 .iter()
100 .map(|peer| peer.peer_id.clone())
101 .collect::<Vec<_>>();
102 super::relay_rate::RelayQuotaState::new(
103 self.a2a_quotas,
104 &peers,
105 self.a2a_tenant_id.as_deref().unwrap_or(""),
106 self.a2a_project_id.as_deref().unwrap_or(""),
107 std::time::Instant::now(),
108 )
109 .map(Some)
110 .map_err(|error| anyhow!(error))
111 }
112
113 pub(super) fn oauth_enabled(&self) -> bool {
115 self.oauth || self.oauth_issuer.is_some()
116 }
117
118 pub(super) fn oauth_issuer_url(&self) -> Result<Option<String>> {
123 if !self.oauth_enabled() {
124 return Ok(None);
125 }
126 if let Some(raw) = self.oauth_issuer.as_deref() {
127 return super::oauth::canonical_issuer(raw)
128 .map(Some)
129 .map_err(|error| anyhow!(error));
130 }
131 let host = self.host.trim().to_lowercase();
132 match host.as_str() {
133 "127.0.0.1" | "localhost" => Ok(Some(format!("http://{host}:{}", self.port))),
134 "::1" => Ok(Some(format!("http://[::1]:{}", self.port))),
135 _ => Err(anyhow!(
136 "--oauth on host='{host}' needs --oauth-issuer https://<public host>"
137 )),
138 }
139 }
140
141 pub(super) fn oauth_exposure_warnings(&self) -> Vec<String> {
145 let mut warnings = Vec::new();
146 if !self.oauth_enabled() {
147 return warnings;
148 }
149 let host = self.host.trim().to_lowercase();
150 let loopback_bind = matches!(host.as_str(), "127.0.0.1" | "localhost" | "::1");
151 if !loopback_bind {
152 warnings.push(format!(
153 "OAuth is served on host='{host}' over plain HTTP: `serve` has no TLS. \
154 Put a TLS-terminating reverse proxy at the --oauth-issuer origin in front of it \
155 and keep port {} unreachable from other machines, or the instance token typed \
156 on the consent page and every OAuth token cross the network unencrypted.",
157 self.port
158 ));
159 }
160 let public_issuer = self
161 .oauth_issuer_url()
162 .ok()
163 .flatten()
164 .and_then(|issuer| reqwest::Url::parse(&issuer).ok())
165 .is_some_and(|url| {
166 !matches!(
167 url.host_str().map(|h| h.trim_matches(['[', ']'])),
168 Some("127.0.0.1" | "localhost" | "::1")
169 )
170 });
171 if public_issuer && self.auth_token.as_deref().is_none_or(str::is_empty) {
172 warnings.push(
173 "OAuth is published at a public --oauth-issuer, but no --auth-token is set: \
174 the consent page is guarded only by the token generated for this start, and \
175 grants are not bound to it. Set --auth-token (or LEAN_CTX_HTTP_TOKEN_FILE)."
176 .to_string(),
177 );
178 }
179 warnings
180 }
181
182 pub fn validate(&self) -> Result<()> {
183 self.relay_quota_state()?;
184 self.oauth_issuer_url()?;
185 let host = self.host.trim().to_lowercase();
186 let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
187 if !is_loopback && self.auth_token.as_deref().unwrap_or("").is_empty() {
188 let oauth_note = if self.oauth_enabled() {
189 " --oauth does not replace it: the owner approves every OAuth client with that token."
190 } else {
191 ""
192 };
193 return Err(anyhow!(
194 "Refusing to bind to host='{host}' without auth. Provide --auth-token (or bind to 127.0.0.1).{oauth_note}"
195 ));
196 }
197 if self.a2a_signing_key.as_ref().is_some_and(String::is_empty) {
198 return Err(anyhow!("a2a_signing_key must not be empty"));
199 }
200 self.a2a_peers
201 .validate(false)
202 .map_err(|error| anyhow!("invalid a2a peer table: {error}"))?;
203 self.a2a_peers
204 .reject_shared_secret()
205 .map_err(|error| anyhow!("invalid a2a peer credentials: {error}"))?;
206 if !self.a2a_peers.peers.is_empty() && self.a2a_recipient_id.is_none() {
207 return Err(anyhow!(
208 "a2a_recipient_id is required when relay peers are configured"
209 ));
210 }
211 if self.a2a_signing_key.is_some() && self.a2a_signing_key == self.auth_token {
212 return Err(anyhow!("a2a_signing_key must be distinct from auth_token"));
213 }
214 if self.a2a_signing_key.is_some() {
215 for (name, value) in [
216 ("a2a_recipient_id", self.a2a_recipient_id.as_deref()),
217 ("a2a_tenant_id", self.a2a_tenant_id.as_deref()),
218 ("a2a_project_id", self.a2a_project_id.as_deref()),
219 ] {
220 if value.is_none_or(str::is_empty) {
221 return Err(anyhow!("{name} is required when A2A signing is enabled"));
222 }
223 }
224 }
225 self.a2a_task_authority
229 .validate()
230 .map_err(|error| anyhow!("invalid a2a task authority policy: {error}"))?;
231 for secret in [self.auth_token.as_deref(), self.a2a_signing_key.as_deref()]
232 .into_iter()
233 .flatten()
234 {
235 self.a2a_task_authority
236 .reject_shared_secret(secret)
237 .map_err(|error| anyhow!(error.to_string()))?;
238 }
239 if !self.a2a_task_authority.peers.is_empty() && self.a2a_signing_key.is_none() {
240 return Err(anyhow!(
241 "a2a_signing_key is required when a task authority policy is configured"
242 ));
243 }
244 if !self.a2a_task_authority.peers.is_empty()
245 && (self.a2a_recipient_id.is_none()
246 || self.a2a_tenant_id.is_none()
247 || self.a2a_project_id.is_none())
248 {
249 return Err(anyhow!(
250 "a2a recipient, tenant, and project ids are required when a task authority policy is configured"
251 ));
252 }
253 match (
254 self.a2a_tenant_id.as_deref(),
255 self.a2a_project_id.as_deref(),
256 ) {
257 (Some(tenant_id), Some(project_id)) => {
258 lean_ctx::core::a2a::dlq::DlqScope::new(tenant_id, project_id)
259 .map_err(|error| anyhow!(error.to_string()))?;
260 }
261 (None, None) => {}
262 _ => {
263 return Err(anyhow!(
264 "a2a_tenant_id and a2a_project_id must be configured together"
265 ));
266 }
267 }
268 Ok(())
269 }
270
271 pub fn effective_auth_token(&self) -> Option<String> {
272 if let Some(ref token) = self.auth_token
273 && !token.is_empty()
274 {
275 return Some(token.clone());
276 }
277 let host = self.host.trim().to_lowercase();
278 let is_loopback = host == "127.0.0.1" || host == "localhost" || host == "::1";
279 if is_loopback {
280 let auto_token = lean_ctx::core::session_token::generate_token();
281 eprintln!(
282 "[lean-ctx] Auto-generated auth token for loopback: {auto_token}\n\
283 Pass as Bearer token or set --auth-token explicitly."
284 );
285 Some(auto_token)
286 } else {
287 None
288 }
289 }
290
291 pub(super) fn mcp_http_config(&self) -> StreamableHttpServerConfig {
292 let mut cfg = StreamableHttpServerConfig::default()
293 .with_legacy_session_mode(self.stateful_mode)
294 .with_json_response(self.json_response);
295
296 if self.disable_host_check {
297 tracing::warn!(
298 "⚠ --disable-host-check is active: DNS rebinding protection is OFF. \
299 Do NOT use this in production or on non-loopback interfaces."
300 );
301 cfg = cfg.disable_allowed_hosts();
302 return cfg;
303 }
304
305 if !self.allowed_hosts.is_empty() {
306 cfg = cfg.with_allowed_hosts(self.allowed_hosts.clone());
307 return cfg;
308 }
309
310 let host = self.host.trim();
312 if host == "127.0.0.1" || host == "localhost" || host == "::1" {
313 cfg.allowed_hosts.push(host.to_string());
314 }
315
316 cfg
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use super::HttpServerConfig;
323
324 #[test]
325 fn a2a_signing_key_must_be_nonempty_and_distinct_from_bearer() {
326 let empty = HttpServerConfig {
327 a2a_signing_key: Some(String::new()),
328 ..HttpServerConfig::default()
329 };
330 assert!(empty.validate().is_err());
331
332 let reused = HttpServerConfig {
333 auth_token: Some("same-secret".to_string()),
334 a2a_signing_key: Some("same-secret".to_string()),
335 ..HttpServerConfig::default()
336 };
337 assert!(reused.validate().is_err());
338
339 let missing_scope = HttpServerConfig {
340 auth_token: Some("bearer-secret".to_string()),
341 a2a_signing_key: Some("signing-secret".to_string()),
342 ..HttpServerConfig::default()
343 };
344 assert!(missing_scope.validate().is_err());
345
346 let scoped = HttpServerConfig {
347 auth_token: Some("bearer-secret".to_string()),
348 a2a_signing_key: Some("signing-secret".to_string()),
349 a2a_recipient_id: Some("recipient".to_string()),
350 a2a_tenant_id: Some("tenant-a".to_string()),
351 a2a_project_id: Some("project-a".to_string()),
352 ..HttpServerConfig::default()
353 };
354 assert!(scoped.validate().is_ok());
355 }
356}