Skip to main content

systemprompt_models/
secrets.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::path::Path;
5use std::sync::OnceLock;
6
7use crate::profile::{resolve_with_home, SecretsSource, SecretsValidationMode};
8use crate::profile_bootstrap::ProfileBootstrap;
9
10static SECRETS: OnceLock<Secrets> = OnceLock::new();
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct Secrets {
14    pub jwt_secret: String,
15
16    pub database_url: String,
17
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub sync_token: Option<String>,
20
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub gemini: Option<String>,
23
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub anthropic: Option<String>,
26
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub openai: Option<String>,
29
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub github: Option<String>,
32
33    #[serde(default, flatten)]
34    pub custom: HashMap<String, String>,
35}
36
37const JWT_SECRET_MIN_LENGTH: usize = 32;
38
39impl Secrets {
40    pub fn parse(content: &str) -> Result<Self> {
41        let secrets: Self =
42            serde_json::from_str(content).context("Failed to parse secrets JSON")?;
43        secrets.validate()?;
44        Ok(secrets)
45    }
46
47    fn validate(&self) -> Result<()> {
48        if self.jwt_secret.len() < JWT_SECRET_MIN_LENGTH {
49            anyhow::bail!(
50                "jwt_secret must be at least {} characters (got {})",
51                JWT_SECRET_MIN_LENGTH,
52                self.jwt_secret.len()
53            );
54        }
55        Ok(())
56    }
57
58    pub const fn has_ai_provider(&self) -> bool {
59        self.gemini.is_some() || self.anthropic.is_some() || self.openai.is_some()
60    }
61
62    pub fn get(&self, key: &str) -> Option<&String> {
63        match key {
64            "jwt_secret" | "JWT_SECRET" => Some(&self.jwt_secret),
65            "database_url" | "DATABASE_URL" => Some(&self.database_url),
66            "sync_token" | "SYNC_TOKEN" => self.sync_token.as_ref(),
67            "gemini" | "GEMINI_API_KEY" => self.gemini.as_ref(),
68            "anthropic" | "ANTHROPIC_API_KEY" => self.anthropic.as_ref(),
69            "openai" | "OPENAI_API_KEY" => self.openai.as_ref(),
70            "github" | "GITHUB_TOKEN" => self.github.as_ref(),
71            other => self.custom.get(other),
72        }
73    }
74
75    pub fn log_configured_providers(&self) {
76        let configured: Vec<&str> = [
77            self.gemini.as_ref().map(|_| "gemini"),
78            self.anthropic.as_ref().map(|_| "anthropic"),
79            self.openai.as_ref().map(|_| "openai"),
80            self.github.as_ref().map(|_| "github"),
81        ]
82        .into_iter()
83        .flatten()
84        .collect();
85
86        tracing::info!(providers = ?configured, "Configured API providers");
87    }
88
89    pub fn custom_env_vars(&self) -> Vec<(String, &str)> {
90        self.custom
91            .iter()
92            .flat_map(|(key, value)| {
93                let upper_key = key.to_uppercase();
94                let value_str = value.as_str();
95                if upper_key == *key {
96                    vec![(key.clone(), value_str)]
97                } else {
98                    vec![(key.clone(), value_str), (upper_key, value_str)]
99                }
100            })
101            .collect()
102    }
103
104    pub fn custom_env_var_names(&self) -> Vec<String> {
105        self.custom.keys().map(|key| key.to_uppercase()).collect()
106    }
107}
108
109#[derive(Debug, Clone, Copy)]
110pub struct SecretsBootstrap;
111
112#[derive(Debug, thiserror::Error)]
113pub enum SecretsBootstrapError {
114    #[error(
115        "Secrets not initialized. Call SecretsBootstrap::init() after ProfileBootstrap::init()"
116    )]
117    NotInitialized,
118
119    #[error("Secrets already initialized")]
120    AlreadyInitialized,
121
122    #[error("Profile not initialized. Call ProfileBootstrap::init() first")]
123    ProfileNotInitialized,
124
125    #[error("Secrets file not found: {path}")]
126    FileNotFound { path: String },
127
128    #[error("Invalid secrets file: {message}")]
129    InvalidSecretsFile { message: String },
130
131    #[error("No secrets configured. Create a secrets.json file.")]
132    NoSecretsConfigured,
133
134    #[error(
135        "JWT secret is required. Add 'jwt_secret' to your secrets file or set JWT_SECRET \
136         environment variable."
137    )]
138    JwtSecretRequired,
139
140    #[error(
141        "Database URL is required. Add 'database_url' to your secrets.json or set DATABASE_URL \
142         environment variable."
143    )]
144    DatabaseUrlRequired,
145}
146
147impl SecretsBootstrap {
148    pub fn init() -> Result<&'static Secrets> {
149        if SECRETS.get().is_some() {
150            anyhow::bail!(SecretsBootstrapError::AlreadyInitialized);
151        }
152
153        let secrets = Self::load_from_profile_config()?;
154
155        Self::log_loaded_secrets(&secrets);
156
157        SECRETS
158            .set(secrets)
159            .map_err(|_| anyhow::anyhow!(SecretsBootstrapError::AlreadyInitialized))?;
160
161        SECRETS
162            .get()
163            .ok_or_else(|| anyhow::anyhow!(SecretsBootstrapError::NotInitialized))
164    }
165
166    pub fn jwt_secret() -> Result<&'static str, SecretsBootstrapError> {
167        Ok(&Self::get()?.jwt_secret)
168    }
169
170    pub fn database_url() -> Result<&'static str, SecretsBootstrapError> {
171        Ok(&Self::get()?.database_url)
172    }
173
174    fn load_from_env() -> Result<Secrets> {
175        let jwt_secret = std::env::var("JWT_SECRET")
176            .ok()
177            .filter(|s| !s.is_empty())
178            .ok_or(SecretsBootstrapError::JwtSecretRequired)?;
179
180        let database_url = std::env::var("DATABASE_URL")
181            .ok()
182            .filter(|s| !s.is_empty())
183            .ok_or(SecretsBootstrapError::DatabaseUrlRequired)?;
184
185        let custom = std::env::var("SYSTEMPROMPT_CUSTOM_SECRETS")
186            .ok()
187            .filter(|s| !s.is_empty())
188            .map_or_else(HashMap::new, |keys| {
189                keys.split(',')
190                    .filter_map(|key| {
191                        let key = key.trim();
192                        std::env::var(key)
193                            .ok()
194                            .filter(|v| !v.is_empty())
195                            .map(|v| (key.to_owned(), v))
196                    })
197                    .collect()
198            });
199
200        let secrets = Secrets {
201            jwt_secret,
202            database_url,
203            sync_token: std::env::var("SYNC_TOKEN").ok().filter(|s| !s.is_empty()),
204            gemini: std::env::var("GEMINI_API_KEY")
205                .ok()
206                .filter(|s| !s.is_empty()),
207            anthropic: std::env::var("ANTHROPIC_API_KEY")
208                .ok()
209                .filter(|s| !s.is_empty()),
210            openai: std::env::var("OPENAI_API_KEY")
211                .ok()
212                .filter(|s| !s.is_empty()),
213            github: std::env::var("GITHUB_TOKEN").ok().filter(|s| !s.is_empty()),
214            custom,
215        };
216
217        secrets.validate()?;
218        Ok(secrets)
219    }
220
221    fn load_from_profile_config() -> Result<Secrets> {
222        let is_fly_environment = std::env::var("FLY_APP_NAME").is_ok();
223        let is_subprocess = std::env::var("SYSTEMPROMPT_SUBPROCESS").is_ok();
224
225        if is_subprocess || is_fly_environment {
226            if let Ok(jwt_secret) = std::env::var("JWT_SECRET") {
227                if jwt_secret.len() >= JWT_SECRET_MIN_LENGTH {
228                    tracing::debug!(
229                        "Using JWT_SECRET from environment (subprocess/container mode)"
230                    );
231                    return Self::load_from_env();
232                }
233            }
234        }
235
236        let profile =
237            ProfileBootstrap::get().map_err(|_| SecretsBootstrapError::ProfileNotInitialized)?;
238
239        let secrets_config = profile
240            .secrets
241            .as_ref()
242            .ok_or(SecretsBootstrapError::NoSecretsConfigured)?;
243
244        let is_fly_environment = std::env::var("FLY_APP_NAME").is_ok();
245
246        match secrets_config.source {
247            SecretsSource::Env if is_fly_environment => {
248                tracing::debug!("Loading secrets from environment (Fly.io container)");
249                Self::load_from_env()
250            },
251            SecretsSource::Env => {
252                tracing::debug!(
253                    "Profile source is 'env' but running locally, trying file first..."
254                );
255                Self::resolve_and_load_file(&secrets_config.secrets_path).or_else(|_| {
256                    tracing::debug!("File load failed, falling back to environment");
257                    Self::load_from_env()
258                })
259            },
260            SecretsSource::File => {
261                tracing::debug!("Loading secrets from file (profile source: file)");
262                Self::resolve_and_load_file(&secrets_config.secrets_path)
263                    .or_else(|e| Self::handle_load_error(e, secrets_config.validation))
264            },
265        }
266    }
267
268    fn handle_load_error(e: anyhow::Error, mode: SecretsValidationMode) -> Result<Secrets> {
269        log_secrets_issue(&e, mode);
270        Err(e)
271    }
272
273    pub fn get() -> Result<&'static Secrets, SecretsBootstrapError> {
274        SECRETS.get().ok_or(SecretsBootstrapError::NotInitialized)
275    }
276
277    pub fn require() -> Result<&'static Secrets, SecretsBootstrapError> {
278        Self::get()
279    }
280
281    pub fn is_initialized() -> bool {
282        SECRETS.get().is_some()
283    }
284
285    pub fn try_init() -> Result<&'static Secrets> {
286        if SECRETS.get().is_some() {
287            return Self::get().map_err(Into::into);
288        }
289        Self::init()
290    }
291
292    fn resolve_and_load_file(path_str: &str) -> Result<Secrets> {
293        let profile_path = ProfileBootstrap::get_path()
294            .context("SYSTEMPROMPT_PROFILE not set - cannot resolve secrets path")?;
295
296        let profile_dir = Path::new(profile_path)
297            .parent()
298            .context("Invalid profile path - no parent directory")?;
299
300        let resolved_path = resolve_with_home(profile_dir, path_str);
301        Self::load_from_file(&resolved_path)
302    }
303
304    fn load_from_file(path: &Path) -> Result<Secrets> {
305        if !path.exists() {
306            anyhow::bail!(SecretsBootstrapError::FileNotFound {
307                path: path.display().to_string()
308            });
309        }
310
311        let content = std::fs::read_to_string(path)
312            .with_context(|| format!("Failed to read secrets file: {}", path.display()))?;
313
314        let secrets = Secrets::parse(&content).map_err(|e| {
315            anyhow::anyhow!(SecretsBootstrapError::InvalidSecretsFile {
316                message: e.to_string(),
317            })
318        })?;
319
320        tracing::debug!("Loaded secrets from {}", path.display());
321
322        Ok(secrets)
323    }
324
325    fn log_loaded_secrets(secrets: &Secrets) {
326        let message = build_loaded_secrets_message(secrets);
327        tracing::debug!("{}", message);
328    }
329}
330
331fn log_secrets_issue(e: &anyhow::Error, mode: SecretsValidationMode) {
332    match mode {
333        SecretsValidationMode::Warn => log_secrets_warn(e),
334        SecretsValidationMode::Skip => log_secrets_skip(e),
335        SecretsValidationMode::Strict => {},
336    }
337}
338
339fn log_secrets_warn(e: &anyhow::Error) {
340    tracing::warn!("Secrets file issue: {}", e);
341}
342
343fn log_secrets_skip(e: &anyhow::Error) {
344    tracing::debug!("Skipping secrets file: {}", e);
345}
346
347fn build_loaded_secrets_message(secrets: &Secrets) -> String {
348    let base = ["jwt_secret", "database_url"];
349    let optional_providers = [
350        secrets.gemini.as_ref().map(|_| "gemini"),
351        secrets.anthropic.as_ref().map(|_| "anthropic"),
352        secrets.openai.as_ref().map(|_| "openai"),
353        secrets.github.as_ref().map(|_| "github"),
354    ];
355
356    let loaded: Vec<&str> = base
357        .into_iter()
358        .chain(optional_providers.into_iter().flatten())
359        .collect();
360
361    if secrets.custom.is_empty() {
362        format!("Loaded secrets: {}", loaded.join(", "))
363    } else {
364        format!(
365            "Loaded secrets: {}, {} custom",
366            loaded.join(", "),
367            secrets.custom.len()
368        )
369    }
370}