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.

Person-only routes don't ask for the token from this machine

Lin (kwant bot)f00323fc91c4
diff --git a/docs/bot-actions.md b/docs/bot-actions.md
index 1ae0bc67..1cc01f1f 100644
--- a/docs/bot-actions.md
+++ b/docs/bot-actions.md
@@ -120,7 +120,7 @@ Suggested buttons:
- 409 if it isn't applied, if a newer applied change to the same target exists ("undo the newer change first: …"), or if it can't be put back safely (for example, a bot that already has history, or a channel with messages).
- `POST /api/bot-actions/:id/confirm` and `POST /api/bot-actions/:id/decline`: only for pending actions; 409 otherwise.
- All three return **403** for a turn token (self tools or MCP session) or any non-API bearer.
-- Undo also needs the API token from this machine (401 `{person_only:true}` without it), because undoing a bot or channel deletes its saved passwords. The same holds for `POST /api/imports/:id/undo`, `DELETE /api/kwants/:id` and `DELETE /api/teams/:id`.
+- Undo is person-only: a turn token gets 403, and from another machine (or with `KWNT_REQUIRE_TOKEN=always`) it needs the API token (401 `{person_only:true}` without it), because undoing a bot or channel deletes its saved passwords. The same holds for `POST /api/imports/:id/undo`, `DELETE /api/kwants/:id` and `DELETE /api/teams/:id`.
- After a change, the card's meta is updated and SSE sends `bot_action_updated { action }`. That event is routed to the space and the chat context (channel, direct chat or thread).
## Hiring
diff --git a/docs/camera-to-completed.md b/docs/camera-to-completed.md
index 91b32028..57f1c3ef 100644
--- a/docs/camera-to-completed.md
+++ b/docs/camera-to-completed.md
@@ -9,7 +9,7 @@ sent: the draft is copy or `mailto:` only. The code is `src/documents/`, `src/db
## API
-The person only. The auth middleware lists `/api/documents/*` and `/api/zombie/*` as person-only: no token is 401, a bot's turn
+The person only. The auth middleware lists `/api/documents/*` and `/api/zombie/*` as person-only: no token is 401 from another machine (passes on loopback unless `KWNT_REQUIRE_TOKEN=always`), a bot's turn
token or a wrong token 403.
| route | does |
diff --git a/docs/llm-profiles.md b/docs/llm-profiles.md
index 19a4c107..4b5a9747 100644
--- a/docs/llm-profiles.md
+++ b/docs/llm-profiles.md
@@ -72,7 +72,14 @@ Get the token with `kwnt token` (Docker: `docker compose exec kwnt kwnt token`).
HttpOnly, SameSite=Strict cookie for a year, and clears the address bar. Scripts can send
`Authorization: Bearer <token>` instead.
-`KWNT_REQUIRE_TOKEN=always` requires the token for local requests too; `never` turns the check
+Person-only routes (saved passwords and the vault, answering approval cards, the approvals switch,
+deleting a bot or team, undo, Loose ends, Parallel Universe, letters) refuse a bot's turn token, or
+any bearer that isn't the API token, with 403 from anywhere. From another machine they need the API
+token (401 `{person_only:true}`); from this machine they don't, so the person on it is never asked.
+A bot with a shell here could call them with a bare `curl`, but it could also read the token file.
+
+`KWNT_REQUIRE_TOKEN=always` requires the token for local requests too, person-only routes included
+(the strict setup); `never` turns the check
off (only behind your own authentication). Always open: `/api/health`, `/api/auth/*`, the MCP
OAuth callback and the MCP endpoints, which carry their own per-turn tokens.
diff --git a/docs/parallel-universe.md b/docs/parallel-universe.md
index 57a30269..ba72ea6d 100644
--- a/docs/parallel-universe.md
+++ b/docs/parallel-universe.md
@@ -71,7 +71,7 @@ measured: [verified Figure], cost: estimate|speculation Figure, notes: [{criteri
when prices are stale, when currencies differ, and when options failed.
- The cost is computed when you read the report, so a price goes stale over time.
-## API (person-only: no token 401, bot or wrong token 403)
+## API (person-only: no token 401 from another machine, bot or wrong token 403)
- `GET/POST /api/parallel/scenarios`, `GET/PUT/DELETE /api/parallel/scenarios/:id`. A body that fails validation gets a 400 `{error}`.
- `GET /api/parallel/prices` returns `{prices, stale_after_days}`.
diff --git a/docs/saved-passwords.md b/docs/saved-passwords.md
index 64f902f1..419ea3e4 100644
--- a/docs/saved-passwords.md
+++ b/docs/saved-passwords.md
@@ -37,7 +37,7 @@ With Bitwarden, the API token alone doesn't show a password: that needs the mast
- the UI shows "Locked" until the person unlocks it again.
- Only items in the `kwnt` folder, named `kwnt · <host>` and carrying the custom field `kwnt-owner`, are used. Organisation items, trashed items and items in other folders are never read.
- Showing a password needs the master password, not only the API token. The token sits in kwnt's data folder, where a bot with approvals off can read it. Five wrong master passwords in a row lock the vault.
-- Every vault route is person-only. A bot's turn token gets 403; no token gets 401. Deleting a bot or team and undoing a bot action or import are person-only too, since they delete saved passwords.
+- Every vault route is person-only. A bot's turn token gets 403; no token gets 401 from another machine (or anywhere with `KWNT_REQUIRE_TOKEN=always`) and passes from this one. Deleting a bot or team and undoing a bot action or import are person-only too, since they delete saved passwords.
**Known gap (open, accepted 2026-10-20):** autofill stays on while approvals are off; Oleks decided this. Chrome's DevTools port listens on loopback without authentication, so with approvals off a bot with a shell can attach to it and read a field kwnt has just filled. This holds for both the built-in store and Bitwarden, because the leak is in the browser, not the store. Planned fix, on its own branch: start Chrome with `--remote-debugging-pipe` so there is no port to attach to.
diff --git a/docs/zombie-hunter.md b/docs/zombie-hunter.md
index 1615a329..02ffcc5f 100644
--- a/docs/zombie-hunter.md
+++ b/docs/zombie-hunter.md
@@ -81,7 +81,7 @@ when the queue is empty. Each review is recorded (`GET /api/zombie/reviews`).
(tested). The quote lives only in `evidence`.
- Retention: `retention_days` (90) after a case is closed or dismissed, it is wiped down to its
dedupe key, so a dismissed case stays dismissed without keeping its text.
-- The API is the person's only: no token → 401, a bot's turn token → 403 (all 18 method/route
+- The API is the person's only: no token from another machine → 401, a bot's turn token → 403 (all 18 method/route
pairs are tested).
## API
diff --git a/src/server/attachments.rs b/src/server/attachments.rs
index 6fddb85f..0a3ac706 100644
--- a/src/server/attachments.rs
+++ b/src/server/attachments.rs
@@ -14,11 +14,12 @@ use crate::db::models::{MessageExtra, NewMessage};
use crate::drivers::events::RuntimeEvent;
use axum::{
body::Body,
- extract::{Path, Query, Request, State},
+ extract::{ConnectInfo, Path, Query, Request, State},
http::{header, HeaderMap, HeaderValue, StatusCode},
response::{IntoResponse, Response},
Json,
};
+use std::net::SocketAddr;
use futures::StreamExt;
use serde::Deserialize;
use serde_json::{json, Value};
@@ -332,11 +333,11 @@ pub struct ListQuery {
}
/// `GET /api/attachments?context_id=`: a chat's files, newest first.
-pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>, headers: HeaderMap) -> Response {
+pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>, peer: Option<ConnectInfo<SocketAddr>>, headers: HeaderMap) -> Response {
let Some(ctx) = q.context_id.filter(|c| !c.is_empty()) else {
return error(StatusCode::BAD_REQUEST, "context_id is required");
};
- if let Err(r) = letter_guard(&state, &headers, Some(&ctx)).await {
+ if let Err(r) = letter_guard(&state, &headers, peer, Some(&ctx)).await {
return r;
}
match state.db.list_attachments_in(&ctx, 200).await {
@@ -346,21 +347,21 @@ pub async fn list(State(state): State<AppState>, Query(q): Query<ListQuery>, hea
}
/// A letter's pages (`crate::documents`, context `document:<case id>`) are the person's only:
-/// a bot's turn token gets 403 here too, and no token 401 (a bot's shell on this machine could
-/// otherwise fetch them with a bare `curl`).
+/// a bot's turn token gets 403 here too, and no token 401 where `auth::person_only` routes need
+/// the token (from another machine, or anywhere with `KWNT_REQUIRE_TOKEN=always`).
#[allow(clippy::result_large_err)]
-async fn letter_guard(state: &AppState, headers: &HeaderMap, context_id: Option<&str>) -> Result<(), Response> {
+async fn letter_guard(state: &AppState, headers: &HeaderMap, peer: Option<ConnectInfo<SocketAddr>>, context_id: Option<&str>) -> Result<(), Response> {
if context_id.is_some_and(|c| c.starts_with("document:")) {
super::mcp_suggest::refuse_agent_tokens(state, headers, "only the person can see their letters").await?;
- super::auth::require_person_token(state, headers)?;
+ super::auth::require_person_token(state, headers, peer.map(|c| c.0.ip()))?;
}
Ok(())
}
-pub async fn get(State(state): State<AppState>, Path(id): Path<String>, headers: HeaderMap) -> Response {
+pub async fn get(State(state): State<AppState>, Path(id): Path<String>, peer: Option<ConnectInfo<SocketAddr>>, headers: HeaderMap) -> Response {
match load(&state, &id).await {
Some(a) => {
- if let Err(r) = letter_guard(&state, &headers, a.context_id.as_deref()).await {
+ if let Err(r) = letter_guard(&state, &headers, peer, a.context_id.as_deref()).await {
return r;
}
Json(view(&a)).into_response()
@@ -396,7 +397,7 @@ pub async fn content(State(state): State<AppState>, Path(id): Path<String>, Quer
let Some(a) = load(&state, &id).await else {
return StatusCode::NOT_FOUND.into_response();
};
- if let Err(r) = letter_guard(&state, req.headers(), a.context_id.as_deref()).await {
+ if let Err(r) = letter_guard(&state, req.headers(), req.extensions().get::<ConnectInfo<SocketAddr>>().copied(), a.context_id.as_deref()).await {
return r;
}
let Some(path) = blob_path(&root(&state), &a.sha256).filter(|p| p.is_file()) else {
diff --git a/src/server/auth.rs b/src/server/auth.rs
index f1e8db02..730148ca 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -184,9 +184,9 @@ fn exempt(path: &str) -> bool {
}
/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, Loose ends and Parallel Universe, the
-/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). They need the token from this machine too, because a bot's shell runs on
-/// this machine and would otherwise reach them with a bare `curl`. Turn tokens are refused by the
-/// handlers themselves (403).
+/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). A bot's turn token (or any
+/// bearer that isn't the API token) is refused with 403 everywhere. From another machine they need the API token (401);
+/// from this machine they don't, unless `KWNT_REQUIRE_TOKEN=always` (`person_token_needed`).
pub fn person_only(method: &Method, path: &str) -> bool {
let segs: Vec<&str> = path.trim_end_matches('/').split('/').collect();
match segs.as_slice() {
@@ -258,16 +258,25 @@ fn needs_token(api: &ApiToken, headers: &HeaderMap, peer: Option<IpAddr>) -> boo
}
}
+/// Whether a person-only route needs the API token for this request. Not from this machine:
+/// the person there shouldn't be asked for a token to answer their own approval cards. A bot's
+/// shell there could reach these routes with a bare `curl`, but it could read the token file just
+/// as well; `KWNT_REQUIRE_TOKEN=always` asks for the token on loopback too.
+fn person_token_needed(api: &ApiToken, headers: &HeaderMap, peer: Option<IpAddr>) -> bool {
+ api.require != Require::Never && needs_token(api, headers, peer)
+}
+
fn deny(status: StatusCode, msg: &str) -> Response {
(status, Json(json!({ "error": msg }))).into_response()
}
/// 401 for a person-only route without the token: `{error, person_only: true}`.
/// For a handler guarding something person-only that `person_only` can't see from the path (a
-/// letter's pages under `/api/attachments`): the API token must be presented, unless tokens are off.
+/// letter's pages under `/api/attachments`): the API token must be presented where
+/// `person_token_needed` says so.
#[allow(clippy::result_large_err)]
-pub(super) fn require_person_token(state: &AppState, headers: &HeaderMap) -> Result<(), Response> {
- if state.api_token.require != Require::Never && !presented_token_ok(&state.api_token, headers) {
+pub(super) fn require_person_token(state: &AppState, headers: &HeaderMap, peer: Option<IpAddr>) -> Result<(), Response> {
+ if person_token_needed(&state.api_token, headers, peer) && !presented_token_ok(&state.api_token, headers) {
return Err(person_token_required());
}
Ok(())
@@ -311,10 +320,11 @@ pub async fn guard(State(state): State<AppState>, req: Request, next: Next) -> R
{
deny(StatusCode::UNAUTHORIZED, "API token required")
} else if api.require != Require::Never && person_only(req.method(), &path) {
- // A bot's turn token (or any bearer that isn't the API token) is a 403; no token a 401
+ // A bot's turn token (or any bearer that isn't the API token) is a 403, from anywhere;
+ // no token a 401 where the token is needed
if let Err(refused) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person can do this").await {
refused
- } else if !presented_token_ok(&api, &headers) {
+ } else if person_token_needed(&api, &headers, peer) && !presented_token_ok(&api, &headers) {
person_token_required()
} else {
next.run(req).await
@@ -359,8 +369,8 @@ pub async fn status(State(state): State<AppState>, req: Request) -> Response {
let required = needs_token(&state.api_token, headers, peer);
let has_token = presented_token_ok(&state.api_token, headers);
let authenticated = !required || has_token;
- // Person-only actions (passwords, approvals) need the token even where the rest doesn't
- let person_required = state.api_token.require != Require::Never;
+ // Person-only actions (passwords, approvals) need it from another machine, or with `always`
+ let person_required = person_token_needed(&state.api_token, headers, peer);
Json(json!({
"auth_required": required,
"authenticated": authenticated,
diff --git a/tests/bitwarden_test.rs b/tests/bitwarden_test.rs
index 27b7b265..e951915c 100644
--- a/tests/bitwarden_test.rs
+++ b/tests/bitwarden_test.rs
@@ -72,6 +72,16 @@ async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body:
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
call(&self.app, method, uri, Some(self.state.api_token.reveal()), body).await
@@ -132,8 +142,8 @@ async fn vault_routes_are_the_persons_only() {
("POST", "/api/passwords/migrate", None),
];
for (method, uri, body) in &routes {
- let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
+ let (s, v) = call_remote(&e.app, method, uri, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
}
diff --git a/tests/documents_test.rs b/tests/documents_test.rs
index f8bdcfbc..2dcc6033 100644
--- a/tests/documents_test.rs
+++ b/tests/documents_test.rs
@@ -115,6 +115,16 @@ async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body:
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
call(&self.app, method, uri, Some(self.state.api_token.reveal()), body).await
@@ -212,8 +222,8 @@ async fn every_route_is_the_persons_only() {
("PATCH", "/api/zombie/cases/x/fields", Some(json!({"deadline": {}}))),
];
for (method, uri, body) in &routes {
- let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
+ let (s, v) = call_remote(&e.app, method, uri, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
let (s, v) = call(&e.app, method, uri, Some("not-the-token"), body.clone()).await;
@@ -229,8 +239,11 @@ async fn every_route_is_the_persons_only() {
for uri in [format!("/api/attachments/{id}"), format!("/api/attachments/{id}/content"), format!("/api/attachments?context_id=document:{case_id}")] {
let (s, _) = call(&e.app, "GET", &uri, Some(&turn), None).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{uri} with a bot's turn token");
+ let (s, _) = call_remote(&e.app, "GET", &uri, None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{uri} from another machine without a token");
+ // The person's own browser on this machine isn't asked for the token
let (s, _) = call(&e.app, "GET", &uri, None, None).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{uri} without a token");
+ assert_eq!(s, StatusCode::OK, "{uri} from this machine without a token");
let (s, _) = e.person("GET", &uri, None).await;
assert_eq!(s, StatusCode::OK, "{uri} as the person");
}
diff --git a/tests/local_person_test.rs b/tests/local_person_test.rs
new file mode 100644
index 00000000..baccfae9
--- /dev/null
+++ b/tests/local_person_test.rs
@@ -0,0 +1,127 @@
+//! Person-only routes from the person's own machine (2026-10-21): the person's browser on this
+//! machine isn't asked for the API token, a bot's turn token is still a 403 there, another machine
+//! still needs the token (401), and `KWNT_REQUIRE_TOKEN=always` asks for it on loopback too.
+
+use axum::{
+ body::{to_bytes, Body},
+ extract::ConnectInfo,
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{spaces::SpaceId, Database},
+ router::LayaRouter,
+ server::{
+ auth::{ApiToken, Require},
+ continuity::SelfScope,
+ create_router, mcp_runtime, AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::Value;
+use std::net::SocketAddr;
+use std::sync::Arc;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const TOKEN: &str = "test-api-token-0123456789";
+
+async fn setup(require: Require) -> (Router, AppState, TempDir) {
+ let tmp = tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ let config = Config { data_dir: data.clone(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(data.join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests(TOKEN, require, config.port));
+ (create_router(state.clone()), state, tmp)
+}
+
+/// A GET from `peer` with `host`, as the real server sees it (with its peer address).
+async fn get(app: &Router, peer: &str, host: &str, uri: &str, bearer: Option<&str>) -> (StatusCode, Value) {
+ let mut req = Request::builder().method("GET").uri(uri).header("host", host);
+ if let Some(t) = bearer {
+ req = req.header("authorization", format!("Bearer {t}"));
+ }
+ let mut req = req.body(Body::empty()).unwrap();
+ req.extensions_mut().insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+/// A real bot's saved passwords: the route the "Confirm it's you" popup guarded.
+async fn passwords(state: &AppState) -> String {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ format!("/api/sandbox/{}/passwords", bot.id)
+}
+
+async fn turn_token(state: &AppState, folder: &std::path::Path) -> String {
+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let (_, token) = mcp_runtime::prepare_turn_with_self(state, &bot, None, Some(folder.to_path_buf()), Some(scope))
+ .await
+ .unwrap();
+ token
+}
+
+#[tokio::test]
+async fn local_without_a_token_goes_through() {
+ let (app, state, _tmp) = setup(Require::Auto).await;
+ let pw = passwords(&state).await;
+ let (s, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", &pw, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert!(v["passwords"].is_array(), "{v}");
+ let (s, v) = get(&app, "[::1]:50000", "localhost:8799", "/api/auth/status", None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(v["person_auth_required"], false, "the UI never asks for the token here: {v}");
+ assert_eq!(v["person_authenticated"], true, "{v}");
+}
+
+#[tokio::test]
+async fn local_bot_token_is_refused() {
+ let (app, state, _tmp) = setup(Require::Auto).await;
+ let pw = passwords(&state).await;
+ let folder = tempdir().unwrap();
+ let turn = turn_token(&state, folder.path()).await;
+ let (s, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", &pw, Some(&turn)).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "a bot's turn token: {v}");
+ let (s, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", &pw, Some("not-the-token")).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "a wrong token: {v}");
+ assert!(v.get("passwords").is_none(), "{v}");
+}
+
+#[tokio::test]
+async fn another_machine_without_a_token_is_refused() {
+ let (app, state, _tmp) = setup(Require::Auto).await;
+ let pw = passwords(&state).await;
+ let (s, v) = get(&app, "203.0.113.9:50000", "kwnt.example.com", &pw, None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");
+ // Loopback Host through a remote peer is still remote
+ let (s, _) = get(&app, "203.0.113.9:50000", "127.0.0.1:8799", &pw, None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED);
+ let (_, v) = get(&app, "203.0.113.9:50000", "kwnt.example.com", "/api/auth/status", None).await;
+ assert_eq!(v["person_auth_required"], true, "{v}");
+ let (s, v) = get(&app, "203.0.113.9:50000", "kwnt.example.com", &pw, Some(TOKEN)).await;
+ assert_eq!(s, StatusCode::OK, "with the API token: {v}");
+}
+
+#[tokio::test]
+async fn require_always_asks_for_the_token_locally_too() {
+ let (app, state, _tmp) = setup(Require::Always).await;
+ let pw = passwords(&state).await;
+ let (s, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", &pw, None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{v}");
+ let (_, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", "/api/auth/status", None).await;
+ assert_eq!(v["person_auth_required"], true, "{v}");
+ let (s, v) = get(&app, "127.0.0.1:50000", "127.0.0.1:8799", &pw, Some(TOKEN)).await;
+ assert_eq!(s, StatusCode::OK, "with the API token: {v}");
+}
diff --git a/tests/parallel_test.rs b/tests/parallel_test.rs
index fcf47b7f..a31f010c 100644
--- a/tests/parallel_test.rs
+++ b/tests/parallel_test.rs
@@ -91,6 +91,16 @@ impl Harness for Fake {
}
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
/// Polls a run until it is no longer running.
async fn finished(&self, run_id: &str) -> Value {
@@ -165,8 +175,8 @@ async fn every_route_is_the_persons_only() {
("GET", "/api/parallel/runs/x", None),
];
for (method, uri, body) in &routes {
- let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
+ let (s, v) = call_remote(&e.app, method, uri, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
let (s, v) = call(&e.app, method, uri, Some("not-the-token"), body.clone()).await;
diff --git a/tests/person_only_deletes_test.rs b/tests/person_only_deletes_test.rs
index d4a2fdd1..65c37de6 100644
--- a/tests/person_only_deletes_test.rs
+++ b/tests/person_only_deletes_test.rs
@@ -1,7 +1,7 @@
//! Deleting a bot or team, and undoing a bot action or an import, are person-only (audit
//! 2026-10-20, F-13). Since F-11 they delete saved passwords too, so a bare `curl` from a bot's
-//! shell could wipe another bot's logins: no token is a 401 `{person_only:true}`, a bot's turn
-//! token or a wrong token a 403, and nothing is deleted. The person's token goes through.
+//! shell could wipe another bot's logins: a bot's turn token or a wrong token is a 403, no token
+//! from another machine a 401, and nothing is deleted. The person's token goes through.
use axum::{
body::{to_bytes, Body},
@@ -56,6 +56,16 @@ async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>) -> (S
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
fn token(&self) -> &str {
self.state.api_token.reveal()
@@ -113,9 +123,8 @@ async fn deletes_and_undos_refuse_no_token_and_bot_tokens() {
("POST", "/api/imports/some-import/undo".to_string()),
];
for (method, uri) in &routes {
- let (s, v) = call(&e.app, method, uri, None).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
- assert_eq!(v["person_only"], true, "{v}");
+ let (s, v) = call_remote(&e.app, method, uri, None).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
let (s, v) = call(&e.app, method, uri, Some(&turn)).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
let (s, _) = call(&e.app, method, uri, Some("not-the-token")).await;
diff --git a/tests/profiles_api_test.rs b/tests/profiles_api_test.rs
index 5d43562b..4262dd63 100644
--- a/tests/profiles_api_test.rs
+++ b/tests/profiles_api_test.rs
@@ -585,6 +585,6 @@ async fn remote_requests_need_the_token() {
.await;
assert_eq!(
serde_json::from_str::<Value>(&body).unwrap(),
- json!({"auth_required": false, "authenticated": true, "person_auth_required": true, "person_authenticated": false})
+ json!({"auth_required": false, "authenticated": true, "person_auth_required": false, "person_authenticated": true})
);
}
diff --git a/tests/saved_passwords_test.rs b/tests/saved_passwords_test.rs
index cb24d803..1dd8f9f4 100644
--- a/tests/saved_passwords_test.rs
+++ b/tests/saved_passwords_test.rs
@@ -2,8 +2,8 @@
//!
//! - F-1/F-7: passwords live encrypted in the server's own data dir (0700 dir, 0600 files), never
//! in a bot's folder; an old `.saved_passwords.json` moves in on start and is deleted.
-//! - F-2: the password routes, answering a card and the approvals switch need the API token even
-//! from this machine (401), and a bot's turn token is refused (403).
+//! - F-2: the password routes, answering a card and the approvals switch need the API token from
+//! another machine (401), and a bot's turn token is refused (403) from anywhere.
//! - F-3: the list is metadata only, a save doesn't echo the password, reveal is explicit.
//! - F-4: an id from another space is a 404; names don't resolve.
//! - F-5/F-6: a captured password waits for the person's confirmation (browser side in
@@ -68,6 +68,16 @@ async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body:
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null), headers)
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
fn token(&self) -> &str {
self.state.api_token.reveal()
@@ -154,9 +164,8 @@ async fn f2_person_only_routes_refuse_no_token_and_bot_tokens() {
("PUT", format!("/api/kwants/{}/approvals", bot.id), Some(json!({"approvals": "off"}))),
];
for (method, uri, body) in &routes {
- let (s, v, _) = call(&e.app, method, uri, None, body.clone()).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
- assert_eq!(v["person_only"], true, "{v}");
+ let (s, v) = call_remote(&e.app, method, uri, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
assert!(!v.to_string().contains("DUMMY"), "{v}");
let (s, v, _) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
@@ -169,15 +178,14 @@ async fn f2_person_only_routes_refuse_no_token_and_bot_tokens() {
let (_, v) = e.person("GET", "/api/spaces/spc_default/approvals", None).await;
assert_eq!(v["approvals"], "ask");
- // The rest of the local app still works without a token, and reading the switch is open
- let (s, _, _) = call(&e.app, "GET", "/api/kwants", None, None).await;
- assert_eq!(s, StatusCode::OK);
+ // From this machine the person isn't asked for the token: the passwords open without it
+ let (s, v, _) = call(&e.app, "GET", &format!("/api/sandbox/{team}/passwords"), None, None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
let (s, _, _) = call(&e.app, "GET", "/api/spaces/spc_default/approvals", None, None).await;
assert_eq!(s, StatusCode::OK);
- // The UI learns it needs the token for these
let (_, v, _) = call(&e.app, "GET", "/api/auth/status", None, None).await;
- assert_eq!(v["person_auth_required"], true);
- assert_eq!(v["person_authenticated"], false);
+ assert_eq!(v["person_auth_required"], false);
+ assert_eq!(v["person_authenticated"], true);
let (_, v) = e.person("GET", "/api/auth/status", None).await;
assert_eq!(v["person_authenticated"], true);
}
diff --git a/tests/zombie_test.rs b/tests/zombie_test.rs
index 0f8eb47e..1465f9ad 100644
--- a/tests/zombie_test.rs
+++ b/tests/zombie_test.rs
@@ -399,6 +399,16 @@ async fn call(app: &Router, method: &str, uri: &str, bearer: Option<&str>, body:
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
+/// `call` from another machine (a non-loopback Host), without a token.
+async fn call_remote(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json").header("host", "kwnt.example.com");
+ let body = body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty);
+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
impl Env {
async fn person(&self, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
call(&self.app, method, uri, Some(self.state.api_token.reveal()), body).await
@@ -446,8 +456,8 @@ async fn every_route_is_the_persons_only() {
("GET", "/api/zombie/reviews", None),
];
for (method, uri, body) in &routes {
- let (s, v) = call(&e.app, method, uri, None, body.clone()).await;
- assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} without a token: {v}");
+ let (s, v) = call_remote(&e.app, method, uri, body.clone()).await;
+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{method} {uri} from another machine without a token: {v}");
let (s, v) = call(&e.app, method, uri, Some(&turn), body.clone()).await;
assert_eq!(s, StatusCode::FORBIDDEN, "{method} {uri} with a bot's turn token: {v}");
}