use std::sync::{Arc, Mutex};
use std::time::Duration;
use serde_json::json;
use crate::agents::config::AgentConfig;
use crate::agents::md_loader::project_embedded_md;
use crate::permissions::{
Decision, DenySource, HARNESS_REGISTERED_TOOLS, Outcome, PermissionBroker, PermissionContext,
PermissionDecision, PermissionEvents, PermissionGate, PermissionMode, SessionPermissions,
redact_subject,
};
use super::{agent_with_allowlist, agent_with_permissions};
#[test]
fn legacy_allowlist_denial_precedes_the_map() {
let agent = agent_with_allowlist(&["read_file"], Some("permissions:\n bash: allow\n"));
assert_eq!(
PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
Decision::Deny {
rule: "tcode_tools allowlist".to_string()
}
);
}
#[test]
fn legacy_allowlist_absent_means_every_tool() {
assert_eq!(
PermissionGate::evaluate(&AgentConfig::default(), "bash", &json!({"command": "ls"})),
Decision::Allow
);
}
#[test]
fn unmatched_tool_is_allowed() {
let agent = agent_with_permissions("permissions:\n read_file: deny\n");
assert_eq!(
PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
Decision::Allow
);
}
#[test]
fn deny_rule_produces_deny() {
let agent = agent_with_permissions("permissions:\n bash:\n \"rm *\": deny\n");
assert_eq!(
PermissionGate::evaluate(&agent, "bash", &json!({"command": "rm -rf build"})),
Decision::Deny {
rule: "bash[rm *]".to_string()
}
);
}
#[test]
fn ask_rule_produces_ask() {
let agent = agent_with_permissions("permissions:\n \"mcp__*\": ask\n");
assert_eq!(
PermissionGate::evaluate(&agent, "mcp__fixture__search", &json!({"q": "x"})),
Decision::Ask {
rule: "mcp__*".to_string()
}
);
}
fn stock_pm_agent() -> AgentConfig {
let root = trusty_common::test_harness::test_repo_root().expect("workspace root");
let content =
trusty_agents_common::agent_content::checkout_content(&root).expect("repo content");
let md = crate::assets::content::direct_agent_from(&content, "pm")
.expect("content carries pm.md")
.expect("the built-in roster carries a Direct `pm` agent");
project_embedded_md("pm", &md).expect("stock pm.md loads")
}
#[test]
fn stock_pm_agent_may_call_delegate_to_agent() {
let pm = stock_pm_agent();
let allowed = pm
.tools
.as_ref()
.and_then(|t| t.allowed.as_ref())
.expect("stock pm.md declares a tcode_tools allowlist");
assert!(
!allowed.iter().any(|t| t == "delegate_to_agent"),
"fixture premise: stock pm.md must still omit delegate_to_agent, got {allowed:?}"
);
assert_eq!(
PermissionGate::evaluate(
&pm,
"delegate_to_agent",
&json!({"agent_name": "engineer", "task": "build it"})
),
Decision::Allow
);
}
#[test]
fn stock_pm_agent_may_call_todo_write() {
let pm = stock_pm_agent();
let allowed = pm
.tools
.as_ref()
.and_then(|t| t.allowed.as_ref())
.expect("stock pm.md declares a tcode_tools allowlist");
assert!(
!allowed.iter().any(|t| t == "todo_write"),
"fixture premise: stock pm.md must still omit todo_write, got {allowed:?}"
);
assert_eq!(
PermissionGate::evaluate(
&pm,
"todo_write",
&json!({"todos": [{"content": "plan", "status": "in_progress"}]})
),
Decision::Allow
);
}
#[test]
fn harness_registered_tool_bypasses_the_legacy_allowlist() {
let agent = agent_with_allowlist(&["read_file"], None);
for tool in HARNESS_REGISTERED_TOOLS {
assert_eq!(
PermissionGate::evaluate(&agent, tool, &json!({})),
Decision::Allow,
"{tool} is harness-registered and must clear the allowlist"
);
}
}
#[test]
fn harness_exemption_does_not_widen_an_ordinary_tool() {
let agent = agent_with_allowlist(&["read_file"], None);
assert_eq!(
PermissionGate::evaluate(&agent, "bash", &json!({"command": "ls"})),
Decision::Deny {
rule: "tcode_tools allowlist".to_string()
}
);
}
#[test]
fn explicit_deny_beats_the_harness_registered_exemption() {
let agent = agent_with_allowlist(
&["read_file"],
Some("permissions:\n delegate_to_agent: deny\n"),
);
assert_eq!(
PermissionGate::evaluate(&agent, "delegate_to_agent", &json!({"agent_name": "qa"})),
Decision::Deny {
rule: "delegate_to_agent".to_string()
}
);
}
#[tokio::test]
async fn absolute_in_root_path_meets_a_relative_deny() {
let agent = agent_with_permissions("permissions:\n read_file:\n \"secrets/**\": deny\n");
let root = std::path::PathBuf::from("/Users/me/proj");
let call = json!({"path": "/Users/me/proj/secrets/x"});
let rooted = PermissionContext::headless(PermissionMode::Default).with_root(root);
assert_eq!(
gate(&rooted, agent.clone())
.resolve("read_file", &call)
.await,
Outcome::Denied {
rule: "read_file[secrets/**]".to_string(),
source: DenySource::Policy
}
);
let rootless = PermissionContext::headless(PermissionMode::Default);
assert_eq!(
gate(&rootless, agent).resolve("read_file", &call).await,
Outcome::Allow,
"with no root the gate can only judge the spelling the model wrote"
);
}
#[derive(Default)]
struct RecordingEvents {
lines: Mutex<Vec<String>>,
request_ids: Mutex<Vec<String>>,
detached: std::sync::atomic::AtomicBool,
}
impl RecordingEvents {
fn lines(&self) -> Vec<String> {
self.lines.lock().expect("lock").clone()
}
fn pending_request_id(&self) -> Option<String> {
self.request_ids.lock().expect("lock").last().cloned()
}
fn detached() -> Self {
Self {
detached: std::sync::atomic::AtomicBool::new(true),
..Self::default()
}
}
}
impl PermissionEvents for RecordingEvents {
fn permission_requested(
&self,
_session_id: &str,
request_id: &str,
agent: &str,
_agent_id: &str,
tool: &str,
subject: &str,
rule: &str,
) {
self.lines
.lock()
.expect("lock")
.push(format!("requested {agent} {tool} {subject} {rule}"));
self.request_ids
.lock()
.expect("lock")
.push(request_id.to_string());
}
fn permission_resolved(
&self,
_session_id: &str,
_request_id: &str,
_agent: &str,
_agent_id: &str,
decision: &str,
source: &str,
) {
self.lines
.lock()
.expect("lock")
.push(format!("resolved {decision} {source}"));
}
fn prompter_attached(&self, _session_id: &str) -> bool {
!self.detached.load(std::sync::atomic::Ordering::Relaxed)
}
}
fn interactive_ctx(
broker: &PermissionBroker,
session: &str,
timeout: Duration,
) -> (PermissionContext, Arc<RecordingEvents>) {
ctx_with_events(broker, session, timeout, RecordingEvents::default())
}
fn ctx_with_events(
broker: &PermissionBroker,
session: &str,
timeout: Duration,
sink: RecordingEvents,
) -> (PermissionContext, Arc<RecordingEvents>) {
let events = Arc::new(sink);
let ctx = PermissionContext {
mode: PermissionMode::Default,
timeout,
session_id: session.to_string(),
ask: Some(broker.session(session)),
events: Some(Arc::clone(&events) as Arc<dyn PermissionEvents>),
root: None,
delegator: None,
};
(ctx, events)
}
fn gate(ctx: &PermissionContext, agent: AgentConfig) -> PermissionGate {
ctx.gate_for(Arc::new(agent), "agent-1")
}
fn ask_bash() -> AgentConfig {
agent_with_permissions("permissions:\n bash: ask\n")
}
#[tokio::test]
async fn delegator_write_is_denied_before_any_rule() {
let ctx = PermissionContext::headless(PermissionMode::AllowAsks).with_delegator("t");
let delegator =
agent_with_permissions("permissions:\n write_file: allow\n edit: ask\n bash: ask\n");
let denied = Outcome::Denied {
rule: crate::permissions::gate::DELEGATOR_DENY_RULE.to_string(),
source: DenySource::Policy,
};
for (tool, args) in [
("write_file", json!({"path": "src/lib.rs", "content": "x"})),
("write_file", json!("not an object")),
("write_files", json!(null)),
("edit", json!({"path": "src/lib.rs"})),
("bash", json!({"command": "echo x > src/lib.rs"})),
] {
let outcome = gate(&ctx, delegator.clone()).resolve(tool, &args).await;
assert_eq!(outcome, denied, "{tool}({args}) must be denied");
}
assert_eq!(
gate(&ctx, delegator.clone())
.resolve("read_file", &json!({"path": "src/lib.rs"}))
.await,
Outcome::Allow,
"the lock covers writes only"
);
let mut other = delegator;
other.agent.name = "engineer".into();
assert_eq!(
gate(&ctx, other)
.resolve("write_file", &json!({"path": "src/lib.rs", "content": "x"}))
.await,
Outcome::Allow,
"a delegated engineer keeps its own write decision"
);
}
#[tokio::test]
async fn delegator_lock_ignores_case() {
let ctx = PermissionContext::headless(PermissionMode::AllowAsks).with_delegator("pm");
let mut card = agent_with_permissions("permissions:\n write_file: ask\n");
card.agent.name = "PM".into();
assert_eq!(
gate(&ctx, card)
.resolve("write_file", &json!({"path": "src/lib.rs", "content": "x"}))
.await,
Outcome::Denied {
rule: crate::permissions::gate::DELEGATOR_DENY_RULE.to_string(),
source: DenySource::Policy,
}
);
}
#[tokio::test]
async fn gate_for_agent_without_a_map_allows_everything() {
let ctx = PermissionContext::headless(PermissionMode::Default);
let outcome = gate(&ctx, AgentConfig::default())
.resolve("bash", &json!({"command": "rm -rf /"}))
.await;
assert_eq!(outcome, Outcome::Allow);
}
#[tokio::test]
async fn headless_ask_is_denied() {
let ctx = PermissionContext::headless(PermissionMode::Default);
assert_eq!(
gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await,
Outcome::Denied {
rule: "bash".to_string(),
source: DenySource::Headless
}
);
}
#[tokio::test]
async fn ask_without_an_attached_prompter_denies_immediately() {
let broker = PermissionBroker::new();
let (ctx, events) = ctx_with_events(
&broker,
"s-no-client",
Duration::from_secs(crate::permissions::DEFAULT_ASK_TIMEOUT_SECS),
RecordingEvents::detached(),
);
let gate = gate(&ctx, ask_bash());
let outcome = tokio::time::timeout(
Duration::from_millis(200),
gate.resolve("bash", &json!({"command": "ls"})),
)
.await
.expect("an ask nobody can answer must not wait out the ask timeout");
assert_eq!(
outcome,
Outcome::Denied {
rule: "bash".to_string(),
source: DenySource::Headless
}
);
assert_eq!(
outcome.message().as_deref(),
Some("denied by policy (bash): headless run")
);
assert!(
events.lines().is_empty(),
"nothing was asked, so nothing may be published: {:?}",
events.lines()
);
}
#[tokio::test]
async fn an_ask_with_no_event_sink_is_headless() {
let broker = PermissionBroker::new();
let ctx = PermissionContext {
ask: Some(broker.session("s-silent")),
..PermissionContext::headless(PermissionMode::Default)
};
let outcome = tokio::time::timeout(
Duration::from_millis(200),
gate(&ctx, ask_bash()).resolve("bash", &json!({"command": "ls"})),
)
.await
.expect("an unpublishable ask must not wait out the ask timeout");
assert_eq!(
outcome,
Outcome::Denied {
rule: "bash".to_string(),
source: DenySource::Headless
}
);
}
#[tokio::test]
async fn an_ask_on_an_unwatched_session_is_headless_while_a_sibling_is_watched() {
use crate::binding::ProjectBinding;
use crate::permissions::DEFAULT_ASK_TIMEOUT_SECS;
use crate::session::registry::SessionRegistry;
use uuid::Uuid;
let registry = Arc::new(SessionRegistry::new());
let watched = registry.create("watched".to_string(), None, ProjectBinding::None);
let headless = registry.create("headless".to_string(), None, ProjectBinding::None);
let broker = PermissionBroker::new();
let (notify, _held) = tokio::sync::mpsc::unbounded_channel();
registry
.attach(&watched.id, Uuid::new_v4(), notify)
.expect("attach must succeed");
let ctx_for = |session_id: &str| PermissionContext {
mode: PermissionMode::Default,
timeout: Duration::from_secs(DEFAULT_ASK_TIMEOUT_SECS),
session_id: session_id.to_string(),
ask: Some(broker.session(session_id)),
events: Some(Arc::clone(®istry) as Arc<dyn PermissionEvents>),
root: None,
delegator: None,
};
let agent = Arc::new(ask_bash());
let denied = tokio::time::timeout(
Duration::from_millis(200),
ctx_for(&headless.id)
.gate_for(Arc::clone(&agent), "agent-1")
.resolve("bash", &json!({"command": "ls"})),
)
.await
.expect("an unwatched session must not wait out the ask timeout");
assert_eq!(
denied,
Outcome::Denied {
rule: "bash".to_string(),
source: DenySource::Headless
}
);
let pending = tokio::time::timeout(
Duration::from_millis(200),
ctx_for(&watched.id)
.gate_for(agent, "agent-2")
.resolve("bash", &json!({"command": "ls"})),
)
.await;
assert!(
pending.is_err(),
"the watched session's ask must still be waiting for its client: {pending:?}"
);
}
#[tokio::test]
async fn allow_asks_mode_permits_an_ask() {
let ctx = PermissionContext::headless(PermissionMode::AllowAsks);
assert_eq!(
gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await,
Outcome::Allow
);
}
#[tokio::test]
async fn allow_asks_mode_emits_an_audit_event() {
let events = Arc::new(RecordingEvents::default());
let ctx = PermissionContext {
events: Some(Arc::clone(&events) as Arc<dyn PermissionEvents>),
..PermissionContext::headless(PermissionMode::AllowAsks)
};
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await;
assert_eq!(outcome, Outcome::Allow);
assert_eq!(events.lines(), vec!["resolved allow_once allow_asks"]);
}
#[tokio::test]
async fn allow_asks_mode_does_not_soften_a_deny() {
let ctx = PermissionContext::headless(PermissionMode::AllowAsks);
let agent = agent_with_permissions("permissions:\n bash: deny\n");
assert!(matches!(
gate(&ctx, agent)
.resolve("bash", &json!({"command": "ls"}))
.await,
Outcome::Denied {
source: DenySource::Policy,
..
}
));
}
#[tokio::test]
async fn timed_out_ask_is_denied() {
let broker = PermissionBroker::new();
let (ctx, events) = interactive_ctx(&broker, "s-timeout", Duration::from_millis(30));
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await;
assert_eq!(
outcome,
Outcome::Denied {
rule: "bash".to_string(),
source: DenySource::Timeout
}
);
assert_eq!(
outcome.message().as_deref(),
Some("denied by policy (bash): no decision")
);
assert_eq!(
events.lines().last().map(String::as_str),
Some("resolved deny timeout")
);
}
#[tokio::test]
async fn abandoned_request_resolves_to_deny() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-abandon", Duration::from_secs(30));
let state = broker.session("s-abandon");
let abandoning = tokio::spawn({
let events = Arc::clone(&events);
async move {
let id = wait_for_request(&events).await;
state.forget(&id);
}
});
let started = std::time::Instant::now();
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await;
abandoning.await.expect("abandoning task must not panic");
assert!(matches!(
outcome,
Outcome::Denied {
source: DenySource::Timeout,
..
}
));
assert!(
started.elapsed() < Duration::from_secs(10),
"a dropped responder must resolve at once, not wait out the timeout"
);
}
#[tokio::test]
async fn client_deny_is_denied() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-deny", Duration::from_secs(5));
let answering = answer_next_request(&broker, "s-deny", events, PermissionDecision::Deny);
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await;
answering.await.expect("answering task must not panic");
assert!(matches!(
outcome,
Outcome::Denied {
source: DenySource::Client,
..
}
));
}
#[tokio::test]
async fn ask_emits_requested_then_resolved() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-events", Duration::from_secs(5));
let answering = answer_next_request(
&broker,
"s-events",
Arc::clone(&events),
PermissionDecision::AllowOnce,
);
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls -la"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(outcome, Outcome::Allow);
assert_eq!(
events.lines(),
vec!["requested t bash ls -la bash", "resolved allow_once client"]
);
}
#[tokio::test]
async fn allow_for_session_is_remembered_for_a_later_matching_call() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-remember", Duration::from_secs(5));
let gate = gate(&ctx, ask_bash());
let answering = answer_next_request(
&broker,
"s-remember",
Arc::clone(&events),
PermissionDecision::AllowForSession {
pattern: Some("git *".to_string()),
},
);
let first = gate
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(first, Outcome::Allow);
let second = gate.resolve("bash", &json!({"command": "git diff"})).await;
assert_eq!(second, Outcome::Allow);
assert_eq!(
events.lines(),
vec![
"requested t bash git status bash",
"resolved allow_for_session client",
"resolved allow_for_session remembered",
]
);
}
#[tokio::test]
async fn remembered_grant_emits_a_resolution_event() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-remember-event", Duration::from_secs(5));
let gate = gate(&ctx, ask_bash());
let answering = answer_next_request(
&broker,
"s-remember-event",
Arc::clone(&events),
PermissionDecision::AllowForSession {
pattern: Some("git *".to_string()),
},
);
let first = gate
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(first, Outcome::Allow);
let before = events.lines().len();
assert_eq!(
gate.resolve("bash", &json!({"command": "git diff"})).await,
Outcome::Allow
);
assert_eq!(
events.lines().get(before..),
Some(["resolved allow_for_session remembered".to_string()].as_slice()),
"the remembered grant must record the call it covered"
);
}
#[tokio::test]
async fn allow_for_session_does_not_leak_across_sessions() {
let broker = Arc::new(PermissionBroker::new());
let (first, events) = interactive_ctx(&broker, "s-a", Duration::from_secs(5));
let answering = answer_next_request(
&broker,
"s-a",
events,
PermissionDecision::AllowForSession {
pattern: Some("git *".to_string()),
},
);
let granted = gate(&first, ask_bash())
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(granted, Outcome::Allow);
let (second, _events) = interactive_ctx(&broker, "s-b", Duration::from_millis(30));
let other = gate(&second, ask_bash())
.resolve("bash", &json!({"command": "git diff"}))
.await;
assert!(
matches!(
other,
Outcome::Denied {
source: DenySource::Timeout,
..
}
),
"session A's grant must not reach session B"
);
}
#[tokio::test]
async fn bare_allow_for_session_grants_only_that_subject() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-bare", Duration::from_millis(30));
let gate = gate(&ctx, ask_bash());
let answering = answer_next_request(
&broker,
"s-bare",
events,
PermissionDecision::AllowForSession { pattern: None },
);
let first = gate
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(first, Outcome::Allow);
assert_eq!(
gate.resolve("bash", &json!({"command": "git status"}))
.await,
Outcome::Allow,
"the exact same subject is covered"
);
assert!(
matches!(
gate.resolve("bash", &json!({"command": "git status --short"}))
.await,
Outcome::Denied { .. }
),
"a bare grant must not widen to a prefix match"
);
}
#[tokio::test]
async fn allow_for_session_pattern_grants_the_glob() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-glob", Duration::from_millis(30));
let gate = gate(&ctx, ask_bash());
let answering = answer_next_request(
&broker,
"s-glob",
events,
PermissionDecision::AllowForSession {
pattern: Some("*".to_string()),
},
);
let first = gate
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(first, Outcome::Allow);
assert_eq!(
gate.resolve("bash", &json!({"command": "anything at all"}))
.await,
Outcome::Allow
);
}
#[tokio::test]
async fn unusable_allow_for_session_pattern_remembers_nothing() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-badglob", Duration::from_millis(30));
let gate = gate(&ctx, ask_bash());
let answering = answer_next_request(
&broker,
"s-badglob",
events,
PermissionDecision::AllowForSession {
pattern: Some("a[".to_string()),
},
);
let first = gate
.resolve("bash", &json!({"command": "git status"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(first, Outcome::Allow);
assert!(matches!(
gate.resolve("bash", &json!({"command": "git status"}))
.await,
Outcome::Denied { .. }
));
}
#[test]
fn deny_message_names_the_rule() {
let denied = Outcome::Denied {
rule: "bash[rm *]".to_string(),
source: DenySource::Policy,
};
assert_eq!(
denied.message().as_deref(),
Some("denied by policy (bash[rm *])")
);
assert!(Outcome::Allow.message().is_none());
}
#[test]
fn broker_hands_the_same_state_back_for_one_session() {
let broker = PermissionBroker::new();
let a = broker.session("s");
assert!(Arc::ptr_eq(&a, &broker.session("s")));
assert!(!Arc::ptr_eq(&a, &broker.session("other")));
}
#[test]
fn respond_to_unknown_request_is_an_error() {
let err = SessionPermissions::default()
.respond("missing", PermissionDecision::AllowOnce)
.expect_err("an unknown request id must be rejected");
assert!(err.message.contains("missing"), "{}", err.message);
}
#[test]
fn respond_to_unknown_session_is_an_error() {
let err = PermissionBroker::new()
.respond("nope", "req", PermissionDecision::AllowOnce)
.expect_err("an unknown session must be rejected");
assert!(err.message.contains("nope"), "{}", err.message);
}
#[tokio::test]
async fn respond_resolves_the_waiting_gate() {
let broker = Arc::new(PermissionBroker::new());
let (ctx, events) = interactive_ctx(&broker, "s-resp", Duration::from_secs(5));
let answering = answer_next_request(&broker, "s-resp", events, PermissionDecision::AllowOnce);
let outcome = gate(&ctx, ask_bash())
.resolve("bash", &json!({"command": "ls"}))
.await;
answering.await.expect("answering task must not panic");
assert_eq!(outcome, Outcome::Allow);
}
#[test]
fn permission_mode_parses_allow_asks_spellings() {
for spelling in ["allow-asks", "allow_asks", "ALLOW-ASKS", " allow-asks "] {
assert_eq!(
PermissionMode::parse_lenient(spelling),
Some(PermissionMode::AllowAsks),
"{spelling}"
);
}
assert_eq!(
PermissionMode::parse_lenient("default"),
Some(PermissionMode::Default)
);
assert_eq!(PermissionMode::parse_lenient("yolo"), None);
}
#[test]
fn cli_permission_mode_outranks_the_env_var() {
assert_eq!(
PermissionMode::resolve_from(Some("default"), Some("allow-asks")),
PermissionMode::Default
);
}
#[test]
fn env_permission_mode_applies_when_no_flag_is_given() {
assert_eq!(
PermissionMode::resolve_from(None, Some("allow-asks")),
PermissionMode::AllowAsks
);
}
#[test]
fn unrecognised_permission_mode_falls_back_to_default() {
assert_eq!(
PermissionMode::resolve_from(Some("yolo"), None),
PermissionMode::Default
);
assert_eq!(
PermissionMode::resolve_from(Some("yolo"), Some("allow-asks")),
PermissionMode::AllowAsks
);
assert_eq!(
PermissionMode::resolve_from(None, Some("yolo")),
PermissionMode::Default
);
}
#[test]
fn redacts_a_lowercase_token_assignment() {
let out = redact_subject("curl -d token=abc123 https://example.test");
assert!(!out.contains("abc123"), "{out}");
assert!(out.contains("token=<redacted>"), "{out}");
}
#[test]
fn redacts_an_uppercase_env_assignment() {
let out = redact_subject("GITHUB_TOKEN=ghp_realsecret gh pr create");
assert!(!out.contains("ghp_realsecret"), "{out}");
assert!(out.contains("GITHUB_TOKEN=<redacted>"), "{out}");
assert!(out.contains("gh pr create"), "{out}");
}
#[test]
fn redacts_an_authorization_header() {
let out = redact_subject("curl -H 'Authorization: Bearer abc123' https://example.test");
assert!(!out.contains("abc123"), "{out}");
assert!(out.contains("Authorization: <redacted>"), "{out}");
}
#[test]
fn leaves_an_ordinary_command_untouched() {
let command = "cargo test -p trusty-code --no-fail-fast";
assert_eq!(redact_subject(command), command);
}
#[test]
fn bounds_the_subject_to_500_chars() {
assert_eq!(redact_subject(&"a".repeat(2_000)).chars().count(), 501);
}
async fn wait_for_request(events: &RecordingEvents) -> String {
let deadline = std::time::Instant::now() + Duration::from_secs(5);
loop {
if let Some(id) = events.pending_request_id() {
return id;
}
assert!(
std::time::Instant::now() < deadline,
"no permission request arrived within 5s"
);
tokio::time::sleep(Duration::from_millis(2)).await;
}
}
fn answer_next_request(
broker: &Arc<PermissionBroker>,
session: &str,
events: Arc<RecordingEvents>,
decision: PermissionDecision,
) -> tokio::task::JoinHandle<()> {
let broker = Arc::clone(broker);
let session = session.to_string();
tokio::spawn(async move {
let id = wait_for_request(&events).await;
broker
.respond(&session, &id, decision)
.expect("respond must succeed");
})
}