Skip to main content

lean_ctx/core/
roles.rs

1//! Role-based access control for agent governance.
2//!
3//! Roles define what tools an agent can use, shell policy, and resource limits.
4//! Resolution order: Env (`LEAN_CTX_ROLE`) -> Project `.lean-ctx/roles/` -> Global `~/.lean-ctx/roles/` -> Built-in.
5
6use serde::{Deserialize, Serialize};
7use std::collections::{HashMap, HashSet};
8use std::env;
9use std::path::{Path, PathBuf};
10use std::sync::OnceLock;
11
12static ACTIVE_ROLE_NAME: OnceLock<std::sync::Mutex<String>> = OnceLock::new();
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Role {
16    #[serde(default)]
17    pub role: RoleMeta,
18    #[serde(default)]
19    pub tools: ToolPolicy,
20    #[serde(default)]
21    pub io: IoPolicy,
22    #[serde(default)]
23    pub limits: RoleLimits,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct RoleMeta {
28    #[serde(default)]
29    pub name: String,
30    #[serde(default)]
31    pub inherits: Option<String>,
32    #[serde(default)]
33    pub description: String,
34    #[serde(default = "default_shell_policy")]
35    pub shell_policy: String,
36}
37
38impl Default for RoleMeta {
39    fn default() -> Self {
40        Self {
41            name: String::new(),
42            inherits: None,
43            description: String::new(),
44            shell_policy: default_shell_policy(),
45        }
46    }
47}
48
49fn default_shell_policy() -> String {
50    "track".to_string()
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, Default)]
54pub struct ToolPolicy {
55    #[serde(default)]
56    pub allowed: Vec<String>,
57    #[serde(default)]
58    pub denied: Vec<String>,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize)]
62pub struct RoleLimits {
63    #[serde(default = "default_context_tokens")]
64    pub max_context_tokens: usize,
65    #[serde(default = "default_shell_invocations")]
66    pub max_shell_invocations: usize,
67    #[serde(default = "default_cost_usd")]
68    pub max_cost_usd: f64,
69    #[serde(default = "default_warn_pct")]
70    pub warn_at_percent: u8,
71    #[serde(default = "default_block_pct")]
72    pub block_at_percent: u8,
73}
74
75impl Default for RoleLimits {
76    fn default() -> Self {
77        Self {
78            max_context_tokens: default_context_tokens(),
79            max_shell_invocations: default_shell_invocations(),
80            max_cost_usd: default_cost_usd(),
81            warn_at_percent: default_warn_pct(),
82            block_at_percent: default_block_pct(),
83        }
84    }
85}
86
87fn default_context_tokens() -> usize {
88    200_000
89}
90fn default_shell_invocations() -> usize {
91    100
92}
93fn default_cost_usd() -> f64 {
94    5.0
95}
96fn default_warn_pct() -> u8 {
97    80
98}
99fn default_block_pct() -> u8 {
100    // 255 = effectively never block (would need >255% budget usage)
101    // LeanCTX philosophy: always help, never block. Warnings are enough.
102    // Users can explicitly set block_at_percent: 100 in role config if they want blocking.
103    255
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize)]
107pub struct IoPolicy {
108    /// Boundary enforcement mode for sensitive I/O (warn|enforce).
109    #[serde(default = "default_boundary_mode")]
110    pub boundary_mode: String,
111    /// Allow search to ignore .gitignore and scan everything.
112    #[serde(default)]
113    pub allow_ignore_gitignore: bool,
114    /// Allow reading/indexing secret-like paths (e.g. .env, *.pem).
115    #[serde(default)]
116    pub allow_secret_paths: bool,
117    /// Enable output redaction for tool outputs (admin can disable; non-admin always on).
118    #[serde(default = "default_redact_outputs")]
119    pub redact_outputs: bool,
120    /// Allow cross-project knowledge search (default: false for non-admin roles).
121    #[serde(default)]
122    pub allow_cross_project_search: bool,
123}
124
125fn default_boundary_mode() -> String {
126    "enforce".to_string()
127}
128
129fn default_redact_outputs() -> bool {
130    true
131}
132
133impl Default for IoPolicy {
134    fn default() -> Self {
135        Self {
136            boundary_mode: default_boundary_mode(),
137            allow_ignore_gitignore: false,
138            allow_secret_paths: false,
139            redact_outputs: default_redact_outputs(),
140            allow_cross_project_search: false,
141        }
142    }
143}
144
145impl IoPolicy {
146    fn is_default(&self) -> bool {
147        self.boundary_mode == default_boundary_mode()
148            && !self.allow_ignore_gitignore
149            && !self.allow_secret_paths
150            && self.redact_outputs == default_redact_outputs()
151    }
152}
153
154impl Role {
155    pub fn is_tool_allowed(&self, tool_name: &str) -> bool {
156        if !self.tools.denied.is_empty()
157            && self.tools.denied.iter().any(|d| d == tool_name || d == "*")
158        {
159            return false;
160        }
161        if self.tools.allowed.is_empty() || self.tools.allowed.iter().any(|a| a == "*") {
162            return true;
163        }
164        self.tools.allowed.iter().any(|a| a == tool_name)
165    }
166
167    pub fn is_shell_allowed(&self) -> bool {
168        self.role.shell_policy != "deny"
169    }
170
171    pub fn allowed_tools_set(&self) -> HashSet<String> {
172        if self.tools.allowed.is_empty() || self.tools.allowed.iter().any(|a| a == "*") {
173            return HashSet::new(); // empty = all allowed
174        }
175        self.tools.allowed.iter().cloned().collect()
176    }
177}
178
179// ── Built-in roles ──────────────────────────────────────────────
180
181fn builtin_coder() -> Role {
182    Role {
183        role: RoleMeta {
184            name: "coder".into(),
185            description: "Full access for code implementation".into(),
186            shell_policy: "track".into(),
187            inherits: None,
188        },
189        tools: ToolPolicy {
190            allowed: vec!["*".into()],
191            denied: vec![],
192        },
193        io: IoPolicy::default(),
194        limits: RoleLimits {
195            max_context_tokens: 200_000,
196            max_shell_invocations: 100,
197            max_cost_usd: 5.0,
198            ..Default::default()
199        },
200    }
201}
202
203/// A role used when an inherited source view has closed or lost its authority.
204/// Returning a denying role prevents stale worker state from falling through
205/// to a more permissive process-wide active role.
206pub(crate) fn closed_source_view_role() -> Role {
207    Role {
208        role: RoleMeta {
209            name: "closed-source-view".into(),
210            inherits: None,
211            description: "closed source policy view".into(),
212            shell_policy: "deny".into(),
213        },
214        tools: ToolPolicy {
215            allowed: Vec::new(),
216            denied: vec!["*".into()],
217        },
218        io: IoPolicy::default(),
219        limits: RoleLimits {
220            max_context_tokens: 0,
221            max_shell_invocations: 0,
222            max_cost_usd: 0.0,
223            warn_at_percent: 0,
224            block_at_percent: 0,
225        },
226    }
227}
228
229fn builtin_reviewer() -> Role {
230    Role {
231        role: RoleMeta {
232            name: "reviewer".into(),
233            description: "Read-only access for code review".into(),
234            shell_policy: "track".into(),
235            inherits: None,
236        },
237        tools: ToolPolicy {
238            allowed: vec![
239                "ctx_read".into(),
240                "ctx_multi_read".into(),
241                "ctx_smart_read".into(),
242                "ctx_fill".into(),
243                "ctx_search".into(),
244                "ctx_tree".into(),
245                "ctx_graph".into(),
246                "ctx_architecture".into(),
247                "ctx_analyze".into(),
248                "ctx_diff".into(),
249                "ctx_symbol".into(),
250                "ctx_expand".into(),
251                "ctx_deps".into(),
252                "ctx_review".into(),
253                "ctx_session".into(),
254                "ctx_knowledge".into(),
255                "ctx_semantic_search".into(),
256                "ctx_overview".into(),
257                "ctx_preload".into(),
258                "ctx_metrics".into(),
259                "ctx_cost".into(),
260                "ctx_gain".into(),
261            ],
262            denied: vec!["ctx_edit".into(), "ctx_shell".into(), "ctx_execute".into()],
263        },
264        io: IoPolicy {
265            boundary_mode: "enforce".into(),
266            ..Default::default()
267        },
268        limits: RoleLimits {
269            max_context_tokens: 150_000,
270            max_shell_invocations: 0,
271            max_cost_usd: 3.0,
272            ..Default::default()
273        },
274    }
275}
276
277fn builtin_debugger() -> Role {
278    Role {
279        role: RoleMeta {
280            name: "debugger".into(),
281            description: "Debug-focused with shell access".into(),
282            shell_policy: "track".into(),
283            inherits: None,
284        },
285        tools: ToolPolicy {
286            allowed: vec!["*".into()],
287            denied: vec![],
288        },
289        io: IoPolicy::default(),
290        limits: RoleLimits {
291            max_context_tokens: 150_000,
292            max_shell_invocations: 200,
293            max_cost_usd: 5.0,
294            ..Default::default()
295        },
296    }
297}
298
299fn builtin_ops() -> Role {
300    Role {
301        role: RoleMeta {
302            name: "ops".into(),
303            description: "Infrastructure and CI/CD operations".into(),
304            shell_policy: "compress".into(),
305            inherits: None,
306        },
307        tools: ToolPolicy {
308            allowed: vec![
309                "ctx_read".into(),
310                "ctx_shell".into(),
311                "ctx_search".into(),
312                "ctx_tree".into(),
313                "ctx_session".into(),
314                "ctx_knowledge".into(),
315                "ctx_overview".into(),
316                "ctx_metrics".into(),
317                "ctx_cost".into(),
318            ],
319            denied: vec!["ctx_edit".into()],
320        },
321        io: IoPolicy::default(),
322        limits: RoleLimits {
323            max_context_tokens: 100_000,
324            max_shell_invocations: 300,
325            max_cost_usd: 3.0,
326            ..Default::default()
327        },
328    }
329}
330
331fn builtin_admin() -> Role {
332    Role {
333        role: RoleMeta {
334            name: "admin".into(),
335            description: "Unrestricted access, all tools and unlimited budgets".into(),
336            shell_policy: "track".into(),
337            inherits: None,
338        },
339        tools: ToolPolicy {
340            allowed: vec!["*".into()],
341            denied: vec![],
342        },
343        io: IoPolicy {
344            boundary_mode: "enforce".into(),
345            allow_ignore_gitignore: true,
346            allow_secret_paths: true,
347            redact_outputs: true,
348            allow_cross_project_search: true,
349        },
350        limits: RoleLimits {
351            max_context_tokens: 500_000,
352            max_shell_invocations: 500,
353            max_cost_usd: 50.0,
354            warn_at_percent: 90,
355            ..Default::default() // block_at_percent: 255 (never block)
356        },
357    }
358}
359
360fn builtin_roles() -> HashMap<String, Role> {
361    let mut m = HashMap::new();
362    m.insert("coder".into(), builtin_coder());
363    m.insert("reviewer".into(), builtin_reviewer());
364    m.insert("debugger".into(), builtin_debugger());
365    m.insert("ops".into(), builtin_ops());
366    m.insert("admin".into(), builtin_admin());
367    m
368}
369
370// ── Disk loading ────────────────────────────────────────────────
371
372fn roles_dir_global() -> Option<PathBuf> {
373    crate::core::data_dir::lean_ctx_data_dir()
374        .ok()
375        .map(|d| d.join("roles"))
376}
377
378fn roles_dir_project() -> Option<PathBuf> {
379    match crate::core::policy::runtime::REQUEST_PROJECT.try_with(|slot| slot.borrow().clone()) {
380        Ok(Some(project_root)) => {
381            let candidate = project_root.join(".lean-ctx").join("roles");
382            candidate.is_dir().then_some(candidate)
383        }
384        // An explicit unbound scope must not fall back to the process CWD.
385        Ok(None) => None,
386        Err(_) => roles_dir_project_from(None),
387    }
388}
389
390fn roles_dir_project_from(project_root: Option<&str>) -> Option<PathBuf> {
391    if let Some(root) = project_root {
392        let candidate = PathBuf::from(root).join(".lean-ctx").join("roles");
393        if candidate.is_dir() {
394            return Some(candidate);
395        }
396    }
397    let mut dir = std::env::current_dir().ok()?;
398    loop {
399        let candidate = dir.join(".lean-ctx").join("roles");
400        if candidate.is_dir() {
401            return Some(candidate);
402        }
403        if !dir.pop() {
404            break;
405        }
406    }
407    None
408}
409
410fn try_load_toml(path: &Path) -> Option<Role> {
411    let content = std::fs::read_to_string(path).ok()?;
412    toml::from_str(&content).ok()
413}
414
415fn load_role_from_disk(name: &str) -> Option<Role> {
416    if !is_valid_role_name(name) {
417        tracing::warn!(
418            "[SECURITY] Invalid role name rejected (path-traversal/special chars): {name}"
419        );
420        return None;
421    }
422
423    let filename = format!("{name}.toml");
424    if let Some(dir) = roles_dir_project() {
425        let path = dir.join(&filename);
426        if path.exists() {
427            if RESERVED_ROLE_NAMES
428                .iter()
429                .any(|r| r.eq_ignore_ascii_case(name))
430            {
431                tracing::warn!(
432                    "[SECURITY] Project-level shadowing of reserved role '{name}' ignored. \
433                     Use global ~/.lean-ctx/roles/ to customize built-in roles."
434                );
435            } else if let Some(mut r) = try_load_toml(&path) {
436                r.role.name = name.to_string();
437                return Some(r);
438            }
439        }
440    }
441    if let Some(dir) = roles_dir_global() {
442        let path = dir.join(&filename);
443        if let Some(mut r) = try_load_toml(&path) {
444            r.role.name = name.to_string();
445            return Some(r);
446        }
447    }
448    None
449}
450
451fn merge_roles(parent: &Role, child: &Role) -> Role {
452    Role {
453        role: RoleMeta {
454            name: child.role.name.clone(),
455            inherits: child.role.inherits.clone(),
456            description: if child.role.description.is_empty() {
457                parent.role.description.clone()
458            } else {
459                child.role.description.clone()
460            },
461            shell_policy: if child.role.shell_policy == default_shell_policy()
462                && parent.role.shell_policy != default_shell_policy()
463            {
464                parent.role.shell_policy.clone()
465            } else {
466                child.role.shell_policy.clone()
467            },
468        },
469        tools: if child.tools.allowed.is_empty() && child.tools.denied.is_empty() {
470            parent.tools.clone()
471        } else {
472            child.tools.clone()
473        },
474        io: if child.io.is_default() && !parent.io.is_default() {
475            parent.io.clone()
476        } else {
477            child.io.clone()
478        },
479        limits: RoleLimits {
480            max_context_tokens: child.limits.max_context_tokens,
481            max_shell_invocations: child.limits.max_shell_invocations,
482            max_cost_usd: child.limits.max_cost_usd,
483            warn_at_percent: child.limits.warn_at_percent,
484            block_at_percent: child.limits.block_at_percent,
485        },
486    }
487}
488
489fn load_role_recursive(name: &str, visited: &mut HashSet<String>) -> Option<Role> {
490    if !visited.insert(name.to_string()) {
491        tracing::warn!("[SECURITY] Circular role inheritance detected at '{name}'");
492        return None;
493    }
494    let role = load_role_from_disk(name).or_else(|| builtin_roles().remove(name))?;
495    if let Some(parent_name) = &role.role.inherits {
496        if is_privileged_role(parent_name) && roles_dir_project().is_some() {
497            let is_from_project =
498                roles_dir_project().is_some_and(|d| d.join(format!("{name}.toml")).exists());
499            if is_from_project {
500                tracing::warn!(
501                    "[SECURITY] Project-level role '{name}' inheriting from privileged \
502                     role '{parent_name}' is blocked."
503                );
504                return None;
505            }
506        }
507        if let Some(parent) = load_role_recursive(parent_name, visited) {
508            return Some(merge_roles(&parent, &role));
509        }
510    }
511    Some(role)
512}
513
514// ── Public API ──────────────────────────────────────────────────
515
516pub fn load_role(name: &str) -> Option<Role> {
517    let mut visited = HashSet::new();
518    load_role_recursive(name, &mut visited)
519}
520
521pub fn active_role_name() -> String {
522    let lock = ACTIVE_ROLE_NAME.get_or_init(|| std::sync::Mutex::new(String::new()));
523    let mut guard = lock
524        .lock()
525        .unwrap_or_else(std::sync::PoisonError::into_inner);
526
527    if guard.is_empty() {
528        let from_env = env::var("LEAN_CTX_ROLE")
529            .ok()
530            .map(|s| s.trim().to_string())
531            .filter(|s| !s.is_empty());
532        *guard = from_env.unwrap_or_else(|| "coder".to_string());
533    }
534
535    guard.clone()
536}
537
538pub fn active_role() -> Role {
539    if let Some(role) = crate::core::policy::runtime::pinned_role() {
540        return role;
541    }
542    #[cfg(test)]
543    if let Ok(Some(role)) = TEST_ACTIVE_ROLE.try_with(|slot| slot.borrow().clone()) {
544        return role;
545    }
546    let name = active_role_name();
547    load_role(&name).unwrap_or_else(builtin_coder)
548}
549
550#[cfg(test)]
551tokio::task_local! {
552    static TEST_ACTIVE_ROLE: std::cell::RefCell<Option<Role>>;
553}
554
555#[cfg(test)]
556pub(crate) fn with_test_active_role<T>(role: Role, operation: impl FnOnce() -> T) -> T {
557    TEST_ACTIVE_ROLE.sync_scope(std::cell::RefCell::new(Some(role)), operation)
558}
559
560#[cfg(test)]
561pub(crate) fn set_test_active_role(role: Role) {
562    TEST_ACTIVE_ROLE.with(|slot| *slot.borrow_mut() = Some(role));
563}
564
565/// Held by every test that changes the process-wide role with
566/// [`set_active_role`]: serializes them and restores the previous role on
567/// drop, so a switch to `reviewer` or `admin` neither races another such test
568/// nor leaks into unrelated tests. Tests that only need a role for their own
569/// thread use [`with_test_active_role`] instead.
570#[cfg(test)]
571pub(crate) struct GlobalRoleGuard {
572    previous: String,
573    _lock: std::sync::MutexGuard<'static, ()>,
574}
575
576#[cfg(test)]
577pub(crate) fn lock_global_role() -> GlobalRoleGuard {
578    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
579    let lock = LOCK
580        .lock()
581        .unwrap_or_else(std::sync::PoisonError::into_inner);
582    GlobalRoleGuard {
583        previous: active_role_name(),
584        _lock: lock,
585    }
586}
587
588#[cfg(test)]
589impl Drop for GlobalRoleGuard {
590    fn drop(&mut self) {
591        let slot = ACTIVE_ROLE_NAME.get_or_init(|| std::sync::Mutex::new(String::new()));
592        *slot
593            .lock()
594            .unwrap_or_else(std::sync::PoisonError::into_inner) = self.previous.clone();
595    }
596}
597
598/// Roles that grant elevated privileges and cannot be activated via MCP tool calls.
599/// These roles must be set via env var (`LEAN_CTX_ROLE`) or config file.
600const PRIVILEGED_ROLES: &[&str] = &["admin", "ops"];
601
602/// Reserved role names that cannot be shadowed from project-level config.
603const RESERVED_ROLE_NAMES: &[&str] = &["coder", "reviewer", "debugger", "ops", "admin"];
604
605/// Returns true if the named role has elevated privileges that require
606/// explicit configuration (env/config) rather than runtime activation.
607/// Case-insensitive comparison to prevent "Admin" bypass.
608pub fn is_privileged_role(name: &str) -> bool {
609    let lower = name.to_ascii_lowercase();
610    PRIVILEGED_ROLES.iter().any(|p| *p == lower)
611}
612
613/// Validate role name: alphanumeric, underscore, hyphen only. No path traversal.
614fn is_valid_role_name(name: &str) -> bool {
615    !name.is_empty()
616        && name.len() <= 64
617        && name
618            .chars()
619            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
620}
621
622/// Check if a merged role is effectively privileged (wildcard tools + no denials, or secret paths).
623fn is_effectively_privileged(role: &Role) -> bool {
624    let wildcard_tools =
625        role.tools.allowed.iter().any(|a| a == "*") && role.tools.denied.is_empty();
626    wildcard_tools || role.io.allow_secret_paths
627}
628
629pub fn set_active_role(name: &str) -> Result<Role, String> {
630    set_active_role_with_source(name, false)
631}
632
633/// Set active role. `from_config` = true allows privileged roles (env/config startup).
634pub fn set_active_role_with_source(name: &str, from_config: bool) -> Result<Role, String> {
635    if !is_valid_role_name(name) {
636        return Err(format!(
637            "[SECURITY] Invalid role name '{name}'. Only alphanumeric, underscore, and hyphen allowed."
638        ));
639    }
640
641    let role = load_role(name).ok_or_else(|| format!("Role '{name}' not found"))?;
642
643    if !from_config && is_privileged_role(name) {
644        return Err(format!(
645            "[SECURITY] Cannot escalate to privileged role '{name}' at runtime. \
646             Set LEAN_CTX_ROLE={name} in your environment or config to use this role."
647        ));
648    }
649
650    let is_builtin = builtin_roles().contains_key(name);
651    if !from_config && !is_builtin && is_effectively_privileged(&role) {
652        return Err(format!(
653            "[SECURITY] Cannot activate role '{name}' at runtime: it has effectively \
654             privileged permissions (wildcard tools or secret path access). \
655             Set LEAN_CTX_ROLE={name} in environment or config."
656        ));
657    }
658
659    let prev = active_role_name();
660    let lock = ACTIVE_ROLE_NAME.get_or_init(|| std::sync::Mutex::new("coder".to_string()));
661    match lock.lock() {
662        Ok(mut g) => *g = name.to_string(),
663        Err(poisoned) => *poisoned.into_inner() = name.to_string(),
664    }
665    if prev != name {
666        crate::core::events::emit_role_changed(&prev, name);
667    }
668    Ok(role)
669}
670
671pub fn list_roles() -> Vec<RoleInfo> {
672    let active = active_role_name();
673    let builtins = builtin_roles();
674    let mut seen = HashSet::new();
675    let mut result = Vec::new();
676
677    for dir in [roles_dir_project(), roles_dir_global()]
678        .into_iter()
679        .flatten()
680    {
681        if let Ok(entries) = std::fs::read_dir(&dir) {
682            for entry in entries.flatten() {
683                let path = entry.path();
684                if path.extension().is_some_and(|e| e == "toml")
685                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
686                    && seen.insert(stem.to_string())
687                    && let Some(r) = load_role(stem)
688                {
689                    result.push(RoleInfo {
690                        name: stem.to_string(),
691                        source: if dir == roles_dir_project().unwrap_or_default() {
692                            RoleSource::Project
693                        } else {
694                            RoleSource::Global
695                        },
696                        description: r.role.description.clone(),
697                        is_active: stem == active,
698                    });
699                }
700            }
701        }
702    }
703
704    for (name, r) in &builtins {
705        if seen.insert(name.clone()) {
706            result.push(RoleInfo {
707                name: name.clone(),
708                source: RoleSource::BuiltIn,
709                description: r.role.description.clone(),
710                is_active: name == &active,
711            });
712        }
713    }
714
715    result.sort_by_key(|r| r.name.clone());
716    result
717}
718
719#[derive(Debug, Clone)]
720pub struct RoleInfo {
721    pub name: String,
722    pub source: RoleSource,
723    pub description: String,
724    pub is_active: bool,
725}
726
727#[derive(Debug, Clone, PartialEq)]
728pub enum RoleSource {
729    BuiltIn,
730    Project,
731    Global,
732}
733
734impl std::fmt::Display for RoleSource {
735    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
736        match self {
737            Self::BuiltIn => write!(f, "built-in"),
738            Self::Project => write!(f, "project"),
739            Self::Global => write!(f, "global"),
740        }
741    }
742}
743
744// ── Tests ───────────────────────────────────────────────────────
745
746#[cfg(test)]
747pub mod tests {
748    use super::*;
749
750    #[test]
751    fn builtin_count() {
752        assert_eq!(builtin_roles().len(), 5);
753    }
754
755    #[test]
756    fn coder_allows_all() {
757        let r = builtin_coder();
758        assert!(r.is_tool_allowed("ctx_read"));
759        assert!(r.is_tool_allowed("ctx_edit"));
760        assert!(r.is_tool_allowed("ctx_shell"));
761        assert!(r.is_tool_allowed("anything"));
762    }
763
764    #[test]
765    fn reviewer_denies_edits() {
766        let r = builtin_reviewer();
767        assert!(r.is_tool_allowed("ctx_read"));
768        assert!(r.is_tool_allowed("ctx_review"));
769        assert!(!r.is_tool_allowed("ctx_edit"));
770        assert!(!r.is_tool_allowed("ctx_shell"));
771        assert!(!r.is_tool_allowed("ctx_execute"));
772    }
773
774    #[test]
775    fn reviewer_no_shell() {
776        let r = builtin_reviewer();
777        assert_eq!(r.limits.max_shell_invocations, 0);
778    }
779
780    #[test]
781    fn ops_denies_edit() {
782        let r = builtin_ops();
783        assert!(!r.is_tool_allowed("ctx_edit"));
784        assert!(r.is_tool_allowed("ctx_shell"));
785        assert!(r.is_shell_allowed());
786    }
787
788    #[test]
789    fn admin_unlimited() {
790        let r = builtin_admin();
791        assert!(r.is_tool_allowed("ctx_edit"));
792        assert!(r.is_tool_allowed("ctx_shell"));
793        assert_eq!(r.limits.max_context_tokens, 500_000);
794        assert_eq!(r.limits.max_cost_usd, 50.0);
795    }
796
797    #[test]
798    fn denied_overrides_allowed() {
799        let r = Role {
800            role: RoleMeta {
801                name: "test".into(),
802                ..Default::default()
803            },
804            tools: ToolPolicy {
805                allowed: vec!["*".into()],
806                denied: vec!["ctx_edit".into()],
807            },
808            io: IoPolicy::default(),
809            limits: RoleLimits::default(),
810        };
811        assert!(r.is_tool_allowed("ctx_read"));
812        assert!(!r.is_tool_allowed("ctx_edit"));
813    }
814
815    #[test]
816    fn shell_deny_policy() {
817        let r = Role {
818            role: RoleMeta {
819                name: "noshell".into(),
820                shell_policy: "deny".into(),
821                ..Default::default()
822            },
823            tools: ToolPolicy::default(),
824            io: IoPolicy::default(),
825            limits: RoleLimits::default(),
826        };
827        assert!(!r.is_shell_allowed());
828    }
829
830    #[test]
831    fn load_builtin_by_name() {
832        assert!(load_role("coder").is_some());
833        assert!(load_role("reviewer").is_some());
834        assert!(load_role("debugger").is_some());
835        assert!(load_role("ops").is_some());
836        assert!(load_role("admin").is_some());
837        assert!(load_role("nonexistent").is_none());
838    }
839
840    #[test]
841    fn merge_inherits_parent_tools() {
842        let parent = builtin_reviewer();
843        let child = Role {
844            role: RoleMeta {
845                name: "custom".into(),
846                inherits: Some("reviewer".into()),
847                description: "Custom reviewer".into(),
848                ..Default::default()
849            },
850            tools: ToolPolicy::default(),
851            io: IoPolicy::default(),
852            limits: RoleLimits {
853                max_context_tokens: 50_000,
854                ..Default::default()
855            },
856        };
857        let merged = merge_roles(&parent, &child);
858        assert_eq!(merged.role.name, "custom");
859        assert_eq!(merged.role.description, "Custom reviewer");
860        assert!(!merged.is_tool_allowed("ctx_edit"));
861        assert_eq!(merged.limits.max_context_tokens, 50_000);
862    }
863
864    #[test]
865    fn default_role_is_coder() {
866        let name = active_role_name();
867        assert!(!name.is_empty());
868    }
869
870    #[test]
871    fn list_roles_includes_builtins() {
872        let roles = list_roles();
873        let names: Vec<_> = roles.iter().map(|r| r.name.as_str()).collect();
874        assert!(names.contains(&"coder"));
875        assert!(names.contains(&"reviewer"));
876        assert!(names.contains(&"admin"));
877    }
878
879    #[test]
880    fn warn_and_block_thresholds() {
881        let r = builtin_coder();
882        assert_eq!(r.limits.warn_at_percent, 80);
883        // 255 = never block (LeanCTX philosophy: always help, never block)
884        assert_eq!(r.limits.block_at_percent, 255);
885    }
886
887    #[test]
888    fn runtime_escalation_to_admin_blocked() {
889        let _role = lock_global_role();
890        let result = set_active_role("admin");
891        assert!(
892            result.is_err(),
893            "runtime escalation to admin must be blocked"
894        );
895        let err = result.unwrap_err();
896        assert!(
897            err.contains("SECURITY"),
898            "error must indicate security: {err}"
899        );
900    }
901
902    #[test]
903    fn runtime_escalation_to_ops_blocked() {
904        let _role = lock_global_role();
905        let result = set_active_role("ops");
906        assert!(result.is_err(), "runtime escalation to ops must be blocked");
907    }
908
909    #[test]
910    fn config_escalation_to_admin_allowed() {
911        let _role = lock_global_role();
912        let result = set_active_role_with_source("admin", true);
913        assert!(
914            result.is_ok(),
915            "config-source escalation to admin must work"
916        );
917    }
918
919    #[test]
920    fn runtime_switch_to_coder_allowed() {
921        let _role = lock_global_role();
922        let result = set_active_role("coder");
923        assert!(result.is_ok(), "switching to coder must always work");
924    }
925
926    #[test]
927    fn runtime_switch_to_reviewer_allowed() {
928        let _role = lock_global_role();
929        let result = set_active_role("reviewer");
930        assert!(result.is_ok(), "switching to reviewer must always work");
931    }
932
933    #[test]
934    fn privileged_roles_detected() {
935        assert!(is_privileged_role("admin"));
936        assert!(is_privileged_role("ops"));
937        assert!(!is_privileged_role("coder"));
938        assert!(!is_privileged_role("reviewer"));
939        assert!(!is_privileged_role("debugger"));
940    }
941
942    // --- Phase 2 V2: Role name validation ---
943
944    #[test]
945    fn valid_role_names() {
946        assert!(is_valid_role_name("coder"));
947        assert!(is_valid_role_name("my-custom-role"));
948        assert!(is_valid_role_name("Role_123"));
949        assert!(is_valid_role_name("ADMIN"));
950    }
951
952    #[test]
953    fn invalid_role_names() {
954        assert!(!is_valid_role_name(""));
955        assert!(!is_valid_role_name("../../evil"));
956        assert!(!is_valid_role_name("role with spaces"));
957        assert!(!is_valid_role_name("role;drop"));
958        assert!(!is_valid_role_name("a".repeat(65).as_str()));
959    }
960
961    #[test]
962    fn case_insensitive_privileged_check() {
963        assert!(is_privileged_role("Admin"));
964        assert!(is_privileged_role("ADMIN"));
965        assert!(is_privileged_role("Ops"));
966        assert!(is_privileged_role("OPS"));
967    }
968
969    #[test]
970    fn invalid_role_name_rejected_at_set() {
971        let _role = lock_global_role();
972        let result = set_active_role("../../evil");
973        assert!(result.is_err());
974        assert!(result.unwrap_err().contains("Invalid role name"));
975    }
976
977    #[test]
978    fn effectively_privileged_role_blocked_at_runtime() {
979        let role = Role {
980            role: RoleMeta {
981                name: "sneaky".into(),
982                ..Default::default()
983            },
984            tools: ToolPolicy {
985                allowed: vec!["*".into()],
986                denied: vec![],
987            },
988            io: IoPolicy::default(),
989            limits: RoleLimits::default(),
990        };
991        assert!(
992            is_effectively_privileged(&role),
993            "wildcard + no denials = effectively privileged"
994        );
995    }
996
997    #[test]
998    fn debugger_runtime_switch_allowed() {
999        let _role = lock_global_role();
1000        let result = set_active_role("debugger");
1001        assert!(
1002            result.is_ok(),
1003            "built-in debugger must be activatable at runtime"
1004        );
1005    }
1006}