Skip to main content

zeph_core/
config.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Extension trait for resolving vault secrets into a Config.
5//!
6//! This trait is defined in zeph-core (not in zeph-config) due to Rust's orphan rule:
7//! implementing a foreign trait on a foreign type requires the trait to be defined locally.
8
9// Re-export Config types from zeph-config for internal use.
10pub use zeph_config::{
11    AcpAuthMethod, AcpConfig, AcpLspConfig, AcpTransport, AdditionalDir, AdditionalDirError,
12    AgentConfig, CandleConfig, CandleInlineConfig, CascadeClassifierMode, CascadeConfig,
13    ClassifiersConfig, CompressionConfig, CompressionStrategy, Config, ConfigError, ContextFormat,
14    CostConfig, DaemonConfig, DebugConfig, DetectorMode, DiscordConfig, DocumentConfig, DumpFormat,
15    ExperimentConfig, ExperimentSchedule, FocusConfig, GatewayConfig, GenerationParams, GonkaNode,
16    GraphConfig, HookAction, HookDef, HookMatcher, IndexConfig, LearningConfig, LlmConfig,
17    LlmRoutingStrategy, LogRotation, LoggingConfig, MAX_TOKENS_CAP, McpConfig, McpOAuthConfig,
18    McpServerConfig, McpTrustLevel, MemoryConfig, MemoryScope, NoteLinkingConfig,
19    OAuthTokenStorage, OrchestrationConfig, PermissionMode, ProviderEntry, ProviderKind,
20    ProviderName, PruningStrategy, RateLimitConfig, ResolvedSecrets, RetrievalConfig, RouterConfig,
21    RouterStrategyConfig, ScheduledTaskConfig, ScheduledTaskKind, SchedulerConfig,
22    SchedulerDaemonConfig, SecurityConfig, SemanticConfig, SessionsConfig, SidequestConfig,
23    SkillFilter, SkillPromptMode, SkillsConfig, SlackConfig, StoreRoutingConfig,
24    StoreRoutingStrategy, SttConfig, SubAgentConfig, SubAgentLifecycleHooks, SubagentHooks,
25    TaskSupervisorConfig, TelegramConfig, TimeoutConfig, ToolDiscoveryConfig,
26    ToolDiscoveryStrategyConfig, ToolFilterConfig, ToolPolicy, TraceConfig, TrustConfig, TuiConfig,
27    VaultConfig, VectorBackend,
28};
29
30pub use zeph_config::{
31    AutoDreamConfig, CategoryConfig, ContextStrategy, DigestConfig, MagicDocsConfig,
32    MicrocompactConfig, PersonaConfig, TrajectoryConfig, TreeConfig,
33};
34pub use zeph_config::{DiagnosticSeverity, DiagnosticsConfig, HoverConfig, LspConfig};
35pub use zeph_config::{QualityConfig, TriggerPolicy};
36pub use zeph_config::{TelemetryBackend, TelemetryConfig};
37
38pub use zeph_config::{
39    ContentIsolationConfig, CustomPiiPattern, ExfiltrationGuardConfig, MemoryWriteValidationConfig,
40    PiiFilterConfig, QuarantineConfig,
41};
42pub use zeph_config::{GuardrailAction, GuardrailConfig, GuardrailFailStrategy};
43
44pub use zeph_config::A2aServerConfig;
45pub use zeph_config::ChannelSkillsConfig;
46pub use zeph_config::{FileChangedConfig, HooksConfig};
47
48pub use zeph_config::{
49    DEFAULT_DEBUG_DIR, DEFAULT_LOG_FILE, DEFAULT_SKILLS_DIR, DEFAULT_SQLITE_PATH,
50    default_debug_dir, default_log_file_path, default_skills_dir, default_sqlite_path,
51    is_legacy_default_debug_dir, is_legacy_default_log_file, is_legacy_default_skills_path,
52    is_legacy_default_sqlite_path,
53};
54
55pub use zeph_config::providers::{default_stt_language, default_stt_provider, validate_pool};
56
57pub mod migrate {
58    pub use zeph_config::migrate::*;
59}
60
61use crate::vault::{Secret, VaultProvider};
62
63/// Extension trait for resolving vault secrets into a [`Config`].
64///
65/// Implemented for [`Config`] in `zeph-core` because `VaultProvider` lives here.
66/// Call with `use zeph_core::config::SecretResolver` in scope.
67pub trait SecretResolver {
68    /// Populate `secrets` fields from the vault.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if the vault backend fails.
73    fn resolve_secrets(
74        &mut self,
75        vault: &dyn VaultProvider,
76    ) -> impl std::future::Future<Output = Result<(), ConfigError>> + Send;
77}
78
79fn log_gonka_credential_status(has_key: bool, has_address: bool) {
80    match (has_key, has_address) {
81        (true, true) => tracing::info!("gonka wallet credentials resolved from vault"),
82        (true, false) => tracing::warn!(
83            "ZEPH_GONKA_PRIVATE_KEY is set but ZEPH_GONKA_ADDRESS is missing from vault"
84        ),
85        (false, true) => tracing::warn!(
86            "ZEPH_GONKA_ADDRESS is set but ZEPH_GONKA_PRIVATE_KEY is missing from vault"
87        ),
88        (false, false) => {}
89    }
90}
91
92// TODO(critic): vault values are inserted verbatim into typed config fields.
93// Consider centralizing whitespace trimming and empty-string normalization
94// here so every consumer (qdrant client, claude, openai, etc.) sees a clean value.
95impl SecretResolver for Config {
96    async fn resolve_secrets(&mut self, vault: &dyn VaultProvider) -> Result<(), ConfigError> {
97        if let Some(val) = vault.get_secret("ZEPH_CLAUDE_API_KEY").await? {
98            self.secrets.claude_api_key = Some(Secret::new(val));
99        }
100        if let Some(val) = vault.get_secret("ZEPH_OPENAI_API_KEY").await? {
101            self.secrets.openai_api_key = Some(Secret::new(val));
102        }
103        if let Some(val) = vault.get_secret("ZEPH_GEMINI_API_KEY").await? {
104            self.secrets.gemini_api_key = Some(Secret::new(val));
105        }
106        if let Some(val) = vault.get_secret("ZEPH_GONKA_PRIVATE_KEY").await? {
107            self.secrets.gonka_private_key = Some(Secret::new(val));
108        }
109        if let Some(val) = vault.get_secret("ZEPH_GONKA_ADDRESS").await? {
110            self.secrets.gonka_address = Some(Secret::new(val));
111        }
112        log_gonka_credential_status(
113            self.secrets.gonka_private_key.is_some(),
114            self.secrets.gonka_address.is_some(),
115        );
116        if let Some(val) = vault.get_secret("ZEPH_TELEGRAM_TOKEN").await?
117            && let Some(tg) = self.telegram.as_mut()
118        {
119            tg.token = Some(val);
120        }
121        if let Some(val) = vault.get_secret("ZEPH_A2A_AUTH_TOKEN").await? {
122            self.a2a.auth_token = Some(val);
123        }
124        for entry in &self.llm.providers {
125            if entry.provider_type == crate::config::ProviderKind::Compatible
126                && let Some(ref name) = entry.name
127            {
128                let env_key = format!("ZEPH_COMPATIBLE_{}_API_KEY", name.to_uppercase());
129                if let Some(val) = vault.get_secret(&env_key).await? {
130                    self.secrets
131                        .compatible_api_keys
132                        .insert(name.clone(), Secret::new(val));
133                }
134            }
135        }
136        if let Some(val) = vault.get_secret("ZEPH_HF_TOKEN").await? {
137            self.classifiers.hf_token = Some(val.clone());
138            if let Some(candle) = self.llm.candle.as_mut() {
139                candle.hf_token = Some(val);
140            }
141        }
142        if let Some(val) = vault.get_secret("ZEPH_GATEWAY_TOKEN").await? {
143            self.gateway.auth_token = Some(val);
144        }
145        if let Some(val) = vault.get_secret("ZEPH_DATABASE_URL").await? {
146            self.memory.database_url = Some(val);
147        }
148        if let Some(val) = vault.get_secret("ZEPH_QDRANT_API_KEY").await? {
149            self.memory.qdrant_api_key = Some(Secret::new(val));
150        }
151        if let Some(val) = vault.get_secret("ZEPH_DISCORD_TOKEN").await?
152            && let Some(dc) = self.discord.as_mut()
153        {
154            dc.token = Some(val);
155        }
156        if let Some(val) = vault.get_secret("ZEPH_DISCORD_APP_ID").await?
157            && let Some(dc) = self.discord.as_mut()
158        {
159            dc.application_id = Some(val);
160        }
161        if let Some(val) = vault.get_secret("ZEPH_SLACK_BOT_TOKEN").await?
162            && let Some(sl) = self.slack.as_mut()
163        {
164            sl.bot_token = Some(val);
165        }
166        if let Some(val) = vault.get_secret("ZEPH_SLACK_SIGNING_SECRET").await?
167            && let Some(sl) = self.slack.as_mut()
168        {
169            sl.signing_secret = Some(val);
170        }
171        for key in vault.list_keys() {
172            if let Some(custom_name) = key.strip_prefix("ZEPH_SECRET_")
173                && !custom_name.is_empty()
174                && let Some(val) = vault.get_secret(&key).await?
175            {
176                // Canonical form uses underscores. Both `_` and `-` in vault key names
177                // are normalized to `_` so that ZEPH_SECRET_MY-KEY and ZEPH_SECRET_MY_KEY
178                // both map to "my_key", matching SKILL.md requires-secrets parsing.
179                let normalized = custom_name.to_lowercase().replace('-', "_");
180                self.secrets.custom.insert(normalized, Secret::new(val));
181            }
182        }
183        Ok(())
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    #[tokio::test]
192    #[cfg(any(test, feature = "mock"))]
193    async fn resolve_secrets_with_mock_vault() {
194        use crate::vault::MockVaultProvider;
195
196        let vault = MockVaultProvider::new()
197            .with_secret("ZEPH_CLAUDE_API_KEY", "sk-test-123")
198            .with_secret("ZEPH_TELEGRAM_TOKEN", "tg-token-456");
199
200        let mut config = Config::load(std::path::Path::new("/nonexistent/config.toml")).unwrap();
201        config.resolve_secrets(&vault).await.unwrap();
202
203        assert_eq!(
204            config.secrets.claude_api_key.as_ref().unwrap().expose(),
205            "sk-test-123"
206        );
207        if let Some(tg) = config.telegram {
208            assert_eq!(tg.token.as_deref(), Some("tg-token-456"));
209        }
210    }
211
212    #[tokio::test]
213    #[cfg(any(test, feature = "mock"))]
214    async fn resolve_gonka_secrets_both_present() {
215        use crate::vault::MockVaultProvider;
216
217        let vault = MockVaultProvider::new()
218            .with_secret("ZEPH_GONKA_PRIVATE_KEY", "gonka-priv-key-abc")
219            .with_secret("ZEPH_GONKA_ADDRESS", "gonka1xyzaddress");
220
221        let mut config = Config::load(std::path::Path::new("/nonexistent/config.toml")).unwrap();
222        config.resolve_secrets(&vault).await.unwrap();
223
224        assert_eq!(
225            config.secrets.gonka_private_key.as_ref().unwrap().expose(),
226            "gonka-priv-key-abc"
227        );
228        assert_eq!(
229            config.secrets.gonka_address.as_ref().unwrap().expose(),
230            "gonka1xyzaddress"
231        );
232    }
233
234    #[tokio::test]
235    #[cfg(any(test, feature = "mock"))]
236    async fn resolve_gonka_partial_only_private_key() {
237        use crate::vault::MockVaultProvider;
238
239        let vault =
240            MockVaultProvider::new().with_secret("ZEPH_GONKA_PRIVATE_KEY", "gonka-priv-key-only");
241
242        let mut config = Config::load(std::path::Path::new("/nonexistent/config.toml")).unwrap();
243        config.resolve_secrets(&vault).await.unwrap();
244
245        assert!(config.secrets.gonka_private_key.is_some());
246        assert!(config.secrets.gonka_address.is_none());
247    }
248}