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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
kwnt token: read the token, never create one
Lin (kwant bot)9ac486776fc4
diff --git a/src/main.rs b/src/main.rsindex 656b4f52..09bd2135 100644--- a/src/main.rs+++ b/src/main.rs@@ -45,7 +45,8 @@ pub enum Commands {/// List channels stored in the local databaseChannels,- /// Print the link that signs a browser on another machine in (`--raw`: just the token, for scripts)+ /// Print the link that signs a browser on another machine in (`--raw`: just the token, for scripts).+ /// Only reads the existing token; never creates oneToken {/// Print only the token, for `Authorization: Bearer` in scripts#[arg(long)]@@ -125,11 +126,23 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {Some(Commands::Teams) => print_teams(&config).await?,Some(Commands::Channels) => print_channels(&config).await?,Some(Commands::Token { raw }) => {- let token = std::env::var("KWNT_API_TOKEN")- .ok()- .map(|t| t.trim().to_string())- .filter(|t| t.len() >= 16)- .unwrap_or_else(|| kwnt::server::auth::load_or_create(&config.data_dir));+ // Read only: a token created here (wrong user, wrong data dir) would be rejected.+ let token = match kwnt::server::auth::env_token()+ .map(Ok)+ .unwrap_or_else(|| kwnt::server::auth::read_existing(&config.data_dir))+ {+ Ok(t) => t,+ Err(e) => {+ eprintln!("kwnt token: {e}");+ eprintln!("kwnt token only reads the token of a kwant install; it never makes one.");+ eprintln!(" - Run it as the user that runs `kwnt serve`, with the same KWNT_DATA_DIR");+ eprintln!(" (systemd setup from the README: sudo cat /var/lib/kwnt/api-token).");+ eprintln!(" - Docker: docker compose exec kwnt kwnt token");+ eprintln!(" - If KWNT_API_TOKEN is set for the server, that value is the token.");+ eprintln!(" - Never started yet? `kwnt serve` creates the token on first run.");+ std::process::exit(1);+ }+ };if raw {println!("{token}");} else {diff --git a/src/server/auth.rs b/src/server/auth.rsindex aabbf362..aea6356d 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -17,7 +17,7 @@ use axum::{use serde::Deserialize;use serde_json::json;use std::net::{IpAddr, SocketAddr};-use std::path::Path;+use std::path::{Path, PathBuf};pub const COOKIE: &str = "kwnt_token";const TOKEN_FILE: &str = "api-token";@@ -66,11 +66,7 @@ impl ApiToken {.map(|o| o.trim().trim_end_matches('/').to_string()).filter(|o| !o.is_empty()).collect();- let token = std::env::var("KWNT_API_TOKEN")- .ok()- .map(|t| t.trim().to_string())- .filter(|t| t.len() >= 16)- .unwrap_or_else(|| load_or_create(&config.data_dir));+ let token = env_token().unwrap_or_else(|| load_or_create(&config.data_dir));Self {token,require,@@ -115,15 +111,53 @@ impl ApiToken {}}+/// `KWNT_API_TOKEN` when it is set to a usable token (16+ characters).+pub fn env_token() -> Option<String> {+ std::env::var("KWNT_API_TOKEN")+ .ok()+ .map(|t| t.trim().to_string())+ .filter(|t| t.len() >= 16)+}++/// Why the token file could not be read. `kwnt token` reports these instead of writing a new+/// token: one made by another user or for another data dir is a token the server rejects.+#[derive(Debug)]+pub enum ReadTokenError {+ Missing(PathBuf),+ Unreadable(PathBuf, std::io::Error),+ Invalid(PathBuf),+}++impl std::fmt::Display for ReadTokenError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Missing(p) => write!(f, "no token file at {}", p.display()),+ Self::Unreadable(p, e) => write!(f, "can't read {}: {e}", p.display()),+ Self::Invalid(p) => write!(f, "{} doesn't hold a valid token", p.display()),+ }+ }+}++impl std::error::Error for ReadTokenError {}++/// Reads `<data_dir>/api-token` without ever creating or changing it.+pub fn read_existing(data_dir: &Path) -> Result<String, ReadTokenError> {+ let path = data_dir.join(TOKEN_FILE);+ match std::fs::read_to_string(&path) {+ Ok(t) if t.trim().len() >= 16 => Ok(t.trim().to_string()),+ Ok(_) => Err(ReadTokenError::Invalid(path)),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(ReadTokenError::Missing(path)),+ Err(e) => Err(ReadTokenError::Unreadable(path, e)),+ }+}+/// Reads the token file, or writes a new random one. Falls back to an in-memory token.+/// Only the server calls this; `kwnt token` uses [`read_existing`].pub fn load_or_create(data_dir: &Path) -> String {- let path = data_dir.join(TOKEN_FILE);- if let Ok(t) = std::fs::read_to_string(&path) {- let t = t.trim().to_string();- if t.len() >= 16 {- return t;- }+ if let Ok(t) = read_existing(data_dir) {+ return t;}+ let path = data_dir.join(TOKEN_FILE);let token = format!("{}{}",uuid::Uuid::new_v4().simple(),@@ -650,6 +684,20 @@ mod tests {.collect()}+ #[test]+ fn read_existing_never_creates_a_token() {+ let dir = tempfile::tempdir().unwrap();+ assert!(matches!(read_existing(dir.path()), Err(ReadTokenError::Missing(_))));+ assert!(!dir.path().join(TOKEN_FILE).exists());++ std::fs::write(dir.path().join(TOKEN_FILE), "short\n").unwrap();+ assert!(matches!(read_existing(dir.path()), Err(ReadTokenError::Invalid(_))));+ assert_eq!(std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(), "short\n");++ let made = load_or_create(dir.path());+ assert_eq!(read_existing(dir.path()).unwrap(), made);+ }+#[test]fn token_file_is_private_and_stable() {let dir = tempfile::tempdir().unwrap();diff --git a/tests/token_cli_test.rs b/tests/token_cli_test.rsnew file mode 100644index 00000000..c1ea7344--- /dev/null+++ b/tests/token_cli_test.rs@@ -0,0 +1,51 @@+//! `kwnt token` only reads the token; it must never create one (a token made by the wrong user+//! or for the wrong data dir is one the server rejects).++use std::process::Command;++fn kwnt_token(data_dir: &std::path::Path, raw: bool) -> std::process::Output {+ let mut cmd = Command::new(env!("CARGO_BIN_EXE_kwnt"));+ cmd.arg("token").env("KWNT_DATA_DIR", data_dir).env_remove("KWNT_API_TOKEN");+ if raw {+ cmd.arg("--raw");+ }+ cmd.output().expect("run kwnt token")+}++#[test]+fn token_fails_without_a_token_file_and_creates_nothing() {+ let dir = tempfile::tempdir().unwrap();+ let out = kwnt_token(dir.path(), true);+ assert!(!out.status.success());+ assert!(out.stdout.is_empty(), "nothing printed to stdout on failure");+ let err = String::from_utf8_lossy(&out.stderr);+ assert!(err.contains("no token file at"), "{err}");+ assert!(err.contains("as the user that runs `kwnt serve`"), "{err}");+ assert!(!dir.path().join("api-token").exists());+}++#[test]+fn token_prints_the_existing_token() {+ let dir = tempfile::tempdir().unwrap();+ let tok = "abcdefghijklmnopqrstuvwxyz012345";+ std::fs::write(dir.path().join("api-token"), format!("{tok}\n")).unwrap();+ let out = kwnt_token(dir.path(), true);+ assert!(out.status.success());+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), tok);+ let link = kwnt_token(dir.path(), false);+ assert!(String::from_utf8_lossy(&link.stdout).contains(&format!("#kwnt_token={tok}")));+}++#[test]+fn token_prefers_kwnt_api_token() {+ let dir = tempfile::tempdir().unwrap();+ let out = Command::new(env!("CARGO_BIN_EXE_kwnt"))+ .args(["token", "--raw"])+ .env("KWNT_DATA_DIR", dir.path())+ .env("KWNT_API_TOKEN", "from-env-0123456789abcdef")+ .output()+ .unwrap();+ assert!(out.status.success());+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "from-env-0123456789abcdef");+ assert!(!dir.path().join("api-token").exists());+}