-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
487 lines (446 loc) · 14.1 KB
/
main.rs
File metadata and controls
487 lines (446 loc) · 14.1 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
#[cfg(test)]
use clap::CommandFactory;
#[cfg(test)]
use clap::error::ErrorKind;
use clap::{Parser, Subcommand};
use colored::Colorize;
use std::process;
use tccutil_rs::tcc::{
DbTarget, SERVICE_MAP, TccDb, TccEntry, TccError, auth_value_display, compact_client,
};
#[derive(Parser, Debug)]
#[command(name = "tccutil-rs", about = "Manage macOS TCC permissions", version)]
struct Cli {
/// Operate on user DB instead of system DB
#[arg(short, long, global = true)]
user: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
/// List all TCC permissions
List {
/// Filter by client name (partial match)
#[arg(long)]
client: Option<String>,
/// Filter by service name (partial match)
#[arg(long)]
service: Option<String>,
/// Compact mode: show only binary name instead of full path
#[arg(short, long, conflicts_with = "json")]
compact: bool,
/// Output as JSON array
#[arg(long)]
json: bool,
},
/// Grant a TCC permission (inserts new entry)
Grant {
/// Service name (e.g. Accessibility, Camera)
service: String,
/// Client bundle ID or path
client_path: String,
},
/// Revoke a TCC permission (deletes entry)
Revoke {
/// Service name (e.g. Accessibility, Camera)
service: String,
/// Client bundle ID or path
client_path: String,
},
/// Enable a TCC permission (set auth_value=2 for existing entry)
Enable {
/// Service name (e.g. Accessibility, Camera)
service: String,
/// Client bundle ID or path
client_path: String,
},
/// Disable a TCC permission (set auth_value=0 for existing entry)
Disable {
/// Service name (e.g. Accessibility, Camera)
service: String,
/// Client bundle ID or path
client_path: String,
},
/// Reset (delete) TCC entries for a service
Reset {
/// Service name (e.g. Accessibility, Camera)
service: String,
/// Optional: specific client to reset (if omitted, resets all entries for the service)
client_path: Option<String>,
},
/// List all known TCC service names
Services,
/// Show TCC database info, macOS version, and SIP status
Info,
}
fn print_entries(entries: &[TccEntry], compact: bool) {
if entries.is_empty() {
println!("{}", "No entries found.".dimmed());
return;
}
let display_clients: Vec<String> = if compact {
entries.iter().map(|e| compact_client(&e.client)).collect()
} else {
entries.iter().map(|e| e.client.clone()).collect()
};
let hdr_svc = "SERVICE";
let hdr_client = "CLIENT";
let hdr_status = "STATUS";
let hdr_source = "SOURCE";
let hdr_modified = "LAST MODIFIED";
let svc_w = entries
.iter()
.map(|e| e.service_display.len())
.max()
.unwrap_or(0)
.max(hdr_svc.len());
let client_w = display_clients
.iter()
.map(|c| c.len())
.max()
.unwrap_or(0)
.max(hdr_client.len());
let status_w = entries
.iter()
.map(|e| auth_value_display(e.auth_value).len())
.max()
.unwrap_or(0)
.max(hdr_status.len());
let source_w = hdr_source.len();
let modified_w = entries
.iter()
.map(|e| e.last_modified.len())
.max()
.unwrap_or(0)
.max(hdr_modified.len());
println!(
"{:<sw$} {:<cw$} {:<stw$} {:<srw$} {}",
hdr_svc,
hdr_client,
hdr_status,
hdr_source,
hdr_modified,
sw = svc_w,
cw = client_w,
stw = status_w,
srw = source_w,
);
println!(
"{} {} {} {} {}",
"─".repeat(svc_w),
"─".repeat(client_w),
"─".repeat(status_w),
"─".repeat(source_w),
"─".repeat(modified_w),
);
let mut prev_client: Option<&str> = None;
for (entry, display_client) in entries.iter().zip(display_clients.iter()) {
let status_plain = auth_value_display(entry.auth_value);
let status_colored = match entry.auth_value {
0 => status_plain.red().to_string(),
2 => status_plain.green().to_string(),
3 => status_plain.yellow().to_string(),
_ => status_plain.clone(),
};
// Pad based on visible length, then append the invisible ANSI tail
let status_pad = status_w.saturating_sub(status_plain.len());
let status_cell = format!("{}{}", status_colored, " ".repeat(status_pad));
let client_cell = if prev_client == Some(display_client.as_str()) {
"\u{2033}".to_string() // ″ double prime (ditto mark)
} else {
display_client.clone()
};
prev_client = Some(display_client.as_str());
let source = if entry.is_system { "system" } else { "user" };
println!(
"{:<sw$} {:<cw$} {} {:<srw$} {}",
entry.service_display,
client_cell,
status_cell,
source,
entry.last_modified,
sw = svc_w,
cw = client_w,
srw = source_w,
);
}
println!("\n{} entries total", entries.len());
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
Cli::try_parse_from(args)
}
// ── Subcommand parsing ─────────────────────────────────────────
#[test]
fn parse_list_no_flags() {
let cli = parse(&["tcc", "list"]).unwrap();
assert!(matches!(cli.command, Commands::List { .. }));
assert!(!cli.user);
}
#[test]
fn parse_list_with_client_and_service_filter() {
let cli = parse(&["tcc", "list", "--client", "apple", "--service", "Camera"]).unwrap();
match cli.command {
Commands::List {
client,
service,
compact,
json,
} => {
assert_eq!(client.as_deref(), Some("apple"));
assert_eq!(service.as_deref(), Some("Camera"));
assert!(!compact);
assert!(!json);
}
_ => panic!("expected List"),
}
}
#[test]
fn parse_list_compact() {
let cli = parse(&["tcc", "list", "-c"]).unwrap();
match cli.command {
Commands::List { compact, .. } => assert!(compact),
_ => panic!("expected List"),
}
}
#[test]
fn parse_list_json() {
let cli = parse(&["tcc", "list", "--json"]).unwrap();
match cli.command {
Commands::List { json, .. } => assert!(json),
_ => panic!("expected List"),
}
}
#[test]
fn parse_services() {
let cli = parse(&["tcc", "services"]).unwrap();
assert!(matches!(cli.command, Commands::Services));
}
#[test]
fn parse_info() {
let cli = parse(&["tcc", "info"]).unwrap();
assert!(matches!(cli.command, Commands::Info));
}
#[test]
fn parse_grant() {
let cli = parse(&["tcc", "grant", "Camera", "com.app.test"]).unwrap();
match cli.command {
Commands::Grant {
service,
client_path,
} => {
assert_eq!(service, "Camera");
assert_eq!(client_path, "com.app.test");
}
_ => panic!("expected Grant"),
}
}
#[test]
fn parse_revoke() {
let cli = parse(&["tcc", "revoke", "Camera", "com.app.test"]).unwrap();
match cli.command {
Commands::Revoke {
service,
client_path,
} => {
assert_eq!(service, "Camera");
assert_eq!(client_path, "com.app.test");
}
_ => panic!("expected Revoke"),
}
}
#[test]
fn parse_enable() {
let cli = parse(&["tcc", "enable", "Accessibility", "/usr/bin/foo"]).unwrap();
match cli.command {
Commands::Enable {
service,
client_path,
} => {
assert_eq!(service, "Accessibility");
assert_eq!(client_path, "/usr/bin/foo");
}
_ => panic!("expected Enable"),
}
}
#[test]
fn parse_disable() {
let cli = parse(&["tcc", "disable", "Microphone", "com.app.x"]).unwrap();
match cli.command {
Commands::Disable {
service,
client_path,
} => {
assert_eq!(service, "Microphone");
assert_eq!(client_path, "com.app.x");
}
_ => panic!("expected Disable"),
}
}
#[test]
fn parse_reset_with_client() {
let cli = parse(&["tcc", "reset", "Camera", "com.app.test"]).unwrap();
match cli.command {
Commands::Reset {
service,
client_path,
} => {
assert_eq!(service, "Camera");
assert_eq!(client_path.as_deref(), Some("com.app.test"));
}
_ => panic!("expected Reset"),
}
}
#[test]
fn parse_reset_without_client() {
let cli = parse(&["tcc", "reset", "Camera"]).unwrap();
match cli.command {
Commands::Reset {
service,
client_path,
} => {
assert_eq!(service, "Camera");
assert!(client_path.is_none());
}
_ => panic!("expected Reset"),
}
}
#[test]
fn parse_user_flag_global() {
let cli = parse(&["tcc", "--user", "list"]).unwrap();
assert!(cli.user);
}
#[test]
fn parse_user_flag_after_subcommand() {
let cli = parse(&["tcc", "list", "--user"]).unwrap();
assert!(cli.user);
}
// ── Error cases ────────────────────────────────────────────────
#[test]
fn parse_no_subcommand_is_error() {
let err = parse(&["tcc"]).unwrap_err();
assert_eq!(
err.kind(),
ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
);
}
#[test]
fn parse_unknown_subcommand_is_error() {
let err = parse(&["tcc", "foobar"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidSubcommand);
}
#[test]
fn parse_grant_missing_args_is_error() {
let err = parse(&["tcc", "grant"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);
}
#[test]
fn parse_list_compact_and_json_conflict() {
let err = parse(&["tcc", "list", "--compact", "--json"]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::ArgumentConflict);
}
#[test]
fn cli_has_version() {
let cmd = Cli::command();
assert!(cmd.get_version().is_some());
}
}
/// Run a TCC command and handle the result uniformly
fn run_command(result: Result<String, TccError>) {
match result {
Ok(msg) => println!("{}", msg.green()),
Err(e) => {
eprintln!("{}: {}", "Error".red().bold(), e);
process::exit(1);
}
}
}
/// Create a TccDb or exit with an error
fn make_db(target: DbTarget) -> TccDb {
match TccDb::new(target) {
Ok(db) => db,
Err(e) => {
eprintln!("{}: {}", "Error".red().bold(), e);
process::exit(1);
}
}
}
fn main() {
let cli = Cli::parse();
let target = if cli.user {
DbTarget::User
} else {
DbTarget::Default
};
match cli.command {
Commands::List {
client,
service,
compact,
json,
} => {
let db = make_db(target);
match db.list(client.as_deref(), service.as_deref()) {
Ok(entries) => {
if json {
match serde_json::to_string_pretty(&entries) {
Ok(json_str) => println!("{}", json_str),
Err(e) => {
eprintln!(
"{}: failed to serialize entries: {}",
"Error".red().bold(),
e
);
process::exit(1);
}
}
} else {
print_entries(&entries, compact);
}
}
Err(e) => {
eprintln!("{}: {}", "Error".red().bold(), e);
process::exit(1);
}
}
}
Commands::Grant {
service,
client_path,
} => run_command(make_db(target).grant(&service, &client_path)),
Commands::Revoke {
service,
client_path,
} => run_command(make_db(target).revoke(&service, &client_path)),
Commands::Enable {
service,
client_path,
} => run_command(make_db(target).enable(&service, &client_path)),
Commands::Disable {
service,
client_path,
} => run_command(make_db(target).disable(&service, &client_path)),
Commands::Reset {
service,
client_path,
} => run_command(make_db(target).reset(&service, client_path.as_deref())),
Commands::Services => {
println!("{:<35} DESCRIPTION", "INTERNAL NAME");
println!("{:<35} {}", "─".repeat(35), "─".repeat(25));
let mut pairs: Vec<_> = SERVICE_MAP.iter().collect();
pairs.sort_by_key(|(_, desc)| *desc);
for (key, desc) in pairs {
println!("{:<35} {}", key.dimmed(), desc);
}
}
Commands::Info => {
let db = make_db(target);
for line in db.info() {
println!("{}", line);
}
}
}
}