diff --git a/cli/src/app.rs b/cli/src/app.rs index e6efdd018..41f2cd1a5 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -1114,42 +1114,6 @@ pub(crate) mod tests { ); } - #[test] - fn only_claude_hook_invocations_are_admitted_to_managed_hook_telemetry() { - const HOOK: Option = Some(ManagedSpanKind::ClaudeHook); - const COMMAND: Option = Some(ManagedSpanKind::Command); - let cases: [(&[&str], bool, Option); 20] = [ - (&["sce", "hooks", "claude-mutation-scope"], false, HOOK), - (&["sce", "hooks", "claude-model-state"], false, HOOK), - (&["sce", "hooks", "diff-trace"], true, HOOK), - (&["sce", "hooks", "diff-trace"], false, None), - (&["sce", "hooks", "conversation-trace"], true, HOOK), - (&["sce", "hooks", "conversation-trace"], false, None), - (&["sce", "policy", "bash"], true, HOOK), - (&["sce", "policy", "bash"], false, None), - (&["sce", "hooks", "pre-commit"], true, None), - (&["sce", "--verbose", "hooks", "codex"], true, None), - (&["sce", "hooks", "codex-mutation-scope"], true, None), - (&["sce", "hooks", "opencode-mutation-scope"], true, None), - (&["sce", "hooks", "pi-mutation-scope"], true, None), - (&["sce", "hooks"], true, None), - (&["sce", "auth", "telemetry-headers"], true, None), - (&["sce", "setup"], true, None), - (&["sce", "setup", "--claude"], true, None), - (&["sce", "auth", "login"], true, COMMAND), - (&["sce", "config", "show"], false, COMMAND), - (&["sce", "doctor"], true, COMMAND), - ]; - for (args, claude_caller, expected) in cases { - let args = args.iter().map(ToString::to_string).collect::>(); - assert_eq!( - managed_span_kind(&args, claude_caller), - expected, - "{args:?} claude_caller={claude_caller}" - ); - } - } - #[tokio::test] async fn disallowed_managed_telemetry_resolves_to_noop_without_credential_lookup() { let telemetry = diff --git a/cli/src/app/doctor_reconciliation_cli_tests.rs b/cli/src/app/doctor_reconciliation_cli_tests.rs index aac1d3fa4..c57fd331f 100644 --- a/cli/src/app/doctor_reconciliation_cli_tests.rs +++ b/cli/src/app/doctor_reconciliation_cli_tests.rs @@ -16,11 +16,6 @@ const STATE_FILE: &str = "ref-maintenance.json"; const LOCK_FILE: &str = "mutation-cursor.lock"; const RECONCILIATION_DETAIL_PREFIX: &str = "Snapshot ref reconciliation"; -const AUTH_DB_TEST_SECRET: &str = "doctor-cli-test-secret"; -const UNREADABLE_AUTH_DB: &[u8] = b"not an encrypted auth database"; - -const TELEMETRY_ENABLED_CONFIG: &str = r#"{"telemetry":{"enabled":true}}"#; -const TELEMETRY_OPT_IN_NOTE: &str = "Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the global SCE config to resume it."; const EXIT_SUCCESS: &str = "success"; const EXIT_FAILURE: &str = "failure"; @@ -143,12 +138,6 @@ impl Sandbox { .expect("state JSON") } - fn telemetry_enabled_config(&self) -> String { - let path = self.dir.path().join("telemetry-enabled.json"); - std::fs::write(&path, TELEMETRY_ENABLED_CONFIG).expect("telemetry config"); - path.to_string_lossy().into_owned() - } - fn run(&self, args: &[&str]) -> CliRun { self.run_with_env(args, &[]) } @@ -612,180 +601,3 @@ async fn doctor_fix_recovers_from_every_initial_maintenance_state_condition() { ); } } - -fn global_state_warnings(report: &Value) -> Vec { - report["problems"] - .as_array() - .expect("problems array") - .iter() - .filter(|problem| problem["category"] == "global_state" && problem["severity"] == "warning") - .cloned() - .collect() -} - -#[tokio::test(flavor = "multi_thread")] -async fn doctor_on_fresh_state_reports_unconfigured_telemetry_without_a_warning() { - let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); - let auth_dir = sandbox.state_root().join("sce"); - let config = sandbox.telemetry_enabled_config(); - - let report = sandbox - .run_with_env( - &["doctor", "--format", "json"], - &[ - (AUTH_DB_ENCRYPTION_KEY_ENV, ""), - ("SCE_CONFIG_FILE", config.as_str()), - ], - ) - .json(); - - assert_eq!(report["managed_telemetry"]["state"], "not_configured"); - let warnings = global_state_warnings(&report); - assert!(warnings.is_empty(), "{warnings:#?}"); - assert!(!auth_dir.join("auth.db").exists()); -} - -#[tokio::test(flavor = "multi_thread")] -async fn doctor_fix_reports_unreadable_telemetry_credentials_without_auth_side_effects() { - let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); - let auth_dir = sandbox.state_root().join("sce"); - std::fs::create_dir_all(&auth_dir).expect("auth dir"); - let auth_db = auth_dir.join("auth.db"); - std::fs::write(&auth_db, UNREADABLE_AUTH_DB).expect("auth DB"); - let config = sandbox.telemetry_enabled_config(); - let env = [ - (AUTH_DB_ENCRYPTION_KEY_ENV, AUTH_DB_TEST_SECRET), - ("SCE_CONFIG_FILE", config.as_str()), - ]; - - let fix = sandbox.run_with_env(&["doctor", "--fix", "--format", "json"], &env); - let report = fix.json(); - - assert_eq!( - report["managed_telemetry"], - serde_json::json!({ - "state": "disabled", - "reason": "database_error", - "kind": "managed_telemetry_database_error", - "severity": "warning", - "next_action": "manual_steps", - }), - "{}", - fix.stdout - ); - let warnings = global_state_warnings(&report); - assert_eq!(warnings.len(), 1, "{}", fix.stdout); - assert_eq!(warnings[0]["fixability"], "manual_only"); - assert_eq!(warnings[0]["remediation"]["next_action"], "manual_steps"); - let summary = warnings[0]["summary"].as_str().expect("summary"); - let fixes = report["fix_results"] - .as_array() - .expect("fix_results array") - .iter() - .filter(|entry| { - entry["category"] == "global_state" - && entry["detail"] - .as_str() - .is_some_and(|detail| detail.starts_with(summary)) - }) - .collect::>(); - assert_eq!(fixes.len(), 1, "{}", fix.stdout); - assert_eq!(fixes[0]["outcome"], "manual"); - assert_eq!( - std::fs::read(&auth_db).expect("auth DB kept"), - UNREADABLE_AUTH_DB - ); - assert!(!fix.stdout.contains(AUTH_DB_TEST_SECRET)); - assert!(!fix.stderr.contains(AUTH_DB_TEST_SECRET)); -} - -#[tokio::test(flavor = "multi_thread")] -async fn doctor_reports_post_commit_auto_sync_disabled_when_auth_is_disabled() { - let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); - let config_dir = sandbox.repo.join(".sce"); - std::fs::create_dir_all(&config_dir).expect("config dir"); - let config = config_dir.join("config.json"); - - std::fs::write(&config, r#"{"agent_trace":{"auto_sync":true}}"#).expect("config"); - let allowed = sandbox.run(&["doctor", "--format", "json"]).json(); - assert_eq!(allowed["post_commit_auto_sync"]["enabled"], true); - assert_ne!(allowed["post_commit_auto_sync"]["state"], "disabled"); - - std::fs::write( - &config, - r#"{"agent_trace":{"auto_sync":true},"auth":{"mode":"disabled"}}"#, - ) - .expect("config"); - let report = sandbox.run(&["doctor", "--format", "json"]).json(); - assert_eq!( - report["post_commit_auto_sync"], - serde_json::json!({ - "state": "disabled", - "enabled": false, - "source": "config_file", - "config_source": "default_discovered_local", - }) - ); - let text = sandbox.run(&["doctor"]); - assert!( - text.stdout - .contains("[PASS] Post-commit Agent Trace auto-sync (disabled by config)\n"), - "{}", - text.stdout - ); -} - -#[tokio::test(flavor = "multi_thread")] -async fn doctor_with_telemetry_disabled_by_config_never_reads_the_auth_db() { - let sandbox = Sandbox::new("https://example.invalid/org/repo-a.git"); - let auth_dir = sandbox.state_root().join("sce"); - let env = [(AUTH_DB_ENCRYPTION_KEY_ENV, "")]; - - let fresh = sandbox.run_with_env(&["doctor"], &env); - assert!( - fresh - .stdout - .contains("[PASS] Managed telemetry (disabled by config)\n"), - "{}", - fresh.stdout - ); - assert!( - !fresh.stdout.contains(TELEMETRY_OPT_IN_NOTE), - "{}", - fresh.stdout - ); - assert!(!auth_dir.join("auth.db").exists()); - - std::fs::create_dir_all(&auth_dir).expect("auth dir"); - let auth_db = auth_dir.join("auth.db"); - std::fs::write(&auth_db, UNREADABLE_AUTH_DB).expect("auth DB"); - - let report = sandbox - .run_with_env(&["doctor", "--format", "json"], &env) - .json(); - assert_eq!( - report["managed_telemetry"], - serde_json::json!({ - "state": "disabled_by_config", - "reason": "disabled_by_config", - "kind": null, - "severity": null, - "next_action": null, - }) - ); - let warnings = global_state_warnings(&report); - assert!(warnings.is_empty(), "{warnings:#?}"); - - let text = sandbox.run_with_env(&["doctor"], &env); - assert!( - text.stdout.contains(&format!( - "[PASS] Managed telemetry (disabled by config)\n {TELEMETRY_OPT_IN_NOTE}\n" - )), - "{}", - text.stdout - ); - assert_eq!( - std::fs::read(&auth_db).expect("auth DB kept"), - UNREADABLE_AUTH_DB - ); -} diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 48e33741c..8b02aeb15 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -898,8 +898,6 @@ fn unexpected_auth_command_error(error: anyhow::Error) -> CliError { #[cfg(test)] mod tests { use super::*; - use crate::services::config::{ConfigPathSource, ValueSource}; - use crate::services::error::AuthPolicyConfigFile; fn storage_failure() -> TokenStorageError { TokenStorageError::Database("failed".to_string()) @@ -996,56 +994,6 @@ mod tests { } } - #[test] - fn login_device_flow_storage_failure_uses_noncircular_guidance() { - for (storage, failure) in [ - ( - TokenStorageError::CredentialAccessUnavailable, - AuthStorageFailure::CredentialAccess, - ), - ( - TokenStorageError::DatabaseLocked("busy".to_string()), - AuthStorageFailure::DatabaseLocked, - ), - ( - TokenStorageError::Database("corrupt".to_string()), - AuthStorageFailure::Database, - ), - ] { - assert_login_storage_guidance(&map_login_error(AuthError::Storage(storage)), failure); - } - assert_login_storage_guidance( - &map_login_error(AuthError::Io(std::io::Error::other("io"))), - AuthStorageFailure::Database, - ); - let CliError::User { error, .. } = map_login_error(AuthError::MissingClientId) else { - panic!("expected a user-facing error"); - }; - assert_eq!(error, UserError::UnexpectedFailure); - } - - #[tokio::test] - async fn logout_storage_failure_keeps_command_storage_guidance() { - let error = run_logout_with( - AuthFormat::Json, - async { Err(TokenStorageError::CredentialAccessUnavailable) }, - async { Ok(false) }, - ) - .await - .expect_err("storage failure fails logout"); - let CliError::User { - error: user_error, .. - } = &error - else { - panic!("expected a user-facing storage error"); - }; - assert_eq!( - *user_error, - UserError::AuthStorageUnavailable(AuthStorageFailure::CredentialAccess) - ); - assert!(error.to_string().contains("sce auth login")); - } - #[tokio::test] async fn telemetry_headers_fail_closed_before_lookup_without_repository_or_on_conflict() { use std::sync::atomic::{AtomicBool, Ordering}; @@ -1148,125 +1096,6 @@ mod tests { assert_eq!(headers, r#"{"Authorization":"Bearer tok-scoped"}"#); } - #[tokio::test] - async fn repository_readiness_lookup_fails_closed_unless_repository_is_authorized() { - enum Lookup { - Authorized, - Unauthorized, - AccessFailure, - Hangs, - } - - let cases = [ - ( - "authorized repository", - true, - Some("repo-a"), - Lookup::Authorized, - true, - ), - ( - "auth.db absent", - false, - Some("repo-a"), - Lookup::Authorized, - false, - ), - ( - "missing repository identity", - true, - None, - Lookup::Authorized, - false, - ), - ( - "missing, expired, or foreign-bound credential", - true, - Some("repo-a"), - Lookup::Unauthorized, - false, - ), - ( - "non-interactive access failure", - true, - Some("repo-a"), - Lookup::AccessFailure, - false, - ), - ("lookup timeout", true, Some("repo-a"), Lookup::Hangs, false), - ]; - - for (case, auth_db, repository, lookup, expected) in cases { - let started = std::time::Instant::now(); - let credential = authorized_repository_credential_with( - PathBuf::from("/workspace/repo"), - || auth_db, - move |dir: &Path| { - assert_eq!(dir, Path::new("/workspace/repo")); - repository.map(str::to_string) - }, - move |repository_id: String| async move { - assert_eq!(repository_id, "repo-a"); - match lookup { - Lookup::Authorized => Ok(Some(telemetry_credential("tok-scoped"))), - Lookup::Unauthorized => Ok(None), - Lookup::AccessFailure => Err(storage_failure()), - Lookup::Hangs => std::future::pending().await, - } - }, - ) - .await; - - assert_eq!(credential.is_some(), expected, "{case}"); - assert!( - started.elapsed() < CREDENTIAL_LOOKUP_DEADLINE * 2, - "{case}: lookup exceeded deadline" - ); - } - } - - #[test] - fn telemetry_headers_policy_follows_auth_and_invalid_config() { - let dir = tempfile::tempdir().unwrap(); - std::fs::create_dir(dir.path().join(".git")).unwrap(); - let global = dir.path().join("global.json"); - let local_dir = dir.path().join(".sce"); - std::fs::create_dir_all(&local_dir).unwrap(); - let local = local_dir.join("config.json"); - let enabled = |global_json: &str, local_json: Option<&str>| { - std::fs::write(&global, global_json).unwrap(); - match local_json { - Some(json) => std::fs::write(&local, json).unwrap(), - None => { - let _ = std::fs::remove_file(&local); - } - } - config::resolver::resolve_auth_runtime_config_with( - dir.path(), - |_| None, - |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), - Path::exists, - || Ok(global.clone()), - ) - .is_ok_and(|config| config.access_policy.telemetry_enabled()) - }; - - assert!(enabled(r#"{"telemetry":{"enabled":true}}"#, None)); - assert!(!enabled("{}", None)); - assert!(!enabled( - r#"{"telemetry":{"enabled":true},"auth":{"mode":"disabled"}}"#, - None - )); - assert!(!enabled( - r#"{"telemetry":{"enabled":true}}"#, - Some(r#"{"auth":{"mode":"disabled"}}"#) - )); - assert!(!enabled( - r#"{"telemetry":{"enabled":true}}"#, - Some(r#"{"telemetry":{"enabled":"yes"}}"#) - )); - } - #[test] fn telemetry_headers_failures_use_fixed_secret_free_diagnostic() { let missing = render_telemetry_headers(Ok(None)).expect_err("missing should fail"); @@ -1312,44 +1141,6 @@ mod tests { } } - #[tokio::test] - async fn stored_credentials_are_provisioned_only_after_renewal_completes() { - let original = stored_tokens(); - let renewed = StoredTokens { - access_token: "renewed-access".to_string(), - refresh_token: "renewed-refresh".to_string(), - ..original.clone() - }; - for returned in [original.clone(), renewed] { - let events = std::sync::Mutex::new(Vec::new()); - let events = &events; - let expected_stored = original.clone(); - let output = run_login_with_stored_credentials( - AuthFormat::Json, - Some(original.clone()), - |stored| async move { - assert_eq!(stored, expected_stored); - tokio::task::yield_now().await; - events.lock().unwrap().push("renewal-complete"); - Ok(Some(returned)) - }, - || async move { - events.lock().unwrap().push("provision"); - TelemetryProvisioningResult::Issued - }, - |_format| async { panic!("stored credentials must not use device login") }, - ) - .await - .expect("stored login should succeed"); - - assert_eq!(*events.lock().unwrap(), ["renewal-complete", "provision"]); - assert_eq!(output.telemetry, TelemetryProvisioningResult::Issued); - let output = output.rendered; - assert!(output.contains("\"renewed\": true")); - assert!(output.contains("\"status\": \"issued\"")); - } - } - #[tokio::test] async fn missing_stored_credentials_use_device_login_result() { let output = run_login_with_stored_credentials( @@ -1411,421 +1202,4 @@ mod tests { assert!(!unavailable.contains("workos-access")); assert!(!unavailable.contains("workos-refresh")); } - - #[tokio::test] - async fn logout_attempts_both_deletions_before_reporting() { - use AuthStorageFailure::{CredentialAccess, DatabaseLocked}; - - fn deletion(result: Result) -> Result { - result.map_err(|failure| match failure { - CredentialAccess => TokenStorageError::CredentialAccessUnavailable, - _ => TokenStorageError::DatabaseLocked("busy".to_string()), - }) - } - - for (workos, telemetry, expected) in [ - (Ok(false), Ok(true), Ok(())), - (Ok(true), Err(DatabaseLocked), Err(DatabaseLocked)), - (Err(CredentialAccess), Ok(true), Err(CredentialAccess)), - ( - Err(CredentialAccess), - Err(DatabaseLocked), - Err(CredentialAccess), - ), - ] { - let events = std::sync::Mutex::new(Vec::new()); - let result = run_logout_with( - AuthFormat::Json, - async { - events.lock().unwrap().push("delete-workos"); - deletion(workos) - }, - async { - events.lock().unwrap().push("delete-telemetry"); - deletion(telemetry) - }, - ) - .await; - - assert_eq!( - *events.lock().unwrap(), - ["delete-workos", "delete-telemetry"], - "{workos:?} {telemetry:?}" - ); - match (result, expected) { - (Ok(output), Ok(())) => assert!(output.contains("\"credentials_removed\": true")), - (Err(CliError::User { error, .. }), Err(failure)) => { - assert_eq!(error, UserError::AuthStorageUnavailable(failure)); - } - (result, expected) => { - panic!("{workos:?} {telemetry:?}: {result:?} != {expected:?}") - } - } - } - } - - fn access_policy(mode: AuthMode, source: ValueSource, telemetry: bool) -> ResolvedAccessPolicy { - use crate::services::config::{ - ResolvedValue, TelemetryDisabledReason, TelemetryPolicyState, - }; - - ResolvedAccessPolicy { - auth_mode: ResolvedValue { - value: mode, - source, - }, - telemetry_enabled: ResolvedValue { - value: telemetry, - source: ValueSource::Default, - }, - telemetry: if telemetry { - TelemetryPolicyState::Enabled - } else { - TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled) - }, - background_cloud_allowed: mode != AuthMode::Disabled, - } - } - - fn global_policy(mode: AuthMode, telemetry: bool) -> ResolvedAccessPolicy { - access_policy( - mode, - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), - telemetry, - ) - } - - fn me_response() -> MeResponse { - use crate::services::agent_trace_sync::control_plane::{MeAuthorization, MeUser}; - - MeResponse { - user: MeUser { - email: "dev@example.test".to_string(), - first_name: None, - last_name: None, - }, - authorization: MeAuthorization { - permissions: Vec::new(), - role: None, - }, - workspace: None, - } - } - - #[derive(Clone, Copy, Debug)] - enum StoredCredentials { - None, - Valid, - Expired, - } - - fn user_error_key(result: &Result) -> Option<&'static str> { - match result { - Err(CliError::User { error, .. }) => Some(error.key()), - _ => None, - } - } - - #[tokio::test] - async fn login_follows_auth_mode_across_stored_credentials() { - for mode in [AuthMode::Disabled, AuthMode::Optional, AuthMode::Mandatory] { - for stored in [ - StoredCredentials::None, - StoredCredentials::Valid, - StoredCredentials::Expired, - ] { - let policy = global_policy(mode, true); - let storage_reads = std::sync::atomic::AtomicUsize::new(0); - let storage_reads = &storage_reads; - let result = run_login_with( - AuthFormat::Json, - &policy, - || async move { - storage_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(match stored { - StoredCredentials::None => None, - StoredCredentials::Valid | StoredCredentials::Expired => { - Some(stored_tokens()) - } - }) - }, - |tokens| async move { - Ok(match stored { - StoredCredentials::Valid => Some(tokens), - StoredCredentials::None | StoredCredentials::Expired => None, - }) - }, - || async { TelemetryProvisioningResult::Issued }, - |_format| async { Ok(device_login_report()) }, - ) - .await - .map(|report| report.rendered); - - let reads = storage_reads.load(std::sync::atomic::Ordering::SeqCst); - match (mode, stored) { - (AuthMode::Disabled, _) => { - assert_eq!(user_error_key(&result), Some("auth.disabled_by_config")); - assert_eq!(reads, 0, "{mode:?} {stored:?}"); - } - (_, StoredCredentials::Valid) => { - let output = result.expect("renewed login should succeed"); - assert!(output.contains("\"renewed\": true")); - assert!(output.contains("\"status\": \"issued\"")); - assert_eq!(reads, 1); - } - (_, StoredCredentials::None | StoredCredentials::Expired) => { - assert_eq!(result.expect("device login"), "device-login-complete"); - assert_eq!(reads, 1); - } - } - } - } - } - - #[tokio::test] - async fn login_skips_provisioning_unless_telemetry_is_enabled() { - for mode in [AuthMode::Optional, AuthMode::Mandatory] { - let output = run_login_with( - AuthFormat::Json, - &global_policy(mode, false), - || async { Ok(Some(stored_tokens())) }, - |tokens| async move { Ok(Some(tokens)) }, - || async { panic!("provisioning must not run without telemetry consent") }, - |_format| async { panic!("renewed credentials must not use device login") }, - ) - .await - .expect("renewed login should succeed"); - - assert_eq!(output.telemetry, TelemetryProvisioningResult::Disabled); - let output = output.rendered; - assert!(output.contains("\"status\": \"disabled\"")); - assert!(output.contains(TELEMETRY_PROVISIONING_DISABLED)); - } - - let disabled = provision_if_enabled(false, || async { - panic!("provisioning must not run without telemetry consent") - }) - .await; - let enabled = - provision_if_enabled(true, || async { TelemetryProvisioningResult::Unavailable }).await; - - assert_eq!(disabled, TelemetryProvisioningResult::Disabled); - assert_eq!(enabled, TelemetryProvisioningResult::Unavailable); - } - - #[tokio::test] - async fn whoami_follows_auth_mode_across_stored_credentials() { - let unauthenticated = - render_unauthenticated_whoami(AuthFormat::Json).expect("unauthenticated render"); - let authenticated = - render_whoami_result(&me_response(), AuthFormat::Json).expect("profile render"); - - for mode in [AuthMode::Disabled, AuthMode::Optional, AuthMode::Mandatory] { - for stored in [ - StoredCredentials::None, - StoredCredentials::Valid, - StoredCredentials::Expired, - ] { - let policy = global_policy(mode, false); - let storage_reads = std::sync::atomic::AtomicUsize::new(0); - let storage_reads = &storage_reads; - let result = run_whoami_with( - AuthFormat::Json, - &policy, - || async move { - storage_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(match stored { - StoredCredentials::None => None, - StoredCredentials::Valid | StoredCredentials::Expired => { - Some(stored_tokens()) - } - }) - }, - || async move { - match stored { - StoredCredentials::Valid => Ok(me_response()), - StoredCredentials::Expired => Err( - ControlPlaneError::AuthenticationFailed("expired".to_string()), - ), - StoredCredentials::None => { - panic!("no stored credentials must not fetch a profile") - } - } - }, - ) - .await; - - let reads = storage_reads.load(std::sync::atomic::Ordering::SeqCst); - match (mode, stored) { - (AuthMode::Disabled, _) => { - assert_eq!(user_error_key(&result), Some("auth.disabled_by_config")); - assert_eq!(reads, 0); - } - (AuthMode::Optional, StoredCredentials::None) => { - assert_eq!(result.expect("unauthenticated success"), unauthenticated); - } - (AuthMode::Mandatory, StoredCredentials::None) - | (_, StoredCredentials::Expired) => { - assert_eq!( - user_error_key(&result), - Some("auth.not_authenticated"), - "{mode:?} {stored:?}" - ); - } - (_, StoredCredentials::Valid) => { - assert_eq!(result.expect("profile"), authenticated); - } - } - if mode != AuthMode::Disabled { - assert_eq!(reads, 1, "{mode:?} {stored:?}"); - } - } - } - } - - #[test] - fn auth_disabled_rejection_names_the_deciding_config_file() { - for (source, expected) in [ - ( - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), - AuthPolicyConfigFile::Global, - ), - ( - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal), - AuthPolicyConfigFile::Repository, - ), - ( - ValueSource::ConfigFile(ConfigPathSource::Flag), - AuthPolicyConfigFile::ConfigFlag, - ), - ( - ValueSource::ConfigFile(ConfigPathSource::Env), - AuthPolicyConfigFile::ConfigEnv, - ), - ] { - let Err(CliError::User { error, .. }) = - ensure_auth_allowed(&access_policy(AuthMode::Disabled, source, true)) - else { - panic!("disabled auth must be rejected for {source:?}"); - }; - assert_eq!(error, UserError::AuthDisabledByConfig(expected)); - } - - for mode in [AuthMode::Optional, AuthMode::Mandatory] { - assert!(ensure_auth_allowed(&global_policy(mode, false)).is_ok()); - } - } - - #[test] - fn login_reports_disabled_telemetry_provisioning_in_text_and_json() { - let text = - render_login_text_with_color_policy(TelemetryProvisioningResult::Disabled, false); - let json = render_login_result_with_telemetry( - &device_auth_result(), - AuthFormat::Json, - TelemetryProvisioningResult::Disabled, - ) - .expect("disabled JSON login output should render"); - let value: serde_json::Value = serde_json::from_str(&json).expect("valid JSON"); - - assert_eq!( - text, - "✓ Authentication succeeded.\nNote: Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it." - ); - assert_eq!( - value["telemetry_provisioning"], - json!({ - "status": "disabled", - "message": TELEMETRY_PROVISIONING_DISABLED, - }) - ); - } - - #[tokio::test] - async fn logout_deletes_both_credential_rows_when_auth_is_disabled_by_config() { - let dir = tempfile::tempdir().unwrap(); - let global = dir.path().join("global.json"); - std::fs::write(&global, r#"{"auth":{"mode":"disabled"}}"#).unwrap(); - let policy = config::resolver::resolve_auth_runtime_config_with( - dir.path(), - |_| None, - |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), - Path::exists, - || Ok(global.clone()), - ) - .expect("config resolves") - .access_policy; - assert!(!policy.auth_allowed()); - - let events = std::sync::Mutex::new(Vec::new()); - let output = run_logout_with( - AuthFormat::Json, - async { - events.lock().unwrap().push("delete-workos"); - Ok(true) - }, - async { - events.lock().unwrap().push("delete-telemetry"); - Ok(true) - }, - ) - .await - .expect("logout should succeed"); - - assert_eq!( - *events.lock().unwrap(), - ["delete-workos", "delete-telemetry"] - ); - assert!(output.contains("\"credentials_removed\": true")); - } - - #[tokio::test] - async fn login_report_carries_issued_telemetry_when_policy_enables_it() { - for mode in [AuthMode::Optional, AuthMode::Mandatory] { - let report = run_login_with( - AuthFormat::Text, - &global_policy(mode, true), - || async { Ok(Some(stored_tokens())) }, - |tokens| async move { Ok(Some(tokens)) }, - || async { TelemetryProvisioningResult::Issued }, - |_format| async { panic!("renewed credentials must not use device login") }, - ) - .await - .expect("renewed login should succeed"); - - assert_eq!(report.telemetry, TelemetryProvisioningResult::Issued); - } - } - - #[tokio::test] - async fn repository_enrollment_uses_the_supplied_working_directory() { - let working_dir = Path::new("/tmp/sce-login-working-dir"); - let looked_up = std::sync::Mutex::new(None); - let bound = std::sync::Mutex::new(None); - let looked_up = &looked_up; - let bound = &bound; - - enroll_repository_if_unbound_with( - working_dir, - |dir| { - *looked_up.lock().unwrap() = Some(dir.to_path_buf()); - Some("repo-id".to_string()) - }, - |repository_id| async move { - *bound.lock().unwrap() = Some(repository_id); - Ok(true) - }, - ) - .await; - - assert_eq!(looked_up.lock().unwrap().as_deref(), Some(working_dir),); - assert_eq!(bound.lock().unwrap().as_deref(), Some("repo-id")); - - enroll_repository_if_unbound_with( - working_dir, - |_dir| None, - |_repository_id| async { panic!("unresolved repository must not bind") }, - ) - .await; - } } diff --git a/cli/src/services/auth_db/mod.rs b/cli/src/services/auth_db/mod.rs index 5e464738d..5e2934bb0 100644 --- a/cli/src/services/auth_db/mod.rs +++ b/cli/src/services/auth_db/mod.rs @@ -35,6 +35,3 @@ impl DbSpec for AuthDbSpec { pub type AuthDb = EncryptedTursoDb; pub mod lifecycle; - -#[cfg(test)] -mod multiprocess_tests; diff --git a/cli/src/services/auth_db/multiprocess_tests.rs b/cli/src/services/auth_db/multiprocess_tests.rs deleted file mode 100644 index 059064518..000000000 --- a/cli/src/services/auth_db/multiprocess_tests.rs +++ /dev/null @@ -1,1562 +0,0 @@ -use std::collections::BTreeSet; -use std::io::{BufRead, BufReader, Read, Write}; -use std::path::{Path, PathBuf}; -use std::process::{Child, ChildStdin, Command, Stdio}; -use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; -use std::sync::{Mutex, MutexGuard}; -use std::time::{Duration, Instant}; - -use anyhow::Result; - -use super::{AuthDb, AuthDbSpec}; -use crate::generated_migrations; -use crate::services::bash_policy::{ - run_bash_policy_request, BashPolicyRequest, PolicyInputMode, PolicyOutputMode, -}; -use crate::services::db::encryption_key::AUTH_DB_ENCRYPTION_KEY_ENV; -use crate::services::db::{DatabaseKind, DbSpec, EncryptedTursoDb}; -use crate::services::default_paths::auth_db_path; -use crate::services::error::CliError; -use crate::services::hooks::{run_hooks_subcommand, HookSubcommand}; -use crate::services::managed_telemetry::claude_helper::repository_id_for; -use crate::services::managed_telemetry::claude_helper::tests::git_repository_with_remote; -use crate::services::managed_telemetry::trace_export::tests::{ - capture_requests_until, loopback_hook_telemetry, trace_spans, -}; -use crate::services::managed_telemetry::trace_export::{ClaudeHookCommand, ManagedSpanKind}; -use crate::services::managed_telemetry::{ - inspect_health, ManagedTelemetryHealth, RuntimeTelemetry, TelemetryFallbackReason, -}; -use crate::services::observability::traits::{NoopLogger, Telemetry}; -use crate::services::telemetry_credential_storage::{ - bind_repository_telemetry, delete_telemetry_credential, load_repository_telemetry_credential, - load_telemetry_credential, save_telemetry_credential, test_access_token, RepositoryBindingMode, - TelemetryCredential, TelemetryCredentialLookup, TelemetryIdentity, -}; - -const CHILD_TEST: &str = "services::auth_db::multiprocess_tests::auth_db_child_process"; -const ROLE_ENV: &str = "SCE_AUTH_DB_TEST_CHILD_ROLE"; -const COLLECTOR_ENV: &str = "SCE_AUTH_DB_TEST_COLLECTOR"; -const HOOK_INDEX_ENV: &str = "SCE_AUTH_DB_TEST_HOOK_INDEX"; -const TEST_SECRET: &str = "auth-db-multiprocess-test-secret"; -const WRONG_SECRET: &str = "auth-db-multiprocess-wrong-secret"; -const TOKEN: &str = "tok-multiprocess"; -const USER_ID: &str = "user_mp"; -const WORKSPACE_ID: &str = "workspace_mp"; -const READY: &str = "SCE_AUTH_DB_CHILD_READY"; -const TOKEN_PREFIX: &str = "SCE_AUTH_DB_CHILD_TOKEN="; -const HEALTH_PREFIX: &str = "SCE_AUTH_DB_CHILD_TELEMETRY_HEALTH="; -const HOOK_TELEMETRY_PREFIX: &str = "SCE_AUTH_DB_CHILD_HOOK_TELEMETRY="; -const HOOK_CREDENTIAL_VALID: &str = "credential_valid"; -const LEGACY_READINESS_MARKER: &str = "telemetry-ready.json"; -const LEGACY_READINESS_MARKER_CASES: [(&str, Option<&[u8]>); 4] = [ - ("absent", None), - ("valid", Some(br#"{"expires_at_unix_seconds":4102444800}"#)), - ("expired", Some(br#"{"expires_at_unix_seconds":1}"#)), - ("malformed", Some(b"not json")), -]; -const CONCURRENT_PROCESSES: usize = 32; -const CONCURRENT_MIGRATORS: usize = 4; -const CONCURRENT_LOOKUPS: usize = 8; -const CHILD_KILL_AFTER: Duration = Duration::from_mins(1); -const CHILD_POLL_INTERVAL: Duration = Duration::from_millis(10); -const FAR_FUTURE: u64 = 4_102_444_800; -const HOOK_COMMANDS: [ClaudeHookCommand; 5] = [ - ClaudeHookCommand::DiffTrace, - ClaudeHookCommand::ConversationTrace, - ClaudeHookCommand::ClaudeMutationScope, - ClaudeHookCommand::ClaudeModelState, - ClaudeHookCommand::PolicyBash, -]; -const PRE_BINDING_MIGRATIONS: usize = 3; -const BINDING_MIGRATION_ID: &str = "004_bind_telemetry_credentials"; -const WRITER_ENV: &str = "SCE_AUTH_DB_TEST_WRITER"; -const COMMITTED_PREFIX: &str = "SCE_AUTH_DB_CHILD_COMMITTED="; -const ROW_PREFIX: &str = "SCE_AUTH_DB_CHILD_ROW="; -const WRITER_ROWS: usize = 8; -const WRITER_PAUSE: Duration = Duration::from_millis(20); -const CONCURRENT_WRITERS: usize = 4; -const INSERT_BINDING_SQL: &str = "INSERT INTO telemetry_repository_bindings \ - (repository_id, user_id, workspace_id, bound_at_unix_seconds) VALUES (?1, ?2, ?3, 1)"; -const AUTH_DB_FILES: [&str; 3] = ["auth.db", "auth.db-wal", "auth.db-tshm"]; -const HEADERS_REPOSITORY: &str = "bound-repo"; -const UNBOUND_REPOSITORY: &str = "unbound-repo"; -const HEADERS_AUTHORIZATION: &str = r#"{"Authorization":"Bearer tok-multiprocess"}"#; -const HEADERS_UNAVAILABLE: &str = "Telemetry credential is unavailable."; -const STDIN_SECRET: &str = "SECRET_STDIN_VALUE"; -const TELEMETRY_FALLBACK_EVENT: &str = "event_id=sce.telemetry.fallback"; -const FALLBACK_REASON_PREFIX: &str = "reason="; -const CLI_ARGS_ENV: &str = "SCE_AUTH_DB_TEST_CLI_ARGS"; -const CLI_SUCCESS_PREFIX: &str = "SCE_AUTH_DB_CHILD_CLI_SUCCESS="; -const AUTH_DISABLED_BY_REPOSITORY: &str = - "Authentication is disabled by `auth.mode: disabled` in the repository SCE config"; -const AUTH_DISABLED_BY_GLOBAL: &str = - "Authentication is disabled by `auth.mode: disabled` in the global SCE config"; -const FAIL_OPEN_HOOK_COMMANDS: [ClaudeHookCommand; 3] = [ - ClaudeHookCommand::DiffTrace, - ClaudeHookCommand::ConversationTrace, - ClaudeHookCommand::ClaudeModelState, -]; - -struct PreBindingAuthDbSpec; - -impl DbSpec for PreBindingAuthDbSpec { - fn db_name() -> &'static str { - AuthDbSpec::db_name() - } - - fn db_path() -> Result { - auth_db_path() - } - - fn migrations() -> &'static [(&'static str, &'static str)] { - &generated_migrations::AUTH_MIGRATIONS[..PRE_BINDING_MIGRATIONS] - } - - const KIND: DatabaseKind = DatabaseKind::Auth; -} - -static FAN_OUT_LOCK: Mutex<()> = Mutex::new(()); - -fn serialize_fan_out() -> MutexGuard<'static, ()> { - FAN_OUT_LOCK - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) -} - -struct SchemalessAuthDbSpec; - -impl DbSpec for SchemalessAuthDbSpec { - fn db_name() -> &'static str { - AuthDbSpec::db_name() - } - - fn db_path() -> Result { - auth_db_path() - } - - fn migrations() -> &'static [(&'static str, &'static str)] { - &[] - } - - const KIND: DatabaseKind = DatabaseKind::Auth; -} - -struct Sandbox { - dir: tempfile::TempDir, -} - -impl Sandbox { - fn new() -> Self { - Self { - dir: tempfile::tempdir().expect("sandbox"), - } - } - - fn command(&self, role: &str) -> Command { - let root = self.dir.path(); - let mut command = Command::new(std::env::current_exe().expect("test binary")); - command - .args(["--exact", CHILD_TEST, "--nocapture", "--test-threads=1"]) - .env(ROLE_ENV, role) - .env("HOME", root) - .env("XDG_STATE_HOME", root.join("state")) - .env("XDG_CONFIG_HOME", root.join("config")) - .env("XDG_CACHE_HOME", root.join("cache")) - .env("XDG_DATA_HOME", root.join("data")) - .env(AUTH_DB_ENCRYPTION_KEY_ENV, TEST_SECRET) - .env_remove("TRACEPARENT") - .env_remove("TRACESTATE") - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()); - for (key, _) in std::env::vars_os() { - if key.to_string_lossy().starts_with("OTEL_") { - command.env_remove(key); - } - } - command - } - - fn rows(&self) -> BTreeSet { - prefixed_lines(&self.run("verify-rows"), ROW_PREFIX) - } - - fn sce_state_dir(&self) -> PathBuf { - let root = self.dir.path(); - let state_root = if cfg!(target_os = "macos") { - root.join("Library").join("Application Support") - } else { - root.join("state") - }; - state_root.join("sce") - } - - fn global_config_file(&self) -> PathBuf { - let root = self.dir.path(); - let config_root = if cfg!(target_os = "macos") { - root.join("Library").join("Application Support") - } else { - root.join("config") - }; - config_root.join("sce").join("config.json") - } - - fn write_global_config(&self, config: &serde_json::Value) { - write_config_file(&self.global_config_file(), config); - } - - fn auth_db_files(&self) -> Vec { - let state = self.sce_state_dir(); - AUTH_DB_FILES - .iter() - .filter(|name| state.join(name).exists()) - .map(ToString::to_string) - .collect() - } - - fn run(&self, role: &str) -> String { - wait_success(role, self.command(role).spawn().expect("spawn child")) - } - - fn hold(&self, role: &str) -> HeldChild { - Self::hold_command(role, self.command(role)) - } - - fn hold_command(role: &str, mut command: Command) -> HeldChild { - let mut child = command.stdin(Stdio::piped()).spawn().expect("spawn holder"); - let stdin = child.stdin.take().expect("holder stdin"); - let stdout = child.stdout.take().expect("holder stdout"); - let (sender, lines) = mpsc::channel(); - std::thread::spawn(move || { - for line in BufReader::new(stdout).lines().map_while(Result::ok) { - if sender.send(line).is_err() { - break; - } - } - }); - let mut held = HeldChild { - role: role.to_string(), - child, - stdin, - lines, - }; - held.wait_ready(); - held - } - - fn seed(&self) { - self.run("seed"); - } -} - -struct HeldChild { - role: String, - child: Child, - stdin: ChildStdin, - lines: Receiver, -} - -impl HeldChild { - fn signal(&mut self) { - writeln!(self.stdin).expect("release holder"); - } - - fn wait_ready(&mut self) -> String { - let deadline = Instant::now() + CHILD_KILL_AFTER; - let mut captured = String::new(); - loop { - match self - .lines - .recv_timeout(deadline.saturating_duration_since(Instant::now())) - { - Ok(line) if line.trim_end().ends_with(READY) => return captured, - Ok(line) => { - captured.push_str(&line); - captured.push('\n'); - } - Err(RecvTimeoutError::Timeout) => self.abort( - &format!("was not ready within {CHILD_KILL_AFTER:?}"), - &captured, - ), - Err(RecvTimeoutError::Disconnected) => self.abort("exited before ready", &captured), - } - } - } - - fn abort(&mut self, reason: &str, stdout: &str) -> ! { - let _ = self.child.kill(); - let _ = self.child.wait(); - let mut stderr = String::new(); - if let Some(mut pipe) = self.child.stderr.take() { - let _ = pipe.read_to_string(&mut stderr); - } - panic!("{} holder {reason}:\n{stdout}\n{stderr}", self.role); - } - - fn release(mut self) { - self.signal(); - wait_bounded(&self.role, &mut self.child); - let rest = self.lines.iter().collect::>().join("\n"); - let output = self.child.wait_with_output().expect("holder output"); - assert!( - output.status.success() && rest.contains("1 passed"), - "{} holder failed:\n{rest}\n{}", - self.role, - String::from_utf8_lossy(&output.stderr) - ); - } -} - -fn wait_bounded(role: &str, child: &mut Child) { - let started = Instant::now(); - while child.try_wait().expect("child status").is_none() { - if started.elapsed() > CHILD_KILL_AFTER { - let _ = child.kill(); - let _ = child.wait(); - panic!("{role} child did not exit within {CHILD_KILL_AFTER:?}"); - } - std::thread::sleep(CHILD_POLL_INTERVAL); - } -} - -fn wait_success(role: &str, mut child: Child) -> String { - wait_bounded(role, &mut child); - let output = child.wait_with_output().expect("child output"); - let stdout = String::from_utf8_lossy(&output.stdout).to_string(); - assert!( - output.status.success() && stdout.contains("1 passed"), - "{role} child failed:\n{stdout}\n{}", - String::from_utf8_lossy(&output.stderr) - ); - stdout -} - -fn prefixed_lines(stdout: &str, prefix: &str) -> BTreeSet { - stdout - .lines() - .filter_map(|line| line.split_once(prefix).map(|(_, value)| value.to_string())) - .collect() -} - -fn coordinated_writer_rows(sandbox: &Sandbox) -> BTreeSet { - // Open every connection before writes start, and keep every connection - // alive until all writes finish so WAL startup/teardown cannot race them. - let mut writers = (0..CONCURRENT_WRITERS) - .map(|index| { - let mut command = sandbox.command("coordinated-writer"); - command.env(WRITER_ENV, format!("writer-{index}")); - Sandbox::hold_command("coordinated-writer", command) - }) - .collect::>(); - for writer in &mut writers { - writer.signal(); - } - let mut committed = BTreeSet::new(); - for writer in &mut writers { - committed.extend(prefixed_lines(&writer.wait_ready(), COMMITTED_PREFIX)); - } - for writer in writers { - writer.release(); - } - committed -} - -fn expected_writer_rows() -> BTreeSet { - (0..CONCURRENT_WRITERS) - .flat_map(|index| (0..WRITER_ROWS).map(move |row| format!("writer-{index}-{row:02}"))) - .collect() -} - -fn read_token(stdout: &str) -> Option<&str> { - stdout - .lines() - .find_map(|line| line.split_once(TOKEN_PREFIX).map(|(_, token)| token)) -} - -fn spawn_readers(sandbox: &Sandbox) -> Vec { - (0..CONCURRENT_PROCESSES) - .map(|_| sandbox.command("read").spawn().expect("spawn reader")) - .collect() -} - -fn wait_readers(readers: Vec) -> usize { - readers - .into_iter() - .map(|child| wait_success("read", child)) - .filter(|stdout| read_token(stdout) == Some(TOKEN)) - .count() -} - -#[test] -fn reader_succeeds_while_another_process_holds_auth_db_open() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - - let holder = sandbox.hold("hold-open"); - let reader = sandbox.run("read"); - assert_eq!(read_token(&reader), Some(TOKEN)); - holder.release(); -} - -#[test] -fn thirty_two_reader_processes_all_resolve_the_credential() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - - assert_eq!(wait_readers(spawn_readers(&sandbox)), CONCURRENT_PROCESSES); -} - -#[test] -fn current_schema_reader_performs_no_migration_write_under_held_write_lock() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - - let writer = sandbox.hold("hold-write"); - let reader = sandbox.run("read"); - assert_eq!(read_token(&reader), Some(TOKEN)); - writer.release(); - sandbox.run("verify-schema"); -} - -struct NoRepositoryContext; - -impl crate::app::HasRepoRoot for NoRepositoryContext { - fn repo_root(&self) -> Option<&Path> { - None - } -} - -fn run_setup_lifecycle_child(sandbox: &Sandbox, role: &str) { - wait_success( - role, - sandbox - .command(role) - .env(AUTH_DB_ENCRYPTION_KEY_ENV, "") - .spawn() - .expect("spawn setup child"), - ); -} - -#[test] -fn setup_lifecycle_on_fresh_state_creates_no_auth_db_and_resolves_no_key() { - let _fan_out = serialize_fan_out(); - run_setup_lifecycle_child(&Sandbox::new(), "setup-fresh"); -} - -#[test] -fn setup_lifecycle_leaves_existing_auth_db_unchanged_and_resolves_no_key() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - run_setup_lifecycle_child(&sandbox, "setup-existing"); -} - -#[test] -fn telemetry_lookup_never_creates_a_missing_auth_db() { - let _fan_out = serialize_fan_out(); - Sandbox::new().run("lookup-missing"); -} - -fn telemetry_health(sandbox: &Sandbox, secret: &str) -> String { - let stdout = wait_success( - "telemetry-health", - sandbox - .command("telemetry-health") - .env(AUTH_DB_ENCRYPTION_KEY_ENV, secret) - .spawn() - .expect("spawn health child"), - ); - let health = prefixed_lines(&stdout, HEALTH_PREFIX); - assert_eq!(health.len(), 1, "{stdout}"); - health.into_iter().next().expect("one health line") -} - -fn hook_telemetry(sandbox: &Sandbox) -> String { - let stdout = sandbox.run("hook-resolve"); - let resolved = prefixed_lines(&stdout, HOOK_TELEMETRY_PREFIX); - assert_eq!(resolved.len(), 1, "{stdout}"); - resolved - .into_iter() - .next() - .expect("one hook telemetry line") -} - -fn write_legacy_readiness_marker(sandbox: &Sandbox, marker: Option<&[u8]>) -> PathBuf { - let path = sandbox.sce_state_dir().join(LEGACY_READINESS_MARKER); - match marker { - Some(bytes) => std::fs::write(&path, bytes).expect("legacy marker"), - None => { - let _ = std::fs::remove_file(&path); - } - } - path -} - -#[test] -fn doctor_telemetry_health_on_fresh_state_resolves_no_key_and_creates_no_auth_db() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - assert_eq!(telemetry_health(&sandbox, ""), "not_configured"); - assert!(sandbox.auth_db_files().is_empty()); -} - -#[test] -fn doctor_telemetry_health_classifies_real_auth_db_states_without_mutating_them() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - let auth_db = sandbox.sce_state_dir().join("auth.db"); - for (case, mutation, secret, expected) in [ - ("valid", None, TEST_SECRET, "healthy"), - ("wrong key", None, WRONG_SECRET, "database_error"), - ("missing key", None, "", "database_error"), - ( - "expired", - Some("seed-expired-credential"), - TEST_SECRET, - "credential_expired", - ), - ( - "no telemetry row", - Some("delete-telemetry-credential"), - TEST_SECRET, - "not_configured", - ), - ] { - if let Some(role) = mutation { - sandbox.run(role); - } - let before = std::fs::read(&auth_db).expect("auth DB"); - assert_eq!(telemetry_health(&sandbox, secret), expected, "{case}"); - assert_eq!(std::fs::read(&auth_db).expect("auth DB"), before, "{case}"); - } -} - -#[test] -fn valid_credential_without_readiness_marker_resolves_managed_telemetry_and_headers() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - let bound = git_repository_with_remote( - sandbox.dir.path(), - HEADERS_REPOSITORY, - "https://github.com/acme/bound-repo", - ); - sandbox.seed(); - let mut bind = sandbox.command("bind"); - bind.current_dir(&bound); - wait_success("bind", bind.spawn().expect("spawn bind")); - let marker = write_legacy_readiness_marker(&sandbox, None); - assert!(!marker.exists()); - - assert_eq!(hook_telemetry(&sandbox), HOOK_CREDENTIAL_VALID); - assert_eq!(telemetry_health(&sandbox, TEST_SECRET), "healthy"); - let enabled = headers_policy_config(&sandbox, true); - assert_headers_served(spawn_headers(&sandbox, &bound, Some(&enabled))); - assert!(!marker.exists()); -} - -#[test] -fn logout_then_lookup_reports_not_configured() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - assert_eq!(telemetry_health(&sandbox, TEST_SECRET), "healthy"); - - let logout = run_cli( - &sandbox, - sandbox.dir.path(), - &["sce", "auth", "logout", "--format", "json"], - None, - ); - assert!(logout.success, "{}{}", logout.stdout, logout.stderr); - assert!( - logout.stdout.contains("\"credentials_removed\": true"), - "{}", - logout.stdout - ); - - assert!(sandbox.sce_state_dir().join("auth.db").is_file()); - assert_eq!(telemetry_health(&sandbox, TEST_SECRET), "not_configured"); - assert_eq!(hook_telemetry(&sandbox), "not_configured"); - assert!(!sandbox - .sce_state_dir() - .join(LEGACY_READINESS_MARKER) - .exists()); -} - -#[test] -fn legacy_readiness_marker_is_ignored() { - let _fan_out = serialize_fan_out(); - for (credential_case, delete_credential, expected_health, expected_hook) in [ - ("valid credential", false, "healthy", HOOK_CREDENTIAL_VALID), - ("no credential", true, "not_configured", "not_configured"), - ] { - let sandbox = Sandbox::new(); - sandbox.seed(); - if delete_credential { - sandbox.run("delete-telemetry-credential"); - } - for (marker_case, marker) in LEGACY_READINESS_MARKER_CASES { - let case = format!("{credential_case}, {marker_case} marker"); - let path = write_legacy_readiness_marker(&sandbox, marker); - assert_eq!( - telemetry_health(&sandbox, TEST_SECRET), - expected_health, - "{case}" - ); - assert_eq!(hook_telemetry(&sandbox), expected_hook, "{case}"); - assert_eq!( - std::fs::read(&path).ok().as_deref(), - marker, - "{case}: marker bytes changed" - ); - } - } -} - -#[test] -fn concurrent_migration_of_schemaless_db_applies_each_migration_once() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.run("create-schemaless"); - - let initializers = (0..CONCURRENT_MIGRATORS) - .map(|_| sandbox.command("init").spawn().expect("spawn initializer")) - .collect::>(); - for child in initializers { - wait_success("init", child); - } - sandbox.run("verify-schema"); -} - -#[test] -fn readiness_lookup_never_migrates_outdated_auth_db() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.run("create-outdated"); - let auth_db = sandbox.sce_state_dir().join("auth.db"); - let before = std::fs::read(&auth_db).expect("outdated auth DB"); - - let lookups = (0..CONCURRENT_LOOKUPS) - .map(|_| { - sandbox - .command("lookup-outdated") - .spawn() - .expect("spawn lookup") - }) - .collect::>(); - for child in lookups { - wait_success("lookup-outdated", child); - } - - assert_eq!(std::fs::read(&auth_db).expect("auth DB"), before); - sandbox.run("verify-outdated"); - sandbox.run("lookup-then-migrate"); -} - -#[test] -fn outdated_schema_is_migrated_and_partial_schema_fails_clearly() { - let _fan_out = serialize_fan_out(); - Sandbox::new().run("upgrade"); - Sandbox::new().run("partial"); -} - -#[test] -fn concurrent_current_version_writers_persist_every_row() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - - assert_eq!(coordinated_writer_rows(&sandbox), expected_writer_rows()); - assert_eq!(sandbox.rows(), expected_writer_rows()); -} - -#[cfg(target_os = "macos")] -#[test] -fn macos_current_version_processes_share_the_lock_concurrently() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - - let holders = [sandbox.hold("hold-open"), sandbox.hold("hold-open")]; - assert_eq!(coordinated_writer_rows(&sandbox), expected_writer_rows()); - assert_eq!(read_token(&sandbox.run("read")), Some(TOKEN)); - for holder in holders { - holder.release(); - } - assert_eq!(sandbox.rows(), expected_writer_rows()); -} - -#[test] -fn repository_telemetry_lookup_never_creates_a_missing_auth_db() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - let mut lookup = sandbox.command("repository-lookup-missing"); - lookup.env(AUTH_DB_ENCRYPTION_KEY_ENV, ""); - wait_success( - "repository-lookup-missing", - lookup.spawn().expect("spawn lookup"), - ); - assert!(sandbox.auth_db_files().is_empty()); -} - -#[test] -fn concurrent_telemetry_headers_on_missing_auth_db_fail_closed_without_creating_it() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - let repository = git_repository_with_remote( - sandbox.dir.path(), - HEADERS_REPOSITORY, - "https://github.com/acme/bound-repo", - ); - - let config = headers_policy_config(&sandbox, true); - let helpers = (0..CONCURRENT_PROCESSES) - .map(|_| spawn_headers(&sandbox, &repository, Some(&config))) - .collect::>(); - for helper in helpers { - assert_headers_unavailable(helper); - } - assert!(sandbox.auth_db_files().is_empty()); -} - -#[test] -fn telemetry_headers_serve_only_the_bound_repository() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - let bound = git_repository_with_remote( - sandbox.dir.path(), - HEADERS_REPOSITORY, - "https://github.com/acme/bound-repo", - ); - let unbound = git_repository_with_remote( - sandbox.dir.path(), - UNBOUND_REPOSITORY, - "https://github.com/acme/unbound-repo", - ); - sandbox.seed(); - let mut bind = sandbox.command("bind"); - bind.current_dir(&bound); - wait_success("bind", bind.spawn().expect("spawn bind")); - - let enabled = headers_policy_config(&sandbox, true); - let disabled = headers_policy_config(&sandbox, false); - assert_headers_served(spawn_headers(&sandbox, &bound, Some(&enabled))); - assert_headers_unavailable(spawn_headers(&sandbox, &unbound, Some(&enabled))); - assert_headers_unavailable(spawn_headers(&sandbox, &bound, Some(&disabled))); -} - -fn write_config_file(path: &Path, config: &serde_json::Value) { - std::fs::create_dir_all(path.parent().expect("config parent")).expect("config dir"); - std::fs::write(path, config.to_string()).expect("config file"); -} - -fn headers_policy_config(sandbox: &Sandbox, telemetry_enabled: bool) -> PathBuf { - let config = sandbox - .dir - .path() - .join(format!("headers-policy-{telemetry_enabled}.json")); - std::fs::write( - &config, - serde_json::json!({ "telemetry": { "enabled": telemetry_enabled } }).to_string(), - ) - .expect("headers policy config"); - config -} - -fn spawn_headers(sandbox: &Sandbox, repository: &Path, config: Option<&Path>) -> Child { - let mut helper = sandbox.command("headers"); - helper.current_dir(repository); - if let Some(config) = config { - helper.env("SCE_CONFIG_FILE", config); - } - helper.spawn().expect("spawn headers") -} - -fn assert_headers_served(helper: Child) { - let output = helper.wait_with_output().expect("headers output"); - assert!(output.status.success(), "headers child failed"); - assert!( - String::from_utf8_lossy(&output.stdout).contains(HEADERS_AUTHORIZATION), - "{}", - String::from_utf8_lossy(&output.stderr) - ); -} - -fn assert_headers_unavailable(helper: Child) { - let output = helper.wait_with_output().expect("headers output"); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!(output.status.success(), "headers child failed: {stderr}"); - assert!(stdout.contains("1 passed"), "{stdout}"); - assert!(!stdout.contains("Authorization"), "{stdout}"); - assert!(stderr.contains(HEADERS_UNAVAILABLE), "{stderr}"); -} - -fn policy_hook_fallback_reasons(sandbox: &Sandbox, telemetry_enabled: bool) -> Vec { - let root = sandbox.dir.path(); - let work = root.join("work"); - std::fs::create_dir_all(&work).expect("work dir"); - let config = root.join(format!("policy-{telemetry_enabled}.json")); - std::fs::write( - &config, - serde_json::json!({ "telemetry": { "enabled": telemetry_enabled } }).to_string(), - ) - .expect("policy config"); - hook_fallback_reasons( - sandbox, - &work, - Some(&config), - &format!("logs-{telemetry_enabled}"), - ) -} - -fn hook_fallback_reasons( - sandbox: &Sandbox, - working_dir: &Path, - explicit_config: Option<&Path>, - log_label: &str, -) -> Vec { - let log_dir = sandbox.dir.path().join(log_label); - std::fs::create_dir_all(&log_dir).expect("log dir"); - let mut hook = sandbox.command("policy-hook"); - hook.current_dir(working_dir) - .env(AUTH_DB_ENCRYPTION_KEY_ENV, "") - .env("SCE_LOG_LEVEL", "debug") - .env("SCE_LOG_FORMAT", "text") - .env("SCE_LOG_DIR", &log_dir) - .env("CLAUDECODE", "1") - .env("CLAUDE_PROJECT_DIR", working_dir); - if let Some(config) = explicit_config { - hook.env("SCE_CONFIG_FILE", config); - } - wait_success("policy-hook", hook.spawn().expect("spawn policy hook")); - let mut reasons = Vec::new(); - for entry in std::fs::read_dir(&log_dir).expect("log entries") { - let log = std::fs::read_to_string(entry.expect("log entry").path()).expect("log file"); - reasons.extend( - log.lines() - .filter(|line| line.contains(TELEMETRY_FALLBACK_EVENT)) - .filter_map(|line| { - line.split_whitespace() - .find_map(|token| token.strip_prefix(FALLBACK_REASON_PREFIX)) - .map(ToString::to_string) - }), - ); - } - reasons -} - -struct CliRun { - success: bool, - stdout: String, - stderr: String, -} - -fn run_cli( - sandbox: &Sandbox, - working_dir: &Path, - args: &[&str], - explicit_config: Option<&Path>, -) -> CliRun { - let mut command = sandbox.command("cli"); - command - .current_dir(working_dir) - .env(CLI_ARGS_ENV, args.join("\n")); - if let Some(config) = explicit_config { - command.env("SCE_CONFIG_FILE", config); - } - let output = command - .spawn() - .expect("spawn cli") - .wait_with_output() - .expect("cli output"); - let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); - let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); - assert!(output.status.success(), "cli child failed: {stderr}"); - CliRun { - success: stdout.contains(&format!("{CLI_SUCCESS_PREFIX}true")), - stdout, - stderr, - } -} - -fn bound_repository(sandbox: &Sandbox) -> PathBuf { - let repository = git_repository_with_remote( - sandbox.dir.path(), - HEADERS_REPOSITORY, - "https://github.com/acme/bound-repo", - ); - sandbox.seed(); - let mut bind = sandbox.command("bind"); - bind.current_dir(&repository); - wait_success("bind", bind.spawn().expect("spawn bind")); - repository -} - -#[test] -fn cli_launched_from_a_repository_subdirectory_honors_repository_policy() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.write_global_config(&serde_json::json!({ - "auth": { "mode": "optional" }, - "telemetry": { "enabled": true }, - })); - let repository = bound_repository(&sandbox); - let nested = repository.join("src").join("module"); - let repository_config = repository.join(".sce").join("config.json"); - - assert_headers_served(spawn_headers(&sandbox, &nested, None)); - assert_eq!( - hook_fallback_reasons(&sandbox, &nested, None, "logs-consented"), - ["database_error"] - ); - - write_config_file( - &repository_config, - &serde_json::json!({ "telemetry": { "enabled": false } }), - ); - assert_headers_unavailable(spawn_headers(&sandbox, &nested, None)); - assert_eq!( - hook_fallback_reasons(&sandbox, &nested, None, "logs-repository-opt-out"), - ["disabled_by_config"] - ); - - write_config_file( - &repository_config, - &serde_json::json!({ "auth": { "mode": "disabled" } }), - ); - let sync = run_cli( - &sandbox, - &nested, - &["sce", "sync", "--format", "json"], - None, - ); - assert!(!sync.success, "{}", sync.stdout); - assert!( - sync.stderr.contains(AUTH_DISABLED_BY_REPOSITORY), - "{}", - sync.stderr - ); - assert_headers_unavailable(spawn_headers(&sandbox, &nested, None)); -} - -#[test] -fn explicit_config_cannot_enable_access_the_global_config_forbids() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - let repository = bound_repository(&sandbox); - let explicit = sandbox.dir.path().join("explicit-config.json"); - write_config_file( - &explicit, - &serde_json::json!({ - "auth": { "mode": "optional" }, - "telemetry": { "enabled": true }, - }), - ); - assert_headers_served(spawn_headers(&sandbox, &repository, Some(&explicit))); - - sandbox.write_global_config(&serde_json::json!({ - "auth": { "mode": "disabled" }, - "telemetry": { "enabled": false }, - })); - assert_headers_unavailable(spawn_headers(&sandbox, &repository, Some(&explicit))); - assert_eq!( - hook_fallback_reasons(&sandbox, &repository, Some(&explicit), "logs-explicit"), - ["disabled_by_config"] - ); - let sync = run_cli( - &sandbox, - &repository, - &["sce", "sync", "--format", "json"], - Some(&explicit), - ); - assert!(!sync.success, "{}", sync.stdout); - assert!( - sync.stderr.contains(AUTH_DISABLED_BY_GLOBAL), - "{}", - sync.stderr - ); - - let show = run_cli( - &sandbox, - &repository, - &[ - "sce", - "config", - "show", - "--config", - explicit.to_str().expect("utf-8 path"), - "--format", - "json", - ], - None, - ); - assert!(show.success, "{}", show.stderr); - for expected in [ - r#""state": "disabled""#, - r#""reason": "auth_disabled""#, - r#""config_source": "default_discovered_global""#, - ] { - assert!( - show.stdout.contains(expected), - "{expected}: {}", - show.stdout - ); - } -} - -#[test] -fn claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - sandbox.seed(); - let state = sandbox.sce_state_dir(); - let auth_db = std::fs::read(state.join("auth.db")).expect("seeded auth DB"); - - assert_eq!( - policy_hook_fallback_reasons(&sandbox, false), - ["disabled_by_config"] - ); - assert_eq!( - policy_hook_fallback_reasons(&sandbox, true), - ["database_error"] - ); - assert_eq!( - std::fs::read(state.join("auth.db")).expect("auth DB"), - auth_db - ); -} - -#[test] -fn every_claude_hook_entry_point_records_its_command_identity() { - let _fan_out = serialize_fan_out(); - let sandbox = Sandbox::new(); - std::fs::create_dir_all(sandbox.dir.path().join("work")).expect("work dir"); - tokio::runtime::Builder::new_multi_thread() - .worker_threads(4) - .enable_all() - .build() - .expect("test runtime") - .block_on(export_hook_entry_spans(&sandbox)); -} - -fn hook_stdin_cases(command: ClaudeHookCommand) -> [(Vec, String); 4] { - let tool_use_id = format!("toolu_entry_{}", command.as_str()); - let valid = serde_json::json!({ - "hook_event_name": "PreToolUse", - "tool_name": "Bash", - "session_id": "session-entry", - "tool_use_id": tool_use_id, - "tool_input": { "command": "true" }, - }) - .to_string(); - [ - (valid.into_bytes(), tool_use_id), - (Vec::new(), String::new()), - ( - format!("{{\"tool_use_id\":\"{STDIN_SECRET}").into_bytes(), - String::new(), - ), - ( - [b"\xff\xfe".as_slice(), STDIN_SECRET.as_bytes()].concat(), - String::new(), - ), - ] -} - -async fn export_hook_entry_spans(sandbox: &Sandbox) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("bind"); - let address = listener.local_addr().expect("addr"); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let receiver = tokio::spawn(capture_requests_until(listener, stopped)); - - let mut expected = Vec::new(); - let mut hooks = Vec::new(); - for (index, command) in HOOK_COMMANDS.iter().enumerate() { - for (stdin, tool_use_id) in hook_stdin_cases(*command) { - let mut child = sandbox - .command("hook-entry") - .current_dir(sandbox.dir.path().join("work")) - .env(COLLECTOR_ENV, address.to_string()) - .env(HOOK_INDEX_ENV, index.to_string()) - .stdin(Stdio::piped()) - .spawn() - .expect("spawn hook entry"); - let mut child_stdin = child.stdin.take().expect("hook entry stdin"); - child_stdin.write_all(&stdin).expect("write hook stdin"); - drop(child_stdin); - hooks.push(child); - expected.push((command.as_str().to_string(), tool_use_id)); - } - } - tokio::task::spawn_blocking(move || { - for child in hooks { - wait_success("hook-entry", child); - } - }) - .await - .expect("hook entry children join"); - stop.send(()).expect("stop collector"); - - let requests = receiver.await.expect("collector join"); - for request in &requests { - let body = String::from_utf8_lossy(&request.body); - assert!(!body.contains(STDIN_SECRET), "hook payload leaked"); - assert!(!body.contains("bao-token-value"), "token leaked"); - } - let mut observed = Vec::new(); - for span in trace_spans(&requests) - .iter() - .filter(|span| span.name == "sce.hook") - { - let attribute = |key: &str| { - span.attributes - .iter() - .find(|(name, _)| name == key) - .map(|(_, value)| value.clone()) - .unwrap_or_default() - }; - let command = attribute("sce.hook.command"); - let tool_use_id = attribute("sce.claude.tool_use_id"); - let outcome = attribute("sce.outcome"); - if FAIL_OPEN_HOOK_COMMANDS - .iter() - .any(|hook| hook.as_str() == command) - { - assert_eq!(outcome, "success", "{command} must fail open"); - } - if command == ClaudeHookCommand::PolicyBash.as_str() && tool_use_id.is_empty() { - assert_eq!(outcome, "failure", "malformed policy-bash input must fail"); - } - observed.push((command, tool_use_id)); - } - observed.sort(); - expected.sort(); - assert_eq!(observed, expected); -} - -async fn run_hook_entry_child() { - let index = std::env::var(HOOK_INDEX_ENV) - .expect("hook index") - .parse::() - .expect("numeric hook index"); - let address = std::env::var(COLLECTOR_ENV) - .expect("collector address") - .parse() - .expect("socket address"); - let telemetry = loopback_hook_telemetry(address, "bao-token-value"); - let command = HOOK_COMMANDS[index]; - let _ = telemetry - .with_default_subscriber(&mut || async move { - let subcommand = match command { - ClaudeHookCommand::DiffTrace => HookSubcommand::DiffTrace, - ClaudeHookCommand::ConversationTrace => HookSubcommand::ConversationTrace, - ClaudeHookCommand::ClaudeMutationScope => HookSubcommand::ClaudeMutationScope, - ClaudeHookCommand::ClaudeModelState => HookSubcommand::ClaudeModelState, - ClaudeHookCommand::PolicyBash => { - return run_bash_policy_request(&BashPolicyRequest { - input: PolicyInputMode::ClaudePreToolUse, - output: PolicyOutputMode::ClaudeHook, - }); - } - }; - run_hooks_subcommand(&subcommand, None::<&NoopLogger>) - .await - .map_err(CliError::runtime) - }) - .await; - telemetry.shutdown().await; -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn auth_db_child_process() { - let Ok(role) = std::env::var(ROLE_ENV) else { - return; - }; - match role.as_str() { - "seed" => seed().await, - "hold-open" => { - let _db = AuthDb::new().await.expect("holder opens auth DB"); - wait_for_release(); - } - "hold-write" => { - let db = AuthDb::new().await.expect("writer opens auth DB"); - db.execute("BEGIN IMMEDIATE", ()) - .await - .expect("writer takes write lock"); - wait_for_release(); - db.execute("ROLLBACK", ()).await.expect("writer rollback"); - } - "read" => { - let credential = load_telemetry_credential() - .await - .expect("credential lookup succeeds") - .into_valid() - .expect("credential present"); - println!("{TOKEN_PREFIX}{}", credential.token); - } - "telemetry-health" => { - let label = match inspect_health(true).await { - ManagedTelemetryHealth::Healthy => "healthy", - ManagedTelemetryHealth::Disabled(reason) => reason.as_str(), - ManagedTelemetryHealth::DisabledByConfig { .. } => "disabled_by_config", - }; - println!("{HEALTH_PREFIX}{label}"); - } - "lookup-missing" => { - assert_eq!( - load_telemetry_credential() - .await - .expect("missing auth DB is not an error"), - TelemetryCredentialLookup::Missing - ); - assert!(!auth_db_path().expect("auth DB path").exists()); - } - "setup-fresh" | "setup-existing" => { - use crate::services::lifecycle::ServiceLifecycle; - let path = auth_db_path().expect("auth DB path"); - let before = std::fs::read(&path).ok(); - assert_eq!(before.is_some(), role == "setup-existing"); - super::lifecycle::AuthDbLifecycle - .setup(&NoRepositoryContext) - .await - .expect("setup needs no auth DB key"); - assert!(path.parent().expect("auth DB parent").is_dir()); - assert_eq!(std::fs::read(&path).ok(), before); - } - "create-outdated" | "lookup-outdated" | "verify-outdated" | "lookup-then-migrate" => { - run_outdated_schema_child(&role).await; - } - "create-schemaless" => { - let db = EncryptedTursoDb::::new() - .await - .expect("schemaless auth DB opens"); - assert!(applied_migrations(&db).await.is_empty()); - } - "init" => { - let db = AuthDb::new().await.expect("initializer opens auth DB"); - assert_eq!(applied_migrations(&db).await.len(), expected_migrations()); - } - "verify-schema" => { - let db = AuthDb::new().await.expect("verifier opens auth DB"); - assert_eq!(applied_migrations(&db).await.len(), expected_migrations()); - let check = db - .query_map("PRAGMA integrity_check", (), |row| { - row.get::(0).map_err(Into::into) - }) - .await - .expect("integrity check"); - assert_eq!(check, vec!["ok".to_string()]); - } - "upgrade" => upgrade_outdated_schema().await, - "partial" => reject_partial_schema().await, - "verify-rows" => print_verified_rows().await, - "coordinated-writer" => run_coordinated_writer_child().await, - "hook-entry" => run_hook_entry_child().await, - "policy-hook" => { - let _ = Box::pin(crate::app::run( - ["sce", "hooks", "claude-model-state"] - .into_iter() - .map(String::from), - )) - .await; - } - other => run_binding_child(other).await, - } -} - -async fn run_binding_child(role: &str) { - match role { - "repository-lookup-missing" => { - assert_eq!( - load_repository_telemetry_credential("repo-missing".to_string()) - .await - .expect("missing auth DB is not an error"), - None - ); - assert_eq!( - load_telemetry_credential() - .await - .expect("missing auth DB is not an error"), - TelemetryCredentialLookup::Missing - ); - } - "hook-resolve" => { - let (telemetry, fallback) = RuntimeTelemetry::resolve_when_enabled( - true, - load_telemetry_credential(), - ManagedSpanKind::ClaudeHook, - ) - .await; - let label = match (&telemetry, fallback) { - (RuntimeTelemetry::Managed(_), None) => HOOK_CREDENTIAL_VALID, - (_, Some(fallback)) - if fallback.reason == TelemetryFallbackReason::ExporterInitFailed => - { - HOOK_CREDENTIAL_VALID - } - (_, Some(fallback)) => fallback.reason.as_str(), - (RuntimeTelemetry::Noop(_), None) => "noop", - }; - telemetry.shutdown().await; - println!("{HOOK_TELEMETRY_PREFIX}{label}"); - } - "seed-expired-credential" => save_telemetry_credential(&TelemetryCredential { - token: TOKEN.to_string(), - accessor: "accessor-multiprocess".to_string(), - expires_at_unix_seconds: 1, - identity: TelemetryIdentity { - user_id: USER_ID.to_string(), - workspace_id: WORKSPACE_ID.to_string(), - }, - }) - .await - .expect("expired telemetry credential seeds"), - "delete-telemetry-credential" => { - assert!(delete_telemetry_credential() - .await - .expect("telemetry credential deletes")); - } - "bind" => { - let repository_id = repository_id_for(&std::env::current_dir().expect("cwd")) - .expect("repository identity"); - assert!( - bind_repository_telemetry(repository_id, RepositoryBindingMode::Enroll) - .await - .expect("binding succeeds") - ); - } - "cli" => { - let args = std::env::var(CLI_ARGS_ENV).expect("cli args"); - let code = Box::pin(crate::app::run(args.split('\n').map(String::from))).await; - println!(); - println!( - "{CLI_SUCCESS_PREFIX}{}", - code == std::process::ExitCode::SUCCESS - ); - } - "headers" => { - let code = Box::pin(crate::app::run( - ["sce", "auth", "telemetry-headers"] - .into_iter() - .map(String::from), - )) - .await; - println!(); - if code != std::process::ExitCode::SUCCESS { - assert_eq!(code, std::process::ExitCode::from(4)); - } - } - other => panic!("unknown child role {other}"), - } -} - -async fn run_coordinated_writer_child() { - let db = AuthDb::new() - .await - .expect("coordinated writer opens auth DB"); - wait_for_release(); - for row in writer_rows() { - db.execute(INSERT_BINDING_SQL, (row.as_str(), USER_ID, WORKSPACE_ID)) - .await - .unwrap_or_else(|error| panic!("writer failed at {row}: {error:#}")); - println!("{COMMITTED_PREFIX}{row}"); - tokio::time::sleep(WRITER_PAUSE).await; - } - wait_for_release(); -} - -async fn seed() { - let db = AuthDb::new().await.expect("seed opens auth DB"); - db.execute( - "INSERT OR REPLACE INTO auth_credentials \ - (id, access_token, token_type, expires_in, refresh_token, scope, stored_at_unix_seconds) \ - VALUES (1, ?1, 'Bearer', 3600, 'refresh', NULL, 1)", - (test_access_token(USER_ID, Some(WORKSPACE_ID)),), - ) - .await - .expect("session seeds"); - drop(db); - save_telemetry_credential(&TelemetryCredential { - token: TOKEN.to_string(), - accessor: "accessor-multiprocess".to_string(), - expires_at_unix_seconds: FAR_FUTURE, - identity: TelemetryIdentity { - user_id: USER_ID.to_string(), - workspace_id: WORKSPACE_ID.to_string(), - }, - }) - .await - .expect("telemetry credential seeds"); -} - -fn writer_rows() -> Vec { - let writer = std::env::var(WRITER_ENV).expect("writer id"); - (0..WRITER_ROWS) - .map(|row| format!("{writer}-{row:02}")) - .collect() -} - -async fn print_verified_rows() { - let db = AuthDb::new().await.expect("verifier opens auth DB"); - assert_credential_rows_intact(&db).await; - for row in db - .query_map( - "SELECT repository_id FROM telemetry_repository_bindings ORDER BY repository_id", - (), - |row| row.get::(0).map_err(Into::into), - ) - .await - .expect("binding rows") - { - println!("{ROW_PREFIX}{row}"); - } -} - -async fn assert_credential_rows_intact(db: &AuthDb) { - let tokens = db - .query_map( - "SELECT token, user_id, workspace_id FROM telemetry_credentials", - (), - |row| { - Ok(( - row.get::(0)?, - row.get::(1)?, - row.get::(2)?, - )) - }, - ) - .await - .expect("telemetry credential rows"); - assert_eq!( - tokens, - vec![( - TOKEN.to_string(), - USER_ID.to_string(), - WORKSPACE_ID.to_string() - )] - ); - let sessions = db - .query_map("SELECT access_token FROM auth_credentials", (), |row| { - row.get::(0).map_err(Into::into) - }) - .await - .expect("session rows"); - assert_eq!( - sessions, - vec![test_access_token(USER_ID, Some(WORKSPACE_ID))] - ); - let check = db - .query_map("PRAGMA integrity_check", (), |row| { - row.get::(0).map_err(Into::into) - }) - .await - .expect("integrity check"); - assert_eq!(check, vec!["ok".to_string()]); -} - -fn wait_for_release() { - println!("{READY}"); - let mut line = String::new(); - let _ = std::io::stdin().read_line(&mut line); -} - -fn expected_migrations() -> usize { - generated_migrations::AUTH_MIGRATIONS.len() -} - -async fn applied_migrations(db: &EncryptedTursoDb) -> Vec { - db.query_map("SELECT id FROM __sce_migrations ORDER BY id", (), |row| { - row.get::(0).map_err(Into::into) - }) - .await - .expect("migration ids") -} - -async fn run_outdated_schema_child(role: &str) { - match role { - "create-outdated" | "verify-outdated" => { - let db = EncryptedTursoDb::::new() - .await - .expect("pre-binding schema opens"); - assert_eq!(applied_migrations(&db).await.len(), PRE_BINDING_MIGRATIONS); - } - "lookup-outdated" => assert_outdated_lookups_are_unusable().await, - "lookup-then-migrate" => { - assert_outdated_lookups_are_unusable().await; - let db = crate::services::token_storage::open_or_create_auth_db() - .await - .expect("interactive open migrates outdated auth DB"); - assert_eq!(applied_migrations(db).await.len(), expected_migrations()); - assert_eq!( - load_telemetry_credential() - .await - .expect("lookup after migration"), - TelemetryCredentialLookup::Missing - ); - } - other => panic!("unknown outdated-schema child role: {other}"), - } -} - -async fn assert_outdated_lookups_are_unusable() { - assert_eq!( - load_telemetry_credential() - .await - .expect("outdated auth DB lookup is not an error"), - TelemetryCredentialLookup::Unusable - ); - assert_eq!( - load_repository_telemetry_credential(HEADERS_REPOSITORY.to_string()) - .await - .expect("outdated auth DB repository lookup is not an error"), - None - ); -} - -async fn upgrade_outdated_schema() { - let old = EncryptedTursoDb::::new() - .await - .expect("pre-binding schema opens"); - assert_eq!(applied_migrations(&old).await.len(), PRE_BINDING_MIGRATIONS); - drop(old); - let db = AuthDb::new().await.expect("outdated schema upgrades"); - assert_eq!(applied_migrations(&db).await.len(), expected_migrations()); - db.query_map( - "SELECT user_id, workspace_id FROM telemetry_credentials", - (), - |_| Ok(()), - ) - .await - .expect("binding columns exist"); -} - -async fn reject_partial_schema() { - let old = EncryptedTursoDb::::new() - .await - .expect("pre-binding schema opens"); - old.execute( - "ALTER TABLE telemetry_credentials ADD COLUMN user_id TEXT NOT NULL DEFAULT ''", - (), - ) - .await - .expect("partial migration applies"); - drop(old); - let error = AuthDb::new() - .await - .err() - .expect("partially migrated schema must not open"); - let chain = format!("{error:#}"); - assert!(chain.contains(BINDING_MIGRATION_ID), "{chain}"); - let old = EncryptedTursoDb::::new() - .await - .expect("pre-binding schema reopens"); - assert_eq!(applied_migrations(&old).await.len(), PRE_BINDING_MIGRATIONS); -} diff --git a/cli/src/services/config/render.rs b/cli/src/services/config/render.rs index d2b7332fa..4abed0f74 100644 --- a/cli/src/services/config/render.rs +++ b/cli/src/services/config/render.rs @@ -12,7 +12,7 @@ use super::types::{ }; use super::{ConfigPathSource, ReportFormat, ResolvedOptionalValue, ResolvedValue, ValueSource}; -const TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE: &str = "Claude Code telemetry settings written by earlier sce setup runs are not changed by telemetry.enabled."; +const TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE: &str = "Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place."; #[allow(clippy::too_many_lines)] pub(super) fn format_show_output(runtime: &RuntimeConfig, report_format: ReportFormat) -> String { @@ -662,264 +662,3 @@ fn format_database_retry_json(value: &ResolvedOptionalValue "config_source": value.source.and_then(ValueSource::config_source).map(ConfigPathSource::as_str), }) } - -#[cfg(test)] -mod tests { - use std::path::{Path, PathBuf}; - - use serde_json::{json, Value}; - - use super::{ - format_show_output, format_validate_output, TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, - }; - use crate::services::config::resolver::{ - resolve_runtime_config_with, RuntimeConfig, - WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT, - WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED, - }; - use crate::services::config::{ConfigRequest, ReportFormat}; - - const GLOBAL_PATH: &str = "/tmp/render-policy-global/sce/config.json"; - const LOCAL_PATH: &str = "/tmp/render-policy-repo/.sce/config.json"; - - struct PolicyCase { - name: &'static str, - global: &'static str, - local: &'static str, - text_lines: Vec, - auth_json: Value, - telemetry_json: Value, - warnings: Vec, - } - - fn discovered_paths_exist(path: &Path) -> bool { - path == Path::new(GLOBAL_PATH) || path == Path::new(LOCAL_PATH) - } - - fn resolve(global: &'static str, local: &'static str) -> RuntimeConfig { - resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: None, - log_level: None, - }, - Path::new("/tmp/render-policy-repo"), - |_| None, - move |path| { - if path == Path::new(GLOBAL_PATH) { - Ok(global.to_string()) - } else { - Ok(local.to_string()) - } - }, - discovered_paths_exist, - || Ok(PathBuf::from(GLOBAL_PATH)), - ) - .unwrap() - } - - fn strip_ansi(text: &str) -> String { - let mut stripped = String::with_capacity(text.len()); - let mut chars = text.chars(); - while let Some(ch) = chars.next() { - if ch == '\u{1b}' { - for next in chars.by_ref() { - if next == 'm' { - break; - } - } - } else { - stripped.push(ch); - } - } - stripped - } - - fn policy_text_block(output: &str) -> Vec { - let lines = strip_ansi(output) - .lines() - .map(str::to_string) - .collect::>(); - let start = lines - .iter() - .position(|line| line.starts_with("- agent_trace.auto_sync:")) - .expect("show output should list agent_trace.auto_sync") - + 1; - let end = lines - .iter() - .position(|line| line.starts_with("- otel.endpoint:")) - .expect("show output should list otel.endpoint"); - lines[start..end].to_vec() - } - - fn resolved_json(source: &str, config_source: Option<&str>, value: &Value) -> Value { - json!({ - "value": value, - "source": source, - "config_source": config_source, - }) - } - - fn policy_cases() -> Vec { - let note_line = format!("- telemetry.note: {TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE}"); - vec![ - PolicyCase { - name: "default", - global: "{}", - local: "{}", - text_lines: vec![ - "- auth.mode: optional (source: default)".to_string(), - "- telemetry.enabled: false (source: default)".to_string(), - "- telemetry.effective: disabled (reason: not_enabled)".to_string(), - note_line.clone(), - ], - auth_json: json!({ - "mode": resolved_json("default", None, &json!("optional")), - }), - telemetry_json: json!({ - "enabled": resolved_json("default", None, &json!(false)), - "effective": {"state": "disabled", "reason": "not_enabled"}, - "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, - }), - warnings: Vec::new(), - }, - PolicyCase { - name: "user-enabled", - global: r#"{"telemetry":{"enabled":true}}"#, - local: "{}", - text_lines: vec![ - "- auth.mode: optional (source: default)".to_string(), - "- telemetry.enabled: true (source: config_file, config_source: default_discovered_global)".to_string(), - "- telemetry.effective: enabled".to_string(), - ], - auth_json: json!({ - "mode": resolved_json("default", None, &json!("optional")), - }), - telemetry_json: json!({ - "enabled": resolved_json("config_file", Some("default_discovered_global"), &json!(true)), - "effective": {"state": "enabled", "reason": null}, - "note": null, - }), - warnings: Vec::new(), - }, - PolicyCase { - name: "repo-only-enabled", - global: "{}", - local: r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, - text_lines: vec![ - "- auth.mode: mandatory (source: config_file, config_source: default_discovered_local)".to_string(), - "- telemetry.enabled: true (source: config_file, config_source: default_discovered_local)".to_string(), - "- telemetry.effective: disabled (reason: no_user_consent)".to_string(), - note_line.clone(), - ], - auth_json: json!({ - "mode": resolved_json("config_file", Some("default_discovered_local"), &json!("mandatory")), - }), - telemetry_json: json!({ - "enabled": resolved_json("config_file", Some("default_discovered_local"), &json!(true)), - "effective": {"state": "disabled", "reason": "no_user_consent"}, - "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, - }), - warnings: vec![WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string()], - }, - PolicyCase { - name: "auth-disabled-with-telemetry", - global: r#"{"auth":{"mode":"disabled"},"telemetry":{"enabled":true}}"#, - local: "{}", - text_lines: vec![ - "- auth.mode: disabled (source: config_file, config_source: default_discovered_global)".to_string(), - "- telemetry.enabled: true (source: config_file, config_source: default_discovered_global)".to_string(), - "- telemetry.effective: disabled (reason: auth_disabled)".to_string(), - note_line, - ], - auth_json: json!({ - "mode": resolved_json("config_file", Some("default_discovered_global"), &json!("disabled")), - }), - telemetry_json: json!({ - "enabled": resolved_json("config_file", Some("default_discovered_global"), &json!(true)), - "effective": {"state": "disabled", "reason": "auth_disabled"}, - "note": TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE, - }), - warnings: vec![WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string()], - }, - ] - } - - fn warnings_text_line(warnings: &[String]) -> String { - if warnings.is_empty() { - "Validation warnings: none".to_string() - } else { - format!("Validation warnings: {}", warnings.join(" | ")) - } - } - - #[test] - fn show_text_reports_access_policy_after_agent_trace_and_lists_policy_warnings() { - for case in policy_cases() { - let runtime = resolve(case.global, case.local); - let output = format_show_output(&runtime, ReportFormat::Text); - - assert_eq!(policy_text_block(&output), case.text_lines, "{}", case.name); - assert_eq!( - strip_ansi(&output).lines().last(), - Some(warnings_text_line(&case.warnings).as_str()), - "{}", - case.name - ); - } - } - - #[test] - fn show_json_reports_resolved_auth_and_telemetry_policy() { - for case in policy_cases() { - let runtime = resolve(case.global, case.local); - let payload: Value = - serde_json::from_str(&format_show_output(&runtime, ReportFormat::Json)).unwrap(); - let resolved = &payload["result"]["resolved"]; - - assert_eq!(resolved["auth"], case.auth_json, "{}", case.name); - assert_eq!(resolved["telemetry"], case.telemetry_json, "{}", case.name); - assert_eq!( - payload["result"]["warnings"], - json!(case.warnings), - "{}", - case.name - ); - } - } - - #[test] - fn validate_lists_policy_warnings_without_policy_fields() { - for case in policy_cases() { - let runtime = resolve(case.global, case.local); - let text = strip_ansi(&format_validate_output(&runtime, ReportFormat::Text)); - let payload: Value = - serde_json::from_str(&format_validate_output(&runtime, ReportFormat::Json)) - .unwrap(); - - assert_eq!( - text, - format!( - "SCE config validation: valid\nValidation issues: none\n{}", - warnings_text_line(&case.warnings) - ), - "{}", - case.name - ); - assert_eq!( - payload, - json!({ - "status": "ok", - "result": { - "command": "config_validate", - "valid": true, - "issues": [], - "warnings": case.warnings, - } - }), - "{}", - case.name - ); - } - } -} diff --git a/cli/src/services/config/resolver.rs b/cli/src/services/config/resolver.rs index 7a7fe8d63..1786e524f 100644 --- a/cli/src/services/config/resolver.rs +++ b/cli/src/services/config/resolver.rs @@ -1417,777 +1417,3 @@ mod tests { ); } } - -#[cfg(test)] -mod access_policy_tests { - use std::path::{Path, PathBuf}; - - use super::*; - - const GLOBAL_PATH: &str = "/tmp/policy-global/sce/config.json"; - const LOCAL_PATH: &str = "/tmp/policy-repo/.sce/config.json"; - const EXPLICIT_PATH: &str = "/tmp/policy-explicit.json"; - - #[derive(Clone, Copy, Debug)] - enum Decider { - Default, - User, - Repository, - } - - fn layer( - source: ConfigPathSource, - auth_mode: Option, - telemetry: Option, - ) -> AccessPolicyLayer { - AccessPolicyLayer { - auth_mode: auth_mode.map(|value| schema::FileConfigValue { value, source }), - telemetry_enabled: telemetry.map(|value| schema::FileConfigValue { value, source }), - } - } - - fn user(auth_mode: Option, telemetry: Option) -> AccessPolicyLayer { - layer( - ConfigPathSource::DefaultDiscoveredGlobal, - auth_mode, - telemetry, - ) - } - - fn repository(auth_mode: Option, telemetry: Option) -> AccessPolicyLayer { - layer( - ConfigPathSource::DefaultDiscoveredLocal, - auth_mode, - telemetry, - ) - } - - fn decider_source(decider: Decider) -> ValueSource { - match decider { - Decider::Default => ValueSource::Default, - Decider::User => ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), - Decider::Repository => { - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) - } - } - } - - #[test] - fn access_policy_auth_mode_most_restrictive_layer_wins() { - use AuthMode::{Disabled, Mandatory, Optional}; - use Decider::{Default, Repository, User}; - - let cases = [ - (None, None, Optional, Default), - (None, Some(Disabled), Disabled, Repository), - (None, Some(Optional), Optional, Repository), - (None, Some(Mandatory), Mandatory, Repository), - (Some(Disabled), None, Disabled, User), - (Some(Disabled), Some(Disabled), Disabled, Repository), - (Some(Disabled), Some(Optional), Disabled, User), - (Some(Disabled), Some(Mandatory), Disabled, User), - (Some(Optional), None, Optional, User), - (Some(Optional), Some(Disabled), Disabled, Repository), - (Some(Optional), Some(Optional), Optional, Repository), - (Some(Optional), Some(Mandatory), Mandatory, Repository), - (Some(Mandatory), None, Mandatory, User), - (Some(Mandatory), Some(Disabled), Disabled, Repository), - (Some(Mandatory), Some(Optional), Mandatory, User), - (Some(Mandatory), Some(Mandatory), Mandatory, Repository), - ]; - - for (user_mode, repository_mode, expected_mode, decider) in cases { - for degraded in [false, true] { - let policy = resolve_access_policy( - &user(user_mode, None), - &repository(repository_mode, None), - &AccessPolicyLayer::default(), - degraded, - ); - let case = format!( - "user={user_mode:?} repository={repository_mode:?} degraded={degraded}" - ); - - assert_eq!(policy.auth_mode.value, expected_mode, "{case}"); - assert_eq!(policy.auth_mode.source, decider_source(decider), "{case}"); - assert_eq!(policy.auth_allowed(), expected_mode != Disabled, "{case}"); - assert_eq!( - policy.background_cloud_allowed, - expected_mode != Disabled && !degraded, - "{case}" - ); - assert_eq!( - policy.auto_sync_allowed(true), - policy.background_cloud_allowed, - "{case}" - ); - assert!(!policy.auto_sync_allowed(false), "{case}"); - } - } - } - - #[test] - fn access_policy_telemetry_requires_user_consent_and_honors_opt_outs() { - use TelemetryDisabledReason::{ - AuthDisabled, InvalidConfig, NoUserConsent, NotEnabled, RepositoryOptOut, UserOptOut, - }; - use TelemetryPolicyState::{Disabled, Enabled}; - - let base_cases = [ - (None, None, Disabled(NotEnabled), false, Decider::Default), - ( - None, - Some(true), - Disabled(NoUserConsent), - true, - Decider::Repository, - ), - ( - None, - Some(false), - Disabled(RepositoryOptOut), - false, - Decider::Repository, - ), - (Some(true), None, Enabled, true, Decider::User), - (Some(true), Some(true), Enabled, true, Decider::Repository), - ( - Some(true), - Some(false), - Disabled(RepositoryOptOut), - false, - Decider::Repository, - ), - ( - Some(false), - None, - Disabled(UserOptOut), - false, - Decider::User, - ), - ( - Some(false), - Some(true), - Disabled(UserOptOut), - true, - Decider::Repository, - ), - ( - Some(false), - Some(false), - Disabled(UserOptOut), - false, - Decider::Repository, - ), - ]; - - for (user_telemetry, repository_telemetry, base_state, configured, decider) in base_cases { - for degraded in [false, true] { - for auth_disabled in [false, true] { - let user_mode = auth_disabled.then_some(AuthMode::Disabled); - let policy = resolve_access_policy( - &user(user_mode, user_telemetry), - &repository(None, repository_telemetry), - &AccessPolicyLayer::default(), - degraded, - ); - let expected = if degraded { - Disabled(InvalidConfig) - } else if auth_disabled { - Disabled(AuthDisabled) - } else { - base_state - }; - let case = format!( - "user={user_telemetry:?} repository={repository_telemetry:?} degraded={degraded} auth_disabled={auth_disabled}" - ); - - assert_eq!(policy.telemetry, expected, "{case}"); - assert_eq!(policy.telemetry_enabled(), expected == Enabled, "{case}"); - assert_eq!(policy.telemetry_enabled.value, configured, "{case}"); - assert_eq!( - policy.telemetry_enabled.source, - decider_source(decider), - "{case}" - ); - } - } - } - } - - #[test] - fn access_policy_repository_auth_disabled_forces_telemetry_off() { - let policy = resolve_access_policy( - &user(None, Some(true)), - &repository(Some(AuthMode::Disabled), None), - &AccessPolicyLayer::default(), - false, - ); - - assert_eq!( - policy.telemetry, - TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) - ); - assert!(!policy.background_cloud_allowed); - } - - #[test] - fn access_policy_warnings_are_deterministic_and_ordered() { - let user_layer = user(Some(AuthMode::Disabled), None); - let repository_layer = repository(Some(AuthMode::Mandatory), Some(true)); - let explicit_layer = AccessPolicyLayer::default(); - let policy = resolve_access_policy(&user_layer, &repository_layer, &explicit_layer, true); - - assert_eq!( - build_access_policy_warnings( - &user_layer, - &repository_layer, - &explicit_layer, - &policy, - true, - true - ), - vec![ - WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), - WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string(), - WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string(), - WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string(), - WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string(), - ] - ); - - let consenting_user = user(Some(AuthMode::Optional), Some(true)); - let consenting_policy = - resolve_access_policy(&consenting_user, &repository_layer, &explicit_layer, false); - assert!(build_access_policy_warnings( - &consenting_user, - &repository_layer, - &explicit_layer, - &consenting_policy, - true, - false, - ) - .is_empty()); - - let restricting_user = user(Some(AuthMode::Mandatory), Some(false)); - let silent_repository = repository(None, None); - let permissive_explicit = - layer(ConfigPathSource::Flag, Some(AuthMode::Optional), Some(true)); - let overridden_policy = resolve_access_policy( - &restricting_user, - &silent_repository, - &permissive_explicit, - false, - ); - assert_eq!( - build_access_policy_warnings( - &restricting_user, - &silent_repository, - &permissive_explicit, - &overridden_policy, - false, - false, - ), - vec![ - WARNING_EXPLICIT_AUTH_MODE_OVERRIDDEN.to_string(), - WARNING_EXPLICIT_TELEMETRY_OVERRIDDEN.to_string(), - ] - ); - } - - fn discovered_paths_exist(path: &Path) -> bool { - path == Path::new(GLOBAL_PATH) || path == Path::new(LOCAL_PATH) - } - - fn resolve_discovered(global: &'static str, local: &'static str) -> RuntimeConfig { - resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: None, - log_level: None, - }, - Path::new("/tmp/policy-repo"), - |_| None, - move |path| { - if path == Path::new(GLOBAL_PATH) { - Ok(global.to_string()) - } else { - Ok(local.to_string()) - } - }, - discovered_paths_exist, - || Ok(PathBuf::from(GLOBAL_PATH)), - ) - .unwrap() - } - - fn all_policy_paths_exist(path: &Path) -> bool { - [GLOBAL_PATH, LOCAL_PATH, EXPLICIT_PATH] - .iter() - .any(|candidate| path == Path::new(candidate)) - } - - fn resolve_with_explicit( - source: ConfigPathSource, - global: &'static str, - repository: &'static str, - explicit: &'static str, - ) -> RuntimeConfig { - let request = ConfigRequest { - config_path: (source == ConfigPathSource::Flag).then(|| PathBuf::from(EXPLICIT_PATH)), - report_format: ReportFormat::Text, - log_level: None, - }; - resolve_runtime_config_with( - &request, - Path::new("/tmp/policy-repo"), - move |key| { - (source == ConfigPathSource::Env && key == "SCE_CONFIG_FILE") - .then(|| EXPLICIT_PATH.to_string()) - }, - move |path| { - Ok(if path == Path::new(GLOBAL_PATH) { - global - } else if path == Path::new(LOCAL_PATH) { - repository - } else { - explicit - } - .to_string()) - }, - all_policy_paths_exist, - || Ok(PathBuf::from(GLOBAL_PATH)), - ) - .unwrap() - } - - #[test] - fn explicit_config_cannot_bypass_global_or_repository_restrictions() { - use TelemetryDisabledReason::{AuthDisabled, InvalidConfig, RepositoryOptOut, UserOptOut}; - use TelemetryPolicyState::{Disabled, Enabled}; - - #[derive(Clone, Copy, Debug)] - enum Deciding { - Default, - Global, - Repository, - Explicit, - } - - const TELEMETRY_ON: &str = r#"{"telemetry":{"enabled":true}}"#; - const TELEMETRY_OFF: &str = r#"{"telemetry":{"enabled":false}}"#; - let cases = [ - ( - TELEMETRY_OFF, - "{}", - TELEMETRY_ON, - AuthMode::Optional, - Deciding::Default, - Disabled(UserOptOut), - ), - ( - r#"{"auth":{"mode":"disabled"}}"#, - "{}", - r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, - AuthMode::Disabled, - Deciding::Global, - Disabled(AuthDisabled), - ), - ( - TELEMETRY_ON, - TELEMETRY_OFF, - TELEMETRY_ON, - AuthMode::Optional, - Deciding::Default, - Disabled(RepositoryOptOut), - ), - ( - r#"{"auth":{"mode":"optional"}}"#, - r#"{"auth":{"mode":"disabled"}}"#, - r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, - AuthMode::Disabled, - Deciding::Repository, - Disabled(AuthDisabled), - ), - ( - TELEMETRY_OFF, - TELEMETRY_ON, - TELEMETRY_ON, - AuthMode::Optional, - Deciding::Default, - Disabled(UserOptOut), - ), - ( - "{}", - "{}", - r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, - AuthMode::Mandatory, - Deciding::Explicit, - Enabled, - ), - ( - r#"{"telemetry":{"enabled":"no"}}"#, - "{}", - TELEMETRY_ON, - AuthMode::Optional, - Deciding::Default, - Disabled(InvalidConfig), - ), - ]; - - for (global, repository, explicit, auth_mode, deciding, telemetry) in cases { - for source in [ConfigPathSource::Flag, ConfigPathSource::Env] { - let runtime = resolve_with_explicit(source, global, repository, explicit); - let policy = &runtime.access_policy; - let case = format!( - "global={global} repository={repository} explicit={explicit} source={source:?}" - ); - let expected_auth_source = match deciding { - Deciding::Default => ValueSource::Default, - Deciding::Global => { - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) - } - Deciding::Repository => { - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal) - } - Deciding::Explicit => ValueSource::ConfigFile(source), - }; - let cloud_allowed = - auth_mode != AuthMode::Disabled && telemetry != Disabled(InvalidConfig); - - assert_eq!(policy.auth_mode.value, auth_mode, "{case}"); - assert_eq!(policy.auth_mode.source, expected_auth_source, "{case}"); - assert_eq!(policy.telemetry, telemetry, "{case}"); - assert_eq!(policy.background_cloud_allowed, cloud_allowed, "{case}"); - } - } - } - - #[test] - fn explicit_config_keeps_replacing_discovered_ordinary_values() { - for source in [ConfigPathSource::Flag, ConfigPathSource::Env] { - let runtime = resolve_with_explicit( - source, - r#"{"log_level":"warn","agent_trace":{"auto_sync":true}}"#, - r#"{"agent_trace":{"repository_remote":"upstream"}}"#, - r#"{"log_level":"debug"}"#, - ); - - assert_eq!(runtime.log_level.value, LogLevel::Debug); - assert_eq!(runtime.log_level.source, ValueSource::ConfigFile(source)); - assert_eq!(runtime.agent_trace_auto_sync.source, ValueSource::Default); - assert_eq!( - runtime.agent_trace_repository_remote.source, - ValueSource::Default - ); - assert_eq!( - runtime - .loaded_config_paths - .iter() - .map(|loaded| loaded.source) - .collect::>(), - vec![ - ConfigPathSource::DefaultDiscoveredGlobal, - ConfigPathSource::DefaultDiscoveredLocal, - source, - ] - ); - } - } - - fn git(dir: &Path, args: &[&str]) { - let status = std::process::Command::new("git") - .arg("-C") - .arg(dir) - .args([ - "-c", - "user.name=SCE Test", - "-c", - "user.email=sce@example.invalid", - "-c", - "commit.gpgsign=false", - ]) - .args(args) - .env_remove("GIT_DIR") - .env_remove("GIT_WORK_TREE") - .env_remove("GIT_INDEX_FILE") - .status() - .unwrap(); - assert!(status.success(), "git {args:?} in {}", dir.display()); - } - - fn write_repository_config(dir: &Path, contents: &str) -> PathBuf { - let path = RepoPaths::new(dir).sce_config_file(); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(&path, contents).unwrap(); - path - } - - #[test] - fn repository_policy_outside_git_is_discovered_from_the_working_directory_only() { - let at_directory = resolve_discovered( - r#"{"telemetry":{"enabled":true}}"#, - r#"{"telemetry":{"enabled":false}}"#, - ); - assert_eq!( - at_directory.access_policy.telemetry, - TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut) - ); - - let below_directory = resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: None, - log_level: None, - }, - Path::new("/tmp/policy-repo/src"), - |_| None, - |_| Ok(r#"{"telemetry":{"enabled":true}}"#.to_string()), - discovered_paths_exist, - || Ok(PathBuf::from(GLOBAL_PATH)), - ) - .unwrap(); - assert_eq!(below_directory.loaded_config_paths.len(), 1); - assert_eq!( - below_directory.access_policy.telemetry, - TelemetryPolicyState::Enabled - ); - } - - #[test] - fn repository_policy_is_discovered_from_the_enclosing_git_root() { - let dir = tempfile::tempdir().unwrap(); - let base = dir.path(); - let global = base.join("global-config.json"); - std::fs::write( - &global, - r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, - ) - .unwrap(); - - let repo = base.join("repo"); - std::fs::create_dir_all(&repo).unwrap(); - git(&repo, &["init", "--quiet"]); - let repo_config = write_repository_config(&repo, r#"{"telemetry":{"enabled":false}}"#); - git(&repo, &["add", ".sce/config.json"]); - git(&repo, &["commit", "--quiet", "-m", "init"]); - let worktree = base.join("worktree"); - git( - &repo, - &["worktree", "add", "--quiet", worktree.to_str().unwrap()], - ); - let worktree_config = RepoPaths::new(&worktree).sce_config_file(); - - let inner = repo.join("vendor").join("inner"); - std::fs::create_dir_all(&inner).unwrap(); - git(&inner, &["init", "--quiet"]); - let inner_config = write_repository_config(&inner, r#"{"auth":{"mode":"disabled"}}"#); - - for nested in [&repo, &worktree, &inner] { - std::fs::create_dir_all(nested.join("src").join("module")).unwrap(); - } - - let resolve = |cwd: &Path| { - resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: None, - log_level: None, - }, - cwd, - |_| None, - |path| Ok(std::fs::read_to_string(path)?), - Path::exists, - || Ok(global.clone()), - ) - .unwrap() - }; - let repository_opt_out = - TelemetryPolicyState::Disabled(TelemetryDisabledReason::RepositoryOptOut); - let auth_disabled = TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled); - let cases = [ - ( - &repo, - Some(&repo_config), - AuthMode::Optional, - repository_opt_out, - ), - ( - &worktree, - Some(&worktree_config), - AuthMode::Optional, - repository_opt_out, - ), - ( - &inner, - Some(&inner_config), - AuthMode::Disabled, - auth_disabled, - ), - ]; - - for (root, config, auth_mode, telemetry) in cases { - for cwd in [root.clone(), root.join("src").join("module")] { - let runtime = resolve(&cwd); - let case = cwd.display().to_string(); - assert_eq!( - runtime - .loaded_config_paths - .last() - .map(|loaded| &loaded.path), - config, - "{case}" - ); - assert_eq!(runtime.access_policy.auth_mode.value, auth_mode, "{case}"); - assert_eq!(runtime.access_policy.telemetry, telemetry, "{case}"); - } - } - } - - #[test] - fn access_policy_invalid_global_layer_is_skipped_and_degrades_policy() { - let runtime = resolve_discovered( - r#"{"auth":{"mode":"sometimes"}}"#, - r#"{"telemetry":{"enabled":true}}"#, - ); - - assert_eq!(runtime.validation_errors.len(), 1); - assert_eq!( - runtime.access_policy.telemetry, - TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) - ); - assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Optional); - assert!(!runtime.access_policy.background_cloud_allowed); - assert_eq!( - runtime.validation_warnings, - vec![ - WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), - WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string(), - ] - ); - } - - #[test] - fn access_policy_invalid_local_layer_is_skipped_and_degrades_policy() { - let runtime = resolve_discovered( - r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true}}"#, - r#"{"telemetry":{"enabled":"yes"}}"#, - ); - - assert_eq!(runtime.validation_errors.len(), 1); - assert_eq!( - runtime.access_policy.telemetry, - TelemetryPolicyState::Disabled(TelemetryDisabledReason::InvalidConfig) - ); - assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Mandatory); - assert_eq!( - runtime.access_policy.auth_mode.source, - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) - ); - assert!(!runtime.access_policy.background_cloud_allowed); - assert_eq!( - runtime.validation_warnings, - vec![WARNING_INVALID_LAYER_DISABLES_CLOUD.to_string()] - ); - } - - #[test] - fn access_policy_merge_loop_routes_layers_and_appends_ordered_warnings() { - let runtime = resolve_discovered( - r#"{"auth":{"mode":"disabled"}}"#, - r#"{"auth":{"mode":"mandatory"},"telemetry":{"enabled":true},"agent_trace":{"auto_sync":true}}"#, - ); - - assert!(runtime.validation_errors.is_empty()); - assert_eq!(runtime.access_policy.auth_mode.value, AuthMode::Disabled); - assert_eq!( - runtime.access_policy.auth_mode.source, - ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal) - ); - assert_eq!( - runtime.access_policy.telemetry, - TelemetryPolicyState::Disabled(TelemetryDisabledReason::AuthDisabled) - ); - assert_eq!( - runtime.validation_warnings, - vec![ - WARNING_REPOSITORY_TELEMETRY_WITHOUT_USER_CONSENT.to_string(), - WARNING_TELEMETRY_ENABLED_WITH_AUTH_DISABLED.to_string(), - WARNING_AUTO_SYNC_WITH_AUTH_DISABLED.to_string(), - WARNING_REPOSITORY_MANDATORY_OVERRIDDEN_BY_USER_DISABLED.to_string(), - ] - ); - } - - #[test] - fn access_policy_defaults_when_no_config_files_exist() { - let runtime = resolve_runtime_config_with( - &ConfigRequest { - report_format: ReportFormat::Text, - config_path: None, - log_level: None, - }, - Path::new("/tmp/policy-repo"), - |_| None, - |_| Ok("{}".to_string()), - |_| false, - || Ok(PathBuf::from(GLOBAL_PATH)), - ) - .unwrap(); - - assert_eq!( - runtime.access_policy, - ResolvedAccessPolicy { - auth_mode: ResolvedValue { - value: AuthMode::Optional, - source: ValueSource::Default, - }, - telemetry_enabled: ResolvedValue { - value: false, - source: ValueSource::Default, - }, - telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), - background_cloud_allowed: true, - } - ); - assert!(runtime.validation_warnings.is_empty()); - } - - #[test] - fn access_policy_is_exposed_on_projected_runtime_configs() { - let expected = resolve_discovered( - r#"{"telemetry":{"enabled":true}}"#, - r#"{"auth":{"mode":"mandatory"}}"#, - ) - .access_policy; - let read = |path: &Path| { - if path == Path::new(GLOBAL_PATH) { - Ok(r#"{"telemetry":{"enabled":true}}"#.to_string()) - } else { - Ok(r#"{"auth":{"mode":"mandatory"}}"#.to_string()) - } - }; - let cwd = Path::new("/tmp/policy-repo"); - let global = || Ok(PathBuf::from(GLOBAL_PATH)); - - let auth = - resolve_auth_runtime_config_with(cwd, |_| None, read, discovered_paths_exist, global) - .unwrap(); - let hook = - resolve_hook_runtime_config_with(cwd, |_| None, read, discovered_paths_exist, global) - .unwrap(); - let observability = resolve_observability_runtime_config_with( - cwd, - |_| None, - read, - discovered_paths_exist, - global, - ) - .unwrap(); - - assert_eq!(expected.telemetry, TelemetryPolicyState::Enabled); - assert_eq!(auth.access_policy, expected); - assert_eq!(hook.access_policy, expected); - assert_eq!(observability.access_policy, expected); - } -} diff --git a/cli/src/services/config/schema.rs b/cli/src/services/config/schema.rs index 80836673e..1307f36ab 100644 --- a/cli/src/services/config/schema.rs +++ b/cli/src/services/config/schema.rs @@ -1124,136 +1124,6 @@ mod agent_trace_config_tests { } } -#[cfg(test)] -mod access_policy_config_tests { - use std::path::Path; - - use super::{parse_file_config, AuthMode, ConfigPathSource, FileConfig}; - - const CONFIG_PATH: &str = "/tmp/sce-config.json"; - - fn parse_from(raw: &str, source: ConfigPathSource) -> anyhow::Result { - parse_file_config(raw, Path::new(CONFIG_PATH), source) - } - - #[test] - fn auth_and_telemetry_sections_parse_with_layer_source() { - let sources = [ - ConfigPathSource::Flag, - ConfigPathSource::Env, - ConfigPathSource::DefaultDiscoveredGlobal, - ConfigPathSource::DefaultDiscoveredLocal, - ]; - let cases = [ - ("disabled", AuthMode::Disabled, false), - ("optional", AuthMode::Optional, true), - ("mandatory", AuthMode::Mandatory, false), - ]; - - for source in sources { - for (raw_mode, mode, enabled) in cases { - let config = parse_from( - &format!( - r#"{{"auth":{{"mode":"{raw_mode}"}},"telemetry":{{"enabled":{enabled}}}}}"# - ), - source, - ) - .unwrap(); - - let auth_mode = config.auth_mode.unwrap(); - assert_eq!(auth_mode.value, mode); - assert_eq!(auth_mode.source, source); - assert_eq!(mode.as_str(), raw_mode); - let telemetry_enabled = config.telemetry_enabled.unwrap(); - assert_eq!(telemetry_enabled.value, enabled); - assert_eq!(telemetry_enabled.source, source); - } - } - } - - #[test] - fn omitted_or_empty_auth_and_telemetry_sections_parse_as_unset() { - for raw in [ - "{}", - r#"{"log_level":"warn"}"#, - r#"{"auth":{},"telemetry":{}}"#, - ] { - let config = parse_from(raw, ConfigPathSource::Flag).unwrap(); - assert_eq!(config.auth_mode, None, "{raw}"); - assert_eq!(config.telemetry_enabled, None, "{raw}"); - } - } - - #[test] - fn invalid_auth_and_telemetry_sections_fail_with_schema_pointer() { - let cases = [ - (r#"{"auth":{"mode":"required"}}"#, "/auth/mode"), - (r#"{"auth":{"mode":true}}"#, "/auth/mode"), - (r#"{"auth":{"level":"optional"}}"#, "/auth"), - (r#"{"auth":"optional"}"#, "/auth"), - (r#"{"telemetry":{"enabled":"true"}}"#, "/telemetry/enabled"), - (r#"{"telemetry":{"enabled":1}}"#, "/telemetry/enabled"), - (r#"{"telemetry":{"export":true}}"#, "/telemetry"), - (r#"{"telemetry":true}"#, "/telemetry"), - ]; - - for (raw, pointer) in cases { - let error = parse_from(raw, ConfigPathSource::DefaultDiscoveredLocal) - .unwrap_err() - .to_string(); - assert!( - error.starts_with(&format!( - "Config file '{CONFIG_PATH}' failed schema validation against generated schema" - )), - "{raw}: {error}" - ); - assert!(error.contains(&format!(": {pointer}: ")), "{raw}: {error}"); - } - } - - #[test] - fn auth_and_telemetry_key_checks_reject_unknown_keys_as_backstop() { - let object = serde_json::json!({"auth": {"level": "optional"}}); - let error = super::map_auth_config( - None, - object.as_object().unwrap(), - Path::new(CONFIG_PATH), - ConfigPathSource::Flag, - ) - .unwrap_err() - .to_string(); - assert_eq!( - error, - "Config key 'auth' in '/tmp/sce-config.json' contains unknown key 'level'. Allowed keys: mode." - ); - - let object = serde_json::json!({"telemetry": {"export": true}}); - let error = super::map_telemetry_config( - None, - object.as_object().unwrap(), - Path::new(CONFIG_PATH), - ConfigPathSource::Flag, - ) - .unwrap_err() - .to_string(); - assert_eq!( - error, - "Config key 'telemetry' in '/tmp/sce-config.json' contains unknown key 'export'. Allowed keys: enabled." - ); - } - - #[test] - fn auth_mode_parse_rejects_unknown_value() { - let error = AuthMode::parse("required", "test source") - .unwrap_err() - .to_string(); - assert_eq!( - error, - "Invalid auth mode 'required' from test source. Valid values: disabled, optional, mandatory." - ); - } -} - #[cfg(test)] mod database_retry_config_tests { use std::path::Path; diff --git a/cli/src/services/db/encryption_key.rs b/cli/src/services/db/encryption_key.rs index f79f0243c..3054d823c 100644 --- a/cli/src/services/db/encryption_key.rs +++ b/cli/src/services/db/encryption_key.rs @@ -382,48 +382,3 @@ fn hex_encode(bytes: &[u8]) -> String { } hex } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn storage_access_failures_are_tagged_as_credential_access_denied() { - let error = keyring_error( - keyring_core::Error::NoStorageAccess(Box::new(std::io::Error::other("locked"))), - "auth_db", - ) - .context("failed to read encryption key"); - assert!(error.is::()); - assert_eq!(error.to_string(), "failed to read encryption key"); - - for untagged in [ - keyring_core::Error::NoEntry, - keyring_core::Error::PlatformFailure(Box::new(std::io::Error::other("other"))), - ] { - assert!(!keyring_error(untagged, "auth_db").is::()); - } - } - - #[cfg(target_os = "macos")] - #[test] - fn macos_authorization_status_codes_are_tagged_by_code() { - let platform_failure = |code| { - keyring_core::Error::PlatformFailure(Box::new( - security_framework::base::Error::from_code(code), - )) - }; - for code in MACOS_AUTHORIZATION_FAILURE_CODES { - assert!( - keyring_error(platform_failure(code), "auth_db").is::(), - "{code}" - ); - } - for code in [-50, -25299, -34018] { - assert!( - !keyring_error(platform_failure(code), "auth_db").is::(), - "{code}" - ); - } - } -} diff --git a/cli/src/services/doctor/managed_telemetry.rs b/cli/src/services/doctor/managed_telemetry.rs index a7da3b336..49a6a3c12 100644 --- a/cli/src/services/doctor/managed_telemetry.rs +++ b/cli/src/services/doctor/managed_telemetry.rs @@ -193,177 +193,3 @@ pub(super) fn json(health: ManagedTelemetryHealth) -> Value { }), } } - -#[cfg(test)] -mod tests { - use super::*; - - fn disabled(reason: TelemetryFallbackReason) -> ManagedTelemetryHealth { - ManagedTelemetryHealth::Disabled(reason) - } - - #[test] - fn not_configured_and_healthy_telemetry_report_no_problem() { - assert_eq!(problem(ManagedTelemetryHealth::Healthy), None); - assert_eq!( - problem(disabled(TelemetryFallbackReason::NotConfigured)), - None - ); - assert_eq!( - json(ManagedTelemetryHealth::Healthy), - json!({ - "state": "healthy", - "reason": null, - "kind": null, - "severity": null, - "next_action": null, - }) - ); - assert_eq!( - json(disabled(TelemetryFallbackReason::NotConfigured)), - json!({ - "state": "not_configured", - "reason": "not_configured", - "kind": null, - "severity": null, - "next_action": null, - }) - ); - } - - #[test] - fn telemetry_disabled_by_config_reports_no_problem_and_a_stable_json_state() { - for auth_db_present in [false, true] { - let health = ManagedTelemetryHealth::DisabledByConfig { auth_db_present }; - assert_eq!(problem(health), None); - assert_eq!( - json(health), - json!({ - "state": "disabled_by_config", - "reason": "disabled_by_config", - "kind": null, - "severity": null, - "next_action": null, - }) - ); - } - assert_eq!( - problem(disabled(TelemetryFallbackReason::DisabledByConfig)), - None - ); - } - - #[test] - fn macos_inaccessible_credential_is_an_actionable_always_allow_warning() { - let diagnostic = diagnostic_for_platform( - disabled(TelemetryFallbackReason::CredentialInaccessible), - CredentialStorePlatform::Macos, - ) - .expect("inaccessible credentials are diagnosed"); - assert_eq!(diagnostic.reason, "credential_inaccessible"); - assert_eq!(diagnostic.kind, "managed_telemetry_credential_inaccessible"); - assert_eq!(diagnostic.next_action, "auth_login"); - assert_eq!( - diagnostic.summary, - "SCE cannot access its encryption key in macOS Keychain without user interaction." - ); - assert_eq!(diagnostic.remediation, MACOS_INACCESSIBLE_REMEDIATION); - assert!(diagnostic.remediation.contains("select \"Always Allow\".")); - } - - #[test] - fn always_allow_is_only_recommended_for_macos_keychain_authorization() { - use CredentialStorePlatform::{Linux, Macos, Other, Windows}; - use TelemetryFallbackReason::{CredentialInaccessible, LookupTimeout}; - - for (platform, reason, expects_always_allow) in [ - (Macos, CredentialInaccessible, true), - (Macos, LookupTimeout, false), - (Linux, CredentialInaccessible, false), - (Windows, CredentialInaccessible, false), - (Other, CredentialInaccessible, false), - (Linux, LookupTimeout, false), - ] { - let diagnostic = diagnostic_for_platform(disabled(reason), platform) - .expect("disabled telemetry is diagnosed"); - let text = format!("{} {}", diagnostic.summary, diagnostic.remediation); - assert_eq!( - text.contains("Always Allow"), - expects_always_allow, - "{platform:?}/{reason:?}: {text}" - ); - assert_eq!( - text.contains("macOS"), - platform == Macos, - "{platform:?}/{reason:?}: {text}" - ); - } - } - - #[test] - fn every_disabled_reason_has_a_stable_kind_and_safe_remediation() { - let expected = [ - ( - TelemetryFallbackReason::CredentialInaccessible, - "managed_telemetry_credential_inaccessible", - "auth_login", - ), - ( - TelemetryFallbackReason::CredentialUnavailable, - "managed_telemetry_credential_unavailable", - "auth_login", - ), - ( - TelemetryFallbackReason::CredentialExpired, - "managed_telemetry_credential_expired", - "auth_login", - ), - ( - TelemetryFallbackReason::LookupTimeout, - "managed_telemetry_lookup_timeout", - "manual_steps", - ), - ( - TelemetryFallbackReason::DatabaseError, - "managed_telemetry_database_error", - "manual_steps", - ), - ( - TelemetryFallbackReason::PathResolutionError, - "managed_telemetry_path_resolution_error", - "manual_steps", - ), - ( - TelemetryFallbackReason::ExporterInitFailed, - "managed_telemetry_exporter_init_failed", - "manual_steps", - ), - ]; - for (reason, kind, next_action) in expected { - let health = disabled(reason); - let problem = problem(health).expect("disabled telemetry is a problem"); - assert_eq!(problem.kind, ProblemKind::ManagedTelemetryUnavailable); - assert_eq!(problem.severity, ProblemSeverity::Warning); - assert_eq!(problem.fixability, ProblemFixability::ManualOnly); - assert_eq!(problem.next_action, next_action); - assert!(problem.summary.ends_with(HOOK_IMPACT)); - let lowered = format!("{} {}", problem.summary, problem.remediation).to_lowercase(); - for forbidden in ["delete", "regenerat", "reset", "bearer", "token:"] { - assert!( - !lowered.contains(forbidden), - "{reason:?} mentions {forbidden}" - ); - } - assert_eq!( - json(health), - json!({ - "state": "disabled", - "reason": reason.as_str(), - "kind": kind, - "severity": "warning", - "next_action": next_action, - }) - ); - } - } -} diff --git a/cli/src/services/doctor/render.rs b/cli/src/services/doctor/render.rs index 021187285..16146a9b6 100644 --- a/cli/src/services/doctor/render.rs +++ b/cli/src/services/doctor/render.rs @@ -1283,74 +1283,3 @@ mod reconciliation_render_tests { } } } - -#[cfg(test)] -mod managed_telemetry_render_tests { - use super::{managed_telemetry_node, render_display_node}; - use crate::services::managed_telemetry::{ManagedTelemetryHealth, TelemetryFallbackReason}; - - fn rendered(health: ManagedTelemetryHealth) -> Vec { - let mut lines = Vec::new(); - render_display_node(&mut lines, &managed_telemetry_node(health), false, 2, true); - lines - } - - #[test] - fn healthy_and_unconfigured_telemetry_render_as_single_pass_rows() { - assert_eq!( - rendered(ManagedTelemetryHealth::Healthy), - [" [PASS] Managed telemetry"] - ); - assert_eq!( - rendered(ManagedTelemetryHealth::Disabled( - TelemetryFallbackReason::NotConfigured - )), - [" [PASS] Managed telemetry (not configured)"] - ); - } - - #[test] - fn telemetry_disabled_by_config_renders_pass_row_with_opt_in_line_only_when_auth_db_exists() { - assert_eq!( - rendered(ManagedTelemetryHealth::DisabledByConfig { - auth_db_present: false - }), - [" [PASS] Managed telemetry (disabled by config)"] - ); - assert_eq!( - rendered(ManagedTelemetryHealth::DisabledByConfig { - auth_db_present: true - }), - [ - " [PASS] Managed telemetry (disabled by config)", - " Managed telemetry export is off because telemetry.enabled is not true; set telemetry.enabled: true in the global SCE config to resume it.", - ] - ); - } - - #[test] - fn inaccessible_credentials_render_reason_impact_and_login_steps() { - let lines = rendered(ManagedTelemetryHealth::Disabled( - TelemetryFallbackReason::CredentialInaccessible, - )); - assert_eq!(lines[0], " [WARN] Managed telemetry"); - assert_eq!(lines[1], " Reason: credential_inaccessible"); - assert!(lines[2].contains("without user interaction.")); - assert_eq!( - lines[3], - " Claude Code hooks continue working, but telemetry export is disabled." - ); - assert_eq!(lines[4], " To fix:"); - assert!(lines - .iter() - .any(|line| line.ends_with(". Run `sce auth login` in an interactive terminal."))); - assert_eq!( - lines.last().map(String::as_str), - Some(" 3. Run `sce doctor` again to verify access.") - ); - assert_eq!( - lines.iter().any(|line| line.contains("Always Allow")), - cfg!(target_os = "macos") - ); - } -} diff --git a/cli/src/services/error.rs b/cli/src/services/error.rs index 92441cf34..6282b6fc1 100644 --- a/cli/src/services/error.rs +++ b/cli/src/services/error.rs @@ -461,69 +461,6 @@ mod tests { assert!(error.to_string().contains("You are not logged in")); } - #[test] - fn auth_disabled_by_config_has_stable_runtime_catalog_mapping_per_file() { - for (file, location) in [ - (AuthPolicyConfigFile::Global, "in the global SCE config."), - ( - AuthPolicyConfigFile::Repository, - "in the repository SCE config (`.sce/config.json`).", - ), - ( - AuthPolicyConfigFile::ConfigFlag, - "in the SCE config file passed with `--config`.", - ), - ( - AuthPolicyConfigFile::ConfigEnv, - "in the SCE config file named by `SCE_CONFIG_FILE`.", - ), - ] { - let user_error = UserError::AuthDisabledByConfig(file); - let error = CliError::User { - error: user_error.clone(), - source: None, - }; - - assert_eq!(error.class(), FailureClass::Runtime); - assert_eq!(error.code(), "SCE-ERR-RUNTIME"); - assert_eq!(user_error.key(), "auth.disabled_by_config"); - assert_eq!( - user_error.message(), - format!( - "Authentication is disabled by `auth.mode: disabled` {location}\n\nTo use SCE authentication, set `auth.mode` to `optional` or `mandatory` in that file, then retry." - ) - ); - assert_eq!(error.to_string(), user_error.message()); - } - } - - #[test] - fn setup_login_required_has_stable_runtime_catalog_mapping_and_keeps_its_source() { - let error = CliError::user_with_source( - UserError::SetupLoginRequired, - anyhow::anyhow!("device flow expired"), - ); - - assert_eq!(error.class(), FailureClass::Runtime); - assert_eq!(error.code(), "SCE-ERR-RUNTIME"); - assert_eq!( - UserError::SetupLoginRequired.key(), - "auth.setup_login_required" - ); - assert_eq!( - error.to_string(), - "Local SCE setup completed, but the SCE login required by `auth.mode: mandatory` did not succeed.\n\nTo finish setup, run `sce auth login`, then rerun `sce setup`." - ); - let CliError::User { - source: Some(source), - .. - } = &error - else { - panic!("expected a user error with a source"); - }; - assert_eq!(source.to_string(), "device flow expired"); - } - #[test] fn not_git_repository_has_stable_runtime_catalog_mapping() { let error = CliError::User { @@ -623,177 +560,4 @@ mod tests { assert_eq!(validation_error.class(), FailureClass::Validation); assert_eq!(validation_error.to_string(), "bad value"); } - - const ALL_PLATFORMS: [CredentialStorePlatform; 4] = [ - CredentialStorePlatform::Macos, - CredentialStorePlatform::Linux, - CredentialStorePlatform::Windows, - CredentialStorePlatform::Other, - ]; - const ALL_OPERATIONS: [AuthStorageOperation; 2] = - [AuthStorageOperation::Command, AuthStorageOperation::Login]; - const ALL_FAILURES: [AuthStorageFailure; 3] = [ - AuthStorageFailure::CredentialAccess, - AuthStorageFailure::DatabaseLocked, - AuthStorageFailure::Database, - ]; - - #[test] - fn auth_storage_unavailable_keeps_stable_key_class_and_exit_code() { - for failure in ALL_FAILURES { - for user_error in [ - UserError::AuthStorageUnavailable(failure), - UserError::LoginAuthStorageUnavailable(failure), - ] { - let error = CliError::user_with_source( - user_error.clone(), - anyhow::anyhow!("keychain item secret-key-material denied"), - ); - assert_eq!(user_error.key(), "auth.storage_unavailable"); - assert_eq!(error.class(), FailureClass::Runtime); - assert_eq!(error.code(), "SCE-ERR-RUNTIME"); - assert_eq!(error.class().exit_code(), 4); - assert_eq!(error.to_string(), user_error.message()); - assert!(!error.to_string().contains("secret-key-material")); - } - } - } - - #[test] - fn macos_auth_storage_guidance_explains_login_and_always_allow() { - let message = auth_storage_unavailable_message( - CredentialStorePlatform::Macos, - AuthStorageOperation::Command, - AuthStorageFailure::CredentialAccess, - ); - assert!(message.starts_with("Authentication storage is unavailable.\n")); - assert!(message.contains("macOS Keychain")); - assert!(message.contains("Run `sce auth login` in an interactive terminal.")); - assert!(message.contains("choose \"Always Allow\".")); - assert!(message.contains("Retry the original command, or run `sce doctor`")); - assert!(message.contains("login Keychain is unlocked")); - } - - #[test] - fn macos_login_storage_guidance_is_not_circular() { - let message = auth_storage_unavailable_message( - CredentialStorePlatform::Macos, - AuthStorageOperation::Login, - AuthStorageFailure::CredentialAccess, - ); - assert!(message.contains("Running login again does not help until")); - assert!(message.contains("Unlock your login Keychain")); - assert!(message.contains("\"Always Allow\" to authorize this SCE executable")); - assert!(!message.contains("Retry the original command")); - } - - #[test] - fn database_failures_never_blame_the_credential_store() { - for platform in ALL_PLATFORMS { - for operation in ALL_OPERATIONS { - let locked = auth_storage_unavailable_message( - platform, - operation, - AuthStorageFailure::DatabaseLocked, - ); - assert!(locked.contains("locked by another SCE process")); - let generic = auth_storage_unavailable_message( - platform, - operation, - AuthStorageFailure::Database, - ); - assert!( - generic.contains("could not open or read its local authentication database") - ); - for message in [locked, generic] { - assert!(message.starts_with("Authentication storage is unavailable.\n")); - assert!( - !message.contains("encryption key"), - "{platform:?}/{operation:?}" - ); - assert!(!message.contains("Keychain"), "{platform:?}/{operation:?}"); - assert!( - !message.contains("Always Allow"), - "{platform:?}/{operation:?}" - ); - assert!( - !message.contains("sce auth login"), - "{platform:?}/{operation:?}" - ); - } - } - } - } - - #[test] - fn non_macos_auth_storage_guidance_never_mentions_macos() { - for platform in [ - CredentialStorePlatform::Linux, - CredentialStorePlatform::Windows, - CredentialStorePlatform::Other, - ] { - for operation in ALL_OPERATIONS { - for failure in ALL_FAILURES { - let message = auth_storage_unavailable_message(platform, operation, failure); - assert!(message.starts_with("Authentication storage is unavailable.\n")); - assert!(!message.contains("macOS"), "{platform:?}"); - assert!(!message.contains("Keychain"), "{platform:?}"); - assert!(!message.contains("Always Allow"), "{platform:?}"); - } - assert!( - auth_storage_unavailable_message( - platform, - operation, - AuthStorageFailure::CredentialAccess - ) - .contains("sce auth login"), - "{platform:?}" - ); - } - } - } - - #[test] - fn auth_storage_guidance_never_recommends_destructive_repair() { - for platform in ALL_PLATFORMS { - for operation in ALL_OPERATIONS { - for failure in ALL_FAILURES { - let message = auth_storage_unavailable_message(platform, operation, failure) - .to_lowercase(); - for forbidden in ["auth.db", "delete", "regenerat", "reset", "permanent"] { - assert!( - !message.contains(forbidden), - "{platform:?}/{operation:?}/{failure:?} mentions {forbidden:?}" - ); - } - } - } - } - } - - #[test] - fn current_platform_message_is_selected_for_display() { - for failure in ALL_FAILURES { - assert_eq!( - UserError::AuthStorageUnavailable(failure).message(), - auth_storage_unavailable_message( - CURRENT_CREDENTIAL_STORE_PLATFORM, - AuthStorageOperation::Command, - failure - ) - ); - assert_eq!( - UserError::LoginAuthStorageUnavailable(failure).message(), - auth_storage_unavailable_message( - CURRENT_CREDENTIAL_STORE_PLATFORM, - AuthStorageOperation::Login, - failure - ) - ); - } - assert_eq!( - CURRENT_CREDENTIAL_STORE_PLATFORM == CredentialStorePlatform::Macos, - cfg!(target_os = "macos") - ); - } } diff --git a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs index 97f0a9bbb..eebf1cafb 100644 --- a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs +++ b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs @@ -523,259 +523,3 @@ pub(crate) async fn repair_blocked>, - seam_payloads: Vec, - state: state::AdapterState, - } - - async fn run_hook_sequence(telemetry: &T) -> HookRun { - let git_dir = tempfile::tempdir().expect("temp dir"); - let seam_payloads = Mutex::new(Vec::new()); - let resolve = async |_: &str| Ok::<_, anyhow::Error>(git_dir.path().to_path_buf()); - let model_state = async |_: &Path, _: &str, _: &str| Ok::<_, anyhow::Error>(None); - let seam = async |_: &Path, payload: &str, _: Option<&NoopLogger>| { - let mut payloads = seam_payloads.lock().expect("seam payloads"); - payloads.push(payload.to_string()); - if payloads.len() == FAILING_SEAM_CALL { - anyhow::bail!("seam failure"); - } - Ok(String::new()) - }; - let mut outputs = Vec::new(); - for payload in HOOK_SEQUENCE { - let output = telemetry - .with_default_subscriber(&mut || async { - record_claude_hook_command(ClaudeHookCommand::ClaudeMutationScope); - record_claude_hook_payload(payload); - run_claude_mutation_scope_from_payload_with_resolver::( - payload, - None, - &resolve, - &model_state, - &seam, - ) - .await - .map_err(CliError::runtime) - }) - .await; - outputs.push(output.ok()); - } - HookRun { - outputs, - seam_payloads: seam_payloads.into_inner().expect("seam payloads"), - state: state::read_state(git_dir.path()).await.expect("state"), - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn failing_managed_telemetry_cannot_change_claude_hook_behavior() { - let baseline = run_hook_sequence(&NoopTelemetry).await; - assert!(baseline - .outputs - .iter() - .flatten() - .any(|output| output.contains("\"permissionDecision\":\"deny\""))); - - let refused = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let refused_address = refused.local_addr().expect("addr"); - drop(refused); - let stalled = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let stalled_address = stalled.local_addr().expect("addr"); - let holder = tokio::spawn(async move { - let mut held = Vec::new(); - while let Ok((stream, _)) = stalled.accept().await { - held.push(stream); - } - }); - - for address in [refused_address, stalled_address] { - let telemetry = loopback_hook_telemetry(address, "bao-token-value"); - let observed = run_hook_sequence(&telemetry).await; - let started = Instant::now(); - telemetry.shutdown().await; - assert!(started.elapsed() < SHUTDOWN_TIMEOUT + SHUTDOWN_MARGIN); - assert_eq!(observed, baseline); - } - holder.abort(); - } - - fn git(root: &Path, args: &[&str]) { - let status = Command::new("git") - .args(args) - .current_dir(root) - .status() - .expect("git"); - assert!(status.success(), "git {args:?} failed"); - } - - fn init_repo(root: &Path) { - std::fs::create_dir_all(root).expect("repo dir"); - git(root, &["init", "-q"]); - git(root, &["config", "user.email", "t@example.invalid"]); - git(root, &["config", "user.name", "T"]); - git(root, &["config", "commit.gpgsign", "false"]); - std::fs::write(root.join("tracked.txt"), "tracked\n").expect("write file"); - git(root, &["add", "tracked.txt"]); - git(root, &["commit", "-q", "-m", "initial"]); - } - - async fn export_claude_hook_spans(payload: &str) -> (Option, Vec) { - let dir = tempfile::tempdir().expect("temp dir"); - let root = dir.path().join("repo"); - init_repo(&root); - let git_dir = root.join(".git"); - let db_path = dir.path().join("agent-trace.db"); - RepositoryAgentTraceDb::new_at(&db_path) - .await - .expect("create db") - .verify_or_initialize_repository_metadata(TEST_REPOSITORY_ID) - .await - .expect("initialize metadata"); - let resolve = async |_: &str| Ok::<_, anyhow::Error>(git_dir.clone()); - let model_state = async |_: &Path, _: &str, _: &str| Ok::<_, anyhow::Error>(None); - let seam = async |_: &Path, payload: &str, _: Option<&NoopLogger>| { - drive_mutation_scope( - &root, - parse_mutation_scope_payload(payload)?, - None::<&NoopLogger>, - &mut Vec::new(), - async |root: &Path, boundary| { - coordinate(root, boundary, async || { - RepositoryAgentTraceDb::open_without_migrations_at(&db_path).await - }) - .await - }, - async |root: &Path, scope| { - abandon_scope(root, scope, async || { - RepositoryAgentTraceDb::open_without_migrations_at(&db_path).await - }) - .await - }, - advise_after_completed_boundary, - ) - .await - }; - - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let address = listener.local_addr().expect("addr"); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let receiver = tokio::spawn(capture_requests_until(listener, stopped)); - let telemetry = loopback_hook_telemetry(address, "bao-token-value"); - let output = telemetry - .with_default_subscriber(&mut || async { - record_claude_hook_command(ClaudeHookCommand::ClaudeMutationScope); - record_claude_hook_payload(payload); - run_claude_mutation_scope_from_payload_with_resolver::( - payload, - None, - &resolve, - &model_state, - &seam, - ) - .await - .map_err(CliError::runtime) - }) - .await; - telemetry.shutdown().await; - stop.send(()).expect("stop receiver"); - let spans = trace_spans(&receiver.await.expect("receiver join")); - (output.ok(), spans) - } - - fn span_named<'a>(spans: &'a [DecodedSpan], name: &str) -> &'a DecodedSpan { - spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("missing {name}: {spans:?}")) - } - - fn sorted_names(spans: &[DecodedSpan]) -> Vec<&str> { - let mut names = spans - .iter() - .map(|span| span.name.as_str()) - .collect::>(); - names.sort_unstable(); - names - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn tracked_claude_hook_exports_mutation_snapshot_and_persistence_children() { - let (output, spans) = export_claude_hook_spans(WRITE_PRE_TOOL_USE).await; - - assert_eq!(output.as_deref(), Some("")); - assert_eq!( - sorted_names(&spans), - [ - "sce.git_snapshot", - "sce.hook", - "sce.mutation_scope", - "sce.persistence" - ] - ); - let hook = span_named(&spans, "sce.hook"); - let mutation_scope = span_named(&spans, "sce.mutation_scope"); - let git_snapshot = span_named(&spans, "sce.git_snapshot"); - let persistence = span_named(&spans, "sce.persistence"); - assert!(hook.parent_span_id.is_empty()); - assert_eq!(mutation_scope.parent_span_id, hook.span_id); - assert_eq!(git_snapshot.parent_span_id, mutation_scope.span_id); - assert_eq!(persistence.parent_span_id, mutation_scope.span_id); - let success = vec![("sce.outcome".to_string(), "success".to_string())]; - for child in [mutation_scope, git_snapshot, persistence] { - assert_eq!(child.trace_id, hook.trace_id, "{}", child.name); - assert_eq!(child.sce_attributes(), success, "{}", child.name); - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn read_only_claude_hook_exports_no_operation_children() { - let payload = - WRITE_PRE_TOOL_USE.replace("\"tool_name\":\"Write\"", "\"tool_name\":\"Read\""); - assert_ne!(payload, WRITE_PRE_TOOL_USE); - - let (output, spans) = export_claude_hook_spans(&payload).await; - - assert_eq!(output.as_deref(), Some("")); - assert_eq!(sorted_names(&spans), ["sce.hook"]); - } -} diff --git a/cli/src/services/hooks/commit_hooks.rs b/cli/src/services/hooks/commit_hooks.rs index 5e360261b..72daba144 100644 --- a/cli/src/services/hooks/commit_hooks.rs +++ b/cli/src/services/hooks/commit_hooks.rs @@ -760,9 +760,9 @@ mod tests { use anyhow::{anyhow, Result}; - use crate::services::agent_trace::{validate_agent_trace_value, AgentTrace, AgentTraceVcsType}; + use crate::services::agent_trace::{validate_agent_trace_value, AgentTrace}; use crate::services::agent_trace_db::AgentTraceInsert; - use crate::services::config::resolver::resolve_hook_runtime_config_with; + use crate::services::error::CliError; use crate::services::observability::traits::Logger; use crate::services::patch::ParsedPatch; @@ -770,8 +770,7 @@ mod tests { use super::super::commit_patch_id::compute_commit_patch_id; use super::{ capture_post_commit_patch_from_git, resolve_post_commit_commit_patch_id, - run_post_commit_agent_trace_flow_with, run_post_commit_subcommand_with, - PostCommitIntersectionFlowResult, AUTO_SYNC_SKIPPED_BY_POLICY_EVENT, + run_post_commit_agent_trace_flow_with, PostCommitIntersectionFlowResult, COMMIT_PATCH_ID_UNAVAILABLE_EVENT, }; @@ -790,10 +789,6 @@ mod tests { fn warnings(&self) -> Vec<(String, String)> { self.warnings.lock().unwrap().clone() } - - fn debugs(&self) -> Vec { - self.debugs.lock().unwrap().clone() - } } impl Logger for RecordingLogger { @@ -1040,91 +1035,4 @@ mod tests { .expect_err("persistence failure must propagate"); assert_eq!(persistence_error.to_string(), "persistence rejected"); } - - #[tokio::test] - async fn post_commit_launches_auto_sync_only_when_background_cloud_is_allowed() { - let dir = tempfile::tempdir().expect("temp dir"); - let root = dir.path().join("repo"); - std::fs::create_dir_all(&root).expect("repo dir"); - init_repository_with_commit(&root); - let global = dir.path().join("global.json"); - let local = root.join(".sce").join("config.json"); - std::fs::create_dir_all(local.parent().expect("local config dir")).expect("local dir"); - - for auto_sync in [false, true] { - for (case, auth_mode, degraded) in [ - ("disabled", "disabled", false), - ("optional", "optional", false), - ("mandatory", "mandatory", false), - ("degraded", "optional", true), - ] { - std::fs::write( - &global, - format!( - r#"{{"agent_trace":{{"auto_sync":{auto_sync}}},"auth":{{"mode":"{auth_mode}"}}}}"# - ), - ) - .expect("global config"); - if degraded { - std::fs::write(&local, r#"{"auth":{"mode":"bogus"}}"#).expect("local config"); - } else { - let _ = std::fs::remove_file(&local); - } - - let logger = RecordingLogger::default(); - let launches = RefCell::new(0_usize); - let output = run_post_commit_subcommand_with( - &root, - None, - REMOTE_URL, - async |root: &Path| Ok(flow_result(root)), - async |_: &Path, - result: &PostCommitIntersectionFlowResult, - _: Option, - _: &str, - _: Option<&RecordingLogger>| { - Ok(run_flow_capturing(result, None).await.0) - }, - |root| { - resolve_hook_runtime_config_with( - root, - |_| None, - |path| std::fs::read_to_string(path).map_err(anyhow::Error::from), - Path::exists, - || Ok(global.clone()), - ) - }, - |_| { - *launches.borrow_mut() += 1; - Ok(()) - }, - async |_: &Path| Ok(()), - Some(&logger), - ) - .await - .unwrap_or_else(|error| panic!("{case} auto_sync={auto_sync}: {error:#}")); - - let allowed = auth_mode != "disabled" && !degraded; - assert!( - output.starts_with("post-commit hook processed intersection: commit="), - "{case} auto_sync={auto_sync}: {output}" - ); - assert_eq!( - *launches.borrow(), - usize::from(auto_sync && allowed), - "{case} auto_sync={auto_sync}" - ); - let expected_debugs = if auto_sync && !allowed { - vec![AUTO_SYNC_SKIPPED_BY_POLICY_EVENT.to_string()] - } else { - Vec::new() - }; - assert_eq!( - logger.debugs(), - expected_debugs, - "{case} auto_sync={auto_sync}" - ); - } - } - } } diff --git a/cli/src/services/managed_telemetry.rs b/cli/src/services/managed_telemetry.rs index b00f4c5de..9aa19f54d 100644 --- a/cli/src/services/managed_telemetry.rs +++ b/cli/src/services/managed_telemetry.rs @@ -445,240 +445,6 @@ mod tests { } } - #[tokio::test] - async fn claude_hook_without_auth_db_resolves_not_configured() { - let looked_up = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let flag = looked_up.clone(); - - let (telemetry, fallback) = RuntimeTelemetry::resolve_when_enabled( - true, - async move { - flag.store(true, std::sync::atomic::Ordering::SeqCst); - Ok(TelemetryCredentialLookup::Missing) - }, - ManagedSpanKind::ClaudeHook, - ) - .await; - - assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("missing credential is diagnosed"); - assert_eq!(fallback.reason, TelemetryFallbackReason::NotConfigured); - assert!(!fallback.reason.is_failure()); - assert!(looked_up.load(std::sync::atomic::Ordering::SeqCst)); - } - - fn forbidden_lookup() -> Result { - panic!("credential lookup must not run when telemetry is disabled by config") - } - - #[tokio::test] - async fn telemetry_disabled_by_config_never_looks_up_credentials() { - for span_kind in [ManagedSpanKind::Command, ManagedSpanKind::ClaudeHook] { - let (telemetry, fallback) = RuntimeTelemetry::resolve_when_enabled( - false, - async { forbidden_lookup() }, - span_kind, - ) - .await; - - assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("policy-disabled telemetry is diagnosed"); - assert_eq!(fallback.reason, TelemetryFallbackReason::DisabledByConfig); - assert_eq!(fallback.reason.as_str(), "disabled_by_config"); - assert!(!fallback.reason.is_failure()); - assert_eq!(fallback.detail, None); - } - } - - #[tokio::test] - async fn health_disabled_by_config_never_looks_up_credentials() { - for present in [false, true] { - let health = - inspect_health_with(false, || present, async { forbidden_lookup() }, NOW).await; - assert_eq!( - health, - ManagedTelemetryHealth::DisabledByConfig { - auth_db_present: present - } - ); - } - } - - #[tokio::test] - async fn claude_hook_with_inaccessible_credential_store_skips_quietly() { - let (telemetry, fallback) = RuntimeTelemetry::resolve_when_enabled( - true, - async { Err(TokenStorageError::CredentialAccessUnavailable) }, - ManagedSpanKind::ClaudeHook, - ) - .await; - - assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("inaccessible credentials are diagnosed"); - assert_eq!( - fallback.reason, - TelemetryFallbackReason::CredentialInaccessible - ); - assert!(!fallback.reason.is_failure()); - let output = telemetry - .with_default_subscriber(&mut || async { Ok("hook-output".to_string()) }) - .await; - assert_eq!(output.expect("hook result unaffected"), "hook-output"); - } - - #[tokio::test] - async fn claude_hook_credential_failure_or_expiry_resolves_noop_with_reason() { - let (failed, fallback) = RuntimeTelemetry::resolve_with( - async { Err(TokenStorageError::Database("locked".to_string())) }, - ManagedSpanKind::ClaudeHook, - ) - .await; - assert!(matches!(failed, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("database failure is diagnosed"); - assert_eq!(fallback.reason, TelemetryFallbackReason::DatabaseError); - assert!(fallback.reason.is_failure()); - assert!(fallback - .detail - .as_deref() - .is_some_and(|detail| detail.contains("locked"))); - - let (path, fallback) = RuntimeTelemetry::resolve_with( - async { Err(TokenStorageError::PathResolution("no home".to_string())) }, - ManagedSpanKind::ClaudeHook, - ) - .await; - assert!(matches!(path, RuntimeTelemetry::Noop(_))); - assert_eq!( - fallback.map(|fallback| fallback.reason), - Some(TelemetryFallbackReason::PathResolutionError) - ); - - let (expired, fallback) = RuntimeTelemetry::resolve_with( - async { Ok(TelemetryCredentialLookup::Valid(credential("bao-token", 1))) }, - ManagedSpanKind::ClaudeHook, - ) - .await; - assert!(matches!(expired, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("expiry is diagnosed"); - assert_eq!(fallback.reason, TelemetryFallbackReason::CredentialExpired); - assert!(!fallback.reason.is_failure()); - assert_eq!(fallback.detail, None); - - for (lookup, reason) in [ - ( - TelemetryCredentialLookup::Missing, - TelemetryFallbackReason::NotConfigured, - ), - ( - TelemetryCredentialLookup::Expired, - TelemetryFallbackReason::CredentialExpired, - ), - ( - TelemetryCredentialLookup::Unusable, - TelemetryFallbackReason::CredentialUnavailable, - ), - ] { - let (telemetry, fallback) = - RuntimeTelemetry::resolve_with(async { Ok(lookup) }, ManagedSpanKind::ClaudeHook) - .await; - assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); - let fallback = fallback.expect("unusable lookup is diagnosed"); - assert_eq!(fallback.reason, reason); - assert!(!fallback.reason.is_failure()); - assert_eq!(fallback.detail, None); - } - } - - fn tracked_lookup( - result: Result, - ) -> ( - std::sync::Arc, - impl Future> + Send + 'static, - ) { - let looked_up = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let flag = looked_up.clone(); - (looked_up, async move { - flag.store(true, std::sync::atomic::Ordering::SeqCst); - result - }) - } - - #[tokio::test] - async fn health_classifies_lookup_outcomes() { - let cases: Vec<( - Result, - ManagedTelemetryHealth, - )> = vec![ - ( - Ok(TelemetryCredentialLookup::Valid(credential( - "bao-token", - NOW + 60, - ))), - ManagedTelemetryHealth::Healthy, - ), - ( - Err(TokenStorageError::CredentialAccessUnavailable), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::CredentialInaccessible), - ), - ( - Ok(TelemetryCredentialLookup::Missing), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::NotConfigured), - ), - ( - Ok(TelemetryCredentialLookup::Expired), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::CredentialExpired), - ), - ( - Ok(TelemetryCredentialLookup::Unusable), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::CredentialUnavailable), - ), - ( - Ok(TelemetryCredentialLookup::Valid(credential( - "bao-token", - NOW, - ))), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::CredentialExpired), - ), - ( - Err(TokenStorageError::Database("locked".to_string())), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::DatabaseError), - ), - ( - Err(TokenStorageError::PathResolution("no home".to_string())), - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::PathResolutionError), - ), - ]; - for (result, expected) in cases { - let (looked_up, lookup) = tracked_lookup(result); - let health = inspect_health_with( - true, - || panic!("auth.db presence must not be probed when telemetry is enabled"), - lookup, - NOW, - ) - .await; - assert_eq!(health, expected); - assert!(looked_up.load(std::sync::atomic::Ordering::SeqCst)); - } - } - - #[tokio::test] - async fn health_lookup_is_bounded_by_the_credential_lookup_deadline() { - let started = std::time::Instant::now(); - let health = inspect_health_with( - true, - || false, - std::future::pending::>(), - NOW, - ) - .await; - assert!(started.elapsed() < CREDENTIAL_LOOKUP_DEADLINE * 2); - assert_eq!( - health, - ManagedTelemetryHealth::Disabled(TelemetryFallbackReason::LookupTimeout) - ); - } - #[test] fn absent_expired_or_blank_credential_selects_noop() { assert_eq!(select_mode(None, NOW), ManagedTelemetryMode::Noop); diff --git a/cli/src/services/managed_telemetry/trace_export.rs b/cli/src/services/managed_telemetry/trace_export.rs index 00e104219..957e1bf33 100644 --- a/cli/src/services/managed_telemetry/trace_export.rs +++ b/cli/src/services/managed_telemetry/trace_export.rs @@ -634,55 +634,6 @@ pub(crate) mod tests { loopback_telemetry_of_kind(address, token, ManagedSpanKind::Command) } - pub(crate) fn loopback_hook_telemetry( - address: std::net::SocketAddr, - token: &str, - ) -> ManagedTraceTelemetry { - loopback_telemetry_of_kind(address, token, ManagedSpanKind::ClaudeHook) - } - - fn loopback_hook_telemetry_with_traceparent( - address: std::net::SocketAddr, - traceparent: Option<&str>, - ) -> ManagedTraceTelemetry { - let mut telemetry = loopback_hook_telemetry(address, "bao-token-value"); - telemetry.parent_context = extract_parent_context( - traceparent.map(str::to_string), - Some("vendor=opaque".to_string()), - ); - telemetry - } - - const UPSTREAM_TRACE_ID: [u8; 16] = [ - 0x4b, 0xf9, 0x2f, 0x35, 0x77, 0xb3, 0x4d, 0xa6, 0xa3, 0xce, 0x92, 0x9d, 0x0e, 0x0e, 0x47, - 0x36, - ]; - const UPSTREAM_SPAN_ID: [u8; 8] = [0x00, 0xf0, 0x67, 0xaa, 0x0b, 0xa9, 0x02, 0xb7]; - const UPSTREAM_TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; - - async fn export_hook_spans( - traceparent: Option<&str>, - action: impl Future + Send + 'static, - ) -> Vec { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let address = listener.local_addr().expect("addr"); - let receiver = tokio::spawn(capture_requests(listener, "HTTP/1.1 200 OK", 1)); - let telemetry = loopback_hook_telemetry_with_traceparent(address, traceparent); - let mut action = Some(action); - let result = telemetry - .with_default_subscriber(&mut || { - let action = action.take().expect("single invocation"); - async move { - action.await; - Ok(String::new()) - } - }) - .await; - assert_eq!(result.expect("hook result"), ""); - telemetry.shutdown().await; - trace_spans(&receiver.await.expect("receiver join")) - } - fn loopback_telemetry_of_kind( address: std::net::SocketAddr, token: &str, @@ -827,186 +778,6 @@ pub(crate) mod tests { } } - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn claude_hook_export_posts_one_hook_span_with_correlation_ids_only() { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let address = listener.local_addr().expect("addr"); - let receiver = tokio::spawn(capture_requests(listener, "HTTP/1.1 200 OK", 1)); - let telemetry = loopback_hook_telemetry(address, "bao-token-value"); - let payload = r#"{"session_id":"session-7d07","transcript_path":"/home/u/private-repo/transcript.jsonl","cwd":"/home/u/private-repo","prompt":"PROMPT_TEXT_VALUE","hook_event_name":"PostToolUse","tool_name":"Write","tool_input":{"file_path":"/home/u/private-repo/src/secret.rs","content":"FILE_CONTENT_VALUE Bearer leak-value"},"tool_response":{"success":true,"output":"TOOL_RESPONSE_VALUE"},"tool_use_id":"toolu_01KN1s"}"#; - - let result = telemetry - .with_default_subscriber(&mut || async { - record_command_name("hooks"); - record_claude_hook_command(ClaudeHookCommand::DiffTrace); - record_claude_hook_payload(payload); - tokio::task::yield_now().await; - Ok(String::new()) - }) - .await; - assert_eq!(result.expect("hook result"), ""); - telemetry.shutdown().await; - - let requests = receiver.await.expect("receiver join"); - let spans = trace_spans(&requests); - assert_eq!(spans.len(), 1, "{spans:?}"); - let span = &spans[0]; - assert_eq!(span.name, "sce.hook"); - assert!(span.parent_span_id.is_empty()); - assert!(span - .resource_attributes - .contains(&("service.name".to_string(), "sce".to_string()))); - let expected = [ - ("sce.agent", "claude"), - ("sce.claude.session_id", "session-7d07"), - ("sce.claude.tool_use_id", "toolu_01KN1s"), - ("sce.hook.command", "diff-trace"), - ("sce.hook.event", "PostToolUse"), - ("sce.hook.tool", "Write"), - ("sce.outcome", "success"), - ] - .map(|(key, value)| (key.to_string(), value.to_string())); - assert_eq!(span.sce_attributes(), expected); - for request in &requests { - let body = String::from_utf8_lossy(&request.body).to_string(); - for leaked in [ - "private-repo", - "PROMPT_TEXT_VALUE", - "FILE_CONTENT_VALUE", - "TOOL_RESPONSE_VALUE", - "leak-value", - "bao-token-value", - "local-accessor-secret", - "sce.command", - ] { - assert!(!body.contains(leaked), "leaked {leaked}"); - } - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn claude_hook_span_joins_valid_upstream_trace_with_fresh_span_id() { - let spans = export_hook_spans(Some(UPSTREAM_TRACEPARENT), async { - tokio::task::yield_now().await; - }) - .await; - assert_eq!(spans.len(), 1, "{spans:?}"); - let span = &spans[0]; - assert_eq!(span.name, "sce.hook"); - assert_eq!(span.trace_id, UPSTREAM_TRACE_ID); - assert_eq!(span.parent_span_id, UPSTREAM_SPAN_ID); - assert_eq!(span.span_id.len(), 8); - assert_ne!(span.span_id, UPSTREAM_SPAN_ID); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn claude_hook_span_starts_independent_root_without_usable_traceparent() { - for traceparent in [ - None, - Some(""), - Some("not-a-traceparent"), - Some("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7"), - Some("00-4BF92F3577B34DA6A3CE929D0E0E4736-00f067aa0ba902b7-01"), - Some("ff-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"), - Some("00-00000000000000000000000000000000-00f067aa0ba902b7-01"), - Some("00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000000-01"), - ] { - let spans = export_hook_spans(traceparent, async {}).await; - assert_eq!(spans.len(), 1, "{traceparent:?}: {spans:?}"); - let span = &spans[0]; - assert_eq!(span.name, "sce.hook"); - assert!(span.parent_span_id.is_empty(), "{traceparent:?}"); - assert_eq!(span.trace_id.len(), 16, "{traceparent:?}"); - assert_ne!(span.trace_id, UPSTREAM_TRACE_ID, "{traceparent:?}"); - assert!( - span.trace_id.iter().any(|byte| *byte != 0), - "{traceparent:?}" - ); - } - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - async fn claude_hook_child_spans_inherit_upstream_trace_across_polls_and_workers() { - let spans = export_hook_spans(Some(UPSTREAM_TRACEPARENT), async { - for _ in 0..8 { - tokio::task::yield_now().await; - } - in_child_span(ManagedChildSpan::MutationScope, async { - tokio::task::yield_now().await; - tokio::spawn( - async { - tokio::task::yield_now().await; - in_child_span(ManagedChildSpan::GitSnapshot, async { - for _ in 0..4 { - tokio::task::yield_now().await; - } - Ok::<(), ()>(()) - }) - .await - } - .in_current_span() - .with_current_subscriber(), - ) - .await - .expect("spawned child join") - }) - .await - .expect("child span result"); - }) - .await; - assert_eq!(spans.len(), 3, "{spans:?}"); - let by_name = |name: &str| { - spans - .iter() - .find(|span| span.name == name) - .unwrap_or_else(|| panic!("missing {name}")) - }; - let hook = by_name("sce.hook"); - let child = by_name("sce.mutation_scope"); - let grandchild = by_name("sce.git_snapshot"); - for span in [hook, child, grandchild] { - assert_eq!(span.trace_id, UPSTREAM_TRACE_ID, "{}", span.name); - } - assert_eq!(hook.parent_span_id, UPSTREAM_SPAN_ID); - assert_eq!(child.parent_span_id, hook.span_id); - assert_eq!(grandchild.parent_span_id, child.span_id); - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn command_export_keeps_single_command_span_when_child_operations_run() { - let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); - let address = listener.local_addr().expect("addr"); - let (stop, stopped) = tokio::sync::oneshot::channel(); - let receiver = tokio::spawn(capture_requests_until(listener, stopped)); - let telemetry = loopback_telemetry(address, "bao-token-value"); - - let result = telemetry - .with_default_subscriber(&mut || async { - record_command_name("doctor"); - for kind in [ - ManagedChildSpan::MutationScope, - ManagedChildSpan::GitSnapshot, - ManagedChildSpan::Persistence, - ] { - in_child_span(kind, async { Ok::<(), ()>(()) }) - .await - .expect("child operation"); - } - Ok(String::new()) - }) - .await; - assert_eq!(result.expect("command result"), ""); - telemetry.shutdown().await; - stop.send(()).expect("stop receiver"); - - let spans = trace_spans(&receiver.await.expect("receiver join")); - let names = spans - .iter() - .map(|span| span.name.as_str()) - .collect::>(); - assert_eq!(names, ["sce.command"]); - } - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn managed_trace_export_does_not_follow_redirects_or_alter_results() { let destination = TcpListener::bind("127.0.0.1:0") diff --git a/cli/src/services/parse/command_runtime.rs b/cli/src/services/parse/command_runtime.rs index 7f745f796..3bea38104 100644 --- a/cli/src/services/parse/command_runtime.rs +++ b/cli/src/services/parse/command_runtime.rs @@ -582,46 +582,6 @@ mod tests { } } - #[test] - fn setup_reconfigure_parses_to_interactive_reconfigure_request() { - let RuntimeCommand::Setup(command) = parse(&["sce", "setup", "--reconfigure"]) else { - panic!("expected setup command"); - }; - - assert_eq!( - command.request.config_mode, - Some(services::setup::SetupMode::Interactive) - ); - assert!(command.request.reconfigure); - } - - #[test] - fn setup_reconfigure_with_a_target_fails_validation() { - let error = parse_runtime_command( - ["sce", "setup", "--claude", "--reconfigure"].map(String::from), - &CommandRegistry::default(), - None, - ) - .err() - .expect("reconfigure with a target should fail"); - - assert_eq!( - error.to_string(), - "Option '--reconfigure' cannot be used with '--claude'. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively." - ); - } - - #[test] - fn setup_help_lists_the_reconfigure_flag() { - let help = - cli_schema::render_help_for_path(&["setup"]).expect("setup help should be renderable"); - - assert!( - help.contains("--reconfigure"), - "setup help should list --reconfigure, got: {help}" - ); - } - #[test] fn sync_parses_to_sync_request_with_default_text_format() { let command = parse(&["sce", "sync"]); diff --git a/cli/src/services/setup/access_preferences.rs b/cli/src/services/setup/access_preferences.rs index 7a548b566..690d9f02a 100644 --- a/cli/src/services/setup/access_preferences.rs +++ b/cli/src/services/setup/access_preferences.rs @@ -208,333 +208,3 @@ fn read_optional(path: &Path) -> anyhow::Result>> { .with_context(|| format!("Failed to read global SCE config '{}'", path.display())), } } - -#[cfg(test)] -mod tests { - use super::*; - use serde_json::json; - - fn read_json(path: &Path) -> Value { - serde_json::from_slice(&fs::read(path).unwrap()).unwrap() - } - - fn write_json(path: &Path, value: &Value) { - fs::write(path, serde_json::to_vec_pretty(value).unwrap()).unwrap(); - } - - #[test] - fn access_preferences_writer_sets_only_requested_keys() { - struct Case { - name: &'static str, - initial: Option, - auth_mode: Option, - telemetry_enabled: Option, - expected: Value, - } - - let schema = sce_config_schema_url(); - let cases = [ - Case { - name: "missing file", - initial: None, - auth_mode: Some(AuthMode::Optional), - telemetry_enabled: Some(false), - expected: json!({ - "$schema": schema, - "auth": {"mode": "optional"}, - "telemetry": {"enabled": false} - }), - }, - Case { - name: "empty object", - initial: Some(json!({})), - auth_mode: None, - telemetry_enabled: Some(true), - expected: json!({"telemetry": {"enabled": true}}), - }, - Case { - name: "unrelated keys preserved", - initial: Some(json!({ - "log_level": "debug", - "agent_trace": {"auto_sync": true}, - "policies": {"attribution_hooks": {"enabled": false}} - })), - auth_mode: Some(AuthMode::Mandatory), - telemetry_enabled: None, - expected: json!({ - "log_level": "debug", - "agent_trace": {"auto_sync": true}, - "policies": {"attribution_hooks": {"enabled": false}}, - "auth": {"mode": "mandatory"} - }), - }, - Case { - name: "explicit values replaced", - initial: Some(json!({ - "auth": {"mode": "disabled"}, - "telemetry": {"enabled": true} - })), - auth_mode: Some(AuthMode::Optional), - telemetry_enabled: Some(false), - expected: json!({ - "auth": {"mode": "optional"}, - "telemetry": {"enabled": false} - }), - }, - ]; - - for case in cases { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("sce").join("config.json"); - if let Some(initial) = &case.initial { - fs::create_dir_all(path.parent().unwrap()).unwrap(); - write_json(&path, initial); - } - - let outcome = - persist_global_access_preferences(&path, case.auth_mode, case.telemetry_enabled) - .unwrap(); - - assert_eq!(outcome, GlobalWriteOutcome::Written, "{}", case.name); - assert_eq!(read_json(&path), case.expected, "{}", case.name); - assert!( - fs::read_to_string(&path).unwrap().ends_with("}\n"), - "{}", - case.name - ); - assert_eq!( - read_global_access_preferences(&path).unwrap(), - GlobalAccessPreferences::Valid { - auth_mode: case.auth_mode, - telemetry_enabled: case.telemetry_enabled, - }, - "{}", - case.name - ); - } - } - - #[test] - fn access_preferences_writer_is_idempotent_on_rerun() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - - persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); - let first = fs::read(&path).unwrap(); - - let outcome = - persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); - - assert_eq!(outcome, GlobalWriteOutcome::Unchanged); - assert_eq!(fs::read(&path).unwrap(), first); - } - - #[test] - fn access_preferences_writer_without_answers_never_creates_file() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - - let outcome = persist_global_access_preferences(&path, None, None).unwrap(); - - assert_eq!(outcome, GlobalWriteOutcome::Unchanged); - assert!(!path.exists()); - } - - #[cfg(unix)] - #[test] - fn access_preferences_writer_preserves_existing_mode_and_creates_private_file() { - use std::os::unix::fs::PermissionsExt; - - let dir = tempfile::tempdir().unwrap(); - let existing = dir.path().join("existing.json"); - write_json(&existing, &json!({})); - fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap(); - let created = dir.path().join("created.json"); - - persist_global_access_preferences(&existing, Some(AuthMode::Optional), None).unwrap(); - persist_global_access_preferences(&created, Some(AuthMode::Optional), None).unwrap(); - - assert_eq!( - fs::metadata(&existing).unwrap().permissions().mode() & 0o777, - 0o644 - ); - assert_eq!( - fs::metadata(&created).unwrap().permissions().mode() & 0o777, - 0o600 - ); - } - - #[test] - fn access_preferences_writer_refuses_invalid_files_without_touching_them() { - let cases: [(&str, &[u8]); 4] = [ - ("invalid json", b"{not json"), - ("schema invalid mode", br#"{"auth":{"mode":"required"}}"#), - ("unknown top-level key", br#"{"surprise":true}"#), - ("not utf8", &[0xff, 0xfe, 0x00]), - ]; - - for (name, bytes) in cases { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - fs::write(&path, bytes).unwrap(); - - let error = - persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)) - .unwrap_err(); - - assert!( - matches!( - error, - GlobalAccessPreferencesError::InvalidGlobalConfig { .. } - ), - "{name}: {error}" - ); - assert_eq!(fs::read(&path).unwrap(), bytes, "{name}"); - assert_eq!( - read_global_access_preferences(&path).unwrap(), - GlobalAccessPreferences::Invalid, - "{name}" - ); - } - } - - #[test] - fn access_preferences_writer_detects_concurrent_modification_before_rename() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - write_json(&path, &json!({"log_level": "info"})); - let concurrent = br#"{"log_level":"debug"}"#.to_vec(); - - let error = persist_global_access_preferences_with( - &path, - Some(AuthMode::Optional), - Some(true), - |reread_path| { - fs::write(reread_path, &concurrent).unwrap(); - read_optional(reread_path) - }, - ) - .unwrap_err(); - - assert!(matches!( - error, - GlobalAccessPreferencesError::ConcurrentModification { .. } - )); - assert_eq!(fs::read(&path).unwrap(), concurrent); - } - - #[cfg(unix)] - #[test] - fn access_preferences_writer_reports_io_error_for_read_only_directory() { - use std::os::unix::fs::PermissionsExt; - - let dir = tempfile::tempdir().unwrap(); - let config_dir = dir.path().join("sce"); - fs::create_dir_all(&config_dir).unwrap(); - let path = config_dir.join("config.json"); - let original = br#"{"log_level":"info"}"#.to_vec(); - fs::write(&path, &original).unwrap(); - fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o555)).unwrap(); - - let result = persist_global_access_preferences(&path, Some(AuthMode::Optional), None); - - fs::set_permissions(&config_dir, fs::Permissions::from_mode(0o755)).unwrap(); - assert!(matches!(result, Err(GlobalAccessPreferencesError::Io(_)))); - assert_eq!(fs::read(&path).unwrap(), original); - } - - #[cfg(unix)] - #[test] - fn access_preferences_writer_refuses_to_replace_symlinked_global_config() { - use std::os::unix::fs::{symlink, PermissionsExt}; - - let original = br#"{"log_level":"info"}"#.to_vec(); - for (name, target_exists, target_mode) in [ - ("valid target", true, 0o644), - ("read-only target", true, 0o444), - ("dangling target", false, 0o644), - ] { - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("store").join("config.json"); - fs::create_dir_all(target.parent().unwrap()).unwrap(); - if target_exists { - fs::write(&target, &original).unwrap(); - fs::set_permissions(&target, fs::Permissions::from_mode(target_mode)).unwrap(); - } - let path = dir.path().join("config.json"); - symlink(&target, &path).unwrap(); - - let error = - persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)) - .unwrap_err(); - - assert!( - matches!(error, GlobalAccessPreferencesError::SymlinkManaged { .. }), - "{name}: {error}" - ); - assert!( - error - .to_string() - .contains("Update the file's source directly"), - "{name}" - ); - assert!( - fs::symlink_metadata(&path) - .unwrap() - .file_type() - .is_symlink(), - "{name}" - ); - assert_eq!(fs::read_link(&path).unwrap(), target, "{name}"); - if target_exists { - assert_eq!(fs::read(&target).unwrap(), original, "{name}"); - } else { - assert!(!target.exists(), "{name}"); - } - assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2, "{name}"); - } - } - - #[cfg(unix)] - #[test] - fn access_preferences_writer_leaves_symlinked_global_config_alone_when_unchanged() { - use std::os::unix::fs::symlink; - - let dir = tempfile::tempdir().unwrap(); - let target = dir.path().join("target.json"); - let current = br#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#.to_vec(); - fs::write(&target, ¤t).unwrap(); - let path = dir.path().join("config.json"); - symlink(&target, &path).unwrap(); - - let outcome = - persist_global_access_preferences(&path, Some(AuthMode::Optional), Some(true)).unwrap(); - - assert_eq!(outcome, GlobalWriteOutcome::Unchanged); - assert!(fs::symlink_metadata(&path) - .unwrap() - .file_type() - .is_symlink()); - assert_eq!(fs::read(&target).unwrap(), current); - } - - #[test] - fn access_preferences_reader_distinguishes_missing_and_absent_keys() { - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - - assert_eq!( - read_global_access_preferences(&path).unwrap(), - GlobalAccessPreferences::Missing - ); - - write_json(&path, &json!({"log_level": "info"})); - assert_eq!( - read_global_access_preferences(&path).unwrap(), - GlobalAccessPreferences::Valid { - auth_mode: None, - telemetry_enabled: None, - } - ); - } -} diff --git a/cli/src/services/setup/claude_telemetry.rs b/cli/src/services/setup/claude_telemetry.rs index 0bbe7ffb8..ebb56fdbe 100644 --- a/cli/src/services/setup/claude_telemetry.rs +++ b/cli/src/services/setup/claude_telemetry.rs @@ -7,7 +7,9 @@ use anyhow::{Context, Result}; use super::atomic_write::write_atomically; use super::config_merge::{ - merge_claude_telemetry_settings, ClaudeTelemetryMergeOutcome, ClaudeTelemetrySkipReason, + merge_claude_telemetry_settings, remove_claude_telemetry_settings, + settings_configure_claude_telemetry, ClaudeTelemetryMergeOutcome, ClaudeTelemetryRemovalMerge, + ClaudeTelemetrySkipReason, }; const CLAUDE_CONFIG_DIR_ENV: &str = "CLAUDE_CONFIG_DIR"; @@ -42,13 +44,53 @@ const SKIPPED_HELPER_SETTING_LINE: &str = const SKIPPED_MANAGED_LINE: &str = "Claude telemetry: skipped; managed Claude settings own the telemetry configuration."; const SKIPPED_INVALID_LINE: &str = - "Claude telemetry: skipped; existing Claude settings could not be parsed and were left unchanged."; + "Claude telemetry: skipped; existing Claude settings contain invalid JSON or an invalid structure and were left unchanged. Fix the settings, then rerun 'sce setup'."; +const SKIPPED_SYMLINK_LINE: &str = + "Claude telemetry: skipped; settings.json is symlink-managed and was left unchanged. Update the telemetry settings at their source (for example Nix or Home Manager), then rerun 'sce setup'."; +const INSTALL_READ_FAILED_LINE: &str = + "Claude telemetry: failed to read Claude settings. Check settings files and directory permissions, then rerun 'sce setup'."; +const INSTALL_WRITE_FAILED_LINE: &str = + "Claude telemetry: failed to write Claude settings. Check directory permissions and available disk space, then rerun 'sce setup'."; +const SETTINGS_PATH_UNAVAILABLE_LINE: &str = + "Claude telemetry: could not resolve the Claude settings path. Set CLAUDE_CONFIG_DIR, then rerun 'sce setup'."; +pub(crate) const CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE: &str = + "Claude telemetry: skipped; SCE telemetry is disabled by config."; + +const REMOVAL_LINE_PREFIX: &str = "Claude telemetry:"; +const REMOVED_TEXT: &str = "removed SCE-managed telemetry settings from user-level Claude settings"; +const REMOVED_REASON_TEXT: &str = "because the global SCE config disables telemetry."; +const PRESERVED_TEXT: &str = "left user-level Claude settings"; +const PRESERVED_MODIFIED_TEXT: &str = "unchanged; SCE-managed telemetry settings were modified"; +const PRESERVED_HELPER_MISSING_TEXT: &str = + "unchanged; they set the SCE OTLP endpoint without the SCE headers helper."; +const PRESERVED_INVALID_TEXT: &str = + "unchanged; they could not be parsed. Fix the file, then rerun 'sce setup'."; +const PRESERVED_SYMLINK_TEXT: &str = + "unchanged; the file is a symlink. Remove the SCE telemetry entries from its source directly (for example Nix or Home Manager)."; +const PRESERVED_READ_ONLY_TEXT: &str = + "unchanged; the file is read-only. Remove the SCE telemetry entries manually."; +const MANUAL_REMOVAL_TEXT: &str = "Remove the SCE telemetry entries manually."; +const STAYS_DISABLED_TEXT: &str = "SCE telemetry stays disabled by config."; +const FAILED_TEXT: &str = + "did not remove SCE-managed telemetry settings from user-level Claude settings"; +const CONSENT_WITHDRAWN_TEXT: &str = "SCE telemetry consent remains withdrawn."; +const CONCURRENT_MODIFICATION_TEXT: &str = + "the file changed while setup was updating it; rerun 'sce setup'"; +const READ_FAILED_TEXT: &str = "the file could not be read"; +const WRITE_FAILED_TEXT: &str = "the file could not be replaced"; +const MANAGED_NOTE_LINE: &str = + "Claude telemetry: managed Claude settings also configure telemetry; SCE does not change them."; #[derive(Debug, Eq, PartialEq)] pub(crate) enum ClaudeTelemetryInstallOutcome { Configured, + AlreadyCurrent, SkippedConflict(ClaudeTelemetrySkipReason), SkippedInvalid, + SkippedSymlink, + ReadFailed, + WriteFailed, + SettingsPathUnavailable, } pub(crate) fn resolve_claude_settings_path() -> Option { @@ -72,22 +114,46 @@ pub(crate) fn managed_claude_settings_path() -> PathBuf { pub(crate) fn install_claude_telemetry( settings_path: &Path, managed_settings_path: &Path, -) -> Result { - let existing = read_optional(settings_path)?; - let managed = read_optional(managed_settings_path).unwrap_or(None); +) -> ClaudeTelemetryInstallOutcome { + let is_symlink = match fs::symlink_metadata(settings_path) { + Ok(metadata) => metadata.file_type().is_symlink(), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => return ClaudeTelemetryInstallOutcome::ReadFailed, + }; + let existing = match read_optional(settings_path) { + Ok(None) if is_symlink => return ClaudeTelemetryInstallOutcome::SkippedSymlink, + Ok(existing) => existing, + Err(_) => return ClaudeTelemetryInstallOutcome::ReadFailed, + }; + let Ok(managed) = read_optional(managed_settings_path) else { + return ClaudeTelemetryInstallOutcome::ReadFailed; + }; let source_path = settings_path.display().to_string(); match merge_claude_telemetry_settings(existing.as_deref(), managed.as_deref(), &source_path) { - Err(_) => Ok(ClaudeTelemetryInstallOutcome::SkippedInvalid), + Err(_) => ClaudeTelemetryInstallOutcome::SkippedInvalid, Ok(ClaudeTelemetryMergeOutcome::AlreadyCurrent) => { - Ok(ClaudeTelemetryInstallOutcome::Configured) + ClaudeTelemetryInstallOutcome::AlreadyCurrent } Ok(ClaudeTelemetryMergeOutcome::Skipped(reason)) => { - Ok(ClaudeTelemetryInstallOutcome::SkippedConflict(reason)) + ClaudeTelemetryInstallOutcome::SkippedConflict(reason) } Ok(ClaudeTelemetryMergeOutcome::Installed(bytes)) => { - write_atomically(settings_path, &bytes)?; - Ok(ClaudeTelemetryInstallOutcome::Configured) + if is_symlink { + return ClaudeTelemetryInstallOutcome::SkippedSymlink; + } + match fs::symlink_metadata(settings_path) { + Ok(metadata) if metadata.file_type().is_symlink() => { + return ClaudeTelemetryInstallOutcome::SkippedSymlink; + } + Ok(_) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return ClaudeTelemetryInstallOutcome::ReadFailed, + } + match write_atomically(settings_path, &bytes) { + Ok(()) => ClaudeTelemetryInstallOutcome::Configured, + Err(_) => ClaudeTelemetryInstallOutcome::WriteFailed, + } } } } @@ -104,7 +170,8 @@ pub(crate) fn format_claude_telemetry_report( authorization: RepositoryAuthorization, ) -> String { match outcome { - ClaudeTelemetryInstallOutcome::Configured => match authorization { + ClaudeTelemetryInstallOutcome::Configured + | ClaudeTelemetryInstallOutcome::AlreadyCurrent => match authorization { RepositoryAuthorization::Authorized => CONFIGURED_LINE.to_string(), RepositoryAuthorization::Unauthorized => { format!("{CONFIGURED_LINE}\n{NOT_READY_LINE}") @@ -115,6 +182,12 @@ pub(crate) fn format_claude_telemetry_report( skipped_conflict_line(*reason).to_string() } ClaudeTelemetryInstallOutcome::SkippedInvalid => SKIPPED_INVALID_LINE.to_string(), + ClaudeTelemetryInstallOutcome::SkippedSymlink => SKIPPED_SYMLINK_LINE.to_string(), + ClaudeTelemetryInstallOutcome::ReadFailed => INSTALL_READ_FAILED_LINE.to_string(), + ClaudeTelemetryInstallOutcome::WriteFailed => INSTALL_WRITE_FAILED_LINE.to_string(), + ClaudeTelemetryInstallOutcome::SettingsPathUnavailable => { + SETTINGS_PATH_UNAVAILABLE_LINE.to_string() + } } } @@ -132,6 +205,179 @@ fn skipped_conflict_line(reason: ClaudeTelemetrySkipReason) -> &'static str { } } +#[derive(Debug, Eq, PartialEq)] +pub(crate) enum ClaudeTelemetryRemovalOutcome { + Removed, + NotInstalled, + PreservedModified(ClaudeTelemetrySkipReason), + PreservedHelperMissing, + PreservedInvalid, + PreservedSymlink, + PreservedReadOnly, + Failed(String), +} + +#[derive(Debug, Eq, PartialEq)] +pub(crate) struct ClaudeTelemetryRemovalReport { + pub(crate) settings_path: PathBuf, + pub(crate) outcome: ClaudeTelemetryRemovalOutcome, + pub(crate) managed_configures_telemetry: bool, +} + +pub(crate) fn remove_claude_telemetry( + settings_path: &Path, + managed_settings_path: &Path, +) -> ClaudeTelemetryRemovalReport { + remove_claude_telemetry_with(settings_path, managed_settings_path, |path| fs::read(path)) +} + +fn remove_claude_telemetry_with( + settings_path: &Path, + managed_settings_path: &Path, + reread: R, +) -> ClaudeTelemetryRemovalReport +where + R: FnOnce(&Path) -> std::io::Result>, +{ + let managed_configures_telemetry = read_optional(managed_settings_path) + .ok() + .flatten() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .is_some_and(|managed| settings_configure_claude_telemetry(&managed)); + ClaudeTelemetryRemovalReport { + settings_path: settings_path.to_path_buf(), + outcome: removal_outcome(settings_path, reread), + managed_configures_telemetry, + } +} + +fn removal_outcome(settings_path: &Path, reread: R) -> ClaudeTelemetryRemovalOutcome +where + R: FnOnce(&Path) -> std::io::Result>, +{ + let original = match fs::read(settings_path) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + return ClaudeTelemetryRemovalOutcome::NotInstalled; + } + Err(error) => { + return ClaudeTelemetryRemovalOutcome::Failed(format!("{READ_FAILED_TEXT}: {error}")); + } + }; + let source_path = settings_path.display().to_string(); + + let bytes = match remove_claude_telemetry_settings(Some(&original), &source_path) { + Err(_) => return ClaudeTelemetryRemovalOutcome::PreservedInvalid, + Ok(ClaudeTelemetryRemovalMerge::NotInstalled) => { + return ClaudeTelemetryRemovalOutcome::NotInstalled; + } + Ok(ClaudeTelemetryRemovalMerge::Modified(reason)) => { + return ClaudeTelemetryRemovalOutcome::PreservedModified(reason); + } + Ok(ClaudeTelemetryRemovalMerge::HelperMissing) => { + return ClaudeTelemetryRemovalOutcome::PreservedHelperMissing; + } + Ok(ClaudeTelemetryRemovalMerge::Removed(bytes)) => bytes, + }; + + let metadata = match fs::symlink_metadata(settings_path) { + Ok(metadata) => metadata, + Err(error) => { + return ClaudeTelemetryRemovalOutcome::Failed(format!("{READ_FAILED_TEXT}: {error}")); + } + }; + if metadata.file_type().is_symlink() { + return ClaudeTelemetryRemovalOutcome::PreservedSymlink; + } + if is_read_only(&metadata) { + return ClaudeTelemetryRemovalOutcome::PreservedReadOnly; + } + match reread(settings_path) { + Ok(current) if current == original => {} + Ok(_) => { + return ClaudeTelemetryRemovalOutcome::Failed(CONCURRENT_MODIFICATION_TEXT.to_string()); + } + Err(error) => { + return ClaudeTelemetryRemovalOutcome::Failed(format!("{READ_FAILED_TEXT}: {error}")); + } + } + + match write_atomically(settings_path, &bytes) { + Ok(()) => ClaudeTelemetryRemovalOutcome::Removed, + Err(error) => { + ClaudeTelemetryRemovalOutcome::Failed(format!("{WRITE_FAILED_TEXT}: {error:#}")) + } + } +} + +#[cfg(unix)] +fn is_read_only(metadata: &fs::Metadata) -> bool { + use std::os::unix::fs::PermissionsExt; + + metadata.permissions().mode() & 0o200 == 0 +} + +#[cfg(not(unix))] +fn is_read_only(metadata: &fs::Metadata) -> bool { + metadata.permissions().readonly() +} + +pub(crate) fn format_claude_telemetry_removal_report( + report: &ClaudeTelemetryRemovalReport, + claude_selected: bool, +) -> Option { + let path = report.settings_path.display(); + let line = match &report.outcome { + ClaudeTelemetryRemovalOutcome::Removed => { + format!("{REMOVAL_LINE_PREFIX} {REMOVED_TEXT} '{path}' {REMOVED_REASON_TEXT}") + } + ClaudeTelemetryRemovalOutcome::NotInstalled if claude_selected => { + CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE.to_string() + } + ClaudeTelemetryRemovalOutcome::NotInstalled => return None, + ClaudeTelemetryRemovalOutcome::PreservedModified(reason) => format!( + "{REMOVAL_LINE_PREFIX} {PRESERVED_TEXT} '{path}' {PRESERVED_MODIFIED_TEXT} ({}). {MANUAL_REMOVAL_TEXT} {STAYS_DISABLED_TEXT}", + modified_reason_text(*reason) + ), + ClaudeTelemetryRemovalOutcome::PreservedHelperMissing => format!( + "{REMOVAL_LINE_PREFIX} {PRESERVED_TEXT} '{path}' {PRESERVED_HELPER_MISSING_TEXT} {MANUAL_REMOVAL_TEXT} {STAYS_DISABLED_TEXT}" + ), + ClaudeTelemetryRemovalOutcome::PreservedInvalid => format!( + "{REMOVAL_LINE_PREFIX} {PRESERVED_TEXT} '{path}' {PRESERVED_INVALID_TEXT} {STAYS_DISABLED_TEXT}" + ), + ClaudeTelemetryRemovalOutcome::PreservedSymlink => format!( + "{REMOVAL_LINE_PREFIX} {PRESERVED_TEXT} '{path}' {PRESERVED_SYMLINK_TEXT} {STAYS_DISABLED_TEXT}" + ), + ClaudeTelemetryRemovalOutcome::PreservedReadOnly => format!( + "{REMOVAL_LINE_PREFIX} {PRESERVED_TEXT} '{path}' {PRESERVED_READ_ONLY_TEXT} {STAYS_DISABLED_TEXT}" + ), + ClaudeTelemetryRemovalOutcome::Failed(detail) => format!( + "{REMOVAL_LINE_PREFIX} {FAILED_TEXT} '{path}'; {detail}. {MANUAL_REMOVAL_TEXT} {CONSENT_WITHDRAWN_TEXT}" + ), + }; + if report.managed_configures_telemetry { + Some(format!("{line}\n{MANAGED_NOTE_LINE}")) + } else { + Some(line) + } +} + +fn modified_reason_text(reason: ClaudeTelemetrySkipReason) -> &'static str { + match reason { + ClaudeTelemetrySkipReason::UserHelperPresent => "different otelHeadersHelper", + ClaudeTelemetrySkipReason::TelemetryDisabled => "telemetry or tracing disabled", + ClaudeTelemetrySkipReason::PrivacySettingConflict => "repository attributes opted out", + ClaudeTelemetrySkipReason::ConflictingEndpoint => "different OTLP endpoint", + ClaudeTelemetrySkipReason::ConflictingHeaders => "OTLP headers defined", + ClaudeTelemetrySkipReason::ConflictingProtocol => "different OTLP protocol", + ClaudeTelemetrySkipReason::ConflictingExporter => "different telemetry exporter", + ClaudeTelemetrySkipReason::ConflictingHelperSetting => { + "different headers helper refresh interval" + } + ClaudeTelemetrySkipReason::ManagedSettingsConflict => "managed settings conflict", + } +} + fn read_optional(path: &Path) -> Result>> { match fs::read(path) { Ok(bytes) => Ok(Some(bytes)), @@ -151,13 +397,101 @@ mod tests { serde_json::from_slice(&fs::read(path).unwrap()).unwrap() } + #[cfg(unix)] + #[test] + fn claude_telemetry_install_preserves_symlinks_and_their_targets() { + use std::os::unix::fs::{symlink, MetadataExt}; + + for case in ["needs_changes", "dangling", "already_current"] { + let dir = tempfile::tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + let target = dir.path().join("source.json"); + let managed = dir.path().join("managed.json"); + if case == "already_current" { + assert_eq!( + install_claude_telemetry(&target, &managed), + ClaudeTelemetryInstallOutcome::Configured + ); + } else if case == "needs_changes" { + fs::write(&target, b"{\"env\":{\"KEEP\":\"me\"}}\n").unwrap(); + } + symlink(&target, &settings).unwrap(); + let snapshot = |path: &Path| { + fs::symlink_metadata(path).ok().map(|metadata| { + ( + metadata.ino(), + metadata.mode(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.ctime(), + metadata.ctime_nsec(), + ) + }) + }; + let link_before = snapshot(&settings); + let target_before = snapshot(&target); + let bytes_before = fs::read(&target).ok(); + + let outcome = install_claude_telemetry(&settings, &managed); + + assert_eq!( + outcome, + if case == "already_current" { + ClaudeTelemetryInstallOutcome::AlreadyCurrent + } else { + ClaudeTelemetryInstallOutcome::SkippedSymlink + }, + "{case}" + ); + assert_eq!(fs::read_link(&settings).unwrap(), target); + assert_eq!(snapshot(&settings), link_before, "{case}"); + assert_eq!(snapshot(&target), target_before, "{case}"); + assert_eq!(fs::read(&target).ok(), bytes_before, "{case}"); + assert!(!settings.with_extension("json.sce-tmp").exists()); + } + } + + #[test] + fn claude_telemetry_install_classifies_filesystem_failures() { + for case in ["user_read", "managed_read", "write"] { + let dir = tempfile::tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + let managed = dir.path().join("managed.json"); + if case == "user_read" { + fs::create_dir(&settings).unwrap(); + } else { + fs::write(&settings, b"{}").unwrap(); + if case == "managed_read" { + fs::create_dir(&managed).unwrap(); + } else { + fs::create_dir(settings.with_extension("json.sce-tmp")).unwrap(); + } + } + let outcome = install_claude_telemetry(&settings, &managed); + assert_eq!( + outcome, + if case == "write" { + ClaudeTelemetryInstallOutcome::WriteFailed + } else { + ClaudeTelemetryInstallOutcome::ReadFailed + }, + "{case}" + ); + if case == "user_read" { + assert!(settings.is_dir()); + } else { + assert_eq!(fs::read(&settings).unwrap(), b"{}"); + } + } + } + #[test] fn claude_telemetry_install_writes_env_and_helper_idempotently() { let dir = tempfile::tempdir().unwrap(); let settings = dir.path().join("claude").join("settings.json"); let managed = dir.path().join("managed.json"); - let outcome = install_claude_telemetry(&settings, &managed).unwrap(); + let outcome = install_claude_telemetry(&settings, &managed); assert_eq!(outcome, ClaudeTelemetryInstallOutcome::Configured); let first = fs::read(&settings).unwrap(); let parsed: Value = serde_json::from_slice(&first).unwrap(); @@ -167,7 +501,10 @@ mod tests { .unwrap() .contains(FIXTURE_TOKEN)); - install_claude_telemetry(&settings, &managed).unwrap(); + assert_eq!( + install_claude_telemetry(&settings, &managed), + ClaudeTelemetryInstallOutcome::AlreadyCurrent + ); assert_eq!(fs::read(&settings).unwrap(), first); } @@ -190,7 +527,7 @@ mod tests { .unwrap(); fs::set_permissions(&settings, fs::Permissions::from_mode(0o640)).unwrap(); - install_claude_telemetry(&settings, &managed).unwrap(); + install_claude_telemetry(&settings, &managed); let parsed = read_json(&settings); assert_eq!(parsed["permissions"]["allow"][0], "Bash(ls)"); @@ -208,7 +545,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let settings = dir.path().join("settings.json"); - install_claude_telemetry(&settings, &dir.path().join("managed.json")).unwrap(); + install_claude_telemetry(&settings, &dir.path().join("managed.json")); assert_eq!( fs::metadata(&settings).unwrap().permissions().mode() & 0o777, 0o600 @@ -222,8 +559,7 @@ mod tests { let original = serde_json::to_vec(&json!({"otelHeadersHelper": "my-helper"})).unwrap(); fs::write(&settings, &original).unwrap(); - let outcome = - install_claude_telemetry(&settings, &dir.path().join("managed.json")).unwrap(); + let outcome = install_claude_telemetry(&settings, &dir.path().join("managed.json")); assert!(matches!( outcome, @@ -234,15 +570,16 @@ mod tests { #[test] fn claude_telemetry_install_refuses_malformed_json_without_overwriting() { - let dir = tempfile::tempdir().unwrap(); - let settings = dir.path().join("settings.json"); - fs::write(&settings, b"{ not json").unwrap(); + for original in [b"{ not json".as_slice(), b"[]", b"{\"env\": []}"] { + let dir = tempfile::tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + fs::write(&settings, original).unwrap(); - let outcome = - install_claude_telemetry(&settings, &dir.path().join("managed.json")).unwrap(); + let outcome = install_claude_telemetry(&settings, &dir.path().join("managed.json")); - assert_eq!(outcome, ClaudeTelemetryInstallOutcome::SkippedInvalid); - assert_eq!(fs::read(&settings).unwrap(), b"{ not json"); + assert_eq!(outcome, ClaudeTelemetryInstallOutcome::SkippedInvalid); + assert_eq!(fs::read(&settings).unwrap(), original); + } } #[test] @@ -256,7 +593,7 @@ mod tests { ) .unwrap(); - let outcome = install_claude_telemetry(&settings, &managed).unwrap(); + let outcome = install_claude_telemetry(&settings, &managed); assert!(matches!( outcome, @@ -273,8 +610,7 @@ mod tests { serde_json::to_vec(&json!({"env": {"CLAUDE_CODE_ENABLE_TELEMETRY": "0"}})).unwrap(); fs::write(&settings, &original).unwrap(); - let outcome = - install_claude_telemetry(&settings, &dir.path().join("managed.json")).unwrap(); + let outcome = install_claude_telemetry(&settings, &dir.path().join("managed.json")); assert_eq!( outcome, @@ -288,22 +624,4 @@ mod tests { assert!(report.contains("explicitly disable telemetry")); assert!(!report.contains("configured")); } - - #[test] - fn claude_telemetry_report_marks_unready_repository_without_helper_name() { - let report = |authorization| { - format_claude_telemetry_report( - &ClaudeTelemetryInstallOutcome::Configured, - authorization, - ) - }; - let pending = report(RepositoryAuthorization::Unauthorized); - let not_checked = report(RepositoryAuthorization::NotChecked); - - assert!(pending.contains("not ready for this repository")); - assert_eq!(report(RepositoryAuthorization::Authorized), CONFIGURED_LINE); - assert_eq!(not_checked, NOT_CHECKED_LINE); - assert!(!not_checked.contains("not ready")); - assert!(!pending.contains("telemetry-headers")); - } } diff --git a/cli/src/services/setup/command.rs b/cli/src/services/setup/command.rs index 1846477fc..de70722dd 100644 --- a/cli/src/services/setup/command.rs +++ b/cli/src/services/setup/command.rs @@ -11,13 +11,12 @@ use crate::services::lifecycle::{ lifecycle_providers, RequiredHookInstallStatus, RequiredHooksInstallOutcome, }; use crate::services::setup::access_preferences::{ - persist_global_access_preferences, read_global_access_preferences, + persist_global_access_preferences, read_global_access_preferences, GlobalAccessPreferences, GlobalAccessPreferencesError, GlobalWriteOutcome, }; +use crate::services::setup::claude_telemetry::CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE; use crate::services::{config, managed_telemetry, setup}; -const CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE: &str = - "Claude telemetry: skipped; SCE telemetry is disabled by config."; const SCE_ACCESS_HEADING: &str = "SCE access:"; const SAVED_ACCESS_SCOPE: &str = "applies to all repositories on this machine"; const AUTH_LOGOUT_HINT_LINE: &str = @@ -112,7 +111,19 @@ impl SetupCommand { .map_err(unexpected_failure)?; sections.push(setup_message); - if let Some((access_save, auth_db_present)) = &interactive_access { + let render_claude_telemetry = async |action| { + claude_telemetry_report( + &repository_root, + action, + claude_telemetry_selected, + authorization_check, + ) + .await + }; + + let deferred_telemetry_action = if let Some((access_save, auth_db_present)) = + &interactive_access + { let (access_section, policy) = setup_access_report( &repository_root, access_save, @@ -121,17 +132,27 @@ impl SetupCommand { )?; sections.push(access_section); + let (removal_action, deferred_action) = + split_pre_login_removal(claude_telemetry_action( + read_global_preferences(&access_save.global_config_path), + policy.telemetry_enabled(), + claude_telemetry_selected, + true, + )); + sections.extend(render_claude_telemetry(removal_action).await); + let login_status = run_setup_login_step(setup_login_action(&policy, login_intent), || { auth_command::run_login_in(&repository_root, AuthFormat::Text) }) .await?; sections.push(render_setup_login_section(&login_status)); - } + deferred_action + } else { + non_interactive_claude_telemetry_action(&repository_root, claude_telemetry_selected) + }; - if claude_telemetry_selected { - sections.push(claude_telemetry_report(&repository_root, authorization_check).await); - } + sections.extend(render_claude_telemetry(deferred_telemetry_action).await); } Ok(sections.join("\n\n")) @@ -508,15 +529,91 @@ impl RepositoryAuthorizationCheck { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ClaudeTelemetryAction { + Install, + Remove, + SkipDisabled, +} + +fn global_consent_withdrawn(global: GlobalAccessPreferences) -> bool { + matches!( + global, + GlobalAccessPreferences::Valid { + telemetry_enabled: Some(false), + .. + } | GlobalAccessPreferences::Valid { + auth_mode: Some(AuthMode::Disabled), + .. + } + ) +} + +fn claude_telemetry_action( + global: GlobalAccessPreferences, + effective_enabled: bool, + claude_selected: bool, + interactive: bool, +) -> Option { + if global_consent_withdrawn(global) && (interactive || claude_selected) { + return Some(ClaudeTelemetryAction::Remove); + } + if !claude_selected { + return None; + } + if effective_enabled { + Some(ClaudeTelemetryAction::Install) + } else { + Some(ClaudeTelemetryAction::SkipDisabled) + } +} + +fn split_pre_login_removal( + action: Option, +) -> (Option, Option) { + match action { + Some(ClaudeTelemetryAction::Remove) => (action, None), + _ => (None, action), + } +} + +fn non_interactive_claude_telemetry_action( + repository_root: &Path, + claude_selected: bool, +) -> Option { + if !claude_selected { + return None; + } + let global = config::resolver::resolve_default_global_config_path() + .map_or(GlobalAccessPreferences::Invalid, |path| { + read_global_preferences(&path) + }); + claude_telemetry_action( + global, + effective_telemetry_enabled(repository_root), + claude_selected, + false, + ) +} + +fn read_global_preferences(global_config_path: &Path) -> GlobalAccessPreferences { + read_global_access_preferences(global_config_path).unwrap_or(GlobalAccessPreferences::Invalid) +} + +fn effective_telemetry_enabled(repository_root: &Path) -> bool { + config::resolve_auth_runtime_config(repository_root) + .is_ok_and(|config| config.access_policy.telemetry_enabled()) +} + async fn claude_telemetry_report( repository_root: &std::path::Path, + action: Option, + claude_selected: bool, authorization_check: RepositoryAuthorizationCheck, -) -> String { - let telemetry_enabled = config::resolve_auth_runtime_config(repository_root) - .is_ok_and(|config| config.access_policy.telemetry_enabled()); - - render_claude_telemetry_section( - telemetry_enabled, +) -> Option { + render_claude_telemetry_action( + action?, + claude_selected, setup::claude_telemetry::resolve_claude_settings_path().as_deref(), &setup::claude_telemetry::managed_claude_settings_path(), authorization_check, @@ -525,6 +622,43 @@ async fn claude_telemetry_report( .await } +async fn render_claude_telemetry_action( + action: ClaudeTelemetryAction, + claude_selected: bool, + settings_path: Option<&std::path::Path>, + managed_settings_path: &std::path::Path, + authorization_check: RepositoryAuthorizationCheck, + repository_authorized: A, +) -> Option +where + A: FnOnce() -> AF, + AF: Future, +{ + use setup::claude_telemetry::{ + format_claude_telemetry_removal_report, remove_claude_telemetry, + }; + + match action { + ClaudeTelemetryAction::Remove => match settings_path { + Some(settings_path) => format_claude_telemetry_removal_report( + &remove_claude_telemetry(settings_path, managed_settings_path), + claude_selected, + ), + None => claude_selected.then(|| CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE.to_string()), + }, + ClaudeTelemetryAction::Install | ClaudeTelemetryAction::SkipDisabled => Some( + render_claude_telemetry_section( + action == ClaudeTelemetryAction::Install, + settings_path, + managed_settings_path, + authorization_check, + repository_authorized, + ) + .await, + ), + } +} + async fn render_claude_telemetry_section( telemetry_enabled: bool, settings_path: Option<&std::path::Path>, @@ -546,12 +680,15 @@ where } let installed = match settings_path { - Some(settings_path) => install_claude_telemetry(settings_path, managed_settings_path) - .unwrap_or(ClaudeTelemetryInstallOutcome::SkippedInvalid), - None => ClaudeTelemetryInstallOutcome::SkippedInvalid, + Some(settings_path) => install_claude_telemetry(settings_path, managed_settings_path), + None => ClaudeTelemetryInstallOutcome::SettingsPathUnavailable, }; let authorization = match (&installed, authorization_check) { - (ClaudeTelemetryInstallOutcome::Configured, RepositoryAuthorizationCheck::Verify) => { + ( + ClaudeTelemetryInstallOutcome::Configured + | ClaudeTelemetryInstallOutcome::AlreadyCurrent, + RepositoryAuthorizationCheck::Verify, + ) => { if repository_authorized().await { RepositoryAuthorization::Authorized } else { @@ -628,7 +765,7 @@ mod tests { use serde_json::Value; use super::*; - use crate::services::auth_command::TelemetryProvisioningResult; + use crate::services::config::AuthMode; use crate::services::setup::{ resolve_setup_dispatch, resolve_setup_request, ConcreteSetupTarget, @@ -650,14 +787,6 @@ mod tests { telemetry_consent: false, } } - - fn answering(auth_mode: AuthMode, telemetry_consent: bool) -> Self { - Self { - targets: Some(vec![ConcreteSetupTarget::OpenCode]), - auth_mode: Some(auth_mode), - telemetry_consent, - } - } } impl SetupTargetPrompter for FakePrompter { @@ -755,147 +884,34 @@ mod tests { const CLAUDE_CONFIGURED_LINE: &str = "Claude telemetry: configured in user-level Claude settings for native OpenTelemetry export."; + const CLAUDE_NOT_READY_LINE: &str = "Claude telemetry: not ready for this repository; no valid SCE telemetry credential is authorized for it, so Claude will not export. Run 'sce auth login' in this repository with the SCE account it is enrolled under."; const CLAUDE_NOT_CHECKED_LINE: &str = "Claude telemetry: configured; repository authorization was not checked during non-interactive setup."; #[test] - fn setup_claude_telemetry_readiness_follows_repository_authorization() { - use RepositoryAuthorizationCheck::{Skip, Verify}; - - let configured_not_ready = format!("{CLAUDE_CONFIGURED_LINE}\n{CLAUDE_NOT_READY_LINE}"); - let conflict = Some(r#"{"otelHeadersHelper":"my-helper"}"#); - let conflict_line = "Claude telemetry: skipped; existing Claude settings define a different otelHeadersHelper."; - let invalid_line = "Claude telemetry: skipped; existing Claude settings could not be parsed and were left unchanged."; - let cases = [ - ( - "interactive authorized", - Verify, - true, - None, - Some(true), - CLAUDE_CONFIGURED_LINE, - ), - ( - "interactive unauthorized", - Verify, - true, - None, - Some(false), - configured_not_ready.as_str(), - ), - ( - "non-interactive not checked", - Skip, - true, - None, - None, - CLAUDE_NOT_CHECKED_LINE, - ), - ( - "interactive telemetry disabled", - Verify, - false, - None, - None, - CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE, - ), - ( - "non-interactive telemetry disabled", - Skip, - false, - None, - None, - CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE, - ), - ( - "interactive settings conflict", - Verify, - true, - conflict, - None, - conflict_line, - ), - ( - "non-interactive settings conflict", - Skip, - true, - conflict, - None, - conflict_line, - ), - ( - "interactive invalid settings", - Verify, - true, - Some("{not json"), - None, - invalid_line, - ), - ( - "non-interactive invalid settings", - Skip, - true, - Some("{not json"), - None, - invalid_line, - ), - ]; - - for (name, check, telemetry_enabled, existing, authorized, expected) in cases { + fn setup_claude_telemetry_reports_install_failures_without_authorization_lookup() { + for (case, expected) in [ + ("read", "Claude telemetry: failed to read Claude settings. Check settings files and directory permissions, then rerun 'sce setup'."), + ("write", "Claude telemetry: failed to write Claude settings. Check directory permissions and available disk space, then rerun 'sce setup'."), + ("invalid", "Claude telemetry: skipped; existing Claude settings contain invalid JSON or an invalid structure and were left unchanged. Fix the settings, then rerun 'sce setup'."), + ] { let dir = tempfile::tempdir().unwrap(); let settings = dir.path().join("settings.json"); - if let Some(existing) = existing { - fs::write(&settings, existing).unwrap(); + match case { + "read" => fs::create_dir(&settings).unwrap(), + "write" => fs::create_dir(settings.with_extension("json.sce-tmp")).unwrap(), + "invalid" => fs::write(&settings, b"{fixture-secret-token").unwrap(), + _ => unreachable!(), } - let (report, looked_up) = render_claude_telemetry( - telemetry_enabled, - &settings, - &dir.path().join("managed.json"), - check, - authorized, + true, &settings, &dir.path().join("managed.json"), + RepositoryAuthorizationCheck::Verify, None, ); - - assert_eq!(report, expected, "{name}"); - assert_eq!(looked_up, authorized.is_some(), "{name}"); - assert!(!report.contains("Bearer"), "{name}"); + assert_eq!(report, expected, "{case}"); + assert!(!looked_up, "{case}"); } } - #[test] - fn setup_repository_authorization_is_checked_only_for_interactive_setup() { - let request_mode = |target, non_interactive| { - resolve_setup_request(SetupCliOptions { - target, - non_interactive, - ..SetupCliOptions::default() - }) - .unwrap() - .config_mode - }; - - assert_eq!( - RepositoryAuthorizationCheck::for_mode(request_mode(None, false)), - RepositoryAuthorizationCheck::Verify - ); - for target in [SetupTarget::Claude, SetupTarget::All] { - for non_interactive in [true, false] { - assert_eq!( - RepositoryAuthorizationCheck::for_mode(request_mode( - Some(target), - non_interactive - )), - RepositoryAuthorizationCheck::Skip, - "{target:?} non_interactive={non_interactive}" - ); - } - } - assert_eq!( - RepositoryAuthorizationCheck::for_mode(None), - RepositoryAuthorizationCheck::Skip - ); - } - fn assert_installed(root: &Path) { let parsed: Value = serde_json::from_slice(&fs::read(root.join("settings.json")).unwrap()).unwrap(); @@ -943,82 +959,6 @@ mod tests { } } - #[test] - fn setup_claude_telemetry_skips_install_when_telemetry_is_disabled_by_config() { - let mode = Some(SetupMode::NonInteractive(SetupTarget::Claude)); - let dispatch = dispatch_for(SetupMode::NonInteractive(SetupTarget::Claude), None); - - let dir = tempfile::tempdir().unwrap(); - assert_eq!( - run_claude_telemetry_stage(mode, Some(&dispatch), false, dir.path()).as_deref(), - Some(CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE) - ); - assert_untouched(dir.path()); - - let dir = tempfile::tempdir().unwrap(); - let existing = br#"{"env":{"FOO":"bar"},"model":"opus"}"#; - fs::write(dir.path().join("settings.json"), existing).unwrap(); - assert_eq!( - run_claude_telemetry_stage(mode, Some(&dispatch), false, dir.path()).as_deref(), - Some("Claude telemetry: skipped; SCE telemetry is disabled by config.") - ); - assert_eq!( - fs::read(dir.path().join("settings.json")).unwrap(), - existing - ); - - let report = run_claude_telemetry_stage(mode, Some(&dispatch), true, dir.path()).unwrap(); - assert_eq!(report, CLAUDE_NOT_CHECKED_LINE); - assert_installed(dir.path()); - let parsed: Value = - serde_json::from_slice(&fs::read(dir.path().join("settings.json")).unwrap()).unwrap(); - assert_eq!(parsed["model"], "opus"); - assert_eq!(parsed["env"]["FOO"], "bar"); - } - - #[test] - fn setup_claude_telemetry_policy_follows_layered_config() { - let dir = tempfile::tempdir().unwrap(); - fs::create_dir(dir.path().join(".git")).unwrap(); - let global = dir.path().join("global.json"); - let local_dir = dir.path().join(".sce"); - fs::create_dir_all(&local_dir).unwrap(); - let local = local_dir.join("config.json"); - let enabled = |global_json: &str, local_json: Option<&str>| { - fs::write(&global, global_json).unwrap(); - match local_json { - Some(json) => fs::write(&local, json).unwrap(), - None => { - let _ = fs::remove_file(&local); - } - } - config::resolver::resolve_auth_runtime_config_with( - dir.path(), - |_| None, - |path| fs::read_to_string(path).map_err(anyhow::Error::from), - Path::exists, - || Ok(global.clone()), - ) - .is_ok_and(|config| config.access_policy.telemetry_enabled()) - }; - - assert!(enabled(r#"{"telemetry":{"enabled":true}}"#, None)); - assert!(!enabled("{}", None)); - assert!(!enabled("{}", Some(r#"{"telemetry":{"enabled":true}}"#))); - assert!(!enabled( - r#"{"telemetry":{"enabled":true}}"#, - Some(r#"{"telemetry":{"enabled":false}}"#) - )); - assert!(!enabled( - r#"{"telemetry":{"enabled":true}}"#, - Some(r#"{"auth":{"mode":"disabled"}}"#) - )); - assert!(!enabled( - r#"{"telemetry":{"enabled":true}}"#, - Some(r#"{"telemetry":{"enabled":"yes"}}"#) - )); - } - #[test] fn setup_claude_telemetry_leaves_settings_untouched_when_claude_is_not_installed() { let hooks_only = resolve_setup_request(SetupCliOptions { @@ -1054,619 +994,328 @@ mod tests { } } - struct AccessFixture { - _dir: tempfile::TempDir, - repo: std::path::PathBuf, - global: std::path::PathBuf, - } + const SCE_GLOBAL_CONSENT: &str = r#"{"telemetry":{"enabled":true}}"#; + const SCE_GLOBAL_WITHDRAWAL: &str = r#"{"telemetry":{"enabled":false}}"#; + const SCE_GLOBAL_AUTH_DISABLED: &str = r#"{"auth":{"mode":"disabled"}}"#; + const UNRELATED_CLAUDE_SETTINGS: &str = r#"{"env":{"FOO":"bar"},"model":"opus"}"#; - impl AccessFixture { - fn new() -> Self { - let dir = tempfile::tempdir().unwrap(); - let repo = dir.path().join("repo"); - fs::create_dir_all(repo.join(".git")).unwrap(); - let global = dir.path().join("global").join("config.json"); - fs::create_dir_all(global.parent().unwrap()).unwrap(); - Self { - _dir: dir, - repo, - global, - } - } - - fn write_repo_config(&self, json: &str) { - fs::create_dir_all(self.repo.join(".sce")).unwrap(); - fs::write(self.repo.join(".sce").join("config.json"), json).unwrap(); - } - - fn resolve_policy(&self) -> impl Fn(&Path) -> Result + '_ { - move |root| { - config::resolver::resolve_auth_runtime_config_with( - root, - |_| None, - |path| fs::read_to_string(path).map_err(anyhow::Error::from), - Path::exists, - || Ok(self.global.clone()), - ) - .map(|config| config.access_policy) - } - } - - fn prepare(&self, prompter: &FakePrompter) -> Result { - self.prepare_with(prompter, false) - } - - fn prepare_with( - &self, - prompter: &FakePrompter, - reconfigure: bool, - ) -> Result { - prepare_interactive_setup( - &self.repo, - prompter, - &[], - &self.global, - self.resolve_policy(), - false, - reconfigure, - ) - } - - fn report(&self, access_save: &SetupAccessSave, auth_db_present: bool) -> String { - setup_access_report( - &self.repo, - access_save, - self.resolve_policy(), - auth_db_present, - ) - .unwrap() - .0 - } - - fn policy(&self) -> ResolvedAccessPolicy { - self.resolve_policy()(&self.repo).unwrap() - } - } - - fn ready(setup: Result) -> (SetupDispatch, SetupAccessSave) { - match setup.expect("interactive setup should prepare") { - InteractiveSetup::Ready { - dispatch, - access_save, - } => (dispatch, access_save), - InteractiveSetup::Cancelled => panic!("interactive setup should not cancel"), - } + fn removed_line(settings: &Path) -> String { + format!( + "Claude telemetry: removed SCE-managed telemetry settings from user-level Claude settings '{}' because the global SCE config disables telemetry.", + settings.display() + ) } - fn read_json_file(path: &Path) -> Value { - serde_json::from_slice(&fs::read(path).unwrap()).unwrap() + fn authorization_must_not_run() -> std::future::Ready { + panic!("repository authorization must not run"); } - #[test] - fn interactive_setup_saves_access_answers_only_to_the_global_config() { - let fixture = AccessFixture::new(); - fs::write(&fixture.global, "{\"log_level\": \"debug\"}\n").unwrap(); - - let (dispatch, access_save) = - ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); - - let global = read_json_file(&fixture.global); - assert_eq!(global["auth"]["mode"], "mandatory"); - assert_eq!(global["telemetry"]["enabled"], true); - assert_eq!(global["log_level"], "debug"); - assert_eq!(access_save.outcome, GlobalWriteOutcome::Written); - - let SetupDispatch::Proceed { - targets, - target_persistence, - agent_trace_auto_sync, - attribution_hooks_enabled, - .. - } = dispatch - else { - panic!("dispatch should proceed"); - }; - setup::persist_integration_targets( - &fixture.repo, - &targets, - target_persistence, - &[], - agent_trace_auto_sync, - attribution_hooks_enabled, - ) - .unwrap(); - - let repository = read_json_file(&fixture.repo.join(".sce").join("config.json")); - let repository = repository.as_object().unwrap(); - assert!(!repository.contains_key("auth")); - assert!(!repository.contains_key("telemetry")); + fn run_claude_telemetry_action( + action: ClaudeTelemetryAction, + claude_selected: bool, + settings: &Path, + authorization_check: RepositoryAuthorizationCheck, + ) -> Option { + tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(render_claude_telemetry_action( + action, + claude_selected, + Some(settings), + &settings.with_file_name("managed.json"), + authorization_check, + authorization_must_not_run, + )) } - #[test] - fn interactive_setup_rerun_leaves_the_global_config_bytes_unchanged() { - let fixture = AccessFixture::new(); - let prompter = FakePrompter::answering(AuthMode::Optional, false); - - ready(fixture.prepare(&prompter)); - let first = fs::read(&fixture.global).unwrap(); - - let (_, rerun) = ready(fixture.prepare(&prompter)); - assert_eq!( - rerun, - SetupAccessSave { - global_config_path: fixture.global.clone(), - auth_mode: None, - telemetry_enabled: None, - outcome: GlobalWriteOutcome::Unchanged, - prompts_suppressed: true, - } + fn install_sce_claude_settings(settings: &Path) -> Vec { + fs::write(settings, UNRELATED_CLAUDE_SETTINGS).unwrap(); + run_claude_telemetry_action( + ClaudeTelemetryAction::Install, + true, + settings, + RepositoryAuthorizationCheck::Skip, ); - assert_eq!(fs::read(&fixture.global).unwrap(), first); - - let repeated = persist_setup_access_preferences( - &fixture.global, - Some(AuthMode::Optional), - Some(false), - ) - .unwrap(); - assert_eq!(repeated.outcome, GlobalWriteOutcome::Unchanged); - assert_eq!(fs::read(&fixture.global).unwrap(), first); + assert_installed(settings.parent().unwrap()); + fs::read(settings).unwrap() } #[test] - fn interactive_setup_skips_access_writes_when_the_global_config_is_invalid() { - let fixture = AccessFixture::new(); - let invalid = b"{\"auth\": {\"mode\": \"sometimes\"}}\n"; - fs::write(&fixture.global, invalid).unwrap(); + fn claude_telemetry_action_follows_global_withdrawal_only() { + use ClaudeTelemetryAction::{Install, Remove, SkipDisabled}; - let (dispatch, access_save) = - ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); + let valid = |auth_mode, telemetry_enabled| GlobalAccessPreferences::Valid { + auth_mode, + telemetry_enabled, + }; + let withdrawn = [ + valid(None, Some(false)), + valid(Some(AuthMode::Disabled), None), + valid(Some(AuthMode::Disabled), Some(true)), + valid(Some(AuthMode::Optional), Some(false)), + ]; + let not_withdrawn = [ + valid(None, Some(true)), + valid(Some(AuthMode::Optional), Some(true)), + valid(Some(AuthMode::Mandatory), None), + valid(None, None), + GlobalAccessPreferences::Missing, + GlobalAccessPreferences::Invalid, + ]; + let modes = [(true, true), (true, false), (false, true), (false, false)]; - assert!(matches!( - dispatch, - SetupDispatch::Proceed { - auth_mode: None, - telemetry_enabled: None, - .. + for global in withdrawn { + for (claude_selected, interactive) in modes { + assert_eq!( + claude_telemetry_action(global, false, claude_selected, interactive), + (claude_selected || interactive).then_some(Remove), + "{global:?} claude_selected={claude_selected} interactive={interactive}" + ); } - )); - assert_eq!(access_save.outcome, GlobalWriteOutcome::Unchanged); - assert_eq!(fs::read(&fixture.global).unwrap(), invalid); - } - - #[cfg(unix)] - #[test] - fn interactive_setup_aborts_before_repository_writes_when_the_global_config_is_read_only() { - use std::os::unix::fs::PermissionsExt; - - let fixture = AccessFixture::new(); - let global_dir = fixture.global.parent().unwrap().to_path_buf(); - fs::set_permissions(&global_dir, fs::Permissions::from_mode(0o555)).unwrap(); - - let result = fixture.prepare(&FakePrompter::answering(AuthMode::Optional, true)); - fs::set_permissions(&global_dir, fs::Permissions::from_mode(0o755)).unwrap(); - - let error = result.expect_err("read-only global config should abort setup"); - let message = error.to_string(); - assert!(message.starts_with(&format!( - "Failed to save SCE access preferences to the global SCE config '{}'.\n", - fixture.global.display() - ))); - assert!(message.ends_with(GLOBAL_ACCESS_WRITE_REMEDIATION)); - assert_eq!(error.code(), "SCE-ERR-RUNTIME"); - assert!(!fixture.global.exists()); - assert!(!fixture.repo.join("context").exists()); - assert!(!fixture.repo.join(".sce").exists()); - } - - #[cfg(unix)] - #[test] - fn interactive_setup_aborts_before_repository_writes_when_the_global_config_is_a_symlink() { - let fixture = AccessFixture::new(); - let target = fixture.global.with_file_name("managed.json"); - let original = b"{\"log_level\": \"info\"}\n"; - fs::write(&target, original).unwrap(); - std::os::unix::fs::symlink(&target, &fixture.global).unwrap(); - - let error = fixture - .prepare(&FakePrompter::answering(AuthMode::Optional, true)) - .expect_err("symlinked global config should abort setup"); - - let message = error.to_string(); - assert!(message.contains("is a symlink and was left unchanged")); - assert!(message.ends_with(GLOBAL_ACCESS_SYMLINK_REMEDIATION)); - assert!(!message.contains("sce config validate")); - assert_eq!(fs::read_link(&fixture.global).unwrap(), target); - assert_eq!(fs::read(&target).unwrap(), original); - assert!(!fixture.repo.join("context").exists()); - assert!(!fixture.repo.join(".sce").exists()); - } - - #[test] - fn setup_access_write_refuses_an_invalid_global_config_with_a_fixed_message() { - let fixture = AccessFixture::new(); - fs::write(&fixture.global, "{not json").unwrap(); - - let error = persist_setup_access_preferences(&fixture.global, None, Some(true)) - .expect_err("invalid global config should not be overwritten"); - - let message = error.to_string(); - assert!(message.starts_with(&format!( - "Failed to save SCE access preferences to the global SCE config '{}'.\nGlobal SCE config '{}' is invalid and was left unchanged: ", - fixture.global.display(), - fixture.global.display() - ))); - assert!(message.ends_with(&format!("\n{GLOBAL_ACCESS_WRITE_REMEDIATION}"))); - assert_eq!(fs::read(&fixture.global).unwrap(), b"{not json"); + } + for global in not_withdrawn { + for repository_opt_out in [false, true] { + for (claude_selected, interactive) in modes { + let expected = match (claude_selected, repository_opt_out) { + (false, _) => None, + (true, false) => Some(Install), + (true, true) => Some(SkipDisabled), + }; + assert_eq!( + claude_telemetry_action( + global, + !repository_opt_out, + claude_selected, + interactive + ), + expected, + "{global:?} repository_opt_out={repository_opt_out} claude_selected={claude_selected} interactive={interactive}" + ); + } + } + } } #[test] - fn setup_access_section_reports_repository_opt_out_after_global_consent() { + fn setup_claude_telemetry_consent_cycle_is_idempotent() { let fixture = AccessFixture::new(); - fixture.write_repo_config(r#"{"telemetry":{"enabled":false}}"#); - - let (_, access_save) = - ready(fixture.prepare(&FakePrompter::answering(AuthMode::Optional, true))); - - assert_eq!( - fixture.report(&access_save, false), - format!( - "SCE access:\n\ - - auth.mode: optional (saved to global SCE config '{path}'; applies to all repositories on this machine)\n\ - - telemetry.enabled: true (saved to global SCE config '{path}'; applies to all repositories on this machine)\n\ - - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ - - effective telemetry: disabled (reason: repository_opt_out)", - path = fixture.global.display() + let settings = fixture.global.with_file_name("settings.json"); + fs::write(&settings, UNRELATED_CLAUDE_SETTINGS).unwrap(); + let run = |global_json: &str, interactive: bool| { + fs::write(&fixture.global, global_json).unwrap(); + let action = claude_telemetry_action( + read_global_preferences(&fixture.global), + fixture.policy().telemetry_enabled(), + true, + interactive, ) - ); - } - - #[test] - fn setup_access_section_renders_exact_lines() { - let unchanged = |fixture: &AccessFixture| SetupAccessSave { - global_config_path: fixture.global.clone(), - auth_mode: None, - telemetry_enabled: None, - outcome: GlobalWriteOutcome::Unchanged, - prompts_suppressed: false, + .unwrap(); + run_claude_telemetry_action( + action, + true, + &settings, + RepositoryAuthorizationCheck::for_mode(Some(if interactive { + SetupMode::Interactive + } else { + SetupMode::NonInteractive(SetupTarget::Claude) + })), + ) + .unwrap() }; + let modified = || fs::metadata(&settings).unwrap().modified().unwrap(); - let fixture = AccessFixture::new(); - fs::write( - &fixture.global, - r#"{"auth":{"mode":"optional"},"telemetry":{"enabled":true}}"#, - ) - .unwrap(); - assert_eq!( - fixture.report(&unchanged(&fixture), true), - format!( - "SCE access:\n\ - - saved access preferences: unchanged (global SCE config '{}')\n\ - - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ - - effective telemetry: enabled", - fixture.global.display() - ) - ); + assert_eq!(run(SCE_GLOBAL_CONSENT, false), CLAUDE_NOT_CHECKED_LINE); + let installed = fs::read(&settings).unwrap(); - let fixture = AccessFixture::new(); - let access_save = - persist_setup_access_preferences(&fixture.global, Some(AuthMode::Disabled), None) - .unwrap(); + assert_eq!(run(SCE_GLOBAL_WITHDRAWAL, true), removed_line(&settings)); + let removed = fs::read(&settings).unwrap(); + let parsed: Value = serde_json::from_slice(&removed).unwrap(); assert_eq!( - fixture.report(&access_save, true), - format!( - "SCE access:\n\ - - auth.mode: disabled (saved to global SCE config '{}'; applies to all repositories on this machine)\n\ - - effective auth.mode: disabled (source: config_file, config_source: default_discovered_global)\n\ - - effective telemetry: disabled (reason: auth_disabled)\n\ - {AUTH_LOGOUT_HINT_LINE}", - fixture.global.display() - ) + parsed, + serde_json::from_str::(UNRELATED_CLAUDE_SETTINGS).unwrap() ); - assert!(!fixture - .report(&access_save, false) - .contains("sce auth logout")); + let removed_at = modified(); - let fixture = AccessFixture::new(); - fixture.write_repo_config(r#"{"auth":{"mode":"disabled"}}"#); assert_eq!( - fixture.report(&unchanged(&fixture), false), - format!( - "SCE access:\n\ - - saved access preferences: unchanged (global SCE config '{}')\n\ - - effective auth.mode: disabled (source: config_file, config_source: default_discovered_local)\n\ - - effective telemetry: disabled (reason: auth_disabled)\n\ - - Authentication is disabled by `auth.mode: disabled` in the repository SCE config (`.sce/config.json`).", - fixture.global.display() - ) + run(SCE_GLOBAL_WITHDRAWAL, false), + CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE ); - } + assert_eq!(fs::read(&settings).unwrap(), removed); + assert_eq!(modified(), removed_at); - #[test] - fn setup_access_section_hints_reconfigure_when_saved_answers_suppressed_prompts() { - let fixture = AccessFixture::new(); - let prompter = FakePrompter::answering(AuthMode::Optional, false); - ready(fixture.prepare(&prompter)); + assert_eq!(run(SCE_GLOBAL_CONSENT, false), CLAUDE_NOT_CHECKED_LINE); + assert_eq!(fs::read(&settings).unwrap(), installed); - let (_, rerun) = ready(fixture.prepare(&prompter)); assert_eq!( - fixture.report(&rerun, false), - format!( - "SCE access:\n\ - - saved access preferences: unchanged (global SCE config '{}')\n\ - - effective auth.mode: optional (source: config_file, config_source: default_discovered_global)\n\ - - effective telemetry: disabled (reason: user_opt_out)\n\ - - Run 'sce setup --reconfigure' to change saved setup answers.", - fixture.global.display() - ) + run(SCE_GLOBAL_AUTH_DISABLED, false), + removed_line(&settings) ); - - let (_, reconfigured) = ready(fixture.prepare_with(&prompter, true)); - assert!(!reconfigured.prompts_suppressed); - assert!(!fixture - .report(&reconfigured, false) - .contains(RECONFIGURE_HINT_LINE)); + assert_eq!(fs::read(&settings).unwrap(), removed); } #[test] - fn reconfigure_rewrites_saved_global_answers() { + fn setup_claude_telemetry_repository_opt_out_preserves_user_settings() { let fixture = AccessFixture::new(); - ready(fixture.prepare(&FakePrompter::answering(AuthMode::Disabled, false))); - assert_eq!(read_json_file(&fixture.global)["auth"]["mode"], "disabled"); - - let (rerun, _) = - ready(fixture.prepare(&FakePrompter::answering(AuthMode::Mandatory, true))); - assert!(matches!( - rerun, - SetupDispatch::Proceed { - auth_mode: None, - telemetry_enabled: None, - .. - } - )); - assert_eq!(read_json_file(&fixture.global)["auth"]["mode"], "disabled"); - - let (dispatch, access_save) = - ready(fixture.prepare_with(&FakePrompter::answering(AuthMode::Mandatory, true), true)); - assert!(matches!( - dispatch, - SetupDispatch::Proceed { - auth_mode: Some(AuthMode::Mandatory), - telemetry_enabled: Some(true), - .. - } - )); - assert_eq!(access_save.outcome, GlobalWriteOutcome::Written); - let global = read_json_file(&fixture.global); - assert_eq!(global["auth"]["mode"], "mandatory"); - assert_eq!(global["telemetry"]["enabled"], true); - } - - const LOGIN_RENDERED: &str = "Logged in to SCE.\nTelemetry credential provisioned."; - - fn login_success(telemetry: TelemetryProvisioningResult) -> SetupLoginStatus { - SetupLoginStatus::Authenticated(LoginReport { - rendered: LOGIN_RENDERED.to_string(), - telemetry, - }) - } - - fn policy_for(global: Option<&str>, repository: Option<&str>) -> ResolvedAccessPolicy { - let fixture = AccessFixture::new(); - if let Some(global) = global { - fs::write(&fixture.global, global).unwrap(); - } - if let Some(repository) = repository { - fixture.write_repo_config(repository); - } - fixture.policy() - } - - fn run_login_step(action: SetupLoginAction, login: F) -> Result - where - F: FnOnce() -> Result, - { - tokio::runtime::Builder::new_current_thread() - .build() + fs::write(&fixture.global, SCE_GLOBAL_CONSENT).unwrap(); + let settings = fixture.global.with_file_name("settings.json"); + let installed = install_sce_claude_settings(&settings); + let explicit = fixture.global.with_file_name("explicit.json"); + fs::write(&explicit, SCE_GLOBAL_WITHDRAWAL).unwrap(); + let explicit_policy = |root: &Path| { + config::resolver::resolve_auth_runtime_config_with( + root, + |key| (key == "SCE_CONFIG_FILE").then(|| explicit.display().to_string()), + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(fixture.global.clone()), + ) .unwrap() - .block_on(run_setup_login_step(action, || async move { login() })) - } - - fn login_must_not_run() -> Result { - panic!("login must not be invoked") - } - - #[test] - fn setup_login_action_covers_every_effective_mode_and_intent() { - use crate::services::setup::SetupLoginIntent::{Declined, NotOffered, Requested}; - - let optional = policy_for(Some(r#"{"auth":{"mode":"optional"}}"#), None); - let mandatory = policy_for(Some(r#"{"auth":{"mode":"mandatory"}}"#), None); - let disabled = policy_for(Some(r#"{"auth":{"mode":"disabled"}}"#), None); - let repository_mandatory = policy_for( - Some(r#"{"auth":{"mode":"optional"}}"#), - Some(r#"{"auth":{"mode":"mandatory"}}"#), - ); - let repository_disabled = policy_for( - Some(r#"{"auth":{"mode":"mandatory"}}"#), - Some(r#"{"auth":{"mode":"disabled"}}"#), - ); - let default = policy_for(None, None); + .access_policy + }; - let auth_disabled = SetupLoginAction::Skip(SetupLoginSkip::AuthDisabled); - let required = SetupLoginAction::Run { required: true }; - for (policy, intent, expected) in [ - ( - &optional, - Requested, - SetupLoginAction::Run { required: false }, - ), - ( - &optional, - Declined, - SetupLoginAction::Skip(SetupLoginSkip::Declined), - ), - ( - &optional, - NotOffered, - SetupLoginAction::Skip(SetupLoginSkip::NotOffered), - ), + let cases = [ ( - &default, - Requested, - SetupLoginAction::Run { required: false }, + "repository A telemetry opt-out", + Some(SCE_GLOBAL_WITHDRAWAL), + false, ), ( - &default, - NotOffered, - SetupLoginAction::Skip(SetupLoginSkip::NotOffered), + "repository A auth disabled", + Some(SCE_GLOBAL_AUTH_DISABLED), + false, ), - (&mandatory, Requested, required), - (&mandatory, Declined, required), - (&mandatory, NotOffered, required), - (&repository_mandatory, Declined, required), - (&repository_mandatory, NotOffered, required), - (&disabled, Requested, auth_disabled), - (&disabled, Declined, auth_disabled), - (&disabled, NotOffered, auth_disabled), - (&repository_disabled, Requested, auth_disabled), - (&repository_disabled, NotOffered, auth_disabled), - ] { - assert_eq!( - setup_login_action(policy, intent), - expected, - "{:?} {intent:?}", - policy.auth_mode - ); + ("explicit layer telemetry opt-out", None, true), + ("repository B without opt-out", None, false), + ]; + for (name, repository_json, explicit_layer) in cases { + match repository_json { + Some(json) => fixture.write_repo_config(json), + None => { + let _ = fs::remove_file(fixture.repo.join(".sce").join("config.json")); + } + } + let policy = if explicit_layer { + explicit_policy(&fixture.repo) + } else { + fixture.policy() + }; + let opted_out = repository_json.is_some() || explicit_layer; + assert_eq!(!policy.telemetry_enabled(), opted_out, "{name}"); + + for (claude_selected, interactive) in + [(true, true), (true, false), (false, true), (false, false)] + { + let action = claude_telemetry_action( + read_global_preferences(&fixture.global), + policy.telemetry_enabled(), + claude_selected, + interactive, + ); + let expected = claude_selected.then_some(if opted_out { + ClaudeTelemetryAction::SkipDisabled + } else { + ClaudeTelemetryAction::Install + }); + assert_eq!(action, expected, "{name}"); + if let Some(action) = action { + let report = run_claude_telemetry_action( + action, + claude_selected, + &settings, + RepositoryAuthorizationCheck::Skip, + ); + if opted_out { + assert_eq!( + report.as_deref(), + Some(CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE), + "{name}" + ); + } + } + assert_eq!(fs::read(&settings).unwrap(), installed, "{name}"); + } } } #[test] - fn setup_login_step_never_invokes_login_when_skipped() { - for skip in [ - SetupLoginSkip::AuthDisabled, - SetupLoginSkip::Declined, - SetupLoginSkip::NotOffered, + fn setup_claude_telemetry_removal_never_checks_authorization() { + for (mode, claude_selected) in [ + (SetupMode::Interactive, true), + (SetupMode::Interactive, false), + (SetupMode::NonInteractive(SetupTarget::Claude), true), + (SetupMode::NonInteractive(SetupTarget::All), true), ] { - let status = run_login_step(SetupLoginAction::Skip(skip), login_must_not_run).unwrap(); - assert_eq!(status, SetupLoginStatus::Skipped(skip)); - } - } + let dir = tempfile::tempdir().unwrap(); + let settings = dir.path().join("settings.json"); + install_sce_claude_settings(&settings); - #[test] - fn setup_login_step_reports_optional_failure_as_successful_setup() { - let status = run_login_step(SetupLoginAction::Run { required: false }, || { - Err(CliError::user_with_source( - UserError::NotAuthenticated, - anyhow::anyhow!("device code expired"), - )) - }) - .unwrap(); - assert_eq!( - status, - SetupLoginStatus::Failed(UserError::NotAuthenticated) - ); - assert_eq!( - render_setup_login_section(&status), - format!( - "SCE login: failed: {}\nRun 'sce auth login' to retry.", - UserError::NotAuthenticated.message() - ) - ); + let action = claude_telemetry_action( + GlobalAccessPreferences::Valid { + auth_mode: None, + telemetry_enabled: Some(false), + }, + false, + claude_selected, + mode == SetupMode::Interactive, + ); + assert_eq!(action, Some(ClaudeTelemetryAction::Remove), "{mode:?}"); - let status = run_login_step(SetupLoginAction::Run { required: false }, || { - Err(CliError::runtime(anyhow::anyhow!( - "access_token=secret-value leaked in a diagnostic" - ))) - }) - .unwrap(); - assert_eq!( - status, - SetupLoginStatus::Failed(UserError::UnexpectedFailure) - ); - assert!(!render_setup_login_section(&status).contains("secret-value")); + let report = run_claude_telemetry_action( + ClaudeTelemetryAction::Remove, + claude_selected, + &settings, + RepositoryAuthorizationCheck::for_mode(Some(mode)), + ); + assert_eq!(report, Some(removed_line(&settings)), "{mode:?}"); + assert_eq!( + fs::read_to_string(&settings).unwrap(), + "{\n \"env\": {\n \"FOO\": \"bar\"\n },\n \"model\": \"opus\"\n}\n", + "{mode:?}" + ); + } } - #[test] - fn setup_login_step_fails_mandatory_login_with_setup_login_required() { - let error = run_login_step(SetupLoginAction::Run { required: true }, || { - Err(CliError::user_with_source( - UserError::NotAuthenticated, - anyhow::anyhow!("device code expired"), - )) - }) - .unwrap_err(); - - let CliError::User { - error: user_error, - source: Some(source), - } = &error - else { - panic!("expected a user error with the login error as source"); - }; - assert_eq!(*user_error, UserError::SetupLoginRequired); - assert_eq!(user_error.key(), "auth.setup_login_required"); - assert_eq!(error.code(), "SCE-ERR-RUNTIME"); - assert_eq!(source.to_string(), UserError::NotAuthenticated.message()); + struct AccessFixture { + _dir: tempfile::TempDir, + repo: std::path::PathBuf, + global: std::path::PathBuf, } - #[test] - fn setup_login_step_includes_login_text_for_mandatory_and_accepted_optional_login() { - for required in [true, false] { - let status = run_login_step(SetupLoginAction::Run { required }, || { - Ok(LoginReport { - rendered: LOGIN_RENDERED.to_string(), - telemetry: TelemetryProvisioningResult::Issued, - }) - }) - .unwrap(); - assert_eq!(status, login_success(TelemetryProvisioningResult::Issued)); - assert_eq!(render_setup_login_section(&status), LOGIN_RENDERED); + impl AccessFixture { + fn new() -> Self { + let dir = tempfile::tempdir().unwrap(); + let repo = dir.path().join("repo"); + fs::create_dir_all(repo.join(".git")).unwrap(); + let global = dir.path().join("global").join("config.json"); + fs::create_dir_all(global.parent().unwrap()).unwrap(); + Self { + _dir: dir, + repo, + global, + } } - } - #[test] - fn setup_login_section_renders_exact_skip_lines_without_credentials() { - for (skip, expected) in [ - ( - SetupLoginSkip::AuthDisabled, - "SCE login: skipped; SCE authentication is disabled by config.", - ), - ( - SetupLoginSkip::Declined, - "SCE login: skipped; run 'sce auth login' to log in.", - ), - ( - SetupLoginSkip::NotOffered, - "SCE login: not requested; run 'sce auth login' to log in or refresh credentials.", - ), - ] { - assert_eq!( - render_setup_login_section(&SetupLoginStatus::Skipped(skip)), - expected - ); + fn write_repo_config(&self, json: &str) { + fs::create_dir_all(self.repo.join(".sce")).unwrap(); + fs::write(self.repo.join(".sce").join("config.json"), json).unwrap(); } - let tokens = crate::services::token_storage::StoredTokens { - access_token: "secret-access-token-value".to_string(), - token_type: "Bearer".to_string(), - expires_in: 3600, - refresh_token: "secret-refresh-token-value".to_string(), - scope: None, - stored_at_unix_seconds: 1, - }; - let rendered = auth_command::render_login_refresh_result_with_telemetry( - &tokens, - AuthFormat::Text, - TelemetryProvisioningResult::Issued, - ) - .unwrap(); - let output = render_setup_login_section(&SetupLoginStatus::Authenticated(LoginReport { - rendered, - telemetry: TelemetryProvisioningResult::Issued, - })); - assert!(output.contains("Authentication succeeded.")); - assert!(!output.contains("secret-access-token-value")); - assert!(!output.contains("secret-refresh-token-value")); + fn resolve_policy(&self) -> impl Fn(&Path) -> Result + '_ { + move |root| { + config::resolver::resolve_auth_runtime_config_with( + root, + |_| None, + |path| fs::read_to_string(path).map_err(anyhow::Error::from), + Path::exists, + || Ok(self.global.clone()), + ) + .map(|config| config.access_policy) + } + } + + fn policy(&self) -> ResolvedAccessPolicy { + self.resolve_policy()(&self.repo).unwrap() + } } } diff --git a/cli/src/services/setup/config_merge.rs b/cli/src/services/setup/config_merge.rs index 5af9e3299..215713952 100644 --- a/cli/src/services/setup/config_merge.rs +++ b/cli/src/services/setup/config_merge.rs @@ -387,6 +387,96 @@ pub(crate) fn merge_claude_telemetry_settings( )) } +#[derive(Debug, Eq, PartialEq)] +pub(crate) enum ClaudeTelemetryRemovalMerge { + Removed(Vec), + NotInstalled, + Modified(ClaudeTelemetrySkipReason), + HelperMissing, +} + +pub(crate) fn remove_claude_telemetry_settings( + existing_bytes: Option<&[u8]>, + source_path: &str, +) -> Result { + let Some(bytes) = existing_bytes else { + return Ok(ClaudeTelemetryRemovalMerge::NotInstalled); + }; + let existing: Value = serde_json::from_slice(bytes).with_context(|| { + format!("Existing config file '{source_path}' must contain valid JSON.") + })?; + let mut settings = existing.as_object().cloned().with_context(|| { + format!("Existing config file '{source_path}' must contain a top-level JSON object.") + })?; + let mut env = match settings.get("env") { + Some(value) => Some(value.as_object().cloned().with_context(|| { + format!("Existing config file '{source_path}' key 'env' must be a JSON object.") + })?), + None => None, + }; + + match settings.get(CLAUDE_OTEL_HEADERS_HELPER_KEY) { + Some(helper) if helper.as_str() == Some(CLAUDE_OTEL_HEADERS_HELPER_COMMAND) => {} + Some(_) => return Ok(ClaudeTelemetryRemovalMerge::NotInstalled), + None => { + let sce_endpoint = env + .as_ref() + .and_then(|env| env.get("OTEL_EXPORTER_OTLP_ENDPOINT")) + .and_then(Value::as_str) + == Some(MANAGED_OTLP_ENDPOINT); + return Ok(if sce_endpoint { + ClaudeTelemetryRemovalMerge::HelperMissing + } else { + ClaudeTelemetryRemovalMerge::NotInstalled + }); + } + } + + if let Some(reason) = claude_telemetry_conflict(&existing) { + return Ok(ClaudeTelemetryRemovalMerge::Modified(reason)); + } + + settings.remove(CLAUDE_OTEL_HEADERS_HELPER_KEY); + if let Some(env) = env.as_mut() { + let was_empty = env.is_empty(); + for (key, value) in claude_telemetry_env_entries() { + if env.get(key).and_then(Value::as_str) == Some(value) { + env.remove(key); + } + } + if !was_empty && env.is_empty() { + settings.remove("env"); + } else { + settings.insert("env".to_string(), Value::Object(env.clone())); + } + } + + let mut serialized = serde_json::to_string_pretty(&Value::Object(settings)) + .context("Failed to serialize Claude settings after telemetry removal")?; + serialized.push('\n'); + Ok(ClaudeTelemetryRemovalMerge::Removed( + serialized.into_bytes(), + )) +} + +pub(crate) fn settings_configure_claude_telemetry(settings: &Value) -> bool { + if settings.get(CLAUDE_OTEL_HEADERS_HELPER_KEY).is_some() { + return true; + } + let Some(env) = settings.get("env").and_then(Value::as_object) else { + return false; + }; + CLAUDE_TELEMETRY_SWITCH_KEYS + .iter() + .chain(CLAUDE_TELEMETRY_PRIVACY_KEYS.iter()) + .chain(CLAUDE_OTEL_ENDPOINT_KEYS.iter()) + .chain(CLAUDE_OTEL_HEADERS_KEYS.iter()) + .chain(CLAUDE_OTEL_PROTOCOL_KEYS.iter()) + .chain(CLAUDE_OTEL_EXPORTER_KEYS.iter()) + .chain(CLAUDE_TELEMETRY_HELPER_SETTING_KEYS.iter()) + .any(|key| env.contains_key(*key)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/cli/src/services/setup/mod.rs b/cli/src/services/setup/mod.rs index 536968fa6..3f488443d 100644 --- a/cli/src/services/setup/mod.rs +++ b/cli/src/services/setup/mod.rs @@ -1265,791 +1265,8 @@ pub fn setup_cancelled_text() -> String { #[cfg(test)] mod tests { - use std::cell::RefCell; use super::*; - use crate::services::config::{ResolvedValue, TelemetryDisabledReason, TelemetryPolicyState}; - - #[derive(Clone, Copy, Debug, Eq, PartialEq)] - enum PromptCall { - Targets, - Workflows, - AutoSync(bool), - Attribution(bool), - AuthMode(AuthMode), - Telemetry(bool), - Login, - } - - struct RecordingPrompter { - calls: RefCell>, - auth_mode: Option, - telemetry: Option, - login: Option, - } - - impl RecordingPrompter { - fn answering( - auth_mode: Option, - telemetry: Option, - login: Option, - ) -> Self { - Self { - calls: RefCell::new(Vec::new()), - auth_mode, - telemetry, - login, - } - } - - fn record(&self, call: PromptCall) { - self.calls.borrow_mut().push(call); - } - - fn access_calls(&self) -> Vec { - self.calls - .borrow() - .iter() - .copied() - .filter(|call| { - matches!( - call, - PromptCall::AuthMode(_) | PromptCall::Telemetry(_) | PromptCall::Login - ) - }) - .collect() - } - } - - impl SetupTargetPrompter for RecordingPrompter { - fn prompt_targets( - &self, - _defaults: &[ConcreteSetupTarget], - ) -> Result>> { - self.record(PromptCall::Targets); - Ok(Some(vec![ConcreteSetupTarget::Claude])) - } - - fn prompt_optional_workflows(&self, _defaults: &[String]) -> Result>> { - self.record(PromptCall::Workflows); - Ok(Some(Vec::new())) - } - - fn prompt_agent_trace_auto_sync(&self, default: bool) -> Result> { - self.record(PromptCall::AutoSync(default)); - Ok(Some(true)) - } - - fn prompt_attribution_hooks_enabled(&self, default: bool) -> Result> { - self.record(PromptCall::Attribution(default)); - Ok(Some(true)) - } - - fn prompt_auth_mode(&self, default: AuthMode) -> Result> { - self.record(PromptCall::AuthMode(default)); - Ok(self.auth_mode) - } - - fn prompt_telemetry_consent(&self, default: bool) -> Result> { - self.record(PromptCall::Telemetry(default)); - Ok(self.telemetry) - } - - fn prompt_login(&self) -> Result> { - self.record(PromptCall::Login); - Ok(self.login) - } - } - - fn interactive_dispatch( - prompter: &RecordingPrompter, - persisted: PersistedSetupConfirmations, - gate: SetupAccessGate, - ) -> SetupDispatch { - resolve_setup_dispatch( - SetupMode::Interactive, - prompter, - &[], - &[], - persisted, - gate, - false, - ) - .expect("dispatch should resolve") - } - - fn access_values( - dispatch: &SetupDispatch, - ) -> (Option, Option, SetupLoginIntent) { - match dispatch { - SetupDispatch::Proceed { - auth_mode, - telemetry_enabled, - login_intent, - .. - } => (*auth_mode, *telemetry_enabled, *login_intent), - SetupDispatch::Cancelled => panic!("dispatch was cancelled"), - } - } - - #[test] - fn first_interactive_run_asks_access_prompts_after_existing_prompts_with_defaults() { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Optional), Some(true), Some(true)); - - let dispatch = interactive_dispatch( - &prompter, - PersistedSetupConfirmations::default(), - SetupAccessGate::default(), - ); - - assert_eq!( - *prompter.calls.borrow(), - vec![ - PromptCall::Targets, - PromptCall::Workflows, - PromptCall::AutoSync(true), - PromptCall::Attribution(true), - PromptCall::AuthMode(AuthMode::Optional), - PromptCall::Telemetry(false), - PromptCall::Login, - ] - ); - assert_eq!( - access_values(&dispatch), - ( - Some(AuthMode::Optional), - Some(true), - SetupLoginIntent::Requested - ) - ); - } - - type AccessValues = (Option, Option, SetupLoginIntent); - type AccessCase = ( - &'static str, - Option, - PersistedSetupConfirmations, - SetupAccessGate, - Vec, - AccessValues, - ); - - fn persisted_access( - auth_mode: Option, - telemetry_enabled: Option, - global_config_invalid: bool, - ) -> PersistedSetupConfirmations { - PersistedSetupConfirmations { - auth_mode, - telemetry_enabled, - global_config_invalid, - ..PersistedSetupConfirmations::default() - } - } - - fn access_gate( - auth_locked_by: Option, - mandatory_locked: bool, - auth_db_present: bool, - ) -> SetupAccessGate { - SetupAccessGate { - auth_locked_by, - mandatory_locked, - auth_db_present, - } - } - - fn assert_access_cases(cases: Vec) { - for (name, auth_answer, persisted, gate, expected_calls, expected_values) in cases { - let prompter = RecordingPrompter::answering( - auth_answer, - expected_values.1.or(Some(true)), - Some(expected_values.2 != SetupLoginIntent::Declined), - ); - - let dispatch = interactive_dispatch(&prompter, persisted, gate); - - assert_eq!(prompter.access_calls(), expected_calls, "{name}"); - assert_eq!(access_values(&dispatch), expected_values, "{name}"); - } - } - - #[test] - fn access_mode_and_telemetry_prompts_follow_persisted_values_locks_and_selected_mode() { - use AuthMode::{Disabled, Mandatory, Optional}; - use PromptCall::{AuthMode as Mode, Login, Telemetry}; - use SetupLoginIntent::{Declined, NotOffered}; - - assert_access_cases(vec![ - ( - "persisted globals suppress mode and telemetry; auth.db present skips login", - Some(Optional), - persisted_access(Some(Optional), Some(true), false), - access_gate(None, false, true), - vec![], - (None, None, NotOffered), - ), - ( - "persisted mode with telemetry unanswered asks telemetry then login", - None, - persisted_access(Some(Optional), None, false), - access_gate(None, false, true), - vec![Telemetry(false), Login], - (None, Some(false), Declined), - ), - ( - "selected disabled skips telemetry and login", - Some(Disabled), - PersistedSetupConfirmations::default(), - access_gate(None, false, false), - vec![Mode(Optional)], - (Some(Disabled), None, NotOffered), - ), - ( - "persisted global disabled skips every access prompt", - None, - persisted_access(Some(Disabled), None, false), - access_gate(None, false, false), - vec![], - (None, None, NotOffered), - ), - ( - "repository lock skips mode, telemetry, and login", - Some(Mandatory), - PersistedSetupConfirmations::default(), - access_gate(Some(AuthPolicyConfigFile::Repository), false, false), - vec![], - (None, None, NotOffered), - ), - ( - "explicit config lock skips mode, telemetry, and login", - Some(Optional), - PersistedSetupConfirmations::default(), - access_gate(Some(AuthPolicyConfigFile::ConfigEnv), false, false), - vec![], - (None, None, NotOffered), - ), - ( - "invalid global skips mode and telemetry", - Some(Optional), - persisted_access(None, None, true), - access_gate(None, false, true), - vec![], - (None, None, NotOffered), - ), - ]); - } - - #[test] - fn login_offer_follows_mode_auth_db_and_prompts_asked_this_run() { - use AuthMode::{Mandatory, Optional}; - use PromptCall::{AuthMode as Mode, Login, Telemetry}; - use SetupLoginIntent::{Declined, NotOffered, Requested}; - - assert_access_cases(vec![ - ( - "persisted globals without auth.db still offer login", - Some(Optional), - persisted_access(Some(Optional), Some(false), false), - access_gate(None, false, false), - vec![Login], - (None, None, Declined), - ), - ( - "selected mandatory skips login", - Some(Mandatory), - PersistedSetupConfirmations::default(), - access_gate(None, false, false), - vec![Mode(Optional), Telemetry(false)], - (Some(Mandatory), Some(false), NotOffered), - ), - ( - "effective mandatory skips login after an optional answer", - Some(Optional), - PersistedSetupConfirmations::default(), - access_gate(None, true, false), - vec![Mode(Optional), Telemetry(false)], - (Some(Optional), Some(false), NotOffered), - ), - ( - "invalid global offers login when auth.db is absent", - Some(Optional), - persisted_access(None, None, true), - access_gate(None, false, false), - vec![Login], - (None, None, Requested), - ), - ( - "answers asked this run offer login even with auth.db present", - Some(Optional), - PersistedSetupConfirmations::default(), - access_gate(None, false, true), - vec![Mode(Optional), Telemetry(false), Login], - (Some(Optional), Some(true), Requested), - ), - ]); - } - - #[test] - fn cancelling_any_access_prompt_cancels_setup() { - let cases = [ - RecordingPrompter::answering(None, Some(true), Some(true)), - RecordingPrompter::answering(Some(AuthMode::Optional), None, Some(true)), - RecordingPrompter::answering(Some(AuthMode::Optional), Some(true), None), - ]; - - for (index, prompter) in cases.iter().enumerate() { - let dispatch = interactive_dispatch( - prompter, - PersistedSetupConfirmations::default(), - SetupAccessGate::default(), - ); - - assert_eq!(dispatch, SetupDispatch::Cancelled); - assert_eq!(prompter.access_calls().len(), index + 1); - } - } - - #[test] - fn telemetry_default_ignores_claude_target_and_auth_db() { - for auth_db_present in [false, true] { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)); - - interactive_dispatch( - &prompter, - PersistedSetupConfirmations { - agent_trace_auto_sync: Some(true), - ..PersistedSetupConfirmations::default() - }, - SetupAccessGate { - auth_db_present, - ..SetupAccessGate::default() - }, - ); - - assert!(prompter - .calls - .borrow() - .contains(&PromptCall::Telemetry(false))); - } - } - - #[test] - fn non_interactive_targets_prompt_nothing_and_carry_no_access_values() { - for target in [ - SetupTarget::OpenCode, - SetupTarget::Claude, - SetupTarget::Pi, - SetupTarget::Codex, - SetupTarget::All, - ] { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Mandatory), Some(true), Some(true)); - - let dispatch = resolve_setup_dispatch( - SetupMode::NonInteractive(target), - &prompter, - &[], - &[], - PersistedSetupConfirmations::default(), - SetupAccessGate::default(), - false, - ) - .unwrap(); - - assert!(prompter.calls.borrow().is_empty()); - assert_eq!( - access_values(&dispatch), - (None, None, SetupLoginIntent::NotOffered) - ); - } - } - - fn reconfigure_dispatch( - prompter: &RecordingPrompter, - persisted: PersistedSetupConfirmations, - gate: SetupAccessGate, - ) -> SetupDispatch { - resolve_setup_dispatch( - SetupMode::Interactive, - prompter, - &[], - &[], - persisted, - gate, - true, - ) - .expect("dispatch should resolve") - } - - fn prompts_suppressed(dispatch: &SetupDispatch) -> bool { - match dispatch { - SetupDispatch::Proceed { - prompts_suppressed, .. - } => *prompts_suppressed, - SetupDispatch::Cancelled => panic!("dispatch was cancelled"), - } - } - - fn persisted_answers( - agent_trace_auto_sync: bool, - attribution_hooks_enabled: bool, - auth_mode: AuthMode, - telemetry_enabled: bool, - ) -> PersistedSetupConfirmations { - PersistedSetupConfirmations { - agent_trace_auto_sync: Some(agent_trace_auto_sync), - attribution_hooks_enabled: Some(attribution_hooks_enabled), - auth_mode: Some(auth_mode), - telemetry_enabled: Some(telemetry_enabled), - global_config_invalid: false, - } - } - - #[test] - fn reconfigure_asks_every_persisted_prompt_with_the_persisted_defaults() { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(true)); - - let dispatch = reconfigure_dispatch( - &prompter, - persisted_answers(false, true, AuthMode::Mandatory, true), - access_gate(None, false, true), - ); - - assert_eq!( - *prompter.calls.borrow(), - vec![ - PromptCall::Targets, - PromptCall::Workflows, - PromptCall::AutoSync(false), - PromptCall::Attribution(true), - PromptCall::AuthMode(AuthMode::Mandatory), - PromptCall::Telemetry(true), - PromptCall::Login, - ] - ); - assert_eq!( - access_values(&dispatch), - ( - Some(AuthMode::Optional), - Some(false), - SetupLoginIntent::Requested - ) - ); - assert!(!prompts_suppressed(&dispatch)); - } - - #[test] - fn reconfigure_uses_a_persisted_global_disabled_as_the_auth_mode_cursor() { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Disabled), Some(true), Some(true)); - - let dispatch = reconfigure_dispatch( - &prompter, - persisted_answers(true, false, AuthMode::Disabled, false), - access_gate(None, false, false), - ); - - assert_eq!( - *prompter.calls.borrow(), - vec![ - PromptCall::Targets, - PromptCall::Workflows, - PromptCall::AutoSync(true), - PromptCall::Attribution(false), - PromptCall::AuthMode(AuthMode::Disabled), - ] - ); - assert_eq!( - access_values(&dispatch), - (Some(AuthMode::Disabled), None, SetupLoginIntent::NotOffered) - ); - } - - #[test] - fn reconfigure_keeps_the_lock_and_invalid_global_gates() { - use AuthMode::Optional; - use PromptCall::{Attribution, AutoSync, Targets, Workflows}; - - let cases = [ - ( - "repository lock skips access prompts", - persisted_answers(true, true, Optional, true), - access_gate(Some(AuthPolicyConfigFile::Repository), false, false), - ), - ( - "explicit lock skips access prompts", - persisted_answers(true, true, Optional, true), - access_gate(Some(AuthPolicyConfigFile::ConfigFlag), false, false), - ), - ( - "invalid global skips mode and telemetry", - PersistedSetupConfirmations { - agent_trace_auto_sync: Some(true), - attribution_hooks_enabled: Some(true), - global_config_invalid: true, - ..PersistedSetupConfirmations::default() - }, - access_gate(None, true, true), - ), - ]; - - for (name, persisted, gate) in cases { - let prompter = - RecordingPrompter::answering(Some(AuthMode::Disabled), Some(false), Some(true)); - - let dispatch = reconfigure_dispatch(&prompter, persisted, gate); - - assert_eq!( - *prompter.calls.borrow(), - vec![Targets, Workflows, AutoSync(true), Attribution(true)], - "{name}" - ); - assert_eq!( - access_values(&dispatch), - (None, None, SetupLoginIntent::NotOffered), - "{name}" - ); - } - } - - #[test] - fn reconfigure_from_a_global_mandatory_offers_login_for_optional() { - let global_mandatory = ResolvedAccessPolicy { - auth_mode: ResolvedValue { - value: AuthMode::Mandatory, - source: ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal), - }, - telemetry_enabled: ResolvedValue { - value: false, - source: ValueSource::Default, - }, - telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), - background_cloud_allowed: true, - }; - let prompter = - RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(true)); - - let dispatch = reconfigure_dispatch( - &prompter, - persisted_answers(true, true, AuthMode::Mandatory, false), - SetupAccessGate::from_policy(&global_mandatory, true), - ); - - assert_eq!( - prompter.access_calls(), - vec![ - PromptCall::AuthMode(AuthMode::Mandatory), - PromptCall::Telemetry(false), - PromptCall::Login, - ] - ); - assert_eq!( - access_values(&dispatch), - ( - Some(AuthMode::Optional), - Some(false), - SetupLoginIntent::Requested - ) - ); - } - - #[test] - fn persisted_answers_mark_prompts_suppressed_only_without_reconfigure() { - let first_run = interactive_dispatch( - &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), - PersistedSetupConfirmations::default(), - SetupAccessGate::default(), - ); - assert!(!prompts_suppressed(&first_run)); - - let suppressed_cases = [ - PersistedSetupConfirmations { - agent_trace_auto_sync: Some(true), - ..PersistedSetupConfirmations::default() - }, - PersistedSetupConfirmations { - attribution_hooks_enabled: Some(false), - ..PersistedSetupConfirmations::default() - }, - persisted_access(Some(AuthMode::Disabled), None, false), - persisted_access(None, Some(false), false), - ]; - for persisted in suppressed_cases { - let rerun = interactive_dispatch( - &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), - persisted, - SetupAccessGate::default(), - ); - assert!(prompts_suppressed(&rerun), "{persisted:?}"); - } - - let locked = interactive_dispatch( - &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), - persisted_access(None, None, true), - access_gate(Some(AuthPolicyConfigFile::Repository), false, false), - ); - assert!(!prompts_suppressed(&locked)); - - let reconfigured = reconfigure_dispatch( - &RecordingPrompter::answering(Some(AuthMode::Optional), Some(false), Some(false)), - persisted_answers(true, true, AuthMode::Optional, true), - SetupAccessGate::default(), - ); - assert!(!prompts_suppressed(&reconfigured)); - } - - #[test] - fn reconfigure_request_rejects_every_non_interactive_combination() { - let reconfigure = |options: SetupCliOptions| { - resolve_setup_request(SetupCliOptions { - reconfigure: true, - ..options - }) - }; - let message = |flag: &str| { - format!( - "Option '--reconfigure' cannot be used with '{flag}'. Try: run 'sce setup --reconfigure' alone to change saved setup answers interactively." - ) - }; - - let mut cases: Vec<(SetupCliOptions, &str)> = [ - (SetupTarget::OpenCode, "--opencode"), - (SetupTarget::Claude, "--claude"), - (SetupTarget::Pi, "--pi"), - (SetupTarget::Codex, "--codex"), - (SetupTarget::All, "--all"), - ] - .into_iter() - .map(|(target, flag)| { - ( - SetupCliOptions { - target: Some(target), - ..SetupCliOptions::default() - }, - flag, - ) - }) - .collect(); - cases.extend([ - ( - SetupCliOptions { - non_interactive: true, - ..SetupCliOptions::default() - }, - "--non-interactive", - ), - ( - SetupCliOptions { - hooks: true, - ..SetupCliOptions::default() - }, - "--hooks", - ), - ( - SetupCliOptions { - hooks: true, - repo_path: Some(PathBuf::from("repo")), - ..SetupCliOptions::default() - }, - "--hooks", - ), - ( - SetupCliOptions { - repo_path: Some(PathBuf::from("repo")), - ..SetupCliOptions::default() - }, - "--repo", - ), - ( - SetupCliOptions { - bootstrap_context: true, - ..SetupCliOptions::default() - }, - "--bootstrap-context", - ), - ]); - - for (options, flag) in cases { - let error = reconfigure(options.clone()) - .expect_err("reconfigure combination should be rejected"); - assert_eq!(error.to_string(), message(flag), "{options:?}"); - } - - let request = reconfigure(SetupCliOptions::default()).expect("reconfigure alone is valid"); - assert_eq!(request.config_mode, Some(SetupMode::Interactive)); - assert!(request.reconfigure); - assert!(request.install_hooks); - - let plain = resolve_setup_request(SetupCliOptions::default()).unwrap(); - assert!(!plain.reconfigure); - } - - #[test] - fn access_gate_locks_only_for_repository_or_explicit_disabled() { - let policy = |mode, source| ResolvedAccessPolicy { - auth_mode: ResolvedValue { - value: mode, - source, - }, - telemetry_enabled: ResolvedValue { - value: false, - source: ValueSource::Default, - }, - telemetry: TelemetryPolicyState::Disabled(TelemetryDisabledReason::NotEnabled), - background_cloud_allowed: false, - }; - let local = ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredLocal); - let global = ValueSource::ConfigFile(ConfigPathSource::DefaultDiscoveredGlobal); - - let cases = [ - ( - policy(AuthMode::Disabled, local), - Some(AuthPolicyConfigFile::Repository), - false, - ), - ( - policy( - AuthMode::Disabled, - ValueSource::ConfigFile(ConfigPathSource::Flag), - ), - Some(AuthPolicyConfigFile::ConfigFlag), - false, - ), - ( - policy( - AuthMode::Disabled, - ValueSource::ConfigFile(ConfigPathSource::Env), - ), - Some(AuthPolicyConfigFile::ConfigEnv), - false, - ), - (policy(AuthMode::Disabled, global), None, false), - (policy(AuthMode::Mandatory, local), None, true), - (policy(AuthMode::Mandatory, global), None, false), - ( - policy(AuthMode::Optional, ValueSource::Default), - None, - false, - ), - ]; - - for (policy, locked_by, mandatory) in cases { - let gate = SetupAccessGate::from_policy(&policy, true); - - assert_eq!( - gate, - SetupAccessGate { - auth_locked_by: locked_by, - mandatory_locked: mandatory, - auth_db_present: true, - } - ); - } - } #[test] fn sce_info_assets_install_only_for_claude_and_exclude_development_files() { diff --git a/cli/src/services/setup/prompt.rs b/cli/src/services/setup/prompt.rs index 979852d17..a95f978ee 100644 --- a/cli/src/services/setup/prompt.rs +++ b/cli/src/services/setup/prompt.rs @@ -265,79 +265,3 @@ pub(super) fn setup_prompt_target_label_with_color_policy( prompt_value_with_color_policy(label, color_enabled) } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn auth_mode_rows_map_to_modes_in_fixed_order_with_fixed_labels() { - let rows = auth_mode_prompt_rows(); - let mapped: Vec<(AuthMode, String)> = - rows.iter().map(|row| (row.0, row.to_string())).collect(); - - assert_eq!( - mapped, - vec![ - ( - AuthMode::Optional, - "Optional: use SCE locally and log in when you want SCE cloud features" - .to_string() - ), - ( - AuthMode::Mandatory, - "Mandatory: require an SCE login when setting up".to_string() - ), - ( - AuthMode::Disabled, - "Disabled: local only; no SCE login, cloud sync, or telemetry".to_string() - ), - ] - ); - } - - #[test] - fn auth_mode_default_cursor_points_at_the_default_row() { - let rows = auth_mode_prompt_rows(); - - for mode in [AuthMode::Optional, AuthMode::Mandatory, AuthMode::Disabled] { - let index = auth_mode_prompt_default_index(mode); - assert_eq!(rows[index].0, mode); - } - assert_eq!(auth_mode_prompt_default_index(AuthMode::Optional), 0); - } - - #[test] - fn new_prompt_labels_and_defaults_are_fixed() { - assert_eq!( - TELEMETRY_CONSENT_PROMPT_LABEL, - "Share SCE telemetry?\n(Sends SCE usage telemetry to SCE servers using your SCE login. If Claude is\nselected, also configures Claude Code's native telemetry export. Separate from\nAgent Trace sync. Applies to all repositories on this machine.)" - ); - assert_eq!( - LOGIN_PROMPT_LABEL, - "Log in to SCE now?\n(Opens a device login in your browser. An existing login on this machine is\nreused. You can log in later with 'sce auth login'.)" - ); - assert_eq!(AUTH_MODE_PROMPT_TITLE, "SCE account mode for this machine"); - } - - #[test] - fn interactive_prompt_result_maps_cancel_and_not_tty_like_existing_prompts() { - assert_eq!( - interactive_prompt_result(Ok(AuthMode::Mandatory)).unwrap(), - Some(AuthMode::Mandatory) - ); - assert_eq!( - interactive_prompt_result::(Err(InquireError::OperationCanceled)).unwrap(), - None - ); - assert_eq!( - interactive_prompt_result::(Err(InquireError::OperationInterrupted)).unwrap(), - None - ); - let error = interactive_prompt_result::(Err(InquireError::NotTTY)).unwrap_err(); - assert_eq!( - error.to_string(), - "Interactive setup requires a TTY. Re-run with '--non-interactive' and one of '--opencode', '--claude', '--pi', '--codex', or '--all'." - ); - } -} diff --git a/cli/src/services/sync/command.rs b/cli/src/services/sync/command.rs index b62f88651..25c2fb463 100644 --- a/cli/src/services/sync/command.rs +++ b/cli/src/services/sync/command.rs @@ -94,31 +94,3 @@ impl SyncCommand { .map_err(|error| CliError::runtime(anyhow::Error::msg(format!("{error:#}")))) } } - -#[cfg(test)] -mod tests { - use super::classify_sync_error; - use crate::services::error::{AuthPolicyConfigFile, CliError, UserError}; - use crate::services::sync::sync::TraceSyncError; - - #[test] - fn classify_sync_error_maps_disabled_auth_to_auth_disabled_by_config() { - for file in [ - AuthPolicyConfigFile::Global, - AuthPolicyConfigFile::Repository, - AuthPolicyConfigFile::ConfigFlag, - AuthPolicyConfigFile::ConfigEnv, - ] { - let error = classify_sync_error(TraceSyncError::AuthDisabled(file)); - let CliError::User { - error: user_error, .. - } = &error - else { - panic!("expected a user-facing error for {file:?}"); - }; - assert_eq!(*user_error, UserError::AuthDisabledByConfig(file)); - assert_eq!(user_error.key(), "auth.disabled_by_config"); - assert_eq!(error.to_string(), user_error.message()); - } - } -} diff --git a/cli/src/services/sync/sync.rs b/cli/src/services/sync/sync.rs index 1557b02ba..ecfaa8bee 100644 --- a/cli/src/services/sync/sync.rs +++ b/cli/src/services/sync/sync.rs @@ -546,10 +546,7 @@ mod tests { use serde_json::{json, Value}; use tokio::sync::{oneshot, Notify}; - use super::{ - join_three_to_completion, run_current_sync_with_progress_and_clock, sync_one_stream, - StreamSyncReport, SystemSyncProgressClock, TraceSyncError, - }; + use super::{join_three_to_completion, sync_one_stream, StreamSyncReport, TraceSyncError}; use crate::services::agent_trace_db::MessageRole; use crate::services::agent_trace_export::AgentTraceMessageExportRow; use crate::services::agent_trace_sync::control_plane::{ @@ -559,7 +556,7 @@ mod tests { use crate::services::agent_trace_sync::StreamSyncError; use crate::services::auth::TokenResponse; use crate::services::db::encryption_key::CredentialAccess; - use crate::services::error::AuthPolicyConfigFile; + use crate::services::sync::progress::NoopProgressReporter; use crate::services::token_storage::StoredTokens; @@ -569,36 +566,6 @@ mod tests { const TEST_DEADLINE: Duration = Duration::from_secs(10); const STALL_SAFETY_BOUND: Duration = Duration::from_secs(10); - #[tokio::test] - async fn sync_rejects_disabled_auth_before_storage_or_credential_access() { - let dir = tempfile::tempdir().expect("temp dir"); - std::fs::create_dir(dir.path().join(".git")).expect("repository marker"); - std::fs::create_dir_all(dir.path().join(".sce")).expect("config dir"); - std::fs::write( - dir.path().join(".sce").join("config.json"), - r#"{"auth":{"mode":"disabled"}}"#, - ) - .expect("repository config"); - - let error = run_current_sync_with_progress_and_clock( - dir.path(), - &mut NoopProgressReporter, - &SystemSyncProgressClock, - ) - .await - .expect_err("disabled auth must reject sync"); - - assert!( - matches!( - error, - TraceSyncError::AuthDisabled(AuthPolicyConfigFile::Repository) - ), - "{error:?}" - ); - assert!(!error.is_authentication_failure()); - assert_eq!(error.storage_failure(), None); - } - #[tokio::test] async fn sibling_failure_does_not_cancel_in_flight_credential_save() { let (save_started_tx, save_started_rx) = oneshot::channel::<()>(); diff --git a/cli/src/services/telemetry_credential_storage.rs b/cli/src/services/telemetry_credential_storage.rs index d1a833cc9..ed07c22be 100644 --- a/cli/src/services/telemetry_credential_storage.rs +++ b/cli/src/services/telemetry_credential_storage.rs @@ -509,105 +509,6 @@ mod tests { assert_eq!(loaded, TelemetryCredentialLookup::Valid(saved)); } - async fn insert_raw_credential(db: &TestDb, token: &str, user_id: &str, expires_at: i64) { - db.execute( - "INSERT OR REPLACE INTO telemetry_credentials \ - (id, token, accessor, expires_at_unix_seconds, stored_at_unix_seconds, user_id, workspace_id) \ - VALUES (1, ?1, 'acc', ?2, 0, ?3, ?4)", - ( - token, - expires_at, - user_id, - if user_id.is_empty() { "" } else { WORKSPACE_A }, - ), - ) - .await - .expect("raw telemetry row should insert"); - } - - #[derive(Clone, Copy, Debug)] - enum StoredState { - NoRow, - Valid, - Expired, - NoWorkosSession, - IdentityMismatch, - LegacyIdentityless, - EmptyToken, - NegativeExpiry, - } - - #[tokio::test] - async fn telemetry_credential_lookup_classifies_auth_db_states() { - let far_future = i64::try_from(FAR_FUTURE).expect("fits"); - let (_guard, db) = open_db().await; - for (state, expected) in [ - (StoredState::NoRow, TelemetryCredentialLookup::Missing), - ( - StoredState::Valid, - TelemetryCredentialLookup::Valid(credential("tok-valid", FAR_FUTURE)), - ), - (StoredState::Expired, TelemetryCredentialLookup::Expired), - ( - StoredState::NoWorkosSession, - TelemetryCredentialLookup::Unusable, - ), - ( - StoredState::IdentityMismatch, - TelemetryCredentialLookup::Unusable, - ), - ( - StoredState::LegacyIdentityless, - TelemetryCredentialLookup::Unusable, - ), - (StoredState::EmptyToken, TelemetryCredentialLookup::Unusable), - ( - StoredState::NegativeExpiry, - TelemetryCredentialLookup::Unusable, - ), - ] { - delete_with(&db).await.expect("delete should succeed"); - seed_session(&db, USER_A, WORKSPACE_A).await; - match state { - StoredState::NoRow => {} - StoredState::Valid => save_with(&db, &credential("tok-valid", FAR_FUTURE)) - .await - .expect("save should succeed"), - StoredState::Expired => save_with(&db, &credential("tok-expired", now() - 10)) - .await - .expect("save should succeed"), - StoredState::NoWorkosSession => { - save_with(&db, &credential("tok-orphan", FAR_FUTURE)) - .await - .expect("save should succeed"); - db.execute("DELETE FROM auth_credentials", ()) - .await - .expect("workos row should be cleared"); - } - StoredState::IdentityMismatch => { - save_with(&db, &credential("tok-a", FAR_FUTURE)) - .await - .expect("save should succeed"); - seed_session(&db, USER_B, WORKSPACE_A).await; - } - StoredState::LegacyIdentityless => { - insert_raw_credential(&db, "tok-legacy", "", far_future).await; - } - StoredState::EmptyToken => { - insert_raw_credential(&db, "", USER_A, far_future).await; - } - StoredState::NegativeExpiry => { - insert_raw_credential(&db, "tok", USER_A, -5).await; - } - } - assert_eq!( - load_with(&db, now()).await.expect("load should succeed"), - expected, - "{state:?}" - ); - } - } - #[tokio::test] async fn telemetry_credential_storage_leaves_workos_credentials_untouched() { let (_guard, db) = open_db().await; @@ -954,46 +855,6 @@ mod tests { assert_eq!(repository_token(&db, REPOSITORY_A).await, None); } - #[tokio::test] - async fn repository_readiness_follows_binding_rather_than_credential_issuance() { - let (_guard, db) = open_db().await; - log_in_as(&db, USER_A, WORKSPACE_A, "tok-a").await; - assert!( - bind_repository_with(&db, now(), REPOSITORY_A, RepositoryBindingMode::Enroll) - .await - .expect("bind should succeed") - ); - - log_in_as(&db, USER_B, WORKSPACE_B, "tok-b").await; - assert!( - !bind_repository_with( - &db, - now(), - REPOSITORY_A, - RepositoryBindingMode::EnrollIfUnbound - ) - .await - .expect("bind should succeed"), - "issued credential must not take over a repository bound to another identity" - ); - assert!(load_with(&db, now()) - .await - .expect("load should succeed") - .into_valid() - .is_some()); - assert_eq!(repository_token(&db, REPOSITORY_A).await, None); - - seed_session(&db, USER_A, WORKSPACE_A).await; - save_with(&db, &credential("tok-a-existing", FAR_FUTURE)) - .await - .expect("save should succeed"); - assert_eq!( - repository_token(&db, REPOSITORY_A).await, - Some("tok-a-existing".to_string()), - "already-authorized repository is ready without a new enrollment" - ); - } - #[tokio::test] async fn incomplete_identity_is_never_saved() { let (_guard, db) = open_db().await; diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 80ea03c5e..4c7584084 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -110,12 +110,12 @@ Each string is a `WARNING_*` constant in `resolver.rs`. The skipped file's own e - `- auth.mode: (source: …[, config_source: …])` (the effective mode and its deciding layer) - `- telemetry.enabled: (source: …[, config_source: …])` (the configured merged value) - `- telemetry.effective: enabled`, or `- telemetry.effective: disabled (reason: )` - - only when disabled: `- telemetry.note: Claude Code telemetry settings written by earlier sce setup runs are not changed by telemetry.enabled.` + - only when disabled: `- telemetry.note: Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` - **JSON:** `result.resolved.auth.mode` and `result.resolved.telemetry.enabled` use the usual `{value, source, config_source}` shape. `result.resolved.telemetry.effective` is `{state, reason}`, where `reason` is `null` when the state is enabled. `result.resolved.telemetry.note` is the fixed note string, or `null` when enabled. - **Reason strings** (`TelemetryDisabledReason::as_str`): `not_enabled`, `user_opt_out`, `no_user_consent`, `repository_opt_out`, `auth_disabled`, `invalid_config`. - **Warnings:** the contradiction warnings appear in `show` warnings after any `Skipped invalid config: …` entries. In `validate` they appear in `warnings` / `Validation warnings`. `validate` adds no policy fields. -The note documents a coverage limit: telemetry opt-out does not remove Claude-native telemetry settings already written to user-level Claude settings. +The note documents a coverage limit: a repository or explicit-layer opt-out does not remove Claude-native telemetry settings already written to user-level Claude settings. Only a global withdrawal does, on the next `sce setup` run (see Enforcement). ## Setup @@ -132,7 +132,7 @@ Setup then enforces the re-resolved mode with a login step: it never logs in und - **Managed telemetry startup** (commands and admitted Claude hooks): `cli/src/app.rs` takes `telemetry_enabled()` from the startup `ResolvedObservabilityRuntimeConfig`. When telemetry is not `Enabled`, `RuntimeTelemetry::resolve` returns Noop with fallback reason `disabled_by_config` (logged at `debug`). This happens before `auth.db` is opened or the credential store is touched. See [telemetry credential](../sce/telemetry-credential.md). - **`sce doctor` managed-telemetry health:** doctor resolves the policy for the inspected repository root. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it reports `[PASS] Managed telemetry (disabled by config)` (JSON `state` / `reason` `disabled_by_config`). It may check whether `auth.db` exists (for the opt-in note), but never opens it or touches the credential store. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). - **`sce auth telemetry-headers`** (Claude's `otelHeadersHelper`): the helper resolves the policy from its working directory through `resolve_auth_runtime_config`. A missing working directory or a resolution failure counts as not enabled. When telemetry is not `Enabled`, it fails closed with the existing fixed `Telemetry credential is unavailable.` diagnostic and empty stdout. This happens before the destination tripwire, the `auth.db` existence check, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). -- **`sce setup` Claude telemetry install:** with the Claude target selected, setup resolves the policy for the setup repository root through `resolve_auth_runtime_config`. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it skips the Claude-native install with the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and leaves user Claude settings unchanged. See [telemetry credential: Claude-native telemetry](../sce/telemetry-credential.md#claude-native-telemetry). +- **`sce setup` Claude telemetry install:** with the Claude target selected, setup resolves the policy for the setup repository root through `resolve_auth_runtime_config`. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it skips the Claude-native install with the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and leaves user Claude settings unchanged. The exception is a withdrawal in the global user config itself (`telemetry.enabled: false` or `auth.mode: disabled`, read with `read_global_access_preferences`, never the effective reason): setup then removes the SCE-owned Claude settings, in every interactive run and in non-interactive runs with Claude selected. See [telemetry credential: Claude-native telemetry](../sce/telemetry-credential.md#claude-native-telemetry). - **`sce auth login` / `sce auth whoami`:** both resolve the policy from the working directory through `resolve_auth_runtime_config` and check `auth_allowed()` before any `token_storage` call. A resolution failure is a command error. - Under `disabled`, both fail with `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`, runtime class, exit code 4) before `auth.db` or the credential store is touched. The fixed message names `auth.mode: disabled` and the config file of the deciding layer: the global SCE config, the repository `.sce/config.json`, the `--config` file, or the `SCE_CONFIG_FILE` file (`AuthPolicyConfigFile`). It tells the user to set `auth.mode` to `optional` or `mandatory` there. - Login provisions a telemetry credential only when telemetry is `Enabled`. Otherwise `telemetry_provisioning` is `disabled`, with the fixed message ``Telemetry credential provisioning is disabled by SCE config. Set `telemetry.enabled: true` in the global SCE config to enable it.``, shown in text as a `Note:` line. Disabled provisioning issues nothing and enrolls no repository. diff --git a/context/context-map.md b/context/context-map.md index 7f8dc9e63..8052f4c37 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -25,7 +25,7 @@ Feature/domain context: - `context/cli/async-persistence-guarantees.md` (verified guarantees and named limits of the directly awaited Turso persistence migration — exclusive `&mut` transactions, deferred rollback, credential-rotation and terminal-sync behavior, lease/descriptor protection — plus PR1–PR4 staging and the PR3 cleanup ledger) - `context/cli/agent-trace-sync-command.md` (composed local-to-control-plane `sce sync` architecture: the `hooks/plugins → repository Agent Trace DB → AgentTraceExportReader → sce sync → HTTPS + WorkOS Bearer → control plane` data flow, the `sce auth login` / `cd ` / `sce sync` user flow, the no-local-cursor/no-`agent-trace-sync.db`/no-Turso-Sync/no-`BridgeLock`/no-local-DWH invariants, the four-local-capture-streams versus three-remote-streams boundary with its `diff_traces` release gate, the optional `commitPatchId` field on the existing `agent_traces` stream with its Control Plane release dependency and no-backfill limit, and `401`/`409`/ambiguous-batch-failure recovery semantics) - `context/cli/config-precedence-contract.md` (implemented `sce config` show/validate command contract, deterministic `flags > env > config file > defaults` resolution order, focused `config/resolver.rs` ownership for config discovery/merge/runtime precedence plus default-discovered invalid-file degradation, focused `config/render.rs` ownership for `show`/`validate` text+JSON output construction, canonical `$schema` acceptance for startup-loaded `sce/config.json` files, shared auth-key env/config/optional baked-default support starting with `workos_client_id`, shared runtime resolution for flat logging observability keys including config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` with `/sce/logs` defaulting plus config-file/default-only positive `log_file_retention_limit`, config-file-only `agent_trace.repository_id`/`agent_trace.repository_remote` repository-identity keys with default remote `origin`, `agent_trace.auto_sync` resolution with omitted-value fallback `false`, explicit-false opt-out, and setup-written explicit `true` bootstrap behavior for the post-commit trigger boundary, the catalog-derived `integrations.optional_workflows` optional-workflow selection key, schema-validated per-layer `auth.mode` / `telemetry.enabled` sections, JSON-pointer-prefixed schema-validation errors, canonical Pkl-generated `sce/config.json` schema ownership plus CLI embedding/reuse contract including `policies.attribution_hooks.enabled` default-true/explicit-false opt-out metadata, config-file selection order, `show` provenance output, and trimmed `validate` output contract) -- `context/cli/access-policy.md` (effective access policy resolved from user (global), repository (Git-root `.sce/config.json`), and explicit (`--config` / `SCE_CONFIG_FILE`) config layers, where an explicit file cannot lift a global or repository restriction: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before the `auth.db` existence check, repository resolution, and the `auth.db` lookup), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed), and the `sce setup` Claude-native telemetry install (skipped with a fixed line unless telemetry is enabled); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) +- `context/cli/access-policy.md` (effective access policy resolved from user (global), repository (Git-root `.sce/config.json`), and explicit (`--config` / `SCE_CONFIG_FILE`) config layers, where an explicit file cannot lift a global or repository restriction: `auth.mode` most-restrictive-wins, consent-gated `telemetry.enabled` state and disabled reasons, degraded-config shutdown of telemetry and background cloud operations, fixed contradiction warnings, `sce config show` policy reporting, exposure on the auth/hook/observability runtime projections, and enforcement in managed telemetry startup, `sce doctor` health (`disabled_by_config`), the hidden `sce auth telemetry-headers` helper (fail closed before the `auth.db` existence check, repository resolution, and the `auth.db` lookup), `sce auth login`/`whoami` (`auth.disabled_by_config` rejection before credential storage, `disabled` telemetry provisioning without consent, `mandatory` unauthenticated whoami failure), `sce sync` (`auth.disabled_by_config` before storage or credentials), post-commit auto-sync plus its doctor row (launch only when background cloud operations are allowed), and the `sce setup` Claude-native telemetry install (skipped with a fixed line unless telemetry is enabled, with SCE-owned Claude settings removed only on a global-config withdrawal); decision in `context/decisions/2026-10-20-consent-gated-access-policy-precedence.md`) - `context/cli/capability-traits.md` (current broad CLI capability seam in `cli/src/services/capabilities.rs`, including `FsOps`/`StdFsOps` (method-less marker), `GitOps`/`ProcessGitOps` (command execution and availability), compile-time-typed borrowed AppContext wiring with scoped borrowing across directly awaited commands with associated-type narrow capability accessors plus `ContextWithRepoRoot` repo-root-scoped context derivation, generic command execution bounds, and test-only unimplemented stubs; current service internals do not consume fs/git traits until later lifecycle migration tasks) - `context/cli/service-lifecycle.md` (current async lifecycle seam in `cli/src/services/lifecycle.rs`, including default no-op `ServiceLifecycle` diagnose/fix/setup methods against narrow `HasRepoRoot`, lifecycle-owned health/fix/setup result types with generic setup messages, doctor/setup adapter boundaries, the static `LifecycleProvider` enum catalog/dispatcher, hook/config/local_db/auth_db/agent_trace_db lifecycle providers including setup-time repository-scoped Agent Trace DB initialization plus checkout identity diagnostics, implemented doctor aggregation over diagnose/fix providers, and implemented setup aggregation over `setup` providers in order config → local_db → auth_db → agent_trace_db → hooks when requested) - `context/cli/mutation-trace-protocol.md` (pure, dependency-free `cli/src/services/mutation_trace/` refinement of the verified `spec/mutation_cursor.qnt` mutation-cursor protocol: the full pure action set — `prepare`/`commit` transition logic, attribution/mutation-event materialization, snapshot-failure/database-failure taint actions, scope abandonment, and recovery with an explicit observed-tree input — plus cross-action sequence/invariant tests and a module-level Quint refinement matrix are all complete (`types.rs`, `protocol.rs`, `mod.rs`, `tests.rs`, registered with `#[allow(dead_code)]`); opaque-newtype identity refinement decisions vs. the Quint model's bounded enums, and the `coordinator.rs` target end-state seam this layout leaves room for but does not create — `store.rs`, `runtime/git_snapshot.rs`, and `runtime/coordinator.rs` (including its public `coordinate()` entrypoint) now exist, built out by the `mutation-cursor-store-persistence` and `mutation-cursor-runtime-coordinator` plans respectively; `protocol.rs` is invoked only through the runtime, and the runtime is now driven by the generic `sce hooks mutation-scope` CLI ingress and a first Claude Code adapter driver, registered by `sce setup` and reachable by a real Claude Code session, now proven against real Git repositories and a real Agent Trace DB by the `claude-mutation-scope-integration` plan's T08 regressions) @@ -95,7 +95,7 @@ Feature/domain context: - `context/sce/shared-turso-db.md` (current shared `cli/src/services/db/mod.rs` Turso database infrastructure seam, including `DbSpec`, generic `TursoDb`, encrypted `EncryptedTursoDb`, build-time generated migration constants from `cli/build.rs`/Cargo `OUT_DIR`, config-driven async constructor/open-connect retry via `run_with_retry`, no-migration `TursoDb::open_without_migrations()` / explicit-path `open_without_migrations_at(path)` for hot runtime paths, migration-running `new()` / explicit-path `new_at(path)` / `run_migrations()` with per-database `__sce_migrations` tracking, config-driven async operation retry for `execute`/`query_map` (retry-policy budget, not a wall-clock bound), per-`DbSpec` Turso busy timeout on connect (1000 ms for the Agent Trace DB, unset for other databases), the Agent Trace-only outer write-contention retry for replay-safe write units including the opt-in `execute_idempotent_write` and its structured contention-exhaustion error plus `sce.agent_trace_db.contention_exhausted` tracing event, raw-value row fetching for deterministic operator-facing rendering, row-mapping excluded from retry, generic embedded migration execution, non-mutating `migration_metadata_problems()` and `ensure_schema_ready(setup_guidance)` readiness methods on `TursoDb`, non-mutating-data `passive_checkpoint()` PASSIVE WAL checkpoint method on `TursoDb` (not on `EncryptedTursoDb`, fail-open, no truncation guarantee, called once by `sce hooks post-commit` after successful Agent Trace persistence — see `context/sce/agent-trace-hooks-command-routing.md`), and async concrete wrappers for `LocalDb`, `AuthDb`, plus `RepositoryAgentTraceDb`; no adapter runtime bridge) - `context/sce/agent-trace-db-write-contention-evidence.md` (measured Agent Trace DB write-contention behavior under the busy-timeout/outer-retry/contention-deadline contract: the `lock_contention_tests.rs` suite with its lock-budget boundary, strict N=2–4 in-process and real-hook gates and N=8 stress characterization, policy history from 500 / 1250 to the current 1000 / 2250 defaults, the supported-load failure that motivated the tuning, before-vs-after comparison, and the bounded-policy exhaustion failure mode) - `context/sce/auth-db.md` (encrypted `AuthDb = EncryptedTursoDb` adapter, canonical `/sce/auth.db` path, build-time generated `AUTH_MIGRATIONS` from `cli/migrations/auth/`, auth credential schema and updated-at trigger baseline, lifecycle setup/doctor integration, async encrypted token-storage persistence through a Result-valued Tokio OnceCell, and `SCE_AUTH_DB_ENCRYPTION_KEY`/OS credential-store key handling) -- `context/sce/telemetry-credential.md` (telemetry-only OpenBao credential: typed Control Plane issuance client, save-on-issue, single-row encrypted `auth.db` storage that never mints on lookup, deterministic auth-login `telemetry_provisioning` status/message rendering with secret-free unavailable warnings, production issue-and-save after WorkOS persistence on fresh/valid-stored/renewed paths, logout deletion alongside WorkOS credentials, issuing-token identity binding with session-ownership checks, repository-to-workspace enrollment bindings, local deletion not revoking the OpenBao token, and its use as the managed OTLP bearer source, the hidden `telemetry-headers` helper and its OS-user trust boundary with no endpoint-pinning claim, and Claude-native telemetry setup, rotation, logout, conflict handling, and override limits) +- `context/sce/telemetry-credential.md` (telemetry-only OpenBao credential: typed Control Plane issuance client, save-on-issue, single-row encrypted `auth.db` storage that never mints on lookup, deterministic auth-login `telemetry_provisioning` status/message rendering with secret-free unavailable warnings, production issue-and-save after WorkOS persistence on fresh/valid-stored/renewed paths, logout deletion alongside WorkOS credentials, issuing-token identity binding with session-ownership checks, repository-to-workspace enrollment bindings, local deletion not revoking the OpenBao token, and its use as the managed OTLP bearer source, the hidden `telemetry-headers` helper and its OS-user trust boundary with no endpoint-pinning claim, and Claude-native telemetry setup, removal of SCE-owned settings on global-config withdrawal, rotation, logout, conflict handling, and override limits) - `context/sce/agent-trace-db.md` (implemented Agent Trace database adapter: the sole repository-scoped `RepositoryAgentTraceDb` backed by the fresh multi-statement baseline schema plus additive `source_instance_id`, `claude_model_state`, mutation-trace, and `007_commit_patch_id` (nullable `agent_traces.commit_patch_id`, setup-only upgrade) migrations, with `repository_metadata` carrying both `repository_id` and a concurrency-safe atomic-claim `source_instance_id` (physical database identity, independent of `repository_id`), narrow concurrent-first-open repair for missing one-file baseline migration metadata after all required schema tables exist, no trace-table `checkout_id` columns, repository-level typed insert helpers for diff traces, post-commit intersections, Agent Trace rows, messages, parts, and the non-exported exact-scope Claude model-state register, repository-level recent diff-trace reads without checkout filtering including persisted hunk-model plus canonical touched-line-session enrichment for structured rows, async on-demand command/hook initialization with no daemon/background service, and the never-touch on-disk boundary for any pre-migration checkout-scoped/global DB files; the checkout-scoped `AgentTraceDb` adapter, its `agent_trace_db_path()`/`agent_trace_db_path_for_checkout()` helpers, and the 15-file `cli/migrations/agent-trace/` chain were removed by the `retire-legacy-agent-trace-db` plan; active hook writers/readers and Agent Trace setup/lifecycle resolve repository storage through `agent_trace_storage`) - `context/sce/agent-trace-db-schema.md` (per-table columns, lookup indexes, and `updated_at` triggers of the repository-scoped Agent Trace database, including the nullable `agent_traces.commit_patch_id` column) - `context/sce/agent-trace-export-readers.md` (implemented `AgentTraceExportReader<'a>` in `cli/src/services/agent_trace_export/mod.rs`: the read-only async local export boundary over `RepositoryAgentTraceDb` — `read_messages_after`/`read_parts_after`/`read_agent_traces_after`, each cursor/limit/JS-safe-integer validated, materialized into owned camelCase `serde::Serialize` DTOs, with `agent_traces` rows carrying an always-present nullable `commitPatchId`; composes directly with `ResolvedAgentTraceStorage` without owning `source_instance_id`; `diff_traces` has no reader; no local sync cursor, no `agent-trace-sync.db`, no Turso Sync, no ETL, no DWH) diff --git a/context/decisions/2026-10-21-claude-telemetry-removal-on-global-withdrawal.md b/context/decisions/2026-10-21-claude-telemetry-removal-on-global-withdrawal.md new file mode 100644 index 000000000..054bbdf92 --- /dev/null +++ b/context/decisions/2026-10-21-claude-telemetry-removal-on-global-withdrawal.md @@ -0,0 +1,64 @@ +# Decision: Remove SCE-owned Claude telemetry settings only on global consent withdrawal + +Date: 2026-10-21 +Status: Accepted +Plan: `context/plans/claude-telemetry-consent-reconciliation.md` +Task: `T03` + +## Context + +`sce setup` installs Claude Code's native OpenTelemetry settings into user-level Claude settings when telemetry is enabled. Before this decision, withdrawing consent left those settings in place. Claude kept sending OTLP payloads to the managed collector without an `Authorization` header, so data still left the machine even though the server rejected it. Claude settings are user-owned files outside the repository, they may also hold user or third-party telemetry, and one user-level file serves every repository on the machine. + +## Decision + +`sce setup` removes SCE-owned entries from user-level Claude settings only when the global user config itself records a withdrawal (`telemetry.enabled: false` or `auth.mode: disabled`, read with `read_global_access_preferences`). Repository-layer and explicit-layer (`--config` / `SCE_CONFIG_FILE`) opt-outs never modify Claude settings. + +Ownership is established by exact-value matching. The anchor is `otelHeadersHelper == "sce auth telemetry-headers"`, and every telemetry key present must equal SCE's written value (`claude_telemetry_conflict == None`). Interactive runs reconcile whatever the target, before the setup login step. Non-interactive runs reconcile only with the Claude target selected. + +## Rationale + +Under the resolver, a global withdrawal disables SCE telemetry in every repository, and no repository or explicit layer can lift it. Removing user-level settings therefore cannot break another repository. Repository and explicit opt-outs are local, so the `sce auth telemetry-headers` helper already enforces them by failing closed. Exact-value matching with an SCE-specific anchor identifies SCE's writes without new durable state. + +## Alternatives considered + +- **Remove on any effective disable (including repository or explicit opt-out)** — would disable Claude telemetry that other repositories still rely on. +- **Remove every `OTEL_*` / `CLAUDE_CODE_*` key** — would destroy user or third-party telemetry. +- **Marker file, ownership registry, or database** — adds durable state that drifts from user edits and causes multi-machine and dotfile-sync problems, and still needs value checks. +- **Partial removal from modified settings** — removing shared switches would disable the user's own exporter. + +## Compatibility and risks + +- Removal re-sorts keys and pretty-prints the file, the same effect install already has. +- A key the user set before install with exactly SCE's value cannot be distinguished from SCE's write and is removed. +- In interactive runs, the removal line appears before the `SCE login` section. +- An older SCE binary may reinstall the settings when it runs with consent enabled. + +## Guardrails + +- Managed (enterprise) Claude settings are never written. A note line reports when they also configure telemetry. +- Modified, partial, malformed, symlinked, or read-only settings are left byte-identical, with a fixed report line and manual remediation. +- Removal never opens `auth.db` or the credential store and never runs repository authorization or login. +- Cleanup failure is non-fatal and never rolls back the saved global consent. +- `sce auth logout` does not touch Claude settings. + +## Consequences + +- After a global withdrawal, the next `sce setup` run stops Claude-native export to the managed collector. +- Re-enabling global consent reinstalls the settings through the unchanged install path. +- Repository-level opt-outs keep relying on the helper's fail-closed behavior. + +## Follow-up + +- None. + +## References + +- Plan: [`claude-telemetry-consent-reconciliation`](../plans/claude-telemetry-consent-reconciliation.md) +- Task: `T03` +- Current-state context: [`telemetry-credential.md`](../sce/telemetry-credential.md) +- Current-state context: [`access-policy.md`](../cli/access-policy.md) +- Current-state context: [`setup-repo-local-config-bootstrap.md`](../sce/setup-repo-local-config-bootstrap.md) +- Evidence: [`command.rs`](../../cli/src/services/setup/command.rs) +- Evidence: [`claude_telemetry.rs`](../../cli/src/services/setup/claude_telemetry.rs) +- Related decision: [Setup writes access answers to user layer only](2026-10-21-setup-writes-access-answers-to-user-layer-only.md) +- Related decision: [Consent-gated access policy precedence](2026-10-20-consent-gated-access-policy-precedence.md) diff --git a/context/plans/claude-telemetry-consent-reconciliation.md b/context/plans/claude-telemetry-consent-reconciliation.md new file mode 100644 index 000000000..8ab0e3270 --- /dev/null +++ b/context/plans/claude-telemetry-consent-reconciliation.md @@ -0,0 +1,461 @@ +# Plan: claude-telemetry-consent-reconciliation + +## Change summary + +PR title: `fix: Reconcile Claude-native telemetry settings with SCE consent`. + +Today `sce setup` installs Claude Code's native OpenTelemetry settings into user-level Claude settings when the Claude target is selected and the effective access policy enables telemetry. When the user later withdraws consent (for example `sce setup --reconfigure` answering "Share SCE telemetry?" with No, or choosing account mode `disabled`), setup saves the withdrawal to the global SCE config but leaves the Claude settings in place. SCE's own exporter and the `sce auth telemetry-headers` helper already fail closed, but Claude keeps `CLAUDE_CODE_ENABLE_TELEMETRY=1` and keeps sending OTLP requests to `https://otel.crocoderlab.dev` without an `Authorization` header. The payloads still leave the machine even though the server rejects them. `sce config show` documents this gap with its `telemetry.note` line. + +This plan extends the existing Claude telemetry stage with a removal path. When the **global user config** records a withdrawal (`telemetry.enabled: false` or `auth.mode: disabled`), setup removes only the Claude settings it can attribute to SCE. Attribution uses exact-value fingerprint matching against the values SCE writes, anchored on `otelHeadersHelper == "sce auth telemetry-headers"`. Unrelated settings, user-owned or third-party telemetry, and managed (enterprise) settings are preserved. Repository-local opt-outs are never treated as global withdrawal, so another repository's Claude telemetry is not disabled. No marker file, database, or ownership registry is introduced. Install behavior, conflict detection, and the PR #339 non-interactive no-auth-storage contract are unchanged. + +Base: branch `sce-setup` at `a1712e4b` (includes PR #339, `setup: Skip Claude authorization checks for non-interactive runs`). + +## Current implementation findings + +All paths are under `cli/src/services/`. + +### Keys SCE writes (verified from code) + +`setup/config_merge.rs::claude_telemetry_env_entries` plus `merge_claude_telemetry_settings` write exactly these 10 entries: + +| Location | Key | Value written | +|---|---|---| +| top level | `otelHeadersHelper` | `sce auth telemetry-headers` (`CLAUDE_OTEL_HEADERS_HELPER_COMMAND`) | +| `env` | `CLAUDE_CODE_ENABLE_TELEMETRY` | `1` | +| `env` | `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA` | `1` | +| `env` | `OTEL_TRACES_EXPORTER` | `otlp` | +| `env` | `OTEL_METRICS_EXPORTER` | `otlp` | +| `env` | `OTEL_LOGS_EXPORTER` | `otlp` | +| `env` | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` (`managed_telemetry::MANAGED_OTLP_PROTOCOL`) | +| `env` | `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://otel.crocoderlab.dev` (`managed_telemetry::MANAGED_OTLP_ENDPOINT`) | +| `env` | `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS` | `300000` | +| `env` | `OTEL_METRICS_INCLUDE_REPOSITORY` | `true` | + +SCE never writes `ENABLE_ENHANCED_TELEMETRY_BETA`, which is only recognized as an alias in conflict detection. It also never writes `OTEL_EXPORTER_OTLP_HEADERS`, per-signal endpoints, protocols, or headers. + +### Flows + +- **Path resolution:** `setup/claude_telemetry.rs::resolve_claude_settings_path` uses `$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`, and returns `None` when there is no home directory. `managed_claude_settings_path` is `/etc/claude-code/managed-settings.json` on Linux and `/Library/Application Support/ClaudeCode/managed-settings.json` on macOS. +- **Conflict detection:** `config_merge.rs::claude_telemetry_conflict(&Value) -> Option`. It returns `UserHelperPresent` for any non-SCE `otelHeadersHelper`. For `env` key classes (switches + alias, privacy, endpoints ×4, headers ×4, protocols ×4, exporters ×3, debounce), a key that is present with a value other than SCE's expected value is a conflict, and so is any `OTEL_*_EXPORTER=none`. Per-signal keys have no expected value, so their mere presence is a conflict. `None` means that every telemetry key present is exactly SCE's value. +- **Install:** `setup/claude_telemetry.rs::install_claude_telemetry(settings_path, managed_path)` reads both files. A managed read error becomes `None`, but malformed managed JSON makes the merge `Err`, which ends as `SkippedInvalid`. It then calls `merge_claude_telemetry_settings`: + - Managed conflict → `Skipped(ManagedSettingsConflict)`. + - User conflict → `Skipped(reason)`. + - Otherwise it inserts the 10 entries and returns `AlreadyCurrent` or `Installed(bytes)`, using `to_string_pretty` + newline. `serde_json` has no `preserve_order`, so keys are re-sorted. + - Writes go through `setup/atomic_write.rs::write_atomically`: a sibling `.sce-tmp` file, the existing mode kept (`0o600` for a new file), and a rename. Install does no symlink check and no re-read before the rename. +- **Policy gate and reporting:** `setup/command.rs::claude_telemetry_report` resolves `config::resolve_auth_runtime_config(repository_root)`, which gives the **effective** policy for the setup repository, and calls `render_claude_telemetry_section`: + - Not enabled → the fixed `CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE`. No read or write. + - Enabled → install. An `Err` from the install, including a write I/O error, is collapsed to `SkippedInvalid`. + - After a `Configured` install, `RepositoryAuthorizationCheck::for_mode` decides the next step. Interactive runs call `auth_command::repository_telemetry_authorized`. Non-interactive and target-flag runs skip it (`NotChecked`, PR #339). + - `format_claude_telemetry_report` renders fixed lines. +- **Stage trigger:** `SetupCommand::execute` runs the stage only when `dispatch_targets_claude(...)`. It runs after `run_setup_for_targets`, after the `SCE access` section, and after the setup login step. A mandatory login failure returns `Err` before the Claude stage runs. +- **Consent persistence:** `command.rs::prepare_interactive_setup` → `persist_setup_access_preferences` → `setup/access_preferences.rs::persist_global_access_preferences`. This is the first write of the run. It writes only to the global user config and has symlink refusal (`SymlinkManaged`), re-read concurrency refusal (`ConcurrentModification`), and parse validation. `read_global_access_preferences(path) -> GlobalAccessPreferences::{Missing, Valid{auth_mode, telemetry_enabled}, Invalid}` reads the user layer without credential access. The non-interactive path in `prepare_dispatch` never computes `resolve_default_global_config_path` today. +- **Resolver authority:** `config/resolver.rs::resolve_access_policy`. A user-side `telemetry.enabled: false` → `Disabled(UserOptOut)`, and auth mode is most-restrictive-wins, so a global `auth.mode: disabled` → `Disabled(AuthDisabled)`. Both rules apply in **every** repository on the machine, and no repository or explicit layer can lift them. A repository `false` → `RepositoryOptOut` applies only there. `UserOptOut` is also produced by an explicit `--config`/`SCE_CONFIG_FILE` `false`, so the effective reason alone cannot identify a *global* withdrawal. +- **Helper backstop:** `sce auth telemetry-headers` resolves the policy from its working directory and fails closed when telemetry is not `Enabled`. Repository opt-outs are enforced there, not in Claude settings. +- **Logout:** `auth_command::run_logout` deletes credential rows without a policy check. It never touches Claude settings. +- **Reporting note:** `config/render.rs::TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE` is shown whenever telemetry is effectively disabled. + +## Consent and ownership semantics + +### Global withdrawal (the only removal trigger) + +Global withdrawal is a property of the **global user config only**, as read by `read_global_access_preferences` after setup's own write: + +- `Valid { telemetry_enabled: Some(false), .. }`, or +- `Valid { auth_mode: Some(AuthMode::Disabled), .. }`. + +`Missing`, `Invalid`, and `Valid` with absent or `true` keys are **not** withdrawal. A degraded or invalid global config cannot establish what the user wants, so nothing is removed. + +Why this is safe: under the resolver, either value disables SCE telemetry in every repository on the machine. Explicit and repository layers cannot lift it. User-level SCE-owned Claude settings therefore cannot be serving any repository, and removing them cannot break repository A while setup runs in repository B. + +These are **not** global withdrawal and never remove anything: + +- Repository `telemetry.enabled: false`. +- Repository `auth.mode: disabled`. +- An explicit-layer `false` or `disabled`. +- `no_user_consent`, `not_enabled`, `invalid_config`. + +The existing helper and resolver gates keep enforcing them per repository. + +### Ownership (who wrote a Claude setting) + +| Candidate signal | Safety | Used? | +|---|---|---| +| Every `OTEL_*` / `CLAUDE_CODE_*` key | Unsafe: destroys user or third-party telemetry | No | +| Endpoint == `MANAGED_OTLP_ENDPOINT` alone | Ambiguous: the security doc recommends orgs set this endpoint themselves; a user may set it by hand | Only to report a residue, never to remove | +| `otelHeadersHelper == "sce auth telemetry-headers"` | Strong anchor: SCE-specific command string no other tool writes | Required anchor | +| Anchor + `claude_telemetry_conflict(user) == None` | Every telemetry key present is exactly SCE's value, the same condition under which install would leave the file `AlreadyCurrent` | **Removal predicate** | +| Marker file / ownership registry / DB | Tracks provenance, but adds new durable state, drift (user edits the file without the registry noticing), and multi-machine/dotfile-sync problems; still needs value checks to detect user edits | Rejected: exact-value matching with a required anchor answers every case below without new state | + +Classification of user-level settings (pure, no I/O): + +1. **No anchor, endpoint ≠ SCE endpoint (or absent):** `NotInstalled`. Unchanged. This covers custom helpers, other exporters, and unrelated env. +2. **No anchor, `env.OTEL_EXPORTER_OTLP_ENDPOINT == MANAGED_OTLP_ENDPOINT`:** `HelperMissing`. Unchanged and reported, because this could be a partially hand-edited SCE install or a hand-made config. +3. **Different helper value:** `NotInstalled`. Another integration owns telemetry, and install would also have skipped (`UserHelperPresent`). +4. **Anchor + `claude_telemetry_conflict == Some(reason)`:** `Modified(reason)`. The user changed an SCE-written value or added a per-signal key, endpoint, or header next to SCE's config. Everything stays unchanged and reported. Removing the shared switches (`CLAUDE_CODE_ENABLE_TELEMETRY`) would disable the user's own exporter, so partial removal is never attempted. +5. **Anchor + no conflict:** `Removed`. Remove `otelHeadersHelper` and each of the 9 SCE `env` keys present whose value equals SCE's value. Everything else in `env` survives, including telemetry-adjacent keys outside the conflict classes (for example `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_LOG_USER_PROMPTS`, `ENABLE_ENHANCED_TELEMETRY_BETA`). Without `CLAUDE_CODE_ENABLE_TELEMETRY` those keys are inert. Drop the `env` key only when it was a non-empty object before removal and is empty after. + +Residual ambiguity, accepted and documented: a key the user set before SCE's install with exactly SCE's value (for example `OTEL_METRICS_INCLUDE_REPOSITORY=true`) is indistinguishable from SCE's write and is removed. Install had already merged over it identically, so the file reached that state through SCE. + +Managed settings are never written. When the managed-settings file parses and configures telemetry (`otelHeadersHelper` present, or any conflict-class `env` key present), removal of the user-level SCE keys still proceeds, and a fixed note line reports that managed settings also configure telemetry and SCE does not change them. A missing, unreadable, or malformed managed file adds no note and does not block removal. Server-managed settings, MDM plists, `--settings` files, and shell environment are not inspectable. This is the same limit as install. + +## Reconciliation algorithm + +Pure core in `setup/config_merge.rs`: + +```rust +#[derive(Debug, Eq, PartialEq)] +pub(crate) enum ClaudeTelemetryRemovalMerge { + Removed(Vec), + NotInstalled, + Modified(ClaudeTelemetrySkipReason), + HelperMissing, +} + +pub(crate) fn remove_claude_telemetry_settings( + existing_bytes: Option<&[u8]>, + source_path: &str, +) -> Result; + +pub(crate) fn settings_configure_claude_telemetry(settings: &Value) -> bool; +``` + +1. `None` bytes → `NotInstalled`. +2. Parse JSON. A parse failure, a non-object top level, or a non-object `env` → `Err` naming `source_path`, the same wording family as `merge_claude_telemetry_settings`. +3. Classify per the ownership table, reusing `claude_telemetry_conflict`, `claude_telemetry_env_entries`, and the existing constants. +4. On `Removed`, remove the matched keys, drop `env` only if this removal emptied it, and serialize with `to_string_pretty` + `\n`, the install's format. Return the bytes. Re-parsing the result is part of the unit test, not a runtime step: the value is produced by `serde_json`. + +Filesystem shell in `setup/claude_telemetry.rs`: + +```rust +#[derive(Debug, Eq, PartialEq)] +pub(crate) enum ClaudeTelemetryRemovalOutcome { + Removed, + NotInstalled, + PreservedModified(ClaudeTelemetrySkipReason), + PreservedHelperMissing, + PreservedInvalid, + PreservedSymlink, + PreservedReadOnly, + Failed(String), +} + +pub(crate) struct ClaudeTelemetryRemovalReport { + pub(crate) outcome: ClaudeTelemetryRemovalOutcome, + pub(crate) managed_configures_telemetry: bool, +} + +pub(crate) fn remove_claude_telemetry(settings_path: &Path, managed_settings_path: &Path) -> ClaudeTelemetryRemovalReport; +``` + +`remove_claude_telemetry` delegates to a private `remove_claude_telemetry_with(settings_path, managed_settings_path, reread)`, mirroring `persist_global_access_preferences_with`, so the concurrency check can be tested. + +1. Read the settings file. `NotFound` → `NotInstalled`. Other read errors → `Failed(fixed message + path)`. +2. Read and parse the managed file best-effort and compute `managed_configures_telemetry`. It never gates the result. +3. Call `remove_claude_telemetry_settings`. `Err` → `PreservedInvalid`. `NotInstalled` / `Modified` / `HelperMissing` map 1:1 with **no write**, so a no-op never rewrites the file. +4. On `Removed(bytes)`, check in this order: + - `fs::symlink_metadata`: a symlink → `PreservedSymlink`. + - On Unix, no owner write bit (`mode & 0o200 == 0`) → `PreservedReadOnly`. + - `reread(path)` ≠ original bytes → `Failed(concurrent-modification message)`. +5. `write_atomically(path, &bytes)`. An error → `Failed(error text)`. The temp file is removed on rename failure, as today. Success → `Removed`. +6. `format_claude_telemetry_removal_report(&report, claude_selected) -> Option` renders fixed lines. `NotInstalled` renders the existing `Claude telemetry: skipped; SCE telemetry is disabled by config.` line when Claude is selected, and nothing otherwise. Preserved and failed lines include the settings path and an actionable next step. A failed line states that consent is still withdrawn. The managed note is appended when its flag is set. + +There are no traits, no dynamic dispatch, and no new modules. Everything is a static function over existing types. + +## Global versus repository behavior + +| Situation | Effect on user-level Claude settings | Why | +|---|---|---| +| Global `telemetry.enabled: false` | Reconcile (remove SCE-owned only) | Disables SCE telemetry in every repository | +| Global `auth.mode: disabled` | Reconcile | Most-restrictive auth wins machine-wide → telemetry `auth_disabled` everywhere. This is a machine-level prohibition, so cleanup is consistent with it | +| Repository `telemetry.enabled: false` | Unchanged; existing skip line | Other repositories may rely on the settings; the helper fails closed here | +| Repository `auth.mode: disabled` | Unchanged; existing skip line | Repository-local restriction | +| Explicit (`--config` / `SCE_CONFIG_FILE`) `false` / `disabled` | Unchanged; existing skip line | Per-invocation layer, not a machine-wide decision | +| Global config invalid (degraded) | Unchanged; existing skip line | Consent cannot be established | +| Global keys absent (`not_enabled`) | Unchanged; existing skip line | Never consented ≠ withdrew | + +## Triggering and lifecycle + +Trigger contract. A pure decision in `setup/command.rs`: + +```rust +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ClaudeTelemetryAction { Install, Remove, SkipDisabled } + +fn claude_telemetry_action( + global: GlobalAccessPreferences, + effective_enabled: bool, + claude_selected: bool, + interactive: bool, +) -> Option; +``` + +- `Remove` when the global user config records a withdrawal **and** (the run is interactive **or** Claude is selected). Global withdrawal implies effective disabled, so `Install` and `Remove` are mutually exclusive by the resolver. +- `Install` when effective telemetry is enabled and Claude is selected. Unchanged. +- `SkipDisabled` when Claude is selected and neither applies. Unchanged line and no I/O. +- `None` otherwise: no line and no I/O. + +Answers to the lifecycle questions: + +- **`sce setup --reconfigure` withdrawal:** yes. Setup writes the withdrawal to the global config first (existing order), then re-reads it, and the Claude removal runs in the same invocation. It runs even when Claude was installed by a previous run. +- **Claude not selected (interactive):** cleanup still runs. Consent is machine-wide and the SCE-owned keys are inert without it. When nothing SCE-owned exists, no line is printed. +- **Ordinary `sce setup` with consent already withdrawn:** reconciles. The trigger is state-based and idempotent, so a manual edit of the global config is applied by rerunning `sce setup`. No new command is added. +- **Non-interactive / target-flag setup:** reconciles only when Claude is selected (`--claude`, `--all`), the same surface that installs today. It reads the global config path through `resolve_default_global_config_path` + `read_global_access_preferences`, a config-file read only. It never opens `auth.db` or the OS credential store. Hooks-only, context-only, and non-Claude non-interactive runs never touch Claude settings. +- **Placement:** in interactive runs, `Remove` executes and renders **immediately after the `SCE access` section and before the setup login step**, so a mandatory-login failure (`auth.setup_login_required`) cannot skip cleanup. `Install` keeps its current position after login, because its authorization check depends on enrollment done by login. In non-interactive runs the stage position is unchanged. +- **`sce auth logout`:** no change. Logout removes credentials, not consent. After logout the helper fails closed. Coupling the two would make logout rewrite Claude settings that a still-consenting user wants for the next login. +- **Re-enable:** after removal, the settings have no SCE keys and no conflict, so a later run with global `telemetry.enabled: true` and Claude selected installs again through the unchanged install path. Repeated disable runs return `NotInstalled` without writing. +- **No auth dependency:** removal never calls `repository_telemetry_authorized`, `run_login_in`, `managed_telemetry::auth_db_present`, or any token storage. + +## Failure and recovery behavior + +| Condition | Outcome | Write? | Report | +|---|---|---|---| +| Missing settings file / no home directory | `NotInstalled` | No | Existing skip line if Claude selected, else none | +| Malformed JSON / non-object top level or `env` | `PreservedInvalid` | No | Path + "could not be parsed and were left unchanged" | +| Unreadable file (permission error) | `Failed` | No | Path + error + manual remediation | +| Read-only file (no owner write bit) | `PreservedReadOnly` | No | Path + "is read-only; remove the SCE entries manually" | +| Symlink-managed file | `PreservedSymlink` | No | Path + "update its source directly (for example Nix or Home Manager)" | +| Concurrent modification between read and rename | `Failed` | No | Path + "changed while setup was updating it; rerun 'sce setup'" | +| Partial match (anchor missing, SCE endpoint present) | `PreservedHelperMissing` | No | Path + manual remediation | +| User-modified SCE values / custom OTLP exporter or endpoint beside anchor | `PreservedModified(reason)` | No | Path + reason + manual remediation | +| Custom helper / other integration only | `NotInstalled` | No | As missing | +| Managed settings configure telemetry | Removal proceeds | User file only | Extra fixed note line | +| Atomic replace fails (dir unwritable, rename error) | `Failed` | Temp removed | Path + error | + +Ordering and consent: + +- The global consent write happens first, unchanged, and is never rolled back or restored when cleanup fails. +- Cleanup failure is **non-fatal**. Setup completes and exits 0, the same posture as existing Claude conflict skips. The rendered line says cleanup did not happen, names the file and the next step, and states that SCE telemetry stays disabled by config. +- The success line is printed only after `write_atomically` returns `Ok`. + +## Behavioral matrix + +| Global consent (user layer) | Repository / explicit policy | Existing Claude user settings | Mode | Expected behavior | +|---|---|---|---|---| +| `true` | none | none | Claude selected | Install SCE settings (unchanged) | +| `true` | none | SCE-managed | Claude selected | `AlreadyCurrent`, no rewrite (unchanged) | +| `true` | none | custom exporter / endpoint / helper | Claude selected | Preserve; existing conflict skip line (unchanged) | +| `true` | repository `telemetry.enabled: false` | SCE-managed | any | Preserve byte-identical; existing "disabled by config" line if Claude selected | +| `true` | repository `telemetry.enabled: false` | none | Claude selected | Do not install; existing skip line | +| `true` | repository `auth.mode: disabled` | SCE-managed | any | Preserve; existing skip line | +| `true` | explicit `telemetry.enabled: false` | SCE-managed | any | Preserve; existing skip line | +| `false` | any | SCE-managed (exact) | interactive, or Claude selected | Remove SCE keys; keep unrelated keys; report removed | +| `false` | any | SCE-managed + unrelated `env` | interactive, or Claude selected | Remove only the 10 SCE entries; `env` keeps the unrelated keys | +| `false` | any | custom exporter (no SCE helper) | interactive, or Claude selected | `NotInstalled`; preserve | +| `false` | any | SCE helper + user-changed endpoint / added per-signal key | interactive, or Claude selected | `PreservedModified`; preserve all; report | +| `false` | any | SCE endpoint without SCE helper | interactive, or Claude selected | `PreservedHelperMissing`; preserve; report | +| `false` | any | none | any | No-op; no write | +| `false` | any | SCE-managed | non-interactive, Claude not selected | Untouched (not this run's surface) | +| `auth.mode: disabled` | any | SCE-managed | interactive, or Claude selected | Remove (global prohibition) | +| absent | any | SCE-managed (installed through an explicit-file consent) | any | Preserve; existing skip line (never consented ≠ withdrew) | +| invalid global config | any | SCE-managed | any | Preserve; existing skip line | +| `true` again after removal | none | previously cleaned | Claude selected | Reinstall via unchanged install path | +| `false` (second run) | any | previously cleaned | interactive, or Claude selected | `NotInstalled`; no write | + +## Acceptance criteria + +- [x] AC1: With global `telemetry.enabled: false` or global `auth.mode: disabled`, removal deletes exactly `otelHeadersHelper` and the 9 SCE `env` entries from SCE-owned settings. Unrelated top-level keys, hooks, permissions, and non-SCE `env` keys survive, and `env` is dropped only when the removal emptied it. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_removal` (table-driven ownership tests in `config_merge.rs`; confirm a non-zero match count with `-- --list`). +- [x] AC2: Settings that are not attributable to SCE stay byte-identical and are reported with a fixed line naming the file: custom helper, other exporter, user-modified SCE values, per-signal additions, SCE endpoint without helper, malformed JSON, symlink, read-only file, and managed settings. + - Validate: same filter; the shell tests assert file bytes before and after, and `fs::read_link` stays unchanged for the symlink case. +- [x] AC3: A repository-level or explicit-layer opt-out (`telemetry.enabled: false` or `auth.mode: disabled`) never modifies user-level Claude settings, while global consent stays `true`. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_claude_telemetry` (repository A/B and explicit-layer cases assert byte-identical settings). +- [x] AC4: Interactive `sce setup` / `--reconfigure` that records a global withdrawal removes SCE-owned Claude settings in the same run, whether or not Claude is selected and even if a mandatory login fails afterwards. A non-interactive run reconciles only when Claude is selected. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_action` plus the `setup_claude_telemetry` integration-style tests in `setup/command.rs`. +- [x] AC5: Enable → disable → enable → disable cycles are idempotent. A second disable performs no write, and re-enabling reinstalls the same bytes as a first install. + - Validate: lifecycle test in `setup/command.rs` comparing file bytes and mtime-independent content across the cycle. +- [x] AC6: Removal never touches `auth.db`, the OS credential store, the repository-authorization lookup, or login, in either interactive or non-interactive mode. + - Validate: tests pass an authorization closure that panics if called; inspection confirms that `remove_claude_telemetry` and the removal branch call no `auth_command` / `token_storage` / `auth_db_present` function. +- [x] AC7: A cleanup failure (concurrent modification, unwritable directory) is reported as not done, with the path and a remediation. Setup exits 0, and the withdrawn global consent remains saved. + - Validate: shell tests with an injected re-read and a `0o555` directory assert the `Failed` line and an unchanged global config. +- [x] AC8: `sce config show` `telemetry.note` describes the new reconciliation behavior in place of the old "not changed" wording. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. +- [x] AC9: The existing install, conflict-detection, and PR #339 non-interactive tests pass unmodified, apart from tests whose asserted output order intentionally changes. + - Validate: `nix flake check`. + +### Full validation + +- `nix flake check` + +### Context sync + +- `context/sce/telemetry-credential.md`, section "Claude-native telemetry": the removal trigger, ownership predicate, preserved cases, and failure lines; remove "Settings written by earlier setups are not removed." +- `context/cli/access-policy.md`: the Enforcement bullet for `sce setup` Claude telemetry install, the Reporting `telemetry.note` text, and the coverage-limit sentence. +- `context/sce/setup-repo-local-config-bootstrap.md`: the Setup login / Claude telemetry stage ordering (removal before login in interactive runs). +- `context/context-map.md`: the annotations for `telemetry-credential.md` and `access-policy.md`, if they mention the limitation. +- `context/glossary.md`: add "global telemetry withdrawal" only if the term is used across files. + +## Task context synchronization lifecycle + +- **Task context synchronization:** every task carries `pending | synced | blocked`. A completed task must be `synced` before another task can start or the plan can finish. +- For `blocked`, record **Blocker**, **Required action**, and **Retry condition** beside the status. Never infer `synced` from conversation history; write every lifecycle transition to the plan file. + +## Constraints and non-goals + +- **In scope:** `cli/src/services/setup/config_merge.rs`, `cli/src/services/setup/claude_telemetry.rs`, `cli/src/services/setup/command.rs`, `cli/src/services/config/render.rs` (note text only), and the context files listed under Context sync. +- **Out of scope:** + - Auth DB schema, credential migration, Keychain / Secret Service, WorkOS, `sce auth logout`. + - Resolver precedence (`resolve_access_policy`). + - Telemetry readiness markers, repository enrollment, optional login recovery. + - Other agent integrations (OpenCode, Codex, Pi). + - Agent Trace auto-sync. + - Claude managed / server-managed settings writes. + - `sce doctor` reporting of stale Claude settings. + - A general settings-management framework. +- **Constraints:** + - Static functions and existing enums only. + - Reuse `claude_telemetry_conflict`, `claude_telemetry_env_entries`, `write_atomically`, and `read_global_access_preferences`. + - Fixed, deterministic output strings held in constants. + - No comments in code (repository-owner preference). + - Non-interactive runs must never open `auth.db` or the credential store (PR #339). +- **Non-goal:** + - An ownership registry, marker file, or install-time snapshot. + - Partial removal from settings that the user modified. + - Hardening the existing install path (symlink check, distinct write-failure line); see Open questions. + +## Assumptions + +- "Global consent" means the global user config layer only (`GlobalAccessPreferences`), per [ADR: setup writes access answers to user layer only](../decisions/2026-10-21-setup-writes-access-answers-to-user-layer-only.md). The explicit layer is per-invocation and is not machine-wide. +- A global `auth.mode: disabled` counts as withdrawal. The resolver already makes it disable telemetry in every repository, so cleanup cannot affect any repository that still needs the settings. +- Cleanup failure is non-fatal (exit 0, explicit failure line). This matches existing Claude conflict skips and the "assets not rolled back" posture of mandatory-login failure. +- Re-serialization with sorted keys on removal is acceptable because install already rewrites the same file that way. +- Removal output position (before login, interactive only) may change the relative order of the Claude line in tests that assert the full interactive output. Install ordering is unchanged. + +## Task stack + +- [x] T01: `Add pure SCE-owned Claude telemetry removal` (status:done) + - Task ID: T01 + - Scope: + - In: `setup/config_merge.rs`: + - Add `ClaudeTelemetryRemovalMerge`, `remove_claude_telemetry_settings(existing_bytes, source_path)`, and `settings_configure_claude_telemetry(&Value)`, implementing the ownership classification (anchor `otelHeadersHelper`, `claude_telemetry_conflict == None`, exact-value removal of the 10 entries, `env` drop only when emptied, `to_string_pretty` + newline). + - Add one table-driven test `claude_telemetry_removal_classifies_ownership`. Cases: exact SCE install; SCE + unrelated env/hooks/permissions; partial SCE set (subset of the 9 keys + helper); user-modified endpoint; added per-signal endpoint; added `OTEL_EXPORTER_OTLP_HEADERS`; custom helper; other exporter without helper; SCE endpoint without helper; `env` emptied vs `env` with leftovers; `None` bytes. + - Add `claude_telemetry_removal_rejects_malformed_json_naming_the_path`. + - Add `claude_telemetry_removal_then_install_round_trips` (install(remove(install(x))) == install(x), and remove(remove(x)) is `NotInstalled`). + - Out: filesystem I/O, reporting, triggers. + - Dependencies: none + - Done when: + - The pure function returns the documented variant for every case. + - Removed output re-parses and contains no SCE key, while preserving every non-SCE key. + - The existing `telemetry_merge_*` tests are unchanged and pass. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_removal -- --list` (non-zero), then without `--list`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_merge`. + - Completed: 2026-10-21 + - Files changed: `cli/src/services/setup/config_merge.rs` + - Result: Added `ClaudeTelemetryRemovalMerge`, `remove_claude_telemetry_settings`, and `settings_configure_claude_telemetry`, implementing the ownership classification. A different helper or no anchor → `NotInstalled`. No anchor with the SCE endpoint → `HelperMissing`. Anchor with a conflict → `Modified(reason)`. Anchor without a conflict → `Removed`, which drops the helper and the exact-value SCE `env` entries, and drops `env` only when this removal emptied it. Malformed JSON, a non-object top level, or a non-object `env` → `Err` naming the path. Added the three planned tests, with the preserved-case table extracted into the `preserved_removal_cases` helper to satisfy `clippy::too_many_lines`. `remove_claude_telemetry_settings` and `settings_configure_claude_telemetry` carry `#[cfg_attr(not(test), expect(dead_code))]` until T02 wires them in; T02 must remove those attributes. + - Verify outcomes: `claude_telemetry_removal -- --list` → 3 tests (passed); `claude_telemetry_removal` → 3 passed, 0 failed (passed); `telemetry_merge` → 9 passed, 0 failed, existing tests unchanged (passed). Extra: `run-cli-cargo.sh clippy --all-targets` clean (passed). + - Context impact: none. This adds internal pure helpers with no callers, and there is no user-visible behavior change until T02/T03. + - Context synchronization: synced + +- [x] T02: `Add guarded filesystem removal and fixed report lines` (status:done) + - Task ID: T02 + - Scope: + - In: `setup/claude_telemetry.rs`: + - Add `ClaudeTelemetryRemovalOutcome`, `ClaudeTelemetryRemovalReport`, `remove_claude_telemetry(settings_path, managed_settings_path)`, and private `remove_claude_telemetry_with(.., reread)`. The order is read → managed note (best-effort) → pure removal → symlink check (`fs::symlink_metadata`) → owner-write-bit check (Unix) → re-read concurrency check → `write_atomically`. + - Add fixed `const` report lines and `format_claude_telemetry_removal_report(&report, claude_selected) -> Option`. + - Add table-driven test `claude_telemetry_removal_filesystem_outcomes`. Cases: missing file; exact SCE file (mode `0o640` preserved); invalid JSON byte-identical; symlink with link + target unchanged; `0o444` file unchanged; injected concurrent re-read → `Failed` and file unchanged; `0o555` parent dir → `Failed`; no-op `NotInstalled`/`PreservedModified` leaves bytes **and** inode/mtime untouched; managed file configuring telemetry → note flag, user file still cleaned. + - Add one report-rendering test covering each variant and the `claude_selected` false/true `NotInstalled` lines. + - Out: setup wiring, install path changes. + - Dependencies: T01 + - Done when: + - Every failure-table row maps to the documented outcome and line, with no write in any non-`Removed` outcome. + - The success line appears only after `write_atomically` returns `Ok`. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_removal`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_install`. + - Completed: 2026-10-21 + - Files changed: `cli/src/services/setup/claude_telemetry.rs`, `cli/src/services/setup/config_merge.rs`, `cli/src/services/setup/command.rs` + - Result: Added `ClaudeTelemetryRemovalOutcome`, `ClaudeTelemetryRemovalReport`, `remove_claude_telemetry`, and private `remove_claude_telemetry_with(.., reread)`. The steps run in the planned order: read → best-effort managed note via `settings_configure_claude_telemetry` → pure removal → `symlink_metadata` symlink check → owner-write-bit check (Unix; `readonly()` elsewhere) → injected re-read comparison → `write_atomically`. Outcomes other than `Removed` never write. Added fixed text constants and `format_claude_telemetry_removal_report(&report, claude_selected)`. `NotInstalled` renders the existing disabled-by-config line only when Claude is selected. Preserved lines name the path, give a remediation, and say SCE telemetry stays disabled by config. The `Failed` line names the path and detail and says consent remains withdrawn. The managed note is appended as a second line. Deviations: `ClaudeTelemetryRemovalReport` carries `settings_path` so the report lines can name the file. `CLAUDE_TELEMETRY_DISABLED_BY_CONFIG_LINE` moved from `command.rs` to `claude_telemetry.rs` as `pub(crate)` and is imported back, with the same text. The `0o555` parent-directory case is its own test, `claude_telemetry_removal_reports_failed_replace_in_unwritable_directory`, because it needs permissions restored before cleanup. T01's `expect(dead_code)` attributes were removed from `config_merge.rs`. `remove_claude_telemetry` and `format_claude_telemetry_removal_report` now carry `#[cfg_attr(not(test), expect(dead_code))]` until T03 wires them in, and T03 must remove them. + - Verify outcomes: `claude_telemetry_removal` → 6 passed, 0 failed (3 from T01 + `claude_telemetry_removal_filesystem_outcomes`, `claude_telemetry_removal_reports_failed_replace_in_unwritable_directory`, `claude_telemetry_removal_report_renders_fixed_lines`) (passed); `claude_telemetry_install` → 8 passed, 0 failed (passed). Extra: `run-cli-cargo.sh clippy --all-targets -- -D warnings` clean; `claude_telemetry` filter → 19 passed (passed). + - Context impact: none. These are internal filesystem helpers with no production callers yet, so user-visible behavior is unchanged until T03 wires the removal into setup. + - Context synchronization: synced + +- [x] T03: `Trigger Claude telemetry removal on global consent withdrawal in setup` (status:done) + - Task ID: T03 + - Scope: + - In: `setup/command.rs`: + - Add `ClaudeTelemetryAction` and `claude_telemetry_action(global, effective_enabled, claude_selected, interactive)`, plus a `global_consent_withdrawn(GlobalAccessPreferences) -> bool` predicate (`telemetry_enabled: Some(false)` or `auth_mode: Some(AuthMode::Disabled)` in `Valid`). + - Interactive path: after `persist_setup_access_preferences`, re-read the global config with `read_global_access_preferences(&access_save.global_config_path)`. On `Remove`, run `remove_claude_telemetry` and push its section right after the `SCE access` section, before `run_setup_login_step`. + - Non-interactive path: compute `resolve_default_global_config_path` + `read_global_access_preferences` only when Claude is selected. A path or read error counts as not withdrawn. + - `Install` and `SkipDisabled` keep `render_claude_telemetry_section` and its position unchanged. + - Tests: + - Table test `claude_telemetry_action_follows_global_withdrawal_only`. Rows: global false / disabled / true / absent / invalid × repository opt-out × Claude selected × interactive. + - Lifecycle test `setup_claude_telemetry_consent_cycle_is_idempotent` (enable → disable → disable → enable → disable over one temp settings file). + - `setup_claude_telemetry_repository_opt_out_preserves_user_settings` (repository A/B and explicit-layer `false` with global `true`; bytes unchanged). + - `setup_claude_telemetry_removal_never_checks_authorization` (panicking authorization closure; interactive and non-interactive). + - Out: changes to `prepare_interactive_setup` consent writing, the login step, the install path, and `RepositoryAuthorizationCheck`. + - Dependencies: T02 + - Done when: + - Withdrawal recorded in this run or earlier removes SCE-owned settings in interactive runs regardless of target, and in non-interactive runs only with Claude selected. + - Repository and explicit opt-outs leave settings byte-identical. + - Removal happens before a possible mandatory-login failure. + - The existing `setup_claude_telemetry_*` and PR #339 tests pass. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_telemetry_action`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_claude_telemetry`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml setup_repository_authorization_is_checked_only_for_interactive_setup -- --exact`. Expected: nonzero test counts and all passing. + - Completed: 2026-10-21 + - Files changed: `cli/src/services/setup/command.rs`, `cli/src/services/setup/claude_telemetry.rs` + - Result: Added `ClaudeTelemetryAction { Install, Remove, SkipDisabled }`, `global_consent_withdrawn`, and `claude_telemetry_action(global, effective_enabled, claude_selected, interactive)`. `Remove` applies when the global user config is `Valid` with `telemetry_enabled: Some(false)` or `auth_mode: Some(Disabled)` and the run is interactive or Claude is selected. Otherwise the action is `Install`/`SkipDisabled` when Claude is selected, else `None`. In interactive runs, `execute` re-reads the global config through `read_global_preferences(&access_save.global_config_path)` (a read error maps to `Invalid`) and uses the access-section policy for `effective_enabled`. `split_pre_login_removal` renders a `Remove` immediately after `SCE access` and before `run_setup_login_step`. `Install`/`SkipDisabled` keep their position after login. In non-interactive runs, `non_interactive_claude_telemetry_action` reads the global config only when Claude is selected, and a path or read error maps to `Invalid`. The stage keeps its existing position. The new `render_claude_telemetry_action` routes `Remove` to `remove_claude_telemetry` + `format_claude_telemetry_removal_report` (with no settings path, `NotInstalled` semantics apply) and routes `Install`/`SkipDisabled` to the unchanged `render_claude_telemetry_section`. `claude_telemetry_report` now takes `Option` and `claude_selected`, and the effective-policy computation moved to `effective_telemetry_enabled`. T02's `expect(dead_code)` attributes were removed from `claude_telemetry.rs`. Added the 4 planned tests. Deviation: to stay under `clippy::too_many_lines`, `execute` uses an async closure for the Claude report call plus the two small helpers above. The pre-login placement is verified by inspecting the `execute` order, because `execute` runs a real login and has no unit-test seam. + - Verify outcomes: `claude_telemetry_action` → 1 passed, 0 failed (passed); `setup_claude_telemetry` → 8 passed, 0 failed (4 existing + 4 new) (passed); `services::setup::command::tests::setup_repository_authorization_is_checked_only_for_interactive_setup -- --exact` → 1 passed (passed; the bare name matches 0 tests under `--exact`, so the full path was used). Extra: `claude_telemetry_removal` → 7 passed; `claude_telemetry_install` → 8 passed; `setup` → 119 passed; `run-cli-cargo.sh clippy --all-targets -- -D warnings` clean (all passed). + - Context impact: important. This is a user-visible behavior change: `sce setup` now removes SCE-owned Claude settings on global withdrawal, and in interactive runs that output appears before `SCE login`. Affected context: `context/sce/telemetry-credential.md` (Claude-native telemetry), `context/cli/access-policy.md` (Enforcement/coverage limit), `context/sce/setup-repo-local-config-bootstrap.md` (stage ordering). + - Context synchronization: synced + +- [x] T04: `Update config show telemetry note for Claude settings reconciliation` (status:done) + - Task ID: T04 + - Scope: + - In: `config/render.rs`: + - Change `TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE` to a fixed string stating that `sce setup` removes SCE-managed Claude Code telemetry settings when the global SCE config sets `telemetry.enabled: false` or `auth.mode: disabled`, and that repository-level opt-outs leave them in place. For example: `Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` + - Existing tests already reference the constant. + - Out: show/validate structure, JSON field names, and when the note is shown. + - Dependencies: T03 + - Done when: text and JSON `telemetry.note` render the new constant, and the render tests pass. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml config::render`. + - Completed: 2026-10-21 + - Files changed: `cli/src/services/config/render.rs` + - Result: `TELEMETRY_DISABLED_CLAUDE_SETTINGS_NOTE` now reads `Claude Code telemetry settings written by sce setup are removed by the next sce setup run after the global SCE config sets telemetry.enabled to false or auth.mode to disabled; repository-level opt-outs leave them in place.` (the plan's example wording verbatim). The text and JSON `telemetry.note` render through the existing constant references. Show/validate structure, JSON field names, and when the note is shown are unchanged. No test edits were needed. + - Verify outcomes: `config::render` → 3 passed, 0 failed (passed). + - Context impact: important. The user-visible `sce config show` `telemetry.note` text changed. `context/cli/access-policy.md` quotes the old note text in its Reporting section. + - Context synchronization: synced + +## Compatibility concerns + +- **Output order:** in interactive runs that remove settings, the Claude line now appears before the `SCE login` section. Install-path output and order are unchanged. +- **Formatting:** a removal rewrite re-sorts keys and pretty-prints the file, the same effect install already has on this file. +- **Claude Code versions:** removing keys is version-neutral. Claude falls back to its defaults (telemetry off). +- **Older SCE binaries:** an older `sce setup` with telemetry enabled may reinstall the settings. That is expected, because it reflects consent at that point. +- **Shared dotfiles:** when `~/.claude/settings.json` is synced across machines, removal on one machine propagates. The symlink refusal covers the Home Manager/Nix case. Plain-file syncing is the user's choice. + +## Open questions + +- Should non-interactive `sce setup --claude` / `--all` also remove settings on global withdrawal? This plan says yes, because it is the same surface that installs and needs no auth storage. The narrower alternative is to reconcile only in interactive runs, which leaves non-interactive runs printing the existing skip line over stale settings. +- Should cleanup failure be fatal (non-zero exit) instead of a reported warning? The plan keeps it non-fatal for consistency with conflict skips. A fatal exit would also suppress the remaining sections, because errors return early. +- The existing install path replaces a symlinked `settings.json` through `write_atomically` without the symlink check, and reports write I/O errors as "could not be parsed" because of `unwrap_or(SkippedInvalid)`. Both are pre-existing install defects outside this plan's scope. Fix them in a separate PR, or fold them into T02, since they reuse the same guard? + +## Validation Report + +**Status:** validated +**Date:** 2026-10-21 + +### Commands run + +- `nix flake check` (run 1, concurrent with targeted cargo runs) -> exit 1 (759 passed, 1 failed: `services::auth_db::multiprocess_tests::claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential`, "seed child did not exit within 60s") +- `run-cli-cargo.sh test ... claude_hook_with_telemetry_disabled_by_config_never_resolves_the_credential` -> exit 0 (1 passed in 0.13s) +- `nix flake check` (run 2, isolated) -> exit 1 (758 passed, 2 failed: `app::tests::stalled_telemetry_headers_lookup_fails_closed_within_deadline`, `services::auth_db::multiprocess_tests::concurrent_current_version_writers_persist_every_row`) +- `nix flake check` (run 3, isolated) -> exit 0 (all checks passed) +- `run-cli-cargo.sh test ... claude_telemetry_removal` -> exit 0 (7 passed) +- `run-cli-cargo.sh test ... setup_claude_telemetry` -> exit 0 (8 passed) +- `run-cli-cargo.sh test ... claude_telemetry_action` -> exit 0 (1 passed) +- `run-cli-cargo.sh test ... config::render` -> exit 0 (3 passed) + +### Success-criteria verification + +- [x] AC1: exact removal of the 10 SCE entries, unrelated keys kept, `env` dropped only when emptied -> `claude_telemetry_removal_classifies_ownership` and `claude_telemetry_removal_then_install_round_trips` passed +- [x] AC2: non-attributable settings stay byte-identical and are reported -> `claude_telemetry_removal_filesystem_outcomes` (invalid JSON, symlink, read-only, modified, helper-missing, managed note) and `claude_telemetry_removal_report_renders_fixed_lines` passed +- [x] AC3: repository and explicit-layer opt-outs never modify user Claude settings -> `setup_claude_telemetry_repository_opt_out_preserves_user_settings` passed +- [x] AC4: interactive withdrawal removes regardless of target and before login; non-interactive only with Claude selected -> `claude_telemetry_action_follows_global_withdrawal_only` passed; pre-login placement confirmed by T03 inspection of `execute` order (no unit seam) +- [x] AC5: enable/disable cycles are idempotent -> `setup_claude_telemetry_consent_cycle_is_idempotent` passed +- [x] AC6: removal never touches auth storage, authorization, or login -> `setup_claude_telemetry_removal_never_checks_authorization` (panicking closure) passed; inspection: no `auth_command`/`token_storage`/`auth_db_present`/`repository_telemetry_authorized`/`run_login` reference in `claude_telemetry.rs` or `config_merge.rs`, and the `Remove` arm of `render_claude_telemetry_action` calls only `remove_claude_telemetry` + `format_claude_telemetry_removal_report` +- [x] AC7: cleanup failure is reported as not done, non-fatal, consent kept -> `claude_telemetry_removal_reports_failed_replace_in_unwritable_directory` and the injected-reread case in `claude_telemetry_removal_filesystem_outcomes` passed +- [x] AC8: `config show` `telemetry.note` describes reconciliation -> `config::render` 3 passed against the updated constant +- [x] AC9: existing install, conflict, and PR #339 tests pass -> `nix flake check` run 3 exit 0 + +### Failed checks and follow-ups + +- None. + +### Residual risks + +- `nix flake check` failed in 2 of 3 runs on timing-sensitive multiprocess/deadline tests in `cli/src/app.rs` and `cli/src/services/auth_db/multiprocess_tests.rs`. This plan does not touch those files, and the failing tests changed between runs. They are flaky under load and may fail CI intermittently. diff --git a/context/sce/setup-repo-local-config-bootstrap.md b/context/sce/setup-repo-local-config-bootstrap.md index b931fa7f2..5baab6eb3 100644 --- a/context/sce/setup-repo-local-config-bootstrap.md +++ b/context/sce/setup-repo-local-config-bootstrap.md @@ -67,7 +67,7 @@ Setup saves `auth.mode` and `telemetry.enabled` only to the global user config, ## Setup login -Interactive setup runs login after the `SCE access` section and before the Claude telemetry stage. It never runs for non-interactive, hooks-only, or context-only setup. The action is decided by `setup_login_action` (`cli/src/services/setup/command.rs`) from the same re-resolved effective policy the `SCE access` section reports, plus the dispatch's `SetupLoginIntent`, not from the prompt answer alone: +Interactive setup runs login after the `SCE access` section and before the Claude telemetry install stage. When the global user config records a telemetry withdrawal, the [Claude telemetry removal](telemetry-credential.md#claude-native-telemetry) runs and reports between the `SCE access` section and login, whatever the target, so a failed mandatory login cannot skip it. Login never runs for non-interactive, hooks-only, or context-only setup. The login action is decided by `setup_login_action` (`cli/src/services/setup/command.rs`) from the same re-resolved effective policy the `SCE access` section reports, plus the dispatch's `SetupLoginIntent`, not from the prompt answer alone: | Effective `auth.mode` | Login intent | Action | |---|---|---| diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 6ee4860a7..b0b039896 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -90,7 +90,8 @@ flowchart LR Claude Code's own OpenTelemetry export is separate from the SCE-CLI managed exporter above. `sce setup` configures it; the SCE CLI exporter is unchanged. - Install: when the Claude target is selected and setup proceeds (`--claude`, `--all`, interactive Claude/All, with or without `--non-interactive`), `cli/src/services/setup/claude_telemetry.rs` merges settings into Claude's user-level `settings.json` (`$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`). OpenCode/Codex/Pi-only, `--hooks`-only, `--bootstrap-context`, and cancelled runs leave it untouched. Scope is user-level, not repository-level. -- Policy gate: setup installs only when the effective access policy resolved for the setup repository root enables telemetry ([access-policy.md](../cli/access-policy.md)); a resolution failure counts as not enabled. Otherwise it prints the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and neither reads nor writes Claude settings. Settings written by earlier setups are not removed. +- Policy gate: setup installs only when the effective access policy resolved for the setup repository root enables telemetry ([access-policy.md](../cli/access-policy.md)); a resolution failure counts as not enabled. Otherwise it prints the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and does not install. Settings written by earlier setups are removed only on global withdrawal (next bullet). +- Removal on global withdrawal: when the global user config (not the repository or explicit layer) sets `telemetry.enabled: false` or `auth.mode: disabled`, setup removes the SCE-owned entries from user-level Claude settings. Interactive runs always reconcile, whatever the target, right after the `SCE access` section and before the setup login step, so a failed mandatory login cannot skip it. Non-interactive runs reconcile only with the Claude target selected (`--claude`, `--all`), and the only extra read is the global config file. Ownership is exact-value matching anchored on `otelHeadersHelper == "sce auth telemetry-headers"`: entries are removed only when every telemetry key present equals SCE's written value. Then the helper and the matching `env` entries are removed, and `env` is dropped only when this removal emptied it. A modified SCE value or an added endpoint, header, or per-signal key beside the anchor, the SCE endpoint without the helper, malformed JSON, a symlink, or a read-only file leaves the file byte-identical, with a fixed line naming the path and a manual remediation. Files with no SCE entries are never rewritten. Managed settings are never written; when they also configure telemetry, a note line says so. Cleanup failure (for example, concurrent modification or an unwritable directory) is reported but does not fail setup, and the saved withdrawal is kept. Removal never runs the repository-authorization check or login and never opens `auth.db` or the credential store. Repository and explicit opt-outs leave Claude settings unchanged, because the helper already fails closed there ([ADR](../decisions/2026-10-21-claude-telemetry-removal-on-global-withdrawal.md)). - Written keys: `otelHeadersHelper` set to `sce auth telemetry-headers`, plus an `env` block with `CLAUDE_CODE_ENABLE_TELEMETRY=1`, `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1` (required by Claude Code for span tracing), `OTEL_{TRACES,METRICS,LOGS}_EXPORTER=otlp`, `OTEL_EXPORTER_OTLP_PROTOCOL` / `OTEL_EXPORTER_OTLP_ENDPOINT` from `MANAGED_OTLP_PROTOCOL` / `MANAGED_OTLP_ENDPOINT`, `CLAUDE_CODE_OTEL_HEADERS_HELPER_DEBOUNCE_MS=300000`, and `OTEL_METRICS_INCLUDE_REPOSITORY=true` (unconditional because the Claude Code version cannot be detected during setup; unknown variables are ignored). - Authentication: no token is ever written to settings, generated assets, or setup output, and `OTEL_EXPORTER_OTLP_HEADERS` is never set. Claude runs the hidden helper (see Hidden header helper) and uses its `Authorization` header. - Rotation: Claude re-runs the helper at most every five minutes (debounce 300000 ms), so a credential replaced by a later `sce auth login` is picked up without rewriting settings. `sce auth logout` deletes the stored credential, after which the helper fails and Claude export stops authenticating; local deletion does not revoke the OpenBao token.