Watch
0
0
Fork
You've already forked hyperhive
0

revoking a linked Matrix account also deletes its key-backup passphrase; a plain unlink keeps it for a relink

This commit is contained in:
maia 2026-11-16 22:21:20 +01:00 • committed by mara
commit 6b3e1f0fb2

View file

@ -366,6 +366,9 @@ pub(crate) enum Removal {
Revoke(String),
/// The store refused or could not be reached.
Store(Error),
/// The account is deleted, and the store refused or could not be reached
/// when its key-backup passphrase was deleted.
Recovery(Error),
}
impl Removal {
@ -384,6 +387,13 @@ impl Removal {
),
),
Self::Store(e) => error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
Self::Recovery(e) => error_problem(
StatusCode::INTERNAL_SERVER_ERROR,
&format!(
"the account was deleted, but its key-backup passphrase was not: {e}; \
delete the account again with revoke to finish"
),
),
}
}
}
@ -411,23 +421,64 @@ async fn remove(store: &impl AccountStore, path: &str) -> Result<(), Removal> {
/// Delete the matrix account at `path`. With `revoke`, its token is first
/// handed to `revoke` with the stored homeserver, and the entry stays when that
/// fails.
///
/// `passphrase` is the account's key-backup passphrase, given on a revoking
/// delete only: it goes last, once the account is gone, and a store that
/// refuses is [`Removal::Recovery`]. A plain delete leaves it, so a relink
/// finds the passphrase its backup was enabled with. An account already gone is
/// not an error when `passphrase` is given, so a revoking delete that stopped
/// at the passphrase can be sent again and finish.
async fn remove_matrix<F, Fut>(
store: &impl AccountStore,
path: &str,
passphrase: Option<&str>,
revoke: Option<F>,
) -> Result<(), Removal>
where
F: FnOnce(String, String) -> Fut,
Fut: Future<Output = Result<(), String>>,
{
let credential: matrix::Credential = stored(store, path).await?;
let credential: matrix::Credential = match stored(store, path).await {
Ok(credential) => credential,
Err(Removal::NotFound) if passphrase.is_some() => {
return remove_passphrase(store, passphrase).await;
}
Err(e) => return Err(e),
};
if let Some(revoke) = revoke {
let homeserver = credential.homeserver.ok_or(Removal::NoHomeserver)?;
revoke(homeserver, credential.value)
.await
.map_err(Removal::Revoke)?;
}
remove(store, path).await
remove(store, path).await?;
remove_passphrase(store, passphrase).await
}
/// The path of the key-backup passphrase a matrix account delete takes with
/// it: only a revoking delete does. A plain one is how an account is unlinked
/// to be linked again, and a relink must find the passphrase its backup was
/// enabled with, since a new one locks the agent out of the old backup.
fn passphrase_to_delete(
revoke: bool,
agent: &str,
account: &str,
) -> Result<Option<String>, swarm_secret_client::Error> {
revoke
.then(|| matrix::recovery_path(agent, account))
.transpose()
}
/// Delete every version of the key-backup passphrase at `path`, when there is
/// one to delete. A passphrase that is not stored is already deleted.
async fn remove_passphrase(store: &impl AccountStore, path: Option<&str>) -> Result<(), Removal> {
match path {
Some(path) => store
.delete_all_versions(path)
.await
.map_err(Removal::Recovery),
None => Ok(()),
}
}
/// Delete the forge account, GitLab account or GitHub token at `path`.
@ -442,8 +493,10 @@ async fn remove_plain<T: DeserializeOwned + Send>(
/// `delete_matrix_account`'s query.
#[derive(Deserialize, IntoParams)]
pub struct DeleteMatrixAccountQuery {
/// Log the stored token out at its homeserver before deleting. When that
/// fails, the account is not deleted.
/// Log the stored token out at its homeserver before deleting, and delete
/// the account's key-backup passphrase after it. When the logout fails,
/// the account is not deleted. Without `revoke` the passphrase stays, so a
/// relink of the account reuses it.
#[serde(default)]
revoke: bool,
}
@ -462,10 +515,10 @@ pub struct DeleteMatrixAccountQuery {
responses(
(status = 204, description = "deleted"),
(status = 400, description = "a name is not an identifier, the account name is not a single path segment, the account is 'main' (reserved), or the hive is not in this swarm (problem+json)", body = String),
(status = 404, description = "no such account is stored (problem+json)", body = String),
(status = 404, description = "no such account is stored, and revoke was not asked for (problem+json)", body = String),
(status = 409, description = "revoke was asked for and the account has no homeserver stored; not deleted (problem+json)", body = String),
(status = 502, description = "revoke was asked for and the homeserver did not revoke the token; not deleted (problem+json)", body = String),
(status = 500, description = "the store could not be read or written (problem+json)", body = String),
(status = 500, description = "the store could not be read or written; or, with revoke, the account is deleted and its key-backup passphrase is not, and sending the delete again finishes it (problem+json)", body = String),
),
tag = "agents"
)]
@ -502,12 +555,19 @@ pub async fn delete_matrix_account(
.await
.map_err(|e| format!("{e:#}"))
});
remove_matrix(&store, &path, revoke).await.map_err(|e| {
let passphrase = passphrase_to_delete(query.revoke, &agent, &account)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
let outcome = remove_matrix(&store, &path, passphrase.as_deref(), revoke).await;
if let Err(e) = &outcome {
tracing::warn!(%hive, %agent, %account, error = ?e, "deleting the matrix account failed");
e.problem()
})?;
crate::link_egress::removed(&state, &agent, &crate::link_egress::matrix_source(&account))
.await?;
}
// The account is gone when only its passphrase is left, so its egress
// bookkeeping goes too, ahead of the error the caller is owed.
if matches!(outcome, Ok(()) | Err(Removal::Recovery(_))) {
crate::link_egress::removed(&state, &agent, &crate::link_egress::matrix_source(&account))
.await?;
}
outcome.map_err(|e| e.problem())?;
tracing::info!(%hive, %agent, %account, revoked = query.revoke, "matrix account deleted");
Ok(StatusCode::NO_CONTENT)
@ -706,8 +766,8 @@ pub(crate) mod tests {
use swarm_secret_client::Error;
use super::{
AccountKind, AccountStore, LinkedAccount, Removal, linked_accounts, remove_matrix,
remove_plain,
AccountKind, AccountStore, LinkedAccount, Removal, linked_accounts, passphrase_to_delete,
remove_matrix, remove_plain,
};
use swarm_secret_client::{forge, github, gitlab};
@ -721,6 +781,8 @@ pub(crate) mod tests {
denied: bool,
written: Mutex<Vec<String>>,
deleted: Mutex<Vec<String>>,
/// Paths whose delete the store refuses.
refusing_delete: Vec<String>,
}
impl FakeStore {
@ -732,6 +794,12 @@ pub(crate) mod tests {
}
}
/// A store that refuses to delete `path`, and takes every other call.
pub(crate) fn refusing_delete_of(mut self, path: &str) -> Self {
self.refusing_delete.push(path.to_owned());
self
}
pub(crate) fn with(self, path: &str, object: Value) -> Self {
self.objects
.lock()
@ -799,7 +867,7 @@ pub(crate) mod tests {
}
async fn delete_all_versions(&self, path: &str) -> Result<(), Error> {
if self.denied {
if self.denied || self.refusing_delete.iter().any(|p| p == path) {
return Err(Error::MissingEnv("BAO_ADDR"));
}
self.deleted
@ -954,6 +1022,7 @@ pub(crate) mod tests {
remove_matrix(
&store,
"swarm/agents/atlas/matrix/catgirl",
None,
None::<NoRevoke>,
)
.await
@ -989,6 +1058,7 @@ pub(crate) mod tests {
remove_matrix(
&store,
"swarm/agents/atlas/matrix/catgirl",
None,
None::<NoRevoke>,
)
.await,
@ -1015,6 +1085,7 @@ pub(crate) mod tests {
remove_matrix(
&store,
"swarm/agents/atlas/matrix/catgirl",
None,
Some(|homeserver: String, token: String| {
*asked.lock().expect("not poisoned") = Some((homeserver, token));
std::future::ready(Ok(()))
@ -1038,6 +1109,7 @@ pub(crate) mod tests {
let removal = remove_matrix(
&store,
"swarm/agents/atlas/matrix/catgirl",
None,
Some(|_: String, _: String| {
std::future::ready(Err("/logout HTTP 502 Bad Gateway: down".to_owned()))
}),
@ -1058,6 +1130,7 @@ pub(crate) mod tests {
let removal = remove_matrix(
&store,
"swarm/agents/atlas/matrix/old",
None,
Some(
|_: String, _: String| -> std::future::Ready<Result<(), String>> {
panic!("there is no homeserver to call")
@ -1211,4 +1284,180 @@ pub(crate) mod tests {
}
assert_eq!(deleted(&store).len(), 1);
}
const CATGIRL: &str = "swarm/agents/atlas/matrix/catgirl";
const CATGIRL_PASSPHRASE: &str = "swarm/agents/atlas/matrix-recovery/catgirl";
/// `every_kind` plus the passphrase minted for `catgirl`.
fn with_passphrase() -> FakeStore {
every_kind().with(CATGIRL_PASSPHRASE, json!({"value": "backup-passphrase"}))
}
fn logged_out() -> impl FnOnce(String, String) -> std::future::Ready<Result<(), String>> {
|_: String, _: String| std::future::ready(Ok(()))
}
#[tokio::test]
async fn revoking_deletes_the_key_backup_passphrase_after_the_account() {
let store = with_passphrase();
remove_matrix(
&store,
CATGIRL,
Some(CATGIRL_PASSPHRASE),
Some(logged_out()),
)
.await
.expect("revoked");
assert_eq!(deleted(&store), [CATGIRL, CATGIRL_PASSPHRASE]);
}
#[tokio::test]
async fn a_plain_delete_keeps_the_key_backup_passphrase() {
let store = with_passphrase();
remove_matrix(&store, CATGIRL, None, None::<NoRevoke>)
.await
.expect("deleted");
assert_eq!(deleted(&store), [CATGIRL]);
}
/// The path the handler hands `remove_matrix`: one for a revoking delete,
/// none for a plain one.
#[test]
fn only_a_revoking_delete_names_the_passphrase() {
assert_eq!(
passphrase_to_delete(true, "atlas", "catgirl").expect("a path"),
Some(CATGIRL_PASSPHRASE.to_owned())
);
assert_eq!(
passphrase_to_delete(false, "atlas", "catgirl").expect("no path"),
None
);
assert!(passphrase_to_delete(true, "atlas", "a/b").is_err());
}
#[tokio::test]
async fn a_relink_after_a_plain_delete_finds_the_same_passphrase() {
use crate::matrix_account::recovery::{Outcome, PassphraseStore, ensure};
/// The recovery pass's view of the fake: a path is held while its
/// object is stored and nothing has deleted it.
struct Held<'a>(&'a FakeStore);
impl PassphraseStore for Held<'_> {
async fn exists(&self, path: &str) -> Result<bool, Error> {
Ok(self
.0
.objects
.lock()
.expect("not poisoned")
.contains_key(path)
&& !deleted(self.0).iter().any(|p| p == path))
}
async fn create(
&self,
path: &str,
value: &swarm_secret_client::matrix::Recovery,
) -> Result<(), Error> {
self.0.write(path, &json!({"value": value.value})).await
}
}
let store = with_passphrase();
remove_matrix(&store, CATGIRL, None, None::<NoRevoke>)
.await
.expect("unlinked");
assert_eq!(
ensure(&Held(&store), CATGIRL_PASSPHRASE)
.await
.expect("checked"),
Outcome::Present
);
assert!(store.written().is_empty(), "nothing is minted");
// The control: after a revoking delete the next pass mints a new one.
let store = with_passphrase();
remove_matrix(
&store,
CATGIRL,
Some(CATGIRL_PASSPHRASE),
Some(logged_out()),
)
.await
.expect("revoked");
assert_eq!(
ensure(&Held(&store), CATGIRL_PASSPHRASE)
.await
.expect("checked"),
Outcome::Minted
);
}
#[tokio::test]
async fn a_passphrase_that_will_not_delete_is_reported_after_the_account_went() {
let store = with_passphrase().refusing_delete_of(CATGIRL_PASSPHRASE);
let removal = remove_matrix(
&store,
CATGIRL,
Some(CATGIRL_PASSPHRASE),
Some(logged_out()),
)
.await
.expect_err("the store refused");
assert!(matches!(removal, Removal::Recovery(_)), "{removal:?}");
assert_eq!(deleted(&store), [CATGIRL]);
let problem = removal.problem();
assert_eq!(
problem.status,
Some(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
);
let detail = problem.detail.expect("a detail");
assert!(detail.contains("key-backup passphrase"), "{detail}");
}
#[tokio::test]
async fn a_missing_passphrase_is_already_deleted() {
// `every_kind` stores no passphrase: the store answers a delete of a
// path it does not hold with success, as the real one does.
let store = every_kind();
remove_matrix(
&store,
CATGIRL,
Some(CATGIRL_PASSPHRASE),
Some(logged_out()),
)
.await
.expect("revoked");
assert_eq!(deleted(&store), [CATGIRL, CATGIRL_PASSPHRASE]);
}
#[tokio::test]
async fn sending_a_revoking_delete_again_finishes_what_stopped_at_the_passphrase() {
// The account is gone and the passphrase is not: the first send left
// exactly this. The second must not stop at "no such account".
let store = FakeStore::default().with(CATGIRL_PASSPHRASE, json!({"value": "p"}));
remove_matrix(
&store,
CATGIRL,
Some(CATGIRL_PASSPHRASE),
Some(logged_out()),
)
.await
.expect("finished");
assert_eq!(deleted(&store), [CATGIRL_PASSPHRASE]);
// Without revoke, the same request is still a 404.
let removal = remove_matrix(&store, CATGIRL, None, None::<NoRevoke>)
.await
.expect_err("nothing is stored");
assert!(matches!(removal, Removal::NotFound), "{removal:?}");
}
#[tokio::test]
async fn a_plain_delete_through_the_route_leaves_the_passphrase() {
let store = Arc::new(with_passphrase());
let status = delete_matrix(&store, "catgirl", false)
.await
.expect("stored");
assert_eq!(status, axum::http::StatusCode::NO_CONTENT);
assert_eq!(deleted(&store), [CATGIRL]);
}
}