-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtcc.rs
More file actions
1212 lines (1074 loc) · 42 KB
/
tcc.rs
File metadata and controls
1212 lines (1074 loc) · 42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use chrono::{Local, TimeZone};
use rusqlite::{Connection, OpenFlags};
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::LazyLock;
/// Mapping of internal TCC service keys (e.g. `kTCCServiceCamera`) to human-readable names.
pub static SERVICE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
let mut m = HashMap::new();
m.insert("kTCCServiceAccessibility", "Accessibility");
m.insert("kTCCServiceScreenCapture", "Screen Recording");
m.insert("kTCCServiceSystemPolicyAllFiles", "Full Disk Access");
m.insert(
"kTCCServiceSystemPolicySysAdminFiles",
"Administer Computer (SysAdmin)",
);
m.insert("kTCCServiceSystemPolicyDesktopFolder", "Desktop Folder");
m.insert("kTCCServiceSystemPolicyDocumentsFolder", "Documents Folder");
m.insert("kTCCServiceSystemPolicyDownloadsFolder", "Downloads Folder");
m.insert("kTCCServiceSystemPolicyNetworkVolumes", "Network Volumes");
m.insert(
"kTCCServiceSystemPolicyRemovableVolumes",
"Removable Volumes",
);
m.insert("kTCCServiceSystemPolicyDeveloperFiles", "Developer Files");
m.insert("kTCCServiceCamera", "Camera");
m.insert("kTCCServiceMicrophone", "Microphone");
m.insert("kTCCServicePhotos", "Photos");
m.insert("kTCCServicePhotosAdd", "Photos (Add Only)");
m.insert("kTCCServiceCalendar", "Calendar");
m.insert("kTCCServiceContacts", "Contacts");
m.insert("kTCCServiceReminders", "Reminders");
m.insert("kTCCServiceLocation", "Location");
m.insert("kTCCServiceAddressBook", "Address Book");
m.insert("kTCCServiceMediaLibrary", "Media Library");
m.insert("kTCCServiceAppleEvents", "Apple Events / Automation");
m.insert("kTCCServiceListenEvent", "Input Monitoring");
m.insert("kTCCServicePostEvent", "Post Events");
m.insert("kTCCServiceSpeechRecognition", "Speech Recognition");
m.insert("kTCCServiceBluetoothAlways", "Bluetooth");
m.insert("kTCCServiceDeveloperTool", "Developer Tool");
m.insert("kTCCServiceEndpointSecurityClient", "Endpoint Security");
m.insert("kTCCServiceFileProviderDomain", "File Provider");
m.insert("kTCCServiceFileProviderPresence", "File Provider Presence");
m.insert("kTCCServiceFocusStatus", "Focus Status");
m.insert("kTCCServiceLiverpool", "User Data (Liverpool)");
m
});
/// Known schema digest hashes for the TCC access table, grouped by macOS version range.
/// Derived from tccutil.py's digest_check function.
const KNOWN_DIGESTS: &[&str] = &[
"8e93d38f7c", // prior to El Capitan
"9b2ea61b30", // El Capitan, Sierra, High Sierra
"1072dc0e4b", // El Capitan, Sierra, High Sierra (alt)
"ecc443615f", // Mojave, Catalina
"80a4bb6912", // Mojave, Catalina (alt)
"3d1c2a0e97", // Big Sur+
"cef70648de", // Big Sur+ (alt)
"34abf99d20", // Sonoma
"e3a2181c14", // Sonoma (alt)
"f773496775", // Sonoma (alt)
];
/// Errors returned by TCC database operations.
#[derive(Debug)]
pub enum TccError {
DbOpen { path: PathBuf, source: String },
NotFound { service: String, client: String },
NeedsRoot { message: String },
UnknownService(String),
AmbiguousService { input: String, matches: Vec<String> },
QueryFailed(String),
SchemaInvalid(String),
HomeDirNotFound,
WriteFailed(String),
}
impl fmt::Display for TccError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TccError::DbOpen { path, source } => {
write!(f, "Failed to open {}: {}", path.display(), source)
}
TccError::NotFound { service, client } => {
write!(
f,
"No entry found for service '{}' and client '{}'",
service, client
)
}
TccError::NeedsRoot { message } => write!(f, "{}", message),
TccError::UnknownService(s) => write!(
f,
"Unknown service '{}'. Run `tcc services` to see available services.",
s
),
TccError::AmbiguousService { input, matches } => write!(
f,
"Ambiguous service '{}'. Matches: {}",
input,
matches.join(", ")
),
TccError::QueryFailed(s) => write!(f, "{}", s),
TccError::SchemaInvalid(s) => write!(f, "{}", s),
TccError::HomeDirNotFound => write!(f, "Cannot determine home directory"),
TccError::WriteFailed(s) => write!(f, "{}", s),
}
}
}
/// A single row from the TCC `access` table, enriched with a human-readable service name.
#[derive(Debug, Serialize)]
pub struct TccEntry {
pub service_raw: String,
pub service_display: String,
pub client: String,
pub auth_value: i32,
pub last_modified: String,
pub is_system: bool,
}
/// Which TCC database(s) to target for reads and writes.
#[derive(Clone, Copy, PartialEq)]
pub enum DbTarget {
/// Use both DBs for reads, system for writes (default)
Default,
/// User DB only
User,
}
/// Handle for reading and writing macOS TCC.db databases.
pub struct TccDb {
user_db_path: PathBuf,
system_db_path: PathBuf,
target: DbTarget,
}
impl TccDb {
/// Open the user and system TCC databases for the given target mode.
pub fn new(target: DbTarget) -> Result<Self, TccError> {
let home = dirs::home_dir().ok_or(TccError::HomeDirNotFound)?;
Ok(Self {
user_db_path: home.join("Library/Application Support/com.apple.TCC/TCC.db"),
system_db_path: PathBuf::from("/Library/Application Support/com.apple.TCC/TCC.db"),
target,
})
}
#[cfg(test)]
pub fn with_paths(user: PathBuf, system: PathBuf, target: DbTarget) -> Self {
Self {
user_db_path: user,
system_db_path: system,
target,
}
}
pub(crate) fn format_timestamp(ts: i64) -> String {
if ts == 0 {
return "N/A".to_string();
}
// macOS TCC uses CoreData timestamps (seconds since 2001-01-01) or Unix timestamps.
let unix_ts = if ts < 1_000_000_000 {
ts + 978_307_200
} else {
ts
};
match Local.timestamp_opt(unix_ts, 0) {
chrono::LocalResult::Single(dt) => dt.format("%Y-%m-%d %H:%M:%S").to_string(),
_ => format!("{}", ts),
}
}
pub(crate) fn service_display_name(raw: &str) -> String {
SERVICE_MAP
.get(raw)
.map(|s| s.to_string())
.unwrap_or_else(|| raw.strip_prefix("kTCCService").unwrap_or(raw).to_string())
}
fn read_db(path: &Path, is_system: bool) -> Result<Vec<TccEntry>, TccError> {
if !path.exists() {
return Ok(vec![]);
}
let conn =
Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).map_err(|e| {
TccError::DbOpen {
path: path.to_path_buf(),
source: e.to_string(),
}
})?;
let query = "SELECT service, client, auth_value, \
COALESCE(last_modified, 0) as modified \
FROM access";
let result = conn.prepare(query);
let mut stmt = match result {
Ok(s) => s,
Err(_) => {
let fallback = "SELECT service, client, auth_value, 0 as modified FROM access";
conn.prepare(fallback).map_err(|e| {
TccError::QueryFailed(format!("Query failed on {}: {}", path.display(), e))
})?
}
};
let rows = stmt
.query_map([], |row| {
let service_raw: String = row.get(0)?;
let client: String = row.get(1)?;
let auth_value: i32 = row.get(2)?;
let modified: i64 = row.get(3)?;
Ok(TccEntry {
service_display: Self::service_display_name(&service_raw),
service_raw,
client,
auth_value,
last_modified: Self::format_timestamp(modified),
is_system,
})
})
.map_err(|e| {
TccError::QueryFailed(format!("Query error on {}: {}", path.display(), e))
})?;
let mut entries = Vec::new();
for result in rows {
match result {
Ok(entry) => entries.push(entry),
Err(e) => eprintln!(
"Warning: skipping malformed row in {}: {}",
path.display(),
e
),
}
}
Ok(entries)
}
/// List TCC entries, optionally filtered by client and/or service substring.
pub fn list(
&self,
client_filter: Option<&str>,
service_filter: Option<&str>,
) -> Result<Vec<TccEntry>, TccError> {
let mut entries = Vec::new();
if self.target == DbTarget::Default || self.target == DbTarget::User {
match Self::read_db(&self.user_db_path, false) {
Ok(mut e) => entries.append(&mut e),
Err(e) => eprintln!("Warning: {}", e),
}
}
if self.target == DbTarget::Default {
match Self::read_db(&self.system_db_path, true) {
Ok(mut e) => entries.append(&mut e),
Err(e) => eprintln!("Warning: {}", e),
}
}
if let Some(cf) = client_filter {
let cf_lower = cf.to_lowercase();
entries.retain(|e| e.client.to_lowercase().contains(&cf_lower));
}
if let Some(sf) = service_filter {
let sf_lower = sf.to_lowercase();
entries.retain(|e| {
e.service_display.to_lowercase().contains(&sf_lower)
|| e.service_raw.to_lowercase().contains(&sf_lower)
});
}
entries.sort_by(|a, b| {
a.service_display
.cmp(&b.service_display)
.then(a.client.cmp(&b.client))
});
Ok(entries)
}
/// Resolve a user-supplied service name to the internal `kTCCService*` key.
pub fn resolve_service_name(&self, input: &str) -> Result<String, TccError> {
if SERVICE_MAP.contains_key(input) {
return Ok(input.to_string());
}
let input_lower = input.to_lowercase();
// Exact display name match (case-insensitive)
for (key, display) in SERVICE_MAP.iter() {
if display.to_lowercase() == input_lower {
return Ok(key.to_string());
}
}
// Partial display name match — collect all, error if ambiguous
let partial_matches: Vec<_> = SERVICE_MAP
.iter()
.filter(|(_, display)| display.to_lowercase().contains(&input_lower))
.collect();
match partial_matches.len() {
0 => {}
1 => return Ok(partial_matches[0].0.to_string()),
_ => {
let mut names: Vec<_> =
partial_matches.iter().map(|(_, d)| d.to_string()).collect();
names.sort();
return Err(TccError::AmbiguousService {
input: input.to_string(),
matches: names,
});
}
}
let prefixed = format!("kTCCService{}", input);
if SERVICE_MAP.contains_key(prefixed.as_str()) {
return Ok(prefixed);
}
Err(TccError::UnknownService(input.to_string()))
}
fn is_system_service(service: &str) -> bool {
matches!(
service,
"kTCCServiceAccessibility"
| "kTCCServiceScreenCapture"
| "kTCCServiceListenEvent"
| "kTCCServicePostEvent"
| "kTCCServiceEndpointSecurityClient"
| "kTCCServiceDeveloperTool"
)
}
/// Determine the target DB path for a write operation
fn write_db_path(&self, service_key: &str) -> &Path {
match self.target {
DbTarget::User => &self.user_db_path,
DbTarget::Default => {
if Self::is_system_service(service_key) {
&self.system_db_path
} else {
&self.user_db_path
}
}
}
}
/// Check if root is needed and we don't have it
fn check_root_for_write(
&self,
service_key: &str,
action: &str,
service_input: &str,
client: &str,
) -> Result<(), TccError> {
let db_path = self.write_db_path(service_key);
if db_path == self.system_db_path && !nix_is_root() {
return Err(TccError::NeedsRoot {
message: format!(
"Service '{}' requires the system TCC database.\n\
Run with sudo: sudo tcc {} {} {}",
Self::service_display_name(service_key),
action,
service_input,
client
),
});
}
Ok(())
}
/// Validate the DB schema before writing. Returns Ok with an optional warning.
fn validate_schema(conn: &Connection) -> Result<Option<String>, TccError> {
let digest: Option<String> = conn
.query_row(
"SELECT sql FROM sqlite_master WHERE name='access' AND type='table'",
[],
|row| row.get(0),
)
.ok();
if let Some(sql) = digest {
let mut hasher = sha1_smol::Sha1::new();
hasher.update(sql.as_bytes());
let hex = hasher.digest().to_string();
let short = &hex[..10];
if KNOWN_DIGESTS.contains(&short) {
Ok(None)
} else {
Ok(Some(format!(
"Warning: Unknown TCC database schema (digest: {}). Proceeding anyway — results may vary.",
short
)))
}
} else {
Err(TccError::SchemaInvalid(
"Could not read TCC database schema. The access table may not exist.".to_string(),
))
}
}
/// Open a writable connection with schema validation
fn open_writable(&self, service_key: &str) -> Result<(Connection, Option<String>), TccError> {
let db_path = self.write_db_path(service_key);
let conn = Connection::open(db_path).map_err(|e| TccError::DbOpen {
path: db_path.to_path_buf(),
source: e.to_string(),
})?;
let warning = Self::validate_schema(&conn)?;
Ok((conn, warning))
}
/// Insert or replace a TCC entry with `auth_value = 2` (granted).
pub fn grant(&self, service: &str, client: &str) -> Result<String, TccError> {
let service_key = self.resolve_service_name(service)?;
self.check_root_for_write(&service_key, "grant", service, client)?;
let (conn, warning) = self.open_writable(&service_key)?;
if let Some(w) = &warning {
eprintln!("{}", w);
}
let client_type: i32 = if client.starts_with('/') { 0 } else { 1 };
let now = chrono::Utc::now().timestamp() - 978_307_200;
let sql = "INSERT OR REPLACE INTO access \
(service, client, client_type, auth_value, auth_reason, auth_version, flags, last_modified) \
VALUES (?1, ?2, ?3, 2, 0, 1, 0, ?4)";
conn.execute(
sql,
rusqlite::params![service_key, client, client_type, now],
)
.map_err(|e| {
TccError::WriteFailed(format!(
"Failed to grant: {}. Note: SIP may prevent TCC.db writes on macOS 10.14+",
e
))
})?;
Ok(format!(
"Granted {} access for '{}'",
Self::service_display_name(&service_key),
client
))
}
/// Delete a TCC entry for the given service and client.
pub fn revoke(&self, service: &str, client: &str) -> Result<String, TccError> {
let service_key = self.resolve_service_name(service)?;
self.check_root_for_write(&service_key, "revoke", service, client)?;
let (conn, warning) = self.open_writable(&service_key)?;
if let Some(w) = &warning {
eprintln!("{}", w);
}
let deleted = conn
.execute(
"DELETE FROM access WHERE service = ?1 AND client = ?2",
rusqlite::params![service_key, client],
)
.map_err(|e| {
TccError::WriteFailed(format!(
"Failed to revoke: {}. Note: SIP may prevent TCC.db writes.",
e
))
})?;
if deleted == 0 {
Err(TccError::NotFound {
service: Self::service_display_name(&service_key),
client: client.to_string(),
})
} else {
Ok(format!(
"Revoked {} access for '{}'",
Self::service_display_name(&service_key),
client
))
}
}
pub fn enable(&self, service: &str, client: &str) -> Result<String, TccError> {
let service_key = self.resolve_service_name(service)?;
self.check_root_for_write(&service_key, "enable", service, client)?;
let (conn, warning) = self.open_writable(&service_key)?;
if let Some(w) = &warning {
eprintln!("{}", w);
}
let now = chrono::Utc::now().timestamp() - 978_307_200;
let updated = conn
.execute(
"UPDATE access SET auth_value = 2, last_modified = ?3 WHERE service = ?1 AND client = ?2",
rusqlite::params![service_key, client, now],
)
.map_err(|e| {
TccError::WriteFailed(format!(
"Failed to enable: {}. Note: SIP may prevent TCC.db writes.",
e
))
})?;
if updated == 0 {
Err(TccError::NotFound {
service: format!(
"{}. Use `tcc grant` to insert a new entry",
Self::service_display_name(&service_key)
),
client: client.to_string(),
})
} else {
Ok(format!(
"Enabled {} access for '{}'",
Self::service_display_name(&service_key),
client
))
}
}
pub fn disable(&self, service: &str, client: &str) -> Result<String, TccError> {
let service_key = self.resolve_service_name(service)?;
self.check_root_for_write(&service_key, "disable", service, client)?;
let (conn, warning) = self.open_writable(&service_key)?;
if let Some(w) = &warning {
eprintln!("{}", w);
}
let now = chrono::Utc::now().timestamp() - 978_307_200;
let updated = conn
.execute(
"UPDATE access SET auth_value = 0, last_modified = ?3 WHERE service = ?1 AND client = ?2",
rusqlite::params![service_key, client, now],
)
.map_err(|e| {
TccError::WriteFailed(format!(
"Failed to disable: {}. Note: SIP may prevent TCC.db writes.",
e
))
})?;
if updated == 0 {
Err(TccError::NotFound {
service: Self::service_display_name(&service_key),
client: client.to_string(),
})
} else {
Ok(format!(
"Disabled {} access for '{}'",
Self::service_display_name(&service_key),
client
))
}
}
pub fn reset(&self, service: &str, client: Option<&str>) -> Result<String, TccError> {
let service_key = self.resolve_service_name(service)?;
if let Some(c) = client {
// Delete specific client entry
self.check_root_for_write(&service_key, "reset", service, c)?;
let (conn, warning) = self.open_writable(&service_key)?;
if let Some(w) = &warning {
eprintln!("{}", w);
}
let deleted = conn
.execute(
"DELETE FROM access WHERE service = ?1 AND client = ?2",
rusqlite::params![service_key, c],
)
.map_err(|e| TccError::WriteFailed(format!("Failed to reset: {}", e)))?;
if deleted == 0 {
Err(TccError::NotFound {
service: Self::service_display_name(&service_key),
client: c.to_string(),
})
} else {
Ok(format!(
"Reset {} entry for '{}'",
Self::service_display_name(&service_key),
c
))
}
} else {
// Delete all entries for this service
// For default target, try to reset in both DBs
let mut total_deleted = 0usize;
let mut errors = Vec::new();
let paths: Vec<(&Path, &str)> = match self.target {
DbTarget::User => vec![(&self.user_db_path, "user")],
DbTarget::Default => vec![
(&self.user_db_path, "user"),
(&self.system_db_path, "system"),
],
};
for (db_path, label) in paths {
if !db_path.exists() {
continue;
}
// Check root for system DB writes
if db_path == self.system_db_path && !nix_is_root() {
return Err(TccError::NeedsRoot {
message: format!(
"Resetting all '{}' entries requires the system TCC database.\n\
Run with sudo: sudo tcc reset {}",
Self::service_display_name(&service_key),
service
),
});
}
match Connection::open(db_path) {
Ok(conn) => {
if let Err(e) = Self::validate_schema(&conn) {
errors.push(format!("{} DB: {}", label, e));
continue;
}
match conn.execute(
"DELETE FROM access WHERE service = ?1",
rusqlite::params![service_key],
) {
Ok(n) => total_deleted += n,
Err(e) => errors.push(format!("{} DB: {}", label, e)),
}
}
Err(e) => errors.push(format!("{} DB: {}", label, e)),
}
}
if total_deleted == 0 && !errors.is_empty() {
Err(TccError::WriteFailed(format!(
"Failed to reset: {}",
errors.join("; ")
)))
} else {
let mut msg = format!(
"Reset all {} entries ({} deleted)",
Self::service_display_name(&service_key),
total_deleted
);
for e in errors {
msg.push_str(&format!("\nWarning: {}", e));
}
Ok(msg)
}
}
}
pub fn info(&self) -> Vec<String> {
let mut lines = Vec::new();
// macOS version — use absolute path for defensive coding
let macos_ver = Command::new("/usr/bin/sw_vers")
.arg("-productVersion")
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_else(|_| "unknown".to_string());
lines.push(format!("macOS version: {}", macos_ver));
// SIP status — use absolute path for defensive coding
let sip = Command::new("/usr/bin/csrutil")
.arg("status")
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_else(|_| "unknown (csrutil not available)".to_string());
lines.push(format!("SIP status: {}", sip));
lines.push(String::new());
// DB info
for (label, path) in [
("User DB", &self.user_db_path),
("System DB", &self.system_db_path),
] {
lines.push(format!("{}: {}", label, path.display()));
if path.exists() {
let readable =
Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).is_ok();
let writable =
Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE).is_ok();
lines.push(format!(
" Readable: {}",
if readable { "yes" } else { "no" }
));
lines.push(format!(
" Writable: {}",
if writable { "yes" } else { "no" }
));
// Schema digest
if readable
&& let Ok(conn) =
Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
&& let Ok(sql) = conn.query_row::<String, _, _>(
"SELECT sql FROM sqlite_master WHERE name='access' AND type='table'",
[],
|row| row.get(0),
)
{
let mut hasher = sha1_smol::Sha1::new();
hasher.update(sql.as_bytes());
let hex = hasher.digest().to_string();
let short = &hex[..10];
let known = if KNOWN_DIGESTS.contains(&short) {
"known"
} else {
"UNKNOWN"
};
lines.push(format!(" Schema digest: {} ({})", short, known));
}
} else {
lines.push(" Not found".to_string());
}
lines.push(String::new());
}
lines
}
}
pub fn nix_is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
/// Truncate a client path to just the binary name
pub fn compact_client(client: &str) -> String {
if client.starts_with('/') {
// It's a path — extract just the filename
std::path::Path::new(client)
.file_name()
.map(|f| f.to_string_lossy().to_string())
.unwrap_or_else(|| client.to_string())
} else {
client.to_string()
}
}
/// Map auth_value to a display string
pub fn auth_value_display(value: i32) -> String {
match value {
0 => "denied".to_string(),
2 => "granted".to_string(),
3 => "limited".to_string(),
v => format!("unknown({})", v),
}
}
#[cfg(test)]
mod tests {
use super::*;
// ── Service name mapping ──────────────────────────────────────────
#[test]
fn known_service_keys_resolve_to_human_names() {
assert_eq!(
TccDb::service_display_name("kTCCServiceAccessibility"),
"Accessibility"
);
assert_eq!(
TccDb::service_display_name("kTCCServiceScreenCapture"),
"Screen Recording"
);
assert_eq!(TccDb::service_display_name("kTCCServiceCamera"), "Camera");
assert_eq!(
TccDb::service_display_name("kTCCServiceMicrophone"),
"Microphone"
);
assert_eq!(
TccDb::service_display_name("kTCCServiceSystemPolicyAllFiles"),
"Full Disk Access"
);
assert_eq!(TccDb::service_display_name("kTCCServicePhotos"), "Photos");
}
#[test]
fn unknown_service_key_with_prefix_strips_prefix() {
// Unknown key with kTCCService prefix should strip the prefix
assert_eq!(
TccDb::service_display_name("kTCCServiceSomethingNew"),
"SomethingNew"
);
}
#[test]
fn unknown_service_key_without_prefix_returns_raw() {
// Key without the standard prefix returns as-is
assert_eq!(
TccDb::service_display_name("com.example.custom"),
"com.example.custom"
);
assert_eq!(TccDb::service_display_name("FooBar"), "FooBar");
}
// ── Auth value display ────────────────────────────────────────────
#[test]
fn auth_value_denied() {
assert_eq!(auth_value_display(0), "denied");
}
#[test]
fn auth_value_granted() {
assert_eq!(auth_value_display(2), "granted");
}
#[test]
fn auth_value_limited() {
assert_eq!(auth_value_display(3), "limited");
}
#[test]
fn auth_value_unknown_values() {
assert_eq!(auth_value_display(1), "unknown(1)");
assert_eq!(auth_value_display(99), "unknown(99)");
assert_eq!(auth_value_display(-1), "unknown(-1)");
}
// ── Compact path display ──────────────────────────────────────────
#[test]
fn compact_client_extracts_binary_name_from_path() {
assert_eq!(compact_client("/usr/local/bin/my-tool"), "my-tool");
assert_eq!(
compact_client("/Applications/Safari.app/Contents/MacOS/Safari"),
"Safari"
);
}
#[test]
fn compact_client_returns_bundle_id_unchanged() {
assert_eq!(compact_client("com.apple.Terminal"), "com.apple.Terminal");
assert_eq!(compact_client("org.mozilla.firefox"), "org.mozilla.firefox");
}
#[test]
fn compact_client_root_path() {
// Edge case: root path "/"
assert_eq!(compact_client("/"), "/");
}
// ── Client/service filtering (partial match) ──────────────────────
#[test]
fn client_filter_partial_match() {
let entries = vec![
make_entry("kTCCServiceCamera", "com.apple.Terminal", 2),
make_entry("kTCCServiceMicrophone", "com.google.Chrome", 0),
make_entry("kTCCServiceCamera", "com.apple.Safari", 2),
];
let filtered = filter_entries(entries, Some("apple"), None);
assert_eq!(filtered.len(), 2);
assert!(filtered.iter().all(|e| e.client.contains("apple")));
}
#[test]
fn service_filter_partial_match_display_name() {
let entries = vec![
make_entry("kTCCServiceCamera", "com.app.a", 2),
make_entry("kTCCServiceMicrophone", "com.app.b", 0),
make_entry("kTCCServiceScreenCapture", "com.app.c", 2),
];
// Matches "Camera" display name
let filtered = filter_entries(entries, None, Some("Camer"));
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].service_raw, "kTCCServiceCamera");
}
#[test]
fn service_filter_partial_match_raw_key() {
let entries = vec![
make_entry("kTCCServiceCamera", "com.app.a", 2),
make_entry("kTCCServiceMicrophone", "com.app.b", 0),
];
// Matches raw key
let filtered = filter_entries(entries, None, Some("kTCCServiceMicro"));
assert_eq!(filtered.len(), 1);
assert_eq!(filtered[0].service_raw, "kTCCServiceMicrophone");
}
#[test]
fn filter_case_insensitive() {
let entries = vec![make_entry("kTCCServiceCamera", "com.Apple.Terminal", 2)];
let filtered = filter_entries(entries, Some("APPLE"), None);
assert_eq!(filtered.len(), 1);
}
#[test]
fn filter_no_match_returns_empty() {
let entries = vec![make_entry("kTCCServiceCamera", "com.apple.Terminal", 2)];
let filtered = filter_entries(entries, Some("nonexistent"), None);
assert!(filtered.is_empty());
}
// ── SERVICE_MAP sanity ────────────────────────────────────────────
#[test]
fn service_map_contains_expected_entries() {
assert!(SERVICE_MAP.contains_key("kTCCServiceAccessibility"));
assert!(SERVICE_MAP.contains_key("kTCCServiceCamera"));
assert!(SERVICE_MAP.contains_key("kTCCServiceMicrophone"));
assert!(SERVICE_MAP.contains_key("kTCCServiceScreenCapture"));
assert!(SERVICE_MAP.len() > 20);
}
// ── Format timestamp ──────────────────────────────────────────────
#[test]
fn format_timestamp_zero_returns_na() {
assert_eq!(TccDb::format_timestamp(0), "N/A");
}
#[test]
fn format_timestamp_large_unix_value() {
// A recent Unix timestamp should produce a valid date
let result = TccDb::format_timestamp(1_700_000_000);
assert!(result.contains("2023"), "Expected 2023 in: {}", result);
}
#[test]
fn format_timestamp_coredata_value() {
// CoreData timestamp (seconds since 2001-01-01) — small value
// 700_000_000 + 978_307_200 = 1_678_307_200 → 2023
let result = TccDb::format_timestamp(700_000_000);
assert!(
result.contains("2023") || result.contains("2024"),
"Got: {}",
result
);
}
// ── Helpers ───────────────────────────────────────────────────────
fn make_entry(service_raw: &str, client: &str, auth_value: i32) -> TccEntry {
TccEntry {
service_raw: service_raw.to_string(),
service_display: TccDb::service_display_name(service_raw),
client: client.to_string(),
auth_value,
last_modified: "2024-01-01 00:00:00".to_string(),
is_system: false,
}
}
/// Applies the same filtering logic as TccDb::list
fn filter_entries(
mut entries: Vec<TccEntry>,
client_filter: Option<&str>,
service_filter: Option<&str>,
) -> Vec<TccEntry> {
if let Some(cf) = client_filter {
let cf_lower = cf.to_lowercase();
entries.retain(|e| e.client.to_lowercase().contains(&cf_lower));
}
if let Some(sf) = service_filter {
let sf_lower = sf.to_lowercase();
entries.retain(|e| {
e.service_display.to_lowercase().contains(&sf_lower)
|| e.service_raw.to_lowercase().contains(&sf_lower)
});
}
entries
}
// ── Resolve service name ──────────────────────────────────────────
fn make_test_db() -> TccDb {
TccDb::with_paths(
PathBuf::from("/nonexistent/user.db"),
PathBuf::from("/nonexistent/system.db"),
DbTarget::User,
)
}
#[test]
fn resolve_exact_key() {
let db = make_test_db();
assert_eq!(
db.resolve_service_name("kTCCServiceCamera").unwrap(),
"kTCCServiceCamera"
);