keyhog 0.5.73

GPU-accelerated secret scanner for code, Git history, cloud, containers, browser assets, and live credential verification
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
//! `keyhog guard {add, remove, list, status, reconcile}` subcommand.
//!
//! Connects to the daemon and sends guard control frames. When no daemon
//! is available, reports that clearly instead of silently doing nothing.

use crate::args::{GuardAction, GuardArgs};
use crate::daemon::client;
use crate::daemon::protocol::{response_kind, Request, Response};
use crate::exit_codes;
use crate::style;
use std::process::ExitCode;

use crate::daemon::server::default_socket_path;

pub(crate) async fn run(args: GuardArgs) -> anyhow::Result<ExitCode> {
    match args.action {
        GuardAction::Add { root, mode } => run_add(root, mode).await,
        GuardAction::Remove { root } => run_remove(root).await,
        GuardAction::List => run_list().await,
        GuardAction::Status { root, format } => run_status(root, format).await,
        GuardAction::Reconcile { root } => run_reconcile(root).await,
        GuardAction::Rebuild { root, mode } => run_rebuild(root, mode).await,
    }
}

async fn run_add(root: std::path::PathBuf, mode: String) -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(conn) => conn,
        Err(error) => {
            anyhow::bail!(
                "guard add: no compatible daemon at {} (start one with `keyhog daemon start`): {error}",
                socket.display()
            );
        }
    };

    let canonical = canonicalize_root(&root)?;
    let request = Request::GuardAdd {
        root: canonical,
        mode,
    };
    let canonical_for_reconcile = match conn.round_trip(&request).await? {
        Response::GuardAdded {
            root: ref added_root,
            state: ref add_state,
            terminal_sequence,
        } => {
            let palette = style::for_stderr();
            eprintln!(
                "{} guard: root {} registered (state {}, sequence {})",
                style::pass("OK", &palette),
                root.display(),
                add_state,
                terminal_sequence
            );
            added_root.clone()
        }
        Response::Error { message } => {
            anyhow::bail!("{message}");
        }
        other => {
            anyhow::bail!(
                "guard add: protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    };
    // Trigger baseline reconciliation so the root reaches a terminal
    // state. The help text promises this waits for the initial check.
    let reconcile_request = Request::GuardReconcile {
        root: canonical_for_reconcile.clone(),
    };
    match conn.round_trip(&reconcile_request).await? {
        Response::GuardReconcileStarted { root: _ } => {
            // Reconciliation completed. Query the final state.
            let status_request = Request::GuardStatus {
                root: canonical_for_reconcile,
            };
            match conn.round_trip(&status_request).await? {
                Response::GuardStatusResult {
                    state,
                    findings_count,
                    ..
                } => {
                    let palette = style::for_stderr();
                    eprintln!(
                        "{} guard: reconciliation complete, root is {}",
                        style::pass("OK", &palette),
                        state
                    );
                    Ok(exit_for_guard_state(&state, findings_count))
                }
                Response::Error { message } => {
                    anyhow::bail!("guard add: status after reconcile: {message}");
                }
                other => {
                    anyhow::bail!(
                        "guard add: status protocol mismatch (got {})",
                        response_kind(&other)
                    );
                }
            }
        }
        Response::Error { message } => {
            anyhow::bail!("guard add: reconcile failed: {message}");
        }
        other => {
            anyhow::bail!(
                "guard add: reconcile protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }
}

async fn run_remove(root: std::path::PathBuf) -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(conn) => conn,
        Err(error) => {
            anyhow::bail!(
                "guard remove: no compatible daemon at {} (start one with `keyhog daemon start`): {error}",
                socket.display()
            );
        }
    };

    let canonical = resolve_root_for_control(&root)?;
    let request = Request::GuardRemove { root: canonical };
    match conn.round_trip(&request).await? {
        Response::GuardRemoved => {
            let palette = style::for_stderr();
            eprintln!(
                "{} guard: removed {}",
                style::pass("OK", &palette),
                root.display()
            );
            Ok(ExitCode::SUCCESS)
        }
        Response::Error { message } => {
            anyhow::bail!("{message}");
        }
        other => {
            anyhow::bail!(
                "guard remove: protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }
}

async fn run_list() -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(c) => c,
        Err(e) => {
            anyhow::bail!(
                "guard list: no compatible daemon at {} (start one with `keyhog daemon start`): {e}",
                socket.display()
            );
        }
    };

    let request = Request::GuardList;
    match conn.round_trip(&request).await? {
        Response::GuardListResult { roots } => {
            if roots.is_empty() {
                let palette = style::for_stderr();
                eprintln!("{} no guard roots registered", style::pass("OK", &palette));
            } else {
                let palette = style::for_stderr();
                eprintln!(
                    "{} {} guard root{} registered",
                    style::pass("OK", &palette),
                    roots.len(),
                    if roots.len() == 1 { "" } else { "s" }
                );
                for entry in &roots {
                    println!(
                        "  {}  {}  seq={}",
                        entry.root, entry.state, entry.terminal_sequence
                    );
                }
            }
            Ok(ExitCode::SUCCESS)
        }
        Response::Error { message } => {
            let palette = style::for_stderr();
            eprintln!("{} guard list: {}", style::warn("WARN", &palette), message);
            Ok(ExitCode::from(exit_codes::EXIT_SOURCE_FAILED))
        }
        other => {
            let palette = style::for_stderr();
            eprintln!(
                "{} guard list: unexpected daemon response: {}",
                style::warn("WARN", &palette),
                response_kind(&other)
            );
            Ok(ExitCode::from(exit_codes::EXIT_SOURCE_FAILED))
        }
    }
}

async fn run_status(root: std::path::PathBuf, format: String) -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(conn) => conn,
        Err(error) => {
            anyhow::bail!(
                "guard status: no compatible daemon at {} (start one with `keyhog daemon start`): {error}",
                socket.display()
            );
        }
    };

    let canonical = resolve_root_for_control(&root)?;
    let request = Request::GuardStatus { root: canonical };
    match conn.round_trip(&request).await? {
        Response::GuardStatusResult {
            root: daemon_root,
            mode,
            state,
            terminal_sequence,
            accepted_event_sequence,
            completed_event_sequence,
            pending_events,
            files_scanned,
            bytes_scanned,
            attestation_hits,
            attestation_misses,
            findings_count,
            coverage_gaps,
            initial_reconciliation_time,
            last_reconciliation_time,
            scanner_residency,
            backend_route_label,
            build_identity_short,
            detector_digest_short,
            suppression_digest_short,
            config_digest_short,
            autoroute_evidence_status,
            store_schema_version,
            store_path,
            repair_command,
        } => {
            if format != "human" && format != "json" {
                anyhow::bail!(
                    "guard status: invalid format '{}': expected 'human' or 'json'",
                    format
                );
            }
            if format == "json" {
                let json = serde_json::json!({
                    "root": daemon_root,
                    "mode": mode,
                    "state": state,
                    "terminal_sequence": terminal_sequence,
                    "accepted_event_sequence": accepted_event_sequence,
                    "completed_event_sequence": completed_event_sequence,
                    "pending_events": pending_events,
                    "files_scanned": files_scanned,
                    "bytes_scanned": bytes_scanned,
                    "attestation_hits": attestation_hits,
                    "attestation_misses": attestation_misses,
                    "findings_count": findings_count,
                    "coverage_gaps": coverage_gaps,
                    "initial_reconciliation_time": initial_reconciliation_time,
                    "last_reconciliation_time": last_reconciliation_time,
                    "scanner_residency": scanner_residency,
                    "backend_route_label": backend_route_label,
                    "build_identity_short": build_identity_short,
                    "detector_digest_short": detector_digest_short,
                    "suppression_digest_short": suppression_digest_short,
                    "config_digest_short": config_digest_short,
                    "autoroute_evidence_status": autoroute_evidence_status,
                    "store_schema_version": store_schema_version,
                    "store_path": store_path,
                    "repair_command": repair_command,
                });
                println!("{json}");
            } else {
                let palette = style::for_stderr();
                println!("root:           {}", daemon_root);
                println!("mode:           {mode}");
                println!("state:          {state}");
                println!("sequence:       {terminal_sequence}");
                println!("accepted seq:   {accepted_event_sequence}");
                println!("completed seq:  {completed_event_sequence}");
                println!("pending events: {pending_events}");
                println!("files scanned:  {files_scanned}");
                println!("bytes scanned:  {bytes_scanned}");
                println!("cache hits:     {attestation_hits}");
                println!("cache misses:   {attestation_misses}");
                println!("findings:       {findings_count}");
                println!("coverage gaps:  {coverage_gaps}");
                if let Some(t) = initial_reconciliation_time {
                    println!("initial recon:  {t}");
                }
                if let Some(t) = last_reconciliation_time {
                    println!("last recon:     {t}");
                }
                println!("residency:      {scanner_residency}");
                println!("backend route:  {backend_route_label}");
                if !build_identity_short.is_empty() {
                    println!("build digest:   {build_identity_short}");
                }
                if !detector_digest_short.is_empty() {
                    println!("detector:       {detector_digest_short}");
                }
                if !suppression_digest_short.is_empty() {
                    println!("suppression:    {suppression_digest_short}");
                }
                if !config_digest_short.is_empty() {
                    println!("config:         {config_digest_short}");
                }
                println!("autoroute:      {autoroute_evidence_status}");
                println!("store schema:   {store_schema_version}");
                if !store_path.is_empty() {
                    println!("store path:     {store_path}");
                }
                if state == "degraded" || state == "stale-policy" {
                    eprintln!("{} repair: {repair_command}", style::warn("WARN", &palette));
                }
            }
            // Exit 13 for any state that is not a proven-clean Current root.
            Ok(exit_for_guard_state(&state, findings_count))
        }
        Response::Error { message } => {
            anyhow::bail!("{message}");
        }
        other => {
            anyhow::bail!(
                "guard status: protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }
}

async fn run_reconcile(root: std::path::PathBuf) -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(conn) => conn,
        Err(error) => {
            anyhow::bail!(
                "guard reconcile: no compatible daemon at {} (start one with `keyhog daemon start`): {error}",
                socket.display()
            );
        }
    };
    let canonical = canonicalize_root(&root)?;
    let request = Request::GuardReconcile {
        root: canonical.clone(),
    };
    match conn.round_trip(&request).await? {
        Response::GuardReconcileStarted { root: _ } => {
            // Reconciliation completed synchronously. Query the
            // final state to report it to the operator.
            let status_request = Request::GuardStatus {
                root: canonical.clone(),
            };
            match conn.round_trip(&status_request).await? {
                Response::GuardStatusResult {
                    state,
                    findings_count,
                    ..
                } => {
                    let palette = style::for_stderr();
                    eprintln!(
                        "{} guard: reconciliation complete for {}, state is {}",
                        style::pass("OK", &palette),
                        root.display(),
                        state
                    );
                    Ok(exit_for_guard_state(&state, findings_count))
                }
                Response::Error { message } => {
                    anyhow::bail!("guard reconcile: status after reconcile: {message}");
                }
                other => {
                    anyhow::bail!(
                        "guard reconcile: status protocol mismatch (got {})",
                        response_kind(&other)
                    );
                }
            }
        }
        Response::Error { message } => {
            anyhow::bail!("{message}");
        }
        other => {
            anyhow::bail!(
                "guard reconcile: protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }
}

/// Rebuild the guard state for a root. This removes the root from the
/// guard, which clears its persisted state and attestations from the
/// durable store, then re-adds it, triggering a fresh baseline
/// reconciliation. Use after store corruption or when the persisted
/// state is irrecoverably stale.
async fn run_rebuild(root: std::path::PathBuf, mode: String) -> anyhow::Result<ExitCode> {
    let socket = default_socket_path();
    let mut conn = match client::connect(&socket).await {
        Ok(conn) => conn,
        Err(error) => {
            anyhow::bail!(
                "guard rebuild: no compatible daemon at {} (start one with `keyhog daemon start`): {error}",
                socket.display()
            );
        }
    };
    let canonical = canonicalize_root(&root)?;
    let palette = style::for_stderr();

    // 1. Remove the root from the guard. This clears its durable store
    //    entries (root record, root gaps, attestations for that root).
    let remove_request = Request::GuardRemove {
        root: canonical.clone(),
    };
    match conn.round_trip(&remove_request).await? {
        Response::GuardRemoved => {
            eprintln!(
                "{} guard: removed root {} for rebuild",
                style::pass("OK", &palette),
                root.display()
            );
        }
        Response::Error { message } => {
            // If the root is not registered, continue with rebuild.
            if message.contains("not registered") {
                eprintln!(
                    "{} guard: root {} was not registered, proceeding with add",
                    style::warn("WARN", &palette),
                    root.display()
                );
            } else {
                anyhow::bail!("guard rebuild: remove failed: {message}");
            }
        }
        other => {
            anyhow::bail!(
                "guard rebuild: remove protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }

    // 2. Re-add the root. This triggers a fresh baseline reconciliation.
    let add_request = Request::GuardAdd {
        root: canonical.clone(),
        mode: mode.clone(),
    };
    let added_root = match conn.round_trip(&add_request).await? {
        Response::GuardAdded {
            root: ref added_root,
            state: ref add_state,
            terminal_sequence,
        } => {
            eprintln!(
                "{} guard: root {} re-registered for rebuild (state {}, sequence {})",
                style::pass("OK", &palette),
                root.display(),
                add_state,
                terminal_sequence
            );
            added_root.clone()
        }
        Response::Error { message } => {
            anyhow::bail!("guard rebuild: add failed: {message}");
        }
        other => {
            anyhow::bail!(
                "guard rebuild: add protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    };

    // 3. Wait for baseline reconciliation so rebuild reports a terminal state,
    // matching `guard add` and the exit-code docs.
    let reconcile_request = Request::GuardReconcile {
        root: added_root.clone(),
    };
    match conn.round_trip(&reconcile_request).await? {
        Response::GuardReconcileStarted { root: _ } => {
            let status_request = Request::GuardStatus { root: added_root };
            match conn.round_trip(&status_request).await? {
                Response::GuardStatusResult {
                    state,
                    findings_count,
                    terminal_sequence,
                    ..
                } => {
                    eprintln!(
                        "{} guard: rebuild complete for {}, state is {} (sequence {})",
                        style::pass("OK", &palette),
                        root.display(),
                        state,
                        terminal_sequence
                    );
                    Ok(exit_for_guard_state(&state, findings_count))
                }
                Response::Error { message } => {
                    anyhow::bail!("guard rebuild: status after reconcile: {message}");
                }
                other => {
                    anyhow::bail!(
                        "guard rebuild: status protocol mismatch (got {})",
                        response_kind(&other)
                    );
                }
            }
        }
        Response::Error { message } => {
            anyhow::bail!("guard rebuild: reconcile failed: {message}");
        }
        other => {
            anyhow::bail!(
                "guard rebuild: reconcile protocol mismatch (got {})",
                response_kind(&other)
            );
        }
    }
}

/// Map a guard root state label to the CLI exit code byte.
/// Dirty is unproven (events observed, not yet reconciled) and must not
/// report success. Exit 13 for any non-proven-clean state; exit 1 for
/// blocked / findings; exit 0 only for current with zero findings.
fn exit_code_for_guard_state(state: &str, findings_count: u64) -> u8 {
    if matches!(
        state,
        "degraded" | "stale-policy" | "stopped" | "indexing" | "dirty"
    ) {
        exit_codes::EXIT_SOURCE_FAILED
    } else if state == "blocked" || findings_count > 0 {
        exit_codes::EXIT_FINDINGS
    } else {
        exit_codes::EXIT_SUCCESS
    }
}

fn exit_for_guard_state(state: &str, findings_count: u64) -> ExitCode {
    ExitCode::from(exit_code_for_guard_state(state, findings_count))
}

/// Canonicalize a root path on the client side before sending it to the
/// daemon. The daemon must not re-resolve relative paths against its own
/// working directory. Non-UTF-8 paths are rejected with an explicit error
/// rather than silently mangled by lossy conversion.
fn canonicalize_root(root: &std::path::Path) -> anyhow::Result<String> {
    let canonical = std::fs::canonicalize(root)
        .map_err(|e| anyhow::anyhow!("guard: cannot canonicalize {}: {}", root.display(), e))?;
    canonical
        .into_os_string()
        .into_string()
        .map_err(|s| anyhow::anyhow!("guard: root path is not valid UTF-8: {:?}", s))
}

/// Resolve a root for daemon control frames when the directory may already
/// be gone (remove / status of a deleted root). Prefer canonicalize; on
/// NotFound fall back to an absolute lexical path so the daemon can still
/// match the registered key.
fn resolve_root_for_control(root: &std::path::Path) -> anyhow::Result<String> {
    match std::fs::canonicalize(root) {
        Ok(canonical) => canonical
            .into_os_string()
            .into_string()
            .map_err(|s| anyhow::anyhow!("guard: root path is not valid UTF-8: {:?}", s)),
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            let absolute = if root.is_absolute() {
                root.to_path_buf()
            } else {
                std::env::current_dir()
                    .map_err(|e| {
                        anyhow::anyhow!("guard: cannot resolve cwd for {}: {}", root.display(), e)
                    })?
                    .join(root)
            };
            absolute
                .into_os_string()
                .into_string()
                .map_err(|s| anyhow::anyhow!("guard: root path is not valid UTF-8: {:?}", s))
        }
        Err(err) => Err(anyhow::anyhow!(
            "guard: cannot resolve {}: {}",
            root.display(),
            err
        )),
    }
}
#[cfg(test)]
#[path = "../../tests/unit/subcommands_guard_exit_codes.rs"]
mod exit_code_for_guard_state_tests;

#[cfg(test)]
#[path = "../../tests/unit/subcommands_guard_resolve_root.rs"]
mod resolve_root_for_control_tests;