systemprompt_cloud/credentials_bootstrap/
mod.rs1mod error;
7
8use std::path::Path;
9use std::sync::OnceLock;
10
11use chrono::{Duration, Utc};
12use systemprompt_identifiers::{CloudAuthToken, Email};
13use systemprompt_models::read_env_optional;
14
15pub use error::CredentialsBootstrapError;
16
17use crate::error::{CloudError, CloudResult};
18use crate::{CloudApiClient, CloudCredentials};
19
20static CREDENTIALS: OnceLock<Option<CloudCredentials>> = OnceLock::new();
21
22#[derive(Debug, Clone, Copy)]
23pub struct CredentialsBootstrap;
24
25impl CredentialsBootstrap {
26 pub async fn init() -> CloudResult<Option<&'static CloudCredentials>> {
27 if CREDENTIALS.get().is_some() {
28 return Err(CredentialsBootstrapError::AlreadyInitialized.into());
29 }
30
31 if Self::is_fly_container() {
32 tracing::debug!("Fly.io container detected, loading credentials from environment");
33 let creds = Self::load_from_env();
34 if let Some(ref c) = creds
35 && let Err(e) = Self::validate_with_api(c).await
36 {
37 if Self::allow_unvalidated() {
38 tracing::warn!(
39 target: "security_audit",
40 error = %e,
41 "cloud credentials unvalidated; proceeding under SYSTEMPROMPT_ALLOW_UNVALIDATED_CREDS=1"
42 );
43 } else {
44 return Err(CredentialsBootstrapError::ApiValidationFailed {
45 message: format!(
46 "tenant pod credentials rejected by api.systemprompt.io (token in \
47 SYSTEMPROMPT_API_TOKEN). Re-run 'systemprompt cloud deploy' or \
48 set SYSTEMPROMPT_ALLOW_UNVALIDATED_CREDS=1 to bypass. \
49 Underlying: {e}"
50 ),
51 }
52 .into());
53 }
54 }
55 CREDENTIALS
56 .set(creds)
57 .map_err(|_e| CredentialsBootstrapError::AlreadyInitialized)?;
58 return Ok(CREDENTIALS
59 .get()
60 .ok_or(CredentialsBootstrapError::NotInitialized)?
61 .as_ref());
62 }
63
64 let cloud_paths = crate::paths::get_cloud_paths();
65 let credentials_path = cloud_paths.resolve(crate::paths::CloudPath::Credentials);
66
67 let mut creds = Self::load_credentials_from_path(&credentials_path)?;
68 if Self::validation_is_fresh(&creds) {
69 tracing::debug!("Cloud credentials within validation TTL; skipping API round-trip");
70 } else {
71 Self::validate_with_api(&creds).await?;
72 creds.last_validated_at = Some(Utc::now());
73 if let Err(e) = creds.save_to_path(&credentials_path) {
74 tracing::debug!(error = %e, "failed to persist credential validation timestamp");
75 }
76 }
77
78 CREDENTIALS
79 .set(Some(creds))
80 .map_err(|_e| CredentialsBootstrapError::AlreadyInitialized)?;
81 Ok(CREDENTIALS
82 .get()
83 .ok_or(CredentialsBootstrapError::NotInitialized)?
84 .as_ref())
85 }
86
87 async fn validate_with_api(creds: &CloudCredentials) -> CloudResult<()> {
88 let client = CloudApiClient::new(&creds.api_url, creds.api_token.as_str())?;
89 client.get_user().await?;
90 tracing::debug!("Cloud credentials validated with API");
91 Ok(())
92 }
93
94 fn validation_is_fresh(creds: &CloudCredentials) -> bool {
95 let Some(last) = creds.last_validated_at else {
96 return false;
97 };
98 if creds.expires_within(Duration::hours(1)) {
99 return false;
100 }
101 let age = Utc::now().signed_duration_since(last);
102 age >= Duration::zero()
103 && age < Duration::seconds(crate::constants::credentials::VALIDATION_TTL_SECS)
104 }
105
106 fn is_fly_container() -> bool {
107 std::env::var("FLY_APP_NAME").is_ok()
108 }
109
110 fn allow_unvalidated() -> bool {
111 std::env::var("SYSTEMPROMPT_ALLOW_UNVALIDATED_CREDS").as_deref() == Ok("1")
112 }
113
114 fn load_from_env() -> Option<CloudCredentials> {
115 let api_token = CloudAuthToken::new(read_env_optional("SYSTEMPROMPT_API_TOKEN")?);
116 let user_email = Email::new(read_env_optional("SYSTEMPROMPT_USER_EMAIL")?);
117
118 tracing::debug!("Loading cloud credentials from environment variables");
119
120 Some(CloudCredentials {
121 api_token,
122 api_url: read_env_optional("SYSTEMPROMPT_API_URL")
123 .unwrap_or_else(|| crate::constants::api::PRODUCTION_URL.into()),
124 authenticated_at: Utc::now(),
125 user_email,
126 last_validated_at: None,
127 })
128 }
129
130 pub fn get() -> Result<Option<&'static CloudCredentials>, CredentialsBootstrapError> {
131 CREDENTIALS
132 .get()
133 .map(|opt| opt.as_ref())
134 .ok_or(CredentialsBootstrapError::NotInitialized)
135 }
136
137 pub fn require() -> Result<&'static CloudCredentials, CredentialsBootstrapError> {
138 Self::get()?.ok_or(CredentialsBootstrapError::NotAvailable)
139 }
140
141 #[must_use]
142 pub fn is_initialized() -> bool {
143 CREDENTIALS.get().is_some()
144 }
145
146 pub fn init_empty() {
147 if CREDENTIALS.set(None).is_err() {
148 tracing::debug!("Credentials cell already initialised; init_empty is a no-op");
149 }
150 }
151
152 pub async fn try_init() -> CloudResult<Option<&'static CloudCredentials>> {
153 if CREDENTIALS.get().is_some() {
154 return Self::get().map_err(Into::into);
155 }
156 Self::init().await
157 }
158
159 #[must_use]
160 pub fn expires_within(duration: Duration) -> bool {
161 match Self::get() {
162 Ok(Some(c)) => c.expires_within(duration),
163 Ok(None) => false,
164 Err(e) => {
165 tracing::debug!(error = %e, "Credentials not available for expiry check");
166 false
167 },
168 }
169 }
170
171 pub async fn reload() -> Result<CloudCredentials, CredentialsBootstrapError> {
172 let cloud_paths = crate::paths::get_cloud_paths();
173 let credentials_path = cloud_paths.resolve(crate::paths::CloudPath::Credentials);
174
175 let creds = Self::load_credentials_from_path(&credentials_path).map_err(|e| {
176 CredentialsBootstrapError::InvalidCredentials {
177 message: e.to_string(),
178 }
179 })?;
180
181 Self::validate_with_api(&creds).await.map_err(|e| {
182 CredentialsBootstrapError::ApiValidationFailed {
183 message: e.to_string(),
184 }
185 })?;
186
187 Ok(creds)
188 }
189
190 fn load_credentials_from_path(path: &Path) -> CloudResult<CloudCredentials> {
191 let creds = CloudCredentials::load_from_path(path).map_err(|e| {
192 if path.exists() {
193 CloudError::from(CredentialsBootstrapError::InvalidCredentials {
194 message: e.to_string(),
195 })
196 } else {
197 CloudError::from(CredentialsBootstrapError::FileNotFound {
198 path: path.display().to_string(),
199 })
200 }
201 })?;
202
203 if creds.is_token_expired() {
204 return Err(CredentialsBootstrapError::TokenExpired.into());
205 }
206
207 if creds.expires_within(Duration::hours(1)) {
208 tracing::warn!(
209 "Cloud token will expire soon. Consider running 'systemprompt cloud login' to \
210 refresh."
211 );
212 }
213
214 tracing::debug!(path = %path.display(), user = ?creds.user_email, "Loaded cloud credentials");
215
216 Ok(creds)
217 }
218}