fix(host,gui): the Connect page's keys: never replaced, no admin, revoked by id, a quoted command, a leftover file said

Make the key asks the server first and never replaces: a live key whose copy
is missing here may be in use, so it is said in words and left alone. A
page-made key carries read, write and post, not admin (the connect command
keeps its scopes). Revoke names the key's id, so a stale row cannot end a
newer key of the same name; a revoke that leaves the token file says the key
is dead and where the file is. The copyable command is single-quoted for a
POSIX shell and PowerShell, and refused when cmd.exe would act on a part.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-21 10:23:11 -07:00
1 parent e34b18ec73
commit fd847701e8
8 files changed
+588 -55

No files matched your search

+190 -20
View File
@@ -1435,27 +1435,189 @@ pub fn bridge_serve_args(common: &Common, book: &str) -> Result<Vec<std::ffi::Os
program_args(common, &["mcp", "--book", &book])
}
/// This program run with `words`, as a line to type in a terminal: a part
/// with a space in it is quoted.
pub fn command_line(common: &Common, words: &[&str]) -> Result<String, String> {
Ok(program_args(common, words)?
.iter()
.map(|a| {
let a = a.to_string_lossy();
if a.contains(char::is_whitespace) {
format!("\"{a}\"")
} else {
a.into_owned()
}
})
.collect::<Vec<_>>()
.join(" "))
/// Whether `c` may stand in a shell word unquoted, in a POSIX shell.
fn unix_plain(c: char) -> bool {
c.is_ascii_alphanumeric() || "_@%+=:,./-".contains(c)
}
/// The default token of the books `book` exists and its copy is in the token
/// file (made now if it is not): what `connect` does first. `Ok(true)` when
/// it was made now.
pub fn ensure_key(common: &Common, book: &str) -> Result<bool, String> {
/// `part` as one word of a POSIX shell line (sh, bash, zsh, fish): left as
/// it is when every character is plain, else in single quotes, in which
/// nothing is special but `'` itself, written `'\''`.
pub fn quote_unix(part: &str) -> String {
if !part.is_empty() && part.chars().all(unix_plain) {
return part.to_string();
}
format!("'{}'", part.replace('\'', "'\\''"))
}
/// `part` as one word of a Windows line: left as it is when every
/// character is plain (the same in PowerShell and in cmd.exe), else in
/// PowerShell's single quotes (a `'`, and the curly quotes PowerShell
/// reads as one, doubled). Single quotes mean nothing to cmd.exe, so a
/// part that needs them and holds a character cmd.exe acts on (`&`, `|`,
/// `<`, `>`, `^`, `%`, `"`, `!`, or a control character) is refused:
/// pasted into cmd.exe it could run something else. Returns the word and
/// whether it was quoted.
pub fn quote_windows(part: &str) -> Result<(String, bool), String> {
let plain = |c: char| c.is_ascii_alphanumeric() || "_@+:./\\-".contains(c);
if !part.is_empty() && part.chars().all(plain) {
return Ok((part.to_string(), false));
}
if let Some(bad) = part
.chars()
.find(|c| c.is_control() || "&|<>^%\"!".contains(*c))
{
return Err(format!(
"a folder or file name on the way to the program holds the character {bad:?}, which cannot be written in a line that is safe to paste into both PowerShell and cmd.exe: move the program to a folder without it"
));
}
let doubled: String = part
.chars()
.flat_map(|c| {
let twice = matches!(c, '\'' | '\u{2018}' | '\u{2019}' | '\u{201A}' | '\u{201B}');
std::iter::repeat_n(c, if twice { 2 } else { 1 })
})
.collect();
Ok((format!("'{doubled}'"), true))
}
/// `parts` as one line to paste in a terminal: for a POSIX shell, or (with
/// `windows`) for PowerShell (plain parts only: cmd.exe too). A line with
/// a quoted program in PowerShell starts with `&`, which cmd.exe does not
/// take: such a line is for PowerShell alone (it fails in cmd.exe, it
/// never runs another program, see `quote_windows`).
pub fn shell_line(parts: &[String], windows: bool) -> Result<String, String> {
if !windows {
return Ok(parts
.iter()
.map(|p| quote_unix(p))
.collect::<Vec<_>>()
.join(" "));
}
let mut words = Vec::new();
for (i, p) in parts.iter().enumerate() {
let (word, quoted) = quote_windows(p)?;
words.push(if i == 0 && quoted {
format!("& {word}")
} else {
word
});
}
Ok(words.join(" "))
}
/// This program run with `words`, as a line to paste in a terminal, quoted
/// so that it runs as it reads (`shell_line`). A part that is not valid
/// text is an error, never a guess.
pub fn command_line(common: &Common, words: &[&str]) -> Result<String, String> {
let parts = program_args(common, words)?
.into_iter()
.map(|a| {
a.into_string().map_err(|_| {
"a folder or file name on the way to the program is not valid text, so no command can be shown for it"
.to_string()
})
})
.collect::<Result<Vec<String>, String>>()?;
shell_line(&parts, cfg!(windows))
}
/// Why a key that lives on the server cannot be handed out from this
/// computer: said in words (INVARIANT 7: nothing is replaced).
fn key_in_use(book: &str, name: &str, why: KeyState) -> String {
match why {
KeyState::CopyMissing => format!(
"A key called “{name}” for {book} already exists, but its copy is not on this computer, so it cannot be handed to an assistant from here. It may be in use by an assistant now, so nothing was changed. To start over, revoke it under “Who can reach these books” and make the key again."
),
_ => format!(
"A key called “{name}” for {book} already exists, but the copy on this computer is not its text any more (it was made again elsewhere). Nothing was changed. To start over, revoke it under “Who can reach these books” and make the key again."
),
}
}
/// How the default key of a company stands.
#[derive(Clone, Copy, PartialEq, Eq)]
enum KeyState {
/// No live key of that name.
Absent,
/// A live key, and this computer holds its text.
Kept,
/// A live key, and this computer holds no copy.
CopyMissing,
/// A live key, and the copy here is not its text.
CopyStale,
}
/// Ask the server whether the key `account` names is live, and whether
/// the copy in the token file is its text.
fn key_state(
common: &Common,
keeper: &crate::tokens::Keeper,
account: &crate::tokens::Account,
book: &str,
) -> Result<KeyState, String> {
let copy = keeper.get(account)?;
let sha256 = copy
.as_deref()
.map(|t| ledger_store::journal::sha256_hex(t.as_bytes()))
.unwrap_or_default();
let request = Request::TokenCheck {
book: book.to_string(),
name: crate::tokens::DEFAULT_NAME.to_string(),
sha256,
};
match with_server(common, request)? {
Response::TokenChecked { live: None, .. } => Ok(KeyState::Absent),
Response::TokenChecked { matches: true, .. } => Ok(KeyState::Kept),
Response::TokenChecked { .. } if copy.is_none() => Ok(KeyState::CopyMissing),
Response::TokenChecked { .. } => Ok(KeyState::CopyStale),
Response::Refused(why) => Err(why),
other => Err(format!("the books server answered oddly: {other:?}")),
}
}
/// The default key of the books `book` exists, with `scopes`, and its copy
/// is in the token file (made now if there is none): what the window's
/// "Make the key" does. `Ok(true)` when it was made now, `Ok(false)` when
/// it was there already. It never replaces a key (INVARIANT 7): a live key
/// whose copy is missing here may be in use by an assistant, so that is an
/// `Err` that says what to do, and nothing changes.
pub fn ensure_key(
common: &Common,
book: &str,
scopes: &[ledger_store::auth::Scope],
) -> Result<bool, String> {
let book = ledger_store::root::BookId::parse(book)
.map_err(|e| e.to_string())?
.to_string();
let found =
ledger_store::root::Root::find(common.root.as_deref()).map_err(|e| e.to_string())?;
let run = found.run_dir().map_err(|e| e.to_string())?;
let account = crate::tokens::Account::new(found.path(), &book, crate::tokens::DEFAULT_NAME);
let keeper = crate::tokens::keeper(&run);
let name = crate::tokens::DEFAULT_NAME;
match key_state(common, &keeper, &account, &book)? {
KeyState::Kept => return Ok(false),
KeyState::Absent => {}
other => return Err(key_in_use(&book, name, other)),
}
let scopes: Vec<String> = scopes.iter().map(|s| s.as_str().to_string()).collect();
match make_token(common, &book, name, scopes, false) {
Ok(_) => Ok(true),
Err(why) => match key_state(common, &keeper, &account, &book) {
// Another window made it between the question and the make:
// theirs stands, and this one made nothing.
Ok(KeyState::Kept) => Ok(false),
Ok(KeyState::Absent) | Err(_) => Err(why),
Ok(other) => Err(key_in_use(&book, name, other)),
},
}
}
/// What `connect` does first: the default key's copy is in the token file,
/// or the key is made again with every scope (replacing a live key whose
/// copy is missing: the owner asked to connect an agent here).
fn ensure_agent_key(common: &Common, book: &str) -> Result<bool, String> {
let book = ledger_store::root::BookId::parse(book)
.map_err(|e| e.to_string())?
.to_string();
@@ -1474,6 +1636,14 @@ pub fn ensure_key(common: &Common, book: &str) -> Result<bool, String> {
Ok(true)
}
/// Where the token file copy of the token `name` of `book` is kept
/// (`run_dir` is the root's `run/` folder).
pub fn token_file_path(run_dir: &Path, book: &str, name: &str) -> PathBuf {
let root = run_dir.parent().unwrap_or(run_dir).to_path_buf();
let account = crate::tokens::Account::new(&root, book, name);
crate::tokens::keeper(run_dir).file(&account)
}
/// A revoked token's copy in the token file goes with it (what `token
/// revoke` does after the server has ended the token). `run_dir` is the
/// root's `run/` folder.
@@ -1506,7 +1676,7 @@ pub fn connect_agent(common: &Common, agent: &str, book: &str) -> Result<Vec<Str
let serve = bridge_serve_args(common, &book)?;
let mut lines = Vec::new();
// The token: kept in its file, or made now.
if ensure_key(common, &book)? {
if ensure_agent_key(common, &book)? {
lines.push(format!(
"Made the agent token of the books {book}, kept in a token file in the data root."
));