Skip to main content

adk_server/
config.rs

1use std::{sync::Arc, time::Duration};
2
3use crate::auth_bridge::RequestContextExtractor;
4use adk_core::{CacheCapable, ContextCacheConfig, EventsCompactionConfig};
5
6#[cfg(feature = "yaml-agent")]
7use std::path::PathBuf;
8
9/// Security configuration for the ADK server.
10///
11/// The defaults admit only same-origin browser traffic for loopback host names and IP
12/// addresses. Each field below lists what to set when the server is reached another way.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_server::SecurityConfig;
18///
19/// let security = SecurityConfig {
20///     allowed_origins: vec!["https://app.example.com".to_string()],
21///     allowed_hosts: vec!["agents.example.com".to_string()],
22///     ..SecurityConfig::default()
23/// };
24/// assert!(security.allows_host("agents.example.com:443"));
25/// assert!(!security.allows_host("rebind.attacker.example"));
26/// ```
27#[derive(Clone, Debug)]
28pub struct SecurityConfig {
29    /// Browser origins allowed to call the server from another origin (CORS).
30    ///
31    /// Empty — the default — allows no cross-origin access: preflights get no
32    /// `Access-Control-Allow-Origin`, and a request whose `Origin` names another origin is
33    /// refused with `403`. Entries are exact origins (`https://app.example.com`), an origin
34    /// with any port (`http://localhost:*`), or `*` for every origin.
35    pub allowed_origins: Vec<String>,
36    /// Host names the server answers, in addition to `localhost`, `*.localhost`, and IP
37    /// addresses, which are always answered.
38    ///
39    /// A request whose `Host` names any other host is refused with `403`, so a page on a
40    /// DNS-rebinding domain cannot reach the server through the browser. Entries are exact
41    /// names (`agents.example.com`), a domain and its subdomains (`.example.com`), or `*`
42    /// for every host. The host of an A2A base URL and of the backend URL configured on
43    /// [`ServerConfig`] is added automatically. List the public host names here when the
44    /// server listens beyond loopback.
45    pub allowed_hosts: Vec<String>,
46    /// Maximum request body size in bytes (default: 10MB)
47    pub max_body_size: usize,
48    /// Request timeout duration (default: 30 seconds). Agent runs take
49    /// [`run_timeout`](Self::run_timeout) instead.
50    pub request_timeout: Duration,
51    /// How long a request that runs an agent may take before it is answered `408`: `POST
52    /// /api/run`, `/api/run/{app}/{user}/{session}`, `/api/run_sse`, `/a2a`, and `/a2a/stream`
53    /// (default: [`DEFAULT_RUN_TIMEOUT`], 15 minutes). A model turn with tool calls routinely
54    /// outlasts [`request_timeout`](Self::request_timeout), so agent runs have their own
55    /// limit. A streamed run is bounded until its response starts.
56    pub run_timeout: Duration,
57    /// Whether error responses carry every error's own message (default: `false`;
58    /// [`SecurityConfig::development`] sets it).
59    ///
60    /// Off, a response carries an error's own message only when the server wrote it about the
61    /// request. All three must hold:
62    ///
63    /// - the category rejects the request: `invalid_input`, `unauthorized`, `forbidden`,
64    ///   `not_found`, `unsupported`, `conflict`, or `resource_exhausted`;
65    /// - the component handles the request inside the server: `server`, `auth`, `session`,
66    ///   `agent`, or `guardrail`;
67    /// - the error carries no upstream status code and no provider.
68    ///
69    /// Every other message — a model provider's response, a tool's service, a store or
70    /// driver failure — is replaced by a generic message for the error's category, such as
71    /// `Internal server error` or `Authentication failed`, and the full error is logged with
72    /// `tracing` inside the request's `http.request` span, whose `request.id` is the
73    /// response's `x-request-id`. The rule applies to the run endpoints' Problem JSON (its
74    /// `code`, `component`, `category`, `requestId`, `retryAfter`, and `upstreamStatusCode`
75    /// are kept), the `error_message` of their SSE error event and the AG-UI `RUN_ERROR`
76    /// `message`, and the `error` of a `503` from `POST /api/admin/freeze` or
77    /// `/api/admin/unfreeze`.
78    ///
79    /// # Example
80    ///
81    /// ```rust
82    /// use adk_server::SecurityConfig;
83    ///
84    /// assert!(!SecurityConfig::default().expose_error_details);
85    /// assert!(SecurityConfig::development().expose_error_details);
86    /// ```
87    pub expose_error_details: bool,
88    /// Whether to expose admin-only debug endpoints when auth is configured.
89    pub expose_admin_debug: bool,
90    /// The scope that makes an authenticated caller an administrator (default:
91    /// [`ADMIN_SCOPE`], `"admin"`).
92    ///
93    /// `POST /api/admin/freeze` and `POST /api/admin/unfreeze`, mounted by
94    /// [`ServerBuilder::enable_governance_endpoints`](crate::ServerBuilder::enable_governance_endpoints),
95    /// admit only a caller whose [`RequestContext::scopes`](adk_core::RequestContext::scopes)
96    /// include it: a caller without it is refused with `403`, and a request with no caller —
97    /// a server without a `RequestContextExtractor` — with `401`.
98    pub admin_scope: String,
99}
100
101/// The default [`SecurityConfig::admin_scope`]: the scope that makes a caller an
102/// administrator of the governance endpoints.
103///
104/// # Example
105///
106/// ```rust
107/// use adk_server::{ADMIN_SCOPE, SecurityConfig};
108///
109/// assert_eq!(SecurityConfig::default().admin_scope, ADMIN_SCOPE);
110/// ```
111pub const ADMIN_SCOPE: &str = "admin";
112
113/// The [`SecurityConfig::run_timeout`] of every preset: 15 minutes, long enough for an agent
114/// turn with several model and tool calls.
115pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(15 * 60);
116
117impl Default for SecurityConfig {
118    fn default() -> Self {
119        Self {
120            allowed_origins: Vec::new(),
121            allowed_hosts: Vec::new(),
122            max_body_size: 10 * 1024 * 1024, // 10MB
123            request_timeout: Duration::from_secs(30),
124            run_timeout: DEFAULT_RUN_TIMEOUT,
125            expose_error_details: false,
126            expose_admin_debug: false,
127            admin_scope: ADMIN_SCOPE.to_string(),
128        }
129    }
130}
131
132/// Origins [`SecurityConfig::development`] admits: loopback on any port.
133const LOOPBACK_ORIGINS: [&str; 6] = [
134    "http://localhost:*",
135    "https://localhost:*",
136    "http://127.0.0.1:*",
137    "https://127.0.0.1:*",
138    "http://[::1]:*",
139    "https://[::1]:*",
140];
141
142impl SecurityConfig {
143    /// A development configuration: detailed errors, admin debug endpoints, and
144    /// cross-origin access from loopback origins on any port, so a frontend dev server on
145    /// `http://localhost:5173` can call the API.
146    pub fn development() -> Self {
147        Self {
148            allowed_origins: LOOPBACK_ORIGINS.iter().map(|origin| (*origin).to_string()).collect(),
149            allowed_hosts: Vec::new(),
150            max_body_size: 10 * 1024 * 1024,
151            request_timeout: Duration::from_secs(60),
152            run_timeout: DEFAULT_RUN_TIMEOUT,
153            expose_error_details: true,
154            expose_admin_debug: true,
155            admin_scope: ADMIN_SCOPE.to_string(),
156        }
157    }
158
159    /// A production configuration admitting cross-origin calls from `allowed_origins` only.
160    pub fn production(allowed_origins: Vec<String>) -> Self {
161        Self {
162            allowed_origins,
163            allowed_hosts: Vec::new(),
164            max_body_size: 10 * 1024 * 1024,
165            request_timeout: Duration::from_secs(30),
166            run_timeout: DEFAULT_RUN_TIMEOUT,
167            expose_error_details: false,
168            expose_admin_debug: false,
169            admin_scope: ADMIN_SCOPE.to_string(),
170        }
171    }
172
173    /// Sets the host names the server answers besides loopback names and IP addresses,
174    /// replacing any list set before; see [`allowed_hosts`](Self::allowed_hosts).
175    ///
176    /// [`ServerConfig::with_allowed_hosts`] sets the same list the same way.
177    ///
178    /// # Example
179    ///
180    /// ```rust
181    /// use adk_server::SecurityConfig;
182    ///
183    /// let security = SecurityConfig::default()
184    ///     .with_allowed_hosts(["staging.example.com"])
185    ///     .with_allowed_hosts(["agents.example.com", "api.example.com"]);
186    /// assert!(security.allows_host("agents.example.com"));
187    /// assert!(!security.allows_host("staging.example.com"));
188    /// ```
189    pub fn with_allowed_hosts<I, S>(mut self, hosts: I) -> Self
190    where
191        I: IntoIterator<Item = S>,
192        S: Into<String>,
193    {
194        self.allowed_hosts = hosts.into_iter().map(Into::into).collect();
195        self
196    }
197
198    /// Whether a request whose `Host` header (or URI authority) is `host` is answered.
199    ///
200    /// `localhost`, its subdomains, and IP addresses are always answered; any other name
201    /// must match [`allowed_hosts`](Self::allowed_hosts). The port is ignored.
202    ///
203    /// # Example
204    ///
205    /// ```rust
206    /// use adk_server::SecurityConfig;
207    ///
208    /// let security = SecurityConfig::default();
209    /// assert!(security.allows_host("127.0.0.1:8080"));
210    /// assert!(security.allows_host("localhost:8080"));
211    /// assert!(!security.allows_host("rebind.attacker.example:8080"));
212    /// ```
213    pub fn allows_host(&self, host: &str) -> bool {
214        host_allowed(host, &self.allowed_hosts)
215    }
216
217    /// Whether a browser on `origin` may call the server from another origin.
218    ///
219    /// # Example
220    ///
221    /// ```rust
222    /// use adk_server::SecurityConfig;
223    ///
224    /// assert!(!SecurityConfig::default().allows_origin("https://evil.example"));
225    /// assert!(SecurityConfig::development().allows_origin("http://localhost:5173"));
226    /// ```
227    pub fn allows_origin(&self, origin: &str) -> bool {
228        self.allowed_origins.iter().any(|entry| origin_matches(entry, origin))
229    }
230}
231
232/// The host part of a `Host` header or authority: no port, no IPv6 brackets, no trailing
233/// dot, lowercase.
234pub(crate) fn host_name(authority: &str) -> String {
235    let authority = authority.trim();
236    let host = if let Some(rest) = authority.strip_prefix('[') {
237        rest.split(']').next().unwrap_or_default()
238    } else {
239        match authority.rsplit_once(':') {
240            // A bare IPv6 address has more than one colon and no port.
241            Some((host, port))
242                if !host.contains(':') && port.bytes().all(|byte| byte.is_ascii_digit()) =>
243            {
244                host
245            }
246            _ => authority,
247        }
248    };
249    host.trim_end_matches('.').to_ascii_lowercase()
250}
251
252fn host_allowed(authority: &str, allowed: &[String]) -> bool {
253    let host = host_name(authority);
254    if host.parse::<std::net::IpAddr>().is_ok()
255        || host == "localhost"
256        || host.ends_with(".localhost")
257    {
258        return true;
259    }
260    allowed.iter().any(|entry| {
261        let entry = entry.trim();
262        if entry == "*" {
263            return true;
264        }
265        match entry.strip_prefix("*.").or_else(|| entry.strip_prefix('.')) {
266            Some(domain) => {
267                let domain = host_name(domain);
268                host == domain || host.ends_with(&format!(".{domain}"))
269            }
270            None => host == host_name(entry),
271        }
272    })
273}
274
275fn origin_matches(entry: &str, origin: &str) -> bool {
276    let entry = entry.trim().trim_end_matches('/');
277    if entry == "*" || entry.eq_ignore_ascii_case(origin) {
278        return true;
279    }
280    let Some(prefix) = entry.strip_suffix(":*") else {
281        return false;
282    };
283    let Some(head) = origin.get(..prefix.len()) else {
284        return false;
285    };
286    if !head.eq_ignore_ascii_case(prefix) {
287        return false;
288    }
289    match &origin[prefix.len()..] {
290        "" => true,
291        rest => rest
292            .strip_prefix(':')
293            .is_some_and(|port| !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit())),
294    }
295}
296
297/// Configuration for the ADK server.
298#[derive(Clone)]
299pub struct ServerConfig {
300    pub agent_loader: Arc<dyn adk_core::AgentLoader>,
301    pub session_service: Arc<dyn adk_session::SessionService>,
302    pub artifact_service: Option<Arc<dyn adk_artifact::ArtifactService>>,
303    pub memory_service: Option<Arc<dyn adk_core::Memory>>,
304    pub compaction_config: Option<EventsCompactionConfig>,
305    pub context_cache_config: Option<ContextCacheConfig>,
306    pub cache_capable: Option<Arc<dyn CacheCapable>>,
307    pub span_exporter: Option<Arc<adk_telemetry::AdkSpanExporter>>,
308    pub backend_url: Option<String>,
309    pub security: SecurityConfig,
310    pub request_context_extractor: Option<Arc<dyn RequestContextExtractor>>,
311    /// Optional interceptor chain for A2A request/response middleware.
312    ///
313    /// When set, the chain is invoked before and after A2A executor processing.
314    #[cfg(feature = "a2a-interceptors")]
315    pub interceptor_chain: Option<Arc<crate::a2a::interceptor::InterceptorChain>>,
316    /// Directories containing YAML agent definitions to watch for hot reload.
317    /// Only used when the `yaml-agent` feature is enabled.
318    #[cfg(feature = "yaml-agent")]
319    pub yaml_agent_dirs: Vec<PathBuf>,
320    /// Kill switch shared by every runner the server builds.
321    ///
322    /// Freezing it — directly or through `POST /api/admin/freeze` when
323    /// [`ServerBuilder::enable_governance_endpoints`](crate::ServerBuilder::enable_governance_endpoints)
324    /// is set — fails new runs and stops running ones before their next model or tool call.
325    pub governance: adk_core::GovernanceControl,
326    /// The sessions with a turn in flight, shared by every runner the server builds and by the
327    /// session history routes, which refuse to fork, rewind, or edit a session while a turn
328    /// runs on it.
329    pub session_activity: adk_runner::SessionActivity,
330}
331
332impl ServerConfig {
333    pub fn new(
334        agent_loader: Arc<dyn adk_core::AgentLoader>,
335        session_service: Arc<dyn adk_session::SessionService>,
336    ) -> Self {
337        Self {
338            agent_loader,
339            session_service,
340            artifact_service: None,
341            memory_service: None,
342            compaction_config: None,
343            context_cache_config: None,
344            cache_capable: None,
345            span_exporter: None,
346            backend_url: None,
347            security: SecurityConfig::default(),
348            request_context_extractor: None,
349            #[cfg(feature = "a2a-interceptors")]
350            interceptor_chain: None,
351            #[cfg(feature = "yaml-agent")]
352            yaml_agent_dirs: Vec::new(),
353            governance: adk_core::GovernanceControl::new(),
354            session_activity: adk_runner::SessionActivity::new(),
355        }
356    }
357
358    /// Shares `activity` with every runner the server builds, so the session history routes
359    /// also see the runs of runners built outside the server, such as a background worker's.
360    ///
361    /// # Example
362    ///
363    /// ```rust,ignore
364    /// let activity = adk_runner::SessionActivity::new();
365    /// let config = ServerConfig::new(loader, sessions).with_session_activity(activity.clone());
366    /// let worker_runner = Runner::builder()
367    ///     .app_name("ops")
368    ///     .agent(agent)
369    ///     .session_service(sessions)
370    ///     .session_activity(activity)
371    ///     .build()?;
372    /// ```
373    pub fn with_session_activity(mut self, activity: adk_runner::SessionActivity) -> Self {
374        self.session_activity = activity;
375        self
376    }
377
378    /// Shares `control` with every runner the server builds.
379    ///
380    /// # Example
381    ///
382    /// ```rust,ignore
383    /// let control = adk_core::GovernanceControl::new();
384    /// let config = ServerConfig::new(loader, sessions).with_governance(control.clone());
385    /// control.freeze("incident 4012");
386    /// ```
387    pub fn with_governance(mut self, control: adk_core::GovernanceControl) -> Self {
388        self.governance = control;
389        self
390    }
391
392    pub fn with_artifact_service(
393        mut self,
394        artifact_service: Arc<dyn adk_artifact::ArtifactService>,
395    ) -> Self {
396        self.artifact_service = Some(artifact_service);
397        self
398    }
399
400    pub fn with_artifact_service_opt(
401        mut self,
402        artifact_service: Option<Arc<dyn adk_artifact::ArtifactService>>,
403    ) -> Self {
404        self.artifact_service = artifact_service;
405        self
406    }
407
408    /// Configure a memory service for semantic search across sessions.
409    ///
410    /// When set, the runner injects memory into the invocation context,
411    /// allowing agents to search previous conversation content via
412    /// `ToolContext::search_memory()`.
413    pub fn with_memory_service(mut self, memory_service: Arc<dyn adk_core::Memory>) -> Self {
414        self.memory_service = Some(memory_service);
415        self
416    }
417
418    /// Configure automatic context compaction for long-running sessions.
419    pub fn with_compaction(mut self, compaction_config: EventsCompactionConfig) -> Self {
420        self.compaction_config = Some(compaction_config);
421        self
422    }
423
424    /// Configure automatic prompt-cache lifecycle management for cache-capable models.
425    pub fn with_context_cache(
426        mut self,
427        context_cache_config: ContextCacheConfig,
428        cache_capable: Arc<dyn CacheCapable>,
429    ) -> Self {
430        self.context_cache_config = Some(context_cache_config);
431        self.cache_capable = Some(cache_capable);
432        self
433    }
434
435    pub fn with_backend_url(mut self, backend_url: impl Into<String>) -> Self {
436        self.backend_url = Some(backend_url.into());
437        self
438    }
439
440    pub fn with_security(mut self, security: SecurityConfig) -> Self {
441        self.security = security;
442        self
443    }
444
445    pub fn with_span_exporter(
446        mut self,
447        span_exporter: Arc<adk_telemetry::AdkSpanExporter>,
448    ) -> Self {
449        self.span_exporter = Some(span_exporter);
450        self
451    }
452
453    /// Sets the browser origins allowed to call the server cross-origin; see
454    /// [`SecurityConfig::allowed_origins`].
455    pub fn with_allowed_origins(mut self, origins: Vec<String>) -> Self {
456        self.security.allowed_origins = origins;
457        self
458    }
459
460    /// Sets the host names the server answers besides loopback names and IP addresses,
461    /// replacing any list set before, including one in a [`SecurityConfig`] passed to
462    /// [`with_security`](Self::with_security); see [`SecurityConfig::allowed_hosts`].
463    ///
464    /// [`SecurityConfig::with_allowed_hosts`] sets the same list the same way.
465    ///
466    /// # Example
467    ///
468    /// ```rust,ignore
469    /// let config = ServerConfig::new(loader, sessions)
470    ///     .with_allowed_hosts(["agents.example.com", "api.example.com"]);
471    /// ```
472    pub fn with_allowed_hosts<I, S>(mut self, hosts: I) -> Self
473    where
474        I: IntoIterator<Item = S>,
475        S: Into<String>,
476    {
477        self.security = self.security.with_allowed_hosts(hosts);
478        self
479    }
480
481    /// Configure maximum request body size
482    pub fn with_max_body_size(mut self, size: usize) -> Self {
483        self.security.max_body_size = size;
484        self
485    }
486
487    /// Configure request timeout
488    pub fn with_request_timeout(mut self, timeout: Duration) -> Self {
489        self.security.request_timeout = timeout;
490        self
491    }
492
493    /// Sets how long a request that runs an agent may take; see
494    /// [`SecurityConfig::run_timeout`].
495    ///
496    /// # Example
497    ///
498    /// ```rust,ignore
499    /// let config = ServerConfig::new(agent_loader, session_service)
500    ///     .with_run_timeout(std::time::Duration::from_secs(30 * 60));
501    /// ```
502    pub fn with_run_timeout(mut self, timeout: Duration) -> Self {
503        self.security.run_timeout = timeout;
504        self
505    }
506
507    /// Sets whether error responses carry every error's own message; see
508    /// [`SecurityConfig::expose_error_details`]. Enable it for development only: an upstream
509    /// or store message can name hosts, tables, accounts, or request content.
510    ///
511    /// # Example
512    ///
513    /// ```rust,ignore
514    /// let config = ServerConfig::new(agent_loader, session_service).with_error_details(true);
515    /// ```
516    pub fn with_error_details(mut self, expose: bool) -> Self {
517        self.security.expose_error_details = expose;
518        self
519    }
520
521    /// Configure a request context extractor for auth middleware bridging.
522    ///
523    /// When set, the server invokes the extractor on each incoming request
524    /// to extract authenticated identity (user_id, scopes, metadata) from
525    /// HTTP headers. The extracted context flows into `InvocationContext`,
526    /// making scopes available via `ToolContext::user_scopes()`.
527    pub fn with_request_context(mut self, extractor: Arc<dyn RequestContextExtractor>) -> Self {
528        self.request_context_extractor = Some(extractor);
529        self
530    }
531
532    /// Configure an interceptor chain for A2A request/response middleware.
533    ///
534    /// When set, the chain's `run_before` is called before the A2A executor
535    /// processes a request, and `run_after` is called after it completes.
536    /// Interceptors can reject, short-circuit, or modify requests and responses.
537    ///
538    /// # Example
539    ///
540    /// ```rust,ignore
541    /// use adk_server::a2a::interceptor::InterceptorChain;
542    /// use std::sync::Arc;
543    ///
544    /// let chain = InterceptorChain::new()
545    ///     .add(my_auth_interceptor)
546    ///     .add(my_rate_limiter);
547    ///
548    /// let config = ServerConfig::new(loader, session)
549    ///     .with_interceptor_chain(Arc::new(chain));
550    /// ```
551    #[cfg(feature = "a2a-interceptors")]
552    pub fn with_interceptor_chain(
553        mut self,
554        chain: Arc<crate::a2a::interceptor::InterceptorChain>,
555    ) -> Self {
556        self.interceptor_chain = Some(chain);
557        self
558    }
559
560    /// Configure directories containing YAML agent definitions to watch.
561    ///
562    /// When the `yaml-agent` feature is enabled and directories are configured,
563    /// the server starts a [`HotReloadWatcher`](crate::yaml_agent::HotReloadWatcher)
564    /// for each directory at startup, automatically loading and hot-reloading
565    /// YAML-defined agents.
566    #[cfg(feature = "yaml-agent")]
567    pub fn with_yaml_agent_dirs(mut self, dirs: Vec<PathBuf>) -> Self {
568        self.yaml_agent_dirs = dirs;
569        self
570    }
571
572    /// Add a single YAML agent directory to watch.
573    ///
574    /// Convenience method that appends one directory to the list.
575    #[cfg(feature = "yaml-agent")]
576    pub fn with_yaml_agent_dir(mut self, dir: impl Into<PathBuf>) -> Self {
577        self.yaml_agent_dirs.push(dir.into());
578        self
579    }
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585    use adk_core::{
586        Agent, BaseEventsSummarizer, Event, EventStream, InvocationContext, Result as AdkResult,
587        SingleAgentLoader,
588    };
589    use adk_session::InMemorySessionService;
590    use async_trait::async_trait;
591    use futures::stream;
592
593    struct TestAgent;
594
595    #[async_trait]
596    impl Agent for TestAgent {
597        fn name(&self) -> &str {
598            "server_config_test_agent"
599        }
600
601        fn description(&self) -> &str {
602            "server config test agent"
603        }
604
605        fn sub_agents(&self) -> &[Arc<dyn Agent>] {
606            &[]
607        }
608
609        async fn run(&self, _ctx: Arc<dyn InvocationContext>) -> AdkResult<EventStream> {
610            Ok(Box::pin(stream::empty()))
611        }
612    }
613
614    struct TestCache;
615
616    struct TestSummarizer;
617
618    #[async_trait]
619    impl CacheCapable for TestCache {
620        async fn create_cache(
621            &self,
622            _system_instruction: &str,
623            _tools: &adk_core::ToolDeclarations,
624            _ttl_seconds: u32,
625        ) -> adk_core::Result<String> {
626            Ok("cache".to_string())
627        }
628
629        async fn delete_cache(&self, _name: &str) -> adk_core::Result<()> {
630            Ok(())
631        }
632    }
633
634    #[async_trait]
635    impl BaseEventsSummarizer for TestSummarizer {
636        async fn summarize_events(&self, _events: &[Event]) -> adk_core::Result<Option<Event>> {
637            Ok(Some(Event::new("summary")))
638        }
639    }
640
641    fn test_config() -> ServerConfig {
642        let agent_loader = Arc::new(SingleAgentLoader::new(Arc::new(TestAgent)));
643        let session_service = Arc::new(InMemorySessionService::new());
644        ServerConfig::new(agent_loader, session_service)
645    }
646
647    #[test]
648    fn host_name_strips_port_brackets_and_trailing_dot() {
649        assert_eq!(host_name("Agents.Example.com:8443"), "agents.example.com");
650        assert_eq!(host_name("[::1]:8080"), "::1");
651        assert_eq!(host_name("::1"), "::1");
652        assert_eq!(host_name("localhost."), "localhost");
653        assert_eq!(host_name("127.0.0.1:80"), "127.0.0.1");
654    }
655
656    #[test]
657    fn default_security_answers_loopback_names_and_ip_addresses_only() {
658        let security = SecurityConfig::default();
659        for host in ["localhost:8080", "app.localhost", "127.0.0.1:8080", "[::1]:8080", "10.0.0.5"]
660        {
661            assert!(security.allows_host(host), "{host} should be answered");
662        }
663        for host in ["rebind.attacker.example:8080", "localhost.attacker.example", "example.com"] {
664            assert!(!security.allows_host(host), "{host} should be refused");
665        }
666    }
667
668    #[test]
669    fn allowed_hosts_match_exact_names_domains_and_wildcard() {
670        let exact = SecurityConfig::default().with_allowed_hosts(["agents.example.com"]);
671        assert!(exact.allows_host("AGENTS.example.com:443"));
672        assert!(!exact.allows_host("api.agents.example.com"));
673
674        let domain = SecurityConfig::default().with_allowed_hosts([".example.com"]);
675        assert!(domain.allows_host("example.com"));
676        assert!(domain.allows_host("api.example.com"));
677        assert!(!domain.allows_host("example.com.attacker.example"));
678        assert!(!domain.allows_host("notexample.com"));
679
680        let any = SecurityConfig::default().with_allowed_hosts(["*"]);
681        assert!(any.allows_host("anything.example"));
682    }
683
684    #[test]
685    fn allowed_hosts_setters_replace_the_list() {
686        let security = SecurityConfig::default()
687            .with_allowed_hosts(["old.example.com"])
688            .with_allowed_hosts(["agents.example.com"]);
689        assert_eq!(security.allowed_hosts, ["agents.example.com"]);
690    }
691
692    #[test]
693    fn default_security_allows_no_cross_origin_access() {
694        let security = SecurityConfig::default();
695        assert!(!security.allows_origin("https://evil.example"));
696        assert!(!security.allows_origin("http://localhost:5173"));
697    }
698
699    #[test]
700    fn origin_entries_match_exact_any_port_and_wildcard() {
701        let security = SecurityConfig::production(vec![
702            "https://app.example.com".to_string(),
703            "http://localhost:*".to_string(),
704        ]);
705        assert!(security.allows_origin("https://app.example.com"));
706        assert!(!security.allows_origin("https://app.example.com.attacker.example"));
707        assert!(security.allows_origin("http://localhost:5173"));
708        assert!(security.allows_origin("http://localhost"));
709        assert!(!security.allows_origin("http://localhost.attacker.example"));
710        assert!(!security.allows_origin("http://localhost:"));
711        assert!(!security.allows_origin("https://localhost:5173"));
712
713        assert!(SecurityConfig::production(vec!["*".to_string()]).allows_origin("null"));
714    }
715
716    #[test]
717    fn development_security_allows_loopback_origins_on_any_port() {
718        let security = SecurityConfig::development();
719        assert!(security.allows_origin("http://localhost:5173"));
720        assert!(security.allows_origin("http://127.0.0.1:3000"));
721        assert!(security.allows_origin("http://[::1]:8080"));
722        assert!(!security.allows_origin("https://evil.example"));
723    }
724
725    #[test]
726    fn with_compaction_sets_optional_config() {
727        let compaction_config = EventsCompactionConfig {
728            compaction_interval: 10,
729            overlap_size: 2,
730            summarizer: Arc::new(TestSummarizer),
731        };
732
733        let config = test_config().with_compaction(compaction_config.clone());
734
735        assert!(config.compaction_config.is_some());
736        assert_eq!(config.compaction_config.as_ref().unwrap().compaction_interval, 10);
737        assert_eq!(config.compaction_config.as_ref().unwrap().overlap_size, 2);
738    }
739
740    #[test]
741    fn with_context_cache_sets_cache_fields() {
742        let context_cache_config =
743            ContextCacheConfig { min_tokens: 512, ttl_seconds: 300, cache_intervals: 2 };
744        let cache_capable = Arc::new(TestCache);
745
746        let config =
747            test_config().with_context_cache(context_cache_config.clone(), cache_capable.clone());
748
749        assert_eq!(config.context_cache_config.as_ref().unwrap().min_tokens, 512);
750        assert_eq!(config.context_cache_config.as_ref().unwrap().ttl_seconds, 300);
751        assert_eq!(config.context_cache_config.as_ref().unwrap().cache_intervals, 2);
752        assert!(config.cache_capable.is_some());
753        let configured = config.cache_capable.as_ref().unwrap();
754        let expected: Arc<dyn CacheCapable> = cache_capable;
755        assert!(Arc::ptr_eq(configured, &expected));
756    }
757}