keep the operator matrix admin grant record in nats kv, not on disk
This commit is contained in:
parent
c24f3c3d88
commit
28d847cb7e
6 changed files with 312 additions and 87 deletions
|
|
@ -136,13 +136,15 @@ each member not yet in `#admins:<server_name>` it sends
|
|||
lands on.
|
||||
|
||||
- **Leaving `admins` revokes what the sync granted.** The controller
|
||||
records each account it sends a grant for in
|
||||
`/var/lib/swarm-controller/operator-matrix-admins.json`. When one of
|
||||
them is no longer in `admins` but still in `#admins`, it sends
|
||||
records each account it sends a grant for under the key `granted` of the
|
||||
`operator-matrix-admins` NATS KV bucket, which only the controller writes.
|
||||
An upgraded controller imports the old
|
||||
`/var/lib/swarm-controller/operator-matrix-admins.json` once and deletes it.
|
||||
When one of them is no longer in `admins` but still in `#admins`, it sends
|
||||
`!admin users force-leave-room @<name>:<server_name> <admin room id>`
|
||||
there as `@swarm`; leaving that room is what ends homeserver admin.
|
||||
- **Admins the sync didn't make keep admin.** An admin missing from that
|
||||
file, `@swarm`, the server user `@conduit:<server_name>`, every agent's
|
||||
record, `@swarm`, the server user `@conduit:<server_name>`, every agent's
|
||||
account, and every user id in
|
||||
`services.hyperhive.deploy.swarm-controller.matrixAdminSync.ignoreUsers` are never
|
||||
revoked.
|
||||
|
|
|
|||
|
|
@ -573,13 +573,22 @@ the store answers that it holds none, never because a read failed.
|
|||
|
||||
<!-- vale write-good.Passive = YES -->
|
||||
|
||||
- `operator-matrix-admins.json` — the matrix user ids the operator admin
|
||||
sync has made homeserver admin, a JSON array. The sync revokes admin
|
||||
only from these, so deleting the file leaves every current admin in
|
||||
place; a missing file is an empty set. A file the controller can't
|
||||
read or parse stops the sync, grants included, and the controller logs
|
||||
`operator matrix admin: pass failed` on every pass. See
|
||||
[`docs/2-handbook/swarm/matrix.md`](../../2-handbook/swarm/matrix.md#operators-are-homeserver-admins).
|
||||
The operator admin sync's set of granted matrix user ids isn't kept here. It
|
||||
lives in the `operator-matrix-admins` NATS KV bucket, under the key
|
||||
`granted`, as a JSON array. Only the controller reads or writes it. The sync
|
||||
revokes admin only from ids in that set, so a missing key leaves every
|
||||
current admin in place; a key it can't parse stops the sync, grants
|
||||
included, and the controller logs `operator matrix admin: pass failed` on
|
||||
every pass. A controller that finds no key and an
|
||||
`operator-matrix-admins.json` in this directory imports the file into the
|
||||
key and deletes the file; the upgrade needs no manual step. See
|
||||
[matrix.md](../../2-handbook/swarm/matrix.md#operators-are-homeserver-admins).
|
||||
|
||||
Everything else here is rebuildable once the store holds the webhook secret:
|
||||
the legacy `webhook-secret` file, the forge avatar markers
|
||||
`forge-config-org-avatar-set` and `forge-service-avatar-<login>` (losing one
|
||||
costs one re-upload), and the optional host-only `bao-client.pem` and
|
||||
`bao-client-key.pem`.
|
||||
|
||||
## Run-time dirs
|
||||
|
||||
|
|
|
|||
|
|
@ -126,8 +126,10 @@ The swarm's control plane. The swarm UI and `swarmctl` are its clients.
|
|||
→ [`docs/4-implementation/swarm/credentials-reference.md`](../docs/4-implementation/swarm/credentials-reference.md).
|
||||
|
||||
It reads its configuration once at startup, from the environment the nix module
|
||||
sets. It keeps the webhook HMAC secret in the secret store and
|
||||
`operator-matrix-admins.json` in its state directory.
|
||||
sets. It keeps the webhook HMAC secret in the secret store and the
|
||||
operator admin sync's granted set in the `operator-matrix-admins` KV bucket,
|
||||
which this daemon alone reads and writes. Its state directory holds only files
|
||||
it can rebuild.
|
||||
The job graph lives in memory; hive status and wanted state live in the swarm
|
||||
queue, so both survive a restart.
|
||||
|
||||
|
|
|
|||
|
|
@ -11,8 +11,9 @@
|
|||
//!
|
||||
//! It keeps the webhook HMAC secret in the swarm secret store (see `webhook`),
|
||||
//! because that key is handed to Forgejo at registration and so cannot be
|
||||
//! regenerated per boot, and the operator admin sync's granted set under its
|
||||
//! `StateDirectory` (see `matrix_account::operator_admin`).
|
||||
//! regenerated per boot, and the operator admin sync's granted set in a NATS
|
||||
//! KV bucket (see `matrix_account::operator_admin`). Its `StateDirectory` holds
|
||||
//! only files it can re-derive.
|
||||
//!
|
||||
//! Distinct from `hive-c0re`, which is per-hive: c0re owns the agents on
|
||||
//! one host, this owns what is true across hives.
|
||||
|
|
@ -181,7 +182,7 @@ async fn main() -> Result<()> {
|
|||
hive_jobq::resources::ResourceTable::new(),
|
||||
)));
|
||||
let hives = load_hives().into_entries();
|
||||
spawn_matrix_account_backfill(&jobq, deps.matrix_homeserver.clone(), auth.clone());
|
||||
spawn_matrix_account_backfill(&jobq, &deps);
|
||||
spawn_jobq_worker(Arc::clone(&jobq), deps);
|
||||
// Bound to a named variable, not `_` — dropping the provider stops its
|
||||
// `PeriodicReader`, so it must live as long as `main` does (which it
|
||||
|
|
|
|||
|
|
@ -4,23 +4,26 @@
|
|||
//! sync made admin loses it once its owner leaves the group.
|
||||
//!
|
||||
//! The account an operator's SSO login lands on is named after authelia's
|
||||
//! `preferred_username`, lowercased: `hive-matrix.nix` sets `userid_claims`,
|
||||
//! and tuwunel lowercases the claim and refuses one that is not a legal
|
||||
//! localpart. [`localpart`] applies the same rule.
|
||||
//! `preferred_username`, lowercased: `hive-matrix.nix` sets `userid_claims`, and
|
||||
//! tuwunel refuses an illegal localpart. [`localpart`] applies the same rule.
|
||||
//!
|
||||
//! Both commands go to the admin room `#admins:<server>` as `@swarm`, with the
|
||||
//! swarm appservice token: `@swarm` is the one account the homeserver promotes
|
||||
//! at boot, and tuwunel runs a command only when its sender is already an
|
||||
//! admin. Being an admin *is* being joined to that room. The grant,
|
||||
//! `!admin users make-user-admin <user>`, goes to each operator outside the
|
||||
//! room who has an account; the revoke is
|
||||
//! admin. Being an admin *is* being joined to that room. The grant is
|
||||
//! `!admin users make-user-admin <user>`, the revoke
|
||||
//! `!admin users force-leave-room <user> <room>`.
|
||||
//!
|
||||
//! The revoke reaches only the user ids in [`GRANTED_FILE`], those this sync
|
||||
//! The revoke reaches only the user ids in the granted set, those this sync
|
||||
//! sent a grant for, and never `@swarm`, the server user, an agent's account
|
||||
//! or a user id in [`IGNORE_USERS_ENV`]. One that would leave no admin but
|
||||
//! `@swarm` and the server user is held back and logged.
|
||||
//!
|
||||
//! The granted set is key [`KEY`] in the [`BUCKET`] KV bucket, written only by
|
||||
//! this daemon, against the revision the pass read: a concurrent pass loses
|
||||
//! and fails, and the next one rebuilds from the key and its sent grants. With
|
||||
//! no key, [`LEGACY_FILE`] is imported and deleted; with neither, it is empty.
|
||||
//!
|
||||
//! The bot's reply is not read, and each command is sent **at most once per
|
||||
//! account per controller process**: one still unconfirmed on a later pass is
|
||||
//! logged as `… failed to take` and not sent again until the controller
|
||||
|
|
@ -31,11 +34,13 @@ use std::path::Path;
|
|||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use async_nats::jetstream::kv::Store;
|
||||
use swarm_matrix_client::{self as homeserver, Whoami};
|
||||
use swarm_secret_client::{client::DEFAULT_CERT_MOUNT, policy};
|
||||
|
||||
use super::agent_token::appservice_token;
|
||||
use crate::auth::AuthBridge;
|
||||
use crate::schedules::{read_with, write, write_revision};
|
||||
|
||||
/// How often [`spawn`] re-checks the operator group.
|
||||
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
|
||||
|
|
@ -48,10 +53,18 @@ const ADMIN_ROOM_ALIAS_LOCALPART: &str = "admins";
|
|||
/// `hive-matrix.nix` does not set it.
|
||||
const SERVER_USER_LOCALPART: &str = "conduit";
|
||||
|
||||
/// The set of user ids this sync sent a grant for, a JSON array, in the
|
||||
/// controller's state directory. A missing file is an empty set. A revoked
|
||||
/// user id stays in it until a pass sees it out of the admin room.
|
||||
const GRANTED_FILE: &str = "operator-matrix-admins.json";
|
||||
/// The bucket holding the granted set. No other service holds a grant on it.
|
||||
pub const BUCKET: &str = "operator-matrix-admins";
|
||||
|
||||
/// The one key in [`BUCKET`]: the set of user ids this sync sent a grant for,
|
||||
/// a JSON array. No key is an empty set. A revoked user id stays in it until a
|
||||
/// pass sees it out of the admin room.
|
||||
pub const KEY: &str = "granted";
|
||||
|
||||
/// The file in the controller's state directory that held the granted set
|
||||
/// before it moved to [`BUCKET`], in the same JSON format. It is imported
|
||||
/// when [`KEY`] is absent and deleted once [`KEY`] exists.
|
||||
const LEGACY_FILE: &str = "operator-matrix-admins.json";
|
||||
|
||||
/// Whitespace-separated user ids the revoke never touches, set from
|
||||
/// `services.hyperhive.deploy.swarm-controller.matrixAdminSync.ignoreUsers`.
|
||||
|
|
@ -113,7 +126,7 @@ pub fn plan(
|
|||
plan
|
||||
}
|
||||
|
||||
/// What one pass decided about the user ids in [`GRANTED_FILE`].
|
||||
/// What one pass decided about the user ids in the granted set.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub struct Revokes {
|
||||
/// No longer operators and still admins: sent a revoke.
|
||||
|
|
@ -169,28 +182,107 @@ fn parse_ignore_users(raw: &str) -> BTreeSet<String> {
|
|||
raw.split_whitespace().map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
/// The set stored at `path`; empty when there is no file.
|
||||
fn load_granted(path: &Path) -> Result<BTreeSet<String>> {
|
||||
/// The granted set as stored, with the revision to write it back against.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct Granted {
|
||||
set: BTreeSet<String>,
|
||||
/// The revision of [`KEY`], `None` when no key exists yet.
|
||||
revision: Option<u64>,
|
||||
}
|
||||
|
||||
/// Open [`BUCKET`], creating it if nothing has yet.
|
||||
async fn open(client: &async_nats::Client) -> Result<Store> {
|
||||
let js = async_nats::jetstream::new(client.clone());
|
||||
if let Ok(store) = js.get_key_value(BUCKET).await {
|
||||
return Ok(store);
|
||||
}
|
||||
js.create_key_value(async_nats::jetstream::kv::Config {
|
||||
bucket: BUCKET.to_owned(),
|
||||
description: "The operator accounts the swarm controller made homeserver admin".to_owned(),
|
||||
history: 1,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.with_context(|| format!("creating the {BUCKET} bucket"))
|
||||
}
|
||||
|
||||
/// The set under [`KEY`]. With no key, the set in `legacy` is imported into
|
||||
/// it and the file deleted; with neither, the set is empty. A key or file
|
||||
/// that does not parse is an error, never an empty set: an empty set would
|
||||
/// forget every grant.
|
||||
async fn load_granted(store: &Store, legacy: &Path) -> Result<Granted> {
|
||||
let (stored, revision) = read_with(store, KEY, |bytes| {
|
||||
serde_json::from_slice::<BTreeSet<String>>(bytes)
|
||||
.map(Some)
|
||||
.with_context(|| format!("parsing {KEY} in {BUCKET}"))
|
||||
})
|
||||
.await?;
|
||||
if let Some(set) = stored {
|
||||
remove_legacy(legacy);
|
||||
return Ok(Granted { set, revision });
|
||||
}
|
||||
let Some(set) = read_legacy(legacy)? else {
|
||||
return Ok(Granted {
|
||||
set: BTreeSet::new(),
|
||||
revision,
|
||||
});
|
||||
};
|
||||
let Some(revision) = write_revision(store, KEY, &set, revision).await? else {
|
||||
bail!(
|
||||
"{KEY} in {BUCKET} was written while importing {}",
|
||||
legacy.display()
|
||||
);
|
||||
};
|
||||
tracing::info!(
|
||||
granted = set.len(),
|
||||
file = %legacy.display(),
|
||||
bucket = BUCKET,
|
||||
"imported the granted operator admins from the legacy file"
|
||||
);
|
||||
remove_legacy(legacy);
|
||||
Ok(Granted {
|
||||
set,
|
||||
revision: Some(revision),
|
||||
})
|
||||
}
|
||||
|
||||
/// The set in the legacy file; `None` when there is no file.
|
||||
fn read_legacy(path: &Path) -> Result<Option<BTreeSet<String>>> {
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes)
|
||||
.map(Some)
|
||||
.with_context(|| format!("parsing the granted operator admins in {}", path.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the set stored at `path`: written beside it and renamed over it,
|
||||
/// so a reader sees the old set or the new one, never part of either.
|
||||
fn save_granted(path: &Path, granted: &BTreeSet<String>) -> Result<()> {
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let bytes = serde_json::to_vec(granted).context("encoding the granted operator admins")?;
|
||||
let mut file =
|
||||
std::fs::File::create(&tmp).with_context(|| format!("creating {}", tmp.display()))?;
|
||||
std::io::Write::write_all(&mut file, &bytes)
|
||||
.and_then(|()| file.sync_all())
|
||||
.with_context(|| format!("writing {}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, path)
|
||||
.with_context(|| format!("renaming {} to {}", tmp.display(), path.display()))
|
||||
/// Delete the legacy file. A failure is logged and retried on the next pass:
|
||||
/// the key is the record, so a file that stays is ignored.
|
||||
fn remove_legacy(path: &Path) {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => tracing::info!(file = %path.display(), "deleted the legacy granted-admins file"),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => tracing::warn!(
|
||||
file = %path.display(),
|
||||
error = %e,
|
||||
"could not delete the legacy granted-admins file"
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the set under [`KEY`], against `revision` from [`load_granted`].
|
||||
/// Fails when another write landed since: this pass's decisions rest on a
|
||||
/// set that is no longer current.
|
||||
async fn save_granted(
|
||||
store: &Store,
|
||||
granted: &BTreeSet<String>,
|
||||
revision: Option<u64>,
|
||||
) -> Result<()> {
|
||||
if !write(store, KEY, granted, revision).await? {
|
||||
bail!("{KEY} in {BUCKET} changed during the pass; nothing written");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The server name of a full user id, `@<localpart>:<server>`.
|
||||
|
|
@ -230,8 +322,8 @@ struct AdminRoom<'a> {
|
|||
|
||||
/// One pass: read the operator group, send a grant for each operator who has
|
||||
/// a matrix account, is not an admin, and is not in `memory.sent`, then a
|
||||
/// revoke for each account [`plan_revokes`] picks out of the set stored at
|
||||
/// `granted_path`.
|
||||
/// revoke for each account [`plan_revokes`] picks out of the set stored in
|
||||
/// [`BUCKET`] (see [`load_granted`] for `legacy`).
|
||||
///
|
||||
/// Fails as a whole when the group, the token, the server name, the admin
|
||||
/// room, its members, the agent roster or the stored set cannot be read: with
|
||||
|
|
@ -240,17 +332,18 @@ async fn pass(
|
|||
bridge: &AuthBridge,
|
||||
base: &str,
|
||||
ignore: &BTreeSet<String>,
|
||||
granted_path: &Path,
|
||||
queue: &async_nats::Client,
|
||||
legacy: &Path,
|
||||
memory: &mut Memory,
|
||||
) -> Result<Outcome> {
|
||||
let operators = bridge
|
||||
.list_operators()
|
||||
.await
|
||||
.context("reading authelia's operator group")?;
|
||||
let store = crate::store::connect()
|
||||
let secrets = crate::store::connect()
|
||||
.await
|
||||
.context("logging in to the swarm secret store")?;
|
||||
let token = appservice_token(&store).await?;
|
||||
let token = appservice_token(&secrets).await?;
|
||||
let http = homeserver::client()?;
|
||||
let Whoami::User(sender) = homeserver::whoami(&http, base, &token)
|
||||
.await
|
||||
|
|
@ -268,12 +361,13 @@ async fn pass(
|
|||
)
|
||||
.await?;
|
||||
let admins = homeserver::joined_members(&http, base, &token, &room).await?;
|
||||
let roles = store
|
||||
let roles = secrets
|
||||
.list_cert_roles(DEFAULT_CERT_MOUNT)
|
||||
.await
|
||||
.context("listing the store's cert-auth roles")?;
|
||||
let stored = load_granted(granted_path)?;
|
||||
let mut granted: BTreeSet<String> = stored.union(&memory.sent).cloned().collect();
|
||||
let store = open(queue).await?;
|
||||
let stored = load_granted(&store, legacy).await?;
|
||||
let mut granted: BTreeSet<String> = stored.set.union(&memory.sent).cloned().collect();
|
||||
let admin_room = AdminRoom {
|
||||
http: &http,
|
||||
base,
|
||||
|
|
@ -313,8 +407,8 @@ async fn pass(
|
|||
);
|
||||
send_revokes(&admin_room, &revokes, memory, &mut granted, &mut outcome).await;
|
||||
|
||||
if granted != stored {
|
||||
save_granted(granted_path, &granted)?;
|
||||
if granted != stored.set {
|
||||
save_granted(&store, &granted, stored.revision).await?;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
|
@ -466,15 +560,15 @@ async fn grant(
|
|||
|
||||
/// Run [`pass`] now and every [`RECONCILE_INTERVAL`] after. A pass that fails
|
||||
/// is logged and retried on the next tick; it never stops the daemon.
|
||||
pub fn spawn(bridge: Arc<AuthBridge>, base: Arc<str>) {
|
||||
pub fn spawn(bridge: Arc<AuthBridge>, base: Arc<str>, queue: async_nats::Client) {
|
||||
let ignore = parse_ignore_users(&std::env::var(IGNORE_USERS_ENV).unwrap_or_default());
|
||||
let granted_path = crate::webhook::state_dir().join(GRANTED_FILE);
|
||||
let legacy = crate::webhook::state_dir().join(LEGACY_FILE);
|
||||
tokio::spawn(async move {
|
||||
let mut memory = Memory::default();
|
||||
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
|
||||
loop {
|
||||
ticker.tick().await;
|
||||
match pass(&bridge, &base, &ignore, &granted_path, &mut memory).await {
|
||||
match pass(&bridge, &base, &ignore, &queue, &legacy, &mut memory).await {
|
||||
Ok(outcome) if outcome.failed > 0 => tracing::warn!(
|
||||
granted = outcome.granted,
|
||||
revoked = outcome.revoked,
|
||||
|
|
@ -747,31 +841,141 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_granted_set_survives_a_save_and_a_load() {
|
||||
let dir = std::env::temp_dir().join(format!("operator-admin-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("mkdir");
|
||||
let path = dir.join(GRANTED_FILE);
|
||||
use crate::test_nats::TestNats;
|
||||
|
||||
let missing = load_granted(&path);
|
||||
let set = ids(&["@mara:t.local", "@ex:t.local"]);
|
||||
save_granted(&path, &set).expect("first save");
|
||||
let first = load_granted(&path);
|
||||
save_granted(&path, &ids(&["@mara:t.local"])).expect("second save");
|
||||
let second = load_granted(&path);
|
||||
let leftovers: Vec<_> = std::fs::read_dir(&dir)
|
||||
.expect("list")
|
||||
.map(|e| e.expect("entry").file_name())
|
||||
.collect();
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
/// A store on a fresh server, and a directory standing for the state
|
||||
/// directory. The server lives as long as the first value.
|
||||
async fn fixture() -> (TestNats, Store, tempfile::TempDir) {
|
||||
let nats = TestNats::start();
|
||||
let store = open(&nats.client().await).await.expect("bucket");
|
||||
let dir = tempfile::tempdir().expect("state dir");
|
||||
(nats, store, dir)
|
||||
}
|
||||
|
||||
assert_eq!(missing.expect("a missing file loads"), BTreeSet::new());
|
||||
assert_eq!(first.expect("loads"), set);
|
||||
assert_eq!(second.expect("loads"), ids(&["@mara:t.local"]));
|
||||
fn stored_in(dir: &tempfile::TempDir) -> std::path::PathBuf {
|
||||
dir.path().join(LEGACY_FILE)
|
||||
}
|
||||
|
||||
async fn raw(store: &Store) -> Option<BTreeSet<String>> {
|
||||
let bytes = store.get(KEY).await.expect("read")?;
|
||||
Some(serde_json::from_slice(&bytes).expect("a JSON array"))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn with_no_key_and_no_file_the_set_is_empty_and_nothing_is_written() {
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let loaded = load_granted(&store, &stored_in(&dir)).await.expect("loads");
|
||||
assert_eq!(
|
||||
leftovers,
|
||||
[GRANTED_FILE],
|
||||
"no temporary file is left beside it"
|
||||
loaded,
|
||||
Granted {
|
||||
set: BTreeSet::new(),
|
||||
revision: None
|
||||
}
|
||||
);
|
||||
assert_eq!(raw(&store).await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_legacy_file_is_imported_once_and_deleted() {
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let file = stored_in(&dir);
|
||||
std::fs::write(&file, br#"["@mara:t.local","@ex:t.local"]"#).expect("legacy file");
|
||||
|
||||
let first = load_granted(&store, &file).await.expect("imports");
|
||||
assert_eq!(first.set, ids(&["@mara:t.local", "@ex:t.local"]));
|
||||
assert!(first.revision.is_some());
|
||||
assert_eq!(raw(&store).await, Some(first.set.clone()));
|
||||
assert!(!file.exists(), "the file is deleted after the import");
|
||||
|
||||
// A later load reads the key, whatever a file would now say.
|
||||
let again = load_granted(&store, &file).await.expect("loads");
|
||||
assert_eq!(again, first);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_imported_grant_is_still_revoked() {
|
||||
// The point of the import: an ex-operator the old controller granted
|
||||
// loses admin under the new one.
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let file = stored_in(&dir);
|
||||
std::fs::write(&file, br#"["@ex:t.local"]"#).expect("legacy file");
|
||||
let loaded = load_granted(&store, &file).await.expect("imports");
|
||||
let revokes = plan_revokes(
|
||||
&loaded.set,
|
||||
&BTreeSet::new(),
|
||||
&ids(&["@swarm:t.local", "@mara:t.local", "@ex:t.local"]),
|
||||
&keepers(),
|
||||
&keepers(),
|
||||
&BTreeSet::new(),
|
||||
);
|
||||
assert_eq!(revokes.revoke, ["@ex:t.local"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_leftover_file_beside_a_key_is_deleted_and_the_key_wins() {
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let file = stored_in(&dir);
|
||||
save_granted(&store, &ids(&["@mara:t.local"]), None)
|
||||
.await
|
||||
.expect("first write");
|
||||
std::fs::write(&file, br#"["@other:t.local"]"#).expect("legacy file");
|
||||
|
||||
let loaded = load_granted(&store, &file).await.expect("loads");
|
||||
assert_eq!(loaded.set, ids(&["@mara:t.local"]));
|
||||
assert!(!file.exists());
|
||||
assert_eq!(raw(&store).await, Some(ids(&["@mara:t.local"])));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unparseable_file_or_key_is_an_error_and_changes_nothing() {
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let file = stored_in(&dir);
|
||||
std::fs::write(&file, b"not json").expect("legacy file");
|
||||
load_granted(&store, &file)
|
||||
.await
|
||||
.expect_err("a bad file is not an empty set");
|
||||
assert!(file.exists(), "the file is kept");
|
||||
assert_eq!(raw(&store).await, None, "nothing is imported");
|
||||
|
||||
std::fs::remove_file(&file).expect("remove");
|
||||
store
|
||||
.put(KEY, b"{}".to_vec().into())
|
||||
.await
|
||||
.expect("put a bad key");
|
||||
load_granted(&store, &file)
|
||||
.await
|
||||
.expect_err("a bad key is not an empty set");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_save_round_trips_and_a_stale_revision_is_refused() {
|
||||
let (_nats, store, dir) = fixture().await;
|
||||
let file = stored_in(&dir);
|
||||
let set = ids(&["@mara:t.local", "@ex:t.local"]);
|
||||
save_granted(&store, &set, None).await.expect("create");
|
||||
let loaded = load_granted(&store, &file).await.expect("loads");
|
||||
assert_eq!(loaded.set, set);
|
||||
|
||||
// Another pass writes between this one's load and its save.
|
||||
let other = ids(&["@mara:t.local"]);
|
||||
save_granted(&store, &other, loaded.revision)
|
||||
.await
|
||||
.expect("the other pass");
|
||||
save_granted(&store, &BTreeSet::new(), loaded.revision)
|
||||
.await
|
||||
.expect_err("the stale revision loses");
|
||||
assert_eq!(
|
||||
raw(&store).await,
|
||||
Some(other.clone()),
|
||||
"the first write stands"
|
||||
);
|
||||
|
||||
// Two passes that both saw no key: one creates it, the other loses.
|
||||
let (_nats2, fresh, _dir2) = fixture().await;
|
||||
save_granted(&fresh, &set, None).await.expect("creates");
|
||||
save_granted(&fresh, &other, None)
|
||||
.await
|
||||
.expect_err("the key now exists");
|
||||
assert_eq!(raw(&fresh).await, Some(set));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,9 +19,10 @@ use utoipa::OpenApi;
|
|||
use utoipa_axum::{router::OpenApiRouter, routes};
|
||||
|
||||
use crate::jobq::{
|
||||
Late, SwarmNodeKind, SwarmResourceKind, queue_agent_renewals, queue_builder_forge_token_mint,
|
||||
queue_ci_metrics_forge_token_mint, queue_classifier_forge_token_mint, queue_docs_grants,
|
||||
queue_forge_token_mints, queue_hive_forge_token_mints, queue_matrix_account_mints,
|
||||
Late, SwarmNodeKind, SwarmResourceKind, WorkerDeps, queue_agent_renewals,
|
||||
queue_builder_forge_token_mint, queue_ci_metrics_forge_token_mint,
|
||||
queue_classifier_forge_token_mint, queue_docs_grants, queue_forge_token_mints,
|
||||
queue_hive_forge_token_mints, queue_matrix_account_mints,
|
||||
};
|
||||
use crate::routes::hives::{HiveEntry, ServiceLink};
|
||||
use crate::routes::{self, AppState, agents, config_prs, forge_admin, hives, jobq_graph};
|
||||
|
|
@ -262,19 +263,25 @@ pub(crate) fn configured_matrix_homeserver() -> Option<Arc<str>> {
|
|||
|
||||
/// Start the recovery passphrase pass, which needs only the store; the
|
||||
/// matrix-account backfill when a homeserver is configured; and the operator
|
||||
/// admin pass when the bridge is too. Lifted out of `main` for
|
||||
/// admin pass when the bridge and the swarm queue are too. Lifted out of `main` for
|
||||
/// `clippy::too_many_lines`.
|
||||
pub(crate) fn spawn_matrix_account_backfill(
|
||||
jobq: &Arc<Mutex<hive_jobq::scheduler::Scheduler<SwarmNodeKind, SwarmResourceKind>>>,
|
||||
homeserver: Option<Arc<str>>,
|
||||
auth: Option<Arc<auth::AuthBridge>>,
|
||||
deps: &WorkerDeps,
|
||||
) {
|
||||
matrix_account::recovery::spawn();
|
||||
let Some(base) = homeserver else {
|
||||
let Some(base) = deps.matrix_homeserver.clone() else {
|
||||
return;
|
||||
};
|
||||
if let Some(bridge) = auth {
|
||||
matrix_account::operator_admin::spawn(bridge, Arc::clone(&base));
|
||||
match (deps.auth.clone(), deps.queue.clone()) {
|
||||
(Some(bridge), Some(queue)) => {
|
||||
matrix_account::operator_admin::spawn(bridge, Arc::clone(&base), queue);
|
||||
}
|
||||
(Some(_), None) => tracing::warn!(
|
||||
"operator matrix admin: no swarm queue is configured, so the granted set has \
|
||||
nowhere to live; the sync is not started"
|
||||
),
|
||||
(None, _) => {}
|
||||
}
|
||||
let sched = Arc::clone(jobq);
|
||||
matrix_account::agent_token::spawn(base, move |agents| {
|
||||
|
|
|
|||
Loading…
Reference in a new issue