use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn is_telemetry_disabled() -> bool {
std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
}
pub fn is_offline_mode() -> bool {
std::env::var("IRONMON_OFFLINE").is_ok()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentScope {
BasicTelemetry,
HardwareInfo,
PerformanceMetrics,
DetailedDiagnostics,
Analytics,
}
impl ConsentScope {
pub fn name(&self) -> &'static str {
match self {
Self::BasicTelemetry => "Basic Telemetry",
Self::HardwareInfo => "Hardware Information",
Self::PerformanceMetrics => "Performance Metrics",
Self::DetailedDiagnostics => "Detailed Diagnostics",
Self::Analytics => "Anonymous Analytics",
}
}
pub fn description(&self) -> &'static str {
match self {
Self::BasicTelemetry =>
"Basic usage statistics and crash reports. Helps improve stability and reliability. \
No personally identifiable information is collected.",
Self::HardwareInfo =>
"Anonymized hardware information (GPU models, CPU types, RAM size). \
Helps prioritize hardware support. Serial numbers and MAC addresses are never collected.",
Self::PerformanceMetrics =>
"Aggregated performance metrics (frame rates, GPU utilization averages). \
Helps optimize performance. All data is anonymized and aggregated.",
Self::DetailedDiagnostics =>
"Detailed system information for troubleshooting (driver versions, kernel info). \
Only collected when explicitly requested for bug reports.",
Self::Analytics =>
"Anonymous analytics about feature usage patterns. \
Helps understand which features are most valuable. No tracking or profiling.",
}
}
pub fn is_collected(&self) -> bool {
match self {
Self::BasicTelemetry
| Self::HardwareInfo
| Self::PerformanceMetrics
| Self::DetailedDiagnostics
| Self::Analytics => false,
}
}
pub fn data_points(&self) -> Vec<&'static str> {
match self {
Self::BasicTelemetry => vec![
"Application version",
"Operating system type (Linux/Windows/macOS)",
"Crash stack traces (anonymized)",
"Error frequency (aggregated)",
],
Self::HardwareInfo => vec![
"GPU vendor (NVIDIA/AMD/Intel)",
"GPU generation (e.g., RTX 30-series, not exact model)",
"CPU architecture (x86_64/ARM)",
"Approximate RAM size (e.g., 16GB range)",
],
Self::PerformanceMetrics => vec![
"Average GPU utilization",
"Average memory usage",
"Frame time distributions",
"Application startup time",
],
Self::DetailedDiagnostics => vec![
"Exact GPU model and driver version",
"Kernel version",
"System configuration",
"Running processes (names only, no PIDs or paths)",
],
Self::Analytics => vec![
"Feature usage frequency",
"Tab/view navigation patterns",
"Configuration changes (types, not values)",
"Session duration",
],
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsentRecord {
pub scope: ConsentScope,
pub granted: bool,
pub timestamp: u64,
pub prompt_version: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub ip_hash: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsentConfig {
pub records: HashMap<ConsentScope, ConsentRecord>,
pub first_prompt_timestamp: Option<u64>,
pub last_review_timestamp: Option<u64>,
pub review_reminder_days: Option<u32>,
pub consent_version: u32,
}
impl Default for ConsentConfig {
fn default() -> Self {
Self {
records: HashMap::new(),
first_prompt_timestamp: None,
last_review_timestamp: None,
review_reminder_days: Some(90), consent_version: 1,
}
}
}
pub struct ConsentManager {
config: ConsentConfig,
config_path: PathBuf,
}
impl ConsentManager {
const CURRENT_PROMPT_VERSION: u32 = 1;
pub fn default_path() -> Result<PathBuf> {
let config_dir = if cfg!(windows) {
std::env::var("APPDATA")
.map(PathBuf::from)
.map_err(|_| IronError::Configuration("APPDATA not set".into()))?
} else {
std::env::var("HOME")
.map(|h| PathBuf::from(h).join(".config"))
.map_err(|_| IronError::Configuration("HOME not set".into()))?
};
Ok(config_dir.join("ironmon").join("consent.toml"))
}
pub fn legacy_record() -> Option<std::path::PathBuf> {
let current = Self::default_path().ok()?;
crate::legacy_paths::legacy_consent_exists(¤t)
}
pub fn load() -> Result<Self> {
let path = Self::default_path()?;
Self::load_from(&path)
}
pub fn load_from(path: &PathBuf) -> Result<Self> {
let config = if path.exists() {
let contents = fs::read_to_string(path).map_err(|e| {
IronError::Configuration(format!("Failed to read consent config: {}", e))
})?;
toml::from_str(&contents).map_err(|e| {
IronError::Configuration(format!("Failed to parse consent config: {}", e))
})?
} else {
ConsentConfig::default()
};
Ok(Self {
config,
config_path: path.clone(),
})
}
pub fn save(&self) -> Result<()> {
if let Some(parent) = self.config_path.parent() {
fs::create_dir_all(parent).map_err(|e| {
IronError::Configuration(format!("Failed to create config directory: {}", e))
})?;
}
let contents = toml::to_string_pretty(&self.config).map_err(|e| {
IronError::Configuration(format!("Failed to serialize consent config: {}", e))
})?;
fs::write(&self.config_path, contents).map_err(|e| {
IronError::Configuration(format!("Failed to write consent config: {}", e))
})?;
Ok(())
}
pub fn has_consent(&self, scope: ConsentScope) -> bool {
if std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
{
return false;
}
let sandbox_detector = crate::sandbox::SandboxDetector::new();
if sandbox_detector.is_sandboxed() {
return false;
}
self.config
.records
.get(&scope)
.map(|r| r.granted)
.unwrap_or(false)
}
pub fn should_collect_data(&self, scope: ConsentScope) -> bool {
if !scope.is_collected() {
return false;
}
if std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
{
return false;
}
let sandbox_detector = crate::sandbox::SandboxDetector::new();
if sandbox_detector.is_sandboxed() {
return false;
}
self.has_consent(scope)
}
pub fn needs_consent_prompt(&self) -> bool {
if self.config.first_prompt_timestamp.is_none() {
return true;
}
if let (Some(last_review), Some(reminder_days)) = (
self.config.last_review_timestamp,
self.config.review_reminder_days,
) {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let days_since_review = (now - last_review) / 86400;
if days_since_review >= reminder_days as u64 {
return true;
}
}
false
}
pub fn record_consent(&mut self, scope: ConsentScope, granted: bool) -> Result<()> {
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
if self.config.first_prompt_timestamp.is_none() {
self.config.first_prompt_timestamp = Some(timestamp);
}
self.config.last_review_timestamp = Some(timestamp);
let record = ConsentRecord {
scope,
granted,
timestamp,
prompt_version: Self::CURRENT_PROMPT_VERSION,
ip_hash: None, };
self.config.records.insert(scope, record);
self.save()?;
Ok(())
}
pub fn revoke_consent(&mut self, scope: ConsentScope) -> Result<()> {
self.record_consent(scope, false)?;
Ok(())
}
pub fn revoke_all(&mut self) -> Result<()> {
for scope in [
ConsentScope::BasicTelemetry,
ConsentScope::HardwareInfo,
ConsentScope::PerformanceMetrics,
ConsentScope::DetailedDiagnostics,
ConsentScope::Analytics,
] {
self.revoke_consent(scope)?;
}
Ok(())
}
pub fn get_all_consents(&self) -> &HashMap<ConsentScope, ConsentRecord> {
&self.config.records
}
pub fn export_consent_status(&self) -> String {
let mut output = String::from("=== IronMonitor - Consent Status ===\n\n");
if let Some(first_prompt) = self.config.first_prompt_timestamp {
output.push_str(&format!(
"First prompted: {}\n",
format_timestamp(first_prompt)
));
}
if let Some(last_review) = self.config.last_review_timestamp {
output.push_str(&format!(
"Last reviewed: {}\n",
format_timestamp(last_review)
));
}
output.push_str(&format!(
"\nConsent version: {}\n\n",
self.config.consent_version
));
output.push_str("Current consents:\n");
output.push_str("─────────────────────────────────────────\n");
for scope in [
ConsentScope::BasicTelemetry,
ConsentScope::HardwareInfo,
ConsentScope::PerformanceMetrics,
ConsentScope::DetailedDiagnostics,
ConsentScope::Analytics,
] {
let status = if self.has_consent(scope) {
"[+] GRANTED"
} else {
"[-] DENIED"
};
output.push_str(&format!("{:<30} {}\n", scope.name(), status));
if let Some(record) = self.config.records.get(&scope) {
output.push_str(&format!(
" Recorded: {}\n",
format_timestamp(record.timestamp)
));
}
}
output.push_str("\n=== End of Consent Status ===\n");
output
}
pub fn request_consent(&mut self, scope: ConsentScope) -> Result<bool> {
println!("\n╔════════════════════════════════════════════════════════════════╗");
println!("║ IronMonitor - Data Collection Consent ║");
println!("╚════════════════════════════════════════════════════════════════╝\n");
println!("Scope: {}\n", scope.name());
println!("Description:\n{}\n", scope.description());
println!("Data collected:");
for point in scope.data_points() {
println!(" * {}", point);
}
println!();
println!("You can review and change your consent at any time by:");
println!(" - Running: ironmon --consent-status");
println!(" - Running: ironmon --revoke-consent");
println!();
loop {
println!("Do you consent to this data collection? [y/N]: ");
let mut input = String::new();
let bytes = std::io::stdin()
.read_line(&mut input)
.map_err(|e| IronError::Configuration(format!("Failed to read input: {}", e)))?;
if bytes == 0 {
return Err(IronError::Configuration(format!(
"no answer for {} on standard input; consent was not recorded",
scope.name()
)));
}
let input = input.trim().to_lowercase();
match input.as_str() {
"y" | "yes" => {
self.record_consent(scope, true)?;
println!("[+] Consent granted for {}\n", scope.name());
return Ok(true);
}
"n" | "no" | "" => {
self.record_consent(scope, false)?;
println!("[-] Consent denied for {}\n", scope.name());
return Ok(false);
}
_ => {
println!("Invalid input. Please enter 'y' for yes or 'n' for no.");
}
}
}
}
pub fn request_all_consents(&mut self) -> Result<()> {
println!("\n╔════════════════════════════════════════════════════════════════╗");
println!("║ Welcome to IronMonitor! ║");
println!("╚════════════════════════════════════════════════════════════════╝\n");
println!("This is your first time running IronMonitor.");
println!("We respect your privacy and will only collect data you explicitly consent to.\n");
println!("You'll be asked about several types of optional data collection.");
println!("You can say 'no' to all of them - the tool works perfectly without any data collection.\n");
println!("Press Enter to continue...");
let mut input = String::new();
std::io::stdin().read_line(&mut input).ok();
for scope in [
ConsentScope::BasicTelemetry,
ConsentScope::HardwareInfo,
ConsentScope::PerformanceMetrics,
ConsentScope::Analytics,
] {
self.request_consent(scope)?;
}
println!("╔════════════════════════════════════════════════════════════════╗");
println!("║ Consent Setup Complete ║");
println!("╚════════════════════════════════════════════════════════════════╝\n");
println!("You can review or change these settings at any time:");
println!(" ironmon --consent-status # View current consent status");
println!(" ironmon --revoke-consent # Revoke all consents");
println!(" ironmon --consent-review # Review and change specific consents\n");
Ok(())
}
}
fn format_timestamp(timestamp: u64) -> String {
match chrono::DateTime::from_timestamp(timestamp as i64, 0) {
Some(datetime) => datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
None => "unknown time".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_consent() {
let manager = ConsentManager {
config: ConsentConfig::default(),
config_path: PathBuf::from("/tmp/test_consent.toml"),
};
assert!(manager.config.records.is_empty());
}
#[test]
fn test_consent_recording() {
let mut manager = ConsentManager {
config: ConsentConfig::default(),
config_path: PathBuf::from("/tmp/test_consent.toml"),
};
manager
.record_consent(ConsentScope::BasicTelemetry, true)
.unwrap();
let record = manager.config.records.get(&ConsentScope::BasicTelemetry);
assert!(record.is_some());
assert!(record.unwrap().granted);
manager
.revoke_consent(ConsentScope::BasicTelemetry)
.unwrap();
let record = manager.config.records.get(&ConsentScope::BasicTelemetry);
assert!(record.is_some());
assert!(!record.unwrap().granted);
}
#[test]
fn test_consent_scope_descriptions() {
let scope = ConsentScope::BasicTelemetry;
assert!(!scope.name().is_empty());
assert!(!scope.description().is_empty());
assert!(!scope.data_points().is_empty());
}
const EVERY_SCOPE: [ConsentScope; 5] = [
ConsentScope::BasicTelemetry,
ConsentScope::HardwareInfo,
ConsentScope::PerformanceMetrics,
ConsentScope::DetailedDiagnostics,
ConsentScope::Analytics,
];
#[test]
fn granting_every_scope_still_collects_nothing() {
let mut manager = ConsentManager {
config: ConsentConfig::default(),
config_path: PathBuf::from("unused-in-this-test.toml"),
};
for scope in EVERY_SCOPE {
manager.config.records.insert(
scope,
ConsentRecord {
scope,
granted: true,
timestamp: 1,
prompt_version: 1,
ip_hash: None,
},
);
}
for scope in EVERY_SCOPE {
assert!(
!scope.is_collected(),
concat!(
"{} claims to be collected. If that is now true, update the ",
"module docs and the three `ironmon privacy` screens, which ",
"all state that IronMonitor collects and transmits nothing."
),
scope.name()
);
assert!(
!manager.should_collect_data(scope),
concat!(
"{} was granted and reported that it should collect, but ",
"no collector for it exists"
),
scope.name()
);
}
}
#[test]
fn a_scope_with_no_record_is_not_granted() {
let manager = ConsentManager {
config: ConsentConfig::default(),
config_path: PathBuf::from("unused-in-this-test.toml"),
};
assert!(
manager.config.records.is_empty(),
"the default config records no answers"
);
let answered = manager
.config
.records
.get(&ConsentScope::Analytics)
.map(|r| r.granted)
.unwrap_or(false);
assert!(
!answered,
"an unanswered scope defaults to denied, not granted"
);
}
}