Skip to main content

greentic_runner_host/
config.rs

1use crate::gtbind::PackBinding;
2use crate::gtbind::TenantBindings;
3use crate::oauth::OAuthBrokerConfig;
4use crate::runner::mocks::MocksConfig;
5use crate::trace::TraceConfig;
6use crate::validate::ValidationConfig;
7use anyhow::{Context, Result};
8use parking_lot::RwLock;
9use serde::Deserialize;
10use serde_json::Value;
11use serde_yaml_bw as serde_yaml;
12use std::collections::{HashMap, HashSet};
13use std::fs;
14use std::path::{Path, PathBuf};
15use std::str::FromStr;
16use std::sync::Arc;
17
18#[derive(Debug, Clone)]
19pub struct HostConfig {
20    pub tenant: String,
21    pub bindings_path: PathBuf,
22    pub flow_type_bindings: HashMap<String, FlowBinding>,
23    pub rate_limits: RateLimits,
24    pub retry: FlowRetryConfig,
25    pub http_enabled: bool,
26    pub secrets_policy: SecretsPolicy,
27    pub state_store_policy: StateStorePolicy,
28    pub webhook_policy: WebhookPolicy,
29    pub timers: Vec<TimerBinding>,
30    pub oauth: Option<OAuthConfig>,
31    pub mocks: Option<MocksConfig>,
32    pub pack_bindings: Vec<PackBinding>,
33    pub env_passthrough: Vec<String>,
34    pub trace: TraceConfig,
35    pub validation: ValidationConfig,
36    pub operator_policy: OperatorPolicy,
37    pub fast2flow: Fast2FlowRoutingConfig,
38    /// Operator-declared Digital Worker agent configs, keyed by `agent_id`.
39    /// Sourced from the `agents:` section of the bindings YAML and consumed
40    /// by the production `ConfigProvider` (Task 4.3).
41    /// Only populated when the `agentic-worker` feature is enabled.
42    #[cfg(feature = "agentic-worker")]
43    pub agents: HashMap<String, greentic_aw_runtime::AgentConfig>,
44    /// Operator/producer-declared agent-graph configs, keyed by `graph_id`.
45    /// The pack loader (Task 8) reads `agent-graph.json` sidecars directly, but
46    /// this map is the contract that external producers (e.g. greentic-start's
47    /// env-file path, the admin registry hand-off) populate to supply graphs
48    /// that do not ship as a pack sidecar. Merged with pack-sidecar graphs at
49    /// runtime construction (producer entries win on `graph_id` collision).
50    /// Only populated when the `agentic-worker` feature is enabled.
51    #[cfg(feature = "agentic-worker")]
52    pub graphs: HashMap<String, greentic_aw_runtime::graph::GraphConfig>,
53}
54
55#[derive(Debug, Clone, Deserialize)]
56pub struct BindingsFile {
57    pub tenant: String,
58    #[serde(default)]
59    pub flow_type_bindings: HashMap<String, FlowBinding>,
60    #[serde(default)]
61    pub rate_limits: RateLimits,
62    #[serde(default)]
63    pub retry: FlowRetryConfig,
64    #[serde(default)]
65    pub timers: Vec<TimerBinding>,
66    #[serde(default)]
67    pub oauth: Option<OAuthConfig>,
68    #[serde(default)]
69    pub mocks: Option<MocksConfig>,
70    #[serde(default)]
71    pub state_store: StateStorePolicy,
72    #[serde(default)]
73    pub operator: OperatorPolicyConfig,
74    #[serde(default)]
75    pub fast2flow: Fast2FlowRoutingConfig,
76    /// Digital Worker agent configs keyed by `agent_id`. The whole section is
77    /// optional; each value must be a complete `AgentConfig` (all `limits`
78    /// fields are required — `AgentLimits` has no serde defaults).
79    /// Only present when the `agentic-worker` feature is enabled.
80    #[cfg(feature = "agentic-worker")]
81    #[serde(default)]
82    pub agents: HashMap<String, greentic_aw_runtime::AgentConfig>,
83    /// Operator-declared agent-graph configs keyed by `graph_id`. The whole
84    /// section is optional; each value must be a complete `GraphConfig`
85    /// (camelCase fields, same wire shape as the `agent-graph.json` sidecar).
86    /// Only present when the `agentic-worker` feature is enabled.
87    #[cfg(feature = "agentic-worker")]
88    #[serde(default)]
89    pub graphs: HashMap<String, greentic_aw_runtime::graph::GraphConfig>,
90}
91
92#[derive(Debug, Clone, Deserialize)]
93pub struct FlowBinding {
94    pub adapter: String,
95    #[serde(default)]
96    pub config: serde_yaml::Value,
97    #[serde(default)]
98    pub secrets: Vec<String>,
99}
100
101#[derive(Debug, Clone, Deserialize)]
102pub struct RateLimits {
103    #[serde(default = "default_messaging_qps")]
104    pub messaging_send_qps: u32,
105    #[serde(default = "default_messaging_burst")]
106    pub messaging_burst: u32,
107}
108
109#[derive(Debug, Clone)]
110pub struct SecretsPolicy {
111    /// Secret names allowed by the bindings file.
112    binding_allowed: HashSet<String>,
113    /// Secret names discovered at flow-load time from node configs that
114    /// reference secrets via fields ending in `_secret` (e.g.
115    /// `api_key_secret: "llm-api-key"`). Shared across all clones so that
116    /// flow loading can register names after policy construction.
117    flow_discovered: Arc<RwLock<HashSet<String>>>,
118    allow_all: bool,
119}
120
121#[derive(Debug, Clone, Deserialize, Default)]
122pub struct OperatorPolicyConfig {
123    #[serde(default)]
124    pub allowed_providers: Vec<String>,
125    #[serde(default)]
126    pub allowed_ops: HashMap<String, Vec<String>>,
127}
128
129#[derive(Debug, Clone)]
130pub struct OperatorPolicy {
131    allow_all: bool,
132    allowed_providers: HashSet<String>,
133    allowed_ops: HashMap<String, HashSet<String>>,
134}
135
136#[derive(Debug, Clone, Deserialize)]
137pub struct Fast2FlowRoutingConfig {
138    #[serde(default)]
139    pub enabled: bool,
140    #[serde(default = "default_fast2flow_component_ref")]
141    pub component_ref: String,
142    #[serde(default = "default_fast2flow_operation")]
143    pub operation: String,
144    #[serde(default)]
145    pub scope: Option<String>,
146    #[serde(default)]
147    pub registry_path: String,
148    #[serde(default)]
149    pub indexes_path: String,
150    #[serde(default = "default_fast2flow_time_budget_ms")]
151    pub time_budget_ms: u64,
152}
153
154impl Default for Fast2FlowRoutingConfig {
155    fn default() -> Self {
156        Self {
157            enabled: false,
158            component_ref: default_fast2flow_component_ref(),
159            operation: default_fast2flow_operation(),
160            scope: None,
161            registry_path: String::new(),
162            indexes_path: String::new(),
163            time_budget_ms: default_fast2flow_time_budget_ms(),
164        }
165    }
166}
167
168fn default_fast2flow_component_ref() -> String {
169    "fast2flow-routing".to_owned()
170}
171
172fn default_fast2flow_operation() -> String {
173    "route".to_owned()
174}
175
176fn default_fast2flow_time_budget_ms() -> u64 {
177    250
178}
179
180#[derive(Debug, Clone, Deserialize)]
181pub struct FlowRetryConfig {
182    #[serde(default = "default_retry_attempts")]
183    pub max_attempts: u32,
184    #[serde(default = "default_retry_base_delay_ms")]
185    pub base_delay_ms: u64,
186}
187
188#[derive(Debug, Clone, Default)]
189pub struct WebhookPolicy {
190    allow_paths: Vec<String>,
191    deny_paths: Vec<String>,
192}
193
194#[derive(Debug, Clone, Deserialize)]
195pub struct StateStorePolicy {
196    #[serde(default = "default_state_store_allow")]
197    pub allow: bool,
198}
199
200#[derive(Debug, Clone, Deserialize)]
201pub struct WebhookBindingConfig {
202    #[serde(default)]
203    pub allow_paths: Vec<String>,
204    #[serde(default)]
205    pub deny_paths: Vec<String>,
206}
207
208#[derive(Debug, Clone, Deserialize)]
209pub struct TimerBinding {
210    pub flow_id: String,
211    pub cron: String,
212    #[serde(default)]
213    pub schedule_id: Option<String>,
214}
215
216#[derive(Debug, Clone, Deserialize)]
217pub struct OAuthConfig {
218    pub http_base_url: String,
219    pub nats_url: String,
220    pub provider: String,
221    #[serde(default)]
222    pub env: Option<String>,
223    #[serde(default)]
224    pub team: Option<String>,
225    #[serde(default)]
226    pub shared_secret: Option<String>,
227}
228
229impl HostConfig {
230    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self> {
231        let path = path.as_ref();
232        let content = fs::read_to_string(path)
233            .with_context(|| format!("failed to read bindings file {path:?}"))?;
234        let bindings: BindingsFile = serde_yaml::from_str(&content)
235            .with_context(|| format!("failed to parse bindings file {path:?}"))?;
236
237        let secrets_policy = SecretsPolicy::from_bindings(&bindings);
238        let http_enabled = bindings.flow_type_bindings.contains_key("messaging");
239        let webhook_policy = webhook_policy_from_bindings(&bindings)?;
240
241        // Reject unusable tenant ids up front instead of silently running as
242        // the `local` tenant later.
243        tenant_ctx_for(&bindings.tenant, greentic_env().as_deref())
244            .with_context(|| format!("invalid tenant in bindings file {path:?}"))?;
245
246        Ok(Self {
247            tenant: bindings.tenant.clone(),
248            bindings_path: path.to_path_buf(),
249            flow_type_bindings: bindings.flow_type_bindings.clone(),
250            rate_limits: bindings.rate_limits.clone(),
251            retry: bindings.retry.clone(),
252            http_enabled,
253            secrets_policy,
254            state_store_policy: bindings.state_store.clone(),
255            webhook_policy,
256            timers: bindings.timers.clone(),
257            oauth: bindings.oauth.clone(),
258            mocks: bindings.mocks.clone(),
259            pack_bindings: Vec::new(),
260            env_passthrough: Vec::new(),
261            trace: TraceConfig::from_env(),
262            validation: ValidationConfig::from_env(),
263            operator_policy: OperatorPolicy::from_config(bindings.operator.clone()),
264            fast2flow: bindings.fast2flow.clone(),
265            #[cfg(feature = "agentic-worker")]
266            agents: bindings.agents.clone(),
267            #[cfg(feature = "agentic-worker")]
268            graphs: bindings.graphs.clone(),
269        })
270    }
271
272    pub fn from_gtbind(bindings: TenantBindings) -> Self {
273        Self {
274            tenant: bindings.tenant,
275            bindings_path: PathBuf::from("<gtbind>"),
276            flow_type_bindings: HashMap::new(),
277            rate_limits: RateLimits::default(),
278            retry: FlowRetryConfig::default(),
279            // GTBind-backed embedded hosts do not populate flow_type_bindings,
280            // so the YAML-path heuristic cannot be used here. Keep outbound
281            // host HTTP enabled so components like component-llm-openai can
282            // reach their configured providers.
283            http_enabled: true,
284            secrets_policy: SecretsPolicy::allow_all(),
285            state_store_policy: StateStorePolicy::default(),
286            webhook_policy: WebhookPolicy::default(),
287            timers: Vec::new(),
288            oauth: None,
289            mocks: None,
290            pack_bindings: bindings.packs,
291            env_passthrough: bindings.env_passthrough,
292            trace: TraceConfig::from_env(),
293            validation: ValidationConfig::from_env(),
294            operator_policy: OperatorPolicy::allow_all(),
295            fast2flow: Fast2FlowRoutingConfig::default(),
296            // TODO(phase-4): TenantBindings (gtbind) has no agents section yet.
297            // When embedded gtbind hosts need Digital Worker agents, extend
298            // TenantBindings to carry them and populate this map here.
299            #[cfg(feature = "agentic-worker")]
300            agents: HashMap::new(),
301            // TODO(phase-4): likewise, gtbind carries no agent-graph section;
302            // pack sidecars remain the local source of graphs for now.
303            #[cfg(feature = "agentic-worker")]
304            graphs: HashMap::new(),
305        }
306    }
307
308    pub fn messaging_binding(&self) -> Option<&FlowBinding> {
309        self.flow_type_bindings.get("messaging")
310    }
311
312    pub fn retry_config(&self) -> FlowRetryConfig {
313        self.retry.clone()
314    }
315
316    pub fn oauth_broker_config(&self) -> Option<OAuthBrokerConfig> {
317        let env_secret = std::env::var("GREENTIC_OAUTH_BROKER_SHARED_SECRET").ok();
318        self.oauth_broker_config_with_env(env_secret.as_deref())
319    }
320
321    /// Internal builder that accepts the env-var value explicitly so that
322    /// tests can exercise the priority logic without mutating the process
323    /// environment (which is unsafe in Rust 2024).
324    fn oauth_broker_config_with_env(&self, env_secret: Option<&str>) -> Option<OAuthBrokerConfig> {
325        let oauth = self.oauth.as_ref()?;
326        let mut cfg = OAuthBrokerConfig::new(&oauth.http_base_url, &oauth.nats_url);
327        if !oauth.provider.is_empty() {
328            cfg.default_provider = Some(oauth.provider.clone());
329        }
330        if let Some(team) = &oauth.team
331            && !team.is_empty()
332        {
333            cfg.team = Some(team.clone());
334        }
335        // Prefer env var; fall back to yaml field. Never log the value. A
336        // blank env value is "not set" (like every other blank env knob), so an
337        // empty `GREENTIC_OAUTH_BROKER_SHARED_SECRET=` cannot override a
338        // configured secret with nothing. The value itself is kept verbatim.
339        let usable = |raw: &str| !raw.trim().is_empty();
340        cfg.shared_secret = env_secret
341            .filter(|raw| usable(raw))
342            .map(str::to_owned)
343            .or_else(|| oauth.shared_secret.clone().filter(|raw| usable(raw)));
344        Some(cfg)
345    }
346
347    /// Derive a tenant context for the current configuration. This is used when
348    /// evaluating scoped requirements (e.g. secrets).
349    ///
350    /// Fails when the tenant id or `GREENTIC_ENV` is not a valid identifier;
351    /// it never substitutes the `local` tenant/env.
352    pub fn try_tenant_ctx(&self) -> Result<greentic_types::TenantCtx> {
353        tenant_ctx_for(&self.tenant, greentic_env().as_deref())
354    }
355
356    /// Infallible variant kept for callers that cannot propagate errors.
357    ///
358    /// Configs are validated with [`Self::try_tenant_ctx`] when loaded
359    /// (`load_from_path`, `run`), so the fallback below is unreachable for
360    /// validated configs; it logs loudly if it is ever taken.
361    pub fn tenant_ctx(&self) -> greentic_types::TenantCtx {
362        match self.try_tenant_ctx() {
363            Ok(ctx) => ctx,
364            Err(err) => {
365                tracing::error!(
366                    tenant = %self.tenant,
367                    error = %err,
368                    "invalid tenant/env identifier; falling back to local context"
369                );
370                local_fallback_ctx()
371            }
372        }
373    }
374}
375
376/// Last-resort context for the infallible [`HostConfig::tenant_ctx`] shim.
377///
378/// `local` is a compile-time literal that satisfies the identifier grammar, so
379/// the `expect`s below cannot fire; validated configs never reach this path.
380#[allow(clippy::expect_used)]
381fn local_fallback_ctx() -> greentic_types::TenantCtx {
382    greentic_types::TenantCtx::new(
383        greentic_types::EnvId::new("local").expect("`local` is a valid env id"),
384        greentic_types::TenantId::new("local").expect("`local` is a valid tenant id"),
385    )
386}
387
388/// A raw `GREENTIC_ENV` / `DEFAULT_TENANT` style value: trimmed, and `None` when
389/// absent OR blank. A blank value is "not configured", exactly like an unset one.
390pub(crate) fn non_blank(raw: Option<&str>) -> Option<String> {
391    raw.map(str::trim)
392        .filter(|v| !v.is_empty())
393        .map(str::to_string)
394}
395
396/// The deployment env from `GREENTIC_ENV`, `None` when unset or blank. Every
397/// reader goes through this so an empty value cannot behave differently per
398/// call site (previously: `""` in one place, an error in another).
399pub(crate) fn greentic_env() -> Option<String> {
400    non_blank(std::env::var("GREENTIC_ENV").ok().as_deref())
401}
402
403/// [`greentic_env`] with the documented `local` default.
404pub(crate) fn greentic_env_or_local() -> String {
405    greentic_env().unwrap_or_else(|| "local".to_string())
406}
407
408fn tenant_ctx_for(tenant: &str, env: Option<&str>) -> Result<greentic_types::TenantCtx> {
409    // An empty `GREENTIC_ENV` is "not configured", like an unset one.
410    let env = env
411        .map(str::trim)
412        .filter(|v| !v.is_empty())
413        .unwrap_or("local");
414    let env_id = greentic_types::EnvId::from_str(env)
415        .map_err(|err| anyhow::anyhow!("invalid GREENTIC_ENV `{env}`: {err}"))?;
416    let tenant_id = greentic_types::TenantId::from_str(tenant)
417        .map_err(|err| anyhow::anyhow!("invalid tenant id `{tenant}`: {err}"))?;
418    // The strictest downstream rule (secrets path), enforced once here.
419    crate::secrets_broker::validate_tenant_segment(tenant)?;
420    Ok(greentic_types::TenantCtx::new(env_id, tenant_id))
421}
422
423fn webhook_policy_from_bindings(bindings: &BindingsFile) -> Result<WebhookPolicy> {
424    match bindings.flow_type_bindings.get("webhook") {
425        Some(binding) => serde_yaml::from_value::<WebhookBindingConfig>(binding.config.clone())
426            .map(WebhookPolicy::from)
427            .context("failed to parse webhook binding config"),
428        None => Ok(WebhookPolicy::default()),
429    }
430}
431
432impl SecretsPolicy {
433    fn from_bindings(bindings: &BindingsFile) -> Self {
434        let binding_allowed = bindings
435            .flow_type_bindings
436            .values()
437            .flat_map(|binding| binding.secrets.iter().cloned())
438            .collect::<HashSet<_>>();
439        Self {
440            binding_allowed,
441            flow_discovered: Arc::new(RwLock::new(HashSet::new())),
442            allow_all: false,
443        }
444    }
445
446    pub fn is_allowed(&self, key: &str) -> bool {
447        if self.allow_all || self.binding_allowed.contains(key) {
448            return true;
449        }
450        self.flow_discovered.read().contains(key)
451    }
452
453    pub fn allow_all() -> Self {
454        Self {
455            binding_allowed: HashSet::new(),
456            flow_discovered: Arc::new(RwLock::new(HashSet::new())),
457            allow_all: true,
458        }
459    }
460
461    /// Register a secret name discovered while loading a flow's node config.
462    ///
463    /// Components are gated by [`is_allowed`]; the bindings file is the
464    /// authoritative source, but flows that reference secrets directly via
465    /// node config fields (`api_key_secret: "llm-api-key"`) would otherwise
466    /// have their lookups denied even when the secret is provisioned. Calling
467    /// this from the pack flow loader closes that gap without changing the
468    /// component manifest contract.
469    pub fn register_flow_secret(&self, name: &str) {
470        if name.is_empty() {
471            return;
472        }
473        self.flow_discovered.write().insert(name.to_string());
474    }
475
476    /// Walk a JSON value (typically a flow node's config block) and register
477    /// any string-valued field whose key ends in `_secret`. Recurses through
478    /// nested objects and arrays.
479    pub fn register_flow_secret_refs(&self, value: &Value) {
480        match value {
481            Value::Object(map) => {
482                for (key, val) in map {
483                    if key.ends_with("_secret")
484                        && let Value::String(name) = val
485                    {
486                        self.register_flow_secret(name);
487                    } else {
488                        self.register_flow_secret_refs(val);
489                    }
490                }
491            }
492            Value::Array(items) => {
493                for item in items {
494                    self.register_flow_secret_refs(item);
495                }
496            }
497            _ => {}
498        }
499    }
500}
501
502impl OperatorPolicy {
503    pub fn from_config(config: OperatorPolicyConfig) -> Self {
504        let allowed_providers = config.allowed_providers.into_iter().collect::<HashSet<_>>();
505        let allowed_ops = config
506            .allowed_ops
507            .into_iter()
508            .map(|(provider, ops)| (provider, ops.into_iter().collect::<HashSet<_>>()))
509            .collect::<HashMap<_, _>>();
510        let allow_all = allowed_providers.is_empty() && allowed_ops.is_empty();
511        Self {
512            allow_all,
513            allowed_providers,
514            allowed_ops,
515        }
516    }
517
518    pub fn allow_all() -> Self {
519        Self {
520            allow_all: true,
521            allowed_providers: HashSet::new(),
522            allowed_ops: HashMap::new(),
523        }
524    }
525
526    pub fn allows_provider(&self, provider_id: Option<&str>, provider_type: &str) -> bool {
527        if self.allow_all {
528            return true;
529        }
530        provider_id
531            .map(|id| self.allowed_providers.contains(id))
532            .unwrap_or(false)
533            || self.allowed_providers.contains(provider_type)
534    }
535
536    pub fn allows_op(&self, provider_id: Option<&str>, provider_type: &str, op_id: &str) -> bool {
537        if self.allow_all {
538            return true;
539        }
540        if let Some(ops) = provider_id.and_then(|id| self.allowed_ops.get(id)) {
541            return ops.contains(op_id);
542        }
543        if let Some(ops) = self.allowed_ops.get(provider_type) {
544            return ops.contains(op_id);
545        }
546        self.allows_provider(provider_id, provider_type)
547    }
548}
549
550impl Default for RateLimits {
551    fn default() -> Self {
552        Self {
553            messaging_send_qps: default_messaging_qps(),
554            messaging_burst: default_messaging_burst(),
555        }
556    }
557}
558
559impl Default for StateStorePolicy {
560    fn default() -> Self {
561        Self {
562            allow: default_state_store_allow(),
563        }
564    }
565}
566
567fn default_messaging_qps() -> u32 {
568    10
569}
570
571fn default_messaging_burst() -> u32 {
572    20
573}
574
575fn default_state_store_allow() -> bool {
576    true
577}
578
579impl From<WebhookBindingConfig> for WebhookPolicy {
580    fn from(value: WebhookBindingConfig) -> Self {
581        Self {
582            allow_paths: value.allow_paths,
583            deny_paths: value.deny_paths,
584        }
585    }
586}
587
588impl WebhookPolicy {
589    pub fn is_allowed(&self, path: &str) -> bool {
590        if self
591            .deny_paths
592            .iter()
593            .any(|prefix| path.starts_with(prefix))
594        {
595            return false;
596        }
597
598        if self.allow_paths.is_empty() {
599            return true;
600        }
601
602        self.allow_paths
603            .iter()
604            .any(|prefix| path.starts_with(prefix))
605    }
606}
607
608impl TimerBinding {
609    pub fn schedule_id(&self) -> &str {
610        self.schedule_id.as_deref().unwrap_or(self.flow_id.as_str())
611    }
612}
613
614impl Default for FlowRetryConfig {
615    fn default() -> Self {
616        Self {
617            max_attempts: default_retry_attempts(),
618            base_delay_ms: default_retry_base_delay_ms(),
619        }
620    }
621}
622
623#[cfg(test)]
624mod operator_policy_tests {
625    use super::{OperatorPolicy, OperatorPolicyConfig};
626    use std::collections::HashMap;
627
628    #[test]
629    fn policy_allows_configured_provider_op() {
630        let mut allowed_ops = HashMap::new();
631        allowed_ops.insert("provider.allowed".into(), vec!["op1".into(), "op2".into()]);
632        let config = OperatorPolicyConfig {
633            allowed_providers: vec!["provider.allowed".into()],
634            allowed_ops,
635        };
636        let policy = OperatorPolicy::from_config(config);
637        assert!(policy.allows_provider(Some("provider.allowed"), "provider.allowed"));
638        assert!(policy.allows_op(Some("provider.allowed"), "provider.allowed", "op1"));
639        assert!(!policy.allows_op(Some("provider.allowed"), "provider.allowed", "other"));
640        assert!(!policy.allows_provider(Some("provider.denied"), "provider.denied"));
641    }
642
643    #[test]
644    fn policy_allow_all_defaults_true() {
645        let policy = OperatorPolicy::allow_all();
646        assert!(policy.allows_provider(None, "any"));
647        assert!(policy.allows_op(None, "any", "op"));
648    }
649}
650
651fn default_retry_attempts() -> u32 {
652    3
653}
654
655fn default_retry_base_delay_ms() -> u64 {
656    250
657}
658
659#[cfg(test)]
660#[allow(clippy::items_after_test_module)]
661mod tests {
662    use super::*;
663
664    #[test]
665    fn blank_greentic_env_is_treated_as_unset() {
666        for blank in [None, Some(""), Some("  ")] {
667            let ctx = tenant_ctx_for("tenant-a", blank).expect("blank env means local");
668            assert_eq!(ctx.env.as_str(), "local");
669        }
670        assert!(tenant_ctx_for("tenant-a", Some("bad env!")).is_err());
671    }
672
673    use crate::gtbind::{PackBinding, TenantBindings};
674    use std::collections::HashMap;
675    use std::path::PathBuf;
676
677    fn host_config_with_oauth(oauth: Option<OAuthConfig>) -> HostConfig {
678        HostConfig {
679            tenant: "tenant-a".to_string(),
680            bindings_path: PathBuf::from("/tmp/bindings.yaml"),
681            flow_type_bindings: HashMap::new(),
682            rate_limits: RateLimits::default(),
683            retry: FlowRetryConfig::default(),
684            http_enabled: false,
685            secrets_policy: SecretsPolicy::allow_all(),
686            state_store_policy: StateStorePolicy::default(),
687            webhook_policy: WebhookPolicy::default(),
688            timers: Vec::new(),
689            oauth,
690            mocks: None,
691            pack_bindings: Vec::new(),
692            env_passthrough: Vec::new(),
693            trace: TraceConfig::from_env(),
694            validation: ValidationConfig::from_env(),
695            operator_policy: OperatorPolicy::allow_all(),
696            fast2flow: Fast2FlowRoutingConfig::default(),
697            #[cfg(feature = "agentic-worker")]
698            agents: HashMap::new(),
699            #[cfg(feature = "agentic-worker")]
700            graphs: HashMap::new(),
701        }
702    }
703
704    #[cfg(feature = "agentic-worker")]
705    #[test]
706    fn load_from_path_parses_agents_section() {
707        // All seven `limits` fields are required: AgentLimits has no serde
708        // defaults, so operator-authored YAML must spell each one out.
709        let yaml = r#"
710tenant: acme
711agents:
712  greeter:
713    agent_id: greeter
714    system_prompt: "You are a greeter."
715    tools: []
716    llm:
717      provider: openai
718      model: gpt-4o-mini
719    limits:
720      max_iter: 8
721      timeout: 60
722      max_history_turns: 20
723      llm_retry_attempts: 3
724      llm_retry_backoff: 250
725      provider_failure_message: null
726      daily_token_cap_per_tenant: null
727"#;
728        let dir = tempfile::tempdir().unwrap();
729        let path = dir.path().join("bindings.yaml");
730        std::fs::write(&path, yaml).unwrap();
731        let cfg = HostConfig::load_from_path(&path).unwrap();
732        assert!(cfg.agents.contains_key("greeter"));
733        let greeter = &cfg.agents["greeter"];
734        assert_eq!(greeter.system_prompt, "You are a greeter.");
735        assert_eq!(greeter.limits.max_iter, 8);
736        // duration_secs / duration_ms custom serde maps the integers above.
737        assert_eq!(greeter.limits.timeout, std::time::Duration::from_secs(60));
738        assert_eq!(
739            greeter.limits.llm_retry_backoff,
740            std::time::Duration::from_millis(250)
741        );
742    }
743
744    #[cfg(feature = "agentic-worker")]
745    #[test]
746    fn load_from_path_omitted_agents_section_yields_empty_map() {
747        let yaml = "tenant: acme\n";
748        let dir = tempfile::tempdir().unwrap();
749        let path = dir.path().join("bindings.yaml");
750        std::fs::write(&path, yaml).unwrap();
751        let cfg = HostConfig::load_from_path(&path).unwrap();
752        assert!(cfg.agents.is_empty());
753    }
754
755    #[test]
756    fn host_config_loads_fast2flow_routing_block() {
757        let temp = tempfile::TempDir::new().expect("tempdir");
758        let path = temp.path().join("bindings.yaml");
759        std::fs::write(
760            &path,
761            r#"
762tenant: demo
763fast2flow:
764  enabled: true
765  component_ref: router.fast2flow
766  operation: handle-hook
767  scope: tenant-a
768  registry_path: /mnt/registry
769  indexes_path: /mnt/indexes
770  time_budget_ms: 750
771"#,
772        )
773        .expect("write bindings");
774
775        let cfg = HostConfig::load_from_path(&path).expect("load config");
776
777        assert!(cfg.fast2flow.enabled);
778        assert_eq!(cfg.fast2flow.component_ref, "router.fast2flow");
779        assert_eq!(cfg.fast2flow.operation, "handle-hook");
780        assert_eq!(cfg.fast2flow.scope.as_deref(), Some("tenant-a"));
781        assert_eq!(cfg.fast2flow.registry_path, "/mnt/registry");
782        assert_eq!(cfg.fast2flow.indexes_path, "/mnt/indexes");
783        assert_eq!(cfg.fast2flow.time_budget_ms, 750);
784    }
785
786    #[test]
787    fn secrets_policy_register_flow_secret_refs_walks_nested_objects() {
788        let policy = SecretsPolicy {
789            binding_allowed: HashSet::new(),
790            flow_discovered: Arc::new(RwLock::new(HashSet::new())),
791            allow_all: false,
792        };
793
794        // Bare bindings deny anything by default.
795        assert!(!policy.is_allowed("llm-api-key"));
796
797        // Simulate a flow node config block carrying both a top-level
798        // *_secret reference and a nested one inside an arbitrary subtree.
799        let node_config = serde_json::json!({
800            "api_key_secret": "llm-api-key",
801            "provider": "openai",
802            "fallback": {
803                "secondary_api_key_secret": "openrouter-key",
804                "model": "gpt-4o",
805            },
806            "list": [
807                { "tertiary_secret": "another-key" },
808                { "non_secret_field": "ignored" },
809            ],
810            "ignored_field": ""
811        });
812
813        policy.register_flow_secret_refs(&node_config);
814
815        assert!(policy.is_allowed("llm-api-key"));
816        assert!(policy.is_allowed("openrouter-key"));
817        assert!(policy.is_allowed("another-key"));
818        assert!(!policy.is_allowed("non_secret_field"));
819        assert!(!policy.is_allowed("ignored"));
820    }
821
822    #[test]
823    fn secrets_policy_ignores_empty_or_non_string_secret_values() {
824        let policy = SecretsPolicy {
825            binding_allowed: HashSet::new(),
826            flow_discovered: Arc::new(RwLock::new(HashSet::new())),
827            allow_all: false,
828        };
829
830        let node_config = serde_json::json!({
831            "api_key_secret": "",
832            "fallback_secret": null,
833            "numeric_secret": 42,
834            "real_secret": "good-key",
835        });
836
837        policy.register_flow_secret_refs(&node_config);
838
839        assert!(policy.is_allowed("good-key"));
840        assert!(!policy.is_allowed(""));
841    }
842
843    #[test]
844    fn oauth_broker_config_absent_without_block() {
845        let cfg = host_config_with_oauth(None);
846        assert!(cfg.oauth_broker_config().is_none());
847    }
848
849    #[test]
850    fn oauth_broker_config_maps_fields() {
851        let cfg = host_config_with_oauth(Some(OAuthConfig {
852            http_base_url: "https://oauth.example/".into(),
853            nats_url: "nats://broker:4222".into(),
854            provider: "demo".into(),
855            env: None,
856            team: Some("ops".into()),
857            shared_secret: None,
858        }));
859        // Use `_with_env(None)` so the test is not perturbed by a set
860        // GREENTIC_OAUTH_BROKER_SHARED_SECRET environment variable.
861        let broker = cfg
862            .oauth_broker_config_with_env(None)
863            .expect("missing broker config");
864        assert_eq!(broker.http_base_url, "https://oauth.example/");
865        assert_eq!(broker.nats_url, "nats://broker:4222");
866        assert_eq!(broker.default_provider.as_deref(), Some("demo"));
867        assert_eq!(broker.team.as_deref(), Some("ops"));
868        assert!(broker.shared_secret.is_none());
869    }
870
871    #[test]
872    fn oauth_broker_config_maps_shared_secret_from_yaml() {
873        let cfg = host_config_with_oauth(Some(OAuthConfig {
874            http_base_url: "https://oauth.example/".into(),
875            nats_url: "nats://broker:4222".into(),
876            provider: "demo".into(),
877            env: None,
878            team: None,
879            shared_secret: Some("yaml-secret".into()),
880        }));
881        // Pass None as the env var to exercise the yaml-field fallback path.
882        let broker = cfg
883            .oauth_broker_config_with_env(None)
884            .expect("missing broker config");
885        assert_eq!(broker.shared_secret.as_deref(), Some("yaml-secret"));
886    }
887
888    #[test]
889    fn oauth_broker_config_env_overrides_yaml_shared_secret() {
890        let cfg = host_config_with_oauth(Some(OAuthConfig {
891            http_base_url: "https://oauth.example/".into(),
892            nats_url: "nats://broker:4222".into(),
893            provider: "demo".into(),
894            env: None,
895            team: None,
896            shared_secret: Some("yaml-secret".into()),
897        }));
898        let broker = cfg
899            .oauth_broker_config_with_env(Some("env-secret"))
900            .expect("missing broker config");
901        assert_eq!(broker.shared_secret.as_deref(), Some("env-secret"));
902    }
903
904    #[test]
905    fn oauth_broker_config_env_provides_secret_when_yaml_absent() {
906        let cfg = host_config_with_oauth(Some(OAuthConfig {
907            http_base_url: "https://oauth.example/".into(),
908            nats_url: "nats://broker:4222".into(),
909            provider: "demo".into(),
910            env: None,
911            team: None,
912            shared_secret: None,
913        }));
914        let broker = cfg
915            .oauth_broker_config_with_env(Some("env-only-secret"))
916            .expect("missing broker config");
917        assert_eq!(broker.shared_secret.as_deref(), Some("env-only-secret"));
918    }
919
920    #[test]
921    fn a_blank_env_shared_secret_does_not_override_the_yaml_one() {
922        let cfg = host_config_with_oauth(Some(OAuthConfig {
923            http_base_url: "https://oauth.example/".into(),
924            nats_url: "nats://broker:4222".into(),
925            provider: "demo".into(),
926            env: None,
927            team: None,
928            shared_secret: Some("yaml-secret".into()),
929        }));
930        for blank in ["", "   "] {
931            let broker = cfg
932                .oauth_broker_config_with_env(Some(blank))
933                .expect("missing broker config");
934            assert_eq!(
935                broker.shared_secret.as_deref(),
936                Some("yaml-secret"),
937                "{blank:?}"
938            );
939        }
940        // Blank everywhere means no secret, not an empty one.
941        let none = host_config_with_oauth(Some(OAuthConfig {
942            http_base_url: "https://oauth.example/".into(),
943            nats_url: "nats://broker:4222".into(),
944            provider: "demo".into(),
945            env: None,
946            team: None,
947            shared_secret: Some(String::new()),
948        }));
949        let broker = none
950            .oauth_broker_config_with_env(Some(""))
951            .expect("missing broker config");
952        assert_eq!(broker.shared_secret, None);
953    }
954
955    #[test]
956    fn invalid_webhook_binding_config_is_an_error_not_allow_all() {
957        let bindings: BindingsFile = serde_yaml::from_str(
958            "tenant: demo\nflow_type_bindings:\n  webhook:\n    adapter: webhook\n    config:\n      deny_paths: not-a-list\n",
959        )
960        .expect("bindings parse");
961        let err = webhook_policy_from_bindings(&bindings).expect_err("must fail");
962        assert!(format!("{err:#}").contains("webhook binding config"));
963    }
964
965    #[test]
966    fn valid_webhook_binding_config_keeps_deny_paths() {
967        let bindings: BindingsFile = serde_yaml::from_str(
968            "tenant: demo\nflow_type_bindings:\n  webhook:\n    adapter: webhook\n    config:\n      deny_paths: [/admin]\n",
969        )
970        .expect("bindings parse");
971        let policy = webhook_policy_from_bindings(&bindings).expect("policy");
972        assert!(!policy.is_allowed("/admin/x"));
973        assert!(policy.is_allowed("/hook"));
974    }
975
976    #[test]
977    fn tenant_ids_a_secret_read_would_refuse_are_rejected_at_load() {
978        for bad in [".hidden", "a..b", "..", ".", &"a".repeat(129)] {
979            let err = tenant_ctx_for(bad, None).expect_err(bad);
980            assert!(
981                err.to_string().contains("invalid tenant id"),
982                "{bad:?}: {err}"
983            );
984        }
985        for good in ["demo", "acme-1.eu", "T_1", "a.b"] {
986            assert!(tenant_ctx_for(good, None).is_ok(), "{good:?}");
987        }
988    }
989
990    #[test]
991    fn tenant_ctx_for_rejects_invalid_ids_instead_of_falling_back() {
992        assert!(tenant_ctx_for("bad tenant!", None).is_err());
993        assert!(tenant_ctx_for("demo", Some("bad env!")).is_err());
994        let ctx = tenant_ctx_for("demo", None).expect("valid");
995        assert_eq!(ctx.tenant.as_str(), "demo");
996        assert_eq!(ctx.env.as_str(), "local");
997    }
998
999    #[test]
1000    fn gtbind_configs_enable_outbound_http() {
1001        let cfg = HostConfig::from_gtbind(TenantBindings {
1002            tenant: "demo".into(),
1003            packs: vec![PackBinding {
1004                pack_id: "deep-research-demo".into(),
1005                pack_ref: "deep-research-demo@0.1.0".into(),
1006                pack_locator: None,
1007                flows: vec!["main".into()],
1008            }],
1009            env_passthrough: Vec::new(),
1010        });
1011
1012        assert!(
1013            cfg.http_enabled,
1014            "gtbind-backed tenants should allow outbound component HTTP"
1015        );
1016    }
1017}
1018
1019#[cfg(test)]
1020mod non_blank_tests {
1021    use super::*;
1022
1023    #[test]
1024    fn blank_and_whitespace_are_unset() {
1025        assert_eq!(non_blank(None), None);
1026        assert_eq!(non_blank(Some("")), None);
1027        assert_eq!(non_blank(Some("  \t")), None);
1028        assert_eq!(non_blank(Some(" prod ")), Some("prod".to_string()));
1029    }
1030}