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

+10 -3
View File
@@ -142,6 +142,7 @@ impl ledger_gui::owner::Owner for ViewerOwner {
.tokens
.into_iter()
.map(|t| TokenRow {
id: t.id,
book: t.book,
name: t.name,
scopes: t.scopes,
@@ -151,8 +152,8 @@ impl ledger_gui::owner::Owner for ViewerOwner {
Ok(Roster { assistants, tokens })
}
fn serve_revoke(&self, book: &str, name: &str) -> Result<String, String> {
self.server.revoke_token(book, name)
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.server.revoke_token(book, name, id)
}
fn command_line(&self, words: &[&str]) -> Result<String, String> {
@@ -160,7 +161,13 @@ impl ledger_gui::owner::Owner for ViewerOwner {
}
fn make_key(&self, book: &str) -> Result<bool, String> {
ledger_host::commands::ensure_key(&self.common, book)
use ledger_store::auth::Scope;
// What a page-made key may do: read, draft and post; never admin.
ledger_host::commands::ensure_key(
&self.common,
book,
&[Scope::Read, Scope::Write, Scope::Post],
)
}
fn close_books(&self) -> Result<String, String> {
+183 -2
View File
@@ -766,7 +766,13 @@ fn the_roster_lists_a_connected_key_and_revoking_it_ends_its_use() {
assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*token));
// Revoked: said in words, and no longer usable.
let said = server.revoke_token(BOOK, "agent").unwrap();
let id = roster
.tokens
.iter()
.find(|t| t.book == BOOK && t.name == "agent")
.map(|t| t.id.clone())
.unwrap();
let said = server.revoke_token(BOOK, "agent", &id).unwrap();
assert!(said.contains("access"), "{said}");
// (a) the roster no longer lists the key, nor a session on it,
let after = server.roster(Duration::from_secs(30)).unwrap();
@@ -787,6 +793,181 @@ fn the_roster_lists_a_connected_key_and_revoking_it_ends_its_use() {
// (c) and the token file's copy is gone.
assert_eq!(keeper.get(&account).unwrap(), None);
// Asking again for a key that is gone says so, and breaks nothing.
assert!(server.revoke_token(BOOK, "agent").is_err());
assert!(server.revoke_token(BOOK, "agent", &id).is_err());
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// The host's own `Common` on `home`'s root: what the window's owner holds.
fn common_on(home: &Home) -> ledger_host::commands::Common {
ledger_host::commands::Common {
root: Some(home.root()),
..Default::default()
}
}
/// The id of the live key `agent` of `BOOK`, by the roster.
fn key_id(server: &AppServer) -> Option<String> {
server
.roster(Duration::from_secs(30))
.unwrap()
.tokens
.iter()
.find(|t| t.book == BOOK && t.name == "agent")
.map(|t| t.id.clone())
}
/// The scopes of the live key `agent` of `BOOK`, by the roster.
fn key_scopes(server: &AppServer) -> Vec<String> {
server
.roster(Duration::from_secs(30))
.unwrap()
.tokens
.iter()
.find(|t| t.book == BOOK && t.name == "agent")
.map(|t| t.scopes.clone())
.unwrap()
}
/// "Make the key" (the Connect page) makes the key once, with read, write
/// and post and no admin; a second click, or a click with the copy here
/// gone, replaces nothing and says why in words; a revoke of a row whose
/// key was since replaced ends nothing.
#[test]
fn make_the_key_never_replaces_a_key_and_a_stale_revoke_ends_nothing() {
use ledger_store::auth::Scope;
let scopes = [Scope::Read, Scope::Write, Scope::Post];
let home = Home::new("app-make-key");
let run = home.run();
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
home.create(BOOK, "USD");
assert_eq!(server.open_book(BOOK), Ok(None));
let common = common_on(&home);
let account = ledger_host::tokens::Account::new(&home.root(), BOOK, "agent");
let keeper = ledger_host::tokens::keeper(&run);
// Made once, and kept; read, write and post, not admin.
assert_eq!(
ledger_host::commands::ensure_key(&common, BOOK, &scopes),
Ok(true)
);
let first = key_id(&server).expect("the key was made");
let text = keeper.get(&account).unwrap().expect("its copy is kept");
assert_eq!(
key_scopes(&server),
["books:read", "books:write", "books:post"]
);
// A second click: nothing is made, nothing replaced.
assert_eq!(
ledger_host::commands::ensure_key(&common, BOOK, &scopes),
Ok(false)
);
assert_eq!(key_id(&server).as_deref(), Some(first.as_str()));
assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*text));
// The key works for ordinary bookkeeping and is refused an admin call.
let mut bridge = Bridge::start(&home);
assert!(bridge.initialize().get("error").is_none());
let read = bridge.start_call();
assert!(
read.get("error").is_none() && read["result"]["isError"] != json!(true),
"{read}"
);
let admin = bridge.ask(
"tools/call",
json!({"name": "books.access_log", "arguments": {}}),
);
let refused = admin.get("error").is_some() || admin["result"]["isError"] == json!(true);
assert!(refused, "an admin call must be refused: {admin}");
assert!(
admin.to_string().contains("books:admin"),
"it is refused for want of admin: {admin}"
);
// The copy here goes missing while the key lives (an assistant may be
// using it): said in words, and nothing is replaced.
keeper.delete(&account).unwrap();
let said = ledger_host::commands::ensure_key(&common, BOOK, &scopes).unwrap_err();
assert!(
said.contains("already exists") && said.contains("revoke it"),
"{said}"
);
assert!(!said.contains(&*text), "never the key's text");
assert_eq!(key_id(&server).as_deref(), Some(first.as_str()));
assert_eq!(keeper.get(&account).unwrap(), None, "no copy was made");
// The assistant already using the key is not cut off.
let still = bridge.start_call();
assert!(still.get("error").is_none(), "{still}");
// The same when the copy here is not the live key's text.
keeper.set(&account, "wb_not_the_key").unwrap();
let said = ledger_host::commands::ensure_key(&common, BOOK, &scopes).unwrap_err();
assert!(said.contains("not its text any more"), "{said}");
assert_eq!(key_id(&server).as_deref(), Some(first.as_str()));
// The key is made again elsewhere (a row of the old one is on screen):
// revoking the old row's id ends nothing, and says why.
let newer_text = home.token_with(BOOK, "agent", &["read", "write", "post"]);
keeper.set(&account, &newer_text).unwrap();
let newer = key_id(&server).unwrap();
assert_ne!(newer, first);
let said = server.revoke_token(BOOK, "agent", &first).unwrap_err();
assert!(said.contains("already replaced or revoked"), "{said}");
assert_eq!(key_id(&server).as_deref(), Some(newer.as_str()));
assert_eq!(
keeper.get(&account).unwrap().as_deref(),
Some(newer_text.as_str()),
"the newer key's copy stays"
);
// Its own id ends it.
assert!(server.revoke_token(BOOK, "agent", &newer).is_ok());
assert_eq!(key_id(&server), None);
assert_eq!(keeper.get(&account).unwrap(), None);
drop(bridge);
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
/// A key ended whose token file copy cannot be deleted is not reported as
/// done: the words say the key is dead and where the file is, and never
/// hold the file's text.
#[cfg(unix)]
#[test]
fn a_revoke_that_leaves_the_token_file_says_so() {
use std::os::unix::fs::PermissionsExt;
// SAFETY: geteuid has no preconditions.
if unsafe { libc::geteuid() } == 0 {
return; // root deletes in a read-only folder: nothing to show
}
let home = Home::new("app-revoke-left");
let run = home.run();
let server = start(&home, &[]);
server.wait_ready(Duration::from_secs(60)).unwrap();
home.create(BOOK, "USD");
assert_eq!(server.open_book(BOOK), Ok(None));
let token = home.token_with(BOOK, "agent", &["read"]);
let account = ledger_host::tokens::Account::new(&home.root(), BOOK, "agent");
let keeper = ledger_host::tokens::keeper(&run);
keeper.set(&account, &token).unwrap();
let id = key_id(&server).unwrap();
let folder = run.join("tokens");
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o500)).unwrap();
let result = server.revoke_token(BOOK, "agent", &id);
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o700)).unwrap();
let said = result.unwrap_err();
assert!(said.contains("key is dead"), "{said}");
assert!(said.contains("a file with its text remains at"), "{said}");
assert!(
said.contains(
&ledger_host::commands::token_file_path(&run, BOOK, "agent")
.display()
.to_string()
),
"{said}"
);
assert!(!said.contains(&*token), "never the file's text");
// The key is dead all the same.
assert_eq!(key_id(&server), None);
assert_eq!(keeper.get(&account).unwrap().as_deref(), Some(&*token));
assert_eq!(server.stop(Duration::from_secs(60)), Stopped::Closed);
}
+15 -10
View File
@@ -442,7 +442,9 @@ impl State {
if let Some((what, rx)) = &self.job
&& let Ok(result) = rx.try_recv()
{
if what.starts_with("Revoke") && result.is_ok() {
// Whatever came of it (a key already gone, a file left behind),
// the list is read again.
if what.starts_with("Revoke") {
self.refresh = true;
}
self.done = Some((what.clone(), result));
@@ -587,7 +589,7 @@ impl State {
);
return;
}
let mut revoke: Option<String> = None;
let mut revoke: Option<(String, String)> = None;
for row in &rows {
Frame::new()
.fill(p.surface)
@@ -608,7 +610,7 @@ impl State {
});
ui.add_space(6.0);
}
if let (Some(name), Some(owner)) = (revoke, owner.clone()) {
if let (Some((name, id)), Some(owner)) = (revoke, owner.clone()) {
self.confirm = None;
let b = book.to_string();
self.start(
@@ -616,7 +618,7 @@ impl State {
jobs,
format!("Revoke {name}"),
"Ending an assistant's access",
Box::new(move || owner.serve_revoke(&b, &name)),
Box::new(move || owner.serve_revoke(&b, &name, &id)),
);
}
}
@@ -795,7 +797,7 @@ fn another_row(
Box::new(move || {
o.make_key(&b).map(|made| {
if made {
"made, and kept on this computer.".to_string()
"made, and kept on this computer. It can read the books, draft entries and post them; it cannot see the access record.".to_string()
} else {
"it was already made.".to_string()
}
@@ -851,7 +853,7 @@ fn connection_row(
row: &Connection<'_>,
status: &Status,
confirm: &mut Option<String>,
revoke: &mut Option<String>,
revoke: &mut Option<(String, String)>,
busy: bool,
can_revoke: bool,
) {
@@ -887,12 +889,12 @@ fn connection_row(
if !can_revoke {
return;
}
if confirm.as_deref() == Some(t.name.as_str()) {
if confirm.as_deref() == Some(t.id.as_str()) {
if ui
.add_enabled(!busy, egui::Button::new("Yes, revoke"))
.clicked()
{
*revoke = Some(t.name.clone());
*revoke = Some((t.name.clone(), t.id.clone()));
}
if ui.button("Keep it").clicked() {
*confirm = None;
@@ -902,11 +904,14 @@ fn connection_row(
.on_hover_text("Ends this key: the assistant using it is cut off and cannot reach these books again")
.clicked()
{
*confirm = Some(t.name.clone());
*confirm = Some(t.id.clone());
}
});
});
if confirm.as_deref() == Some(row.name.as_str()) {
if row
.token
.is_some_and(|t| confirm.as_deref() == Some(t.id.as_str()))
{
ui.label(
RichText::new(format!(
"Revoke the key “{}”? Anything using it is cut off now; {}'s books are not changed.",
+12 -5
View File
@@ -190,6 +190,9 @@ pub struct Assistant {
/// A token, as listed: who may connect to a company (never its text).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TokenRow {
/// Its id: what a revoke names, so a row of a key since replaced
/// cannot end the new one.
pub id: String,
/// The company it opens.
pub book: String,
/// Its name.
@@ -262,9 +265,11 @@ pub trait Owner: Send + Sync {
fn serve_roster(&self) -> Result<Roster, String> {
Ok(Roster::default())
}
/// End the token `name` of the company `book` (what `wanderbooks token
/// revoke` does): `Ok` says what was done, in words. Blocks.
fn serve_revoke(&self, _book: &str, _name: &str) -> Result<String, String> {
/// End the token `name`, whose id is `id`, of the company `book` (what
/// `wanderbooks token revoke` does, for that one key): `Ok` says what
/// was done, in words; a key already replaced or revoked is an `Err`
/// that says so. Blocks.
fn serve_revoke(&self, _book: &str, _name: &str, _id: &str) -> Result<String, String> {
Err("not here".into())
}
/// This program run with `words`, as a line to type in a terminal (the
@@ -274,8 +279,10 @@ pub trait Owner: Send + Sync {
Err("not here".into())
}
/// The key an assistant needs to reach the company `book` exists (made
/// now if it did not): `Ok(true)` when it was made now. What `connect`
/// does first, for an assistant set up by hand. Blocks.
/// now if it did not), able to read, draft and post but not to see the
/// access record: `Ok(true)` when it was made now. It never replaces a
/// key: one that exists with no copy here is an `Err` that says so.
/// Blocks.
fn make_key(&self, _book: &str) -> Result<bool, String> {
Err("not here".into())
}
+2 -1
View File
@@ -187,7 +187,7 @@ impl Owner for Fake {
.clone()
.unwrap_or_else(|| Ok(Roster::default()))
}
fn serve_revoke(&self, book: &str, name: &str) -> Result<String, String> {
fn serve_revoke(&self, book: &str, name: &str, _id: &str) -> Result<String, String> {
self.note(format!("revoke {book} {name}"));
if let Some(Ok(r)) = self.roster.lock().unwrap().as_mut() {
r.tokens.retain(|t| !(t.book == book && t.name == name));
@@ -246,6 +246,7 @@ fn session(book: &str, token: &str, program: &str, running: u32, last: Option<&s
fn token(book: &str, name: &str) -> TokenRow {
TokenRow {
id: format!("tok_{book}_{name}"),
book: book.into(),
name: name.into(),
scopes: ["books:read", "books:write", "books:post"]
+35 -14
View File
@@ -419,29 +419,50 @@ impl AppServer {
Ok(Roster { sessions, tokens })
}
/// End the token `name` of the company `book`, as `wanderbooks token
/// revoke` does (INVARIANT 12): the server ends the token and the
/// sessions it opened, and the token file's copy is removed. `Ok` says
/// what was done, in words; a token file that could not be cleaned is
/// said, and the token is revoked all the same.
pub fn revoke_token(&self, book: &str, name: &str) -> Result<String, String> {
/// End the key `id`, named `name`, of the company `book`, as
/// `wanderbooks token revoke` does (INVARIANT 12): the server ends that
/// key and the sessions it opened, and the token file's copy is
/// removed. It goes by the key's id, never its name alone: a row that
/// shows a key since replaced must not end the new one. `Ok` says what
/// was done, in words. When the key is ended but the token file's copy
/// cannot be deleted, that is an `Err` that says so (the key is dead; a
/// file holding its text remains at that path), never its text.
pub fn revoke_token(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.wait_ready(READY_WAIT)?;
let request = Request::TokenRevoke {
book: book.into(),
name: name.into(),
id: None,
id: Some(id.into()),
};
match self.ask_raw(request, Some(Duration::from_secs(30))) {
Ok(Response::TokenRevoked(t)) => {
let said = format!("Ended {:?}'s access to {}.", t.name, t.book);
match crate::commands::forget_token_file(&self.run, book, name) {
Ok(()) => Ok(said),
Err(why) => Ok(format!(
"{said} Its token file still holds its text ({why}); it opens nothing now."
)),
Err(why) => {
let at = crate::commands::token_file_path(&self.run, book, name);
Err(format!(
"{said} The key is dead and opens nothing now. But the copy of its text kept on this computer could not be deleted ({why}); a file with its text remains at {}. Delete that file yourself.",
at.display()
))
}
}
}
Ok(Response::Refused(why)) => Err(why),
Ok(Response::Refused(why)) => {
// Refused because that key is gone (replaced or revoked
// since the row was read), or for another reason.
let gone = matches!(
self.ask_raw(Request::TokenList, Some(Duration::from_secs(10))),
Ok(Response::Tokens(list)) if !list.iter().any(|t| t.id == id)
);
Err(if gone {
format!(
"This key was already replaced or revoked, so nothing was ended. The list now shows the keys of {book} as they stand."
)
} else {
why
})
}
Ok(other) => Err(format!("the books server answered oddly: {other:?}")),
Err(e) => Err(e.to_string()),
}
@@ -697,9 +718,9 @@ impl AppHost {
self.running()?.roster(wait)
}
/// End a token (INVARIANT 12).
pub fn revoke_token(&self, book: &str, name: &str) -> Result<String, String> {
self.running()?.revoke_token(book, name)
/// End the key `id` (INVARIANT 12).
pub fn revoke_token(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.running()?.revoke_token(book, name, id)
}
/// The format upgrade of the company `id` (INVARIANT 10).
+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."
));
+141
View File
@@ -0,0 +1,141 @@
//! The line the Connect page shows to copy (commands.rs INVARIANT 8; plan
//! P15 unit A4).
//!
//! ```text
//! GOAL: a command pasted into a terminal runs as it reads: whatever a
//! path holds, a POSIX shell gets back exactly the parts it was
//! given; PowerShell's quoting doubles what it must; a part that
//! cannot be written safely for both PowerShell and cmd.exe is
//! refused, in words, never shown.
//! SOURCE: WB-app-1 (the window shows an exact command), POSIX shell
//! command language, "Quoting": single quotes keep every
//! character literal but the single quote itself.
//! INVARIANTS:
//! 1. For any parts, `sh` reads the Unix line back as those parts.
//! 2. Plain parts are left as they are.
//! 3. PowerShell: a `'` is doubled; a part with a character cmd.exe
//! acts on and that needs quoting is refused.
//! ```
use ledger_host::commands::{quote_unix, quote_windows, shell_line};
#[cfg(unix)]
use std::process::Command;
/// The parts a POSIX shell reads from `line` as the words of a command,
/// by `printf` (which prints each word then a NUL).
#[cfg(unix)]
fn sh_words(line: &str) -> Vec<String> {
let out = Command::new("sh")
.arg("-c")
.arg(format!("printf '%s\\0' {line}"))
.output()
.expect("sh runs");
assert!(out.status.success(), "sh refused: {line}");
let mut words: Vec<String> = out
.stdout
.split(|b| *b == 0)
.map(|w| String::from_utf8(w.to_vec()).unwrap())
.collect();
assert_eq!(words.pop().as_deref(), Some(""), "ends with a NUL");
words
}
/// A small deterministic generator (no extra dependency).
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
/// Random text weighted to what a shell cares about.
fn random_part(rng: &mut Rng) -> String {
const SPECIAL: &[char] = &[
' ', '\t', '\n', '$', '`', ';', '&', '|', '<', '>', '(', ')', '{', '}', '[', ']', '*', '?',
'~', '#', '!', '\'', '"', '\\', '%', '^', '=', ',', ':', '/', '.', '-', '_', '+', '@', 'a',
'Z', '0', 'é', '日', '😀',
];
let len = (rng.next() % 14) as usize;
(0..len)
.map(|_| SPECIAL[(rng.next() % SPECIAL.len() as u64) as usize])
.collect()
}
#[cfg(unix)]
#[test]
fn a_posix_shell_reads_back_exactly_the_parts_whatever_they_hold() {
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
for _ in 0..150 {
let n = 1 + (rng.next() % 4) as usize;
let parts: Vec<String> = (0..n).map(|_| random_part(&mut rng)).collect();
let line = shell_line(&parts, false).unwrap();
assert_eq!(sh_words(&line), parts, "line: {line}");
}
// The ones that bite, by name.
for part in [
"/home/a b/$HOME/`id`/;rm -rf x/&|'q'\"",
"it's",
"''",
"",
"-",
"a\nb",
"~/x",
"*",
] {
let parts = vec![part.to_string(), "mcp".to_string()];
let line = shell_line(&parts, false).unwrap();
assert_eq!(sh_words(&line), parts, "line: {line}");
}
}
#[test]
fn plain_parts_are_left_as_they_are() {
assert_eq!(quote_unix("mcp"), "mcp");
assert_eq!(
quote_unix("/opt/wander-books/bin_1.2/x@y:z,w=1+2%3"),
"/opt/wander-books/bin_1.2/x@y:z,w=1+2%3"
);
assert_eq!(quote_unix("a b"), "'a b'");
assert_eq!(quote_unix("it's"), "'it'\\''s'");
assert_eq!(quote_unix(""), "''");
let line = shell_line(
&[
"/opt/wb".into(),
"mcp".into(),
"--book".into(),
"acme".into(),
],
false,
);
assert_eq!(line.unwrap(), "/opt/wb mcp --book acme");
}
#[test]
fn powershell_quoting_doubles_quotes_and_refuses_what_cmd_would_act_on() {
// Plain: the same line in PowerShell and cmd.exe.
let plain = shell_line(&["C:\\wb\\wanderbooks.exe".into(), "mcp".into()], true).unwrap();
assert_eq!(plain, "C:\\wb\\wanderbooks.exe mcp");
// A space: PowerShell's single quotes, and `&` to run a quoted program.
let spaced = shell_line(&["C:\\Program Files\\wb\\x.exe".into(), "mcp".into()], true).unwrap();
assert_eq!(spaced, "& 'C:\\Program Files\\wb\\x.exe' mcp");
// A quote is doubled (also the curly ones PowerShell reads as quotes).
assert_eq!(quote_windows("it's").unwrap(), ("'it''s'".into(), true));
assert_eq!(
quote_windows("a\u{2019}b").unwrap(),
("'a\u{2019}\u{2019}b'".into(), true)
);
// `$` and a backtick are literal in single quotes.
assert_eq!(quote_windows("$x`y").unwrap(), ("'$x`y'".into(), true));
// What cmd.exe acts on: refused, in words.
for bad in [
"a&b", "a|b", "a<b", "a>b", "a^b", "50%", "a\"b", "hi!", "a\nb",
] {
let why = quote_windows(bad).unwrap_err();
assert!(why.contains("cmd.exe"), "{bad}: {why}");
assert!(shell_line(&[bad.to_string()], true).is_err());
}
}