coralogix-cli 0.1.38

Coralogix CLI - the observability backbone for AI agents and engineering teams.
Documentation
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
use std::io::IsTerminal;

use anyhow::{bail, Result};
use inquire::validator::MinLengthValidator;
use inquire::{Confirm, Text};

const WRITE_VERBS: &[&str] = &[
    "acknowledge",
    "activate",
    "add",
    "archive",
    "assign",
    "batch",
    "bulk-delete",
    "clear-priority",
    "close",
    "create",
    "delete",
    "deploy",
    "disable",
    "enable",
    "mute",
    "overwrite",
    "remove",
    "rename",
    "reorder",
    "replace",
    "resolve",
    "set",
    "set-active",
    "set-default",
    "set-idp",
    "set-parent",
    "set-priority",
    "set-status",
    "settings-update",
    "share",
    "stop",
    "unacknowledge",
    "unarchive",
    "unassign",
    "undeploy",
    "unlink",
    "unmute",
    "update",
];

pub fn is_write_verb(name: &str) -> bool {
    WRITE_VERBS.binary_search(&name).is_ok()
}

pub fn get_leaf_subcommand_name(matches: &clap::ArgMatches) -> Option<String> {
    match matches.subcommand() {
        Some((name, sub)) => get_leaf_subcommand_name(sub).or(Some(name.to_string())),
        None => None,
    }
}

pub fn get_top_level_subcommand_name(matches: &clap::ArgMatches) -> Option<String> {
    matches.subcommand().map(|(name, _)| name.to_string())
}

/// Every subcommand name on the path to the leaf, for example
/// `["alerts", "delete"]`.
pub fn get_subcommand_path(matches: &clap::ArgMatches) -> Vec<String> {
    let mut path = Vec::new();
    let mut current = matches;
    while let Some((name, sub)) = current.subcommand() {
        path.push(name.to_string());
        current = sub;
    }
    path
}

/// The stderr line printed before a write command runs against more than one
/// profile (repeated `-p`, or `--label`), so the blast radius is visible in a
/// terminal, in logs and in an agent's session. `None` for a single profile
/// or for a read command.
pub fn multi_profile_write_notice(command_path: &[String], profiles: &[String]) -> Option<String> {
    let leaf = command_path.last()?;
    if profiles.len() < 2 || !is_write_verb(leaf) {
        return None;
    }
    Some(format!(
        "Running '{}' against {} profiles: {}",
        command_path.join(" "),
        profiles.len(),
        profiles.join(", ")
    ))
}

pub fn env_is_truthy(var: &str) -> bool {
    std::env::var(var)
        .ok()
        .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
        .unwrap_or(false)
}

pub fn enforce_read_only(verb: &str) -> Result<()> {
    enforce_read_only_with_reason(
        verb,
        "--read-only flag, CX_READ_ONLY env var, global or per-profile \
         read_only config, or an administrator policy",
    )
}

/// Block a write command and explain the specific setting that enabled
/// read-only mode.
pub fn enforce_read_only_with_reason(verb: &str, reason: &str) -> Result<()> {
    if is_write_verb(verb) {
        bail!("Write operation '{verb}' is blocked in read-only mode: {reason}.");
    }
    Ok(())
}

pub(crate) const AGENT_ENV_VARS: &[&str] = &[
    "AIDER",
    "AMAZON_Q",
    "AWS_Q_DEVELOPER",
    "CLAUDECODE",
    "CLAUDE_CODE",
    "CLINE",
    "CODEX",
    "COPILOT_AGENT",
    "CURSOR_AGENT",
    "CX_AGENT_MODE",
    "GEMINI_CODE_ASSIST",
    "GITHUB_COPILOT",
    "OPENAI_CODEX",
    "SRC_CODY",
    "WINDSURF_AGENT",
];

pub fn is_agent_mode() -> bool {
    AGENT_ENV_VARS.iter().any(|var| std::env::var(var).is_ok())
}

/// How much of the macOS Keychain the current Seatbelt sandbox allows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeychainSandbox {
    /// Not sandboxed, or the sandbox allows the Keychain service and both
    /// reads and writes of the login Keychain database.
    Unrestricted,
    /// Stored items can be read, but the login Keychain database cannot be
    /// written, so saving or deleting an item can show a Keychain dialog.
    /// Coding-agent sandboxes that limit writes to the project look like this.
    ReadOnly,
    /// The Keychain service or reads of the login Keychain database are denied.
    Denied,
}

impl KeychainSandbox {
    pub fn allows_writes(self) -> bool {
        self == Self::Unrestricted
    }
}

/// Query the current macOS Seatbelt policy for Keychain access.
/// `sandbox_check` is exported by the public System framework and queries the
/// active policy without opening Keychain, so it cannot trigger the dialog
/// that a credential read or write would.
pub fn macos_keychain_sandbox() -> KeychainSandbox {
    if let Some(value) = test_keychain_sandbox_override() {
        return value;
    }
    #[cfg(target_os = "macos")]
    {
        if mach_lookup_is_denied(c"com.apple.SecurityServer")
            || login_keychain_access_is_denied(c"file-read-data")
        {
            KeychainSandbox::Denied
        } else if login_keychain_access_is_denied(c"file-write-data") {
            KeychainSandbox::ReadOnly
        } else {
            KeychainSandbox::Unrestricted
        }
    }
    #[cfg(not(target_os = "macos"))]
    {
        KeychainSandbox::Unrestricted
    }
}

/// Whether cx must not save or delete Keychain items in this process because
/// the sandbox denies Keychain or makes it read-only.
pub fn is_macos_keychain_sandboxed() -> bool {
    !macos_keychain_sandbox().allows_writes()
}

/// Debug/test-only switch for integration tests. Release builds always query
/// Seatbelt directly, so this cannot change shipped credential behavior.
fn test_keychain_sandbox_override() -> Option<KeychainSandbox> {
    #[cfg(debug_assertions)]
    {
        std::env::var("CX_TEST_KEYCHAIN_SANDBOXED")
            .ok()
            .map(|value| keychain_sandbox_override_from(&value))
    }
    #[cfg(not(debug_assertions))]
    {
        None
    }
}

/// `read-only` selects a read-only Keychain, `1`/`true`/`yes`/`on` a denied
/// one, and any other value an unrestricted one.
#[cfg(any(debug_assertions, test))]
fn keychain_sandbox_override_from(value: &str) -> KeychainSandbox {
    match value.to_ascii_lowercase().as_str() {
        "read-only" => KeychainSandbox::ReadOnly,
        "1" | "true" | "yes" | "on" => KeychainSandbox::Denied,
        _ => KeychainSandbox::Unrestricted,
    }
}

#[cfg(target_os = "macos")]
fn mach_lookup_is_denied(service: &std::ffi::CStr) -> bool {
    sandbox_access_is_denied(unsafe {
        sandbox_check(
            std::process::id() as std::os::raw::c_int,
            c"mach-lookup".as_ptr(),
            SANDBOX_FILTER_GLOBAL_NAME | SANDBOX_CHECK_NO_REPORT,
            service.as_ptr(),
        )
    })
}

#[cfg(target_os = "macos")]
fn login_keychain_access_is_denied(operation: &std::ffi::CStr) -> bool {
    use std::os::unix::ffi::OsStrExt;

    let Some(home) = std::env::var_os("HOME") else {
        return false;
    };
    let path = std::path::Path::new(&home)
        .join("Library")
        .join("Keychains")
        .join("login.keychain-db");
    let Ok(path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
        return false;
    };

    sandbox_access_is_denied(unsafe {
        sandbox_check(
            std::process::id() as std::os::raw::c_int,
            operation.as_ptr(),
            SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT,
            path.as_ptr(),
        )
    })
}

#[cfg(target_os = "macos")]
const SANDBOX_FILTER_PATH: std::os::raw::c_int = 1;

#[cfg(target_os = "macos")]
const SANDBOX_FILTER_GLOBAL_NAME: std::os::raw::c_int = 2;

#[cfg(target_os = "macos")]
// `sandbox_check` returns `0` when allowed, `1` when denied, and `-1` on an
// invalid query or other error. Errors are deliberately treated as allowed:
// failing open preserves normal Keychain behavior rather than blocking every
// profile because detection itself failed.
#[link(name = "System", kind = "framework")]
extern "C" {
    fn sandbox_check(
        pid: std::os::raw::c_int,
        operation: *const std::os::raw::c_char,
        filter_type: std::os::raw::c_int,
        ...
    ) -> std::os::raw::c_int;
    static SANDBOX_CHECK_NO_REPORT: std::os::raw::c_int;
}

#[cfg(any(target_os = "macos", test))]
fn sandbox_access_is_denied(sandbox_check_result: std::os::raw::c_int) -> bool {
    sandbox_check_result == 1
}

/// Interactively prompt the user for a required non-empty text value.
///
/// Returns `Ok(Some(value))` when the user supplied a string in an interactive
/// terminal, and `Ok(None)` when prompting is skipped because the user opted
/// out (`yes == true`), is non-interactive (no TTY), or is running under an
/// agent. Callers should treat `None` as "fall back to the value already
/// provided by the caller / leave the field unset."
pub fn prompt_optional_text(
    label: &str,
    help: Option<&str>,
    yes: bool,
    agent_mode: bool,
) -> Result<Option<String>> {
    if yes || agent_mode || !std::io::stdin().is_terminal() {
        return Ok(None);
    }
    let mut prompt = Text::new(label).with_validator(MinLengthValidator::new(1));
    if let Some(h) = help {
        prompt = prompt.with_help_message(h);
    }
    Ok(Some(prompt.prompt()?))
}

pub fn confirm_destructive(action: &str, yes: bool, agent_mode: bool) -> Result<()> {
    if yes {
        eprintln!("[auto-approved via --yes] {action}");
        return Ok(());
    }
    if agent_mode {
        bail!(
            "This operation requires user confirmation: {action}\n\
             You are running in agent mode. Ask the user to confirm this \
             operation, then re-run with --yes to proceed."
        );
    }
    if !std::io::stdin().is_terminal() {
        bail!(
            "This operation requires confirmation but stdin is not a terminal.\n\
             Pass --yes to skip the confirmation prompt."
        );
    }
    let confirmed = Confirm::new(action).with_default(false).prompt()?;
    if !confirmed {
        bail!("Cancelled.");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn names(items: &[&str]) -> Vec<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn multi_profile_write_notice_names_command_and_every_profile() {
        let line =
            multi_profile_write_notice(&names(&["alerts", "delete"]), &names(&["a", "b", "c"]));
        assert_eq!(
            line.as_deref(),
            Some("Running 'alerts delete' against 3 profiles: a, b, c")
        );
    }

    #[test]
    fn multi_profile_write_notice_is_silent_for_one_profile_or_a_read() {
        assert!(
            multi_profile_write_notice(&names(&["alerts", "delete"]), &names(&["a"])).is_none()
        );
        assert!(
            multi_profile_write_notice(&names(&["alerts", "list"]), &names(&["a", "b"])).is_none()
        );
        assert!(multi_profile_write_notice(&[], &names(&["a", "b"])).is_none());
    }

    #[test]
    fn test_write_verbs_sorted() {
        let mut sorted = WRITE_VERBS.to_vec();
        sorted.sort();
        assert_eq!(
            WRITE_VERBS,
            &sorted[..],
            "WRITE_VERBS must be sorted for binary_search"
        );
    }

    #[test]
    fn test_write_verbs_detected() {
        let verbs = [
            "create",
            "update",
            "delete",
            "set",
            "enable",
            "disable",
            "deploy",
            "undeploy",
            "reorder",
            "overwrite",
            "remove",
            "add",
            "acknowledge",
            "resolve",
            "close",
            "assign",
            "unassign",
            "bulk-delete",
            "set-status",
            "set-idp",
            "set-active",
            "set-default",
            "set-priority",
            "clear-priority",
            "unacknowledge",
            "batch",
            "activate",
            "settings-update",
            "rename",
            "share",
            "stop",
            "archive",
            "unarchive",
        ];
        for verb in verbs {
            assert!(
                is_write_verb(verb),
                "{verb} should be detected as a write verb"
            );
        }
    }

    #[test]
    fn test_read_verbs_not_detected() {
        let verbs = [
            "list",
            "get",
            "search",
            "catalog",
            "show",
            "system",
            "sp-params",
            "validate",
            "settings",
            "deployed",
            "query",
            "test",
            "send-data-keys",
        ];
        for verb in verbs {
            assert!(
                !is_write_verb(verb),
                "{verb} should NOT be detected as a write verb"
            );
        }
    }

    #[test]
    fn test_unknown_verbs_not_detected() {
        for verb in ["foo", "bar", "", "unknown-verb"] {
            assert!(
                !is_write_verb(verb),
                "{verb} should NOT be detected as a write verb"
            );
        }
    }

    #[test]
    fn test_enforce_read_only_blocks_write_verb() {
        let err = enforce_read_only("delete").unwrap_err();
        assert!(
            err.to_string().contains("read-only mode"),
            "expected read-only error, got: {err}"
        );
    }

    #[test]
    fn test_enforce_read_only_allows_read_verb() {
        assert!(enforce_read_only("list").is_ok());
        assert!(enforce_read_only("get").is_ok());
        assert!(enforce_read_only("query").is_ok());
    }

    #[test]
    fn test_confirm_destructive_fails_in_agent_mode_without_yes() {
        let err = confirm_destructive("test action?", false, true).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("requires user confirmation"), "got: {msg}");
        assert!(msg.contains("--yes"), "should mention --yes, got: {msg}");
    }

    #[test]
    fn test_confirm_destructive_succeeds_with_yes_in_agent_mode() {
        assert!(confirm_destructive("test action?", true, true).is_ok());
    }

    #[test]
    fn test_confirm_destructive_succeeds_with_yes_no_agent() {
        assert!(confirm_destructive("test action?", true, false).is_ok());
    }

    #[test]
    fn test_prompt_optional_text_returns_none_with_yes() {
        let r = prompt_optional_text("label", None, true, false).unwrap();
        assert!(r.is_none());
    }

    #[test]
    fn test_prompt_optional_text_returns_none_in_agent_mode() {
        let r = prompt_optional_text("label", None, false, true).unwrap();
        assert!(r.is_none());
    }

    #[test]
    fn test_agent_env_vars_sorted() {
        let mut sorted = AGENT_ENV_VARS.to_vec();
        sorted.sort();
        assert_eq!(
            AGENT_ENV_VARS,
            &sorted[..],
            "AGENT_ENV_VARS must be sorted alphabetically"
        );
    }

    #[test]
    fn keychain_sandbox_check_only_rejects_denied_access() {
        assert!(!sandbox_access_is_denied(0));
        assert!(sandbox_access_is_denied(1));
        assert!(!sandbox_access_is_denied(-1));
    }

    #[test]
    fn only_an_unrestricted_keychain_allows_writes() {
        assert!(KeychainSandbox::Unrestricted.allows_writes());
        assert!(!KeychainSandbox::ReadOnly.allows_writes());
        assert!(!KeychainSandbox::Denied.allows_writes());
    }

    #[test]
    fn keychain_sandbox_test_override_selects_each_level() {
        assert_eq!(
            keychain_sandbox_override_from("read-only"),
            KeychainSandbox::ReadOnly
        );
        assert_eq!(keychain_sandbox_override_from("1"), KeychainSandbox::Denied);
        assert_eq!(
            keychain_sandbox_override_from("0"),
            KeychainSandbox::Unrestricted
        );
    }
}