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:
1 parent
e34b18ec73
commit
fd847701e8
8 files changed
+588
-55
No files matched your search
@@ -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).
|
||||
|
||||
@@ -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."
|
||||
));
|
||||
|
||||
Reference in new issue
Block a user