tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
//! `tirith context status|guard|label` (M8 ch1).
//!
//! - `status` — print the active context + label per provider (stable JSON).
//! - `guard on|off` — flip `context_guard_enabled` by appending/rewriting that
//!   one key in `policy.yaml` (never round-tripping the whole file).
//! - `label <provider:context> <criticality> [--scope user|repo]` — write one
//!   entry into the flat-YAML labels file, preserving existing entries.
//!
//! We never round-trip the hand-edited `policy.yaml` through serde (to keep
//! comments / ordering intact).

use std::io::Write;
use std::path::PathBuf;

use tirith_core::context_detect::{self, ContextDetectFailure, Provider, ProviderContext};
use tirith_core::policy::{self as policy_mod, Policy};

/// Allowed criticality values (case-insensitive synonyms of
/// `rules::context::is_critical_label`); we persist exactly what the operator typed.
const ALLOWED_CRITICALITIES: &[&str] = &[
    "critical",
    "production",
    "prod",
    "live",
    "p0",
    "p1",
    "p2",
    "staging",
    "dev",
    "test",
];

/// Scope for `tirith context label` writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LabelScope {
    User,
    Repo,
}

impl LabelScope {
    fn as_str(self) -> &'static str {
        match self {
            Self::User => "user",
            Self::Repo => "repo",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_lowercase().as_str() {
            "user" => Some(Self::User),
            "repo" | "project" | "workspace" => Some(Self::Repo),
            _ => None,
        }
    }
}

/// `tirith context status` — list active contexts and labels.
pub fn status(json: bool) -> i32 {
    let mut policy = Policy::discover_partial(None);
    policy.load_context_labels(None);

    let detection = context_detect::detect_all();

    if json {
        return emit_status_json(&detection, &policy);
    }

    if detection.contexts.is_empty() && detection.failures.is_empty() {
        eprintln!("tirith context status: no cloud / k8s context detected");
        eprintln!("  (configure ~/.kube/config, AWS_PROFILE, gcloud or az to populate)");
        return 0;
    }

    eprintln!("tirith context status:");
    for provider in [
        Provider::Kube,
        Provider::Aws,
        Provider::Gcp,
        Provider::Azure,
    ] {
        match (
            detection.contexts.get(&provider),
            detection.failures.get(&provider),
        ) {
            (Some(ctx), _) => {
                let label = policy
                    .context_labels
                    .get(&ctx.label_key())
                    .map(String::as_str)
                    .unwrap_or("(unlabeled)");
                // Context names and repo-controlled labels are untrusted
                // display values: scrub terminal controls / deceptive Unicode
                // before human rendering (JSON stays raw, serde-escaped).
                let context = super::sanitize_for_human_output(&ctx.context, false);
                let label = super::sanitize_for_human_output(label, false);
                eprintln!("  {:<6} {}  [label: {label}]", provider.as_str(), context,);
            }
            (None, Some(failure)) => {
                let failure = super::sanitize_for_human_output(&failure.to_string(), false);
                eprintln!("  {:<6} <error: {failure}>", provider.as_str());
            }
            (None, None) => {
                eprintln!("  {:<6} (not configured)", provider.as_str());
            }
        }
    }
    eprintln!(
        "  guard: {}  label-file (user): {}",
        if policy.context_guard_enabled {
            "ON"
        } else {
            "OFF"
        },
        policy_mod::user_context_labels_path()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "<unknown>".into()),
    );
    0
}

fn emit_status_json(detection: &context_detect::DetectionResult, policy: &Policy) -> i32 {
    #[derive(serde::Serialize)]
    struct ProviderEntry {
        provider: &'static str,
        context: Option<String>,
        label: Option<String>,
        error: Option<String>,
    }
    #[derive(serde::Serialize)]
    struct Out {
        schema_version: u32,
        guard_enabled: bool,
        user_label_file: Option<String>,
        repo_label_file: Option<String>,
        providers: Vec<ProviderEntry>,
    }

    let mut providers = Vec::new();
    for provider in [
        Provider::Kube,
        Provider::Aws,
        Provider::Gcp,
        Provider::Azure,
    ] {
        let (context, label, error) = match (
            detection.contexts.get(&provider),
            detection.failures.get(&provider),
        ) {
            (Some(ctx), _) => (
                Some(ctx.context.clone()),
                policy.context_labels.get(&ctx.label_key()).cloned(),
                None,
            ),
            (None, Some(f)) => (None, None, Some(f.to_string())),
            (None, None) => (None, None, None),
        };
        providers.push(ProviderEntry {
            provider: provider.as_str(),
            context,
            label,
            error,
        });
    }

    let out = Out {
        schema_version: 1,
        guard_enabled: policy.context_guard_enabled,
        user_label_file: policy_mod::user_context_labels_path().map(|p| p.display().to_string()),
        repo_label_file: policy_mod::repo_context_labels_path(None)
            .map(|p| p.display().to_string()),
        providers,
    };

    let mut stdout = std::io::stdout().lock();
    if serde_json::to_writer_pretty(&mut stdout, &out).is_err() || writeln!(stdout).is_err() {
        eprintln!("tirith context status: failed to write JSON output");
        return 1;
    }
    0
}

/// `tirith context guard on|off` — flip the operator switch by appending or
/// rewriting the single `context_guard_enabled` line in `policy.yaml` (never
/// round-tripping it through serde). Creates a user-config policy if none exists.
pub fn guard(action: &str, json: bool) -> i32 {
    let enable = match action {
        "on" | "enable" | "true" => true,
        "off" | "disable" | "false" => false,
        "status" => return guard_status(json),
        other => {
            eprintln!("tirith context guard: unknown action '{other}' (expected on|off|status)");
            return 2;
        }
    };

    let target_path = match resolve_policy_path_for_guard() {
        Ok(p) => p,
        Err(code) => return code,
    };

    if let Err(e) = update_policy_guard_key(&target_path, enable) {
        eprintln!(
            "tirith context guard: failed to update {}: {e}",
            target_path.display()
        );
        return 1;
    }

    if json {
        let out = serde_json::json!({
            "schema_version": 1,
            "guard_enabled": enable,
            "policy_path": target_path.display().to_string(),
        });
        let mut stdout = std::io::stdout().lock();
        if serde_json::to_writer_pretty(&mut stdout, &out).is_err() || writeln!(stdout).is_err() {
            return 1;
        }
    } else {
        eprintln!(
            "tirith context guard: {} (written to {})",
            if enable { "ON" } else { "OFF" },
            target_path.display(),
        );
    }
    0
}

fn guard_status(json: bool) -> i32 {
    let policy = Policy::discover_partial(None);
    if json {
        let out = serde_json::json!({
            "schema_version": 1,
            "guard_enabled": policy.context_guard_enabled,
            "policy_path": policy.path,
        });
        let mut stdout = std::io::stdout().lock();
        if serde_json::to_writer_pretty(&mut stdout, &out).is_err() || writeln!(stdout).is_err() {
            return 1;
        }
    } else {
        eprintln!(
            "tirith context guard: {}",
            if policy.context_guard_enabled {
                "ON"
            } else {
                "OFF"
            }
        );
    }
    0
}

fn resolve_policy_path_for_guard() -> Result<PathBuf, i32> {
    if let Some(existing) = policy_mod::discover_local_policy_path(None) {
        return Ok(existing);
    }
    // No existing policy — create one in the user config dir.
    let user = policy_mod::config_dir().ok_or_else(|| {
        eprintln!("tirith context guard: could not resolve user config dir");
        1
    })?;
    Ok(user.join("policy.yaml"))
}

/// Idempotently append-or-rewrite the `context_guard_enabled` line in a policy
/// YAML file, never touching other lines.
///
/// Write-side hardening (repo-0371): the discovered path may be a
/// repository-controlled policy, so this writer
/// - binds the containing directory and target through retained capabilities,
///   refusing symlinked/reparse directory or final components,
/// - never treats an unreadable / non-UTF-8 existing file as empty input
///   (which previously clobbered the target with only the guard key), and
/// - publishes through a 0600 atomic temp-file rename instead of truncating
///   in place.
pub(super) fn update_policy_guard_key(path: &std::path::Path, enable: bool) -> std::io::Result<()> {
    let root = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "policy path has no containing directory",
            )
        })?;
    let policy = Policy::discover_local_only(root.to_str());
    let contained =
        super::prepare_config_destination_permitted(root, path, true, &policy, true, true)?;
    let existing = read_existing_policy_for_guard(&contained, path)?;
    let new_line = format!("context_guard_enabled: {enable}");

    let mut out = String::new();
    let mut replaced = false;
    for line in existing.lines() {
        // Root-mapping keys ONLY (column zero). An indented lookalike is a
        // nested mapping entry — rewriting it at column zero would corrupt
        // the YAML and suppress the real append, the same failure shape as
        // repo-0385 in the hooks guard.
        if line.starts_with("context_guard_enabled:") {
            out.push_str(&new_line);
            out.push('\n');
            replaced = true;
        } else {
            out.push_str(line);
            out.push('\n');
        }
    }
    if !replaced {
        if !out.is_empty() && !out.ends_with('\n') {
            out.push('\n');
        }
        out.push_str(&new_line);
        out.push('\n');
    }

    // Verify BEFORE publishing: the candidate must parse and its top-level
    // `context_guard_enabled` must equal the requested value.
    verify_context_guard_effective(&out, enable)?;

    super::write_prepared_config_file_permitted(
        root,
        path,
        contained,
        out.as_bytes(),
        true,
        &policy,
        true,
    )
}

/// Parse the candidate policy and require the top-level `context_guard_enabled`
/// to equal `expected`, so a corrupt or lookalike-only document can never be
/// published as a successful guard toggle.
fn verify_context_guard_effective(candidate: &str, expected: bool) -> std::io::Result<()> {
    let parsed: serde_yaml::Value = serde_yaml::from_str(candidate).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("resulting policy would not parse as YAML: {e}"),
        )
    })?;
    let effective = parsed
        .get("context_guard_enabled")
        .and_then(serde_yaml::Value::as_bool);
    if effective == Some(expected) {
        Ok(())
    } else {
        Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "resulting policy does not have the requested top-level context_guard_enabled value",
        ))
    }
}

/// Read the existing policy text for a guard update. A missing file is empty
/// input; ANY other failure (unreadable, non-UTF-8, symlink, oversized) is an
/// error — never silently treat the target as empty and clobber it.
fn read_existing_policy_for_guard(
    contained: &tirith_core::util::ContainedAtomicFile,
    path: &std::path::Path,
) -> std::io::Result<String> {
    use tirith_core::util::OpenRegularError;
    const GUARD_POLICY_READ_CAP: u64 = 1024 * 1024;
    match contained.read_capped(GUARD_POLICY_READ_CAP) {
        Ok(bytes) => String::from_utf8(bytes).map_err(|_| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "refusing to update {}: existing policy is not valid UTF-8",
                    path.display()
                ),
            )
        }),
        Err(OpenRegularError::NotFound) => Ok(String::new()),
        Err(OpenRegularError::NotRegularFile) => Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            format!(
                "refusing to update {}: not a regular file (symlink?)",
                path.display()
            ),
        )),
        Err(OpenRegularError::TooLarge) => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("refusing to update {}: exceeds 1 MiB", path.display()),
        )),
        Err(OpenRegularError::Io(e)) => Err(e),
    }
}

/// `tirith context label <provider:context> <criticality> [--scope user|repo]`.
pub fn label(label_key: &str, criticality: &str, scope: LabelScope, json: bool) -> i32 {
    if !label_key.contains(':') {
        eprintln!(
            "tirith context label: '{label_key}' is not a valid 'provider:context' key (e.g. kube:prod-us-east)"
        );
        return 2;
    }
    let (provider_str, ctx_part) = match label_key.split_once(':') {
        Some(parts) => parts,
        None => unreachable!("contains ':' checked above"),
    };
    if Provider::parse(provider_str).is_none() {
        eprintln!(
            "tirith context label: unknown provider '{provider_str}' (expected one of: kube, aws, gcp, azure)"
        );
        return 2;
    }
    if ctx_part.is_empty() {
        eprintln!("tirith context label: context name is empty after the colon");
        return 2;
    }

    let criticality_norm = criticality.trim().to_lowercase();
    if !ALLOWED_CRITICALITIES.iter().any(|c| *c == criticality_norm) {
        eprintln!(
            "tirith context label: '{criticality}' is not a known criticality (expected one of: {}; case-insensitive)",
            ALLOWED_CRITICALITIES.join(", "),
        );
        return 2;
    }

    let target_path = match scope {
        LabelScope::User => match policy_mod::user_context_labels_path() {
            Some(p) => p,
            None => {
                eprintln!("tirith context label: could not resolve user config dir");
                return 1;
            }
        },
        LabelScope::Repo => match policy_mod::repo_context_labels_path(None) {
            Some(p) => p,
            None => {
                eprintln!("tirith context label: --scope repo requires running inside a git repo");
                return 1;
            }
        },
    };

    let policy = Policy::discover_local_only(
        target_path
            .parent()
            .and_then(std::path::Path::parent)
            .and_then(std::path::Path::to_str),
    );
    if let Err(e) =
        super::write_context_labels_permitted(&target_path, &[(label_key, criticality)], &policy)
    {
        eprintln!(
            "tirith context label: failed to write {}: {e}",
            target_path.display()
        );
        return 1;
    }

    if json {
        let out = serde_json::json!({
            "schema_version": 1,
            "scope": scope.as_str(),
            "path": target_path.display().to_string(),
            "label_key": label_key,
            "criticality": criticality,
        });
        let mut stdout = std::io::stdout().lock();
        if serde_json::to_writer_pretty(&mut stdout, &out).is_err() || writeln!(stdout).is_err() {
            return 1;
        }
    } else {
        eprintln!(
            "tirith context label: {label_key} -> {criticality} (scope={}, file={})",
            scope.as_str(),
            target_path.display(),
        );
    }
    0
}

// Silence unused-import warnings under cfg combinations.
#[allow(dead_code)]
fn _silence_unused(_pc: &ProviderContext, _f: &ContextDetectFailure) {}

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

    #[test]
    fn label_scope_parse() {
        assert_eq!(LabelScope::parse("user"), Some(LabelScope::User));
        assert_eq!(LabelScope::parse("USER"), Some(LabelScope::User));
        assert_eq!(LabelScope::parse("repo"), Some(LabelScope::Repo));
        assert_eq!(LabelScope::parse("workspace"), Some(LabelScope::Repo));
        assert_eq!(LabelScope::parse("invalid"), None);
    }

    #[test]
    fn update_policy_guard_key_creates_file() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.yaml");
        update_policy_guard_key(&path, true).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("context_guard_enabled: true"));
    }

    #[test]
    fn update_policy_guard_key_replaces_existing() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.yaml");
        std::fs::write(
            &path,
            "paranoia: 2\ncontext_guard_enabled: true\nfail_mode: open\n",
        )
        .unwrap();
        update_policy_guard_key(&path, false).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("context_guard_enabled: false"));
        assert!(content.contains("paranoia: 2"));
        assert!(content.contains("fail_mode: open"));
        assert!(!content.contains("context_guard_enabled: true"));
    }

    #[test]
    fn update_policy_guard_key_appends_when_missing() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.yaml");
        std::fs::write(&path, "paranoia: 2\n").unwrap();
        update_policy_guard_key(&path, true).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("paranoia: 2"));
        assert!(content.contains("context_guard_enabled: true"));
    }

    #[test]
    fn update_policy_guard_key_ignores_indented_lookalike() {
        // An indented nested-mapping lookalike must not be rewritten at column
        // zero; the real root key is appended and the document stays valid.
        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.yaml");
        std::fs::write(
            &path,
            "custom_rule:\n  context_guard_enabled: false\n  other: 1\n",
        )
        .unwrap();
        update_policy_guard_key(&path, true).unwrap();
        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("  context_guard_enabled: false"));
        let top_level = content
            .lines()
            .filter(|l| l.starts_with("context_guard_enabled:"))
            .count();
        assert_eq!(top_level, 1);
        let parsed: serde_yaml::Value = serde_yaml::from_str(&content).unwrap();
        assert_eq!(
            parsed
                .get("context_guard_enabled")
                .and_then(|v| v.as_bool()),
            Some(true)
        );
    }

    #[cfg(unix)]
    #[test]
    fn update_policy_guard_key_refuses_symlink_target() {
        // Regression: repo-0371 — a repository-controlled policy.yaml symlink
        // must not turn the guard update into an arbitrary-file rewrite.
        let dir = tempdir().unwrap();
        let outside = dir.path().join("outside.txt");
        std::fs::write(&outside, "do not touch\n").unwrap();
        let link = dir.path().join("policy.yaml");
        std::os::unix::fs::symlink(&outside, &link).unwrap();
        let err = update_policy_guard_key(&link, true).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput);
        assert_eq!(std::fs::read_to_string(&outside).unwrap(), "do not touch\n");
    }

    #[test]
    fn update_policy_guard_key_refuses_non_utf8_existing() {
        // Regression: repo-0371 — non-UTF-8 content must not be treated as
        // empty and clobbered with only the guard key.
        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.yaml");
        std::fs::write(&path, [0xff, 0xfe, 0x00, 0x01]).unwrap();
        let err = update_policy_guard_key(&path, true).unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(
            std::fs::read(&path).unwrap(),
            vec![0xff, 0xfe, 0x00, 0x01],
            "target must be left untouched"
        );
    }

    #[test]
    fn status_sanitizes_untrusted_fields() {
        // Regression: repo-0372 — context names / labels must not carry
        // terminal control sequences into human status output.
        let s = super::super::sanitize_for_human_output(
            "aws:default\u{1b}]52;c;SGFja2Vk\u{7}\u{202e}",
            false,
        );
        assert!(!s.contains('\u{1b}'));
        assert!(!s.contains('\u{202e}'));
    }
}