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.

Spaces S1: refuse cross-space routine runs, keep one pre-spaces backup

Lin (kwant bot)d1cbe5c1429b
diff --git a/src/db/spaces.rs b/src/db/spaces.rs
index ba1cada3..0dae8fff 100644
--- a/src/db/spaces.rs
+++ b/src/db/spaces.rs
@@ -244,10 +244,32 @@ impl Database {
.await?;
restrict(&partial, 0o600)?;
std::fs::rename(&partial, &path)?;
+ remove_older_pre_spaces_backups(&dir, &path);
Ok(path)
}
}
+/// Removes every other `kwnt-pre-spaces-*` file once a new backup is complete. Backups are only
+/// written while the database is still before spaces, so an older one is from a start whose
+/// migration failed and is superseded by the new copy; leftover `.partial` files are cut-off
+/// copies. Without this every refused restart would leave another full copy on disk. An older
+/// backup is not reused instead: the previous release may have written to the database since.
+fn remove_older_pre_spaces_backups(dir: &Path, keep: &Path) {
+ let Ok(entries) = std::fs::read_dir(dir) else { return };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ let ours = path
+ .file_name()
+ .and_then(|n| n.to_str())
+ .is_some_and(|n| n.starts_with("kwnt-pre-spaces-") && (n.ends_with(".db") || n.ends_with(".db.partial")));
+ if ours && path != keep {
+ if let Err(e) = std::fs::remove_file(&path) {
+ tracing::warn!(file = %path.display(), error = %e, "could not remove an older pre-spaces backup");
+ }
+ }
+ }
+}
+
#[cfg(unix)]
fn restrict(path: &Path, mode: u32) -> std::io::Result<()> {
use std::os::unix::fs::PermissionsExt;
diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs
index 516e831e..54fe1f58 100644
--- a/src/server/scheduler.rs
+++ b/src/server/scheduler.rs
@@ -377,9 +377,21 @@ async fn execute(state: &AppState, routine: &RoutineRow) -> Result<Option<String
.await
.map_err(|_| "could not load the agent".to_string())?
.ok_or_else(|| "the routine's agent no longer exists".to_string())?;
+ // The API never makes a routine across spaces, but a row edited by hand must not run one
+ // space's bot in another space's chat
+ if kwant.space_id != routine.space_id {
+ return Err("the routine's agent is in another space, so it was not run".into());
+ }
if let Some(c) = &routine.channel_id {
- if state.db.get_channel(c).await.ok().flatten().is_none() {
- return Err("the routine's channel no longer exists".into());
+ let channel = state
+ .db
+ .get_channel(c)
+ .await
+ .ok()
+ .flatten()
+ .ok_or_else(|| "the routine's channel no longer exists".to_string())?;
+ if channel.space_id != routine.space_id {
+ return Err("the routine's channel is in another space, so it was not run".into());
}
}
let message = crate::db::models::NewMessage {
diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rs
index 0c50adab..f3aa8dcc 100644
--- a/tests/spaces_isolation_test.rs
+++ b/tests/spaces_isolation_test.rs
@@ -690,3 +690,69 @@ async fn a_second_general_in_a_space_is_refused_but_each_space_has_its_own() {
.await;
assert!(matches!(mixed, Err(kwnt::db::DbError::OtherSpace(_))));
}
+
+// Routines edited by hand across spaces
+
+/// Inserts a routine straight into the db, as the API refuses to make one across spaces, and
+/// runs a scheduler tick. Returns its runs once the run has finished.
+async fn tick_routine(env: &Env, id: &str, kwant_id: &str, channel_id: Option<&str>, space: &SpaceId, tag: &str) -> Vec<kwnt::db::continuity::RoutineRun> {
+ let pool = sqlx::sqlite::SqlitePoolOptions::new()
+ .connect(&format!("sqlite://{}", env.data.join("kwnt.db").display()))
+ .await
+ .unwrap();
+ sqlx::query(
+ "INSERT INTO routines (id, kwant_id, channel_id, name, instructions, schedule, enabled, next_run_at, created_at, space_id) \
+ VALUES (?, ?, ?, 'Evil', ?, '{\"type\":\"interval\",\"every_minutes\":60}', 1, '2000-01-01T00:00:00Z', '2000-01-01T00:00:00Z', ?)",
+ )
+ .bind(id)
+ .bind(kwant_id)
+ .bind(channel_id)
+ .bind(format!("REPLYTAG:{tag}"))
+ .bind(space.as_str())
+ .execute(&pool)
+ .await
+ .unwrap();
+ assert_eq!(kwnt::server::scheduler::tick(&env.state, chrono::Utc::now()).await, 1);
+ let mut runs = Vec::new();
+ wait_for("the run to finish", || {
+ let db = env.state.db.clone();
+ let id = id.to_string();
+ async move {
+ let r = db.list_routine_runs(&id, 10).await.unwrap();
+ let done = r.iter().all(|r| r.status != "running") && !r.is_empty();
+ done
+ }
+ })
+ .await;
+ runs.extend(env.state.db.list_routine_runs(id, 10).await.unwrap());
+ runs
+}
+
+#[tokio::test]
+async fn the_scheduler_does_not_run_a_routine_whose_bot_and_channel_are_in_different_spaces() {
+ let env = setup(true).await;
+ let general_a = env.general(&env.a).await;
+ let before = env.messages(&general_a).await.len();
+ let runs = tick_routine(&env, "rx_channel", &env.ada_b.id, Some(&general_a), &env.a, "xspace_channel").await;
+
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].status, "error");
+ assert!(runs[0].error.as_deref().unwrap_or("").contains("another space"), "{:?}", runs[0].error);
+ assert!(calls_with("xspace_channel").is_empty(), "B's bot never ran");
+ assert_eq!(env.messages(&general_a).await.len(), before, "nothing was posted in A's #general");
+ assert!(env.messages(&env.ada_b.id).await.is_empty());
+}
+
+#[tokio::test]
+async fn the_scheduler_does_not_run_a_direct_chat_routine_for_a_bot_in_another_space() {
+ let env = setup(true).await;
+ // A direct-chat routine filed under A whose bot is B's Ada
+ let runs = tick_routine(&env, "rx_direct", &env.ada_b.id, None, &env.a, "xspace_direct").await;
+
+ assert_eq!(runs.len(), 1);
+ assert_eq!(runs[0].status, "error");
+ assert!(runs[0].error.as_deref().unwrap_or("").contains("another space"), "{:?}", runs[0].error);
+ assert!(calls_with("xspace_direct").is_empty(), "B's bot never ran");
+ assert!(env.messages(&env.ada_b.id).await.is_empty(), "nothing was posted in B's direct chat");
+ assert!(env.messages(&env.ada_a.id).await.is_empty());
+}
diff --git a/tests/spaces_migration_test.rs b/tests/spaces_migration_test.rs
index 7cf2ff37..b4b0cd81 100644
--- a/tests/spaces_migration_test.rs
+++ b/tests/spaces_migration_test.rs
@@ -248,6 +248,35 @@ async fn failed_schema_change_rolls_back_everything_and_refuses_startup() {
assert_eq!(backups(tmp.path()).len(), 1);
}
+#[tokio::test]
+async fn repeated_failed_starts_keep_one_current_backup() {
+ let tmp = tempfile::tempdir().unwrap();
+ let pool = legacy(tmp.path()).await;
+ exec(&pool, "ALTER TABLE mcp_servers ADD COLUMN local_note TEXT").await;
+ // A copy cut off by a kill from an earlier start
+ std::fs::create_dir_all(tmp.path().join("backups")).unwrap();
+ std::fs::write(tmp.path().join("backups/kwnt-pre-spaces-20200101T000000Z.db.partial"), "cut off").unwrap();
+
+ refused_start(tmp.path()).await;
+ assert_eq!(backups(tmp.path()).len(), 1, "{:?}", backups(tmp.path()));
+ // The previous release may write in between: the next backup must hold that, not the old copy
+ exec(&pool, "INSERT INTO settings (key, value) VALUES ('written_between_starts', 'yes')").await;
+ let before = snapshot(&pool).await;
+ refused_start(tmp.path()).await;
+
+ let files = backups(tmp.path());
+ assert_eq!(files.len(), 1, "two failed starts leave one backup: {files:?}");
+ assert!(files[0].extension().is_some_and(|e| e == "db"), "{files:?}");
+ let backup = raw(&files[0]).await;
+ assert_eq!(scalar_i64(&backup, "PRAGMA user_version").await, 0);
+ assert_eq!(snapshot(&backup).await, before);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&files[0]).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+}
+
#[tokio::test]
async fn foreign_key_problems_already_in_the_data_do_not_block_it() {
let tmp = tempfile::tempdir().unwrap();