use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use lean_ctx_protocol::cloud::metrics_v2::DetectorName;
use serde::{Deserialize, Serialize};
use super::buffer::dir_in;
use crate::CloudError;
use crate::state::write_private;
const SWITCH_FILE: &str = "secret-hits.on";
pub(crate) const HITS_FILE: &str = "secret-hits.jsonl";
const MAX_HITS_BYTES: u64 = 4 * 1024 * 1024;
const DIR_CACHE: Duration = Duration::from_secs(60);
pub(crate) fn detector(label: &str) -> DetectorName {
let l = label.to_ascii_lowercase();
let has = |w: &str| l.contains(w);
let name = if has("aws") && has("secret") {
"aws_secret_key"
} else if has("aws") {
"aws_access_key"
} else if has("gcp") || has("google") {
"gcp_key"
} else if has("azure") {
"azure_key"
} else if has("github") {
"github_token"
} else if has("gitlab") {
"gitlab_token"
} else if has("slack") {
"slack_token"
} else if has("stripe") {
"stripe_key"
} else if has("openai") {
"openai_key"
} else if has("anthropic") {
"anthropic_key"
} else if has("private key") {
"private_key"
} else if has("jwt") {
"jwt"
} else if has("password") {
"password_assignment"
} else if has("database") || has("url credentials") || has("connection") {
"connection_string"
} else if has("api key") || has("token") || has("secret") || has("key") {
"generic_api_key"
} else {
"other"
};
DetectorName::or_other(name)
}
pub(crate) fn enable(cloud_data: &Path) -> Result<(), CloudError> {
write_private(&dir_in(cloud_data), SWITCH_FILE, b"on\n")
}
pub(crate) fn enabled(cloud_data: &Path) -> bool {
dir_in(cloud_data).join(SWITCH_FILE).is_file()
}
pub(crate) fn remove(cloud_data: &Path) {
let dir = dir_in(cloud_data);
let _ = std::fs::remove_file(dir.join(SWITCH_FILE));
let _ = std::fs::remove_file(dir.join(HITS_FILE));
let _ = std::fs::remove_file(dir.join(super::signals::SIGNALS_FILE));
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Hit {
pub(crate) ts: String,
pub(crate) detector: DetectorName,
#[serde(default)]
pub(crate) project: Option<String>,
}
type Cached = (Instant, crate::CloudStore, bool);
static STORE: Mutex<Option<Cached>> = Mutex::new(None);
pub(super) fn sink() -> Option<PathBuf> {
if !crate::available_locally() {
return None;
}
let mut cache = STORE
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let (store, allowed) = match cache.as_ref() {
Some((at, store, allowed)) if at.elapsed() < DIR_CACHE => (store.clone(), *allowed),
_ => {
let store = crate::CloudStore::open().ok()?;
let allowed = store.recording_allowed(&lean_ctx::core::config::Config::load().cloud);
*cache = Some((Instant::now(), store.clone(), allowed));
(store, allowed)
}
};
drop(cache);
let dir = dir_in(store.data_dir());
(allowed && dir.join(SWITCH_FILE).is_file() && store.may_record()).then_some(dir)
}
pub(crate) fn note(labels: &[&str]) {
if labels.is_empty() {
return;
}
let Some(dir) = sink() else {
return;
};
let path = dir.join(HITS_FILE);
if std::fs::metadata(&path).is_ok_and(|m| m.len() > MAX_HITS_BYTES) {
return;
}
let project = lean_ctx::core::savings_ledger::project_scope::current_project_key();
let ts =
lean_ctx_time::UtcDateTime::now().to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true);
let mut lines = String::new();
for label in labels {
let hit = Hit {
ts: ts.clone(),
detector: detector(label),
project: project.clone(),
};
if let Ok(line) = serde_json::to_string(&hit) {
lines.push_str(&line);
lines.push('\n');
}
}
let file = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path);
if let Ok(mut file) = file {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = file.set_permissions(std::fs::Permissions::from_mode(0o600));
}
let _ = file.write_all(lines.as_bytes());
}
}
pub(crate) fn hits(cloud_data: &Path) -> Vec<(lean_ctx_time::UtcDateTime, Hit)> {
let Ok(text) = std::fs::read_to_string(dir_in(cloud_data).join(HITS_FILE)) else {
return Vec::new();
};
text.lines()
.filter_map(|line| serde_json::from_str::<Hit>(line).ok())
.filter_map(|hit| {
let at = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(&hit.ts)
.ok()?
.to_utc();
Some((at, hit))
})
.collect()
}
pub(crate) fn prune(cloud_data: &Path, before: lean_ctx_time::UtcDateTime) {
let path = dir_in(cloud_data).join(HITS_FILE);
let kept: String = hits(cloud_data)
.into_iter()
.filter(|(at, _)| *at >= before)
.filter_map(|(_, hit)| serde_json::to_string(&hit).ok())
.map(|line| line + "\n")
.collect();
if kept.is_empty() {
let _ = std::fs::remove_file(path);
} else {
let _ = write_private(&dir_in(cloud_data), HITS_FILE, kept.as_bytes());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn labels_map_to_closed_detectors_and_nothing_value_derived_is_kept() {
assert_eq!(detector("AWS access key").as_str(), "aws_access_key");
assert_eq!(detector("Generic long secret").as_str(), "generic_api_key");
assert_eq!(
detector("Database credentials").as_str(),
"connection_string"
);
assert_eq!(detector("Private key block").as_str(), "private_key");
assert_eq!(detector("中文").as_str(), "other");
let hit = Hit {
ts: "2026-10-26T16:00:00Z".into(),
detector: detector("GitHub token"),
project: None,
};
let json = serde_json::to_value(&hit).unwrap();
assert_eq!(json.as_object().unwrap().len(), 3, "{json}");
}
}