Watch
0
0
Fork
You've already forked hyperhive
0

swarm-controller: move the accounts concern into its own module

Refs #6897
This commit is contained in:
atlas 2026-11-27 13:13:28 +01:00
commit 9b2ba275d8
10 changed files with 22 additions and 15 deletions

View file

@ -0,0 +1,257 @@
//! An agent's accounts on external forges: an operator hands us a base URL and
//! a token, we put them in the swarm's secret store.
//!
//! The agent end is `nix/agent-modules/forge-accounts.nix`, which lists the
//! agent's accounts and reads each under the agent's own certificate, and writes
//! the files `hive-forge -f <label>` reads. No hive is in the path.
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};
use swarm_secret_client::forge;
use utoipa::ToSchema;
use super::linked_accounts::link;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
/// The account to store for one agent's external forge.
///
/// No `Debug` derive: this carries a token.
#[derive(Deserialize, ToSchema)]
pub struct PutForgeAccountRequest {
/// The forge's base URL, `http://` or `https://`. A trailing slash is
/// dropped.
#[schema(example = "https://forge.example.org")]
url: String,
/// The access token. Never logged, and never returned by this route.
token: String,
}
/// `put_forge_account`'s success body.
#[derive(Debug, Serialize, ToSchema)]
pub struct PutForgeAccountResponse {
/// The base URL as stored.
url: String,
}
/// Store an agent's external forge account, unless one is stored under the
/// label already.
#[utoipa::path(
put,
path = "/api/hives/{hive}/agents/{agent}/forge-accounts/{label}",
params(
("hive" = String, Path, description = "hive the agent runs on"),
("agent" = String, Path, description = "agent the account belongs to"),
("label" = String, Path, description = "the name the agent passes to `hive-forge -f`"),
),
request_body = PutForgeAccountRequest,
responses(
(status = 200, description = "stored", body = PutForgeAccountResponse),
(status = 400, description = "the agent or label is not an identifier, the URL is not http(s), the token is empty, or the hive is not in this swarm (problem+json)", body = String),
(status = 409, description = "an account is stored under the label already; nothing was written (problem+json)", body = String),
(status = 500, description = "the store could not be read or written (problem+json)", body = String),
),
tag = "agents"
)]
pub async fn put_forge_account(
State(state): State<AppState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutForgeAccountRequest>,
) -> Result<Json<PutForgeAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let agent = hive_types::Ident::parse(&agent)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
// `hive-forge` accepts only `[a-z0-9-]` after `-f`, narrower than the
// store's charset, so a label it would refuse is refused here.
let label = hive_types::Ident::parse(&label)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
let secret_path = forge::account_path(&agent, &label)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
let account = account(req).map_err(|e| error_problem(StatusCode::BAD_REQUEST, e))?;
let store = state.accounts.open().await.map_err(|e| {
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
link(&store, &secret_path, &account).await.map_err(|e| {
// The path names the agent and the label; the value is not in it.
tracing::warn!(path = %secret_path, error = ?e, "linking the forge account failed");
e.problem(&existing(&agent, &label))
})?;
crate::link_egress::added(
&state,
&agent,
&crate::link_egress::Link::Forge {
label: &label,
url: &account.url,
},
)
.await?;
tracing::info!(%hive, %agent, %label, url = %account.url, "forge account stored");
Ok(Json(PutForgeAccountResponse { url: account.url }))
}
/// The account a refused link names.
fn existing(agent: &str, label: &str) -> String {
format!("agent {agent} already has forge account {label:?}")
}
/// The request as it is stored, or why it cannot be.
fn account(req: PutForgeAccountRequest) -> Result<forge::Account, &'static str> {
let url = req.url.trim().trim_end_matches('/');
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("url must start with http:// or https://");
}
if req.token.trim().is_empty() {
return Err("token is required");
}
Ok(forge::Account {
value: req.token,
url: url.to_owned(),
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::super::linked_accounts::{Accounts, tests::FakeStore};
use super::{PutForgeAccountRequest, account};
fn request(url: &str, token: &str) -> PutForgeAccountRequest {
PutForgeAccountRequest {
url: url.to_owned(),
token: token.to_owned(),
}
}
#[test]
fn the_url_loses_its_trailing_slash_and_the_token_is_kept() {
let a = account(request("https://forge.example.org/ ", "t0k3n")).expect("valid");
assert_eq!(a.url, "https://forge.example.org");
assert_eq!(a.value, "t0k3n");
}
#[test]
fn a_url_that_is_not_http_is_refused() {
assert!(account(request("forge.example.org", "t")).is_err());
assert!(account(request("file:///etc/passwd", "t")).is_err());
// The control: plain http is accepted.
assert!(account(request("http://forge.lan", "t")).is_ok());
}
#[test]
fn an_empty_token_is_refused() {
assert!(account(request("https://forge.example.org", " ")).is_err());
}
/// Bare-minimum `AppState`, as `matrix_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
hives: std::sync::Arc::new(vec![crate::routes::hives::HiveEntry {
name: "pr1ma".to_owned(),
domain: "pr1ma.example".to_owned(),
dashboard: "pr1ma.hives.example".to_owned(),
}]),
links: std::sync::Arc::new(Vec::new()),
status: None,
wanted: None,
agent_status: None,
agent_icons: None,
agents_md: None,
reported_inference: None,
agent_login: None,
jobq: std::sync::Arc::new(std::sync::Mutex::new(hive_jobq::scheduler::Scheduler::new(
hive_jobq::Graph::new(),
hive_jobq::resources::ResourceTable::new(),
))),
webhook_secret: std::sync::Arc::default(),
config_prs: std::sync::Arc::default(),
swarm_name: None,
auth: None,
forge: std::sync::Arc::default(),
create_gate: std::sync::Arc::default(),
accounts: Accounts::Fake(Arc::clone(store)),
try_outs: crate::review_classifier::TryOuts::default(),
reviews: std::sync::Arc::default(),
runs: crate::review_classifier::runs::Runs::Live(None),
builds: crate::builder::runs::Builds::Live(None),
alerts: None,
}
}
async fn put(
store: &Arc<FakeStore>,
label: &str,
) -> Result<axum::Json<super::PutForgeAccountResponse>, problem_details::ProblemDetails> {
super::put_forge_account(
axum::extract::State(state(store)),
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned(), label.to_owned())),
axum::Json(request("https://forge.example.org", "t0k3n")),
)
.await
}
/// A label `hive-forge -f` could not name is refused before the store.
#[tokio::test]
async fn a_label_hive_forge_cannot_name_is_refused_before_the_store() {
let store = Arc::default();
for bad in ["MyForge", "my_forge", "../x"] {
let problem = put(&store, bad).await.expect_err("refused");
assert_eq!(
problem.status,
Some(axum::http::StatusCode::BAD_REQUEST),
"{bad}: {problem:?}"
);
}
assert!(store.written().is_empty());
}
/// The control: a plain label is written.
#[tokio::test]
async fn a_plain_label_reaches_the_store() {
let store = Arc::default();
let stored = put(&store, "myforge").await.expect("nothing is stored");
assert_eq!(stored.url, "https://forge.example.org");
assert_eq!(store.written(), ["swarm/agents/atlas/forge/myforge"]);
}
#[tokio::test]
async fn linking_a_label_twice_is_a_409_and_the_first_account_stays() {
use super::super::linked_accounts::{AccountStore, link};
use swarm_secret_client::forge;
let store = FakeStore::default();
let path = forge::account_path("atlas", "myforge").expect("a valid path");
let first = account(request("https://forge.example.org", "t0k3n-first")).expect("valid");
let second = account(request("https://forge.lan", "t0k3n-second")).expect("valid");
link(&store, &path, &first)
.await
.expect("nothing is stored");
let problem = link(&store, &path, &second)
.await
.expect_err("an account is stored")
.problem(&super::existing("atlas", "myforge"));
assert_eq!(problem.status, Some(axum::http::StatusCode::CONFLICT));
let detail = problem.detail.expect("a detail");
assert!(
detail.contains(r#"agent atlas already has forge account "myforge""#),
"{detail}"
);
assert_eq!(store.written(), std::slice::from_ref(&path));
let kept: forge::Account = store
.read_optional(&path)
.await
.expect("store answers")
.expect("still stored");
assert_eq!(kept.url, "https://forge.example.org");
assert_eq!(kept.value, "t0k3n-first");
}
}

View file

@ -0,0 +1,230 @@
//! An agent's GitHub personal access token: an operator hands us the token, we
//! put it in the swarm's secret store.
//!
//! The agent end is `nix/agent-modules/github-token.nix`, which reads it under
//! the agent's own certificate into the file under `/run` its `gh` wrapper,
//! git credential helper and `hive-github-notify` read. No hive is in the path.
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::Deserialize;
use swarm_secret_client::github;
use utoipa::ToSchema;
use super::linked_accounts::link;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
/// The token to store for one agent.
///
/// No `Debug` derive: this carries a token.
#[derive(Deserialize, ToSchema)]
pub struct PutGithubAccountRequest {
/// The personal access token. Never logged, and never returned by this
/// route.
token: String,
}
/// Store an agent's GitHub token, unless it has one stored already.
#[utoipa::path(
put,
path = "/api/hives/{hive}/agents/{agent}/github-account",
params(
("hive" = String, Path, description = "hive the agent runs on"),
("agent" = String, Path, description = "agent the token belongs to"),
),
request_body = PutGithubAccountRequest,
responses(
(status = 204, description = "stored"),
(status = 400, description = "the agent is not an identifier, the token is empty, or the hive is not in this swarm (problem+json)", body = String),
(status = 409, description = "the agent has a token stored already; nothing was written (problem+json)", body = String),
(status = 500, description = "the store could not be read or written (problem+json)", body = String),
),
tag = "agents"
)]
pub async fn put_github_account(
State(state): State<AppState>,
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
Json(req): Json<PutGithubAccountRequest>,
) -> Result<StatusCode, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let agent = hive_types::Ident::parse(&agent)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
let secret_path = github::account_path(&agent)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
let credential = credential(&req).map_err(|e| error_problem(StatusCode::BAD_REQUEST, e))?;
let store = state.accounts.open().await.map_err(|e| {
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
link(&store, &secret_path, &credential).await.map_err(|e| {
// The path names the agent; the value is not in it.
tracing::warn!(path = %secret_path, error = ?e, "linking the github token failed");
e.problem(&existing(&agent))
})?;
crate::link_egress::added(&state, &agent, &crate::link_egress::Link::Github).await?;
tracing::info!(%hive, %agent, "github token stored");
Ok(StatusCode::NO_CONTENT)
}
/// The token a refused link names.
fn existing(agent: &str) -> String {
format!("agent {agent} already has a github token")
}
/// The request as it is stored, or why it cannot be.
fn credential(req: &PutGithubAccountRequest) -> Result<github::Credential, &'static str> {
let token = req.token.trim();
if token.is_empty() {
return Err("token is required");
}
Ok(github::Credential {
value: token.to_owned(),
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::super::linked_accounts::{Accounts, tests::FakeStore};
use super::{PutGithubAccountRequest, credential};
fn request(token: &str) -> PutGithubAccountRequest {
PutGithubAccountRequest {
token: token.to_owned(),
}
}
#[test]
fn the_token_is_kept_without_surrounding_whitespace() {
let c = credential(&request(" t0k3n\n")).expect("valid");
assert_eq!(c.value, "t0k3n");
}
#[test]
fn an_empty_token_is_refused() {
assert!(credential(&request(" ")).is_err());
assert!(credential(&request("")).is_err());
}
/// Bare-minimum `AppState`, as `forge_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
hives: std::sync::Arc::new(vec![crate::routes::hives::HiveEntry {
name: "pr1ma".to_owned(),
domain: "pr1ma.example".to_owned(),
dashboard: "pr1ma.hives.example".to_owned(),
}]),
links: std::sync::Arc::new(Vec::new()),
status: None,
wanted: None,
agent_status: None,
agent_icons: None,
agents_md: None,
reported_inference: None,
agent_login: None,
jobq: std::sync::Arc::new(std::sync::Mutex::new(hive_jobq::scheduler::Scheduler::new(
hive_jobq::Graph::new(),
hive_jobq::resources::ResourceTable::new(),
))),
webhook_secret: std::sync::Arc::default(),
config_prs: std::sync::Arc::default(),
swarm_name: None,
auth: None,
forge: std::sync::Arc::default(),
create_gate: std::sync::Arc::default(),
accounts: Accounts::Fake(Arc::clone(store)),
try_outs: crate::review_classifier::TryOuts::default(),
reviews: std::sync::Arc::default(),
runs: crate::review_classifier::runs::Runs::Live(None),
builds: crate::builder::runs::Builds::Live(None),
alerts: None,
}
}
async fn put(
store: &Arc<FakeStore>,
agent: &str,
token: &str,
) -> Result<axum::http::StatusCode, problem_details::ProblemDetails> {
super::put_github_account(
axum::extract::State(state(store)),
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned())),
axum::Json(request(token)),
)
.await
}
/// An agent name or an empty token is refused before the store.
#[tokio::test]
async fn a_bad_agent_or_an_empty_token_is_refused_before_the_store() {
let store = Arc::default();
for (agent, token) in [("Atlas", "t0k3n"), ("../x", "t0k3n"), ("atlas", " ")] {
let problem = put(&store, agent, token).await.expect_err("refused");
assert_eq!(
problem.status,
Some(axum::http::StatusCode::BAD_REQUEST),
"{agent:?}: {problem:?}"
);
}
assert!(store.written().is_empty());
}
/// The control: a plain agent and a token are written.
#[tokio::test]
async fn a_plain_request_reaches_the_store() {
use super::super::linked_accounts::AccountStore;
use swarm_secret_client::github;
let store = Arc::default();
let status = put(&store, "atlas", "t0k3n")
.await
.expect("nothing is stored");
assert_eq!(status, axum::http::StatusCode::NO_CONTENT);
assert_eq!(store.written(), ["swarm/agents/atlas/github-token"]);
let stored: github::Credential = store
.read_optional("swarm/agents/atlas/github-token")
.await
.expect("store answers")
.expect("stored");
assert_eq!(stored.value, "t0k3n");
}
#[tokio::test]
async fn linking_a_second_token_is_a_409_and_the_first_stays() {
use super::super::linked_accounts::{AccountStore, link};
use swarm_secret_client::github;
let store = FakeStore::default();
let path = github::account_path("atlas").expect("a valid path");
let first = credential(&request("t0k3n-first")).expect("valid");
let second = credential(&request("t0k3n-second")).expect("valid");
link(&store, &path, &first)
.await
.expect("nothing is stored");
let problem = link(&store, &path, &second)
.await
.expect_err("a token is stored")
.problem(&super::existing("atlas"));
assert_eq!(problem.status, Some(axum::http::StatusCode::CONFLICT));
let detail = problem.detail.expect("a detail");
assert!(
detail.contains("agent atlas already has a github token"),
"{detail}"
);
assert_eq!(store.written(), std::slice::from_ref(&path));
let kept: github::Credential = store
.read_optional(&path)
.await
.expect("store answers")
.expect("still stored");
assert_eq!(kept.value, "t0k3n-first");
}
}

View file

@ -0,0 +1,322 @@
//! An agent's accounts on GitLab instances: an operator hands us a base URL and
//! a token, we put them in the swarm's secret store.
//!
//! The agent end is `nix/agent-modules/gitlab-accounts.nix`, which lists the
//! agent's accounts and reads each under the agent's own certificate, and writes
//! the `glab` configuration. No hive is in the path.
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};
use swarm_secret_client::gitlab;
use utoipa::ToSchema;
use super::linked_accounts::link;
use crate::backend_egress::host_of;
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
/// The account to store for one agent's GitLab instance.
///
/// No `Debug` derive: this carries a token.
#[derive(Deserialize, ToSchema)]
pub struct PutGitlabAccountRequest {
/// The instance's base URL, `http://` or `https://`, with a DNS name as its
/// host. A trailing slash is dropped.
#[schema(example = "https://gitlab.example.org")]
url: String,
/// The access token, scoped `api` and `write_repository`. Never logged, and
/// never returned by this route.
token: String,
}
/// `put_gitlab_account`'s success body.
#[derive(Debug, Serialize, ToSchema)]
pub struct PutGitlabAccountResponse {
/// The base URL as stored.
url: String,
}
/// Store an agent's GitLab account, unless one is stored under the label
/// already.
#[utoipa::path(
put,
path = "/api/hives/{hive}/agents/{agent}/gitlab-accounts/{label}",
params(
("hive" = String, Path, description = "hive the agent runs on"),
("agent" = String, Path, description = "agent the account belongs to"),
("label" = String, Path, description = "the account's name"),
),
request_body = PutGitlabAccountRequest,
responses(
(status = 200, description = "stored", body = PutGitlabAccountResponse),
(status = 400, description = "the agent or label is not an identifier, the URL is not http(s) with a DNS name as its host, the token is empty, or the hive is not in this swarm (problem+json)", body = String),
(status = 409, description = "an account is stored under the label already; nothing was written (problem+json)", body = String),
(status = 500, description = "the store could not be read or written (problem+json)", body = String),
),
tag = "agents"
)]
pub async fn put_gitlab_account(
State(state): State<AppState>,
axum::extract::Path((hive, agent, label)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutGitlabAccountRequest>,
) -> Result<Json<PutGitlabAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let agent = hive_types::Ident::parse(&agent)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
let label = hive_types::Ident::parse(&label)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
let secret_path = gitlab::account_path(&agent, &label)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
let account = account(req).map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e))?;
let store = state.accounts.open().await.map_err(|e| {
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
link(&store, &secret_path, &account).await.map_err(|e| {
// The path names the agent and the label; the value is not in it.
tracing::warn!(path = %secret_path, error = ?e, "linking the gitlab account failed");
e.problem(&existing(&agent, &label))
})?;
crate::link_egress::added(
&state,
&agent,
&crate::link_egress::Link::Gitlab {
label: &label,
url: &account.url,
},
)
.await?;
tracing::info!(%hive, %agent, %label, url = %account.url, "gitlab account stored");
Ok(Json(PutGitlabAccountResponse { url: account.url }))
}
/// The account a refused link names.
fn existing(agent: &str, label: &str) -> String {
format!("agent {agent} already has gitlab account {label:?}")
}
/// The request as it is stored, or why it cannot be.
///
/// The URL must match [`gitlab::URL_PATTERN`], the rule the agent end filters by,
/// so a stored account is never one the agent drops. The host must also be a
/// name the egress allow list takes: the agent reaches the instance through its
/// hive's proxy, so an address or `localhost` would be stored and never reachable.
fn account(req: PutGitlabAccountRequest) -> Result<gitlab::Account, String> {
let url = req.url.trim().trim_end_matches('/');
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("url must start with http:// or https://".to_owned());
}
let authority = url
.split_once("://")
.and_then(|(_, rest)| rest.split(['/', '?', '#']).next())
.unwrap_or_default();
if authority.contains('@') {
return Err("url must not carry user information; the token is its own field".to_owned());
}
if !gitlab::is_instance_url(url) {
return Err(format!(
"url must match {}: http(s), a host name, an optional port, and an optional path of \
letters, digits and . _ ~ / - (no query, fragment, '@' or spaces)",
gitlab::URL_PATTERN
));
}
let host = host_of(url).ok_or("url has no host")?;
swarm_wire::egress_allow::normalize_domain(host).map_err(|why| format!("url host: {why}"))?;
if req.token.trim().is_empty() {
return Err("token is required".to_owned());
}
Ok(gitlab::Account {
value: req.token,
url: url.to_owned(),
})
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::super::linked_accounts::{Accounts, tests::FakeStore};
use super::{PutGitlabAccountRequest, account};
fn request(url: &str, token: &str) -> PutGitlabAccountRequest {
PutGitlabAccountRequest {
url: url.to_owned(),
token: token.to_owned(),
}
}
#[test]
fn the_url_loses_its_trailing_slash_and_the_token_is_kept() {
let a = account(request("https://gitlab.example.org/ ", "t0k3n")).expect("valid");
assert_eq!(a.url, "https://gitlab.example.org");
assert_eq!(a.value, "t0k3n");
// A port and a subfolder are part of the instance's address.
let a = account(request("https://gitlab.example.org:8443/gl/", "t")).expect("valid");
assert_eq!(a.url, "https://gitlab.example.org:8443/gl");
}
#[test]
fn a_url_that_is_not_http_is_refused() {
assert!(account(request("gitlab.example.org", "t")).is_err());
assert!(account(request("file:///etc/passwd", "t")).is_err());
// The control: plain http with a name is accepted.
assert!(account(request("http://gitlab.lan", "t")).is_ok());
}
#[test]
fn a_host_the_egress_list_would_refuse_is_refused() {
for url in [
"http://10.0.0.5",
"https://10.0.0.5:8443",
"http://[::1]",
"https://localhost",
"https://gitlab",
"https://*.example.org",
"https://",
] {
assert!(account(request(url, "t")).is_err(), "{url}");
}
}
#[test]
fn user_information_in_the_url_is_refused() {
assert!(account(request("https://oauth2:t0k3n@gitlab.example.org", "t")).is_err());
// A path character the agent end drops is refused here too.
for url in [
"https://gitlab.example.org/@x",
"https://gitlab.example.org/?x=1",
"https://gitlab.example.org/#f",
"https://gitlab.example.org/a b",
] {
assert!(account(request(url, "t")).is_err(), "{url}");
}
}
#[test]
fn an_empty_token_is_refused() {
assert!(account(request("https://gitlab.example.org", " ")).is_err());
}
/// Bare-minimum `AppState`, as `forge_account`'s tests build it.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
hives: std::sync::Arc::new(vec![crate::routes::hives::HiveEntry {
name: "pr1ma".to_owned(),
domain: "pr1ma.example".to_owned(),
dashboard: "pr1ma.hives.example".to_owned(),
}]),
links: std::sync::Arc::new(Vec::new()),
status: None,
wanted: None,
agent_status: None,
agent_icons: None,
agents_md: None,
reported_inference: None,
agent_login: None,
jobq: std::sync::Arc::new(std::sync::Mutex::new(hive_jobq::scheduler::Scheduler::new(
hive_jobq::Graph::new(),
hive_jobq::resources::ResourceTable::new(),
))),
webhook_secret: std::sync::Arc::default(),
config_prs: std::sync::Arc::default(),
swarm_name: None,
auth: None,
forge: std::sync::Arc::default(),
create_gate: std::sync::Arc::default(),
accounts: Accounts::Fake(Arc::clone(store)),
try_outs: crate::review_classifier::TryOuts::default(),
reviews: std::sync::Arc::default(),
runs: crate::review_classifier::runs::Runs::Live(None),
builds: crate::builder::runs::Builds::Live(None),
alerts: None,
}
}
async fn put(
store: &Arc<FakeStore>,
agent: &str,
label: &str,
url: &str,
) -> Result<axum::Json<super::PutGitlabAccountResponse>, problem_details::ProblemDetails> {
super::put_gitlab_account(
axum::extract::State(state(store)),
axum::extract::Path(("pr1ma".to_owned(), agent.to_owned(), label.to_owned())),
axum::Json(request(url, "t0k3n")),
)
.await
}
#[tokio::test]
async fn a_plain_account_reaches_the_store_under_the_agents_gitlab_directory() {
let store = Arc::default();
let stored = put(&store, "atlas", "work", "https://gitlab.example.org")
.await
.expect("nothing is stored");
assert_eq!(stored.url, "https://gitlab.example.org");
assert_eq!(store.written(), ["swarm/agents/atlas/gitlab/work"]);
}
/// Refused before the store, whatever the part: an address, a label or an
/// agent that is not an identifier.
#[tokio::test]
async fn a_request_the_swarm_would_refuse_is_a_400_and_writes_nothing() {
let store = Arc::default();
for (agent, label, url) in [
("atlas", "work", "http://10.0.0.5:8080"),
("atlas", "work", "https://localhost"),
("atlas", "work", "https://gitlab.example.org/@x"),
("atlas", "work", "https://gitlab.example.org/?x=1"),
("atlas", "My_Label", "https://gitlab.example.org"),
("atlas", "../x", "https://gitlab.example.org"),
("../x", "work", "https://gitlab.example.org"),
] {
let problem = put(&store, agent, label, url).await.expect_err("refused");
assert_eq!(
problem.status,
Some(axum::http::StatusCode::BAD_REQUEST),
"{agent} {label} {url}: {problem:?}"
);
}
assert!(store.written().is_empty());
}
#[tokio::test]
async fn linking_a_label_twice_is_a_409_and_the_first_account_stays() {
use super::super::linked_accounts::{AccountStore, link};
use swarm_secret_client::gitlab;
let store = FakeStore::default();
let path = gitlab::account_path("atlas", "work").expect("a valid path");
let first = account(request("https://gitlab.example.org", "t0k3n-first")).expect("valid");
let second = account(request("https://gitlab.lan", "t0k3n-second")).expect("valid");
link(&store, &path, &first)
.await
.expect("nothing is stored");
let problem = link(&store, &path, &second)
.await
.expect_err("an account is stored")
.problem(&super::existing("atlas", "work"));
assert_eq!(problem.status, Some(axum::http::StatusCode::CONFLICT));
let detail = problem.detail.expect("a detail");
assert!(
detail.contains(r#"agent atlas already has gitlab account "work""#),
"{detail}"
);
assert_eq!(store.written(), std::slice::from_ref(&path));
let kept: gitlab::Account = store
.read_optional(&path)
.await
.expect("store answers")
.expect("still stored");
assert_eq!(kept.url, "https://gitlab.example.org");
assert_eq!(kept.value, "t0k3n-first");
}
}

View file

@ -0,0 +1,741 @@
//! The hosts an agent's linked accounts reach, kept as derived entries of the
//! egress allow list (`crate::egress_allow`), so a restricted agent with a
//! linked GitHub, external matrix, external forge or GitLab account reaches
//! that service through its hive's proxy.
//!
//! An entry is marked `derived` and carries the account as its `source`
//! (`link:github`, `link:matrix:<account>`, `link:forge:<label>`,
//! `link:gitlab:<label>`), so
//! the backend environment's entries (`crate::backend_egress`) and each
//! account's are replaced and dropped independently. A hive renders it like
//! any other.
//!
//! The controller alone writes the four leaves the entries come from; the
//! agent's store policy grants it `create` on its own `backend-env` leaf and
//! nothing else (`swarm-secret-client/src/policy.rs`), so what these leaves
//! hold is the operator's choice, unlike the backend environment's.
//! [`added`] and [`removed`] follow the operator's link and unlink, and
//! [`reconcile`] makes the entries match the leaves at start: it adds the
//! entries of accounts linked before this existed and drops those of accounts
//! whose leaf is gone, and an agent whose leaves cannot be read keeps what it
//! has.
//!
//! The `homeserver` and `url` of an account go through
//! [`crate::backend_egress::host_of`] and `egress_allow::checked`, the check
//! an operator's own entry gets. An agent's `matrixAccounts.*.homeserver` in
//! its own configuration is not read: the controller never sees it.
use std::collections::{BTreeMap, BTreeSet};
use problem_details::ProblemDetails;
use swarm_wire::egress_allow::{AllowList, Entry, LINK_SOURCE_PREFIX, MAX_ENTRIES};
use crate::backend_egress::host_of;
use crate::egress_allow::{base_domains, checked, current, modify};
use crate::linked_accounts::{AccountKind, AccountStore, linked_accounts};
use crate::routes::{AppState, error_problem, wanted_error_status};
use crate::schedules::queue;
/// What the GitHub token is used against: `gh`'s API, git over HTTPS, and the
/// raw file, archive and release-asset downloads.
const GITHUB_HOSTS: [&str; 5] = [
"github.com",
"api.github.com",
"raw.githubusercontent.com",
"codeload.github.com",
"objects.githubusercontent.com",
];
/// An account the operator links to an agent.
pub(crate) enum Link<'a> {
Github,
Matrix {
account: &'a str,
homeserver: Option<&'a str>,
},
Forge {
label: &'a str,
url: &'a str,
},
Gitlab {
label: &'a str,
url: &'a str,
},
}
pub(crate) fn github_source() -> String {
format!("{LINK_SOURCE_PREFIX}github")
}
pub(crate) fn matrix_source(account: &str) -> String {
format!("{LINK_SOURCE_PREFIX}matrix:{account}")
}
pub(crate) fn forge_source(label: &str) -> String {
format!("{LINK_SOURCE_PREFIX}forge:{label}")
}
pub(crate) fn gitlab_source(label: &str) -> String {
format!("{LINK_SOURCE_PREFIX}gitlab:{label}")
}
impl Link<'_> {
fn source(&self) -> String {
match self {
Self::Github => github_source(),
Self::Matrix { account, .. } => matrix_source(account),
Self::Forge { label, .. } => forge_source(label),
Self::Gitlab { label, .. } => gitlab_source(label),
}
}
/// The entries for `agent`: one per host that passes
/// `egress_allow::checked`. A host that does not (an IP address,
/// `localhost`, a name the base list already allows) is logged and left
/// out. The URL is never logged: it can carry credentials.
fn entries(&self, agent: &str, base: &[String]) -> Vec<Entry> {
let source = self.source();
let hosts: Vec<Option<&str>> = match self {
Self::Github => GITHUB_HOSTS.iter().map(|h| Some(*h)).collect(),
Self::Matrix { homeserver, .. } => homeserver.iter().map(|u| host_of(u)).collect(),
Self::Forge { url, .. } | Self::Gitlab { url, .. } => vec![host_of(url)],
};
let mut entries = Vec::new();
for host in hosts {
let Some(host) = host else {
tracing::warn!(%agent, %source, "link egress: not an http(s) URL; no entry");
continue;
};
let request = swarm_controller_api::egress::AllowedDomain {
domain: host.to_owned(),
agent: Some(agent.to_owned()),
derived: false,
};
match checked(&request, base) {
Ok(entry) => entries.push(Entry {
derived: true,
source: Some(source.clone()),
..entry
}),
Err(why) => {
tracing::warn!(%agent, %source, %why, "link egress: no entry for this host");
}
}
}
entries
}
}
/// `list` without the entries `stale` names, plus `add`. A full list takes no
/// more entries.
fn replaced(mut list: AllowList, stale: impl Fn(&Entry) -> bool, add: &[Entry]) -> AllowList {
list.entries.retain(|e| !stale(e));
for entry in add {
if list.entries.len() >= MAX_ENTRIES {
tracing::warn!(
domain = %entry.domain,
"link egress: the allow list is full; no entry for this host"
);
break;
}
list.entries.push(entry.clone());
}
list
}
/// Whether `e` is `agent`'s entry derived from exactly `source`.
fn is_of(e: &Entry, agent: &str, source: &str) -> bool {
e.derived && e.agent.as_deref() == Some(agent) && e.source.as_deref() == Some(source)
}
/// Replace `agent`'s entries of `source` with `entries`. A host without a
/// queue (`state.status` unset) has no allow list, so nothing happens.
async fn follow(
state: &AppState,
agent: &str,
source: &str,
entries: Vec<Entry>,
stored: &str,
) -> Result<(), ProblemDetails> {
if state.status.is_none() {
return Ok(());
}
let updated = async {
let client = queue(state).map_err(|(_, why)| anyhow::anyhow!(why))?;
modify(&client, |list| {
replaced(list, |e| is_of(e, agent, source), &entries)
})
.await
}
.await;
match updated {
Ok(true) => tracing::info!(%agent, %source, "link egress: derived entries updated"),
Ok(false) => {}
Err(e) => {
tracing::warn!(%agent, %source, error = %format!("{e:#}"), "link egress: updating the allow list failed");
return Err(error_problem(
wanted_error_status(&e),
&format!(
"the account is {stored}, but the allowed domains were not updated \
({e:#}); the controller corrects them when it next starts"
),
));
}
}
Ok(())
}
/// Give `agent` the entries of the account `link` just stored.
///
/// # Errors
/// A problem naming that the account is linked but the list was not updated.
pub(crate) async fn added(
state: &AppState,
agent: &str,
link: &Link<'_>,
) -> Result<(), ProblemDetails> {
let entries = link.entries(agent, &base_domains());
follow(state, agent, &link.source(), entries, "linked").await
}
/// Take from `agent` the entries of the account stored at `source`, which was
/// just deleted.
///
/// # Errors
/// A problem naming that the account is deleted but the list was not updated.
pub(crate) async fn removed(
state: &AppState,
agent: &str,
source: &str,
) -> Result<(), ProblemDetails> {
follow(state, agent, source, Vec::new(), "deleted").await
}
/// The entries the accounts stored for `agent` call for.
async fn wanted_entries(
store: &impl AccountStore,
agent: &str,
base: &[String],
) -> Result<Vec<Entry>, swarm_secret_client::Error> {
let mut entries = Vec::new();
for account in linked_accounts(store, agent).await? {
let link = match account.kind {
AccountKind::Github => Link::Github,
AccountKind::Matrix if !account.reserved => Link::Matrix {
account: &account.name,
homeserver: account.host.as_deref(),
},
AccountKind::Forgejo => match account.host.as_deref() {
Some(url) => Link::Forge {
label: &account.name,
url,
},
None => continue,
},
AccountKind::Gitlab => match account.host.as_deref() {
Some(url) => Link::Gitlab {
label: &account.name,
url,
},
None => continue,
},
AccountKind::Matrix | AccountKind::Backend => continue,
};
entries.extend(link.entries(agent, base));
}
Ok(entries)
}
/// `list` with, for each agent in `desired`, its link-derived entries replaced
/// by the given ones. Entries of other agents, operator-added entries and
/// entries derived from the backend environment are untouched.
fn synced(list: AllowList, desired: &BTreeMap<String, Vec<Entry>>) -> AllowList {
let add: Vec<Entry> = desired.values().flatten().cloned().collect();
replaced(
list,
|e| e.from_link() && e.agent.as_ref().is_some_and(|a| desired.contains_key(a)),
&add,
)
}
/// Make the link-derived entries match the stored accounts of every agent in
/// `live` and of every agent that has one: add what a stored account calls for,
/// drop what no stored account does. Logs the counts.
///
/// An agent whose accounts cannot be read keeps its entries and is counted in
/// the answer, which is how many agents that was.
///
/// # Errors
/// A queue failure reading or writing the list.
pub(crate) async fn reconcile(
client: &async_nats::Client,
store: &impl AccountStore,
live: &BTreeSet<String>,
) -> anyhow::Result<usize> {
let before = current(client).await?.unwrap_or_default();
let mut agents = live.clone();
agents.extend(
before
.entries
.iter()
.filter(|e| e.from_link())
.filter_map(|e| e.agent.clone()),
);
let base = base_domains();
let mut desired = BTreeMap::new();
let mut unreadable = 0;
for agent in agents {
match wanted_entries(store, &agent, &base).await {
Ok(entries) => {
desired.insert(agent, entries);
}
Err(e) => {
tracing::warn!(%agent, error = %e, "link egress: reading the linked accounts failed; its entries stay");
unreadable += 1;
}
}
}
let had: BTreeSet<&Entry> = before.entries.iter().filter(|e| e.from_link()).collect();
let after = synced(before.clone(), &desired);
let has: BTreeSet<&Entry> = after.entries.iter().filter(|e| e.from_link()).collect();
let (added, removed) = (has.difference(&had).count(), had.difference(&has).count());
modify(client, |list| synced(list, &desired)).await?;
tracing::info!(
agents = desired.len(),
unreadable,
added,
removed,
"link egress: entries match the linked accounts"
);
Ok(unreadable)
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use axum::extract::{Path, State};
use serde_json::json;
use super::*;
use crate::agent_limits::tests::declared;
use crate::linked_accounts::tests::FakeStore;
use crate::test_nats::TestNats;
fn base() -> Vec<String> {
vec!["api.anthropic.com".to_owned()]
}
fn hosts(link: &Link<'_>) -> Vec<String> {
link.entries("atlas", &base())
.into_iter()
.map(|e| e.domain)
.collect()
}
fn entry(domain: &str, agent: &str, source: Option<&str>) -> Entry {
Entry {
domain: domain.to_owned(),
agent: Some(agent.to_owned()),
derived: source.is_some(),
source: source.map(str::to_owned),
}
}
#[test]
fn each_kind_yields_the_hosts_its_service_is_reached_at() {
let github = Link::Github.entries("atlas", &base());
assert_eq!(
github,
[
entry("github.com", "atlas", Some("link:github")),
entry("api.github.com", "atlas", Some("link:github")),
entry("raw.githubusercontent.com", "atlas", Some("link:github")),
entry("codeload.github.com", "atlas", Some("link:github")),
entry(
"objects.githubusercontent.com",
"atlas",
Some("link:github")
),
]
);
// A port, a path, a trailing slash and a scheme-less value all reduce
// to the bare host.
for homeserver in [
"https://Matrix.Example.org:8448/_matrix/",
"https://matrix.example.org/",
"matrix.example.org",
] {
let link = Link::Matrix {
account: "work",
homeserver: Some(homeserver),
};
assert_eq!(hosts(&link), ["matrix.example.org"], "{homeserver}");
assert_eq!(
link.entries("atlas", &base()),
[entry(
"matrix.example.org",
"atlas",
Some("link:matrix:work")
)]
);
}
let forge = Link::Forge {
label: "oss",
url: "https://forge.example.org:3000/sub",
};
assert_eq!(
forge.entries("atlas", &base()),
[entry("forge.example.org", "atlas", Some("link:forge:oss"))]
);
let gitlab = Link::Gitlab {
label: "work",
url: "https://GitLab.Example.org:8443/sub",
};
assert_eq!(
gitlab.entries("atlas", &base()),
[entry(
"gitlab.example.org",
"atlas",
Some("link:gitlab:work")
)]
);
}
#[test]
fn a_host_the_swarm_would_refuse_gets_no_entry() {
for url in [
"http://10.0.0.5:3000",
"https://localhost",
"ftp://forge.example.org",
"https://",
"https://*.example.org",
// The base list already allows it.
"https://api.anthropic.com",
] {
let forge = Link::Forge { label: "x", url };
assert_eq!(hosts(&forge), Vec::<String>::new(), "{url:?}");
let gitlab = Link::Gitlab { label: "x", url };
assert_eq!(hosts(&gitlab), Vec::<String>::new(), "{url:?}");
}
// Controls: a public name gets one, and a matrix account with no
// homeserver has none to derive.
let forge = Link::Forge {
label: "x",
url: "https://forge.example.org",
};
assert_eq!(hosts(&forge), ["forge.example.org"]);
let gitlab = Link::Gitlab {
label: "x",
url: "https://gitlab.example.org",
};
assert_eq!(hosts(&gitlab), ["gitlab.example.org"]);
let matrix = Link::Matrix {
account: "work",
homeserver: None,
};
assert_eq!(hosts(&matrix), Vec::<String>::new());
}
#[test]
fn unlinking_removes_only_that_sources_entries() {
let list = AllowList {
entries: vec![
entry("github.com", "atlas", Some("link:github")),
entry("github.com", "iris", Some("link:github")),
entry("forge.example.org", "atlas", Some("link:forge:oss")),
entry("forge.example.org", "atlas", Some("link:forge:work")),
entry("llm.example.com", "atlas", Some("backend-env")),
entry("old.example.com", "atlas", Some("backend-env")),
entry("github.com", "atlas", None),
],
};
let after = replaced(
list.clone(),
|e| is_of(e, "atlas", &forge_source("oss")),
&[],
);
assert_eq!(after.entries.len(), list.entries.len() - 1);
assert!(!after.entries.contains(&entry(
"forge.example.org",
"atlas",
Some("link:forge:oss")
)));
// Control: the same lookup finds the entry it removed.
assert!(
list.entries
.iter()
.any(|e| is_of(e, "atlas", "link:forge:oss"))
);
// The manual entry for the same name as a derived one stays.
let after = replaced(list, |e| is_of(e, "atlas", &github_source()), &[]);
assert!(after.entries.contains(&entry("github.com", "atlas", None)));
assert!(
!after
.entries
.contains(&entry("github.com", "atlas", Some("link:github")))
);
}
/// The state of a test swarm whose `pr1ma` declares `atlas`, with `store`
/// as the secret store.
async fn swarm(client: &async_nats::Client, store: &Arc<FakeStore>) -> AppState {
AppState {
accounts: crate::linked_accounts::Accounts::Fake(Arc::clone(store)),
..declared(client).await
}
}
async fn list_of(client: &async_nats::Client) -> Vec<Entry> {
let mut entries = current(client)
.await
.expect("the queue answers")
.map(|l| l.entries)
.unwrap_or_default();
entries.sort();
entries
}
fn sorted(mut entries: Vec<Entry>) -> Vec<Entry> {
entries.sort();
entries
}
fn github_entries(agent: &str) -> Vec<Entry> {
GITHUB_HOSTS
.iter()
.map(|h| entry(h, agent, Some("link:github")))
.collect()
}
fn path(parts: &str) -> Path<(String, String)> {
Path(("pr1ma".to_owned(), parts.to_owned()))
}
/// Link `atlas`'s GitLab account `work` through the route.
async fn link_gitlab(state: &AppState) {
let _ = crate::gitlab_account::put_gitlab_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::Json(
serde_json::from_value(
json!({"url": "https://gitlab.example.org:8443/", "token": "t"}),
)
.expect("a body"),
),
)
.await
.expect("linked");
}
#[tokio::test]
async fn linking_and_unlinking_through_the_routes_moves_the_entries() {
let nats = TestNats::start();
let client = nats.client().await;
let store = Arc::default();
let state = swarm(&client, &store).await;
let _ = crate::github_account::put_github_account(
State(state.clone()),
path("atlas"),
axum::Json(serde_json::from_value(json!({"token": "t"})).expect("a body")),
)
.await
.expect("linked");
let _ = crate::forge_account::put_forge_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "oss".to_owned())),
axum::Json(
serde_json::from_value(
json!({"url": "https://forge.example.org:3000/", "token": "t"}),
)
.expect("a body"),
),
)
.await
.expect("linked");
link_gitlab(&state).await;
let _ = crate::matrix_account::put_matrix_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::Json(
serde_json::from_value(json!({
"mode": "token", "token": "t", "homeserver": "https://matrix.example.org/"
}))
.expect("a body"),
),
)
.await
.expect("linked");
let forge = entry("forge.example.org", "atlas", Some("link:forge:oss"));
let gitlab = entry("gitlab.example.org", "atlas", Some("link:gitlab:work"));
let matrix = entry("matrix.example.org", "atlas", Some("link:matrix:work"));
let mut all = github_entries("atlas");
all.extend([forge.clone(), gitlab.clone(), matrix.clone()]);
assert_eq!(list_of(&client).await, sorted(all));
// The backend environment's own save and delete leave them alone.
crate::backend_env::put_backend_env(
State(state.clone()),
path("atlas"),
axum::Json(
serde_json::from_value(
json!({"env": "ANTHROPIC_BASE_URL=https://llm.example.com\n"}),
)
.expect("a body"),
),
)
.await
.expect("stored");
crate::linked_accounts::delete_backend_env(State(state.clone()), path("atlas"))
.await
.expect("deleted");
assert_eq!(list_of(&client).await.len(), 3 + GITHUB_HOSTS.len());
crate::linked_accounts::delete_github_account(State(state.clone()), path("atlas"))
.await
.expect("deleted");
assert_eq!(
list_of(&client).await,
sorted(vec![forge.clone(), gitlab.clone(), matrix.clone()])
);
crate::linked_accounts::delete_forge_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "oss".to_owned())),
)
.await
.expect("deleted");
assert_eq!(
list_of(&client).await,
sorted(vec![gitlab.clone(), matrix.clone()])
);
crate::linked_accounts::delete_gitlab_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
)
.await
.expect("deleted");
assert_eq!(list_of(&client).await, [matrix]);
crate::linked_accounts::delete_matrix_account(
State(state.clone()),
Path(("pr1ma".to_owned(), "atlas".to_owned(), "work".to_owned())),
axum::extract::Query(serde_json::from_value(json!({})).expect("a query")),
)
.await
.expect("deleted");
assert_eq!(list_of(&client).await, []);
}
#[tokio::test]
async fn the_backfill_adds_entries_for_existing_links_and_prunes_orphans() {
let nats = TestNats::start();
let client = nats.client().await;
let store =
FakeStore::default().with("swarm/agents/atlas/github-token", json!({"value": "t"}));
let store = store.with(
"swarm/agents/atlas/matrix/work",
json!({"value": "t", "homeserver": "https://matrix.example.org"}),
);
let store = store.with(
"swarm/agents/atlas/gitlab/work",
json!({"value": "t", "url": "https://gitlab.example.org:8443"}),
);
// The agent's own account has a homeserver of its own and no entry.
let store = store.with(
"swarm/agents/atlas/matrix/main",
json!({"value": "t", "homeserver": "https://hive.example.org"}),
);
modify(&client, |mut list| {
list.entries.extend([
// A link from before the host list grew: the pass adds the rest.
entry("github.com", "atlas", Some("link:github")),
// An orphan: iris has no leaf for it.
entry("github.com", "iris", Some("link:github")),
// An orphan on a live agent whose forge leaf is gone.
entry("gitlab.example.org", "atlas", Some("link:gitlab:old")),
entry("forge.example.org", "atlas", Some("link:forge:old")),
entry("llm.example.com", "atlas", Some("backend-env")),
entry("crates.io", "atlas", None),
]);
list
})
.await
.expect("seed");
let live = BTreeSet::from(["atlas".to_owned()]);
assert_eq!(reconcile(&client, &store, &live).await.expect("pass"), 0);
let mut want = github_entries("atlas");
want.extend([
entry("gitlab.example.org", "atlas", Some("link:gitlab:work")),
entry("matrix.example.org", "atlas", Some("link:matrix:work")),
entry("llm.example.com", "atlas", Some("backend-env")),
entry("crates.io", "atlas", None),
]);
assert_eq!(list_of(&client).await, sorted(want.clone()));
// A second pass changes nothing.
reconcile(&client, &store, &live).await.expect("again");
assert_eq!(list_of(&client).await, sorted(want));
}
/// The host of a GitLab entry is the controller-written leaf's `url`. The
/// one object an agent can create in the store is its `backend-env` leaf,
/// and a GitLab host named there yields no `link:gitlab` entry.
#[tokio::test]
async fn a_gitlab_entry_comes_from_the_controller_leaf_and_nothing_an_agent_writes() {
let agent_written = FakeStore::default().with(
"swarm/agents/atlas/backend-env",
json!({"env": "GITLAB_HOST=https://evil.example.com\nANTHROPIC_BASE_URL=https://evil.example.com\n"}),
);
let got = wanted_entries(&agent_written, "atlas", &base())
.await
.expect("store answers");
assert_eq!(got, []);
// The control: the controller's leaf yields the entry.
let leaf = agent_written.with(
"swarm/agents/atlas/gitlab/work",
json!({"value": "t", "url": "https://gitlab.example.org:8443/sub"}),
);
let got = wanted_entries(&leaf, "atlas", &base())
.await
.expect("store answers");
assert_eq!(
got,
[entry(
"gitlab.example.org",
"atlas",
Some("link:gitlab:work")
)]
);
}
#[tokio::test]
async fn a_store_error_prunes_nothing_and_adds_nothing() {
let nats = TestNats::start();
let client = nats.client().await;
let seeded = vec![
entry("github.com", "iris", Some("link:github")),
entry("forge.example.org", "atlas", Some("link:forge:old")),
];
modify(&client, |mut list| {
list.entries.extend(seeded.clone());
list
})
.await
.expect("seed");
let live = BTreeSet::from(["atlas".to_owned()]);
let unreadable = reconcile(&client, &FakeStore::denying(), &live)
.await
.expect("pass");
assert_eq!(unreadable, 2, "atlas and iris");
assert_eq!(list_of(&client).await, sorted(seeded.clone()));
// Control: a store that answers, and holds nothing, prunes both.
reconcile(&client, &FakeStore::default(), &live)
.await
.expect("pass");
assert_eq!(list_of(&client).await, []);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,596 @@
//! An agent's matrix accounts, from this daemon's two sides of them.
//!
//! **The internal one** — [`agent_token`] — is the agent's own `main` account on
//! the swarm's homeserver, minted with the swarm's appservice token and stored
//! where the agent's daemon reads it. See docs/4-implementation/swarm/credentials-reference.md for why
//! `main` is the one name [`put_matrix_account`] refuses to write.
//! [`operator_admin`] makes authelia's operators homeserver admins with the same
//! appservice token.
//! [`recovery`] mints the passphrase that opens each account's server-side key
//! backup, for the swarm's accounts and external ones alike.
//!
//! **The external one** — [`put_matrix_account`] and everything under it — is
//! an account somewhere else that an operator hands us a credential for: put it
//! in the swarm's secret store.
//!
//! The agent end is `hive-matrix-daemon`, which lists the agent's accounts and
//! reads each under the agent's own certificate. No hive is in the path.
//!
//! Two credential modes, chosen by `PutMatrixAccountRequest::mode`: `token`
//! (default, back-compat with the original blind-store shape — the caller
//! already has a bearer token) and `password` (this daemon performs
//! `m.login.password` against the caller-given homeserver itself and stores
//! the resulting token; the password is never stored — only the derived token
//! is). Done here so the browser never
//! has to hold the password long enough to call an arbitrary homeserver
//! directly.
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use serde::{Deserialize, Serialize};
use swarm_secret_client::matrix;
use utoipa::ToSchema;
use super::linked_accounts::{AccountStore, Linking, link, refuse_linked};
use crate::routes::agents::swarm_hive;
use crate::routes::{AppState, error_problem};
pub mod agent_token;
pub mod operator_admin;
pub mod recovery;
fn default_mode() -> String {
"token".to_owned()
}
/// Env var the controller's NixOS module sets from
/// `services.hyperhive.deploy.swarm-controller.matrixHomeserverUrl` — the
/// swarm-wide default `PutMatrixAccountRequest::homeserver` falls back to
/// when a caller omits one. Read via [`configured_default_homeserver`], not
/// directly — see that fn's doc.
///
/// Also the homeserver [`agent_token`] mints agents' own accounts on. Not yet
/// consulted by [`put_matrix_account`]: `homeserver_or_configured_default`
/// below exists for a later slice of this homeserver-default rollout to call.
pub(crate) const DEFAULT_HOMESERVER_ENV: &str = "SWARM_CONTROLLER_MATRIX_HOMESERVER_URL";
/// `caller`'s own homeserver, or `default` when the caller left it unset.
/// `caller` always wins — this only fills a gap it left, never replaces a
/// value it gave.
///
/// Takes `default` as a plain parameter rather than reading
/// [`DEFAULT_HOMESERVER_ENV`] itself: a caller wants that env read done once,
/// at the edge (see [`configured_default_homeserver`]), and keeping this fn
/// pure makes it testable without mutating shared process env — three tests
/// doing exactly that raced each other under `cargo test`'s default
/// parallelism in review.
pub(crate) fn homeserver_or_configured_default(
caller: Option<String>,
default: Option<String>,
) -> Option<String> {
caller.or(default)
}
/// Reads [`DEFAULT_HOMESERVER_ENV`] fresh each call — the one place this
/// crate touches that env var, so [`homeserver_or_configured_default`] above
/// can stay a pure function.
pub(crate) fn configured_default_homeserver() -> Option<String> {
std::env::var(DEFAULT_HOMESERVER_ENV).ok()
}
/// The credential to store for one agent's external matrix account.
///
/// No `Debug` derive: this carries a password and a token, so nothing may
/// `{:?}`-log it by accident.
#[derive(Deserialize, ToSchema)]
pub struct PutMatrixAccountRequest {
/// `"token"` (default, back-compat) or `"password"`. Token mode stores
/// `token` as given; password mode logs into `homeserver` with `user_id`
/// + `password` and stores the token that comes back instead.
#[serde(default = "default_mode")]
#[schema(example = "token")]
mode: String,
/// The access token. Required (and used as given) in token mode; ignored
/// in password mode, where the token comes from the login instead. Never
/// logged, and never returned by this route.
token: Option<String>,
/// Password-mode only: the matrix user id (or bare localpart) to log in
/// as.
user_id: Option<String>,
/// Password-mode only. Never logged and never stored — only the token
/// `m.login.password` returns is.
password: Option<String>,
/// The account's homeserver, when it is not this swarm's own. Stored
/// beside the token, which is where the agent's daemon reads it.
///
/// Optional in token mode (omitted means "resolve to the agent's own
/// `services.hyperhive.agent.matrix.url` on the hive side" — this route never needs to
/// know it itself for a blind store). **Required** in password mode:
/// logging in needs somewhere to log in against, and unlike token mode
/// there is no hive-side fallback to defer to.
#[schema(example = "https://matrix.example.org")]
homeserver: Option<String>,
}
/// `put_matrix_account`'s success body.
#[derive(Debug, Serialize, ToSchema)]
pub struct PutMatrixAccountResponse {
/// The account's matrix user id, recovered from the login response in
/// password mode. `None` in token mode — the caller already knows which
/// account their own token belongs to, and this route does not spend a
/// `whoami` round trip validating a token it was simply handed.
user_id: Option<String>,
}
/// Store an agent's external matrix account credential, unless an account is
/// stored under the name already.
#[utoipa::path(
put,
path = "/api/hives/{hive}/agents/{agent}/matrix-accounts/{account}",
params(
("hive" = String, Path, description = "hive the agent runs on"),
("agent" = String, Path, description = "agent the credential belongs to"),
("account" = String, Path, description = "the external account this credential authenticates as"),
),
request_body = PutMatrixAccountRequest,
responses(
(status = 200, description = "stored", body = PutMatrixAccountResponse),
(status = 400, description = "a name is not an identifier, the account name is not a single path segment, the account is 'main' (reserved), the mode is unrecognized, a mode's required fields are missing, or the hive is not in this swarm (problem+json)", body = String),
(status = 409, description = "an account is stored under the name already; nothing was written and no login was made (problem+json)", body = String),
(status = 500, description = "the store could not be read or written (problem+json)", body = String),
),
tag = "agents"
)]
pub async fn put_matrix_account(
State(state): State<AppState>,
axum::extract::Path((hive, agent, account)): axum::extract::Path<(String, String, String)>,
Json(req): Json<PutMatrixAccountRequest>,
) -> Result<Json<PutMatrixAccountResponse>, problem_details::ProblemDetails> {
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
let agent = hive_types::Ident::parse(&agent)
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
.into_string();
// Built before the store is reached, so a malformed account name costs a
// parse and not a login. `account_path` is the validator: the store's
// charset is its rule to state, not this handler's to restate.
let secret_path = matrix::account_path(&agent, &account)
.map_err(|e| error_problem(StatusCode::BAD_REQUEST, &e.to_string()))?;
// `main` is the hive-internal account `nix/agent-modules/matrix.nix`
// declares per agent from `services.hyperhive.agent.matrix.url` — the
// module owns that `matrixAccounts` entry, which is why this route
// refuses to write one: an extra account literally named `main` would
// not overwrite the real one (it lands at a different token-file suffix)
// but would confuse anything that lists accounts by name. Checked
// before any mode-specific work (including a network login) runs.
if is_reserved_account(&account) {
return Err(error_problem(
StatusCode::BAD_REQUEST,
"'main' is the hive-internal account, declared per agent from \
services.hyperhive.agent.matrix.url — it cannot be set through this route.",
));
}
let store = state.accounts.open().await.map_err(|e| {
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
})?;
let user_id = link_matrix(&store, &secret_path, &existing(&agent, &account), &req)
.await
.map_err(|b| *b)?;
crate::link_egress::added(
&state,
&agent,
&crate::link_egress::Link::Matrix {
account: &account,
homeserver: req.homeserver.as_deref(),
},
)
.await?;
tracing::info!(%hive, %agent, %account, "credential stored");
Ok(Json(PutMatrixAccountResponse { user_id }))
}
/// The account a refused link names.
fn existing(agent: &str, account: &str) -> String {
format!("agent {agent} already has matrix account {account:?}")
}
/// Resolve `req`'s credential and write it at `path`, unless an account is
/// stored there already; `existing` names that account in the 409.
///
/// The check comes before password mode's login, so a refused link makes no
/// login and so mints no device at the homeserver. A failed login writes
/// nothing.
async fn link_matrix(
store: &impl AccountStore,
path: &str,
existing: &str,
req: &PutMatrixAccountRequest,
) -> Result<Option<String>, Box<problem_details::ProblemDetails>> {
let refused = |e: Linking| {
// The path names the agent and the account; the value is not in it.
tracing::warn!(path, error = ?e, "linking the matrix account failed");
Box::new(e.problem(existing))
};
refuse_linked(store, path).await.map_err(refused)?;
let (token, homeserver, user_id) = resolve_credential(req).await?;
link(
store,
path,
&matrix::Credential {
value: token,
homeserver,
},
)
.await
.map_err(refused)?;
Ok(user_id)
}
/// Whether `account` is the agent's own account, which [`agent_token`] mints
/// and `nix/agent-modules/matrix.nix` declares per agent — see
/// [`put_matrix_account`]'s comment on it for why that route must never write
/// one. `linked_accounts::delete_matrix_account` refuses to delete it too.
pub(crate) fn is_reserved_account(account: &str) -> bool {
account == agent_token::ACCOUNT
}
/// Token-mode's only requirement: a token was actually given. Split out of
/// `resolve_credential` (with `password_fields` below) so each mode's
/// validation is unit-testable directly — only the actual network login in
/// `resolve_credential` itself needs an async runtime to exercise. Returns a
/// plain `&'static str` rather than a `ProblemDetails` — `clippy::result_large_err`
/// (this workspace runs `pedantic = deny`) flags a private fn returning one of
/// those directly; `put_matrix_account` itself is exempt only because it is
/// `pub` (clippy's `avoid-breaking-exported-api` default), which these
/// helpers are not.
fn token_credential(
req: &PutMatrixAccountRequest,
) -> Result<(String, Option<String>), &'static str> {
let Some(token) = req.token.clone() else {
return Err("token mode needs a token");
};
Ok((token, req.homeserver.clone()))
}
/// Password mode's required fields, validated present, with the
/// homeserver's trailing slash already trimmed — this is what actually
/// reaches [`swarm_matrix_client::password_login`], not the caller's raw
/// string, so the login URL never ends up with a doubled `//`.
struct PasswordFields<'a> {
homeserver: String,
user_id: &'a str,
password: &'a str,
}
fn password_fields(req: &PutMatrixAccountRequest) -> Result<PasswordFields<'_>, &'static str> {
let (Some(homeserver), Some(user_id), Some(password)) = (
req.homeserver.as_deref(),
req.user_id.as_deref(),
req.password.as_deref(),
) else {
return Err("password mode needs homeserver, user_id, and password");
};
Ok(PasswordFields {
homeserver: homeserver.trim_end_matches('/').to_owned(),
user_id,
password,
})
}
/// Resolve a request's credential mode to a concrete `(token, homeserver,
/// resolved user id)`. Extracted out of `put_matrix_account` to keep that
/// function under `clippy::too_many_lines`, and so the mode branching has
/// something to unit-test directly (via `token_credential`/`password_fields`
/// above) instead of only through the full route.
///
/// `Box`ed error for the same `result_large_err` reason `token_credential`'s
/// doc explains — this fn is private too, so it does not get `put_matrix_account`'s
/// exported-API exemption. Unboxed in `put_matrix_account` instead of
/// changing that fn's own (exempt, and part of the route's documented
/// contract) return type.
async fn resolve_credential(
req: &PutMatrixAccountRequest,
) -> Result<(String, Option<String>, Option<String>), Box<problem_details::ProblemDetails>> {
match req.mode.as_str() {
"token" => {
let (token, homeserver) = token_credential(req)
.map_err(|e| Box::new(error_problem(StatusCode::BAD_REQUEST, e)))?;
Ok((token, homeserver, None))
}
"password" => {
let fields = password_fields(req)
.map_err(|e| Box::new(error_problem(StatusCode::BAD_REQUEST, e)))?;
let refused = |e: anyhow::Error| {
Box::new(error_problem(StatusCode::BAD_REQUEST, &format!("{e:#}")))
};
let http = swarm_matrix_client::client().map_err(refused)?;
let (token, resolved_user_id) = swarm_matrix_client::password_login(
&http,
&fields.homeserver,
fields.user_id,
fields.password,
)
.await
.map_err(refused)?;
Ok((token, Some(fields.homeserver), Some(resolved_user_id)))
}
other => Err(Box::new(error_problem(
StatusCode::BAD_REQUEST,
&format!("unknown mode {other:?} (want token|password)"),
))),
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::super::linked_accounts::{Accounts, tests::FakeStore};
use super::{
PutMatrixAccountRequest, homeserver_or_configured_default, is_reserved_account,
password_fields, resolve_credential, token_credential,
};
fn request(mode: &str) -> PutMatrixAccountRequest {
PutMatrixAccountRequest {
mode: mode.to_owned(),
token: None,
user_id: None,
password: None,
homeserver: None,
}
}
// `homeserver_or_configured_default` takes its default as a plain
// parameter rather than reading the env var itself, so these are pure
// — no process env mutation, and so no risk of racing each other (or
// any other test in the crate) under `cargo test`'s default parallelism.
#[test]
fn caller_supplied_homeserver_wins_even_with_a_default_configured() {
let result = homeserver_or_configured_default(
Some("https://caller.example.org".to_owned()),
Some("https://default.example.org".to_owned()),
);
assert_eq!(result.as_deref(), Some("https://caller.example.org"));
}
#[test]
fn falls_back_to_the_configured_default_when_the_caller_omits_one() {
let result =
homeserver_or_configured_default(None, Some("https://default.example.org".to_owned()));
assert_eq!(result.as_deref(), Some("https://default.example.org"));
}
#[test]
fn none_when_neither_caller_nor_default_is_set() {
assert_eq!(homeserver_or_configured_default(None, None), None);
}
#[test]
fn main_is_reserved_but_nothing_else_is() {
assert!(is_reserved_account("main"));
assert!(!is_reserved_account("ops-relay"));
// Case-sensitive on purpose: `matrixAccounts` is a nix attrset, so
// `Main` is a distinct, legal key from the reserved `main`.
assert!(!is_reserved_account("Main"));
}
#[test]
fn token_mode_needs_a_token() {
assert!(token_credential(&request("token")).is_err());
}
#[test]
fn token_mode_passes_through_token_and_homeserver_unchanged() {
let mut req = request("token");
req.token = Some("t0k3n".to_owned());
req.homeserver = Some("https://matrix.example.org".to_owned());
let (token, homeserver) = token_credential(&req).expect("token + homeserver both given");
assert_eq!(token, "t0k3n");
assert_eq!(homeserver.as_deref(), Some("https://matrix.example.org"));
}
#[test]
fn password_mode_needs_all_three_fields() {
let mut req = request("password");
assert!(password_fields(&req).is_err(), "none given");
req.homeserver = Some("https://matrix.example.org".to_owned());
assert!(
password_fields(&req).is_err(),
"still missing user_id + password"
);
req.user_id = Some("@a:matrix.example.org".to_owned());
assert!(password_fields(&req).is_err(), "still missing password");
req.password = Some("hunter2".to_owned());
assert!(password_fields(&req).is_ok(), "now all three given");
}
#[test]
fn password_mode_trims_a_trailing_slash_off_the_homeserver() {
let mut req = request("password");
req.homeserver = Some("https://matrix.example.org/".to_owned());
req.user_id = Some("@a:matrix.example.org".to_owned());
req.password = Some("hunter2".to_owned());
let fields = password_fields(&req).expect("all three fields given");
assert_eq!(fields.homeserver, "https://matrix.example.org");
}
#[test]
fn password_mode_leaves_a_homeserver_with_no_trailing_slash_unchanged() {
let mut req = request("password");
req.homeserver = Some("https://matrix.example.org".to_owned());
req.user_id = Some("@a:matrix.example.org".to_owned());
req.password = Some("hunter2".to_owned());
let fields = password_fields(&req).expect("all three fields given");
assert_eq!(fields.homeserver, "https://matrix.example.org");
}
#[tokio::test]
async fn resolve_credential_token_mode_end_to_end() {
let mut req = request("token");
req.token = Some("t0k3n".to_owned());
let (token, homeserver, user_id) = resolve_credential(&req)
.await
.expect("token mode with a token given");
assert_eq!(token, "t0k3n");
assert_eq!(homeserver, None);
assert_eq!(user_id, None);
}
#[tokio::test]
async fn resolve_credential_rejects_an_unknown_mode() {
assert!(
resolve_credential(&request("carrier-pigeon"))
.await
.is_err()
);
}
/// Bare-minimum `AppState` for a handler test: one hive, nothing
/// queue-backed, an empty in-memory job graph the endpoint under test
/// never touches, and `store` as the account store.
fn state(store: &Arc<FakeStore>) -> crate::routes::AppState {
crate::routes::AppState {
hives: std::sync::Arc::new(vec![crate::routes::hives::HiveEntry {
name: "pr1ma".to_owned(),
domain: "pr1ma.example".to_owned(),
dashboard: "pr1ma.hives.example".to_owned(),
}]),
links: std::sync::Arc::new(Vec::new()),
status: None,
wanted: None,
agent_status: None,
agent_icons: None,
agents_md: None,
reported_inference: None,
agent_login: None,
jobq: std::sync::Arc::new(std::sync::Mutex::new(hive_jobq::scheduler::Scheduler::new(
hive_jobq::Graph::new(),
hive_jobq::resources::ResourceTable::new(),
))),
webhook_secret: std::sync::Arc::default(),
config_prs: std::sync::Arc::default(),
swarm_name: None,
auth: None,
forge: std::sync::Arc::default(),
create_gate: std::sync::Arc::default(),
accounts: Accounts::Fake(Arc::clone(store)),
try_outs: crate::review_classifier::TryOuts::default(),
reviews: std::sync::Arc::default(),
runs: crate::review_classifier::runs::Runs::Live(None),
builds: crate::builder::runs::Builds::Live(None),
alerts: None,
}
}
/// Refused before the store is reached.
#[tokio::test]
async fn a_reserved_account_name_is_refused_before_the_store() {
let store = Arc::default();
let result = super::put_matrix_account(
axum::extract::State(state(&store)),
axum::extract::Path(("pr1ma".to_owned(), "atlas".to_owned(), "main".to_owned())),
axum::Json(PutMatrixAccountRequest {
mode: "token".to_owned(),
token: Some("t0k3n".to_owned()),
user_id: None,
password: None,
homeserver: None,
}),
)
.await;
let problem = result.expect_err("'main' is reserved");
assert_eq!(
problem.status,
Some(axum::http::StatusCode::BAD_REQUEST),
"{problem:?}"
);
assert!(store.written().is_empty());
}
/// The control for the test above: an ordinary name gets past every check
/// and is written, so the 400 above is not what every call answers.
#[tokio::test]
async fn an_ordinary_account_name_reaches_the_store() {
use super::super::linked_accounts::AccountStore;
use swarm_secret_client::matrix;
let store = Arc::default();
let result = super::put_matrix_account(
axum::extract::State(state(&store)),
axum::extract::Path((
"pr1ma".to_owned(),
"atlas".to_owned(),
"workaccount".to_owned(),
)),
axum::Json(PutMatrixAccountRequest {
mode: "token".to_owned(),
token: Some("t0k3n".to_owned()),
user_id: None,
password: None,
homeserver: None,
}),
)
.await;
let response = result.expect("nothing is stored");
assert_eq!(response.user_id, None);
let path = "swarm/agents/atlas/matrix/workaccount";
assert_eq!(store.written(), [path]);
let stored: matrix::Credential = store
.read_optional(path)
.await
.expect("store answers")
.expect("stored");
assert_eq!(stored.value, "t0k3n");
}
/// The second link is password mode against a port nothing listens on:
/// a login attempt would answer 400, so the 409 is the check running first.
#[tokio::test]
async fn linking_a_name_twice_is_a_409_and_the_first_account_stays() {
use super::super::linked_accounts::AccountStore;
use swarm_secret_client::matrix;
let store = FakeStore::default();
let path = matrix::account_path("atlas", "workaccount").expect("a valid path");
let existing = &super::existing("atlas", "workaccount");
let mut first = request("token");
first.token = Some("t0k3n-first".to_owned());
first.homeserver = Some("https://matrix.example.org".to_owned());
let mut second = request("password");
second.homeserver = Some("http://127.0.0.1:9".to_owned());
second.user_id = Some("@a:matrix.example.org".to_owned());
second.password = Some("hunter2".to_owned());
super::link_matrix(&store, &path, existing, &first)
.await
.expect("nothing is stored");
let problem = super::link_matrix(&store, &path, existing, &second)
.await
.expect_err("an account is stored");
assert_eq!(problem.status, Some(axum::http::StatusCode::CONFLICT));
let detail = problem.detail.expect("a detail");
assert_eq!(
detail,
r#"agent atlas already has matrix account "workaccount" linked; delete it first"#
);
assert_eq!(store.written(), std::slice::from_ref(&path));
let kept: matrix::Credential = store
.read_optional(&path)
.await
.expect("store answers")
.expect("still stored");
assert_eq!(kept.value, "t0k3n-first");
assert_eq!(
kept.homeserver.as_deref(),
Some("https://matrix.example.org")
);
}
}

View file

@ -0,0 +1,383 @@
//! Each agent's own account on the swarm's homeserver: created here with the
//! **swarm's** appservice token, stored at `swarm/agents/<agent>/matrix/main`,
//! and pulled from there by the agent's matrix daemon itself.
//!
//! The appservice token is minted inside the matrix container and published
//! to `swarm_secret_client::matrix::swarm_appservice_token_path`, which only
//! matrix-ctl and this daemon may read. No hive holds it, and no hive mints an
//! agent's account any more.
//!
//! ⚠️ **Every mint replaces the agent's live token.** Both calls pin the
//! device id `hyperhive-<agent>`, so a login for an existing account replaces
//! that device's token: the one in the store before, or the file token a hive
//! minted. That is why the decision reads the stored token back with `whoami`
//! ([`classify`]) instead of only checking that the store holds something, and
//! why a failed read never mints ([`Observed::Unknown`]).
//!
//! Two callers insert the same `MintAgentMatrixAccount` job node: agent
//! creation, and [`spawn`]'s pass at start and every [`RECONCILE_INTERVAL`]
//! over every agent that holds a store identity — the same roster and shape as
//! `crate::forge::agent_token`.
use std::sync::Arc;
use anyhow::{Context, Result, bail};
use swarm_matrix_client::{self as homeserver, Whoami};
use swarm_secret_client::{SecretStore, client::DEFAULT_CERT_MOUNT, matrix, policy};
/// The account name every agent's own matrix credential is stored under.
///
/// `main` is what `nix/agent-modules/matrix.nix` declares per agent and what
/// the agent's daemon reads first. ⚠️ `PUT .../matrix-accounts/{account}`
/// refuses this exact name (`super::is_reserved_account`): that route stores
/// an **external** account an operator supplies, and one called `main` would
/// overwrite this. Two writers, one reserved name, and the reservation is what
/// keeps them apart.
pub const ACCOUNT: &str = "main";
/// How often [`spawn`] re-checks every agent's account.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// Why an account's token has to be (re)minted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MintReason {
/// The store holds nothing for this agent: a new agent, or one whose
/// account a hive created before the swarm did this.
NotStored,
/// The homeserver does not know the stored token: another login on the
/// same device replaced it.
Revoked,
/// The stored token is live but belongs to another account.
OtherUser,
}
/// What one look at an agent's stored token found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Probe {
/// Nothing at the agent's path.
NotStored,
/// The homeserver's verdict on the stored token.
Whoami(Whoami),
}
/// What to do about one agent's account.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Decision {
/// The stored token is a live token for this agent's own account.
Keep,
/// Mint and store a new one.
Mint(MintReason),
}
/// What one pass found for one agent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Observed {
/// Both reads worked, and this is what [`classify`] made of them.
Decided(Decision),
/// A read failed. Nothing is known, so nothing is done.
Unknown,
}
/// The localpart of a full user id, `@<localpart>:<server>`.
fn localpart(user_id: &str) -> Option<&str> {
user_id.strip_prefix('@')?.split_once(':').map(|(l, _)| l)
}
/// Decide what to do about `agent`'s account from what its stored token is.
pub fn classify(agent: &str, probe: &Probe) -> Decision {
match probe {
Probe::NotStored => Decision::Mint(MintReason::NotStored),
Probe::Whoami(Whoami::UnknownToken) => Decision::Mint(MintReason::Revoked),
Probe::Whoami(Whoami::User(user)) if localpart(user) == Some(agent) => Decision::Keep,
Probe::Whoami(Whoami::User(_)) => Decision::Mint(MintReason::OtherUser),
}
}
/// The agents a pass mints for.
///
/// [`Observed::Unknown`] never mints: a homeserver or store outage must not
/// turn into a new token for every agent, each of which kills the one the
/// agent is running on.
pub fn plan(observed: &[(String, Observed)]) -> Vec<String> {
observed
.iter()
.filter(|(_, o)| matches!(o, Observed::Decided(Decision::Mint(_))))
.map(|(agent, _)| agent.clone())
.collect()
}
/// The swarm appservice token, or an error naming why there is none.
pub(super) async fn appservice_token(store: &SecretStore) -> Result<String> {
let path = matrix::swarm_appservice_token_path()?;
let stored: Option<matrix::Credential> = store
.read_optional(&path)
.await
.with_context(|| format!("reading {path}"))?;
match stored {
Some(c) if !c.value.trim().is_empty() => Ok(c.value.trim().to_owned()),
_ => bail!(
"nothing at {path}: the matrix container has not published the swarm \
appservice token (swarm-matrix-appservice-sync)"
),
}
}
/// What the store and the homeserver say about `agent`'s stored token.
async fn probe(
store: &SecretStore,
http: &reqwest::Client,
base: &str,
agent: &str,
) -> Result<Probe> {
probe_at(store, http, base, &matrix::account_path(agent, ACCOUNT)?).await
}
/// What the store and the homeserver say about the token stored at `path`.
pub(super) async fn probe_at(
store: &SecretStore,
http: &reqwest::Client,
base: &str,
path: &str,
) -> Result<Probe> {
let stored: Option<matrix::Credential> = store
.read_optional(path)
.await
.with_context(|| format!("reading {path}"))?;
let Some(stored) = stored else {
return Ok(Probe::NotStored);
};
let verdict = homeserver::whoami(http, base, stored.value.trim())
.await
.with_context(|| format!("asking the homeserver about the token at {path}"))?;
Ok(Probe::Whoami(verdict))
}
/// Make sure `agent` holds a live token for its own account on the swarm's
/// homeserver at `base`, creating the account or logging in to it when it
/// does not. The whole job of the `MintAgentMatrixAccount` node.
///
/// Reads the new token back with `whoami` before reporting success, so the
/// node does not report success on a write nobody has read. A crash between
/// the login and the write leaves a dead token in the store, which the next
/// pass classifies as [`MintReason::Revoked`].
///
/// # Errors
/// When the store or the homeserver refuses a step, the swarm appservice
/// token has not been published, or the new token authenticates as someone
/// else.
pub async fn ensure_agent_matrix_account(base: &str, agent: &str) -> Result<()> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let as_token = appservice_token(&store).await?;
let http = homeserver::client()?;
let reason = match classify(agent, &probe(&store, &http, base, agent).await?) {
Decision::Keep => {
tracing::debug!(agent, "agent matrix account is current; left as it is");
return Ok(());
}
Decision::Mint(reason) => reason,
};
let path = matrix::account_path(agent, ACCOUNT)?;
mint_at(&store, &http, base, agent, &as_token, &path).await?;
tracing::info!(agent, ?reason, %path, "agent matrix account token minted and stored");
Ok(())
}
/// Create the account `account` (a localpart), or log in to it as the appservice when it
/// exists, store the token at `path`, and read it back with `whoami`.
///
/// # Errors
/// When the store or the homeserver refuses a step, or the new token
/// authenticates as someone else.
pub(super) async fn mint_at(
store: &SecretStore,
http: &reqwest::Client,
base: &str,
account: &str,
as_token: &str,
path: &str,
) -> Result<()> {
let token = match homeserver::register(http, base, account, as_token).await? {
homeserver::Registered::Token(token) => token,
// An account minted before, or one a hive created itself: log in as
// the appservice on the same device instead.
homeserver::Registered::AlreadyExists => {
homeserver::appservice_login(http, base, account, as_token).await?
}
};
store
.write(
path,
&matrix::Credential {
value: token.clone(),
homeserver: Some(base.to_owned()),
},
)
.await
.with_context(|| format!("storing @{account}'s matrix token at {path}"))?;
match homeserver::whoami(http, base, &token)
.await
.with_context(|| format!("using @{account}'s new matrix token"))?
{
Whoami::User(user) if localpart(&user) == Some(account) => Ok(()),
_ => bail!("@{account}'s new matrix token does not authenticate as @{account}"),
}
}
/// One pass: every agent holding a store identity, observed.
///
/// Fails as a whole, rather than per agent, when the swarm appservice token is
/// not published: every mint would fail on it, and one message says so.
async fn observe_all(base: &str) -> Result<Vec<(String, Observed)>> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
appservice_token(&store).await?;
let http = homeserver::client()?;
let roles = store
.list_cert_roles(DEFAULT_CERT_MOUNT)
.await
.context("listing the store's cert-auth roles")?;
let mut observed = Vec::new();
for agent in policy::agents_from_role_names(&roles) {
let o = match probe(&store, &http, base, &agent).await {
Ok(p) => Observed::Decided(classify(&agent, &p)),
Err(e) => {
tracing::warn!(agent, error = %format!("{e:#}"), "agent matrix account: read failed");
Observed::Unknown
}
};
observed.push((agent, o));
}
Ok(observed)
}
/// Check every agent's account now and every [`RECONCILE_INTERVAL`] after, and
/// hand the agents that need a token to `enqueue`, which inserts a
/// `MintAgentMatrixAccount` node for each.
///
/// The roster is the store's `hive-agent-*` cert-auth roles: exactly the
/// agents that can read what the node writes. A pass that fails is logged and
/// retried on the next tick; it never stops the daemon.
pub fn spawn(base: Arc<str>, enqueue: impl Fn(Vec<String>) + Send + 'static) {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
match observe_all(&base).await {
Ok(observed) => {
let agents = plan(&observed);
if agents.is_empty() {
tracing::debug!(
checked = observed.len(),
"agent matrix accounts: all current"
);
} else {
tracing::info!(
checked = observed.len(),
minting = agents.len(),
"agent matrix accounts: queueing mints"
);
enqueue(agents);
}
}
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"agent matrix accounts: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
fn user(id: &str) -> Probe {
Probe::Whoami(Whoami::User(id.to_owned()))
}
#[test]
fn a_live_token_for_the_agent_is_kept() {
assert_eq!(classify("atlas", &user("@atlas:t.local")), Decision::Keep);
}
#[test]
fn nothing_stored_mints() {
assert_eq!(
classify("atlas", &Probe::NotStored),
Decision::Mint(MintReason::NotStored)
);
}
#[test]
fn a_replaced_token_mints() {
// The shape a hive re-login on the same device leaves behind.
assert_eq!(
classify("atlas", &Probe::Whoami(Whoami::UnknownToken)),
Decision::Mint(MintReason::Revoked)
);
}
#[test]
fn a_token_for_another_account_mints() {
// Localpart compared whole, so a prefix of the agent's name is not it.
for other in ["@argus:t.local", "@atlas2:t.local", "@atla:t.local"] {
assert_eq!(
classify("atlas", &user(other)),
Decision::Mint(MintReason::OtherUser),
"{other}"
);
}
}
#[test]
fn a_pass_mints_only_what_it_knows_needs_one() {
let observed = [
("a".to_owned(), Observed::Decided(Decision::Keep)),
(
"b".to_owned(),
Observed::Decided(Decision::Mint(MintReason::NotStored)),
),
("c".to_owned(), Observed::Unknown),
(
"d".to_owned(),
Observed::Decided(Decision::Mint(MintReason::Revoked)),
),
];
assert_eq!(plan(&observed), ["b", "d"]);
}
#[test]
fn an_outage_plans_nothing() {
// Each mint replaces the token an agent is running on, so a pass that
// could not read must not mint for everyone.
let observed = [
("a".to_owned(), Observed::Unknown),
("b".to_owned(), Observed::Unknown),
];
assert!(plan(&observed).is_empty());
}
#[test]
fn the_published_path_is_the_hiveless_one_the_agent_reads() {
// The literal is the point, and the absence of a hive segment is the
// half of it that was decided: an agent's account follows the agent.
assert_eq!(
matrix::account_path("atlas", ACCOUNT).expect("a plain name is legal"),
"swarm/agents/atlas/matrix/main"
);
}
#[test]
fn the_account_name_is_the_one_the_agent_module_declares() {
// `nix/agent-modules/matrix.nix` renders this as a `matrixAccounts`
// key and nothing wires an override across.
assert_eq!(ACCOUNT, "main");
}
}

View file

@ -0,0 +1,981 @@
//! Homeserver admin for authelia's operators: every member of the operator
//! group who has an account on the swarm's homeserver is made a homeserver
//! admin, at start and every [`RECONCILE_INTERVAL`] after, and an account this
//! 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 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 is
//! `!admin users make-user-admin <user>`, the revoke
//! `!admin users force-leave-room <user> <room>`.
//!
//! 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
//! restarts, since every command stays in the room's history.
use std::collections::BTreeSet;
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);
/// The localpart of tuwunel's admin room alias, `#admins:<server>`.
const ADMIN_ROOM_ALIAS_LOCALPART: &str = "admins";
/// The localpart of tuwunel's server user, which creates the admin room and
/// stays joined to it. tuwunel's default `server_user_localpart`;
/// `hive-matrix.nix` does not set it.
const SERVER_USER_LOCALPART: &str = "conduit";
/// 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`.
const IGNORE_USERS_ENV: &str = "SWARM_CONTROLLER_MATRIX_ADMIN_SYNC_IGNORE_USERS";
/// The localpart an SSO login by authelia user `username` lands on, or `None`
/// when tuwunel would refuse the name and no account can exist for it.
///
/// Lowercased and then checked against the user-id grammar's localpart
/// characters, which is what tuwunel does with the claim.
pub fn localpart(username: &str) -> Option<String> {
let lower = username.to_lowercase();
let legal = !lower.is_empty()
&& lower.bytes().all(|b| {
b.is_ascii_lowercase()
|| b.is_ascii_digit()
|| matches!(b, b'.' | b'_' | b'=' | b'-' | b'/' | b'+')
});
legal.then_some(lower)
}
/// What one pass decided, before any account is looked up.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Plan {
/// `(authelia username, user id)` for each operator not yet an admin.
pub grant: Vec<(String, String)>,
/// Operators whose username maps to no legal localpart.
pub unmappable: Vec<String>,
/// `(authelia username, user id)` for each operator this process already
/// sent a grant for who is still not an admin. Not sent again.
pub unconfirmed: Vec<(String, String)>,
}
/// Decide which of `operators` need a grant on `server`, given the user ids
/// already joined to the admin room and those this process already sent a
/// grant for.
pub fn plan(
operators: &[String],
server: &str,
admins: &BTreeSet<String>,
sent: &BTreeSet<String>,
) -> Plan {
let mut plan = Plan::default();
for name in operators {
let Some(localpart) = localpart(name) else {
plan.unmappable.push(name.clone());
continue;
};
let user_id = format!("@{localpart}:{server}");
if admins.contains(&user_id) {
continue;
}
if sent.contains(&user_id) {
plan.unconfirmed.push((name.clone(), user_id));
} else {
plan.grant.push((name.clone(), user_id));
}
}
plan
}
/// 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.
pub revoke: Vec<String>,
/// Those this process already sent a revoke for. Not sent again.
pub unconfirmed: Vec<String>,
/// Held back: revoking them would leave no admin outside `keepers`.
pub last_admin: Vec<String>,
/// Neither operators nor admins: dropped from the set.
pub forget: Vec<String>,
}
/// Decide which of `granted` lose admin, given the operator group's user ids,
/// the admin room's joined members, the accounts never revoked (`exempt`),
/// the accounts that do not count as an admin left behind (`keepers`, a
/// subset of `exempt`), and the user ids this process already sent a revoke
/// for.
pub fn plan_revokes(
granted: &BTreeSet<String>,
operators: &BTreeSet<String>,
admins: &BTreeSet<String>,
exempt: &BTreeSet<String>,
keepers: &BTreeSet<String>,
revoked: &BTreeSet<String>,
) -> Revokes {
let mut out = Revokes::default();
let mut left: BTreeSet<&String> = admins.iter().filter(|a| !keepers.contains(*a)).collect();
for user_id in granted {
if operators.contains(user_id) {
continue;
}
if !admins.contains(user_id) {
out.forget.push(user_id.clone());
continue;
}
if exempt.contains(user_id) {
continue;
}
if revoked.contains(user_id) {
out.unconfirmed.push(user_id.clone());
} else if left.len() <= 1 {
out.last_admin.push(user_id.clone());
} else {
left.remove(user_id);
out.revoke.push(user_id.clone());
}
}
out
}
/// The user ids in [`IGNORE_USERS_ENV`]'s value.
fn parse_ignore_users(raw: &str) -> BTreeSet<String> {
raw.split_whitespace().map(str::to_owned).collect()
}
/// 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(None),
Err(e) => Err(e).with_context(|| format!("reading {}", 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>`.
fn server_name(user_id: &str) -> Option<&str> {
user_id
.strip_prefix('@')?
.split_once(':')
.map(|(_, server)| server)
.filter(|server| !server.is_empty())
}
/// What one pass did.
#[derive(Debug, Default)]
struct Outcome {
granted: usize,
revoked: usize,
no_account: usize,
failed: usize,
}
/// What [`spawn`]'s loop carries from one pass to the next.
#[derive(Debug, Default)]
struct Memory {
/// User ids this process sent a grant for, which a sent grant joins.
sent: BTreeSet<String>,
/// User ids this process sent a revoke for.
revoked: BTreeSet<String>,
}
/// The admin room, and what sending to it takes.
struct AdminRoom<'a> {
http: &'a reqwest::Client,
base: &'a str,
token: &'a str,
id: &'a str,
}
/// 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 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
/// any of them missing there is no decision to make.
async fn pass(
bridge: &AuthBridge,
base: &str,
ignore: &BTreeSet<String>,
queue: &async_nats::Client,
legacy: &Path,
memory: &mut Memory,
) -> Result<Outcome> {
let operators = bridge
.list_operators()
.await
.context("reading authelia's operator group")?;
let secrets = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let token = appservice_token(&secrets).await?;
let http = homeserver::client()?;
let Whoami::User(sender) = homeserver::whoami(&http, base, &token)
.await
.context("asking the homeserver who the swarm appservice token is")?
else {
bail!("the homeserver does not know the swarm appservice token");
};
let server = server_name(&sender)
.with_context(|| format!("the homeserver named the swarm sender {sender:?}"))?;
let room = homeserver::resolve_alias(
&http,
base,
&token,
&format!("#{ADMIN_ROOM_ALIAS_LOCALPART}:{server}"),
)
.await?;
let admins = homeserver::joined_members(&http, base, &token, &room).await?;
let roles = secrets
.list_cert_roles(DEFAULT_CERT_MOUNT)
.await
.context("listing the store's cert-auth roles")?;
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,
token: &token,
id: &room,
};
let mut outcome = send_grants(
&admin_room,
&plan(&operators, server, &admins, &memory.sent),
memory,
&mut granted,
)
.await;
let operator_ids = operators
.iter()
.filter_map(|name| localpart(name))
.map(|l| format!("@{l}:{server}"))
.collect();
let keepers: BTreeSet<String> =
[sender.clone(), format!("@{SERVER_USER_LOCALPART}:{server}")].into();
let mut exempt = keepers.clone();
exempt.extend(
policy::agents_from_role_names(&roles)
.into_iter()
.map(|agent| format!("@{agent}:{server}")),
);
exempt.extend(ignore.iter().cloned());
let revokes = plan_revokes(
&granted,
&operator_ids,
&admins,
&exempt,
&keepers,
&memory.revoked,
);
send_revokes(&admin_room, &revokes, memory, &mut granted, &mut outcome).await;
if granted != stored.set {
save_granted(&store, &granted, stored.revision).await?;
}
Ok(outcome)
}
/// Log `plan`'s findings and send its grants, adding each one sent to
/// `memory.sent` and `granted`.
async fn send_grants(
room: &AdminRoom<'_>,
plan: &Plan,
memory: &mut Memory,
granted: &mut BTreeSet<String>,
) -> Outcome {
for name in &plan.unmappable {
tracing::warn!(
operator = %name,
"operator's username is no legal matrix localpart, so no SSO login can \
have an account to make admin; skipped"
);
}
for (name, user_id) in &plan.unconfirmed {
tracing::warn!(
operator = %name,
%user_id,
"make-user-admin for an operator failed to take: sent earlier by this process, \
still not in the admin room; not sent again until the controller restarts"
);
}
let mut outcome = Outcome::default();
for (name, user_id) in &plan.grant {
match grant(room.http, room.base, room.token, room.id, user_id).await {
Ok(true) => {
memory.sent.insert(user_id.clone());
memory.revoked.remove(user_id);
granted.insert(user_id.clone());
tracing::info!(
operator = %name,
%user_id,
"sent make-user-admin for an operator who is not a homeserver admin"
);
outcome.granted += 1;
}
Ok(false) => {
tracing::debug!(
operator = %name,
%user_id,
"operator has no matrix account yet; nothing to make admin"
);
outcome.no_account += 1;
}
Err(e) => {
tracing::warn!(
operator = %name,
%user_id,
error = %format!("{e:#}"),
"make-user-admin for an operator failed"
);
outcome.failed += 1;
}
}
}
outcome
}
/// Log `revokes`' findings, drop the forgotten user ids from `granted` and
/// `memory`, and send its revokes, adding each one sent to `memory.revoked`.
async fn send_revokes(
room: &AdminRoom<'_>,
revokes: &Revokes,
memory: &mut Memory,
granted: &mut BTreeSet<String>,
outcome: &mut Outcome,
) {
for user_id in &revokes.forget {
granted.remove(user_id);
memory.sent.remove(user_id);
memory.revoked.remove(user_id);
tracing::debug!(
%user_id,
"granted account is neither an operator nor an admin; no longer tracked"
);
}
for user_id in &revokes.unconfirmed {
tracing::warn!(
%user_id,
"force-leave-room for a former operator failed to take: sent earlier by this \
process, still in the admin room; not sent again until the controller restarts"
);
}
for user_id in &revokes.last_admin {
tracing::warn!(
%user_id,
"former operator is the last homeserver admin besides @swarm and the server \
user; not revoked"
);
}
for user_id in &revokes.revoke {
match homeserver::send_text(
room.http,
room.base,
room.token,
room.id,
&format!("!admin users force-leave-room {user_id} {}", room.id),
)
.await
{
Ok(_) => {
memory.revoked.insert(user_id.clone());
memory.sent.remove(user_id);
tracing::info!(
%user_id,
"sent force-leave-room for a former operator this sync made admin"
);
outcome.revoked += 1;
}
Err(e) => {
tracing::warn!(
%user_id,
error = %format!("{e:#}"),
"force-leave-room for a former operator failed"
);
outcome.failed += 1;
}
}
}
}
/// Send the grant for `user_id` when its account exists; `false` when it
/// does not, and nothing was sent.
async fn grant(
http: &reqwest::Client,
base: &str,
token: &str,
room: &str,
user_id: &str,
) -> Result<bool> {
if !homeserver::user_exists(http, base, token, user_id).await? {
return Ok(false);
}
homeserver::send_text(
http,
base,
token,
room,
&format!("!admin users make-user-admin {user_id}"),
)
.await?;
Ok(true)
}
/// 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>, queue: async_nats::Client) {
let ignore = parse_ignore_users(&std::env::var(IGNORE_USERS_ENV).unwrap_or_default());
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, &queue, &legacy, &mut memory).await {
Ok(outcome) if outcome.failed > 0 => tracing::warn!(
granted = outcome.granted,
revoked = outcome.revoked,
failed = outcome.failed,
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"operator matrix admin: pass incomplete; retrying next tick"
),
Ok(outcome) if outcome.granted > 0 || outcome.revoked > 0 => tracing::info!(
granted = outcome.granted,
revoked = outcome.revoked,
no_account = outcome.no_account,
"operator matrix admin: commands sent"
),
Ok(outcome) => tracing::debug!(
no_account = outcome.no_account,
"operator matrix admin: every operator with an account is an admin"
),
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"operator matrix admin: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
fn names(names: &[&str]) -> Vec<String> {
names.iter().map(|&n| n.to_owned()).collect()
}
fn ids(ids: &[&str]) -> BTreeSet<String> {
ids.iter().map(|&n| n.to_owned()).collect()
}
#[test]
fn an_operator_already_in_the_admin_room_gets_no_command() {
let plan = plan(
&names(&["mara", "vinzenz"]),
"t.local",
&ids(&["@mara:t.local", "@swarm:t.local"]),
&BTreeSet::new(),
);
assert_eq!(
plan.grant,
[("vinzenz".to_owned(), "@vinzenz:t.local".to_owned())]
);
assert!(plan.unmappable.is_empty());
}
#[test]
fn a_pass_with_every_operator_admin_sends_nothing() {
let plan = plan(
&names(&["mara"]),
"t.local",
&ids(&["@mara:t.local"]),
&BTreeSet::new(),
);
assert_eq!(plan, Plan::default());
}
#[test]
fn an_uppercase_username_maps_to_the_lowercased_account() {
// tuwunel lowercases the claim, so `Mara`'s login is `@mara:`, and that
// account being admin already is a match, not a second grant.
let plan = plan(
&names(&["Mara"]),
"t.local",
&ids(&["@mara:t.local"]),
&BTreeSet::new(),
);
assert_eq!(plan, Plan::default());
assert_eq!(localpart("Mara.B_c").as_deref(), Some("mara.b_c"));
}
#[test]
fn a_name_tuwunel_would_refuse_is_reported_not_granted() {
let plan = plan(
&names(&["bad name", "ok"]),
"t.local",
&BTreeSet::new(),
&BTreeSet::new(),
);
assert_eq!(plan.grant, [("ok".to_owned(), "@ok:t.local".to_owned())]);
assert_eq!(plan.unmappable, ["bad name"]);
assert_eq!(localpart(""), None);
assert_eq!(localpart("é"), None);
}
#[test]
fn a_grant_already_sent_by_this_process_is_not_sent_again() {
// The cap on the admin room: a command tuwunel ignored leaves the
// operator outside the room, and that must not produce a second send.
let plan = plan(
&names(&["mara", "vinzenz"]),
"t.local",
&BTreeSet::new(),
&ids(&["@mara:t.local"]),
);
assert_eq!(
plan.grant,
[("vinzenz".to_owned(), "@vinzenz:t.local".to_owned())]
);
assert_eq!(
plan.unconfirmed,
[("mara".to_owned(), "@mara:t.local".to_owned())]
);
}
#[test]
fn a_sent_grant_that_took_is_neither_sent_nor_reported() {
let plan = plan(
&names(&["mara"]),
"t.local",
&ids(&["@mara:t.local"]),
&ids(&["@mara:t.local"]),
);
assert_eq!(plan, Plan::default());
}
#[test]
fn the_server_name_comes_from_the_full_user_id() {
assert_eq!(server_name("@swarm:t.local"), Some("t.local"));
assert_eq!(server_name("@swarm:t.local:8448"), Some("t.local:8448"));
assert_eq!(server_name("@swarm:"), None);
assert_eq!(server_name("swarm"), None);
}
/// `@swarm` and the server user, the accounts `pass` always exempts.
fn keepers() -> BTreeSet<String> {
ids(&["@swarm:t.local", "@conduit:t.local"])
}
#[test]
fn a_former_operator_the_sync_granted_is_revoked() {
let revokes = plan_revokes(
&ids(&["@mara:t.local", "@ex:t.local"]),
&ids(&["@mara:t.local"]),
&ids(&[
"@swarm:t.local",
"@conduit:t.local",
"@mara:t.local",
"@ex:t.local",
]),
&keepers(),
&keepers(),
&BTreeSet::new(),
);
assert_eq!(
revokes,
Revokes {
revoke: vec!["@ex:t.local".to_owned()],
..Revokes::default()
}
);
}
#[test]
fn a_hand_made_admin_is_never_revoked() {
// `@hand` is no operator and an admin, but the sync never granted it.
let revokes = plan_revokes(
&ids(&["@mara:t.local"]),
&ids(&["@mara:t.local"]),
&ids(&["@swarm:t.local", "@mara:t.local", "@hand:t.local"]),
&keepers(),
&keepers(),
&BTreeSet::new(),
);
assert_eq!(revokes, Revokes::default());
}
#[test]
fn an_ignored_user_is_never_revoked() {
let ignore = parse_ignore_users(" @ex:t.local\n@other:t.local ");
assert_eq!(ignore, ids(&["@ex:t.local", "@other:t.local"]));
let mut exempt = keepers();
exempt.extend(ignore);
let revokes = plan_revokes(
&ids(&["@ex:t.local"]),
&BTreeSet::new(),
&ids(&["@swarm:t.local", "@mara:t.local", "@ex:t.local"]),
&exempt,
&keepers(),
&BTreeSet::new(),
);
assert_eq!(revokes, Revokes::default());
}
#[test]
fn swarm_the_server_user_and_agents_are_never_revoked() {
// An operator whose username matches an agent's name shares its
// account; leaving the group must not take the agent's admin.
let mut exempt = keepers();
exempt.insert("@argus:t.local".to_owned());
let revokes = plan_revokes(
&ids(&["@swarm:t.local", "@conduit:t.local", "@argus:t.local"]),
&BTreeSet::new(),
&ids(&[
"@swarm:t.local",
"@conduit:t.local",
"@argus:t.local",
"@mara:t.local",
]),
&exempt,
&keepers(),
&BTreeSet::new(),
);
assert_eq!(revokes, Revokes::default());
}
#[test]
fn the_last_admin_besides_swarm_and_the_server_user_is_not_revoked() {
let revokes = plan_revokes(
&ids(&["@exa:t.local", "@exb:t.local"]),
&BTreeSet::new(),
&ids(&[
"@swarm:t.local",
"@conduit:t.local",
"@exa:t.local",
"@exb:t.local",
]),
&keepers(),
&keepers(),
&BTreeSet::new(),
);
assert_eq!(revokes.revoke, ["@exa:t.local"]);
assert_eq!(revokes.last_admin, ["@exb:t.local"]);
}
#[test]
fn a_revoke_already_sent_by_this_process_is_not_sent_again() {
let revokes = plan_revokes(
&ids(&["@ex:t.local"]),
&BTreeSet::new(),
&ids(&["@swarm:t.local", "@mara:t.local", "@ex:t.local"]),
&keepers(),
&keepers(),
&ids(&["@ex:t.local"]),
);
assert_eq!(
revokes,
Revokes {
unconfirmed: vec!["@ex:t.local".to_owned()],
..Revokes::default()
}
);
}
#[test]
fn a_granted_account_out_of_the_room_and_the_group_is_forgotten() {
// Forgotten, so an admin someone makes of it by hand later is theirs.
let revokes = plan_revokes(
&ids(&["@mara:t.local", "@ex:t.local"]),
&ids(&["@mara:t.local"]),
&ids(&["@swarm:t.local", "@mara:t.local"]),
&keepers(),
&keepers(),
&ids(&["@ex:t.local"]),
);
assert_eq!(
revokes,
Revokes {
forget: vec!["@ex:t.local".to_owned()],
..Revokes::default()
}
);
}
use crate::test_nats::TestNats;
/// 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)
}
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!(
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));
}
}

View file

@ -0,0 +1,285 @@
//! A recovery passphrase for every matrix account of every agent, stored at
//! `swarm_secret_client::matrix::recovery_path`: what the agent's matrix daemon
//! turns on server-side key backup with, and recovers its keys with once its
//! local crypto store is gone.
//!
//! Minted here because the agent's store policy is read-only. [`spawn`]'s pass
//! runs at start and every [`RECONCILE_INTERVAL`] over every agent that holds a
//! store identity — the same roster as [`super::agent_token`] — and every
//! account listed under that agent's `matrix/` directory.
//!
//! ⚠️ **Never replaced.** A backup can only be opened with the passphrase it
//! was enabled with, so a new one locks the agent out of everything backed up
//! under the old. The write is a `cas=0` create, and a path that holds anything
//! is left alone.
use anyhow::{Context, Result};
use serde::de::IgnoredAny;
use swarm_secret_client::{Error, SecretStore, client::DEFAULT_CERT_MOUNT, matrix, policy};
/// How often [`spawn`] re-checks every account.
const RECONCILE_INTERVAL: std::time::Duration = std::time::Duration::from_mins(5);
/// Bytes drawn from the kernel's CSPRNG per passphrase.
const PASSPHRASE_BYTES: usize = 32;
/// What [`ensure`] did at one path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
/// The path already held a passphrase.
Present,
/// This pass wrote one.
Minted,
/// Another writer's create landed between this pass's read and its own.
LostRace,
}
/// The two store calls [`ensure`] makes, so a test can stand in for the store.
pub(crate) trait PassphraseStore {
/// Whether anything is stored at `path`, as [`SecretStore::read_optional`]
/// answers it. The value is decoded as [`IgnoredAny`] and never held.
fn exists(&self, path: &str) -> impl Future<Output = Result<bool, Error>> + Send;
/// As [`SecretStore::create`].
fn create(
&self,
path: &str,
value: &matrix::Recovery,
) -> impl Future<Output = Result<(), Error>> + Send;
}
impl PassphraseStore for SecretStore {
async fn exists(&self, path: &str) -> Result<bool, Error> {
Ok(self.read_optional::<IgnoredAny>(path).await?.is_some())
}
async fn create(&self, path: &str, value: &matrix::Recovery) -> Result<(), Error> {
SecretStore::create(self, path, value).await
}
}
/// A passphrase: [`PASSPHRASE_BYTES`] from the kernel's CSPRNG, base64url
/// without padding.
///
/// # Errors
/// When the kernel will not supply randomness.
fn generate() -> Result<matrix::Recovery> {
let mut bytes = [0u8; PASSPHRASE_BYTES];
getrandom::fill(&mut bytes)
.context("drawing a recovery passphrase from the kernel's CSPRNG")?;
Ok(matrix::Recovery {
value: base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, bytes),
})
}
/// Make sure `path` holds a passphrase, writing one only if it holds nothing.
///
/// A create that fails is read back: if the path now holds something, a
/// concurrent writer won and that is the passphrase.
///
/// # Errors
/// When the store refuses the read, or the create fails and the path is still
/// empty.
pub(crate) async fn ensure(store: &impl PassphraseStore, path: &str) -> Result<Outcome> {
if store
.exists(path)
.await
.with_context(|| format!("reading {path}"))?
{
return Ok(Outcome::Present);
}
let Err(e) = store.create(path, &generate()?).await else {
return Ok(Outcome::Minted);
};
if store
.exists(path)
.await
.with_context(|| format!("reading {path} back after a failed create"))?
{
return Ok(Outcome::LostRace);
}
Err(anyhow::Error::new(e).context(format!("creating {path}")))
}
/// The account names listed under `agent`'s `matrix/` directory. A key ending
/// in `/` is a directory below it, not an account.
async fn accounts(store: &SecretStore, agent: &str) -> Result<Vec<String>> {
let dir = matrix::accounts_dir(agent)?;
let keys = store
.list(&dir)
.await
.with_context(|| format!("listing {dir}"))?;
Ok(keys.into_iter().filter(|k| !k.ends_with('/')).collect())
}
/// One pass over every agent's accounts. Returns how many paths were checked
/// and how many were minted. A failure for one agent or account is logged and
/// the pass carries on.
async fn pass() -> Result<(usize, usize)> {
let store = crate::store::connect()
.await
.context("logging in to the swarm secret store")?;
let roles = store
.list_cert_roles(DEFAULT_CERT_MOUNT)
.await
.context("listing the store's cert-auth roles")?;
let (mut checked, mut minted) = (0, 0);
for agent in policy::agents_from_role_names(&roles) {
let names = match accounts(&store, &agent).await {
Ok(names) => names,
Err(e) => {
tracing::warn!(agent, error = %format!("{e:#}"), "matrix recovery passphrases: listing failed");
continue;
}
};
for account in names {
checked += 1;
let path = match matrix::recovery_path(&agent, &account) {
Ok(path) => path,
Err(e) => {
tracing::warn!(agent, account, error = %e, "matrix recovery passphrase: unusable account name");
continue;
}
};
match ensure(&store, &path).await {
Ok(Outcome::Present) => {}
Ok(Outcome::Minted) => {
minted += 1;
tracing::info!(agent, account, %path, "matrix recovery passphrase minted");
}
Ok(Outcome::LostRace) => {
tracing::info!(agent, account, %path, "matrix recovery passphrase: another writer created it first");
}
Err(e) => tracing::warn!(
agent,
account,
error = %format!("{e:#}"),
"matrix recovery passphrase: mint failed"
),
}
}
}
Ok((checked, minted))
}
/// 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() {
tokio::spawn(async move {
let mut ticker = tokio::time::interval(RECONCILE_INTERVAL);
loop {
ticker.tick().await;
match pass().await {
Ok((checked, minted)) => {
tracing::debug!(checked, minted, "matrix recovery passphrases: pass done");
}
Err(e) => tracing::warn!(
error = %format!("{e:#}"),
retry_in_s = RECONCILE_INTERVAL.as_secs(),
"matrix recovery passphrases: pass failed; retrying next tick"
),
}
}
});
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Mutex;
use super::*;
/// An in-memory store. `race` makes the next create find the path taken by
/// someone else, the way a concurrent `cas=0` loses.
#[derive(Default)]
struct Fake {
held: Mutex<HashMap<String, String>>,
race: Option<String>,
refuse_reads: bool,
}
/// A store error with no store behind it.
fn refused() -> Error {
Error::MissingEnv("BAO_ADDR")
}
impl PassphraseStore for Fake {
async fn exists(&self, path: &str) -> Result<bool, Error> {
if self.refuse_reads {
return Err(refused());
}
Ok(self.held.lock().unwrap().contains_key(path))
}
async fn create(&self, path: &str, value: &matrix::Recovery) -> Result<(), Error> {
let mut held = self.held.lock().unwrap();
if let Some(winner) = &self.race {
held.insert(path.to_owned(), winner.clone());
return Err(refused());
}
if held.contains_key(path) {
return Err(refused());
}
held.insert(path.to_owned(), value.value.clone());
Ok(())
}
}
const PATH: &str = "swarm/agents/atlas/matrix-recovery/main";
#[tokio::test]
async fn an_empty_path_gets_a_passphrase() {
let store = Fake::default();
assert_eq!(ensure(&store, PATH).await.unwrap(), Outcome::Minted);
assert!(store.held.lock().unwrap().contains_key(PATH));
}
#[tokio::test]
async fn a_held_passphrase_is_never_replaced() {
let store = Fake::default();
store
.held
.lock()
.unwrap()
.insert(PATH.to_owned(), "first".to_owned());
assert_eq!(ensure(&store, PATH).await.unwrap(), Outcome::Present);
assert_eq!(store.held.lock().unwrap()[PATH], "first");
}
#[tokio::test]
async fn a_create_another_writer_beat_counts_as_done() {
let store = Fake {
race: Some("winner".to_owned()),
..Fake::default()
};
assert_eq!(ensure(&store, PATH).await.unwrap(), Outcome::LostRace);
assert_eq!(store.held.lock().unwrap()[PATH], "winner");
}
#[tokio::test]
async fn a_store_that_cannot_be_read_gets_no_write() {
// Reading "absent" into a refusal would overwrite a live passphrase
// whenever the store was merely unreachable.
let store = Fake {
refuse_reads: true,
..Fake::default()
};
assert!(ensure(&store, PATH).await.is_err());
assert!(store.held.lock().unwrap().is_empty());
}
#[test]
fn a_passphrase_is_32_random_bytes_in_a_plain_alphabet() {
let a = generate().unwrap().value;
let b = generate().unwrap().value;
// 32 bytes is 43 base64 characters without padding.
assert_eq!(a.len(), 43, "{a}");
assert!(
a.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'),
"{a}"
);
assert_ne!(a, b);
}
}

View file

@ -0,0 +1,9 @@
//! The accounts concern: the swarm's matrix accounts and the external accounts
//! linked to it (forge, github, gitlab), with their egress and routes.
pub(crate) mod forge_account;
pub(crate) mod github_account;
pub(crate) mod gitlab_account;
pub(crate) mod link_egress;
pub(crate) mod linked_accounts;
pub(crate) mod matrix_account;