Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Late Allow: the one-time grant works only in its own conversation and is dropped if the resumed turn doesn't use it

Lin (kwant bot)d91bb1f86d1f
diff --git a/src/broker/mod.rs b/src/broker/mod.rs
index 75957dbc..62bfaadf 100644
--- a/src/broker/mod.rs
+++ b/src/broker/mod.rs
@@ -36,6 +36,9 @@ pub const GRANT_TTL: std::time::Duration = std::time::Duration::from_secs(30 * 6
#[derive(Debug, Clone)]
struct Grant {
kwant_id: String,
+ /// The chat the card belonged to (thread, else channel or direct chat): the grant only
+ /// works there, not in another conversation of the same bot.
+ conversation: String,
tool_name: String,
arguments: Value,
until: std::time::Instant,
@@ -60,13 +63,15 @@ impl PermissionBroker {
}
}
- /// Lets one later call of `tool_name` with these `arguments` by this kwant run without a
- /// card (a late Allow). Lapses after [`GRANT_TTL`].
- pub async fn grant_once(&self, kwant_id: &str, tool_name: &str, arguments: &Value) {
+ /// Lets one later call of `tool_name` with these `arguments` by this kwant, in this
+ /// `conversation`, run without a card (a late Allow). Lapses after [`GRANT_TTL`], or when
+ /// [`drop_grant`](Self::drop_grant) is called because the resumed turn ended without it.
+ pub async fn grant_once(&self, kwant_id: &str, conversation: &str, tool_name: &str, arguments: &Value) {
let mut grants = self.grants.lock().await;
grants.retain(|g| g.until > std::time::Instant::now());
grants.push(Grant {
kwant_id: kwant_id.to_string(),
+ conversation: conversation.to_string(),
tool_name: tool_name.to_string(),
arguments: grant_arguments(arguments),
until: std::time::Instant::now() + GRANT_TTL,
@@ -74,12 +79,11 @@ impl PermissionBroker {
}
/// Uses up a matching [`grant_once`](Self::grant_once); false when there is none.
- pub async fn take_grant(&self, kwant_id: &str, tool_name: &str, arguments: &Value) -> bool {
+ pub async fn take_grant(&self, kwant_id: &str, conversation: &str, tool_name: &str, arguments: &Value) -> bool {
let mut grants = self.grants.lock().await;
let now = std::time::Instant::now();
grants.retain(|g| g.until > now);
- let wanted = grant_arguments(arguments);
- match grants.iter().position(|g| g.kwant_id == kwant_id && g.tool_name == tool_name && g.arguments == wanted) {
+ match Self::find_grant(&grants, kwant_id, conversation, tool_name, arguments) {
Some(i) => {
grants.remove(i);
true
@@ -88,6 +92,26 @@ impl PermissionBroker {
}
}
+ /// Forgets a [`grant_once`](Self::grant_once) the resumed turn didn't use, so the same call
+ /// later asks again. True when there was one.
+ pub async fn drop_grant(&self, kwant_id: &str, conversation: &str, tool_name: &str, arguments: &Value) -> bool {
+ let mut grants = self.grants.lock().await;
+ match Self::find_grant(&grants, kwant_id, conversation, tool_name, arguments) {
+ Some(i) => {
+ grants.remove(i);
+ true
+ }
+ None => false,
+ }
+ }
+
+ fn find_grant(grants: &[Grant], kwant_id: &str, conversation: &str, tool_name: &str, arguments: &Value) -> Option<usize> {
+ let wanted = grant_arguments(arguments);
+ grants.iter().position(|g| {
+ g.kwant_id == kwant_id && g.conversation == conversation && g.tool_name == tool_name && g.arguments == wanted
+ })
+ }
+
/// Registers a pending approval ticket and returns a receiver waiting for user choice.
pub async fn request_approval(&self, request: ApprovalRequest) -> oneshot::Receiver<ApprovalDecision> {
let (tx, rx) = oneshot::channel();
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index 62125a34..7a04daa9 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -205,7 +205,7 @@ impl ToolApprover for BrokerApprover {
return ApprovalOutcome::Allowed;
}
// The person allowed this exact call on a card its earlier turn stopped waiting for
- if self.broker.take_grant(&req.kwant_id, &req.tool_name, &req.arguments).await {
+ if self.broker.take_grant(&req.kwant_id, &self.conversation, &req.tool_name, &req.arguments).await {
tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, "ran a call the person allowed after its turn ended");
return ApprovalOutcome::Allowed;
}
@@ -327,7 +327,7 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: A
let thread_id = chat["thread_id"].as_str().map(str::to_string);
let channel_id = chat["channel_id"].as_str().map(str::to_string);
let conversation = thread_id.clone().or_else(|| channel_id.clone()).or_else(|| chat["direct_kwant_id"].as_str().map(str::to_string)).unwrap_or_else(|| kwant.id.clone());
- state.broker.grant_once(&kwant.id, &approval.tool_name, &arguments).await;
+ state.broker.grant_once(&kwant.id, &conversation, &approval.tool_name, &arguments).await;
if decision == ApprovalDecision::AlwaysAllowSession {
state.broker.allow_for_session(&kwant.id, &conversation, &approval.tool_name).await;
}
@@ -342,9 +342,14 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: A
};
let prompt = late_approval_prompt(&approval.tool_name, &arguments);
let target = kwant.clone();
+ let (broker, tool_name) = (state.broker.clone(), approval.tool_name.clone());
tokio::spawn(async move {
let _job = job;
let _ = super::routes::try_kwant_turn(&scope, &target, prompt, Default::default()).await;
+ // The grant was for this turn: unused, it must not let the same call through later
+ if broker.drop_grant(&target.id, &conversation, &tool_name, &arguments).await {
+ tracing::info!(kwant = %target.id, tool = %tool_name, "dropped a late-Allow grant the resumed turn didn't use");
+ }
});
Some(json!({"ticket_id": ticket_id, "resolved": true, "status": status, "resumed": "new_turn"}))
}
diff --git a/tests/late_approval_test.rs b/tests/late_approval_test.rs
index 50aa77b4..32f41b55 100644
--- a/tests/late_approval_test.rs
+++ b/tests/late_approval_test.rs
@@ -66,19 +66,47 @@ async fn an_unanswered_card_stays_open_and_a_late_allow_resumes_the_work() {
assert!(prompt.contains("[The person allowed a tool call you asked for earlier]"), "{prompt}");
assert!(prompt.contains("Tool: Bash"));
- // The resumed turn's same call runs once without a card (a new description is fine)
+ // The stub's resumed turn ends without making the call: its grant goes with it, so the
+ // same call later gets a card again instead of running unasked
+ wait_reply(&env, &env.a, "answer none").await;
+ wait_for("the resumed turn to end", || async { env.state.turns.active_turns().is_empty() }).await;
let a = approver(&env, Duration::from_millis(200));
let again = json!({"command": "ls LATE_ALLOW_MARK", "description": "list the files"});
- assert_eq!(tokio::time::timeout(Duration::from_secs(1), a.decide(request(&env, again.clone()))).await.unwrap(), ApprovalOutcome::Allowed);
- // Only once, and only that call
- assert_eq!(a.decide(request(&env, again)).await, ApprovalOutcome::Unanswered);
- assert_eq!(a.decide(request(&env, json!({"command": "rm -rf LATE_ALLOW_MARK"}))).await, ApprovalOutcome::Unanswered);
+ wait_for("the unused grant to be dropped", || async {
+ !env.state.broker.drop_grant(&env.a, &env.a, "Bash", &again).await
+ })
+ .await;
+ assert_eq!(a.decide(request(&env, again)).await, ApprovalOutcome::Unanswered, "an unused grant must not outlive its turn");
// An answered card can't be answered again
let (s, _) = call(&env.app, "POST", &format!("/api/approvals/{ticket}/resolve"), Some(json!({"decision": "allow_once"}))).await;
assert_eq!(s.as_u16(), 409);
}
+#[tokio::test]
+async fn a_grant_runs_once_only_in_its_own_conversation() {
+ let env = setup().await;
+ let args = json!({"command": "ls GRANT_SCOPE_MARK", "description": "list"});
+ env.state.broker.grant_once(&env.a, &env.a, "Bash", &args).await;
+ // Another conversation of the same bot can't use it
+ let elsewhere = BrokerApprover {
+ db: env.state.db.clone(),
+ broker: env.state.broker.clone(),
+ events: env.state.event_sender.clone(),
+ timeout: Duration::from_millis(200),
+ conversation: "some-other-thread".into(),
+ chat: Some(json!({"thread_id": "some-other-thread"})),
+ };
+ assert_eq!(elsewhere.decide(request(&env, args.clone())).await, ApprovalOutcome::Unanswered);
+ // Its own conversation can, once (a new description is fine), and only that call
+ let a = approver(&env, Duration::from_millis(200));
+ let again = json!({"command": "ls GRANT_SCOPE_MARK", "description": "list the files"});
+ assert_eq!(tokio::time::timeout(Duration::from_secs(1), a.decide(request(&env, again.clone()))).await.unwrap(), ApprovalOutcome::Allowed);
+ assert_eq!(a.decide(request(&env, again)).await, ApprovalOutcome::Unanswered);
+ env.state.broker.grant_once(&env.a, &env.a, "Bash", &args).await;
+ assert_eq!(a.decide(request(&env, json!({"command": "rm -rf GRANT_SCOPE_MARK"}))).await, ApprovalOutcome::Unanswered);
+}
+
#[tokio::test]
async fn a_late_deny_closes_the_card_and_starts_nothing() {
let env = setup().await;
@@ -101,7 +129,7 @@ async fn kwnt_secrets_stay_refused_even_after_a_late_allow() {
// A grant can't reach past the secret check (it runs first)
let secret = json!({"command": "cat ~/.kwnt/api-token"});
assert!(kwnt::sandbox::credentials::call_touches_kwnt_secrets(&secret, None));
- env.state.broker.grant_once(&env.a, "Bash", &secret).await;
+ env.state.broker.grant_once(&env.a, &env.a, "Bash", &secret).await;
assert_eq!(a.decide(request(&env, secret)).await, ApprovalOutcome::Denied);
}