返回 CodeWhale
lib.rs
根目录 / crates / cloud-facts / src / lib.rs
1 //! Cloud facts client: fetch `https://codewhale.net/api/facts/v1/<channel>`,
2 //! verify the Ed25519 envelope against the keys pinned in
3 //! `codewhale_config::cloud_facts::keys`, cache it under
4 //! `$CODEWHALE_HOME/facts/cloud-facts.json`, and install the scoped view as the
5 //! process-wide overlay. Modeled on the TUI's `models_dev_live` producer.
6 //!
7 //! Guarantees:
8 //! - Never a startup dependency: [`maybe_load_persisted_cache`] is a bounded
9 //! synchronous disk read; all network happens in [`spawn_background_refresh`].
10 //! - Off by default (`[cloud_facts].enabled = false`); `CODEWHALE_CLOUD_FACTS=1`
11 //! flips it, `CODEWHALE_DISABLE_CLOUD_FACTS=1` beats everything, CI markers
12 //! suppress the fetch.
13 //! - The disk cache is re-verified on every load; untrusted bytes are cleared while the rollback floor is retained.
14 //! - The fetch sends only a fixed user agent and `If-None-Match`; no
15 //! identifiers, cookies, or query parameters (PRD §5).
16 //! - With no active pinned key the layer is inert even when enabled.
17
18 use std::io::Read as _;
19 use std::path::{Path, PathBuf};
20 use std::sync::Arc;
21 use std::time::Duration;
22
23 use codewhale_config::catalog::now_unix;
24 use codewhale_config::cloud_facts::{
25 CloudFactsState, CloudFactsStatus, FactsOrigin, FactsRejection, TrustedKey, VerifiedFacts,
26 overlay, scoped_view, verify_envelope,
27 };
28 use codewhale_config::persistence::atomic_write;
29 use serde::{Deserialize, Serialize};
30
31 pub mod registry;
32 pub use registry::RegistrySettings;
33
34 /// `{channel}` is replaced with the channel slug.
35 pub const DEFAULT_URL_TEMPLATE: &str = "https://codewhale.net/api/facts/v1/{channel}";
36 /// Refresh interval for a verified payload (6 h).
37 pub const DEFAULT_TTL_SECS: u64 = 6 * 60 * 60;
38 /// Bounded HTTP budget.
39 pub const FETCH_TIMEOUT: Duration = Duration::from_secs(10);
40 pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
41 /// Largest response body accepted.
42 pub const MAX_BODY_BYTES: usize = codewhale_config::cloud_facts::MAX_ENVELOPE_BYTES;
43 /// Fixed, identifier-free user agent.
44 pub const USER_AGENT: &str = concat!("CodeWhale/", env!("CARGO_PKG_VERSION"), " (+cloud-facts)");
45 /// State subdir + file under `$CODEWHALE_HOME`.
46 pub const STATE_SUBDIR: &str = "facts";
47 pub const CACHE_FILE: &str = "cloud-facts.json";
48 const CACHE_SCHEMA_VERSION: u32 = 2;
49 const MAX_SOURCE_BYTES: usize = 4096;
50 const MAX_CACHE_BYTES: usize = MAX_BODY_BYTES * 6 + 32 * 1024;
51 const BACKOFF_BASE_SECS: u64 = 10 * 60;
52
53 /// Env: `1`/`0` overrides `[cloud_facts].enabled`.
54 pub const ENV_ENABLED: &str = "CODEWHALE_CLOUD_FACTS";
55 /// Env: hard kill switch (truthy) — beats config and `ENV_ENABLED`.
56 pub const ENV_DISABLE: &str = "CODEWHALE_DISABLE_CLOUD_FACTS";
57 /// Env: full URL override (may contain `{channel}`).
58 pub const ENV_URL: &str = "CODEWHALE_CLOUD_FACTS_URL";
59 /// Env: channel slug override.
60 pub const ENV_CHANNEL: &str = "CODEWHALE_CLOUD_FACTS_CHANNEL";
61 /// Env: read the envelope from a local file instead of the network.
62 pub const ENV_PATH: &str = "CODEWHALE_CLOUD_FACTS_PATH";
63 const CI_MARKERS: &[&str] = &[
64 "CI",
65 "GITHUB_ACTIONS",
66 "GITLAB_CI",
67 "BUILDKITE",
68 "CIRCLECI",
69 "JENKINS_URL",
70 "TEAMCITY_VERSION",
71 "TF_BUILD",
72 ];
73
74 /// Resolved runtime settings (config + env).
75 #[derive(Debug, Clone, PartialEq, Eq)]
76 pub struct Settings {
77 pub enabled: bool,
78 pub channel: String,
79 pub url: Option<String>,
80 pub ttl_secs: u64,
81 /// Explicit cache file (tests); otherwise `$CODEWHALE_HOME/facts/cloud-facts.json`.
82 pub cache_path: Option<PathBuf>,
83 /// Local envelope path (`ENV_PATH`); skips the network.
84 pub local_path: Option<PathBuf>,
85 }
86
87 impl Default for Settings {
88 fn default() -> Self {
89 Self {
90 enabled: false,
91 channel: "stable".to_string(),
92 url: None,
93 ttl_secs: DEFAULT_TTL_SECS,
94 cache_path: None,
95 local_path: None,
96 }
97 }
98 }
99
100 fn env_truthy(name: &str) -> Option<bool> {
101 let value = std::env::var(name).ok()?;
102 match value.trim().to_ascii_lowercase().as_str() {
103 "1" | "true" | "yes" | "on" => Some(true),
104 "0" | "false" | "no" | "off" => Some(false),
105 _ => None,
106 }
107 }
108
109 impl Settings {
110 /// Apply env overrides on top of config-derived settings.
111 #[must_use]
112 pub fn resolve(mut self) -> Self {
113 if let Some(enabled) = env_truthy(ENV_ENABLED) {
114 self.enabled = enabled;
115 }
116 if let Ok(channel) = std::env::var(ENV_CHANNEL) {
117 let channel = channel.trim();
118 if valid_channel(channel) {
119 self.channel = channel.to_string();
120 }
121 }
122 if let Ok(url) = std::env::var(ENV_URL) {
123 let url = url.trim();
124 if !url.is_empty() {
125 self.url = Some(url.to_string());
126 }
127 }
128 if let Ok(path) = std::env::var(ENV_PATH) {
129 let path = path.trim();
130 if !path.is_empty() {
131 self.local_path = Some(PathBuf::from(path));
132 }
133 }
134 if hard_disabled() {
135 self.enabled = false;
136 }
137 self.ttl_secs = self.ttl_secs.max(60);
138 self
139 }
140
141 /// The effective envelope URL.
142 #[must_use]
143 pub fn url(&self) -> String {
144 self.url
145 .as_deref()
146 .unwrap_or(DEFAULT_URL_TEMPLATE)
147 .replace("{channel}", &self.channel)
148 }
149
150 fn cache_file(&self) -> Option<PathBuf> {
151 self.cache_path.clone().or_else(|| {
152 let path = cache_path()?;
153 if self.channel == "stable" {
154 Some(path)
155 } else {
156 Some(path.with_file_name(format!("cloud-facts-{}.json", self.channel)))
157 }
158 })
159 }
160 }
161
162 /// Channel slugs are `[a-z0-9][a-z0-9-]{0,31}`.
163 #[must_use]
164 pub fn valid_channel(slug: &str) -> bool {
165 let bytes = slug.as_bytes();
166 (1..=32).contains(&bytes.len())
167 && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
168 && bytes
169 .iter()
170 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
171 }
172
173 /// Production network policy. Local fixtures inject their transport explicitly.
174 #[must_use]
175 pub fn fetch_suppressed() -> bool {
176 CI_MARKERS.iter().any(|name| {
177 env_truthy(name).unwrap_or_else(|| std::env::var(name).is_ok_and(|v| !v.trim().is_empty()))
178 })
179 }
180
181 /// Default cache path under the CodeWhale state root.
182 #[must_use]
183 pub fn cache_path() -> Option<PathBuf> {
184 codewhale_config::resolve_state_dir(STATE_SUBDIR)
185 .ok()
186 .map(|dir| dir.join(CACHE_FILE))
187 }
188
189 fn hard_disabled() -> bool {
190 overlay::hard_disabled()
191 }
192
193 fn source(settings: &Settings) -> Result<String, RefreshError> {
194 if !valid_channel(&settings.channel) {
195 return Err(RefreshError::InvalidSettings("invalid channel".into()));
196 }
197 if let Some(path) = &settings.local_path {
198 let path = if path.is_absolute() {
199 path.clone()
200 } else {
201 std::env::current_dir()
202 .map_err(|e| RefreshError::Io(e.to_string()))?
203 .join(path)
204 };
205 let value = format!("file:{}", path.display());
206 if value.len() > MAX_SOURCE_BYTES {
207 return Err(RefreshError::TooLarge(value.len()));
208 }
209 return Ok(value);
210 }
211 checked_url(&settings.url())
212 }
213
214 fn checked_url(raw: &str) -> Result<String, RefreshError> {
215 if raw.len() > MAX_SOURCE_BYTES {
216 return Err(RefreshError::TooLarge(raw.len()));
217 }
218 let url = reqwest::Url::parse(raw)
219 .map_err(|_| RefreshError::InvalidSettings("invalid URL".into()))?;
220 if !matches!(url.scheme(), "http" | "https")
221 || url.host_str().is_none()
222 || !url.username().is_empty()
223 || url.password().is_some()
224 || url.fragment().is_some()
225 || url.query().is_some()
226 {
227 return Err(RefreshError::InvalidSettings(
228 "URL must be HTTP(S), without credentials, query or fragment".into(),
229 ));
230 }
231 Ok(url.to_string())
232 }
233
234 fn source_identity(settings: &Settings, keys: &[TrustedKey]) -> Result<String, RefreshError> {
235 // Trust inputs are public pins, not credentials. Including them invalidates
236 // a previously issued ticket when a test or a future reload changes trust.
237 Ok(format!(
238 "{}\n{}\n{}\n{}\n{:?}",
239 settings.channel,
240 source(settings)?,
241 settings.ttl_secs,
242 codewhale_config::cloud_facts::current_version(),
243 keys
244 ))
245 }
246
247 /// Publish admitted settings synchronously, before spawning work. Refreshing
248 /// an old Settings value can never re-enable or change this authority.
249 pub fn configure(settings: &Settings) {
250 configure_with_keys(settings, codewhale_config::cloud_facts::TRUSTED_KEYS);
251 }
252
253 fn configure_with_keys(settings: &Settings, keys: &[TrustedKey]) {
254 if !settings.enabled || hard_disabled() {
255 overlay::configure(false, "");
256 return;
257 }
258 let identity = match source_identity(settings, keys) {
259 Ok(identity) => identity,
260 Err(_) => {
261 overlay::configure(false, "");
262 return;
263 }
264 };
265 if let Some(ticket) = overlay::configure(true, &identity)
266 && !keys
267 .iter()
268 .any(|key| key.status == codewhale_config::cloud_facts::KeyStatus::Active)
269 {
270 overlay::publish(
271 &ticket,
272 None,
273 state_status(CloudFactsState::Inert, None, ""),
274 );
275 }
276 }
277
278 fn ticket(
279 settings: &Settings,
280 keys: &[TrustedKey],
281 ) -> Result<overlay::OverlayTicket, RefreshError> {
282 if !settings.enabled || hard_disabled() {
283 return Err(RefreshError::Disabled);
284 }
285 if !keys
286 .iter()
287 .any(|key| key.status == codewhale_config::cloud_facts::KeyStatus::Active)
288 {
289 return Err(RefreshError::Inert);
290 }
291 overlay::current_ticket(&source_identity(settings, keys)?).ok_or(RefreshError::Superseded)
292 }
293
294 #[derive(Debug, Clone, Serialize, Deserialize, Default)]
295 struct PersistedCache {
296 schema_version: u32,
297 channel: String,
298 url: String,
299 #[serde(default)]
300 source_identity: String,
301 fetched_at: u64,
302 #[serde(default)]
303 etag: Option<String>,
304 #[serde(default)]
305 highest_seen_version: Option<u64>,
306 #[serde(default)]
307 backoff_until: Option<u64>,
308 #[serde(default)]
309 failures: u32,
310 #[serde(default)]
311 envelope: String,
312 }
313
314 fn read_bounded_regular(path: &Path, limit: usize) -> Result<Vec<u8>, RefreshError> {
315 let mut options = std::fs::OpenOptions::new();
316 options.read(true);
317 #[cfg(unix)]
318 {
319 use std::os::unix::fs::OpenOptionsExt as _;
320 options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK);
321 }
322 #[cfg(windows)]
323 {
324 use std::os::windows::fs::OpenOptionsExt as _;
325 options.custom_flags(0x0020_0000);
326 }
327 let file = options
328 .open(path)
329 .map_err(|e| RefreshError::Io(e.to_string()))?;
330 let metadata = file
331 .metadata()
332 .map_err(|e| RefreshError::Io(e.to_string()))?;
333 let mut regular = metadata.is_file();
334 #[cfg(unix)]
335 {
336 use std::os::unix::fs::MetadataExt as _;
337 regular &= metadata.nlink() == 1;
338 }
339 #[cfg(windows)]
340 {
341 use std::os::windows::fs::MetadataExt as _;
342 use std::os::windows::io::AsRawHandle as _;
343 use windows_sys::Win32::Storage::FileSystem::{
344 BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
345 };
346 let mut information: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
347 // SAFETY: this is the live handle already opened without following
348 // reparse points; `information` is writable for the synchronous call.
349 let inspected =
350 unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut information) };
351 regular &= metadata.file_attributes() & 0x0000_0400 == 0
352 && inspected != 0
353 && information.nNumberOfLinks == 1;
354 }
355 if !regular {
356 return Err(RefreshError::Io(
357 "facts file must be a regular file with one link".into(),
358 ));
359 }
360 if metadata.len() > limit as u64 {
361 return Err(RefreshError::TooLarge(limit.saturating_add(1)));
362 }
363 let mut bytes = Vec::new();
364 file.take(limit.saturating_add(1) as u64)
365 .read_to_end(&mut bytes)
366 .map_err(|e| RefreshError::Io(e.to_string()))?;
367 if bytes.len() > limit {
368 return Err(RefreshError::TooLarge(bytes.len()));
369 }
370 Ok(bytes)
371 }
372
373 async fn off_runtime<T: Send + 'static>(
374 work: impl FnOnce() -> Result<T, RefreshError> + Send + 'static,
375 ) -> Result<T, RefreshError> {
376 tokio::task::spawn_blocking(work)
377 .await
378 .map_err(|e| RefreshError::Io(e.to_string()))?
379 }
380
381 async fn publish_off_runtime(
382 publish: impl FnOnce() -> bool + Send + 'static,
383 ) -> Result<(), RefreshError> {
384 if off_runtime(move || Ok(publish())).await? {
385 Ok(())
386 } else {
387 Err(RefreshError::Superseded)
388 }
389 }
390
391 async fn fetch_envelope<F, Fut>(
392 local_path: Option<PathBuf>,
393 limit: usize,
394 suppress_network: bool,
395 url: impl FnOnce() -> Result<String, RefreshError>,
396 etag: Option<String>,
397 transport: F,
398 ) -> Result<Fetched, RefreshError>
399 where
400 F: FnOnce(String, Option<String>) -> Fut,
401 Fut: std::future::Future<Output = Result<Fetched, RefreshError>>,
402 {
403 if let Some(local) = local_path {
404 return off_runtime(move || read_bounded_regular(&local, limit))
405 .await
406 .map(|bytes| Fetched::Body { bytes, etag: None });
407 }
408 if suppress_network {
409 return Err(RefreshError::Suppressed);
410 }
411 transport(url()?, etag).await
412 }
413
414 fn load_cache(path: &Path) -> Option<PersistedCache> {
415 let bytes = read_bounded_regular(path, MAX_CACHE_BYTES).ok()?;
416 let cache: PersistedCache = serde_json::from_slice(&bytes).ok()?;
417 (cache.schema_version == CACHE_SCHEMA_VERSION
418 && valid_channel(&cache.channel)
419 && cache.envelope.len() <= MAX_BODY_BYTES
420 && cache.url.len() <= MAX_SOURCE_BYTES
421 && cache.source_identity.len() <= 16 * MAX_SOURCE_BYTES
422 && cache
423 .etag
424 .as_ref()
425 .is_none_or(|etag| etag.len() <= MAX_SOURCE_BYTES))
426 .then_some(cache)
427 }
428
429 fn save_cache(path: &Path, cache: &PersistedCache) {
430 if cache.envelope.len() > MAX_BODY_BYTES
431 || cache.url.len() > MAX_SOURCE_BYTES
432 || cache.source_identity.len() > 16 * MAX_SOURCE_BYTES
433 || cache
434 .etag
435 .as_ref()
436 .is_some_and(|etag| etag.len() > MAX_SOURCE_BYTES)
437 {
438 return;
439 }
440 if let Ok(bytes) = serde_json::to_vec(cache)
441 && bytes.len() <= MAX_CACHE_BYTES
442 && let Err(err) = atomic_write(path, &bytes)
443 {
444 tracing::debug!(target: "cloud_facts", error = %err, "cache write failed");
445 }
446 }
447
448 #[derive(Debug, Clone, PartialEq, Eq)]
449 pub enum RefreshError {
450 Disabled,
451 Inert,
452 Suppressed,
453 Superseded,
454 InvalidSettings(String),
455 BackingOff { until: u64 },
456 Network(String),
457 HttpStatus(u16),
458 TooLarge(usize),
459 Rejected(FactsRejection),
460 Io(String),
461 }
462 impl std::fmt::Display for RefreshError {
463 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464 match self {
465 Self::Disabled => write!(f, "cloud facts disabled"),
466 Self::Inert => write!(f, "no active trusted key"),
467 Self::Suppressed => write!(f, "production network fetch suppressed by CI"),
468 Self::Superseded => write!(f, "facts settings changed before publication"),
469 Self::InvalidSettings(e) => write!(f, "invalid settings: {e}"),
470 Self::BackingOff { until } => write!(f, "backing off until {until}"),
471 Self::Network(e) => write!(f, "network: {e}"),
472 Self::HttpStatus(code) => write!(f, "HTTP {code}"),
473 Self::TooLarge(n) => write!(f, "response too large ({n} bytes)"),
474 Self::Rejected(e) => write!(f, "{e}"),
475 Self::Io(e) => write!(f, "io: {e}"),
476 }
477 }
478 }
479
480 #[derive(Debug, Clone, PartialEq, Eq)]
481 pub enum RefreshOutcome {
482 NotModified { facts_version: Option<u64> },
483 Updated { facts_version: u64 },
484 Fresh { facts_version: Option<u64> },
485 NoFacts,
486 }
487
488 fn state_status(
489 state: CloudFactsState,
490 etag: Option<String>,
491 source_label: &str,
492 ) -> CloudFactsStatus {
493 CloudFactsStatus {
494 state,
495 last_attempt: Some(now_unix()),
496 etag,
497 source_label: source_label.into(),
498 }
499 }
500
501 fn verify_with(
502 bytes: &[u8],
503 settings: &Settings,
504 highest: Option<u64>,
505 keys: &[TrustedKey],
506 now: u64,
507 ) -> Result<VerifiedFacts, FactsRejection> {
508 verify_envelope(
509 bytes,
510 &settings.channel,
511 &codewhale_config::cloud_facts::current_version(),
512 highest.max(overlay::highest_seen(&settings.channel)),
513 keys,
514 now,
515 )
516 }
517
518 fn publish_verified(
519 ticket: &overlay::OverlayTicket,
520 verified: &VerifiedFacts,
521 origin: FactsOrigin,
522 cache: &PersistedCache,
523 path: Option<&Path>,
524 now: u64,
525 ) -> Result<u64, RefreshError> {
526 let scoped = scoped_view(
527 verified,
528 &codewhale_config::cloud_facts::current_version(),
529 now,
530 );
531 let (patches, defaults, announcements) = scoped.item_counts();
532 let version = scoped.facts_version;
533 let status = state_status(
534 CloudFactsState::Verified {
535 channel: scoped.channel.clone(),
536 facts_version: version,
537 key_id: scoped.key_id.clone(),
538 fetched_at: cache.fetched_at,
539 origin,
540 stale: scoped.stale,
541 patches,
542 defaults,
543 announcements,
544 },
545 cache.etag.clone(),
546 &cache.url,
547 );
548 if overlay::publish_with(ticket, Some(scoped), status, || {
549 if let Some(path) = path {
550 save_cache(path, cache);
551 }
552 }) {
553 Ok(version)
554 } else {
555 Err(RefreshError::Superseded)
556 }
557 }
558
559 fn cache_for(settings: &Settings, keys: &[TrustedKey]) -> Result<PersistedCache, RefreshError> {
560 let identity = source_identity(settings, keys)?;
561 let mut cache = settings
562 .cache_file()
563 .as_deref()
564 .and_then(load_cache)
565 .filter(|cache| cache.channel == settings.channel)
566 .unwrap_or_default();
567 // The persisted high-water hint is unsigned. Recover any stronger floor
568 // from the authenticated body before a source switch discards its bytes,
569 // including refreshes that did not first seed the process overlay.
570 if !cache.envelope.is_empty()
571 && let Ok(verified) =
572 verify_with(cache.envelope.as_bytes(), settings, None, keys, now_unix())
573 {
574 cache.highest_seen_version = cache
575 .highest_seen_version
576 .max(Some(verified.facts.facts_version));
577 }
578 if cache.source_identity != identity {
579 // Retain the channel rollback floor while discarding another source's
580 // validators, body and retry state. Channels use separate default files.
581 let floor = cache.highest_seen_version;
582 cache = PersistedCache {
583 highest_seen_version: floor,
584 ..PersistedCache::default()
585 };
586 }
587 cache.highest_seen_version = cache
588 .highest_seen_version
589 .max(overlay::highest_seen(&settings.channel));
590 // Local cache metadata is only a hint. A forged/future timestamp must
591 // not grant an indefinitely fresh view or suppress all future refreshes.
592 let now = now_unix();
593 if cache.fetched_at > now {
594 cache.fetched_at = 0;
595 cache.backoff_until = None;
596 }
597 let max_backoff = (BACKOFF_BASE_SECS << 9).min(settings.ttl_secs);
598 if cache
599 .backoff_until
600 .is_some_and(|until| until > now.saturating_add(max_backoff))
601 {
602 cache.backoff_until = None;
603 }
604 cache.schema_version = CACHE_SCHEMA_VERSION;
605 cache.channel = settings.channel.clone();
606 cache.source_identity = identity;
607 cache.url = source(settings)?;
608 Ok(cache)
609 }
610
611 pub fn maybe_load_persisted_cache(settings: &Settings) -> Option<u64> {
612 maybe_load_persisted_cache_with_keys(settings, codewhale_config::cloud_facts::TRUSTED_KEYS)
613 }
614 fn maybe_load_persisted_cache_with_keys(settings: &Settings, keys: &[TrustedKey]) -> Option<u64> {
615 let ticket = ticket(settings, keys).ok()?;
616 registry::load_cached_registry(&RegistrySettings::from_facts(settings), &ticket, keys);
617 let cache = cache_for(settings, keys).ok()?;
618 if cache.envelope.is_empty() {
619 return None;
620 }
621 let now = now_unix();
622 match verify_with(
623 cache.envelope.as_bytes(),
624 settings,
625 cache.highest_seen_version,
626 keys,
627 now,
628 ) {
629 Ok(mut verified) => {
630 verified.stale |= now.saturating_sub(cache.fetched_at) >= settings.ttl_secs;
631 publish_verified(
632 &ticket,
633 &verified,
634 FactsOrigin::DiskCache,
635 &cache,
636 None,
637 now,
638 )
639 .ok()
640 }
641 Err(reason) => {
642 // Retain the channel's rollback floor, replacing the rejected body
643 // through the same generation-guarded cache publication boundary.
644 let mut rejected = cache.clone();
645 rejected.envelope.clear();
646 rejected.etag = None;
647 overlay::publish_with(
648 &ticket,
649 None,
650 state_status(
651 CloudFactsState::Rejected {
652 reason: reason.to_string(),
653 at: now,
654 },
655 None,
656 &cache.url,
657 ),
658 || {
659 if let Some(path) = settings.cache_file() {
660 save_cache(&path, &rejected);
661 }
662 },
663 );
664 None
665 }
666 }
667 }
668
669 enum Fetched {
670 NotModified,
671 NotFound,
672 Body {
673 bytes: Vec<u8>,
674 etag: Option<String>,
675 },
676 }
677
678 async fn fetch(url: String, etag: Option<String>) -> Result<Fetched, RefreshError> {
679 fetch_limited(url, etag, MAX_BODY_BYTES).await
680 }
681
682 async fn fetch_limited(
683 url: String,
684 etag: Option<String>,
685 limit: usize,
686 ) -> Result<Fetched, RefreshError> {
687 let client = codewhale_release::tls::reqwest_client_builder()
688 .timeout(FETCH_TIMEOUT)
689 .connect_timeout(CONNECT_TIMEOUT)
690 .user_agent(USER_AGENT)
691 .redirect(reqwest::redirect::Policy::none())
692 .build()
693 .map_err(|e| RefreshError::Network(e.to_string()))?;
694 let mut request = client.get(url).header("Accept", "application/json");
695 if let Some(etag) = etag {
696 request = request.header("If-None-Match", etag);
697 }
698 let mut response = request
699 .send()
700 .await
701 .map_err(|e| RefreshError::Network(e.to_string()))?;
702 let status = response.status().as_u16();
703 if status == 304 {
704 return Ok(Fetched::NotModified);
705 }
706 if status == 404 {
707 return Ok(Fetched::NotFound);
708 }
709 if !(200..300).contains(&status) {
710 return Err(RefreshError::HttpStatus(status));
711 }
712 if response
713 .content_length()
714 .is_some_and(|len| len > limit as u64)
715 {
716 return Err(RefreshError::TooLarge(limit + 1));
717 }
718 let etag = response
719 .headers()
720 .get("etag")
721 .and_then(|v| v.to_str().ok())
722 .filter(|value| value.len() <= MAX_SOURCE_BYTES)
723 .map(str::to_string);
724 let mut bytes = Vec::new();
725 while let Some(chunk) = response
726 .chunk()
727 .await
728 .map_err(|e| RefreshError::Network(e.to_string()))?
729 {
730 let size = bytes.len().saturating_add(chunk.len());
731 if size > limit {
732 return Err(RefreshError::TooLarge(size));
733 }
734 bytes.extend_from_slice(&chunk);
735 }
736 Ok(Fetched::Body { bytes, etag })
737 }
738
739 /// Uses only admitted settings; callers must configure synchronously first.
740 pub async fn refresh(settings: &Settings, force: bool) -> Result<RefreshOutcome, RefreshError> {
741 if let Ok(admitted) = ticket(settings, codewhale_config::cloud_facts::TRUSTED_KEYS) {
742 registry::spawn_registry_refresh(RegistrySettings::from_facts(settings), admitted, None);
743 }
744 refresh_with_keys(settings, force, codewhale_config::cloud_facts::TRUSTED_KEYS).await
745 }
746 async fn refresh_with_keys(
747 settings: &Settings,
748 force: bool,
749 keys: &[TrustedKey],
750 ) -> Result<RefreshOutcome, RefreshError> {
751 refresh_using(settings, force, keys, None, fetch_suppressed(), fetch).await
752 }
753
754 // Tests inject an explicit transport/policy, leaving the production CI gate
755 // intact. Their dependencies cannot override settings/trust admission.
756 async fn refresh_using<F, Fut>(
757 settings: &Settings,
758 force: bool,
759 keys: &[TrustedKey],
760 admitted: Option<overlay::OverlayTicket>,
761 suppress_network: bool,
762 transport: F,
763 ) -> Result<RefreshOutcome, RefreshError>
764 where
765 F: FnOnce(String, Option<String>) -> Fut,
766 Fut: std::future::Future<Output = Result<Fetched, RefreshError>>,
767 {
768 let ticket = admitted.map(Ok).unwrap_or_else(|| ticket(settings, keys))?;
769 let _ = self::ticket(settings, keys)?;
770 if !overlay::is_current(&ticket) {
771 return Err(RefreshError::Superseded);
772 }
773 let before_generation = overlay::snapshot().generation;
774 let mut cache = {
775 let (settings, keys) = (settings.clone(), keys.to_vec());
776 off_runtime(move || cache_for(&settings, &keys)).await?
777 };
778 let path = settings.cache_file();
779 let now = now_unix();
780 if settings.local_path.is_none() {
781 if suppress_network {
782 return Err(RefreshError::Suppressed);
783 }
784 if !force {
785 if let Some(until) = cache.backoff_until
786 && now < until
787 {
788 return Err(RefreshError::BackingOff { until });
789 }
790 if !cache.envelope.is_empty()
791 && now.saturating_sub(cache.fetched_at) < settings.ttl_secs
792 && let Ok(verified) = verify_with(
793 cache.envelope.as_bytes(),
794 settings,
795 cache.highest_seen_version,
796 keys,
797 now,
798 )
799 {
800 let version = publish_verified(
801 &ticket,
802 &verified,
803 FactsOrigin::DiskCache,
804 &cache,
805 None,
806 now,
807 )?;
808 return Ok(RefreshOutcome::Fresh {
809 facts_version: Some(version),
810 });
811 }
812 }
813 }
814 let fetched = fetch_envelope(
815 settings.local_path.clone(),
816 MAX_BODY_BYTES,
817 suppress_network,
818 || Ok(cache.url.clone()),
819 cache.etag.clone().filter(|_| !cache.envelope.is_empty()),
820 transport,
821 )
822 .await;
823 let mut not_modified = false;
824 let (bytes, etag) = match fetched {
825 Ok(Fetched::NotModified) => {
826 not_modified = true;
827 (cache.envelope.as_bytes().to_vec(), cache.etag.clone())
828 }
829 Ok(Fetched::NotFound) => {
830 if overlay::snapshot().generation != before_generation {
831 return Err(RefreshError::Superseded);
832 }
833 cache.envelope.clear();
834 cache.etag = None;
835 cache.failures = 0;
836 cache.backoff_until = None;
837 cache.fetched_at = now;
838 let status = state_status(CloudFactsState::BundledOnly, None, &cache.url);
839 publish_off_runtime(move || {
840 overlay::publish_with(&ticket, None, status, || {
841 if let Some(path) = &path {
842 save_cache(path, &cache);
843 }
844 })
845 })
846 .await?;
847 return Ok(RefreshOutcome::NoFacts);
848 }
849 Ok(Fetched::Body { bytes, etag }) => (bytes, etag),
850 Err(err) => {
851 if overlay::snapshot().generation != before_generation {
852 return Err(err);
853 }
854 cache.failures = cache.failures.saturating_add(1);
855 cache.backoff_until = Some(
856 now.saturating_add(
857 (BACKOFF_BASE_SECS << cache.failures.min(10).saturating_sub(1))
858 .min(settings.ttl_secs),
859 ),
860 );
861 // Reverify retained facts on failure too; the status must never
862 // hide a revoked or expired overlay behind a prior successful fetch.
863 let kept = verify_with(
864 cache.envelope.as_bytes(),
865 settings,
866 cache.highest_seen_version,
867 keys,
868 now,
869 )
870 .ok()
871 .map(|mut verified| {
872 verified.stale |= now.saturating_sub(cache.fetched_at) >= settings.ttl_secs;
873 scoped_view(
874 &verified,
875 &codewhale_config::cloud_facts::current_version(),
876 now,
877 )
878 });
879 let keeping = kept
880 .as_ref()
881 .filter(|facts| !facts.stale)
882 .map(|facts| facts.facts_version);
883 let status = state_status(
884 CloudFactsState::Failed {
885 last_error: err.to_string(),
886 at: now,
887 keeping,
888 },
889 cache.etag.clone(),
890 &cache.url,
891 );
892 publish_off_runtime(move || {
893 overlay::publish_with(&ticket, kept, status, || {
894 if let Some(path) = &path {
895 save_cache(path, &cache);
896 }
897 })
898 })
899 .await?;
900 return Err(err);
901 }
902 };
903 // 304 is a transport optimization, never a trust decision. This also
904 // rejects a 304 without an authenticated matching cached envelope.
905 match verify_with(
906 &bytes,
907 settings,
908 cache.highest_seen_version,
909 keys,
910 now_unix(),
911 ) {
912 Ok(verified) => {
913 let verified_now = now_unix();
914 cache.fetched_at = verified_now;
915 cache.etag = etag;
916 cache.failures = 0;
917 cache.backoff_until = None;
918 cache.highest_seen_version = Some(
919 cache
920 .highest_seen_version
921 .unwrap_or(0)
922 .max(verified.facts.facts_version),
923 );
924 cache.envelope =
925 String::from_utf8(bytes).map_err(|e| RefreshError::Io(e.to_string()))?;
926 let origin = if settings.local_path.is_some() {
927 FactsOrigin::LocalFile
928 } else {
929 FactsOrigin::Network
930 };
931 let version = off_runtime(move || {
932 publish_verified(
933 &ticket,
934 &verified,
935 origin,
936 &cache,
937 path.as_deref(),
938 verified_now,
939 )
940 })
941 .await?;
942 Ok(if not_modified {
943 RefreshOutcome::NotModified {
944 facts_version: Some(version),
945 }
946 } else {
947 RefreshOutcome::Updated {
948 facts_version: version,
949 }
950 })
951 }
952 Err(reason) => {
953 if matches!(reason, FactsRejection::Rollback { .. })
954 && overlay::snapshot().generation != before_generation
955 {
956 return Err(RefreshError::Superseded);
957 }
958 // Drop the now-untrusted body, retain rollback floor, and do not
959 // let the next response reuse its ETag.
960 cache.envelope.clear();
961 cache.etag = None;
962 cache.highest_seen_version = cache
963 .highest_seen_version
964 .max(overlay::highest_seen(&settings.channel));
965 let status = match &reason {
966 FactsRejection::NotApplicable { applies_to } => CloudFactsState::NotApplicable {
967 applies_to: applies_to.clone(),
968 },
969 _ => CloudFactsState::Rejected {
970 reason: reason.to_string(),
971 at: now_unix(),
972 },
973 };
974 let status = state_status(status, None, &cache.url);
975 publish_off_runtime(move || {
976 overlay::publish_with(&ticket, None, status, || {
977 if let Some(path) = &path {
978 save_cache(path, &cache);
979 }
980 })
981 })
982 .await?;
983 Err(RefreshError::Rejected(reason))
984 }
985 }
986 }
987
988 pub fn spawn_background_refresh(
989 settings: Settings,
990 on_update: Option<Arc<dyn Fn() + Send + Sync>>,
991 ) {
992 let Ok(admitted) = ticket(&settings, codewhale_config::cloud_facts::TRUSTED_KEYS) else {
993 return;
994 };
995 registry::spawn_registry_refresh(
996 RegistrySettings::from_facts(&settings),
997 admitted.clone(),
998 on_update.clone(),
999 );
1000 if settings.local_path.is_none() && fetch_suppressed() {
1001 return;
1002 }
1003 tokio::spawn(async move {
1004 let before = overlay::snapshot().generation;
1005 let outcome = refresh_using(
1006 &settings,
1007 false,
1008 codewhale_config::cloud_facts::TRUSTED_KEYS,
1009 Some(admitted),
1010 fetch_suppressed(),
1011 fetch,
1012 )
1013 .await;
1014 tracing::debug!(target: "cloud_facts", ?outcome, "cloud facts refresh settled");
1015 if overlay::snapshot().generation != before
1016 && let Some(hook) = on_update
1017 {
1018 hook();
1019 }
1020 });
1021 }
1022
1023 #[must_use]
1024 pub fn status() -> CloudFactsStatus {
1025 overlay::status()
1026 }
1027
1028 #[cfg(test)]
1029 mod tests;
1030
1030 lines RUST